microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
eng/scripts/legacy-helpers.js
51lines · modecode
| 1 | import { spawn, spawnSync } from "child_process"; |
| 2 | import { dirname, resolve } from "path"; |
| 3 | import { fileURLToPath } from "url"; |
| 4 | |
| 5 | const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); |
| 6 | const prettier = resolve(repoRoot, "packages/compiler/node_modules/.bin/prettier"); |
| 7 | const tsc = resolve(repoRoot, "packages/compiler/node_modules/.bin/tsc"); |
| 8 | |
| 9 | // We could use { shell: true } to let Windows find .cmd, but that causes other issues. |
| 10 | // It breaks ENOENT checking for command-not-found and also handles command/args with spaces |
| 11 | // poorly. |
| 12 | const isCmdOnWindows = ["rush", "npm", "code", "code-insiders", "docusaurus", tsc, prettier]; |
| 13 | |
| 14 | export class CommandFailedError extends Error { |
| 15 | constructor(msg, proc) { |
| 16 | super(msg); |
| 17 | this.proc = proc; |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | export function run(command, args, options) { |
| 22 | console.log(); |
| 23 | console.log(`> ${command} ${args.join(" ")}`); |
| 24 | |
| 25 | options = { |
| 26 | stdio: "inherit", |
| 27 | sync: true, |
| 28 | throwOnNonZeroExit: true, |
| 29 | ...options, |
| 30 | }; |
| 31 | |
| 32 | if (process.platform === "win32" && isCmdOnWindows.includes(command)) { |
| 33 | command += ".cmd"; |
| 34 | } |
| 35 | |
| 36 | const proc = (options.sync ? spawnSync : spawn)(command, args, options); |
| 37 | if (proc.error) { |
| 38 | if (options.ignoreCommandNotFound && proc.error.code === "ENOENT") { |
| 39 | console.log(`Skipped: Command \`${command}\` not found.`); |
| 40 | } else { |
| 41 | throw proc.error; |
| 42 | } |
| 43 | } else if (options.throwOnNonZeroExit && proc.status !== undefined && proc.status !== 0) { |
| 44 | throw new CommandFailedError( |
| 45 | `Command \`${command} ${args.join(" ")}\` failed with exit code ${proc.status}`, |
| 46 | proc |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | return proc; |
| 51 | } |
| 52 | |