fallow-cli 2.78.1

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
mod jscpd;
mod jsonc;
mod knip;
mod knip_fields;
mod knip_tables;
#[cfg(test)]
mod tests;
mod toml_gen;

use std::path::Path;
use std::process::ExitCode;

use jscpd::migrate_jscpd;
use jsonc::generate_jsonc;
use knip::migrate_knip;
use toml_gen::generate_toml;

/// A warning about a config field that could not be migrated.
#[derive(Debug)]
struct MigrationWarning {
    pub(super) source: &'static str,
    pub(super) field: String,
    pub(super) message: String,
    pub(super) suggestion: Option<String>,
}

impl std::fmt::Display for MigrationWarning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "[{}] `{}`: {}", self.source, self.field, self.message)?;
        if let Some(ref suggestion) = self.suggestion {
            write!(f, " (suggestion: {suggestion})")?;
        }
        Ok(())
    }
}

/// Result of migrating one or more source configs.
#[derive(Debug)]
struct MigrationResult {
    pub(super) config: serde_json::Value,
    pub(super) warnings: Vec<MigrationWarning>,
    pub(super) sources: Vec<String>,
}

/// Output format selection for the generated fallow config.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputFormat {
    Json,
    Jsonc,
    Toml,
}

impl OutputFormat {
    #[expect(
        clippy::case_sensitive_file_extension_comparisons,
        reason = "config file extensions are always lowercase"
    )]
    fn pick(use_toml: bool, use_jsonc: bool, result: &MigrationResult) -> Self {
        if use_toml {
            return Self::Toml;
        }
        if use_jsonc {
            return Self::Jsonc;
        }
        // Auto-mirror: if any source we read was JSONC-named, default to .fallowrc.jsonc.
        // Sources is populated with bare filenames ("knip.jsonc"), full paths
        // ("<dir>/knip.jsonc"), or `<file> (knip key)` / `<file> (jscpd key)` /
        // `<file> (knip config)` / `<file> (jscpd config)` suffixed forms. Strip
        // any " (...)" suffix before checking the extension so the
        // content-detection branch (which appends the tool tag for downstream
        // gates like the glob-drift caveat) does not break auto-mirror.
        if result
            .sources
            .iter()
            .any(|s| source_head(s).ends_with(".jsonc"))
        {
            Self::Jsonc
        } else {
            Self::Json
        }
    }

    fn filename(self) -> &'static str {
        match self {
            Self::Toml => "fallow.toml",
            Self::Jsonc => ".fallowrc.jsonc",
            Self::Json => ".fallowrc.json",
        }
    }
}

