@actions/exec#exec TypeScript Examples

The following examples show how to use @actions/exec#exec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: eslint.ts    From action-eslint with MIT License 6 votes vote down vote up
runEslint = async (inputs: Inputs): Promise<void> => {
  if (!inputs.annotations) {
    disableAnnotations();
  }

  const changedFiles = await getChangedFiles(inputs.token);

  startGroup('Files changed.');
  changedFiles.forEach((file) => info(`- ${file}`));
  endGroup();

  const files = changedFiles.filter((filename) => {
    const isFileSupported = inputs.extensions.find((ext) => filename.endsWith(`.${ext}`));
    return isFileSupported;
  });

  if (files.length === 0) {
    notice('No files found. Skipping.');
    return;
  }

  startGroup('Files for linting.');
  files.forEach((file) => info(`- ${file}`));
  endGroup();

  const execOptions = [
    path.resolve(inputs.binPath, 'eslint'),
    ...files,
    ...inputs.eslintArgs,
  ].filter(Boolean);

  await exec('node', execOptions);
}
Example #2
Source File: minikube.ts    From setup-minikube with MIT License 6 votes vote down vote up
export async function downloadMinikube(version: string): Promise<void> {
  const url = getDownloadUrl(version)
  const downloadPath = await downloadTool(url)
  const binPath =
    getPlatform() === 'darwin' ? '/Users/runner/bin' : '/home/runner/bin'
  await mkdirP(binPath)
  await exec('chmod', ['+x', downloadPath])
  await mv(downloadPath, join(binPath, 'minikube'))
  addPath(binPath)
}
Example #3
Source File: find.ts    From setup-poetry with MIT License 6 votes vote down vote up
export async function findPoetry(inputs: Inputs): Promise<void> {
  // Download get-poetry.py
  const getPoetryPath = await downloadTool(GET_POETRY_URL)

  // Run Poetry installation script
  await exec("python", [getPoetryPath, ...getPoetryInstallArgs(inputs)])

  // Add Poetry executable to the PATH
  const poetryPath = path.join(os.homedir(), ...getPoetryPathArgs())
  addPath(poetryPath)
}
Example #4
Source File: apt-installer.ts    From cuda-toolkit with MIT License 6 votes vote down vote up
export async function aptSetup(version: SemVer): Promise<void> {
  const osType = await getOs()
  if (osType !== OSType.linux) {
    throw new Error(
      `apt setup can only be run on linux runners! Current os type: ${osType}`
    )
  }
  core.debug(`Setup packages for ${version}`)
  const ubuntuVersion: string = await execReturnOutput('lsb_release', ['-sr'])
  const ubuntuVersionNoDot = ubuntuVersion.replace('.', '')
  const pinFilename = `cuda-ubuntu${ubuntuVersionNoDot}.pin`
  const arch = `x86_64`
  const pinUrl = `https://developer.download.nvidia.com/compute/cuda/repos/ubuntu${ubuntuVersionNoDot}/${arch}/${pinFilename}`
  const repoUrl = `http://developer.download.nvidia.com/compute/cuda/repos/ubuntu${ubuntuVersionNoDot}/${arch}/`
  const keyRingVersion = `1.0-1`
  const keyRingUrl = `https://developer.download.nvidia.com/compute/cuda/repos/ubuntu${ubuntuVersionNoDot}/${arch}/cuda-keyring_${keyRingVersion}_all.deb`
  const keyRingFilename = `cuda_keyring.deb`

  core.debug(`Pin filename: ${pinFilename}`)
  core.debug(`Pin url: ${pinUrl}`)
  core.debug(`Keyring url: ${keyRingUrl}`)

  core.debug(`Downloading keyring`)
  await exec(`wget ${keyRingUrl} -O ${keyRingFilename}`)
  await exec(`sudo dpkg -i ${keyRingFilename}`)

  core.debug('Adding CUDA Repository')
  await exec(`wget ${pinUrl}`)
  await exec(
    `sudo mv ${pinFilename} /etc/apt/preferences.d/cuda-repository-pin-600`
  )
  await exec(`sudo add-apt-repository "deb ${repoUrl} /"`)
  await exec(`sudo apt-get update`)
}
Example #5
Source File: apt-installer.ts    From cuda-toolkit with MIT License 6 votes vote down vote up
export async function aptInstall(
  version: SemVer,
  subPackages: string[]
): Promise<number> {
  const osType = await getOs()
  if (osType !== OSType.linux) {
    throw new Error(
      `apt install can only be run on linux runners! Current os type: ${osType}`
    )
  }
  if (subPackages.length === 0) {
    // Install everything
    const packageName = `cuda-${version.major}-${version.minor}`
    core.debug(`Install package: ${packageName}`)
    return await exec(`sudo apt-get -y install`, [packageName])
  } else {
    // Only install specified packages
    const versionedSubPackages = subPackages.map(
      subPackage => `cuda-${subPackage}-${version.major}-${version.minor}`
    )
    core.debug(`Only install subpackages: ${versionedSubPackages}`)
    return await exec(`sudo apt-get -y install`, versionedSubPackages)
  }
}
Example #6
Source File: run-command.ts    From cuda-toolkit with MIT License 6 votes vote down vote up
export async function execReturnOutput(
  command: string,
  args: string[] = []
): Promise<string> {
  let result = ''
  const execOptions = {
    listeners: {
      stdout: (data: Buffer) => {
        result += data.toString()
      },
      stderr: (data: Buffer) => {
        core.debug(`Error: ${data.toString()}`)
      }
    }
  }
  const exitCode = await exec(command, args, execOptions)
  if (exitCode) {
    core.debug(`Error executing: ${command}. Exit code: ${exitCode}`)
  }
  return result.trim()
}
Example #7
Source File: action.ts    From actions-clever-cloud with MIT License 6 votes vote down vote up
async function checkForShallowCopy(): Promise<void> {
  let output = ''
  await exec('git', ['rev-parse', '--is-shallow-repository'], {
    listeners: {
      stdout: (data: Buffer) => (output += data.toString())
    }
  })
  if (output.trim() === 'true') {
    throw new Error(`This action requires an unshallow working copy.
-> Use the following step before running this action:
 - uses: actions/checkout@v3
   with:
     fetch-depth: 0
`)
  }
}
Example #8
Source File: pub.ts    From vscode-drawio with GNU General Public License v3.0 6 votes vote down vote up
export async function run(): Promise<void> {
	const version = getChangelog().latestVersion;
	if (version.kind === "unreleased") {
		return;
	}

	await exec("yarn", [
		"vsce",
		"publish",
		"--packagePath",
		"./vscode-drawio.vsix",
		"--pat",
		process.env.MARKETPLACE_TOKEN!,
	]);

	const gitTag = `v${version.version}`;
	console.log(`Creating a version tag "${gitTag}".`);
	const api = new GitHub(process.env.GH_TOKEN!);
	await api.git.createRef({
		...context.repo,
		ref: `refs/tags/${gitTag}`,
		sha: context.sha,
	});

	console.log("Uploading to open-vsx...");
	await exec("yarn", [
		"ovsx",
		"publish",
		"./vscode-drawio.vsix",
		"-p",
		process.env.OPEN_VSX_TOKEN!,
	]);
}
Example #9
Source File: foreman.ts    From setup-foreman with MIT License 5 votes vote down vote up
async function authenticate(token: string): Promise<void> {
  await exec("foreman", ["github-auth", token]);
}
Example #10
Source File: minikube.ts    From setup-minikube with MIT License 5 votes vote down vote up
export async function startMinikube(): Promise<void> {
  const args = ['start', '--wait', 'all']
  setArgs(args)
  await exec('minikube', args)
}
Example #11
Source File: action.ts    From jest-github-action with MIT License 5 votes vote down vote up
async function execJest(cmd: string, cwd?: string) {
  try {
    await exec(cmd, [], { silent: true, cwd })
    console.debug("Jest command executed")
  } catch (e) {
    console.error("Jest execution failed. Tests have likely failed.", e)
  }
}
Example #12
Source File: Term.ts    From size-limit-action with ISC License 5 votes vote down vote up
async execSizeLimit(
    branch?: string,
    skipStep?: string,
    buildScript?: string,
    cleanScript?: string,
    windowsVerbatimArguments?: boolean,
    directory?: string,
    script?: string
  ): Promise<{ status: number; output: string }> {
    const manager = hasYarn(directory)
      ? "yarn"
      : hasPNPM(directory)
      ? "pnpm"
      : "npm";
    let output = "";

    if (branch) {
      try {
        await exec(`git fetch origin ${branch} --depth=1`);
      } catch (error) {
        console.log("Fetch failed", error.message);
      }

      await exec(`git checkout -f ${branch}`);
    }

    if (skipStep !== INSTALL_STEP && skipStep !== BUILD_STEP) {
      await exec(`${manager} install`, [], {
        cwd: directory
      });
    }

    if (skipStep !== BUILD_STEP) {
      const script = buildScript || "build";
      await exec(`${manager} run ${script}`, [], {
        cwd: directory
      });
    }

    const status = await exec(script, [], {
      windowsVerbatimArguments,
      ignoreReturnCode: true,
      listeners: {
        stdout: (data: Buffer) => {
          output += data.toString();
        }
      },
      cwd: directory
    });

    if (cleanScript) {
      await exec(`${manager} run ${cleanScript}`, [], {
        cwd: directory
      });
    }

    return {
      status,
      output
    };
  }
