Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
46 changes: 46 additions & 0 deletions packages/create-cli/src/lib/setup/gitignore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileExists, getGitRoot, readTextFile } from '@code-pushup/utils';
import type { FileChange } from './types.js';

const GITIGNORE_FILENAME = '.gitignore';
const REPORTS_DIR = '.code-pushup';

export async function resolveGitignore(): Promise<FileChange | null> {
const gitRoot = await getGitRoot();
const gitignorePath = path.join(gitRoot, GITIGNORE_FILENAME);

const section = `# Code PushUp reports\n${REPORTS_DIR}\n`;

const hasGitignore = await fileExists(gitignorePath);
if (!hasGitignore) {
return { type: 'CREATE', path: GITIGNORE_FILENAME, content: section };
}

const currentContent = await readTextFile(gitignorePath);
if (currentContent.includes(REPORTS_DIR)) {
return null;
}
Comment thread
matejchalk marked this conversation as resolved.
Outdated

const separator = currentContent.endsWith('\n\n')
? ''
: currentContent.endsWith('\n')
? '\n'
: '\n\n';

return {
type: 'UPDATE',
path: GITIGNORE_FILENAME,
content: `${currentContent}${separator}${section}`,
};
}

export async function updateGitignore(
change: FileChange | null,
): Promise<void> {
if (change == null) {
return;
}
const gitRoot = await getGitRoot();
await writeFile(path.join(gitRoot, change.path), change.content);
}
78 changes: 78 additions & 0 deletions packages/create-cli/src/lib/setup/gitignore.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { vol } from 'memfs';
import { readFile } from 'node:fs/promises';
import { MEMFS_VOLUME } from '@code-pushup/test-utils';
import { resolveGitignore, updateGitignore } from './gitignore.js';

describe('resolveGitignore', () => {
it('should return CREATE change with comment when no .gitignore exists', async () => {
vol.fromJSON({ 'package.json': '{}' }, MEMFS_VOLUME);

await expect(resolveGitignore()).resolves.toStrictEqual({
type: 'CREATE',
path: '.gitignore',
content: '# Code PushUp reports\n.code-pushup\n',
});
});

it('should return UPDATE change with blank line separator for existing .gitignore', async () => {
vol.fromJSON({ '.gitignore': 'node_modules\n' }, MEMFS_VOLUME);

await expect(resolveGitignore()).resolves.toStrictEqual({
type: 'UPDATE',
path: '.gitignore',
content: 'node_modules\n\n# Code PushUp reports\n.code-pushup\n',
});
});

it('should preserve existing blank line before appending', async () => {
vol.fromJSON({ '.gitignore': 'node_modules\n\n' }, MEMFS_VOLUME);

await expect(resolveGitignore()).resolves.toStrictEqual({
type: 'UPDATE',
path: '.gitignore',
content: 'node_modules\n\n# Code PushUp reports\n.code-pushup\n',
});
});

it('should add double newline separator when .gitignore has no trailing newline', async () => {
vol.fromJSON({ '.gitignore': 'node_modules' }, MEMFS_VOLUME);

await expect(resolveGitignore()).resolves.toStrictEqual({
type: 'UPDATE',
path: '.gitignore',
content: 'node_modules\n\n# Code PushUp reports\n.code-pushup\n',
});
});

it('should return null if entry already in .gitignore', async () => {
vol.fromJSON({ '.gitignore': '.code-pushup\n' }, MEMFS_VOLUME);

await expect(resolveGitignore()).resolves.toBeNull();
});
});

describe('updateGitignore', () => {
it('should skip writing when change is null', async () => {
vol.fromJSON({ 'package.json': '{}' }, MEMFS_VOLUME);

await updateGitignore(null);

expect(vol.toJSON(MEMFS_VOLUME)).toStrictEqual({
[`${MEMFS_VOLUME}/package.json`]: '{}',
});
});

it('should write .gitignore file to git root', async () => {
vol.fromJSON({ 'package.json': '{}' }, MEMFS_VOLUME);

await updateGitignore({
type: 'CREATE',
path: '.gitignore',
content: '# Code PushUp reports\n.code-pushup\n',
});

await expect(readFile(`${MEMFS_VOLUME}/.gitignore`, 'utf8')).resolves.toBe(
'# Code PushUp reports\n.code-pushup\n',
);
});
});
53 changes: 53 additions & 0 deletions packages/create-cli/src/lib/setup/wizard.int.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { cleanTestFolder } from '@code-pushup/test-utils';
import { getGitRoot } from '@code-pushup/utils';
import type { PluginSetupBinding } from './types.js';
import { runSetupWizard } from './wizard.js';

