facts.ts
This file
Path
apps/cli/src/local/facts.ts
318 lines · 9.2 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319// Nothing here writes to the working repo, its config or its refs.import { Fetch, FetchFailed } from "@repo/artifacts/fetch";import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";import type { RepoNotFound } from "@repo/artifacts/repo-host";import { RepoHostLocal } from "@repo/artifacts/repo-host/local";import type { PushFacts, PushTarget } from "@repo/gate/facts";import { addedLines, treeDiff } from "@repo/git/tree-diff";import type { Change } from "@repo/git/tree-diff";import type { Ask } from "@repo/protocol/domain/ask";import type { ClaimView } from "@repo/protocol/domain/claim";import { RefNameText } from "@repo/protocol/domain/common";import type { Policy } from "@repo/protocol/domain/policy";import { CommitSha, RepoName, TreeSha } from "@repo/protocol/ids";import type { Principal } from "@repo/protocol/principal";import { Effect, FileSystem, Layer, Option, Path, Schema, Stream,} from "effect";import type { Scope } from "effect";import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { NotARepo } from "../repo-context.ts";
export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()( "UnknownRevision", { revision: Schema.String, root: Schema.String }) { override get message() { return `${this.root} has no commit ${this.revision}`; }}
export interface GitRan { readonly exitCode: number; readonly stdout: string; readonly stderr: string;}
const text = <E>(bytes: Stream.Stream<Uint8Array, E>) => bytes.pipe(Stream.decodeText(), Stream.mkString);
/** A git that saw a hook's exported env in a temp repo would read and write the hook's repo instead. */export const outsideAnyHook = { GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined, GIT_COMMON_DIR: undefined, GIT_CONFIG: undefined, GIT_CONFIG_COUNT: undefined, GIT_CONFIG_PARAMETERS: undefined, GIT_DIR: undefined, GIT_INDEX_FILE: undefined, GIT_NAMESPACE: undefined, GIT_OBJECT_DIRECTORY: undefined, GIT_PREFIX: undefined, GIT_WORK_TREE: undefined,};
/** No optional lock (an index refresh would write) and no password prompt. */export const readOnlyGit = { ...outsideAnyHook, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0",};
export const runGit = ( cwd: string, args: readonly string[]): Effect.Effect<GitRan, NotARepo, ChildProcessSpawner.ChildProcessSpawner> => Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn( ChildProcess.make("git", args, { cwd, env: readOnlyGit, extendEnv: true, stdin: "ignore", }) );
const [stdout, stderr, exitCode] = yield* Effect.all( [text(child.stdout), text(child.stderr), child.exitCode], { concurrency: "unbounded" } );
return { exitCode: Number(exitCode), stderr, stdout }; }) ).pipe(Effect.catchTag("PlatformError", () => new NotARepo({ cwd })));
export const commitOf = (root: string, revision: string) => Effect.gen(function* () { const ran = yield* runGit(root, [ "rev-parse", "--verify", "--quiet", "--end-of-options", `${revision}^{commit}`, ]);
const sha = ran.stdout.trim();
return ran.exitCode === 0 && Schema.is(CommitSha)(sha) ? sha : yield* new UnknownRevision({ revision, root }); });
const mergeBase = (root: string, base: string, head: CommitSha) => Effect.gen(function* () { const from = yield* commitOf(root, base); const ran = yield* runGit(root, ["merge-base", from, head]); const sha = ran.stdout.trim();
return ran.exitCode === 0 && Schema.is(CommitSha)(sha) ? sha : yield* new UnknownRevision({ revision: `${base}...${head}`, root }); });
const noNetwork = Layer.succeed(Fetch)({ fetch: (request) => Effect.fail( new FetchFailed({ reason: "the local check makes no requests", url: request.url, }) ),});
const WORKING = RepoName.make("working");
const COPY = RepoName.make("copy");
const hostOver = (folder: string) => RepoHostLocal.layer({ remoteBase: `file://${folder}`, root: folder }).pipe( Layer.provide(noNetwork) );
const readsAll = (name: RepoName, shas: readonly CommitSha[]) => Effect.forEach(shas, (sha) => RepoHost.use((host) => host.readCommit(name, sha)) ).pipe( Effect.map((commits) => commits.every(Option.isSome)), Effect.catchTag("RepoNotFound", () => Effect.succeed(false)) );
interface Opened { readonly host: Layer.Layer<RepoHost>; readonly name: RepoName;}
/** isomorphic-git cannot follow `objects/info/alternates`, so such a store is fetched into a temp bare copy. */const openWorking = ( root: string, shas: readonly CommitSha[]): Effect.Effect< Opened, NotARepo, | ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Scope.Scope> => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const failed = () => new NotARepo({ cwd: root });
const common = yield* runGit(root, [ "rev-parse", "--path-format=absolute", "--git-common-dir", ]);
if (common.exitCode !== 0) { return yield* failed(); }
const store = common.stdout.trim();
const folder = yield* fs .makeTempDirectoryScoped({ prefix: "check-repo-" }) .pipe(Effect.mapError(failed));
const host = hostOver(folder);
const borrows = yield* fs .exists(path.join(store, "objects", "info", "alternates")) .pipe(Effect.mapError(failed));
if (!borrows) { yield* fs .symlink(store, path.join(folder, `${WORKING}.git`)) .pipe(Effect.mapError(failed));
if (yield* readsAll(WORKING, shas).pipe(Effect.provide(host))) { return { host, name: WORKING } satisfies Opened; } }
const copy = path.join(folder, `${COPY}.git`); const made = yield* runGit(folder, ["init", "--quiet", "--bare", copy]);
const fetched = yield* runGit(copy, [ "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", root, ...shas.map((sha, index) => `${sha}:refs/heads/at-${index}`), ]);
if (made.exitCode !== 0 || fetched.exitCode !== 0) { return yield* failed(); }
return { host, name: COPY } satisfies Opened; });
export interface LocalFactsInput { readonly root: string; readonly base: string; readonly head: string; readonly policy: Policy; readonly ask: Option.Option<Ask>; readonly claim: Option.Option<ClaimView>; readonly pusher: Principal; readonly target: PushTarget; readonly claimsHeld: number;}
const blobText = (name: RepoName, blob: string | undefined) => blob === undefined ? Effect.succeedNone : RepoHost.use((host) => host.readBlob(name, ObjectId.make(blob))).pipe( Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))) );
const ScriptsOf = Schema.fromJsonString( Schema.Struct({ scripts: Schema.optionalKey(Schema.Json) }));
const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);
const scriptsIn = (manifest: Option.Option<string>) => Option.getOrElse( Option.map(Option.flatMap(manifest, decodeScripts), ({ scripts }) => JSON.stringify(scripts ?? null) ), () => "" );
const scriptsChanged = (name: RepoName, changes: readonly Change[]) => Option.match( Option.fromUndefinedOr(changes.find(({ path }) => path === "package.json")), { onNone: () => Effect.succeed(false), onSome: (change) => Effect.map( Effect.all([ blobText(name, change.before), blobText(name, change.after), ]), ([before, after]) => scriptsIn(before) !== scriptsIn(after) ), } );
const treeOf = (name: RepoName, sha: CommitSha) => RepoHost.use((host) => host.readCommit(name, sha)).pipe( Effect.flatMap(Effect.fromOption), Effect.map(({ tree }) => TreeSha.make(tree)), Effect.orDie );
export const localFacts = ( input: LocalFactsInput): Effect.Effect< PushFacts, NotARepo | RepoNotFound | UnknownRevision, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path> => Effect.scoped( Effect.gen(function* () { const head = yield* commitOf(input.root, input.head); const base = yield* mergeBase(input.root, input.base, head); const opened = yield* openWorking(input.root, [base, head]);
return yield* Effect.gen(function* () { const changes = yield* treeDiff( opened.name, yield* treeOf(opened.name, base), yield* treeOf(opened.name, head) );
return { addedLines: yield* addedLines(opened.name, changes), ask: input.ask, base, changes, claim: input.claim, claimsHeld: input.claimsHeld, head, landed: input.policy.at, layerPaths: new Set(), opensAsk: false, policy: input.policy, pusher: input.pusher, ref: RefNameText.make("refs/heads/main"), scriptsChanged: yield* scriptsChanged(opened.name, changes), target: input.target, } satisfies PushFacts; }).pipe(Effect.provide(opened.host)); }) );