fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
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
use std::path::{Path, PathBuf};

use fallow_config::{
    AnalysisSelection, CommandKind, ConfigFallback, ConfigKey, EnvSnapshot, PlannedAnalysis,
    RunInputs, SelectionInput, SkipReason, Surface,
};
use fallow_types::sourced::{Given, Origin, Source};

use super::resolve::{InputField, InputProblem, ResolveError, resolve_run};
use super::{AnalysisSlot, ResolvedRun};
use crate::project_config::ProductionModes;

const ORIGIN: Origin = Origin::Flag("--test");

const fn given<T>(value: T) -> Given<T> {
    Given {
        value,
        origin: ORIGIN,
    }
}

fn project(config: Option<&str>) -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dunce::canonicalize(dir.path()).expect("canonical root");
    std::fs::create_dir(root.join(".git")).expect("git marker");
    std::fs::write(root.join("package.json"), r#"{"name":"app"}"#).expect("package.json");
    if let Some(config) = config {
        std::fs::write(root.join(".fallowrc.json"), config).expect("config");
    }
    (dir, root)
}

fn combined(root: &Path) -> RunInputs {
    let mut inputs = RunInputs::new(
        Surface::Cli,
        EnvSnapshot::none().with_cwd(root.to_path_buf()),
        CommandKind::Combined,
        SelectionInput::Lists {
            only: Vec::new(),
            skip: Vec::new(),
            origin: ORIGIN,
        },
    );
    inputs.threads = Some(given(2));
    inputs
}

fn resolve(inputs: &RunInputs) -> ResolvedRun {
    resolve_run(inputs).expect("the run resolves")
}

const SPLIT_CONFIG: &str = r#"{
  "production": { "deadCode": true, "health": true, "dupes": false },
  "duplicates": { "enabled": true }
}"#;

#[test]
fn the_run_keeps_the_surface_the_command_and_the_root() {
    let (_dir, root) = project(None);
    let run = resolve(&combined(&root));
    assert_eq!(run.surface(), Surface::Cli);
    assert_eq!(run.command(), CommandKind::Combined);
    assert_eq!(run.root().value(), &root);
    assert_eq!(
        run.root().source(),
        &Source::Default {
            rule: "current-dir"
        }
    );
    assert_eq!(
        run.config_file().source(),
        &Source::Default { rule: "no-config" }
    );
}

#[test]
fn each_production_mode_gets_its_own_config() {
    let (_dir, root) = project(Some(SPLIT_CONFIG));
    let run = resolve(&combined(&root));
    assert_eq!(
        run.production_modes(),
        ProductionModes {
            dead_code: true,
            health: true,
            dupes: false,
        }
    );
    let runnable = |analysis| match run.analysis(analysis) {
        AnalysisSlot::Runs(runnable) => runnable,
        AnalysisSlot::Skipped { .. } => panic!("{analysis:?} runs"),
    };
    let dead_code = runnable(PlannedAnalysis::DeadCode);
    let dupes = runnable(PlannedAnalysis::Duplication);
    let health = runnable(PlannedAnalysis::Health);
    assert_eq!(dead_code.analysis(), PlannedAnalysis::DeadCode);
    assert!(dead_code.config().production);
    assert!(!dupes.config().production);
    assert!(dead_code.shares_files_with(health));
    assert!(!dead_code.shares_files_with(dupes));
    assert_eq!(
        run.config().production,
        fallow_config::ProductionConfig::PerAnalysis(fallow_config::PerAnalysisProductionConfig {
            dead_code: true,
            health: true,
            dupes: false,
            ignore: Vec::new(),
        }),
        "the run keeps the config before the production mode is flattened"
    );
    let session = dead_code.open_session();
    assert!(session.config().production);
    assert_eq!(
        session.config_path(),
        Some(root.join(".fallowrc.json").as_path())
    );
}