Example #13
Source File: main.ts    From setup-foreman with MIT License 5 votes vote down vote up
async function run(): Promise<void> {
  try {
    const versionReq: string = getInput("version");
    const githubToken: string = getInput("token");
    const workingDir: string = getInput("working-directory");

    const octokit = new GitHub(githubToken);
    const releases = await foreman.getReleases(octokit);

    debug("Choosing release from GitHub API");

    const release = foreman.chooseRelease(versionReq, releases);
    if (release == null) {
      throw new Error(
        `Could not find Foreman release for version ${versionReq}`
      );
    }

    debug(`Chose release ${release.tag_name}`);

    const asset = foreman.chooseAsset(release);
    if (asset == null) {
      throw new Error(
        `Could not find asset for version ${release.tag_name} on platform ${process.platform}`
      );
    }

    debug(`Chose release asset ${asset.browser_download_url}`);

    const zipPath = await downloadTool(asset.browser_download_url);
    const extractedPath = await extractZip(zipPath, ".foreman-install");
    addPath(resolve(extractedPath));

    if (process.platform === "darwin" || process.platform === "linux") {
      await exec("chmod +x .foreman-install/foreman");
    }

    await foreman.authenticate(githubToken);
    foreman.addBinDirToPath();

    if (workingDir !== undefined && workingDir !== null && workingDir !== "") {
      process.chdir(workingDir);
    }
    await foreman.installTools();
  } catch (error) {
    if (error instanceof Error) {
      setFailed(error.message);
    }
  }
}
Example #14
Source File: foreman.ts    From setup-foreman with MIT License 5 votes vote down vote up
async function installTools(): Promise<void> {
  await exec("foreman install");
}
Example #15
Source File: ArchiveTools.ts    From powershell with MIT License 5 votes vote down vote up
private async unzipUsing7Zip(zipPath: string, destination: string) {
        debug(`Using 7zip to extract ${zipPath} to ${destination}`);
        const path7Zip = await which("7z.exe", true);
        const exitCode = await exec(`${path7Zip} x -o${destination} ${zipPath}`);
        if (exitCode != 0) {
            throw new Error(`Extraction using 7zip failed from ${zipPath} to ${destination}`);
        }
    }
