(
files: readonly string[],
edges: readonly ModuleDependency[]
)
| 416 | * finitely many edges and each pass either places a file or removes one. |
| 417 | */ |
| 418 | export function topsortFiles( |
| 419 | files: readonly string[], |
| 420 | edges: readonly ModuleDependency[] |
| 421 | ): TopsortResult { |
| 422 | const nodes = [...new Set(files)].sort(compareText); |
| 423 | const normalized = normalizeEdges(edges, nodes); |
| 424 | |
| 425 | // `dependents.get(x)` is every file that imports x: placing x releases them. |
| 426 | const dependents = new Map<string, string[]>(); |
| 427 | const inDegree = new Map<string, number>(); |
| 428 | for (const node of nodes) { |
| 429 | dependents.set(node, []); |
| 430 | inDegree.set(node, 0); |
| 431 | } |
| 432 | const live = new Set<string>(); |
| 433 | for (const edge of normalized) { |
| 434 | dependents.get(edge.to)!.push(edge.from); |
| 435 | inDegree.set(edge.from, (inDegree.get(edge.from) ?? 0) + 1); |
| 436 | live.add(`${edge.from} ${edge.to}`); |
| 437 | } |
| 438 | |
| 439 | const ready: string[] = nodes.filter(node => inDegree.get(node) === 0); |
| 440 | const order: string[] = []; |
| 441 | const placed = new Set<string>(); |
| 442 | const brokenEdges: ModuleDependency[] = []; |
| 443 | |
| 444 | const release = (node: string): void => { |
| 445 | for (const dependent of dependents.get(node) ?? []) { |
| 446 | const left = (inDegree.get(dependent) ?? 0) - 1; |
| 447 | inDegree.set(dependent, left); |
| 448 | if (left === 0 && !placed.has(dependent)) { |
| 449 | insertSorted(ready, dependent); |
| 450 | } |
| 451 | } |
| 452 | }; |
| 453 | |
| 454 | while (order.length < nodes.length) { |
| 455 | if (ready.length === 0) { |
| 456 | const broken = breakCycle(normalized, live, placed, inDegree); |
| 457 | if (broken === undefined) { |
| 458 | // Unreachable while the bookkeeping above holds: a file that is |
| 459 | // neither placed nor blocked by a live edge has in-degree zero |
| 460 | // and is already in the ready set. Bailing out in path order |
| 461 | // rather than looping is the safe reading of an impossible |
| 462 | // state. |
| 463 | for (const node of nodes) { |
| 464 | if (!placed.has(node)) { |
| 465 | placed.add(node); |
| 466 | order.push(node); |
| 467 | } |
| 468 | } |
| 469 | break; |
| 470 | } |
| 471 | brokenEdges.push(broken); |
| 472 | live.delete(`${broken.from} ${broken.to}`); |
| 473 | const left = (inDegree.get(broken.from) ?? 0) - 1; |
| 474 | inDegree.set(broken.from, left); |
| 475 | if (left === 0 && !placed.has(broken.from)) { |
no test coverage detected