Skip to content

Commit

Permalink
fix(config loader): deal with config file charset (#525)
Browse files Browse the repository at this point in the history
make sure that config file charset is utf-8, or throw detail to notify.
for #465 [Question] SyntaxError: Parsing JSON at for commitizen config failed
  • Loading branch information
hxzhao527 authored and jimthedev committed Oct 19, 2018
1 parent 42c8bb6 commit c74eeb9
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -85,6 +85,7 @@
"lodash": "4.17.11",
"minimist": "1.2.0",
"shelljs": "0.7.6",
"strip-bom": "3.0.0",
"strip-json-comments": "2.0.1"
},
"babel": {
Expand Down
21 changes: 20 additions & 1 deletion src/configLoader/getContent.js
Expand Up @@ -2,6 +2,8 @@ import fs from 'fs';
import path from 'path';

import stripJSONComments from 'strip-json-comments';
import isUTF8 from 'is-utf8';
import stripBom from 'strip-bom';

import { getNormalizedConfig } from '../configLoader';

Expand All @@ -17,7 +19,7 @@ export default getConfigContent;
function readConfigContent (configPath) {
const parsedPath = path.parse(configPath)
const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json';
const jsonString = fs.readFileSync(configPath, 'utf-8');
const jsonString = readConfigFileContent(configPath);
const parse = isRcFile ?
(contents) => JSON.parse(stripJSONComments(contents)) :
(contents) => JSON.parse(contents);
Expand Down Expand Up @@ -61,3 +63,20 @@ function getConfigContent (configPath, baseDirectory) {
const content = readConfigContent(resolvedPath);
return getNormalizedConfig(configBasename, content);
};

/**
* Read proper content from config file.
* If the chartset of the config file is not utf-8, one error will be thrown.
* @param {String} configPath
* @return {String}
*/
function readConfigFileContent (configPath) {

let rawBufContent = fs.readFileSync(configPath);

if (!isUTF8(rawBufContent)) {
throw new Error(`The config file at "${configPath}" contains invalid charset, expect utf8`);
}

return stripBom(rawBufContent.toString("utf8"));
}
Binary file added test/fixtures/invalid-charset.json
Binary file not shown.
2 changes: 2 additions & 0 deletions test/tests/configLoader.js
Expand Up @@ -13,6 +13,8 @@ describe('configLoader', function () {
.to.throw(/parsing json at/i);
expect(() => getContent('invalid-json-rc', fixturesPath))
.to.throw(/parsing json at/i);
expect(() => getContent('invalid-charset.json', fixturesPath))
.to.throw(/contains invalid charset/i);
});

it('parses json files with comments', function () {
Expand Down

0 comments on commit c74eeb9

Please sign in to comment.