import type { CheckoutEvent, GitContext, Hooks } from "@neon/config"; import type { Branch } from "@neon/sdk"; import chalk from "chalk"; import prompts from "prompts"; import type yargs from "yargs"; import { isNeonApiError } from "../api.js"; import { isClaimableEnvTarget } from "../claimable/state.js"; import { applyContext, contextBranch, readContextFile } from "../context.js"; import { isCi } from "../env.js"; import { loadEnvFileIntoProcess } from "../env_file.js"; import { ProjectNotLinkedError } from "../errors.js"; import { log } from "../log.js"; import type { CommonProps } from "../types.js"; import { createBranch, pickBranchInteractively, } from "../utils/branch_picker.js"; import { getCliName } from "../utils/cli_name.js"; import { fillSingleProject, listAllProjectBranches, } from "../utils/enrichers.js"; import { looksLikeBranchId } from "../utils/formats.js"; import { buildCheckoutEvent, readGitContext } from "../utils/git.js"; import { buildHookBranch, loadHookConfig, resolveHookEnv, runCheckoutAfterHook, runCheckoutBeforeHook, runCreateAfterHook, runCreateBeforeHook, } from "../utils/hooks.js"; import { applyPolicyOnCreate, createBranchFromPolicyOnCheckout, envFlag, } from "./config.js"; import { autoPullEnvAfterPin } from "./env.js"; import { handler as linkHandler } from "./link.js"; type CheckoutProps = CommonProps & { projectId?: string; orgId?: string; id?: string; envPull: boolean; env?: string; create?: boolean; /** Global `--color` flag (default true); `--no-color` sets it false to force plain output. */ color?: boolean; configDir?: string; }; // The positional is optional: omitting it in an interactive terminal opens a // branch picker. In non-interactive contexts a missing branch is an error. export const command = "checkout [id|name]"; export const describe = "Pin a branch in the local context (.neon) so subsequent commands target it"; export const formatCheckoutPolicyFailure = (opts: { branchName: string; branchId: string; failure: string; env?: string; }): string => { const cli = getCliName(); const envArg = opts.env ? ` --env ${opts.env}` : ""; return [ `Branch ${opts.branchName} (${opts.branchId}) was created and checked out, but applying neon.ts to it failed: ${opts.failure}`, `The branch is usable but does not match the policy, and \`${cli} checkout\` never reconciles a branch that already exists.`, `Fix the cause above, then run \`${cli} deploy --update-existing${envArg}\` to apply the policy to it — or, if your policy only configures new branches (keyed on \`!branch.exists\`), delete the branch and check it out again: \`${cli} branches delete ${opts.branchName}\` then \`${cli} checkout ${opts.branchName} --create${envArg}\`.`, ].join("\n"); }; export const builder = (argv: yargs.Argv) => argv .usage("$0 checkout [id|name] [options]") .positional("id", { describe: "Branch name or id to check out. Omit to pick interactively from the list of branches.", type: "string", }) .options({ "project-id": { describe: "Project ID", type: "string", }, "env-pull": { describe: "Pull the branch's Neon env vars (DATABASE_URL, …) into a local .env after " + "checkout. On by default; use --no-env-pull to skip (e.g. when injecting env at " + "runtime with `neon-env run` / `neon dev`).", type: "boolean", default: true, }, create: { describe: "Create the named branch if it does not exist, then check it out. " + "New branches start from the parent set in neon.ts, else the project's default branch. " + "An existing branch is checked out unchanged.", type: "boolean", default: false, }, ...envFlag, env: { ...envFlag.env, describe: envFlag.env.describe + " Used when this checkout creates a branch from neon.ts; ignored for an existing branch.", }, }) .example([ [ "$0 checkout", "Pick a branch interactively from the project in the closest .neon file", ], [ "$0 checkout main", 'Pin the branch named "main" in the closest .neon file', ], [ "$0 checkout dev --create", "Create and pin a missing branch named dev", ], [ "$0 checkout feat --create --env .env.local", "Create feat from neon.ts, loading Function env from .env.local first", ], [ "$0 checkout br-cool-snow-12345678 --project-id project-id-123", "Pin a branch by id for an explicit project", ], ]); export const handler = async (props: CheckoutProps) => { // Show where the context is pinned *before* we switch it, so the user sees the move // ("currently on X" → "checked out Y") and can catch a checkout they didn't mean to make. // Read straight from `.neon` (a name, no API call); silent when nothing is pinned yet. const previousBranch = contextBranch(readContextFile(props.contextFile)); if (previousBranch) { log.info( "%s Currently on branch %s", chalk.dim("→"), chalk.cyan.bold(previousBranch), ); } if (props.create && !props.id?.trim()) { throw new Error( `No branch specified. Pass a branch name with --create (e.g. \`${getCliName()} checkout dev --create\`).`, ); } // Branch listing is project-scoped, so `projectId` is the only thing // `checkout` actually needs. Resolve it through the standard chain // (--project-id flag > .neon file > single-project auto-detect); when // nothing resolves, fall back to an interactive `neonctl link`. const projectId = await resolveProjectId(props); // `--create` (only) best-effort loads `--env` before hook discovery, not just before the // policy-driven create later in `createBranchFromPolicyOnCheckout`: a neon.ts that reads // `process.env.X` at module-evaluation time — e.g. to build its `experimental.hooks` // block — must see the same environment on both loads, or the checkout.before hook is // silently skipped by a load failure that would have succeeded with the file applied. // Best-effort because `--create` on a name that already exists never creates anything, so // a bogus `--env` path must stay harmless here too — same contract as before hooks // existed. A genuine create with a bad `--env` still fails loudly, just later, from // `createBranchFromPolicyOnCheckout`'s own (unconditional) load. if (props.create && props.env) { try { loadEnvFileIntoProcess(props.env); } catch (err) { log.debug( "checkout: could not preload --env for hook discovery (continuing): %s", err instanceof Error ? err.message : String(err), ); } } // Lifecycle hooks (Preview): read git facts + load the neon.ts `experimental.hooks` block // once. The `checkout.before` hook may rewrite the branch name (e.g. map a git branch to // a Neon slug) before we resolve it — it runs before resolution because the name isn't // pinned yet. const cwd = process.cwd(); const git = readGitContext(cwd); // `event` reflects the raw trigger data (the git branch, or the id/name as typed) — not // anything a hook already rewrote. See `CheckoutEvent` in `@neon/config`. const event = buildCheckoutEvent(git, props.id); const config = await loadHookConfig(cwd, props.contextFile); const hooks = config?.experimental?.hooks; if (props.id) { const renamed = await runCheckoutBeforeHook({ hooks, event, git, cwd }); if (renamed && renamed !== props.id) { log.info( "%s checkout.before hook mapped %s → %s", chalk.dim("→"), chalk.cyan(props.id), chalk.cyan.bold(renamed), ); props.id = renamed; } } // The org lookup needs only the project, so it runs while the branch resolves (which can // prompt or create a branch) and is awaited where it always was. Claimable Neon does not // complete concurrent Management API reads, so there it still waits for the branch. const claimable = isClaimableEnvTarget({ apiHost: props.apiHost, contextFile: props.contextFile, configDir: props.configDir ?? "", }); const orgRead = claimable ? undefined : resolveOrgId(props, projectId); orgRead?.catch(() => undefined); const { branchId, branchName, created, policyApplied, policyFailure } = await resolveBranchId(props, projectId, { hooks, git, event, cwd }); const orgId = await (orgRead ?? resolveOrgId(props, projectId)); if (props.create && !created) { log.warning( "Branch %s (%s) already exists, so --create did not create a new one; checking out the existing branch unchanged. Pass a new name for a fresh branch.", branchName, branchId, ); } // `checkout` is a thin helper over `link`. It fully "heals" the context file: // it always (re)writes `projectId`, `branch`, and `orgId` (when the project // has one) so a `.neon` that drifted or was missing fields ends up complete // and consistent after checkout. The branch is stored as its name when known // (see `link`'s `branch` field), matching what `link` writes. applyContext(props.contextFile, { projectId, ...(orgId ? { orgId } : {}), branch: branchName, }); log.info( "Checked out branch %s on project %s%s. Updated %s.", branchId, projectId, orgId ? ` (org ${orgId})` : "", props.contextFile, ); // When checkout *created* the branch and a neon.ts exists, the branch was created straight // from the policy (evaluated as a new branch) so its settings/infra are already applied — // see `policyApplied`. The fallback below covers the case where the branch was created bare // (e.g. a policy-driven create wasn't possible); `applyPolicyOnCreate` is a no-op when there // is no neon.ts on disk. Checking out an existing branch never reconciles it. const failure = created && !policyApplied ? await applyPolicyOrDescribeFailure({ projectId, branchId, branchName, contextFile: props.contextFile, ...(props.apiKey ? { apiKey: props.apiKey } : {}), ...(props.apiHost ? { apiHost: props.apiHost } : {}), ...(props.color !== undefined ? { color: props.color } : {}), ...(props.env ? { env: props.env } : {}), }) : policyFailure; // Bundle `env pull` so the branch-first loop is just link + checkout: the branch you // checked out is immediately usable for local dev. `--no-env-pull` opts out. await autoPullEnvAfterPin( { ...props, projectId, branch: branchId, envPull: props.envPull, }, { branchId, branchName, usedDefault: false }, ); // `checkout.after` / `create.after` hooks (Preview): run once the branch is pinned and env // is resolved, regardless of a policy-apply failure above (the branch is checked out // either way). Env is resolved in-memory here even under `--no-env-pull`, so a migration // hook always has a connection string. A hook failure degrades to a warning — the checkout // itself already succeeded. const needsCreateAfter = created && hooks?.create?.after; if (config && (hooks?.checkout?.after || needsCreateAfter)) { const env = await resolveHookEnv(config, { projectId, branch: branchId, ...(props.apiKey ? { apiKey: props.apiKey } : {}), ...(props.apiHost ? { apiHost: props.apiHost } : {}), }); if (env) { const branch = await buildHookBranch({ apiClient: props.apiClient, projectId, branchId, created, }); if (hooks?.checkout?.after) { await runCheckoutAfterHook({ hooks, branch, env, git, event, cwd, }); } if (needsCreateAfter) { await runCreateAfterHook({ hooks, branch, env, git, event, cwd, }); } } } // A policy that didn't fully apply is reported last, after the pin and the env pull, so the // created branch is left in a consistent, usable, re-runnable state: the failure is what // needs fixing, not the checkout. Still a non-zero exit — the branch does not match the // policy, and `checkout` will not reconcile it on a second run. if (failure) { throw new Error( formatCheckoutPolicyFailure({ branchName, branchId, failure, ...(props.env ? { env: props.env } : {}), }), ); } }; /** * Apply the policy to a branch `checkout` just created bare, returning the failure message * instead of throwing it. The branch and the context pin already stand at this point, so a * failed apply must not abort the rest of the checkout — the handler reports it at the end. */ const applyPolicyOrDescribeFailure = async ( props: Parameters[0], ): Promise => { try { await applyPolicyOnCreate(props); return undefined; } catch (err) { return err instanceof Error ? err.message : String(err); } }; /** * Resolve the branch id to check out. * * - Branch **id** (`br-…`): looked up by id. A non-existent id is a hard "not * found" error — we never offer to create one, since ids are server-assigned. * - Branch **name**: looked up by name. If it doesn't exist, `--create` creates * it (like `neon branch create --name `). Without the flag, a TTY offers * to create it; CI / non-TTY exits with a not-found error that names `--create`. * - **Omitted**: open an interactive picker listing the project's branches plus a * "create a new branch" option (TTY only); in a non-interactive context a missing * branch is a hard error. */ type ResolvedBranch = { branchId: string; /** Value to persist in `.neon` (the branch name when known, else its id). */ branchName: string; /** True only when this checkout created a new branch (vs. selecting an existing one). */ created: boolean; /** * True when the branch was created through the local `neon.ts` policy, so the handler must * not apply the policy a second time — whether or not every declared setting landed (see * `policyFailure`). False for an existing branch or a bare create with no policy on disk. */ policyApplied: boolean; /** * Why the policy did not fully apply to a branch this checkout created. The branch exists * (so it still gets pinned), but its settings diverge from `neon.ts` — the handler reports * this at the end with the remediation. */ policyFailure?: string; }; /** Read-only bundle of lifecycle-hook inputs threaded through branch resolution. */ type HookCtx = { hooks: Hooks | undefined; git: GitContext; event: CheckoutEvent; cwd: string; }; const resolveBranchId = async ( props: CheckoutProps, projectId: string, hookCtx: HookCtx, ): Promise => { const branches = await listAllProjectBranches(props.apiClient, projectId); if (!props.id) { const picked = await pickBranchInteractively(branches, { message: "Which branch would you like to check out?", nonInteractiveMessage: `No branch specified. Pass a branch name or id (e.g. \`${getCliName()} checkout main\`), ` + "or run interactively to pick one from a list.", }); if (picked.kind === "existing") { const existing = branches.find( (b: Branch) => b.id === picked.branchId, ); return { branchId: picked.branchId, branchName: existing?.name ?? picked.branchId, created: false, policyApplied: false, }; } // The user chose "create a new branch" from the picker. return createCheckoutBranch( props, projectId, picked.name, branches, hookCtx, ); } const ref = props.id; // A `br-…` value is an id; match strictly by id and never offer to create. if (looksLikeBranchId(ref)) { const byId = branches.find((b: Branch) => b.id === ref); if (byId) { return { branchId: byId.id, branchName: byId.name ?? byId.id, created: false, policyApplied: false, }; } throw new Error(notFoundMessage(ref, branches)); } const byName = branches.find((b: Branch) => b.name === ref); if (byName) { return { branchId: byName.id, branchName: byName.name ?? byName.id, created: false, policyApplied: false, }; } if (props.create) { return createCheckoutBranch(props, projectId, ref, branches, hookCtx); } const missingName = notFoundMessage(ref, branches, { suggestCreate: true }); // Name not found: offer to create it interactively, mirroring `branch create`. if (isCi() || !process.stdout.isTTY) { throw new Error(missingName); } log.info(missingName); const { create } = await prompts({ type: "confirm", name: "create", message: `Branch "${ref}" does not exist. Create it now?`, initial: true, }); if (!create) { throw new Error( `Aborted: branch "${ref}" was not found and not created.`, ); } return createCheckoutBranch(props, projectId, ref, branches, hookCtx); }; /** * Create the branch to check out. When a `neon.ts` exists, route through the policy-driven * create so the new branch comes up branched from the policy's `parent` and configured with * its declared TTL / compute / services (evaluated as a *new* branch). Otherwise fall back to * a bare branch off the default — the handler then applies the policy (a no-op with no * `neon.ts`). */ const createCheckoutBranch = async ( props: CheckoutProps, projectId: string, name: string, branches: Branch[], hookCtx: HookCtx, ): Promise => { // `create.before` (Preview): fires only here, right before a branch is actually created — // never for the existing-branch paths above. Throws propagate to abort the checkout. await runCreateBeforeHook({ hooks: hookCtx.hooks, branchName: name, git: hookCtx.git, event: hookCtx.event, cwd: hookCtx.cwd, }); const fromPolicy = await createBranchFromPolicyOnCheckout({ projectId, branchName: name, contextFile: props.contextFile, ...(props.apiKey ? { apiKey: props.apiKey } : {}), ...(props.apiHost ? { apiHost: props.apiHost } : {}), ...(props.color !== undefined ? { color: props.color } : {}), ...(props.env ? { env: props.env } : {}), }); if (fromPolicy) { return { branchId: fromPolicy.branchId, branchName: name, created: true, policyApplied: true, ...(fromPolicy.policyFailure ? { policyFailure: fromPolicy.policyFailure } : {}), }; } return { branchId: await createBranch( props.apiClient, projectId, name, branches, ), branchName: name, created: true, policyApplied: false, }; }; const notFoundMessage = ( ref: string, branches: Branch[], opts?: { suggestCreate: boolean }, ): string => `Branch ${ref} not found.${opts?.suggestCreate ? " Pass --create to create it." : ""}\nAvailable branches: ${branches .map((b: Branch) => b.name) .join(", ")}`; /** * Resolve the org id to heal into the context file. * * Prefer an org id we already know (from `--org-id`, the `.neon` file, or a * freshly-run `link`). Otherwise look it up from the project itself so the * `.neon` file ends up with an accurate `orgId` even when it was previously * missing. Projects on a personal account have no org; in that case (or if the * lookup fails for a non-auth reason) we return `undefined` and simply omit the * field rather than failing the checkout. */ const resolveOrgId = async ( props: CheckoutProps, projectId: string, ): Promise => { if (props.orgId) { return props.orgId; } try { const { data } = await props.apiClient.getProject(projectId); return data.project.org_id ?? undefined; } catch (err) { if (isNeonApiError(err) && err.status === 401) { throw err; } log.debug( "checkout: could not resolve org id for project %s: %s", projectId, err instanceof Error ? err.message : String(err), ); return undefined; } }; /** * Resolve the project id `checkout` should target. * * `props.projectId` is already populated from the `--project-id` flag or the * closest `.neon` file (via the global `enrichFromContext` middleware). When * it's still missing we try to auto-detect a single project (same behaviour as * `branches` / `connection-string`). If that fails we surface a telling error * and, in an interactive terminal, offer to run `neonctl link` in the current * folder so the user can pick a project/branch without having to re-run the * command by hand. */ const resolveProjectId = async (props: CheckoutProps): Promise => { if (props.projectId) { return props.projectId; } const autoDetected = await tryAutoDetectProject(props); if (autoDetected) { return autoDetected; } const missingProjectMessage = "Could not determine which Neon project to check out a branch from. " + "Provide one via the --project-id flag " + `or a .neon file (created by \`${getCliName()} link\` / \`${getCliName()} set-context\`).`; if (isCi() || !process.stdout.isTTY) { throw new Error(missingProjectMessage); } log.info(missingProjectMessage); const { runLink } = await prompts({ type: "confirm", name: "runLink", message: `Run \`${getCliName()} link\` in the current folder to pick a project now?`, initial: true, }); if (!runLink) { throw new Error( "Aborted: no project selected. Re-run with --project-id or link a project first.", ); } await linkHandler({ ...props, yes: false, clear: false, checks: true, }); const linked = readContextFile(props.contextFile); if (!linked.projectId) { throw new Error( `Linking did not produce a project id. Re-run \`${getCliName()} checkout\` once the directory is linked.`, ); } // Carry the freshly-linked org id forward so the merge below keeps it. if (linked.orgId) { props.orgId = linked.orgId; } return linked.projectId; }; /** * Best-effort single-project auto-detection. Returns the project id when the * API key maps to exactly one project, or `undefined` when the project can't be * determined unambiguously (zero or multiple projects) so the caller can fall * back to the interactive `link` flow. */ const tryAutoDetectProject = async ( props: CheckoutProps, ): Promise => { try { const filled = await fillSingleProject(props); return filled.projectId; } catch (err) { // `fillSingleProject` throws on "No projects found" / "Multiple projects // found" — both mean we can't pick a project automatically. Network/auth // errors are real and should surface to the user, and so does a project-scoped // key, which `link` cannot help with because it cannot list projects either. if (isNeonApiError(err) || err instanceof ProjectNotLinkedError) { throw err; } log.debug( "checkout: could not auto-detect a single project: %s", err instanceof Error ? err.message : String(err), ); return undefined; } };