Skip to content

Commit

Permalink
Breaks if no package.json is present
Browse files Browse the repository at this point in the history
If there is no `package.json` available then the path is `null` and you can't stop it from breaking.

Even if you manually provide the `projectName` in options it will still break. This adds a few simple checks to prevent it from blowing up when you do provide the name.

I've also added an appropriate test, which properly fails when run without the changes to `index.js` and correctly passes once added.

Closes #6
  • Loading branch information
Jim Buck authored and sindresorhus committed Jul 12, 2016
1 parent 134308a commit f879200
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ const parentDir = path.dirname(module.parent.filename);
class Conf {
constructor(opts) {
const pkgPath = pkgUp.sync(parentDir);
opts = Object.assign({projectName: require(pkgPath).name}, opts);

opts = Object.assign({
// if the package.json was not found, avoid breaking with `require(null)`
projectName: pkgPath && require(pkgPath).name
}, opts);

if (!opts.projectName && !opts.cwd) {
throw new Error('Project name could not be inferred. Please specify the `projectName` option.');
Expand Down
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'path';
import {serial as test} from 'ava';
import tempfile from 'tempfile';
import del from 'del';
import pkgUp from 'pkg-up';
import Conf from './';

const fixture = '🦄';
Expand Down Expand Up @@ -161,3 +162,15 @@ test('`cwd` option overrides `projectName` option', t => {
t.is(conf.get('foo'), fixture);
del.sync(conf.path, {force: true});
});

test('safely handle missing package.json', t => {
const pkgUpSyncOrig = pkgUp.sync;
pkgUp.sync = () => null;

let conf;
t.notThrows(() => {
conf = new Conf({projectName: 'conf-fixture-project-name'});
});
del.sync(conf.path, {force: true});
pkgUp.sync = pkgUpSyncOrig;
});

0 comments on commit f879200

Please sign in to comment.