fallow-cli 2.91.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
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{LazyLock, Mutex, OnceLock};

use fallow_config::{
    FallowConfig, OutputFormat, PartialRulesConfig, ProductionAnalysis, ResolvedConfig, RulesConfig,
};
use rustc_hash::FxHashSet;

static CONFIG_LOADED_LOGGED: LazyLock<Mutex<FxHashSet<PathBuf>>> =
    LazyLock::new(|| Mutex::new(FxHashSet::default()));

/// The `--max-file-size` global flag value, set once from `main()` after clap
/// parse. `Some(Some(mb))` means the flag was passed; `Some(None)` / unset
/// means it was not. Held in a `OnceLock` rather than threaded through the ten
/// `load_config_for_analysis` callers (the skill-endorsed set-once-read-by-many
/// pattern; avoids `set_var`, which is unsafe under edition 2024).
static MAX_FILE_SIZE_OVERRIDE: OnceLock<Option<u32>> = OnceLock::new();

/// Record the `--max-file-size` flag value (megabytes; `Some(0)` = unlimited).
/// Called once from `main()` before dispatch. Subsequent calls are ignored.
pub fn set_max_file_size_override(max_file_size_mb: Option<u32>) {
    let _ = MAX_FILE_SIZE_OVERRIDE.set(max_file_size_mb);
}

/// Resolve the effective per-file size ceiling override (in megabytes): the
/// `--max-file-size` flag wins, then `FALLOW_MAX_FILE_SIZE`, else `None` (the
/// built-in default applies). `Some(0)` from either source means unlimited.
fn resolve_max_file_size_mb() -> Option<u32> {
    if let Some(Some(mb)) = MAX_FILE_SIZE_OVERRIDE.get() {
        return Some(*mb);
    }
    std::env::var("FALLOW_MAX_FILE_SIZE")
        .ok()
        .and_then(|raw| raw.trim().parse::<u32>().ok())
}

/// Analysis types for --only/--skip selection.
#[derive(Clone, PartialEq, Eq, clap::ValueEnum)]
pub enum AnalysisKind {
    #[value(alias = "check")]
    DeadCode,
    Dupes,
    Health,
}

/// Grouping mode for `--group-by`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum GroupBy {
    /// Group by CODEOWNERS file ownership (first owner, last matching rule).
    #[value(alias = "team", alias = "codeowner")]
    Owner,
    /// Group by first directory component of the file path.
    Directory,
    /// Group by workspace package (monorepo).
    #[value(alias = "workspace", alias = "pkg")]
    Package,
    /// Group by GitLab CODEOWNERS section name (`[Section]` headers).
    /// Stable across reviewer rotation; produces distinct groups when
    /// multiple sections share a common default owner.
    #[value(alias = "gl-section")]
    Section,
}

/// Build an `OwnershipResolver` from CLI `--group-by` and config settings.
///
/// Returns `None` when no grouping is requested. Returns `Err(ExitCode)` when
/// `--group-by owner` is requested but no CODEOWNERS file can be found.
pub fn build_ownership_resolver(
    group_by: Option<GroupBy>,
    root: &Path,
    codeowners_path: Option<&str>,
    output: OutputFormat,
) -> Result<Option<crate::report::OwnershipResolver>, ExitCode> {
    let Some(mode) = group_by else {
        return Ok(None);
    };
    match mode {
        GroupBy::Owner => match crate::codeowners::CodeOwners::load(root, codeowners_path) {
            Ok(co) => Ok(Some(crate::report::OwnershipResolver::Owner(co))),
            Err(e) => Err(crate::error::emit_error(&e, 2, output)),
        },
        GroupBy::Section => match crate::codeowners::CodeOwners::load(root, codeowners_path) {
            Ok(co) => {
                if co.has_sections() {
                    Ok(Some(crate::report::OwnershipResolver::Section(co)))
                } else {
                    Err(crate::error::emit_error(
                        "--group-by section requires a GitLab-style CODEOWNERS file \
                         with `[Section]` headers. This CODEOWNERS has no sections; \
                         use --group-by owner instead.",
                        2,
                        output,
                    ))
                }
            }
            Err(e) => Err(crate::error::emit_error(&e, 2, output)),
        },
        GroupBy::Directory => Ok(Some(crate::report::OwnershipResolver::Directory)),
        GroupBy::Package => {
            let workspaces = fallow_config::discover_workspaces(root);
            if workspaces.is_empty() {
                Err(crate::error::emit_error(
                    "--group-by package requires a monorepo with workspace packages \
                     (package.json workspaces, pnpm-workspace.yaml, or tsconfig references). \
                     For single-package projects try --group-by directory instead.",
                    2,
                    output,
                ))
            } else {
                Ok(Some(crate::report::OwnershipResolver::Package(
                    crate::report::grouping::PackageResolver::new(root, &workspaces),
                )))
            }
        }
    }
}

