Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 15 additions & 15 deletions packages/create-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Each plugin exposes its own configuration keys that can be passed as CLI argumen
| ------------------------- | --------- | ------------- | --------------------- |
| **`--eslint.eslintrc`** | `string` | auto-detected | Path to ESLint config |
| **`--eslint.patterns`** | `string` | `src` or `.` | File patterns to lint |
| **`--eslint.categories`** | `boolean` | `true` | Add ESLint categories |
| **`--eslint.categories`** | `boolean` | `true` | Add categories |

#### Coverage

Expand All @@ -47,37 +47,37 @@ Each plugin exposes its own configuration keys that can be passed as CLI argumen
| **`--coverage.testCommand`** | `string` | auto-detected | Command to run tests |
| **`--coverage.types`** | `('function'` \| `'branch'` \| `'line')[]` | all | Coverage types to measure |
| **`--coverage.continueOnFail`** | `boolean` | `true` | Continue if test command fails |
| **`--coverage.categories`** | `boolean` | `true` | Add Code coverage categories |
| **`--coverage.categories`** | `boolean` | `true` | Add categories |

#### JS Packages

| Option | Type | Default | Description |
| ------------------------------------ | ---------------------------------------------------------- | ------------- | -------------------------- |
| **`--js-packages.packageManager`** | `'npm'` \| `'yarn-classic'` \| `'yarn-modern'` \| `'pnpm'` | auto-detected | Package manager |
| **`--js-packages.checks`** | `('audit'` \| `'outdated')[]` | both | Checks to run |
| **`--js-packages.dependencyGroups`** | `('prod'` \| `'dev'` \| `'optional')[]` | `prod`, `dev` | Dependency groups |
| **`--js-packages.categories`** | `boolean` | `true` | Add JS packages categories |
| Option | Type | Default | Description |
| ------------------------------------ | ---------------------------------------------------------- | ------------- | ----------------- |
| **`--js-packages.packageManager`** | `'npm'` \| `'yarn-classic'` \| `'yarn-modern'` \| `'pnpm'` | auto-detected | Package manager |
| **`--js-packages.checks`** | `('audit'` \| `'outdated')[]` | both | Checks to run |
| **`--js-packages.dependencyGroups`** | `('prod'` \| `'dev'` \| `'optional')[]` | `prod`, `dev` | Dependency groups |
| **`--js-packages.categories`** | `boolean` | `true` | Add categories |

#### TypeScript

| Option | Type | Default | Description |
| ----------------------------- | --------- | ------------- | ------------------------- |
| **`--typescript.tsconfig`** | `string` | auto-detected | TypeScript config file |
| **`--typescript.categories`** | `boolean` | `true` | Add TypeScript categories |
| Option | Type | Default | Description |
| ----------------------------- | --------- | ------------- | ---------------------- |
| **`--typescript.tsconfig`** | `string` | auto-detected | TypeScript config file |
| **`--typescript.categories`** | `boolean` | `true` | Add categories |

#### Lighthouse

| Option | Type | Default | Description |
| ----------------------------- | ---------------------------------------------------------------- | ----------------------- | ------------------------------- |
| **`--lighthouse.urls`** | `string \| string[]` | `http://localhost:4200` | Target URL(s) (comma-separated) |
| **`--lighthouse.categories`** | `('performance'` \| `'a11y'` \| `'best-practices'` \| `'seo')[]` | all | Lighthouse categories |
| **`--lighthouse.categories`** | `('performance'` \| `'a11y'` \| `'best-practices'` \| `'seo')[]` | all | Categories |

#### JSDocs

| Option | Type | Default | Description |
| ------------------------- | -------------------- | -------------------------------------------- | -------------------------------------- |
| **`--jsdocs.patterns`** | `string \| string[]` | `src/**/*.ts, src/**/*.js, !**/node_modules` | Source file patterns (comma-separated) |
| **`--jsdocs.categories`** | `boolean` | `true` | Add JSDocs categories |
| **`--jsdocs.categories`** | `boolean` | `true` | Add categories |

#### Axe

Expand All @@ -86,7 +86,7 @@ Each plugin exposes its own configuration keys that can be passed as CLI argumen
| **`--axe.urls`** | `string \| string[]` | `http://localhost:4200` | Target URL(s) (comma-separated) |
| **`--axe.preset`** | `'wcag21aa'` \| `'wcag22aa'` \| `'best-practice'` \| `'all'` | `wcag21aa` | Accessibility preset |
| **`--axe.setupScript`** | `boolean` | `false` | Create setup script for auth-protected app |
| **`--axe.categories`** | `boolean` | `true` | Add Axe categories |
| **`--axe.categories`** | `boolean` | `true` | Add categories |

### Examples

Expand Down
9 changes: 7 additions & 2 deletions packages/create-cli/src/lib/setup/virtual-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ export function createTree(
},

