fallow-cli 3.16.0

CLI for fallow, 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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "tests and benches use unwrap and expect to keep fixture setup concise"
)]

#[path = "common/mod.rs"]
mod common;

use common::{parse_json, run_fallow_raw};
use std::fs;

/// Create a temp dir with a knip config for migration testing.
fn migrate_temp_dir(suffix: &str, config_name: &str, config_content: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "fallow-migrate-test-{}-{}",
        std::process::id(),
        suffix
    ));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join("package.json"),
        r#"{"name": "migrate-test", "main": "src/index.ts"}"#,
    )
    .unwrap();
    fs::write(dir.join(config_name), config_content).unwrap();
    dir
}

fn cleanup(dir: &std::path::Path) {
    let _ = fs::remove_dir_all(dir);
}

#[test]
fn migrate_dry_run_outputs_config() {
    let dir = migrate_temp_dir(
        "dryrun",
        "knip.json",
        r#"{"entry": ["src/index.ts"], "ignore": ["dist/**"]}"#,
    );
    let output = run_fallow_raw(&[
        "migrate",
        "--dry-run",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(
        output.code, 0,
        "migrate --dry-run should exit 0, stderr: {}",
        output.stderr
    );
    assert!(
        output.stdout.contains("entry") || output.stdout.contains("$schema"),
        "dry-run should output the migrated config"
    );
    cleanup(&dir);
}

#[test]
fn migrate_dry_run_toml_output() {
    let dir = migrate_temp_dir("toml", "knip.json", r#"{"entry": ["src/index.ts"]}"#);
    let output = run_fallow_raw(&[
        "migrate",
        "--dry-run",
        "--toml",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(output.code, 0, "migrate --dry-run --toml should exit 0");
    assert!(
        output.stdout.contains('='),
        "TOML output should use = syntax"
    );
    cleanup(&dir);
}

#[test]
fn migrate_writes_fallowrc_json_when_source_is_knip_json() {
    let dir = migrate_temp_dir("out-json", "knip.json", r#"{"entry": ["src/index.ts"]}"#);
    let output = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(
        dir.join(".fallowrc.json").exists(),
        ".fallowrc.json should be written for knip.json source"
    );
    assert!(
        !dir.join(".fallowrc.jsonc").exists(),
        ".fallowrc.jsonc should NOT be written for knip.json source"
    );
    cleanup(&dir);
}

/// Issue #1794: with a local `node_modules/fallow/schema.json` present,
/// `fallow migrate` writes the local schema path instead of the remote URL,
/// and the migrated config still loads through the real config loader.
#[test]
fn migrate_schema_prefers_local_when_node_modules_fallow_present() {
    let dir = migrate_temp_dir(
        "schema-local",
        "knip.json",
        r#"{"entry": ["src/index.ts"]}"#,
    );
    fs::create_dir_all(dir.join("node_modules/fallow")).unwrap();
    fs::write(dir.join("node_modules/fallow/schema.json"), "{}").unwrap();

    let output = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(output.code, 0, "stderr: {}", output.stderr);

    let config_path = dir.join(".fallowrc.json");
    let content = fs::read_to_string(&config_path).unwrap();
    assert!(
        content.contains("\"$schema\": \"./node_modules/fallow/schema.json\""),
        "expected local schema path with node_modules/fallow present, got: {content}"
    );
    assert!(!content.contains("raw.githubusercontent.com"));

    fallow_config::FallowConfig::load(&config_path)
        .unwrap_or_else(|e| panic!("migrated output with local schema must load: {e:?}"));
    cleanup(&dir);
}

#[test]
fn migrate_auto_writes_fallowrc_jsonc_when_source_is_knip_jsonc() {
    let dir = migrate_temp_dir(
        "out-jsonc-auto",
        "knip.jsonc",
        "{\n  // header comment\n  \"entry\": [\"src/index.ts\"]\n}\n",
    );
    let output = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(
        dir.join(".fallowrc.jsonc").exists(),
        ".fallowrc.jsonc should be written when source is knip.jsonc"
    );
    assert!(
        !dir.join(".fallowrc.json").exists(),
        ".fallowrc.json should NOT be written when source is knip.jsonc"
    );
    cleanup(&dir);
}

#[test]
fn migrate_explicit_jsonc_flag_overrides_json_source() {
    let dir = migrate_temp_dir(
        "out-jsonc-flag",
        "knip.json",
        r#"{"entry": ["src/index.ts"]}"#,
    );
    let output = run_fallow_raw(&[
        "migrate",
        "--jsonc",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(
        dir.join(".fallowrc.jsonc").exists(),
        "--jsonc must force .fallowrc.jsonc even when source is knip.json"
    );
    assert!(!dir.join(".fallowrc.json").exists());
    cleanup(&dir);
}

#[test]
fn migrate_jsonc_and_toml_are_mutually_exclusive() {
    let dir = migrate_temp_dir("exclusive", "knip.json", r#"{"entry": ["src/index.ts"]}"#);
    let output = run_fallow_raw(&[
        "migrate",
        "--jsonc",
        "--toml",
        "--dry-run",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_ne!(
        output.code, 0,
        "clap should reject --jsonc and --toml together"
    );
    assert!(
        output.stderr.contains("cannot be used with") || output.stderr.contains("conflicts"),
        "expected clap conflict error, got stderr: {}",
        output.stderr
    );
    cleanup(&dir);
}

#[test]
fn migrate_existing_fallowrc_jsonc_blocks_run() {
    let dir = migrate_temp_dir(
        "blocked-jsonc",
        "knip.json",
        r#"{"entry": ["src/index.ts"]}"#,
    );
    fs::write(dir.join(".fallowrc.jsonc"), "{}").unwrap();
    let output = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(
        output.code, 2,
        "migrate should refuse to overwrite existing .fallowrc.jsonc"
    );
    assert!(
        output.stderr.contains(".fallowrc.jsonc already exists"),
        "stderr should mention the blocking file, got: {}",
        output.stderr
    );
    cleanup(&dir);
}

/// Build a fixture where a plugin-owned entry imports one source file while a
/// second source file is unused and ignored only at reporting time.
fn graph_preserving_fixture(suffix: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "fallow-migrate-roundtrip-{}-{}",
        std::process::id(),
        suffix
    ));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();

    fs::write(
        dir.join("package.json"),
        r#"{"name": "graph-preserving-fixture", "devDependencies": {"vitest": "latest"}}"#,
    )
    .unwrap();
    fs::create_dir_all(dir.join("src")).unwrap();
    fs::write(
        dir.join("vitest.config.ts"),
        "import './src/feature';\nexport default {};\n",
    )
    .unwrap();
    fs::write(dir.join("src/feature.ts"), "export const feature = true;\n").unwrap();
    fs::write(dir.join("src/hidden.ts"), "export const hidden = true;\n").unwrap();

    dir
}

#[test]
fn migrate_knip_ignore_suppresses_findings_without_removing_files() {
    let dir = graph_preserving_fixture("ignore-findings");
    fs::write(
        dir.join("knip.json"),
        r#"{"ignore": ["vitest.config.ts", "src/hidden.ts"]}"#,
    )
    .unwrap();

    fs::write(
        dir.join(".fallowrc.json"),
        r#"{"ignorePatterns":["vitest.config.ts","src/hidden.ts"]}"#,
    )
    .unwrap();
    let legacy = run_fallow_raw(&[
        "dead-code",
        "--format",
        "json",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    let legacy_findings = parse_json(&legacy);
    assert!(
        legacy_findings["unused_files"]
            .as_array()
            .unwrap()
            .iter()
            .any(|finding| finding["path"] == "src/feature.ts"),
        "fixture must reproduce the old graph-removing migration"
    );
    fs::remove_file(dir.join(".fallowrc.json")).unwrap();

    let migrate = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(
        migrate.code, 0,
        "migrate should exit 0, stderr: {}",
        migrate.stderr
    );
    assert!(
        dir.join(".fallowrc.json").exists(),
        ".fallowrc.json should be written"
    );
    let migrated = fs::read_to_string(dir.join(".fallowrc.json")).unwrap();
    assert!(migrated.contains("\"ignoreFindings\""));
    assert!(!migrated.contains("\"ignorePatterns\""));

    let list = run_fallow_raw(&[
        "list",
        "--files",
        "--format",
        "json",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(
        list.code, 0,
        "list --files should exit 0, stderr: {}",
        list.stderr
    );

    let body = parse_json(&list);
    let files: Vec<String> = body
        .get("files")
        .and_then(|v| v.as_array())
        .expect("list --files JSON should carry a files array")
        .iter()
        .filter_map(|v| v.as_str().map(str::to_owned))
        .collect();

    let normalized: Vec<String> = files.iter().map(|f| f.replace('\\', "/")).collect();
    assert!(
        normalized.iter().any(|path| path == "src/hidden.ts"),
        "ignored findings must not remove their source file from discovery: {normalized:?}"
    );
    assert!(
        normalized.iter().any(|path| path == "vitest.config.ts"),
        "an ignored entry must stay discovered so its imports remain reachable: {normalized:?}"
    );

    let dead_code = run_fallow_raw(&[
        "dead-code",
        "--format",
        "json",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    let findings = parse_json(&dead_code);
    let unused_files = findings["unused_files"].as_array().unwrap();
    assert!(
        unused_files
            .iter()
            .all(|finding| finding["path"] != "src/hidden.ts"),
        "ignored source finding leaked into dead-code output: {unused_files:?}"
    );
    assert!(
        unused_files
            .iter()
            .all(|finding| finding["path"] != "src/feature.ts"),
        "the imported source should remain reachable through the plugin entry: {unused_files:?}"
    );

    cleanup(&dir);
}

#[test]
fn migrate_knip_ignore_warns_for_invalid_entries_without_dropping_valid_patterns() {
    let dir = migrate_temp_dir(
        "ignore-warning",
        "knip.json",
        r#"{"ignore": ["src/**", 7, null, "!src/keep.ts"]}"#,
    );
    let output = run_fallow_raw(&["migrate", "--dry-run", "--root", dir.to_str().unwrap()]);

    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(output.stdout.contains("\"ignoreFindings\""));
    assert!(output.stdout.contains("\"!src/keep.ts\""));
    assert!(!output.stdout.contains("\"ignorePatterns\""));
    assert!(output.stderr.contains("Warnings (2):"));
    assert!(output.stderr.contains("ignore[1]"));
    assert!(output.stderr.contains("ignore[2]"));

    cleanup(&dir);
}

/// Marker phrase of the note that states how knip's `ignore` scope differs
/// from fallow's `ignoreFindings`.
const IGNORE_SCOPE_NOTE_MARKER: &str =
    "knip's ignore also suppresses dependency and manifest issues";

#[test]
fn migrate_knip_states_ignore_scope_difference_once_even_without_ignore() {
    let dir = migrate_temp_dir(
        "ignore-scope-note",
        "knip.json",
        r#"{"entry": ["src/index.ts"]}"#,
    );
    let output = run_fallow_raw(&["migrate", "--dry-run", "--root", dir.to_str().unwrap()]);

    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(
        !output.stdout.contains("ignoreFindings"),
        "the note must not change the generated config: {}",
        output.stdout
    );
    assert_eq!(
        output.stderr.matches(IGNORE_SCOPE_NOTE_MARKER).count(),
        1,
        "expected exactly one ignore-scope note, got stderr: {}",
        output.stderr
    );

    cleanup(&dir);
}

#[test]
fn migrate_without_knip_omits_ignore_scope_note() {
    let dir = migrate_temp_dir(
        "ignore-scope-note-jscpd",
        ".jscpd.json",
        r#"{"minTokens": 100}"#,
    );
    let output = run_fallow_raw(&["migrate", "--dry-run", "--root", dir.to_str().unwrap()]);

    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(
        !output.stderr.contains(IGNORE_SCOPE_NOTE_MARKER),
        "a jscpd-only migration should not mention knip's ignore: {}",
        output.stderr
    );

    cleanup(&dir);
}

#[test]
fn migrate_knip_workspace_ignore_warns_instead_of_guessing_a_root() {
    let dir = migrate_temp_dir(
        "workspace-ignore-warning",
        "knip.json",
        r#"{"workspaces":{"packages/*":{"ignore":["src/generated/**"]}}}"#,
    );
    let output = run_fallow_raw(&["migrate", "--dry-run", "--root", dir.to_str().unwrap()]);

    assert_eq!(output.code, 0, "stderr: {}", output.stderr);
    assert!(output.stdout.contains("$schema"));
    assert!(!output.stdout.contains("ignoreFindings"));
    assert!(output.stderr.contains("workspaces.packages/*.ignore"));
    assert!(
        output
            .stderr
            .contains("project-root-relative ignoreFindings")
    );

    cleanup(&dir);
}

#[test]
fn migrate_no_config_exits_2() {
    let dir = std::env::temp_dir().join(format!("fallow-migrate-noconfig-{}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("package.json"), r#"{"name": "no-config"}"#).unwrap();

    let output = run_fallow_raw(&[
        "migrate",
        "--dry-run",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(
        output.code, 2,
        "migrate with no source config should exit 2"
    );
    let _ = fs::remove_dir_all(&dir);
}

/// Fixture for entry-glob conformance: a Next.js-shaped tree where the knip
/// `entry` globs select a known subset and the rest must stay out of scope.
fn entry_glob_fixture(suffix: &str) -> std::path::PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "fallow-migrate-roundtrip-{}-{}",
        std::process::id(),
        suffix
    ));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();

    fs::write(
        dir.join("package.json"),
        r#"{"name": "roundtrip-fixture", "main": "app/page.tsx"}"#,
    )
    .unwrap();

    let matched = [
        "app/layout.tsx",
        "app/page.tsx",
        "app/api/route.ts",
        "components/button.tsx",
        "components/card.tsx",
        "lib/utils.ts",
        "lib/db.ts",
        // Matches `lib/**/*.ts` like any other file there; knip selects it too.
        "lib/db.test.ts",
        "pages/_app.tsx",
        "pages/api/hello.ts",
    ];
    let unmatched = [
        "__tests__/utils.test.ts",
        "dist/bundle.js",
        "node_modules/foo/index.js",
        "scripts/build.ts",
    ];

    for rel in matched.iter().chain(unmatched.iter()) {
        let path = dir.join(rel);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, "export const x = 1;\n").unwrap();
    }

    dir
}

/// Migrated knip `entry` globs must scope the same file set knip documents.
///
/// This is the entry half of the former `migrate_roundtrip_globs_match_knip_documented_semantics`.
/// Its `ignore` half moved to `migrate_knip_ignore_suppresses_findings_without_removing_files`
/// when `ignore` started migrating to `ignoreFindings`, which deliberately no
/// longer narrows the file set. Entry-glob scoping did not change, so it keeps
/// its own end-to-end guard: a brace-expansion or globset regression in the
/// migrator's pattern copy would otherwise go unnoticed.
///
/// Asserts on `list --entry-points`, not `list --files`: discovery is scoped by
/// `ignorePatterns`, so the file list would measure the ignore path rather than
/// the entry globs this test is about.
#[test]
fn migrate_roundtrip_entry_globs_match_knip_documented_semantics() {
    let knip = r#"{
        "entry": [
            "app/**/*.{ts,tsx}",
            "pages/**/*.{ts,tsx}",
            "components/**/*.{ts,tsx}",
            "lib/**/*.ts"
        ]
    }"#;

    let dir = entry_glob_fixture("entry-globs");
    fs::write(dir.join("knip.json"), knip).unwrap();

    let migrate = run_fallow_raw(&["migrate", "--root", dir.to_str().unwrap(), "--quiet"]);
    assert_eq!(
        migrate.code, 0,
        "migrate should exit 0, stderr: {}",
        migrate.stderr
    );
    assert!(
        dir.join(".fallowrc.json").exists(),
        ".fallowrc.json should be written"
    );

    let list = run_fallow_raw(&[
        "list",
        "--entry-points",
        "--format",
        "json",
        "--root",
        dir.to_str().unwrap(),
        "--quiet",
    ]);
    assert_eq!(
        list.code, 0,
        "list --entry-points should exit 0, stderr: {}",
        list.stderr
    );

    let body = parse_json(&list);
    let entries: Vec<String> = body
        .get("entry_points")
        .and_then(|v| v.as_array())
        .expect("list --entry-points JSON should carry an entry_points array")
        .iter()
        .filter_map(|v| v.get("path").and_then(|p| p.as_str()).map(str::to_owned))
        .collect();

    let expected: Vec<&str> = vec![
        "app/api/route.ts",
        "app/layout.tsx",
        "app/page.tsx",
        "components/button.tsx",
        "components/card.tsx",
        "lib/db.test.ts",
        "lib/db.ts",
        "lib/utils.ts",
        "pages/_app.tsx",
        "pages/api/hello.ts",
    ];

    let normalised: Vec<String> = entries.iter().map(|f| f.replace('\\', "/")).collect();
    assert_eq!(
        normalised, expected,
        "fallow's entry set diverged from knip's documented entry-glob \
         semantics, including `{{ts,tsx}}` brace expansion. If knip recently \
         changed engines this is real drift; otherwise check fallow's globset \
         or the migrator's pattern copy."
    );

    cleanup(&dir);
}