Skip to content
Myr

why.ts

This file

Path

apps/cli/src/local/why.ts

376 lines · 10.9 KiB · TypeScript

Last changed by

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

History of this file

Take 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–20why, one step back
1import { notesRef } from "@repo/git/notes";
2import { parseTrailers } from "@repo/git/trailers";3import type { Trailer } from "@repo/git/trailers";4import { Client } from "@repo/protocol/contracts";5import { Verdict } from "@repo/protocol/domain/answer";6import { LandingView } from "@repo/protocol/domain/landing";7import { CommitSha, ProjectName, RepoPath } from "@repo/protocol/ids";8import { Refusal } from "@repo/protocol/refusal";9import {10 Context,11 DateTime,12 Effect,13 Option,14 Runtime,15 Schema,16 Stream,17} from "effect";18import { Argument, Command, Flag } from "effect/cli";19import { ChildProcess, ChildProcessSpawner } from "effect/process";20

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

line 21why, one step back
21import { endRefused, Output } from "../output.ts";

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 22–52why, one step back
22import type { View } from "../output.ts";
23import { repoContext } from "../repo-context.ts";24import type { RepoContext } from "../repo-context.ts";2526export const WorkingDirectory = Context.Reference<string>(27 "cli/WorkingDirectory",28 { defaultValue: () => "." }29);3031export class UsageError extends Schema.TaggedError<UsageError>()("UsageError", {32 reason: Schema.String,33}) {34 override readonly [Runtime.errorExitCode] = 2;35 override readonly [Runtime.errorReported] = false;3637 override get message() {38 return this.reason;39 }40}4142export const usage = (reason: string) =>43 Effect.fail(new UsageError({ reason }));4445const isRefusal = Schema.is(Refusal);4647export const reportRefusals =48 (command: string, json: boolean) =>49 <A, E, R>(effect: Effect.Effect<A, E, R>) =>50 effect.pipe(51 Effect.catchIf(isRefusal, (refusal) =>52 Output.use((output) =>

Merge cli/exit-codes into mainoscabrielbefore adoptionc19a862

lines 53–54why, one step back
53 endRefused(output, { command, json, refusals: [refusal] })
54 )

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 55–70why, one step back
55 )
56 );5758export const projectOf = (59 named: Option.Option<ProjectName>,60 context: Option.Option<RepoContext>61) =>62 Option.match(63 Option.orElse(named, () =>64 Option.flatMap(context, ({ repo }) =>65 Option.map(repo, ({ project }) => project)66 )67 ),68 {69 onNone: () =>70 usage(

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 71why, one step back
71 "Name the project with --project <owner>/<name>: this repo has no remote on a platform."

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 72–76why, one step back
72 ),
73 onSome: Effect.succeed,74 }75 );76

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