write: async (filePath: string, content: string): Promise<void> => {
const type = (await fs.exists(resolve(filePath))) ? 'UPDATE' : 'CREATE';
pending.set(filePath, { content, type });
const entry = pending.get(filePath);
if (entry) {
pending.set(filePath, { ...entry, content });
} else {
const type = (await fs.exists(resolve(filePath))) ? 'UPDATE' : 'CREATE';
pending.set(filePath, { content, type });
}
},

listChanges: (): FileChange[] =>
Expand Down
10 changes: 10 additions & 0 deletions packages/create-cli/src/lib/setup/virtual-fs.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ describe('createTree', () => {
]);
});

it('should preserve CREATE type when writing to the same path twice', async () => {
const tree = createTree('/project', createMockFs());
await tree.write('new.ts', 'first');
await tree.write('new.ts', 'second');

expect(tree.listChanges()).toStrictEqual([
{ path: 'new.ts', type: 'CREATE', content: 'second' },
]);
});

it('should mark existing files as UPDATE', async () => {
const tree = createTree(
'/project',
Expand Down
49 changes: 27 additions & 22 deletions packages/create-cli/src/lib/setup/wizard.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ansis from 'ansis';
import path from 'node:path';
import {
type MonorepoTool,
Expand Down Expand Up @@ -28,7 +29,6 @@ import {
import { promptPluginOptions, promptPluginSelection } from './prompts.js';
import type {
CliArgs,
FileChange,
PluginCodegenResult,
PluginSetupBinding,
ScopedPluginResult,
Expand Down Expand Up @@ -83,21 +83,7 @@ export async function runSetupWizard(
await resolveGitignore(tree);
await resolveCi(tree, ciProvider, context);

logChanges(tree.listChanges());

if (cliArgs['dry-run']) {
logger.info('Dry run — no files written.');
return;
}

await tree.flush();

logger.info('Setup complete.');
logger.newline();
logNextSteps([
['npx code-pushup', 'Collect your first report'],
['https://github.com/code-pushup/cli#readme', 'Documentation'],
]);
await finalize(tree, cliArgs['dry-run']);
}

async function resolveBinding(
Expand All @@ -106,7 +92,12 @@ async function resolveBinding(
targetDir: string,
tree: Pick<Tree, 'read' | 'write'>,
): Promise<PluginCodegenResult> {
const descriptors = binding.prompts ? await binding.prompts(targetDir) : [];
if (!binding.prompts) {
return binding.generateConfig({}, tree);
}
logger.newline();
logger.info(ansis.bold(binding.title));
const descriptors = await binding.prompts(targetDir);
const answers =
descriptors.length > 0
? await promptPluginOptions(descriptors, cliArgs)
Expand Down Expand Up @@ -161,18 +152,32 @@ async function writeMonorepoConfigs(
);
}

function logChanges(changes: FileChange[]): void {
changes.forEach(change => {
async function finalize(tree: Tree, dryRun?: boolean): Promise<void> {
logger.newline();

tree.listChanges().forEach(change => {
logger.info(`${change.type} ${change.path}`);
});
}

function logNextSteps(steps: [string, string][]): void {
if (dryRun) {
logger.newline();
logger.info('Dry run — no files written.');
return;
}

await tree.flush();

logger.newline();
logger.info('Setup complete.');
logger.newline();
logger.info(
formatAsciiTable(
{
title: 'Next steps:',
rows: steps,
rows: [
['npx code-pushup', 'Collect your first report'],
['https://github.com/code-pushup/cli#readme', 'Documentation'],
],
},
{ borderless: true },
),
Expand Down
113 changes: 60 additions & 53 deletions packages/create-cli/src/lib/setup/wizard.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,26 @@ vi.mock('./monorepo.js', async importOriginal => ({
addCodePushUpCommand: vi.fn().mockResolvedValue(undefined),
}));

const TEST_BINDING: PluginSetupBinding = {
slug: 'test-plugin',
title: 'Test Plugin',
packageName: '@code-pushup/test-plugin',
isRecommended: () => Promise.resolve(true),
generateConfig: () => ({
imports: [
{
moduleSpecifier: '@code-pushup/test-plugin',
defaultImport: 'testPlugin',
},
],
pluginInit: ['testPlugin(),'],
}),
};
function createBinding(
overrides?: Partial<PluginSetupBinding>,
): PluginSetupBinding {
return {
slug: 'test-plugin',
title: 'Test Plugin',
packageName: '@code-pushup/test-plugin',
isRecommended: () => Promise.resolve(true),
generateConfig: () => ({
imports: [
{
moduleSpecifier: '@code-pushup/test-plugin',
defaultImport: 'testPlugin',
},
],
pluginInit: ['testPlugin(),'],
}),
...overrides,
};
}

describe('runSetupWizard', () => {
describe('TypeScript config', () => {
Expand All @@ -41,7 +46,7 @@ describe('runSetupWizard', () => {
});

it('should generate ts config and log success', async () => {
await runSetupWizard([TEST_BINDING], {
await runSetupWizard([createBinding()], {
yes: true,
'target-dir': MEMFS_VOLUME,
});
Expand All @@ -67,7 +72,7 @@ describe('runSetupWizard', () => {
});

it('should log dry-run message without writing files', async () => {
await runSetupWizard([TEST_BINDING], {
await runSetupWizard([createBinding()], {
yes: true,
'dry-run': true,
'target-dir': MEMFS_VOLUME,
Expand Down Expand Up @@ -109,7 +114,7 @@ describe('runSetupWizard', () => {
});

it('should generate .mjs config when js format is auto-detected', async () => {
await runSetupWizard([TEST_BINDING], {
await runSetupWizard([createBinding()], {
yes: true,
'target-dir': MEMFS_VOLUME,
});
Expand All @@ -136,7 +141,7 @@ describe('runSetupWizard', () => {
MEMFS_VOLUME,
);

await runSetupWizard([TEST_BINDING], {
await runSetupWizard([createBinding()], {
yes: true,
'config-format': 'js',
'target-dir': MEMFS_VOLUME,
Expand All @@ -159,40 +164,26 @@ describe('runSetupWizard', () => {
});
});

describe('Monorepo config', () => {
const PROJECT_BINDING: PluginSetupBinding = {
slug: 'test-plugin',
title: 'Test Plugin',
packageName: '@code-pushup/test-plugin',
isRecommended: () => Promise.resolve(true),
generateConfig: () => ({
imports: [
{
moduleSpecifier: '@code-pushup/test-plugin',
defaultImport: 'testPlugin',
},
it('should log a heading for each plugin with prompts', async () => {
vol.fromJSON({ 'tsconfig.json': '{}' }, MEMFS_VOLUME);
const withPrompts = (title: string) =>
createBinding({
title,
prompts: async () => [
{ key: 'x', message: 'X:', type: 'input', default: '' },
],
pluginInit: ['testPlugin(),'],
}),
};

const ROOT_BINDING: PluginSetupBinding = {
slug: 'root-plugin',
title: 'Root Plugin',
packageName: '@code-pushup/root-plugin',
scope: 'root',
isRecommended: () => Promise.resolve(true),
generateConfig: () => ({
imports: [
{
moduleSpecifier: '@code-pushup/root-plugin',
defaultImport: 'rootPlugin',
},
],
pluginInit: ['rootPlugin(),'],
}),
};
});

await runSetupWizard(
[withPrompts('Alpha'), createBinding(), withPrompts('Beta')],
{ yes: true, 'target-dir': MEMFS_VOLUME },
);

expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Alpha'));
expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('Beta'));
});

describe('Monorepo config', () => {
beforeEach(() => {
vol.fromJSON(
{
Expand All @@ -216,7 +207,7 @@ describe('runSetupWizard', () => {
});

it('should generate preset and per-project configs', async () => {
await runSetupWizard([PROJECT_BINDING], {
await runSetupWizard([createBinding()], {
yes: true,
mode: 'monorepo',
'target-dir': MEMFS_VOLUME,
Expand Down Expand Up @@ -269,7 +260,23 @@ describe('runSetupWizard', () => {
});

it('should generate root config for root-scoped plugins', async () => {
await runSetupWizard([PROJECT_BINDING, ROOT_BINDING], {
const rootBinding = createBinding({
slug: 'root-plugin',
title: 'Root Plugin',
packageName: '@code-pushup/root-plugin',
scope: 'root',
generateConfig: () => ({
imports: [
{
moduleSpecifier: '@code-pushup/root-plugin',
defaultImport: 'rootPlugin',
},
],
pluginInit: ['rootPlugin(),'],
}),
});

await runSetupWizard([createBinding(), rootBinding], {
yes: true,
mode: 'monorepo',
'target-dir': MEMFS_VOLUME,
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-axe/src/lib/binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ export const axeSetupBinding = {
prompts: async () => [
{
key: 'axe.urls',
message: 'Target URL(s) (comma-separated)',
message: 'Target URL(s) (comma-separated):',
type: 'input',
default: DEFAULT_URL,
},
{
key: 'axe.preset',
message: 'Accessibility preset',
message: 'Accessibility preset:',
type: 'select',
choices: [...PRESET_CHOICES],
default: AXE_DEFAULT_PRESET,
Expand All @@ -79,7 +79,7 @@ export const axeSetupBinding = {
},
{
key: 'axe.categories',
message: 'Add Axe categories?',
message: 'Add categories?',
type: 'confirm',
default: true,
},
Expand Down
Loading
Loading