-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvalidate-circular-deps.ts
More file actions
254 lines (220 loc) · 6.66 KB
/
validate-circular-deps.ts
File metadata and controls
254 lines (220 loc) · 6.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Circular dependency checker for workspace packages.
*
* Detects circular dependencies between packages in the workspace.
*
* Library usage:
* ```typescript
* import * as circularDeps from "@eserstack/codebase/validate-circular-deps";
*
* const result = await circularDeps.checkCircularDeps();
* if (result.hasCycles) {
* console.log("Cycles found:", result.cycles);
* }
* ```
*
* CLI usage:
* deno run --allow-all ./validate-circular-deps.ts
*
* @module
*/
import * as primitives from "@eserstack/primitives";
import * as functions from "@eserstack/functions";
import type * as shellArgs from "@eserstack/shell/args";
import * as span from "@eserstack/streams/span";
import * as workspaceDiscovery from "./workspace-discovery.ts";
import { createCliOutput, runCliMain } from "./cli-support.ts";
const out = createCliOutput();
/**
* Options for circular dependency checking.
*/
export type CheckCircularDepsOptions = {
/** Root directory (default: ".") */
readonly root?: string;
};
/**
* Result of circular dependency check.
*/
export type CheckCircularDepsResult = {
/** Whether any cycles were found */
readonly hasCycles: boolean;
/** Detected cycles (each cycle is an array of package names) */
readonly cycles: string[][];
/** Number of packages checked */
readonly packagesChecked: number;
};
/**
* Builds a dependency graph from package configurations.
*
* @param packages - Discovered packages
* @returns Map of package name to its dependencies
*/
const buildDependencyGraph = (
packages: workspaceDiscovery.DiscoveredPackage[],
): Map<string, string[]> => {
const graph = new Map<string, string[]>();
const packageNames = new Set(packages.map((p) => p.name));
for (const pkg of packages) {
const deps: string[] = [];
// Get dependencies from raw loaded files (package.json)
for (const file of pkg.config._loadedFiles) {
const content = file.content as Record<string, unknown>;
// Check dependencies field
const dependencies = content["dependencies"] as
| Record<string, string>
| undefined;
if (dependencies !== undefined) {
for (const depName of Object.keys(dependencies)) {
if (packageNames.has(depName)) {
deps.push(depName);
}
}
}
// Check imports field (deno.json style)
const imports = content["imports"] as Record<string, string> | undefined;
if (imports !== undefined) {
for (const value of Object.values(imports)) {
if (packageNames.has(value)) {
deps.push(value);
}
}
}
}
graph.set(pkg.name, [...new Set(deps)]); // dedupe
}
return graph;
};
/**
* Detects cycles in a directed graph using DFS.
*
* @param graph - Dependency graph
* @returns Array of detected cycles
*/
const detectCycles = (graph: Map<string, string[]>): string[][] => {
const cycles: string[][] = [];
const visited = new Set<string>();
const recursionStack = new Set<string>();
const path: string[] = [];
const dfs = (node: string): void => {
visited.add(node);
recursionStack.add(node);
path.push(node);
const neighbors = graph.get(node) ?? [];
for (const neighbor of neighbors) {
if (!visited.has(neighbor)) {
dfs(neighbor);
} else if (recursionStack.has(neighbor)) {
// Found a cycle
const cycleStart = path.indexOf(neighbor);
const cycle = path.slice(cycleStart);
cycle.push(neighbor); // Complete the cycle
cycles.push(cycle);
}
}
path.pop();
recursionStack.delete(node);
};
for (const node of graph.keys()) {
if (!visited.has(node)) {
dfs(node);
}
}
return cycles;
};
/**
* Checks for circular dependencies between workspace packages.
*
* @param options - Check options
* @returns Check result
*/
export const checkCircularDeps = async (
options: CheckCircularDepsOptions = {},
): Promise<CheckCircularDepsResult> => {
const { root = "." } = options;
const packages = await workspaceDiscovery.discoverPackages(root);
const graph = buildDependencyGraph(packages);
const cycles = detectCycles(graph);
return {
hasCycles: cycles.length > 0,
cycles,
packagesChecked: packages.length,
};
};
// --- Handler ---
/** Handler: wraps checkCircularDeps as a Task via fromPromise. */
export const checkCircularDepsHandler: functions.handler.Handler<
CheckCircularDepsOptions,
CheckCircularDepsResult,
Error
> = (input) => functions.task.fromPromise(() => checkCircularDeps(input));
// --- CLI Adapter ---
/** Adapter: functions.triggers.CliEvent → CheckCircularDepsOptions (no flags needed). */
const cliAdapter: functions.handler.Adapter<
functions.triggers.CliEvent,
CheckCircularDepsOptions
> = (
_event,
) => primitives.results.ok({ root: "." });
// --- CLI ResponseMapper ---
/** ResponseMapper: formats CheckCircularDepsResult for CLI output. */
const cliResponseMapper: functions.handler.ResponseMapper<
CheckCircularDepsResult,
Error | functions.handler.AdaptError,
shellArgs.CliResult<void>
> = (result) => {
if (primitives.results.isFail(result)) {
out.writeln(
span.red("✗"),
span.text(
" " +
(result.error instanceof Error
? result.error.message
: String(result.error)),
),
);
return primitives.results.fail({ exitCode: 1 });
}
const { value } = result;
out.writeln(
span.blue("ℹ"),
span.text(` Checked ${value.packagesChecked} packages.`),
);
if (value.hasCycles) {
out.writeln(
span.red("✗"),
span.text(
` Found ${value.cycles.length} circular dependencies:`,
),
);
for (const cycle of value.cycles) {
out.writeln(
span.yellow("⚠"),
span.text(` ${cycle.join(" → ")}`),
);
}
return primitives.results.fail({ exitCode: 1 });
}
out.writeln(
span.green("✓"),
span.text(" No circular dependencies found."),
);
return primitives.results.ok(undefined);
};
// --- CLI Trigger ---
/** Runnable CLI trigger for check-circular-deps. */
export const handleCli: (
event: functions.triggers.CliEvent,
) => Promise<shellArgs.CliResult<void>> = functions.handler.createTrigger({
handler: checkCircularDepsHandler,
adaptInput: cliAdapter,
adaptOutput: cliResponseMapper,
});
/** CLI entry point for dispatcher compatibility. */
export const main = async (
_cliArgs?: readonly string[],
): Promise<shellArgs.CliResult<void>> =>
await handleCli({ command: "validate-circular-deps", args: [], flags: {} });
if (import.meta.main) {
runCliMain(await main(), out);
}