linkMirror

tcmts.cli.mirror.linkMirror · #kkgtdqr7 · term · runs on the server

uses node:path

Record that into mirrors dir: each file's namespace, content and definitions as they are now. Following the files, it records what they hold (held, by path) as of the log they were last written at, so what the codebase changed meanwhile is written to them at the next sync.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { fileLeaf } from "#codebase/tcmts/cli/files";
import {
  assetFiles, assetName, declarations, joinName, namesIn, namespaceForFile, saveMirror, sha, sourceFiles,
} from "#codebase/tcmts/cli/mirror";
import type { MirrorFile } from "#codebase/tcmts/cli/mirror";
import fs from "node:fs";
import path from "node:path";

export function linkMirror(cb: Codebase, dir: string, into: string, tests: boolean, exclude: string[], following?: { log: number; held: Map<string, string> }) {
  const root = path.resolve(dir);
  const files: Record<string, MirrorFile> = {};
  for (const f of sourceFiles(root, new Set(exclude.map((e) => path.resolve(root, e))), tests)) {
    const ns = joinName(into, namespaceForFile(root, f));
    const text = fs.readFileSync(f, "utf8");
    // what the file declares (the codebase may have more, made while write-back waited: written at the next sync)
    const inCodebase = namesIn(cb, ns);
    const names: Record<string, string> = {};
    for (const leaf of declarations(f, text).keys()) if (inCodebase[leaf]) names[leaf] = following?.held.get(joinName(ns, leaf)) ?? inCodebase[leaf];
    files[path.relative(root, f)] = { ns, sha: sha(text), names };
  }
  // and the files of the codebase that aren't code: each a name in its directory's namespace
  for (const f of assetFiles(root, new Set(exclude.map((e) => path.resolve(root, e))))) {
    const name = assetName(root, into, f);
    const h = following?.held.get(name) ?? cb.store.hashesAt(name).find((x) => cb.store.getDef(x)?.kind === "file");
    files[path.relative(root, f)] = { ns: name.slice(0, name.lastIndexOf(".")), sha: sha(fs.readFileSync(f, "utf8")), names: h ? { [fileLeaf(f)]: h } : {} };
  }
  saveMirror(cb, { dir: root, into, tests, exclude, log: following?.log ?? cb.store.logHead(), files, branch: cb.store.branch().name });
}

uses

used by