@codifycli/plugin-test 1.0.0-beta1
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/.eslintignore +1 -0
- package/.eslintrc.json +30 -0
- package/.github/workflows/unit-test-ci.yaml +24 -0
- package/.prettierrc.json +1 -0
- package/CLAUDE.md +126 -0
- package/README.md +315 -0
- package/codify.json +9 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin-process.d.ts +19 -0
- package/dist/plugin-process.js +119 -0
- package/dist/plugin-process.js.map +1 -0
- package/dist/plugin-tester.d.ts +20 -0
- package/dist/plugin-tester.js +210 -0
- package/dist/plugin-tester.js.map +1 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +37 -0
- package/dist/shell.js.map +1 -0
- package/dist/spawn.d.ts +16 -0
- package/dist/spawn.js +71 -0
- package/dist/spawn.js.map +1 -0
- package/dist/test-utils.d.ts +44 -0
- package/dist/test-utils.js +123 -0
- package/dist/test-utils.js.map +1 -0
- package/dist/utils.d.ts +6 -0
- package/dist/utils.js +34 -0
- package/dist/utils.js.map +1 -0
- package/package.json +56 -0
- package/src/index.ts +3 -0
- package/src/plugin-process.ts +161 -0
- package/src/plugin-tester.ts +281 -0
- package/src/shell.ts +45 -0
- package/src/spawn.ts +101 -0
- package/src/test-utils.test.ts +83 -0
- package/src/test-utils.ts +147 -0
- package/src/utils.ts +42 -0
- package/test/plugin-tester.test.ts +350 -0
- package/test/test-plugin.ts +215 -0
- package/tsconfig.json +24 -0
- package/tsconfig.test.json +10 -0
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@codifycli/plugin-test",
|
|
3
|
+
"version": "1.0.0-beta1",
|
|
4
|
+
"description": "Testing framework for Codify plugins with complete lifecycle testing, IPC communication, and cross-platform support",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"typings": "dist/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"codify",
|
|
10
|
+
"plugin",
|
|
11
|
+
"testing",
|
|
12
|
+
"test",
|
|
13
|
+
"framework",
|
|
14
|
+
"ipc",
|
|
15
|
+
"integration-testing",
|
|
16
|
+
"plugin-testing"
|
|
17
|
+
],
|
|
18
|
+
"author": "Kevin Wang <team@codifycli.com>",
|
|
19
|
+
"license": "ISC",
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "vitest",
|
|
22
|
+
"start": "tsx ./src/index.ts",
|
|
23
|
+
"prepublishOnly": "tsc"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@codifycli/schemas": "1.0.0",
|
|
27
|
+
"ajv": "^8.18.0",
|
|
28
|
+
"ajv-formats": "^3.0.1",
|
|
29
|
+
"lodash.matches": "^4.6.0",
|
|
30
|
+
"lodash.differencewith": "4.5.0",
|
|
31
|
+
"lodash.unionby": "^4.8.0",
|
|
32
|
+
"nanoid": "^5.0.9",
|
|
33
|
+
"chalk": "^5.4.1",
|
|
34
|
+
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.1",
|
|
35
|
+
"strip-ansi": "^7.1.2"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@codifycli/plugin-core": "1.0.0-beta2",
|
|
39
|
+
"@oclif/prettier-config": "^0.2.1",
|
|
40
|
+
"@types/debug": "^4.1.12",
|
|
41
|
+
"@types/node": "^22",
|
|
42
|
+
"@types/lodash.matches": "^4.6.9",
|
|
43
|
+
"@types/lodash.differencewith": "^4.5.9",
|
|
44
|
+
"@types/lodash.unionby": "^4.8.9",
|
|
45
|
+
"eslint": "^8.51.0",
|
|
46
|
+
"eslint-config-oclif": "^5",
|
|
47
|
+
"eslint-config-oclif-typescript": "^3",
|
|
48
|
+
"eslint-config-prettier": "^9.0.0",
|
|
49
|
+
"tsx": "^4.7.3",
|
|
50
|
+
"typescript": "5.3.3",
|
|
51
|
+
"vitest": "^4.0.18"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": ">=18.0.0"
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ApplyRequestData,
|
|
3
|
+
CommandRequestData,
|
|
4
|
+
CommandRequestDataSchema,
|
|
5
|
+
ImportRequestData,
|
|
6
|
+
ImportResponseData,
|
|
7
|
+
InitializeResponseData,
|
|
8
|
+
IpcMessageSchema,
|
|
9
|
+
IpcMessageV2,
|
|
10
|
+
MessageCmd,
|
|
11
|
+
PlanRequestData,
|
|
12
|
+
PlanResponseData,
|
|
13
|
+
ValidateRequestData,
|
|
14
|
+
ValidateResponseData
|
|
15
|
+
} from '@codifycli/schemas';
|
|
16
|
+
import Ajv from 'ajv';
|
|
17
|
+
import { nanoid } from 'nanoid';
|
|
18
|
+
import { ChildProcess, fork } from 'node:child_process';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
|
|
21
|
+
import { spawnSafe } from './spawn.js';
|
|
22
|
+
import { TestUtils } from './test-utils.js';
|
|
23
|
+
|
|
24
|
+
const ajv = new Ajv.default({
|
|
25
|
+
strict: true
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const ipcMessageValidator = ajv.compile(IpcMessageSchema);
|
|
29
|
+
const commandRequestValidator = ajv.compile(CommandRequestDataSchema);
|
|
30
|
+
|
|
31
|
+
export class PluginProcess {
|
|
32
|
+
childProcess: ChildProcess
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* PluginTester is a helper class to integration test plugins. It launches plugins via fork() just like CodifyCLI does.
|
|
36
|
+
*
|
|
37
|
+
* @param pluginPath A fully qualified path
|
|
38
|
+
*/
|
|
39
|
+
constructor(pluginPath: string) {
|
|
40
|
+
if (!path.isAbsolute(pluginPath)) {
|
|
41
|
+
throw new Error('A fully qualified path must be supplied to PluginTester');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const debug = (process.env.DEBUG) ? ['--inspect-brk=9221'] : [];
|
|
45
|
+
|
|
46
|
+
this.childProcess = fork(
|
|
47
|
+
pluginPath,
|
|
48
|
+
[],
|
|
49
|
+
{
|
|
50
|
+
// Use default true to test plugins in secure mode (un-able to request sudo directly)
|
|
51
|
+
// detached: true,
|
|
52
|
+
env: { ...process.env },
|
|
53
|
+
execArgv: ['--import', 'tsx/esm', ...debug],
|
|
54
|
+
stdio: 'pipe',
|
|
55
|
+
},
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
this.childProcess.stderr?.pipe(process.stderr);
|
|
59
|
+
this.childProcess.stdout?.pipe(process.stdout);
|
|
60
|
+
|
|
61
|
+
this.handleIncomingRequests(this.childProcess);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async initialize(): Promise<InitializeResponseData> {
|
|
65
|
+
return TestUtils.sendMessageAndAwaitResponse(this.childProcess, {
|
|
66
|
+
cmd: 'initialize',
|
|
67
|
+
data: { verbosityLevel: 3 },
|
|
68
|
+
requestId: nanoid(6),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async validate(data: ValidateRequestData): Promise<ValidateResponseData> {
|
|
73
|
+
return TestUtils.sendMessageAndAwaitResponse(this.childProcess, {
|
|
74
|
+
cmd: 'validate',
|
|
75
|
+
data,
|
|
76
|
+
requestId: nanoid(6),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async plan(data: PlanRequestData): Promise<PlanResponseData> {
|
|
81
|
+
return TestUtils.sendMessageAndAwaitResponse(this.childProcess, {
|
|
82
|
+
cmd: 'plan',
|
|
83
|
+
data,
|
|
84
|
+
requestId: nanoid(6),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async apply(data: ApplyRequestData): Promise<void> {
|
|
89
|
+
return TestUtils.sendMessageAndAwaitResponse(this.childProcess, {
|
|
90
|
+
cmd: 'apply',
|
|
91
|
+
data,
|
|
92
|
+
requestId: nanoid(6),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async import(data: ImportRequestData): Promise<ImportResponseData> {
|
|
97
|
+
return TestUtils.sendMessageAndAwaitResponse(this.childProcess, {
|
|
98
|
+
cmd: 'import',
|
|
99
|
+
data,
|
|
100
|
+
requestId: nanoid(6),
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
kill() {
|
|
105
|
+
this.childProcess.kill();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private handleIncomingRequests(cp: ChildProcess) {
|
|
109
|
+
// Listen for incoming sudo incoming sudo requests
|
|
110
|
+
cp.on('message', async (message) => {
|
|
111
|
+
if (!ipcMessageValidator(message)) {
|
|
112
|
+
throw new Error(`Invalid message from plugin. ${JSON.stringify(message, null, 2)}`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (message.cmd === MessageCmd.COMMAND_REQUEST) {
|
|
116
|
+
const { data, requestId } = message;
|
|
117
|
+
if (!commandRequestValidator(data)) {
|
|
118
|
+
throw new Error(`Invalid sudo request from plugin. ${JSON.stringify(commandRequestValidator.errors, null, 2)}`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const { command, options } = data as unknown as CommandRequestData;
|
|
122
|
+
const result = await spawnSafe(command, options);
|
|
123
|
+
|
|
124
|
+
cp.send(<IpcMessageV2>{
|
|
125
|
+
cmd: MessageCmd.COMMAND_REQUEST + '_Response',
|
|
126
|
+
data: result,
|
|
127
|
+
requestId,
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (message.cmd === MessageCmd.PRESS_KEY_TO_CONTINUE_REQUEST) {
|
|
132
|
+
const { data, requestId } = message;
|
|
133
|
+
if (!commandRequestValidator(data)) {
|
|
134
|
+
throw new Error(`Invalid sudo request from plugin. ${JSON.stringify(commandRequestValidator.errors, null, 2)}`);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
cp.send(<IpcMessageV2>{
|
|
138
|
+
cmd: MessageCmd.PRESS_KEY_TO_CONTINUE_REQUEST + '_Response',
|
|
139
|
+
data: {},
|
|
140
|
+
requestId,
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (message.cmd === MessageCmd.CODIFY_CREDENTIALS_REQUEST) {
|
|
145
|
+
const { requestId } = message;
|
|
146
|
+
|
|
147
|
+
const testJwt = process.env.VITE_CODIFY_TEST_JWT;
|
|
148
|
+
if (!testJwt) {
|
|
149
|
+
throw new Error('Unable to parse login credentials from VITE_CODIFY_TEST_JWT env var. Please set and try again');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
cp.send(<IpcMessageV2>{
|
|
153
|
+
cmd: MessageCmd.CODIFY_CREDENTIALS_REQUEST + '_Response',
|
|
154
|
+
data: testJwt,
|
|
155
|
+
requestId,
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ImportResponseData,
|
|
3
|
+
PlanResponseData,
|
|
4
|
+
ResourceConfig,
|
|
5
|
+
ResourceOperation,
|
|
6
|
+
} from '@codifycli/schemas';
|
|
7
|
+
import chalk from 'chalk';
|
|
8
|
+
import unionBy from 'lodash.unionby';
|
|
9
|
+
|
|
10
|
+
import { PluginProcess } from './plugin-process.js';
|
|
11
|
+
import { getPlatformOs, splitUserConfig } from './utils.js';
|
|
12
|
+
|
|
13
|
+
export class PluginTester {
|
|
14
|
+
static async fullTest(
|
|
15
|
+
pluginPath: string,
|
|
16
|
+
configs: ResourceConfig[],
|
|
17
|
+
options?: {
|
|
18
|
+
skipUninstall?: boolean,
|
|
19
|
+
skipImport?: boolean,
|
|
20
|
+
validatePlan?: (plans: PlanResponseData[]) => Promise<void> | void
|
|
21
|
+
validateApply?: (plans: PlanResponseData[]) => Promise<void> | void,
|
|
22
|
+
validateDestroy?: (plans: PlanResponseData[]) => Promise<void> | void,
|
|
23
|
+
validateImport?: (importResults: (ImportResponseData['result'][0])[]) => Promise<void> | void,
|
|
24
|
+
testModify?: {
|
|
25
|
+
modifiedConfigs: ResourceConfig[],
|
|
26
|
+
validateModify?: (plans: PlanResponseData[]) => Promise<void> | void,
|
|
27
|
+
}
|
|
28
|
+
}): Promise<void> {
|
|
29
|
+
configs = configs.filter((c) => !c.os || c.os.includes(getPlatformOs()));
|
|
30
|
+
const ids = configs
|
|
31
|
+
.map((c) => `${c.type}${c.name ? `.${c.name}` : ''}`)
|
|
32
|
+
.join(', ')
|
|
33
|
+
console.info(chalk.cyan(`Starting full test of [ ${ids} ]...`));
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
const {
|
|
37
|
+
skipUninstall = false,
|
|
38
|
+
} = options ?? {}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
const plugin = new PluginProcess(pluginPath);
|
|
42
|
+
try {
|
|
43
|
+
console.info(chalk.cyan('Testing initialization...'))
|
|
44
|
+
const initializeResult = await plugin.initialize();
|
|
45
|
+
|
|
46
|
+
const unsupportedConfigs = configs.filter((c) =>
|
|
47
|
+
!initializeResult.resourceDefinitions.some((rd) => rd.type === c.type)
|
|
48
|
+
)
|
|
49
|
+
if (unsupportedConfigs.length > 0) {
|
|
50
|
+
throw new Error(`The plugin does not support the following configs supplied:\n ${JSON.stringify(unsupportedConfigs, null, 2)}\n Initialize result: ${JSON.stringify(initializeResult)}`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// configs = configs.filter((c) => initializeResult.resourceDefinitions.find((rd) => rd.type === c.type)?.operatingSystems?.includes(os.platform() as OS));
|
|
54
|
+
|
|
55
|
+
console.info(chalk.cyan('Testing validate...'))
|
|
56
|
+
const validate = await plugin.validate({
|
|
57
|
+
configs: configs.map((c) => {
|
|
58
|
+
const { coreParameters, parameters } = splitUserConfig(c)
|
|
59
|
+
return { core: coreParameters, parameters };
|
|
60
|
+
})
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const invalidConfigs = validate.resourceValidations.filter((v) => !v.isValid)
|
|
64
|
+
if (invalidConfigs.length > 0) {
|
|
65
|
+
throw new Error(`The following configs did not validate:\n ${JSON.stringify(invalidConfigs, null, 2)}`)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
console.info(chalk.cyan('Testing plan...'))
|
|
69
|
+
const plans = [];
|
|
70
|
+
for (const config of configs) {
|
|
71
|
+
const { coreParameters, parameters } = splitUserConfig(config);
|
|
72
|
+
|
|
73
|
+
plans.push(await plugin.plan({
|
|
74
|
+
core: coreParameters,
|
|
75
|
+
desired: parameters,
|
|
76
|
+
isStateful: false,
|
|
77
|
+
state: undefined,
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (options?.validatePlan) {
|
|
82
|
+
await options.validatePlan(plans);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
console.info(chalk.cyan('Testing apply...'))
|
|
86
|
+
for (const plan of plans) {
|
|
87
|
+
await plugin.apply({
|
|
88
|
+
planId: plan.planId
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (options?.validateApply) {
|
|
93
|
+
await options.validateApply(plans);
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
plugin.kill();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (!options?.skipImport) {
|
|
100
|
+
const importPlugin = new PluginProcess(pluginPath);
|
|
101
|
+
try {
|
|
102
|
+
await importPlugin.initialize();
|
|
103
|
+
console.info(chalk.cyan('Testing import...'))
|
|
104
|
+
|
|
105
|
+
const importResults = [];
|
|
106
|
+
for (const config of configs) {
|
|
107
|
+
const { coreParameters, parameters } = splitUserConfig(config);
|
|
108
|
+
|
|
109
|
+
const importResult = await importPlugin.import({ core: coreParameters, parameters })
|
|
110
|
+
importResults.push(importResult);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (options?.validateImport) {
|
|
114
|
+
await options.validateImport(importResults.map((r) => r.result[0]));
|
|
115
|
+
}
|
|
116
|
+
} finally {
|
|
117
|
+
importPlugin.kill();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (options?.testModify) {
|
|
122
|
+
const modifyPlugin = new PluginProcess(pluginPath);
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
await modifyPlugin.initialize();
|
|
126
|
+
console.info(chalk.cyan('Testing modify...'))
|
|
127
|
+
|
|
128
|
+
const modifyPlans = [];
|
|
129
|
+
for (const config of options.testModify.modifiedConfigs) {
|
|
130
|
+
const { coreParameters, parameters } = splitUserConfig(config);
|
|
131
|
+
|
|
132
|
+
modifyPlans.push(await modifyPlugin.plan({
|
|
133
|
+
core: coreParameters,
|
|
134
|
+
desired: parameters,
|
|
135
|
+
isStateful: false,
|
|
136
|
+
state: undefined,
|
|
137
|
+
}));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (modifyPlans.some((p) => p.operation !== ResourceOperation.MODIFY)) {
|
|
141
|
+
throw new Error(`Error while testing modify. Non-modify results were found in the plan:
|
|
142
|
+
${JSON.stringify(modifyPlans, null, 2)}`)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
for (const plan of modifyPlans) {
|
|
146
|
+
await modifyPlugin.apply({
|
|
147
|
+
planId: plan.planId
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (options.testModify.validateModify) {
|
|
152
|
+
await options.testModify.validateModify(modifyPlans);
|
|
153
|
+
}
|
|
154
|
+
} finally {
|
|
155
|
+
modifyPlugin.kill();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (!skipUninstall) {
|
|
160
|
+
// We need to add unique names to multiple configs with the same type or else it breaks the unionBy below.
|
|
161
|
+
const configsWithNames = this.addNamesToConfigs(configs);
|
|
162
|
+
const modifiedConfigs = this.addNamesToConfigs(options?.testModify?.modifiedConfigs ?? [])
|
|
163
|
+
|
|
164
|
+
const id = (config: ResourceConfig) => config.type + (config.name ? `.${config.name}` : '')
|
|
165
|
+
|
|
166
|
+
const configsToDestroy = unionBy(modifiedConfigs, configsWithNames, id);
|
|
167
|
+
await this.uninstall(pluginPath, configsToDestroy.toReversed(), options);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
static async install(pluginPath: string, configs: ResourceConfig[]) {
|
|
172
|
+
const plugin = new PluginProcess(pluginPath);
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
console.info(chalk.cyan('Testing initialization...'))
|
|
176
|
+
const initializeResult = await plugin.initialize();
|
|
177
|
+
|
|
178
|
+
const unsupportedConfigs = configs.filter((c) =>
|
|
179
|
+
!initializeResult.resourceDefinitions.some((rd) => rd.type === c.type)
|
|
180
|
+
)
|
|
181
|
+
if (unsupportedConfigs.length > 0) {
|
|
182
|
+
throw new Error(`The plugin does not support the following configs supplied:\n ${JSON.stringify(unsupportedConfigs, null, 2)}\n Initialize result: ${JSON.stringify(initializeResult)}`)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// configs = configs.filter((c) => initializeResult.resourceDefinitions.find((rd) => rd.type === c.type)?.operatingSystems?.includes(os.platform() as OS));
|
|
186
|
+
|
|
187
|
+
console.info(chalk.cyan('Testing validate...'))
|
|
188
|
+
const validate = await plugin.validate({
|
|
189
|
+
configs: configs.map((c) => {
|
|
190
|
+
const { coreParameters, parameters } = splitUserConfig(c)
|
|
191
|
+
return { core: coreParameters, parameters };
|
|
192
|
+
})
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
const invalidConfigs = validate.resourceValidations.filter((v) => !v.isValid)
|
|
196
|
+
if (invalidConfigs.length > 0) {
|
|
197
|
+
throw new Error(`The following configs did not validate:\n ${JSON.stringify(invalidConfigs, null, 2)}`)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
console.info(chalk.cyan('Testing plan...'))
|
|
201
|
+
const plans = [];
|
|
202
|
+
for (const config of configs) {
|
|
203
|
+
const { coreParameters, parameters } = splitUserConfig(config);
|
|
204
|
+
|
|
205
|
+
plans.push(await plugin.plan({
|
|
206
|
+
core: coreParameters,
|
|
207
|
+
desired: parameters,
|
|
208
|
+
isStateful: false,
|
|
209
|
+
state: undefined,
|
|
210
|
+
}));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
console.info(chalk.cyan('Testing apply...'))
|
|
214
|
+
for (const plan of plans) {
|
|
215
|
+
await plugin.apply({
|
|
216
|
+
planId: plan.planId
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
} finally {
|
|
220
|
+
plugin.kill();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
static async uninstall(pluginPath: string, configs: ResourceConfig[], options?: {
|
|
225
|
+
validateDestroy?: (plans: PlanResponseData[]) => Promise<void> | void
|
|
226
|
+
}) {
|
|
227
|
+
const destroyPlugin = new PluginProcess(pluginPath);
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
await destroyPlugin.initialize();
|
|
231
|
+
console.info(chalk.cyan('Testing destroy...'))
|
|
232
|
+
|
|
233
|
+
const plans = [];
|
|
234
|
+
for (const config of configs) {
|
|
235
|
+
const { coreParameters, parameters } = splitUserConfig(config);
|
|
236
|
+
|
|
237
|
+
plans.push(await destroyPlugin.plan({
|
|
238
|
+
core: coreParameters,
|
|
239
|
+
isStateful: true,
|
|
240
|
+
state: parameters,
|
|
241
|
+
desired: undefined
|
|
242
|
+
}))
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
for (const plan of plans) {
|
|
246
|
+
if (plan.operation !== ResourceOperation.DESTROY && plan.operation !== ResourceOperation.NOOP) {
|
|
247
|
+
throw new Error(`Expect resource operation to be 'destroy' but instead received plan: \n ${JSON.stringify(plans, null, 2)}`)
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
await destroyPlugin.apply({
|
|
251
|
+
planId: plan.planId
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if (options?.validateDestroy) {
|
|
256
|
+
await options.validateDestroy(plans);
|
|
257
|
+
}
|
|
258
|
+
} finally {
|
|
259
|
+
destroyPlugin.kill();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private static addNamesToConfigs(configs: ResourceConfig[]): ResourceConfig[] {
|
|
264
|
+
const configsWithNames = new Array<ResourceConfig>();
|
|
265
|
+
|
|
266
|
+
const typeSet = new Set(configs.map((c) => c.type));
|
|
267
|
+
for (const type of typeSet) {
|
|
268
|
+
const sameTypeConfigs = configs.filter((c) => c.type === type);
|
|
269
|
+
if (sameTypeConfigs.length > 1) {
|
|
270
|
+
sameTypeConfigs.forEach((c, idx) => {
|
|
271
|
+
c.name = c.name ?? idx.toString()
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
configsWithNames.push(...sameTypeConfigs);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return configsWithNames;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
package/src/shell.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export enum Shell {
|
|
2
|
+
ZSH = 'zsh',
|
|
3
|
+
BASH = 'bash',
|
|
4
|
+
SH = 'sh',
|
|
5
|
+
KSH = 'ksh',
|
|
6
|
+
CSH = 'csh',
|
|
7
|
+
FISH = 'fish',
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
export const ShellUtils = {
|
|
12
|
+
getShell(): Shell | undefined {
|
|
13
|
+
const shell = process.env.SHELL || '';
|
|
14
|
+
|
|
15
|
+
if (shell.endsWith('bash')) {
|
|
16
|
+
return Shell.BASH
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (shell.endsWith('zsh')) {
|
|
20
|
+
return Shell.ZSH
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (shell.endsWith('sh')) {
|
|
24
|
+
return Shell.SH
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (shell.endsWith('csh')) {
|
|
28
|
+
return Shell.CSH
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (shell.endsWith('ksh')) {
|
|
32
|
+
return Shell.KSH
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (shell.endsWith('fish')) {
|
|
36
|
+
return Shell.FISH
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return undefined;
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
getDefaultShell(): string {
|
|
43
|
+
return process.env.SHELL!;
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/spawn.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { SpawnStatus } from '@codifycli/schemas';
|
|
2
|
+
import * as pty from '@homebridge/node-pty-prebuilt-multiarch';
|
|
3
|
+
import stripAnsi from 'strip-ansi';
|
|
4
|
+
|
|
5
|
+
import { Shell, ShellUtils } from './shell.js';
|
|
6
|
+
|
|
7
|
+
export interface SpawnResult {
|
|
8
|
+
status: SpawnStatus;
|
|
9
|
+
exitCode: number;
|
|
10
|
+
data: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface SpawnOptions {
|
|
14
|
+
cwd?: string;
|
|
15
|
+
env?: Record<string, unknown>,
|
|
16
|
+
interactive?: boolean,
|
|
17
|
+
requiresRoot?: boolean,
|
|
18
|
+
stdin?: boolean,
|
|
19
|
+
throws?: boolean,
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function testSpawn(cmd: string, options?: SpawnOptions): Promise<SpawnResult> {
|
|
23
|
+
return spawnSafe(cmd, { interactive: true, ...options, });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function spawnSafe(cmd: string, options?: SpawnOptions): Promise<SpawnResult> {
|
|
27
|
+
if (cmd.toLowerCase().includes('sudo')) {
|
|
28
|
+
throw new Error('Command must not include sudo')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
console.log(`Running command: ${options?.requiresRoot ? 'sudo' : ''} ${cmd}` + (options?.cwd ? `(${options?.cwd})` : ''))
|
|
32
|
+
|
|
33
|
+
return new Promise((resolve, reject) => {
|
|
34
|
+
const output: string[] = [];
|
|
35
|
+
const historyIgnore = ShellUtils.getShell() === Shell.ZSH ? { HISTORY_IGNORE: '*' } : { HISTIGNORE: '*' };
|
|
36
|
+
|
|
37
|
+
// If TERM_PROGRAM=Apple_Terminal is set then ANSI escape characters may be included
|
|
38
|
+
// in the response.
|
|
39
|
+
const env = {
|
|
40
|
+
...process.env, ...options?.env,
|
|
41
|
+
TERM_PROGRAM: 'codify',
|
|
42
|
+
COMMAND_MODE: 'unix2003',
|
|
43
|
+
COLORTERM: 'truecolor',
|
|
44
|
+
...historyIgnore
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Initial terminal dimensions
|
|
48
|
+
const initialCols = 10_000; // Set to a large value to prevent wrapping
|
|
49
|
+
const initialRows = process.stdout.rows ?? 24;
|
|
50
|
+
|
|
51
|
+
const command = options?.requiresRoot ? `sudo ${cmd}` : cmd;
|
|
52
|
+
const args = options?.interactive ? ['-i', '-c', command] : ['-c', command]
|
|
53
|
+
|
|
54
|
+
// Run the command in a pty for interactivity
|
|
55
|
+
const mPty = pty.spawn(ShellUtils.getDefaultShell(), args, {
|
|
56
|
+
...options,
|
|
57
|
+
cols: initialCols,
|
|
58
|
+
rows: initialRows,
|
|
59
|
+
env
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
mPty.onData((data) => {
|
|
63
|
+
process.stdout.write(data);
|
|
64
|
+
output.push(data.toString());
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
const resizeListener = () => {
|
|
68
|
+
const { columns, rows } = process.stdout;
|
|
69
|
+
mPty.resize(columns, rows);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const stdinListener = (data: any) => {
|
|
73
|
+
// console.log('stdinListener', data);
|
|
74
|
+
mPty.write(data.toString());
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Listen to resize events for the terminal window;
|
|
78
|
+
process.stdout.on('resize', resizeListener);
|
|
79
|
+
if (options?.stdin) {
|
|
80
|
+
process.stdin.on('data', stdinListener)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
mPty.onExit((result) => {
|
|
84
|
+
process.stdout.off('resize', resizeListener);
|
|
85
|
+
if (options?.stdin) {
|
|
86
|
+
process.stdin.off('data', stdinListener);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (options?.throws && result.exitCode !== 0) {
|
|
90
|
+
reject(new Error(stripAnsi(output.join('\n').trim())));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
resolve({
|
|
95
|
+
status: result.exitCode === 0 ? SpawnStatus.SUCCESS : SpawnStatus.ERROR,
|
|
96
|
+
exitCode: result.exitCode,
|
|
97
|
+
data: stripAnsi(output.join('\n').trim()),
|
|
98
|
+
})
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
}
|