GeezerVison is showing github.com — fix: cleaner user facing error handing and tests for config file points of failure by lwasser · Pull Request #620 · all-contributors/cli
fix: cleaner user facing error handing and tests for config file points of failure
#620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.js
(5)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
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
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
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
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';
}
}
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
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.