/** * ───────────────────────────────────────────── * SPB Git — Personal Git Platform * ───────────────────────────────────────────── * Author : Simon-Pierre Boucher * Contact : contact@spboucher.ai * File : cli/commands/create.mjs * Purpose : `spbgit create` — create on server, optionally push cwd * License : MIT © Simon-Pierre Boucher * ───────────────────────────────────────────── */ import { existsSync } from 'node:fs'; import { join } from 'node:path'; import pc from 'picocolors'; import { requireCliConfig } from '../lib/config.mjs'; import { api, EXIT } from '../lib/api.mjs'; import { git } from '../lib/git.mjs'; export function registerCreate(program) { program .command('create ') .description('create a repository on the server') .option('-d, --description ', 'repository description', '') .option('--topics ', 'comma-separated topics (max 10)') .option('--pinned', 'pin on the home page', false) .option('--push', 'also init the current directory, add remote, commit and push', false) .action(async (name, opts) => { const config = requireCliConfig(); const topics = (opts.topics ?? '') .split(',') .map((t) => t.trim().toLowerCase()) .filter(Boolean) .slice(0, 10); const repo = await api(config, 'POST', '/api/v1/repos', { name, description: opts.description, topics, pinned: Boolean(opts.pinned), }); console.log(`${pc.green('✓')} Created ${pc.bold(repo.name)} → ${repo.url}`); if (!opts.push) return; const cwd = process.cwd(); if (!existsSync(join(cwd, '.git'))) { const init = await git(cwd, ['init', '-b', 'main']); if (!init.ok) { console.error(pc.red(`✗ git init failed: ${init.stderr}`)); process.exit(EXIT.USER); } console.log(`${pc.green('✓')} Initialized git repository in ${cwd}`); } const hasRemote = await git(cwd, ['remote', 'get-url', 'origin']); if (!hasRemote.ok) { await git(cwd, ['remote', 'add', 'origin', repo.cloneUrl]); console.log(`${pc.green('✓')} Remote origin → ${repo.cloneUrl}`); } const hasCommit = await git(cwd, ['rev-parse', '--verify', 'HEAD']); if (!hasCommit.ok) { await git(cwd, ['add', '-A']); const commit = await git(cwd, ['commit', '-m', 'feat: initial commit']); if (!commit.ok) { console.error(pc.red(`✗ Nothing to commit — add files first, then: git push -u origin main`)); process.exit(EXIT.USER); } console.log(`${pc.green('✓')} Initial commit created`); } const branch = (await git(cwd, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim() || 'main'; const push = await git(cwd, ['push', '-u', 'origin', branch], { token: config.token }); if (!push.ok) { console.error(pc.red(`✗ Push failed: ${push.stderr.trim()}`)); process.exit(EXIT.NETWORK); } console.log(`${pc.green('✓')} Pushed ${branch} — live at ${repo.url}`); }); }