fallow-core 3.31.0

Internal detector backend for fallow-engine and fallow-api
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! Package-manager and task-runner forms that run a command in another
//! location, the npm config flags that take a value, and script names that
//! shadow a binary.

#![expect(
    clippy::disallowed_types,
    reason = "ScriptCatalog takes the serde-deserialized std HashMap"
)]

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use rustc_hash::{FxHashMap, FxHashSet};

use super::{
    IgnoredCommandEntries, NPM_DEPENDENCY_VALUE_FLAGS, NPM_LOCATION_VALUE_FLAGS,
    NPM_OUTPUT_VALUE_FLAGS, NPM_PUBLISH_VALUE_FLAGS, NPM_REGISTRY_VALUE_FLAGS,
    NPM_RUNTIME_VALUE_FLAGS, ScriptAnalysis, ScriptCatalog, WorkspacePackages,
    analyze_commands_with_context,
};

fn scripts_map(scripts: &[(&str, &str)]) -> HashMap<String, String> {
    scripts
        .iter()
        .map(|(name, body)| ((*name).to_string(), (*body).to_string()))
        .collect()
}

fn analyze_with_catalog(
    command: &str,
    catalog: &ScriptCatalog,
    declared: &[&str],
) -> ScriptAnalysis {
    let declared: FxHashSet<String> = declared.iter().map(|name| (*name).to_string()).collect();
    analyze_commands_with_context(
        &[command.to_string()],
        Path::new("/nonexistent"),
        &FxHashMap::default(),
        &declared,
        catalog,
        IgnoredCommandEntries::NONE,
    )
}

fn analyze(command: &str, scripts: &[(&str, &str)], declared: &[&str]) -> ScriptAnalysis {
    analyze_with_catalog(
        command,
        &ScriptCatalog::from_scripts(&scripts_map(scripts)),
        declared,
    )
}

#[test]
fn a_linter_in_other_workspace_packages_is_credited_without_entries() {
    for command in [
        "yarn workspace web eslint src/dead.ts",
        "yarn workspace web run eslint src/dead.ts",
        "yarn workspace web exec eslint src/dead.ts",
        "yarn workspaces foreach -A exec eslint src/dead.ts",
        "yarn workspaces foreach --all --parallel -j 4 run eslint src/dead.ts",
        "yarn workspaces run eslint src/dead.ts",
        "yarn workspaces run -s eslint src/dead.ts",
        "pnpm --filter web eslint src/dead.ts",
        "pnpm -F web eslint src/dead.ts",
        "pnpm --filter=web eslint src/dead.ts",
        "pnpm -r eslint src/dead.ts",
        "pnpm --recursive --parallel eslint src/dead.ts",
        "npm exec -w web -- eslint src/dead.ts",
        "npm --workspaces exec -- eslint src/dead.ts",
    ] {
        let result = analyze(command, &[], &["eslint"]);
        assert!(
            result.used_packages.contains("eslint"),
            "`{command}` did not credit eslint: {:?}",
            result.used_packages
        );
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries: {:?}",
            result.entry_files
        );
    }
}

#[test]
fn a_runner_in_other_workspace_packages_makes_no_entry_here() {
    for command in [
        "yarn workspace web tsx scripts/run.ts",
        "yarn workspaces foreach -A exec tsx scripts/run.ts",
        "pnpm --filter web tsx scripts/run.ts",
        "pnpm --filter web exec tsx scripts/run.ts",
        "pnpm -r exec tsx scripts/run.ts",
        "npm exec --workspace=web -- tsx scripts/run.ts",
        "varlock run -- pnpm -r exec tsx scripts/run.ts",
    ] {
        let result = analyze(command, &[], &["tsx", "varlock"]);
        assert!(
            result.used_packages.contains("tsx"),
            "`{command}` did not credit tsx: {:?}",
            result.used_packages
        );
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries relative to the calling package: {:?}",
            result.entry_files
        );
    }
}

