Skip to content
Myr

git.ts

This file

Path

apps/web/src/dev/git.ts

362 lines · 9.9 KiB · TypeScript

Last changed by

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

History of this file

Take it

The walk stopped after 200 commits: lines older than 1e46e9a point at it.

Fill the README's numbers from the live swarm and core-loop runs on dev-oscabriel, and record their throwawaysoscabrielbefore adoption1e46e9a

lines 1–112why, one step back
1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";
2import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";3import { Brand } from "@repo/brand";4import { BlobSha, CommitSha } from "@repo/protocol/ids";5import type { Handle, RepoName } from "@repo/protocol/ids";6import { Array, DateTime, Effect, Option, Predicate } from "effect";78export type Files = ReadonlyMap<string, string>;910export interface Held {11 readonly blob: BlobSha;12 readonly text: string;13}1415export type Snapshot = ReadonlyMap<string, Held>;1617export interface Identity {18 readonly email: string;19 readonly name: string;20}2122export const platformIdentity: Identity = {23 email: `platform@${Brand.domain}`,24 name: Brand.name,25};2627export const personIdentity = (handle: Handle): Identity => ({28 email: `${handle}@users.${Brand.domain}`,29 name: handle,30});3132export const textOf = (snapshot: Snapshot): Files =>33 new Map([...snapshot].map(([path, { text }]) => [path, text]));3435export const overlay = (36 files: Files,37 changed: Iterable<readonly [string, string]>38): Files => new Map([...files, ...changed]);3940const encoder = new TextEncoder();4142const decoder = new TextDecoder();4344const concat = (parts: readonly Uint8Array[]) => {45 const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));46 let at = 0;4748 for (const part of parts) {49 all.set(part, at);50 at += part.byteLength;51 }5253 return all;54};5556const hex = (bytes: ArrayBuffer) =>57 [...new Uint8Array(bytes)]58 .map((byte) => byte.toString(16).padStart(2, "0"))59 .join("");6061const bytesOfHex = (id: string) =>62 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));6364const deflate = (bytes: Uint8Array) =>65 Effect.promise(() =>66 new Response(67 new Blob([Uint8Array.from(bytes)])68 .stream()69 .pipeThrough(new CompressionStream("deflate"))70 ).arrayBuffer()71 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));7273const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {74 const raw = concat([75 encoder.encode(`${kind} ${content.byteLength}\0`),76 content,77 ]);7879 return Effect.map(80 Effect.promise(() => crypto.subtle.digest("SHA-1", raw)),81 (digest) => ({ id: hex(digest), raw })82 );83};8485const sortKey = (entry: TreeEntry) =>86 encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);8788// git sorts a tree's entries by name, a subtree's name as if it ended in "/".89const treeOrder = (one: TreeEntry, other: TreeEntry) => {90 const left = sortKey(one);91 const right = sortKey(other);9293 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {94 const diff = (left[at] ?? 0) - (right[at] ?? 0);9596 if (diff !== 0) {97 return diff;98 }99 }100101 return left.length - right.length;102};103104const treeBytes = (entries: readonly TreeEntry[]) =>105 concat(106 entries.toSorted(treeOrder).flatMap((entry) => [107 // A tree object spells a subtree's mode without its leading zero.108 encoder.encode(`${entry.mode.replace(/^0/u, "")} ${entry.name}\0`),109 bytesOfHex(entry.sha),110 ])111 );112

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

lines 113–114why, one step back
113// No carriage returns, no leading blank lines, one trailing newline: isomorphic-git writes it back so when the
114// memory host copies the commit, and the id must not change.

Fill the README's numbers from the live swarm and core-loop runs on dev-oscabriel, and record their throwawaysoscabrielbefore adoption1e46e9a