line 77why, one step back
77// The path takes everything before the last colon, so a path may hold one.

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 78–221why, one step back
78const LOCATION = /^(?<path>.+):(?<line>[1-9][0-9]*)$/u;
7980export const parseLocation = (81 text: string82): Option.Option<{ readonly path: RepoPath; readonly line: number }> => {83 const groups = LOCATION.exec(text)?.groups;84 const line = Number(groups?.line);8586 return groups?.path === undefined || !Number.isSafeInteger(line)87 ? Option.none()88 : Option.some({ line, path: RepoPath.make(groups.path) });89};9091const LineOrigin = Schema.Struct({92 landing: Schema.optionalKey(LandingView),93 line: Schema.Int,94 note: Schema.optionalKey(Verdict),95 path: RepoPath,96 sha: CommitSha,97 trailers: Schema.optionalKey(98 Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.String }))99 ),100});101102type LineOrigin = typeof LineOrigin.Type;103104const encodeOrigin = Schema.encodeEffect(LineOrigin);105106const decodeNote = Schema.decodeOption(Schema.fromJsonString(Verdict));107108const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109 bytes.pipe(Stream.decodeText(), Stream.mkString);110111const git = (cwd: string, args: readonly string[]) =>112 Effect.scoped(113 Effect.gen(function* () {114 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;115116 const child = yield* spawner.spawn(117 ChildProcess.make("git", args, {118 cwd,119 stderr: "ignore",120 stdin: "ignore",121 })122 );123124 const [stdout, exitCode] = yield* Effect.all(125 [text(child.stdout), child.exitCode],126 { concurrency: "unbounded" }127 );128129 return { exitCode, stdout };130 })131 );132133const noSuchLine = (location: string) =>134 usage(135 `${location} is not a line of a file committed at HEAD: ${location.replace(/:[0-9]+$/u, "")} is not there, or is shorter.`136 );137138const pathAtHead = (cwd: string, path: RepoPath, location: string) =>139 Effect.flatMap(140 git(cwd, [141 "ls-tree",142 "--full-name",143 "--name-only",144 "-z",145 "HEAD",146 "--",147 path,148 ]),149 ({ exitCode, stdout }) => {150 const [only, ...more] = stdout.split("\0").filter((name) => name !== "");151152 return exitCode === 0 && only !== undefined && more.length === 0153 ? Effect.succeed(RepoPath.make(only))154 : noSuchLine(location);155 }156 );157158// git blame's porcelain opens with the line's commit, then its line numbers.159const BLAMED = /^(?<sha>[0-9a-f]{40}) /u;160161const blamed = (cwd: string, path: RepoPath, line: number, location: string) =>162 Effect.flatMap(163 git(cwd, [164 "blame",165 "--porcelain",166 "-L",167 `${line},${line}`,168 "HEAD",169 "--",170 path,171 ]),172 ({ exitCode, stdout }) => {173 const sha = BLAMED.exec(stdout)?.groups?.sha;174175 return exitCode === 0 && sha !== undefined176 ? Effect.succeed(CommitSha.make(sha))177 : noSuchLine(location);178 }179 );180181const trailersOf = (cwd: string, sha: CommitSha) =>182 Effect.map(git(cwd, ["log", "-1", "--format=%B", sha]), ({ stdout }) =>183 parseTrailers(stdout)184 );185186const noteOn = (cwd: string, sha: CommitSha) =>187 Effect.flatMap(188 git(cwd, ["notes", `--ref=${notesRef}`, "show", sha]),189 ({ exitCode, stdout }) => {190 if (exitCode !== 0) {191 return Effect.succeedNone;192 }193194 const note = decodeNote(stdout.trim());195196 return Option.isSome(note)197 ? Effect.succeed(note)198 : Output.use((output) =>199 output.note(200 `The note on ${sha} in ${notesRef} is not a verdict; it is left out.`201 )202 ).pipe(Effect.as(Option.none<Verdict>()));203 }204 );205206const short = (sha: string) => sha.slice(0, 7);207208interface Row {209 readonly label: string;210 readonly value: string;211 readonly code?: boolean;212}213214const verdictRow = (verdict: Verdict): Row => ({215 label: "Verdict",216 value: [217 `${verdict.outcome._tag} at the ${verdict.stage} stage`,218 ...verdict.lanes.map(({ lane, result }) => `${lane} ${result}`),219 ].join(", "),220});221

Merge build/1002oscabrielbefore adoption1a364b9