/// Emit a terse `"loaded config: <path>"` line on stderr so users can verify
/// which config was picked up. Suppressed for non-human output formats (so
/// JSON/SARIF/markdown consumers get clean machine-readable output) and when
/// `--quiet` is set.
fn log_config_loaded(path: &Path, output: OutputFormat, quiet: bool) {
    if quiet || !matches!(output, OutputFormat::Human) {
        return;
    }
    if !should_log_config_loaded(path) {
        return;
    }
    eprintln!("loaded config: {}", path.display());
}

fn should_log_config_loaded(path: &Path) -> bool {
    let key = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    CONFIG_LOADED_LOGGED
        .lock()
        .is_ok_and(|mut logged| logged.insert(key))
}

#[expect(clippy::ref_option, reason = "&Option matches clap's field type")]
pub fn load_config(
    root: &Path,
    config_path: &Option<PathBuf>,
    output: OutputFormat,
    no_cache: bool,
    threads: usize,
    production: bool,
    quiet: bool,
) -> Result<ResolvedConfig, ExitCode> {
    load_config_for_analysis(
        root,
        config_path,
        output,
        no_cache,
        threads,
        production.then_some(true),
        quiet,
        ProductionAnalysis::DeadCode,
    )
}

#[expect(clippy::ref_option, reason = "&Option matches clap's field type")]
#[expect(
    clippy::too_many_arguments,
    reason = "central config loader mirrors CLI dispatch options"
)]
pub fn load_config_for_analysis(
    root: &Path,
    config_path: &Option<PathBuf>,
    output: OutputFormat,
    no_cache: bool,
    threads: usize,
    production_override: Option<bool>,
    quiet: bool,
    analysis: ProductionAnalysis,
) -> Result<ResolvedConfig, ExitCode> {
    let user_config = if let Some(path) = config_path {
        match FallowConfig::load(path) {
            Ok(c) => {
                log_config_loaded(path, output, quiet);
                Some(c)
            }
            Err(e) => {
                let msg = format!("failed to load config '{}': {e}", path.display());
                return Err(crate::error::emit_error(&msg, 2, output));
            }
        }
    } else {
        match FallowConfig::find_and_load(root) {
            Ok(Some((config, found_path))) => {
                log_config_loaded(&found_path, output, quiet);
                Some(config)
            }
            Ok(None) => None,
            Err(e) => {
                return Err(crate::error::emit_error(&e, 2, output));
            }
        }
    };

    let loaded_user_config = user_config.is_some();
    let final_config = match user_config {
        Some(mut config) => {
            let production =
                production_override.unwrap_or_else(|| config.production.for_analysis(analysis));
            config.production = production.into();
            config
        }
        None => FallowConfig {
            production: production_override.unwrap_or(false).into(),
            ..FallowConfig::default()
        },
    };
    crate::telemetry::note_config_shape(config_shape_for(&final_config, loaded_user_config));

    if let Err(errors) =
        fallow_config::discover_and_validate_external_plugins(root, &final_config.plugins)
    {
        let joined = errors
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n  - ");
        let msg = format!("invalid external plugin definition:\n  - {joined}");
        return Err(crate::error::emit_error(&msg, 2, output));
    }

    if let Err(errors) = final_config.validate_resolved_boundaries(root) {
        let joined = errors
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join("\n  - ");
        let msg = format!("invalid boundary configuration:\n  - {joined}");
        return Err(crate::error::emit_error(&msg, 2, output));
    }

    let cache_max_size_mb = resolve_cache_max_size_env();
    let mut resolved = final_config.resolve(
        root.to_path_buf(),
        output,
        threads,
        no_cache,
        quiet,
        cache_max_size_mb,
    );
    if let Some(mb) = resolve_max_file_size_mb() {
        resolved.max_file_size_bytes = fallow_config::resolve_max_file_size_bytes(Some(mb));
    }
    apply_cache_dir_env_override(root, &mut resolved, resolve_cache_dir_env());
    crate::cache_notice::record_candidate(
        root,
        &resolved.cache_dir,
        output,
        quiet,
        resolved.no_cache,
    );

    match fallow_config::discover_workspaces_with_diagnostics(root, &resolved.ignore_patterns) {
        Ok((_, diagnostics)) => {
            fallow_config::stash_workspace_diagnostics(root, diagnostics.clone());
            if !diagnostics.is_empty() && matches!(output, OutputFormat::Human) && !quiet {
                eprintln!(
                    "fallow: {} workspace discovery diagnostic{}. \
                     Run `fallow list --workspaces` for detail.",
                    diagnostics.len(),
                    if diagnostics.len() == 1 { "" } else { "s" }
                );
            }
        }
        Err(err) => {
            return Err(crate::error::emit_error(&err.to_string(), 2, output));
        }
    }

    Ok(resolved)
}

