fallow-cli 2.100.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use std::path::{Component, Path, PathBuf};
use std::process::{Command, ExitCode};

use fallow_config::OutputFormat;
use serde_json::{Value, json};

use crate::error::emit_error;
use crate::output_envelope::{
    FallowOutput, InspectEvidence, InspectEvidenceScope, InspectEvidenceSection,
    InspectFileIdentity, InspectIdentity, InspectOutput, InspectSectionStatus,
    InspectSymbolIdentity, InspectTargetDescriptor, serialize_root_output,
};
use crate::report;
use crate::report::sink::outln;

#[derive(Clone)]
pub enum InspectTarget {
    File { file: String },
    Symbol { file: String, export_name: String },
}

pub struct InspectOptions<'a> {
    pub root: &'a Path,
    pub config_path: Option<&'a PathBuf>,
    pub output: OutputFormat,
    pub no_cache: bool,
    pub no_production: bool,
    pub max_file_size: Option<u32>,
    pub threads: usize,
    pub quiet: bool,
    pub production: bool,
    pub workspace: Option<&'a Vec<String>>,
    pub target: InspectTarget,
}

#[derive(Debug)]
struct NormalizedTarget {
    file: String,
    export_name: Option<String>,
}

impl NormalizedTarget {
    fn new(root: &Path, target: &InspectTarget) -> Result<Self, String> {
        match target {
            InspectTarget::File { file } => {
                require_non_empty("file", file)?;
                let file = normalize_target_file(root, file)?;
                Ok(Self {
                    file,
                    export_name: None,
                })
            }
            InspectTarget::Symbol { file, export_name } => {
                require_non_empty("symbol file", file)?;
                require_non_empty("symbol export", export_name)?;
                let file = normalize_target_file(root, file)?;
                Ok(Self {
                    file,
                    export_name: Some(export_name.clone()),
                })
            }
        }
    }

    fn target_descriptor(&self) -> InspectTargetDescriptor {
        match self.export_name.as_deref() {
            Some(export_name) => InspectTargetDescriptor::Symbol {
                file: self.file.clone(),
                export_name: export_name.to_string(),
            },
            None => InspectTargetDescriptor::File {
                file: self.file.clone(),
            },
        }
    }
}

pub fn run_inspect(opts: &InspectOptions<'_>) -> ExitCode {
    let target = match NormalizedTarget::new(opts.root, &opts.target) {
        Ok(target) => target,
        Err(message) => return emit_error(&message, 2, opts.output),
    };

    let target_file = target.file.as_str();
    let trace_file = match run_required_json(opts, trace_file_args(target_file)) {
        Ok(value) => value,
        Err(message) => return emit_error(&message, 2, opts.output),
    };
    let trace_export = match target.export_name.as_deref() {
        Some(export_name) => {
            match run_required_json(opts, trace_export_args(target_file, export_name)) {
                Ok(value) => Some(value),
                Err(message) => return emit_error(&message, 2, opts.output),
            }
        }
        None => None,
    };

    let mut warnings = Vec::new();
    if target.export_name.is_some() {
        warnings.push(
            "dead_code, duplication, complexity, and security evidence is file-scoped in v1; file:line symbol narrowing is a follow-up"
                .to_string(),
        );
    }

    let evidence = InspectEvidence {
        trace_file: InspectEvidenceSection::ok(InspectEvidenceScope::File, trace_file.clone()),
        trace_export: trace_export
            .clone()
            .map(|value| InspectEvidenceSection::ok(InspectEvidenceScope::Symbol, value)),
        dead_code: optional_section(
            opts,
            dead_code_args(target_file),
            InspectEvidenceScope::File,
            |value| value,
        ),
        duplication: optional_section(
            opts,
            dupes_args(),
            InspectEvidenceScope::ProjectFilteredToFile,
            |value| filter_path_array(&value, target_file, "clone_groups"),
        ),
        complexity: optional_section(
            opts,
            health_args(),
            InspectEvidenceScope::ProjectFilteredToFile,
            |value| filter_path_array(&value, target_file, "findings"),
        ),
        security: optional_section(
            opts,
            security_args(target_file),
            InspectEvidenceScope::File,
            |value| value,
        ),
    };
    push_inspect_warnings(&mut warnings, &evidence);

    let identity = match trace_export.as_ref() {
        Some(export) => InspectIdentity::Symbol(InspectSymbolIdentity {
            file: target.file.clone(),
            export_name: target.export_name.clone().unwrap_or_default(),
            file_reachable: export.get("file_reachable").cloned(),
            is_entry_point: export.get("is_entry_point").cloned(),
            is_used: export.get("is_used").cloned(),
            reason: export.get("reason").cloned(),
        }),
        None => InspectIdentity::File(InspectFileIdentity {
            file: target.file.clone(),
            is_reachable: trace_file.get("is_reachable").cloned(),
            is_entry_point: trace_file.get("is_entry_point").cloned(),
            export_count: trace_file
                .get("exports")
                .and_then(Value::as_array)
                .map(Vec::len),
            import_count: trace_file
                .get("imports_from")
                .and_then(Value::as_array)
                .map(Vec::len),
            imported_by_count: trace_file
                .get("imported_by")
                .and_then(Value::as_array)
                .map(Vec::len),
        }),
    };

    let bundle = InspectOutput {
        target: target.target_descriptor(),
        identity,
        evidence,
        warnings,
    };

    match opts.output {
        OutputFormat::Json => {
            let value = match serialize_root_output(FallowOutput::Inspect(bundle)) {
                Ok(value) => value,
                Err(err) => {
                    return emit_error(
                        &format!("failed to serialize inspect output: {err}"),
                        2,
                        opts.output,
                    );
                }
            };
            report::emit_json(&value, "inspect")
        }
        OutputFormat::Human => {
            print_human(&bundle, opts.quiet);
            ExitCode::SUCCESS
        }
        _ => emit_error("inspect supports --format json or human", 2, opts.output),
    }
}

