Skip to content
Myr

repo-context.ts

This file

Path

apps/cli/src/repo-context.ts

196 lines · 5.4 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/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–46why, one step back
1import { AskId, Handle, LayerName, ProjectName } from "@repo/protocol/ids";
2import { Array, Effect, Option, Schema, Stream } from "effect";3import { ChildProcess, ChildProcessSpawner } from "effect/process";45import { Credentials } from "./credentials.ts";67export type RepoKind = "canonical" | "claim" | "working" | "layer";89export interface RepoRef {10 readonly kind: RepoKind;11 readonly project: ProjectName;12 readonly ask?: AskId;13 readonly handle?: Handle;14 readonly layer?: LayerName;15}1617const asProject = Schema.decodeOption(ProjectName);1819const asAsk = Schema.decodeOption(AskId);2021const asLayer = Schema.decodeOption(LayerName);2223const asForkHandle = (part: string) =>24 Option.filter(25 Schema.decodeOption(Handle)(part),26 (handle) => handle === handle.toLowerCase()27 );2829const WORKING = "me";3031const forkOf = (32 project: ProjectName,33 second: string,34 third: string35): Option.Option<RepoRef> =>36 second === WORKING37 ? Option.map(asForkHandle(third), (handle): RepoRef => ({38 handle,39 kind: "working",40 project,41 }))42 : Option.map(43 Option.all({ ask: asAsk(second), handle: asForkHandle(third) }),44 ({ ask, handle }): RepoRef => ({ ask, handle, kind: "claim", project })45 );46

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

line 47why, one step back
47/** `--` occurs in no name or ask, so an address splits back into its parts. */

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

line 48why, one step back
48export const parseRepoName = (name: string): Option.Option<RepoRef> => {

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 49–51why, one step back
49 const slash = name.lastIndexOf("/");
50 const [first = "", ...rest] = name.slice(slash + 1).split("--");51 const spelled = slash === -1 ? first : `${name.slice(0, slash)}/${first}`;

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

line 52why, one step back
52

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 53why, one step back
53 return Option.flatMap(asProject(spelled), (project) => {

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 54–93why, one step back
54 const [second, third] = rest;
5556 if (second === undefined) {57 return Option.some<RepoRef>({ kind: "canonical", project });58 }5960 if (third === undefined) {61 return Option.map(asLayer(second), (layer): RepoRef => ({62 kind: "layer",63 layer,64 project,65 }));66 }6768 return rest.length === 2 ? forkOf(project, second, third) : Option.none();69 });70};7172const asUrl = Option.liftThrowable((url: string) => new URL(url));7374const webOrigin = (url: string) =>75 Option.map(76 Option.filter(asUrl(url), ({ protocol }) =>77 ["http:", "https:"].includes(protocol)78 ),79 ({ host, pathname, protocol }) => ({80 origin: `${protocol}//${host}`,81 pathname,82 })83 );8485export const parseRemote = (86 url: string87): Option.Option<{ readonly origin: string; readonly repo: string }> =>88 Option.flatMap(webOrigin(url), ({ origin, pathname }) => {89 const repo = pathname90 .replace(/^\//u, "")91 .replace(/\/$/u, "")92 .replace(/\.git$/u, "");93

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 94why, one step back
94 return /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+){0,2}$/u.test(repo)

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 95–196why, one step back
95 ? Option.some({ origin, repo })
96 : Option.none();97 });9899export interface RepoContext {100 readonly root: string;101 readonly remote: Option.Option<{102 readonly name: string;103 readonly url: string;104 }>;105 readonly origin: Option.Option<string>;106 readonly repo: Option.Option<RepoRef>;107}108109export class NotARepo extends Schema.TaggedError<NotARepo>()("NotARepo", {110 cwd: Schema.String,111}) {112 override get message() {113 return `${this.cwd} is not inside a git repo`;114 }115}116117const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>118 bytes.pipe(Stream.decodeText(), Stream.mkString);119120const git = (cwd: string, args: readonly string[]) =>121 Effect.scoped(122 Effect.gen(function* () {123 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;124125 const child = yield* spawner.spawn(126 ChildProcess.make("git", args, {127 cwd,128 stderr: "ignore",129 stdin: "ignore",130 })131 );132133 const [stdout, exitCode] = yield* Effect.all(134 [text(child.stdout), child.exitCode],135 { concurrency: "unbounded" }136 );137138 return { exitCode, stdout };139 })140 );141142const remotesOf = (listing: string) =>143 listing.split("\n").flatMap((line) => {144 const match = /^(?<name>\S+)\t(?<url>\S+) \(fetch\)$/u.exec(line);145146 return match?.groups?.name === undefined || match.groups.url === undefined147 ? []148 : [{ name: match.groups.name, url: match.groups.url }];149 });150151export const repoContext = (152 cwd: string153): Effect.Effect<154 RepoContext,155 NotARepo,156 ChildProcessSpawner.ChildProcessSpawner157> =>158 Effect.gen(function* () {159 const top = yield* git(cwd, ["rev-parse", "--show-toplevel"]);160161 if (top.exitCode !== 0) {162 return yield* new NotARepo({ cwd });163 }164165 const remotes = remotesOf((yield* git(cwd, ["remote", "-v"])).stdout);166167 const signedIn = yield* Effect.serviceOption(Credentials).pipe(168 Effect.flatMap(169 Option.match({170 onNone: () => Effect.succeedNone,171 onSome: (credentials) => credentials.current,172 })173 ),174 Effect.map(Option.flatMap(({ url }) => webOrigin(url)))175 );176177 const remote = Option.orElse(178 Option.flatMap(signedIn, ({ origin }) =>179 Array.findFirst(remotes, ({ url }) =>180 Option.exists(parseRemote(url), (parsed) => parsed.origin === origin)181 )182 ),183 () => Array.findFirst(remotes, ({ name }) => name === "origin")184 );185186 const parsed = Option.flatMap(remote, ({ url }) => parseRemote(url));187188 return {189 origin: Option.map(parsed, ({ origin }) => origin),190 remote,191 repo: Option.flatMap(parsed, ({ repo }) => parseRepoName(repo)),192 root: top.stdout.trim(),193 };194 }).pipe(195 Effect.catchTag("PlatformError", () => Effect.fail(new NotARepo({ cwd })))196 );