Repository navigation
Add dreamcli create #331
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Add dreamcli create #331
Changes from all commits
ca5c5d9
bc3fd8b
4841e38
a43fbd3
e27a57e
d5b3d2a
e6c19c1
b9d128f
bee3f78
2342c1d
53b34f7
53c32ac
74e330b
eb3a1c8
44ce90b
107a361
ae8b2f8
307de92
b818c74
d906532
6a6e21e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| /** DreamCLI's package executable. @module */ | ||
|
|
||
| import { basename, relative, resolve, sep } from 'node:path'; | ||
| import { fileURLToPath, pathToFileURL } from 'node:url'; | ||
| import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; | ||
| import { scaffold } from '@kjanat/dreamcli/create'; | ||
| import { prompt } from '@kjanat/dreamcli/prompt'; | ||
| import { createAdapter, detectRuntime } from '@kjanat/dreamcli/runtime'; | ||
| import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; | ||
| import { initGit, projectIdentity } from './git.mjs'; | ||
| import { latestTsdown } from './project.mjs'; | ||
|
|
||
| const adapter = createAdapter(); | ||
| const ci = adapter.env.CI; | ||
| const inCI = ci && ci !== 'false' && ci !== '0'; | ||
| const terminal = !inCI && adapter.stdinIsTTY && adapter.isTTY && adapter.stderrIsTTY; | ||
|
|
||
| function nextSteps(directory, test) { | ||
| const commands = []; | ||
| const path = relative(adapter.cwd, directory); | ||
| if (path) { | ||
| if (sep === '\\') { | ||
| // PowerShell recognizes typographic single quotes as delimiters too. | ||
| commands.push(`Set-Location -LiteralPath '${directory.replace(/['‘’‚‛]/gu, "'$&")}'`); | ||
| } else { | ||
| commands.push(`cd './${path.replaceAll("'", "'\\''")}'`); | ||
| } | ||
| } | ||
| if (detectRuntime() === 'bun') { | ||
| // Bun treats '?' in the absolute entry path as a query. The Node start script handles it. | ||
| const start = directory.includes('?') ? 'bun run start' : 'bun src/cli.ts'; | ||
| commands.push('bun install', `${start} hello Jalapeño`); | ||
| if (test) commands.push('bun run test'); | ||
| } else { | ||
| commands.push('npm install', 'npm start -- hello Jalapeño'); | ||
| if (test) commands.push('npm test'); | ||
| } | ||
| return commands.join('\n'); | ||
| } | ||
|
|
||
| const create = command('create') | ||
| .alias('init') | ||
| .description('Generate a DreamCLI starter') | ||
| .arg('directory', arg.string().optional().describe('Project directory (or CLI name with --out)')) | ||
| .flag('name', flag.string().describe('Override the project name')) | ||
| .flag('yes', flag.boolean().alias('y').describe('Use defaults without prompting')) | ||
| .flag( | ||
| 'out', | ||
| flag.path().describe('Write files into this directory instead of creating a project'), | ||
| ) | ||
| .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) | ||
| .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) | ||
| .flag( | ||
| 'force', | ||
| flag.boolean().default(false).describe('Replace existing starter files when using --out'), | ||
| ) | ||
| .action(async ({ args, flags, out, ask }) => { | ||
| const { git: useGit, name: explicitName, yes, ...options } = flags; | ||
| const project = options.out === undefined; | ||
| const interactive = project && !yes && !out.jsonMode && terminal; | ||
|
|
||
| let target = args.directory; | ||
| if (target === undefined && interactive) { | ||
| target = await ask( | ||
| prompt.input({ | ||
|
kjanat marked this conversation as resolved.
Resolved
|
||
| message: 'Where should I create your CLI?', | ||
| empty: 'accept', | ||
| trim: false, | ||
| }), | ||
| ); | ||
| } | ||
| if (!target?.trim()) { | ||
| throw new CLIError( | ||
| project ? 'Provide a project directory.' : 'Provide a CLI name with --out.', | ||
| { | ||
| code: 'SCAFFOLD_DIRECTORY_REQUIRED', | ||
| exitCode: 2, | ||
| suggest: project | ||
| ? 'For example: dreamcli create ./my-cli' | ||
| : 'For example: dreamcli create my-cli --out .', | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| const directory = resolve(adapter.cwd, target); | ||
|
kjanat marked this conversation as resolved.
Resolved
|
||
| const name = explicitName ?? (project ? basename(directory) : target); | ||
| if (interactive && relative(adapter.cwd, directory) === '') { | ||
| if (!(await ask(prompt.confirm({ message: 'Create here?', default: false })))) return; | ||
| } | ||
|
|
||
| const metadata = project | ||
| ? { | ||
| ...projectIdentity(directory, adapter.env), | ||
| tsdownVersion: await latestTsdown(adapter.env), | ||
| } | ||
| : undefined; | ||
| const result = scaffold({ | ||
| ...options, | ||
| name, | ||
| directory, | ||
| metadata, | ||
| skillDirectory: fileURLToPath(new URL('../skills/dreamcli/', import.meta.url)), | ||
| }); | ||
| const git = | ||
| project && useGit | ||
| ? initGit( | ||
| directory, | ||
| result.files.map((path) => relative(directory, path).split(sep).join('/')), | ||
| DREAMCLI_VERSION, | ||
| DREAMCLI_REVISION, | ||
| adapter.env, | ||
| metadata?.repository, | ||
| ) | ||
| : undefined; | ||
| if (out.jsonMode) { | ||
| out.json({ ...result, ...(git && { git }) }); | ||
| return; | ||
| } | ||
| const destination = project ? directory : result.entry; | ||
| const label = out.color.cyan(project ? target : relative(adapter.cwd, destination)); | ||
| out.log(`Created ${out.color.link(pathToFileURL(destination), label)}`); | ||
| if (git?.error) out.warn(`Git: ${git.error}`); | ||
| if (project && !metadata?.tsdownVersion) { | ||
| out.status("Using DreamCLI's tested tsdown version because the npm lookup was unavailable."); | ||
| } | ||
| if (project) out.status(`\n${nextSteps(directory, result.test)}`); | ||
| }); | ||
|
|
||
| const app = cli('dreamcli') | ||
| .manifest({ from: import.meta }) | ||
| .links() | ||
| .help({ commandHeader: true }) | ||
| .description('Create a project with DreamCLI'); | ||
|
|
||
| const program = terminal && adapter.argv.length === 2 ? app.default(create) : app.command(create); | ||
| await program.run({ adapter }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| /** Initialize a standalone starter without touching a surrounding repository. @module */ | ||
|
|
||
| import { spawnSync } from 'node:child_process'; | ||
| import { existsSync } from 'node:fs'; | ||
| import { basename, dirname } from 'node:path'; | ||
|
|
||
| export function projectIdentity(directory, env) { | ||
| let cwd = directory; | ||
| while (!existsSync(cwd) && dirname(cwd) !== cwd) cwd = dirname(cwd); | ||
| const config = (key) => { | ||
| const result = spawnSync('git', ['config', '--get', key], { cwd, env, encoding: 'utf8' }); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Isolate identity lookup from an inherited If For example, an unrelated repository's Apply the same repository-local environment sanitisation before identity lookup. Retain explicit
|
||
| return result.status === 0 ? result.stdout.trim() : ''; | ||
| }; | ||
| const name = env.GIT_AUTHOR_NAME || config('user.name'); | ||
| const email = env.GIT_AUTHOR_EMAIL || config('user.email'); | ||
| const owner = | ||
| config('github.user') || | ||
| /^(?:\d+\+)?([\w-]+)@users\.noreply\.github\.com$/i.exec(email)?.[1] || | ||
| name.trim().replace(/\s+/g, '-'); | ||
| const folder = basename(directory) | ||
| .replace(/[^A-Za-z0-9_.-]+/g, '-') | ||
| .replace(/^-+|-+$/g, ''); | ||
| const repository = | ||
| /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(owner) && folder && !/^\.+$/.test(folder) | ||
| ? `https://github.com/${owner}/${folder}` | ||
| : undefined; | ||
| return { | ||
| ...((name || email) && { author: { ...(name && { name }), ...(email && { email }) } }), | ||
| ...(repository && { repository }), | ||
| }; | ||
| } | ||
|
|
||
| export function initGit(cwd, files, version, revision, env, remote) { | ||
| const options = { cwd, encoding: 'utf8', env: { ...env, LC_ALL: 'C' } }; | ||
| const run = (...args) => spawnSync('git', args, options); | ||
| const local = run('rev-parse', '--local-env-vars'); | ||
| if (local.status !== 0) return failure(local); | ||
| for (const key of local.stdout.trim().split(/\s+/)) delete options.env[key]; | ||
|
|
||
| const repository = run('rev-parse', '--git-dir'); | ||
| if (repository.status === 0) return { skipped: 'existing-repository' }; | ||
| if (!repository.stderr?.includes('not a git repository')) return failure(repository); | ||
|
|
||
| const message = ['-m', `Initialize with dreamcli create ${version}`]; | ||
| if (revision !== 'dev') message.push('-m', `DreamCLI-Revision: ${revision}`); | ||
| for (const args of [ | ||
| ['init', '--template='], | ||
| ...(remote ? [['remote', 'add', 'origin', `${remote}.git`]] : []), | ||
| ['add', '--', ...files], | ||
| ['commit', ...message, '--', ...files], | ||
| ]) { | ||
| const result = run(...args); | ||
| if (result.status !== 0) return failure(result); | ||
| } | ||
| const head = run('rev-parse', 'HEAD'); | ||
| return head.status === 0 ? { commit: head.stdout.trim() } : failure(head); | ||
| } | ||
|
|
||
| function failure(result) { | ||
| return { error: result.stderr?.trim() || result.error?.message || 'Git exited unsuccessfully.' }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| /** Resolve the npm dist-tag at init time; offline scaffolds use the tested build version. @module */ | ||
|
|
||
| export async function latestTsdown(env) { | ||
| if ((env.npm_config_offline ?? env.NPM_CONFIG_OFFLINE) === 'true') return undefined; | ||
| try { | ||
| const registry = | ||
| env.npm_config_registry || env.NPM_CONFIG_REGISTRY || 'https://registry.npmjs.org/'; | ||
| const response = await fetch(new URL('tsdown/latest', registry.replace(/\/?$/, '/')), { | ||
| signal: AbortSignal.timeout(8000), | ||
| headers: { Accept: 'application/json' }, | ||
| }); | ||
| if (!response.ok) return undefined; | ||
| const { version } = await response.json(); | ||
| return typeof version === 'string' && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version) | ||
| ? version | ||
| : undefined; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.