Skip to content
Myr

init.ts

This file

Path

apps/cli/src/local/init.ts

533 lines · 15.3 KiB · TypeScript

Last changed by

Merge project/drop-proposals into mainoscabrielbefore adoptionb4ed08b

History of this file

Take it

1import { Brand } from "@repo/brand";2import { findRunBlock } from "@repo/checks/finder";3import type { RepoFile } from "@repo/checks/finder";4import { PATH_PLACEHOLDER } from "@repo/checks/kinds";5import { ApprovalNeeded } from "@repo/protocol/cli";6import { Client } from "@repo/protocol/contracts";7import type { InitProject } from "@repo/protocol/contracts";8import { ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";9import type { LandedSha } from "@repo/protocol/ids";10import type { Refusal } from "@repo/protocol/refusal";11import {12  Effect,13  FileSystem,14  Option,15  Path,16  Runtime,17  Schema,18  Stream,19} from "effect";20import { Command, Flag } from "effect/cli";21import { ChildProcess, ChildProcessSpawner } from "effect/process";2223import { Credentials, gitHelperConfig } from "../credentials.ts";24import { endRefused, Output } from "../output.ts";25import { parseRemote, repoContext } from "../repo-context.ts";26import { ASKS_DIR, projectFile } from "./project-file.ts";2728const COMMAND = "init";2930const CONFIG = `${Brand.configDir}/project.ts`;3132const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;3334const PENDING = { origin: "<platform>", remote: "<remote>" } as const;3536const NEXT = `Next: write an ask in ${Brand.configDir}/asks/<ask>.ask.ts, with its failing test under ${ASKS_DIR}/, then ${Brand.cli} ask open <ask>.`;3738/** The CLI knows the platform's address alone; the web shows the project at the same path. */39const pageLine = (project: string, remote: string) =>40  Option.match(parseRemote(remote), {41    onNone: () => `The web shows it at /${project}.`,42    onSome: ({ origin }) =>43      `Its address: ${origin}/${project} on the platform; the web shows it at /${project}.`,44  });4546export class InitMisused extends Schema.TaggedError<InitMisused>()(47  "InitMisused",48  { reason: Schema.String }49) {50  override readonly [Runtime.errorExitCode] = 2;5152  override get message() {53    return this.reason;54  }55}5657export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {58  argv: Schema.Array(Schema.String),59  stderr: Schema.String,60}) {61  override get message() {62    return `${this.argv.join(" ")} failed: ${this.stderr.trim()}`;63  }64}6566type Payload = typeof InitProject.payloadSchema.Type;6768interface Plan {69  readonly files: readonly RepoFile[];70  readonly git: readonly (readonly string[])[];71  readonly payload: Payload;72}7374const flags = {75  branch: Flag.String("branch").pipe(76    Flag.withDescription(77      "With --import: the branch to copy, instead of the repo's default."78    ),79    Flag.optional80  ),81  dryRun: Flag.Boolean("dry-run").pipe(82    Flag.withDefault(false),83    Flag.withDescription(84      "Print what init would write, send and run; do none of it."85    )86  ),87  import: Flag.String("import").pipe(88    Flag.withDescription(89      "A public repo's https:// URL for the platform to copy once, instead of this repo."90    ),91    Flag.optional92  ),93  json: Flag.Boolean("json").pipe(94    Flag.withDefault(false),95    Flag.withDescription("Print machine-readable JSON")96  ),97  project: Flag.String("project").pipe(98    Flag.withDescription(99      "The project's name, <owner>/<name>; a bare name is yours (<your handle>/<name>). By default this repo's folder, or an import's last URL segment, under your handle."100    ),101    Flag.optional102  ),103  push: Flag.Boolean("push").pipe(104    Flag.withDefault(true),105    Flag.withDescription(106      "Push HEAD to the new project's main (--no-push leaves that to you)."107    )108  ),109  yes: Flag.Boolean("yes").pipe(110    Flag.withDefault(false),111    Flag.withDescription(112      "Do it: write and commit the config, make the project, push."113    )114  ),115};116117type Input = Command.Command.Config.Infer<typeof flags>;118119const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>120  bytes.pipe(Stream.decodeText(), Stream.mkString);121122const run = (cwd: string, argv: readonly string[]) =>123  Effect.scoped(124    Effect.gen(function* () {125      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;126      const [command = "git", ...args] = argv;127128      const child = yield* spawner.spawn(129        ChildProcess.make(command, args, { cwd, stdin: "ignore" })130      );131132      const [stdout, stderr, exitCode] = yield* Effect.all(133        [text(child.stdout), text(child.stderr), child.exitCode],134        { concurrency: "unbounded" }135      );136137      return { exitCode, stderr, stdout };138    })139  );140141const runOk = (cwd: string, argv: readonly string[]) =>142  run(cwd, argv).pipe(143    Effect.filterOrFail(144      (ran) => ran.exitCode === 0,145      (ran) => new GitFailed({ argv, stderr: ran.stderr })146    )147  );148149const shellWord = (word: string) =>150  /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;151152const shown = (argv: readonly string[]) => argv.map(shellWord).join(" ");153154const READ = [155  /(?:^|\/)package\.json$/u,156  /(?:^|\/)tsconfig[^/]*\.json$/u,157  /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u,158  /^\.?lefthook\.ya?ml$/u,159  /^\.husky\/[^/]+$/u,160  /^\.pre-commit-config\.yaml$/u,161];162163const trackedFiles = (root: string) =>164  Effect.gen(function* () {165    const fs = yield* FileSystem.FileSystem;166    const path = yield* Path.Path;167    const listed = yield* runOk(root, ["git", "ls-files", "-z"]);168169    return yield* Effect.forEach(170      listed.stdout.split("\0").filter((file) => file !== ""),171      (file): Effect.Effect<RepoFile> =>172        READ.some((pattern) => pattern.test(file))173          ? fs.readFileString(path.join(root, file)).pipe(174              Effect.orElseSucceed(() => ""),175              Effect.map((content) => ({ content, path: file }))176            )177          : Effect.succeed({ content: "", path: file }),178      { concurrency: 16 }179    );180  });181182const profileOwner = Effect.map(183  Effect.flatMap(Credentials, ({ current }) => current),184  (profile) =>185    Option.map(186      Option.flatMap(profile, ({ handle }) => Option.fromUndefinedOr(handle)),187      (handle) => handle.toLowerCase()188    )189);190191const projectNamed = (192  given: Option.Option<string>,193  fallback: { readonly owner: Option.Option<string>; readonly short: string }194) =>195  Effect.gen(function* () {196    const word = Option.getOrElse(given, () => fallback.short);197    const known = yield* profileOwner;198199    // An import is yours by default; its source namespace names it only200    // when no handle is known here, or when --project spells it out.201    const owner = Option.isSome(given)202      ? known203      : Option.orElse(known, () => fallback.owner);204205    const spelled = word.includes("/")206      ? word207      : `${Option.getOrElse(owner, () => "")}/${word}`;208209    return yield* Effect.mapError(210      Schema.decodeEffect(ProjectName)(spelled),211      () =>212        new InitMisused({213          reason: spelled.startsWith("/")214            ? `name the project with --project <owner>/<name>: no handle is known here, so "${word}" needs its owner`215            : `--project "${spelled}" is no project name: use <owner>/<name>, lowercase words joined by dashes`,216        })217    );218  });219220const HTTPS = /^https:\/\/\S+$/u;221222const pathnameOf = Option.liftThrowable((url: string) => new URL(url).pathname);223224const lastSegment = (url: string) =>225  Option.getOrElse(pathnameOf(url), () => "")226    .split("/")227    .findLast((segment) => segment !== "")228    ?.replace(/\.git$/u, "") ?? "";229230const wiring = (input: {231  readonly hasRemote: boolean;232  readonly origin: Option.Option<string>;233  readonly push: boolean;234  readonly remote: string;235}): readonly (readonly string[])[] => [236  [237    "git",238    "remote",239    input.hasRemote ? "set-url" : "add",240    Brand.slug,241    input.remote,242  ],243  ...Option.match(input.origin, {244    onNone: () => [],245    onSome: gitHelperConfig,246  }),247  ...(input.push ? [["git", "push", Brand.slug, "HEAD:main"]] : []),248];249250const committing = (paths: readonly string[]) =>251  paths.flatMap((path) => [252    ["git", "add", "--", path],253    ["git", "commit", "--quiet", "--message", SUBJECT, "--", path],254  ]);255256const refuse = (json: boolean) => (refusal: Refusal) =>257  Output.use((output) =>258    endRefused(output, { command: COMMAND, json, refusals: [refusal] })259  );260261const makeProject = (payload: Payload, json: boolean) =>262  Effect.gen(function* () {263    const client = yield* Client;264265    return yield* client.initProject(payload).pipe(266      Effect.catchTags({267        ImportFailed: refuse(json),268        ProjectExists: refuse(json),269      })270    );271  });272273const approved = (input: Input, plan: Plan) =>274  Effect.gen(function* () {275    if (input.dryRun) {276      const output = yield* Output;277278      yield* output.plan({ command: COMMAND, json: input.json, payload: plan });279280      return false;281    }282283    if (!input.yes) {284      return yield* new ApprovalNeeded({ command: COMMAND });285    }286287    return true;288  });289290const httpsOnly = (url: string) =>291  HTTPS.test(url)292    ? Effect.void293    : Effect.fail(294        new InitMisused({295          reason: `--import takes a public repo's https:// URL, and ${url} is not one`,296        })297      );298299const importOnly = (branch: Option.Option<string>) =>300  Option.isNone(branch)301    ? Effect.void302    : Effect.fail(303        new InitMisused({304          reason:305            "--branch names the branch to import, so it goes with --import",306        })307      );308309const withLanded = <A extends object>(310  data: A,311  landed: LandedSha | undefined312) => (landed === undefined ? data : { ...data, landed });313314const imported = (input: Input, url: string, payload: Payload) =>315  Effect.gen(function* () {316    const output = yield* Output;317    const reply = yield* makeProject(payload, input.json);318    const clone = `git clone ${reply.remote}`;319    const page = pageLine(reply.project, reply.remote);320321    yield* output.success({322      command: COMMAND,323      data: withLanded(324        {325          clone,326          files: [],327          project: reply.project,328          pushed: false,329          remote: reply.remote,330        },331        reply.landed332      ),333      json: input.json,334      view: {335        markdown: `Imported ${url} as project **${reply.project}**. Clone it with:\n\n\`\`\`sh\n${clone}\n\`\`\`\n\n${page}\n\n${NEXT}`,336        text: `Imported ${url} as project ${reply.project}. Clone it with:\n  ${clone}\n${page}\n${NEXT}`,337      },338    });339  });340341const importing = (input: Input, url: string) =>342  Effect.gen(function* () {343    yield* httpsOnly(url);344345    // The contract takes a non-empty branch; the client can't send an empty one.346    const source = yield* Option.match(input.branch, {347      onNone: () => Effect.succeed({ url }),348      onSome: (branch) =>349        branch === ""350          ? Effect.fail(351              new InitMisused({352                reason: "--branch takes the name of the branch to import",353              })354            )355          : Effect.succeed({ branch, url }),356    });357358    const project = yield* projectNamed(input.project, {359      owner: sourceNamespaceOf(url),360      short: lastSegment(url),361    });362363    const payload: Payload = { import: source, project };364365    if (yield* approved(input, { files: [], git: [], payload })) {366      yield* imported(input, url, payload);367    }368  });369370const configLine = (atHead: boolean, inTree: boolean) => {371  if (atHead) {372    return `Kept ${CONFIG} as it is.`;373  }374375  return inTree376    ? `Committed ${CONFIG} as the work tree had it, alone.`377    : `Wrote ${CONFIG} and committed it alone.`;378};379380interface Found {381  readonly atHead: boolean;382  readonly commits: readonly string[];383  readonly hasRemote: boolean;384  readonly payload: Payload;385  readonly root: string;386  readonly writes: readonly RepoFile[];387}388389const made = (input: Input, found: Found) =>390  Effect.gen(function* () {391    const fs = yield* FileSystem.FileSystem;392    const path = yield* Path.Path;393    const output = yield* Output;394    const { atHead, commits, hasRemote, payload, root, writes } = found;395396    if (atHead) {397      yield* output.note(`kept ${CONFIG} as it is`);398    }399400    for (const file of writes) {401      yield* fs.makeDirectory(path.dirname(path.join(root, file.path)), {402        recursive: true,403      });404      yield* fs.writeFileString(path.join(root, file.path), file.content);405    }406407    for (const argv of committing(commits)) {408      yield* runOk(root, argv);409    }410411    const reply = yield* makeProject(payload, input.json);412    const origin = Option.map(parseRemote(reply.remote), (at) => at.origin);413414    for (const argv of wiring({415      hasRemote,416      origin,417      push: input.push,418      remote: reply.remote,419    })) {420      if (argv.includes("--global")) {421        yield* output.note(`changed your git config: ${shown(argv)}`);422      }423424      const ran = yield* runOk(root, argv);425426      if (argv[1] === "push" && ran.stderr.trim() !== "") {427        yield* output.note(ran.stderr.trimEnd());428      }429    }430431    const config = configLine(atHead, writes.length === 0);432433    const done = [434      `Made project ${reply.project} at ${reply.remote}.`,435      config,436      input.push437        ? `Pushed HEAD to its main through the remote ${Brand.slug}.`438        : `Push when ready: git push ${Brand.slug} HEAD:main`,439      pageLine(reply.project, reply.remote),440      NEXT,441    ];442443    yield* output.success({444      command: COMMAND,445      data: withLanded(446        {447          files: commits,448          project: reply.project,449          pushed: input.push,450          remote: reply.remote,451        },452        reply.landed453      ),454      json: input.json,455      view: { markdown: done.join("\n\n"), text: done.join("\n") },456    });457  });458459const inRepo = (input: Input) =>460  Effect.gen(function* () {461    yield* importOnly(input.branch);462463    const fs = yield* FileSystem.FileSystem;464    const path = yield* Path.Path;465    const { root } = yield* repoContext(".");466467    const project = yield* projectNamed(input.project, {468      owner: Option.none(),469      short: path.basename(root),470    });471472    const inTree = yield* fs.exists(path.join(root, CONFIG));473474    // HEAD is what the push sends: a config only the work tree has is kept and committed.475    const atHead =476      (yield* run(root, ["git", "cat-file", "-e", `HEAD:${CONFIG}`]))477        .exitCode === 0;478479    const block = findRunBlock(yield* trackedFiles(root));480481    const writes: readonly RepoFile[] =482      inTree || atHead483        ? []484        : [{ content: projectFile(block.run, block.sources), path: CONFIG }];485486    if (487      writes.length > 0 &&488      block.run.test?.includes(PATH_PLACEHOLDER) !== true489    ) {490      yield* Output.use((output) =>491        output.note(492          `No command that runs one test file was found, so ${CONFIG} takes run.fromCI. A red-first ask needs a test command with ${PATH_PLACEHOLDER}, as in test: "vitest run ${PATH_PLACEHOLDER}": add it to run before you open one.`493        )494      );495    }496497    const commits: readonly string[] = atHead ? [] : [CONFIG];498499    const hasRemote =500      (yield* run(root, ["git", "remote", "get-url", Brand.slug])).exitCode ===501      0;502503    const payload: Payload = { project };504505    const plan: Plan = {506      files: writes,507      git: [508        ...committing(commits),509        ...wiring({510          hasRemote,511          origin: Option.some(PENDING.origin),512          push: input.push,513          remote: PENDING.remote,514        }),515      ],516      payload,517    };518519    if (yield* approved(input, plan)) {520      yield* made(input, { atHead, commits, hasRemote, payload, root, writes });521    }522  });523524export const init = Command.make(COMMAND, flags, (input) =>525  Option.match(input.import, {526    onNone: () => inRepo(input),527    onSome: (url) => importing(input, url),528  })529).pipe(530  Command.withDescription(531    "Make this repo, or a public HTTPS repo, a project: find its checks, write its config and push."532  )533);