fallow-cli 2.99.0

CLI for fallow, Rust-native codebase intelligence for TypeScript and JavaScript
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
pub(super) mod check;
mod cross_ref;
pub(super) mod dupes;
pub(super) mod health;
mod health_hotspots;
mod health_runtime;
mod health_targets;
mod perf;
mod traces;

pub(super) use check::*;
pub(super) use cross_ref::*;
pub(super) use dupes::*;
pub(super) use health::*;
pub(super) use perf::*;
pub(super) use traces::*;

use std::io::IsTerminal;
use std::path::Path;

use colored::Colorize;

use super::{Level, plural, relative_path, split_dir_filename};

/// Maximum items shown per flat section (unused files, deps, etc.).
pub(super) const MAX_FLAT_ITEMS: usize = 10;

/// Format a path with dimmed directory and bold filename.
pub(super) fn format_path(path_str: &str) -> String {
    let (dir, filename) = split_dir_filename(path_str);
    format!("{}{}", dir.dimmed(), filename.bold())
}

/// Format a number with thousands separators (e.g., 5433 → "5,433").
pub(super) fn thousands(n: usize) -> String {
    let s = n.to_string();
    let mut result = String::with_capacity(s.len() + s.len() / 3);
    for (i, c) in s.chars().enumerate() {
        if i > 0 && (s.len() - i).is_multiple_of(3) {
            result.push(',');
        }
        result.push(c);
    }
    result
}

pub(super) fn print_explain_tip_if_tty(has_findings: bool, quiet: bool) {
    if has_findings
        && !quiet
        && std::io::stdout().is_terminal()
        && !crate::report::sink::is_redirected()
    {
        println!(
            "{}",
            "Tip: run `fallow explain <issue label>`; spaces and hyphens both work, e.g. `fallow explain unused files`."
                .dimmed()
        );
        println!();
    }
}

/// Build a colored section header with bullet, title, and count.
pub(super) fn build_section_header(title: &str, count: usize, level: Level) -> String {
    let label = format!("{title} ({count})");
    match level {
        Level::Warn => format!("{} {}", "\u{25cf}".yellow(), label.yellow().bold()),
        Level::Info => format!("{} {}", "\u{25cf}".cyan(), label.cyan().bold()),
        Level::Error => format!("{} {}", "\u{25cf}".red(), label.red().bold()),
    }
}

/// Section footer: description + docs URL (with anchor to specific section).
fn section_footer_text(title: &str) -> Option<(&'static str, &'static str)> {
    section_dead_code_footer_text(title)
        .or_else(|| section_dependency_footer_text(title))
        .or_else(|| section_framework_footer_text(title))
        .or_else(|| section_component_footer_text(title))
}

fn section_dead_code_footer_text(title: &str) -> Option<(&'static str, &'static str)> {
    match title {
        "Unused files" => Some((
            "Files not reachable from any entry point",
            "https://docs.fallow.tools/explanations/dead-code#unused-files",
        )),
        "Unused exports" => Some((
            "Exported symbols with no known consumers",
            "https://docs.fallow.tools/explanations/dead-code#unused-exports",
        )),
        "Unused type exports" => Some((
            "Type exports with no known consumers",
            "https://docs.fallow.tools/explanations/dead-code#unused-types",
        )),
        "Private type leaks" => Some((
            "Exported signatures that reference same-file private types",
            "https://docs.fallow.tools/explanations/dead-code#private-type-leaks",
        )),
        "Unused dependencies" => Some((
            "Listed in dependencies but never imported",
            "https://docs.fallow.tools/explanations/dead-code#unused-dependencies",
        )),
        "Unused devDependencies" => Some((
            "Listed in devDependencies but never imported or referenced",
            "https://docs.fallow.tools/explanations/dead-code#unused-dependencies",
        )),
        "Unused optionalDependencies" => Some((
            "Listed in optionalDependencies but never imported",
            "https://docs.fallow.tools/explanations/dead-code#unused-dependencies",
        )),
        "Unused enum members" => Some((
            "Enum members never referenced outside their declaration",
            "https://docs.fallow.tools/explanations/dead-code#unused-enum-members",
        )),
        "Unused class members" => Some((
            "Class methods or properties never referenced outside their class",
            "https://docs.fallow.tools/explanations/dead-code#unused-class-members",
        )),
        "Unused store members" => Some((
            "Store state or actions never accessed by any consumer",
            "https://docs.fallow.tools/explanations/dead-code#unused-store-members",
        )),
        "Unresolved imports" => Some((
            "Import paths that could not be resolved, check for missing packages or broken paths. Framework-specific imports may need a plugin: https://docs.fallow.tools/plugins",
            "https://docs.fallow.tools/explanations/dead-code#unresolved-imports",
        )),
        _ => None,
    }
}

