- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/gitview/test/helpers.ts?format=json
164 linesFirst import 100%Last change First import in version 0, 1 version changed it
1// Test helpers for the git view: temp dirs, a person using the git CLI with an
2// isolated config, and readers for commit trees and working trees.
4import { execFileSync } from "node:child_process";
5import fs from "node:fs";
6import os from "node:os";
7import path from "node:path";
8import { readCommit, resolveRef } from "isomorphic-git";
9import { canonicalText } from "../../engine/index.ts";
10import { gitContext, readTreeFiles } from "../index.ts";
12const made: string[] = [];
14/** A fresh empty temp directory, removed by `cleanup()`. */
15export function tempDir(name = "gitview"): string {
16 const dir = fs.mkdtempSync(path.join(os.tmpdir(), `${name}-`));
17 made.push(dir);
18 return dir;
19}
21/** A path inside a fresh temp directory that doesn't exist yet. */
22export function freshPath(name = "repo"): string {
23 return path.join(tempDir(), name);
24}
26export function cleanup(): void {
27 for (const dir of made.splice(0)) fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 });
28}
30// An empty global config, so the person's git ignores the machine's settings
31// (autocrlf, hooks, LFS filters, signing).
32let emptyConfig: string | undefined;
33function gitEnv(extra: Record<string, string>): NodeJS.ProcessEnv {
34 if (emptyConfig === undefined) {
35 emptyConfig = path.join(tempDir("gitconfig"), "config");
36 fs.writeFileSync(emptyConfig, "");
37 }
38 return { ...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: emptyConfig, ...extra };
39}
41/** Run git in `cwd` and return its stdout. */
42export function git(cwd: string, args: readonly string[], env: Record<string, string> = {}): string {
43 return execFileSync("git", ["-c", "core.autocrlf=false", ...args], {
44 cwd,
45 env: gitEnv(env),
46 encoding: "utf8",
47 stdio: ["ignore", "pipe", "pipe"],
48 });
49}
51/** Someone with ordinary git: clones a view, edits files, commits. */
52export class Person {
53 readonly name: string;
54 readonly email: string;
55 readonly dir: string;
56 /** Seconds since the epoch; each commit is one minute after the last. */
57 #clock: number;
59 constructor(name: string, dir: string, start = 1_700_000_000) {
60 this.name = name;
61 this.email = `${name.toLowerCase()}@example.com`;
62 this.dir = dir;
63 this.#clock = start;
64 }
66 static clone(name: string, from: string, start?: number): Person {
67 const dir = freshPath("clone");
68 git(path.dirname(dir), ["clone", "--quiet", from, dir]);
69 return new Person(name, dir, start);
70 }
72 write(file: string, text: string | Uint8Array): void {
73 const full = path.join(this.dir, file);
74 fs.mkdirSync(path.dirname(full), { recursive: true });
75 fs.writeFileSync(full, text);
76 }
78 read(file: string): string {
79 return fs.readFileSync(path.join(this.dir, file), "utf8");
80 }
82 /** Replace the 1-based line `n` of a file. */
83 setLine(file: string, n: number, text: string): void {
84 const lines = this.read(file).split("\n");
85 lines[n - 1] = text;
86 this.write(file, lines.join("\n"));
87 }
89 remove(file: string): void {
90 git(this.dir, ["rm", "--quiet", file]);
91 }
93 /** Stage everything and commit. Returns the new commit's sha. */
94 commit(message: string): string {
95 return this.#commit(["-m", message]);
96 }
98 /** Stage everything and amend the last commit, keeping its message. */
99 amend(): string {
100 return this.#commit(["--amend", "--no-edit"]);
101 }
103 #commit(args: readonly string[]): string {
104 const date = `${this.#clock} +0000`;
105 this.#clock += 60;
106 git(this.dir, ["add", "--all"]);
107 git(this.dir, ["commit", "--quiet", "--allow-empty", ...args], {
108 GIT_AUTHOR_NAME: this.name,
109 GIT_AUTHOR_EMAIL: this.email,
110 GIT_AUTHOR_DATE: date,
111 GIT_COMMITTER_NAME: this.name,
112 GIT_COMMITTER_EMAIL: this.email,
113 GIT_COMMITTER_DATE: date,
114 });
115 return this.head();
116 }
118 head(): string {
119 return git(this.dir, ["rev-parse", "HEAD"]).trim();
120 }
122 /** The author time of the last commit, in ms. */
123 lastTime(): number {
124 return (this.#clock - 60) * 1000;
125 }
126}
128/** Text files of a commit (path -> canonical text), read with isomorphic-git. */
129export async function commitFiles(dir: string, ref: string): Promise<Record<string, string>> {
130 const ctx = gitContext(dir);
131 const oid = await resolveRef({ fs, dir, ref });
132 const { commit } = await readCommit({ fs, dir, oid });
133 const { files } = await readTreeFiles(ctx, commit.tree);
134 return Object.fromEntries([...files.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
135}
137/** Text files of a working tree (path -> canonical text), skipping .git and empty or binary files. */
138export function workingFiles(dir: string): Record<string, string> {
139 const out: Record<string, string> = {};
140 const walk = (rel: string): void => {
141 for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
142 const name = rel === "" ? entry.name : `${rel}/${entry.name}`;
143 if (entry.name === ".git") continue;
144 if (entry.isDirectory()) walk(name);
145 else {
146 const bytes = fs.readFileSync(path.join(dir, name));
147 if (bytes.length === 0 || bytes.includes(0)) continue;
148 out[name] = canonicalText(bytes.toString("utf8"));
149 }
150 }
151 };
152 walk("");
153 return Object.fromEntries(Object.entries(out).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
154}
156/** Sort a path -> text record by path (so deepEqual compares content, not key order). */
157export function sorted(files: Readonly<Record<string, string>>): Record<string, string> {
158 return Object.fromEntries(Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
159}
161/** Numbered lines "<prefix> 1" .. "<prefix> n", as file text. */
162export function numbered(prefix: string, n: number): string {
163 return Array.from({ length: n }, (_, i) => `${prefix} ${i + 1}\n`).join("");
164}