Skip to content
Myr

git.ts

This file

Path

apps/web/src/dev/git.ts

407 lines · 12.2 KiB · TypeScript

Last changed by

Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e

History of this file

Take it

1/**2 * Git for the dev world: commits written the way git writes them, so the3 * memory repo host takes them by a push like any other, and files read back4 * through `RepoHost`.5 *6 * The world writes three kinds of commit: each example project's first7 * push, an answerer's commit on their claim's fork, and what the dev Lander8 * composes and lands. Each is written whole, every blob and tree of its9 * files, as loose objects in a scratch git directory in memory; a push10 * copies only what the repo lacks. Text files only: the examples hold11 * nothing else.12 */13import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";14import type { PushSource, TreeEntry } from "@repo/artifacts/repo-host";15import { Brand } from "@repo/brand";16import { BlobSha, CommitSha } from "@repo/protocol/ids";17import type { Handle, RepoName } from "@repo/protocol/ids";18import { Array, DateTime, Effect, Option, Predicate } from "effect";1920/** A tree's files, by path, as text: what the world writes. */21export type Files = ReadonlyMap<string, string>;2223/** A file as a commit holds it: its blob's id, and its text. */24export interface Held {25  readonly blob: BlobSha;26  readonly text: string;27}2829/** A commit's files, by path, as read back. */30export type Snapshot = ReadonlyMap<string, Held>;3132/** The name and email an author or committer line carries. */33export interface Identity {34  readonly email: string;35  readonly name: string;36}3738/** The platform, which commits every landing. */39export const platformIdentity: Identity = {40  email: `platform@${Brand.domain}`,41  name: Brand.name,42};4344/** A person, as the author of their own commits and of their landings. */45export const personIdentity = (handle: Handle): Identity => ({46  email: `${handle}@users.${Brand.domain}`,47  name: handle,48});4950/** A snapshot's text alone. */51export const textOf = (snapshot: Snapshot): Files =>52  new Map([...snapshot].map(([path, { text }]) => [path, text]));5354/** `files` with `changed` written over them. */55export const overlay = (56  files: Files,57  changed: Iterable<readonly [string, string]>58): Files => new Map([...files, ...changed]);5960// --------------------------------------------------------------- objects6162const encoder = new TextEncoder();6364const decoder = new TextDecoder();6566const concat = (parts: readonly Uint8Array[]) => {67  const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));68  let at = 0;6970  for (const part of parts) {71    all.set(part, at);72    at += part.byteLength;73  }7475  return all;76};7778const hex = (bytes: ArrayBuffer) =>79  [...new Uint8Array(bytes)]80    .map((byte) => byte.toString(16).padStart(2, "0"))81    .join("");8283const bytesOfHex = (id: string) =>84  Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));8586/** git's zlib stream, as a loose object holds it. */87const deflate = (bytes: Uint8Array) =>88  Effect.promise(() =>89    new Response(90      new Blob([Uint8Array.from(bytes)])91        .stream()92        .pipeThrough(new CompressionStream("deflate"))93    ).arrayBuffer()94  ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));9596/** An object's header and content, and its id: the SHA-1 of both. */97const framed = (kind: "blob" | "tree" | "commit", content: Uint8Array) => {98  const raw = concat([99    encoder.encode(`${kind} ${content.byteLength}\0`),100    content,101  ]);102103  return Effect.map(104    Effect.promise(() => crypto.subtle.digest("SHA-1", raw)),105    (digest) => ({ id: hex(digest), raw })106  );107};108109const sortKey = (entry: TreeEntry) =>110  encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);111112// git sorts a tree's entries by name, a subtree's name as if it ended in "/".113const treeOrder = (one: TreeEntry, other: TreeEntry) => {114  const left = sortKey(one);115  const right = sortKey(other);116117  for (let at = 0; at < Math.min(left.length, right.length); at += 1) {118    const diff = (left[at] ?? 0) - (right[at] ?? 0);119120    if (diff !== 0) {121      return diff;122    }123  }124125  return left.length - right.length;126};127128const treeBytes = (entries: readonly TreeEntry[]) =>129  concat(130    entries.toSorted(treeOrder).flatMap((entry) => [131      // A tree object spells a subtree's mode without its leading zero.132      encoder.encode(`${entry.mode.replace(/^0/u, "")} ${entry.name}\0`),133      bytesOfHex(entry.sha),134    ])135  );136137/**138 * A commit message as git keeps it: no carriage returns, no blank lines139 * first, and one newline last (isomorphic-git writes it back so when the140 * memory host copies the commit, and the id must not change).141 */142const messageOf = (message: string) =>143  `${message.replaceAll("\r", "").replace(/^\n+/u, "").replace(/\n+$/u, "")}\n`;144145const signature = (who: Identity, at: DateTime.Utc) =>146  `${who.name} <${who.email}> ${Math.floor(DateTime.toEpochMillis(at) / 1000)} +0000`;147148/** A commit to write: its tree, parents, people, time and message. */149export interface CommitInput {150  readonly tree: ObjectId;151  readonly parents: readonly CommitSha[];152  readonly author: Identity;153  readonly committer: Identity;154  readonly at: DateTime.Utc;155  readonly message: string;156}157158const commitBytes = (input: CommitInput) =>159  encoder.encode(160    [161      `tree ${input.tree}`,162      ...input.parents.map((parent) => `parent ${parent}`),163      `author ${signature(input.author, input.at)}`,164      `committer ${signature(input.committer, input.at)}`,165      "",166      messageOf(input.message),167    ].join("\n")168  );169170// ------------------------------------------------------------ the source171172const failure = (code: string, path: string) =>173  Promise.reject(Object.assign(new Error(`${code}: ${path}`), { code }));174175const clean = (path: string) =>176  `/${path177    .split("/")178    .filter((part) => part !== "")179    .join("/")}`;180181/** How isomorphic-git asks for a file: as bytes, or as text in "utf8", alone or as `{ encoding }`. */182type ReadOptions = string | { readonly encoding?: string } | undefined;183184const UTF8 = /^utf-?8$/iu;185186const wantsText = (options: ReadOptions) =>187  Predicate.isString(options)188    ? UTF8.test(options)189    : UTF8.test(options?.encoding ?? "");190191/** A write to the scratch directory through the file system: it only reads. */192const readOnly = (raw: string) => failure("EROFS", clean(raw));193194const stats = (kind: "file" | "dir", size: number) => ({195  ctimeMs: 0,196  dev: 1,197  gid: 1,198  ino: 0,199  isDirectory: () => kind === "dir",200  isFile: () => kind === "file",201  isSymbolicLink: () => false,202  mode: kind === "dir" ? 0o4_0000 : 0o10_0644,203  mtimeMs: 0,204  size,205  uid: 1,206});207208/**209 * The part of `fs.promises` isomorphic-git calls when a push reads its210 * source (`docs/fs.md` there), over loose objects kept by path. It only211 * reads: the scratch directory is written by `scratch`, never through it.212 */213const readOnlyFs = (files: ReadonlyMap<string, Uint8Array>) => {214  const childrenOf = (dir: string) => {215    const prefix = dir === "/" ? "/" : `${dir}/`;216217    return Array.dedupe(218      [...files.keys()].flatMap((path) =>219        path.startsWith(prefix)220          ? [path.slice(prefix.length).split("/")[0] ?? ""]221          : []222      )223    );224  };225226  const stat = (raw: string) => {227    const path = clean(raw);228    const file = files.get(path);229230    if (file !== undefined) {231      return Promise.resolve(stats("file", file.byteLength));232    }233234    return childrenOf(path).length > 0235      ? Promise.resolve(stats("dir", 0))236      : failure("ENOENT", path);237  };238239  return {240    promises: {241      lstat: stat,242      mkdir: readOnly,243      // isomorphic-git may call it with no path to learn whether this fs244      // returns promises, so that call answers with a rejected promise.245      readFile: (raw?: string, options?: ReadOptions) => {246        const path = clean(raw ?? "");247        const file = files.get(path);248249        if (file === undefined) {250          return failure(251            childrenOf(path).length > 0 ? "EISDIR" : "ENOENT",252            path253          );254        }255256        return Promise.resolve(257          wantsText(options) ? decoder.decode(file) : file258        );259      },260      readdir: (raw: string) => {261        const path = clean(raw);262        const children = childrenOf(path);263264        return children.length > 0265          ? Promise.resolve(children)266          : failure("ENOENT", path);267      },268      readlink: (raw: string) => failure("EINVAL", clean(raw)),269      rmdir: readOnly,270      stat,271      symlink: (_target: string, raw: string) => failure("ENOSYS", clean(raw)),272      unlink: readOnly,273      writeFile: readOnly,274    },275  };276};277278/** A git directory in memory that a push takes objects from, and how to write into it. */279export interface Scratch {280  readonly source: PushSource;281  /** Every blob and tree of `files`, and the root tree's id. */282  readonly tree: (files: Files) => Effect.Effect<ObjectId>;283  readonly commit: (input: CommitInput) => Effect.Effect<CommitSha>;284}285286const GITDIR = "/scratch.git";287288/** A fresh scratch git directory: loose, zlib-deflated objects named by their ids. */289export const scratch: Effect.Effect<Scratch> = Effect.sync(() => {290  const objects = new Map<string, Uint8Array>();291292  const write = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>293    Effect.gen(function* () {294      const { id, raw } = yield* framed(kind, content);295      const path = `${GITDIR}/objects/${id.slice(0, 2)}/${id.slice(2)}`;296297      if (!objects.has(path)) {298        objects.set(path, yield* deflate(raw));299      }300301      return ObjectId.make(id);302    });303304  const folder = (305    files: readonly (readonly [string, string])[]306  ): Effect.Effect<ObjectId> =>307    Effect.gen(function* () {308      const blobs = files.filter(([path]) => !path.includes("/"));309310      const nested = Array.groupBy(311        files.filter(([path]) => path.includes("/")),312        ([path]) => path.slice(0, path.indexOf("/"))313      );314315      const blobEntries = yield* Effect.forEach(blobs, ([name, text]) =>316        Effect.map(write("blob", encoder.encode(text)), (sha): TreeEntry => ({317          mode: "100644",318          name,319          sha,320          type: "blob",321        }))322      );323324      const treeEntries = yield* Effect.forEach(325        Object.entries(nested),326        ([name, inside]) =>327          Effect.map(328            folder(329              inside.map(330                ([path, text]) => [path.slice(name.length + 1), text] as const331              )332            ),333            (sha): TreeEntry => ({ mode: "040000", name, sha, type: "tree" })334          )335      );336337      return yield* write("tree", treeBytes([...blobEntries, ...treeEntries]));338    });339340  return {341    commit: (input) =>342      Effect.map(write("commit", commitBytes(input)), (id) =>343        CommitSha.make(id)344      ),345    source: { fs: readOnlyFs(objects), gitdir: GITDIR },346    tree: (files) => folder([...files]),347  };348});349350// ----------------------------------------------------------------- reads351352/** One file of a snapshot: its path, its blob's id and its text. */353const fileOf =354  (path: string, blob: ObjectId) =>355  (bytes: Uint8Array): Snapshot =>356    new Map([357      [path, { blob: BlobSha.make(blob), text: decoder.decode(bytes) }],358    ]);359360/** Every file under the tree `tree` of `repo`, by path; none when the repo lacks an object. */361const snapshotOf = (362  repo: RepoName,363  tree: ObjectId,364  prefix: string365): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>366  Effect.gen(function* () {367    const host = yield* RepoHost;368    const entries = yield* host.readTree(repo, tree).pipe(Effect.orDie);369370    if (Option.isNone(entries)) {371      return Option.none();372    }373374    const each = yield* Effect.forEach(entries.value, (entry) => {375      const path = `${prefix}${entry.name}`;376377      if (entry.type === "tree") {378        return snapshotOf(repo, entry.sha, `${path}/`);379      }380381      return host382        .readBlob(repo, entry.sha)383        .pipe(Effect.orDie, Effect.map(Option.map(fileOf(path, entry.sha))));384    });385386    return Option.map(387      Option.all(each),388      (parts): Snapshot => new Map(parts.flatMap((part) => [...part]))389    );390  });391392/** `repo`'s files at `commit`; none when the repo or the commit is not there. */393export const filesAt = (394  repo: RepoName,395  commit: CommitSha396): Effect.Effect<Option.Option<Snapshot>, never, RepoHost> =>397  Effect.gen(function* () {398    const host = yield* RepoHost;399400    const found = yield* host401      .readCommit(repo, commit)402      .pipe(Effect.orElseSucceed(() => Option.none()));403404    return Option.isNone(found)405      ? Option.none()406      : yield* snapshotOf(repo, found.value.tree, "");407  });