@codifycli/plugin-test 1.1.0-beta6 → 1.2.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/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 +60 -36
- 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 -1
- 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 +65 -42
- 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 -1
- 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 +39 -3
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,7 +25,7 @@ export const TestUtils = {
|
|
|
25
25
|
if (response.status === MessageStatus.SUCCESS) {
|
|
26
26
|
resolve(response.data)
|
|
27
27
|
} else {
|
|
28
|
-
reject(
|
|
28
|
+
reject(toError(response.data))
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
});
|
|
@@ -145,3 +145,18 @@ export const TestUtils = {
|
|
|
145
145
|
return os.platform() === 'linux';
|
|
146
146
|
},
|
|
147
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
|
+
});
|
package/src/utils.ts
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
|
-
import { ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
|
|
1
|
+
import { LinuxDistro, ResourceConfig, ResourceOs, StringIndexedObject } from '@codifycli/schemas';
|
|
2
|
+
import fs from 'node:fs';
|
|
2
3
|
import os from 'node:os';
|
|
3
4
|
|
|
5
|
+
const DEBIAN_BASED_DISTROS: LinuxDistro[] = [
|
|
6
|
+
LinuxDistro.DEBIAN,
|
|
7
|
+
LinuxDistro.UBUNTU,
|
|
8
|
+
LinuxDistro.MINT,
|
|
9
|
+
LinuxDistro.POP_OS,
|
|
10
|
+
LinuxDistro.ELEMENTARY_OS,
|
|
11
|
+
LinuxDistro.KALI,
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
const RPM_BASED_DISTROS: LinuxDistro[] = [
|
|
15
|
+
LinuxDistro.FEDORA,
|
|
16
|
+
LinuxDistro.CENTOS,
|
|
17
|
+
LinuxDistro.RHEL,
|
|
18
|
+
LinuxDistro.AMAZON_LINUX,
|
|
19
|
+
LinuxDistro.OPENSUSE,
|
|
20
|
+
LinuxDistro.SUSE,
|
|
21
|
+
];
|
|
22
|
+
|
|
4
23
|
export function splitUserConfig<T extends StringIndexedObject>(
|
|
5
24
|
config: ResourceConfig & T
|
|
6
25
|
): { parameters: T; coreParameters: ResourceConfig } {
|
|
@@ -21,6 +40,56 @@ export function splitUserConfig<T extends StringIndexedObject>(
|
|
|
21
40
|
};
|
|
22
41
|
}
|
|
23
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Whether a config applies to this machine, like the CLI's os and distro filters: `os` must include the current OS,
|
|
45
|
+
* and on Linux `distro` must match the current distribution (`debian-based` / `rpm-based` match their families).
|
|
46
|
+
* `distro` is ignored on other OSes and when the distribution is unknown.
|
|
47
|
+
*/
|
|
48
|
+
export function appliesToCurrentPlatform(config: Pick<ResourceConfig, 'distro' | 'os'>): boolean {
|
|
49
|
+
if (config.os && config.os.length > 0 && !config.os.includes(getPlatformOs())) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!config.distro || config.distro.length === 0 || os.platform() !== 'linux') {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const current = getLinuxDistro();
|
|
58
|
+
return !current || config.distro.some((d) => distroMatches(d, current));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function getLinuxDistro(): LinuxDistro | undefined {
|
|
62
|
+
for (const candidate of ['/etc/os-release', '/usr/lib/os-release']) {
|
|
63
|
+
let osRelease: string;
|
|
64
|
+
try {
|
|
65
|
+
osRelease = fs.readFileSync(candidate, 'utf8');
|
|
66
|
+
} catch {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
for (const line of osRelease.split('\n')) {
|
|
71
|
+
if (line.startsWith('ID=')) {
|
|
72
|
+
const distroId = line.slice(3).trim().replaceAll('"', '');
|
|
73
|
+
return Object.values(LinuxDistro).includes(distroId as LinuxDistro) ? distroId as LinuxDistro : undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function distroMatches(filter: LinuxDistro, current: LinuxDistro): boolean {
|
|
82
|
+
if (filter === LinuxDistro.DEBIAN_BASED) {
|
|
83
|
+
return DEBIAN_BASED_DISTROS.includes(current);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (filter === LinuxDistro.RPM_BASED) {
|
|
87
|
+
return RPM_BASED_DISTROS.includes(current);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return filter === current;
|
|
91
|
+
}
|
|
92
|
+
|
|
24
93
|
export function getPlatformOs(): ResourceOs{
|
|
25
94
|
const currOs = os.platform();
|
|
26
95
|
switch (currOs) {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// A plugin like plugin-core >= 2.3.0: stdout and command events go over IPC, before the response.
|
|
2
|
+
// Older plugins write to the stdout pipe: both are noisy (spinners, progress bars)
|
|
3
|
+
process.on('message', (message) => {
|
|
4
|
+
if (message.cmd !== 'initialize') return;
|
|
5
|
+
|
|
6
|
+
const output = (data) => process.send({ cmd: 'output', data: { data }, requestId: '' });
|
|
7
|
+
process.send({ cmd: 'command_started', data: { id: '1', command: 'npm install', acceptsInput: true, canStop: true }, requestId: '' });
|
|
8
|
+
output('hello from the plugin 🍺\n');
|
|
9
|
+
for (let i = 0; i < 500; i++) output(`\u001B[1G${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i % 10]}\u001B[0K`);
|
|
10
|
+
output('\u001B[1G\u001B[0Kadded 12 packages in 2s\n');
|
|
11
|
+
for (let i = 0; i <= 100; i++) output(`\rDownloading [${'#'.repeat(i / 5).padEnd(20)}] ${i}%`);
|
|
12
|
+
process.send({ cmd: 'command_finished', data: { id: '1', exitCode: 0 }, requestId: '' });
|
|
13
|
+
|
|
14
|
+
// An older plugin: through the stdout pipe
|
|
15
|
+
for (let i = 0; i <= 100; i += 2) process.stdout.write(`\rProgress: [${String(i).padStart(3)}%]`);
|
|
16
|
+
process.stdout.write('\r\u001B[KSetting up curl (8.5.0) ...\n', () => {
|
|
17
|
+
process.send({ cmd: 'initialize_Response', status: 'success', data: { resourceDefinitions: [] }, requestId: message.requestId });
|
|
18
|
+
});
|
|
19
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { PluginProcess } from '../src/plugin-process.js';
|
|
5
|
+
|
|
6
|
+
describe('Plugin output', () => {
|
|
7
|
+
let plugin: PluginProcess | undefined;
|
|
8
|
+
|
|
9
|
+
afterEach(() => {
|
|
10
|
+
plugin?.kill();
|
|
11
|
+
vi.restoreAllMocks();
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('Prints plugin output as a terminal would end up showing it, without a line per spinner frame', async () => {
|
|
15
|
+
const written: string[] = [];
|
|
16
|
+
vi.spyOn(process.stdout, 'write').mockImplementation((chunk: any) => {
|
|
17
|
+
written.push(String(chunk));
|
|
18
|
+
return true;
|
|
19
|
+
});
|
|
20
|
+
plugin = new PluginProcess(path.join(__dirname, './output-plugin.mjs'));
|
|
21
|
+
|
|
22
|
+
await expect(plugin.initialize()).resolves.toEqual({ resourceDefinitions: [] });
|
|
23
|
+
// The stdout pipe and IPC are separate streams: give the pipe a moment
|
|
24
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
25
|
+
|
|
26
|
+
const lines = written.join('').split('\n').filter(Boolean);
|
|
27
|
+
expect(lines).toEqual(expect.arrayContaining([
|
|
28
|
+
'hello from the plugin 🍺',
|
|
29
|
+
'added 12 packages in 2s',
|
|
30
|
+
'Downloading [####################] 100%',
|
|
31
|
+
'Setting up curl (8.5.0) ...',
|
|
32
|
+
]));
|
|
33
|
+
expect(lines).toHaveLength(4);
|
|
34
|
+
expect(written.join('')).not.toMatch(/[⠀-⣿\r\u001B]/);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -6,7 +6,8 @@ import deepMatches from 'lodash.matches';
|
|
|
6
6
|
import differenceWith from 'lodash.differencewith';
|
|
7
7
|
import { PluginProcess } from '../src/plugin-process';
|
|
8
8
|
import * as fs from 'node:fs';
|
|
9
|
-
import { ResourceOs } from '@codifycli/schemas';
|
|
9
|
+
import { LinuxDistro, ResourceOs } from '@codifycli/schemas';
|
|
10
|
+
import { getLinuxDistro } from '../src/utils.js';
|
|
10
11
|
|
|
11
12
|
const pluginPath = path.join(__dirname, './test-plugin.ts');
|
|
12
13
|
|
|
@@ -119,7 +120,7 @@ describe('Plugin tester integration tests', () => {
|
|
|
119
120
|
})
|
|
120
121
|
|
|
121
122
|
it('Handles errors that are thrown', async () => {
|
|
122
|
-
expect(async () => plugin.plan({
|
|
123
|
+
await expect(async () => plugin.plan({
|
|
123
124
|
core: {
|
|
124
125
|
type: 'test',
|
|
125
126
|
},
|
|
@@ -131,7 +132,7 @@ describe('Plugin tester integration tests', () => {
|
|
|
131
132
|
},
|
|
132
133
|
state: undefined,
|
|
133
134
|
isStateful: false,
|
|
134
|
-
})).rejects.toThrowError(
|
|
135
|
+
})).rejects.toThrowError('Prop D is included');
|
|
135
136
|
})
|
|
136
137
|
|
|
137
138
|
it('Has helpers that can test a resource', async () => {
|
|
@@ -314,6 +315,41 @@ describe('Plugin tester integration tests', () => {
|
|
|
314
315
|
}
|
|
315
316
|
})
|
|
316
317
|
|
|
318
|
+
it('Uninstalls when a test fails, and keeps the error of the test', { timeout: 300000 }, async () => {
|
|
319
|
+
const configs = [{ type: 'test-destroy', propA: 'a', propB: 10 }, { type: 'test-destroy', propA: 'b', propB: 10 }];
|
|
320
|
+
try {
|
|
321
|
+
await expect(PluginTester.fullTest(pluginPath, configs.slice(0, 1), {
|
|
322
|
+
validateApply() {
|
|
323
|
+
expect(fs.existsSync('/tmp/test-destroy')).to.be.true;
|
|
324
|
+
throw new Error('Apply assertion failed');
|
|
325
|
+
},
|
|
326
|
+
})).rejects.toThrowError('Apply assertion failed');
|
|
327
|
+
|
|
328
|
+
expect(fs.existsSync('/tmp/test-destroy')).to.be.false;
|
|
329
|
+
} finally {
|
|
330
|
+
try { fs.rmSync('/tmp/test-destroy'); } catch (e) {}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// The caller's configs aren't changed (names are only added to copies)
|
|
334
|
+
expect(configs.every((c) => !('name' in c))).to.be.true;
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it('Can filter out unsupported configs based on distro', { timeout: 300000 }, async () => {
|
|
338
|
+
await PluginTester.fullTest(pluginPath, [{
|
|
339
|
+
type: 'windows-only',
|
|
340
|
+
os: [ResourceOs.LINUX],
|
|
341
|
+
distro: [LinuxDistro.ARCH, LinuxDistro.FEDORA],
|
|
342
|
+
}], {
|
|
343
|
+
skipUninstall: true,
|
|
344
|
+
skipImport: true,
|
|
345
|
+
validatePlan(plan) {
|
|
346
|
+
if (getLinuxDistro() !== LinuxDistro.ARCH && getLinuxDistro() !== LinuxDistro.FEDORA) {
|
|
347
|
+
expect(plan.length).to.eq(0);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
});
|
|
352
|
+
|
|
317
353
|
it('Can filter out unsupported configs based on OS', { timeout: 300000 }, async () => {
|
|
318
354
|
await PluginTester.fullTest(pluginPath, [{
|
|
319
355
|
type: 'windows-only',
|