fn config_shape_for(
    config: &FallowConfig,
    loaded_user_config: bool,
) -> crate::telemetry::ConfigShape {
    if !config.plugins.is_empty() || !config.framework.is_empty() {
        return crate::telemetry::ConfigShape::PluginsEnabled;
    }
    if config.rules != RulesConfig::default()
        || config
            .overrides
            .iter()
            .any(|entry| partial_rules_config_has_values(&entry.rules))
    {
        return crate::telemetry::ConfigShape::CustomRules;
    }
    if loaded_user_config {
        return crate::telemetry::ConfigShape::CustomConfig;
    }
    crate::telemetry::ConfigShape::Default
}

fn partial_rules_config_has_values(rules: &PartialRulesConfig) -> bool {
    serde_json::to_value(rules)
        .ok()
        .and_then(|value| value.as_object().map(|object| !object.is_empty()))
        .unwrap_or(false)
}

/// Read the workspace-discovery diagnostics produced by the most recent
/// `load_config_for_analysis` call for `root`. Thin re-export over
/// [`fallow_config::workspace_diagnostics_for`] so call sites inside the
/// CLI crate (`report::json::build_json*`) keep a stable module-local path.
#[must_use]
pub fn workspace_diagnostics_for(root: &Path) -> Vec<fallow_config::WorkspaceDiagnostic> {
    fallow_config::workspace_diagnostics_for(root)
}

/// Read `FALLOW_CACHE_MAX_SIZE` (megabytes) into `Option<u32>`, returning
/// `None` when the env var is unset or fails to parse as a positive integer.
/// Resolved here rather than as a clap flag because the cache cap is a
/// platform/CI ergonomic concern, not an analysis input; an env var keeps
/// it out of the `--help` surface (see ADR-009).
fn resolve_cache_max_size_env() -> Option<u32> {
    std::env::var("FALLOW_CACHE_MAX_SIZE")
        .ok()
        .and_then(|raw| raw.trim().parse::<u32>().ok())
        .filter(|mb| *mb > 0)
}

/// Read `FALLOW_CACHE_DIR` into an optional project-root-resolved cache path.
/// Relative values use the same project-root base as `cache.dir`.
fn resolve_cache_dir_env() -> Option<PathBuf> {
    std::env::var_os("FALLOW_CACHE_DIR")
        .map(PathBuf::from)
        .filter(|path| !path.as_os_str().is_empty())
}

fn resolve_cache_dir_value(root: &Path, path: PathBuf) -> PathBuf {
    if path.is_absolute() {
        path
    } else {
        root.join(path)
    }
}

fn apply_cache_dir_env_override(
    root: &Path,
    resolved: &mut ResolvedConfig,
    env_value: Option<PathBuf>,
) {
    if let Some(path) = env_value {
        resolved.cache_dir = resolve_cache_dir_value(root, path);
    }
}

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

    #[test]
    fn config_loaded_notice_dedupes_by_config_path() {
        let dir = tempfile::tempdir().unwrap();
        let first = dir.path().join("first.fallow.json");
        let second = dir.path().join("second.fallow.json");
        std::fs::write(&first, "{}").unwrap();
        std::fs::write(&second, "{}").unwrap();

        assert!(should_log_config_loaded(&first));
        assert!(!should_log_config_loaded(&first));
        assert!(should_log_config_loaded(&second));
    }

    #[test]
    fn cache_dir_env_value_resolves_relative_to_project_root() {
        assert_eq!(
            resolve_cache_dir_value(Path::new("/repo"), PathBuf::from(".cache/fallow")),
            PathBuf::from("/repo/.cache/fallow")
        );
        assert_eq!(
            resolve_cache_dir_value(Path::new("/repo"), PathBuf::from("/tmp/fallow-cache")),
            PathBuf::from("/tmp/fallow-cache")
        );
    }

    #[test]
    fn cache_dir_env_value_wins_over_configured_cache_dir() {
        let mut resolved = FallowConfig {
            cache: fallow_config::CacheConfig {
                dir: Some(PathBuf::from(".cache/from-config")),
                ..Default::default()
            },
            ..Default::default()
        }
        .resolve(
            PathBuf::from("/repo"),
            OutputFormat::Human,
            1,
            false,
            true,
            None,
        );

        apply_cache_dir_env_override(
            Path::new("/repo"),
            &mut resolved,
            Some(PathBuf::from(".cache/from-env")),
        );

        assert_eq!(resolved.cache_dir, PathBuf::from("/repo/.cache/from-env"));
    }
}