fn print_human(bundle: &InspectOutput, quiet: bool) {
    outln!("Inspect target");
    outln!();
    outln!("  target: {}", json_display(&bundle.target));
    outln!("  identity: {}", json_display(&bundle.identity));
    outln!();
    outln!("Evidence");
    print_evidence_summary("trace_file", &bundle.evidence.trace_file);
    if let Some(section) = bundle.evidence.trace_export.as_ref() {
        print_evidence_summary("trace_export", section);
    }
    print_evidence_summary("dead_code", &bundle.evidence.dead_code);
    print_evidence_summary("duplication", &bundle.evidence.duplication);
    print_evidence_summary("complexity", &bundle.evidence.complexity);
    print_evidence_summary("security", &bundle.evidence.security);
    if !bundle.warnings.is_empty() && !quiet {
        outln!();
        for warning in &bundle.warnings {
            outln!("  warning: {warning}");
        }
    }
}

fn json_display(value: &impl serde::Serialize) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "<unprintable>".to_string())
}

fn print_evidence_summary(name: &str, section: &InspectEvidenceSection) {
    let status = match section.status {
        InspectSectionStatus::Ok => "ok",
        InspectSectionStatus::Error => "error",
    };
    let detail = evidence_detail(section)
        .map(|detail| format!(" ({detail})"))
        .unwrap_or_default();
    outln!(
        "  {name}: {status} [{}]{detail}",
        evidence_scope_label(section.scope)
    );
}

fn evidence_scope_label(scope: InspectEvidenceScope) -> &'static str {
    match scope {
        InspectEvidenceScope::Symbol => "symbol",
        InspectEvidenceScope::File => "file",
        InspectEvidenceScope::ProjectFilteredToFile => "project filtered to file",
    }
}

fn evidence_detail(section: &InspectEvidenceSection) -> Option<String> {
    if let Some(message) = section.message.as_deref() {
        return Some(message.to_string());
    }
    let data = section.data.as_ref()?;
    if let Some(count) = data.get("matched_count").and_then(Value::as_u64) {
        return Some(format!("matches: {count}"));
    }
    if let Some(exports) = data.get("exports").and_then(Value::as_array) {
        return Some(format!("exports: {}", exports.len()));
    }
    None
}

fn run_required_json(opts: &InspectOptions<'_>, args: Vec<String>) -> Result<Value, String> {
    run_child_json(opts, args).and_then(|output| output.value)
}

fn optional_section<F>(
    opts: &InspectOptions<'_>,
    args: Vec<String>,
    scope: InspectEvidenceScope,
    filter: F,
) -> InspectEvidenceSection
where
    F: FnOnce(Value) -> Value,
{
    match run_child_json(opts, args) {
        Ok(output) => match output.value {
            Ok(value) => InspectEvidenceSection::ok(scope, filter(value)),
            Err(message) => InspectEvidenceSection::error(scope, message),
        },
        Err(message) => InspectEvidenceSection::error(scope, message),
    }
}

struct ChildJson {
    value: Result<Value, String>,
}

