microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
ee53cc3770641a92bb07e9a3ee4fcf5ff9e1658d

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/internal-build-utils/src/common.ts

97lines · modecode

1import { ChildProcess, spawn, SpawnOptions } from "child_process";
2
3export class CommandFailedError extends Error {
4 constructor(
5 msg: string,
6 public proc: ChildProcess
7 ) {
8 super(msg);
9 }
10}
11
12/**
13 * Return the correct executable name if on unix or windows(with .cmd extension)
14 * @param cmd to run
15 * @returns
16 */
17export function xplatCmd(cmd: string) {
18 return process.platform === "win32" ? `${cmd}.cmd` : cmd;
19}
20
21export interface RunOptions extends SpawnOptions {
22 silent?: boolean;
23 encoding?: string;
24 ignoreCommandNotFound?: boolean;
25 throwOnNonZeroExit?: boolean;
26}
27
28export async function run(command: string, args: string[], options?: RunOptions) {
29 if (!options?.silent) {
30 // eslint-disable-next-line no-console
31 console.log();
32 // eslint-disable-next-line no-console
33 console.log(`> ${command} ${args.join(" ")}`);
34 }
35
36 options = {
37 stdio: "inherit",
38 throwOnNonZeroExit: true,
39 ...options,
40 };
41
42 try {
43 const result = await execAsync(command, args, options);
44 if (options.throwOnNonZeroExit && result.exitCode !== undefined && result.exitCode !== 0) {
45 throw new CommandFailedError(
46 `Command \`${command} ${args.join(" ")}\` failed with exit code ${result.exitCode}`,
47 result.proc
48 );
49 }
50 return result;
51 } catch (e: any) {
52 if (options.ignoreCommandNotFound && e.code === "ENOENT") {
53 // eslint-disable-next-line no-console
54 console.log(`Skipped: Command \`${command}\` not found.`);
55 return { exitCode: 0, stdout: "", stderr: "" };
56 } else {
57 throw e;
58 }
59 }
60}
61
62export async function execAsync(
63 command: string,
64 args: string[],
65 options: SpawnOptions
66): Promise<{ exitCode: number; stdout: string; stderr: string; proc: ChildProcess }> {
67 const child = spawn(command, args, options);
68
69 return new Promise((resolve, reject) => {
70 child.on("error", (error) => {
71 reject(error);
72 });
73 const stdout: Buffer[] = [];
74 const stderr: Buffer[] = [];
75 child.stdout?.on("data", (data) => stdout.push(data));
76 child.stderr?.on("data", (data) => stderr.push(data));
77
78 child.on("exit", (exitCode) => {
79 resolve({
80 exitCode: exitCode ?? -1,
81 stdout: Buffer.concat(stdout).toString(),
82 stderr: Buffer.concat(stderr).toString(),
83 proc: child,
84 });
85 });
86 });
87}
88
89export function clearScreen() {
90 process.stdout.write("\x1bc");
91}
92
93export function logWithTime(msg: string) {
94 const time = new Date().toLocaleTimeString();
95 // eslint-disable-next-line no-console
96 console.log(`[${time}] ${msg}`);
97}
98