lines 115–362why, one step back
115const messageOf = (message: string) =>
116 `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;117118const signature = (who: Identity, at: DateTime.Utc) =>119 `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;120121export interface CommitInput {122 readonly tree: ObjectId;123 readonly parents: readonly CommitSha[];124 readonly author: Identity;125 readonly committer: Identity;126 readonly at: DateTime.Utc;127 readonly message: string;128}129130const commitBytes = (input: CommitInput) =>131 encoder.encode(132 [133 `tree ${input.tree}`,134 ...input.parents.map((parent) => `parent ${parent}`),135 `author ${signature(input.author, input.at)}`,136 `committer ${signature(input.committer, input.at)}`,137 "",138 messageOf(input.message),139 ].join("\n")140 );141142const failure = (code: string, path: string) =>143 Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));144145const clean = (path: string) =>146 `/${path147 .split("/")148 .filter((part) => part !== "")149 .join("/")}`;150151type ReadOptions = string | { readonly encoding?: string } | undefined;152153const UTF8 = /^utf-?8$/iu;154155const wantsText = (options: ReadOptions) =>156 Predicate.isString(options)157 ? UTF8.test(options)158 : UTF8.test(options?.encoding ?? "");159160const readOnly = (raw: string) => failure("EROFS", clean(raw));161162const stats = (kind: "file" | "dir", size: number) => ({163 ctimeMs: 0,164 dev: 1,165 gid: 1,166 ino: 0,167 isDirectory: () => kind === "dir",168 isFile: () => kind === "file",169 isSymbolicLink: () => false,170 mode: kind === "dir" ? 0o4_0000 : 0o10_0644,171 mtimeMs: 0,172 size,173 uid: 1,174});175176const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {177 const childrenOf = (dir: string) => {178 const prefix = dir === "/" ? "/" : `${dir}/`;179180 return Array.dedupe(181 [...files.keys()].flatMap((path) =>182 path.startsWith(prefix)183 ? [path.slice(prefix.length).split("/")[0] ?? ""]184 : []185 )186 );187 };188189 const stat = (raw: string) => {190 const path = clean(raw);191 const file = files.get(path);192193 if (file !== undefined) {194 return Promise.resolve(stats("file", file.byteLength));195 }196197 return childrenOf(path).length > 0198 ? Promise.resolve(stats("dir", 0))199 : failure("ENOENT", path);200 };201202 return {203 promises: {204 lstat: stat,205 mkdir: readOnly,206 // isomorphic-git may call it with no path to learn whether this fs207 // returns promises, so that call answers with a rejected promise.208 readFile: (raw?: string, options?: ReadOptions) => {209 const path = clean(raw ?? "");210 const file = files.get(path);211212 if (file === undefined) {213 return failure(214 childrenOf(path).length > 0 ? "EISDIR" : "ENOENT",215 path216 );217 }218219 return Promise.resolve(220 wantsText(options) ? decoder.decode(file) : file221 );222 },223 readdir: (raw: string) => {224 const path = clean(raw);225 const children = childrenOf(path);226227 return children.length > 0228 ? Promise.resolve(children)229 : failure("ENOENT", path);230 },231 readlink: (raw: string) => failure("EINVAL", clean(raw)),232 rmdir: readOnly,233 stat,234 symlink: (_target: string, raw: string) => failure("ENOSYS", clean(raw)),235 unlink: readOnly,236 writeFile: readOnly,237 },238 };239};240241export interface Scratch {242 readonly source: PushSource;243 readonly tree: (files: Files) => Effect.Effect<ObjectId>;244 readonly commit: (input: CommitInput) => Effect.Effect<CommitSha>;245}246247const GITDIR = "/scratch.git";248249export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {250 const objects = new Map<string, Uint8Array>();251252 const write = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>253 Effect.gen(function* () {254 const { id, raw } = yield* framed(kind, content);255 const path = `${GITDIR}/objects/${id.slice(0, 2)}/${id.slice(2)}`;256257 if (!objects.has(path)) {258 objects.set(path, yield* deflate(raw));259 }260261 return ObjectId.make(id);262 });263264 const folder = (265 files: readonly (readonly [string, string])[]266 ): Effect.Effect<ObjectId> =>267 Effect.gen(function* () {268 const blobs = files.filter(([path]) => !path.includes("/"));269270 const nested = Array.groupBy(271 files.filter(([path]) => path.includes("/")),272 ([path]) => path.slice(0, path.indexOf("/"))273 );274275 const blobEntries = yield* Effect.forEach(blobs, ([name, text]) =>276 Effect.map(write("blob", encoder.encode(text)), (sha): TreeEntry => ({277 mode: "100644",278 name,279 sha,280 type: "blob",281 }))282 );283284 const treeEntries = yield* Effect.forEach(285 Object.entries(nested),286 ([name, inside]) =>287 Effect.map(288 folder(289 inside.map(290 ([path, text]) => [path.slice(name.length + 1), text] as const291 )292 ),293 (sha): TreeEntry => ({ mode: "040000", name, sha, type: "tree" })294 )295 );296297 return yield* write("tree", treeBytes([...blobEntries, ...treeEntries]));298 });299300 return {301 commit: (input) =>302 Effect.map(write("commit", commitBytes(input)), (id) =>303 CommitSha.make(id)304 ),305 source: { fs: readOnlyFs(objects), gitdir: GITDIR },306 tree: (files) => folder([...files]),307 };308});309310const fileOf =311 (path: string, blob: ObjectId) =>312 (bytes: Uint8Array): Snapshot =>313 new Map([314 [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],315 ]);316317const snapshotOf = (318 repo: RepoName,319 tree: ObjectId,320 prefix: string321): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>322 Effect.gen(function* () {323 const host = yield* RepoHost;324 const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);325326 if (Option.isNone(entries)) {327 return Option.none();328 }329330 const each = yield* Effect.forEach(entries.value, (entry) => {331 const path = `${prefix}${entry.name}`;332333 if (entry.type === "tree") {334 return snapshotOf(repo, entry.sha, `${path}/`);335 }336337 return host338 .readBlob(repo, entry.sha)339 .pipe(Effect.orDie, Effect.map(Option.map(fileOf(path, entry.sha))));340 });341342 return Option.map(343 Option.all(each),344 (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))345 );346 });347348export const filesAt = (349 repo: RepoName,350 commit: CommitSha351): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>352 Effect.gen(function* () {353 const host = yield* RepoHost;354355 const found = yield* host356 .readCommit(repo, commit)357 .pipe(Effect.orElseSucceed(() => Option.none()));358359 return Option.isNone(found)360 ? Option.none()361 : yield* snapshotOf(repo, found.value.tree, "");362 });