notes.ts
This file
Path
packages/git/src/notes.ts
241 lines · 6.8 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–194why, 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";1516export const notesRef = RefName.make(`refs/notes/${Brand.slug}`);1718export interface NoteInput {19 readonly repo: RepoName;20 readonly notesParent: Option.Option<CommitSha>;21 readonly target: CommitSha;22 readonly verdict: Verdict;23 readonly now: DateTime.Utc;24}2526export interface ScratchSource extends PushSource {27 readonly fs: MemoryFs;28}2930type MemoryFs = ReturnType<typeof memoryFs>;3132const encoder = new TextEncoder();3334const concat = (parts: readonly Uint8Array[]) => {35 const all = new Uint8Array(parts.reduce((n, part) => n + part.byteLength, 0));36 let at = 0;3738 for (const part of parts) {39 all.set(part, at);40 at += part.byteLength;41 }4243 return all;44};4546const hex = (bytes: ArrayBuffer) =>47 [...new Uint8Array(bytes)]48 .map((byte) => byte.toString(16).padStart(2, "0"))49 .join("");5051const bytesOfHex = (id: string) =>52 Uint8Array.from(id.match(/../gu) ?? [], (pair) => Number.parseInt(pair, 16));5354const deflate = (bytes: Uint8Array) =>55 Effect.promise(() =>56 new Response(57 // A copy on its own `ArrayBuffer`: Node's `Blob` types refuse a view58 // that may sit on a `SharedArrayBuffer`, as `@repo/project` sees them.59 new Blob([Uint8Array.from(bytes)])60 .stream()61 .pipeThrough(new CompressionStream("deflate"))62 ).arrayBuffer()63 ).pipe(Effect.map((buffer) => new Uint8Array(buffer)));6465const sortKey = (entry: TreeEntry) =>66 encoder.encode(entry.type === "tree" ? `${entry.name}/` : entry.name);6768// git sorts a tree's entries by name, a subtree's name as if it ended in "/".69const treeOrder = (one: TreeEntry, other: TreeEntry) => {70 const left = sortKey(one);71 const right = sortKey(other);7273 for (let at = 0; at < Math.min(left.length, right.length); at += 1) {74 const diff = (left[at] ?? 0) - (right[at] ?? 0);7576 if (diff !== 0) {77 return diff;78 }79 }8081 return left.length - right.length;82};8384// A tree object spells a subtree's mode without its leading zero.85const modeOf = (entry: TreeEntry) => entry.mode.replace(/^0/u, "");8687const treeBytes = (entries: readonly TreeEntry[]) =>88 concat(89 entries90 .toSorted(treeOrder)91 .flatMap((entry) => [92 encoder.encode(`${modeOf(entry)} ${entry.name}\0`),93 bytesOfHex(entry.sha),94 ])95 );9697const signature = (now: DateTime.Utc) =>98 `${committerLine.name} <${committerLine.email}> ${Math.floor(DateTime.toEpochMillis(now) / 1000)} +0000`;99100const commitBytes = (input: {101 readonly tree: string;102 readonly parents: readonly CommitSha[];103 readonly now: DateTime.Utc;104 readonly message: string;105}) =>106 encoder.encode(107 [108 `tree ${input.tree}`,109 ...input.parents.map((parent) => `parent ${parent}`),110 `author ${signature(input.now)}`,111 `committer ${signature(input.now)}`,112 "",113 input.message,114 ].join("\n")115 );116117const scratch = () =>118 Effect.gen(function* () {119 const fs = memoryFs();120 const gitdir = "/notes.git";121 const made = new Set<string>();122123 const mkdir = (path: string) =>124 made.has(path)125 ? Effect.void126 : Effect.promise(() => fs.promises.mkdir(path)).pipe(127 Effect.tap(() => Effect.sync(() => made.add(path)))128 );129130 const write = (path: string, data: string | Uint8Array) =>131 Effect.promise(() => fs.promises.writeFile(path, data));132133 yield* Effect.forEach(134 ["", "/objects", "/refs", "/refs/heads", "/refs/notes", "/refs/tags"],135 (dir) => mkdir(`${gitdir}${dir}`)136 );137 yield* write(`${gitdir}/HEAD`, "ref: refs/heads/main\n");138 yield* write(139 `${gitdir}/config`,140 "[core]\n\trepositoryformatversion = 0\n\tbare = true\n"141 );142143 const object = (kind: "blob" | "tree" | "commit", content: Uint8Array) =>144 Effect.gen(function* () {145 const raw = concat([146 encoder.encode(`${kind} ${content.byteLength}\0`),147 content,148 ]);149150 const id = hex(151 yield* Effect.promise(() => crypto.subtle.digest("SHA-1", raw))152 );153154 const dir = `${gitdir}/objects/${id.slice(0, 2)}`;155156 yield* mkdir(dir);157 yield* write(`${dir}/${id.slice(2)}`, yield* deflate(raw));158159 return id;160 });161162 return {163 object,164 ref: (ref: RefName, sha: CommitSha) =>165 write(`${gitdir}/${ref}`, `${sha}\n`),166 source: { fs, gitdir } satisfies ScratchSource,167 };168 });169170const notesAt = (repo: RepoName, parent: Option.Option<CommitSha>) =>171 Option.match(parent, {172 onNone: () => Effect.succeed<readonly TreeEntry[]>([]),173 onSome: (sha) =>174 Effect.gen(function* () {175 const host = yield* RepoHost;176 const commit = yield* host.readCommit(repo, sha);177178 if (Option.isNone(commit)) {179 return yield* Effect.die(`${repo} has no notes commit ${sha}`);180 }181182 const tree = yield* host.readTree(repo, commit.value.tree);183184 if (Option.isNone(tree)) {185 return yield* Effect.die(`${repo} has no tree ${commit.value.tree}`);186 }187188 return tree.value;189 }),190 });191192const encodeVerdict = Schema.encodeEffect(Schema.fromJsonString(Verdict));193194/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 195–196why, one step back195 * git's own notes layout: a fanout-free tree with one blob per annotated196 * commit, named by its SHA. The new objects sit in a scratch git directory inMerge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 197–241why, one step back197 * memory, which `RepoHost.push` takes them from; the earlier notes' objects198 * are referenced by id and are already in `repo`.199 */200export const noteCommit = (201 input: NoteInput202): Effect.Effect<203 { readonly source: ScratchSource; readonly commit: CommitSha },204 RepoNotFound,205 RepoHost206> =>207 Effect.gen(function* () {208 const earlier = yield* notesAt(input.repo, input.notesParent);209 const json = yield* encodeVerdict(input.verdict).pipe(Effect.orDie);210 const repo = yield* scratch();211 const blob = yield* repo.object("blob", encoder.encode(`${json}\n`));212213 const tree = yield* repo.object(214 "tree",215 treeBytes([216 ...earlier.filter(({ name }) => name !== input.target),217 {218 mode: "100644",219 name: input.target,220 sha: ObjectId.make(blob),221 type: "blob",222 },223 ])224 );225226 const commit = CommitSha.make(227 yield* repo.object(228 "commit",229 commitBytes({230 message: `Verdict on ${input.target}\n`,231 now: input.now,232 parents: Option.toArray(input.notesParent),233 tree,234 })235 )236 );237238 yield* repo.ref(notesRef, commit);239240 return { commit, source: repo.source };241 });