#[test]
fn a_skipped_analysis_has_its_config_key() {
    let (_dir, root) = project(Some(r#"{ "duplicates": { "enabled": false } }"#));
    let run = resolve(&combined(&root));
    let AnalysisSlot::Skipped { reason } = run.analysis(PlannedAnalysis::Duplication) else {
        panic!("duplication is off");
    };
    assert_eq!(
        reason.value(),
        &AnalysisSelection::Skipped(SkipReason::Config(ConfigKey::DuplicatesEnabled))
    );
    assert_eq!(
        reason.source(),
        &Source::ConfigFile {
            file: root.join(".fallowrc.json"),
            key: "duplicates.enabled",
        }
    );
}

#[test]
fn an_adjustment_of_a_decided_field_fails() {
    let (_dir, root) = project(None);
    let run = resolve(&combined(&root));
    let AnalysisSlot::Runs(runnable) = run.analysis(PlannedAnalysis::DeadCode) else {
        panic!("dead code runs");
    };
    let session = runnable
        .open_session_adjusted(|config| config.show_cascade = true)
        .expect("a rule setting can change");
    assert!(session.config().show_cascade);
    let err = runnable
        .open_session_adjusted(|config| config.production = !config.production)
        .expect_err("the production mode is decided");
    assert!(err.message().contains("`production`"), "{err}");
    let err = runnable
        .open_session_adjusted(|config| config.threads += 1)
        .expect_err("the thread count is decided");
    assert!(err.message().contains("`threads`"), "{err}");
}

#[test]
fn the_view_names_each_decision_and_no_env_value() {
    let (_dir, root) = project(Some(SPLIT_CONFIG));
    let env = EnvSnapshot::from_pairs(
        &[
            ("FALLOW_PRODUCTION_DUPES", "true"),
            ("FALLOW_CHANGED_SINCE", "secret-ref"),
        ],
        Some(&root),
    );
    let mut with_env = RunInputs::new(
        Surface::Cli,
        env,
        CommandKind::Combined,
        combined(&root).selection,
    );
    with_env.threads = Some(given(2));
    with_env.include_entry_exports = Some(given(true));
    let view = serde_json::to_value(resolve(&with_env).view()).expect("view serializes");
    assert_eq!(view["schema_version"], 1);
    assert_eq!(view["surface"], "cli");
    assert_eq!(view["command"], "combined");
    assert_eq!(
        view["analyses"]["duplication"]["production"]["source"],
        serde_json::json!({ "kind": "environment", "name": "FALLOW_PRODUCTION_DUPES" })
    );
    assert_eq!(
        view["analyses"]["dead_code"]["production"]["source"]["key"],
        "production.deadCode"
    );
    assert_eq!(view["settings"]["threads"]["value"], 2);
    assert_eq!(
        view["settings"]["include_entry_exports"]["source"],
        serde_json::json!({ "kind": "given", "origin": { "kind": "flag", "name": "--test" } })
    );
    assert_eq!(view["settings"]["allow_remote_extends"]["value"], false);
    assert_eq!(view["settings"]["package_baselines"]["value"], true);
    assert_eq!(
        view["env"],
        serde_json::json!({
            "read": ["FALLOW_PRODUCTION_DUPES"],
            "ignored": ["FALLOW_CHANGED_SINCE"],
        })
    );
    assert!(!view.to_string().contains("secret-ref"));
    assert_eq!(view["fell_back"], false);
}

#[test]
fn plugin_readiness_names_a_missing_plugin_file() {
    let (_dir, root) = project(Some(r#"{ "plugins": ["plugins/missing.json"] }"#));
    let mut inputs = combined(&root);
    inputs.config_fallback = ConfigFallback::Fail;
    let result = resolve_run(&inputs);
    let run = match result {
        Ok(run) => run,
        Err(ResolveError::ConfigInvalid { file, message }) => {
            panic!("{file:?}: {message}")
        }
        Err(err) => panic!("{err:?}"),
    };
    assert_eq!(run.plugin_readiness().len(), 1);
}

#[test]
fn input_errors_name_the_field() {
    let (_dir, root) = project(None);
    let mut inputs = combined(&root);
    inputs.threads = Some(given(0));
    assert!(matches!(
        resolve_run(&inputs),
        Err(ResolveError::Input {
            field: InputField::Threads,
            problem: InputProblem::Zero,
            ..
        })
    ));

    let inputs = RunInputs::new(
        Surface::Api,
        EnvSnapshot::none(),
        CommandKind::Combined,
        SelectionInput::Single(PlannedAnalysis::DeadCode),
    );
    assert!(matches!(
        resolve_run(&inputs),
        Err(ResolveError::Input {
            field: InputField::Root,
            problem: InputProblem::CwdUnavailable,
            ..
        })
    ));

    let mut inputs = combined(&root);
    inputs.root = Some(given(root.join("missing")));
    assert!(matches!(
        resolve_run(&inputs),
        Err(ResolveError::Input {
            field: InputField::Root,
            problem: InputProblem::Invalid,
            ..
        })
    ));

    let mut inputs = RunInputs::new(
        Surface::Api,
        EnvSnapshot::none(),
        CommandKind::Combined,
        SelectionInput::Single(PlannedAnalysis::DeadCode),
    );
    inputs.root = Some(given(root));
    inputs.config_path = Some(given(PathBuf::from("custom.json")));
    assert!(matches!(
        resolve_run(&inputs),
        Err(ResolveError::Input {
            field: InputField::ConfigPath,
            problem: InputProblem::CwdUnavailable,
            ..
        })
    ));
}

const MB: u64 = 1024 * 1024;

/// A combined CLI run of `root` with the variables of `pairs`.
fn combined_with_env(root: &Path, pairs: &[(&str, &str)]) -> RunInputs {
    let mut inputs = RunInputs::new(
        Surface::Cli,
        EnvSnapshot::from_pairs(pairs, Some(root)),
        CommandKind::Combined,
        combined(root).selection,
    );
    inputs.threads = Some(given(2));
    inputs
}

fn runnable(run: &ResolvedRun, analysis: PlannedAnalysis) -> super::Runnable<'_> {
    match run.analysis(analysis) {
        AnalysisSlot::Runs(runnable) => runnable,
        AnalysisSlot::Skipped { .. } => panic!("{analysis:?} runs"),
    }
}

/// The config that a dead-code session resolves for duplication, which runs
/// in another production mode.
fn own_duplication_config(run: &ResolvedRun) -> fallow_config::ResolvedConfig {
    let session = runnable(run, PlannedAnalysis::DeadCode).open_session();
    session
        .own_duplication_config()
        .expect("duplication has its own production mode")
        .clone()
}

#[test]
fn the_own_duplication_scope_keeps_the_given_settings() {
    let (_dir, root) = project(Some(SPLIT_CONFIG));
    let mut inputs = combined_with_env(&root, &[("FALLOW_MAX_FILE_SIZE", "5")]);
    inputs.max_file_size_mb = Some(given(1));
    inputs.cache_dir = Some(given(PathBuf::from("given-cache")));
    inputs.include_entry_exports = Some(given(true));
    let run = resolve(&inputs);
    let dupes = runnable(&run, PlannedAnalysis::Duplication);
    assert_eq!(dupes.config().max_file_size_bytes, Some(MB));
    let own = own_duplication_config(&run);
    assert!(!own.production);
    assert_eq!(own.max_file_size_bytes, Some(MB));
    assert_eq!(own.cache_dir, root.join("given-cache"));
    assert!(own.include_entry_exports);
    assert_eq!(own.cache_dir, dupes.config().cache_dir);
}

#[test]
fn the_own_duplication_scope_reads_the_environment() {
    let (_dir, root) = project(Some(SPLIT_CONFIG));
    let run = resolve(&combined_with_env(
        &root,
        &[
            ("FALLOW_MAX_FILE_SIZE", "5"),
            ("FALLOW_CACHE_MAX_SIZE", "33"),
        ],
    ));
    let own = own_duplication_config(&run);
    assert_eq!(own.max_file_size_bytes, Some(5 * MB));
    assert_eq!(own.cache_max_size_mb, Some(33));
}

/// A split production config with a package baseline.
const BASELINE_CONFIG: &str = r#"{
  "production": { "deadCode": true, "health": true, "dupes": false },
  "workspaces": { "changedSince": { "packages/web": "main" } }
}"#;

fn baselines(run: &ResolvedRun) -> Vec<String> {
    runnable(run, PlannedAnalysis::DeadCode)
        .config()
        .workspace_changed_since
        .keys()
        .cloned()
        .collect()
}

#[test]
fn a_given_package_baselines_wins_over_the_environment() {
    let web = vec!["packages/web".to_owned()];
    let (_dir, root) = project(Some(BASELINE_CONFIG));
    let off = [("FALLOW_PACKAGE_BASELINES", "off")];

    let run = resolve(&combined_with_env(&root, &off));
    assert!(!*run.settings().package_baselines.value());
    assert!(baselines(&run).is_empty(), "the variable clears the map");

    let mut inputs = combined_with_env(&root, &off);
    inputs.package_baselines = Some(given(true));
    let run = resolve(&inputs);
    assert!(*run.settings().package_baselines.value());
    assert_eq!(baselines(&run), web);
    assert_eq!(
        own_duplication_config(&run)
            .workspace_changed_since
            .keys()
            .cloned()
            .collect::<Vec<_>>(),
        web
    );

    let mut inputs = combined_with_env(&root, &[]);
    inputs.package_baselines = Some(given(false));
    let run = resolve(&inputs);
    assert!(baselines(&run).is_empty());
    assert!(
        own_duplication_config(&run)
            .workspace_changed_since
            .is_empty()
    );
}

#[test]
fn a_selection_error_does_not_fall_back() {
    let (_dir, root) = project(None);
    let mut inputs = combined(&root);
    inputs.config_fallback = ConfigFallback::DefaultsOnDiscoveredError;
    inputs.selection = SelectionInput::Lists {
        only: Vec::new(),
        skip: vec![
            PlannedAnalysis::DeadCode,
            PlannedAnalysis::Duplication,
            PlannedAnalysis::Health,
        ],
        origin: ORIGIN,
    };
    assert!(matches!(
        resolve_run(&inputs),
        Err(ResolveError::NothingSelected { .. })
    ));
}

#[test]
fn a_given_include_entry_exports_wins_over_a_workspace_false() {
    let (_dir, root) = project(Some(
        r#"{ "workspaces": { "settings": { "packages/a": { "includeEntryExports": false } } } }"#,
    ));
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"app","workspaces":["packages/*"]}"#,
    )
    .expect("root manifest");
    std::fs::create_dir_all(root.join("packages/a")).expect("workspace dir");
    std::fs::write(root.join("packages/a/package.json"), r#"{"name":"a"}"#)
        .expect("workspace manifest");
    let file = root.join("packages/a/index.ts");
    let include_for = |given_include: Option<bool>| {
        let mut inputs = combined(&root);
        inputs.include_entry_exports = given_include.map(given);
        let run = resolve(&inputs);
        let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
            panic!("dead code runs");
        };
        let config = dead_code.config();
        config
            .workspace_settings
            .bind(&root, dead_code.workspaces());
        config.include_entry_exports_for(&file)
    };
    assert!(!include_for(None));
    assert!(include_for(Some(true)));
}

