Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/sxzz/create. Command-line for creating projects from templates.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import path from 'node:path'import { toArray } from '@antfu/utils'import ansis from 'ansis'import consola from 'consola'import { replaceInFile, type ReplaceInFileConfig } from 'replace-in-file'import type { ConfigReplace, ConfigReplaceFromCallback, ConfigReplaceToCallback, Context,} from '../types.ts'
export async function replace(ctx: Context): Promise<void> { const { template } = ctx for (const replace of template.replaces) { await doReplace(ctx, replace).catch((error) => { console.error(error) }) }}
async function doReplace( { template, project }: Context, replace: ConfigReplace,) { 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' // eslint-disable-next-line baseline-js/use-baseline return new RegExp(RegExp.escape(from), flags) }
const from = ( typeof replace.from === 'function' ? (file) => (replace.from as ConfigReplaceFromCallback)({ file, project, template, }) : 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, template, }) : replace.to
const results = await 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( `${ansis.blue.bold( path.relative(project.path, result.file), )} was replaced in ${ansis.green(result.numReplacements)} place(s).`, ) }}