1use std::path::Path;
2
3use fallow_core::duplicates::DuplicationReport;
4use fallow_core::results::{AnalysisResults, UnusedExport, UnusedMember};
5
6use super::grouping::ResultGroup;
7use super::{normalize_uri, relative_path};
8
9pub(super) fn print_compact(results: &AnalysisResults, root: &Path) {
10 for line in build_compact_lines(results, root) {
11 println!("{line}");
12 }
13}
14
15pub fn build_compact_lines(results: &AnalysisResults, root: &Path) -> Vec<String> {
18 let rel = |p: &Path| normalize_uri(&relative_path(p, root).display().to_string());
19
20 let compact_export = |export: &UnusedExport, kind: &str, re_kind: &str| -> String {
21 let tag = if export.is_re_export { re_kind } else { kind };
22 format!(
23 "{}:{}:{}:{}",
24 tag,
25 rel(&export.path),
26 export.line,
27 export.export_name
28 )
29 };
30
31 let compact_member = |member: &UnusedMember, kind: &str| -> String {
32 format!(
33 "{}:{}:{}:{}.{}",
34 kind,
35 rel(&member.path),
36 member.line,
37 member.parent_name,
38 member.member_name
39 )
40 };
41
42 let mut lines = Vec::new();
43
44 for file in &results.unused_files {
45 lines.push(format!("unused-file:{}", rel(&file.path)));
46 }
47 for export in &results.unused_exports {
48 lines.push(compact_export(export, "unused-export", "unused-re-export"));
49 }
50 for export in &results.unused_types {
51 lines.push(compact_export(
52 export,
53 "unused-type",
54 "unused-re-export-type",
55 ));
56 }
57 for leak in &results.private_type_leaks {
58 lines.push(format!(
59 "private-type-leak:{}:{}:{}->{}",
60 rel(&leak.path),
61 leak.line,
62 leak.export_name,
63 leak.type_name
64 ));
65 }
66 for dep in &results.unused_dependencies {
67 lines.push(format!("unused-dep:{}", dep.package_name));
68 }
69 for dep in &results.unused_dev_dependencies {
70 lines.push(format!("unused-devdep:{}", dep.package_name));
71 }
72 for dep in &results.unused_optional_dependencies {
73 lines.push(format!("unused-optionaldep:{}", dep.package_name));
74 }
75 for member in &results.unused_enum_members {
76 lines.push(compact_member(member, "unused-enum-member"));
77 }
78 for member in &results.unused_class_members {
79 lines.push(compact_member(member, "unused-class-member"));
80 }
81 for import in &results.unresolved_imports {
82 lines.push(format!(
83 "unresolved-import:{}:{}:{}",
84 rel(&import.path),
85 import.line,
86 import.specifier
87 ));
88 }
89 for dep in &results.unlisted_dependencies {
90 lines.push(format!("unlisted-dep:{}", dep.package_name));
91 }
92 for dup in &results.duplicate_exports {
93 lines.push(format!("duplicate-export:{}", dup.export_name));
94 }
95 for dep in &results.type_only_dependencies {
96 lines.push(format!("type-only-dep:{}", dep.package_name));
97 }
98 for dep in &results.test_only_dependencies {
99 lines.push(format!("test-only-dep:{}", dep.package_name));
100 }
101 for cycle in &results.circular_dependencies {
102 let chain: Vec<String> = cycle.files.iter().map(|p| rel(p)).collect();
103 let mut display_chain = chain.clone();
104 if let Some(first) = chain.first() {
105 display_chain.push(first.clone());
106 }
107 let first_file = chain.first().map_or_else(String::new, Clone::clone);
108 let cross_pkg_tag = if cycle.is_cross_package {
109 " (cross-package)"
110 } else {
111 ""
112 };
113 lines.push(format!(
114 "circular-dependency:{}:{}:{}{}",
115 first_file,
116 cycle.line,
117 display_chain.join(" \u{2192} "),
118 cross_pkg_tag
119 ));
120 }
121 for v in &results.boundary_violations {
122 lines.push(format!(
123 "boundary-violation:{}:{}:{} -> {} ({} -> {})",
124 rel(&v.from_path),
125 v.line,
126 rel(&v.from_path),
127 rel(&v.to_path),
128 v.from_zone,
129 v.to_zone,
130 ));
131 }
132 for s in &results.stale_suppressions {
133 lines.push(format!(
134 "stale-suppression:{}:{}:{}",
135 rel(&s.path),
136 s.line,
137 s.description(),
138 ));
139 }
140
141 lines
142}
143
144pub(super) fn print_grouped_compact(groups: &[ResultGroup], root: &Path) {
148 for group in groups {
149 for line in build_compact_lines(&group.results, root) {
150 println!("{}\t{line}", group.key);
151 }
152 }
153}
154
155#[expect(
156 clippy::too_many_lines,
157 reason = "health compact formatter stitches many optional sections into one stream"
158)]
159pub(super) fn print_health_compact(report: &crate::health_types::HealthReport, root: &Path) {
160 if let Some(ref hs) = report.health_score {
161 println!("health-score:{:.1}:{}", hs.score, hs.grade);
162 }
163 if let Some(ref vs) = report.vital_signs {
164 let mut parts = Vec::new();
165 if vs.total_loc > 0 {
166 parts.push(format!("total_loc={}", vs.total_loc));
167 }
168 parts.push(format!("avg_cyclomatic={:.1}", vs.avg_cyclomatic));
169 parts.push(format!("p90_cyclomatic={}", vs.p90_cyclomatic));
170 if let Some(v) = vs.dead_file_pct {
171 parts.push(format!("dead_file_pct={v:.1}"));
172 }
173 if let Some(v) = vs.dead_export_pct {
174 parts.push(format!("dead_export_pct={v:.1}"));
175 }
176 if let Some(v) = vs.maintainability_avg {
177 parts.push(format!("maintainability_avg={v:.1}"));
178 }
179 if let Some(v) = vs.hotspot_count {
180 parts.push(format!("hotspot_count={v}"));
181 }
182 if let Some(v) = vs.circular_dep_count {
183 parts.push(format!("circular_dep_count={v}"));
184 }
185 if let Some(v) = vs.unused_dep_count {
186 parts.push(format!("unused_dep_count={v}"));
187 }
188 println!("vital-signs:{}", parts.join(","));
189 }
190 for finding in &report.findings {
191 let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
192 let severity = match finding.severity {
193 crate::health_types::FindingSeverity::Critical => "critical",
194 crate::health_types::FindingSeverity::High => "high",
195 crate::health_types::FindingSeverity::Moderate => "moderate",
196 };
197 let crap_suffix = match finding.crap {
198 Some(crap) => {
199 let coverage = finding
200 .coverage_pct
201 .map(|pct| format!(",coverage_pct={pct:.1}"))
202 .unwrap_or_default();
203 format!(",crap={crap:.1}{coverage}")
204 }
205 None => String::new(),
206 };
207 println!(
208 "high-complexity:{}:{}:{}:cyclomatic={},cognitive={},severity={}{}",
209 relative,
210 finding.line,
211 finding.name,
212 finding.cyclomatic,
213 finding.cognitive,
214 severity,
215 crap_suffix,
216 );
217 }
218 for score in &report.file_scores {
219 let relative = normalize_uri(&relative_path(&score.path, root).display().to_string());
220 println!(
221 "file-score:{}:mi={:.1},fan_in={},fan_out={},dead={:.2},density={:.2},crap_max={:.1},crap_above={}",
222 relative,
223 score.maintainability_index,
224 score.fan_in,
225 score.fan_out,
226 score.dead_code_ratio,
227 score.complexity_density,
228 score.crap_max,
229 score.crap_above_threshold,
230 );
231 }
232 if let Some(ref gaps) = report.coverage_gaps {
233 println!(
234 "coverage-gap-summary:runtime_files={},covered_files={},file_coverage_pct={:.1},untested_files={},untested_exports={}",
235 gaps.summary.runtime_files,
236 gaps.summary.covered_files,
237 gaps.summary.file_coverage_pct,
238 gaps.summary.untested_files,
239 gaps.summary.untested_exports,
240 );
241 for item in &gaps.files {
242 let relative = normalize_uri(&relative_path(&item.path, root).display().to_string());
243 println!(
244 "untested-file:{}:value_exports={}",
245 relative, item.value_export_count,
246 );
247 }
248 for item in &gaps.exports {
249 let relative = normalize_uri(&relative_path(&item.path, root).display().to_string());
250 println!(
251 "untested-export:{}:{}:{}",
252 relative, item.line, item.export_name,
253 );
254 }
255 }
256 if let Some(ref production) = report.runtime_coverage {
257 for line in build_runtime_coverage_compact_lines(production, root) {
258 println!("{line}");
259 }
260 }
261 for entry in &report.hotspots {
262 let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
263 let ownership_suffix = entry
264 .ownership
265 .as_ref()
266 .map(|o| {
267 let mut parts = vec![
268 format!("bus={}", o.bus_factor),
269 format!("contributors={}", o.contributor_count),
270 format!("top={}", o.top_contributor.identifier),
271 format!("top_share={:.3}", o.top_contributor.share),
272 ];
273 if let Some(owner) = &o.declared_owner {
274 parts.push(format!("owner={owner}"));
275 }
276 if let Some(unowned) = o.unowned {
277 parts.push(format!("unowned={unowned}"));
278 }
279 if o.drift {
280 parts.push("drift=true".to_string());
281 }
282 format!(",{}", parts.join(","))
283 })
284 .unwrap_or_default();
285 println!(
286 "hotspot:{}:score={:.1},commits={},churn={},density={:.2},fan_in={},trend={}{}",
287 relative,
288 entry.score,
289 entry.commits,
290 entry.lines_added + entry.lines_deleted,
291 entry.complexity_density,
292 entry.fan_in,
293 entry.trend,
294 ownership_suffix,
295 );
296 }
297 if let Some(ref trend) = report.health_trend {
298 println!(
299 "trend:overall:direction={}",
300 trend.overall_direction.label()
301 );
302 for m in &trend.metrics {
303 println!(
304 "trend:{}:previous={:.1},current={:.1},delta={:+.1},direction={}",
305 m.name,
306 m.previous,
307 m.current,
308 m.delta,
309 m.direction.label(),
310 );
311 }
312 }
313 for target in &report.targets {
314 let relative = normalize_uri(&relative_path(&target.path, root).display().to_string());
315 let category = target.category.compact_label();
316 let effort = target.effort.label();
317 let confidence = target.confidence.label();
318 println!(
319 "refactoring-target:{}:priority={:.1},efficiency={:.1},category={},effort={},confidence={}:{}",
320 relative,
321 target.priority,
322 target.efficiency,
323 category,
324 effort,
325 confidence,
326 target.recommendation,
327 );
328 }
329}
330
331fn build_runtime_coverage_compact_lines(
332 production: &crate::health_types::RuntimeCoverageReport,
333 root: &Path,
334) -> Vec<String> {
335 let mut lines = vec![format!(
336 "runtime-coverage-summary:functions_tracked={},functions_hit={},functions_unhit={},functions_untracked={},coverage_percent={:.1},trace_count={},period_days={},deployments_seen={}",
337 production.summary.functions_tracked,
338 production.summary.functions_hit,
339 production.summary.functions_unhit,
340 production.summary.functions_untracked,
341 production.summary.coverage_percent,
342 production.summary.trace_count,
343 production.summary.period_days,
344 production.summary.deployments_seen,
345 )];
346 for finding in &production.findings {
347 let relative = normalize_uri(&relative_path(&finding.path, root).display().to_string());
348 let invocations = finding
349 .invocations
350 .map_or_else(|| "null".to_owned(), |hits| hits.to_string());
351 lines.push(format!(
352 "runtime-coverage:{}:{}:{}:id={},verdict={},invocations={},confidence={}",
353 relative,
354 finding.line,
355 finding.function,
356 finding.id,
357 finding.verdict,
358 invocations,
359 finding.confidence,
360 ));
361 }
362 for entry in &production.hot_paths {
363 let relative = normalize_uri(&relative_path(&entry.path, root).display().to_string());
364 lines.push(format!(
365 "production-hot-path:{}:{}:{}:id={},invocations={},percentile={}",
366 relative, entry.line, entry.function, entry.id, entry.invocations, entry.percentile,
367 ));
368 }
369 lines
370}
371
372pub(super) fn print_duplication_compact(report: &DuplicationReport, root: &Path) {
373 for (i, group) in report.clone_groups.iter().enumerate() {
374 for instance in &group.instances {
375 let relative =
376 normalize_uri(&relative_path(&instance.file, root).display().to_string());
377 println!(
378 "clone-group-{}:{}:{}-{}:{}tokens",
379 i + 1,
380 relative,
381 instance.start_line,
382 instance.end_line,
383 group.token_count
384 );
385 }
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use super::*;
392 use crate::health_types::{
393 RuntimeCoverageConfidence, RuntimeCoverageDataSource, RuntimeCoverageEvidence,
394 RuntimeCoverageFinding, RuntimeCoverageHotPath, RuntimeCoverageReport,
395 RuntimeCoverageReportVerdict, RuntimeCoverageSummary, RuntimeCoverageVerdict,
396 };
397 use crate::report::test_helpers::sample_results;
398 use fallow_core::extract::MemberKind;
399 use fallow_core::results::*;
400 use std::path::PathBuf;
401
402 #[test]
403 fn compact_empty_results_no_lines() {
404 let root = PathBuf::from("/project");
405 let results = AnalysisResults::default();
406 let lines = build_compact_lines(&results, &root);
407 assert!(lines.is_empty());
408 }
409
410 #[test]
411 fn compact_unused_file_format() {
412 let root = PathBuf::from("/project");
413 let mut results = AnalysisResults::default();
414 results.unused_files.push(UnusedFile {
415 path: root.join("src/dead.ts"),
416 });
417
418 let lines = build_compact_lines(&results, &root);
419 assert_eq!(lines.len(), 1);
420 assert_eq!(lines[0], "unused-file:src/dead.ts");
421 }
422
423 #[test]
424 fn compact_unused_export_format() {
425 let root = PathBuf::from("/project");
426 let mut results = AnalysisResults::default();
427 results.unused_exports.push(UnusedExport {
428 path: root.join("src/utils.ts"),
429 export_name: "helperFn".to_string(),
430 is_type_only: false,
431 line: 10,
432 col: 4,
433 span_start: 120,
434 is_re_export: false,
435 });
436
437 let lines = build_compact_lines(&results, &root);
438 assert_eq!(lines[0], "unused-export:src/utils.ts:10:helperFn");
439 }
440
441 #[test]
442 fn compact_health_includes_runtime_coverage_lines() {
443 let root = PathBuf::from("/project");
444 let report = crate::health_types::HealthReport {
445 runtime_coverage: Some(RuntimeCoverageReport {
446 verdict: RuntimeCoverageReportVerdict::ColdCodeDetected,
447 summary: RuntimeCoverageSummary {
448 data_source: RuntimeCoverageDataSource::Local,
449 last_received_at: None,
450 functions_tracked: 4,
451 functions_hit: 2,
452 functions_unhit: 1,
453 functions_untracked: 1,
454 coverage_percent: 50.0,
455 trace_count: 512,
456 period_days: 7,
457 deployments_seen: 2,
458 capture_quality: None,
459 },
460 findings: vec![RuntimeCoverageFinding {
461 id: "fallow:prod:deadbeef".to_owned(),
462 path: root.join("src/cold.ts"),
463 function: "coldPath".to_owned(),
464 line: 14,
465 verdict: RuntimeCoverageVerdict::ReviewRequired,
466 invocations: Some(0),
467 confidence: RuntimeCoverageConfidence::Medium,
468 evidence: RuntimeCoverageEvidence {
469 static_status: "used".to_owned(),
470 test_coverage: "not_covered".to_owned(),
471 v8_tracking: "tracked".to_owned(),
472 untracked_reason: None,
473 observation_days: 7,
474 deployments_observed: 2,
475 },
476 actions: vec![],
477 }],
478 hot_paths: vec![RuntimeCoverageHotPath {
479 id: "fallow:hot:cafebabe".to_owned(),
480 path: root.join("src/hot.ts"),
481 function: "hotPath".to_owned(),
482 line: 3,
483 invocations: 250,
484 percentile: 99,
485 actions: vec![],
486 }],
487 blast_radius: vec![],
488 importance: vec![],
489 watermark: None,
490 warnings: vec![],
491 }),
492 ..Default::default()
493 };
494
495 let lines = build_runtime_coverage_compact_lines(
496 report
497 .runtime_coverage
498 .as_ref()
499 .expect("runtime coverage should be set"),
500 &root,
501 );
502 assert_eq!(
503 lines[0],
504 "runtime-coverage-summary:functions_tracked=4,functions_hit=2,functions_unhit=1,functions_untracked=1,coverage_percent=50.0,trace_count=512,period_days=7,deployments_seen=2"
505 );
506 assert_eq!(
507 lines[1],
508 "runtime-coverage:src/cold.ts:14:coldPath:id=fallow:prod:deadbeef,verdict=review_required,invocations=0,confidence=medium"
509 );
510 assert_eq!(
511 lines[2],
512 "production-hot-path:src/hot.ts:3:hotPath:id=fallow:hot:cafebabe,invocations=250,percentile=99"
513 );
514 }
515
516 #[test]
517 fn compact_unused_type_format() {
518 let root = PathBuf::from("/project");
519 let mut results = AnalysisResults::default();
520 results.unused_types.push(UnusedExport {
521 path: root.join("src/types.ts"),
522 export_name: "OldType".to_string(),
523 is_type_only: true,
524 line: 5,
525 col: 0,
526 span_start: 60,
527 is_re_export: false,
528 });
529
530 let lines = build_compact_lines(&results, &root);
531 assert_eq!(lines[0], "unused-type:src/types.ts:5:OldType");
532 }
533
534 #[test]
535 fn compact_unused_dep_format() {
536 let root = PathBuf::from("/project");
537 let mut results = AnalysisResults::default();
538 results.unused_dependencies.push(UnusedDependency {
539 package_name: "lodash".to_string(),
540 location: DependencyLocation::Dependencies,
541 path: root.join("package.json"),
542 line: 5,
543 used_in_workspaces: Vec::new(),
544 });
545
546 let lines = build_compact_lines(&results, &root);
547 assert_eq!(lines[0], "unused-dep:lodash");
548 }
549
550 #[test]
551 fn compact_unused_devdep_format() {
552 let root = PathBuf::from("/project");
553 let mut results = AnalysisResults::default();
554 results.unused_dev_dependencies.push(UnusedDependency {
555 package_name: "jest".to_string(),
556 location: DependencyLocation::DevDependencies,
557 path: root.join("package.json"),
558 line: 5,
559 used_in_workspaces: Vec::new(),
560 });
561
562 let lines = build_compact_lines(&results, &root);
563 assert_eq!(lines[0], "unused-devdep:jest");
564 }
565
566 #[test]
567 fn compact_unused_enum_member_format() {
568 let root = PathBuf::from("/project");
569 let mut results = AnalysisResults::default();
570 results.unused_enum_members.push(UnusedMember {
571 path: root.join("src/enums.ts"),
572 parent_name: "Status".to_string(),
573 member_name: "Deprecated".to_string(),
574 kind: MemberKind::EnumMember,
575 line: 8,
576 col: 2,
577 });
578
579 let lines = build_compact_lines(&results, &root);
580 assert_eq!(
581 lines[0],
582 "unused-enum-member:src/enums.ts:8:Status.Deprecated"
583 );
584 }
585
586 #[test]
587 fn compact_unused_class_member_format() {
588 let root = PathBuf::from("/project");
589 let mut results = AnalysisResults::default();
590 results.unused_class_members.push(UnusedMember {
591 path: root.join("src/service.ts"),
592 parent_name: "UserService".to_string(),
593 member_name: "legacyMethod".to_string(),
594 kind: MemberKind::ClassMethod,
595 line: 42,
596 col: 4,
597 });
598
599 let lines = build_compact_lines(&results, &root);
600 assert_eq!(
601 lines[0],
602 "unused-class-member:src/service.ts:42:UserService.legacyMethod"
603 );
604 }
605
606 #[test]
607 fn compact_unresolved_import_format() {
608 let root = PathBuf::from("/project");
609 let mut results = AnalysisResults::default();
610 results.unresolved_imports.push(UnresolvedImport {
611 path: root.join("src/app.ts"),
612 specifier: "./missing-module".to_string(),
613 line: 3,
614 col: 0,
615 specifier_col: 0,
616 });
617
618 let lines = build_compact_lines(&results, &root);
619 assert_eq!(lines[0], "unresolved-import:src/app.ts:3:./missing-module");
620 }
621
622 #[test]
623 fn compact_unlisted_dep_format() {
624 let root = PathBuf::from("/project");
625 let mut results = AnalysisResults::default();
626 results.unlisted_dependencies.push(UnlistedDependency {
627 package_name: "chalk".to_string(),
628 imported_from: vec![],
629 });
630
631 let lines = build_compact_lines(&results, &root);
632 assert_eq!(lines[0], "unlisted-dep:chalk");
633 }
634
635 #[test]
636 fn compact_duplicate_export_format() {
637 let root = PathBuf::from("/project");
638 let mut results = AnalysisResults::default();
639 results.duplicate_exports.push(DuplicateExport {
640 export_name: "Config".to_string(),
641 locations: vec![
642 DuplicateLocation {
643 path: root.join("src/a.ts"),
644 line: 15,
645 col: 0,
646 },
647 DuplicateLocation {
648 path: root.join("src/b.ts"),
649 line: 30,
650 col: 0,
651 },
652 ],
653 });
654
655 let lines = build_compact_lines(&results, &root);
656 assert_eq!(lines[0], "duplicate-export:Config");
657 }
658
659 #[test]
660 fn compact_all_issue_types_produce_lines() {
661 let root = PathBuf::from("/project");
662 let results = sample_results(&root);
663 let lines = build_compact_lines(&results, &root);
664
665 assert_eq!(lines.len(), 16);
667
668 assert!(lines[0].starts_with("unused-file:"));
670 assert!(lines[1].starts_with("unused-export:"));
671 assert!(lines[2].starts_with("unused-type:"));
672 assert!(lines[3].starts_with("unused-dep:"));
673 assert!(lines[4].starts_with("unused-devdep:"));
674 assert!(lines[5].starts_with("unused-optionaldep:"));
675 assert!(lines[6].starts_with("unused-enum-member:"));
676 assert!(lines[7].starts_with("unused-class-member:"));
677 assert!(lines[8].starts_with("unresolved-import:"));
678 assert!(lines[9].starts_with("unlisted-dep:"));
679 assert!(lines[10].starts_with("duplicate-export:"));
680 assert!(lines[11].starts_with("type-only-dep:"));
681 assert!(lines[12].starts_with("test-only-dep:"));
682 assert!(lines[13].starts_with("circular-dependency:"));
683 assert!(lines[14].starts_with("boundary-violation:"));
684 }
685
686 #[test]
687 fn compact_strips_root_prefix_from_paths() {
688 let root = PathBuf::from("/project");
689 let mut results = AnalysisResults::default();
690 results.unused_files.push(UnusedFile {
691 path: PathBuf::from("/project/src/deep/nested/file.ts"),
692 });
693
694 let lines = build_compact_lines(&results, &root);
695 assert_eq!(lines[0], "unused-file:src/deep/nested/file.ts");
696 }
697
698 #[test]
701 fn compact_re_export_tagged_correctly() {
702 let root = PathBuf::from("/project");
703 let mut results = AnalysisResults::default();
704 results.unused_exports.push(UnusedExport {
705 path: root.join("src/index.ts"),
706 export_name: "reExported".to_string(),
707 is_type_only: false,
708 line: 1,
709 col: 0,
710 span_start: 0,
711 is_re_export: true,
712 });
713
714 let lines = build_compact_lines(&results, &root);
715 assert_eq!(lines[0], "unused-re-export:src/index.ts:1:reExported");
716 }
717
718 #[test]
719 fn compact_type_re_export_tagged_correctly() {
720 let root = PathBuf::from("/project");
721 let mut results = AnalysisResults::default();
722 results.unused_types.push(UnusedExport {
723 path: root.join("src/index.ts"),
724 export_name: "ReExportedType".to_string(),
725 is_type_only: true,
726 line: 3,
727 col: 0,
728 span_start: 0,
729 is_re_export: true,
730 });
731
732 let lines = build_compact_lines(&results, &root);
733 assert_eq!(
734 lines[0],
735 "unused-re-export-type:src/index.ts:3:ReExportedType"
736 );
737 }
738
739 #[test]
742 fn compact_unused_optional_dep_format() {
743 let root = PathBuf::from("/project");
744 let mut results = AnalysisResults::default();
745 results.unused_optional_dependencies.push(UnusedDependency {
746 package_name: "fsevents".to_string(),
747 location: DependencyLocation::OptionalDependencies,
748 path: root.join("package.json"),
749 line: 12,
750 used_in_workspaces: Vec::new(),
751 });
752
753 let lines = build_compact_lines(&results, &root);
754 assert_eq!(lines[0], "unused-optionaldep:fsevents");
755 }
756
757 #[test]
760 fn compact_circular_dependency_format() {
761 let root = PathBuf::from("/project");
762 let mut results = AnalysisResults::default();
763 results.circular_dependencies.push(CircularDependency {
764 files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
765 length: 2,
766 line: 3,
767 col: 0,
768 is_cross_package: false,
769 });
770
771 let lines = build_compact_lines(&results, &root);
772 assert_eq!(lines.len(), 1);
773 assert!(lines[0].starts_with("circular-dependency:src/a.ts:3:"));
774 assert!(lines[0].contains("src/a.ts"));
775 assert!(lines[0].contains("src/b.ts"));
776 assert!(lines[0].contains("\u{2192}"));
778 }
779
780 #[test]
781 fn compact_circular_dependency_closes_cycle() {
782 let root = PathBuf::from("/project");
783 let mut results = AnalysisResults::default();
784 results.circular_dependencies.push(CircularDependency {
785 files: vec![
786 root.join("src/a.ts"),
787 root.join("src/b.ts"),
788 root.join("src/c.ts"),
789 ],
790 length: 3,
791 line: 1,
792 col: 0,
793 is_cross_package: false,
794 });
795
796 let lines = build_compact_lines(&results, &root);
797 let chain_part = lines[0].split(':').next_back().unwrap();
799 let parts: Vec<&str> = chain_part.split(" \u{2192} ").collect();
800 assert_eq!(parts.len(), 4);
801 assert_eq!(parts[0], parts[3]); }
803
804 #[test]
807 fn compact_type_only_dep_format() {
808 let root = PathBuf::from("/project");
809 let mut results = AnalysisResults::default();
810 results.type_only_dependencies.push(TypeOnlyDependency {
811 package_name: "zod".to_string(),
812 path: root.join("package.json"),
813 line: 8,
814 });
815
816 let lines = build_compact_lines(&results, &root);
817 assert_eq!(lines[0], "type-only-dep:zod");
818 }
819
820 #[test]
823 fn compact_multiple_unused_files() {
824 let root = PathBuf::from("/project");
825 let mut results = AnalysisResults::default();
826 results.unused_files.push(UnusedFile {
827 path: root.join("src/a.ts"),
828 });
829 results.unused_files.push(UnusedFile {
830 path: root.join("src/b.ts"),
831 });
832
833 let lines = build_compact_lines(&results, &root);
834 assert_eq!(lines.len(), 2);
835 assert_eq!(lines[0], "unused-file:src/a.ts");
836 assert_eq!(lines[1], "unused-file:src/b.ts");
837 }
838
839 #[test]
842 fn compact_ordering_optional_dep_between_devdep_and_enum() {
843 let root = PathBuf::from("/project");
844 let mut results = AnalysisResults::default();
845 results.unused_dev_dependencies.push(UnusedDependency {
846 package_name: "jest".to_string(),
847 location: DependencyLocation::DevDependencies,
848 path: root.join("package.json"),
849 line: 5,
850 used_in_workspaces: Vec::new(),
851 });
852 results.unused_optional_dependencies.push(UnusedDependency {
853 package_name: "fsevents".to_string(),
854 location: DependencyLocation::OptionalDependencies,
855 path: root.join("package.json"),
856 line: 12,
857 used_in_workspaces: Vec::new(),
858 });
859 results.unused_enum_members.push(UnusedMember {
860 path: root.join("src/enums.ts"),
861 parent_name: "Status".to_string(),
862 member_name: "Deprecated".to_string(),
863 kind: MemberKind::EnumMember,
864 line: 8,
865 col: 2,
866 });
867
868 let lines = build_compact_lines(&results, &root);
869 assert_eq!(lines.len(), 3);
870 assert!(lines[0].starts_with("unused-devdep:"));
871 assert!(lines[1].starts_with("unused-optionaldep:"));
872 assert!(lines[2].starts_with("unused-enum-member:"));
873 }
874
875 #[test]
878 fn compact_path_outside_root_preserved() {
879 let root = PathBuf::from("/project");
880 let mut results = AnalysisResults::default();
881 results.unused_files.push(UnusedFile {
882 path: PathBuf::from("/other/place/file.ts"),
883 });
884
885 let lines = build_compact_lines(&results, &root);
886 assert!(lines[0].contains("/other/place/file.ts"));
887 }
888}