fn section_dependency_footer_text(title: &str) -> Option<(&'static str, &'static str)> {
    match title {
        "Unlisted dependencies" => Some((
            "Packages imported in code but missing from package.json",
            "https://docs.fallow.tools/explanations/dead-code#unlisted-dependencies",
        )),
        "Duplicate exports" => Some((
            "Same export name defined in multiple files; barrel re-exports may resolve ambiguously",
            "https://docs.fallow.tools/explanations/dead-code#duplicate-exports",
        )),
        "Circular dependencies" => Some((
            "Import cycles that can cause initialization failures and prevent tree-shaking",
            "https://docs.fallow.tools/explanations/dead-code#circular-dependencies",
        )),
        "Boundary violations" => Some((
            "Imports that cross defined architecture zone boundaries",
            "https://docs.fallow.tools/explanations/dead-code#boundary-violations",
        )),
        "Stale suppressions" => Some((
            "Suppression comments or JSDoc tags that no longer match any issue",
            "https://docs.fallow.tools/explanations/dead-code#stale-suppressions",
        )),
        "Unused catalog entries" => Some((
            "pnpm-workspace.yaml catalog entries not referenced by any workspace package via the `catalog:` protocol",
            "https://docs.fallow.tools/explanations/dead-code#unused-catalog-entries",
        )),
        "Unresolved catalog references" => Some((
            "package.json `catalog:` / `catalog:<name>` references whose catalog does not declare the package (pnpm install will error)",
            "https://docs.fallow.tools/explanations/dead-code#unresolved-catalog-references",
        )),
        "Unused dependency overrides" => Some((
            "pnpm `overrides:` entries whose target package is not declared by any workspace package or resolved in pnpm-lock.yaml",
            "https://docs.fallow.tools/explanations/dead-code#unused-dependency-overrides",
        )),
        "Misconfigured dependency overrides" => Some((
            "pnpm `overrides:` entries with an unparsable key or empty value (pnpm install will error)",
            "https://docs.fallow.tools/explanations/dead-code#misconfigured-dependency-overrides",
        )),
        t if t.starts_with("Type-only") => Some((
            "Dependencies only used for type imports; consider moving to devDependencies",
            "https://docs.fallow.tools/explanations/dead-code#type-only-dependencies",
        )),
        _ => None,
    }
}

fn section_framework_footer_text(title: &str) -> Option<(&'static str, &'static str)> {
    match title {
        "Invalid client exports" => Some((
            "Server-only or route-config exports in a \"use client\" file (Next.js rejects this at build time)",
            "https://docs.fallow.tools/explanations/dead-code#invalid-client-exports",
        )),
        "Mixed client/server barrels" => Some((
            "Barrel re-exports both a \"use client\" module and a server-only module (one import drags the other's directive across the boundary)",
            "https://docs.fallow.tools/explanations/dead-code#mixed-client-server-barrels",
        )),
        "Misplaced directives" => Some((
            "A \"use client\" / \"use server\" directive sits below an import, so the RSC bundler ignores it (move it above every import)",
            "https://docs.fallow.tools/explanations/dead-code#misplaced-directives",
        )),
        "Unprovided injects" => Some((
            "A Vue inject / Svelte getContext whose key is provided nowhere in the project, so at runtime it returns undefined",
            "https://docs.fallow.tools/explanations/dead-code#unprovided-injects",
        )),
        _ => None,
    }
}