Example #16
Source File: action.ts    From actions-clever-cloud with MIT License 5 votes vote down vote up
export default async function run({
  token,
  secret,
  appID,
  alias,
  cleverCLI,
  timeout,
  extraEnv = {}
}: Arguments): Promise<void> {
  try {
    await checkForShallowCopy()

    core.debug(`Clever CLI path: ${cleverCLI}`)

    // Authenticate (this will only store the credentials at a known location)
    await exec(cleverCLI, ['login', '--token', token, '--secret', secret])

    // There is an issue when there is a .clever.json file present
    // and only the appID is passed: link will work, but deploy will need
    // an alias to know which app to publish. In this case, we set the alias
    // to the appID, and the alias argument is ignored if also specified.
    if (appID) {
      core.debug(`Linking ${appID}`)
      await exec(cleverCLI, ['link', appID, '--alias', appID])
      alias = appID
    }

    // If there are environment variables to pass to the application,
    // set them before deployment so the new instance can use them.
    for (const envName of Object.keys(extraEnv)) {
      const args = ['env', 'set']
      if (alias) {
        args.push('--alias', alias)
      }
      args.push(envName, extraEnv[envName])
      await exec(cleverCLI, args)
    }

    const args = ['deploy']
    if (appID) {
      args.push('--alias', appID)
    } else if (alias) {
      args.push('--alias', alias)
    }

    if (timeout) {
      let timeoutID: NodeJS.Timeout | undefined
      let timedOut = false
      const timeoutPromise = new Promise<void>(resolve => {
        timeoutID = setTimeout(() => {
          timedOut = true
          resolve()
        }, timeout)
      })
      const result = await Promise.race([exec(cleverCLI, args), timeoutPromise])
      if (timeoutID) {
        clearTimeout(timeoutID)
      }
      if (timedOut) {
        core.info('Deployment timed out, moving on with workflow run')
      }
      core.info(`result: ${result}`)
      if (typeof result === 'number' && result !== 0) {
        throw new Error(`Deployment failed with code ${result}`)
      }
    } else {
      const code = await exec(cleverCLI, args)
      core.info(`code: ${code}`)
      if (code !== 0) {
        throw new Error(`Deployment failed with code ${code}`)
      }
    }
  } catch (error) {
    if (error instanceof Error) {
      core.setFailed(error.message)
    } else {
      core.setFailed(String(error))
    }
  }
}
Example #17
Source File: installer.ts    From cuda-toolkit with MIT License 4 votes vote down vote up
export async function install(
  executablePath: string,
  version: SemVer,
  subPackagesArray: string[],
  linuxLocalArgsArray: string[]
): Promise<void> {
  // Install arguments, see: https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#runfile-advanced
  // and https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html
  let installArgs: string[]

  // Command string that is executed
  let command: string

  // Subset of subpackages to install instead of everything, see: https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html#install-cuda-software
  const subPackages: string[] = subPackagesArray

  // Execution options which contain callback functions for stdout and stderr of install process
  const execOptions = {
    listeners: {
      stdout: (data: Buffer) => {
        core.debug(data.toString())
      },
      stderr: (data: Buffer) => {
        core.debug(`Error: ${data.toString()}`)
      }
    }
  }

  // Configure OS dependent run command and args
  switch (await getOs()) {
    case OSType.linux:
      // Root permission needed on linux
      command = `sudo ${executablePath}`
      // Install silently, and add additional arguments
      installArgs = ['--silent'].concat(linuxLocalArgsArray)
      break
    case OSType.windows:
      // Windows handles permissions automatically
      command = executablePath
      // Install silently
      installArgs = ['-s']
      // Add subpackages to command args (if any)
      installArgs = installArgs.concat(
        subPackages.map(subPackage => {
          // Display driver sub package name is not dependent on version
          if (subPackage === 'Display.Driver') {
            return subPackage
          }
          return `${subPackage}_${version.major}.${version.minor}`
        })
      )
      break
  }

  // Run installer
  try {
    core.debug(`Running install executable: ${executablePath}`)
    const exitCode = await exec(command, installArgs, execOptions)
    core.debug(`Installer exit code: ${exitCode}`)
  } catch (error) {
    core.debug(`Error during installation: ${error}`)
    throw error
  } finally {
    // Always upload installation log regardless of error
    if ((await getOs()) === OSType.linux) {
      const artifactClient = artifact.create()
      const artifactName = 'install-log'
      const files = ['/var/log/cuda-installer.log']
      const rootDirectory = '/var/log'
      const artifactOptions = {
        continueOnError: true
      }
      const uploadResult = await artifactClient.uploadArtifact(
        artifactName,
        files,
        rootDirectory,
        artifactOptions
      )
      core.debug(`Upload result: ${uploadResult}`)
    }
  }
}
Example #18
Source File: main.ts    From setup-rust with MIT License 4 votes vote down vote up
async function run(): Promise<void> {
  try {
    try {
      await io.which("rustup", true);
    } catch (error) {
      switch (process.platform) {
        case "darwin":
        case "linux":
          var rustupSh = await tc.downloadTool("https://sh.rustup.rs");
          await fs.chmod(rustupSh, 0o755);
          core.debug("Starting rustup install!");
          await exec(rustupSh, INSTALL_ARGS);
          break;
        case "win32":
          core.debug("Starting rustup install!");
          await exec(
            await tc.downloadTool("https://win.rustup.rs"),
            INSTALL_ARGS
          );
          break;
        default:
          break;
      }
      core.addPath(path.join(homedir(), ".cargo", "bin"));
    }
    let version = core.getInput("rust-version", { required: true });
    let components = core.getInput("components");
    let targets = core.getInput("targets");

    const cacheKey = `rustup-${
      process.platform
    }-${version}-${components.replace(" ", "-")}-${targets}`;

    await cache.restoreCache(CACHE_PATH, cacheKey);

    let args = [
      "toolchain",
      "install",
      version,
      "--profile",
      "minimal",
      "--allow-downgrade",
    ];
    if (components) {
      components.split(" ").forEach(val => {
        args.push("--component");
        args.push(val);
      });
    }
    if (targets) {
      targets.split(" ").forEach(val => {
        args.push("--target");
        args.push(val);
      });
    }

    core.info(
      `Installing toolchain with components and targets: ${version} -- ${process.platform} -- ${components} -- ${targets}`
    );

    let code = await exec("rustup", args);
    if (code != 0) {
      throw `Failed installing toolchain exited with code: ${code}`;
    }

    core.info(`Setting the default toolchain: ${version}`);
    let default_code = await exec("rustup", ["default", version]);
    if (default_code != 0) {
      throw `Failed setting the default toolchain exited with code: ${default_code}`;
    }

    core.info(`##[add-matcher]${path.join(__dirname, "..", "rustc.json")}`);

    core.debug(`Saving cache: ${cacheKey}`);
    try {
      await cache.saveCache(CACHE_PATH, cacheKey);
    } catch (error) {
      core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`);
    }
  } catch (error) {
    core.setFailed(error.message);
  }
}