lines 222–227why, one step back
222const askRow = (landing: LandingView): Row => {
223 if (landing.ask !== undefined) {224 return { code: true, label: "Ask", value: landing.ask };225 }226227 return landing.opened === undefined

Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571

line 228why, one step back
228 ? { label: "Ask", value: "none (a maintainer's own landing)" }

Merge build/1002oscabrielbefore adoption1a364b9

lines 229–233why, one step back
229 : { code: true, label: "Opened", value: landing.opened };
230};231232const landingRows = (landing: LandingView): readonly Row[] => [233 askRow(landing),

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 234–376why, one step back
234 { label: "Author", value: landing.author },
235 ...landing.credits.map(({ handle, role }) => ({236 label: role,237 value: handle,238 })),239 ...landing.assisted.map(({ harness, model, verified }) => ({240 label: "Assisted-by",241 value: `${harness}${model === undefined ? "" : `:${model}`} (${verified ? "verified" : "claimed"})`,242 })),243 ...(landing.heldBackTrailer === undefined244 ? []245 : [{ label: "Held-back", value: landing.heldBackTrailer }]),246];247248const trailerRows = (trailers: readonly Trailer[]): readonly Row[] =>249 trailers.map(({ key, value }) => ({ label: key, value }));250251const viewOf = (origin: LineOrigin): View => {252 const at = `${origin.path}:${origin.line}`;253 const commit = short(origin.sha);254 const verdict = origin.note ?? origin.landing?.verdict;255256 const [markdown, plain] = Option.match(257 Option.fromUndefinedOr(origin.landing),258 {259 onNone: () => [260 `\`${at}\` comes from commit \`${commit}\`, which is not a platform landing: the platform keeps no record of it, so its trailers are only what its author wrote.`,261 `${at} comes from commit ${commit}, which is not a platform landing: the platform keeps no record of it, so its trailers are only what its author wrote.`,262 ],263 onSome: ({ landedAt }) => [264 `\`${at}\` came to main in landing \`${commit}\`, on ${DateTime.formatIso(landedAt)}.`,265 `${at} came to main in landing ${commit}, on ${DateTime.formatIso(landedAt)}.`,266 ],267 }268 );269270 const rows = [271 ...(origin.landing === undefined ? [] : landingRows(origin.landing)),272 ...trailerRows(origin.trailers ?? []),273 ...(verdict === undefined ? [] : [verdictRow(verdict)]),274 ];275276 const empty =277 origin.landing === undefined && (origin.trailers ?? []).length === 0278 ? ["It carries no trailers."]279 : [];280281 return {282 markdown: [283 markdown,284 "",285 ...rows.map(286 ({ code, label, value }) =>287 `- ${label}: ${code === true ? `\`${value}\`` : value}`288 ),289 ...empty,290 ].join("\n"),291 text: [292 plain,293 ...rows.map(({ label, value }) => ` ${label}: ${value}`),294 ...empty,295 ].join("\n"),296 };297};298299export const why = Command.make(300 "why",301 {302 json: Flag.Boolean("json").pipe(303 Flag.withDefault(false),304 Flag.withDescription("Print machine-readable JSON")305 ),306 location: Argument.String("location").pipe(307 Argument.withMetavar("path:line"),308 Argument.withDescription(309 "A line of a file as committed at HEAD, such as src/week.ts:42"310 )311 ),312 project: Flag.String("project").pipe(313 Flag.withSchema(ProjectName),314 Flag.optional,315 Flag.withDescription(316 "The project whose landings to ask about; the repo's platform remote names it by default"317 )318 ),319 },320 ({ json, location, project }) =>321 Effect.gen(function* () {322 const at = yield* Option.match(parseLocation(location), {323 onNone: () =>324 usage(325 `${location} is not path:line; write one such as src/week.ts:42.`326 ),327 onSome: Effect.succeed,328 });329330 const cwd = yield* WorkingDirectory;331 const context = yield* repoContext(cwd);332 const name = yield* projectOf(project, Option.some(context));333 const path = yield* pathAtHead(cwd, at.path, location);334 const sha = yield* blamed(cwd, at.path, at.line, location);335 const client = yield* Client;336337 const landing = yield* client.landing({ project: name, sha }).pipe(338 Effect.map(({ landing: found }) => Option.some(found)),339 Effect.catchTag("UnknownCommit", () => Effect.succeedNone)340 );341342 const trailers = Option.isNone(landing)343 ? Option.some(yield* trailersOf(cwd, sha))344 : Option.none();345346 const note = yield* noteOn(cwd, sha);347348 const origin: LineOrigin = {349 line: at.line,350 path,351 sha,352 ...Option.match(landing, {353 onNone: () => ({}),354 onSome: (found) => ({ landing: found }),355 }),356 ...Option.match(note, {357 onNone: () => ({}),358 onSome: (verdict) => ({ note: verdict }),359 }),360 ...Option.match(trailers, {361 onNone: () => ({}),362 onSome: (found) => ({ trailers: found }),363 }),364 };365366 const data = yield* encodeOrigin(origin).pipe(Effect.orDie);367368 yield* Output.use((output) =>369 output.success({ command: "why", data, json, view: viewOf(origin) })370 );371 }).pipe(reportRefusals("why", json))372).pipe(373 Command.withDescription(374 "Explain a line: the ask, the answer and the people that landed it."375 )376);