Files
pkgcomp/src/data.js
joe fleming 5d05775560 feat: run command on changes
based on dependencies, devDependencies, and hashes of other included files
2019-04-04 15:51:48 -07:00

40 lines
1.0 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const CONFIG_FILENAME = 'pkgcomp.json';
exports.read = (fileRoot, ident) => {
const stats = fs.statSync(fileRoot);
const filePath = path.join(fileRoot, CONFIG_FILENAME);
// throw if pointing to a file
if (stats.isFile()) throw new Error(`getData expects a directory, got a file; ${fileRoot}`);
// create file if it's missing
if (!stats.isDirectory()) {
mkdirp.sync(fileRoot);
}
try {
const data = JSON.parse(fs.readFileSync(filePath));
return data[ident] || {};
} catch (err) {
if (err.code === 'ENOENT') {
fs.writeFileSync(filePath, JSON.stringify({}));
return {};
}
throw err;
}
};
exports.write = (fileRoot, ident, payload) => {
const filePath = path.join(fileRoot, CONFIG_FILENAME);
const existingCache = JSON.parse(fs.readFileSync(filePath));
// update the cache
existingCache[ident] = payload;
fs.writeFileSync(filePath, JSON.stringify(existingCache));
};