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
8 changes: 6 additions & 2 deletions src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ async function run() {
const configData = await util.configFile.readConfig(argv.config);
Object.assign(argv, configData);
} catch (error) {
if (error instanceof SyntaxError || argv.config !== defaultRCFile) {
if (argv.config !== defaultRCFile || error.cause?.code !== 'ENOENT') {
throw error;
}
// If default config file doesn't exist, that's okay
Expand All @@ -163,7 +163,11 @@ async function run() {
case 'check':
return await checkContributors(argv);
default:
throw new Error(`Unknown command ${command}`);
throw new util.UserError(
`Unknown command: ${command}\n` +
'Valid commands are init, generate, add, and check.\n' +
'Run `all-contributors --help` for more details.',
);
}
} catch (e) {
if (e instanceof util.UserError) {
Expand Down
16 changes: 14 additions & 2 deletions src/util/__tests__/config-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'path';
import { expect, test } from 'vitest';

import { readConfig, writeConfig, writeContributors } from '../config-file.js';
import { UserError } from '../user-error.js';

const absentFile = './abc';
const absentConfigFileExpected = `Configuration file not found: ${absentFile}`;
Expand Down Expand Up @@ -35,8 +36,19 @@ const NoFilesConfigFile = {
files: [],
};

test('Reading an absent configuration file throws a helpful error', async () => {
await expect(readConfig(absentFile)).rejects.toThrow(absentConfigFileExpected);
test('Reading an absent configuration file throws a helpful UserError', async () => {
const result = readConfig(absentFile);

await expect(result).rejects.toBeInstanceOf(UserError);
await expect(result).rejects.toThrow(absentConfigFileExpected);
});

test('Reading a configuration file with malformed JSON throws a UserError', async () => {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'all-contributors-'));
const configPath = path.join(directory, '.all-contributorsrc');
await fs.writeFile(configPath, '{');

await expect(readConfig(configPath)).rejects.toBeInstanceOf(UserError);
});

test('Writing contributors in an absent configuration file throws a helpful error', async () => {
Expand Down
49 changes: 30 additions & 19 deletions src/util/config-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { promises as fs } from 'fs';
import jf from 'json-fixer';

import { formatConfig } from './formatting.js';
import { UserError } from './user-error.js';

export async function readConfig(configPath) {
const config = await readConfigFile(configPath);
Expand All @@ -11,33 +12,43 @@ export async function readConfig(configPath) {
}

async function readConfigFile(configPath) {
let configFileContents;
try {
const configFileContents = await fs.readFile(configPath, 'utf-8');
const { data: config, changed } = jf(configFileContents);

if (changed) {
const formatterConfig = await formatConfig(configPath, config);
//Updates the file with fixes
await fs.writeFile(configPath, formatterConfig);
}

return config;
configFileContents = await fs.readFile(configPath, 'utf-8');
} catch (error) {
if (error instanceof SyntaxError) {
throw new SyntaxError(
`Configuration file has malformed JSON: ${configPath}. Error:: ${error.message}`,
if (error.code === 'ENOENT') {
throw new UserError(
`Configuration file not found: ${configPath}\n` +
'Check that the path is correct, or run `all-contributors init` ' +
'to create a new configuration file.',
{ cause: error },
);
}
throw error;
}

if (error.code === 'ENOENT') {
throw new Error(`Configuration file not found: ${configPath}`, {
cause: error,
});
}
let config;
let changed;
try {
// json-fixer prints "There's still an error!" to stderr itself before
// throwing on malformed JSON message. json-fixer has no option to turn that off.
// we could do something hacky to silence this in the future
({ data: config, changed } = jf(configFileContents));
} catch (error) {
throw new UserError(
`Configuration file has malformed JSON: ${configPath}\n${error.message}\n` +
'Fix the JSON in this file, or delete it and run `all-contributors init`.',
{ cause: error },
);
}

throw error;
if (changed) {
const formatterConfig = await formatConfig(configPath, config);
//Updates the file with fixes
await fs.writeFile(configPath, formatterConfig);
}

return config;
}

export async function writeConfig(configPath, content) {
Expand Down
4 changes: 2 additions & 2 deletions src/util/user-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
* The CLI prints only the message for these, without a stack trace.
*/
export class UserError extends Error {
constructor(message) {
super(message);
constructor(message, options) {
super(message, options);
this.name = 'UserError';
}
}
48 changes: 47 additions & 1 deletion test/e2e/cli.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readdir, readFile, rm } from 'node:fs/promises';
import { readdir, readFile, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';

import { expect } from 'vitest';
Expand All @@ -11,6 +11,14 @@ const it = baseIt.extend({
await rm(path.join(project, 'README.md'));
await use(project);
},
projectWithoutConfig: async ({ project }, use) => {
await rm(path.join(project, '.all-contributorsrc'));
await use(project);
},
projectWithMalformedConfig: async ({ project }, use) => {
await writeFile(path.join(project, '.all-contributorsrc'), '{');
await use(project);
},
});

it('--help exits 0 and lists the commands', async ({ tmpDir }) => {
Expand Down Expand Up @@ -44,3 +52,41 @@ it('generate exits 1 when the README is missing', async ({ projectWithoutReadme
expect(result.stderr).not.toContain('ENOENT');
expect(result.stderr).not.toContain('at readFileToUpdate');
});

it('generate exits 0 when the default config is missing', async ({ projectWithoutConfig }) => {
const result = await runCli(['generate'], { cwd: projectWithoutConfig });

expect(result.code).toBe(0);
});

it('generate exits 1 when the default config has malformed JSON', async ({
projectWithMalformedConfig,
}) => {
const result = await runCli(['generate'], { cwd: projectWithMalformedConfig });

expect(result.code).toBe(1);
expect(result.stderr).toContain('Configuration file has malformed JSON');
expect(result.stderr).toContain('.all-contributorsrc');
expect(result.stderr).toContain('all-contributors init');
expect(result.stderr).not.toContain('at readConfigFile');
});

it('exits 1 for an unknown command', async ({ tmpDir }) => {
const result = await runCli(['nope'], { cwd: tmpDir });

expect(result.code).toBe(1);
expect(result.stderr).toContain('Unknown command: nope');
expect(result.stderr).toContain('all-contributors --help');
expect(result.stderr).not.toContain('at run');
});

it('exits 1 when the -c config file does not exist', async ({ tmpDir }) => {
const result = await runCli(['generate', '-c', 'missing.json'], {
cwd: tmpDir,
});

expect(result.code).toBe(1);
expect(result.stderr).toContain('Configuration file not found');
expect(result.stderr).not.toContain('at readConfigFile');
expect(result.stderr).toContain('all-contributors init');
});
Loading