@farmfe/cli
Version:
CLI of Farm
141 lines • 4.39 kB
JavaScript
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';
import { fileURLToPath } from 'node:url';
import { Logger } from '@farmfe/core';
import spawn from 'cross-spawn';
import walkdir from 'walkdir';
const logger = new Logger();
export const TEMPLATES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'templates');
export async function resolveCore() {
try {
return import('@farmfe/core');
}
catch (err) {
logger.error(`Cannot find @farmfe/core module, Did you successfully install: \n${err.stack},`);
process.exit(1);
}
}
export function copyFiles(source, dest, callback) {
walkdir(source, { sync: true }, (p, stat) => {
if (stat.isFile()) {
const content = readFileSync(p).toString();
const newContent = callback?.(content) ?? content;
const relativePath = path.relative(source, p);
const destPath = path.join(dest, relativePath);
if (!existsSync(path.dirname(destPath))) {
mkdirSync(path.dirname(destPath), { recursive: true });
}
writeFileSync(destPath, newContent);
}
});
if (!existsSync(path.join(dest, '.gitignore'))) {
writeFileSync(path.join(dest, '.gitignore'), `
node_modules
*.farm`);
}
}
export async function install(options) {
const cwd = options.cwd;
return new Promise((resolve, reject) => {
const command = options.package;
const args = ['install'];
const child = spawn(command, args, {
cwd,
stdio: 'inherit'
});
child.once('close', (code) => {
if (code !== 0) {
reject({
command: `${command} ${args.join(' ')}`
});
return;
}
resolve();
});
child.once('error', reject);
});
}
/**
* 用于规范化目标路径
* @param {string |undefined} targetDir
* @returns
*/
export function formatTargetDir(targetDir) {
return targetDir?.trim()?.replace(/\/+$/g, '');
}
/**
* filter duplicate item in options
*/
export function filterDuplicateOptions(options) {
for (const [key, value] of Object.entries(options)) {
if (Array.isArray(value)) {
options[key] = value[value.length - 1];
}
}
}
/**
* clear command screen
*/
export function clearScreen() {
const repeatCount = process.stdout.rows - 2;
const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : '';
console.log(blank);
readline.cursorTo(process.stdout, 0, 0);
readline.clearScreenDown(process.stdout);
}
export function cleanOptions(options) {
const resolveOptions = { ...options };
delete resolveOptions['--'];
delete resolveOptions.m;
delete resolveOptions.c;
delete resolveOptions.w;
delete resolveOptions.l;
delete resolveOptions.lazy;
delete resolveOptions.mode;
delete resolveOptions.base;
delete resolveOptions.config;
delete resolveOptions.clearScreen;
return resolveOptions;
}
export function resolveCommandOptions(options) {
const resolveOptions = { ...options };
filterDuplicateOptions(resolveOptions);
return cleanOptions(resolveOptions);
}
export function getConfigPath(root, configPath) {
return path.resolve(root, configPath ?? '');
}
export async function handleAsyncOperationErrors(asyncOperation, errorMessage) {
try {
await asyncOperation;
}
catch (error) {
logger.error(`${errorMessage}:\n${error.stack}`);
process.exit(1);
}
}
// prevent node experimental warning
export function preventExperimentalWarning() {
const defaultEmit = process.emit;
process.emit = function (...args) {
if (args[1].name === 'ExperimentalWarning') {
return undefined;
}
return defaultEmit.call(this, ...args);
};
}
export function resolveRootPath(rootPath = '') {
return rootPath && path.isAbsolute(rootPath)
? rootPath
: path.resolve(process.cwd(), rootPath);
}
export function resolveCliConfig(root, options) {
root = resolveRootPath(root);
const configPath = getConfigPath(root, options.config);
return {
root,
configPath
};
}
//# sourceMappingURL=utils.js.map