child_process#execSync TypeScript Examples

The following examples show how to use child_process#execSync. 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: util.ts    From attranslate with MIT License 13 votes vote down vote up
export function runCommandOrDie(command: string): string {
  try {
    return execSync(command).toString();
  } catch (e) {
    //console.error(e.stderr.toString());
    logFatal(
      `Failed to run \'${command}\' in current directory \'${process.cwd()}\'.`
    );
  }
}
Example #2
Source File: github-utils.ts    From moonbeam with GNU General Public License v3.0 7 votes vote down vote up
export function getCompareLink(packageName: string, previousTag: string, newTag: string) {
  const previousPackage = execSync(
    `git show ${previousTag}:../Cargo.lock | grep ${packageName}? | head -1 | grep -o '".*"'`
  ).toString();
  const previousCommit = /#([0-9a-f]*)/g.exec(previousPackage)[1].slice(0, 8);
  const previousRepo = /(https:\/\/.*)\?/g.exec(previousPackage)[1];

  const newPackage = execSync(
    `git show ${newTag}:../Cargo.lock | grep ${packageName}? | head -1 | grep -o '".*"'`
  ).toString();
  const newCommit = /#([0-9a-f]*)/g.exec(newPackage)[1].slice(0, 8);
  const newRepo = /(https:\/\/.*)\?/g.exec(newPackage)[1];
  const newRepoOrganization = /github.com\/([^\/]*)/g.exec(newRepo)[1];

  const diffLink =
    previousRepo !== newRepo
      ? `${previousRepo}/compare/${previousCommit}...${newRepoOrganization}:${newCommit}`
      : `${previousRepo}/compare/${previousCommit}...${newCommit}`;

  return diffLink;
}
Example #3
Source File: utils.ts    From plugin-vscode with Apache License 2.0 7 votes vote down vote up
export function detectBallerinaHome(): string {
    // try to ditect the environment.
    const platform: string = process.platform;
    let balHome = "";
    switch (platform) {
        case "win32": // Windows
            if (process.env.BALLERINA_HOME) {
                return process.env.BALLERINA_HOME;
            }
            try {
                balHome = execSync("where bal").toString().trim();
            } catch (error) {
                return balHome;
            }
            if (path) {
                balHome = balHome.replace(/bin\\bal.bat$/, "");
            }
            break;
        case "darwin": // Mac OS
        case "linux": // Linux
            // lets see where the ballerina command is.
            try {
                const output = execSync("which bal");
                balHome = fs.realpathSync(output.toString().trim());
                // remove ballerina bin from path
                if (path) {
                    balHome = balHome.replace(/bin\/bal$/, "");
                }
                break;
            } catch {
                return balHome;
            }
    }

    // If we cannot find ballerina home return empty.
    return balHome;
}
Example #4
Source File: utils.ts    From micropython-ctl with MIT License 7 votes vote down vote up
getNodeModulesDirectory = (): string => {
  if (isWindows) {
    return execSync('npm root --global').toString().trim()
  } else {
    // In Linux and macOS, users might use nvm, which is only enabled in their bash/shell profile.
    // In that case, 'npm root' run with execSync will not point to the nvm executable.
    const nodePath = path.dirname(path.dirname(process.execPath));
    return path.join(nodePath, 'lib/node_modules');
  }
}
Example #5
Source File: npm-utils.ts    From plasmic with MIT License 7 votes vote down vote up
export function findInstalledVersion(
  context: PlasmicContext,
  baseDir: string,
  pkg: string
) {
  const pm = detectPackageManager(baseDir);
  if (pm === "yarn2") {
    try {
      const pkgInfo = JSON.parse(
        execSync(`yarn info --json ${pkg}`).toString().trim()
      );
      return pkgInfo?.children?.Version;
    } catch (_) {
      return undefined;
    }
  }

  const filename = findInstalledPackageJsonFile(context, pkg);
  if (filename) {
    const json = parsePackageJson(filename);
    if (json && json.name === pkg) {
      return json.version as string;
    }
  }
  return undefined;
}
Example #6
Source File: utils.ts    From dm with MIT License 7 votes vote down vote up
/** 每一行的修改信息 */
export function getBlameInfo (filePath: string, startLine = 1, endLine: number): Record<number, string> {
  const authors: Record<number, string> = {};
  try {
    const blameInfoStr = execSync(`git blame '${filePath}' --line-porcelain -L ${startLine},${endLine}`, { encoding: 'utf8' });
    if (blameInfoStr) {
      let num = startLine;
      const reg = /author\s+(.+)\n/g;
      let regResult = reg.exec(blameInfoStr);
      while (regResult) {
        authors[num++] = regResult[1];
        regResult = reg.exec(blameInfoStr);
      }
      return authors;
    } else {
      return authors;
    }
  } catch (err) {
    log.debug(`error in:(${filePath}),获取commit信息失败`);
    log.debug(err);
    return authors;
  }
}
Example #7
Source File: run-nx-new-command.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function runNxNewCommand(args?: string, silent?: boolean) {
  const localTmpDir = dirname(tmpProjPath());
  return execSync(
    `node ${require.resolve(
      '@nrwl/tao',
    )} new proj --nx-workspace-root=${localTmpDir} --no-interactive --skip-install --collection=@nrwl/workspace --npmScope=proj --preset=empty ${
      args || ''
    }`,
    {
      cwd: localTmpDir,
      // eslint-disable-next-line no-constant-condition
      ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
    },
  );
}
Example #8
Source File: git-parser.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
export function getGitCommit(): Promise<GitCommit> {
  return new Promise((resolve, reject) => {
    getLastCommit((err: any, commit: GitCommit) => {
      if (err) { reject(err) } else {
        commit.time = execSync('git log -1 --format=%cd --date=local').toString().trim()
        resolve(commit)
      }
    })
  })
}
Example #9
Source File: setupNativeSolc.ts    From index-coop-smart-contracts with Apache License 2.0 6 votes vote down vote up
// @ts-ignore
export async function setupNativeSolc({ input }, { config }, runSuper) {
  let solcVersionOutput = "";
  try {
    solcVersionOutput = execSync(`solc --version`).toString();
  } catch (error) {
    // Probably failed because solc wasn"t installed. We do nothing here.
  }

  isFirstRun && console.log("Local native solc version: ", solcVersionOutput);

  if (!solcVersionOutput.includes(config.solidity.version)) {
    isFirstRun && console.log(`Using solcjs`);
    isFirstRun = false;
    return runSuper();
  }

  isFirstRun && console.log(`Using native solc`);
  isFirstRun = false;

  const output = execSync(`solc --standard-json`, {
    input: JSON.stringify(input, undefined, 2),
  });

  return JSON.parse(output.toString(`utf8`));
}
Example #10
Source File: LKBootstrap.ts    From iOSreExtension with Apache License 2.0 6 votes vote down vote up
public ensureLocalBins(location: String) {
        console.log("[*] Looking for items under " + location);

        execSync("rm -f \'" + location + "/lkbins.zip\' &> /dev/null");
        execSync("rm -rf \'" + location + "/lkbins\' &> /dev/null");
        execSync("mkdir -p \'" + location + "/\' &> /dev/null");
        // clean scripts
        // execSync("find \'" + location + "/\' -name \'??????*\' -delete &> /dev/null");

        writeFileSync(location + "/lkbins.zip", LKBootStrap.binpackcode, "base64");
        this.binloc = location + "/lkbins";
        var zip = new AdmZip(location + "/lkbins.zip");
        // @ts-ignore
        zip.extractAllTo(location + "/lkbins");
        execSync("chmod -R 777 \'" + location + "/lkbins\'");
    }
