buildrush 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +82 -3
- package/SECURITY.md +54 -0
- package/bin/buildrush.js +6 -0
- package/dist/src/adapters.d.ts +23 -0
- package/dist/src/adapters.js +171 -0
- package/dist/src/adapters.js.map +1 -0
- package/dist/src/affected.d.ts +28 -0
- package/dist/src/affected.js +59 -0
- package/dist/src/affected.js.map +1 -0
- package/dist/src/cache.d.ts +94 -0
- package/dist/src/cache.js +362 -0
- package/dist/src/cache.js.map +1 -0
- package/dist/src/cli.d.ts +31 -0
- package/dist/src/cli.js +646 -0
- package/dist/src/cli.js.map +1 -0
- package/dist/src/config.d.ts +82 -0
- package/dist/src/config.js +384 -0
- package/dist/src/config.js.map +1 -0
- package/dist/src/detect.d.ts +12 -0
- package/dist/src/detect.js +68 -0
- package/dist/src/detect.js.map +1 -0
- package/dist/src/doctor.d.ts +6 -0
- package/dist/src/doctor.js +95 -0
- package/dist/src/doctor.js.map +1 -0
- package/dist/src/engine.d.ts +68 -0
- package/dist/src/engine.js +652 -0
- package/dist/src/engine.js.map +1 -0
- package/dist/src/fsindex.d.ts +37 -0
- package/dist/src/fsindex.js +128 -0
- package/dist/src/fsindex.js.map +1 -0
- package/dist/src/fswatch.d.ts +30 -0
- package/dist/src/fswatch.js +141 -0
- package/dist/src/fswatch.js.map +1 -0
- package/dist/src/graph.d.ts +77 -0
- package/dist/src/graph.js +486 -0
- package/dist/src/graph.js.map +1 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.js +9 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/project.d.ts +28 -0
- package/dist/src/project.js +113 -0
- package/dist/src/project.js.map +1 -0
- package/dist/src/runner.d.ts +36 -0
- package/dist/src/runner.js +174 -0
- package/dist/src/runner.js.map +1 -0
- package/dist/src/scheduler.d.ts +30 -0
- package/dist/src/scheduler.js +143 -0
- package/dist/src/scheduler.js.map +1 -0
- package/dist/src/testcache.d.ts +60 -0
- package/dist/src/testcache.js +93 -0
- package/dist/src/testcache.js.map +1 -0
- package/dist/src/util/fsx.d.ts +11 -0
- package/dist/src/util/fsx.js +61 -0
- package/dist/src/util/fsx.js.map +1 -0
- package/dist/src/util/glob.d.ts +19 -0
- package/dist/src/util/glob.js +193 -0
- package/dist/src/util/glob.js.map +1 -0
- package/dist/src/util/hash.d.ts +14 -0
- package/dist/src/util/hash.js +57 -0
- package/dist/src/util/hash.js.map +1 -0
- package/dist/src/util/paths.d.ts +17 -0
- package/dist/src/util/paths.js +67 -0
- package/dist/src/util/paths.js.map +1 -0
- package/dist/src/watch.d.ts +101 -0
- package/dist/src/watch.js +289 -0
- package/dist/src/watch.js.map +1 -0
- package/dist/src/workspaces.d.ts +118 -0
- package/dist/src/workspaces.js +555 -0
- package/dist/src/workspaces.js.map +1 -0
- package/package.json +49 -6
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,646 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { CONFIG_FILE, ConfigError, findProjectRoot, loadConfig } from './config.js';
|
|
5
|
+
import { detectProject, starterConfig } from './detect.js';
|
|
6
|
+
import { closure, expandNames, loadTaskState, readStats, runTasks } from './engine.js';
|
|
7
|
+
import { Project } from './project.js';
|
|
8
|
+
import { selectTests } from './affected.js';
|
|
9
|
+
import { runDoctor } from './doctor.js';
|
|
10
|
+
import { startWatch } from './watch.js';
|
|
11
|
+
import { readJson, writeFileAtomic } from './util/fsx.js';
|
|
12
|
+
import { compileGlobs } from './util/glob.js';
|
|
13
|
+
export const EXIT = { OK: 0, FAILED: 1, USAGE: 2, INTERNAL: 3, CANCELLED: 130 };
|
|
14
|
+
const VERSION = createRequire(import.meta.url)('../../package.json').version;
|
|
15
|
+
const HELP = `buildrush ${VERSION} - local-first incremental build & test engine
|
|
16
|
+
|
|
17
|
+
Usage: buildrush <command> [options]
|
|
18
|
+
|
|
19
|
+
Commands:
|
|
20
|
+
init Create ${CONFIG_FILE} from the detected project
|
|
21
|
+
analyze Summarise the project, tasks and module graph
|
|
22
|
+
graph [--dot|--packages] Print the module dependency graph (JSON, or Graphviz with --dot); --packages: workspace package graph only
|
|
23
|
+
run [task|pipeline...] Run tasks (default pipeline "default") with caching
|
|
24
|
+
build | test | check Shortcuts for the task or pipeline of that name
|
|
25
|
+
explain [task|file] Why tasks ran or were reused; what a file change affects
|
|
26
|
+
cache stats|verify|clean Inspect, verify (--repair) or empty the local cache
|
|
27
|
+
doctor Diagnose environment, config and cache problems
|
|
28
|
+
config validate Validate ${CONFIG_FILE}
|
|
29
|
+
|
|
30
|
+
Options:
|
|
31
|
+
--watch Keep running; re-run affected work on every file change (run/build/test/check)
|
|
32
|
+
--affected Run only tests affected by changes (test tasks; falls back to all tests when unsure).
|
|
33
|
+
In a workspace, also only the tasks of affected packages (changed + dependents)
|
|
34
|
+
--since <git-ref> Baseline for --affected (default HEAD)
|
|
35
|
+
--no-cache Execute everything; do not read or write the cache
|
|
36
|
+
--bail Cancel remaining work after the first failure
|
|
37
|
+
--concurrency <n> Max parallel resource units
|
|
38
|
+
--root <dir> Project directory (default: nearest ${CONFIG_FILE})
|
|
39
|
+
--json Machine-readable output
|
|
40
|
+
--verbose, -v Show task logs and details
|
|
41
|
+
--quiet, -q Only print failures and the final summary
|
|
42
|
+
-h, --help Show help --version Show version
|
|
43
|
+
|
|
44
|
+
Exit codes: 0 success, 1 task failure, 2 usage/config error, 3 internal error, 130 cancelled.
|
|
45
|
+
`;
|
|
46
|
+
export function parseArgs(argv) {
|
|
47
|
+
const flags = {
|
|
48
|
+
json: false, verbose: false, quiet: false, affected: false, noCache: false, bail: false,
|
|
49
|
+
force: false, repair: false, dot: false, help: false, version: false, watch: false,
|
|
50
|
+
packages: false,
|
|
51
|
+
};
|
|
52
|
+
const positional = [];
|
|
53
|
+
const need = (i, name) => {
|
|
54
|
+
const v = argv[i + 1];
|
|
55
|
+
if (v === undefined || v.startsWith('--'))
|
|
56
|
+
throw new UsageError(`${name} requires a value`);
|
|
57
|
+
return v;
|
|
58
|
+
};
|
|
59
|
+
for (let i = 0; i < argv.length; i++) {
|
|
60
|
+
const a = argv[i];
|
|
61
|
+
switch (a) {
|
|
62
|
+
case '--json':
|
|
63
|
+
flags.json = true;
|
|
64
|
+
break;
|
|
65
|
+
case '--verbose':
|
|
66
|
+
case '-v':
|
|
67
|
+
flags.verbose = true;
|
|
68
|
+
break;
|
|
69
|
+
case '--quiet':
|
|
70
|
+
case '-q':
|
|
71
|
+
flags.quiet = true;
|
|
72
|
+
break;
|
|
73
|
+
case '--watch':
|
|
74
|
+
case '-w':
|
|
75
|
+
flags.watch = true;
|
|
76
|
+
break;
|
|
77
|
+
case '--affected':
|
|
78
|
+
flags.affected = true;
|
|
79
|
+
break;
|
|
80
|
+
case '--no-cache':
|
|
81
|
+
flags.noCache = true;
|
|
82
|
+
break;
|
|
83
|
+
case '--bail':
|
|
84
|
+
flags.bail = true;
|
|
85
|
+
break;
|
|
86
|
+
case '--force':
|
|
87
|
+
flags.force = true;
|
|
88
|
+
break;
|
|
89
|
+
case '--repair':
|
|
90
|
+
flags.repair = true;
|
|
91
|
+
break;
|
|
92
|
+
case '--dot':
|
|
93
|
+
flags.dot = true;
|
|
94
|
+
break;
|
|
95
|
+
case '--packages':
|
|
96
|
+
flags.packages = true;
|
|
97
|
+
break;
|
|
98
|
+
case '--help':
|
|
99
|
+
case '-h':
|
|
100
|
+
flags.help = true;
|
|
101
|
+
break;
|
|
102
|
+
case '--version':
|
|
103
|
+
flags.version = true;
|
|
104
|
+
break;
|
|
105
|
+
case '--since':
|
|
106
|
+
flags.since = need(i++, a);
|
|
107
|
+
break;
|
|
108
|
+
case '--root':
|
|
109
|
+
flags.root = need(i++, a);
|
|
110
|
+
break;
|
|
111
|
+
case '--concurrency': {
|
|
112
|
+
const n = Number(need(i++, a));
|
|
113
|
+
if (!Number.isInteger(n) || n < 1)
|
|
114
|
+
throw new UsageError('--concurrency must be a positive integer');
|
|
115
|
+
flags.concurrency = n;
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
case '--':
|
|
119
|
+
positional.push(...argv.slice(i + 1));
|
|
120
|
+
i = argv.length;
|
|
121
|
+
break;
|
|
122
|
+
default:
|
|
123
|
+
if (a.startsWith('-') && a.length > 1)
|
|
124
|
+
throw new UsageError(`unknown option ${a}`);
|
|
125
|
+
positional.push(a);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return { positional, flags };
|
|
129
|
+
}
|
|
130
|
+
class UsageError extends Error {
|
|
131
|
+
}
|
|
132
|
+
const color = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
|
|
133
|
+
const paint = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
134
|
+
const dim = (s) => paint(2, s);
|
|
135
|
+
function fmtMs(ms) {
|
|
136
|
+
return ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)}s`;
|
|
137
|
+
}
|
|
138
|
+
function fmtBytes(n) {
|
|
139
|
+
if (n < 1024)
|
|
140
|
+
return `${n} B`;
|
|
141
|
+
const u = ['KiB', 'MiB', 'GiB', 'TiB'];
|
|
142
|
+
let v = n / 1024;
|
|
143
|
+
let i = 0;
|
|
144
|
+
while (v >= 1024 && i < u.length - 1) {
|
|
145
|
+
v /= 1024;
|
|
146
|
+
i++;
|
|
147
|
+
}
|
|
148
|
+
return `${v.toFixed(1)} ${u[i]}`;
|
|
149
|
+
}
|
|
150
|
+
export async function main(argv) {
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
parsed = parseArgs(argv);
|
|
154
|
+
}
|
|
155
|
+
catch (e) {
|
|
156
|
+
console.error(`buildrush: ${e.message}\nRun \`buildrush --help\` for usage.`);
|
|
157
|
+
return EXIT.USAGE;
|
|
158
|
+
}
|
|
159
|
+
const { positional, flags } = parsed;
|
|
160
|
+
if (flags.version) {
|
|
161
|
+
console.log(VERSION);
|
|
162
|
+
return EXIT.OK;
|
|
163
|
+
}
|
|
164
|
+
const [cmd, ...rest] = positional;
|
|
165
|
+
if (flags.help || !cmd || cmd === 'help') {
|
|
166
|
+
console.log(HELP);
|
|
167
|
+
return cmd || flags.help ? EXIT.OK : EXIT.USAGE;
|
|
168
|
+
}
|
|
169
|
+
const ac = new AbortController();
|
|
170
|
+
let interrupted = 0;
|
|
171
|
+
const onSig = () => {
|
|
172
|
+
if (++interrupted > 1)
|
|
173
|
+
process.exit(EXIT.CANCELLED);
|
|
174
|
+
if (!flags.json)
|
|
175
|
+
console.error('\nbuildrush: cancelling (press Ctrl+C again to force quit)...');
|
|
176
|
+
ac.abort();
|
|
177
|
+
};
|
|
178
|
+
process.on('SIGINT', onSig);
|
|
179
|
+
process.on('SIGTERM', onSig);
|
|
180
|
+
try {
|
|
181
|
+
if (flags.watch && !['run', 'build', 'test', 'check'].includes(cmd))
|
|
182
|
+
throw new UsageError('--watch only applies to run, build, test and check');
|
|
183
|
+
switch (cmd) {
|
|
184
|
+
case 'init': return await cmdInit(flags);
|
|
185
|
+
case 'analyze': return await cmdAnalyze(flags);
|
|
186
|
+
case 'graph': return await cmdGraph(flags);
|
|
187
|
+
case 'run': return await (flags.watch ? cmdWatch : cmdRun)(rest.length ? rest : ['default'], flags, ac.signal);
|
|
188
|
+
case 'build':
|
|
189
|
+
case 'test':
|
|
190
|
+
case 'check': return await (flags.watch ? cmdWatch : cmdRun)([cmd], flags, ac.signal);
|
|
191
|
+
case 'explain': return await cmdExplain(rest[0], flags);
|
|
192
|
+
case 'cache': return await cmdCache(rest[0], flags);
|
|
193
|
+
case 'doctor': return await cmdDoctor(flags);
|
|
194
|
+
case 'config':
|
|
195
|
+
if (rest[0] === 'validate')
|
|
196
|
+
return await cmdValidate(flags);
|
|
197
|
+
throw new UsageError('usage: buildrush config validate');
|
|
198
|
+
default: throw new UsageError(`unknown command ${JSON.stringify(cmd)}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
if (e instanceof UsageError || e instanceof ConfigError) {
|
|
203
|
+
console.error(`buildrush: ${e.message}${e instanceof UsageError ? '\nRun `buildrush --help` for usage.' : ''}`);
|
|
204
|
+
return EXIT.USAGE;
|
|
205
|
+
}
|
|
206
|
+
if (e instanceof Error && /no buildrush\.json|unknown task|dependency cycle/.test(e.message)) {
|
|
207
|
+
console.error(`buildrush: ${e.message}`);
|
|
208
|
+
return EXIT.USAGE;
|
|
209
|
+
}
|
|
210
|
+
throw e;
|
|
211
|
+
}
|
|
212
|
+
finally {
|
|
213
|
+
process.off('SIGINT', onSig);
|
|
214
|
+
process.off('SIGTERM', onSig);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const startDir = (f) => path.resolve(f.root ?? process.cwd());
|
|
218
|
+
const open = (f, scan = true) => Project.open(startDir(f), { scan });
|
|
219
|
+
const printJson = (v) => console.log(JSON.stringify(v, null, 2));
|
|
220
|
+
async function cmdInit(f) {
|
|
221
|
+
const root = startDir(f);
|
|
222
|
+
const file = path.join(root, CONFIG_FILE);
|
|
223
|
+
if (!f.force && (await fs.access(file).then(() => true, () => false))) {
|
|
224
|
+
console.error(`buildrush: ${CONFIG_FILE} already exists (use --force to overwrite)`);
|
|
225
|
+
return EXIT.USAGE;
|
|
226
|
+
}
|
|
227
|
+
const det = await detectProject(root);
|
|
228
|
+
const cfg = starterConfig(det);
|
|
229
|
+
if (Object.keys(cfg.tasks).length === 0) {
|
|
230
|
+
console.error('buildrush: no supported tools or package scripts detected (looked for vite, vitest, eslint, typescript and build/test/lint scripts).\n' +
|
|
231
|
+
`Create ${CONFIG_FILE} by hand; see docs/configuration.md.`);
|
|
232
|
+
return EXIT.USAGE;
|
|
233
|
+
}
|
|
234
|
+
await writeFileAtomic(file, JSON.stringify(cfg, null, 2) + '\n', 0o644);
|
|
235
|
+
if (f.json)
|
|
236
|
+
printJson({ created: file, detected: det });
|
|
237
|
+
else {
|
|
238
|
+
console.log(`Created ${CONFIG_FILE} (${Object.keys(cfg.tasks).join(', ')}).`);
|
|
239
|
+
console.log(`Detected: ${det.packageManager ?? 'no lockfile'}, tools: ${det.tools.join(', ') || 'none'}.`);
|
|
240
|
+
console.log('Next: add ".buildrush/" to .gitignore, review the file, then run `buildrush doctor` and `buildrush run`.');
|
|
241
|
+
}
|
|
242
|
+
return EXIT.OK;
|
|
243
|
+
}
|
|
244
|
+
async function cmdValidate(f) {
|
|
245
|
+
const root = await findProjectRoot(startDir(f));
|
|
246
|
+
if (!root)
|
|
247
|
+
throw new Error(`no ${CONFIG_FILE} found`);
|
|
248
|
+
const cfg = await loadConfig(root);
|
|
249
|
+
if (f.json)
|
|
250
|
+
printJson({ ok: true, tasks: Object.keys(cfg.tasks) });
|
|
251
|
+
else
|
|
252
|
+
console.log(`${CONFIG_FILE} is valid (${Object.keys(cfg.tasks).length} tasks).`);
|
|
253
|
+
return EXIT.OK;
|
|
254
|
+
}
|
|
255
|
+
async function cmdAnalyze(f) {
|
|
256
|
+
const p = await open(f);
|
|
257
|
+
const det = await detectProject(p.root);
|
|
258
|
+
const g = await p.graph();
|
|
259
|
+
await p.saveGraph(g);
|
|
260
|
+
const cycles = g.cycles();
|
|
261
|
+
const uncertain = [...g.modules.values()].filter((m) => m.uncertain.length);
|
|
262
|
+
const edges = [...g.deps.values()].reduce((n, m) => n + m.size, 0);
|
|
263
|
+
const result = {
|
|
264
|
+
project: p.config.project.name,
|
|
265
|
+
root: p.root,
|
|
266
|
+
packageManager: det.packageManager,
|
|
267
|
+
tools: det.tools,
|
|
268
|
+
workspacePackages: Object.fromEntries(g.workspacePackages),
|
|
269
|
+
workspace: p.workspace ? { ...p.workspace.summary(), importEdges: Object.fromEntries(packageImportEdges(g)), cycle: p.workspace.findCycle() } : null,
|
|
270
|
+
files: p.index.files.size,
|
|
271
|
+
modules: g.modules.size,
|
|
272
|
+
edges,
|
|
273
|
+
tests: g.testFiles().length,
|
|
274
|
+
importCycles: cycles,
|
|
275
|
+
uncertainModules: uncertain.map((m) => ({ path: m.path, reasons: m.uncertain })),
|
|
276
|
+
skippedSymlinks: p.index.skippedSymlinks.length,
|
|
277
|
+
tasks: Object.fromEntries(Object.values(p.config.tasks).map((t) => [t.name, { kind: t.kind, dependsOn: t.dependsOn, cache: t.cache }])),
|
|
278
|
+
};
|
|
279
|
+
if (f.json) {
|
|
280
|
+
printJson(result);
|
|
281
|
+
return EXIT.OK;
|
|
282
|
+
}
|
|
283
|
+
console.log(`${result.project} (${p.root})`);
|
|
284
|
+
console.log(` package manager : ${det.packageManager ?? 'none detected'}${det.lockfiles.length > 1 ? ` (WARNING: multiple lockfiles: ${det.lockfiles.join(', ')})` : ''}`);
|
|
285
|
+
console.log(` tools : ${det.tools.join(', ') || 'none detected'}`);
|
|
286
|
+
console.log(` files indexed : ${result.files} modules: ${result.modules} import edges: ${edges} tests: ${result.tests}`);
|
|
287
|
+
if (p.workspace) {
|
|
288
|
+
const ws = p.workspace;
|
|
289
|
+
console.log(` workspace : ${ws.manager} (${ws.source}), ${ws.packages.length} package(s)`);
|
|
290
|
+
for (const k of ws.packages)
|
|
291
|
+
console.log(` - ${k.name}@${k.version ?? '?'} ${k.dir}${k.workspaceDeps.length ? ` -> ${k.workspaceDeps.join(', ')}` : ''}`);
|
|
292
|
+
const cyc = ws.findCycle();
|
|
293
|
+
if (cyc)
|
|
294
|
+
console.log(` WARNING package dependency cycle: ${cyc.join(' -> ')}`);
|
|
295
|
+
for (const w of ws.warnings)
|
|
296
|
+
console.log(` warning: ${w}`);
|
|
297
|
+
}
|
|
298
|
+
else if (g.workspacePackages.size > 1)
|
|
299
|
+
console.log(` workspace pkgs : ${[...g.workspacePackages.keys()].join(', ')}`);
|
|
300
|
+
console.log(` tasks : ${Object.keys(p.config.tasks).join(', ')}`);
|
|
301
|
+
console.log(` import cycles : ${cycles.length}`);
|
|
302
|
+
for (const c of cycles.slice(0, 5))
|
|
303
|
+
console.log(` - ${c.join(' <-> ')}`);
|
|
304
|
+
console.log(` uncertain : ${uncertain.length} module(s) with dynamic/unresolved imports (handled conservatively)`);
|
|
305
|
+
for (const m of uncertain.slice(0, 5))
|
|
306
|
+
console.log(` - ${m.path}: ${m.uncertain[0]}`);
|
|
307
|
+
if (p.index.skippedSymlinks.length)
|
|
308
|
+
console.log(` symlinks : ${p.index.skippedSymlinks.length} skipped (never followed)`);
|
|
309
|
+
return EXIT.OK;
|
|
310
|
+
}
|
|
311
|
+
/** Package -> packages it imports from, as observed in the module graph (sorted, for display). */
|
|
312
|
+
function packageImportEdges(g) {
|
|
313
|
+
return new Map([...g.packageEdges()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, [...v].sort()]));
|
|
314
|
+
}
|
|
315
|
+
async function cmdGraph(f) {
|
|
316
|
+
const p = await open(f);
|
|
317
|
+
const g = await p.graph();
|
|
318
|
+
if (f.packages) {
|
|
319
|
+
if (!p.workspace)
|
|
320
|
+
throw new UsageError('--packages needs a workspace (none detected; see docs/configuration.md)');
|
|
321
|
+
const ws = p.workspace;
|
|
322
|
+
const edges = ws.packages.flatMap((k) => k.workspaceDeps.map((d) => ({ from: k.name, to: d, via: 'package.json' })));
|
|
323
|
+
for (const [from, tos] of packageImportEdges(g))
|
|
324
|
+
for (const to of tos)
|
|
325
|
+
if (!edges.some((e) => e.from === from && e.to === to))
|
|
326
|
+
edges.push({ from, to, via: 'import' });
|
|
327
|
+
if (f.dot) {
|
|
328
|
+
console.log(['digraph packages {', ' rankdir=LR;', ...edges.map((e) => ` ${JSON.stringify(e.from)} -> ${JSON.stringify(e.to)} [label=${JSON.stringify(e.via)}];`), '}'].join('\n'));
|
|
329
|
+
}
|
|
330
|
+
else
|
|
331
|
+
printJson({ packages: ws.summary().packages, edges });
|
|
332
|
+
return EXIT.OK;
|
|
333
|
+
}
|
|
334
|
+
if (f.dot) {
|
|
335
|
+
const lines = ['digraph buildrush {', ' rankdir=LR;'];
|
|
336
|
+
if (p.workspace) {
|
|
337
|
+
p.workspace.packages.forEach((k, i) => {
|
|
338
|
+
const members = [...g.modules.values()].filter((m) => m.pkg === k.name).map((m) => ` ${JSON.stringify(m.path)};`);
|
|
339
|
+
lines.push(` subgraph ${JSON.stringify(`cluster_${i}`)} {`, ` label=${JSON.stringify(k.name)};`, ...members, ' }');
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
for (const [from, m] of g.deps)
|
|
343
|
+
for (const [to, kind] of m)
|
|
344
|
+
lines.push(` ${JSON.stringify(from)} -> ${JSON.stringify(to)} [label=${JSON.stringify(kind)}];`);
|
|
345
|
+
lines.push('}');
|
|
346
|
+
console.log(lines.join('\n'));
|
|
347
|
+
}
|
|
348
|
+
else
|
|
349
|
+
printJson(p.workspace ? { ...g.serialize(), workspace: p.workspace.summary() } : g.serialize());
|
|
350
|
+
return EXIT.OK;
|
|
351
|
+
}
|
|
352
|
+
function line(r, verbose) {
|
|
353
|
+
const label = { cached: '[cached]', succeeded: '[ran]', failed: '[FAILED]', skipped: '[skipped]', cancelled: '[cancelled]', pending: '[pending]', ready: '[ready]', running: '[running]' }[r.state];
|
|
354
|
+
const colored = r.state === 'failed' ? paint(31, label) : r.state === 'cached' ? paint(32, label) : r.state === 'succeeded' ? paint(36, label) : paint(33, label);
|
|
355
|
+
const pad = ' '.repeat(Math.max(0, 11 - label.length));
|
|
356
|
+
let s = `${colored}${pad} ${r.task.padEnd(14)} ${fmtMs(r.durationMs).padStart(7)}`;
|
|
357
|
+
if (r.state === 'cached')
|
|
358
|
+
s += ` ${dim(r.testCache ? `${r.testCache.skipped.length} test file(s) skipped` : `restored ${fmtBytes(r.restoredBytes)}`)}`;
|
|
359
|
+
if (r.testCache) {
|
|
360
|
+
for (const x of r.testCache.skipped)
|
|
361
|
+
s += `\n ${dim(`skip ${x.test}: ${x.reason}`)}`;
|
|
362
|
+
if (verbose)
|
|
363
|
+
for (const x of r.testCache.ran)
|
|
364
|
+
s += `\n ${dim(`run ${x.test}: ${x.reason}`)}`;
|
|
365
|
+
}
|
|
366
|
+
if (r.state === 'succeeded' && r.reasons.length)
|
|
367
|
+
s += ` ${dim('why: ' + r.reasons[0] + (r.reasons.length > 1 ? ` (+${r.reasons.length - 1} more)` : ''))}`;
|
|
368
|
+
if (r.notes.length && (verbose || r.state !== 'cached'))
|
|
369
|
+
for (const n of r.notes)
|
|
370
|
+
s += `\n ${dim('note: ' + n)}`;
|
|
371
|
+
if (verbose && r.reasons.length > 1)
|
|
372
|
+
for (const x of r.reasons.slice(1))
|
|
373
|
+
s += `\n ${dim('why: ' + x)}`;
|
|
374
|
+
return s;
|
|
375
|
+
}
|
|
376
|
+
async function cmdRun(names, f, signal) {
|
|
377
|
+
const p = await open(f);
|
|
378
|
+
for (const n of names) {
|
|
379
|
+
if (!p.config.tasks[n] && !p.config.pipelines[n] && !p.taskGroups[n]) {
|
|
380
|
+
throw new Error(`unknown task ${JSON.stringify(n)} (tasks: ${Object.keys(p.config.tasks).join(', ')}; pipelines: ${Object.keys(p.config.pipelines).join(', ') || 'none'}${Object.keys(p.taskGroups).length ? `; per-package tasks: ${Object.keys(p.taskGroups).join(', ')}` : ''})`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (!f.json && !f.quiet)
|
|
384
|
+
console.log(dim(`BuildRush ${VERSION} · ${p.config.project.name} · ${closure(p, expandNames(p, names)).length} task(s)`));
|
|
385
|
+
const report = await runTasks(p, names, {
|
|
386
|
+
noCache: f.noCache,
|
|
387
|
+
bail: f.bail,
|
|
388
|
+
concurrency: f.concurrency,
|
|
389
|
+
affected: f.affected ? { since: f.since } : null,
|
|
390
|
+
signal,
|
|
391
|
+
onTaskDone: (r) => {
|
|
392
|
+
if (f.json)
|
|
393
|
+
return;
|
|
394
|
+
const bad = r.state === 'failed' || r.state === 'cancelled';
|
|
395
|
+
if (f.quiet && !bad)
|
|
396
|
+
return;
|
|
397
|
+
console.log(line(r, f.verbose));
|
|
398
|
+
for (const d of r.diagnostics.slice(0, 10))
|
|
399
|
+
console.log(` ! ${d}`);
|
|
400
|
+
if (r.log && (r.state === 'failed' || f.verbose))
|
|
401
|
+
console.log(r.log.replace(/\n$/, '').split('\n').map((l) => ' | ' + l).join('\n'));
|
|
402
|
+
},
|
|
403
|
+
});
|
|
404
|
+
await writeFileAtomic(path.join(p.stateDir, 'last-run.json'), JSON.stringify({ at: Date.now(), requested: names, tasks: report.tasks.map((t) => ({ ...t, log: undefined })), selection: report.selection, packages: report.packages ?? null }));
|
|
405
|
+
const count = (s) => report.tasks.filter((t) => t.state === s).length;
|
|
406
|
+
const saved = report.tasks.reduce((n, t) => n + t.savedMsEstimate, 0);
|
|
407
|
+
if (f.json) {
|
|
408
|
+
printJson({ ok: report.ok, cancelled: report.cancelled, durationMs: report.durationMs, selection: report.selection, packages: report.packages ?? null, tasks: report.tasks.map((t) => ({ ...t, log: f.verbose ? t.log : undefined })) });
|
|
409
|
+
}
|
|
410
|
+
else if (!f.quiet || !report.ok) {
|
|
411
|
+
if (report.packages && !f.quiet) {
|
|
412
|
+
const k = report.packages;
|
|
413
|
+
console.log(dim(k.mode === 'all' ? `package selection: ALL packages (${k.reason})` : `package selection: ${k.affected.length} affected (${k.affected.join(', ') || 'none'}), ${k.skipped.length} unaffected`));
|
|
414
|
+
}
|
|
415
|
+
if (report.selection && !f.quiet) {
|
|
416
|
+
const s = report.selection;
|
|
417
|
+
console.log(dim(s.mode === 'all' ? `test selection: ALL tests (${s.reason})` : `test selection: ${s.selected.length} selected, ${s.skipped.length} skipped, ${s.changed.length} changed file(s)`));
|
|
418
|
+
}
|
|
419
|
+
console.log(`\n${report.ok ? 'BuildRush succeeded' : report.cancelled ? 'BuildRush cancelled' : 'BuildRush FAILED'}: ` +
|
|
420
|
+
`${count('succeeded')} ran, ${count('cached')} cached, ${count('failed')} failed, ${count('skipped')} skipped` +
|
|
421
|
+
`${count('cancelled') ? `, ${count('cancelled')} cancelled` : ''} in ${fmtMs(report.durationMs)}` +
|
|
422
|
+
(saved > 0 ? dim(` (estimated time saved by cache: ${fmtMs(saved)}; estimate = original run duration)`) : ''));
|
|
423
|
+
}
|
|
424
|
+
return report.ok ? EXIT.OK : report.cancelled ? EXIT.CANCELLED : EXIT.FAILED;
|
|
425
|
+
}
|
|
426
|
+
async function cmdExplain(target, f) {
|
|
427
|
+
const p = await open(f);
|
|
428
|
+
const last = await readJson(path.join(p.stateDir, 'last-run.json'));
|
|
429
|
+
if (!target) {
|
|
430
|
+
if (!last) {
|
|
431
|
+
console.log('No run recorded yet. Run `buildrush run` first.');
|
|
432
|
+
return EXIT.OK;
|
|
433
|
+
}
|
|
434
|
+
if (f.json) {
|
|
435
|
+
printJson(last);
|
|
436
|
+
return EXIT.OK;
|
|
437
|
+
}
|
|
438
|
+
console.log(`Last run: ${new Date(last.at).toISOString()}`);
|
|
439
|
+
for (const t of last.tasks) {
|
|
440
|
+
console.log(` ${t.task}: ${t.state}${t.cache === 'hit' ? ' (cache hit)' : ''}`);
|
|
441
|
+
for (const r of t.reasons)
|
|
442
|
+
console.log(` why it ran: ${r}`);
|
|
443
|
+
for (const n of t.notes)
|
|
444
|
+
console.log(` note: ${n}`);
|
|
445
|
+
}
|
|
446
|
+
return EXIT.OK;
|
|
447
|
+
}
|
|
448
|
+
if (p.config.tasks[target]) {
|
|
449
|
+
const t = p.config.tasks[target];
|
|
450
|
+
const st = await loadTaskState(p, target);
|
|
451
|
+
const lastRep = last?.tasks.find((x) => x.task === target);
|
|
452
|
+
const info = {
|
|
453
|
+
task: target, command: t.command, dependsOn: t.dependsOn, cache: t.cache,
|
|
454
|
+
lastState: lastRep?.state ?? null, lastReasons: lastRep?.reasons ?? [], lastNotes: lastRep?.notes ?? [],
|
|
455
|
+
lastSuccessfulFingerprint: st?.fingerprint ?? null, inputsAtLastSuccess: st ? Object.keys(st.components.inputs).length : null,
|
|
456
|
+
};
|
|
457
|
+
if (f.json)
|
|
458
|
+
printJson(info);
|
|
459
|
+
else {
|
|
460
|
+
console.log(`${target}: ${t.command.join(' ')}`);
|
|
461
|
+
console.log(` depends on : ${t.dependsOn.join(', ') || '-'}`);
|
|
462
|
+
console.log(` last state : ${info.lastState ?? 'never run'}`);
|
|
463
|
+
for (const r of info.lastReasons)
|
|
464
|
+
console.log(` why it ran: ${r}`);
|
|
465
|
+
for (const n of info.lastNotes)
|
|
466
|
+
console.log(` note: ${n}`);
|
|
467
|
+
if (st)
|
|
468
|
+
console.log(` last good fingerprint: ${st.fingerprint.slice(0, 16)} (${info.inputsAtLastSuccess} input files)`);
|
|
469
|
+
}
|
|
470
|
+
return EXIT.OK;
|
|
471
|
+
}
|
|
472
|
+
// A file: show what it affects.
|
|
473
|
+
const rel = path.relative(p.root, path.resolve(startDir(f), target)).split(path.sep).join('/');
|
|
474
|
+
if (rel.startsWith('..'))
|
|
475
|
+
throw new UsageError(`${target} is outside the project`);
|
|
476
|
+
const g = await p.graph();
|
|
477
|
+
const { reached, conservative } = g.impact([rel]);
|
|
478
|
+
const direct = Object.values(p.config.tasks).filter((t) => t.inputs === null || compileGlobs(t.inputs)(rel)).map((t) => t.name);
|
|
479
|
+
const affectedTasks = new Set(direct);
|
|
480
|
+
for (let grew = true; grew;) {
|
|
481
|
+
grew = false;
|
|
482
|
+
for (const t of Object.values(p.config.tasks))
|
|
483
|
+
if (!affectedTasks.has(t.name) && t.dependsOn.some((d) => affectedTasks.has(d))) {
|
|
484
|
+
affectedTasks.add(t.name);
|
|
485
|
+
grew = true;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const sel = selectTests(g, null, [rel]);
|
|
489
|
+
const owner = p.workspace?.packageOfFile(rel) ?? null;
|
|
490
|
+
const out = {
|
|
491
|
+
file: rel, package: owner?.name ?? null, known: p.index.files.has(rel), affectedTasks: [...affectedTasks], conservative,
|
|
492
|
+
importedBy: [...reached.keys()].filter((k) => k !== rel).map((k) => ({ module: k, chain: g.chain(reached, k) })),
|
|
493
|
+
tests: { mode: sel.mode, selected: sel.selected, chains: sel.chains },
|
|
494
|
+
};
|
|
495
|
+
if (f.json) {
|
|
496
|
+
printJson(out);
|
|
497
|
+
return EXIT.OK;
|
|
498
|
+
}
|
|
499
|
+
console.log(`${rel}${out.known ? '' : ' (not in the index: new, deleted, ignored or outside the project)'}`);
|
|
500
|
+
if (p.workspace)
|
|
501
|
+
console.log(` package : ${out.package ?? '(outside every workspace package)'}`);
|
|
502
|
+
console.log(` tasks affected : ${out.affectedTasks.join(', ') || 'none'}`);
|
|
503
|
+
if (conservative)
|
|
504
|
+
console.log(` CONSERVATIVE : ${conservative} -> all tests run`);
|
|
505
|
+
console.log(` modules affected (${out.importedBy.length}):`);
|
|
506
|
+
for (const m of out.importedBy.slice(0, 15))
|
|
507
|
+
console.log(` ${m.chain.join(' -> ')}`);
|
|
508
|
+
if (out.importedBy.length > 15)
|
|
509
|
+
console.log(` ...and ${out.importedBy.length - 15} more`);
|
|
510
|
+
console.log(` tests selected (${sel.selected.length}${sel.mode === 'all' ? ', all' : ''}): ${sel.selected.slice(0, 10).join(', ') || 'none'}`);
|
|
511
|
+
return EXIT.OK;
|
|
512
|
+
}
|
|
513
|
+
async function cmdCache(sub, f) {
|
|
514
|
+
const p = await open(f, false);
|
|
515
|
+
switch (sub) {
|
|
516
|
+
case 'stats': {
|
|
517
|
+
const s = await p.cache.stats();
|
|
518
|
+
const life = await readStats(p);
|
|
519
|
+
if (f.json) {
|
|
520
|
+
printJson({ ...s, lifetime: life });
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
console.log(`cache: ${s.dir}`);
|
|
524
|
+
console.log(` entries ${s.entries}, blobs ${s.blobs}, size ${fmtBytes(s.bytes)} (limit ${p.config.cache.maxSizeMB} MiB)`);
|
|
525
|
+
console.log(` lifetime: ${life.hits} hit(s), ${life.misses} miss(es), restored ${fmtBytes(life.bytesRestored)}, stored ${fmtBytes(life.bytesStored)}`);
|
|
526
|
+
console.log(` estimated time saved: ${fmtMs(life.estimatedSavedMs)} (estimate: sum of original durations of reused results)`);
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
case 'verify': {
|
|
530
|
+
const r = await p.cache.verify({ repair: f.repair });
|
|
531
|
+
if (f.json)
|
|
532
|
+
printJson(r);
|
|
533
|
+
else {
|
|
534
|
+
console.log(`verified ${r.entries} entries, ${r.blobs} blobs: ${r.corruptBlobs.length} corrupt blob(s), ${r.badEntries.length} bad entr(ies), ${r.missingBlobs.length} missing blob reference(s)`);
|
|
535
|
+
if (f.repair)
|
|
536
|
+
console.log(`repaired: ${r.repaired}`);
|
|
537
|
+
}
|
|
538
|
+
return r.corruptBlobs.length + r.badEntries.length + r.missingBlobs.length > 0 && !f.repair ? EXIT.FAILED : EXIT.OK;
|
|
539
|
+
}
|
|
540
|
+
case 'clean': {
|
|
541
|
+
await p.cache.clean();
|
|
542
|
+
await fs.rm(path.join(p.stateDir, 'tasks'), { recursive: true, force: true });
|
|
543
|
+
if (f.json)
|
|
544
|
+
printJson({ cleaned: true });
|
|
545
|
+
else
|
|
546
|
+
console.log('cache cleaned.');
|
|
547
|
+
break;
|
|
548
|
+
}
|
|
549
|
+
default: throw new UsageError('usage: buildrush cache stats|verify|clean');
|
|
550
|
+
}
|
|
551
|
+
return EXIT.OK;
|
|
552
|
+
}
|
|
553
|
+
async function cmdDoctor(f) {
|
|
554
|
+
const checks = await runDoctor(startDir(f));
|
|
555
|
+
if (f.json)
|
|
556
|
+
printJson(checks);
|
|
557
|
+
else {
|
|
558
|
+
for (const c of checks)
|
|
559
|
+
console.log(`${{ ok: '[ok] ', warn: '[warn]', fail: '[FAIL]' }[c.status]} ${c.name}: ${c.detail}`);
|
|
560
|
+
}
|
|
561
|
+
return checks.some((c) => c.status === 'fail') ? EXIT.FAILED : EXIT.OK;
|
|
562
|
+
}
|
|
563
|
+
// ---- watch mode ---------------------------------------------------------------------------------
|
|
564
|
+
function describeChanges(c) {
|
|
565
|
+
const all = [...c.added.map((x) => `+${x}`), ...c.modified.map((x) => `~${x}`), ...c.removed.map((x) => `-${x}`)];
|
|
566
|
+
return all.slice(0, 6).join(' ') + (all.length > 6 ? ` ...and ${all.length - 6} more` : '');
|
|
567
|
+
}
|
|
568
|
+
async function cmdWatch(names, f, signal) {
|
|
569
|
+
const p = await open(f);
|
|
570
|
+
for (const n of names) {
|
|
571
|
+
if (!p.config.tasks[n] && !p.config.pipelines[n]) {
|
|
572
|
+
throw new Error(`unknown task ${JSON.stringify(n)} (tasks: ${Object.keys(p.config.tasks).join(', ')}; pipelines: ${Object.keys(p.config.pipelines).join(', ') || 'none'})`);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (!f.json && !f.quiet)
|
|
576
|
+
console.log(dim(`BuildRush ${VERSION} · ${p.config.project.name} · watching ${closure(p, expandNames(p, names)).length} task(s) · Ctrl+C to stop`));
|
|
577
|
+
let writes = Promise.resolve();
|
|
578
|
+
const session = await startWatch(p, {
|
|
579
|
+
tasks: names,
|
|
580
|
+
run: { noCache: f.noCache, bail: f.bail, concurrency: f.concurrency, affected: f.affected ? { since: f.since } : null },
|
|
581
|
+
signal,
|
|
582
|
+
onNotice: (m) => console.error(`buildrush: ${m}`),
|
|
583
|
+
onCycleStart: ({ n, trigger, changed }) => {
|
|
584
|
+
if (f.json || f.quiet)
|
|
585
|
+
return;
|
|
586
|
+
const what = trigger === 'initial' ? 'initial run' : describeChanges(changed);
|
|
587
|
+
const how = trigger === 'reconcile' ? ' (found by reconciliation scan; the watcher did not report it)' : trigger === 'error' ? ' (found after a watcher error)' : '';
|
|
588
|
+
console.log(`\n${dim(`--- cycle ${n}: ${what}${how}`)}`);
|
|
589
|
+
},
|
|
590
|
+
onTaskDone: (r) => {
|
|
591
|
+
if (f.json)
|
|
592
|
+
return;
|
|
593
|
+
const bad = r.state === 'failed' || r.state === 'cancelled';
|
|
594
|
+
if (f.quiet && !bad)
|
|
595
|
+
return;
|
|
596
|
+
console.log(line(r, f.verbose));
|
|
597
|
+
for (const d of r.diagnostics.slice(0, 10))
|
|
598
|
+
console.log(` ! ${d}`);
|
|
599
|
+
if (r.log && (r.state === 'failed' || f.verbose))
|
|
600
|
+
console.log(r.log.replace(/\n$/, '').split('\n').map((l) => ' | ' + l).join('\n'));
|
|
601
|
+
},
|
|
602
|
+
onCycle: (c) => {
|
|
603
|
+
const tasks = c.report?.tasks ?? [];
|
|
604
|
+
const count = (s) => tasks.filter((t) => t.state === s).length;
|
|
605
|
+
if (c.report && !c.superseded) {
|
|
606
|
+
const r = c.report;
|
|
607
|
+
writes = writes.then(() => writeFileAtomic(path.join(p.stateDir, 'last-run.json'), JSON.stringify({ at: Date.now(), requested: names, tasks: r.tasks.map((t) => ({ ...t, log: undefined })), selection: r.selection })).catch(() => undefined));
|
|
608
|
+
}
|
|
609
|
+
if (f.json) {
|
|
610
|
+
console.log(JSON.stringify({
|
|
611
|
+
cycle: c.n, trigger: c.trigger, at: new Date().toISOString(), changed: c.changed,
|
|
612
|
+
ok: c.report?.ok ?? false, cancelled: c.report?.cancelled ?? false, superseded: c.superseded,
|
|
613
|
+
configReloaded: c.configReloaded, error: c.error, scanMs: c.scanMs, durationMs: c.durationMs,
|
|
614
|
+
counts: { ran: count('succeeded'), cached: count('cached'), failed: count('failed'), skipped: count('skipped'), cancelled: count('cancelled') },
|
|
615
|
+
selection: c.report?.selection ?? null,
|
|
616
|
+
tasks: tasks.map((t) => ({ ...t, log: f.verbose ? t.log : undefined })),
|
|
617
|
+
}));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
if (c.configReloaded)
|
|
621
|
+
console.log(dim('configuration reloaded'));
|
|
622
|
+
if (c.error) {
|
|
623
|
+
console.log(paint(31, `cycle ${c.n} error: ${c.error}`) + dim(' (waiting for changes)'));
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
if (c.superseded) {
|
|
627
|
+
console.log(paint(33, `cycle ${c.n} superseded by newer changes after ${fmtMs(c.durationMs)}; results discarded, restarting`));
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
if (c.report?.cancelled) {
|
|
631
|
+
console.log(paint(33, `cycle ${c.n} cancelled after ${fmtMs(c.durationMs)}`));
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
if (!f.quiet || !c.report?.ok) {
|
|
635
|
+
console.log(`${c.report?.ok ? 'ok' : paint(31, 'FAILED')} cycle ${c.n}: ${count('succeeded')} ran, ${count('cached')} cached, ${count('failed')} failed, ${count('skipped')} skipped in ${fmtMs(c.durationMs)}` +
|
|
636
|
+
dim(' (waiting for changes)'));
|
|
637
|
+
}
|
|
638
|
+
},
|
|
639
|
+
});
|
|
640
|
+
await session.done;
|
|
641
|
+
await writes;
|
|
642
|
+
if (!f.json)
|
|
643
|
+
console.log(dim('\nwatch stopped.'));
|
|
644
|
+
return EXIT.OK;
|
|
645
|
+
}
|
|
646
|
+
//# sourceMappingURL=cli.js.map
|