From b4b2b810a246af8bebcd8384fdf251fa9c18adfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=89=E5=92=B2=E6=99=BA=E5=AD=90?= Date: Sun, 9 Oct 2022 01:13:35 +0800 Subject: [PATCH] refactor: re-organize --- bin/create.js | 2 +- package.json | 2 +- src/cli.ts | 13 +++++ src/config.ts | 13 ++--- src/features/command.ts | 19 +++++++ src/features/git.ts | 23 ++++++++ src/features/replace.ts | 71 +++++++++++++++++++++++ src/index.ts | 123 ++++++---------------------------------- src/types.ts | 1 + src/utils.ts | 11 ++-- 10 files changed, 158 insertions(+), 120 deletions(-) create mode 100644 src/cli.ts create mode 100644 src/features/command.ts create mode 100644 src/features/git.ts create mode 100644 src/features/replace.ts diff --git a/bin/create.js b/bin/create.js index 33a61be..b91240a 100755 --- a/bin/create.js +++ b/bin/create.js @@ -1,2 +1,2 @@ #!/usr/bin/env node -import '../dist/index.js' +import '../dist/cli.js' diff --git a/package.json b/package.json index 094b348..db605ab 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ "lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx,.json,.md", "lint:fix": "pnpm run lint --fix", "build": "tsup", - "dev": "tsx ./src/index.ts", + "dev": "tsx ./src/cli.ts", "release": "bumpp && pnpm publish", "prepublishOnly": "pnpm run build" }, diff --git a/src/cli.ts b/src/cli.ts new file mode 100644 index 0000000..f21193f --- /dev/null +++ b/src/cli.ts @@ -0,0 +1,13 @@ +import { program } from 'commander' +import consola from 'consola' +import { config, run } from '.' + +program + .argument('[projectPath]', 'project path') + .action((projectPath?: string) => { + run(projectPath).catch((err) => err && consola.error(err)) + }) +program + .command('config') + .action(() => config().catch((err) => consola.error(err))) +program.parse() diff --git a/src/config.ts b/src/config.ts index 8d9cbfb..d534ea0 100644 --- a/src/config.ts +++ b/src/config.ts @@ -174,10 +174,6 @@ export function normalizeConfig(config: Config): ConfigNormalized { } function normalizeTemplate(template: ConfigTemplate): TemplateNormalized { - const replaces = [ - ...normalizeReplaces(config.replaces), - ...normalizeReplaces(template.replaces), - ] return { ...template, git: { @@ -185,13 +181,14 @@ export function normalizeConfig(config: Config): ConfigNormalized { add: template.git?.add ?? config.git?.add ?? false, }, children: template.children?.map((t) => normalizeTemplate(t)), - replaces, + replaces: [ + ...normalizeReplaces(config.replaces), + ...normalizeReplaces(template.replaces), + ], } } - const templates = toArray(config.templates).map((t) => normalizeTemplate(t)) - return { - templates, + templates: toArray(config.templates).map((t) => normalizeTemplate(t)), } } diff --git a/src/features/command.ts b/src/features/command.ts new file mode 100644 index 0000000..dd51af3 --- /dev/null +++ b/src/features/command.ts @@ -0,0 +1,19 @@ +import { toArray } from '@antfu/utils' +import consola from 'consola' +import { execaCommand } from 'execa' +import type { TemplateNormalized } from '../config' +import type { ProjectInfo } from '../types' + +export async function command( + template: TemplateNormalized, + project: ProjectInfo +) { + for (const command of toArray(template.commands)) { + consola.info(`Running command: ${command}`) + await execaCommand(command, { + stdio: 'inherit', + cwd: project.path, + shell: true, + }) + } +} diff --git a/src/features/git.ts b/src/features/git.ts new file mode 100644 index 0000000..99bd41f --- /dev/null +++ b/src/features/git.ts @@ -0,0 +1,23 @@ +import consola from 'consola' +import { execa } from 'execa' +import type { TemplateNormalized } from '../config' +import type { ProjectInfo } from '../types' + +export async function git(template: TemplateNormalized, project: ProjectInfo) { + if (template.git.init) { + await execa('git', ['init', project.path], { + stdout: 'ignore', + stderr: 'inherit', + }) + consola.success('Git initialized.') + } + + if (template.git.init && template.git.add) { + await execa('git', ['add', '.'], { + stdout: 'ignore', + stderr: 'inherit', + cwd: project.path, + }) + consola.success('All file contents are added to the index.') + } +} diff --git a/src/features/replace.ts b/src/features/replace.ts new file mode 100644 index 0000000..7fb02cb --- /dev/null +++ b/src/features/replace.ts @@ -0,0 +1,71 @@ +import path from 'node:path' +import escapeStringRegexp from 'escape-string-regexp' +import { toArray } from '@antfu/utils' +import chalk from 'chalk' +import consola from 'consola' +import replaceInFile from 'replace-in-file' +import type { ReplaceInFileConfig } from 'replace-in-file' +import type { TemplateNormalized } from '../config' +import type { + ConfigReplace, + ConfigReplaceFromCallback, + ConfigReplaceToCallback, + ProjectInfo, +} from '../types' + +export async function replace( + template: TemplateNormalized, + project: ProjectInfo +) { + for (const replace of template.replaces) { + await doReplace(replace, project).catch((err) => { + console.error(err) + }) + } +} + +async function doReplace(replace: ConfigReplace, project: ProjectInfo) { + const { all = true, ignoreCase = false } = replace + + const buildPattern = (from: string | RegExp) => { + if (typeof from !== 'string') return from + if (!(all || ignoreCase)) return from + + let flags = '' + if (ignoreCase) flags += 'i' + if (all) flags += 'g' + return new RegExp(escapeStringRegexp(from), flags) + } + + const from = ( + typeof replace.from === 'function' + ? (file) => (replace.from as ConfigReplaceFromCallback)({ file, project }) + : toArray(replace.from).map((from) => buildPattern(from)) + ) as ReplaceInFileConfig['from'] + + const to: ReplaceInFileConfig['to'] = + typeof replace.to === 'function' + ? (match, file) => + (replace.to as ConfigReplaceToCallback)({ match, file, project }) + : replace.to + + const results = await replaceInFile.replaceInFile({ + files: replace.include ?? '**/*', + ignore: replace.exclude, + from, + to, + countMatches: true, + glob: { + cwd: project.path, + absolute: true, + }, + }) + for (const result of results) { + if (!result.hasChanged) continue + consola.info( + `${chalk.blue.bold( + path.relative(project.path, result.file) + )} was replaced in ${chalk.green(result.numReplacements)} place(s).` + ) + } +} diff --git a/src/index.ts b/src/index.ts index 8e89517..3eb88d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,43 +1,32 @@ import path from 'node:path' -import escapeStringRegexp from 'escape-string-regexp' import enquirer from 'enquirer' import degit from 'degit' import consola from 'consola' import chalk from 'chalk' -import { program } from 'commander' -import { execa, execaCommand } from 'execa' -import replaceInFile from 'replace-in-file' -import { toArray } from '@antfu/utils' import { getColor } from './utils' import { editConfig, getConfig } from './config' -import type { ReplaceInFileConfig } from 'replace-in-file' -import type { - ConfigReplace, - ConfigReplaceFromCallback, - ConfigReplaceToCallback, - ProjectInfo, -} from './types' -import type { TemplateNormalized } from './config' +import { git } from './features/git' +import { replace } from './features/replace' +import { command } from './features/command' -program - .argument('[projectPath]', 'project path') - .action((projectPath?: string) => { - run(projectPath).catch((err) => err && consola.error(err)) - }) -program - .command('config') - .action(() => config().catch((err) => consola.error(err))) -program.parse() +import type { ProjectInfo } from './types' +import type { TemplateNormalized } from './config' -async function config() { +export async function config() { const { init, file } = await getConfig() if (!init) editConfig(file) } -async function run(projectPath?: string) { +export async function run(projectPath?: string) { const { config: { templates }, } = await getConfig() + const template = await chooseTemplate(templates) + + await create({ projectPath, template }) +} + +async function chooseTemplate(templates: TemplateNormalized[]) { let currentTemplates = templates const templateStacks = [] do { @@ -65,11 +54,7 @@ async function run(projectPath?: string) { } const template = currentTemplates.find(({ name }) => name === templateName)! if (template.url) { - await create({ - projectPath, - template, - }) - break + return template } else if (template.children) { templateStacks.push(currentTemplates) currentTemplates = template.children @@ -107,37 +92,9 @@ async function create({ const emitter = degit(url) await emitter.clone(projectPath) - if (template.git.init) { - await execa('git', ['init', projectPath], { - stdout: 'ignore', - stderr: 'inherit', - }) - consola.success('Git initialized.') - } - - if (template.git.init && template.git.add) { - await execa('git', ['add', '.'], { - stdout: 'ignore', - stderr: 'inherit', - cwd: projectPath, - }) - consola.success('All file contents are added to the index.') - } - - for (const replace of template.replaces) { - await replaceContents(replace, project).catch((err) => { - console.error(err) - }) - } - - for (const command of toArray(template.commands)) { - consola.info(`Running command: ${command}`) - await execaCommand(command, { - stdio: 'inherit', - cwd: projectPath, - shell: true, - }) - } + git(template, project) + replace(template, project) + command(template, project) consola.success( `${chalk.green.bold(`Done. Now run:`)}\n\n ${chalk.blueBright( @@ -145,49 +102,3 @@ async function create({ )}\n` ) } - -async function replaceContents(replace: ConfigReplace, project: ProjectInfo) { - const { all = true, ignoreCase = false } = replace - - const buildPattern = (from: string | RegExp) => { - if (typeof from !== 'string') return from - if (!(all || ignoreCase)) return from - - let flags = '' - if (ignoreCase) flags += 'i' - if (all) flags += 'g' - return new RegExp(escapeStringRegexp(from), flags) - } - - const from = ( - typeof replace.from === 'function' - ? (file) => (replace.from as ConfigReplaceFromCallback)({ file, project }) - : toArray(replace.from).map((from) => buildPattern(from)) - ) as ReplaceInFileConfig['from'] - - const to: ReplaceInFileConfig['to'] = - typeof replace.to === 'function' - ? (match, file) => - (replace.to as ConfigReplaceToCallback)({ match, file, project }) - : replace.to - - const results = await replaceInFile.replaceInFile({ - files: replace.include ?? '**/*', - ignore: replace.exclude, - from, - to, - countMatches: true, - glob: { - cwd: project.path, - absolute: true, - }, - }) - for (const result of results) { - if (!result.hasChanged) continue - consola.info( - `${chalk.blue.bold( - path.relative(project.path, result.file) - )} was replaced in ${chalk.green(result.numReplacements)} place(s).` - ) - } -} diff --git a/src/types.ts b/src/types.ts index ccfc70b..e662a2a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -48,6 +48,7 @@ export interface ConfigTemplate { /** @default false */ add?: boolean } + replaces?: | ({ items: Arrayable> } & Partial) | ConfigReplace[] diff --git a/src/utils.ts b/src/utils.ts index 1b06ebb..9d0ea26 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -54,10 +54,13 @@ export function getColor(color?: string): ChalkInstance { throw new Error(`Unknown color: ${color}`) } -export function which(command: string): Promise { - return execa('which', [command]) - .then((res) => res.exitCode) - .catch((err) => err.exitCode) +export async function which(command: string): Promise { + try { + const { exitCode } = await execa('which', [command]) + return exitCode + } catch (err: any) { + return err.exitCode + } } export async function findConfigTypePath() { -- knotmirror 0.0.1