#[test]
fn a_runner_in_another_directory_resolves_its_file_there() {
    for command in [
        "pnpm -C packages/web exec tsx scripts/run.ts",
        "pnpm --dir=packages/web exec tsx ./scripts/run.ts",
        "npm --prefix packages/web exec -- tsx scripts/run.ts",
        "yarn --cwd packages/web tsx scripts/run.ts",
    ] {
        let result = analyze(command, &[], &["tsx"]);
        assert_eq!(
            result.entry_files,
            vec!["packages/web/scripts/run.ts"],
            "`{command}`"
        );
    }
}

#[test]
fn a_script_call_in_other_workspace_packages_makes_no_entry_here() {
    let scripts = [("gen", "node scripts/gen.js"), ("lint", "eslint")];
    for command in [
        "pnpm -r run gen -- src/a.ts",
        "pnpm -r gen src/a.ts",
        "pnpm --recursive run lint -- src/a.ts",
        "pnpm --filter web run gen src/a.ts",
        "pnpm run --filter web gen src/a.ts",
        "pnpm -C packages/web run gen src/a.ts",
        "npm -w web run gen -- src/a.ts",
        "npm --workspace=web run gen -- src/a.ts",
        "npm --workspaces run gen -- src/a.ts",
        "npm --prefix packages/web run gen -- src/a.ts",
        "yarn workspace web gen src/a.ts",
        "yarn workspace web run gen src/a.ts",
        "yarn workspaces foreach -A run gen src/a.ts",
        "yarn workspaces foreach --include 'web*' gen src/a.ts",
        "yarn workspaces run gen src/a.ts",
        "yarn -s workspaces run lint src/a.ts",
        "yarn workspaces run -s gen src/a.ts",
    ] {
        let result = analyze(command, &scripts, &[]);
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries relative to the calling package: {:?}",
            result.entry_files
        );
    }
}

#[test]
fn a_task_runner_forwards_no_entry() {
    for command in [
        "turbo run lint -- src/dead.ts",
        "turbo lint -- src/dead.ts",
        "npx turbo run lint --filter=web -- src/dead.ts",
        "nx run-many -t lint -- src/dead.ts",
        "lerna run lint -- src/dead.ts",
        "lerna exec -- node scripts/run.ts",
    ] {
        let result = analyze(command, &[], &["turbo", "nx", "lerna"]);
        assert!(
            result.entry_files.is_empty() && result.config_files.is_empty(),
            "`{command}` produced entries: {:?} {:?}",
            result.entry_files,
            result.config_files
        );
    }
    let result = analyze("turbo run lint -- src/dead.ts", &[], &["turbo"]);
    assert!(result.used_packages.contains("turbo"));
}

/// Call `gen` with `flag value` before a forwarded file and check that npm
/// consumes the value: only the forwarded file becomes an entry. A flag that
/// selects a workspace or a directory runs the script in another location,
/// so no file becomes an entry of the calling package.
fn assert_npm_consumes_values(group: &[&str]) {
    let scripts = [("gen", "node scripts/gen.js")];
    for flag in group {
        for command in [
            format!("npm run gen {flag} cfg/value.ts src/a.ts"),
            format!("npm run {flag} cfg/value.ts gen src/a.ts"),
        ] {
            let result = analyze(&command, &scripts, &[]);
            let expected: &[&str] = if matches!(*flag, "-w" | "--workspace" | "-C" | "--prefix") {
                &[]
            } else {
                &["scripts/gen.js", "src/a.ts"]
            };
            assert_eq!(result.entry_files, expected, "`{command}`");
        }
    }
}

#[test]
fn npm_location_flags_take_a_value() {
    assert_npm_consumes_values(NPM_LOCATION_VALUE_FLAGS);
}

#[test]
fn npm_registry_flags_take_a_value() {
    assert_npm_consumes_values(NPM_REGISTRY_VALUE_FLAGS);
}

#[test]
fn npm_dependency_flags_take_a_value() {
    assert_npm_consumes_values(NPM_DEPENDENCY_VALUE_FLAGS);
}

