From adc6788359fa0d1b1b15e77002201e1837416f27 Mon Sep 17 00:00:00 2001 From: "guo.xu" Date: Wed, 24 Feb 2021 11:09:34 +0800 Subject: [PATCH] =?UTF-8?q?feat(cmd):=20=E6=96=B0=E5=A2=9Eclean=E6=8C=87?= =?UTF-8?q?=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/preset-built-in/src/index.ts | 4 +- .../src/plugin/command/clean.ts | 63 +++++++++++++++++++ 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 packages/preset-built-in/src/plugin/command/clean.ts diff --git a/packages/preset-built-in/src/index.ts b/packages/preset-built-in/src/index.ts index 0398a5d..e4ae973 100644 --- a/packages/preset-built-in/src/index.ts +++ b/packages/preset-built-in/src/index.ts @@ -4,7 +4,9 @@ import commandHelp from '@xus/plugin-command-help' import commitlint from '@xus/plugin-command-commit-lint' import buildLib from '@xus/plugin-build-lib' import bundlerRollup from '@xus/plugin-bundler-rollup' +// cmd +import cmdClean from './plugin/command/clean' export default createPreset({ - plugins: [commandHelp, commitlint, buildLib, bundlerRollup] + plugins: [commandHelp, commitlint, buildLib, bundlerRollup, cmdClean] }) diff --git a/packages/preset-built-in/src/plugin/command/clean.ts b/packages/preset-built-in/src/plugin/command/clean.ts new file mode 100644 index 0000000..af17fdf --- /dev/null +++ b/packages/preset-built-in/src/plugin/command/clean.ts @@ -0,0 +1,63 @@ +import { createPlugin, HookTypes, rimraf } from '@xus/cli' +import { existsSync } from 'fs' +import { join, relative } from 'path' + +export default createPlugin({ + name: 'cmd:clean', + apply(api) { + api.registerCommand( + 'clean', + { + desc: 'a command for clean dir', + options: { + '--dirOrFile': 'point need to clean dir or file name', + '--skip': + 'use RegExp to skip some packages/** dir name in lerna project', + '--point': 'use RegExp to point packages/** dir name in lerna project' + } + }, + async (args) => { + if (args.dirOrFile) { + const skipRE = args?.skip ? new RegExp(args.skip) : false + const pointRE = args?.point ? new RegExp(args.point) : false + + ;(args.dirOrFile as string) + .split(',') + .map((dir) => [ + api.getPathBasedOnCtx(dir), + ...api + .getLernaPkgs() + .filter((pkg) => { + const relativePkg = relative(api.cwd, pkg) + if (skipRE && skipRE.test(relativePkg)) return false + if (pointRE && !pointRE.test(relativePkg)) return false + return true + }) + .map((pkg) => join(pkg, dir)) + ]) + .flat() + .filter((dirPath) => existsSync(dirPath)) + .forEach((dir) => { + api.registerHook({ + name: `remove.dir`, + pluginName: 'cmd:clean', + fn: () => { + rimraf.sync(dir) + } + }) + }) + + try { + await api.applyHook({ + name: 'remove.dir', + type: HookTypes.parallel + }) + api.logger.success(`clean dir or file succeed`) + } catch (e) { + api.logger.error(`clean dir or file failed, ${e.massage}`) + } + } + } + ) + } +})