Skip to content

Commit 1adf5c2

Browse files
sudo-suhasdavidtheclark
authored andcommitted
feat: Throw error on getting empty config file
cosmiconfig did not have a consistent behavior for empty files. See #78 (comment) Throw error if cosmiconfig gets an empty file(JS/JSON/YAML) Add tests for empty file(JS/JSON/YAML)
1 parent 6edf306 commit 1adf5c2

5 files changed

Lines changed: 30 additions & 0 deletions

File tree

lib/loadDefinedFile.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ const parseJson = require('./parseJson');
77

88
module.exports = function loadDefinedFile(filepath, options) {
99
function parseContent(content) {
10+
if (!content) {
11+
throw new Error(`Config file is empty! Filepath - "${filepath}".`);
12+
}
13+
1014
const parsedConfig = (() => {
1115
switch (options.format) {
1216
case 'json':

test/failed-files.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,29 @@ test('defined JS file with syntax error, with expected format', assert => {
129129
assert.end();
130130
});
131131
});
132+
133+
function makeEmptyFileTest(format) {
134+
const filepath = `fixtures/foo-empty.${format}`;
135+
return function emptyFileTest(assert) {
136+
const loadConfig = cosmiconfig(null, { format }).load;
137+
const loadConfigSync = cosmiconfig(null, { format, sync: true }).load;
138+
try {
139+
loadConfigSync(null, absolutePath(filepath));
140+
failAssert(assert);
141+
} catch (error) {
142+
assert.ok(/^Config file is empty/.test(error.message));
143+
}
144+
return loadConfig(null, absolutePath(filepath))
145+
.then(failAssert.bind(null, assert))
146+
.catch(error => {
147+
assert.ok(/^Config file is empty/.test(error.message));
148+
assert.end();
149+
});
150+
};
151+
}
152+
153+
test('defined JSON file empty', makeEmptyFileTest('json'));
154+
155+
test('defined YAML file empty', makeEmptyFileTest('yaml'));
156+
157+
test('defined JS file empty', makeEmptyFileTest('js'));

test/fixtures/foo-empty.js

Whitespace-only changes.

test/fixtures/foo-empty.json

Whitespace-only changes.

test/fixtures/foo-empty.yaml

Whitespace-only changes.

0 commit comments

Comments
 (0)