#[test]
fn npm_runtime_flags_take_a_value() {
    assert_npm_consumes_values(NPM_RUNTIME_VALUE_FLAGS);
}

#[test]
fn npm_output_flags_take_a_value() {
    assert_npm_consumes_values(NPM_OUTPUT_VALUE_FLAGS);
}

#[test]
fn npm_publish_flags_take_a_value() {
    assert_npm_consumes_values(NPM_PUBLISH_VALUE_FLAGS);
}

#[test]
fn npm_flags_named_in_the_issue_take_a_value() {
    let scripts = [("gen", "node scripts/gen.js")];
    for flag in [
        "--tag",
        "--scope",
        "--otp",
        "--before",
        "--node-options",
        "--include",
        "--omit",
        "--registry",
        "--userconfig",
    ] {
        let command = format!("npm run gen {flag} cfg/value.ts src/a.ts");
        let result = analyze(&command, &scripts, &[]);
        assert_eq!(
            result.entry_files,
            vec!["scripts/gen.js", "src/a.ts"],
            "`{command}`"
        );
    }
}

#[test]
fn a_declared_script_named_after_a_linter_keeps_its_targets() {
    let scripts = [("eslint", "node tools/check.js")];
    for command in [
        "yarn eslint src/a.ts",
        "yarn run eslint src/a.ts",
        "yarn run -s eslint src/a.ts",
        "pnpm eslint src/a.ts",
        "varlock run -- yarn eslint src/a.ts",
    ] {
        let result = analyze(command, &scripts, &["eslint", "varlock"]);
        assert!(
            result.entry_files.iter().any(|path| path == "src/a.ts"),
            "`{command}` lost the target of the declared `eslint` script: {:?}",
            result.entry_files
        );
    }
}

#[test]
fn a_wrapped_call_of_a_linter_script_makes_no_entry() {
    let scripts = [("lint", "eslint")];
    for command in [
        "varlock run -- yarn lint src/dead.ts",
        "varlock run -- pnpm lint src/dead.ts",
        "varlock run -- npm run lint -- src/dead.ts",
    ] {
        let result = analyze(command, &scripts, &["eslint", "varlock"]);
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries: {:?}",
            result.entry_files
        );
    }
}

/// Two workspace packages: `web` in `packages/web` and `@acme/api` in
/// `packages/api`. `web` declares a `gen` script that runs `tsx` and a
/// `lint` script that runs `eslint`. `@acme/api` declares only `gen`.
fn workspace_packages() -> Arc<WorkspacePackages> {
    let mut packages = WorkspacePackages::default();
    packages.add(
        "web",
        "packages/web",
        Some(&scripts_map(&[("gen", "tsx"), ("lint", "eslint")])),
    );
    packages.add(
        "@acme/api",
        "packages/api",
        Some(&scripts_map(&[("gen", "tsx")])),
    );
    Arc::new(packages)
}

/// Analyze `command` as a script of the package in `package_dir`, with the
/// workspace packages of [`workspace_packages`]. The calling package
/// declares neither `gen` nor `lint`.
fn analyze_in_workspace(command: &str, package_dir: &str) -> ScriptAnalysis {
    let catalog = ScriptCatalog::from_scripts(&scripts_map(&[("check", "node tools/check.js")]))
        .with_workspaces(workspace_packages(), package_dir);
    analyze_with_catalog(command, &catalog, &["tsx", "eslint", "varlock"])
}

