import { realpathSync } from "node:fs" import { resolve } from "node:path" import { CliError, UsageError, bool, c, defineCommand, log, note, prompt } from "../../cli" import { createRepo, whoami, type HubWhoami, type Visibility } from "../../hub/api" import { requireHubConfig } from "../../hub/config" import { git, gitOrThrow } from "../../hub/git" /* * `lecodes hub create [ns/]name [--public | --run-only]` — make the repo + project on hub for the * app in this folder and connect the folder to it (LeCodesHub/docs/cli.md). Nothing in the folder * is required: a project needs no app.json (a Focus project is a folder with main.ts), and whether * there is anything to build is the build's to say at the first push or upload, in the same words * for both. The order keeps a failure cheap: what is local and can refuse (a `hub` remote already * there) is checked before `POST /api/repos`; `git init -b main` and `git remote add hub` come * after it. * Private unless a flag says otherwise. Where the code will live is not asked: a push builds its * branch's environment, an upload (`lecodes hub deploy` from another forge's CI) the environment * it names, and one project may have both. * * Without `ns/` the namespace comes from `GET /api/account`: the user's own account, or — when they * are also in orgs and stdin is a terminal — the one they pick from a numbered list (own account * first, the default). `ns` is always sent explicitly. * * The folder must be the ROOT of its git repo: hub builds the root of every pushed commit, so a * project inside a bigger repo (a subfolder of a monorepo) gets its own repo here. */ const samePath = (a: string, b: string): boolean => { const norm = (p: string): string => { let r = resolve(p) try { r = realpathSync.native(r) } catch { /* as given */ } return process.platform === "win32" ? r.toLowerCase() : r } return norm(a) === norm(b) } /** `den/demo` → { ns: "den", name: "demo" }; `demo` → { name: "demo" } (the server picks the namespace). */ export const parseRepoArg = (arg: string): { ns?: string, name: string } => { const parts = arg.trim().split("/") if (parts.length === 1 && parts[0]) return { name: parts[0] } if (parts.length === 2 && parts[0] && parts[1]) return { ns: parts[0], name: parts[1] } throw new UsageError(`"${arg}" is not [namespace/]name`) } /** * The namespace to create in: the own account when it is the only one or nobody can answer * (`ask` absent = stdin is not a terminal), else the user's pick — a number or a slug; Enter = 1. */ export const pickNamespace = async (me: HubWhoami, ask?: (question: string, fallback: string) => Promise): Promise => { const own = me.account.slug const list = [...(me.namespaces ?? [])].sort((a, b) => Number(b.slug === own) - Number(a.slug === own)) if (!list.some(n => n.slug === own)) list.unshift({ id: me.account.id, slug: own, name: me.account.name, kind: me.account.kind }) if (list.length === 1 || !ask) return own log("Create the repository in:") list.forEach((n, i) => log(` ${i + 1}) ${c.bold(n.slug)}${c.dim(n.slug === own ? " your account" : ` ${n.kind}${n.role ? `, ${n.role}` : ""}`)}`)) const answer = (await ask("Namespace", "1")).trim() const byNumber = /^\d+$/.test(answer) ? list[Number(answer) - 1] : undefined const chosen = byNumber ?? list.find(n => n.slug === answer) if (!chosen) throw new CliError(`"${answer}" is none of the ${list.length} namespaces listed.`) return chosen.slug } export default defineCommand({ name: "create", summary: "Create a hub repo + project for the app in this folder and add it as the `hub` git remote", usage: "[ns/]name", description: "Run it in the project's folder (the one with main.ts; app.json is optional). Calls hub to create the repository and its project, runs `git init -b main` when the folder is not a repository yet, and adds the repository as the remote `hub`. Deploying is then a plain `git push hub main` (every branch pushed gets an environment of its own), or, for code that lives on another forge, `lecodes hub deploy` in its CI.\n\nWithout a namespace the repo goes to your own account; when you are also a member of orgs, the CLI lists them and asks (in a terminal; otherwise your own account). The project is private unless `--public` (anyone runs it and reads its code) or `--run-only` (anyone with its link runs it).", flags: { public: bool("anyone may run the project and read its code"), "run-only": bool("anyone with the link may run the project; its code stays private"), }, examples: ["lecodes hub create demo", "lecodes hub create den/demo --public"], run: async ({ args, flags }) => { const cwd = process.cwd() if (!args[0]) throw new UsageError("name the repository: lecodes hub create [ns/]name") if (flags.public && flags["run-only"]) throw new UsageError("--public and --run-only are two visibilities: choose one") const visibility: Visibility = flags.public ? "public" : flags["run-only"] ? "run" : "private" const { ns, name } = parseRepoArg(args[0]) const config = requireHubConfig() const top = git(["rev-parse", "--show-toplevel"], cwd) const isRepo = top.ok && samePath(top.stdout, cwd) if (isRepo) { const existing = git(["remote", "get-url", "hub"], cwd) if (existing.ok) throw new CliError(`This repository already has a "hub" remote (${existing.stdout}). Remove it first: git remote remove hub`) } const namespace = ns ?? await pickNamespace(await whoami(config.url, config.token), process.stdin.isTTY ? prompt : undefined) const created = await createRepo(config.url, config.token, { ns: namespace, name, visibility }) if (!created || typeof created.remote !== "string") throw new CliError("hub answered without the repository's remote URL.") if (!isRepo) { if (top.ok) note(`(inside the repository at ${top.stdout} — this folder gets a repository of its own)`) gitOrThrow(["init", "-b", "main"], cwd) } gitOrThrow(["remote", "add", "hub", created.remote], cwd) const branch = git(["symbolic-ref", "--short", "HEAD"], cwd) const pushLine = !branch.ok || branch.stdout === "main" ? "git push hub main" : `git push hub ${branch.stdout}:main` log(`Created ${c.bold(created.remote.replace(/\.git$/, ""))} (${visibility === "run" ? "run only" : visibility})`) log(`Remote "hub" added. Deploy with:`) log(` ${pushLine}`) log("Or from another forge's CI:") log(` lecodes hub deploy --project ${namespace}/${name}`) }, })