quiesco 0.1.1 → 0.3.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/README.md +3 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +16 -1
- package/dist/cli.js.map +1 -1
- package/dist/commands/build.d.ts +21 -0
- package/dist/commands/build.d.ts.map +1 -0
- package/dist/commands/build.js +142 -0
- package/dist/commands/build.js.map +1 -0
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +12 -2
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +8 -7
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/list.d.ts +16 -0
- package/dist/commands/list.d.ts.map +1 -0
- package/dist/commands/list.js +56 -0
- package/dist/commands/list.js.map +1 -0
- package/dist/commands/test.d.ts +28 -1
- package/dist/commands/test.d.ts.map +1 -1
- package/dist/commands/test.js +72 -9
- package/dist/commands/test.js.map +1 -1
- package/dist/commands/ui.d.ts +43 -0
- package/dist/commands/ui.d.ts.map +1 -0
- package/dist/commands/ui.js +121 -0
- package/dist/commands/ui.js.map +1 -0
- package/dist/context.d.ts +43 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +85 -0
- package/dist/context.js.map +1 -1
- package/dist/dev-server.d.ts +17 -0
- package/dist/dev-server.d.ts.map +1 -0
- package/dist/dev-server.js +83 -0
- package/dist/dev-server.js.map +1 -0
- package/dist/progress/render.d.ts +31 -0
- package/dist/progress/render.d.ts.map +1 -0
- package/dist/progress/render.js +89 -0
- package/dist/progress/render.js.map +1 -0
- package/dist/progress/run.d.ts +24 -0
- package/dist/progress/run.d.ts.map +1 -0
- package/dist/progress/run.js +95 -0
- package/dist/progress/run.js.map +1 -0
- package/dist/progress/sticky.d.ts +25 -0
- package/dist/progress/sticky.d.ts.map +1 -0
- package/dist/progress/sticky.js +90 -0
- package/dist/progress/sticky.js.map +1 -0
- package/package.json +3 -3
- package/src/cli.ts +16 -1
- package/src/commands/build.ts +152 -0
- package/src/commands/doctor.ts +12 -2
- package/src/commands/init.ts +9 -7
- package/src/commands/list.ts +65 -0
- package/src/commands/test.ts +83 -10
- package/src/commands/ui.ts +152 -0
- package/src/context.ts +114 -0
- package/src/dev-server.ts +91 -0
- package/src/progress/render.ts +117 -0
- package/src/progress/run.ts +105 -0
- package/src/progress/sticky.ts +95 -0
package/src/context.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { spawn as nodeSpawn } from 'node:child_process';
|
|
6
6
|
import fs from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
7
8
|
import path from 'node:path';
|
|
8
9
|
|
|
9
10
|
export interface ExecResult {
|
|
@@ -21,11 +22,44 @@ export interface CliContext {
|
|
|
21
22
|
exec(command: string, args: readonly string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<ExecResult>;
|
|
22
23
|
/** Run a command with the terminal attached (cucumber-js); resolves with its exit code. */
|
|
23
24
|
run(command: string, args: readonly string[], options?: { cwd?: string; env?: NodeJS.ProcessEnv }): Promise<number>;
|
|
25
|
+
/** Run a command with stdin attached and its output handed to the callbacks (the progress bar keeps the last line). */
|
|
26
|
+
runPiped(command: string, args: readonly string[], options: { cwd?: string; env?: NodeJS.ProcessEnv; onStdout: (chunk: string) => void; onStderr: (chunk: string) => void }): Promise<number>;
|
|
27
|
+
/** The terminal, when stdout is one (null when piped or redirected). */
|
|
28
|
+
terminal: Terminal | null;
|
|
29
|
+
/** Resolve `specifier` as code in `dir` would (the project's own packages); null when it is not installed. */
|
|
30
|
+
resolveFrom(dir: string, specifier: string): string | null;
|
|
24
31
|
readFile(path: string): string | null;
|
|
25
32
|
writeFile(path: string, content: string): void;
|
|
26
33
|
exists(path: string): boolean;
|
|
27
34
|
platform: NodeJS.Platform;
|
|
28
35
|
nodeVersion: string;
|
|
36
|
+
/** Whether a person is at the terminal (stdout is a TTY), not a CI job. */
|
|
37
|
+
interactive: boolean;
|
|
38
|
+
/** Start a long-running process (Metro) in its own process group, its output appended to `logFile`. */
|
|
39
|
+
spawnBackground(command: string, args: readonly string[], options: { cwd: string; env: NodeJS.ProcessEnv; logFile: string }): BackgroundProcess;
|
|
40
|
+
/** GET `url`; null when nothing answers (connection refused, timeout). */
|
|
41
|
+
httpGet(url: string, timeoutMs: number): Promise<{ status: number; body: string } | null>;
|
|
42
|
+
/** Run `cleanup` on Ctrl-C / SIGTERM before exiting; returns a function that removes it. */
|
|
43
|
+
onInterrupt(cleanup: () => Promise<void>): () => void;
|
|
44
|
+
/** Wait (polling a dev server). */
|
|
45
|
+
sleep(ms: number): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface Terminal {
|
|
49
|
+
columns(): number;
|
|
50
|
+
/** Whether colors may be used (a color terminal, NO_COLOR not set). */
|
|
51
|
+
color: boolean;
|
|
52
|
+
stdout(text: string): void;
|
|
53
|
+
stderr(text: string): void;
|
|
54
|
+
/** Called on Ctrl-C without exiting (the child gets the signal too and ends the run); returns a remover. */
|
|
55
|
+
onInterrupt(handler: () => void): () => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface BackgroundProcess {
|
|
59
|
+
/** Resolves with the exit code when the process ends. */
|
|
60
|
+
readonly exited: Promise<number>;
|
|
61
|
+
/** Stop it and everything it started (SIGTERM to the group, SIGKILL after `graceMs`). */
|
|
62
|
+
stop(graceMs?: number): Promise<void>;
|
|
29
63
|
}
|
|
30
64
|
|
|
31
65
|
const isWindows = process.platform === 'win32';
|
|
@@ -52,6 +86,22 @@ export function defaultContext(): CliContext {
|
|
|
52
86
|
child.on('error', () => resolve(127));
|
|
53
87
|
child.on('close', (code) => resolve(code ?? 1));
|
|
54
88
|
}),
|
|
89
|
+
runPiped: (command, args, options) =>
|
|
90
|
+
new Promise((resolve) => {
|
|
91
|
+
const child = nodeSpawn(command, [...args], { cwd: options.cwd, env: options.env ?? process.env, stdio: ['inherit', 'pipe', 'pipe'], shell: isWindows });
|
|
92
|
+
child.stdout?.setEncoding('utf8').on('data', options.onStdout);
|
|
93
|
+
child.stderr?.setEncoding('utf8').on('data', options.onStderr);
|
|
94
|
+
child.on('error', () => resolve(127));
|
|
95
|
+
child.on('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : signal !== null ? 143 : 1)));
|
|
96
|
+
}),
|
|
97
|
+
terminal: process.stdout.isTTY === true ? ttyTerminal() : null,
|
|
98
|
+
resolveFrom: (dir, specifier) => {
|
|
99
|
+
try {
|
|
100
|
+
return createRequire(path.join(dir, 'package.json')).resolve(specifier);
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
},
|
|
55
105
|
readFile: (p) => {
|
|
56
106
|
try {
|
|
57
107
|
return fs.readFileSync(p, 'utf8');
|
|
@@ -66,6 +116,70 @@ export function defaultContext(): CliContext {
|
|
|
66
116
|
exists: (p) => fs.existsSync(p),
|
|
67
117
|
platform: process.platform,
|
|
68
118
|
nodeVersion: process.versions.node,
|
|
119
|
+
interactive: process.stdout.isTTY === true,
|
|
120
|
+
spawnBackground: (command, args, options) => {
|
|
121
|
+
fs.mkdirSync(path.dirname(options.logFile), { recursive: true });
|
|
122
|
+
const log = fs.openSync(options.logFile, 'a');
|
|
123
|
+
// Its own process group (detached): `expo start` starts children; stopping the group stops them all.
|
|
124
|
+
const child = nodeSpawn(command, [...args], { cwd: options.cwd, env: options.env, stdio: ['ignore', log, log], detached: !isWindows, shell: isWindows });
|
|
125
|
+
fs.closeSync(log);
|
|
126
|
+
const exited = new Promise<number>((resolve) => {
|
|
127
|
+
child.on('error', () => resolve(127));
|
|
128
|
+
child.on('exit', (code, signal) => resolve(code ?? (signal !== null ? 128 : 1)));
|
|
129
|
+
});
|
|
130
|
+
const signal = (s: NodeJS.Signals) => {
|
|
131
|
+
try {
|
|
132
|
+
if (!isWindows && child.pid !== undefined) process.kill(-child.pid, s);
|
|
133
|
+
else child.kill(s);
|
|
134
|
+
} catch {
|
|
135
|
+
// already gone
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
exited,
|
|
140
|
+
stop: async (graceMs = 5000) => {
|
|
141
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
142
|
+
signal('SIGTERM');
|
|
143
|
+
const timer = setTimeout(() => signal('SIGKILL'), graceMs);
|
|
144
|
+
await exited;
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
},
|
|
149
|
+
httpGet: async (url, timeoutMs) => {
|
|
150
|
+
try {
|
|
151
|
+
const r = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
152
|
+
return { status: r.status, body: await r.text() };
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
onInterrupt: (cleanup) => {
|
|
158
|
+
const handler = (s: NodeJS.Signals) => {
|
|
159
|
+
void cleanup().finally(() => process.exit(s === 'SIGINT' ? 130 : 143));
|
|
160
|
+
};
|
|
161
|
+
process.once('SIGINT', handler);
|
|
162
|
+
process.once('SIGTERM', handler);
|
|
163
|
+
return () => {
|
|
164
|
+
process.off('SIGINT', handler);
|
|
165
|
+
process.off('SIGTERM', handler);
|
|
166
|
+
};
|
|
167
|
+
},
|
|
168
|
+
sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function ttyTerminal(): Terminal {
|
|
173
|
+
return {
|
|
174
|
+
// Some pseudo-terminals report 0 columns.
|
|
175
|
+
columns: () => (process.stdout.columns > 0 ? process.stdout.columns : 80),
|
|
176
|
+
color: process.env['NO_COLOR'] === undefined && process.stdout.hasColors?.() === true,
|
|
177
|
+
stdout: (text) => void process.stdout.write(text),
|
|
178
|
+
stderr: (text) => void process.stderr.write(text),
|
|
179
|
+
onInterrupt: (handler) => {
|
|
180
|
+
process.on('SIGINT', handler);
|
|
181
|
+
return () => void process.off('SIGINT', handler);
|
|
182
|
+
},
|
|
69
183
|
};
|
|
70
184
|
}
|
|
71
185
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Metro dev server for `quiesco test` (issue #5), like Playwright's `webServer`: when the app loads its JS
|
|
3
|
+
* from Metro (`devClient.metroUrl` on iOS / Android, `apps.web.url` on the web) and nothing answers there,
|
|
4
|
+
* start `expo start` with EXPO_PUBLIC_QUIESCO=1, wait until it is ready, and stop it when the run ends. A
|
|
5
|
+
* Metro that is already running is used as it is. Here, in the CLI, because it is the one process of the run:
|
|
6
|
+
* parallel workers (cucumber-js child processes, Jest workers) would each start and stop their own.
|
|
7
|
+
*/
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
import type { QuiescoConfig } from '@quiesco/core';
|
|
11
|
+
|
|
12
|
+
import type { BackgroundProcess, CliContext, CliPlatform } from './context.js';
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_DEV_SERVER_TIMEOUT_MS = 120_000;
|
|
15
|
+
const POLL_MS = 500;
|
|
16
|
+
const DEFAULT_METRO_URL = 'http://localhost:8081';
|
|
17
|
+
|
|
18
|
+
/** Where the app loads its JS from on `platform`, or null when it does not use a dev server. */
|
|
19
|
+
export function devServerUrl(config: QuiescoConfig, platform: CliPlatform): string | null {
|
|
20
|
+
if (platform === 'web') return config.apps.web?.url ?? null;
|
|
21
|
+
const dc = config.apps[platform]?.devClient;
|
|
22
|
+
return dc === undefined ? null : (dc.metroUrl ?? DEFAULT_METRO_URL);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Whether Metro answers at `url` (its `/status` says `packager-status:running`). */
|
|
26
|
+
export async function metroRunning(ctx: CliContext, url: string): Promise<boolean> {
|
|
27
|
+
const r = await ctx.httpGet(new URL('/status', url).toString(), 2000);
|
|
28
|
+
return r !== null && r.body.includes('packager-status:running');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DevServer {
|
|
32
|
+
/** Stops Metro when this run started it; nothing otherwise. */
|
|
33
|
+
stop(): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const NOTHING: DevServer = { stop: async () => {} };
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Make sure the dev server the app needs is running. Returns how to stop what was started. Throws when it
|
|
40
|
+
* was started but did not become ready (with the end of its log).
|
|
41
|
+
*/
|
|
42
|
+
export async function ensureDevServer(ctx: CliContext, config: QuiescoConfig, platform: CliPlatform): Promise<DevServer> {
|
|
43
|
+
const url = devServerUrl(config, platform);
|
|
44
|
+
if (url === null) return NOTHING;
|
|
45
|
+
if (await metroRunning(ctx, url)) {
|
|
46
|
+
ctx.out(`quiesco: using the Metro dev server at ${url}`);
|
|
47
|
+
return NOTHING;
|
|
48
|
+
}
|
|
49
|
+
const opts = config.devServer ?? {};
|
|
50
|
+
const where = new URL(url);
|
|
51
|
+
if (opts.autoStart === false || !['localhost', '127.0.0.1', '[::1]'].includes(where.hostname)) {
|
|
52
|
+
ctx.out(`quiesco: nothing answers at ${url}; start Metro there (EXPO_PUBLIC_QUIESCO=1 npx expo start) — ${opts.autoStart === false ? 'devServer.autoStart is false' : 'it is not on this machine'}`);
|
|
53
|
+
return NOTHING;
|
|
54
|
+
}
|
|
55
|
+
const port = where.port !== '' ? where.port : where.protocol === 'https:' ? '443' : '80';
|
|
56
|
+
const [command, ...args] = (opts.command ?? ['npx', 'expo', 'start', '--port', '{port}']).map((a) => a.replaceAll('{port}', port));
|
|
57
|
+
if (command === undefined) throw new Error('devServer.command is empty');
|
|
58
|
+
const logFile = path.join(ctx.cwd, config.artifacts?.dir ?? 'artifacts', 'metro.log');
|
|
59
|
+
ctx.out(`quiesco: starting Metro (${[command, ...args].join(' ')}) with EXPO_PUBLIC_QUIESCO=1; log: ${path.relative(ctx.cwd, logFile)}`);
|
|
60
|
+
const proc = ctx.spawnBackground(command, args, { cwd: ctx.cwd, env: { ...ctx.env, EXPO_PUBLIC_QUIESCO: '1' }, logFile });
|
|
61
|
+
const offInterrupt = ctx.onInterrupt(() => proc.stop());
|
|
62
|
+
const server: DevServer = {
|
|
63
|
+
stop: async () => {
|
|
64
|
+
offInterrupt();
|
|
65
|
+
await proc.stop();
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
await waitReady(ctx, url, proc, opts.timeoutMs ?? DEFAULT_DEV_SERVER_TIMEOUT_MS, logFile).catch(async (e: unknown) => {
|
|
69
|
+
await server.stop();
|
|
70
|
+
throw e;
|
|
71
|
+
});
|
|
72
|
+
ctx.out(`quiesco: Metro is ready at ${url}`);
|
|
73
|
+
return server;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function waitReady(ctx: CliContext, url: string, proc: BackgroundProcess, timeoutMs: number, logFile: string): Promise<void> {
|
|
77
|
+
let exitCode: number | null = null;
|
|
78
|
+
void proc.exited.then((c) => (exitCode = c));
|
|
79
|
+
for (let waited = 0; ; waited += POLL_MS) {
|
|
80
|
+
if (await metroRunning(ctx, url)) return;
|
|
81
|
+
if (exitCode !== null) throw new Error(`Metro exited (code ${exitCode}) before it was ready.${tail(ctx, logFile)}`);
|
|
82
|
+
if (waited >= timeoutMs) throw new Error(`Metro was not ready at ${url} within ${timeoutMs}ms (devServer.timeoutMs).${tail(ctx, logFile)}`);
|
|
83
|
+
await ctx.sleep(POLL_MS);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function tail(ctx: CliContext, logFile: string): string {
|
|
88
|
+
const text = ctx.readFile(logFile);
|
|
89
|
+
if (text === null || text.trim() === '') return '';
|
|
90
|
+
return `\nLast lines of ${logFile}:\n${text.trimEnd().split('\n').slice(-15).join('\n')}`;
|
|
91
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The progress bar line of `quiesco test`, from a RunState. Pure (no terminal access) so it can be
|
|
3
|
+
* unit-tested:
|
|
4
|
+
*
|
|
5
|
+
* ▕██████████░░░░░░░░░░▏ 12/30 ✓10 ✗1 ↷1 2m13s ▶ adds a todo
|
|
6
|
+
*
|
|
7
|
+
* - `~30`: the total is an estimate (Vitest) or still growing (Jest).
|
|
8
|
+
* - Several workers: `▶ 1:adds a todo · 2:edits a todo` (worker numbers from 1).
|
|
9
|
+
* - Fits in `width` columns (CJK characters count as two).
|
|
10
|
+
*/
|
|
11
|
+
import type { RunState } from '@quiesco/core';
|
|
12
|
+
|
|
13
|
+
export interface RenderOptions {
|
|
14
|
+
width: number;
|
|
15
|
+
color: boolean;
|
|
16
|
+
/** Bar cells (default 20). */
|
|
17
|
+
barWidth?: number;
|
|
18
|
+
/**
|
|
19
|
+
* When the runner was started (epoch ms): the time shown counts from there, so it includes starting the
|
|
20
|
+
* device and the app. Default: from the first test.
|
|
21
|
+
*/
|
|
22
|
+
since?: number;
|
|
23
|
+
now?: () => number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// eslint-disable-next-line no-control-regex -- ANSI escape sequences start with ESC
|
|
27
|
+
const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
28
|
+
|
|
29
|
+
export function stripAnsi(text: string): string {
|
|
30
|
+
return text.replace(ANSI, '');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** East Asian wide and fullwidth characters, and emoji, take two columns. */
|
|
34
|
+
function isWide(code: number): boolean {
|
|
35
|
+
return (
|
|
36
|
+
(code >= 0x1100 && code <= 0x115f) ||
|
|
37
|
+
(code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
|
|
38
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
39
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
40
|
+
(code >= 0xfe30 && code <= 0xfe4f) ||
|
|
41
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
42
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
43
|
+
(code >= 0x1f300 && code <= 0x1faff) ||
|
|
44
|
+
(code >= 0x20000 && code <= 0x3fffd)
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Terminal columns taken by `text` (ANSI escapes take none). */
|
|
49
|
+
export function textWidth(text: string): number {
|
|
50
|
+
let w = 0;
|
|
51
|
+
for (const ch of stripAnsi(text)) {
|
|
52
|
+
const code = ch.codePointAt(0) ?? 0;
|
|
53
|
+
if (code < 0x20 || (code >= 0x7f && code < 0xa0) || (code >= 0x300 && code <= 0x36f) || code === 0x200d || (code >= 0xfe00 && code <= 0xfe0f)) continue;
|
|
54
|
+
w += isWide(code) ? 2 : 1;
|
|
55
|
+
}
|
|
56
|
+
return w;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Cut plain text (no ANSI) to `width` columns, ending with … when cut. */
|
|
60
|
+
export function truncate(text: string, width: number): string {
|
|
61
|
+
if (width <= 0) return '';
|
|
62
|
+
if (textWidth(text) <= width) return text;
|
|
63
|
+
let out = '';
|
|
64
|
+
let w = 0;
|
|
65
|
+
for (const ch of text) {
|
|
66
|
+
const cw = textWidth(ch);
|
|
67
|
+
if (w + cw > width - 1) break;
|
|
68
|
+
out += ch;
|
|
69
|
+
w += cw;
|
|
70
|
+
}
|
|
71
|
+
return `${out}…`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function formatDuration(ms: number): string {
|
|
75
|
+
const s = Math.floor(ms / 1000);
|
|
76
|
+
if (s < 60) return `${s}s`;
|
|
77
|
+
const m = Math.floor(s / 60);
|
|
78
|
+
if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}s`;
|
|
79
|
+
return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const paint = (on: boolean, code: string, text: string) => (on ? `\u001b[${code}m${text}\u001b[0m` : text);
|
|
83
|
+
|
|
84
|
+
export function renderBar(state: RunState, options: RenderOptions): string {
|
|
85
|
+
const { width, color } = options;
|
|
86
|
+
const cells = options.barWidth ?? 20;
|
|
87
|
+
if (state.phase === 'idle') return truncate('quiesco: waiting for the test runner…', width - 1);
|
|
88
|
+
|
|
89
|
+
const total = state.total;
|
|
90
|
+
const done = state.done;
|
|
91
|
+
const ratio = total > 0 ? Math.min(1, done / total) : 0;
|
|
92
|
+
const filled = Math.round(ratio * cells);
|
|
93
|
+
const failed = state.counts.failed > 0 || state.fileErrors.size > 0 || state.runErrors.length > 0;
|
|
94
|
+
const bar = `▕${paint(color, failed ? '31' : '32', '█'.repeat(filled))}${paint(color, '2', '░'.repeat(cells - filled))}▏`;
|
|
95
|
+
|
|
96
|
+
const totalText = `${state.totalIsApproximate ? '~' : ''}${total}`;
|
|
97
|
+
const c = state.counts;
|
|
98
|
+
const skipped = c.skipped + c.pending + c.todo + c.undefined + c.notRun;
|
|
99
|
+
const parts = [
|
|
100
|
+
`${bar} ${done}/${totalText}`,
|
|
101
|
+
[paint(color, '32', `✓${c.passed}`), ...(c.failed > 0 ? [paint(color, '31', `✗${c.failed}`)] : []), ...(skipped > 0 ? [paint(color, '33', `↷${skipped}`)] : [])].join(' '),
|
|
102
|
+
formatDuration(options.since !== undefined ? Math.max(0, (state.endedAt ?? (options.now ?? Date.now)()) - options.since) : state.elapsedMs),
|
|
103
|
+
];
|
|
104
|
+
let line = parts.join(' ');
|
|
105
|
+
|
|
106
|
+
// What is running now, in the space left.
|
|
107
|
+
const room = width - 1 - textWidth(line) - 4;
|
|
108
|
+
if (state.phase === 'running' && state.running.size > 0 && room > 8) {
|
|
109
|
+
const running = [...state.running.values()].sort((a, b) => (a.worker ?? 0) - (b.worker ?? 0));
|
|
110
|
+
const many = running.length > 1;
|
|
111
|
+
const text = running.map((r) => `${many && r.worker !== undefined ? `${r.worker + 1}:` : ''}${r.test.name}`).join(' · ');
|
|
112
|
+
line += ` ${paint(color, '36', '▶')} ${truncate(text, room)}`;
|
|
113
|
+
} else if (state.phase === 'ended') {
|
|
114
|
+
line += ` ${state.interrupted ? paint(color, '33', 'interrupted') : state.success === true ? paint(color, '32', 'passed') : paint(color, '31', 'failed')}`;
|
|
115
|
+
}
|
|
116
|
+
return textWidth(line) <= width - 1 ? line : truncate(stripAnsi(line), width - 1);
|
|
117
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run the test runner with the progress bar (P3): a run-events socket the runner's Quiesco reporter
|
|
3
|
+
* connects to (QUIESCO_EVENTS), the runner's output piped through so the bar stays on the last line.
|
|
4
|
+
*/
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
|
|
9
|
+
import { RunEventServer, RunState } from '@quiesco/core';
|
|
10
|
+
|
|
11
|
+
import type { CliContext, Terminal } from '../context.js';
|
|
12
|
+
import { renderBar } from './render.js';
|
|
13
|
+
import { StickyTerminal } from './sticky.js';
|
|
14
|
+
|
|
15
|
+
export type RunnerName = 'cucumber' | 'jest' | 'vitest';
|
|
16
|
+
|
|
17
|
+
/** Redraw at most this often for events; the clock ticks once a second. */
|
|
18
|
+
const FRAME_MS = 80;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Whether to show the bar: a terminal, not CI, not turned off (`--no-progress`, QUIESCO_PROGRESS=0).
|
|
22
|
+
*/
|
|
23
|
+
export function progressWanted(ctx: CliContext, noProgressFlag: boolean): ctx is CliContext & { terminal: Terminal } {
|
|
24
|
+
if (noProgressFlag || ctx.terminal === null) return false;
|
|
25
|
+
const env = ctx.env;
|
|
26
|
+
if (env['QUIESCO_PROGRESS'] === '0' || env['QUIESCO_PROGRESS'] === 'false') return false;
|
|
27
|
+
const ci = env['CI'];
|
|
28
|
+
return ci === undefined || ci === '' || ci === '0' || ci === 'false';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The cucumber-js arguments that add Quiesco's events formatter, from the project's own
|
|
33
|
+
* @quiesco/cucumber; [] when it is not installed. The file target keeps the user's stdout formatter
|
|
34
|
+
* (a format without one would replace it).
|
|
35
|
+
*/
|
|
36
|
+
export function cucumberFormatArgs(ctx: CliContext): string[] {
|
|
37
|
+
const file = ctx.resolveFrom(ctx.cwd, '@quiesco/cucumber/events');
|
|
38
|
+
if (file === null) return [];
|
|
39
|
+
const url = pathToFileURL(file).href;
|
|
40
|
+
// Windows: a temp file (cucumber creates the target's directory, which fails for the null device).
|
|
41
|
+
const target = ctx.platform === 'win32' ? path.join(os.tmpdir(), `quiesco-events-${process.pid}.out`) : '/dev/null';
|
|
42
|
+
const descriptor = `"${url}":"${target}"`;
|
|
43
|
+
// Through cmd.exe (Windows runs npx with a shell) the quotes must survive the argument parsing.
|
|
44
|
+
return ['--format', ctx.platform === 'win32' ? `"${descriptor.replaceAll('"', '\\"')}"` : descriptor];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const HINTS: Record<RunnerName, string> = {
|
|
48
|
+
cucumber: "quiesco: no test progress was received. Install @quiesco/cucumber in this project (quiesco test adds its formatter by itself).",
|
|
49
|
+
vitest: "quiesco: no test progress was received. Add quiescoPlugin() to your Vitest config: `import { quiesco, quiescoPlugin } from '@quiesco/vitest/config'` and `plugins: [quiescoPlugin()]`.",
|
|
50
|
+
jest: "quiesco: no test progress was received. Your Jest config replaces the preset's reporters: add '@quiesco/jest/reporter' to `reporters` (next to 'default').",
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export interface ProgressRun {
|
|
54
|
+
command: string;
|
|
55
|
+
args: readonly string[];
|
|
56
|
+
env: NodeJS.ProcessEnv;
|
|
57
|
+
runner: RunnerName;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function runWithProgress(ctx: CliContext & { terminal: Terminal }, run: ProgressRun): Promise<number> {
|
|
61
|
+
const term = ctx.terminal;
|
|
62
|
+
const state = new RunState();
|
|
63
|
+
const since = Date.now();
|
|
64
|
+
const sticky = new StickyTerminal({ write: term.stdout, columns: term.columns });
|
|
65
|
+
const draw = () => sticky.setBar(renderBar(state, { width: term.columns(), color: term.color, since }));
|
|
66
|
+
let frame: NodeJS.Timeout | null = null;
|
|
67
|
+
const schedule = () => {
|
|
68
|
+
frame ??= setTimeout(() => {
|
|
69
|
+
frame = null;
|
|
70
|
+
draw();
|
|
71
|
+
}, FRAME_MS);
|
|
72
|
+
};
|
|
73
|
+
const server = new RunEventServer({
|
|
74
|
+
onEvent: (event) => {
|
|
75
|
+
state.apply(event);
|
|
76
|
+
schedule();
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
await server.listen();
|
|
80
|
+
const clock = setInterval(draw, 1000);
|
|
81
|
+
clock.unref();
|
|
82
|
+
const offInterrupt = term.onInterrupt(() => sticky.stop());
|
|
83
|
+
draw();
|
|
84
|
+
|
|
85
|
+
const env: NodeJS.ProcessEnv = { ...run.env, ...server.env() };
|
|
86
|
+
// The runner's output is a pipe now: keep its colors and width as on the terminal.
|
|
87
|
+
if (term.color && env['FORCE_COLOR'] === undefined && env['NO_COLOR'] === undefined) env['FORCE_COLOR'] = '1';
|
|
88
|
+
if (env['COLUMNS'] === undefined) env['COLUMNS'] = String(term.columns());
|
|
89
|
+
|
|
90
|
+
let code: number;
|
|
91
|
+
try {
|
|
92
|
+
code = await ctx.runPiped(run.command, run.args, { cwd: ctx.cwd, env, onStdout: (c) => sticky.output(c, term.stdout), onStderr: (c) => sticky.output(c, term.stderr) });
|
|
93
|
+
await server.drain();
|
|
94
|
+
} finally {
|
|
95
|
+
clearInterval(clock);
|
|
96
|
+
if (frame !== null) clearTimeout(frame);
|
|
97
|
+
offInterrupt();
|
|
98
|
+
await server.close();
|
|
99
|
+
}
|
|
100
|
+
state.runnerExited(code);
|
|
101
|
+
const received = server.hellos.length > 0;
|
|
102
|
+
sticky.stop(received ? renderBar(state, { width: term.columns(), color: term.color, since }) : undefined);
|
|
103
|
+
if (!received) ctx.err(HINTS[run.runner]);
|
|
104
|
+
return code;
|
|
105
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps one status line at the bottom of the terminal while a child's output scrolls above it.
|
|
3
|
+
*
|
|
4
|
+
* The bottom region is [the child's current unfinished line, if any] + [the status line]. Before the
|
|
5
|
+
* child's output is written the region is erased (cursor up, clear to the end of the screen); complete
|
|
6
|
+
* lines are written; the region is drawn again. An unfinished line (cucumber's progress dots
|
|
7
|
+
* `....F..`) stays visible above the bar and is completed in place by later output.
|
|
8
|
+
*/
|
|
9
|
+
import { textWidth } from './render.js';
|
|
10
|
+
|
|
11
|
+
export interface StickyOutput {
|
|
12
|
+
/** Writes escape sequences and the bottom region (stdout). */
|
|
13
|
+
write(text: string): void;
|
|
14
|
+
/** Current terminal width. */
|
|
15
|
+
columns(): number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export class StickyTerminal {
|
|
19
|
+
private partial = '';
|
|
20
|
+
private bar = '';
|
|
21
|
+
private drawnRows = 0;
|
|
22
|
+
private stopped = false;
|
|
23
|
+
|
|
24
|
+
constructor(private readonly out: StickyOutput) {}
|
|
25
|
+
|
|
26
|
+
/** The child wrote `chunk` (to stdout or stderr: `write` is that stream). */
|
|
27
|
+
output(chunk: string, write: (text: string) => void): void {
|
|
28
|
+
if (this.stopped) {
|
|
29
|
+
write(chunk);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
this.erase();
|
|
33
|
+
const text = this.partial + chunk;
|
|
34
|
+
const nl = text.lastIndexOf('\n');
|
|
35
|
+
if (nl === -1) {
|
|
36
|
+
this.partial = text;
|
|
37
|
+
} else {
|
|
38
|
+
write(text.slice(0, nl + 1));
|
|
39
|
+
this.partial = text.slice(nl + 1);
|
|
40
|
+
}
|
|
41
|
+
this.draw();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Show `line` as the status line (no wider than the terminal). */
|
|
45
|
+
setBar(line: string): void {
|
|
46
|
+
if (this.stopped || line === this.bar) return;
|
|
47
|
+
this.erase();
|
|
48
|
+
this.bar = line;
|
|
49
|
+
this.draw();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Remove the region; write the unfinished line back, then `finalLine` (if any) as plain output. */
|
|
53
|
+
stop(finalLine?: string): void {
|
|
54
|
+
if (this.stopped) return;
|
|
55
|
+
this.erase();
|
|
56
|
+
this.stopped = true;
|
|
57
|
+
let tail = this.partial;
|
|
58
|
+
this.partial = '';
|
|
59
|
+
if (finalLine !== undefined) tail += `${tail === '' ? '' : '\n'}${finalLine}\n`;
|
|
60
|
+
if (tail !== '') this.out.write(tail);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
private visiblePartial(): string {
|
|
64
|
+
// A carriage return inside the unfinished line rewrites it from the start, as a terminal would.
|
|
65
|
+
const cr = this.partial.lastIndexOf('\r');
|
|
66
|
+
return cr === -1 ? this.partial : this.partial.slice(cr + 1);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private rows(text: string): number {
|
|
70
|
+
const cols = Math.max(1, this.out.columns());
|
|
71
|
+
return Math.max(1, Math.ceil(textWidth(text) / cols));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private draw(): void {
|
|
75
|
+
const partial = this.visiblePartial();
|
|
76
|
+
if (partial === '' && this.bar === '') return;
|
|
77
|
+
let text = '';
|
|
78
|
+
let rows = 0;
|
|
79
|
+
if (partial !== '') {
|
|
80
|
+
text += `${partial}\n`;
|
|
81
|
+
rows += this.rows(partial);
|
|
82
|
+
}
|
|
83
|
+
text += this.bar;
|
|
84
|
+
rows += 1;
|
|
85
|
+
this.out.write(text);
|
|
86
|
+
this.drawnRows = rows;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private erase(): void {
|
|
90
|
+
if (this.drawnRows === 0) return;
|
|
91
|
+
const up = this.drawnRows - 1;
|
|
92
|
+
this.out.write(`\r${up > 0 ? `\u001b[${up}A` : ''}\u001b[0J`);
|
|
93
|
+
this.drawnRows = 0;
|
|
94
|
+
}
|
|
95
|
+
}
|