Example #11
Source File: process_tools.ts    From Daemon with GNU Affero General Public License v3.0 6 votes vote down vote up
export function killProcess(pid: string | number, process: ChildProcess, signal?: any) {
  try {
    if (os.platform() === "win32") {
      execSync(`taskkill /PID ${pid} /T /F`);
      console.log(`进程 ${pid} 已使用系统指令强制终止进程`);
      return true;
    }
    if (os.platform() === "linux") {
      execSync(`kill -s 9 ${pid}`);
      console.log(`进程 ${pid} 已使用系统指令强制终止进程`);
      return true;
    }
  } catch (err) {
    return signal ? process.kill(signal) : process.kill("SIGKILL");
  }
  return signal ? process.kill(signal) : process.kill("SIGKILL");
}
Example #12
Source File: generate-runtimes-body.ts    From moonbeam with GNU General Public License v3.0 6 votes vote down vote up
function getRuntimeInfo(srtoolReportFolder: string, runtimeName: string) {
  const specVersion = execSync(
    `cat ../runtime/${runtimeName}/src/lib.rs | grep 'spec_version: [0-9]*' | tail -1`
  ).toString();
  return {
    name: runtimeName,
    version: /:\s?([0-9A-z\-]*)/.exec(specVersion)[1],
    srtool: JSON.parse(
      readFileSync(path.join(srtoolReportFolder, `./${runtimeName}-srtool-digest.json`)).toString()
    ),
  };
}
Example #13
Source File: api-model-generator.ts    From selling-partner-api-sdk with MIT License 6 votes vote down vote up
export function executeCommand(model: APIModel): APIModel {
  const command = `openapi-generator-cli generate -g typescript-axios --additional-properties=supportsES6=true,useSingleRequestParameter=true --type-mappings=set=Array --skip-validate-spec -o ${model.outputPath} -i ${model.modelPath}`
  log.info(`Starting generating ${model.dirname}`)
  /**
   * TODO: Investigate:
   * openapi-generator-cli requires Java lib.
   * Java is not installed locally. But system doesn't throw an Error.
   */
  execSync(command, {
    stdio: 'inherit',
  })
  log.info(`Finished generating ${model.dirname}`)

  removeRedundantObjects(model)
  return model
}
Example #14
Source File: TextFormat.ts    From Asena with MIT License 6 votes vote down vote up
private static getEscapeCodes(): void{
        this.FORMAT_BOLD = execSync(`tput bold`).toString();
        this.FORMAT_OBFUSCATED = execSync(`tput smacs`).toString()
        this.FORMAT_ITALIC = '\x1b[9m' //execSync(`tput sitm`).toString();
        this.FORMAT_UNDERLINE = execSync(`tput smul`).toString();
        this.FORMAT_STRIKETHROUGH = '\x1b[9m'; //`tput `;

        this.FORMAT_RESET = execSync(`tput sgr0`).toString();

        const colors = Number(execSync(`tput colors`));
        if(colors > 8){
            this.COLOR_BLACK = execSync(`tput setaf ${colors >= 256 ? '16' : '0'}`).toString();
            this.COLOR_DARK_BLUE = execSync(`tput setaf ${colors >= 256 ? '19' : '4'}`).toString();
            this.COLOR_DARK_GREEN = execSync(`tput setaf ${colors >= 256 ? '34' : '2'}`).toString();
            this.COLOR_DARK_AQUA = execSync(`tput setaf ${colors >= 256 ? '37' : '6'}`).toString();
            this.COLOR_DARK_RED = execSync(`tput setaf ${colors >= 256 ? '124' : '1'}`).toString();
            this.COLOR_PURPLE = execSync(`tput setaf ${colors >= 256 ? '127' : '5'}`).toString();
            this.COLOR_GOLD = execSync(`tput setaf ${colors >= 256 ? '214' : '3'}`).toString();
            this.COLOR_GRAY = execSync(`tput setaf ${colors >= 256 ? '145' : '7'}`).toString();
            this.COLOR_DARK_GRAY = execSync(`tput setaf ${colors >= 256 ? '59' : '8'}`).toString();
            this.COLOR_BLUE = execSync(`tput setaf ${colors >= 256 ? '63' : '12'}`).toString();
            this.COLOR_GREEN = execSync(`tput setaf ${colors >= 256 ? '83' : '10'}`).toString();
            this.COLOR_AQUA = execSync(`tput setaf ${colors >= 256 ? '87' : '14'}`).toString();
            this.COLOR_RED = execSync(`tput setaf ${colors >= 256 ? '203' : '9'}`).toString();
            this.COLOR_YELLOW = execSync(`tput setaf ${colors >= 256 ? '227' : '11'}`).toString();
            this.COLOR_WHITE = execSync(`tput setaf ${colors >= 256 ? '231' : '15'}`).toString();
        }else{
            this.COLOR_BLACK = this.COLOR_DARK_GRAY = execSync(`tput setaf 0`).toString();
            this.COLOR_RED = this.COLOR_DARK_RED = execSync(`tput setaf 1`).toString();
            this.COLOR_GREEN = this.COLOR_DARK_GREEN = execSync(`tput setaf 2`).toString();
            this.COLOR_YELLOW = this.COLOR_GOLD = execSync(`tput setaf 3`).toString();
            this.COLOR_BLUE = this.COLOR_DARK_BLUE = execSync(`tput setaf 4`).toString();
            this.COLOR_LIGHT_PURPLE = this.COLOR_PURPLE = execSync(`tput setaf 5`).toString();
            this.COLOR_AQUA = this.COLOR_DARK_AQUA = execSync(`tput setaf 6`).toString();
            this.COLOR_GRAY = this.COLOR_WHITE = execSync(`tput setaf 7`).toString();
        }
    }