fn section_component_footer_text(title: &str) -> Option<(&'static str, &'static str)> {
    match title {
        "Unrendered components" => Some((
            "A Vue / Svelte component reachable through a barrel but rendered nowhere in the project (render it somewhere or remove it)",
            "https://docs.fallow.tools/explanations/dead-code#unrendered-components",
        )),
        "Unused component props" => Some((
            "A Vue defineProps prop or React component prop referenced nowhere inside its own component (remove it or use it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-component-props",
        )),
        "Prop drilling" => Some((
            "A React/Preact prop forwarded unused through two or more intermediate components before a component consumes it (colocate the consumer or lift it to a context); opt-in, off by default",
            "https://docs.fallow.tools/explanations/dead-code#prop-drilling",
        )),
        "Thin wrappers" => Some((
            "A React/Preact component whose whole body forwards props to a single child (return <Child {...props}/>); inline it at call sites or delete it; opt-in, off by default",
            "https://docs.fallow.tools/explanations/dead-code#thin-wrapper",
        )),
        "Duplicate prop shapes" => Some((
            "Three or more React/Preact components across two or more files declaring an identical prop-name set (after stripping common DOM props); extract a shared Props type or base component; opt-in, off by default",
            "https://docs.fallow.tools/explanations/dead-code#duplicate-prop-shape",
        )),
        "Unused component emits" => Some((
            "A Vue <script setup> defineEmits event emitted nowhere inside its own component (remove it or emit it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-component-emits",
        )),
        "Unused component inputs" => Some((
            "An Angular @Input() / signal input() declaration read nowhere inside its own component (remove it or use it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-component-inputs",
        )),
        "Unused component outputs" => Some((
            "An Angular @Output() / signal output() declaration emitted nowhere inside its own component (remove it or emit it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-component-outputs",
        )),
        "Unused Svelte events" => Some((
            "A Svelte component dispatching a createEventDispatcher event whose name is listened to nowhere in the project (remove it or listen for it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-svelte-events",
        )),
        "Unused server actions" => Some((
            "A Next.js Server Action exported from a \"use server\" file that no code in the project references (wire it to a consumer or remove it)",
            "https://docs.fallow.tools/explanations/dead-code#unused-server-actions",
        )),
        "Unused load data keys" => Some((
            "A SvelteKit load() return-object key no consumer reads (sibling +page.svelte data.<key> or project-wide page.data.<key>); delete the key or wire a consumer",
            "https://docs.fallow.tools/explanations/dead-code#unused-load-data-keys",
        )),
        _ => None,
    }
}

/// Map section title to the corresponding fallow-ignore rule name.
fn section_suppress_rule(title: &str) -> Option<&'static str> {
    match title {
        "Unused files" => Some("unused-files"),
        "Unused exports" => Some("unused-exports"),
        "Unused type exports" => Some("unused-types"),
        "Private type leaks" => Some("private-type-leak"),
        "Unused dependencies" | "Unused devDependencies" | "Unused optionalDependencies" => {
            Some("unused-dependencies")
        }
        "Unused enum members" => Some("unused-enum-members"),
        "Unused class members" => Some("unused-class-members"),
        "Unused store members" => Some("unused-store-members"),
        "Unresolved imports" => Some("unresolved-imports"),
        "Unlisted dependencies" => Some("unlisted-dependencies"),
        "Duplicate exports" => Some("duplicate-exports"),
        "Circular dependencies" => Some("circular-dependencies"),
        "Boundary violations" => Some("boundary-violation"),
        "Unused catalog entries" => Some("unused-catalog-entry"),
        "Unresolved catalog references" => Some("unresolved-catalog-reference"),
        "Unused dependency overrides" => Some("unused-dependency-override"),
        "Misconfigured dependency overrides" => Some("misconfigured-dependency-override"),
        "Invalid client exports" => Some("invalid-client-export"),
        "Mixed client/server barrels" => Some("mixed-client-server-barrel"),
        "Misplaced directives" => Some("misplaced-directive"),
        "Unprovided injects" => Some("unprovided-injects"),
        "Unrendered components" => Some("unrendered-components"),
        "Unused component props" => Some("unused-component-props"),
        "Prop drilling" => Some("prop-drilling"),
        "Thin wrappers" => Some("thin-wrapper"),
        "Duplicate prop shapes" => Some("duplicate-prop-shape"),
        "Unused component emits" => Some("unused-component-emits"),
        "Unused component inputs" => Some("unused-component-inputs"),
        "Unused component outputs" => Some("unused-component-outputs"),
        "Unused Svelte events" => Some("unused-svelte-event"),
        "Unused server actions" => Some("unused-server-actions"),
        "Unused load data keys" => Some("unused-load-data-keys"),
        _ => None,
    }
}

