runBranch

tcmts.cli.run.runBranch · #gxb6smse · term · runs on the server

uses node:fs

Runs tcm branch.

import { sessionDirFor, sessionDirsGone, unsavedIn } from "#codebase/tcmts/cli/codebase";
import { routeBranch } from "#codebase/tcmts/cli/commands";
import { execute } from "#codebase/tcmts/cli/main";
import { liveMcpServers } from "#codebase/tcmts/cli/mcp";
import type { Context } from "#codebase/tcmts/cli/run";
import { dim, green } from "#codebase/tcmts/cli/style";
import { shownPath } from "#codebase/tcmts/cli/ui";
import { parse } from "@bomb.sh/router";
import fs from "node:fs";

export function runBranch({ cb, cmd, rest }: Context): number {
  const { model } = execute(cmd, parse(routeBranch(), { argv: rest }));
  if (!model.branch) {
    for (const b of cb.store.branches())
      console.log(`${b === cb.store.branch().name ? green("* ") : "  "}${b}`);
    return 0;
  }
  if (model.delete) {
    // (asked in the write transaction servers claim their branches in: none claims it meanwhile)
    cb.store.transaction(() => {
      const on = liveMcpServers(cb.lay.root).find((s) => s.branch === model.branch);
      if (on)
        throw new Error(
          `a session's server (process ${on.pid}) works on ${model.branch}: it goes with the session when that stops, or stop it first`,
        );
      cb.store.deleteBranch(model.branch!);
    });
    // its session's directory goes with it, unless a scratch file there holds unsaved work
    const [dir] = sessionDirsGone(cb.lay.root, cb.store.branches()).filter(
      (d) => d === sessionDirFor(cb.lay.root, model.branch!),
    );
    const unsaved = dir ? unsavedIn(dir) : [];
    if (dir && !unsaved.length) fs.rmSync(dir, { recursive: true, force: true });
    console.log(
      `deleted branch ${model.branch}${unsaved.length ? dim(`; its session's directory stays, holding unsaved work: ${unsaved.map((f) => shownPath(f)).join(", ")}`) : ""}`,
    );
    return 0;
  }
  cb.store.createBranch(model.branch);
  console.log(`created branch ${model.branch} from ${cb.store.branch().name}`);
  return 0;
}

uses

used by