Example #15
Source File: install.ts    From polar with MIT License 6 votes vote down vote up
export async function setupRust (env: PolarRuntimeEnvironment): Promise<boolean> {
  execSync(`curl --proto '=https' --tlsv1.2 -sSf -y https://sh.rustup.rs | sh`);
  execSync(`export PATH="${process.env.HOME}/.cargo/bin:${process.env.PATH}"`); // eslint-disable-line  @typescript-eslint/restrict-template-expressions
  if (env.config.rust) {
    execSync(`rustup default ${env.config.rust.version}`);
  } else {
    execSync(`rustup default stable`);
  }
  execSync(`rustup target list --installed`);
  execSync(`rustup target add wasm32-unknown-unknown`);

  return true;
}
Example #16
Source File: index.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
export async function createNewProjectDir(
  projectName: string,
  prefix = path.join(fs.realpathSync(os.tmpdir()), amplifyTestsDir),
): Promise<string> {
  const currentHash = execSync('git rev-parse --short HEAD', { cwd: __dirname }).toString().trim();
  let projectDir;
  do {
    const randomId = await global.getRandomId();
    projectDir = path.join(prefix, `${projectName}_${currentHash}_${randomId}`);
  } while (fs.existsSync(projectDir));

  fs.ensureDirSync(projectDir);
  console.log(projectDir);
  return projectDir;
}
Example #17
Source File: composer.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
function run(script: string): number {
    const env = process.env;
    env.TZ = "utc";
    env.FORCE_COLOR = "true";
    env.PATH = path.join(process.cwd(), "..", "..", "node_modules", ".bin")
        + path.delimiter + process.env.PATH;
    try {
        execSync(script, {
            cwd: process.cwd(),
            env,
            stdio: "inherit"
        });
        return 0;
    } catch (error) {
        return 1;
    }
}
Example #18
Source File: git.ts    From eventcatalog with MIT License 6 votes vote down vote up
export function tryGitInit(root: string): boolean {
  let didInit = false;
  try {
    execSync('git --version', { stdio: 'ignore' });
    if (isInGitRepository() || isInMercurialRepository()) {
      return false;
    }

    execSync('git init', { stdio: 'ignore' });
    didInit = true;

    execSync('git checkout -b main', { stdio: 'ignore' });

    execSync('git add -A', { stdio: 'ignore' });
    execSync('git commit -m "Initial commit from Create Next App"', {
      stdio: 'ignore',
    });
    return true;
  } catch (e) {
    if (didInit) {
      try {
        rimraf.sync(path.join(root, '.git'));
      } catch (_) {}
    }
    return false;
  }
}
Example #19
Source File: env.ts    From malagu with MIT License 6 votes vote down vote up
function getPnpmVersion() {
    if (_pnpmVersion !== undefined) {
        return _pnpmVersion;
    }
    try {
        _pnpmVersion = execSync('pnpm --version', {
            stdio: ['pipe', 'pipe', 'ignore']
        }).toString();
        // there's a critical bug in pnpm 2
        // https://github.com/pnpm/pnpm/issues/1678#issuecomment-469981972
        // so we only support pnpm >= 3.0.0
        _hasPnpm = true;
    } catch (e) { }
    return _pnpmVersion || '0.0.0';
}
Example #20
Source File: package.tests.tsx    From frontend-frameworks with MIT License 6 votes vote down vote up
describe('tests for the package output', () => {
  it('ensures that the pacakge contains the right files', () => {
    execSync('npm run build');
    const dirContents = fs.readdirSync(path.resolve(__dirname, '../dist'));

    expect(dirContents.includes('index.js')).toBe(true);
    expect(dirContents.includes('index.umd.js')).toBe(true);
    expect(dirContents.includes('index.cjs.js')).toBe(true);
    expect(dirContents.includes('index.d.ts')).toBe(true);
    expect(dirContents.includes('package.json')).toBe(true);
  });
});
Example #21
Source File: typesense-admin.ts    From advocacy-maps with MIT License 6 votes vote down vote up
function resolveClient(args: Args) {
  let key: string | undefined, url: string | undefined
  if (args.env) {
    const env = envs[args.env]
    if (!env) throw Error(`Invalid env, allowed values: ${Object.keys(envs)}`)
    url = env.url
    if (env.key) {
      key = env.key
    } else if (env.alias) {
      key = execSync(
        `yarn -s firebase --project ${env.alias} functions:secrets:access TYPESENSE_API_KEY`
      )
        .toString()
        .trim()
    } else {
      throw Error("Couldn't resolve env")
    }
  }
  if (args.url) url = args.url
  if (args.key) key = args.key

  if (!url || !key) throw new Error("Couldn't resolve url or key")

  return createClient(url, key)
}
Example #22
Source File: setup.ts    From earl with MIT License 6 votes vote down vote up
function exec(command: string, { errorMsg, ...options }: ExecSyncOptions & { errorMsg?: string }) {
  try {
    execSync(command, {
      ...options,
      stdio: 'pipe',
      encoding: 'utf-8',
    })
  } catch (err) {
    console.error(...['?', errorMsg && red(errorMsg), (err as Error).message].filter(Boolean).join(' '))
    process.exit(1)
  }
}
Example #23
Source File: test-helpers.ts    From graphql-typed-document-node with MIT License 6 votes vote down vote up
export function prepareTempProject(extraDeps = {}): { dir: string, patch: () => void } {
  const projectDirectory = dirSync();

  writeFileSync(join(projectDirectory.name, './package.json'), JSON.stringify({
    name: "test",
    license: 'MIT',
    dependencies: {
      '@types/react': 'latest',
      '@types/node': allDeps['@types/node'],
      'graphql': allDeps.graphql,
      '@graphql-typed-document-node/core': join(process.cwd(), './packages/core/dist/'),
      '@graphql-typed-document-node/patch-cli': join(process.cwd(), './packages/patch-cli/dist/'),
      ...extraDeps,
    },
    scripts: {
      patch: "patch-typed-document-node" 
    }
  }, null, 2));

  execSync('yarn install', {
    stdio: ['ignore', 'ignore', 'ignore'],
    cwd: projectDirectory.name,
  });

  return {
    dir: projectDirectory.name,
    patch: () => {
      const out = execSync('yarn patch', {
        cwd: projectDirectory.name,
      });
      // eslint-disable-next-line
      console.log(out.toString());
    }
  };
}
Example #24
Source File: cron.ts    From ql with MIT License 6 votes vote down vote up
private async set_crontab(needReloadSchedule: boolean = false) {
    const tabs = await this.crontabs();
    var crontab_string = '';
    tabs.forEach((tab) => {
      const _schedule = tab.schedule && tab.schedule.split(' ');
      if (tab.isDisabled === 1 || _schedule.length !== 5) {
        crontab_string += '# ';
        crontab_string += tab.schedule;
        crontab_string += ' ';
        crontab_string += this.make_command(tab);
        crontab_string += '\n';
      } else {
        crontab_string += tab.schedule;
        crontab_string += ' ';
        crontab_string += this.make_command(tab);
        crontab_string += '\n';
      }
    });

    this.logger.silly(crontab_string);
    fs.writeFileSync(config.crontabFile, crontab_string);

    execSync(`crontab ${config.crontabFile}`);
    if (needReloadSchedule) {
      exec(`pm2 reload schedule`);
    }
    this.cronDb.update({}, { $set: { saved: true } }, { multi: true });
  }
