child_process#spawnSync TypeScript Examples

The following examples show how to use child_process#spawnSync. 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 malagu with MIT License 8 votes vote down vote up
export function spawnProcess(command: string, args: string[], options: any) {
    return new Promise<any>((resolve, reject) => {
        if (options && options.stdio === 'inherit') {
            spawnSync(command, args, options);
            resolve({});
        } else {
            const child = spawn(command, args, options);
            let stdout = '';
            let stderr = '';
            child.stdout.setEncoding('utf8');
            child.stderr.setEncoding('utf8');
            child.stdout.on('data', (data: any) => {
                stdout += data;
            });
            child.stderr.on('data', (data: any) => {
                stderr += data;
            });
            child.on('error', (err: any) => {
                reject(err);
            });
            child.on('close', (exitCode: number) => {
                if (exitCode !== 0) {
                    reject(new SpawnError(`${command} ${args.join(' ')} failed with code ${exitCode}`, stdout, stderr));
                } else {
                    resolve({ stdout, stderr });
                }
            });
        }
    });
}
Example #2
Source File: utils.ts    From cli with Apache License 2.0 7 votes vote down vote up
export function shimNpm() {
  const tmpDir = tmpDirSync();
  const npmDir = join(tmpDir.name, 'npmShim');
  process.env[npmCachePathEnvVar] = join(npmDir, 'cache');
  copySync(join(__dirname, '..', 'npm-shim'), npmDir);
  const npmCiArgs = [appendCmdIfWindows`npm`, 'ci'];
  spawnSync(npmCiArgs.shift()!, npmCiArgs, {cwd: npmDir});
  process.env[npmPathEnvVar] = resolve(
    npmDir,
    'node_modules',
    'npm',
    'bin',
    'npm-cli.js'
  );
}
Example #3
Source File: utils.ts    From airnode with MIT License 7 votes vote down vote up
runCommand = (command: string) => {
  logger.log(`Running command:\n${command}`);
  const result = spawnSync(command, {
    shell: true,
  });

  if (result.status !== 0 || result.error) {
    throw new Error(`Command failed with non-zero status code. Output:\n${result.stdout.toString()}`);
  }

  const stderr = result.stderr.toString();
  if (stderr) {
    cliPrint.warning(`Stderr output:\n${stderr}`);
  }

  return result.stdout.toString();
}
Example #4
Source File: npm-utils.ts    From plasmic with MIT License 7 votes vote down vote up
export function installUpgrade(
  pkg: string,
  baseDir: string,
  opts: { global?: boolean; dev?: boolean } = {}
) {
  const cmd = installCommand(pkg, baseDir, opts);
  if (!process.env.QUIET) {
    logger.info(cmd);
  }
  const r = spawnSync(cmd, {
    shell: true,
    stdio: process.env.QUIET ? "ignore" : "inherit",
    cwd: baseDir,
  });
  if (r.status === 0) {
    if (!process.env.QUIET) {
      logger.info(`Successfully added ${pkg} dependency.`);
    }
    return true;
  } else {
    logger.warn(
      `Cannot add ${pkg} to your project dependencies. Please add it manually.`
    );
    return false;
  }
}
Example #5
Source File: util.ts    From riju with MIT License 7 votes vote down vote up
rubyVersion = (() => {
  try {
    return spawnSync("ruby", ["-e", "puts RUBY_VERSION"])
      .stdout.toString()
      .trim();
  } catch (err) {
    return null;
  }
})()
Example #6
Source File: paths.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
public linkDirsFromTo(source: string, target: string): boolean {
        // cmd //c mklink //j "$__TARGET_DIR" "$__SOURCE_DIR"
        try {
            if (fs.existsSync(target)) {
                if (!this.removeLink(target)) {
                    this.log.log(LogLevel.ERROR, 'Could not remove link before creating new one');
                    return false;
                }
            }
            return (spawnSync(
                'cmd',
                [
                    '/c',
                    'mklink',
                    '/j',
                    target,
                    source,
                ],
            ).status === 0);
        } catch (e) {
            this.log.log(LogLevel.ERROR, `Error linking ${source} to ${target}`, e);
            return false;
        }
    }