vi.mock('@code-pushup/utils', async () => {
const actual = await vi.importActual('@code-pushup/utils');
return {
...actual,
getGitRoot: vi.fn(),
};
});

const TEST_BINDINGS: PluginSetupBinding[] = [
{
slug: 'alpha',
Expand Down Expand Up @@ -51,6 +60,7 @@ describe('runSetupWizard', () => {

beforeEach(async () => {
await cleanTestFolder(outputDir);
vi.mocked(getGitRoot).mockResolvedValue(path.resolve(outputDir));
});

it('should write a valid ts config file with provided bindings', async () => {
Expand Down Expand Up @@ -167,4 +177,47 @@ describe('runSetupWizard', () => {
"
`);
});

it('should create .gitignore with .code-pushup entry', async () => {
await runSetupWizard(TEST_BINDINGS, {
yes: true,
'config-format': 'ts',
'target-dir': outputDir,
});

await expect(
readFile(path.join(outputDir, '.gitignore'), 'utf8'),
).resolves.toBe('# Code PushUp reports\n.code-pushup\n');
});

it('should append .code-pushup to existing .gitignore', async () => {
await writeFile(path.join(outputDir, '.gitignore'), 'node_modules\n');

await runSetupWizard(TEST_BINDINGS, {
yes: true,
'config-format': 'ts',
'target-dir': outputDir,
});

await expect(
readFile(path.join(outputDir, '.gitignore'), 'utf8'),
).resolves.toBe('node_modules\n\n# Code PushUp reports\n.code-pushup\n');
});

it('should not modify .gitignore if .code-pushup already present', async () => {
await writeFile(
path.join(outputDir, '.gitignore'),
'node_modules\n.code-pushup\n',
);

await runSetupWizard(TEST_BINDINGS, {
yes: true,
'config-format': 'ts',
'target-dir': outputDir,
});

await expect(
readFile(path.join(outputDir, '.gitignore'), 'utf8'),
).resolves.toBe('node_modules\n.code-pushup\n');
});
});
34 changes: 23 additions & 11 deletions packages/create-cli/src/lib/setup/wizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
readPackageJson,
resolveConfigFilename,
} from './config-format.js';
import { resolveGitignore, updateGitignore } from './gitignore.js';
import { promptPluginOptions } from './prompts.js';
import type {
CliArgs,
Expand Down Expand Up @@ -35,21 +36,26 @@ export async function runSetupWizard(
const tree = createTree(targetDir);
await tree.write(filename, generateConfigSource(pluginResults, format));

const changes = tree.listChanges();
const configChanges = tree.listChanges();
const gitignoreChange = await resolveGitignore();
const changes = collectChanges(configChanges, gitignoreChange);

logChanges(changes);

if (cliArgs['dry-run']) {
logChanges(changes);
logger.info('Dry run — no files written.');
} else {
await tree.flush();
logChanges(changes);
logger.info('Setup complete.');
logger.newline();
logNextSteps([
['npx code-pushup', 'Collect your first report'],
['https://github.com/code-pushup/cli#readme', 'Documentation'],
]);
return;
}

await tree.flush();
await updateGitignore(gitignoreChange);
Comment thread
matejchalk marked this conversation as resolved.
Outdated

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

async function resolveBinding(
Expand All @@ -62,6 +68,12 @@ async function resolveBinding(
return binding.generateConfig(answers);
}

function collectChanges(
...sources: (FileChange[] | FileChange | null)[]
): FileChange[] {
return sources.flat().filter((c): c is FileChange => c != null);
}

function logChanges(changes: FileChange[]): void {
changes.forEach(change => {
logger.info(`${change.type} ${change.path}`);
Expand Down