child_process#ExecOptions TypeScript Examples

The following examples show how to use child_process#ExecOptions. 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: utils.ts    From checkov-vscode with Apache License 2.0 7 votes vote down vote up
asyncExec = async (commandToExecute: string, options: ExecOptions = {}): Promise<ExecOutput> => {
    const defaultOptions: ExecOptions = { maxBuffer: 1024 * 1000 };
    return new Promise((resolve, reject) => {
        exec(commandToExecute, { ...defaultOptions, ...options }, (err, stdout, stderr) => {
            if (err) { return reject(err); }
            resolve([stdout, stderr]);
        });
    });
}
Example #2
Source File: utils.ts    From shadowsocks-electron with GNU General Public License v3.0 7 votes vote down vote up
execAsync = (command: string, options?: ExecOptions) => {
  return new Promise<{
    code: number;
    stdout?: string;
    stderr?: string;
  }>((resolve, reject) => {
    exec(command, { ...options, windowsHide: true }, (err, stdout, stderr) => {
      if (!stderr) {
        resolve({
          code: err ? 1 : 0,
          stdout
        });
      } else {
        reject({
          code: err ? 1 : 0,
          stderr
        });
      }
    });
  });
}
Example #3
Source File: exec-process.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function execProcess(
  command: string,
  { env = process.env, ...options }: ExecOptions = {},
): Observable<ProcessOutput> {
  return new Observable<ProcessOutput>((observer) => {
    const child = exec(command, {
      ...options,
      env: processEnv(env),
    });
    const processExitListener = () => {
      observer.complete();
      child.kill();
    };

    process.on('exit', processExitListener);
    child.stdout.on('data', (data) => {
      observer.next({ type: 'OUT', data });
    });
    child.stderr.on('data', (data) => {
      observer.next({ type: 'ERR', data });
    });
    child.on('close', (code) => {
      if (code === 0) {
        observer.complete();
      } else {
        observer.error();
      }

      process.removeListener('exit', processExitListener);
    });
  });
}
Example #4
Source File: exec-async.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export function execAsync(cmd: string, options?: ExecOptions): Promise<string> {
  return new Promise((resolve, reject) => {
    exec(cmd, options, (error, stdout, stderr) => {
      if (error) {
        reject(new ExecError(error, stdout, stderr));
      }
      resolve(stdout);
    });
  });
}
Example #5
Source File: deploy.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
export async function deploy(stage: Stage, options?: ExecOptions): Promise<void> {
    const settings = new SettingsDao(stage)

    if ("test" === stage) {
        settings.resetNextMigration()
    }
    const nextMigration = settings.getSystemDeploySettings().nextMigration

    const basePath = path.join(__dirname, "../publish/migrations")
    const filenames = await readdir(basePath)
    for (const filename of filenames) {
        const migrationPath = path.join(basePath, filename)
        const { batchIndex, layer, configPath } = await loadMigration(migrationPath)

        if (batchIndex < nextMigration.batchIndex) {
            console.info(`Skip migration: ${filename}`)
            continue
        }

        console.info(`Start migration: ${filename}`)
        const network = settings.getNetwork(layer)
        const configPathParam = configPath ? `--config ${configPath}` : ""
        const cmd = `hardhat --network ${network} ${configPathParam} ${TASK_MIGRATE} ${stage} ${migrationPath}`
        await asyncExec(cmd, options)
    }
}
Example #6
Source File: helper.ts    From perpetual-protocol with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Execute command in in local node_modules directory
 * @param commandAndArgs command with arguments
 */