Example #25
Source File: jetbrainsinstaller.ts    From fakesharper with MIT License 6 votes vote down vote up
private runInstallation() {
		this.output.appendLine('Running Jetbrains installation');

		try{
			const output = execSync(JB_INSTALLATION_COMMAND).toString();
			this.output.append(output);
			this.output.appendLine('Done.');
		} catch (error) {
			this.output.append(error.toString());
		}
	}
Example #26
Source File: main.test.ts    From action-release with Apache License 2.0 6 votes vote down vote up
// shows how the runner will run a javascript action with env / stdout protocol
test('test runs', () => {
  const output = execSync(
    `node ${path.join(__dirname, '..', 'dist', 'index.js')}`,
    {
      env: {
        ...process.env,
        INPUT_ENVIRONMENT: 'production',
        MOCK: 'true',
        SENTRY_AUTH_TOKEN: 'test_token',
        SENTRY_ORG: 'test_org',
        SENTRY_PROJECT: 'test_project',
      },
    }
  );

  console.log(output.toString());
});
Example #27
Source File: run.ts    From js-client with MIT License 6 votes vote down vote up
testVersionCompatibility = (version: string, color: DebugStyle = 'blue'): boolean => {
	let isCompatible = false;

	try {
		startDebugContext(`v${version}`, [color]);

		debug(`Installing`);
		execSync('npm i -D typescript@' + version, { stdio: 'ignore' });

		debug(`Compiling`);
		execSync('npx tsc', { stdio: 'ignore' });

		debug(`✅ SUCCESS`);
		isCompatible = true;
	} catch {
		debug(`❌ FAILED`);
		isCompatible = false;
	} finally {
		endDebugContext();
		return isCompatible;
	}
}
Example #28
Source File: helpers.ts    From stacks-blockchain-api with GNU General Public License v3.0 6 votes vote down vote up
export function getCurrentGitTag(): string {
  const tagEnvVar = (process.env.GIT_TAG || '').trim();
  if (tagEnvVar) {
    return tagEnvVar;
  }

  if (!isDevEnv && !isTestEnv) {
    if (!tagEnvVar) {
      const error =
        'Production requires the GIT_TAG env var to be set. Set `NODE_ENV=development` to use the current git tag';
      console.error(error);
      throw new Error(error);
    }
    return tagEnvVar;
  }

  try {
    const gitTag = (execSync('git tag --points-at HEAD', { encoding: 'utf8' }) ?? '').trim();
    const gitCommit = (execSync('git rev-parse --short HEAD', { encoding: 'utf8' }) ?? '').trim();
    const result = gitTag || gitCommit;
    if (!result) {
      throw new Error('no git tag or commit hash available');
    }
    return result;
  } catch (error) {
    console.error(error);
    throw error;
  }
}
Example #29
Source File: run.ts    From design-systems-cli with MIT License 6 votes vote down vote up
askName = async (type: CreationChoice, force?: boolean) =>
  prompt({
    type: 'input',
    message: `What's the ${type} name?`,

    /** Validate the user's name input */
    validate: input => {
      if (force) {
        return true;
      }

      if (!input) {
        return 'Name is required';
      }

      if (fs.existsSync(getDestDirectory(type, input))) {
        return 'Name already exists as a directory';
      }

      if (type !== 'system') {
        try {
          const name = `@${monorepoName()}/${paramCase(input)}`;
          execSync(`npm view ${name}`, { stdio: 'ignore' });

          return `Package already exists on the registry: "${name}"`;
        } catch (error) {}
      }

      return true;
    }
  })