79 lines
2.1 KiB
JavaScript
79 lines
2.1 KiB
JavaScript
const path = require('path');
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const JoyCon = require('joycon');
|
|
const globParent = require('glob-parent');
|
|
|
|
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.getPackageInfo = () => {
|
|
const { name, workspaces } = exports.getFileContents(
|
|
path.join(exports.getRootPath(), 'package.json'),
|
|
{
|
|
format: 'json',
|
|
}
|
|
);
|
|
if (!name) throw new Error('Unable to read project name from package.json');
|
|
return { name, workspaces };
|
|
};
|
|
|
|
exports.getPackageWorkspaces = () => {
|
|
const { workspaces } = exports.getPackageInfo();
|
|
if (!workspaces) return [];
|
|
|
|
return workspaces.reduce((acc, glob) => {
|
|
const parent = globParent(glob);
|
|
const packages = fs
|
|
.readdirSync(parent)
|
|
.map(package => {
|
|
const packageJson = path.join(parent, package, 'package.json');
|
|
if (!exports.canAccessFile(packageJson)) return false;
|
|
return {
|
|
name: package,
|
|
package: packageJson,
|
|
};
|
|
})
|
|
.filter(Boolean);
|
|
return acc.concat(packages);
|
|
}, []);
|
|
};
|
|
|
|
exports.getConfig = (overrides = {}) => {
|
|
const joycon = new JoyCon();
|
|
const defaults = {
|
|
checkFiles: ['package-lock.json', 'yarn.lock'],
|
|
rootDir: process.cwd(),
|
|
dataDir: exports.getDataDir(),
|
|
cmd: false,
|
|
};
|
|
|
|
const result = joycon.loadSync({
|
|
packageKey: 'pkgcomp',
|
|
files: ['.config/pkgcomp.json', '.pkgcomp.json', 'pkgcomp.json', 'package.json'],
|
|
});
|
|
|
|
return Object.assign(defaults, result.data, overrides);
|
|
};
|