finder.ts
This file
Path
packages/checks/src/finder.ts
929 lines · 26.0 KiB · TypeScript
Last changed by
Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f
History of this fileTake it
1import type { RunBlock } from "@repo/protocol/domain/run";2import { LaneName } from "@repo/protocol/ids";3import { Array as Arr, Option, Result, Schema } from "effect";4import { parse } from "yaml";56import { PATH_PLACEHOLDER } from "./kinds.ts";78export type RunBlockEncoded = typeof RunBlock.Encoded;910export interface RepoFile {11 readonly content: string;12 readonly path: string;13}1415export interface FoundRunBlock {16 readonly run: Partial<RunBlockEncoded>;17 readonly sources: readonly string[];18}1920type Canonical = "build" | "format" | "lint" | "types" | "unit";2122const isLaneName = Schema.is(LaneName);2324const words = (command: string): readonly string[] =>25 command.trim().split(/\s+/u).filter(Boolean);2627const startsWith = (tokens: readonly string[], prefix: readonly string[]) =>28 prefix.every((word, index) => tokens[index] === word);2930const hasAny = (tokens: readonly string[], flags: readonly string[]) =>31 tokens.some((token) =>32 flags.some((flag) => token === flag || token.startsWith(`${flag}=`))33 );3435const SETUP: readonly (readonly string[])[] = [36 ["corepack", "enable"],37 ["npm", "ci"],38 ["npm", "install"],39 ["npm", "i"],40 ["pnpm", "install"],41 ["pnpm", "i"],42 ["yarn", "install"],43 ["bun", "install"],44 ["bun", "i"],45 ["pip", "install"],46 ["pip3", "install"],47 ["python", "-m", "pip", "install"],48 ["python3", "-m", "pip", "install"],49 ["uv", "sync"],50 ["uv", "pip", "install"],51 ["poetry", "install"],52 ["pipenv", "install"],53 ["pdm", "install"],54 ["go", "mod", "download"],55 ["cargo", "fetch"],56 ["bundle", "install"],57 ["pre-commit", "install-hooks"],58];5960const withoutEnv = (tokens: readonly string[]) => {61 const first = tokens.findIndex((token) => !/^\w+=/u.test(token));6263 return first === -1 ? [] : tokens.slice(first);64};6566const isSetup = (command: string) => {67 const tokens = withoutEnv(words(command));6869 return (70 (tokens.length === 1 && tokens[0] === "yarn") ||71 SETUP.some((prefix) => startsWith(tokens, prefix))72 );73};7475const RUNNERS: readonly (readonly string[])[] = [76 ["npx"],77 ["bunx"],78 ["pnpm", "exec"],79 ["pnpm", "dlx"],80 ["yarn", "exec"],81 ["yarn", "dlx"],82 ["npm", "exec", "--"],83 ["npm", "exec"],84 ["uv", "run"],85 ["poetry", "run"],86 ["pipenv", "run"],87 ["pdm", "run"],88 ["hatch", "run"],89 ["python", "-m"],90 ["python3", "-m"],91 // pnpm and yarn run a package's binary by its bare name: `pnpm vitest`.92 ["pnpm"],93 ["yarn"],94];9596const toolIndex = (tokens: readonly string[]): number => {97 let at = tokens.length - withoutEnv(tokens).length;9899 for (100 let runner = RUNNERS.find((prefix) => startsWith(tokens.slice(at), prefix));101 runner !== undefined;102 runner = RUNNERS.find((prefix) => startsWith(tokens.slice(at), prefix))103 ) {104 at += runner.length;105 }106107 return at;108};109110const CHECK_FLAGS = ["--check", "-c", "--list-different", "-l"];111112const TOOLS: readonly {113 readonly lane: Canonical;114 readonly tool: readonly string[];115 readonly when?: (args: readonly string[]) => boolean;116}[] = [117 { lane: "unit", tool: ["vitest"] },118 { lane: "unit", tool: ["jest"] },119 { lane: "unit", tool: ["mocha"] },120 { lane: "unit", tool: ["ava"] },121 { lane: "unit", tool: ["bun", "test"] },122 { lane: "unit", tool: ["node", "--test"] },123 { lane: "unit", tool: ["deno", "test"] },124 { lane: "unit", tool: ["pytest"] },125 { lane: "unit", tool: ["go", "test"] },126 { lane: "unit", tool: ["cargo", "test"] },127 { lane: "unit", tool: ["zig", "build", "test"] },128 { lane: "lint", tool: ["eslint"] },129 { lane: "lint", tool: ["oxlint"] },130 { lane: "lint", tool: ["biome", "lint"] },131 { lane: "lint", tool: ["biome", "check"] },132 { lane: "lint", tool: ["biome", "ci"] },133 { lane: "lint", tool: ["ruff", "check"] },134 {135 lane: "format",136 tool: ["ruff", "format"],137 when: (args) => hasAny(args, CHECK_FLAGS),138 },139 // Bare `ruff` is `ruff check`; `ruff format` without `--check` rewrites.140 { lane: "lint", tool: ["ruff"], when: (args) => args[0] !== "format" },141 { lane: "lint", tool: ["flake8"] },142 { lane: "lint", tool: ["pylint"] },143 { lane: "lint", tool: ["golangci-lint"] },144 { lane: "lint", tool: ["go", "vet"] },145 { lane: "lint", tool: ["cargo", "clippy"] },146 { lane: "lint", tool: ["stylelint"] },147 { lane: "lint", tool: ["next", "lint"] },148 { lane: "lint", tool: ["deno", "lint"] },149 { lane: "lint", tool: ["shellcheck"] },150 {151 lane: "build",152 tool: ["tsc"],153 when: (args) => hasAny(args, ["-b", "--build"]),154 },155 { lane: "types", tool: ["tsc"] },156 { lane: "types", tool: ["tsgo"] },157 { lane: "types", tool: ["vue-tsc"] },158 { lane: "types", tool: ["mypy"] },159 { lane: "types", tool: ["pyright"] },160 { lane: "types", tool: ["basedpyright"] },161 { lane: "types", tool: ["deno", "check"] },162 {163 lane: "format",164 tool: ["prettier"],165 when: (args) => hasAny(args, CHECK_FLAGS),166 },167 {168 lane: "format",169 tool: ["oxfmt"],170 when: (args) => hasAny(args, ["--check"]),171 },172 {173 lane: "format",174 tool: ["biome", "format"],175 when: (args) => !hasAny(args, ["--write"]),176 },177 {178 lane: "format",179 tool: ["black"],180 when: (args) => hasAny(args, ["--check"]),181 },182 {183 lane: "format",184 tool: ["cargo", "fmt"],185 when: (args) => hasAny(args, ["--check"]),186 },187 { lane: "format", tool: ["gofmt"], when: (args) => hasAny(args, ["-l"]) },188 {189 lane: "format",190 tool: ["deno", "fmt"],191 when: (args) => hasAny(args, ["--check"]),192 },193 { lane: "build", tool: ["vite", "build"] },194 { lane: "build", tool: ["next", "build"] },195 { lane: "build", tool: ["tsup"] },196 { lane: "build", tool: ["tsdown"] },197 { lane: "build", tool: ["cargo", "build"] },198 { lane: "build", tool: ["go", "build"] },199 { lane: "build", tool: ["zig", "build"] },200];201202const NAMED: readonly { readonly lane: Canonical; readonly names: RegExp }[] = [203 { lane: "unit", names: /^(?:tests?|unit|tests?[:-](?:unit|ci))$/u },204 { lane: "lint", names: /^(?:lint|lint[:-](?:check|ci)|eslint|oxlint)$/u },205 {206 lane: "types",207 names:208 /^(?:types?|typecheck|type-check|tsc|(?:check[:-])types|types?[:-]check|typecheck[:-]ci)$/u,209 },210 {211 lane: "format",212 names: /^(?:(?:format|fmt|prettier)[:-]check|check[:-](?:format|fmt))$/u,213 },214 { lane: "build", names: /^build$/u },215];216217const NEVER_A_LANE =218 /(?:^|[:-])(?:dev|start|serve|preview|watch|deploy|release|publish|prepare|install|clean|version|fix|docs)(?:$|[:-])/u;219220const namedLane = (name: string): Option.Option<Canonical> =>221 Option.fromNullishOr(NAMED.find(({ names }) => names.test(name))?.lane);222223const asLaneName = (name: string): Option.Option<string> =>224 Option.liftPredicate(225 name.replaceAll(/[^A-Za-z0-9-]+/gu, "-").replaceAll(/^-+|-+$/gu, ""),226 isLaneName227 );228229const scriptLane = (name: string): Option.Option<string> =>230 NEVER_A_LANE.test(name) ? Option.none() : asLaneName(name);231232const FIXERS = ["--fix", "--write"];233234const fixes = (body: string) =>235 body.split("&&").some((part) => hasAny(words(part), FIXERS));236237const toolLane = (command: string): Option.Option<Canonical> => {238 const tokens = words(command);239 const rest = tokens.slice(toolIndex(tokens));240241 if (hasAny(rest, FIXERS)) {242 return Option.none();243 }244245 return Option.fromNullishOr(246 TOOLS.find(247 ({ tool, when }) =>248 startsWith(rest, tool) && (when?.(rest.slice(tool.length)) ?? true)249 )?.lane250 );251};252253type PackageManager = "bun" | "npm" | "pnpm" | "yarn";254255const MANAGERS: readonly PackageManager[] = ["bun", "npm", "pnpm", "yarn"];256257const isManager = (word: string | undefined): word is PackageManager =>258 MANAGERS.some((manager) => manager === word);259260interface Scripts {261 readonly byName: ReadonlyMap<string, string>;262 readonly manager: Option.Option<PackageManager>;263}264265const scriptOf = (command: string, scripts: Scripts): Option.Option<string> => {266 const [manager, verb, name] = withoutEnv(words(command));267268 if (!isManager(manager)) {269 return Option.none();270 }271272 if (verb === "test" || verb === "t") {273 return manager === "bun" && verb === "test"274 ? Option.none()275 : Option.some("test");276 }277278 if ((verb === "run" || verb === "run-script") && name !== undefined) {279 return Option.some(name);280 }281282 return manager !== "npm" && verb !== undefined && scripts.byName.has(verb)283 ? Option.some(verb)284 : Option.none();285};286287const TASKS: readonly (readonly string[])[] = [288 ["make"],289 ["just"],290 ["task"],291 ["mise", "run"],292 ["turbo", "run"],293 ["turbo"],294];295296const taskOf = (command: string): Option.Option<string> => {297 const tokens = withoutEnv(words(command));298 const runner = TASKS.find((prefix) => startsWith(tokens, prefix)) ?? [];299300 const names = tokens301 .slice(runner.length)302 .filter((word) => !word.startsWith("-"));303304 return runner.length > 0 && names.length > 0305 ? Option.some(names.join("-"))306 : Option.none();307};308309const segments = (body: string) => body.split("&&").map((part) => part.trim());310311const bodyOf = (312 name: string,313 scripts: Scripts,314 depth = 0315): Option.Option<string> =>316 Option.flatMap(Option.fromNullishOr(scripts.byName.get(name)), (body) => {317 const [only, ...more] = segments(body);318319 const inner =320 only === undefined || more.length > 0 || depth > 3321 ? Option.none()322 : scriptOf(only, scripts);323324 return Option.isSome(inner) && inner.value !== name325 ? Option.orElse(bodyOf(inner.value, scripts, depth + 1), () =>326 Option.some(body)327 )328 : Option.some(body);329 });330331const runScript = (manager: PackageManager, name: string) =>332 manager === "npm" && name === "test" ? "npm test" : `${manager} run ${name}`;333334const insertBefore = (335 tokens: readonly string[],336 marker: string,337 added: readonly string[]338) => {339 const at = tokens.indexOf(marker);340341 return at === -1342 ? [...tokens, ...added]343 : [...tokens.slice(0, at), ...added, ...tokens.slice(at)];344};345346const isGoPackages = (arg: string) =>347 arg === "." ||348 arg.startsWith("./") ||349 arg.startsWith("../") ||350 arg.includes("...");351352// Go runs a package and Cargo a test target, so theirs name the file's353// directory or stem through the shell.354const oneFile = (command: string): Option.Option<string> => {355 const tokens = words(command);356 const at = toolIndex(tokens);357 const head = tokens.slice(0, at);358 const rest = tokens.slice(at);359360 const write = (...parts: readonly string[]) =>361 Option.some([...head, ...parts].join(" "));362363 if (startsWith(rest, ["vitest"])) {364 const args = rest[1] === "run" ? rest.slice(2) : rest.slice(1);365366 return write("vitest", "run", ...args, PATH_PLACEHOLDER);367 }368369 if (370 ["jest", "mocha", "ava", "pytest"].some((tool) => rest[0] === tool) ||371 [372 ["bun", "test"],373 ["node", "--test"],374 ["deno", "test"],375 ].some((tool) => startsWith(rest, tool))376 ) {377 return write(...rest, PATH_PLACEHOLDER);378 }379380 if (startsWith(rest, ["go", "test"])) {381 const flags = rest.slice(2).filter((arg) => !isGoPackages(arg));382383 return write("go", "test", ...flags, `"./$(dirname ${PATH_PLACEHOLDER})"`);384 }385386 if (startsWith(rest, ["cargo", "test"])) {387 return write(388 ...insertBefore(rest, "--", [389 "--test",390 `"$(basename ${PATH_PLACEHOLDER} .rs)"`,391 ])392 );393 }394395 return Option.none();396};397398interface Step {399 readonly command: string;400 readonly name: Option.Option<string>;401}402403interface Offer {404 readonly command: string;405 readonly fallback: Option.Option<string>;406 readonly lane: string;407 readonly path: string;408 readonly runner: { readonly body: string; readonly path: string };409}410411interface Read {412 readonly offers: readonly Offer[];413 readonly path: string;414 readonly setup: readonly string[];415}416417const PACKAGE_JSON = "package.json";418419const oneLine = (message: string) =>420 message421 .split("\n")422 .map((line) => line.trim())423 .filter(Boolean)424 .join(" ");425426// YAML errors keep their first line (the rest is a code frame).427const readYaml = <A>(428 schema: Schema.ConstraintDecoder<A>,429 content: string430): Result.Result<A, string> =>431 Result.try({432 catch: (thrown) => String(thrown).split("\n")[0] ?? "unreadable YAML",433 try: () =>434 Schema.decodeUnknownResult(schema)(435 parse(content, { logLevel: "error", strict: false })436 ),437 }).pipe(438 Result.flatMap((decoded) =>439 Result.mapError(decoded, (issue) => oneLine(issue.message))440 )441 );442443const shellCommands = (text: string): readonly string[] =>444 text445 .replaceAll("\\\n", " ")446 .split("\n")447 .map((line) => line.trim())448 .filter((line) => line !== "" && !line.startsWith("#"))449 .flatMap(segments)450 .filter((command) => command !== "");451452const Workflow = Schema.Struct({453 jobs: Schema.Record(454 Schema.String,455 Schema.Struct({456 steps: Schema.optionalKey(457 Schema.Array(Schema.Struct({ run: Schema.optionalKey(Schema.String) }))458 ),459 })460 ),461});462463const workflowSteps = (content: string) =>464 readYaml(Workflow, content).pipe(465 Result.map((workflow) =>466 Object.values(workflow.jobs)467 .flatMap((job) => job.steps ?? [])468 .flatMap((step) => shellCommands(step.run ?? ""))469 // A workflow expression has no value until the workflow runs.470 .filter((command) => !command.includes("${{"))471 .map((command): Step => ({ command, name: Option.none() }))472 )473 );474475const LefthookHook = Schema.Struct({476 commands: Schema.optionalKey(477 Schema.Record(478 Schema.String,479 Schema.Struct({ run: Schema.optionalKey(Schema.String) })480 )481 ),482 jobs: Schema.optionalKey(483 Schema.Array(484 Schema.Struct({485 name: Schema.optionalKey(Schema.String),486 run: Schema.optionalKey(Schema.String),487 })488 )489 ),490});491492const Lefthook = Schema.Struct({493 "pre-commit": Schema.optionalKey(LefthookHook),494 "pre-push": Schema.optionalKey(LefthookHook),495});496497// Lefthook fills these with the files a commit touches; a check runs on all.498const lefthookFiles = (command: string) =>499 command.replaceAll(/\{(?:staged_files|push_files|all_files|files)\}/gu, ".");500501const lefthookSteps = (content: string) =>502 readYaml(Lefthook, content).pipe(503 Result.map((config) =>504 [config["pre-commit"], config["pre-push"]].flatMap((hook) => [505 ...Object.entries(hook?.commands ?? {}).flatMap(([name, { run }]) =>506 shellCommands(lefthookFiles(run ?? "")).map((command): Step => ({507 command,508 name: Option.some(name),509 }))510 ),511 ...(hook?.jobs ?? []).flatMap(({ name, run }) =>512 shellCommands(lefthookFiles(run ?? "")).map((command): Step => ({513 command,514 name: Option.fromNullishOr(name),515 }))516 ),517 ])518 )519 );520521// Husky's own lines source its helper; they aren't the project's commands.522const huskySteps = (content: string): readonly Step[] =>523 shellCommands(content)524 .filter((line) => !/^(?:\.|source)\s/u.test(line))525 .map((command) => ({ command, name: Option.none() }));526527const PreCommit = Schema.Struct({528 repos: Schema.Array(529 Schema.Struct({530 hooks: Schema.Array(531 Schema.Struct({532 id: Schema.NonEmptyString,533 stages: Schema.optionalKey(Schema.Array(Schema.String)),534 })535 ),536 })537 ),538});539540const PRE_COMMIT_STAGES: ReadonlySet<string> = new Set([541 "commit",542 "pre-commit",543]);544545const HOOKS: ReadonlyMap<string, Canonical> = new Map([546 ["ruff", "lint"],547 ["ruff-check", "lint"],548 ["flake8", "lint"],549 ["pylint", "lint"],550 ["eslint", "lint"],551 ["golangci-lint", "lint"],552 ["ruff-format", "format"],553 ["black", "format"],554 ["prettier", "format"],555 ["isort", "format"],556 ["mypy", "types"],557 ["pyright", "types"],558 ["pytest", "unit"],559]);560561const fileNamed = (path: string) => (file: RepoFile) => file.path === path;562563const workflowFile = /^\.(?:github|forgejo)\/workflows\/[^/]+\.ya?ml$/u;564565const isWorkflow = (file: RepoFile) => workflowFile.test(file.path);566567const huskyFile = /^\.husky\/pre-(?:commit|push)$/u;568569const LEFTHOOK: ReadonlySet<string> = new Set([570 "lefthook.yml",571 "lefthook.yaml",572 ".lefthook.yml",573 ".lefthook.yaml",574]);575576const PRE_COMMIT = ".pre-commit-config.yaml";577578const byPath = (left: RepoFile, right: RepoFile) =>579 left.path < right.path ? -1 : Number(left.path > right.path);580581const PackageJson = Schema.fromJsonString(582 Schema.Struct({583 packageManager: Schema.optionalKey(Schema.String),584 scripts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),585 })586);587588const LOCKFILES: readonly (readonly [string, PackageManager])[] = [589 ["bun.lock", "bun"],590 ["bun.lockb", "bun"],591 ["pnpm-lock.yaml", "pnpm"],592 ["yarn.lock", "yarn"],593 ["package-lock.json", "npm"],594];595596const offerFromStep = (597 step: Step,598 path: string,599 scripts: Scripts600): Option.Option<Offer> => {601 const script = scriptOf(step.command, scripts);602 const body = Option.flatMap(script, (name) => bodyOf(name, scripts));603604 const runner = Option.match(body, {605 onNone: () => ({ body: step.command, path }),606 onSome: (text) => ({ body: text, path: PACKAGE_JSON }),607 });608609 const task = Option.orElse(script, () => taskOf(step.command));610 const ownName = Option.orElse(step.name, () => task);611 const byBody = Option.firstSomeOf(segments(runner.body).map(toolLane));612613 const lane = Option.isSome(task)614 ? Option.orElse(namedLane(task.value), () => byBody)615 : Option.orElse(toolLane(step.command), () =>616 Option.flatMap(step.name, namedLane)617 );618619 const fallback = Option.flatMap(ownName, scriptLane);620621 const neverALane = [step.name, task].some((name) =>622 Option.exists(name, (text) => NEVER_A_LANE.test(text))623 );624625 return neverALane || fixes(runner.body)626 ? Option.none()627 : Option.map(628 Option.orElse(lane, () => fallback),629 (name) => ({630 command: step.command,631 fallback,632 lane: name,633 path,634 runner,635 })636 );637};638639const readSteps = (640 file: RepoFile,641 steps: readonly Step[],642 scripts: Scripts643): Read => ({644 offers: steps.flatMap((step) =>645 isSetup(step.command)646 ? []647 : Option.toArray(offerFromStep(step, file.path, scripts))648 ),649 path: file.path,650 setup: steps.flatMap(({ command }) => (isSetup(command) ? [command] : [])),651});652653const readPreCommit = (file: RepoFile) =>654 readYaml(PreCommit, file.content).pipe(655 Result.map((config): Read => ({656 offers: config.repos657 .flatMap(({ hooks }) => hooks)658 .filter(659 ({ stages }) =>660 stages === undefined ||661 stages.some((stage) => PRE_COMMIT_STAGES.has(stage))662 )663 .flatMap(({ id }) => {664 const command = `pre-commit run ${id} --all-files`;665 const fallback = asLaneName(id);666667 return Option.toArray(668 Option.map(669 Option.orElse(670 Option.fromNullishOr(HOOKS.get(id)),671 () => fallback672 ),673 (lane) => ({674 command,675 fallback,676 lane,677 path: file.path,678 runner: { body: command, path: file.path },679 })680 )681 );682 }),683 path: file.path,684 setup: [],685 }))686 );687688const readScripts = (manager: PackageManager, scripts: Scripts): Read => ({689 offers: [...scripts.byName].flatMap(([name, body]) => {690 const lane = Option.orElse(namedLane(name), () =>691 Option.firstSomeOf(segments(body).map(toolLane))692 );693694 return fixes(body) || NEVER_A_LANE.test(name)695 ? []696 : Option.toArray(697 Option.map(lane, (found) => ({698 command: runScript(manager, name),699 fallback: scriptLane(name),700 lane: found,701 path: PACKAGE_JSON,702 runner: {703 body: Option.getOrElse(bodyOf(name, scripts), () => body),704 path: PACKAGE_JSON,705 },706 }))707 );708 }),709 path: PACKAGE_JSON,710 setup: [],711});712713type Lanes = ReadonlyMap<string, Offer>;714715// One group's offers, merged under the lanes already found by the groups716// before it. Inside a group a second offer for a lane takes its own name;717// a later group only fills lanes the earlier ones lack.718const mergeGroup = (found: Lanes, group: readonly Read[]): Lanes => {719 const added = new Map<string, Offer>();720 const commands = new Set([...found.values()].map(({ command }) => command));721722 for (const offer of group.flatMap(({ offers }) => offers)) {723 const free = (lane: string) => !found.has(lane) && !added.has(lane);724725 const repeated = [...added.values()].some(726 ({ command }) => command === offer.command727 );728729 if (!commands.has(offer.command) && !repeated && !found.has(offer.lane)) {730 const lane = free(offer.lane)731 ? Option.some(offer.lane)732 : Option.filter(offer.fallback, free);733734 if (Option.isSome(lane)) {735 added.set(lane.value, offer);736 }737 }738 }739740 return new Map([...found, ...added]);741};742743const managerOf = (744 files: readonly RepoFile[],745 scripts: Scripts,746 setup: readonly string[]747): PackageManager =>748 Option.firstSomeOf([749 scripts.manager,750 Option.fromNullishOr(751 LOCKFILES.find(([lockfile]) => files.some(fileNamed(lockfile)))?.[1]752 ),753 Option.fromNullishOr(754 setup.map((command) => words(command)[0]).find(isManager)755 ),756 ]).pipe(Option.getOrElse((): PackageManager => "npm"));757758const INSTALL = {759 bun: "bun install --frozen-lockfile",760 npm: "npm ci",761 pnpm: "pnpm install --frozen-lockfile",762 yarn: "yarn install --frozen-lockfile",763} as const satisfies Record<PackageManager, string>;764765const skip = (path: string, reason: string) => `skipped ${path}: ${reason}`;766767const readEach = (768 files: readonly RepoFile[],769 read: (file: RepoFile) => Result.Result<Read, string>770) => {771 const results = files.map((file) =>772 Result.mapError(read(file), (reason) => skip(file.path, reason))773 );774775 return {776 reads: Arr.getSuccesses(results),777 skipped: Arr.getFailures(results),778 };779};780781const readPackage = (files: readonly RepoFile[]) =>782 Option.map(783 Option.fromNullishOr(files.find(fileNamed(PACKAGE_JSON))),784 (file) =>785 Result.mapError(Schema.decodeResult(PackageJson)(file.content), (issue) =>786 skip(PACKAGE_JSON, oneLine(issue.message))787 )788 );789790const scriptsOf = (root: Option.Option<typeof PackageJson.Type>): Scripts => ({791 byName: new Map(792 Object.entries(Option.getOrUndefined(root)?.scripts ?? {}).filter(793 ([, body]) => body.trim() !== ""794 )795 ),796 manager: Option.flatMap(root, ({ packageManager = "" }) =>797 Option.fromNullishOr(798 MANAGERS.find((manager) => packageManager.startsWith(`${manager}@`))799 )800 ),801});802803type Setup = readonly (readonly [command: string, path: string])[];804805// The install commands of the source group setup comes from, plus the hook806// environments pre-commit's lanes need before the network closes.807const setupOf = (reads: readonly Read[], lanes: Lanes): Setup => {808 const found = reads.flatMap(({ path, setup }) =>809 setup.map((command) => [command, path] as const)810 );811812 const hooks = [...lanes.values()].some(({ path }) => path === PRE_COMMIT)813 ? [["pre-commit install-hooks", PRE_COMMIT] as const]814 : [];815816 return [...new Map([...found, ...hooks])];817};818819const testOf = (lanes: Lanes) =>820 Option.map(Option.fromNullishOr(lanes.get("unit")), (unit) =>821 Option.match(Option.firstSomeOf(segments(unit.runner.body).map(oneFile)), {822 onNone: () => ({ command: unit.command, path: unit.path }),823 onSome: (command) => ({ command, path: unit.runner.path }),824 })825 );826827// Sources rank CI workflows, then hooks, then root scripts; a lower source828// only adds lanes the higher ones lack.829export const findRunBlock = (files: readonly RepoFile[]): FoundRunBlock => {830 const sorted = files.toSorted(byPath);831 const root = readPackage(sorted);832 const rootPackage = Option.flatMap(root, Result.getSuccess);833 const scripts = scriptsOf(rootPackage);834835 const workflows = readEach(sorted.filter(isWorkflow), (file) =>836 Result.map(workflowSteps(file.content), (steps) =>837 readSteps(file, steps, scripts)838 )839 );840841 const lefthook = readEach(842 sorted.filter(({ path }) => LEFTHOOK.has(path)).slice(0, 1),843 (file) =>844 Result.map(lefthookSteps(file.content), (steps) =>845 readSteps(file, steps, scripts)846 )847 );848849 const husky = sorted.flatMap((file) =>850 huskyFile.test(file.path)851 ? [readSteps(file, huskySteps(file.content), scripts)]852 : []853 );854855 const preCommit = readEach(856 sorted.filter(fileNamed(PRE_COMMIT)),857 readPreCommit858 );859860 const hooks = [...lefthook.reads, ...husky, ...preCommit.reads];861862 const installing =863 [workflows.reads, hooks].find((reads) =>864 reads.some(({ setup }) => setup.length > 0)865 ) ?? [];866867 const manager = managerOf(868 sorted,869 scripts,870 installing.flatMap(({ setup }) => setup)871 );872873 let lanes: Lanes = new Map();874875 for (const group of [876 workflows.reads,877 hooks,878 Option.isSome(rootPackage) ? [readScripts(manager, scripts)] : [],879 ]) {880 lanes = mergeGroup(lanes, group);881 }882883 const setup = setupOf(installing, lanes);884885 const lockfile = LOCKFILES.find(886 ([name, owner]) => owner === manager && sorted.some(fileNamed(name))887 );888889 // A frozen install refuses to run without a lockfile, so none means a plain one.890 const inferred =891 setup.length === 0 && Option.isSome(rootPackage)892 ? Option.some(893 lockfile === undefined894 ? { command: `${manager} install`, from: PACKAGE_JSON }895 : { command: INSTALL[manager], from: lockfile[0] }896 )897 : Option.none();898899 const commands = [900 ...setup.map(([command]) => command),901 ...Option.toArray(Option.map(inferred, ({ command }) => command)),902 ];903904 const test = testOf(lanes);905906 return {907 run: {908 ...(lanes.size > 0 && {909 checks: Object.fromEntries(910 [...lanes].map(([lane, { command }]) => [lane, command])911 ),912 }),913 ...(commands.length > 0 && { setup: commands.join(" && ") }),914 ...(Option.isSome(test) && { test: test.value.command }),915 },916 sources: [917 ...new Set(setup.map(([, path]) => `setup from ${path}`)),918 ...Option.toArray(919 Option.map(inferred, ({ from }) => `setup inferred from ${from}`)920 ),921 ...Option.toArray(Option.map(test, ({ path }) => `test from ${path}`)),922 ...[...lanes].map(([lane, { path }]) => `checks.${lane} from ${path}`),923 ...Option.toArray(Option.flatMap(root, Result.getFailure)),924 ...workflows.skipped,925 ...lefthook.skipped,926 ...preCommit.skipped,927 ],928 };929};