script.ts
This file
Path
apps/sandbox/src/lander/script.ts
607 lines · 14.9 KiB · TypeScript
Last changed by
Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
History of this fileTake it
1// The Lander checks nothing out and runs nothing from the trees it handles.2// Nothing pushes `main` with force, a lease or `--atomic`: a landing is a3// plain push, which git refuses when `main` moved.4import { Brand } from "@repo/brand";5import type { LandJob, Merged, MergeJob } from "@repo/project/lander/wire";6import { BlobSha, CommitSha, RepoPath, TreeSha } from "@repo/protocol/ids";7import type { RepoName } from "@repo/protocol/ids";8import { Array, Order } from "effect";9import type { Types } from "effect";1011import type { Executed } from "../box.ts";1213export type RemoteName = "main" | "fork";1415export type Expect =16 | "ok"17 /** `merge-tree`: 0 is a clean merge, 1 a merge with conflicts. */18 | "merge"19 | "push"20 /** A question: a non-zero exit means "no". */21 | "probe";2223export interface GitStep {24 readonly argv: Array.NonEmptyReadonlyArray<string>;25 /** Never a token. */26 readonly env?: Readonly<Record<string, string>>;27 readonly remote?: RemoteName;28 readonly expect: Expect;29}3031export const mainCopy = "refs/lander/main";3233export const forkCopy = (fork: RepoName) => `refs/lander/forks/${fork}`;3435export const notesCopy = "refs/lander/notes";3637export const composeCopy = "refs/lander/compose";3839export const mainRef = "refs/heads/main";4041/** Named by the tree, so a ref an answerer rewrote cannot change what is checked. */42export const mergeRef = (tree: string) => `${Brand.refsPrefix}merge/${tree}`;4344// Each git command: no hooks, no helper that could see a token, no redirect45// a header could follow, and nothing running in the background.46const safety = [47 "-c",48 "core.hooksPath=/dev/null",49 "-c",50 "credential.helper=",51 "-c",52 "http.followRedirects=false",53 "-c",54 "gc.auto=0",55 "-c",56 "maintenance.auto=false",57] as const;5859/** Never shallow: Artifacts' receive-pack does not advertise `shallow`. */60export const copyOf = (repo: RepoName) => `repos/${repo}.git`;6162const git = (63 repo: RepoName,64 ...args: readonly string[]65): Array.NonEmptyReadonlyArray<string> => [66 "git",67 ...safety,68 `--git-dir=${copyOf(repo)}`,69 ...args,70];7172const fetch = ["fetch", "--quiet", "--no-tags", "--no-write-fetch-head"];7374/** The container's file writes make no folder on their own. */75export const folders = (76 paths: Array.NonEmptyReadonlyArray<string>77): GitStep => ({ argv: ["mkdir", "-p", "--", ...paths], expect: "ok" });7879export const removeFolder = (folder: string): GitStep => ({80 argv: ["rm", "-rf", "--", folder],81 expect: "ok",82});8384export const initCopy = (repo: RepoName): GitStep => ({85 argv: ["git", ...safety, "init", "--quiet", "--bare", copyOf(repo)],86 expect: "ok",87});8889export const fetchMain = (90 repo: RepoName,91 url: string,92 options: { readonly notes?: boolean } = {}93): GitStep => ({94 argv: git(95 repo,96 ...fetch,97 ...(options.notes === true ? ["--prune"] : []),98 url,99 `+${mainRef}:${mainCopy}`,100 ...(options.notes === true ? [`+refs/notes/*:${notesCopy}/*`] : [])101 ),102 expect: "ok",103 remote: "main",104});105106export const fetchFork = (107 repo: RepoName,108 fork: RepoName,109 url: string110): GitStep => ({111 argv: git(repo, ...fetch, url, `+refs/heads/*:${forkCopy(fork)}/*`),112 expect: "ok",113 remote: "fork",114});115116/** `merge-tree --write-tree` needs git 2.40 or later. */117export const mergeTree = (118 repo: RepoName,119 sides: { readonly base: string; readonly main: string; readonly head: string }120): GitStep => ({121 argv: git(122 repo,123 "merge-tree",124 "--write-tree",125 "-z",126 "--name-only",127 "--no-messages",128 `--merge-base=${sides.base}`,129 sides.main,130 sides.head131 ),132 expect: "merge",133});134135export const diffTree = (136 repo: RepoName,137 from: string,138 to: string139): GitStep => ({140 argv: git(repo, "diff-tree", "-r", "-z", "--no-renames", from, to),141 expect: "ok",142});143144export interface MergeScript {145 readonly fetch: readonly GitStep[];146 readonly merge: GitStep;147 /** The answer's changes against its own base, not main's. */148 readonly changes: GitStep;149}150151export const mergeScript = (152 job: typeof MergeJob.Type,153 remotes: { readonly main: string; readonly fork: string }154): MergeScript => ({155 changes: diffTree(job.repo, job.base, job.head),156 fetch: [157 initCopy(job.repo),158 fetchMain(job.repo, remotes.main),159 fetchFork(job.repo, job.fork, remotes.fork),160 ],161 merge: mergeTree(job.repo, job),162});163164/** `lease` is only ever for a compose ref, never `main`. */165export const pushRef = (166 repo: RepoName,167 url: string,168 update: {169 readonly to: string;170 readonly ref: string;171 readonly lease?: string;172 readonly remote?: RemoteName;173 }174): GitStep => ({175 argv: git(176 repo,177 "push",178 "--porcelain",179 "--no-verify",180 ...(update.lease === undefined181 ? []182 : [`--force-with-lease=${update.ref}:${update.lease}`]),183 url,184 `${update.to}:${update.ref}`185 ),186 expect: "push",187 remote: update.remote ?? "main",188});189190export interface LandScript {191 readonly main: GitStep;192 readonly mirror: GitStep;193}194195export const landScript = (196 job: Pick<typeof LandJob.Type, "repo">,197 url: string,198 landing: CommitSha,199 mirror: string200): LandScript => ({201 main: pushRef(job.repo, url, { ref: mainRef, to: landing }),202 mirror: pushRef(job.repo, url, { ref: mirror, to: landing }),203});204205export interface Signature {206 readonly name: string;207 readonly email: string;208 /** Seconds since the epoch, in UTC. */209 readonly at: number;210}211212export const commitTree = (213 repo: RepoName,214 commit: {215 readonly tree: string;216 readonly parents: readonly string[];217 readonly messageFile: string;218 readonly author: Signature;219 readonly committer: Signature;220 }221): GitStep => ({222 argv: git(223 repo,224 "commit-tree",225 commit.tree,226 ...commit.parents.flatMap((parent) => ["-p", parent]),227 "-F",228 commit.messageFile229 ),230 env: {231 GIT_AUTHOR_DATE: `@${commit.author.at} +0000`,232 GIT_AUTHOR_EMAIL: commit.author.email,233 GIT_AUTHOR_NAME: commit.author.name,234 GIT_COMMITTER_DATE: `@${commit.committer.at} +0000`,235 GIT_COMMITTER_EMAIL: commit.committer.email,236 GIT_COMMITTER_NAME: commit.committer.name,237 },238 expect: "ok",239});240241export const objectType = (repo: RepoName, rev: string): GitStep => ({242 argv: git(repo, "cat-file", "-t", rev),243 expect: "probe",244});245246export const revParse = (repo: RepoName, rev: string): GitStep => ({247 argv: git(repo, "rev-parse", "--verify", "--quiet", rev),248 expect: "probe",249});250251/** A file's bytes stored as a blob, exactly as written: no filter, no line endings. */252export const hashObject = (repo: RepoName, file: string): GitStep => ({253 argv: git(repo, "hash-object", "-w", "--no-filters", "--", file),254 expect: "ok",255});256257export const readTree = (258 repo: RepoName,259 index: string,260 tree?: string261): GitStep => ({262 argv: git(repo, "read-tree", ...(tree === undefined ? ["--empty"] : [tree])),263 env: { GIT_INDEX_FILE: index },264 expect: "ok",265});266267export const updateIndex = (268 repo: RepoName,269 index: string,270 entries: readonly {271 readonly mode: string;272 readonly blob: string;273 readonly path: string;274 }[]275): GitStep => ({276 argv: git(277 repo,278 "update-index",279 "--add",280 ...entries.flatMap(({ blob, mode, path }) => [281 "--cacheinfo",282 `${mode},${blob},${path}`,283 ])284 ),285 env: { GIT_INDEX_FILE: index },286 expect: "ok",287});288289export const writeTree = (repo: RepoName, index: string): GitStep => ({290 argv: git(repo, "write-tree"),291 env: { GIT_INDEX_FILE: index },292 expect: "ok",293});294295/** Symlinks as plain files holding their target, so nothing written points outside. */296export const checkoutIndex = (297 repo: RepoName,298 index: string,299 folder: string300): GitStep => ({301 argv: [302 "git",303 ...safety,304 "-c",305 "core.symlinks=false",306 `--git-dir=${copyOf(repo)}`,307 `--work-tree=${folder}`,308 "checkout-index",309 "--all",310 "--force",311 ],312 env: { GIT_INDEX_FILE: index },313 expect: "ok",314});315316export const lsTree = (317 repo: RepoName,318 tree: string,319 paths: readonly string[]320): GitStep => ({321 argv: git(repo, "ls-tree", "-z", "--full-tree", tree, "--", ...paths),322 expect: "ok",323});324325export const filesUnder = (326 repo: RepoName,327 tree: string,328 folder: string329): GitStep => ({330 argv: git(repo, "ls-tree", "-r", "-z", "--full-tree", tree, "--", folder),331 expect: "ok",332});333334export const catBlob = (repo: RepoName, blob: string): GitStep => ({335 argv: git(repo, "cat-file", "blob", blob),336 expect: "ok",337});338339export const fetchCommit = (340 repo: RepoName,341 url: string,342 commit: string343): GitStep => ({344 argv: git(repo, ...fetch, url, commit),345 expect: "ok",346 remote: "main",347});348349export const firstParents = (350 repo: RepoName,351 tip: string,352 count: number353): GitStep => ({354 argv: git(355 repo,356 "log",357 "--first-parent",358 `--max-count=${count}`,359 "-z",360 "--format=%H %P%n%B",361 tip362 ),363 expect: "ok",364});365366export const lsRemote = (367 repo: RepoName,368 url: string,369 ref: string370): GitStep => ({371 argv: git(repo, "ls-remote", url, ref),372 expect: "ok",373 remote: "main",374});375376export const fetchRef = (377 repo: RepoName,378 url: string,379 ref: string,380 into: string381): GitStep => ({382 argv: git(repo, ...fetch, url, `+${ref}:${into}`),383 expect: "ok",384 remote: "main",385});386387const SCRIPT = /\.[cm]?[jt]sx?$/u;388389const ASK_FILE = /\.ask\.[cm]?[jt]s$/u;390391export const configEntry = `${Brand.configDir}/project.ts`;392393export const isScript = (path: string) => SCRIPT.test(path);394395const visibilityEntry = `${Brand.configDir}/visibility.ts`;396397export const bundleEntries = (paths: readonly string[]) =>398 paths.filter(399 (path) =>400 path === configEntry ||401 path === visibilityEntry ||402 (path.startsWith(`${Brand.configDir}/asks/`) && ASK_FILE.test(path))403 );404405export const bundledAs = (entry: string) => entry.replace(/\.[^./]*$/u, ".js");406407/** Bare imports resolve beside the sdk's copy, so `effect` is the sdk's own. */408export const resolution = (sdk: string) =>409 `${JSON.stringify(410 {411 compilerOptions: {412 paths: { [`${Brand.cliPackage}/rules`]: [sdk], "@repo/sdk": [sdk] },413 },414 },415 null,416 2417 )}\n`;418419export const symlink = (target: string, link: string): GitStep => ({420 argv: ["ln", "-s", "--", target, link],421 expect: "ok",422});423424/** Macros are off, so no code in the folder runs while it is bundled. */425export const bundle = (input: {426 readonly root: string;427 readonly out: string;428 readonly tsconfig: string;429 readonly entries: Array.NonEmptyReadonlyArray<string>;430}): GitStep => ({431 argv: [432 "bun",433 "build",434 "--no-macros",435 "--target=browser",436 "--format=esm",437 "--splitting",438 `--root=${input.root}`,439 `--outdir=${input.out}`,440 `--tsconfig-override=${input.tsconfig}`,441 "--entry-naming=[dir]/[name].[ext]",442 `--chunk-naming=${Brand.configDir}/chunk-[hash].[ext]`,443 ...input.entries.map((entry) => `${input.root}/${entry}`),444 ],445 expect: "ok",446});447448export const listFiles = (folder: string): GitStep => ({449 argv: ["find", folder, "-type", "f", "-printf", "%P\\0"],450 expect: "ok",451});452453export const readFile = (file: string): GitStep => ({454 argv: ["cat", "--", file],455 expect: "ok",456});457458const fields = (text: string) => text.split("\0").filter((part) => part !== "");459460export const readMerge = (stdout: string) => {461 const [tree = "", ...conflicts] = fields(stdout);462463 return {464 conflicts: Array.sort(new Set(conflicts), Order.String).map((path) =>465 RepoPath.make(path)466 ),467 tree: TreeSha.make(tree.trim()),468 };469};470471type Status = (typeof Merged.Type)["changes"][number]["status"];472473/** A raw diff's status letter as a change's status; a type change is a modification. */474const statusOf = (letter: string): Status | undefined => {475 switch (letter) {476 case "A": {477 return "added";478 }479480 case "D": {481 return "deleted";482 }483484 case "M":485 case "T": {486 return "modified";487 }488489 default: {490 return undefined;491 }492 }493};494495// An object id of zeros: no object, on the side of a change that has none.496const NO_OBJECT = /^0+$/u;497498const RAW =499 /^:\d+ \d+ (?<before>[0-9a-f]+) (?<after>[0-9a-f]+) (?<letter>[A-Z])/u;500501type Changed = (typeof Merged.Type)["changes"][number];502503/** A submodule's pointer counts as a file, as `@repo/git/tree-diff` reads them. */504export const readChanges = (stdout: string) =>505 Array.chunksOf(fields(stdout), 2).flatMap(([meta, path = ""]) => {506 const raw = RAW.exec(meta)?.groups;507 const status = statusOf(raw?.letter ?? "");508509 if (raw === undefined || status === undefined) {510 return [];511 }512513 const change: Types.Mutable<Changed> = {514 path: RepoPath.make(path),515 status,516 };517518 if (raw.before !== undefined && !NO_OBJECT.test(raw.before)) {519 change.before = BlobSha.make(raw.before);520 }521522 if (raw.after !== undefined && !NO_OBJECT.test(raw.after)) {523 change.after = BlobSha.make(raw.after);524 }525526 return [change];527 });528529export interface Logged {530 readonly sha: CommitSha;531 readonly parents: readonly CommitSha[];532 readonly message: string;533}534535export const readLog = (stdout: string): readonly Logged[] =>536 fields(stdout).map((record) => {537 const newline = record.indexOf("\n");538 const head = newline === -1 ? record : record.slice(0, newline);539 const [sha = "", ...parents] = head.split(" ").filter((id) => id !== "");540541 return {542 message: newline === -1 ? "" : record.slice(newline + 1),543 parents: parents.map((parent) => CommitSha.make(parent)),544 sha: CommitSha.make(sha),545 };546 });547548export const readEntries = (stdout: string) =>549 new Map(550 fields(stdout).map((line) => {551 const tab = line.indexOf("\t");552 const [mode = "", , sha = ""] = line.slice(0, tab).split(" ");553554 return [line.slice(tab + 1), { mode, sha }] as const;555 })556 );557558export const readFiles = (stdout: string) => fields(stdout);559560export const readRemoteRef = (stdout: string) => {561 const [line = ""] = stdout.split("\n");562 const [sha = ""] = line.split("\t");563564 return sha === "" ? undefined : CommitSha.make(sha);565};566567export type Pushed =568 | "moved"569 | "stale"570 /** Artifacts was busy with another push to the repo; retryable. */571 | "busy"572 | "failed";573574// git's words for a push the ref's current value refused: a client-side575// fast-forward check (`fetch first`, `non-fast-forward`, `stale info` for a576// lease), git receive-pack's compare-and-swap (`incorrect old value577// provided`, git 2.56), and Artifacts' (`stale ref`).578const STALE =579 /fetch first|non-fast-forward|stale info|incorrect old value|stale ref/u;580581const BUSY = "artifacts_git_receive_pack_busy";582583// A porcelain line: the flag, `from:to`, and the summary.584const PORCELAIN = /^(?<flag>.)\t(?<refs>[^\t]*)\t(?<summary>.*)$/u;585586export const readPush = (ran: Executed, ref: string): Pushed => {587 if (`${ran.stdout}\n${ran.stderr}`.includes(BUSY)) {588 return "busy";589 }590591 const line = ran.stdout592 .split("\n")593 .map((text) => PORCELAIN.exec(text)?.groups)594 .find((groups) => groups?.refs?.endsWith(`:${ref}`) === true);595596 if (line === undefined) {597 return "failed";598 }599600 if (ran.exitCode === 0 && [" ", "*", "="].includes(line.flag ?? "")) {601 return "moved";602 }603604 return line.flag === "!" && STALE.test(line.summary ?? "")605 ? "stale"606 : "failed";607};