diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4c87bcf90..3deef2278 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -83,6 +83,21 @@ Therefore, PRs are merged via one of two strategies: - rebase - branch cannot contain merge commits ([rebase instead of merge](https://www.atlassian.com/git/tutorials/merging-vs-rebasing)), - squash - single commit whose message is the PR title (should be in conventional commit format). +## Releases + +We use nx release command to create releases for GitHub as well as publish to npm. + +**Preconditions:** + +- `npm login` - Only users with write access to [code-pushup](https://www.npmjs.com/org/code-pushup) can publish +- (optional) `GITHUB_TOKEN=ghp_...` in `.env` - [Personal access token](https://github.com/settings/personal-access-tokens/new) to create a GitHub release. + +**Steps:** + +- `git checkout main`, `git pull` +- (recommended optional) `npx nx release --dryRun` +- `npx nx release` and confirm publish prompt + ## Project tags [Nx tags](https://nx.dev/core-features/enforce-module-boundaries) are used to enforce module boundaries in the project graph when linting. diff --git a/code-pushup.config.ts b/code-pushup.config.ts index 4ea96774f..0f0f669fa 100644 --- a/code-pushup.config.ts +++ b/code-pushup.config.ts @@ -20,6 +20,9 @@ const config: CoreConfig = { server: 'https://api.staging.code-pushup.dev/graphql', apiKey: process.env['CP_API_KEY'], }, + persist: { + outputDir: '.code-pushup', + }, }), plugins: [], }; diff --git a/e2e/nx-plugin-e2e/tests/plugin-create-nodes.e2e.test.ts b/e2e/nx-plugin-e2e/tests/plugin-create-nodes.e2e.test.ts index fb5408812..7a446969c 100644 --- a/e2e/nx-plugin-e2e/tests/plugin-create-nodes.e2e.test.ts +++ b/e2e/nx-plugin-e2e/tests/plugin-create-nodes.e2e.test.ts @@ -3,6 +3,7 @@ import path from 'node:path'; import { readProjectConfiguration } from 'nx/src/generators/utils/project-configuration'; import { afterEach, expect } from 'vitest'; import { generateCodePushupConfig } from '@code-pushup/nx-plugin'; +import { PACKAGE_NAME } from '@code-pushup/nx-plugin/src/internal/constants.js'; import { generateWorkspaceAndProject, materializeTree, @@ -120,7 +121,7 @@ describe('nx-plugin', () => { expect(projectJson.targets).toStrictEqual({ 'code-pushup--configuration': expect.objectContaining({ options: { - command: `nx g XYZ:configuration --project="${project}"`, + command: `nx g ${PACKAGE_NAME}:configuration --project="${project}"`, }, }), }); diff --git a/nx.json b/nx.json index 7b41eba43..4a023bf26 100644 --- a/nx.json +++ b/nx.json @@ -140,7 +140,7 @@ "watch": false } }, - "code-pushup": { + "old-code-pushup": { "cache": false, "outputs": [ "{projectRoot}/.code-pushup/report.md", @@ -347,6 +347,16 @@ "releaseTagPattern": "v{version}" }, "plugins": [ + { + "plugin": "@code-pushup/nx-plugin", + "options": { + "bin": "packages/cli/src/index.ts", + "env": { + "NODE_OPTIONS": "--import tsx", + "TSX_TSCONFIG_PATH": "tsconfig.base.json" + } + } + }, { "plugin": "@push-based/nx-verdaccio", "options": { diff --git a/package-lock.json b/package-lock.json index b8d79a01d..6009d621b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,6 @@ "version": "0.0.0", "license": "MIT", "dependencies": { - "@code-pushup/portal-client": "^0.16.0", "@isaacs/cliui": "^8.0.2", "@nx/devkit": "21.4.1", "@poppinss/cliui": "6.4.1", @@ -40,7 +39,10 @@ "@actions/core": "^1.11.1", "@actions/github": "^6.0.1", "@beaussan/nx-knip": "^0.0.5-15", + "@code-pushup/cli": "0.86.0", "@code-pushup/eslint-config": "^0.14.2", + "@code-pushup/nx-plugin": "0.86.0", + "@code-pushup/portal-client": "^0.16.0", "@commitlint/cli": "^19.5.0", "@commitlint/config-conventional": "^19.5.0", "@commitlint/config-nx-scopes": "^19.5.0", @@ -2315,6 +2317,47 @@ "url": "https://github.com/sponsors/Borewit" } }, + "node_modules/@code-pushup/cli": { + "version": "0.86.0", + "resolved": "https://registry.npmjs.org/@code-pushup/cli/-/cli-0.86.0.tgz", + "integrity": "sha512-9jQs2Z/ToChxLyn/nOYBIDAsBV66YMwV5pFJqPnFhvwG22dbvHs+ptIMPG/S1WG8HeA1KJQuDcULVc0SdI5pdA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@code-pushup/core": "0.86.0", + "@code-pushup/models": "0.86.0", + "@code-pushup/utils": "0.86.0", + "ansis": "^3.3.0", + "simple-git": "^3.20.0", + "yargs": "^17.7.2" + }, + "bin": { + "code-pushup": "src/index.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@code-pushup/core": { + "version": "0.86.0", + "resolved": "https://registry.npmjs.org/@code-pushup/core/-/core-0.86.0.tgz", + "integrity": "sha512-sqmaCxBp/NFqNyyr5lsh7V4R4QtaQGiyLIA8DHFjT947Mj4gaWPJ62lH0wLGQ7q4Z6IT9LNwfLT2siLruAVChA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@code-pushup/models": "0.86.0", + "@code-pushup/utils": "0.86.0", + "ansis": "^3.3.0" + }, + "peerDependencies": { + "@code-pushup/portal-client": "^0.16.0" + }, + "peerDependenciesMeta": { + "@code-pushup/portal-client": { + "optional": true + } + } + }, "node_modules/@code-pushup/eslint-config": { "version": "0.14.2", "resolved": "https://registry.npmjs.org/@code-pushup/eslint-config/-/eslint-config-0.14.2.tgz", @@ -2399,10 +2442,36 @@ } } }, + "node_modules/@code-pushup/models": { + "version": "0.86.0", + "resolved": "https://registry.npmjs.org/@code-pushup/models/-/models-0.86.0.tgz", + "integrity": "sha512-/mXR5ej19Pcrf+vAZHtHyRn7LeM0oT9RSzksXTrhJsSJG0CdmxmsZoNjg/m3lCzUXX61OA+nc7IzMz3FwSd72A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansis": "^3.3.2", + "vscode-material-icons": "^0.1.0", + "zod": "^4.0.5" + } + }, + "node_modules/@code-pushup/nx-plugin": { + "version": "0.86.0", + "resolved": "https://registry.npmjs.org/@code-pushup/nx-plugin/-/nx-plugin-0.86.0.tgz", + "integrity": "sha512-3ac2PmMLiHs643Y0Fyj3iO8y/PmbbHkVR7l+Yf3ZDLW1HaeEB81UVHFLlLL1I16Z3QTMRJMEpQGYM13o1rSuAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@code-pushup/models": "0.86.0", + "@code-pushup/utils": "0.86.0", + "@nx/devkit": ">=17.0.0", + "nx": ">=17.0.0" + } + }, "node_modules/@code-pushup/portal-client": { "version": "0.16.0", "resolved": "https://registry.npmjs.org/@code-pushup/portal-client/-/portal-client-0.16.0.tgz", "integrity": "sha512-JlMRcTKkJygVfLS+IWQxDRDnvF64p4q+QDLIXzQPep6X99C1OH3MnA9jbfGAOew/3xqOILCrifn0y54fyRs8Qg==", + "dev": true, "license": "MIT", "dependencies": { "graphql": "^16.6.0", @@ -2411,6 +2480,30 @@ "vscode-material-icons": "^0.1.0" } }, + "node_modules/@code-pushup/utils": { + "version": "0.86.0", + "resolved": "https://registry.npmjs.org/@code-pushup/utils/-/utils-0.86.0.tgz", + "integrity": "sha512-QB64eyc9uLwvvbHjnYLUc+p1mqAV5sQLqeCqphP/JaihJuE3ZN+R1EWW8gAR8CToHkXlaEXvNqi8qPja22ZHPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@code-pushup/models": "0.86.0", + "@isaacs/cliui": "^8.0.2", + "@poppinss/cliui": "^6.4.0", + "ansis": "^3.3.0", + "build-md": "^0.4.2", + "bundle-require": "^5.1.0", + "esbuild": "^0.25.2", + "multi-progress-bars": "^5.0.3", + "ora": "^9.0.0", + "semver": "^7.6.0", + "simple-git": "^3.20.0", + "zod": "^4.0.5" + }, + "engines": { + "node": ">=17.0.0" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -3355,6 +3448,7 @@ "version": "3.2.0", "resolved": "https://registry.npmjs.org/@graphql-typed-document-node/core/-/core-3.2.0.tgz", "integrity": "sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==", + "dev": true, "peerDependencies": { "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" } @@ -14182,6 +14276,7 @@ "version": "3.1.8", "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.8.tgz", "integrity": "sha512-cvA+JwZoU0Xq+h6WkMvAUqPEYy92Obet6UdKLfW60qn99ftItKjB5T+BkyWOFWe2pUyfQ+IJHmpOTznqk1M6Kg==", + "dev": true, "dependencies": { "node-fetch": "^2.6.12" } @@ -15164,7 +15259,7 @@ "version": "0.1.13", "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "iconv-lite": "^0.6.2" @@ -15174,7 +15269,7 @@ "version": "0.6.3", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -18235,6 +18330,7 @@ "version": "16.9.0", "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.9.0.tgz", "integrity": "sha512-GGTKBX4SD7Wdb8mqeDLni2oaRGYQWjWHGKPQ24ZMnUtKfcsVoiv4uX8+LJr1K6U5VW2Lu1BwJnj7uiori0YtRw==", + "dev": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -18243,6 +18339,7 @@ "version": "6.1.0", "resolved": "https://registry.npmjs.org/graphql-request/-/graphql-request-6.1.0.tgz", "integrity": "sha512-p+XPfS4q7aIpKVcgmnZKhMNqhltk20hfXtkaIkTfjjmiKMJ5xrt5c743cL03y/K7y1rg3WrIC49xGiEQ4mxdNw==", + "dev": true, "dependencies": { "@graphql-typed-document-node/core": "^3.2.0", "cross-fetch": "^3.1.5" @@ -18255,6 +18352,7 @@ "version": "2.12.6", "resolved": "https://registry.npmjs.org/graphql-tag/-/graphql-tag-2.12.6.tgz", "integrity": "sha512-FdSNcu2QQcWnM2VNvSCCDCVS5PpPqpzgFT8+GXzqJuoDd0CBncxCY278u4mhRO7tMgo2JjgJA5aZ+nWSQ/Z+xg==", + "dev": true, "dependencies": { "tslib": "^2.1.0" }, @@ -23540,6 +23638,7 @@ "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dev": true, "dependencies": { "whatwg-url": "^5.0.0" }, @@ -23558,17 +23657,20 @@ "node_modules/node-fetch/node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "dev": true }, "node_modules/node-fetch/node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "dev": true }, "node_modules/node-fetch/node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dev": true, "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" @@ -27216,7 +27318,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "devOptional": true + "dev": true }, "node_modules/saxes": { "version": "6.0.0", diff --git a/package.json b/package.json index a5fec600c..c59f21800 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,6 @@ }, "private": true, "dependencies": { - "@code-pushup/portal-client": "^0.16.0", "@isaacs/cliui": "^8.0.2", "@nx/devkit": "21.4.1", "@poppinss/cliui": "6.4.1", @@ -51,6 +50,9 @@ "@actions/github": "^6.0.1", "@beaussan/nx-knip": "^0.0.5-15", "@code-pushup/eslint-config": "^0.14.2", + "@code-pushup/cli": "0.86.0", + "@code-pushup/nx-plugin": "0.86.0", + "@code-pushup/portal-client": "^0.16.0", "@commitlint/cli": "^19.5.0", "@commitlint/config-conventional": "^19.5.0", "@commitlint/config-nx-scopes": "^19.5.0", diff --git a/packages/nx-plugin/src/executors/cli/executor.int.test.ts b/packages/nx-plugin/src/executors/cli/executor.int.test.ts index fee1e59d8..0ed775436 100644 --- a/packages/nx-plugin/src/executors/cli/executor.int.test.ts +++ b/packages/nx-plugin/src/executors/cli/executor.int.test.ts @@ -1,5 +1,6 @@ import { afterEach, expect, vi } from 'vitest'; import { executorContext } from '@code-pushup/test-nx-utils'; +import { removeColorCodes } from '@code-pushup/test-utils'; import * as executeProcessModule from '../../internal/execute-process.js'; import runAutorunExecutor from './executor.js'; import * as utils from './utils.js'; @@ -26,27 +27,25 @@ describe('runAutorunExecutor', () => { executeProcessSpy.mockReset(); }); - it('should normalize context, parse CLI options and execute command', async () => { - const output = await runAutorunExecutor( + it('should parse CLI options and execute command', async () => { + const { success, command } = await runAutorunExecutor( { verbose: true }, executorContext('utils'), ); - expect(output.success).toBe(true); - - expect(parseAutorunExecutorOptionsSpy).toHaveBeenCalledTimes(1); - - //is context normalized - expect(parseAutorunExecutorOptionsSpy).toHaveBeenCalledWith( - { verbose: true }, + expect(success).toBe(true); + const cleanCommand = removeColorCodes(command || ''); + expect(cleanCommand).toMatch('npx @code-pushup/cli'); + expect(cleanCommand).toMatch('CP_VERBOSE="true"'); + expect(executeProcessSpy).toHaveBeenCalledTimes(1); + expect(executeProcessSpy).toHaveBeenCalledWith( expect.objectContaining({ - projectConfig: expect.objectContaining({ name: 'utils' }), + command: 'npx', + args: expect.arrayContaining(['@code-pushup/cli']), + cwd: expect.any(String), + env: expect.objectContaining({ + CP_VERBOSE: 'true', + }), }), ); - expect(executeProcessSpy).toHaveBeenCalledTimes(1); - expect(executeProcessSpy).toHaveBeenCalledWith({ - command: 'npx', - args: expect.arrayContaining(['@code-pushup/cli']), - cwd: process.cwd(), - }); }); }); diff --git a/packages/nx-plugin/src/executors/cli/executor.ts b/packages/nx-plugin/src/executors/cli/executor.ts index 2e644f184..b4b208e63 100644 --- a/packages/nx-plugin/src/executors/cli/executor.ts +++ b/packages/nx-plugin/src/executors/cli/executor.ts @@ -1,12 +1,6 @@ -import { type ExecutorContext, logger } from '@nx/devkit'; +import { type ExecutorContext } from '@nx/devkit'; import { executeProcess } from '../../internal/execute-process.js'; -import { - createCliCommandObject, - createCliCommandString, -} from '../internal/cli.js'; -import { normalizeContext } from '../internal/context.js'; import type { AutorunCommandExecutorOptions } from './schema.js'; -import { mergeExecutorOptions, parseAutorunExecutorOptions } from './utils.js'; export type ExecutorOutput = { success: boolean; @@ -16,46 +10,62 @@ export type ExecutorOutput = { export default async function runAutorunExecutor( terminalAndExecutorOptions: AutorunCommandExecutorOptions, - context: ExecutorContext, + { cwd }: ExecutorContext, ): Promise { - const normalizedContext = normalizeContext(context); - const mergedOptions = mergeExecutorOptions( - context.target?.options, - terminalAndExecutorOptions, + const { logger, stringifyError, formatCommand } = await import( + '@code-pushup/utils' ); - const cliArgumentObject = parseAutorunExecutorOptions( - mergedOptions, - normalizedContext, - ); - const { dryRun, verbose, command, bin } = mergedOptions; - const commandString = createCliCommandString({ - command, - args: cliArgumentObject, + const { objectToCliArgs } = await import('@code-pushup/utils'); + + const { + dryRun, + verbose, + command: cliCommand, + env, bin, + ...argsObj + } = terminalAndExecutorOptions; + + const command = bin ? `node` : 'npx'; + const positionals = [ + bin ?? '@code-pushup/cli', + ...(cliCommand ? [cliCommand] : []), + ]; + const args = objectToCliArgs(argsObj); + const envVariables = { + ...process.env, + ...env, + ...(verbose && { CP_VERBOSE: 'true' }), + }; + + const binString = `${command} ${positionals.join(' ')} ${args.join(' ')}`; + const formattedBinString = formatCommand(binString, { + env: envVariables, + cwd, }); - if (verbose) { - logger.info(`Run CLI executor ${command ?? ''}`); - logger.info(`Command: ${commandString}`); - } + if (dryRun) { - logger.warn(`DryRun execution of: ${commandString}`); + logger.warn(`DryRun execution of: \n ${formattedBinString}`); } else { try { await executeProcess({ - ...createCliCommandObject({ command, args: cliArgumentObject, bin }), - ...(context.cwd ? { cwd: context.cwd } : {}), + command, + args: [...positionals, ...args], + env: envVariables, + ...(cwd ? { cwd } : {}), }); } catch (error) { - logger.error(error); + logger.error(stringifyError(error)); return { success: false, - command: commandString, + command: formattedBinString, error: error instanceof Error ? error : new Error(`${error}`), }; } } + return { success: true, - command: commandString, + command: formattedBinString, }; } diff --git a/packages/nx-plugin/src/executors/cli/executor.unit.test.ts b/packages/nx-plugin/src/executors/cli/executor.unit.test.ts index c5684b0ba..c386174f6 100644 --- a/packages/nx-plugin/src/executors/cli/executor.unit.test.ts +++ b/packages/nx-plugin/src/executors/cli/executor.unit.test.ts @@ -1,7 +1,6 @@ -import { logger } from '@nx/devkit'; import { afterAll, afterEach, beforeEach, expect, vi } from 'vitest'; import { executorContext } from '@code-pushup/test-nx-utils'; -import { MEMFS_VOLUME } from '@code-pushup/test-utils'; +import { MEMFS_VOLUME, removeColorCodes } from '@code-pushup/test-utils'; import * as executeProcessModule from '../../internal/execute-process.js'; import runAutorunExecutor from './executor.js'; @@ -9,14 +8,25 @@ describe('runAutorunExecutor', () => { const processEnvCP = Object.fromEntries( Object.entries(process.env).filter(([k]) => k.startsWith('CP_')), ); - const loggerInfoSpy = vi.spyOn(logger, 'info'); - const loggerWarnSpy = vi.spyOn(logger, 'warn'); + let loggerCommandSpy: any; + let loggerWarnSpy: any; const executeProcessSpy = vi.spyOn(executeProcessModule, 'executeProcess'); - beforeAll(() => { + beforeAll(async () => { Object.entries(process.env) .filter(([k]) => k.startsWith('CP_')) .forEach(([k]) => delete process.env[k]); + + const { logger } = await import('@code-pushup/utils'); + loggerCommandSpy = vi + .spyOn(logger, 'command') + .mockImplementation(async (bin, worker, options) => { + // Execute worker immediately since executor doesn't await logger.command + // We await it here to ensure executeProcess is called in tests + await worker(); + return undefined; + }); + loggerWarnSpy = vi.spyOn(logger, 'warn'); }); afterAll(() => { @@ -36,22 +46,31 @@ describe('runAutorunExecutor', () => { afterEach(() => { loggerWarnSpy.mockReset(); - loggerInfoSpy.mockReset(); + loggerCommandSpy.mockReset(); executeProcessSpy.mockReset(); }); it('should call executeProcess with return result', async () => { - const output = await runAutorunExecutor({}, executorContext('utils')); - expect(output.success).toBe(true); - expect(output.command).toMatch('npx @code-pushup/cli'); - expect(executeProcessSpy).toHaveBeenCalledWith({ - command: 'npx', - args: expect.arrayContaining(['@code-pushup/cli']), - cwd: MEMFS_VOLUME, - }); + const { success, command } = await runAutorunExecutor( + {}, + executorContext('utils'), + ); + + expect(success).toBe(true); + expect(removeColorCodes(command || '')).toMatch('npx @code-pushup/cli'); + // The executor now calls executeProcess directly + expect(executeProcessSpy).toHaveBeenCalledTimes(1); + expect(executeProcessSpy).toHaveBeenCalledWith( + expect.objectContaining({ + command: 'npx', + args: expect.arrayContaining(['@code-pushup/cli']), + cwd: MEMFS_VOLUME, + env: expect.any(Object), + }), + ); }); - it('should normalize context', async () => { + it('should get CWD from context', async () => { const output = await runAutorunExecutor( {}, { @@ -59,13 +78,39 @@ describe('runAutorunExecutor', () => { cwd: 'cwd-form-context', }, ); + expect(output.success).toBe(true); - expect(output.command).toMatch('utils'); - expect(executeProcessSpy).toHaveBeenCalledWith({ - command: 'npx', - args: expect.arrayContaining(['@code-pushup/cli']), - cwd: 'cwd-form-context', - }); + const commandWithoutAnsi = removeColorCodes(output.command || ''); + expect(commandWithoutAnsi).toMatch('cwd-form-context'); + expect(executeProcessSpy).toHaveBeenCalledTimes(1); + expect(executeProcessSpy).toHaveBeenCalledWith( + expect.objectContaining({ + cwd: 'cwd-form-context', + }), + ); + }); + + it('should get env variables from options', async () => { + const { command } = await runAutorunExecutor( + { + env: { + CP_API_KEY: '123456789', + CP_PROJECT: 'cli', + }, + }, + executorContext('utils'), + ); + const commandWithoutAnsi = removeColorCodes(command || ''); + expect(commandWithoutAnsi).toMatch('CP_API_KEY="123456789"'); + expect(commandWithoutAnsi).toMatch('CP_PROJECT="cli"'); + expect(executeProcessSpy).toHaveBeenCalledWith( + expect.objectContaining({ + env: expect.objectContaining({ + CP_API_KEY: '123456789', + CP_PROJECT: 'cli', + }), + }), + ); }); it('should process executorOptions', async () => { @@ -74,8 +119,9 @@ describe('runAutorunExecutor', () => { executorContext('testing-utils'), ); expect(output.success).toBe(true); - expect(output.command).toContain('--output="code-pushup.config.json"'); - expect(output.command).toContain('--persist.filename="REPORT"'); + const commandWithoutAnsi = removeColorCodes(output.command || ''); + expect(commandWithoutAnsi).toContain('--output="code-pushup.config.json"'); + expect(commandWithoutAnsi).toContain('--persist.filename="REPORT"'); }); it('should create command from context and options if no api key is set', async () => { @@ -83,56 +129,53 @@ describe('runAutorunExecutor', () => { { persist: { filename: 'REPORT', format: ['md', 'json'] } }, executorContext('core'), ); - expect(output.command).toMatch('--persist.filename="REPORT"'); - expect(output.command).toMatch( + const commandWithoutAnsi = removeColorCodes(output.command || ''); + expect(commandWithoutAnsi).toMatch('--persist.filename="REPORT"'); + expect(commandWithoutAnsi).toMatch( '--persist.format="md" --persist.format="json"', ); }); it('should create command from context, options and arguments if api key is set', async () => { - vi.stubEnv('CP_API_KEY', 'cp_1234567'); const output = await runAutorunExecutor( { persist: { filename: 'REPORT', format: ['md', 'json'] }, - upload: { project: 'CLI' }, + upload: { apiKey: 'cp_1234567', project: 'CLI' }, }, executorContext('core'), ); - expect(output.command).toMatch('--persist.filename="REPORT"'); - expect(output.command).toMatch( + const commandWithoutAnsi = removeColorCodes(output.command || ''); + expect(commandWithoutAnsi).toMatch('--persist.filename="REPORT"'); + expect(commandWithoutAnsi).toMatch( '--persist.format="md" --persist.format="json"', ); - expect(output.command).toMatch('--upload.apiKey="cp_1234567"'); - expect(output.command).toMatch('--upload.project="CLI"'); + expect(commandWithoutAnsi).toMatch('--upload.apiKey="cp_1234567"'); + expect(commandWithoutAnsi).toMatch('--upload.project="CLI"'); }); - it('should log information if verbose is set', async () => { - const output = await runAutorunExecutor( + it('should log information and set CP_VERBOSE if verbose is set ', async () => { + const { command } = await runAutorunExecutor( { verbose: true }, { ...executorContext('github-action'), cwd: '' }, ); - expect(executeProcessSpy).toHaveBeenCalledTimes(1); - expect(output.command).toMatch('--verbose'); - expect(loggerWarnSpy).toHaveBeenCalledTimes(0); - expect(loggerInfoSpy).toHaveBeenCalledTimes(2); - expect(loggerInfoSpy).toHaveBeenCalledWith( - expect.stringContaining(`Run CLI executor`), - ); - expect(loggerInfoSpy).toHaveBeenCalledWith( - expect.stringContaining('Command: npx @code-pushup/cli'), + expect(removeColorCodes(command || '')).toMatch('CP_VERBOSE="true"'); + expect(executeProcessSpy).toHaveBeenCalledTimes(1); + expect(executeProcessSpy).toHaveBeenCalledWith( + expect.objectContaining({ + env: expect.objectContaining({ CP_VERBOSE: 'true' }), + }), ); }); it('should log command if dryRun is set', async () => { await runAutorunExecutor({ dryRun: true }, executorContext('utils')); - expect(loggerInfoSpy).toHaveBeenCalledTimes(0); + expect(loggerCommandSpy).toHaveBeenCalledTimes(0); expect(loggerWarnSpy).toHaveBeenCalledTimes(1); - expect(loggerWarnSpy).toHaveBeenCalledWith( - expect.stringContaining( - 'DryRun execution of: npx @code-pushup/cli --dryRun', - ), - ); + const warnCall = loggerWarnSpy.mock.calls[0]?.[0] as string | undefined; + const warnMessage = removeColorCodes(warnCall || ''); + expect(warnMessage).toContain('DryRun execution of:'); + expect(warnMessage).toContain('npx @code-pushup/cli'); }); }); diff --git a/packages/nx-plugin/src/executors/cli/schema.json b/packages/nx-plugin/src/executors/cli/schema.json index 85cd0de19..635c43c66 100644 --- a/packages/nx-plugin/src/executors/cli/schema.json +++ b/packages/nx-plugin/src/executors/cli/schema.json @@ -21,6 +21,13 @@ "type": "string", "description": "Path to Code PushUp CLI" }, + "env": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Environment variables to pass to the CLI command" + }, "verbose": { "type": "boolean", "description": "Print additional logs" diff --git a/packages/nx-plugin/src/executors/cli/utils.ts b/packages/nx-plugin/src/executors/cli/utils.ts index 5530e00c0..5641b07dd 100644 --- a/packages/nx-plugin/src/executors/cli/utils.ts +++ b/packages/nx-plugin/src/executors/cli/utils.ts @@ -34,7 +34,7 @@ export function parseAutorunExecutorOptions( options: Partial, normalizedContext: NormalizedExecutorContext, ): AutorunCommandExecutorOptions { - const { projectPrefix, persist, upload, command } = options; + const { projectPrefix, persist, upload, command, output } = options; const needsUploadParams = command === 'upload' || command === 'autorun' || command === undefined; const uploadCfg = uploadConfig( @@ -46,6 +46,7 @@ export function parseAutorunExecutorOptions( ...parsePrintConfigExecutorOptions(options), ...parseAutorunExecutorOnlyOptions(options), ...globalConfig(options, normalizedContext), + ...(output ? { output } : {}), persist: persistConfig({ projectPrefix, ...persist }, normalizedContext), // @TODO This is a hack to avoid validation errors of upload config for commands that dont need it. // Fix: use utils and execute the core logic directly diff --git a/packages/nx-plugin/src/executors/cli/utils.unit.test.ts b/packages/nx-plugin/src/executors/cli/utils.unit.test.ts index 025c322fb..647640215 100644 --- a/packages/nx-plugin/src/executors/cli/utils.unit.test.ts +++ b/packages/nx-plugin/src/executors/cli/utils.unit.test.ts @@ -170,6 +170,33 @@ describe('parseAutorunExecutorOptions', () => { ); }, ); + + it.each(['print-config'])( + 'should include output config for command %s', + command => { + const projectName = 'my-app'; + const executorOptions = parseAutorunExecutorOptions( + { + command, + output: 'code-pushup.config.json', + }, + { + projectName, + workspaceRoot: 'workspaceRoot', + projectConfig: { + name: 'my-app', + root: 'root', + }, + }, + ); + + expect(executorOptions).toEqual( + expect.objectContaining({ + output: 'code-pushup.config.json', + }), + ); + }, + ); }); describe('mergeExecutorOptions', () => { diff --git a/packages/nx-plugin/src/executors/internal/cli.ts b/packages/nx-plugin/src/executors/internal/cli.ts deleted file mode 100644 index adbf1627c..000000000 --- a/packages/nx-plugin/src/executors/internal/cli.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { logger } from '@nx/devkit'; - -export function createCliCommandString(options?: { - args?: Record; - command?: string; - bin?: string; -}): string { - const { bin = '@code-pushup/cli', command, args } = options ?? {}; - return `npx ${bin} ${objectToCliArgs({ _: command ?? [], ...args }).join( - ' ', - )}`; -} - -export function createCliCommandObject(options?: { - args?: Record; - command?: string; - bin?: string; -}): import('@code-pushup/utils').ProcessConfig { - const { bin = '@code-pushup/cli', command, args } = options ?? {}; - return { - command: 'npx', - args: [bin, ...objectToCliArgs({ _: command ?? [], ...args })], - }; -} - -type ArgumentValue = number | string | boolean | string[]; -export type CliArgsObject> = - T extends never - ? Record | { _: string } - : T; - -// @TODO import from @code-pushup/utils => get rid of poppins for cjs support -export function objectToCliArgs< - T extends object = Record, ->(params?: CliArgsObject): string[] { - if (!params) { - return []; - } - - return Object.entries(params).flatMap(([key, value]) => { - // process/file/script - if (key === '_') { - return (Array.isArray(value) ? value : [`${value}`]).filter( - v => v != null, - ); - } - - const prefix = key.length === 1 ? '-' : '--'; - // "-*" arguments (shorthands) - if (Array.isArray(value)) { - return value.map(v => `${prefix}${key}="${v}"`); - } - - if (typeof value === 'object') { - return Object.entries(value as Record).flatMap( - // transform nested objects to the dot notation `key.subkey` - ([k, v]) => objectToCliArgs({ [`${key}.${k}`]: v }), - ); - } - - if (typeof value === 'string') { - return [`${prefix}${key}="${value}"`]; - } - - if (typeof value === 'number') { - return [`${prefix}${key}=${value}`]; - } - - if (typeof value === 'boolean') { - return [`${prefix}${value ? '' : 'no-'}${key}`]; - } - - if (value === undefined) { - return []; - } - - throw new Error(`Unsupported type ${typeof value} for key ${key}`); - }); -} diff --git a/packages/nx-plugin/src/executors/internal/cli.unit.test.ts b/packages/nx-plugin/src/executors/internal/cli.unit.test.ts deleted file mode 100644 index 279f23505..000000000 --- a/packages/nx-plugin/src/executors/internal/cli.unit.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { - createCliCommandObject, - createCliCommandString, - objectToCliArgs, -} from './cli.js'; - -describe('objectToCliArgs', () => { - it('should empty params', () => { - const result = objectToCliArgs(); - expect(result).toEqual([]); - }); - - it('should handle the "_" argument as script', () => { - const params = { _: 'bin.js' }; - const result = objectToCliArgs(params); - expect(result).toEqual(['bin.js']); - }); - - it('should handle the "_" argument with multiple values', () => { - const params = { _: ['bin.js', '--help'] }; - const result = objectToCliArgs(params); - expect(result).toEqual(['bin.js', '--help']); - }); - - it('should handle shorthands arguments', () => { - const params = { - e: `test`, - }; - const result = objectToCliArgs(params); - expect(result).toEqual([`-e="${params.e}"`]); - }); - - it('should handle string arguments', () => { - const params = { name: 'Juanita' }; - const result = objectToCliArgs(params); - expect(result).toEqual(['--name="Juanita"']); - }); - - it('should handle number arguments', () => { - const params = { parallel: 5 }; - const result = objectToCliArgs(params); - expect(result).toEqual(['--parallel=5']); - }); - - it('should handle boolean arguments', () => { - const params = { progress: true }; - const result = objectToCliArgs(params); - expect(result).toEqual(['--progress']); - }); - - it('should handle negated boolean arguments', () => { - const params = { progress: false }; - const result = objectToCliArgs(params); - expect(result).toEqual(['--no-progress']); - }); - - it('should handle array of string arguments', () => { - const params = { format: ['json', 'md'] }; - const result = objectToCliArgs(params); - expect(result).toEqual(['--format="json"', '--format="md"']); - }); - - it('should handle objects', () => { - const params = { format: { json: 'simple' } }; - const result = objectToCliArgs(params); - expect(result).toStrictEqual(['--format.json="simple"']); - }); - - it('should handle nested objects', () => { - const params = { persist: { format: ['json', 'md'], verbose: false } }; - const result = objectToCliArgs(params); - expect(result).toEqual([ - '--persist.format="json"', - '--persist.format="md"', - '--no-persist.verbose', - ]); - }); - - it('should handle objects with undefined', () => { - const params = { format: undefined }; - const result = objectToCliArgs(params); - expect(result).toStrictEqual([]); - }); - - it('should throw error for unsupported type', () => { - expect(() => objectToCliArgs({ param: Symbol('') })).toThrow( - 'Unsupported type', - ); - }); -}); - -describe('createCliCommandString', () => { - it('should create command out of object for arguments', () => { - const result = createCliCommandString({ args: { verbose: true } }); - expect(result).toBe('npx @code-pushup/cli --verbose'); - }); - - it('should create command out of object for arguments with positional', () => { - const result = createCliCommandString({ - args: { _: 'autorun', verbose: true }, - }); - expect(result).toBe('npx @code-pushup/cli autorun --verbose'); - }); -}); - -describe('createCliCommandObject', () => { - it('should create command out of object for arguments', () => { - expect(createCliCommandObject({ args: { verbose: true } })).toStrictEqual({ - args: ['@code-pushup/cli', '--verbose'], - command: 'npx', - }); - }); - - it('should create command out of object for arguments with positional', () => { - expect( - createCliCommandObject({ - args: { _: 'autorun', verbose: true }, - }), - ).toStrictEqual({ - args: ['@code-pushup/cli', 'autorun', '--verbose'], - command: 'npx', - }); - }); - - it('should create command out of object for arguments with bin', () => { - expect( - createCliCommandObject({ - bin: 'node_modules/@code-pushup/cli/src/bin.js', - }), - ).toStrictEqual({ - args: ['node_modules/@code-pushup/cli/src/bin.js'], - command: 'npx', - }); - }); -}); diff --git a/packages/nx-plugin/src/executors/internal/config.ts b/packages/nx-plugin/src/executors/internal/config.ts index 1ef022a44..fbe988587 100644 --- a/packages/nx-plugin/src/executors/internal/config.ts +++ b/packages/nx-plugin/src/executors/internal/config.ts @@ -27,17 +27,20 @@ export function persistConfig( options: Partial, context: BaseNormalizedExecutorContext, ): Partial { - const { projectConfig, workspaceRoot } = context; - - const { name: projectName = '' } = projectConfig ?? {}; const { format, - outputDir = path.join(workspaceRoot, '.code-pushup', projectName), // always in /.code-pushup/, + outputDir = '{workspaceRoot}/.code-pushup/{projectName}', filename, } = options; + const { workspaceRoot, projectConfig } = context; + const projectName = projectConfig?.name ?? ''; + const resolvedOutputDir = outputDir + .replace('{workspaceRoot}', workspaceRoot) + .replace('{projectName}', projectName); + return { - outputDir, + outputDir: resolvedOutputDir, ...(format ? { format } : {}), ...(filename ? { filename } : {}), }; diff --git a/packages/nx-plugin/src/executors/internal/types.ts b/packages/nx-plugin/src/executors/internal/types.ts index 2f529038a..677d472ce 100644 --- a/packages/nx-plugin/src/executors/internal/types.ts +++ b/packages/nx-plugin/src/executors/internal/types.ts @@ -30,6 +30,7 @@ export type Command = export type GlobalExecutorOptions = { command?: Command; bin?: string; + env?: Record; verbose?: boolean; progress?: boolean; config?: string; diff --git a/packages/nx-plugin/src/generators/configuration/generator.int.test.ts b/packages/nx-plugin/src/generators/configuration/generator.int.test.ts index 25c6cbae2..ba779c955 100644 --- a/packages/nx-plugin/src/generators/configuration/generator.int.test.ts +++ b/packages/nx-plugin/src/generators/configuration/generator.int.test.ts @@ -7,7 +7,6 @@ import { import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; import * as path from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { DEFAULT_TARGET_NAME, PACKAGE_NAME } from '../../internal/constants.js'; import { configurationGenerator } from './generator.js'; describe('configurationGenerator', () => { diff --git a/packages/nx-plugin/src/generators/configuration/schema.d.ts b/packages/nx-plugin/src/generators/configuration/schema.d.ts index b105270c6..0f0cb7b79 100644 --- a/packages/nx-plugin/src/generators/configuration/schema.d.ts +++ b/packages/nx-plugin/src/generators/configuration/schema.d.ts @@ -2,7 +2,6 @@ import type { DynamicTargetOptions } from '../../internal/types.js'; export type ConfigurationGeneratorOptions = { project: string; - bin?: string; skipTarget?: boolean; skipConfig?: boolean; skipFormat?: boolean; diff --git a/packages/nx-plugin/src/index.ts b/packages/nx-plugin/src/index.ts index c074211c6..cdf7f48f3 100644 --- a/packages/nx-plugin/src/index.ts +++ b/packages/nx-plugin/src/index.ts @@ -1,21 +1,12 @@ -import { createNodes, createNodesV2 } from './plugin/index.js'; - -// default export for nx.json#plugins -const plugin = { - name: '@code-pushup/nx-plugin', - createNodesV2, - // Keep for backwards compatibility with Nx < 21 - createNodes, -}; - -export default plugin; +import { plugin } from './plugin/index.js'; +export { createNodes, createNodesV2 } from './plugin/index.js'; export type { AutorunCommandExecutorOptions } from './executors/cli/schema.js'; -export { objectToCliArgs } from './executors/internal/cli.js'; export { generateCodePushupConfig } from './generators/configuration/code-pushup-config.js'; export { configurationGenerator } from './generators/configuration/generator.js'; export type { ConfigurationGeneratorOptions } from './generators/configuration/schema.js'; export { initGenerator, initSchematic } from './generators/init/generator.js'; export { type InitGeneratorSchema } from './generators/init/schema.js'; export * from './internal/versions.js'; -export { createNodes, createNodesV2 } from './plugin/index.js'; + +export default plugin; diff --git a/packages/nx-plugin/src/internal/types.ts b/packages/nx-plugin/src/internal/types.ts index bf3a2d047..3a34d86d7 100644 --- a/packages/nx-plugin/src/internal/types.ts +++ b/packages/nx-plugin/src/internal/types.ts @@ -1,4 +1,5 @@ export type DynamicTargetOptions = { targetName?: string; bin?: string; + env?: Record; }; diff --git a/packages/nx-plugin/src/plugin/index.ts b/packages/nx-plugin/src/plugin/index.ts index 6af7c1076..450cf2ced 100644 --- a/packages/nx-plugin/src/plugin/index.ts +++ b/packages/nx-plugin/src/plugin/index.ts @@ -1,2 +1,2 @@ -export { createNodes, createNodesV2 } from './plugin.js'; +export { createNodes, createNodesV2, plugin } from './plugin.js'; export type { CreateNodesOptions } from './types.js'; diff --git a/packages/nx-plugin/src/plugin/plugin.ts b/packages/nx-plugin/src/plugin/plugin.ts index 1b4e3e2f1..37a178619 100644 --- a/packages/nx-plugin/src/plugin/plugin.ts +++ b/packages/nx-plugin/src/plugin/plugin.ts @@ -5,6 +5,7 @@ import type { CreateNodesResult, CreateNodesResultV2, CreateNodesV2, + NxPlugin, } from '@nx/devkit'; import { PROJECT_JSON_FILE_NAME } from '../internal/constants.js'; import { createTargets } from './target/targets.js'; @@ -39,14 +40,15 @@ export const createNodes: CreateNodes = [ }, ]; -export const createNodesV2: CreateNodesV2 = [ +export const createNodesV2: CreateNodesV2 = [ `**/${PROJECT_JSON_FILE_NAME}`, async ( projectConfigurationFiles: readonly string[], createNodesOptions: unknown, context: CreateNodesContextV2, ): Promise => { - const parsedCreateNodesOptions = createNodesOptions as CreateNodesOptions; + const parsedCreateNodesOptions = + (createNodesOptions as CreateNodesOptions) ?? {}; return await Promise.all( projectConfigurationFiles.map(async projectConfigurationFile => { @@ -69,3 +71,9 @@ export const createNodesV2: CreateNodesV2 = [ ); }, ]; + +export const plugin = { + name: 'code-pushup', + createNodesV2: createNodesV2 as CreateNodesV2, + createNodes, +} satisfies NxPlugin; diff --git a/packages/nx-plugin/src/plugin/target/configuration-target.ts b/packages/nx-plugin/src/plugin/target/configuration-target.ts index cc9655969..b7af9a723 100644 --- a/packages/nx-plugin/src/plugin/target/configuration-target.ts +++ b/packages/nx-plugin/src/plugin/target/configuration-target.ts @@ -1,17 +1,16 @@ import type { TargetConfiguration } from '@nx/devkit'; import type { RunCommandsOptions } from 'nx/src/executors/run-commands/run-commands.impl'; -import { objectToCliArgs } from '../../executors/internal/cli.js'; import { PACKAGE_NAME } from '../../internal/constants.js'; -export function createConfigurationTarget(options?: { +export async function createConfigurationTarget(options?: { projectName?: string; - bin?: string; -}): TargetConfiguration { - const { projectName, bin = PACKAGE_NAME } = options ?? {}; +}): Promise> { + const { projectName } = options ?? {}; + const { objectToCliArgs } = await import('@code-pushup/utils'); const args = objectToCliArgs({ ...(projectName ? { project: projectName } : {}), }); return { - command: `nx g ${bin}:configuration${args.length > 0 ? ` ${args.join(' ')}` : ''}`, + command: `nx g ${PACKAGE_NAME}:configuration${args.length > 0 ? ` ${args.join(' ')}` : ''}`, }; } diff --git a/packages/nx-plugin/src/plugin/target/configuration.target.unit.test.ts b/packages/nx-plugin/src/plugin/target/configuration.target.unit.test.ts index f520cc813..e849d7853 100644 --- a/packages/nx-plugin/src/plugin/target/configuration.target.unit.test.ts +++ b/packages/nx-plugin/src/plugin/target/configuration.target.unit.test.ts @@ -3,16 +3,16 @@ import { PACKAGE_NAME } from '../../internal/constants.js'; import { createConfigurationTarget } from './configuration-target.js'; describe('createConfigurationTarget', () => { - it('should return code-pushup--configuration target for given project', () => { + it('should return code-pushup--configuration target for given project', async () => { expect( - createConfigurationTarget({ projectName: 'my-project' }), + await createConfigurationTarget({ projectName: 'my-project' }), ).toStrictEqual({ command: `nx g ${PACKAGE_NAME}:configuration --project="my-project"`, }); }); - it('should return code-pushup--configuration target without project name', () => { - expect(createConfigurationTarget()).toStrictEqual({ + it('should return code-pushup--configuration target without project name', async () => { + expect(await createConfigurationTarget()).toStrictEqual({ command: `nx g ${PACKAGE_NAME}:configuration`, }); }); diff --git a/packages/nx-plugin/src/plugin/target/executor-target.ts b/packages/nx-plugin/src/plugin/target/executor-target.ts index d8cfab569..df968154b 100644 --- a/packages/nx-plugin/src/plugin/target/executor-target.ts +++ b/packages/nx-plugin/src/plugin/target/executor-target.ts @@ -5,13 +5,17 @@ import type { ProjectPrefixOptions } from '../types.js'; export function createExecutorTarget(options?: { bin?: string; projectPrefix?: string; -}): TargetConfiguration { - const { bin, projectPrefix } = options ?? {}; + env?: Record; +}): TargetConfiguration< + ProjectPrefixOptions & { env?: Record } +> { + const { bin, projectPrefix, env } = options ?? {}; const executor = `${PACKAGE_NAME}:cli`; - const executorOptions = (bin || projectPrefix) && { + const executorOptions = (bin || projectPrefix || env) && { ...(bin && { bin }), ...(projectPrefix && { projectPrefix }), + ...(env && { env }), }; return { executor, ...(executorOptions && { options: executorOptions }) }; } diff --git a/packages/nx-plugin/src/plugin/target/executor.target.unit.test.ts b/packages/nx-plugin/src/plugin/target/executor.target.unit.test.ts index 2926d3367..baec99a6d 100644 --- a/packages/nx-plugin/src/plugin/target/executor.target.unit.test.ts +++ b/packages/nx-plugin/src/plugin/target/executor.target.unit.test.ts @@ -27,4 +27,23 @@ describe('createExecutorTarget', () => { }, }); }); + + it('should use env if provided', () => { + expect( + createExecutorTarget({ + env: { + NODE_OPTIONS: '--import tsx', + TSX_TSCONFIG_PATH: 'tsconfig.base.json', + }, + }), + ).toStrictEqual({ + executor: '@code-pushup/nx-plugin:cli', + options: { + env: { + NODE_OPTIONS: '--import tsx', + TSX_TSCONFIG_PATH: 'tsconfig.base.json', + }, + }, + }); + }); }); diff --git a/packages/nx-plugin/src/plugin/target/targets.ts b/packages/nx-plugin/src/plugin/target/targets.ts index ae192ffd8..8037c2e98 100644 --- a/packages/nx-plugin/src/plugin/target/targets.ts +++ b/packages/nx-plugin/src/plugin/target/targets.ts @@ -19,17 +19,17 @@ export async function createTargets(normalizedContext: CreateTargetsOptions) { targetName = CP_TARGET_NAME, bin, projectPrefix, + env, } = normalizedContext.createOptions; const rootFiles = await readdir(normalizedContext.projectRoot); return rootFiles.some(filename => filename.match(CODE_PUSHUP_CONFIG_REGEX)) ? { - [targetName]: createExecutorTarget({ bin, projectPrefix }), + [targetName]: createExecutorTarget({ bin, projectPrefix, env }), } : // if NO code-pushup.config.*.(ts|js|mjs) is present return configuration target { - [`${targetName}--configuration`]: createConfigurationTarget({ + [`${targetName}--configuration`]: await createConfigurationTarget({ projectName: normalizedContext.projectJson.name, - bin, }), }; } diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index edf9f1963..8da647314 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -87,7 +87,7 @@ export { } from './lib/guards.js'; export { interpolate } from './lib/interpolate.js'; export { logMultipleResults } from './lib/log-results.js'; -export { Logger, logger } from './lib/logger.js'; +export { Logger, logger, formatCommand } from './lib/logger.js'; export { link, ui, type CliUi, type Column } from './lib/logging.js'; export { mergeConfigs } from './lib/merge-configs.js'; export { getProgressBar, type ProgressBar } from './lib/progress.js'; diff --git a/packages/utils/src/lib/execute-process.int.test.ts b/packages/utils/src/lib/execute-process.int.test.ts index 8c7e5d97c..aa795f694 100644 --- a/packages/utils/src/lib/execute-process.int.test.ts +++ b/packages/utils/src/lib/execute-process.int.test.ts @@ -104,6 +104,7 @@ describe('executeProcess', () => { expect(logger.command).toHaveBeenCalledWith( 'echo hello', expect.any(Function), + {}, ); }); diff --git a/packages/utils/src/lib/execute-process.ts b/packages/utils/src/lib/execute-process.ts index e05bbf444..30346e715 100644 --- a/packages/utils/src/lib/execute-process.ts +++ b/packages/utils/src/lib/execute-process.ts @@ -153,7 +153,15 @@ export type ProcessObserver = { * @param cfg - see {@link ProcessConfig} */ export function executeProcess(cfg: ProcessConfig): Promise { - const { command, args, observer, ignoreExitCode = false, ...options } = cfg; + const { + command, + args, + observer, + ignoreExitCode = false, + env, + cwd, + ...options + } = cfg; const { onStdout, onStderr, onError, onComplete } = observer ?? {}; const bin = [command, ...(args ?? [])].join(' '); @@ -162,11 +170,13 @@ export function executeProcess(cfg: ProcessConfig): Promise { bin, () => new Promise((resolve, reject) => { + const mergedEnv = env ? { ...process.env, ...env } : undefined; const spawnedProcess = spawn(command, args ?? [], { // shell:true tells Windows to use shell command for spawning a child process // https://stackoverflow.com/questions/60386867/node-spawn-child-process-not-working-in-windows shell: true, - windowsHide: true, + ...(mergedEnv && { env: mergedEnv as Record }), + ...(cwd && { cwd: cwd as string }), ...options, }) as ChildProcessByStdio; @@ -210,5 +220,9 @@ export function executeProcess(cfg: ProcessConfig): Promise { } }); }), + { + ...(cwd && { cwd: cwd as string }), + ...(env ? { env: env as Record } : {}), + }, ); } diff --git a/packages/utils/src/lib/logger.ts b/packages/utils/src/lib/logger.ts index c8ba41033..5daf320cb 100644 --- a/packages/utils/src/lib/logger.ts +++ b/packages/utils/src/lib/logger.ts @@ -216,14 +216,15 @@ export class Logger { command( bin: string, worker: () => Promise, - options?: { cwd?: string }, + options?: { + env?: Record; + cwd?: string; + }, ): Promise { - const cwd = options?.cwd && path.relative(process.cwd(), options.cwd); - const cwdPrefix = cwd ? `${ansis.blue(cwd)} ` : ''; return this.#spinner(worker, { - pending: `${cwdPrefix}${ansis.blue('$')} ${bin}`, - success: () => `${cwdPrefix}${ansis.green('$')} ${bin}`, - failure: () => `${cwdPrefix}${ansis.red('$')} ${bin}`, + pending: formatCommand(bin, options, 'pending'), + success: () => formatCommand(bin, options, 'success'), + failure: () => formatCommand(bin, options, 'failure'), }); } @@ -491,3 +492,42 @@ export class Logger { * logger.info('Made with ❤️ by Code PushUp'); */ export const logger = new Logger(); + +/** + * Formats a command string for display with status indicator. + * + * @param bin Command string with arguments. + * @param options Command options (cwd, env). + * @param status Command status ('pending' | 'success' | 'failure'). + * @returns Formatted command string with colored status indicator. + */ +export function formatCommand( + bin: string, + options?: { + env?: Record; + cwd?: string; + }, + status: 'pending' | 'success' | 'failure' = 'pending', +): string { + const cwd = options?.cwd && path.relative(process.cwd(), options.cwd); + const cwdPrefix = cwd ? ansis.blue(cwd) : ''; + const envString = + options?.env && Object.keys(options.env).length > 0 + ? Object.entries(options.env).map(([key, value]) => { + return ansis.gray(`${key}="${value}"`); + }) + : []; + const statusColor = + status === 'pending' + ? ansis.blue('$') + : status === 'success' + ? ansis.green('$') + : ansis.red('$'); + + return [ + ...(cwdPrefix ? [cwdPrefix] : []), + statusColor, + ...envString, + bin, + ].join(' '); +} diff --git a/packages/utils/src/lib/logger.unit.test.ts b/packages/utils/src/lib/logger.unit.test.ts new file mode 100644 index 000000000..7ce28b68f --- /dev/null +++ b/packages/utils/src/lib/logger.unit.test.ts @@ -0,0 +1,73 @@ +import ansis from 'ansis'; +import path from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { formatCommand } from './logger.js'; + +describe('formatCommand', () => { + const originalCwd = process.cwd(); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should format complex command with cwd, env, and status', () => { + vi.spyOn(path, 'relative').mockReturnValue(''); + expect( + formatCommand( + 'npx eslint . --format=json', + { + cwd: '', + env: { CP_VERBOSE: true }, + }, + 'failure', + ), + ).toBe( + `${ansis.blue('')} ${ansis.red('$')} ${ansis.gray('CP_VERBOSE="true"')} npx eslint . --format=json`, + ); + }); + + it.each([ + [undefined, ansis.blue], // default to pending + ['pending' as const, ansis.blue], + ['success' as const, ansis.green], + ['failure' as const, ansis.red], + ])(`should format command status %s explicitly`, (status, color) => { + expect(formatCommand('npx eslint . --format=json', {}, status)).toContain( + `${color('$')}`, + ); + }); + + it('should include cwd prefix when cwd is provided and different from process.cwd()', () => { + const mockCwd = path.join(originalCwd, 'src'); + vi.spyOn(path, 'relative').mockReturnValue('src'); + + expect(formatCommand('npx -v', { cwd: mockCwd })).toStartWith( + `${ansis.blue('src')} `, + ); + }); + + it('should not include cwd prefix when cwd is same as process.cwd()', () => { + vi.spyOn(path, 'relative').mockReturnValue(''); + expect(formatCommand('npx -v', { cwd: originalCwd })).toStartWith( + `${ansis.blue('$')}`, + ); + }); + + it('should format command with multiple environment variables', () => { + const result = formatCommand('npx eslint .', { + env: { NODE_ENV: 'test', NODE_OPTIONS: '--import tsx' }, + }); + expect(result).toStartWith( + `${ansis.blue('$')} ${ansis.gray('NODE_ENV="test"')} ${ansis.gray('NODE_OPTIONS="--import tsx"')}`, + ); + }); + + it('should format command with environment variable containing spaces', () => { + const result = formatCommand('node packages/cli/src/index.ts', { + env: { NODE_OPTIONS: '--import tsx' }, + }); + expect(result).toBe( + `${ansis.blue('$')} ${ansis.gray('NODE_OPTIONS="--import tsx"')} node packages/cli/src/index.ts`, + ); + }); +}); diff --git a/packages/utils/src/lib/transform.ts b/packages/utils/src/lib/transform.ts index 86caf9aef..538b9fd1a 100644 --- a/packages/utils/src/lib/transform.ts +++ b/packages/utils/src/lib/transform.ts @@ -102,6 +102,10 @@ export function objectToCliArgs< return [`${prefix}${value ? '' : 'no-'}${key}`]; } + if (value === null || value === undefined) { + return []; + } + throw new Error(`Unsupported type ${typeof value} for key ${key}`); }); } diff --git a/packages/utils/src/lib/transform.unit.test.ts b/packages/utils/src/lib/transform.unit.test.ts index b72982e3d..deadc162d 100644 --- a/packages/utils/src/lib/transform.unit.test.ts +++ b/packages/utils/src/lib/transform.unit.test.ts @@ -226,8 +226,14 @@ describe('objectToCliArgs', () => { ]); }); + it('should handle objects with undefined', () => { + const params = { format: undefined }; + const result = objectToCliArgs(params); + expect(result).toStrictEqual([]); + }); + it('should throw error for unsupported type', () => { - const params = { unsupported: undefined as any }; + const params = { unsupported: Symbol('test') as any }; expect(() => objectToCliArgs(params)).toThrow('Unsupported type'); }); }); diff --git a/project.json b/project.json index c53ed1a80..7e5be7514 100644 --- a/project.json +++ b/project.json @@ -25,19 +25,6 @@ ] }, "code-pushup-jsdocs": {}, - "code-pushup-typescript": {}, - "code-pushup": { - "dependsOn": ["code-pushup-*"], - "executor": "nx:run-commands", - "options": { - "args": [ - "--no-progress", - "--verbose", - "--cache.read", - "--persist.outputDir={projectRoot}/.code-pushup", - "--upload.project={projectName}" - ] - } - } + "code-pushup-typescript": {} } } diff --git a/testing/test-utils/src/lib/utils/string.ts b/testing/test-utils/src/lib/utils/string.ts index 025df0a2c..e81ae8cb4 100644 --- a/testing/test-utils/src/lib/utils/string.ts +++ b/testing/test-utils/src/lib/utils/string.ts @@ -1,5 +1,6 @@ +import ansis from 'ansis'; + // removes all color codes from the output for snapshot readability export function removeColorCodes(stdout: string) { - // eslint-disable-next-line no-control-regex - return stdout.replace(/\u001B\[\d+m/g, ''); + return ansis.strip(stdout); } diff --git a/tools/src/debug/debug.plugin.ts b/tools/src/debug/debug.plugin.ts index f1a6f307b..f13f0300c 100644 --- a/tools/src/debug/debug.plugin.ts +++ b/tools/src/debug/debug.plugin.ts @@ -1,6 +1,6 @@ import type { CreateNodes, CreateNodesContext } from '@nx/devkit'; import { dirname } from 'node:path'; -import { objectToCliArgs } from '../../../packages/nx-plugin/src/executors/internal/cli.js'; +import { objectToCliArgs } from '@code-pushup/utils'; import { TOOLS_TSCONFIG_PATH } from '../constants.js'; import { KILL_PROCESS_BIN, LIST_PROCESS_BIN } from './constants.js';