package file→ .shtukbase/packages/lenses/kit/src/code.js
kit/src/code.js
107 lines, 4.7 KB.
- // Facts about the code for the lens layers: how many files and tests are in the folders of a record (`repoPaths`),
- // when they were last changed in git, and whether the code has a table with the name from the field `code`.
- // 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.
- import fs from "node:fs";
- import path from "node:path";
- import { execFileSync } from "node:child_process";
- const SKIP = new Set(["node_modules", "dist", "build", ".turbo", ".output", ".next", "coverage", ".git", ".vinxi", ".tanstack"]);
- const SRC = /\.(ts|tsx|js|jsx|mjs|cjs|css|sql|py|go|rs|vue|svelte)$/;
- const TEST = /(\.|_)(test|spec)\.[a-z]+$|(^|\/)(__tests__|tests?|e2e)\//;
- // Drizzle tables: pgTable("name", ...), sqliteTable("name", ...), mysqlTable("name", ...)
- const TABLE = /\b\w*Table\(\s*["'`]([\w.]+)["'`]/g;
- function walk(dir, out) {
- let list;
- try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return out; }
- for (const e of list) {
- if (e.name.startsWith(".") && e.name !== ".github") continue;
- const p = path.join(dir, e.name);
- if (e.isDirectory()) { if (!SKIP.has(e.name)) walk(p, out); }
- else if (SRC.test(e.name)) out.push(p);
- }
- return out;
- }
- function gitRoot(dir) {
- try { return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd: dir, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); }
- catch (e) { return null; }
- }
- function lastCommit(repo, paths) {
- try {
- const t = execFileSync("git", ["log", "-1", "--format=%cs", "--", ...paths], { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
- return t || null;
- } catch (e) { return null; }
- }
- const asList = (v) => (Array.isArray(v) ? v : v ? [v] : []).filter((x) => typeof x === "string");
- /** { [id]: { files, tests, lines, last, paths, missing } } for records with repoPaths;
- * { [id]: { table: "path/to/file.ts" } } for records with the field code, if such a table is in the code. */
- export function codeFacts(root, records) {
- const base = path.resolve(root);
- const repo = gitRoot(base);
- const top = repo || path.dirname(base);
- const out = {};
- const fileCache = new Map();
- const filesOf = (abs) => {
- if (!fileCache.has(abs)) {
- let st = null;
- try { st = fs.statSync(abs); } catch (e) {}
- fileCache.set(abs, !st ? null : st.isDirectory() ? walk(abs, []) : [abs]);
- }
- return fileCache.get(abs);
- };
- const rel = (p) => path.relative(top, p).split(path.sep).join("/");
- for (const [id, r] of Object.entries(records)) {
- const paths = asList(r.props && r.props.repoPaths);
- if (!paths.length) continue;
- let files = 0, tests = 0, lines = 0;
- const found = [], missing = [];
- for (const p of paths) {
- const abs = path.resolve(base, p);
- // the base must not look outside its repository
- if (!abs.startsWith(top + path.sep) && abs !== top) { missing.push(p); continue; }
- const list = filesOf(abs);
- if (!list) { missing.push(p); continue; }
- found.push(rel(abs));
- for (const f of list) {
- if (TEST.test(rel(f))) { tests++; continue; }
- files++;
- try { lines += fs.readFileSync(f, "utf8").split("\n").length; } catch (e) {}
- }
- }
- const o = { files, tests, lines };
- if (repo && found.length) { const last = lastCommit(repo, found); if (last) o.last = last; }
- if (missing.length) o.missing = missing;
- out[id] = o;
- }
- // tables in the code: one pass over the sources of the repository
- const named = Object.entries(records).filter(([, r]) => r.props && typeof r.props.code === "string" && r.props.code);
- if (named.length) {
- const tables = new Map();
- for (const dir of ["apps", "packages", "src", "db"]) {
- for (const f of walk(path.join(top, dir), [])) {
- if (TEST.test(rel(f))) continue;
- let text;
- try { text = fs.readFileSync(f, "utf8"); } catch (e) { continue; }
- if (!text.includes("Table(")) continue;
- for (const m of text.matchAll(TABLE)) {
- // the real schema matters more than test stubs with the same name
- const prev = tables.get(m[1]);
- if (!prev || (!prev.includes("/schema/") && rel(f).includes("/schema/"))) tables.set(m[1], rel(f));
- }
- }
- }
- // we say "no table" only for the types where at least one record was found in the code:
- // the field code is not always about tables
- const tableTypes = new Set(named.filter(([, r]) => tables.has(r.props.code)).map(([, r]) => r.type));
- for (const [id, r] of named) {
- if (!tableTypes.has(r.type)) continue;
- const t = tables.get(r.props.code);
- out[id] = Object.assign(out[id] || {}, { table: t || null });
- }
- }
- return out;
- }