-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun-scripts.ts
131 lines (123 loc) · 5.77 KB
/
run-scripts.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// run-scripts-util ~~ MIT License
// Imports
import { spawn, spawnSync } from 'node:child_process';
import chalk from 'chalk';
import fs from 'fs';
import log from 'fancy-log';
// Types
export type Settings = {
continueOnError: boolean, //do not throw an exception if a task exits with an error status
only: number | null, //execute just one command in the group (starts with 1)
quiet: boolean, //suppress informational messages
verbose: boolean, //add script group name to informational messages
};
export type ProcessInfo = {
group: string,
step: number,
start: number,
pid: number | null,
code: number,
ms: number,
};
type Pkg = {
runScriptsConfig?: { [key: string]: string | { [key: string]: string[] } },
scripts?: { [key: string]: string },
};
// Reporting
const arrow = chalk.gray.bold('→');
const createLogger = (settings: Settings) =>
(...args: string[]) => !settings.quiet && log(chalk.gray('run-scripts'), ...args);
const runScripts = {
exec(group: string, options?: Partial<Settings>) {
// Example that runs spawnSync() for each of the 4 "compile" commands:
// runScripts.exec('compile', { verbose: true });
// [package.json]
// "runScriptsConfig": {
// "clean": [
// "rimraf build dist"
// ],
// "compile": [
// "tsc",
// "lessc src/web-app/style.less build/web-app/style.css",
// "copy-folder src/graphics build/my-app/graphics",
// "replacer src/web-app --ext=.html build/my-app"
// ]
// },
// "scripts": {
// "pretest": "run-scripts clean compile",
// "test": "mocha spec"
// },
const defaults = {
continueOnError: false,
only: null,
quiet: false,
verbose: false,
};
const settings = { ...defaults, ...options };
const pkg = <Pkg>JSON.parse(fs.readFileSync('package.json', 'utf-8'));
const commands = pkg.runScriptsConfig?.[group] ?? [pkg.scripts?.[group]];
const logger = createLogger(settings);
if (!Array.isArray(commands) || commands.some(command => typeof command !== 'string'))
throw new Error('[run-scripts-util] Cannot find commands: ' + group);
const execCommand = (step: number, command: string) => {
const startTime = Date.now();
if (!settings.quiet)
console.log();
const logItems = [chalk.white(group)];
if (settings.verbose)
logItems.push(chalk.yellow(step), arrow);
logger(...logItems, chalk.cyanBright(command));
const task = spawnSync(command, { shell: true, stdio: 'inherit' });
const errorMessage = () => `Task: ${group} (step ${step}), Status: ${task.status}`;
if (task.status !== 0 && settings.continueOnError)
logger(chalk.red('ERROR'), chalk.white('-->'), errorMessage());
if (task.status !== 0 && !settings.continueOnError)
throw new Error('[run-scripts-util] ' + errorMessage() + '\nCommand: ' + command);
logger(...logItems, chalk.green('done'), chalk.white(`(${Date.now() - startTime}ms)`));
};
const skip = (step: number, command: string) => {
const active = settings.only === null || step === settings.only;
const commentedOut = command.startsWith('//');
if (commentedOut)
logger(chalk.yellow('skipping:'), command);
return !active || commentedOut;
};
const processCommand = (command: string, index: number) =>
!skip(index + 1, command) && execCommand(index + 1, command);
(<string[]>commands).forEach(processCommand);
},
execParallel(group: string, options?: Partial<Settings>) {
const defaults = {
continueOnError: false,
only: null,
quiet: false,
verbose: false,
};
const settings = { ...defaults, ...options };
const pkg = <Pkg>JSON.parse(fs.readFileSync('package.json', 'utf-8'));
const commands = pkg.runScriptsConfig?.[group] ?? [pkg.scripts?.[group]];
if (!Array.isArray(commands) || commands.some(command => typeof command !== 'string'))
throw new Error('[run-scripts-util] Cannot find commands: ' + group);
const logger = createLogger(settings);
const active = (step: number) => settings.only === null || step === settings.only;
const process = (step: number, command: string): Promise<ProcessInfo> => new Promise((resolve) => {
const start = Date.now();
const task = spawn(command, { shell: true, stdio: 'inherit' });
const pid = task.pid ?? null;
const logItems = [chalk.white(group), chalk.yellow(step)];
if (settings.verbose)
logItems.push(chalk.magenta('pid: ' + String(pid)), arrow);
logger(...logItems, chalk.cyanBright(command));
const processInfo = (code: number, ms: number): ProcessInfo =>
({ group, step, pid, start, code, ms });
task.on('close', (code: number) => resolve(processInfo(code, Date.now() - start)));
task.on('close', (code: number) => logger(...logItems, chalk.green('done'),
chalk.white(`(code: ${code}, ${Date.now() - start}ms)`)));
});
const createProcess = (command: string, index: number): Promise<ProcessInfo | null> =>
active(index + 1) ? process(index + 1, command) : Promise.resolve(null);
logger(chalk.white(group), chalk.blue('--parallel'));
return Promise.all((<string[]>commands).map(createProcess));
},
};
export { runScripts };