/// Run the migrate command.
///
/// Output format and filename are picked in priority order: `--toml` writes
/// `fallow.toml`, `--jsonc` writes `.fallowrc.jsonc`, otherwise the source
/// extension is mirrored (`knip.jsonc` produces `.fallowrc.jsonc`,
/// `knip.json` / `package.json` keys produce `.fallowrc.json`). The
/// generated JSONC content includes `//` comments either way; the `.jsonc`
/// extension exists so editors auto-detect JSON-with-comments syntax
/// highlighting.
pub fn run_migrate(
    root: &Path,
    use_toml: bool,
    use_jsonc: bool,
    dry_run: bool,
    from: Option<&Path>,
) -> ExitCode {
    // Check if a fallow config already exists
    let existing_names = [
        ".fallowrc.json",
        ".fallowrc.jsonc",
        "fallow.toml",
        ".fallow.toml",
    ];
    if !dry_run {
        for name in &existing_names {
            let path = root.join(name);
            if path.exists() {
                eprintln!(
                    "Error: {name} already exists. Remove it first or use --dry-run to preview."
                );
                return ExitCode::from(2);
            }
        }
    }

    let result = from.map_or_else(|| migrate_auto_detect(root), migrate_from_file);

    let result = match result {
        Ok(r) => r,
        Err(e) => {
            eprintln!("Error: {e}");
            return ExitCode::from(2);
        }
    };

    if result.sources.is_empty() {
        eprintln!("No knip or jscpd configuration found to migrate.");
        return ExitCode::from(2);
    }

    let format = OutputFormat::pick(use_toml, use_jsonc, &result);

    let output_content = match format {
        OutputFormat::Toml => generate_toml(&result),
        OutputFormat::Jsonc | OutputFormat::Json => generate_jsonc(&result),
    };

    if dry_run {
        println!("{output_content}");
    } else {
        let filename = format.filename();
        let output_path = root.join(filename);
        if let Err(e) = std::fs::write(&output_path, &output_content) {
            eprintln!("Error: failed to write {filename}: {e}");
            return ExitCode::from(2);
        }
        eprintln!("Created {filename}");
    }

    // Print source info, stripping any internal tool tag so the user sees
    // the original filename and not the migrator's provenance marker. See
    // issue #457.
    for source in &result.sources {
        eprintln!("Migrated from: {}", source_head(source));
    }

    // Print warnings (singular/plural-aware: a single typo'd rule is the
    // most common count==1 case now that unknown rules warn loudly).
    if !result.warnings.is_empty() {
        let count = result.warnings.len();
        let header = if count == 1 { "Warning" } else { "Warnings" };
        let noun = if count == 1 { "field" } else { "fields" };
        eprintln!();
        eprintln!("{header} ({count} skipped {noun}):");
        for warning in &result.warnings {
            eprintln!("  {warning}");
        }
    }

    // Glob-semantics caveat: knip and fallow use different glob engines, so
    // migrated `entry` / `ignorePatterns` may match a slightly different file
    // set than they did under knip. Single logical line so narrow terminals
    // can soft-wrap. Issue #457.
    if should_emit_glob_caveat(&result) {
        eprintln!();
        eprintln!(
            "Note: knip and fallow use different glob engines; verify migrated entry / ignorePatterns with `fallow check` before relying on CI. See https://docs.fallow.tools/migration/from-knip"
        );
    }

    ExitCode::SUCCESS
}

/// Auto-detect and migrate from knip and/or jscpd configs in the given root.
#[expect(
    clippy::case_sensitive_file_extension_comparisons,
    reason = "JS/TS extensions are always lowercase"
)]
fn migrate_auto_detect(root: &Path) -> Result<MigrationResult, String> {
    let mut config = serde_json::Map::new();
    let mut warnings = Vec::new();
    let mut sources = Vec::new();

    // Try knip configs
    let knip_files = [
        "knip.json",
        "knip.jsonc",
        ".knip.json",
        ".knip.jsonc",
        "knip.ts",
        "knip.config.ts",
    ];

    for name in &knip_files {
        let path = root.join(name);
        if path.exists() {
            if name.ends_with(".ts") {
                warnings.push(MigrationWarning {
                    source: "knip",
                    field: name.to_string(),
                    message: format!(
                        "TypeScript config files ({name}) cannot be parsed. \
                         Convert to knip.json first, then re-run migrate."
                    ),
                    suggestion: None,
                });
                continue;
            }
            let knip_value = load_json_or_jsonc(&path)?;
            migrate_knip(&knip_value, &mut config, &mut warnings);
            sources.push(name.to_string());
            break; // Only use the first knip config found
        }
    }

    // Try jscpd standalone config
    let mut found_jscpd_file = false;
    let jscpd_path = root.join(".jscpd.json");
    if jscpd_path.exists() {
        let jscpd_value = load_json_or_jsonc(&jscpd_path)?;
        migrate_jscpd(&jscpd_value, &mut config, &mut warnings);
        sources.push(".jscpd.json".to_string());
        found_jscpd_file = true;
    }

    // Check package.json for embedded knip/jscpd config (single read)
    let need_pkg_knip = sources.is_empty();
    let need_pkg_jscpd = !found_jscpd_file;
    if need_pkg_knip || need_pkg_jscpd {
        let pkg_path = root.join("package.json");
        if pkg_path.exists() {
            let pkg_content = std::fs::read_to_string(&pkg_path)
                .map_err(|e| format!("failed to read package.json: {e}"))?;
            let pkg_value: serde_json::Value = serde_json::from_str(&pkg_content)
                .map_err(|e| format!("failed to parse package.json: {e}"))?;
            if need_pkg_knip && let Some(knip_config) = pkg_value.get("knip") {
                migrate_knip(knip_config, &mut config, &mut warnings);
                sources.push("package.json (knip key)".to_string());
            }
            if need_pkg_jscpd && let Some(jscpd_config) = pkg_value.get("jscpd") {
                migrate_jscpd(jscpd_config, &mut config, &mut warnings);
                sources.push("package.json (jscpd key)".to_string());
            }
        }
    }

    Ok(MigrationResult {
        config: serde_json::Value::Object(config),
        warnings,
        sources,
    })
}

