NodeJs 获取 Git 用户和邮箱信息

获取 git config 的路径,一种是项目单独配置的,一种是全局配置的

'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

module.exports = function (type) {
    let configPath = '';
    const workDir = process.cwd();

    if (type === 'global') {
        configPath = path.join(os.homedir(), '.gitconfig');
    } else {
        configPath = path.resolve(workDir, '.git/config');
    }

    if (!fs.existsSync(configPath)) {
        configPath = path.join(os.homedir(), '.config/git/config');
    }

    return fs.existsSync(configPath) ? configPath : null;
}

读取配置文件,使用 ini 库解析成对象模式

'use strict'

const fs = require('fs');
const filePath = require('./path');
const ini = require('ini');

module.exports = function (type) {
    const path = filePath(type)
    if (path) {
        const file = fs.readFileSync(path, 'utf8');
        return ini.parse(file);
    }
    return '';
};