Skip to content

Commit

Permalink
feat(configLoader): added fully compatible cosmiconfig support
Browse files Browse the repository at this point in the history
Added fully compatible cosmiconfig support with BOM and encoding checks. Added json5 config format parser. Added tests. Some minor code style changes;

Closes: commitizen#773
  • Loading branch information
andrei committed Oct 31, 2023
1 parent 2e57fd0 commit 636874f
Show file tree
Hide file tree
Showing 12 changed files with 940 additions and 226 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ artifacts/
npm-debug.log
.nyc_output
test/tools/trigger-appveyor-tests.sh
logo/*.png
logo/*.png
.idea
257 changes: 146 additions & 111 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
},
"dependencies": {
"cachedir": "2.3.0",
"cosmiconfig": "8.3.6",
"cz-conventional-changelog": "3.3.0",
"dedent": "0.7.0",
"detect-indent": "6.1.0",
Expand All @@ -83,6 +84,7 @@
"glob": "7.2.3",
"inquirer": "8.2.5",
"is-utf8": "^0.2.1",
"json5": "2.2.3",
"lodash": "4.17.21",
"minimist": "1.2.7",
"strip-bom": "4.0.0",
Expand Down
11 changes: 7 additions & 4 deletions src/commitizen/configLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import { loader } from '../configLoader';

export { load };

// Configuration sources in priority order.
var configs = ['.czrc', '.cz.json', 'package.json'];

/**
* Get content of the configuration file
* @param {string} [config] - partial path to configuration file
* @param {string} [cwd] - directory path which will be joined with config argument
* @return {Object|undefined}
*/
function load (config, cwd) {
return loader(configs, config, cwd);
return loader(config, cwd);
}
81 changes: 81 additions & 0 deletions src/configLoader/cosmiconfigLoader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { cosmiconfigSync, defaultLoadersSync } from 'cosmiconfig';
import JSON5 from 'json5';
import stripBom from 'strip-bom';
import isUTF8 from "is-utf8";

const moduleName = 'cz';
const fullModuleName = 'commitizen';

const searchPlaces = [
`.${moduleName}rc`, // .czrc
`.${moduleName}rc.json`,
`.${moduleName}rc.json5`,
`.${moduleName}rc.yaml`,
`.${moduleName}rc.yml`,
`.${moduleName}rc.js`,
`.${moduleName}rc.cjs`,
`.${moduleName}rc.ts`,
`.config/${moduleName}rc`,
`.config/${moduleName}rc.json`,
`.config/${moduleName}rc.json5`,
`.config/${moduleName}rc.yaml`,
`.config/${moduleName}rc.yml`,
`.config/${moduleName}rc.js`,
`.config/${moduleName}rc.ts`,
`.config/${moduleName}rc.cjs`,
`${moduleName}.config.js`,
`${moduleName}.config.ts`,
`${moduleName}.config.cjs`,
`.${moduleName}.json`, // .cz.json
`.${moduleName}.json5`,
'package.json',
];

function withSafeContentLoader(loader) {
return function (filePath, content) {
if (!isUTF8(Buffer.from(content, 'utf8'))) {
throw new Error(`The config file at "${filePath}" contains invalid charset, expect utf8`);
}
return loader(filePath, stripBom(content));
}
}

function json5Loader(filePath, content) {
try {
return JSON5.parse(content) || null;
} catch (err) {
err.message = `Error parsing json at ${filePath}:\n${err.message}`;
throw err;
}
}

// no '.ts': withSafeContentLoader(defaultLoadersSync['.ts']),
const loaders = {
'.cjs': withSafeContentLoader(defaultLoadersSync['.js']),
'.js': withSafeContentLoader(defaultLoadersSync['.js']),
'.yml': withSafeContentLoader(defaultLoadersSync['.yaml']),
'.json': withSafeContentLoader(json5Loader),
'.json5': withSafeContentLoader(json5Loader),
'.yaml': withSafeContentLoader(defaultLoadersSync['.yaml']),
'.ts': withSafeContentLoader(defaultLoadersSync['.ts']),
noExt: withSafeContentLoader(json5Loader)
}

const defaultConfigExplorer = cosmiconfigSync(moduleName, {
packageProp: ['configs', fullModuleName],
searchPlaces: searchPlaces,
loaders: loaders,
cache: false,
});

/**
* @deprecated
*/
const deprecatedConfigExplorerFallback = cosmiconfigSync(moduleName, {
packageProp: ['czConfig'],
searchPlaces: ['package.json'],
loaders: loaders,
cache: false,
});

export { searchPlaces, moduleName, defaultConfigExplorer, deprecatedConfigExplorerFallback };
50 changes: 50 additions & 0 deletions src/configLoader/findContent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { defaultConfigExplorer, deprecatedConfigExplorerFallback } from "./cosmiconfigLoader";
import { isInTest } from "../common/util";

export default findConfigContent;
/**
* Find content of the configuration file
* @param {String} cwd - partial path to configuration file
* @return {Object|undefined}
*/
function findConfigContent(cwd) {
const maybeConfig = defaultConfigExplorer.search(cwd);
if (maybeConfig) {
return maybeConfig.config
} else {
const deprecatedConfig = findOldCzConfig(cwd);
if (deprecatedConfig) {
return deprecatedConfig
}
}

return undefined;
}