#[test]
fn a_runner_in_a_named_workspace_package_resolves_its_file_there() {
    for command in [
        "pnpm --filter web exec tsx scripts/a.ts",
        "pnpm -F web exec tsx scripts/a.ts",
        "pnpm --filter=web exec tsx ./scripts/a.ts",
        "pnpm --filter web tsx scripts/a.ts",
        "pnpm --filter ./packages/web exec tsx scripts/a.ts",
        "pnpm --filter {packages/web} exec tsx scripts/a.ts",
        "yarn workspace web tsx scripts/a.ts",
        "yarn workspace web exec tsx scripts/a.ts",
        "yarn workspace web node scripts/a.ts",
        "npm exec -w web -- tsx scripts/a.ts",
        "npm exec --workspace=packages/web -- tsx scripts/a.ts",
        "npm -w web exec -- node scripts/a.ts",
        "varlock run -- yarn workspace web node scripts/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert_eq!(
            result.entry_files,
            vec!["packages/web/scripts/a.ts"],
            "`{command}`"
        );
    }
}

#[test]
fn a_script_call_in_a_named_workspace_package_resolves_its_file_there() {
    for command in [
        "npm run -w web gen -- scripts/a.ts",
        "npm -w web run gen -- scripts/a.ts",
        "npm run gen --workspace=web -- scripts/a.ts",
        "pnpm --filter web run gen scripts/a.ts",
        "pnpm --filter web gen scripts/a.ts",
        "yarn workspace web gen scripts/a.ts",
        "yarn workspace web run gen scripts/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert_eq!(
            result.entry_files,
            vec!["packages/web/scripts/a.ts"],
            "`{command}`"
        );
        assert!(
            result.used_packages.contains("tsx"),
            "`{command}` did not credit tsx: {:?}",
            result.used_packages
        );
    }
}

#[test]
fn a_glob_filter_resolves_the_file_in_each_selected_package() {
    for command in [
        "pnpm --filter './packages/*' exec tsx scripts/a.ts",
        "pnpm --filter web --filter @acme/api exec tsx scripts/a.ts",
        "pnpm --filter '*' run gen scripts/a.ts",
    ] {
        let mut entries = analyze_in_workspace(command, "").entry_files;
        entries.sort();
        assert_eq!(
            entries,
            vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
            "`{command}`"
        );
    }
    let result = analyze_in_workspace("pnpm --filter '@acme/*' exec tsx scripts/a.ts", "");
    assert_eq!(result.entry_files, vec!["packages/api/scripts/a.ts"]);
}

#[test]
fn a_named_workspace_selection_resolves_from_another_package() {
    let result = analyze_in_workspace("yarn workspace web node scripts/a.ts", "packages/api");
    assert_eq!(result.entry_files, vec!["../web/scripts/a.ts"]);
}

#[test]
fn a_linter_in_a_named_workspace_package_makes_no_entry() {
    for command in [
        "yarn workspace web eslint src/a.ts",
        "pnpm --filter web exec eslint src/a.ts",
        "npm exec -w web -- eslint src/a.ts",
        "npm run -w web lint -- src/a.ts",
        "yarn workspace web lint src/a.ts",
        "pnpm --filter './packages/*' run lint src/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries: {:?}",
            result.entry_files
        );
        assert!(
            result.used_packages.contains("eslint"),
            "`{command}` did not credit eslint: {:?}",
            result.used_packages
        );
    }
}

#[test]
fn an_unknown_or_unsupported_selection_makes_no_entry() {
    for command in [
        "yarn workspace docs node scripts/a.ts",
        "pnpm --filter docs exec tsx scripts/a.ts",
        "pnpm --filter 'web...' exec tsx scripts/a.ts",
        "pnpm --filter '[origin/main]' exec tsx scripts/a.ts",
        "npm run -w docs gen -- scripts/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries: {:?}",
            result.entry_files
        );
    }
}

#[test]
fn yarn_node_runs_its_file() {
    for (command, expected) in [
        ("yarn node scripts/a.ts", "scripts/a.ts"),
        ("yarn node --inspect scripts/a.ts", "scripts/a.ts"),
        (
            "yarn --cwd packages/web node scripts/a.ts",
            "packages/web/scripts/a.ts",
        ),
        (
            "yarn --cwd=packages/web node ./scripts/a.ts",
            "packages/web/scripts/a.ts",
        ),
    ] {
        let result = analyze(command, &[], &[]);
        assert_eq!(result.entry_files, vec![expected], "`{command}`");
    }
}

