64 lines · 2.5 KBRaw
| 1 | import type { ConfigProblem, Job } from "./pipeline.ts"; |
| 2 | |
| 3 | /** The `needs` edges between jobs. Built only through `JobGraph.check`, so every instance has known needs and no cycle. */ |
| 4 | export class JobGraph { |
| 5 | readonly #needs: ReadonlyMap<string, readonly string[]>; |
| 6 | readonly #dependents: ReadonlyMap<string, readonly string[]>; |
| 7 | |
| 8 | private constructor(needs: ReadonlyMap<string, readonly string[]>) { |
| 9 | this.#needs = needs; |
| 10 | const dependents = new Map<string, string[]>([...needs.keys()].map((name) => [name, []])); |
| 11 | for (const [name, required] of needs) for (const need of required) dependents.get(need)!.push(name); |
| 12 | this.#dependents = dependents; |
| 13 | } |
| 14 | |
| 15 | static check(jobs: ReadonlyMap<string, Pick<Job, "needs">>): { readonly graph: JobGraph } | { readonly problems: readonly ConfigProblem[] } { |
| 16 | const problems: ConfigProblem[] = []; |
| 17 | for (const [name, job] of jobs) { |
| 18 | job.needs.forEach((need, index) => { |
| 19 | if (need === name) problems.push({ path: `jobs.${name}.needs[${index}]`, message: "A job cannot need itself." }); |
| 20 | else if (!jobs.has(need)) problems.push({ path: `jobs.${name}.needs[${index}]`, message: `No job is named "${need}".` }); |
| 21 | }); |
| 22 | } |
| 23 | if (problems.length) return { problems }; |
| 24 | const needs = new Map([...jobs].map(([name, job]) => [name, [...new Set(job.needs)]])); |
| 25 | const cycle = findCycle(needs); |
| 26 | if (cycle) return { problems: [{ path: `jobs.${cycle[0]}.needs`, message: `These jobs need each other in a cycle: ${cycle.join(" → ")}.` }] }; |
| 27 | return { graph: new JobGraph(needs) }; |
| 28 | } |
| 29 | |
| 30 | get names(): readonly string[] { |
| 31 | return [...this.#needs.keys()]; |
| 32 | } |
| 33 | |
| 34 | needsOf(name: string): readonly string[] { |
| 35 | return this.#needs.get(name) ?? []; |
| 36 | } |
| 37 | |
| 38 | dependentsOf(name: string): readonly string[] { |
| 39 | return this.#dependents.get(name) ?? []; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | function findCycle(needs: ReadonlyMap<string, readonly string[]>): string[] | null { |
| 44 | const state = new Map<string, "visiting" | "done">(); |
| 45 | const path: string[] = []; |
| 46 | const visit = (name: string): string[] | null => { |
| 47 | if (state.get(name) === "done") return null; |
| 48 | if (state.get(name) === "visiting") return [...path.slice(path.indexOf(name)), name]; |
| 49 | state.set(name, "visiting"); |
| 50 | path.push(name); |
| 51 | for (const need of needs.get(name)!) { |
| 52 | const cycle = visit(need); |
| 53 | if (cycle) return cycle; |
| 54 | } |
| 55 | path.pop(); |
| 56 | state.set(name, "done"); |
| 57 | return null; |
| 58 | }; |
| 59 | for (const name of needs.keys()) { |
| 60 | const cycle = visit(name); |
| 61 | if (cycle) return cycle; |
| 62 | } |
| 63 | return null; |
| 64 | } |