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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249import { mkdir, readFile, writeFile } from 'node:fs/promises'import { homedir } from 'node:os'import path from 'node:path'import process from 'node:process'import { objectPick, toArray } from '@antfu/utils'import { confirm, isCancel, select } from '@clack/prompts'import ansis from 'ansis'import consola from 'consola'import { x } from 'tinyexec'import { createConfigCoreLoader } from 'unconfig-core'import { parse, stringify } from 'yaml'import { CliError, cmdExists, findConfigTypePath } from './utils.ts'import type { Config, ConfigReplace, ConfigTemplate } from './types.ts'
type MergeObject<O, T> = Omit<O, keyof T> & T
export type TemplateNormalized = MergeObject< ConfigTemplate, { children?: TemplateNormalized[] git: NonNullable<ConfigTemplate['git']> replaces: ConfigReplace[] variables: Array<NonNullable<ConfigTemplate['variables']>> commands: Array<NonNullable<ConfigTemplate['commands']>> cwd: string }>export type ConfigNormalized = MergeObject< Config, { templates: Array<ConfigTemplate> }>
const demoConfig: Config = { git: { add: true, }, templates: [ { name: 'Library', color: 'green', children: [ { name: 'TypeScript', color: '#3178c6', url: 'sxzz/node-lib-starter', }, ], }, { name: 'Web App', url: 'sxzz/node-lib-starter', git: { init: false, }, }, ],}
export const configPath: string = path.resolve( homedir(), '.config/create.config',)
export async function getConfig({ init = true,}: { init?: boolean } = {}): Promise<{ exists: boolean init: boolean config: ConfigNormalized file: string}> { const configs = await createConfigCoreLoader<Config>({ sources: [ { files: [configPath], extensions: ['mts', 'cts', 'ts', 'mjs', 'cjs', 'js', 'json'], parser(filePath) { return import( filePath, filePath.endsWith('.json') ? { with: { type: 'json' } } : undefined ).then((mod) => (mod?.default || mod) as Config) }, }, { files: [configPath], extensions: ['yaml', 'yml'], async parser(filePath) { return parse(await readFile(filePath, 'utf8')) as Config }, }, ], multiple: false, }).load()
if (configs.length) { return { exists: true, init: false, config: normalizeConfig(configs[0].config), file: configs[0].source, } }
if (!init) return { exists: false, init: false, config: undefined as any, file: '', }
consola.warn(ansis.yellowBright('No configuration file found.'))
const filePath = await initConfig() await editConfig(filePath)
const newConfig = await getConfig({ init: false }) if (!newConfig) throw new CliError('No configuration file found.') return { ...newConfig, init: true }}
export async function initConfig(): Promise<string> { const create = await confirm({ message: 'Do you want to create a configuration file?', initialValue: true, }) if (isCancel(create) || !create) { process.exit(1) }
const options = (['JavaScript', 'TypeScript', 'JSON', 'YAML'] as const).map( (kind) => ({ value: kind }), ) const kind = await select({ message: 'What kind of configuration file do you want to create?', options, }) if (isCancel(kind)) { process.exit(1) }
await mkdir(path.dirname(configPath), { recursive: true }).catch( () => undefined, ) let filePath = configPath let contents: string switch (kind) { case 'JSON': filePath += '.json' contents = JSON.stringify(demoConfig, undefined, 2) break case 'JavaScript': filePath += '.js' contents = `export default ${JSON.stringify(demoConfig, undefined, 2)}` break case 'TypeScript': { filePath += '.ts' const configTypePath = findConfigTypePath().replaceAll('\\', '/') contents = `import type { Config } from '${configTypePath}'
const config: Config = ${JSON.stringify(demoConfig, undefined, 2)}
export default config` break } case 'YAML': filePath += '.yml' contents = stringify(demoConfig) break } await writeFile(filePath, contents) return filePath}
export async function editConfig(filePath: string): Promise<void> { const EDITOR = process.env.EDITOR if (EDITOR && (await cmdExists(EDITOR))) { await x(EDITOR, [filePath], { nodeOptions: { stdio: 'inherit' } }) } else if (await cmdExists('code')) { await x('code', [filePath]) } else if (await cmdExists('zed')) { await x('zed', [filePath], { nodeOptions: { stdio: 'inherit' } }) } else if (await cmdExists('vim')) { await x('vim', [filePath], { nodeOptions: { stdio: 'inherit' } }) } else { consola.info( `Editors are not detected, please open and edit config file manually: ${filePath}`, ) }}
export function normalizeConfig(config: Config): ConfigNormalized { return { ...config, templates: toArray(config.templates), }}
export function normalizeTemplate( templates: ConfigTemplate[],): TemplateNormalized { const normalizeReplaces = ( replaces: ConfigTemplate['replaces'], ): ConfigReplace[] => { if (!replaces) return [] return Array.isArray(replaces) ? replaces : toArray(replaces.items).map( (replace) => // eslint-disable-next-line @typescript-eslint/consistent-type-assertions ({ ...objectPick(replaces, ['from', 'to', 'include', 'exclude']), ...replace, }) as ConfigReplace, ) }
const mergeTemplate = ( a: TemplateNormalized, b: ConfigTemplate, ): TemplateNormalized => ({ ...a, ...b, git: { ...a.git, ...b.git, }, replaces: [ ...normalizeReplaces(a.replaces), ...normalizeReplaces(b.replaces), ], variables: [...a.variables, ...(b.variables ? [b.variables] : [])], commands: [...a.commands, ...(b.commands ? [b.commands] : [])], children: undefined, cwd: b.cwd || a.cwd, })
const initial: TemplateNormalized = { name: '', git: {}, replaces: [], variables: [], commands: [], cwd: process.cwd(), } return templates.reduce((a, b) => mergeTemplate(a, b), initial)}