notes.ts
This file
Path
packages/git/src/notes.ts
259 lines · 7.7 KiB · TypeScript
Last changed by
Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6
History of this fileTake it
The walk stopped after 200 commits: lines older than 878da37 point at it.
Merge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 1–16why, one step back1import { ObjectId, RefName, RepoHost } from "@repo/artifacts/repo-host";2import type {3 PushSource,4 RepoNotFound,5 TreeEntry,6} from "@repo/artifacts/repo-host";7import { memoryFs } from "@repo/artifacts/repo-host/memory-fs";8import { Brand } from "@repo/brand";9import { Verdict } from "@repo/protocol/domain/answer";10import { CommitSha } from "@repo/protocol/ids";11import type { RepoName } from "@repo/protocol/ids";12import { DateTime, Effect, Option, Schema } from "effect";1314import { committerLine } from "./trailers.ts";1516/**Drop the private build plan's citations from the code, and fail verify if one comes backoscabrielbefore adoptiona29cef6
line 17why, one step back17 * Where verdicts live as git notes: one JSON note per commit, readMerge build/420-release-downloads: the CLI installs from the platform itself, with no GitHub in the release pathoscabrielbefore adoption878da37
lines 18–259why, one step back18 * with `git notes --ref=<slug> show <commit>`.19 */20export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);2122/** A verdict to write as the note on `target`, on top of the notes at `notesParent` in `repo`. */23export interface NoteInput {24 readonly repo: RepoName;25 readonly notesParent: Option.Option<CommitSha>;26 readonly target: CommitSha;27 readonly verdict: Verdict;28 readonly now: DateTime.Utc;29}3031/**32 * A git directory in memory that a push takes objects from: a `PushSource`33 * whose file system is `memoryFs`, so a reader gets its typed API.34 */35export interface ScratchSource extends PushSource {36 readonly fs: MemoryFs;37}3839type MemoryFs = ReturnType<typeof memoryFs>;4041const encoder = new TextEncoder();4243const concat = (parts: readonly Uint8Array[]) => {44 const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));45 let at = 0;4647 for (const part of parts) {48 all.set(part, at);49 at += part.byteLength;50 }5152 return all;53};5455const hex = (bytes: ArrayBuffer) =>56 [...new Uint8Array(bytes)]57 .map((byte) => byte.toString(16).padStart(2, "0"))58 .join("");5960const bytesOfHex = (id: string) =>61 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));6263/** git's zlib stream, as a loose object holds it. */64const deflate = (bytes: Uint8Array) =>65 Effect.promise(() =>66 new Response(67 // A copy on its own `ArrayBuffer`: Node's `Blob` types refuse a view68 // that may sit on a `SharedArrayBuffer`, as `@repo/project` sees them.69 new Blob([Uint8Array.from(bytes)])70 .stream()71 .pipeThrough(new CompressionStream("deflate"))72 ).arrayBuffer()73 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));7475const sortKey = (entry: TreeEntry) =>76 encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);7778// git sorts a tree's entries by name, a subtree's name as if it ended in "/".79const treeOrder = (one: TreeEntry, other: TreeEntry) => {80 const left = sortKey(one);81 const right = sortKey(other);8283 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {84 const diff = (left[at] ?? 0) - (right[at] ?? 0);8586 if (diff !== 0) {87 return diff;88 }89 }9091 return left.length - right.length;92};9394// A tree object spells a subtree's mode without its leading zero.95const modeOf = (entry: TreeEntry) => entry.mode.replace(/^0/u, "");9697const treeBytes = (entries: readonly TreeEntry[]) =>98 concat(99 entries100 .toSorted(treeOrder)101 .flatMap((entry) => [102 encoder.encode(`${modeOf(entry)} ${entry.name}\0`),103 bytesOfHex(entry.sha),104 ])105 );106107const signature = (now: DateTime.Utc) =>108 `${committerLine.name} <${committerLine.email}> ${Math.floor(DateTime.toEpochMillis(now) / 1000)} +0000`;109110const commitBytes = (input: {111 readonly tree: string;112 readonly parents: readonly CommitSha[];113 readonly now: DateTime.Utc;114 readonly message: string;115}) =>116 encoder.encode(117 [118 `tree ${input.tree}`,119 ...input.parents.map((parent) => `parent ${parent}`),120 `author ${signature(input.now)}`,121 `committer ${signature(input.now)}`,122 "",123 input.message,124 ].join("\n")125 );126127/**128 * A bare git directory in memory that a push takes objects from: loose,129 * zlib-deflated objects named by the SHA-1 of their header and content.130 */131const scratch = () =>132 Effect.gen(function* () {133 const fs = memoryFs();134 const gitdir = "/notes.git";135 const made = new Set<string>();136137 const mkdir = (path: string) =>138 made.has(path)139 ? Effect.void140 : Effect.promise(() => fs.promises.mkdir(path)).pipe(141 Effect.tap(() => Effect.sync(() => made.add(path)))142 );143144 const write = (path: string, data: string | Uint8Array) =>145 Effect.promise(() => fs.promises.writeFile(path, data));146147 yield* Effect.forEach(148 ["", "/objects", "/refs", "/refs/heads", "/refs/notes", "/refs/tags"],149 (dir) => mkdir(`${gitdir}${dir}`)150 );151 yield* write(`${gitdir}/HEAD`, "ref: refs/heads/main\n");152 yield* write(153 `${gitdir}/config`,154 "[core]\n\trepositoryformatversion = 0\n\tbare = true\n"155 );156157 const object = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>158 Effect.gen(function* () {159 const raw = concat([160 encoder.encode(`${kind} ${content.byteLength}\0`),161 content,162 ]);163164 const id = hex(165 yield* Effect.promise(() => crypto.subtle.digest("SHA-1", raw))166 );167168 const dir = `${gitdir}/objects/${id.slice(0, 2)}`;169170 yield* mkdir(dir);171 yield* write(`${dir}/${id.slice(2)}`, yield* deflate(raw));172173 return id;174 });175176 return {177 object,178 ref: (ref: RefName, sha: CommitSha) =>179 write(`${gitdir}/${ref}`, `${sha}\n`),180 source: { fs, gitdir } satisfies ScratchSource,181 };182 });183184/** The notes tree's entries at `parent`, read through the port; none for the first note. */185const notesAt = (repo: RepoName, parent: Option.Option<CommitSha>) =>186 Option.match(parent, {187 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),188 onSome: (sha) =>189 Effect.gen(function* () {190 const host = yield* RepoHost;191 const commit = yield* host.readCommit(repo, sha);192193 if (Option.isNone(commit)) {194 return yield* Effect.die(`${repo} has no notes commit ${sha}`);195 }196197 const tree = yield* host.readTree(repo, commit.value.tree);198199 if (Option.isNone(tree)) {200 return yield* Effect.die(`${repo} has no tree ${commit.value.tree}`);201 }202203 return tree.value;204 }),205 });206207const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));208209/**210 * The notes commit that puts `verdict` on `target`, in git's own notes211 * layout: a fanout-free tree with one blob per annotated commit, named by its212 * SHA, holding the verdict as JSON. The tree keeps every note under213 * `notesParent` (read through the port), and the platform commits it at214 * `now`. The new blob, tree and commit sit in a scratch git directory in215 * memory, which `RepoHost.push` takes them from; the earlier notes' objects216 * are referenced by id and are already in `repo`.217 */218export const noteCommit = (219 input: NoteInput220): Effect.Effect<221 { readonly source: ScratchSource; readonly commit: CommitSha },222 RepoNotFound,223 RepoHost224> =>225 Effect.gen(function* () {226 const earlier = yield* notesAt(input.repo, input.notesParent);227 const json = yield* encodeVerdict(input.verdict).pipe(Effect.orDie);228 const repo = yield* scratch();229 const blob = yield* repo.object("blob", encoder.encode(`${json}\n`));230231 const tree = yield* repo.object(232 "tree",233 treeBytes([234 ...earlier.filter(({ name }) => name !== input.target),235 {236 mode: "100644",237 name: input.target,238 sha: ObjectId.make(blob),239 type: "blob",240 },241 ])242 );243244 const commit = CommitSha.make(245 yield* repo.object(246 "commit",247 commitBytes({248 message: `Verdict on ${input.target}\n`,249 now: input.now,250 parents: Option.toArray(input.notesParent),251 tree,252 })253 )254 );255256 yield* repo.ref(notesRef, commit);257258 return { commit, source: repo.source };259 });