Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 1why, one step back
1// Nothing here writes to the working repo, its config or its refs.

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 2–46why, one step back
2import { Fetch, FetchFailed } from "@repo/artifacts/fetch";
3import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";4import type { RepoNotFound } from "@repo/artifacts/repo-host";5import { RepoHostLocal } from "@repo/artifacts/repo-host/local";6import type { PushFacts, PushTarget } from "@repo/gate/facts";7import { addedLines, treeDiff } from "@repo/git/tree-diff";8import type { Change } from "@repo/git/tree-diff";9import type { Ask } from "@repo/protocol/domain/ask";10import type { ClaimView } from "@repo/protocol/domain/claim";11import { RefNameText } from "@repo/protocol/domain/common";12import type { Policy } from "@repo/protocol/domain/policy";13import { CommitSha, RepoName, TreeSha } from "@repo/protocol/ids";14import type { Principal } from "@repo/protocol/principal";15import {16 Effect,17 FileSystem,18 Layer,19 Option,20 Path,21 Schema,22 Stream,23} from "effect";24import type { Scope } from "effect";25import { ChildProcess, ChildProcessSpawner } from "effect/process";2627import { NotARepo } from "../repo-context.ts";2829export class UnknownRevision extends Schema.TaggedError<UnknownRevision>()(30 "UnknownRevision",31 { revision: Schema.String, root: Schema.String }32) {33 override get message() {34 return `${this.root} has no commit ${this.revision}`;35 }36}3738export interface GitRan {39 readonly exitCode: number;40 readonly stdout: string;41 readonly stderr: string;42}4344const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>45 bytes.pipe(Stream.decodeText(), Stream.mkString);46

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 47why, one step back
47/** A git that saw a hook's exported env in a temp repo would read and write the hook's repo instead. */

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 48–61why, one step back
48export const outsideAnyHook = {
49 GIT_ALTERNATE_OBJECT_DIRECTORIES: undefined,50 GIT_COMMON_DIR: undefined,51 GIT_CONFIG: undefined,52 GIT_CONFIG_COUNT: undefined,53 GIT_CONFIG_PARAMETERS: undefined,54 GIT_DIR: undefined,55 GIT_INDEX_FILE: undefined,56 GIT_NAMESPACE: undefined,57 GIT_OBJECT_DIRECTORY: undefined,58 GIT_PREFIX: undefined,59 GIT_WORK_TREE: undefined,60};61

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 62why, one step back
62/** No optional lock (an index refresh would write) and no password prompt. */

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 63–154why, one step back
63export const readOnlyGit = {
64 ...outsideAnyHook,65 GIT_OPTIONAL_LOCKS: "0",66 GIT_TERMINAL_PROMPT: "0",67};6869export const runGit = (70 cwd: string,71 args: readonly string[]72): Effect.Effect<GitRan, NotARepo, ChildProcessSpawner.ChildProcessSpawner> =>73 Effect.scoped(74 Effect.gen(function* () {75 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;7677 const child = yield* spawner.spawn(78 ChildProcess.make("git", args, {79 cwd,80 env: readOnlyGit,81 extendEnv: true,82 stdin: "ignore",83 })84 );8586 const [stdout, stderr, exitCode] = yield* Effect.all(87 [text(child.stdout), text(child.stderr), child.exitCode],88 { concurrency: "unbounded" }89 );9091 return { exitCode: Number(exitCode), stderr, stdout };92 })93 ).pipe(Effect.catchTag("PlatformError", () => new NotARepo({ cwd })));9495export const commitOf = (root: string, revision: string) =>96 Effect.gen(function* () {97 const ran = yield* runGit(root, [98 "rev-parse",99 "--verify",100 "--quiet",101 "--end-of-options",102 `${revision}^{commit}`,103 ]);104105 const sha = ran.stdout.trim();106107 return ran.exitCode === 0 && Schema.is(CommitSha)(sha)108 ? sha109 : yield* new UnknownRevision({ revision, root });110 });111112const mergeBase = (root: string, base: string, head: CommitSha) =>113 Effect.gen(function* () {114 const from = yield* commitOf(root, base);115 const ran = yield* runGit(root, ["merge-base", from, head]);116 const sha = ran.stdout.trim();117118 return ran.exitCode === 0 && Schema.is(CommitSha)(sha)119 ? sha120 : yield* new UnknownRevision({ revision: `${base}...${head}`, root });121 });122123const noNetwork = Layer.succeed(Fetch)({124 fetch: (request) =>125 Effect.fail(126 new FetchFailed({127 reason: "the local check makes no requests",128 url: request.url,129 })130 ),131});132133const WORKING = RepoName.make("working");134135const COPY = RepoName.make("copy");136137const hostOver = (folder: string) =>138 RepoHostLocal.layer({ remoteBase: `file://${folder}`, root: folder }).pipe(139 Layer.provide(noNetwork)140 );141142const readsAll = (name: RepoName, shas: readonly CommitSha[]) =>143 Effect.forEach(shas, (sha) =>144 RepoHost.use((host) => host.readCommit(name, sha))145 ).pipe(146 Effect.map((commits) => commits.every(Option.isSome)),147 Effect.catchTag("RepoNotFound", () => Effect.succeed(false))148 );149150interface Opened {151 readonly host: Layer.Layer<RepoHost>;152 readonly name: RepoName;153}154

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

