feat: read config, read history, hash files

most of the functionality exists now
This commit is contained in:
2019-04-04 15:28:24 -07:00
parent 655c27a89d
commit ca2fc85135
8 changed files with 194 additions and 10 deletions

64
src/utils.js Normal file
View File

@@ -0,0 +1,64 @@
const path = require('path');
const fs = require('fs');
const os = require('os');
const JoyCon = require('joycon');
exports.getRootPath = () => process.cwd();
exports.getHomeDir = () => os.homedir();
exports.getDataDir = () => path.join(exports.getHomeDir(), '.local/share');
exports.canAccessFile = (p, flag) => {
try {
fs.accessSync(p, flag || fs.constants.R_OK);
return true;
} catch (e) {
return false;
}
};
exports.getFileContents = (filePath, opts = {}) => {
if (!exports.canAccessFile(filePath)) throw new Error(`File not found: ${filePath}`);
const content = fs.readFileSync(filePath);
if (opts.format === 'json') return JSON.parse(content);
if (opts.format === 'text') return content.toString();
return content;
};
exports.getRootFileContents = (filename, opts = {}) => {
return exports.getFileContents(path.join(exports.getRootPath(), filename), opts);
};
exports.getIdent = () => {
const { name } = exports.getRootFileContents('package.json', { format: 'json' });
return name;
};
exports.getBranch = () => {
const headPath = path.join(exports.getRootPath(), '.git/HEAD');
if (!exports.canAccessFile(headPath)) throw new Error(`Git HEAD not found: ${headPath}`);
const head = fs.readFileSync(headPath);
const match = /ref: refs\/heads\/([^\n]+)/.exec(head);
if (!match) throw new Error(`Unable to read branch from ${headPath}`);
return match[1];
};
exports.getConfig = (overrides = {}) => {
const joycon = new JoyCon();
const defaults = {
checkFiles: ['package-lock.json', 'yarn.lock'],
rootDir: process.cwd(),
dataDir: exports.getDataDir(),
cmd: 'npm',
};
const result = joycon.loadSync({
packageKey: 'pkgcomp',
files: ['.config/pkgcomp.json', 'pkgcomp.json', 'package.json'],
});
return Object.assign(defaults, result.data, overrides);
};