t-comm
Version:
专业、稳定、纯粹的工具库
93 lines (86 loc) • 2.59 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var fs = require('fs');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
function getKeyValue(key, sourceLine) {
var result;
var ma;
var re = new RegExp("".concat(key, "\\s*=\\s*(.*?)(\\s|$)"));
for (var _i = 0, sourceLine_1 = sourceLine; _i < sourceLine_1.length; _i++) {
var line = sourceLine_1[_i];
if (line.startsWith('#')) {
// 忽略注释行
continue;
}
ma = line.match(re);
if (ma) {
result = ma[1] || '';
break;
}
}
return result;
}
function getEnvVariableMap(filepath) {
var sourceStr = '';
var re = new RegExp('(.*?)\\s*=\\s*(.*?)(\\s|$)');
if (fs__namespace.existsSync(filepath)) {
sourceStr = fs__namespace.readFileSync(filepath, 'utf-8');
} else {
sourceStr = filepath;
}
var sourceLine = sourceStr.split('\n');
var result = {};
for (var _i = 0, sourceLine_2 = sourceLine; _i < sourceLine_2.length; _i++) {
var line = sourceLine_2[_i];
if (line.startsWith('#')) {
// 忽略注释行
continue;
}
var match = line.match(re);
if (match === null || match === void 0 ? void 0 : match[1]) {
result[match[1]] = match[2] || '';
}
}
return result;
}
/**
* 读取文件中环境变量的值,支持:
* - NPM_TOKEN=xxx
* - NPM_TOKEN = xxx
* @param {string} key 环境变量的key
* @param {string} filepath 保存环境变量的文件路径
* @returns {string} 环境变量的值
*/
function readEnvVariable(key, filepath) {
if (!fs__namespace.existsSync(filepath)) {
console.log('[readEnvVariable] 文件不存在:', filepath, ',请先创建文件');
return '';
}
try {
var sourceStr = fs__namespace.readFileSync(filepath, 'utf-8');
var sourceLine = sourceStr.split('\n');
return getKeyValue(key, sourceLine);
} catch (e) {
console.log('[readEnvVariable] 打开文件失败:', filepath);
process.exit(1);
}
}
exports.getEnvVariableMap = getEnvVariableMap;
exports.readEnvVariable = readEnvVariable;