/// Migrate from a specific config file.
#[expect(
    clippy::case_sensitive_file_extension_comparisons,
    reason = "JS/TS extensions are always lowercase"
)]
fn migrate_from_file(path: &Path) -> Result<MigrationResult, String> {
    if !path.exists() {
        return Err(format!("config file not found: {}", path.display()));
    }

    let mut config = serde_json::Map::new();
    let mut warnings = Vec::new();
    let mut sources = Vec::new();

    let filename = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();

    if filename.contains("knip") {
        if filename.ends_with(".ts") {
            return Err(format!(
                "TypeScript config files ({filename}) cannot be parsed. \
                 Convert to knip.json first, then re-run migrate."
            ));
        }
        let knip_value = load_json_or_jsonc(path)?;
        migrate_knip(&knip_value, &mut config, &mut warnings);
        sources.push(path.display().to_string());
    } else if filename.contains("jscpd") {
        let jscpd_value = load_json_or_jsonc(path)?;
        migrate_jscpd(&jscpd_value, &mut config, &mut warnings);
        sources.push(path.display().to_string());
    } else if filename == "package.json" {
        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
        let pkg_value: serde_json::Value = serde_json::from_str(&content)
            .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
        if let Some(knip_config) = pkg_value.get("knip") {
            migrate_knip(knip_config, &mut config, &mut warnings);
            sources.push(format!("{} (knip key)", path.display()));
        }
        if let Some(jscpd_config) = pkg_value.get("jscpd") {
            migrate_jscpd(jscpd_config, &mut config, &mut warnings);
            sources.push(format!("{} (jscpd key)", path.display()));
        }
        if sources.is_empty() {
            return Err(format!(
                "no knip or jscpd configuration found in {}",
                path.display()
            ));
        }
    } else {
        // Try to detect format from content
        let value = load_json_or_jsonc(path)?;
        // If it has knip-like fields, treat as knip
        if value.get("entry").is_some()
            || value.get("ignore").is_some()
            || value.get("rules").is_some()
            || value.get("project").is_some()
            || value.get("ignoreDependencies").is_some()
            || value.get("ignoreExportsUsedInFile").is_some()
        {
            migrate_knip(&value, &mut config, &mut warnings);
            // Tag the source so `should_emit_glob_caveat` can detect knip
            // provenance for `--from <custom-name>.json` paths whose
            // filename does not contain "knip". Issue #457.
            sources.push(format!("{} (knip config)", path.display()));
        }
        // If it has jscpd-like fields, treat as jscpd
        else if value.get("minTokens").is_some()
            || value.get("minLines").is_some()
            || value.get("threshold").is_some()
            || value.get("mode").is_some()
        {
            migrate_jscpd(&value, &mut config, &mut warnings);
            sources.push(format!("{} (jscpd config)", path.display()));
        } else {
            return Err(format!(
                "could not determine config format for {}",
                path.display()
            ));
        }
    }

    Ok(MigrationResult {
        config: serde_json::Value::Object(config),
        warnings,
        sources,
    })
}

/// Load a JSON or JSONC file, accepting comments and trailing commas.
fn load_json_or_jsonc(path: &Path) -> Result<serde_json::Value, String> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;

    jsonc_parser::parse_to_serde_value(&content, &jsonc_parse_options())
        .map_err(|e| format!("failed to parse {}: {e}", path.display()))
}