/**
* find old czConfig
*
* @deprecated
* @param {string} [searchFrom]
* @return {Object|undefined}
*/
function findOldCzConfig(searchFrom) {
const maybeDeprecatedConfig = deprecatedConfigExplorerFallback.search(searchFrom);
if (maybeDeprecatedConfig) {
showOldCzConfigDeprecationWarning();
return maybeDeprecatedConfig.config;
}

return undefined;
}

/**
* @deprecated
* @return void
*/
function showOldCzConfigDeprecationWarning() {
// Suppress during test
if (!isInTest()) {
console.error("\n********\nWARNING: This repository's package.json is using czConfig. czConfig will be deprecated in Commitizen 3. \nPlease use this instead:\n{\n \"config\": {\n \"commitizen\": {\n \"path\": \"./path/to/adapter\"\n }\n }\n}\nFor more information, see: http://commitizen.github.io/cz-cli/\n********\n");
}
}
12 changes: 10 additions & 2 deletions src/configLoader/findup.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@ import glob from 'glob';

export default findup;

// Before, "findup-sync" package was used,
// but it does not provide filter callback
/**
* Before, "findup-sync" package was used,
* but it does not provide filter callback
*
* @param {string[]} patterns
* @param {Object} options
* @param {string} options.cwd
* @param {(baseName: string) => boolean} fn
* @return {string}
*/
function findup (patterns, options, fn) {
/* jshint -W083 */

Expand Down
102 changes: 40 additions & 62 deletions src/configLoader/getContent.js
Original file line number Diff line number Diff line change
@@ -1,82 +1,60 @@
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';
import { defaultConfigExplorer, deprecatedConfigExplorerFallback } from "./cosmiconfigLoader";
import { isInTest } from "../common/util";

export default getConfigContent;

/**
* Read the content of a configuration file
* - if not js or json: strip any comments
* - if js or json: require it
* @param {String} configPath - full path to configuration file
* @return {Object}
*/
function readConfigContent (configPath) {
const parsedPath = path.parse(configPath)
const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json';
const jsonString = readConfigFileContent(configPath);
const parse = isRcFile ?
(contents) => JSON.parse(stripJSONComments(contents)) :
(contents) => JSON.parse(contents);

try {
const parsed = parse(jsonString);

Object.defineProperty(parsed, 'configPath', {
value: configPath
});

return parsed;
} catch (error) {
error.message = [
`Parsing JSON at ${configPath} for commitizen config failed:`,
error.mesasge
].join('\n');

throw error;
}
}

/**
* Get content of the configuration file
* @param {String} configPath - partial path to configuration file
* @param {String} directory - directory path which will be joined with config argument
* @return {Object}
* @param {String} [configPath] - partial path to configuration file
* @param {String} [baseDirectory] - directory path which will be joined with config argument
* @return {Object|undefined}
*/
function getConfigContent (configPath, baseDirectory) {
if (!configPath) {
return;
}
if (!configPath) {
return;
}

const resolvedPath = path.resolve(baseDirectory, configPath);
const configBasename = path.basename(resolvedPath);
const resolvedPath = path.resolve(baseDirectory, configPath);

if (!fs.existsSync(resolvedPath)) {
return getNormalizedConfig(resolvedPath);
const maybeConfig = defaultConfigExplorer.load(resolvedPath);
if (maybeConfig) {
return maybeConfig.config
} else {
const deprecatedConfig = loadOldCzConfig(resolvedPath);
if (deprecatedConfig) {
return deprecatedConfig
}
}

const content = readConfigContent(resolvedPath);
return getNormalizedConfig(configBasename, content);
};
return undefined;
}

/**
* 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}
* load old czConfig from known place
*
* @deprecated
* @param {string} [fullPath]
* @return {Object|undefined}
*/
function readConfigFileContent (configPath) {
function loadOldCzConfig(fullPath) {
const maybeDeprecatedConfig = deprecatedConfigExplorerFallback.load(fullPath);
if (maybeDeprecatedConfig) {
showOldCzConfigDeprecationWarning();
return maybeDeprecatedConfig.config;
}

let rawBufContent = fs.readFileSync(configPath);
return undefined;
}

if (!isUTF8(rawBufContent)) {
throw new Error(`The config file at "${configPath}" contains invalid charset, expect utf8`);
/**
* @deprecated
* @return void
*/
function showOldCzConfigDeprecationWarning() {
// Suppress during test
if (!isInTest()) {
console.error("\n********\nWARNING: This repository's package.json is using czConfig. czConfig will be deprecated in Commitizen 3. \nPlease use this instead:\n{\n \"config\": {\n \"commitizen\": {\n \"path\": \"./path/to/adapter\"\n }\n }\n}\nFor more information, see: http://commitizen.github.io/cz-cli/\n********\n");
}

return stripBom(rawBufContent.toString("utf8"));
}
11 changes: 7 additions & 4 deletions src/configLoader/getNormalizedConfig.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
export default getNormalizedConfig;

// Given a config and content, plucks the actual
// settings that we're interested in
function getNormalizedConfig (config, content) {
/**
* @deprecated no need this function with cosmiconfig.
*
* Given a config and content, plucks the actual settings that we're interested in
*/
function getNormalizedConfig (baseName, content) {

if (content && (config === 'package.json')) {
if (content && (baseName === 'package.json')) {

// PACKAGE.JSON

Expand Down
Loading

0 comments on commit 636874f

Please sign in to comment.