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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
//! Dependency Analysis command - Build and analyze import dependency graphs
//!
//! Wires tldr-core::analysis::deps to the CLI (Session 7 Phase 5).
//!
//! # Features
//! - Internal dependency graph building
//! - Circular dependency detection
//! - External dependency tracking (optional)
//! - Package-level collapsing (optional)
//! - Multiple output formats: JSON, text, DOT
//!
//! # Risk Mitigations
//! - S7-R31: Command registered in mod.rs and main.rs
//! - S7-R33: analyze_dependencies exported from tldr_core::analysis::deps
//! - S7-R34: Uses Language enum from tldr_core
//! - S7-R35: DepsOptions has pub fields
//! - S7-R36: Exit codes documented
use std::path::PathBuf;
use anyhow::Result;
use clap::Args;
use tldr_core::analysis::deps::{
analyze_dependencies, format_deps_dot, format_deps_text, DepsOptions,
};
use tldr_core::Language;
use crate::output::{OutputFormat, OutputWriter};
/// Analyze module dependencies
///
/// Build import dependency graphs for a project, detect circular dependencies,
/// and optionally include external (third-party) dependencies.
///
/// # Examples
///
/// ```bash
/// # Analyze current directory
/// tldr deps
///
/// # Analyze with external dependencies
/// tldr deps --include-external
///
/// # Only show circular dependencies
/// tldr deps --show-cycles
///
/// # Output as text
/// tldr deps -f text
///
/// # Output as DOT for graphviz
/// tldr deps -f dot | dot -Tpng -o deps.png
/// ```
#[derive(Debug, Args)]
pub struct DepsArgs {
/// Path to analyze (directory)
#[arg(default_value = ".")]
pub path: PathBuf,
/// Output format override (backwards compatibility, prefer global --format/-f)
#[arg(long = "output", short = 'o', hide = true)]
pub output: Option<String>,
/// Programming language filter: python, typescript, go, rust
#[arg(long, short = 'l')]
pub lang: Option<Language>,
// === Dependency Options ===
/// Include external (third-party) dependencies in the report
#[arg(long)]
pub include_external: bool,
/// Collapse files into package-level nodes
#[arg(long)]
pub collapse_packages: bool,
/// Maximum transitive depth (None = unlimited)
#[arg(long, short = 'd')]
pub depth: Option<usize>,
// === Cycle Detection ===
/// Only show circular dependencies (skip full graph)
#[arg(long)]
pub show_cycles: bool,
/// Maximum cycle length to report (default: 10)
#[arg(long, default_value = "10")]
pub max_cycle_length: usize,
}
impl DepsArgs {
/// Resolve the effective output format.
///
/// If the user passed the hidden backward-compat `--output`/`-o` flag,
/// that value takes precedence. Otherwise the global `--format`/`-f`
/// value is used.
pub fn effective_format(&self, global: OutputFormat) -> OutputFormat {
match self.output.as_deref() {
Some("text") => OutputFormat::Text,
Some("dot") => OutputFormat::Dot,
Some("compact") => OutputFormat::Compact,
Some("json") => OutputFormat::Json,
Some(_) => global, // Unknown value falls back to global
None => global,
}
}
/// Run the deps command
pub fn run(&self, format: OutputFormat, quiet: bool) -> Result<()> {
let effective = self.effective_format(format);
let writer = OutputWriter::new(
if effective == OutputFormat::Dot {
OutputFormat::Text // DOT is text-based rendering
} else {
effective
},
quiet,
);
// Build options from args
let options = DepsOptions {
include_external: self.include_external,
collapse_packages: self.collapse_packages,
max_depth: self.depth,
show_cycles_only: self.show_cycles,
max_cycle_length: Some(self.max_cycle_length),
language: self.lang.as_ref().map(|l| l.as_str().to_string()),
};
writer.progress(&format!(
"Analyzing dependencies in {}...",
self.path.display()
));
// Run analysis
let report = analyze_dependencies(&self.path, &options)?;
// Output based on effective format
match effective {
OutputFormat::Dot => {
let dot = format_deps_dot(&report);
println!("{}", dot);
}
OutputFormat::Text => {
let text = format_deps_text(&report);
writer.write_text(&text)?;
}
_ => {
// JSON/Compact/Sarif output
if self.show_cycles {
// Only output cycles when --show-cycles is specified
writer.write(&report.circular_dependencies)?;
} else {
writer.write(&report)?;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use tldr_core::analysis::deps::{DepCycle, DepStats, DepsReport};
fn make_test_report() -> DepsReport {
let mut internal_deps = BTreeMap::new();
internal_deps.insert(
PathBuf::from("src/auth.py"),
vec![PathBuf::from("src/utils.py"), PathBuf::from("src/db.py")],
);
internal_deps.insert(PathBuf::from("src/utils.py"), vec![]);
internal_deps.insert(
PathBuf::from("src/db.py"),
vec![PathBuf::from("src/utils.py")],
);
DepsReport {
root: PathBuf::from("src"),
language: "python".to_string(),
internal_dependencies: internal_deps,
external_dependencies: BTreeMap::new(),
circular_dependencies: vec![],
stats: DepStats {
total_files: 3,
total_internal_deps: 3,
total_external_deps: 0,
max_depth: 2,
cycles_found: 0,
leaf_files: 1,
root_files: 1,
},
}
}
#[test]
fn test_format_deps_text() {
let report = make_test_report();
let text = format_deps_text(&report);
// Updated assertions for new spec-compliant format
assert!(text.contains("Dependency Analysis: src"));
assert!(text.contains("Language: Python")); // Capitalized per spec
assert!(text.contains("Internal Dependencies (3 edges, 3 files)"));
assert!(text.contains("No circular dependencies found"));
}
#[test]
fn test_format_deps_text_with_cycles() {
let mut report = make_test_report();
report.circular_dependencies = vec![DepCycle::new(vec![
PathBuf::from("src/a.py"),
PathBuf::from("src/b.py"),
PathBuf::from("src/c.py"),
])];
report.stats.cycles_found = 1;
let text = format_deps_text(&report);
assert!(text.contains("[CYCLE]")); // Spec format without number
assert!(text.contains("src/a.py -> src/b.py -> src/c.py"));
}
#[test]
fn test_format_deps_dot() {
let report = make_test_report();
let dot = format_deps_dot(&report);
assert!(dot.contains("digraph deps {"));
assert!(dot.contains("rankdir=LR"));
assert!(dot.contains("\"src/auth.py\" -> \"src/utils.py\""));
assert!(dot.contains("\"src/auth.py\" -> \"src/db.py\""));
assert!(dot.ends_with("}\n"));
}
#[test]
fn test_output_field_is_optional() {
// The output field should be None when not explicitly provided,
// allowing the global --format flag to take effect.
let args = DepsArgs {
path: PathBuf::from("."),
output: None,
lang: None,
include_external: false,
collapse_packages: false,
depth: None,
show_cycles: false,
max_cycle_length: 10,
};
assert!(args.output.is_none(), "output should be None when not set");
}
#[test]
fn test_output_field_backward_compat_override() {
// When -o is explicitly provided, it should override the global format.
let args = DepsArgs {
path: PathBuf::from("."),
output: Some("text".to_string()),
lang: None,
include_external: false,
collapse_packages: false,
depth: None,
show_cycles: false,
max_cycle_length: 10,
};
assert_eq!(
args.output.as_deref(),
Some("text"),
"output should contain the explicit value"
);
}
#[test]
fn test_effective_format_uses_global_when_no_local() {
// When output is None, effective_format should return the global format.
let args = DepsArgs {
path: PathBuf::from("."),
output: None,
lang: None,
include_external: false,
collapse_packages: false,
depth: None,
show_cycles: false,
max_cycle_length: 10,
};
let effective = args.effective_format(OutputFormat::Text);
assert_eq!(
effective,
OutputFormat::Text,
"should use global format when no local override"
);
}
#[test]
fn test_effective_format_uses_local_override() {
// When output is Some("text"), effective_format should return Text.
let args = DepsArgs {
path: PathBuf::from("."),
output: Some("text".to_string()),
lang: None,
include_external: false,
collapse_packages: false,
depth: None,
show_cycles: false,
max_cycle_length: 10,
};
let effective = args.effective_format(OutputFormat::Json);
assert_eq!(
effective,
OutputFormat::Text,
"should use local text override"
);
}
#[test]
fn test_effective_format_dot_override() {
// When output is Some("dot"), effective_format should return Dot.
let args = DepsArgs {
path: PathBuf::from("."),
output: Some("dot".to_string()),
lang: None,
include_external: false,
collapse_packages: false,
depth: None,
show_cycles: false,
max_cycle_length: 10,
};
let effective = args.effective_format(OutputFormat::Json);
assert_eq!(
effective,
OutputFormat::Dot,
"should use local dot override"
);
}
#[test]
fn test_format_deps_dot_cycle_highlighting() {
let mut report = make_test_report();
// Add a cycle: a -> b -> a
let mut deps = BTreeMap::new();
deps.insert(PathBuf::from("src/a.py"), vec![PathBuf::from("src/b.py")]);
deps.insert(PathBuf::from("src/b.py"), vec![PathBuf::from("src/a.py")]);
report.internal_dependencies = deps;
report.circular_dependencies = vec![DepCycle::new(vec![
PathBuf::from("src/a.py"),
PathBuf::from("src/b.py"),
])];
let dot = format_deps_dot(&report);
// Cycle edges should be highlighted in red (per spec)
assert!(dot.contains("color=red") || dot.contains("color=\"red\""));
assert!(dot.contains("penwidth=2"));
}
}