Example #7
Source File: extension.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
autoDetectBallerinaHome(): { home: string, isOldBallerinaDist: boolean, isBallerinaNotFound: boolean } {
        let balHomeOutput = "",
            isBallerinaNotFound = false,
            isOldBallerinaDist = false;
        try {
            let response = spawnSync(this.ballerinaCmd, ['home']);
            if (response.stdout.length > 0) {
                balHomeOutput = response.stdout.toString().trim();
            } else if (response.stderr.length > 0) {
                let message = response.stderr.toString();
                // ballerina is installed, but ballerina home command is not found
                isOldBallerinaDist = message.includes("bal: unknown command 'home'");
                // ballerina is not installed
                isBallerinaNotFound = message.includes('command not found')
                    || message.includes('unknown command')
                    || message.includes('is not recognized as an internal or external command');
                log(`Error executing 'bal home'.\n<---- cmd output ---->\n${message}<---- cmd output ---->\n`);
            }

            // specially handle unknown ballerina command scenario for windows
            if (balHomeOutput === "" && process.platform === "win32") {
                isOldBallerinaDist = true;
            }
        } catch ({ message }) {
            // ballerina is installed, but ballerina home command is not found
            isOldBallerinaDist = message.includes("bal: unknown command 'home'");
            // ballerina is not installed
            isBallerinaNotFound = message.includes('command not found')
                || message.includes('unknown command')
                || message.includes('is not recognized as an internal or external command');
            log(`Error executing 'bal home'.\n<---- cmd output ---->\n${message}<---- cmd output ---->\n`);
        }

        return {
            home: isBallerinaNotFound || isOldBallerinaDist ? '' : balHomeOutput,
            isBallerinaNotFound,
            isOldBallerinaDist
        };
    }
Example #8
Source File: git.ts    From workspace-tools with MIT License 6 votes vote down vote up
/**
 * Runs git command - use this for read only commands
 */
export function git(args: string[], options?: { cwd: string; maxBuffer?: number }): ProcessOutput {
  const results = spawnSync("git", args, { maxBuffer: MaxBufferOption, ...options });
  let output: ProcessOutput;

  if (results.status === 0) {
    output = {
      stderr: results.stderr.toString().trimRight(),
      stdout: results.stdout.toString().trimRight(),
      success: true,
    };
  } else {
    output = {
      stderr: results.stderr.toString().trimRight(),
      stdout: results.stdout.toString().trimRight(),
      success: false,
    };
  }

  // notify observers, flipping the observing bit to prevent infinite loops
  if (!observing) {
    observing = true;
    for (const observer of observers) {
      observer(args, output);
    }
    observing = false;
  }

  return output;
}
Example #9
Source File: local-accounts.ts    From amman with Apache License 2.0 6 votes vote down vote up
export async function saveAccount(
  accountId: string,
  endpoint: string,
  accountsFolder: string,
  executable = false
) {
  const makeRemainingArgs = (id: string) => [
    '-u',
    endpoint,
    '-o',
    `${accountsFolder}/${id}.json`,
    '--output',
    'json',
  ]
  logInfo(`Saving account ${accountId} from cluster ${endpoint}`)
  spawnSync('solana', ['account', accountId, ...makeRemainingArgs(accountId)])
  if (executable) {
    logInfo(`Saving executable data for ${accountId} from cluster ${endpoint}`)
    const executableId = await getExecutableAddress(accountId)
    spawnSync('solana', [
      'account',
      executableId,
      ...makeRemainingArgs(executableId),
    ])
  }
}
Example #10
Source File: runner.ts    From bdk with Apache License 2.0 6 votes vote down vote up
// Docker Compose
  private runSpawnSync (args: Array<string>): string {
    logger.debug(`run spawnSync: docker-compose ${args.join(' ')}`)
    const spawnReturn = spawnSync('docker-compose', [...args])
    // TODO ! docker 裡面的 error 不能這樣抓
    // TODO 如果 docker-compose 不存在不會報錯
    if (spawnReturn.error) {
      throw new DockerError(`[x] command [docker-compose]: ${spawnReturn.error.message}`)
    }
    logger.silly(spawnReturn.output.join('\n'))
    return spawnReturn.output.join('\n')
  }