fn sorted_entries(command: &str, package_dir: &str) -> Vec<String> {
    let mut entries = analyze_in_workspace(command, package_dir).entry_files;
    entries.sort();
    entries
}

#[test]
fn a_runner_in_every_workspace_package_resolves_its_file_in_each_package() {
    for command in [
        "pnpm -r exec tsx scripts/a.ts",
        "pnpm --recursive --parallel exec tsx scripts/a.ts",
        "pnpm -r tsx scripts/a.ts",
        "varlock run -- pnpm -r exec tsx scripts/a.ts",
        "yarn workspaces foreach -A exec tsx scripts/a.ts",
        "yarn workspaces foreach --all --parallel node scripts/a.ts",
        "npm --workspaces exec -- tsx scripts/a.ts",
        "npm exec -ws -- tsx scripts/a.ts",
    ] {
        assert_eq!(
            sorted_entries(command, ""),
            vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
            "`{command}`"
        );
    }
}

#[test]
fn every_workspace_package_resolves_from_a_workspace_package() {
    assert_eq!(
        sorted_entries("pnpm -r exec tsx scripts/a.ts", "packages/api"),
        vec!["../web/scripts/a.ts", "scripts/a.ts"]
    );
    // npm sets the calling package as the default workspace.
    assert_eq!(
        sorted_entries("npm --workspaces exec -- tsx scripts/a.ts", "packages/api"),
        vec!["scripts/a.ts"]
    );
    // npm resolves a workspace path against the calling package.
    assert_eq!(
        sorted_entries("npm exec -w ../web -- tsx scripts/a.ts", "packages/api"),
        vec!["../web/scripts/a.ts"]
    );
    assert!(
        sorted_entries(
            "npm exec -w packages/web -- tsx scripts/a.ts",
            "packages/api"
        )
        .is_empty()
    );
}

#[test]
fn excluding_and_including_selections_narrow_every_package() {
    for (command, expected) in [
        (
            "pnpm --filter '!web' exec tsx scripts/a.ts",
            "packages/api/scripts/a.ts",
        ),
        (
            "pnpm -r --filter '!web' exec tsx scripts/a.ts",
            "packages/api/scripts/a.ts",
        ),
        (
            "pnpm -r --filter web exec tsx scripts/a.ts",
            "packages/web/scripts/a.ts",
        ),
        (
            "yarn workspaces foreach -A --include web exec tsx scripts/a.ts",
            "packages/web/scripts/a.ts",
        ),
        (
            "yarn workspaces foreach -A --exclude web exec tsx scripts/a.ts",
            "packages/api/scripts/a.ts",
        ),
    ] {
        assert_eq!(sorted_entries(command, ""), vec![expected], "`{command}`");
    }
    for command in [
        "yarn workspaces foreach -R exec tsx scripts/a.ts",
        "yarn workspaces foreach --since exec tsx scripts/a.ts",
        "yarn workspaces foreach -A --from web exec tsx scripts/a.ts",
        "yarn workspaces foreach -W exec tsx scripts/a.ts",
    ] {
        assert!(sorted_entries(command, "").is_empty(), "`{command}`");
    }
}

#[test]
fn a_script_call_in_every_workspace_package_resolves_its_file_in_each_package() {
    for command in [
        "pnpm -r run gen -- scripts/a.ts",
        "pnpm -r gen scripts/a.ts",
        "npm --workspaces run gen -- scripts/a.ts",
        "npm run gen -ws -- scripts/a.ts",
        "yarn workspaces foreach -A run gen scripts/a.ts",
        "yarn workspaces run gen scripts/a.ts",
        "yarn workspaces run -s gen scripts/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        let mut entries = result.entry_files.clone();
        entries.sort();
        assert_eq!(
            entries,
            vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
            "`{command}`"
        );
        assert!(
            result.used_packages.contains("tsx"),
            "`{command}` did not credit tsx: {:?}",
            result.used_packages
        );
    }
}