export function asyncExec(commandAndArgs: string, options?: ExecOptions): Promise<string> {
    const [command, ...args] = commandAndArgs.split(" ")
    const cwd = options ? options.cwd : undefined
    const npmBin = resolve(getNpmBin(cwd), command)
    const realCommand = test("-e", npmBin) ? `${npmBin} ${args.join(" ")}` : commandAndArgs
    console.log(`> ${realCommand}`)
    return new Promise<string>((resolve, reject) => {
        const cb = (code: number, stdout: string, stderr: string) => {
            if (code !== 0) {
                reject(stderr)
            } else {
                resolve(stdout)
            }
        }

        if (options) {
            exec(realCommand, options, cb)
        } else {
            exec(realCommand, cb)
        }
    })
}
Example #7
Source File: run.ts    From golangci-lint-action with MIT License 5 votes vote down vote up
async function runLint(lintPath: string, patchPath: string): Promise<void> {
  const debug = core.getInput(`debug`)
  if (debug.split(`,`).includes(`cache`)) {
    const res = await execShellCommand(`${lintPath} cache status`)
    printOutput(res)
  }

  const userArgs = core.getInput(`args`)
  const addedArgs: string[] = []

  const userArgNames = new Set<string>(
    userArgs
      .trim()
      .split(/\s+/)
      .map((arg) => arg.split(`=`)[0])
      .filter((arg) => arg.startsWith(`-`))
      .map((arg) => arg.replace(/^-+/, ``))
  )
  if (userArgNames.has(`out-format`)) {
    throw new Error(`please, don't change out-format for golangci-lint: it can be broken in a future`)
  }
  addedArgs.push(`--out-format=github-actions`)

  if (patchPath) {
    if (userArgNames.has(`new`) || userArgNames.has(`new-from-rev`) || userArgNames.has(`new-from-patch`)) {
      throw new Error(`please, don't specify manually --new* args when requesting only new issues`)
    }
    addedArgs.push(`--new-from-patch=${patchPath}`)

    // Override config values.
    addedArgs.push(`--new=false`)
    addedArgs.push(`--new-from-rev=`)
  }

  const workingDirectory = core.getInput(`working-directory`)
  const cmdArgs: ExecOptions = {}
  if (workingDirectory) {
    if (patchPath) {
      // TODO: make them compatible
      throw new Error(`options working-directory and only-new-issues aren't compatible`)
    }
    if (!fs.existsSync(workingDirectory) || !fs.lstatSync(workingDirectory).isDirectory()) {
      throw new Error(`working-directory (${workingDirectory}) was not a path`)
    }
    if (!userArgNames.has(`path-prefix`)) {
      addedArgs.push(`--path-prefix=${workingDirectory}`)
    }
    cmdArgs.cwd = path.resolve(workingDirectory)
  }

  const cmd = `${lintPath} run ${addedArgs.join(` `)} ${userArgs}`.trimRight()
  core.info(`Running [${cmd}] in [${cmdArgs.cwd || ``}] ...`)
  const startedAt = Date.now()
  try {
    const res = await execShellCommand(cmd, cmdArgs)
    printOutput(res)
    core.info(`golangci-lint found no issues`)
  } catch (exc) {
    // This logging passes issues to GitHub annotations but comments can be more convenient for some users.
    // TODO: support reviewdog or leaving comments by GitHub API.
    printOutput(exc)

    if (exc.code === 1) {
      core.setFailed(`issues found`)
    } else {
      core.setFailed(`golangci-lint exit with code ${exc.code}`)
    }
  }

  core.info(`Ran golangci-lint in ${Date.now() - startedAt}ms`)
}
Example #8
Source File: simulate.ts    From perpetual-protocol with GNU General Public License v3.0 5 votes vote down vote up
// This script is for testing in the mainnet fork environment
export async function simulate(stage: Stage, migrationFileName: string, options?: ExecOptions): Promise<void> {
    if (stage !== "production" && stage !== "staging") {
        throw new Error('We only simulate migration for "production" or "staging"')
    }

    // convert relative path to absolute path
    const fullMigrationPath = path.join(__dirname, "..", "publish", "simulations", migrationFileName)

    // load migration file to get required parameters
    const { batchIndex, configPath, layer } = await loadMigration(fullMigrationPath)

    // determine network by stage & layer
    const settingsDao = new SettingsDao(stage)
    const sourceNetwork = settingsDao.getNetwork(layer)

    // copy files in OpenZeppelin's directory
    const ozSettingsFileName = ozNetworkFile[sourceNetwork]
    const stagePath = `${getOpenZeppelinDir()}/${stage}`
    const sourceFile = `${stagePath}/${ozSettingsFileName}.json`
    const destinationPath = `${getOpenZeppelinDir()}/test`
    const destinationFile = `${destinationPath}/unknown-31337.json`

    if (!test("-e", destinationPath)) {
        mkdir("-p", destinationPath)
    }
    cp(sourceFile, destinationFile)
    console.log("%o copied to %o", sourceFile, destinationFile)

    // copy files in metadata
    const metadataSourceFile = getContractMetadataFile(stage)
    const metadataDestinationFile = getContractMetadataFile("test")
    cp(metadataSourceFile, metadataDestinationFile)
    console.log("%o copied to %o", metadataSourceFile, metadataDestinationFile)

    // clone settings
    const modifiedSettings = _.cloneDeep(settingsDao.settingsCached)

    // setting for both layers
    modifiedSettings.layers.layer1!.chainId = 31337
    modifiedSettings.layers.layer1!.network = "localhost"
    modifiedSettings.layers.layer2!.chainId = 31337
    modifiedSettings.layers.layer2!.network = "localhost"

    // allow migration with designated migration file/index
    modifiedSettings.nextMigration.batchIndex = batchIndex

    // write settings for simulation stage "test"
    const settingDestinationFile = getSettingsFile("test")
    ShellString(JSON.stringify(modifiedSettings, null, 2)).to(settingDestinationFile)
    console.log("%o copied", settingDestinationFile)

    // choose JSON-RPC URL to fork from
    let forkSource: string | undefined = undefined
    switch (sourceNetwork) {
        case "homestead":
            forkSource = HOMESTEAD_ARCHIVE_NODE_URL
            break
        case "rinkeby":
            forkSource = RINKEBY_ARCHIVE_NODE_URL
            break
        case "xdai":
            forkSource = XDAI_ARCHIVE_NODE_URL
            break
        default:
            throw new Error(
                `Unsupported network "${sourceNetwork}" (of stage: ${stage}, layer: ${layer}) or *_ARCHIVE_NODE_URL may not set properly`,
            )
    }
    console.log("Fork from %o (host name only)", parseUrl(forkSource).hostname)

    // execute simulation task
    const configPathParam = configPath ? `--config ${configPath}` : ""
    const cmd = `hardhat ${configPathParam} ${TASK_SIMULATE} --fork ${forkSource} ${fullMigrationPath}`
    await asyncExec(cmd, options)
}