testCheckImportsWhatItUses

tcmts.cli.test.e2e.editing.testCheckImportsWhatItUses · #gthgui6r · term

tcm check imports what a scratch file uses and doesn't import, as saving it would, and writes them into it: a codebase name, a name a module it imports from already exports (join), an alias the codebase's code imports by (path_basename), a Node builtin (randomUUID). An import nothing uses it leaves (code using it may be still to be written), saying saving takes it out.

import { okIn, tcmIn, tempDir } from "#codebase/tcmts/cli/test/e2e/harness";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";

export const testCheckImportsWhatItUses = () => {
  const dir = tempDir("check imports");
  const ok = (...args: string[]) => okIn(dir, ...args);
  ok("init");
  const write = (f: string, text: string) => fs.writeFileSync(path.join(dir, f), text);
  write(
    "scratch.ts",
    `// tcm: namespace lib\nimport { basename as path_basename } from "node:path";\n` +
      `export const base = (p: string): string => path_basename(p);\nexport const twice = (n: number): number => n * 2;\n`,
  );
  ok("update");
  write(
    "app.ts",
    `// tcm: namespace app\nimport { dirname } from "node:path";\nimport { cpus } from "node:os";\n\n` +
      `export const g = (p: string): string =>\n  dirname(path_basename(join(p, "x"))) + twice(2) + randomUUID().length;\n`,
  );
  const out = ok("check", "app.ts");
  assert.match(out, /\+ new +app\.g/, out);
  assert.match(out, /nothing uses cpus: saving takes that import out/, out);
  const text = fs.readFileSync(path.join(dir, "app.ts"), "utf8");
  for (const line of [
    /import \{[^}]*\bbasename as path_basename\b[^}]*\} from "node:path";/,
    /import \{[^}]*\bjoin\b[^}]*\} from "node:path";/,
    /import \{ twice \} from "#codebase\/lib";/,
    /import \{ randomUUID \} from "node:crypto";/,
    /import \{ cpus \} from "node:os";/,
  ])
    assert.match(text, line, text);
  // (checked again, it has them: nothing more)
  assert.doesNotMatch(ok("check", "app.ts"), /^ +import /m);
  assert.equal(tcmIn(dir, "update", "app.ts").status, 0);
}

uses