fn run_child_json(opts: &InspectOptions<'_>, args: Vec<String>) -> Result<ChildJson, String> {
    let binary = std::env::current_exe()
        .map_err(|err| format!("failed to locate current fallow binary: {err}"))?;
    let mut command = Command::new(binary);
    command.args(build_child_args(opts, args));
    let output = command
        .output()
        .map_err(|err| format!("failed to run child analysis: {err}"))?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let code = output.status.code().unwrap_or(2);
    if code > 1 {
        let message = child_error_message(code, &stdout, &stderr);
        return Err(message);
    }
    if stdout.trim().is_empty() {
        return Ok(ChildJson {
            value: Err("child analysis returned no JSON".to_string()),
        });
    }
    Ok(ChildJson {
        value: serde_json::from_str(&stdout)
            .map_err(|err| format!("child analysis returned invalid JSON: {err}")),
    })
}

fn build_child_args(opts: &InspectOptions<'_>, command_args: Vec<String>) -> Vec<String> {
    let command_name = command_args.first().map(String::as_str);
    let mut args = vec![
        "--root".to_string(),
        opts.root.to_string_lossy().to_string(),
        "--format".to_string(),
        "json".to_string(),
        "--quiet".to_string(),
    ];
    if let Some(config) = opts.config_path {
        args.extend(["--config".to_string(), config.to_string_lossy().to_string()]);
    }
    if opts.no_cache {
        args.push("--no-cache".to_string());
    }
    if opts.no_production && command_name != Some("security") {
        args.push("--no-production".to_string());
    }
    if let Some(max_file_size) = opts.max_file_size {
        args.extend(["--max-file-size".to_string(), max_file_size.to_string()]);
    }
    args.extend(["--threads".to_string(), opts.threads.to_string()]);
    if opts.production && command_name != Some("security") {
        args.push("--production".to_string());
    }
    if let Some(workspace) = opts.workspace {
        args.extend(["--workspace".to_string(), workspace.join(",")]);
    }
    args.extend(command_args);
    args
}

fn trace_file_args(file: &str) -> Vec<String> {
    vec![
        "dead-code".to_string(),
        "--trace-file".to_string(),
        file.to_string(),
    ]
}

fn trace_export_args(file: &str, export_name: &str) -> Vec<String> {
    vec![
        "dead-code".to_string(),
        "--trace".to_string(),
        format!("{file}:{export_name}"),
    ]
}

fn dead_code_args(file: &str) -> Vec<String> {
    vec![
        "dead-code".to_string(),
        "--file".to_string(),
        file.to_string(),
    ]
}

fn dupes_args() -> Vec<String> {
    vec!["dupes".to_string()]
}

fn health_args() -> Vec<String> {
    vec!["health".to_string(), "--complexity".to_string()]
}

fn security_args(file: &str) -> Vec<String> {
    vec![
        "security".to_string(),
        "--file".to_string(),
        file.to_string(),
    ]
}

fn filter_path_array(value: &Value, file: &str, key: &str) -> Value {
    let matched = value
        .get(key)
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter(|item| value_mentions_file(item, file))
                .cloned()
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    let matched_count = matched.len();

    json!({
        key: matched,
        "matched_count": matched_count,
        "summary": value.get("summary").cloned(),
        "stats": value.get("stats").cloned(),
    })
}

fn value_mentions_file(value: &Value, file: &str) -> bool {
    match value {
        Value::String(s) => path_eq(s, file),
        Value::Array(items) => items.iter().any(|item| value_mentions_file(item, file)),
        Value::Object(map) => map.values().any(|item| value_mentions_file(item, file)),
        _ => false,
    }
}

fn path_eq(left: &str, right: &str) -> bool {
    left.replace('\\', "/") == right.replace('\\', "/")
}

fn normalize_target_file(root: &Path, file: &str) -> Result<String, String> {
    let raw = file.trim();
    let normalized_raw = raw.replace('\\', "/");
    let path = Path::new(&normalized_raw);
    let relative = if path.is_absolute() {
        let absolute = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
        absolute
            .strip_prefix(root)
            .map_err(|_| {
                format!(
                    "inspect target must be inside the project root: {}",
                    absolute.display()
                )
            })?
            .to_path_buf()
    } else {
        path.to_path_buf()
    };
    let mut parts = Vec::new();
    for component in relative.components() {
        match component {
            Component::CurDir => {}
            Component::Normal(part) => parts.push(part.to_string_lossy().to_string()),
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(format!(
                    "inspect target must be a root-relative path inside the project: {raw}"
                ));
            }
        }
    }
    if parts.is_empty() {
        return Err("inspect target file must not be empty".to_string());
    }
    Ok(parts.join("/"))
}