fn jsonc_parse_options() -> jsonc_parser::ParseOptions {
    jsonc_parser::ParseOptions {
        allow_comments: true,
        allow_loose_object_property_names: false,
        allow_trailing_commas: true,
        allow_missing_commas: false,
        allow_single_quoted_strings: false,
        allow_hexadecimal_numbers: false,
        allow_unary_plus_numbers: false,
    }
}

/// Strip JSONC-style trailing commas (`,` immediately before `}` or `]`)
/// without touching commas inside string literals.
#[cfg(test)]
fn strip_trailing_commas(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let bytes = input.as_bytes();
    let mut i = 0;
    let mut last_emit = 0;
    let mut in_string = false;
    let mut escaped = false;

    while i < bytes.len() {
        let b = bytes[i];
        if in_string {
            if escaped {
                escaped = false;
            } else if b == b'\\' {
                escaped = true;
            } else if b == b'"' {
                in_string = false;
            }
            i += 1;
            continue;
        }
        if b == b'"' {
            in_string = true;
            i += 1;
            continue;
        }
        if b == b',' {
            let mut j = i + 1;
            while j < bytes.len() && bytes[j].is_ascii_whitespace() {
                j += 1;
            }
            if j < bytes.len()
                && (bytes[j] == b'}' || bytes[j] == b']')
                && comma_follows_json_value(bytes, i)
            {
                out.push_str(&input[last_emit..i]);
                last_emit = i + 1;
            }
        }
        i += 1;
    }

    out.push_str(&input[last_emit..]);
    out
}

#[cfg(test)]
fn comma_follows_json_value(bytes: &[u8], comma_index: usize) -> bool {
    let Some(prev) = bytes[..comma_index]
        .iter()
        .rev()
        .copied()
        .find(|b| !b.is_ascii_whitespace())
    else {
        return false;
    };

    matches!(prev, b'"' | b'}' | b']' | b'0'..=b'9' | b'e' | b'l')
}

/// Strip any trailing ` (...)` suffix from a `MigrationResult.sources` entry,
/// returning the original filename / path portion. The migrator appends
/// `" (knip key)"`, `" (jscpd key)"`, `" (knip config)"`, or `" (jscpd config)"`
/// to a source so downstream predicates can detect tool provenance, but
/// extension-matching predicates (`OutputFormat::pick`'s `.jsonc` auto-mirror)
/// and user-facing output must see the original filename. Uses `rsplit_once`
/// so a project path containing its own ` (...)` segment (e.g.
/// `/path/to/react (v18)/knip.jsonc`) is preserved correctly; the closing-paren
/// guard rejects accidental matches on unbalanced text. See issue #457.
fn source_head(s: &str) -> &str {
    if let Some((head, tail)) = s.rsplit_once(" (")
        && tail.ends_with(')')
    {
        return head;
    }
    s
}

/// Decide whether the migrate command should print a glob-semantics caveat
/// after the warnings block. Emitted only when knip contributed to the
/// migration AND the resulting config carries `entry` or `ignorePatterns`,
/// since those are the only fields where knip's glob engine and fallow's
/// `globset` can diverge. See issue #457.
fn should_emit_glob_caveat(result: &MigrationResult) -> bool {
    let knip_contributed = result.sources.iter().any(|s| s.contains("knip"));
    if !knip_contributed {
        return false;
    }
    let Some(obj) = result.config.as_object() else {
        return false;
    };
    obj.contains_key("entry") || obj.contains_key("ignorePatterns")
}

/// Extract a string-or-array field as a `Vec<String>`.
fn string_or_array(value: &serde_json::Value) -> Vec<String> {
    match value {
        serde_json::Value::String(s) => vec![s.clone()],
        serde_json::Value::Array(arr) => arr
            .iter()
            .filter_map(|v| v.as_str().map(String::from))
            .collect(),
        _ => vec![],
    }
}