/// The workspace discovery of the resolver matches the ignore globs. An
/// adjustment that writes only rule settings still opens a session after it.
#[test]
fn a_rule_adjustment_opens_a_session_after_the_workspace_discovery() {
    let (_dir, root) = project(Some(r#"{ "ignorePatterns": ["gen/**"] }"#));
    std::fs::write(
        root.join("package.json"),
        r#"{"name":"app","workspaces":["packages/*"]}"#,
    )
    .expect("root manifest");
    std::fs::create_dir_all(root.join("packages/empty")).expect("workspace dir");
    let run = resolve(&combined(&root));
    let AnalysisSlot::Runs(dead_code) = run.analysis(PlannedAnalysis::DeadCode) else {
        panic!("dead code runs");
    };
    assert!(
        dead_code
            .open_session_adjusted(|config| config.show_cascade = true)
            .is_ok()
    );
    assert!(
        dead_code
            .open_session_adjusted(
                |config| config.ignore_patterns = fallow_config::IgnorePatternSet::empty()
            )
            .is_err()
    );
}

/// The run resolves with a type-aware value that it cannot use, and returns
/// the error only to a reader of the type-aware settings. The language server
/// reads no type-aware variable.
#[test]
fn an_unknown_type_aware_value_fails_only_the_type_aware_reader() {
    let (_dir, root) = project(Some(r#"{ "typeAware": { "enabled": true } }"#));
    let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", "maybe")], Some(&root));
    let inputs = RunInputs::new(
        Surface::Cli,
        env.clone(),
        CommandKind::Dupes,
        SelectionInput::Single(PlannedAnalysis::Duplication),
    );
    let run = resolve(&inputs);
    assert!(matches!(
        run.type_aware(),
        Err(ResolveError::Input {
            field: InputField::Env(fallow_config::EnvVar::TypeAware),
            problem: InputProblem::InvalidValue,
            ..
        })
    ));
    let lsp = RunInputs::new(
        Surface::Lsp,
        env,
        CommandKind::Editor,
        SelectionInput::Single(PlannedAnalysis::DeadCode),
    );
    let settings = resolve(&lsp).type_aware().cloned().expect("settings");
    assert!(settings.enabled.value());
    assert!(matches!(
        settings.enabled.source(),
        Source::ConfigFile {
            key: "typeAware.enabled",
            ..
        }
    ));
}