Skip to content

Commit c74eeb9

Browse files
hxzhao527jimthedev
authored andcommitted
fix(config loader): deal with config file charset (#525)
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
1 parent 42c8bb6 commit c74eeb9

File tree

4 files changed

+23
-1
lines changed

4 files changed

+23
-1
lines changed

Diff for: package.json

+1
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@
8585
"lodash": "4.17.11",
8686
"minimist": "1.2.0",
8787
"shelljs": "0.7.6",
88+
"strip-bom": "3.0.0",
8889
"strip-json-comments": "2.0.1"
8990
},
9091
"babel": {

Diff for: src/configLoader/getContent.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import fs from 'fs';
22
import path from 'path';
33

44
import stripJSONComments from 'strip-json-comments';
5+
import isUTF8 from 'is-utf8';
6+
import stripBom from 'strip-bom';
57

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

@@ -17,7 +19,7 @@ export default getConfigContent;
1719
function readConfigContent (configPath) {
1820
const parsedPath = path.parse(configPath)
1921
const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json';
20-
const jsonString = fs.readFileSync(configPath, 'utf-8');
22+
const jsonString = readConfigFileContent(configPath);
2123
const parse = isRcFile ?
2224
(contents) => JSON.parse(stripJSONComments(contents)) :
2325
(contents) => JSON.parse(contents);
@@ -61,3 +63,20 @@ function getConfigContent (configPath, baseDirectory) {
6163
const content = readConfigContent(resolvedPath);
6264
return getNormalizedConfig(configBasename, content);
6365
};
66+
67+
/**
68+
* Read proper content from config file.
69+
* If the chartset of the config file is not utf-8, one error will be thrown.
70+
* @param {String} configPath
71+
* @return {String}
72+
*/
73+
function readConfigFileContent (configPath) {
74+
75+
let rawBufContent = fs.readFileSync(configPath);
76+
77+
if (!isUTF8(rawBufContent)) {
78+
throw new Error(`The config file at "${configPath}" contains invalid charset, expect utf8`);
79+
}
80+
81+
return stripBom(rawBufContent.toString("utf8"));
82+
}

Diff for: test/fixtures/invalid-charset.json

98 Bytes
Binary file not shown.

Diff for: test/tests/configLoader.js

+2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ describe('configLoader', function () {
1313
.to.throw(/parsing json at/i);
1414
expect(() => getContent('invalid-json-rc', fixturesPath))
1515
.to.throw(/parsing json at/i);
16+
expect(() => getContent('invalid-charset.json', fixturesPath))
17+
.to.throw(/contains invalid charset/i);
1618
});
1719

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

0 commit comments

Comments
 (0)