#[test]
fn a_linter_in_every_workspace_package_makes_no_entry() {
    for command in [
        "pnpm -r exec eslint src/a.ts",
        "pnpm -r run lint -- src/a.ts",
        "yarn workspaces foreach -A run lint src/a.ts",
        "yarn workspaces run lint src/a.ts",
        "npm --workspaces run lint -- src/a.ts",
        "pnpm -C packages/web run lint src/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert!(
            result.entry_files.is_empty(),
            "`{command}` produced entries: {:?}",
            result.entry_files
        );
        assert!(
            result.used_packages.contains("eslint"),
            "`{command}` did not credit eslint: {:?}",
            result.used_packages
        );
    }
}

#[test]
fn a_script_call_in_a_package_directory_resolves_its_file_there() {
    for command in [
        "pnpm -C packages/web run gen scripts/a.ts",
        "pnpm --dir=packages/web gen scripts/a.ts",
        "npm --prefix packages/web run gen -- scripts/a.ts",
        "npm run gen --prefix packages/web -- scripts/a.ts",
        "yarn --cwd packages/web gen scripts/a.ts",
        "yarn --cwd=packages/web run gen ./scripts/a.ts",
    ] {
        let result = analyze_in_workspace(command, "");
        assert_eq!(
            result.entry_files,
            vec!["packages/web/scripts/a.ts"],
            "`{command}`"
        );
        assert!(
            result.used_packages.contains("tsx"),
            "`{command}` did not credit tsx: {:?}",
            result.used_packages
        );
    }
    assert_eq!(
        sorted_entries("pnpm -C ../web run gen scripts/a.ts", "packages/api"),
        vec!["../web/scripts/a.ts"]
    );
    // A directory that holds no workspace package forwards nothing.
    assert!(sorted_entries("pnpm -C docs run gen scripts/a.ts", "").is_empty());
}

/// The packages of [`workspace_packages`] plus the root package `monorepo`,
/// which declares a `gen` script that runs `tsx`.
fn analyze_with_root(command: &str, package_dir: &str) -> Vec<String> {
    let mut packages = WorkspacePackages::default();
    packages.add_root("monorepo", Some(&scripts_map(&[("gen", "tsx")])));
    packages.add(
        "web",
        "packages/web",
        Some(&scripts_map(&[("gen", "tsx"), ("lint", "eslint")])),
    );
    packages.add(
        "@acme/api",
        "packages/api",
        Some(&scripts_map(&[("gen", "tsx")])),
    );
    let catalog = ScriptCatalog::from_scripts(&scripts_map(&[("check", "node tools/check.js")]))
        .with_workspaces(Arc::new(packages), package_dir);
    let mut entries = analyze_with_catalog(command, &catalog, &["tsx", "eslint"]).entry_files;
    entries.sort();
    entries
}

#[test]
fn yarn_foreach_all_runs_in_the_root_workspace_too() {
    for command in [
        "yarn workspaces foreach -A exec tsx scripts/a.ts",
        "yarn workspaces foreach --all node scripts/a.ts",
        "yarn workspaces foreach -A run gen scripts/a.ts",
    ] {
        assert_eq!(
            analyze_with_root(command, ""),
            vec![
                "packages/api/scripts/a.ts",
                "packages/web/scripts/a.ts",
                "scripts/a.ts"
            ],
            "`{command}`"
        );
    }
    assert_eq!(
        analyze_with_root(
            "yarn workspaces foreach -A exec tsx scripts/a.ts",
            "packages/web"
        ),
        vec!["../../scripts/a.ts", "../api/scripts/a.ts", "scripts/a.ts"]
    );
    assert_eq!(
        analyze_with_root(
            "yarn workspaces foreach -A --exclude . exec tsx scripts/a.ts",
            ""
        ),
        vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
        "yarn matches `--exclude` against the workspace directory"
    );
    assert_eq!(
        analyze_with_root(
            "yarn workspaces foreach -A --include 'packages/*' exec tsx scripts/a.ts",
            ""
        ),
        vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"]
    );
}