fn child_error_message(code: i32, stdout: &str, stderr: &str) -> String {
    structured_child_message(stdout)
        .or_else(|| {
            let trimmed = strip_ansi(stderr.trim());
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed)
            }
        })
        .unwrap_or_else(|| format!("child analysis exited with code {code}"))
}

fn structured_child_message(stdout: &str) -> Option<String> {
    let value = serde_json::from_str::<Value>(stdout.trim()).ok()?;
    value
        .get("message")
        .or_else(|| value.get("error_message"))
        .and_then(Value::as_str)
        .map(strip_ansi)
        .filter(|message| !message.is_empty())
}

fn strip_ansi(input: &str) -> String {
    let mut output = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '\u{1b}' && chars.peek() == Some(&'[') {
            chars.next();
            for next in chars.by_ref() {
                if ('@'..='~').contains(&next) {
                    break;
                }
            }
            continue;
        }
        if ch.is_control() && ch != '\n' && ch != '\t' {
            continue;
        }
        output.push(ch);
    }
    output.trim().to_string()
}

fn push_inspect_warnings(warnings: &mut Vec<String>, evidence: &InspectEvidence) {
    push_warning(warnings, "dead_code", &evidence.dead_code);
    push_warning(warnings, "duplication", &evidence.duplication);
    push_warning(warnings, "complexity", &evidence.complexity);
    push_warning(warnings, "security", &evidence.security);
}

fn push_warning(warnings: &mut Vec<String>, section: &str, evidence: &InspectEvidenceSection) {
    if matches!(evidence.status, InspectSectionStatus::Error)
        && let Some(message) = evidence.message.as_ref()
    {
        warnings.push(format!("{section} evidence unavailable: {message}"));
    }
}

fn require_non_empty(field: &str, value: &str) -> Result<(), String> {
    if value.trim().is_empty() {
        return Err(format!("{field} must not be empty"));
    }
    Ok(())
}

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

    fn inspect_options<'a>(
        root: &'a Path,
        config_path: Option<&'a PathBuf>,
        target: InspectTarget,
    ) -> InspectOptions<'a> {
        InspectOptions {
            root,
            config_path,
            output: OutputFormat::Json,
            no_cache: true,
            no_production: true,
            max_file_size: Some(2),
            threads: 3,
            quiet: true,
            production: false,
            workspace: None,
            target,
        }
    }

    #[test]
    fn normalized_target_uses_root_relative_posix_path() {
        let root = std::env::current_dir().unwrap();
        let file = root
            .join("src")
            .join("api.ts")
            .to_string_lossy()
            .to_string();

        let target = NormalizedTarget::new(&root, &InspectTarget::File { file }).unwrap();

        assert_eq!(target.file, "src/api.ts");
    }

    #[test]
    fn normalized_target_rejects_parent_paths() {
        let root = PathBuf::from("/repo");
        let file = "../other.ts".to_string();

        let err = NormalizedTarget::new(&root, &InspectTarget::File { file }).unwrap_err();

        assert!(err.contains("inside the project"));
    }

    #[test]
    fn child_args_forward_global_inspect_overrides() {
        let root = PathBuf::from("/repo");
        let config_path = Some(PathBuf::from("/repo/.fallowrc.json"));
        let opts = inspect_options(
            &root,
            config_path.as_ref(),
            InspectTarget::File {
                file: "src/api.ts".to_string(),
            },
        );

        let args = build_child_args(&opts, dead_code_args("src/api.ts"));

        assert!(
            args.windows(2)
                .any(|pair| pair == ["--config", "/repo/.fallowrc.json"])
        );
        assert!(args.contains(&"--no-cache".to_string()));
        assert!(args.contains(&"--no-production".to_string()));
        assert!(args.windows(2).any(|pair| pair == ["--max-file-size", "2"]));
        assert!(args.windows(2).any(|pair| pair == ["--threads", "3"]));
    }

    #[test]
    fn child_args_do_not_forward_production_overrides_to_security() {
        let root = PathBuf::from("/repo");
        let config_path = None;
        let opts = inspect_options(
            &root,
            config_path.as_ref(),
            InspectTarget::File {
                file: "src/api.ts".to_string(),
            },
        );

        let args = build_child_args(&opts, security_args("src/api.ts"));

        assert!(!args.contains(&"--no-production".to_string()));
        assert!(!args.contains(&"--production".to_string()));
    }

    #[test]
    fn child_error_prefers_structured_stdout_message() {
        let stdout = r#"{"message":"\u001b[31mconfig failed\u001b[0m","exit_code":2}"#;
        let stderr = "warning before JSON\n";

        assert_eq!(child_error_message(2, stdout, stderr), "config failed");
    }
}