- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/gitview/tree.ts?version=110&format=json
165 linesFirst import 99% · pinch 1%Last change pinch in version 78, 2 versions changed it
You're reading version 110. The newest is 318, and no version since then changed this file.
1// Git trees as plain files (path -> text), read and written with
2// isomorphic-git. Only text files can be made of atoms' lines; every other
3// tree entry is listed as skipped with the reason.
5import fs from "node:fs";
6import { readBlob, readTree, type TreeEntry, writeBlob, writeTree } from "isomorphic-git";
7import { GitViewError } from "./errors.ts";
8import { decodeBlob } from "./plain.ts";
10/** What every isomorphic-git call here needs: the file system, the repo, and a shared object cache. */
11export interface GitContext {
12 readonly fs: typeof fs;
13 readonly dir: string;
14 /** isomorphic-git's cache for parsed objects; reuse one per repo per operation. */
15 readonly cache: object;
16}
18export function gitContext(dir: string): GitContext {
19 return { fs, dir, cache: {} };
20}
22/** Why a tree entry is not a text file of the projection. */
23export type SkipReason =
24 /** 0 bytes: a file exists in a projection only while it has a line. */
25 | "empty"
26 /** A NUL byte in the first 8000 bytes (git's own test), or not valid UTF-8. */
27 | "binary"
28 | "symlink"
29 | "submodule"
30 /** A path the engine can't hold (it has a line break in it). */
31 | "unsupported-path";
33export interface SkippedEntry {
34 readonly path: string;
35 readonly reason: SkipReason;
36 /** The blob (or submodule commit) id, so a caller can tell when it changed. */
37 readonly oid: string;
38}
40export interface TreeFiles {
41 /** Text files, path -> canonical text ("\n" line endings, a final newline). */
42 readonly files: Map<string, string>;
43 readonly skipped: SkippedEntry[];
44}
46const MODE_TREE = "040000";
47const MODE_FILE = "100644";
48const MODE_LINK = "120000";
49const MODE_SUBMODULE = "160000";
51const ENCODE = new TextEncoder();
53export { decodeBlob };
55/** Every file of a tree, recursively. Paths use "/". */
56export async function readTreeFiles(ctx: GitContext, treeOid: string): Promise<TreeFiles> {
57 const files = new Map<string, string>();
58 const skipped: SkippedEntry[] = [];
59 const visit = async (oid: string, prefix: string): Promise<void> => {
60 const { tree } = await readTree({ fs: ctx.fs, dir: ctx.dir, oid, cache: ctx.cache });
61 for (const entry of tree) {
62 const path = prefix + entry.path;
63 if (entry.mode === MODE_TREE) {
64 await visit(entry.oid, `${path}/`);
65 } else if (entry.mode === MODE_SUBMODULE) {
66 skipped.push({ path, reason: "submodule", oid: entry.oid });
67 } else if (entry.mode === MODE_LINK) {
68 skipped.push({ path, reason: "symlink", oid: entry.oid });
69 } else if (/[\n\r]/.test(path)) {
70 skipped.push({ path, reason: "unsupported-path", oid: entry.oid });
71 } else {
72 const { blob } = await readBlob({ fs: ctx.fs, dir: ctx.dir, oid: entry.oid, cache: ctx.cache });
73 const decoded = decodeBlob(blob);
74 if ("text" in decoded) files.set(path, decoded.text);
75 else skipped.push({ path, reason: decoded.reason, oid: entry.oid });
76 }
77 }
78 };
79 await visit(treeOid, "");
80 skipped.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
81 return { files, skipped };
82}
84/** Object ids already written in this repo, so repeated trees and blobs are hashed once. */
85export interface WriteCache {
86 readonly blobs: Map<string, string>;
87 readonly trees: Map<string, string>;
88}
90export function writeCache(): WriteCache {
91 return { blobs: new Map(), trees: new Map() };
92}
94interface DirNode {
95 readonly files: Map<string, string>;
96 readonly dirs: Map<string, DirNode>;
97}
99/**
100 * Write files (path -> text) as a git tree and return its id. Every file is a
101 * plain 100644 blob. Throws `bad-path` for a path git can't hold: an empty
102 * part, ".", "..", ".git", or a name that is both a file and a directory.
103 */
104export async function writeFilesTree(
105 ctx: GitContext,
106 files: Readonly<Record<string, string>>,
107 cache: WriteCache,
108): Promise<string> {
109 const root: DirNode = { files: new Map(), dirs: new Map() };
110 for (const path of Object.keys(files).sort()) {
111 const parts = path.split("/");
112 for (const part of parts) {
113 if (part === "" || part === "." || part === ".." || part.toLowerCase() === ".git" || part.includes("\0")) {
114 throw new GitViewError("bad-path", `${JSON.stringify(path)} can't be a path in a git tree`);
115 }
116 }
117 let node = root;
118 for (const part of parts.slice(0, -1)) {
119 if (node.files.has(part)) throw new GitViewError("bad-path", `${path}: ${part} is both a file and a directory`);
120 let next = node.dirs.get(part);
121 if (!next) {
122 next = { files: new Map(), dirs: new Map() };
123 node.dirs.set(part, next);
124 }
125 node = next;
126 }
127 const name = parts[parts.length - 1]!;
128 if (node.dirs.has(name)) throw new GitViewError("bad-path", `${path} is both a file and a directory`);
129 node.files.set(name, files[path]!);
130 }
131 return writeDir(ctx, root, cache);
132}
134async function writeDir(ctx: GitContext, node: DirNode, cache: WriteCache): Promise<string> {
135 const entries: TreeEntry[] = [];
136 for (const [name, text] of node.files) {
137 let oid = cache.blobs.get(text);
138 if (oid === undefined) {
139 oid = await writeBlob({ fs: ctx.fs, dir: ctx.dir, blob: ENCODE.encode(text) });
140 cache.blobs.set(text, oid);
141 }
142 entries.push({ mode: MODE_FILE, path: name, oid, type: "blob" });
143 }
144 for (const [name, child] of node.dirs) {
145 entries.push({ mode: MODE_TREE, path: name, oid: await writeDir(ctx, child, cache), type: "tree" });
146 }
147 // isomorphic-git sorts entries the way git does; the key only needs to be stable.
148 const key = entries
149 .map((e) => `${e.mode} ${e.oid} ${e.path}`)
150 .sort()
151 .join("\n");
152 let oid = cache.trees.get(key);
153 if (oid === undefined) {
154 oid = await writeTree({ fs: ctx.fs, dir: ctx.dir, tree: entries });
155 cache.trees.set(key, oid);
156 }
157 return oid;
158}
160/** Whether two path -> text collections hold exactly the same files. */
161export function sameFiles(a: ReadonlyMap<string, string>, b: Readonly<Record<string, string>>): boolean {
162 const keys = Object.keys(b);
163 if (keys.length !== a.size) return false;
164 return keys.every((k) => a.get(k) === b[k]);
165}