#[test]
fn only_the_forms_that_select_the_root_package_run_there() {
    for command in [
        "pnpm -r exec tsx scripts/a.ts",
        "npm --workspaces exec -- tsx scripts/a.ts",
        "yarn workspaces run gen scripts/a.ts",
    ] {
        assert_eq!(
            analyze_with_root(command, ""),
            vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"],
            "`{command}` leaves out the root package"
        );
    }
    assert_eq!(
        analyze_with_root("pnpm -r --include-workspace-root exec tsx scripts/a.ts", ""),
        vec![
            "packages/api/scripts/a.ts",
            "packages/web/scripts/a.ts",
            "scripts/a.ts"
        ]
    );
    assert_eq!(
        analyze_with_root("pnpm -w exec tsx scripts/a.ts", "packages/web"),
        vec!["../../scripts/a.ts"]
    );
    assert_eq!(
        analyze_with_root("pnpm --workspace-root run gen scripts/a.ts", "packages/web"),
        vec!["../../scripts/a.ts"]
    );
    assert_eq!(
        analyze_with_root("yarn workspace monorepo gen scripts/a.ts", "packages/web"),
        vec!["../../scripts/a.ts"]
    );
}

#[test]
fn pnpm_include_workspace_root_adds_the_root_to_an_excluding_filter() {
    for command in [
        "pnpm --filter '!web' --include-workspace-root exec tsx scripts/a.ts",
        "pnpm --include-workspace-root --filter '!web' exec tsx scripts/a.ts",
        "pnpm --filter '!web' --include-workspace-root run gen scripts/a.ts",
    ] {
        assert_eq!(
            analyze_with_root(command, ""),
            vec!["packages/api/scripts/a.ts", "scripts/a.ts"],
            "`{command}`"
        );
    }
    assert_eq!(
        analyze_with_root(
            "pnpm --filter web --include-workspace-root exec tsx scripts/a.ts",
            ""
        ),
        vec!["packages/web/scripts/a.ts"],
        "an including filter keeps the root out"
    );
}

#[test]
fn npm_include_workspace_root_adds_the_root_to_a_workspace_selection() {
    for command in [
        "npm exec -ws --include-workspace-root -- tsx scripts/a.ts",
        "npm -ws -iwr exec -- tsx scripts/a.ts",
        "npm --include-workspace-root=true --workspaces exec -- tsx scripts/a.ts",
        "npm run gen --workspaces --include-workspace-root -- scripts/a.ts",
        "npm -iwr run gen -ws -- scripts/a.ts",
    ] {
        assert_eq!(
            analyze_with_root(command, ""),
            vec![
                "packages/api/scripts/a.ts",
                "packages/web/scripts/a.ts",
                "scripts/a.ts"
            ],
            "`{command}`"
        );
    }
    assert_eq!(
        analyze_with_root(
            "npm -w web --include-workspace-root exec -- tsx scripts/a.ts",
            ""
        ),
        vec!["packages/web/scripts/a.ts", "scripts/a.ts"]
    );
    assert_eq!(
        analyze_with_root(
            "npm -ws --include-workspace-root exec -- tsx scripts/a.ts",
            "packages/api"
        ),
        vec!["../../scripts/a.ts", "scripts/a.ts"],
        "`--workspaces` in a workspace package selects that package and the root"
    );
    assert_eq!(
        analyze_with_root(
            "npm -ws --include-workspace-root=false exec -- tsx scripts/a.ts",
            ""
        ),
        vec!["packages/api/scripts/a.ts", "packages/web/scripts/a.ts"]
    );
    assert_eq!(
        analyze_with_root("npm -iwr exec -- tsx scripts/a.ts", "packages/web"),
        vec!["scripts/a.ts"],
        "the flag without a workspace selection runs in the calling package"
    );
}