all files / src/configLoader/ getContent.js

100% Statements 5/5
87.5% Branches 7/8
100% Functions 2/2
100% Lines 5/5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                              17×                                               53×             53×              
import fs from 'fs';
import path from 'path';
import {sync as existsSync} from 'path-exists';
import stripJSONComments from 'strip-json-comments';
 
import {getNormalizedConfig} from '../configLoader';
 
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 = fs.readFileSync(configPath, 'utf-8');
    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}
 */
function getConfigContent(configPath, baseDirectory) {
    Iif (!configPath) {
      return;
    }
 
    const resolvedPath = path.resolve(baseDirectory, configPath);
    const configBasename = path.basename(resolvedPath);
 
    if (!existsSync(resolvedPath)) {
      return getNormalizedConfig(resolvedPath);
    }
 
    const content = readConfigContent(resolvedPath);
    return getNormalizedConfig(configBasename, content);
};