Skip to content

Commit

Permalink
chore: short option format & format debug info (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
shulandmimi committed May 22, 2024
1 parent 5d9d307 commit 65d0577
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 46 deletions.
6 changes: 6 additions & 0 deletions .changeset/modern-cameras-drive.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'farmup': patch
---

1. short option format
2. format debug info
28 changes: 7 additions & 21 deletions src/executer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { type ExecaChildProcess, execaCommand } from 'execa';
import { ExecuteMode, type ExecuteOption, type ResolvedCommonOptions } from './types/options';
import type { Logger } from '@farmfe/core';
import { delay } from './util/async';
import { trimEndLF } from './util/log';

export class Executer {
child?: ExecaChildProcess;
Expand Down Expand Up @@ -39,33 +40,18 @@ export class Executer {
stdio: 'pipe',
});

child.stdout?.on('data', (data) => {
logger.debug(data.toString());
});
child.stdout?.on('data', (data) => logger.debug(trimEndLF(data.toString())));

child.stderr?.on('data', (err) => {
logger.error(err);
});
child.stderr?.on('data', (err) => logger.error(err));

this.child = child;

process.on('beforeExit', () => {
this.closeChild();
});
process.on('exit', () => {
this.closeChild();
});
process.on('beforeExit', this.closeChild);
process.on('exit', this.closeChild);

child.on('exit', (code) => {
if (child) {
const message = `"${name}" PID ${child.pid}`;
if (code === 0) {
this.logger.info(`${message} done`);
} else {
this.logger.info(`${message} killed`);
}
this.child = undefined;
}
this.logger.info(`"${name}" PID ${child.pid} ${code === 0 ? 'done' : `exit ${code}`}`);
this.child = undefined;
});
}

Expand Down
19 changes: 8 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import autoExecute, { NormalizeOption } from './plugins/auto-execute';
import { ExecuteMode, type CommonOptions } from './types/options';
import autoExternal from './plugins/auto-external';
import path from 'node:path';
import { isString } from 'lodash-es';
import { isBoolean, isString } from 'lodash-es';

const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url)).toString());

Expand Down Expand Up @@ -77,19 +77,17 @@ const cli = cac('farmup');

cli.option(
'--target [target]',
"target for output, default is node, support 'browser' | 'node' | 'node16' | 'node-legacy' | 'node-next' | 'browser-legacy' | 'browser-es2015' | 'browser-es2017' | 'browser-esnext'",
"target for output, default is node, support 'browser''node''node16''node-legacy''node-next''browser-legacy''browser-es2015''browser-es2017''browser-esnext'",
)
.option('--mode [mode]', 'mode for build, default is development, choose one from "development" or "production"')
.option('--minify', 'minify for output')
.option('--config [config]', 'config path, if not path, it will be auto find')
.option('--no-config', 'if farm.config.[ext] exists, it will be ignore')
.option('--format [format]', 'choose one from "cjs" or "esm"')
.option('--external [...external]', 'external')
.option('--watch [...files]', 'watch files', { default: false })
.option('-w [...file]', 'watch files', { default: false })
.option('-w, --watch [...files]', 'watch files', { default: false })
.option('--no-auto-external', 'if not found module, auto as external', { default: true })
.option('--exec [file]', 'custom execute command')
.option('-e [file]', 'custom execute command');
.option('-e, --exec [file]', 'custom execute command');

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
async function commonOptionsFromArgs(args: Record<string, any>): Promise<Partial<CommonOptions>> {
Expand All @@ -102,22 +100,21 @@ async function commonOptionsFromArgs(args: Record<string, any>): Promise<Partial
: args.config
? await getConfigFilePath(root)
: undefined;
const execute =
isString(args.exec) || isString(args.e) ? args.exec || args.e : args.exec === true ? undefined : undefined;
const execute = isString(args.exec) && !isBoolean(args.exec) ? args.exec : undefined;

return {
root,
target: args.target,
args: args['--'],
mode: args.mode,
autoExternal: args.autoExternal,
execute: execute,
execute,
format: args.format,
config: configPath,
minify: args.minify,
noWatch: args.watch === false && args.w === false,
noWatch: args.watch === false,
noExecute: args.exec === false,
watchFiles: [args.watch, args.w]
watchFiles: [args.watch]
.flat()
.map((item) => (item === true ? undefined : item))
.filter(Boolean),
Expand Down
32 changes: 19 additions & 13 deletions src/plugins/auto-execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Logger, type Resource, type JsPlugin } from '@farmfe/core';
import path from 'node:path';
import { type CommonOptions, ExecuteMode, type ResolvedCommonOptions } from '../types/options';
import { NormalizeOption } from '../config/normalize';
import { CLI_NAME, logger } from '../config/constant';
import { CLI_NAME, logger as defaultLogger } from '../config/constant';
import { Executer } from '../executer';

export { NormalizeOption, Executer };
Expand All @@ -24,21 +24,25 @@ function findOutputEntry(resource: Resource[], options: ResolvedCommonOptions) {
}
}