Example #11
Source File: Queue.ts    From lift with MIT License 6 votes vote down vote up
displayLogs(options: CliOptions): void {
        const args = ["logs", "--function", `${this.id}Worker`];
        for (const [option, value] of Object.entries(options)) {
            args.push(option.length === 1 ? `-${option}` : `--${option}`);
            if (typeof value === "string") {
                args.push(value);
            }
        }
        getUtils().log(chalk.gray(`serverless ${args.join(" ")}`));
        args.unshift(process.argv[1]);
        spawnSync(process.argv[0], args, {
            cwd: process.cwd(),
            stdio: "inherit",
        });
    }
Example #12
Source File: dnstwist.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
async function runDNSTwist(domain: Domain) {
  const child = spawnSync(
    'dnstwist',
    ['-r', '--tld', './worker/common_tlds.dict', '-f', 'json', domain.name],
    {
      stdio: 'pipe',
      encoding: 'utf-8'
    }
  );
  const savedOutput = child.stdout;
  const finalResults = JSON.parse(savedOutput);
  console.log(
    `Got ${Object.keys(finalResults).length} similar domains for domain ${
      domain.name
    }`
  );
  return finalResults;
}
Example #13
Source File: examples.spec.ts    From graphql-eslint with MIT License 6 votes vote down vote up
function getESLintOutput(cwd: string): ESLint.LintResult[] {
  const { stdout, stderr } = spawnSync('eslint', ['.', '--format', 'json'], { cwd });
  const errorOutput = stderr.toString();
  if (errorOutput) {
    throw new Error(errorOutput);
  }
  const output = stdout.toString();
  const start = output.indexOf('[{');
  const end = output.lastIndexOf('}]') + 2;
  return JSON.parse(output.slice(start, end));
}
Example #14
Source File: intrigue-ident.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
intrigueIdent = async (domain: LiveDomain): Promise<void> => {
  console.log('Domain', domain.name);
  const { stdout, stderr, status } = spawnSync(
    'intrigue-ident',
    ['--uri', domain.url, '--json'],
    {
      env: {
        ...process.env,
        HTTP_PROXY: process.env.GLOBAL_AGENT_HTTP_PROXY,
        HTTPS_PROXY: process.env.GLOBAL_AGENT_HTTP_PROXY
      },
      maxBuffer: buffer.constants.MAX_LENGTH
    }
  );
  if (stderr?.toString()) {
    console.error('stderr', stderr.toString());
  }
  if (status !== 0) {
    console.error('IntrigueIdent failed');
    return;
  }
  const output = stdout.toString();
  const { fingerprint, content } = JSON.parse(
    output.substring(output.indexOf('{'))
  );
  domain.service.intrigueIdentResults = { fingerprint, content };
  await domain.service.save();
}
Example #15
Source File: builder.ts    From nx-plugins with MIT License 6 votes vote down vote up
function down(
  cwd: string,
  options: NxDeployItDestroyBuilderSchema,
  configuration: string,
  projectName: string
): Observable<BuilderOutput> {
  const args = [
    'destroy',
    '--cwd',
    cwd,
    '--stack',
    `${configuration}-${projectName}`
  ];
  if (options.nonInteractive) {
    args.push('--non-interactive', '--yes');
  }
  const up = spawnSync(getPulumiBinaryPath(), args, {
    env: { ...process.env, PULUMI_SKIP_UPDATE_CHECK: '1' },
    stdio: 'inherit'
  });

  if (up.error) {
    return of({ success: false, error: up.error.message });
  }

  return of({ success: true });
}
Example #16
Source File: pycompile-op.ts    From algo-builder with Apache License 2.0 6 votes vote down vote up
/**
	 * Description: Runs a subprocess to execute python script
	 * @param filename : python filename in assets folder
	 * @param scInitParam : Smart contract initialization parameters.
	 */
	private runPythonScript(filename: string, scInitParam?: string): SpawnSyncReturns<string> {
		const filePath = getPathFromDirRecursive(ASSETS_DIR, filename) as string;
		// used spawnSync instead of spawn, as it is synchronous
		if (scInitParam === undefined) {
			return spawnSync("python3", [filePath], { encoding: "utf8" });
		}

		return spawnSync("python3", [filePath, scInitParam], { encoding: "utf8" });
	}
