commit.ts
This file
Path
packages/project/src/code/commit.ts
236 lines · 7.4 KiB · TypeScript
Last changed by
Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
History of this fileTake it
Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 1–236why, one step back1/**2 * One commit and what it changed against its first parent (a root commit3 * against the empty tree), through `treeDiff` (`@repo/git/tree-diff`): each4 * file's status, both blob ids, whether it is binary, and its old and new5 * text. At most 300 files and 2 MiB of text in all: past 300 files every6 * file is a path only, and once the text runs past 2 MiB the files after7 * it are; either way the diff says it is `truncated`. The list of changes8 * is kept by the commit's id; the landing is asked for on every call.9 */10import { RepoHost } from "@repo/artifacts/repo-host";11import type { RepoNotFound, TreeEntry } from "@repo/artifacts/repo-host";12import { treeDiff } from "@repo/git/tree-diff";13import type { Change } from "@repo/git/tree-diff";14import type { ChangedFile, CommitDiff } from "@repo/protocol/domain/code";15import { BlobSha, TreeSha } from "@repo/protocol/ids";16import type { CommitSha, RepoName } from "@repo/protocol/ids";17import { UnknownCommit } from "@repo/protocol/refusal";18import { Array, Effect, Option, Order } from "effect";1920import type { CodeProject } from "../code.ts";21import { CodeCache } from "./cache.ts";22import { contentsOf } from "./file.ts";23import type { Contents } from "./file.ts";24import { commitViews } from "./log.ts";25import { filesUnder, PATHS_CAP } from "./paths.ts";26import { commitAt } from "./revision.ts";27import { entriesOf, entryAt } from "./tree.ts";2829/** The most files a commit's diff carries text for. */30export const DIFF_FILES = 300;3132/** The most text a commit's diff carries in all: 2 MiB. */33export const DIFF_TEXT = 2 * 1024 * 1024;3435/** The longest list of changes the cache keeps. */36const KEPT_CHANGES = 1000;3738/** A change, and whether each side is a submodule (whose id names no blob here). */39interface Changed extends Change {40 readonly links: { readonly before: boolean; readonly after: boolean };41}4243const isLink = (entry: Option.Option<TreeEntry>) =>44 Option.exists(entry, ({ type }) => type === "commit");4546/** Every file under a root commit's tree, each added. */47const rootChanges = (repo: RepoName, tree: string) =>48 Effect.map(filesUnder(repo, tree, PATHS_CAP), ({ files }) =>49 files.map(({ entry, path }): Changed => ({50 after: BlobSha.make(entry.sha),51 links: { after: entry.type === "commit", before: false },52 path,53 status: "added",54 }))55 );5657/**58 * What changed from `base` to `head`, by `treeDiff` over this repo's trees59 * read through the cache (so the side lookups that follow read none again).60 */61const changesBetween = (repo: RepoName, base: string, head: string) =>62 Effect.gen(function* () {63 const host = yield* RepoHost;6465 const changes = yield* treeDiff(66 repo,67 TreeSha.make(base),68 TreeSha.make(head)69 ).pipe(70 Effect.provideService(71 RepoHost,72 RepoHost.of({73 ...host,74 readTree: (name, id) =>75 name === repo76 ? Effect.asSome(77 Effect.provideService(entriesOf(repo, id), RepoHost, host)78 )79 : host.readTree(name, id),80 })81 )82 );8384 return yield* Effect.forEach(85 changes,86 (change): Effect.Effect<Changed, RepoNotFound, RepoHost> =>87 Effect.map(88 Effect.all([89 entryAt(repo, base, change.path),90 entryAt(repo, head, change.path),91 ]),92 ([before, after]) => ({93 ...change,94 links: { after: isLink(after), before: isLink(before) },95 })96 ),97 { concurrency: 8 }98 );99 });100101const byPath = Order.mapInput(Order.String, (change: Changed) => change.path);102103/** A side's contents, unless it is a submodule or absent. */104const sideOf = (105 repo: RepoName,106 blob: BlobSha | undefined,107 link: boolean108): Effect.Effect<Option.Option<Contents>, RepoNotFound, RepoHost> =>109 blob === undefined || link ? Effect.succeedNone : contentsOf(repo, blob);110111/** A change as a path, its status and its blob ids, with no text. */112const pathOnly = ({ after, before, path, status }: Changed): ChangedFile => {113 const file = { binary: false, path, status };114115 if (before !== undefined && after !== undefined) {116 return { ...file, after, before };117 }118119 if (before !== undefined) {120 return { ...file, before };121 }122123 return after === undefined ? file : { ...file, after };124};125126/** Each change with its text while the budget lasts, and whether any went without. */127const withText = (repo: RepoName, changes: readonly Changed[]) =>128 Effect.gen(function* () {129 if (changes.length > DIFF_FILES) {130 return { files: changes.map(pathOnly), truncated: true };131 }132133 const files: ChangedFile[] = [];134 let budget = DIFF_TEXT;135 let truncated = false;136137 for (const change of changes) {138 if (truncated) {139 files.push(pathOnly(change));140 continue;141 }142143 const before = yield* sideOf(repo, change.before, change.links.before);144 const after = yield* sideOf(repo, change.after, change.links.after);145 const oldText = Option.flatMap(before, ({ text }) => text);146 const newText = Option.flatMap(after, ({ text }) => text);147148 const size =149 Option.getOrElse(150 Option.map(oldText, (text) => text.length),151 () => 0152 ) +153 Option.getOrElse(154 Option.map(newText, (text) => text.length),155 () => 0156 );157158 if (size > budget) {159 truncated = true;160 files.push(pathOnly(change));161 continue;162 }163164 budget -= size;165166 files.push({167 ...pathOnly(change),168 binary:169 Option.exists(before, ({ binary }) => binary) ||170 Option.exists(after, ({ binary }) => binary),171 ...Option.match(oldText, {172 onNone: () => ({}),173 onSome: (text) => ({ oldText: text }),174 }),175 ...Option.match(newText, {176 onNone: () => ({}),177 onSome: (text) => ({ newText: text }),178 }),179 });180 }181182 return { files, truncated };183 });184185/** One commit and the files it changed against its first parent. */186export const commitDiff = (187 project: CodeProject,188 sha: CommitSha189): Effect.Effect<CommitDiff, UnknownCommit, RepoHost> =>190 Effect.gen(function* () {191 const { repo } = project;192 const cache = yield* CodeCache;193194 const commit = yield* commitAt(repo, sha).pipe(195 Effect.orDie,196 Effect.flatMap(197 Option.match({198 onNone: () => Effect.fail(new UnknownCommit({ sha })),199 onSome: Effect.succeed,200 })201 )202 );203204 const parent = yield* Option.match(205 Option.fromUndefinedOr(commit.parents[0]),206 {207 onNone: () => Effect.succeedNone,208 onSome: (first) => commitAt(repo, first),209 }210 ).pipe(Effect.orDie);211212 const changes = yield* cache213 .through(214 `${repo}:changes:${sha}`,215 Option.match(parent, {216 onNone: () => rootChanges(repo, commit.tree),217 onSome: ({ tree }) => changesBetween(repo, tree, commit.tree),218 }),219 // A longer list is listed again, over trees the cache keeps.220 { heavy: true, keep: (all) => all.length <= KEPT_CHANGES }221 )222 .pipe(Effect.orDie);223224 const { files, truncated } = yield* withText(225 repo,226 Array.sort(changes, byPath)227 ).pipe(Effect.orDie);228229 const [view] = yield* commitViews(project, [commit]);230231 if (view === undefined) {232 return yield* Effect.die(`no view of ${sha}`);233 }234235 return { commit: view, files, truncated };236 });