Skip to content
Myr

init.ts

This file

Path

apps/cli/src/local/init.ts

496 lines · 13.9 KiB · TypeScript

Last changed by

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

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 { ApprovalNeeded } from "@repo/protocol/cli";5import { Client } from "@repo/protocol/contracts";6import type { InitProject } from "@repo/protocol/contracts";7import { ProjectName, sourceNamespaceOf } from "@repo/protocol/ids";8import type { LandedSha } from "@repo/protocol/ids";9import type { Refusal } from "@repo/protocol/refusal";10import {11  Effect,12  FileSystem,13  Option,14  Path,15  Runtime,16  Schema,17  Stream,18} from "effect";19import { Command, Flag } from "effect/cli";20import { ChildProcess, ChildProcessSpawner } from "effect/process";2122import { Credentials, gitHelperConfig } from "../credentials.ts";23import { endRefused, Output } from "../output.ts";24import { parseRemote, repoContext } from "../repo-context.ts";25import { projectFile } from "./project-file.ts";2627const COMMAND = "init";2829const CONFIG = `${Brand.configDir}/project.ts`;3031const SUBJECT = `Add ${CONFIG}: the run block ${Brand.cli} ${COMMAND} found`;3233const PENDING = { origin: "<platform>", remote: "<remote>" } as const;3435export class InitMisused extends Schema.TaggedError<InitMisused>()(36  "InitMisused",37  { reason: Schema.String }38) {39  override readonly [Runtime.errorExitCode] = 2;4041  override get message() {42    return this.reason;43  }44}4546export class GitFailed extends Schema.TaggedError<GitFailed>()("GitFailed", {47  argv: Schema.Array(Schema.String),48  stderr: Schema.String,49}) {50  override get message() {51    return `${this.argv.join(" ")} failed: ${this.stderr.trim()}`;52  }53}5455type Payload = typeof InitProject.payloadSchema.Type;5657interface Plan {58  readonly files: readonly RepoFile[];59  readonly git: readonly (readonly string[])[];60  readonly payload: Payload;61}6263const flags = {64  branch: Flag.String("branch").pipe(65    Flag.withDescription(66      "With --import: the branch to copy, instead of the repo's default."67    ),68    Flag.optional69  ),70  dryRun: Flag.Boolean("dry-run").pipe(71    Flag.withDefault(false),72    Flag.withDescription(73      "Print what init would write, send and run; do none of it."74    )75  ),76  import: Flag.String("import").pipe(77    Flag.withDescription(78      "A public repo's https:// URL for the platform to copy once, instead of this repo."79    ),80    Flag.optional81  ),82  json: Flag.Boolean("json").pipe(83    Flag.withDefault(false),84    Flag.withDescription("Print machine-readable JSON")85  ),86  project: Flag.String("project").pipe(87    Flag.withDescription(88      "The project's name, <owner>/<name>; a bare name is yours (<your handle>/<name>). By default this repo's folder, or an import's source path."89    ),90    Flag.optional91  ),92  push: Flag.Boolean("push").pipe(93    Flag.withDefault(true),94    Flag.withDescription(95      "Push HEAD to the new project's main (--no-push leaves that to you)."96    )97  ),98  yes: Flag.Boolean("yes").pipe(99    Flag.withDefault(false),100    Flag.withDescription(101      "Do it: write and commit the config, make the project, push."102    )103  ),104};105106type Input = Command.Command.Config.Infer<typeof flags>;107108const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>109  bytes.pipe(Stream.decodeText(), Stream.mkString);110111const run = (cwd: string, argv: readonly string[]) =>112  Effect.scoped(113    Effect.gen(function* () {114      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;115      const [command = "git", ...args] = argv;116117      const child = yield* spawner.spawn(118        ChildProcess.make(command, args, { cwd, stdin: "ignore" })119      );120121      const [stdout, stderr, exitCode] = yield* Effect.all(122        [text(child.stdout), text(child.stderr), child.exitCode],123        { concurrency: "unbounded" }124      );125126      return { exitCode, stderr, stdout };127    })128  );129130const runOk = (cwd: string, argv: readonly string[]) =>131  run(cwd, argv).pipe(132    Effect.filterOrFail(133      (ran) => ran.exitCode === 0,134      (ran) => new GitFailed({ argv, stderr: ran.stderr })135    )136  );137138const shellWord = (word: string) =>139  /^[\w@%+=:,./-]+$/u.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;140141const shown = (argv: readonly string[]) => argv.map(shellWord).join(" ");142143const READ = [144  /(?:^|\/)package\.json$/u,145  /(?:^|\/)tsconfig[^/]*\.json$/u,146  /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u,147  /^\.?lefthook\.ya?ml$/u,148  /^\.husky\/[^/]+$/u,149  /^\.pre-commit-config\.yaml$/u,150];151152const trackedFiles = (root: string) =>153  Effect.gen(function* () {154    const fs = yield* FileSystem.FileSystem;155    const path = yield* Path.Path;156    const listed = yield* runOk(root, ["git", "ls-files", "-z"]);157158    return yield* Effect.forEach(159      listed.stdout.split("\0").filter((file) => file !== ""),160      (file): Effect.Effect<RepoFile> =>161        READ.some((pattern) => pattern.test(file))162          ? fs.readFileString(path.join(root, file)).pipe(163              Effect.orElseSucceed(() => ""),164              Effect.map((content) => ({ content, path: file }))165            )166          : Effect.succeed({ content: "", path: file }),167      { concurrency: 16 }168    );169  });170171const profileOwner = Effect.map(172  Effect.flatMap(Credentials, ({ current }) => current),173  (profile) =>174    Option.map(175      Option.flatMap(profile, ({ handle }) => Option.fromUndefinedOr(handle)),176      (handle) => handle.toLowerCase()177    )178);179180const projectNamed = (181  given: Option.Option<string>,182  fallback: { readonly owner: Option.Option<string>; readonly short: string }183) =>184  Effect.gen(function* () {185    const word = Option.getOrElse(given, () => fallback.short);186    const known = yield* profileOwner;187188    const owner = Option.isSome(given)189      ? known190      : Option.orElse(fallback.owner, () => known);191192    const spelled = word.includes("/")193      ? word194      : `${Option.getOrElse(owner, () => "")}/${word}`;195196    return yield* Effect.mapError(197      Schema.decodeEffect(ProjectName)(spelled),198      () =>199        new InitMisused({200          reason: spelled.startsWith("/")201            ? `name the project with --project <owner>/<name>: no handle is known here, so "${word}" needs its owner`202            : `--project "${spelled}" is no project name: use <owner>/<name>, lowercase words joined by dashes`,203        })204    );205  });206207const HTTPS = /^https:\/\/\S+$/u;208209const pathnameOf = Option.liftThrowable((url: string) => new URL(url).pathname);210211const lastSegment = (url: string) =>212  Option.getOrElse(pathnameOf(url), () => "")213    .split("/")214    .findLast((segment) => segment !== "")215    ?.replace(/\.git$/u, "") ?? "";216217const wiring = (input: {218  readonly hasRemote: boolean;219  readonly origin: Option.Option<string>;220  readonly push: boolean;221  readonly remote: string;222}): readonly (readonly string[])[] => [223  [224    "git",225    "remote",226    input.hasRemote ? "set-url" : "add",227    Brand.slug,228    input.remote,229  ],230  ...Option.match(input.origin, {231    onNone: () => [],232    onSome: gitHelperConfig,233  }),234  ...(input.push ? [["git", "push", Brand.slug, "HEAD:main"]] : []),235];236237const committing = (paths: readonly string[]) =>238  paths.flatMap((path) => [239    ["git", "add", "--", path],240    ["git", "commit", "--quiet", "--message", SUBJECT, "--", path],241  ]);242243const refuse = (json: boolean) => (refusal: Refusal) =>244  Output.use((output) =>245    endRefused(output, { command: COMMAND, json, refusals: [refusal] })246  );247248const makeProject = (payload: Payload, json: boolean) =>249  Effect.gen(function* () {250    const client = yield* Client;251252    return yield* client.initProject(payload).pipe(253      Effect.catchTags({254        ImportFailed: refuse(json),255        ProjectExists: refuse(json),256      })257    );258  });259260const approved = (input: Input, plan: Plan) =>261  Effect.gen(function* () {262    if (input.dryRun) {263      const output = yield* Output;264265      yield* output.plan({ command: COMMAND, json: input.json, payload: plan });266267      return false;268    }269270    if (!input.yes) {271      return yield* new ApprovalNeeded({ command: COMMAND });272    }273274    return true;275  });276277const httpsOnly = (url: string) =>278  HTTPS.test(url)279    ? Effect.void280    : Effect.fail(281        new InitMisused({282          reason: `--import takes a public repo's https:// URL, and ${url} is not one`,283        })284      );285286const importOnly = (branch: Option.Option<string>) =>287  Option.isNone(branch)288    ? Effect.void289    : Effect.fail(290        new InitMisused({291          reason:292            "--branch names the branch to import, so it goes with --import",293        })294      );295296const withLanded = <A extends object>(297  data: A,298  landed: LandedSha | undefined299) => (landed === undefined ? data : { ...data, landed });300301const imported = (input: Input, url: string, payload: Payload) =>302  Effect.gen(function* () {303    const output = yield* Output;304    const reply = yield* makeProject(payload, input.json);305    const clone = `git clone ${reply.remote}`;306307    yield* output.success({308      command: COMMAND,309      data: withLanded(310        {311          clone,312          files: [],313          project: reply.project,314          pushed: false,315          remote: reply.remote,316        },317        reply.landed318      ),319      json: input.json,320      view: {321        markdown: `Imported ${url} as project **${reply.project}**. Clone it with:\n\n\`\`\`sh\n${clone}\n\`\`\``,322        text: `Imported ${url} as project ${reply.project}. Clone it with:\n  ${clone}`,323      },324    });325  });326327const importing = (input: Input, url: string) =>328  Effect.gen(function* () {329    yield* httpsOnly(url);330331    // The contract takes a non-empty branch; the client can't send an empty one.332    const source = yield* Option.match(input.branch, {333      onNone: () => Effect.succeed({ url }),334      onSome: (branch) =>335        branch === ""336          ? Effect.fail(337              new InitMisused({338                reason: "--branch takes the name of the branch to import",339              })340            )341          : Effect.succeed({ branch, url }),342    });343344    const project = yield* projectNamed(input.project, {345      owner: sourceNamespaceOf(url),346      short: lastSegment(url),347    });348349    const payload: Payload = { import: source, project };350351    if (yield* approved(input, { files: [], git: [], payload })) {352      yield* imported(input, url, payload);353    }354  });355356interface Found {357  readonly commits: readonly string[];358  readonly hasRemote: boolean;359  readonly payload: Payload;360  readonly root: string;361  readonly writes: readonly RepoFile[];362}363364const made = (input: Input, found: Found) =>365  Effect.gen(function* () {366    const fs = yield* FileSystem.FileSystem;367    const path = yield* Path.Path;368    const output = yield* Output;369    const { commits, hasRemote, payload, root, writes } = found;370371    if (writes.length === 0) {372      yield* output.note(`kept ${CONFIG} as it is`);373    }374375    for (const file of writes) {376      yield* fs.makeDirectory(path.dirname(path.join(root, file.path)), {377        recursive: true,378      });379      yield* fs.writeFileString(path.join(root, file.path), file.content);380    }381382    for (const argv of committing(commits)) {383      yield* runOk(root, argv);384    }385386    const reply = yield* makeProject(payload, input.json);387    const origin = Option.map(parseRemote(reply.remote), (at) => at.origin);388389    for (const argv of wiring({390      hasRemote,391      origin,392      push: input.push,393      remote: reply.remote,394    })) {395      if (argv.includes("--global")) {396        yield* output.note(`changed your git config: ${shown(argv)}`);397      }398399      const ran = yield* runOk(root, argv);400401      if (argv[1] === "push" && ran.stderr.trim() !== "") {402        yield* output.note(ran.stderr.trimEnd());403      }404    }405406    const config =407      writes.length === 0 ? `Kept ${CONFIG} as it is` : `Wrote ${CONFIG}`;408409    const done = [410      `Made project ${reply.project} at ${reply.remote}.`,411      commits.length === 0 ? `${config}.` : `${config} and committed it alone.`,412      input.push413        ? `Pushed HEAD to its main through the remote ${Brand.slug}.`414        : `Push when ready: git push ${Brand.slug} HEAD:main`,415    ];416417    yield* output.success({418      command: COMMAND,419      data: withLanded(420        {421          files: commits,422          project: reply.project,423          pushed: input.push,424          remote: reply.remote,425        },426        reply.landed427      ),428      json: input.json,429      view: { markdown: done.join("\n\n"), text: done.join("\n") },430    });431  });432433const inRepo = (input: Input) =>434  Effect.gen(function* () {435    yield* importOnly(input.branch);436437    const fs = yield* FileSystem.FileSystem;438    const path = yield* Path.Path;439    const { root } = yield* repoContext(".");440441    const project = yield* projectNamed(input.project, {442      owner: Option.none(),443      short: path.basename(root),444    });445446    const inTree = yield* fs.exists(path.join(root, CONFIG));447448    // HEAD is what the push sends: a config only the work tree has is kept and committed.449    const atHead =450      (yield* run(root, ["git", "cat-file", "-e", `HEAD:${CONFIG}`]))451        .exitCode === 0;452453    const block = findRunBlock(yield* trackedFiles(root));454455    const writes: readonly RepoFile[] =456      inTree || atHead457        ? []458        : [{ content: projectFile(block.run, block.sources), path: CONFIG }];459460    const commits: readonly string[] = atHead ? [] : [CONFIG];461462    const hasRemote =463      (yield* run(root, ["git", "remote", "get-url", Brand.slug])).exitCode ===464      0;465466    const payload: Payload = { project };467468    const plan: Plan = {469      files: writes,470      git: [471        ...committing(commits),472        ...wiring({473          hasRemote,474          origin: Option.some(PENDING.origin),475          push: input.push,476          remote: PENDING.remote,477        }),478      ],479      payload,480    };481482    if (yield* approved(input, plan)) {483      yield* made(input, { commits, hasRemote, payload, root, writes });484    }485  });486487export const init = Command.make(COMMAND, flags, (input) =>488  Option.match(input.import, {489    onNone: () => inRepo(input),490    onSome: (url) => importing(input, url),491  })492).pipe(493  Command.withDescription(494    "Make this repo, or a public HTTPS repo, a project: find its checks, write its config and push."495  )496);