Example #17
Source File: canary-release.ts    From graphql-eslint with MIT License 6 votes vote down vote up
getRelevantChangesets = (baseBranch: string): string[] => {
  const comparePoint = spawnSync('git', ['merge-base', `origin/${baseBranch}`, 'HEAD'])
    .stdout.toString()
    .trimEnd();
  console.log('compare point', comparePoint);

  const modifiedFiles = spawnSync('git', ['diff', '--name-only', comparePoint]).stdout.toString().trimEnd().split('\n');
  console.log('modified files', modifiedFiles);

  const changesets = modifiedFiles
    .filter(filePath => filePath.startsWith('.changeset/'))
    .map(filePath => basename(filePath, '.md'));
  console.log('changesets', changesets);

  return changesets;
}
Example #18
Source File: locate-compiler-cache.spec.ts    From solc-typed-ast with Apache License 2.0 6 votes vote down vote up
describe(command, () => {
    let exitCode: number | null;
    let outData: string;
    let errData: string;

    before(() => {
        const env: { [key: string]: string | undefined } = {};

        Object.entries(process.env)
            .filter(([name]) => name !== "SOL_AST_COMPILER_CACHE")
            .forEach(([key, val]) => {
                env[key] = val;
            });

        const result = spawnSync("sol-ast-compile", args, { env, encoding: "utf8" });

        outData = result.stdout;
        errData = result.stderr;
        exitCode = result.status;
    });

    it("Exit code is valid", () => {
        expect(exitCode).toEqual(0);
    });

    it("STDERR is empty", () => {
        expect(errData).toEqual("");
    });

    it("STDOUT is correct", () => {
        expect(outData).toContain(".compiler_cache");
    });
});
Example #19
Source File: exec.ts    From gitmars with GNU General Public License v3.0 6 votes vote down vote up
export function runSpawnSync(command: string, cwd: string = ROOT) {
    const [cmd, ...args] = command.split(' ')
    return new Promise((resolve, reject) => {
        const child = spawnSync(cmd, args, {
            cwd,
            stdio: 'inherit',
            shell: process.platform === 'win32'
        })
        if (child.status !== 0) {
            reject(child.error)
        } else {
            resolve(true)
        }
    })
}
Example #20
Source File: base.adapter.ts    From nx-plugins with MIT License 6 votes vote down vote up
getStackOutput(cwd: string, configuration: string, projectName: string) {
    const args = [
      'stack',
      'output',
      '--cwd',
      cwd,
      '--stack',
      `${configuration}-${projectName}`,
      '--json'
    ];

    const output = spawnSync(getPulumiBinaryPath(), args, {
      env: { ...process.env, PULUMI_SKIP_UPDATE_CHECK: '1' }
    });

    return JSON.parse(output.stdout.toString());
  }
