diffDefinitions

tcmts.cli.merge.diffDefinitions · #7fbxxitc · term · runs on the server

uses tcmts.cli.files.fileContent, which uses Buffer

tcm diff #a #b, or of a conflicted name: definitions' code as tcm view shows it (what they use by its name here, or elsewhere), compared line by line, each pair under its title, with two lines of context around what changed.

import type { Codebase } from "#codebase/tcmts/cli/codebase";
import { lineDiff } from "#codebase/tcmts/cli/diff";
import { fileContent, formatOf, isBytes } from "#codebase/tcmts/cli/files";
import { namesElsewhere } from "#codebase/tcmts/cli/merge";
import { bold, dim, green, red } from "#codebase/tcmts/cli/style";
import { render } from "#codebase/tcmts/loader";

export function diffDefinitions(
  cb: Codebase,
  pairs: { from: string; to: string; title: string }[],
): void {
  const src = cb.source();
  const elsewhere = namesElsewhere(cb);
  const nameOf = (h: string) => src.nameOf(h) ?? elsewhere(h)?.name;
  const lines = (h: string) => {
    const rec = cb.store.getDef(h)!;
    if (rec.kind === "file") {
      const at = nameOf(h) ?? "";
      const content = fileContent(cb, rec, at.slice(0, Math.max(0, at.lastIndexOf("."))));
      return isBytes(rec)
        ? [`(${formatOf(rec) || "bytes"}, ${content.length} bytes)`]
        : content.toString("utf8").trimEnd().split("\n");
    }
    return render([rec], src, cb.lay, {
      style: "scratch",
      omitImports: true,
      exportDeclarations: true,
      nameOf,
    })
      .text.trimEnd()
      .split("\n");
  };
  pairs.forEach((p, i) => {
    if (i) console.log();
    console.log(bold(p.title));
    const d = lineDiff(lines(p.from), lines(p.to));
    if (d.every(([op]) => op === " ")) return console.log(dim("  the same code"));
    d.forEach(([op, line], k) => {
      const near = d.slice(Math.max(0, k - 2), k + 3).some(([o]) => o !== " ");
      if (op === " " && !near) {
        if (d[k - 1]?.[0] !== " " || k === 0) console.log(dim("    ⋮"));
        return;
      }
      console.log(
        op === "-" ? red(`  - ${line}`) : op === "+" ? green(`  + ${line}`) : dim(`    ${line}`),
      );
    });
  });
}

uses

used by