line 155why, one step back
155/** isomorphic-git cannot follow `objects/info/alternates`, so such a store is fetched into a temp bare copy. */

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 156–318why, one step back
156const openWorking = (
157 root: string,158 shas: readonly CommitSha[]159): Effect.Effect<160 Opened,161 NotARepo,162 | ChildProcessSpawner.ChildProcessSpawner163 | FileSystem.FileSystem164 | Path.Path165 | Scope.Scope166> =>167 Effect.gen(function* () {168 const fs = yield* FileSystem.FileSystem;169 const path = yield* Path.Path;170 const failed = () => new NotARepo({ cwd: root });171172 const common = yield* runGit(root, [173 "rev-parse",174 "--path-format=absolute",175 "--git-common-dir",176 ]);177178 if (common.exitCode !== 0) {179 return yield* failed();180 }181182 const store = common.stdout.trim();183184 const folder = yield* fs185 .makeTempDirectoryScoped({ prefix: "check-repo-" })186 .pipe(Effect.mapError(failed));187188 const host = hostOver(folder);189190 const borrows = yield* fs191 .exists(path.join(store, "objects", "info", "alternates"))192 .pipe(Effect.mapError(failed));193194 if (!borrows) {195 yield* fs196 .symlink(store, path.join(folder, `${WORKING}.git`))197 .pipe(Effect.mapError(failed));198199 if (yield* readsAll(WORKING, shas).pipe(Effect.provide(host))) {200 return { host, name: WORKING } satisfies Opened;201 }202 }203204 const copy = path.join(folder, `${COPY}.git`);205 const made = yield* runGit(folder, ["init", "--quiet", "--bare", copy]);206207 const fetched = yield* runGit(copy, [208 "fetch",209 "--quiet",210 "--no-tags",211 "--no-write-fetch-head",212 root,213 ...shas.map((sha, index) => `${sha}:refs/heads/at-${index}`),214 ]);215216 if (made.exitCode !== 0 || fetched.exitCode !== 0) {217 return yield* failed();218 }219220 return { host, name: COPY } satisfies Opened;221 });222223export interface LocalFactsInput {224 readonly root: string;225 readonly base: string;226 readonly head: string;227 readonly policy: Policy;228 readonly ask: Option.Option<Ask>;229 readonly claim: Option.Option<ClaimView>;230 readonly pusher: Principal;231 readonly target: PushTarget;232 readonly claimsHeld: number;233}234235const blobText = (name: RepoName, blob: string | undefined) =>236 blob === undefined237 ? Effect.succeedNone238 : RepoHost.use((host) => host.readBlob(name, ObjectId.make(blob))).pipe(239 Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes)))240 );241242const ScriptsOf = Schema.fromJsonString(243 Schema.Struct({ scripts: Schema.optionalKey(Schema.Json) })244);245246const decodeScripts = Schema.decodeUnknownOption(ScriptsOf);247248const scriptsIn = (manifest: Option.Option<string>) =>249 Option.getOrElse(250 Option.map(Option.flatMap(manifest, decodeScripts), ({ scripts }) =>251 JSON.stringify(scripts ?? null)252 ),253 () => ""254 );255256const scriptsChanged = (name: RepoName, changes: readonly Change[]) =>257 Option.match(258 Option.fromUndefinedOr(changes.find(({ path }) => path === "package.json")),259 {260 onNone: () => Effect.succeed(false),261 onSome: (change) =>262 Effect.map(263 Effect.all([264 blobText(name, change.before),265 blobText(name, change.after),266 ]),267 ([before, after]) => scriptsIn(before) !== scriptsIn(after)268 ),269 }270 );271272const treeOf = (name: RepoName, sha: CommitSha) =>273 RepoHost.use((host) => host.readCommit(name, sha)).pipe(274 Effect.flatMap(Effect.fromOption),275 Effect.map(({ tree }) => TreeSha.make(tree)),276 Effect.orDie277 );278279export const localFacts = (280 input: LocalFactsInput281): Effect.Effect<282 PushFacts,283 NotARepo | RepoNotFound | UnknownRevision,284 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path285> =>286 Effect.scoped(287 Effect.gen(function* () {288 const head = yield* commitOf(input.root, input.head);289 const base = yield* mergeBase(input.root, input.base, head);290 const opened = yield* openWorking(input.root, [base, head]);291292 return yield* Effect.gen(function* () {293 const changes = yield* treeDiff(294 opened.name,295 yield* treeOf(opened.name, base),296 yield* treeOf(opened.name, head)297 );298299 return {300 addedLines: yield* addedLines(opened.name, changes),301 ask: input.ask,302 base,303 changes,304 claim: input.claim,305 claimsHeld: input.claimsHeld,306 head,307 landed: input.policy.at,308 layerPaths: new Set(),309 opensAsk: false,310 policy: input.policy,311 pusher: input.pusher,312 ref: RefNameText.make("refs/heads/main"),313 scriptsChanged: yield* scriptsChanged(opened.name, changes),314 target: input.target,315 } satisfies PushFacts;316 }).pipe(Effect.provide(opened.host));317 })318 );