Example #21
Source File: lib.ts    From xcodebuild with The Unlicense 6 votes vote down vote up
export function spawn(
  arg0: string,
  args: string[],
  options: SpawnSyncOptions = { stdio: 'inherit' }
): void {
  const { error, signal, status } = spawnSync(arg0, args, options)
  if (error) throw error
  if (signal) throw new Error(`\`${arg0}\` terminated with signal (${signal})`)
  if (status != 0) throw new Error(`\`${arg0}\` aborted (${status})`)
}
Example #22
Source File: schematic.ts    From nx-plugins with MIT License 6 votes vote down vote up
function generateNewPulumiProject(adapter: BaseAdapter): Rule {
  return (): Rule => {
    const template = getCloudTemplateName(adapter.options.provider);
    const args = [
      'new',
      template,
      '--name',
      adapter.options.project,
      '--dir',
      resolve(join(adapter.project.root, 'infrastructure')),
      '--description',
      'Infrastructure as Code based on Pulumi - managed by @dev-thought/nx-deploy-it',
      '--generate-only',
      '--yes',
    ];

    spawnSync(getPulumiBinaryPath(), args, {
      env: { ...process.env, PULUMI_SKIP_UPDATE_CHECK: '1' },
    });

    return addDependenciesFromPulumiProjectToPackageJson(adapter);
  };
}
Example #23
Source File: init-manager.ts    From Serverless-Devs with MIT License 6 votes vote down vote up
async deploy(appPath: string) {
    const answers: any = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'name',
        default: 'Y',
        message: colors.yellow(i18n('init_pproject_deploy_tip')),
      },
    ]);

    if (answers.name) {
      spawnSync('s deploy', { cwd: appPath, shell: true, stdio: 'inherit' });
    }
  }
Example #24
Source File: dotnet.client.ts    From nx-dotnet with MIT License 6 votes vote down vote up
private spawnAndGetOutput(params: string[]): string {
    params = params.map((param) =>
      param.replace(/\$(\w+)/, (_, varName) => process.env[varName] ?? ''),
    );

    const res = spawnSync(this.cliCommand.command, params, {
      cwd: this.cwd || process.cwd(),
      stdio: 'pipe',
    });
    if (res.status !== 0) {
      throw new Error(
        `dotnet execution returned status code ${res.status} \n ${res.stderr}`,
      );
    }
    return res.stdout.toString();
  }
Example #25
Source File: choose-integration.ts    From airnode with MIT License 6 votes vote down vote up
checkGitTag = () => {
  // skip tag check if git is not present
  const gitNotFound =
    spawnSync(`git --version`, {
      shell: true,
    }).status !== 0;

  if (gitNotFound) return;

  const gitTag = spawnSync(`git describe --exact-match --tags`, {
    shell: true,
  });

  if (gitTag.status !== 0)
    cliPrint.warning(`Warning:
    It appears you may not be on a git tag.
    If you directly downloaded the source code at a specific tag or release, please ignore this warning.
    Otherwise, please check out a git tag before proceeding (see README for more details).`);
}
Example #26
Source File: dotnet.client.ts    From nx-dotnet with MIT License 6 votes vote down vote up
private logAndExecute(params: string[]): void {
    params = params.map((param) =>
      param.replace(/\$(\w+)/, (_, varName) => process.env[varName] ?? ''),
    );

    const cmd = `${this.cliCommand.command} "${params.join('" "')}"`;
    console.log(`Executing Command: ${cmd}`);

    const res = spawnSync(this.cliCommand.command, params, {
      cwd: this.cwd || process.cwd(),
      stdio: 'inherit',
    });
    if (res.status !== 0) {
      throw new Error(`dotnet execution returned status code ${res.status}`);
    }
  }
Example #27
Source File: command-not-found.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
commandNotFound: Hook<'command_not_found'> = async (options) => {
    const command = `relate-${options.id}`;

    if (await binExists(command)) {
        spawnSync(command, process.argv.slice(3), {
            stdio: 'inherit',
        });
        process.exit(0);
    }
}
Example #28
Source File: hosting.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export async function createReactTestProject(): Promise<string> {
  const projRoot = await createNewProjectDir('hosting');
  const projectName = path.basename(projRoot);
  const projectDir = path.dirname(projRoot);

  spawnSync('npx', ['create-react-app', projectName], { cwd: projectDir });

  return projRoot;
}
Example #29
Source File: deploy-services.ts    From opensaas with MIT License 5 votes vote down vote up
function isAppCreated() {
  const child = spawnSync('git remote -v | grep heroku', { encoding: 'utf8', shell: true });
  return child.stdout;
}