Skip to content

Commit fba5f15

Browse files
author
John Doe
committed
refactor: use dynamic imports, delete duplicated code
1 parent 0e5d7a8 commit fba5f15

File tree

23 files changed

+188
-174
lines changed

23 files changed

+188
-174
lines changed

e2e/nx-plugin-e2e/tests/executor-cli.e2e.test.ts

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,17 @@ async function addTargetToWorkspace(
2727
) {
2828
const { cwd, project } = options;
2929
const projectCfg = readProjectConfiguration(tree, project);
30-
const { root } = projectCfg;
31-
const configPath = path.join(root, 'code-pushup.config.ts');
3230
updateProjectConfiguration(tree, project, {
3331
...projectCfg,
3432
targets: {
3533
...projectCfg.targets,
3634
'code-pushup': {
3735
executor: '@code-pushup/nx-plugin:cli',
38-
options: {
39-
config: configPath,
40-
...executorOptions,
41-
},
36+
...(executorOptions && { options: executorOptions }),
4237
},
4338
},
4439
});
40+
const { root } = projectCfg;
4541
generateCodePushupConfig(tree, root, {
4642
plugins: [
4743
{
@@ -148,7 +144,7 @@ describe('executor command', () => {
148144
).resolves.not.toThrow();
149145
});
150146

151-
it('should execute print-config executor with upload config', async () => {
147+
it('should execute print-config executor with api key', async () => {
152148
const cwd = path.join(testFileDir, 'execute-print-config-command');
153149
await addTargetToWorkspace(tree, { cwd, project });
154150

@@ -160,9 +156,6 @@ describe('executor command', () => {
160156
`${project}:code-pushup`,
161157
'print-config',
162158
'--upload.apiKey=a123a',
163-
'--upload.server=https://example.com',
164-
'--upload.organization=test-org',
165-
'--upload.project=test-project',
166159
],
167160
cwd,
168161
});
@@ -210,15 +203,9 @@ describe('executor command', () => {
210203
);
211204
expect(cleanStdout).toContain('Code PushUp CLI');
212205

213-
// Check for report in project root's .reports directory
214-
const reportPath = path.join(
215-
cwd,
216-
'libs',
217-
project,
218-
'.reports',
219-
'terminal-report.json',
220-
);
221-
await expect(readJsonFile(reportPath)).resolves.not.toThrow();
206+
await expect(
207+
readJsonFile(path.join(cwd, '.reports', 'terminal-report.json')),
208+
).resolves.not.toThrow();
222209
});
223210

224211
it('should execute collect executor and add report to sub folder named by project', async () => {
@@ -236,7 +223,7 @@ describe('executor command', () => {
236223
expect(cleanStdout).toContain('nx run my-lib:code-pushup collect');
237224

238225
const report = await readJsonFile(
239-
path.join(cwd, 'libs', project, '.code-pushup', 'report.json'),
226+
path.join(cwd, '.code-pushup', project, 'report.json'),
240227
);
241228
expect(report).toStrictEqual(
242229
expect.objectContaining({

e2e/nx-plugin-e2e/tests/plugin-create-nodes.e2e.test.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ describe('nx-plugin', () => {
2929
TEST_OUTPUT_DIR,
3030
'plugin-create-nodes',
3131
);
32-
const PACKAGE_NAME = '@code-pushup/nx-plugin';
3332

3433
beforeEach(async () => {
3534
tree = await generateWorkspaceAndProject(project);
@@ -121,7 +120,7 @@ describe('nx-plugin', () => {
121120
expect(projectJson.targets).toStrictEqual({
122121
'code-pushup--configuration': expect.objectContaining({
123122
options: {
124-
command: `nx g ${PACKAGE_NAME}:configuration --project="${project}"`,
123+
command: `nx g XYZ:configuration --project="${project}"`,
125124
},
126125
}),
127126
});
@@ -199,9 +198,8 @@ describe('nx-plugin', () => {
199198
const cleanStdout = removeColorCodes(stdout);
200199
// Nx command
201200
expect(cleanStdout).toContain('nx run my-lib:code-pushup');
202-
// Run CLI executor - check for DryRun execution message
203-
expect(cleanStdout).toContain('DryRun execution of:');
204-
expect(cleanStdout).toContain('npx @code-pushup/cli');
201+
// Run CLI executor
202+
expect(cleanStdout).toContain('Command: npx @code-pushup/cli');
205203
expect(cleanStdout).toContain('--dryRun --verbose');
206204
});
207205

nx.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,6 @@
337337
"releaseTagPattern": "v{version}"
338338
},
339339
"plugins": [
340-
"@code-pushup/nx-plugin",
341340
{
342341
"plugin": "@push-based/nx-verdaccio",
343342
"options": {

packages/nx-plugin/src/executors/cli/executor.int.test.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { afterEach, expect, vi } from 'vitest';
22
import { executorContext } from '@code-pushup/test-nx-utils';
3-
import { removeColorCodes } from '@code-pushup/test-utils';
43
import * as executeProcessModule from '../../internal/execute-process.js';
54
import runAutorunExecutor from './executor.js';
65
import * as utils from './utils.js';
@@ -27,25 +26,27 @@ describe('runAutorunExecutor', () => {
2726
executeProcessSpy.mockReset();
2827
});
2928

30-
it('should parse CLI options and execute command', async () => {
31-
const { success, command } = await runAutorunExecutor(
29+
it('should normalize context, parse CLI options and execute command', async () => {
30+
const output = await runAutorunExecutor(
3231
{ verbose: true },
3332
executorContext('utils'),
3433
);
35-
expect(success).toBe(true);
36-
const cleanCommand = removeColorCodes(command || '');
37-
expect(cleanCommand).toMatch('npx @code-pushup/cli');
38-
expect(cleanCommand).toMatch('CP_VERBOSE="true"');
39-
expect(executeProcessSpy).toHaveBeenCalledTimes(1);
40-
expect(executeProcessSpy).toHaveBeenCalledWith(
34+
expect(output.success).toBe(true);
35+
36+
expect(parseAutorunExecutorOptionsSpy).toHaveBeenCalledTimes(1);
37+
38+
//is context normalized
39+
expect(parseAutorunExecutorOptionsSpy).toHaveBeenCalledWith(
40+
{ verbose: true },
4141
expect.objectContaining({
42-
command: 'npx',
43-
args: expect.arrayContaining(['@code-pushup/cli']),
44-
cwd: expect.any(String),
45-
env: expect.objectContaining({
46-
CP_VERBOSE: 'true',
47-
}),
42+
projectConfig: expect.objectContaining({ name: 'utils' }),
4843
}),
4944
);
45+
expect(executeProcessSpy).toHaveBeenCalledTimes(1);
46+
expect(executeProcessSpy).toHaveBeenCalledWith({
47+
command: 'npx',
48+
args: expect.arrayContaining(['@code-pushup/cli']),
49+
cwd: process.cwd(),
50+
});
5051
});
5152
});
Lines changed: 31 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,61 @@
1-
import type { ExecutorContext } from '@nx/devkit';
1+
import { type ExecutorContext, logger } from '@nx/devkit';
22
import { executeProcess } from '../../internal/execute-process.js';
3+
import {
4+
createCliCommandObject,
5+
createCliCommandString,
6+
} from '../internal/cli.js';
7+
import { normalizeContext } from '../internal/context.js';
38
import type { AutorunCommandExecutorOptions } from './schema.js';
9+
import { mergeExecutorOptions, parseAutorunExecutorOptions } from './utils.js';
410

511
export type ExecutorOutput = {
612
success: boolean;
713
command?: string;
814
error?: Error;
915
};
1016

11-
/* eslint-disable max-lines-per-function */
1217
export default async function runAutorunExecutor(
1318
terminalAndExecutorOptions: AutorunCommandExecutorOptions,
14-
{ cwd }: ExecutorContext,
19+
context: ExecutorContext,
1520
): Promise<ExecutorOutput> {
16-
const { logger, stringifyError, objectToCliArgs, formatCommand } =
17-
await import('@code-pushup/utils');
18-
const {
19-
dryRun,
20-
verbose,
21-
command: cliCommand,
22-
env: targetEnv,
21+
const normalizedContext = normalizeContext(context);
22+
const mergedOptions = mergeExecutorOptions(
23+
context.target?.options,
24+
terminalAndExecutorOptions,
25+
);
26+
const cliArgumentObject = parseAutorunExecutorOptions(
27+
mergedOptions,
28+
normalizedContext,
29+
);
30+
const { dryRun, verbose, command, bin } = mergedOptions;
31+
const commandString = createCliCommandString({
32+
command,
33+
args: cliArgumentObject,
2334
bin,
24-
...argsObj
25-
} = terminalAndExecutorOptions;
26-
const command = bin ? `node` : 'npx';
27-
const positionals = [
28-
bin ?? '@code-pushup/cli',
29-
...(cliCommand ? [cliCommand] : []),
30-
];
31-
const args = objectToCliArgs(argsObj);
32-
const executorEnvVariables = {
33-
...targetEnv,
34-
...(verbose && { CP_VERBOSE: 'true' }),
35-
};
36-
const binString = `${command} ${positionals.join(' ')} ${args.join(' ')}`;
37-
const formattedBinString = formatCommand(binString, {
38-
env: executorEnvVariables,
39-
cwd,
4035
});
41-
36+
if (verbose) {
37+
logger.info(`Run CLI executor ${command ?? ''}`);
38+
logger.info(`Command: ${commandString}`);
39+
}
4240
if (dryRun) {
43-
logger.warn(`DryRun execution of: \n ${formattedBinString}`);
41+
logger.warn(`DryRun execution of: ${commandString}`);
4442
} else {
4543
try {
4644
await executeProcess({
47-
command,
48-
args: [...positionals, ...args],
49-
env: {
50-
...process.env,
51-
...executorEnvVariables,
52-
},
53-
...(cwd ? { cwd } : {}),
45+
...createCliCommandObject({ command, args: cliArgumentObject, bin }),
46+
...(context.cwd ? { cwd: context.cwd } : {}),
5447
});
5548
} catch (error) {
56-
logger.error(stringifyError(error));
49+
logger.error(error);
5750
return {
5851
success: false,
59-
command: formattedBinString,
52+
command: commandString,
6053
error: error instanceof Error ? error : new Error(`${error}`),
6154
};
6255
}
6356
}
64-
6557
return {
6658
success: true,
67-
command: formattedBinString,
59+
command: commandString,
6860
};
6961
}
70-
/* eslint-enable max-lines-per-function */

packages/nx-plugin/src/executors/cli/executor.unit.test.ts

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,13 @@ describe('runAutorunExecutor', () => {
4444

4545
it('should call executeProcess with return result', async () => {
4646
const output = await runAutorunExecutor({}, executorContext('utils'));
47-
expect(output).toStrictEqual({
48-
success: true,
49-
command: expect.stringContaining('npx @code-pushup/cli'),
47+
expect(output.success).toBe(true);
48+
expect(output.command).toMatch('npx @code-pushup/cli');
49+
expect(executeProcessSpy).toHaveBeenCalledWith({
50+
command: 'npx',
51+
args: expect.arrayContaining(['@code-pushup/cli']),
52+
cwd: MEMFS_VOLUME,
5053
});
51-
expect(executeProcessSpy).toHaveBeenCalledWith(
52-
expect.objectContaining({
53-
command: 'npx',
54-
args: expect.arrayContaining(['@code-pushup/cli']),
55-
cwd: MEMFS_VOLUME,
56-
}),
57-
);
5854
});
5955

6056
it('should normalize context', async () => {
@@ -66,15 +62,12 @@ describe('runAutorunExecutor', () => {
6662
},
6763
);
6864
expect(output.success).toBe(true);
69-
expect(output.command).toMatch('npx @code-pushup/cli');
70-
expect(output.command).toContain('cwd-form-context');
71-
expect(executeProcessSpy).toHaveBeenCalledWith(
72-
expect.objectContaining({
73-
command: 'npx',
74-
args: expect.arrayContaining(['@code-pushup/cli']),
75-
cwd: 'cwd-form-context',
76-
}),
77-
);
65+
expect(output.command).toMatch('utils');
66+
expect(executeProcessSpy).toHaveBeenCalledWith({
67+
command: 'npx',
68+
args: expect.arrayContaining(['@code-pushup/cli']),
69+
cwd: 'cwd-form-context',
70+
});
7871
});
7972

8073
it('should process executorOptions', async () => {
@@ -111,6 +104,7 @@ describe('runAutorunExecutor', () => {
111104
expect(output.command).toMatch(
112105
'--persist.format="md" --persist.format="json"',
113106
);
107+
expect(output.command).toMatch('--upload.apiKey="cp_1234567"');
114108
expect(output.command).toMatch('--upload.project="CLI"');
115109
});
116110

@@ -121,23 +115,26 @@ describe('runAutorunExecutor', () => {
121115
);
122116
expect(executeProcessSpy).toHaveBeenCalledTimes(1);
123117

124-
expect(output.command).toMatch('CP_VERBOSE="true"');
125-
expect(output.command).not.toMatch('--verbose');
118+
expect(output.command).toMatch('--verbose');
126119
expect(loggerWarnSpy).toHaveBeenCalledTimes(0);
127-
expect(loggerInfoSpy).toHaveBeenCalledTimes(0);
120+
expect(loggerInfoSpy).toHaveBeenCalledTimes(2);
121+
expect(loggerInfoSpy).toHaveBeenCalledWith(
122+
expect.stringContaining(`Run CLI executor`),
123+
);
124+
expect(loggerInfoSpy).toHaveBeenCalledWith(
125+
expect.stringContaining('Command: npx @code-pushup/cli'),
126+
);
128127
});
129128

130129
it('should log command if dryRun is set', async () => {
131-
const output = await runAutorunExecutor(
132-
{ dryRun: true },
133-
executorContext('utils'),
134-
);
130+
await runAutorunExecutor({ dryRun: true }, executorContext('utils'));
135131

136-
expect(output).toStrictEqual({
137-
success: true,
138-
command: expect.stringContaining('npx @code-pushup/cli'),
139-
});
140132
expect(loggerInfoSpy).toHaveBeenCalledTimes(0);
141-
expect(loggerWarnSpy).toHaveBeenCalledTimes(0);
133+
expect(loggerWarnSpy).toHaveBeenCalledTimes(1);
134+
expect(loggerWarnSpy).toHaveBeenCalledWith(
135+
expect.stringContaining(
136+
'DryRun execution of: npx @code-pushup/cli --dryRun',
137+
),
138+
);
142139
});
143140
});

packages/nx-plugin/src/executors/cli/schema.json

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,6 @@
2121
"type": "string",
2222
"description": "Path to Code PushUp CLI"
2323
},
24-
"env": {
25-
"type": "object",
26-
"additionalProperties": {
27-
"type": "string"
28-
},
29-
"description": "Environment variables to pass to the CLI command"
30-
},
3124
"verbose": {
3225
"type": "boolean",
3326
"description": "Print additional logs"

0 commit comments

Comments
 (0)