@codifycli/plugin-test 1.1.0-beta7 → 2.0.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/.github/workflows/publish.yaml +83 -0
- package/CLAUDE.md +17 -11
- package/dist/plugin-process.d.ts +8 -0
- package/dist/plugin-process.js +38 -3
- package/dist/plugin-process.js.map +1 -1
- package/dist/plugin-tester.d.ts +2 -0
- package/dist/plugin-tester.js +61 -37
- package/dist/plugin-tester.js.map +1 -1
- package/dist/spawn.d.ts +8 -0
- package/dist/spawn.js +59 -20
- package/dist/spawn.js.map +1 -1
- package/dist/terminal-lines.d.ts +19 -0
- package/dist/terminal-lines.js +97 -0
- package/dist/terminal-lines.js.map +1 -0
- package/dist/test-utils.js +14 -4
- package/dist/test-utils.js.map +1 -1
- package/dist/utils.d.ts +9 -1
- package/dist/utils.js +60 -1
- package/dist/utils.js.map +1 -1
- package/package.json +8 -8
- package/src/plugin-process.ts +45 -3
- package/src/plugin-tester.ts +66 -43
- package/src/spawn.ts +70 -22
- package/src/terminal-lines.test.ts +77 -0
- package/src/terminal-lines.ts +115 -0
- package/src/test-utils.test.ts +1 -1
- package/src/test-utils.ts +16 -4
- package/src/utils.test.ts +14 -0
- package/src/utils.ts +70 -1
- package/test/output-plugin.mjs +19 -0
- package/test/plugin-output.test.ts +36 -0
- package/test/plugin-tester.test.ts +48 -3
- package/test/test-plugin.ts +40 -7
- package/.claude/settings.local.json +0 -5
package/src/plugin-tester.ts
CHANGED
|
@@ -8,7 +8,7 @@ import chalk from 'chalk';
|
|
|
8
8
|
import unionBy from 'lodash.unionby';
|
|
9
9
|
|
|
10
10
|
import { PluginProcess } from './plugin-process.js';
|
|
11
|
-
import {
|
|
11
|
+
import { appliesToCurrentPlatform, splitUserConfig } from './utils.js';
|
|
12
12
|
|
|
13
13
|
export interface FullTestOptions {
|
|
14
14
|
skipUninstall?: boolean,
|
|
@@ -33,7 +33,8 @@ export class PluginTester {
|
|
|
33
33
|
configs: ResourceConfig[],
|
|
34
34
|
options?: FullTestOptions,
|
|
35
35
|
): Promise<void> {
|
|
36
|
-
configs = configs.filter((c) =>
|
|
36
|
+
configs = configs.filter((c) => appliesToCurrentPlatform(c));
|
|
37
|
+
const modifiedConfigs = options?.testModify?.modifiedConfigs.filter((c) => appliesToCurrentPlatform(c));
|
|
37
38
|
const ids = configs
|
|
38
39
|
.map((c) => `${c.type}${c.name ? `.${c.name}` : ''}`)
|
|
39
40
|
.join(', ')
|
|
@@ -45,47 +46,61 @@ export class PluginTester {
|
|
|
45
46
|
await this.ensurePrerequisites(pluginPath, options.prerequisites);
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
// Uninstall also runs when a phase fails, so a failed test doesn't leave resources installed for the next one
|
|
50
|
+
let failed = false;
|
|
50
51
|
try {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
await this.validateExampleAndDefaultConfigs(plugin, configs);
|
|
52
|
+
const plugin = new PluginProcess(pluginPath);
|
|
54
53
|
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
try {
|
|
55
|
+
const resourceTypes = await this.initializeAndValidate(plugin, configs);
|
|
57
56
|
|
|
58
|
-
|
|
59
|
-
await options.validatePlan(plans);
|
|
60
|
-
}
|
|
57
|
+
await this.validateExampleAndDefaultConfigs(plugin, configs, resourceTypes);
|
|
61
58
|
|
|
62
|
-
|
|
63
|
-
|
|
59
|
+
console.info(chalk.cyan('Testing plan...'))
|
|
60
|
+
const plans = await this.planConfigs(plugin, configs);
|
|
64
61
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
} finally {
|
|
69
|
-
plugin.kill();
|
|
70
|
-
}
|
|
62
|
+
if (options?.validatePlan) {
|
|
63
|
+
await options.validatePlan(plans);
|
|
64
|
+
}
|
|
71
65
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
66
|
+
console.info(chalk.cyan('Testing apply...'))
|
|
67
|
+
await this.applyPlans(plugin, plans);
|
|
75
68
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
69
|
+
if (options?.validateApply) {
|
|
70
|
+
await options.validateApply(plans);
|
|
71
|
+
}
|
|
72
|
+
} finally {
|
|
73
|
+
plugin.kill();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (!options?.skipImport) {
|
|
77
|
+
await this.runImportPhase(pluginPath, configs, options?.validateImport);
|
|
78
|
+
}
|
|
79
79
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
80
|
+
if (options?.testModify && modifiedConfigs) {
|
|
81
|
+
await this.runModifyPhase(pluginPath, { ...options.testModify, modifiedConfigs });
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
failed = true;
|
|
85
|
+
throw error;
|
|
86
|
+
} finally {
|
|
87
|
+
if (!skipUninstall) {
|
|
88
|
+
// We need to add unique names to multiple configs with the same type or else it breaks the unionBy below.
|
|
89
|
+
const configsWithNames = this.addNamesToConfigs(configs);
|
|
90
|
+
const modifiedConfigsWithNames = this.addNamesToConfigs(modifiedConfigs ?? [])
|
|
84
91
|
|
|
85
|
-
|
|
92
|
+
const id = (config: ResourceConfig) => config.type + (config.name ? `.${config.name}` : '')
|
|
86
93
|
|
|
87
|
-
|
|
88
|
-
|
|
94
|
+
const configsToDestroy = unionBy(modifiedConfigsWithNames, configsWithNames, id);
|
|
95
|
+
try {
|
|
96
|
+
// validateDestroy only checks a test that succeeded
|
|
97
|
+
await this.uninstall(pluginPath, configsToDestroy.toReversed(), failed ? undefined : options);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
// Don't hide the error that failed the test
|
|
100
|
+
if (!failed) throw error;
|
|
101
|
+
console.error(chalk.red(`Uninstall after the failed test also failed: ${error}`));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
89
104
|
}
|
|
90
105
|
}
|
|
91
106
|
|
|
@@ -145,7 +160,7 @@ export class PluginTester {
|
|
|
145
160
|
}
|
|
146
161
|
|
|
147
162
|
private static async ensurePrerequisites(pluginPath: string, prerequisites: ResourceConfig[]): Promise<void> {
|
|
148
|
-
prerequisites = prerequisites.filter((c) =>
|
|
163
|
+
prerequisites = prerequisites.filter((c) => appliesToCurrentPlatform(c));
|
|
149
164
|
if (prerequisites.length === 0) return;
|
|
150
165
|
|
|
151
166
|
const ids = prerequisites.map((c) => `${c.type}${c.name ? `.${c.name}` : ''}`).join(', ');
|
|
@@ -197,7 +212,8 @@ export class PluginTester {
|
|
|
197
212
|
}
|
|
198
213
|
}
|
|
199
214
|
|
|
200
|
-
|
|
215
|
+
/** Returns the resource types of the plugin */
|
|
216
|
+
private static async initializeAndValidate(plugin: PluginProcess, configs: ResourceConfig[]): Promise<Set<string>> {
|
|
201
217
|
console.info(chalk.cyan('Testing initialization...'))
|
|
202
218
|
const initializeResult = await plugin.initialize();
|
|
203
219
|
|
|
@@ -224,11 +240,14 @@ export class PluginTester {
|
|
|
224
240
|
}));
|
|
225
241
|
throw new Error(`The following configs did not validate:\n ${JSON.stringify(invalidWithConfigs, null, 2)}`)
|
|
226
242
|
}
|
|
243
|
+
|
|
244
|
+
return new Set(initializeResult.resourceDefinitions.map((rd) => rd.type));
|
|
227
245
|
}
|
|
228
246
|
|
|
229
247
|
private static async validateExampleAndDefaultConfigs(
|
|
230
248
|
plugin: PluginProcess,
|
|
231
249
|
configs: ResourceConfig[],
|
|
250
|
+
resourceTypes: Set<string>,
|
|
232
251
|
): Promise<void> {
|
|
233
252
|
console.info(chalk.cyan('Validating examples and default config...'))
|
|
234
253
|
const uniqueTypes = [...new Set(configs.map((c) => c.type))];
|
|
@@ -236,7 +255,7 @@ export class PluginTester {
|
|
|
236
255
|
const errors: string[] = [];
|
|
237
256
|
|
|
238
257
|
for (const type of uniqueTypes) {
|
|
239
|
-
const { defaultConfig, exampleConfigs } = await plugin.getResourceInfo({ type });
|
|
258
|
+
const { defaultConfig, exampleConfigs } = (await plugin.getResourceInfo({ type })).registry ?? {};
|
|
240
259
|
|
|
241
260
|
// Validate exampleConfigs — these should be fully valid configs
|
|
242
261
|
const exampleEntries: Array<[string, Array<Record<string, unknown>>]> = [];
|
|
@@ -246,6 +265,13 @@ export class PluginTester {
|
|
|
246
265
|
for (const [label, exampleConfigList] of exampleEntries) {
|
|
247
266
|
for (const [idx, exampleConfig] of exampleConfigList.entries()) {
|
|
248
267
|
const configLabel = `resource '${type}' ${label}[${idx}]`;
|
|
268
|
+
// Examples can include resources of other plugins (ex: installing a prerequisite): only this plugin can
|
|
269
|
+
// validate its own
|
|
270
|
+
if (!resourceTypes.has(exampleConfig.type as string)) {
|
|
271
|
+
console.info(chalk.gray(`Skipping ${configLabel}: '${exampleConfig.type}' is not a resource of this plugin`));
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
|
|
249
275
|
await this.validateSingleExampleConfig(plugin, configLabel, exampleConfig, errors);
|
|
250
276
|
}
|
|
251
277
|
}
|
|
@@ -376,19 +402,16 @@ ${JSON.stringify(modifyPlans, null, 2)}`)
|
|
|
376
402
|
}
|
|
377
403
|
}
|
|
378
404
|
|
|
405
|
+
/** Copies of the configs, with names added when there are several of a type (the caller's configs are kept) */
|
|
379
406
|
private static addNamesToConfigs(configs: ResourceConfig[]): ResourceConfig[] {
|
|
380
407
|
const configsWithNames = new Array<ResourceConfig>();
|
|
381
408
|
|
|
382
409
|
const typeSet = new Set(configs.map((c) => c.type));
|
|
383
410
|
for (const type of typeSet) {
|
|
384
411
|
const sameTypeConfigs = configs.filter((c) => c.type === type);
|
|
385
|
-
|
|
386
|
-
sameTypeConfigs.
|
|
387
|
-
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
configsWithNames.push(...sameTypeConfigs);
|
|
412
|
+
configsWithNames.push(...sameTypeConfigs.map((c, idx) => (
|
|
413
|
+
sameTypeConfigs.length > 1 ? { ...c, name: c.name ?? idx.toString() } : { ...c }
|
|
414
|
+
)));
|
|
392
415
|
}
|
|
393
416
|
|
|
394
417
|
return configsWithNames;
|
package/src/spawn.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { SpawnStatus } from '@codifycli/schemas';
|
|
2
|
-
import * as pty from '
|
|
2
|
+
import * as pty from 'node-pty';
|
|
3
3
|
import stripAnsi from 'strip-ansi';
|
|
4
4
|
|
|
5
5
|
import { Shell, ShellUtils } from './shell.js';
|
|
6
|
+
import { TerminalLines } from './terminal-lines.js';
|
|
6
7
|
|
|
7
8
|
export interface SpawnResult {
|
|
8
9
|
status: SpawnStatus;
|
|
@@ -15,20 +16,31 @@ export interface SpawnOptions {
|
|
|
15
16
|
env?: Record<string, unknown>,
|
|
16
17
|
interactive?: boolean,
|
|
17
18
|
requiresRoot?: boolean,
|
|
19
|
+
// Plugins send it for commands that run sudo themselves (ex: the Homebrew installer). Tests run with passwordless
|
|
20
|
+
// sudo, so the command runs as is
|
|
21
|
+
requiresSudoAskpass?: boolean,
|
|
18
22
|
stdin?: boolean,
|
|
19
23
|
throws?: boolean,
|
|
24
|
+
timeout?: number,
|
|
25
|
+
// Forces the terminal width to 10_000 so output isn't wrapped. On by default: tests parse the output
|
|
26
|
+
disableWrapping?: boolean,
|
|
20
27
|
}
|
|
21
28
|
|
|
22
29
|
export function testSpawn(cmd: string, options?: SpawnOptions): Promise<SpawnResult> {
|
|
23
|
-
return spawnSafe(cmd, { interactive: true, ...options
|
|
30
|
+
return spawnSafe(cmd, { interactive: true, ...options });
|
|
24
31
|
}
|
|
25
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Runs a command in a pty, like the CLI does for the commands plugins request (`src/utils/spawn.ts` in the CLI).
|
|
35
|
+
* Output is printed as the lines a terminal would end up showing (no line per spinner frame), except with `stdin`:
|
|
36
|
+
* then the command has the terminal and gets the output as is.
|
|
37
|
+
*/
|
|
26
38
|
export function spawnSafe(cmd: string, options?: SpawnOptions): Promise<SpawnResult> {
|
|
27
39
|
if (cmd.toLowerCase().includes('sudo')) {
|
|
28
40
|
throw new Error('Command must not include sudo')
|
|
29
41
|
}
|
|
30
42
|
|
|
31
|
-
console.log(`Running command: ${options?.requiresRoot ? 'sudo' : ''}
|
|
43
|
+
console.log(`Running command: ${options?.requiresRoot ? 'sudo ' : ''}${cmd}` + (options?.cwd ? ` (${options?.cwd})` : ''))
|
|
32
44
|
|
|
33
45
|
return new Promise((resolve, reject) => {
|
|
34
46
|
const output: string[] = [];
|
|
@@ -42,53 +54,89 @@ export function spawnSafe(cmd: string, options?: SpawnOptions): Promise<SpawnRes
|
|
|
42
54
|
COMMAND_MODE: 'unix2003',
|
|
43
55
|
COLORTERM: 'truecolor',
|
|
44
56
|
...historyIgnore
|
|
45
|
-
}
|
|
57
|
+
} as unknown as Record<string, string>;
|
|
46
58
|
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
const initialRows = process.stdout.rows ?? 24;
|
|
59
|
+
const disableWrapping = options?.disableWrapping ?? true;
|
|
60
|
+
const columns = () => disableWrapping ? 10_000 : process.stdout.columns ?? 80;
|
|
50
61
|
|
|
51
|
-
|
|
62
|
+
// zsh autocorrect prompts (e.g. "zsh: correct 'config' to '.config' [nyae]?") will hang
|
|
63
|
+
// the pty waiting for interactive input. Can't be disabled via env var; must unset the options explicitly.
|
|
64
|
+
const disableAutocorrect = ShellUtils.getShell() === Shell.ZSH ? 'unsetopt CORRECT CORRECT_ALL 2>/dev/null; ' : '';
|
|
65
|
+
const command = options?.requiresRoot
|
|
66
|
+
? `sudo -E ${ShellUtils.getDefaultShell()} ${options?.interactive ? '-i' : ''} -c "${(disableAutocorrect + cmd).replaceAll('"', '\\"')}"`
|
|
67
|
+
: `${disableAutocorrect}${cmd}`;
|
|
52
68
|
const args = options?.interactive ? ['-i', '-c', command] : ['-c', command]
|
|
53
69
|
|
|
54
70
|
// Run the command in a pty for interactivity
|
|
55
71
|
const mPty = pty.spawn(ShellUtils.getDefaultShell(), args, {
|
|
56
|
-
|
|
57
|
-
cols:
|
|
58
|
-
rows:
|
|
59
|
-
env
|
|
72
|
+
cwd: options?.cwd,
|
|
73
|
+
cols: columns(),
|
|
74
|
+
rows: process.stdout.rows ?? 24,
|
|
75
|
+
env,
|
|
60
76
|
});
|
|
61
77
|
|
|
78
|
+
const lines = options?.stdin ? undefined : new TerminalLines();
|
|
79
|
+
const print = (text: string[]) => {
|
|
80
|
+
if (text.length > 0) {
|
|
81
|
+
process.stdout.write(text.map((line) => `${line}\n`).join(''));
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
|
|
62
85
|
mPty.onData((data) => {
|
|
63
|
-
|
|
86
|
+
if (lines) {
|
|
87
|
+
print(lines.push(data));
|
|
88
|
+
} else {
|
|
89
|
+
process.stdout.write(data);
|
|
90
|
+
}
|
|
91
|
+
|
|
64
92
|
output.push(data.toString());
|
|
65
93
|
})
|
|
66
94
|
|
|
95
|
+
const resizeListener = () => {
|
|
96
|
+
mPty.resize(columns(), process.stdout.rows ?? 24);
|
|
97
|
+
}
|
|
67
98
|
|
|
68
|
-
const stdinListener = (data:
|
|
69
|
-
|
|
70
|
-
mPty.write(data.toString());
|
|
99
|
+
const stdinListener = (data: Buffer | string) => {
|
|
100
|
+
mPty.write(data.toString('binary'));
|
|
71
101
|
}
|
|
72
102
|
|
|
103
|
+
process.stdout.on('resize', resizeListener);
|
|
73
104
|
if (options?.stdin) {
|
|
74
105
|
process.stdin.on('data', stdinListener)
|
|
75
106
|
}
|
|
76
107
|
|
|
77
|
-
|
|
108
|
+
let timer: NodeJS.Timeout | undefined;
|
|
109
|
+
let timedOut = false;
|
|
110
|
+
if (options?.timeout) {
|
|
111
|
+
timer = setTimeout(() => {
|
|
112
|
+
timedOut = true;
|
|
113
|
+
mPty.kill();
|
|
114
|
+
}, options.timeout);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
mPty.onExit((exit) => {
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
process.stdout.off('resize', resizeListener);
|
|
78
120
|
if (options?.stdin) {
|
|
79
121
|
process.stdin.off('data', stdinListener);
|
|
80
122
|
}
|
|
81
123
|
|
|
82
|
-
|
|
124
|
+
if (lines) {
|
|
125
|
+
print([lines.flush()].filter(Boolean));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// node-pty reports exitCode 0 for a command killed by a signal: use the shell's 128 + n
|
|
129
|
+
const exitCode = timedOut ? -1 : (exit.signal ? 128 + exit.signal : exit.exitCode);
|
|
130
|
+
const raw = stripAnsi(output.join('')).replaceAll('\r\n', '\n').replaceAll('\r', '\n').trim();
|
|
83
131
|
|
|
84
|
-
if (options?.throws &&
|
|
85
|
-
reject(new Error(raw));
|
|
132
|
+
if (options?.throws && exitCode !== 0) {
|
|
133
|
+
reject(new Error(timedOut ? `Command timed out after ${options.timeout}ms: ${cmd}\n${raw}` : raw));
|
|
86
134
|
return;
|
|
87
135
|
}
|
|
88
136
|
|
|
89
137
|
resolve({
|
|
90
|
-
status:
|
|
91
|
-
exitCode
|
|
138
|
+
status: exitCode === 0 ? SpawnStatus.SUCCESS : SpawnStatus.ERROR,
|
|
139
|
+
exitCode,
|
|
92
140
|
data: raw,
|
|
93
141
|
})
|
|
94
142
|
})
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { TerminalLines } from './terminal-lines.js';
|
|
4
|
+
|
|
5
|
+
/** Feeds the chunks and returns every line shown, including the last one */
|
|
6
|
+
function lines(chunks: string[]): string[] {
|
|
7
|
+
const terminal = new TerminalLines();
|
|
8
|
+
const shown = chunks.flatMap((chunk) => terminal.push(chunk));
|
|
9
|
+
const last = terminal.flush();
|
|
10
|
+
return last ? [...shown, last] : shown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
describe('TerminalLines', () => {
|
|
14
|
+
it('Keeps only the result of npm\'s spinner (cursor to line start, frame, clear line)', () => {
|
|
15
|
+
const spinner = Array.from({ length: 500 }, (_, i) => `\u001B[1G${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i % 10]}\u001B[0K`);
|
|
16
|
+
expect(lines([...spinner, '\u001B[1G\u001B[0K\nadded 1200 packages in 3s\n'])).toEqual(['added 1200 packages in 3s']);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('Keeps the final state of progress bars redrawn with \\r (curl, Homebrew downloads)', () => {
|
|
20
|
+
const progress = Array.from({ length: 100 }, (_, i) => `\r${'#'.repeat(i / 2)} ${(i + 1).toFixed(1)}%`);
|
|
21
|
+
expect(lines(['==> Downloading https://ghcr.io/v2/homebrew/core/git/blobs/sha256:abc\n', ...progress, '\n',
|
|
22
|
+
'==> Pouring git--2.47.0.arm64_sonoma.bottle.tar.gz\n',
|
|
23
|
+
'🍺 /opt/homebrew/Cellar/git/2.47.0: 1,678 files, 54.4MB\n',
|
|
24
|
+
])).toEqual([
|
|
25
|
+
'==> Downloading https://ghcr.io/v2/homebrew/core/git/blobs/sha256:abc',
|
|
26
|
+
`${'#'.repeat(49)} 100.0%`,
|
|
27
|
+
'==> Pouring git--2.47.0.arm64_sonoma.bottle.tar.gz',
|
|
28
|
+
'🍺 /opt/homebrew/Cellar/git/2.47.0: 1,678 files, 54.4MB',
|
|
29
|
+
]);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
it('Drops apt\'s progress bar drawn on the last row', () => {
|
|
33
|
+
const bar = (percent: number) => `\u001B7\u001B[24;0f\u001B[42m\u001B[30mProgress: [${String(percent).padStart(3)}%]\u001B[49m\u001B[39m [${'#'.repeat(percent / 5).padEnd(20, '.')}] \u001B8`;
|
|
34
|
+
expect(lines([
|
|
35
|
+
'Reading package lists... Done\r\n',
|
|
36
|
+
'0% [Working]\r \rGet:1 http://archive.ubuntu.com/ubuntu noble/main amd64 curl amd64 8.5.0 [227 kB]\r\n',
|
|
37
|
+
bar(0), 'Selecting previously unselected package curl.\r\n', bar(20),
|
|
38
|
+
// The bar split between two chunks
|
|
39
|
+
'Unpacking curl (8.5.0) ...\r\n\u001B7\u001B[24;0fProgress: [ 6', '0%] \u001B8Setting up curl (8.5.0) ...\r\n',
|
|
40
|
+
'\u001B7\u001B[0;23r\u001B8\u001B[1A\u001B[J',
|
|
41
|
+
])).toEqual([
|
|
42
|
+
'Reading package lists... Done',
|
|
43
|
+
'Get:1 http://archive.ubuntu.com/ubuntu noble/main amd64 curl amd64 8.5.0 [227 kB]',
|
|
44
|
+
'Selecting previously unselected package curl.',
|
|
45
|
+
'Unpacking curl (8.5.0) ...',
|
|
46
|
+
'Setting up curl (8.5.0) ...',
|
|
47
|
+
]);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('Removes colors, blank lines and puts escape sequences split between chunks back together', () => {
|
|
51
|
+
expect(lines(['\u001B[32mDown', 'loaded\u001B', '[0m node\r\n\r\n\r\n', '\u001B[1', 'G⠙\u001B[0', 'K\u001B[1G\u001B[0K', 'Done\u001B]0;title', '\u0007\n'])).toEqual(['Downloaded node', 'Done']);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('Keeps text exactly (quotes, variables, multibyte characters)', () => {
|
|
55
|
+
expect(lines(['echo "$HOME" \'`x`\' 🍺 ビール ñ\n'])).toEqual(['echo "$HOME" \'`x`\' 🍺 ビール ñ']);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('Shows a prompt (no newline) as the line in progress', () => {
|
|
59
|
+
const terminal = new TerminalLines();
|
|
60
|
+
expect(terminal.push('Installing...\nContinue? [y/N] ')).toEqual(['Installing...']);
|
|
61
|
+
expect(terminal.current()).toEqual('Continue? [y/N]');
|
|
62
|
+
expect(terminal.flush()).toEqual('Continue? [y/N]');
|
|
63
|
+
expect(terminal.current()).toEqual('');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('Bounds the line in progress and handles floods of tiny chunks', () => {
|
|
67
|
+
const terminal = new TerminalLines();
|
|
68
|
+
const start = performance.now();
|
|
69
|
+
for (let i = 0; i < 200_000; i++) {
|
|
70
|
+
terminal.push(`\u001B[1G${'⠋⠙⠹⠸'[i % 4]}\u001B[0K`);
|
|
71
|
+
terminal.push('#');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
expect(performance.now() - start).toBeLessThan(5000);
|
|
75
|
+
expect(terminal.current().length).toBeLessThanOrEqual(4096);
|
|
76
|
+
});
|
|
77
|
+
});
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Same as TerminalLines in the Codify CLI (src/plugins/terminal-lines.ts): keep them in sync
|
|
2
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Longest line in progress kept (a progress bar that never prints a newline). It may grow to twice this before it is
|
|
6
|
+
* cut, so a flood of small chunks without newlines doesn't copy the whole line for every chunk.
|
|
7
|
+
*/
|
|
8
|
+
const MAX_PARTIAL_LENGTH = 4096;
|
|
9
|
+
|
|
10
|
+
// An escape sequence cut off at the end of a chunk (`ESC`, `ESC[1`, an unfinished `ESC]` title): kept for the next chunk
|
|
11
|
+
// eslint-disable-next-line no-control-regex
|
|
12
|
+
const INCOMPLETE_ESCAPE = /\u001B(?:\[[\d;?]*|\][^\u0007\u001B]{0,256})?$/;
|
|
13
|
+
|
|
14
|
+
// Text drawn somewhere else on the screen between saving and restoring the cursor (`ESC 7` … `ESC 8`, `ESC[s` … `ESC[u`):
|
|
15
|
+
// apt's progress bar on the last row. It isn't part of the output's lines
|
|
16
|
+
// eslint-disable-next-line no-control-regex
|
|
17
|
+
const DRAWN_ELSEWHERE = /\u001B7[\s\S]*?\u001B8|\u001B\[s[\s\S]*?\u001B\[u/g;
|
|
18
|
+
|
|
19
|
+
// A cursor save without its restore yet (the rest is in the next chunk)
|
|
20
|
+
// eslint-disable-next-line no-control-regex
|
|
21
|
+
const UNFINISHED_DRAWN_ELSEWHERE = /(?:\u001B7|\u001B\[s)(?![\s\S]*(?:\u001B8|\u001B\[u))[\s\S]*$/;
|
|
22
|
+
|
|
23
|
+
/** Longest unfinished cursor save kept for the next chunk */
|
|
24
|
+
const MAX_PENDING_LENGTH = 1024;
|
|
25
|
+
|
|
26
|
+
// Cursor to the start of the line (`ESC[G`, `ESC[0G`, `ESC[1G`): progress bars redraw the line with it instead of \r
|
|
27
|
+
// eslint-disable-next-line no-control-regex
|
|
28
|
+
const CURSOR_TO_LINE_START = /\u001B\[[01]?G/g;
|
|
29
|
+
|
|
30
|
+
// A line that only holds spinner frames (npm's `⠼ ⠴ ⠦`, `| / - \`)
|
|
31
|
+
const SPINNER_LINE = /^[⠀-⣿|/\\-]+$/;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Turns command output (chunks as they come from a terminal) into the lines a terminal would end up showing:
|
|
35
|
+
* - a line redrawn with `\r` or cursor-to-line-start (spinners, progress bars) keeps only its final state
|
|
36
|
+
* - spinner-only and blank lines are dropped, escape codes (colors) removed
|
|
37
|
+
* - an escape sequence split between two chunks is put back together
|
|
38
|
+
* - text drawn elsewhere on the screen (apt's progress bar on the last row, between a cursor save and restore) is dropped
|
|
39
|
+
*
|
|
40
|
+
* Only the new chunk is processed: a chunk costs its own size, however long the line in progress is.
|
|
41
|
+
*/
|
|
42
|
+
export class TerminalLines {
|
|
43
|
+
private partial = '';
|
|
44
|
+
private pendingEscape = '';
|
|
45
|
+
|
|
46
|
+
/** Adds a chunk of output and returns the lines it completed */
|
|
47
|
+
push(chunk: string): string[] {
|
|
48
|
+
let raw = (this.pendingEscape + chunk).replaceAll(DRAWN_ELSEWHERE, '');
|
|
49
|
+
const incomplete = UNFINISHED_DRAWN_ELSEWHERE.exec(raw) ?? INCOMPLETE_ESCAPE.exec(raw);
|
|
50
|
+
this.pendingEscape = incomplete && incomplete[0].length <= MAX_PENDING_LENGTH ? incomplete[0] : '';
|
|
51
|
+
if (incomplete) {
|
|
52
|
+
raw = raw.slice(0, incomplete.index);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// \r\n line endings: the \r stays at the end of the line, where cleanLine ignores it
|
|
56
|
+
const parts = stripVTControlCharacters(raw.replaceAll(CURSOR_TO_LINE_START, '\r')).split('\n');
|
|
57
|
+
if (parts.length === 1) {
|
|
58
|
+
this.partial += parts[0];
|
|
59
|
+
if (this.partial.length > MAX_PARTIAL_LENGTH * 2) {
|
|
60
|
+
this.partial = this.partial.slice(-MAX_PARTIAL_LENGTH);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return [];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const lines: string[] = [];
|
|
67
|
+
const add = (text: string) => {
|
|
68
|
+
const line = cleanLine(text);
|
|
69
|
+
if (line) {
|
|
70
|
+
lines.push(line);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
add(this.partial + parts[0]);
|
|
75
|
+
for (let i = 1; i < parts.length - 1; i++) {
|
|
76
|
+
add(parts[i]);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
this.partial = parts.at(-1)!;
|
|
80
|
+
if (this.partial.length > MAX_PARTIAL_LENGTH * 2) {
|
|
81
|
+
this.partial = this.partial.slice(-MAX_PARTIAL_LENGTH);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return lines;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The line in progress, as a terminal shows it ('' if there is nothing to show) */
|
|
88
|
+
current(): string {
|
|
89
|
+
return cleanLine(this.partial.slice(-MAX_PARTIAL_LENGTH));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Ends the line in progress (the command finished): returns it, or '' */
|
|
93
|
+
flush(): string {
|
|
94
|
+
const line = this.current();
|
|
95
|
+
this.partial = '';
|
|
96
|
+
this.pendingEscape = '';
|
|
97
|
+
return line;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* What a terminal shows of a line: the text after the last carriage return (progress bars redraw the line), or ''
|
|
103
|
+
* when nothing is left to show (blank, or only spinner frames).
|
|
104
|
+
*/
|
|
105
|
+
function cleanLine(line: string): string {
|
|
106
|
+
const segments = line.split('\r');
|
|
107
|
+
for (let i = segments.length - 1; i >= 0; i--) {
|
|
108
|
+
const segment = segments[i].trimEnd();
|
|
109
|
+
if (segment.trim()) {
|
|
110
|
+
return SPINNER_LINE.test(segment.trim()) ? '' : segment;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return '';
|
|
115
|
+
}
|
package/src/test-utils.test.ts
CHANGED
|
@@ -48,7 +48,7 @@ describe('Test Utils tests', async () => {
|
|
|
48
48
|
const process = mockChildProcess();
|
|
49
49
|
const requestId = nanoid(6);
|
|
50
50
|
|
|
51
|
-
expect(async () => Promise.all([
|
|
51
|
+
await expect(async () => Promise.all([
|
|
52
52
|
(async () => {
|
|
53
53
|
await sleep(30);
|
|
54
54
|
// Note that the response must end in _Response. In accordance to the message schema rules.
|
package/src/test-utils.ts
CHANGED
|
@@ -25,10 +25,7 @@ export const TestUtils = {
|
|
|
25
25
|
if (response.status === MessageStatus.SUCCESS) {
|
|
26
26
|
resolve(response.data)
|
|
27
27
|
} else {
|
|
28
|
-
|
|
29
|
-
const message = errData?.message ?? String(response.data);
|
|
30
|
-
const detail = errData?.data != null ? `\nDetails: ${JSON.stringify(errData.data, null, 2)}` : '';
|
|
31
|
-
reject(new Error(`[${errData?.errorType ?? 'error'}] ${message}${detail}`))
|
|
28
|
+
reject(toError(response.data))
|
|
32
29
|
}
|
|
33
30
|
}
|
|
34
31
|
});
|
|
@@ -148,3 +145,18 @@ export const TestUtils = {
|
|
|
148
145
|
return os.platform() === 'linux';
|
|
149
146
|
},
|
|
150
147
|
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Errors from plugins: plugin-core >= 2.0 sends `{ errorType, message, data? }` (PluginErrorData), shown as
|
|
151
|
+
* `[errorType] message` with the data (ex: the plan of an apply validation error) under `Details:`, and kept on the
|
|
152
|
+
* error (`errorType`, `data`). Older plugins send a string, used as is.
|
|
153
|
+
*/
|
|
154
|
+
function toError(data: unknown): Error {
|
|
155
|
+
if (data && typeof data === 'object' && typeof (data as { message?: unknown }).message === 'string') {
|
|
156
|
+
const { data: errorData, errorType, message } = data as { data?: unknown; errorType?: string; message: string };
|
|
157
|
+
const details = errorData === null || errorData === undefined ? '' : `\nDetails: ${JSON.stringify(errorData, null, 2)}`;
|
|
158
|
+
return Object.assign(new Error(`[${errorType ?? 'error'}] ${message}${details}`), { data: errorData, errorType });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return new Error(String(data));
|
|
162
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { LinuxDistro } from '@codifycli/schemas';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { distroMatches } from './utils.js';
|
|
5
|
+
|
|
6
|
+
describe('distroMatches', () => {
|
|
7
|
+
it('matches a distribution and its family', () => {
|
|
8
|
+
expect(distroMatches(LinuxDistro.UBUNTU, LinuxDistro.UBUNTU)).toBe(true);
|
|
9
|
+
expect(distroMatches(LinuxDistro.FEDORA, LinuxDistro.UBUNTU)).toBe(false);
|
|
10
|
+
expect(distroMatches(LinuxDistro.DEBIAN_BASED, LinuxDistro.UBUNTU)).toBe(true);
|
|
11
|
+
expect(distroMatches(LinuxDistro.RPM_BASED, LinuxDistro.UBUNTU)).toBe(false);
|
|
12
|
+
expect(distroMatches(LinuxDistro.RPM_BASED, LinuxDistro.FEDORA)).toBe(true);
|
|
13
|
+
});
|
|
14
|
+
});
|