export default function autoExecute(options: CommonOptions = {}): JsPlugin {
export default function autoExecute(options: CommonOptions = {}, logger = defaultLogger): JsPlugin {
let outputDir: string | undefined = undefined;
let executer: Executer | null = null;

const normalize_option = new NormalizeOption(options, logger);
const normalizeOption = new NormalizeOption(options, logger);

return {
name: `${CLI_NAME}:execute`,
priority: Number.NEGATIVE_INFINITY,
async config(config) {
const normalizedOption = await normalize_option.config(config);
return normalizedOption;
return await normalizeOption.config(config);
},

configResolved(config) {
outputDir = config.compilation?.output?.path;
const format = config.compilation?.output?.format || normalizeOption.options.format;
const targetEnv = config.compilation?.output?.targetEnv || normalizeOption.options.target;
const entry = Object.values(config.compilation?.input || normalizeOption.options.entry)[0];
logger.debug(`[entry: ${entry}] [format: ${format}] [target: ${targetEnv}]`);
},

configureCompiler(compiler) {
Expand All @@ -57,13 +61,13 @@ export default function autoExecute(options: CommonOptions = {}): JsPlugin {
}

for (const entry of entries) {
compiler.addExtraWatchFile(entry, normalize_option.options.watchFiles);
compiler.addExtraWatchFile(entry, normalizeOption.options.watchFiles);
}
},

writeResources: {
async executor(param) {
if (normalize_option.options.noExecute) {
if (normalizeOption.options.noExecute) {
return;
}

Expand All @@ -72,25 +76,27 @@ export default function autoExecute(options: CommonOptions = {}): JsPlugin {
return;
}

const resourceEntry = findOutputEntry(Object.values(param.resourcesMap), normalize_option.options);
const resourceEntry = findOutputEntry(Object.values(param.resourcesMap), normalizeOption.options);

if (!resourceEntry) {
logger.error('not found output entry');
return;
}

// TODO: multiple entry
const execute_path = path.join(outputDir, resourceEntry!.name);
const executePath = path.join(outputDir, resourceEntry!.name);

if (!executer) {
executer = new Executer(normalize_option.options.execute, logger, normalize_option.options);
executer = new Executer(normalizeOption.options.execute, logger, normalizeOption.options);
}

const nameWithoutExt = path.parse(resourceEntry.name).name;

executer.execute(
execute_path,
resourceEntry.name,
executePath,
nameWithoutExt,
new Logger({
name: `${CLI_NAME}:${resourceEntry.name}`,
name: `${CLI_NAME}:${nameWithoutExt}`,
}),
);
},
Expand Down
2 changes: 1 addition & 1 deletion src/util/file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { stat } from "fs-extra";
import { stat } from 'fs-extra';

export const isExists = async (filename: string) => {
try {
Expand Down
7 changes: 7 additions & 0 deletions src/util/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const trimEndLF = (str: string) => {
if (str.endsWith('\n')) {
return str.slice(0, -1);
}

return str;
};

0 comments on commit 65d0577

Please sign in to comment.