/// Rules that only support file-level suppression (not next-line).
fn is_file_level_only(rule: &str) -> bool {
    matches!(rule, "circular-dependencies" | "boundary-violation")
}

/// Rules whose findings live in YAML files (so the suppression comment must
/// use `#` rather than `//`).
fn is_yaml_comment_only(rule: &str) -> bool {
    matches!(rule, "unused-catalog-entry")
}

/// Rules whose findings live in a file format that does not support comments
/// at all (e.g., `unresolved-catalog-reference` lives in `package.json`), or
/// whose findings can live in either YAML or JSON (`*-dependency-override`),
/// so an inline suppression mechanism would be format-dependent. Suppression
/// for these MUST go through a fallow config entry.
fn is_config_only_suppression(rule: &str) -> bool {
    matches!(
        rule,
        "unresolved-catalog-reference"
            | "unused-dependency-override"
            | "misconfigured-dependency-override"
    )
}

/// Render the config-only suppression hint for a rule that has no inline
/// suppression path.
fn config_only_suppression_hint(rule: &str) -> &'static str {
    match rule {
        "unresolved-catalog-reference" => {
            "To suppress: add an entry to ignoreCatalogReferences in your fallow config"
        }
        "unused-dependency-override" | "misconfigured-dependency-override" => {
            "To suppress: add an entry to ignoreDependencyOverrides in your fallow config"
        }
        _ => "To suppress: add an override in your fallow config",
    }
}

/// Categories that support `fallow fix --dry-run` auto-fix.
fn is_auto_fixable(title: &str) -> bool {
    matches!(
        title,
        "Unused exports" | "Unused type exports" | "Unused enum members"
    )
}

/// Push a dimmed section footer line: description — docs_url, plus suppression hint.
///
/// The `item_count` controls whether the suppress hint is shown (only for sections
/// with 3+ items, to reduce noise for power users scanning many small sections).
pub(super) fn push_section_footer_with_count(
    lines: &mut Vec<String>,
    title: &str,
    item_count: usize,
) {
    push_section_footer_impl(lines, title, item_count, false);
}

/// Push section footer for directory-rollup sections (suggests ignorePatterns config).
pub(super) fn push_section_footer_rollup(lines: &mut Vec<String>, title: &str, item_count: usize) {
    push_section_footer_impl(lines, title, item_count, true);
}

fn push_section_footer_impl(lines: &mut Vec<String>, title: &str, item_count: usize, rollup: bool) {
    if let Some((desc, url)) = section_footer_text(title) {
        lines.push(format!("  {}", format!("{desc} \u{2014} {url}").dimmed()));
    }
    if item_count >= 3 {
        if is_auto_fixable(title) {
            lines.push(format!(
                "  {}",
                "To auto-fix: fallow fix --dry-run".dimmed()
            ));
        }
        if let Some(rule) = section_suppress_rule(title) {
            let comment = if rollup {
                "To suppress a directory: add to ignorePatterns in .fallowrc.json".to_string()
            } else if is_file_level_only(rule) {
                format!("To suppress: // fallow-ignore-file {rule}")
            } else if is_yaml_comment_only(rule) {
                format!("To suppress: # fallow-ignore-next-line {rule}")
            } else if is_config_only_suppression(rule) {
                config_only_suppression_hint(rule).to_string()
            } else {
                format!("To suppress: // fallow-ignore-next-line {rule}")
            };
            lines.push(format!("  {}", comment.dimmed()));
        }
    }
}

