writeRepository

tcmts.dev.writeRepository · #5vqhev63 · term · runs on the server

uses node:fs

Write the files tcm's repository keeps (pnpm repository) as the codebase has them: what's in git is only how to get the codebase (its script, the agents' instructions, the README), and it's changed in the codebase like anything else. Says which changed; commit them by hand.

import { codebaseDir, repository, REPOSITORY_FILES, sh } from "#codebase/tcmts/dev";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

export function writeRepository(): void {
  const tcm = process.env.TCM_BIN;
  if (!tcm)
    throw new Error("run this with `tcm run`, which gives it the codebase's own tcm (TCM_BIN)");
  const repo = repository();
  const changed: string[] = [];
  for (const [name, rel] of Object.entries(REPOSITORY_FILES)) {
    const out = fs.mkdtempSync(path.join(os.tmpdir(), "tcm repository "));
    const r = sh(process.execPath, [tcm, "export", name, out], codebaseDir());
    const [written] = fs.readdirSync(out);
    if (!r.ok || !written) throw new Error(`tcm export ${name}: ${r.out.trim()}`);
    const content = fs.readFileSync(path.join(out, written));
    const to = path.join(repo, rel);
    if (!fs.existsSync(to) || !fs.readFileSync(to).equals(content)) {
      fs.mkdirSync(path.dirname(to), { recursive: true });
      fs.writeFileSync(to, content, { mode: rel.endsWith(".sh") ? 0o755 : 0o644 });
      changed.push(rel);
    }
    fs.rmSync(out, { recursive: true, force: true });
  }
  console.log(
    changed.length
      ? `wrote ${changed.join(", ")}`
      : "the repository's files are as the codebase has them",
  );
}

uses