ShtukbaseStandard
package file→ .shtukbase/packages/lenses/kit/src/code.js

kit/src/code.js

107 lines, 4.7 KB.

  1. // Facts about the code for the lens layers: how many files and tests are in the folders of a record (`repoPaths`),
  2. // when they were last changed in git, and whether the code has a table with the name from the field `code`.
  3. // The code is looked for next to the base: the base lies inside a repository, the paths in `repoPaths` are from the root of the base.
  4. import fs from "node:fs";
  5. import path from "node:path";
  6. import { execFileSync } from "node:child_process";
  7. const SKIP = new Set(["node_modules", "dist", "build", ".turbo", ".output", ".next", "coverage", ".git", ".vinxi", ".tanstack"]);
  8. const SRC = /\.(ts|tsx|js|jsx|mjs|cjs|css|sql|py|go|rs|vue|svelte)$/;
  9. const TEST = /(\.|_)(test|spec)\.[a-z]+$|(^|\/)(__tests__|tests?|e2e)\//;
  10. // Drizzle tables: pgTable("name", ...), sqliteTable("name", ...), mysqlTable("name", ...)
  11. const TABLE = /\b\w*Table\(\s*["'`]([\w.]+)["'`]/g;
  12. function walk(dir, out) {
  13. let list;
  14. try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return out; }
  15. for (const e of list) {
  16. if (e.name.startsWith(".") && e.name !== ".github") continue;
  17. const p = path.join(dir, e.name);
  18. if (e.isDirectory()) { if (!SKIP.has(e.name)) walk(p, out); }
  19. else if (SRC.test(e.name)) out.push(p);
  20. }
  21. return out;
  22. }
  23. function gitRoot(dir) {
  24. try { return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); }
  25. catch (e) { return null; }
  26. }
  27. function lastCommit(repo, paths) {
  28. try {
  29. const t = execFileSync("git", ["log", "-1", "--format=%cs", "--", ...paths], { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
  30. return t || null;
  31. } catch (e) { return null; }
  32. }
  33. const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []).filter((x) => typeof x === "string");
  34. /** { [id]: { files, tests, lines, last, paths, missing } } for records with repoPaths;
  35. * { [id]: { table: "path/to/file.ts" } } for records with the field code, if such a table is in the code. */
  36. export function codeFacts(root, records) {
  37. const base = path.resolve(root);
  38. const repo = gitRoot(base);
  39. const top = repo || path.dirname(base);
  40. const out = {};
  41. const fileCache = new Map();
  42. const filesOf = (abs) => {
  43. if (!fileCache.has(abs)) {
  44. let st = null;
  45. try { st = fs.statSync(abs); } catch (e) {}
  46. fileCache.set(abs, !st ? null : st.isDirectory() ? walk(abs, []) : [abs]);
  47. }
  48. return fileCache.get(abs);
  49. };
  50. const rel = (p) => path.relative(top, p).split(path.sep).join("/");
  51. for (const [id, r] of Object.entries(records)) {
  52. const paths = asList(r.props && r.props.repoPaths);
  53. if (!paths.length) continue;
  54. let files = 0, tests = 0, lines = 0;
  55. const found = [], missing = [];
  56. for (const p of paths) {
  57. const abs = path.resolve(base, p);
  58. // the base must not look outside its repository
  59. if (!abs.startsWith(top + path.sep) && abs !== top) { missing.push(p); continue; }
  60. const list = filesOf(abs);
  61. if (!list) { missing.push(p); continue; }
  62. found.push(rel(abs));
  63. for (const f of list) {
  64. if (TEST.test(rel(f))) { tests++; continue; }
  65. files++;
  66. try { lines += fs.readFileSync(f, "utf8").split("\n").length; } catch (e) {}
  67. }
  68. }
  69. const o = { files, tests, lines };
  70. if (repo && found.length) { const last = lastCommit(repo, found); if (last) o.last = last; }
  71. if (missing.length) o.missing = missing;
  72. out[id] = o;
  73. }
  74. // tables in the code: one pass over the sources of the repository
  75. const named = Object.entries(records).filter(([, r]) => r.props && typeof r.props.code === "string" && r.props.code);
  76. if (named.length) {
  77. const tables = new Map();
  78. for (const dir of ["apps", "packages", "src", "db"]) {
  79. for (const f of walk(path.join(top, dir), [])) {
  80. if (TEST.test(rel(f))) continue;
  81. let text;
  82. try { text = fs.readFileSync(f, "utf8"); } catch (e) { continue; }
  83. if (!text.includes("Table(")) continue;
  84. for (const m of text.matchAll(TABLE)) {
  85. // the real schema matters more than test stubs with the same name
  86. const prev = tables.get(m[1]);
  87. if (!prev || (!prev.includes("/schema/") && rel(f).includes("/schema/"))) tables.set(m[1], rel(f));
  88. }
  89. }
  90. }
  91. // we say "no table" only for the types where at least one record was found in the code:
  92. // the field code is not always about tables
  93. const tableTypes = new Set(named.filter(([, r]) => tables.has(r.props.code)).map(([, r]) => r.type));
  94. for (const [id, r] of named) {
  95. if (!tableTypes.has(r.type)) continue;
  96. const t = tables.get(r.props.code);
  97. out[id] = Object.assign(out[id] || {}, { table: t || null });
  98. }
  99. }
  100. return out;
  101. }