/// Build items grouped by file path, sorted by count descending, with truncation.
pub(super) struct GroupedByFileInput<'out, 'items, T, P, F>
where
    P: Fn(&'items T) -> &'items Path,
    F: Fn(&T) -> String,
{
    pub(super) lines: &'out mut Vec<String>,
    pub(super) items: &'items [T],
    pub(super) root: &'out Path,
    pub(super) get_path: P,
    pub(super) format_detail: &'out F,
    pub(super) max_files: usize,
    pub(super) max_items_per_file: usize,
}

pub(super) fn build_grouped_by_file<'out, 'items, T, P, F>(
    input: GroupedByFileInput<'out, 'items, T, P, F>,
) where
    P: Fn(&'items T) -> &'items Path,
    F: Fn(&T) -> String,
{
    let GroupedByFileInput {
        lines,
        items,
        root,
        get_path,
        format_detail,
        max_files,
        max_items_per_file,
    } = input;
    let mut file_groups: Vec<(String, Vec<usize>)> = Vec::new();
    let mut file_map: rustc_hash::FxHashMap<String, usize> = rustc_hash::FxHashMap::default();

    for (i, item) in items.iter().enumerate() {
        let file_str = relative_path(get_path(item), root).display().to_string();
        if let Some(&group_idx) = file_map.get(&file_str) {
            file_groups[group_idx].1.push(i);
        } else {
            file_map.insert(file_str.clone(), file_groups.len());
            file_groups.push((file_str, vec![i]));
        }
    }

    file_groups.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));

    let total_files = file_groups.len();
    let shown_files = total_files.min(max_files);

    for (file_str, indices) in &file_groups[..shown_files] {
        let count_tag = if indices.len() > 1 {
            format!(" ({})", indices.len()).dimmed().to_string()
        } else {
            String::new()
        };
        lines.push(format!("  {}{}", format_path(file_str), count_tag));

        let shown_items = indices.len().min(max_items_per_file);
        for &i in &indices[..shown_items] {
            lines.push(format!("    {}", format_detail(&items[i])));
        }
        if indices.len() > max_items_per_file {
            lines.push(format!(
                "    {}",
                format!(
                    "... and {} more (--format json for full list)",
                    indices.len() - max_items_per_file
                )
                .dimmed()
            ));
        }
    }

    if total_files > max_files {
        let hidden_files = total_files - max_files;
        let hidden_items: usize = file_groups[max_files..]
            .iter()
            .map(|(_, indices)| indices.len())
            .sum();
        lines.push(format!(
            "  {}",
            format!(
                "... and {} more in {} file{} (--format json for full list)",
                hidden_items,
                hidden_files,
                plural(hidden_files)
            )
            .dimmed()
        ));
    }
}

/// Strip ANSI escape sequences from a string, leaving only the printable text.
#[cfg(test)]
pub(super) fn strip_ansi(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            for inner in chars.by_ref() {
                if inner == 'm' {
                    break;
                }
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Join report lines into a single string with ANSI codes stripped.
#[cfg(test)]
pub(super) fn plain(lines: &[String]) -> String {
    lines
        .iter()
        .map(|l| strip_ansi(l))
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn thousands_zero() {
        assert_eq!(thousands(0), "0");
    }

    #[test]
    fn thousands_small() {
        assert_eq!(thousands(999), "999");
    }

    #[test]
    fn thousands_boundary() {
        assert_eq!(thousands(1000), "1,000");
    }

    #[test]
    fn thousands_large() {
        assert_eq!(thousands(1_000_000), "1,000,000");
    }

    #[test]
    fn thousands_irregular() {
        assert_eq!(thousands(12345), "12,345");
    }

    #[test]
    fn format_path_with_directory() {
        let result = strip_ansi(&format_path("src/components/Button.tsx"));
        assert!(result.ends_with("Button.tsx"));
        assert!(result.contains("src/components/"));
    }

    #[test]
    fn format_path_no_directory() {
        let result = strip_ansi(&format_path("index.ts"));
        assert_eq!(result, "index.ts");
    }

    #[test]
    fn strip_ansi_removes_color_codes() {
        let colored_str = "hello".red().bold().to_string();
        assert_eq!(strip_ansi(&colored_str), "hello");
    }

    #[test]
    fn strip_ansi_preserves_plain_text() {
        assert_eq!(strip_ansi("plain text"), "plain text");
    }

    #[test]
    fn strip_ansi_handles_empty_string() {
        assert_eq!(strip_ansi(""), "");
    }

    #[test]
    fn section_header_uses_bullet_indicator() {
        let header = build_section_header("Test section", 3, Level::Error);
        let text = strip_ansi(&header);
        assert!(text.contains("\u{25cf}"));
        assert!(text.contains("Test section (3)"));
    }

    #[test]
    fn section_header_formats_for_all_levels() {
        for level in [Level::Error, Level::Warn, Level::Info] {
            let header = build_section_header("Items", 7, level);
            let text = strip_ansi(&header);
            assert!(
                text.contains("Items (7)"),
                "Missing title for level {level:?}"
            );
        }
    }
}