Skip to main content

fallow_engine/
change_scope.rs

1//! The Git change scope of one analysis run.
2//!
3//! A run narrows its findings by at most one change scope: the changed files
4//! of one global ref, or the per-workspace refs of `workspaces.changedSince`.
5//! Every surface describes its inputs with a [`ChangeScopeRequest`] and calls
6//! [`ChangeScope::resolve`], which owns the precedence rule and the failure
7//! policy. The resolved value owns the four things that must agree: the
8//! result filter, the `package_baselines` provenance rows, the
9//! `package-baselines` request outcome, and the scope flag that baseline
10//! comparison and finding-id queries read. A surface therefore cannot apply
11//! the filter and forget the flag, or read the package map where the caller
12//! owns the scope.
13//!
14//! The failure policy follows `--changed-since`. A malformed key or ref is
15//! invalid input, and resolution fails. A map that cannot apply as written
16//! stands down as a whole: a key that names no workspace of this project (for
17//! example in a run from a package subdirectory), or a well-formed ref that
18//! Git cannot resolve (for example in a shallow CI clone). The run then
19//! reports in full scope and publishes a `not-applied` request outcome that
20//! says so. The report is wider than asked, never narrower.
21//!
22//! The filter applies to the final result of the run. A surface that narrows
23//! findings before type-aware refinement, to reduce sidecar work, applies the
24//! same scope again after refinement, because refinement can add findings.
25
26use std::path::{Path, PathBuf};
27use std::sync::OnceLock;
28
29use fallow_config::{ResolvedConfig, WorkspaceInfo};
30use fallow_output::{PackageBaselineStatus, RequestName, RequestOutcome};
31use fallow_types::duplicates::DuplicationReport;
32use fallow_types::results::AnalysisResults;
33use rustc_hash::FxHashSet;
34
35use crate::changed_files::{ChangedFilesError, NormalizedChangedFiles};
36use crate::package_baselines::{PackageBaselineError, PackageChangeScope};
37
38/// The `requested` value of the `package-baselines` request outcome.
39const PACKAGE_BASELINES_REQUEST: &str = "workspaces.changedSince";
40
41/// Who owns the change scope of a run.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum ChangeScopeOwner {
44    /// The run owns it: a global ref when one is requested, otherwise the
45    /// configured package baselines.
46    #[default]
47    Run,
48    /// The calling pipeline narrows the findings itself. `audit` is the
49    /// example: it compares a head run and a base run against its own changed
50    /// files. The run reads no package baselines, so it never resolves Git
51    /// refs in a base snapshot and never hides a finding that the comparison
52    /// needs.
53    Caller,
54    /// Like [`ChangeScopeOwner::Caller`], but the change scope keeps every
55    /// unused file and unused export. `audit --gate new-only` compares them
56    /// with the base, because a change can make code unused outside the
57    /// changed files.
58    CallerKeepingUnusedCode,
59}
60
61/// The change-scope inputs of one run.
62#[derive(Debug, Clone, Copy, Default)]
63pub struct ChangeScopeRequest<'a> {
64    /// Who owns the scope.
65    pub owner: ChangeScopeOwner,
66    /// A global changed-since ref was requested. This is `true` also when the
67    /// ref did not resolve: the run then reports in full scope, and the
68    /// package baselines still do not apply.
69    pub global_ref: bool,
70    /// The changed files of the global ref, or a changed-file set that the
71    /// caller supplied.
72    pub files: Option<&'a FxHashSet<PathBuf>>,
73    /// The run-wide memo of the resolved package map. The analyses of one run
74    /// share it, so Git resolves each mapped ref once per run. `None`
75    /// resolves the map without a memo.
76    pub cache: Option<&'a PackageBaselineCache>,
77    /// `--no-package-baselines`: this run ignores `workspaces.changedSince`
78    /// and reports every package in full scope, for example to save or gate a
79    /// whole-project baseline.
80    pub no_package_baselines: bool,
81}
82
83impl ChangeScopeRequest<'_> {
84    /// Whether [`ChangeScope::resolve`] reads `workspaces.changedSince` for
85    /// this request. A surface that discovers workspaces only for the package
86    /// map checks this first.
87    #[must_use]
88    pub fn reads_package_baselines(&self, config: &ResolvedConfig) -> bool {
89        self.owner == ChangeScopeOwner::Run
90            && !self.no_package_baselines
91            && !self.global_ref
92            && self.files.is_none()
93            && !config.workspace_changed_since.is_empty()
94    }
95}
96
97/// The package map of one run, resolved once.
98#[derive(Debug, Clone)]
99struct ResolvedPackages {
100    packages: Option<PackageChangeScope>,
101    outcome: RequestOutcome,
102}
103
104/// The run-wide memo of the resolved package map.
105///
106/// Every analysis of one run resolves the same map against the same
107/// workspaces, so each surface keeps one memo per run: a process-wide value on
108/// the CLI, a field of the programmatic call context, and one value per
109/// project and run in the editor. The first resolution wins. A config error is
110/// kept too, so every analysis of the run fails the same way.
111#[derive(Debug, Default)]
112pub struct PackageBaselineCache(OnceLock<Result<ResolvedPackages, PackageBaselineError>>);
113
114impl PackageBaselineCache {
115    /// An empty memo.
116    #[must_use]
117    pub const fn new() -> Self {
118        Self(OnceLock::new())
119    }
120
121    /// Whether an analysis of the run already resolved the map.
122    #[must_use]
123    pub fn is_resolved(&self) -> bool {
124        self.0.get().is_some()
125    }
126
127    /// The `package-baselines` request outcome of the run, once a run
128    /// resolved the map. `None` when no analysis read the map.
129    #[must_use]
130    pub fn request_outcome(&self) -> Option<RequestOutcome> {
131        match self.0.get()? {
132            Ok(resolved) => Some(resolved.outcome.clone()),
133            Err(_) => None,
134        }
135    }
136
137    fn resolve(
138        &self,
139        config: &ResolvedConfig,
140        workspaces: &[WorkspaceInfo],
141    ) -> Result<ResolvedPackages, PackageBaselineError> {
142        self.0
143            .get_or_init(|| resolve_packages(config, workspaces))
144            .clone()
145    }
146}
147
148fn resolve_packages(
149    config: &ResolvedConfig,
150    workspaces: &[WorkspaceInfo],
151) -> Result<ResolvedPackages, PackageBaselineError> {
152    match PackageChangeScope::resolve(&config.root, &config.workspace_changed_since, workspaces) {
153        Ok(packages) => Ok(ResolvedPackages {
154            packages,
155            outcome: RequestOutcome::applied(
156                RequestName::PackageBaselines,
157                PACKAGE_BASELINES_REQUEST,
158            ),
159        }),
160        Err(PackageBaselineError::Git {
161            key,
162            reference,
163            source,
164        }) if !matches!(source, ChangedFilesError::InvalidRef(_)) => {
165            let cause = source
166                .describe()
167                .split_whitespace()
168                .collect::<Vec<_>>()
169                .join(" ");
170            Ok(stood_down(
171                source.reason(),
172                &format!("the ref '{reference}' for '{key}' did not resolve ({cause})"),
173                "Fetch the ref with full history, or map the package to a ref Git can resolve.",
174            ))
175        }
176        Err(PackageBaselineError::UnknownWorkspace { key, suggestion }) => {
177            let hint =
178                suggestion.map_or_else(String::new, |root| format!(" (did you mean '{root}'?)"));
179            Ok(stood_down(
180                "unknown-workspace",
181                &format!("'{key}' names no workspace package of this project{hint}"),
182                "Use a workspace root as `fallow list --workspaces` prints it.",
183            ))
184        }
185        Err(err) => Err(err),
186    }
187}
188
189/// A package map that stood down: the run reports in full scope, and the
190/// outcome carries the sentence that the CLI also writes to stderr.
191fn stood_down(reason: &str, cause: &str, remedy: &str) -> ResolvedPackages {
192    ResolvedPackages {
193        packages: None,
194        outcome: RequestOutcome::not_applied(
195            RequestName::PackageBaselines,
196            PACKAGE_BASELINES_REQUEST,
197            reason,
198            format!(
199                "workspaces.changedSince was ignored because {cause}, so this report covers \
200                 every workspace package in full scope. {remedy}"
201            ),
202        ),
203    }
204}
205
206/// The resolved change scope of one run.
207#[derive(Debug, Clone, Default)]
208pub struct ChangeScope {
209    kind: ChangeScopeKind,
210    global_ref: bool,
211    outcome: Option<RequestOutcome>,
212    /// The owner is [`ChangeScopeOwner::CallerKeepingUnusedCode`].
213    keeps_unused_code: bool,
214}
215
216#[derive(Debug, Clone, Default)]
217enum ChangeScopeKind {
218    #[default]
219    Full,
220    Files(NormalizedChangedFiles),
221    Packages(PackageChangeScope),
222}
223
224impl ChangeScope {
225    /// Resolve the change scope of a run.
226    ///
227    /// A changed-file set wins. A requested global ref without files, or a
228    /// caller-owned scope, gives the full scope. Otherwise the configured
229    /// package baselines apply, when the config has any. A mapped ref that
230    /// Git cannot resolve stands the map down to the full scope.
231    ///
232    /// # Errors
233    ///
234    /// Returns an error when the package map has a malformed key or Git ref,
235    /// or when a workspace root cannot be read.
236    pub fn resolve(
237        request: ChangeScopeRequest<'_>,
238        config: &ResolvedConfig,
239        workspaces: &[WorkspaceInfo],
240    ) -> Result<Self, PackageBaselineError> {
241        let global_ref = request.global_ref || request.files.is_some();
242        let keeps_unused_code = request.owner == ChangeScopeOwner::CallerKeepingUnusedCode;
243        if let Some(files) = request.files {
244            return Ok(Self {
245                keeps_unused_code,
246                ..Self::changed_files(files)
247            });
248        }
249        if !request.reads_package_baselines(config) {
250            return Ok(Self {
251                global_ref,
252                keeps_unused_code,
253                ..Self::default()
254            });
255        }
256        let resolved = match request.cache {
257            Some(cache) => cache.resolve(config, workspaces)?,
258            None => resolve_packages(config, workspaces)?,
259        };
260        Ok(Self {
261            kind: resolved
262                .packages
263                .map_or(ChangeScopeKind::Full, ChangeScopeKind::Packages),
264            global_ref,
265            outcome: Some(resolved.outcome),
266            keeps_unused_code,
267        })
268    }
269
270    /// The scope of one global changed-file set.
271    #[must_use]
272    pub fn changed_files(files: &FxHashSet<PathBuf>) -> Self {
273        Self {
274            kind: ChangeScopeKind::Files(NormalizedChangedFiles::new(files)),
275            global_ref: true,
276            outcome: None,
277            keeps_unused_code: false,
278        }
279    }
280
281    /// The `scope_reasons` channel that narrowed the run, when a change ref
282    /// did: the package map, or a global ref. The saved-baseline comparison of
283    /// `check` and finding-id queries read this: a finding outside the scope
284    /// is hidden, not gone. `dupes` compares its baseline with the report
285    /// before the package map narrows it, so it reads only the global ref.
286    #[must_use]
287    pub const fn scope_reason(&self) -> Option<fallow_output::ScopeReason> {
288        match (&self.kind, self.global_ref) {
289            (ChangeScopeKind::Packages(_), _) => Some(fallow_output::ScopeReason::PackageBaselines),
290            (_, true) => Some(fallow_output::ScopeReason::ChangedSince),
291            (_, false) => None,
292        }
293    }
294
295    /// The applied package baselines, when the configured map scopes the run.
296    #[must_use]
297    pub const fn packages(&self) -> Option<&PackageChangeScope> {
298        match &self.kind {
299            ChangeScopeKind::Packages(packages) => Some(packages),
300            ChangeScopeKind::Full | ChangeScopeKind::Files(_) => None,
301        }
302    }
303
304    /// The `package-baselines` request outcome, when the run read the map.
305    #[must_use]
306    pub const fn request_outcome(&self) -> Option<&RequestOutcome> {
307        self.outcome.as_ref()
308    }
309
310    /// The sentence to show when the package map stood down, or `None` when
311    /// the map applied or the run did not read it.
312    #[must_use]
313    pub fn stand_down_message(&self) -> Option<&str> {
314        self.outcome
315            .as_ref()
316            .filter(|outcome| outcome.status != fallow_output::RequestStatus::Applied)
317            .and_then(|outcome| outcome.message.as_deref())
318    }
319
320    /// The `package_baselines` provenance rows of the run. Empty unless the
321    /// configured map scopes the run.
322    #[must_use]
323    pub fn package_baselines(&self) -> Vec<PackageBaselineStatus> {
324        self.packages().map_or_else(Vec::new, |packages| {
325            package_baseline_statuses(std::slice::from_ref(packages), packages.project_root())
326        })
327    }
328
329    /// Whether a finding owned by `path` is in scope.
330    #[must_use]
331    pub fn contains(&self, path: &Path) -> bool {
332        use crate::changed_files::ChangedPathScope as _;
333        match &self.kind {
334            ChangeScopeKind::Full => true,
335            ChangeScopeKind::Files(files) => files.contains(path),
336            ChangeScopeKind::Packages(packages) => packages.contains(path),
337        }
338    }
339
340    /// Keep the dead-code findings in scope.
341    pub(crate) fn retain_dead_code(&self, results: &mut AnalysisResults) {
342        let retain = |results: &mut AnalysisResults| match &self.kind {
343            ChangeScopeKind::Full => {}
344            ChangeScopeKind::Files(files) => {
345                crate::changed_files::filter_results_by_path_scope(results, files);
346            }
347            ChangeScopeKind::Packages(packages) => {
348                crate::changed_files::filter_results_by_path_scope(results, packages);
349            }
350        };
351        if self.keeps_unused_code {
352            crate::changed_files::keeping_unused_code(results, retain);
353        } else {
354            retain(results);
355        }
356    }
357
358    /// Keep the clone groups with at least one instance in scope.
359    pub(crate) fn retain_duplication(&self, report: &mut DuplicationReport, root: &Path) {
360        match &self.kind {
361            ChangeScopeKind::Full => {}
362            ChangeScopeKind::Files(files) => {
363                crate::changed_files::filter_duplication_by_path_scope(report, files, root);
364            }
365            ChangeScopeKind::Packages(packages) => {
366                crate::changed_files::filter_duplication_by_path_scope(report, packages, root);
367            }
368        }
369    }
370}
371
372/// The `package_baselines` rows of a combined report: the rows of the first
373/// section that applied the map. The sections of one run resolve the same map,
374/// so a section without rows either did not run or used a global scope.
375#[must_use]
376pub fn first_package_baselines<'a>(
377    sections: impl IntoIterator<Item = Option<&'a [PackageBaselineStatus]>>,
378) -> Vec<PackageBaselineStatus> {
379    sections
380        .into_iter()
381        .flatten()
382        .find(|rows| !rows.is_empty())
383        .map_or_else(Vec::new, <[PackageBaselineStatus]>::to_vec)
384}
385
386/// Project-relative package baseline rows, sorted by workspace root.
387///
388/// An editor that analyzes several project roots passes every applied scope
389/// and its own root, so the rows of all projects share one path base.
390#[must_use]
391pub fn package_baseline_statuses(
392    scopes: &[PackageChangeScope],
393    root: &Path,
394) -> Vec<PackageBaselineStatus> {
395    let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
396    let mut rows = scopes
397        .iter()
398        .flat_map(|scope| {
399            let prefix = scope
400                .project_root()
401                .strip_prefix(&root)
402                .map(|relative| {
403                    relative
404                        .components()
405                        .map(|component| component.as_os_str().to_string_lossy())
406                        .collect::<Vec<_>>()
407                        .join("/")
408                })
409                .unwrap_or_default();
410            scope
411                .configured_baselines()
412                .map(move |(key, reference)| PackageBaselineStatus {
413                    workspace_root: if prefix.is_empty() {
414                        key.to_owned()
415                    } else {
416                        format!("{prefix}/{key}")
417                    },
418                    reference: reference.to_owned(),
419                })
420        })
421        .collect::<Vec<_>>();
422    rows.sort_by(|a, b| a.workspace_root.cmp(&b.workspace_root));
423    rows
424}
425
426#[cfg(test)]
427mod tests {
428    use std::collections::BTreeMap;
429
430    use fallow_config::{FallowConfig, OutputFormat};
431
432    use super::*;
433
434    fn config_with_map(root: &Path, map: &[(&str, &str)]) -> ResolvedConfig {
435        let mut config = FallowConfig::default().resolve(
436            root.to_path_buf(),
437            OutputFormat::Json,
438            1,
439            true,
440            true,
441            None,
442        );
443        config.workspace_changed_since = map
444            .iter()
445            .map(|(key, reference)| ((*key).to_owned(), (*reference).to_owned()))
446            .collect::<BTreeMap<_, _>>();
447        config
448    }
449
450    /// A map that names no discovered workspace fails resolution. The tests
451    /// below use it to prove that a request never reads the map.
452    fn unknown_workspace_map(root: &Path) -> ResolvedConfig {
453        config_with_map(root, &[("packages/missing", "HEAD")])
454    }
455
456    #[test]
457    fn caller_owned_scope_never_reads_the_package_map() {
458        let temp = tempfile::tempdir().expect("tempdir");
459        let config = unknown_workspace_map(temp.path());
460        let request = ChangeScopeRequest {
461            owner: ChangeScopeOwner::Caller,
462            ..ChangeScopeRequest::default()
463        };
464        assert!(!request.reads_package_baselines(&config));
465        let scope = ChangeScope::resolve(request, &config, &[]).expect("caller-owned scope");
466        assert!(scope.scope_reason().is_none());
467        assert!(scope.package_baselines().is_empty());
468        assert!(scope.contains(&temp.path().join("packages/a/index.ts")));
469    }
470
471    #[test]
472    fn a_requested_global_ref_suppresses_the_map_even_without_files() {
473        let temp = tempfile::tempdir().expect("tempdir");
474        let config = unknown_workspace_map(temp.path());
475        let request = ChangeScopeRequest {
476            global_ref: true,
477            ..ChangeScopeRequest::default()
478        };
479        let scope = ChangeScope::resolve(request, &config, &[]).expect("global scope");
480        assert!(scope.scope_reason().is_some());
481        assert!(scope.packages().is_none());
482    }
483
484    #[test]
485    fn a_changed_file_set_wins_over_the_map() {
486        let temp = tempfile::tempdir().expect("tempdir");
487        let config = unknown_workspace_map(temp.path());
488        let changed: FxHashSet<PathBuf> = std::iter::once(temp.path().join("a.ts")).collect();
489        let request = ChangeScopeRequest {
490            files: Some(&changed),
491            ..ChangeScopeRequest::default()
492        };
493        let scope = ChangeScope::resolve(request, &config, &[]).expect("file scope");
494        assert!(scope.scope_reason().is_some());
495        assert!(scope.contains(&temp.path().join("a.ts")));
496        assert!(!scope.contains(&temp.path().join("b.ts")));
497    }
498
499    /// A map that cannot apply as written stands down as a whole. The report
500    /// is then wider than asked, and the outcome says so.
501    #[test]
502    fn a_key_that_names_no_workspace_stands_the_map_down() {
503        let temp = tempfile::tempdir().expect("tempdir");
504        std::fs::create_dir_all(temp.path().join("packages/web")).expect("package");
505        let config = config_with_map(temp.path(), &[("packages/wbe", "HEAD")]);
506        let workspaces = [WorkspaceInfo {
507            root: temp.path().join("packages/web"),
508            name: "web".to_owned(),
509            is_internal_dependency: false,
510        }];
511        let scope = ChangeScope::resolve(ChangeScopeRequest::default(), &config, &workspaces)
512            .expect("an unknown key stands down");
513        assert!(scope.scope_reason().is_none());
514        assert!(scope.packages().is_none());
515        assert!(scope.package_baselines().is_empty());
516        let outcome = scope.request_outcome().expect("the map was read");
517        assert_eq!(outcome.status, fallow_output::RequestStatus::NotApplied);
518        assert_eq!(outcome.reason.as_deref(), Some("unknown-workspace"));
519        let message = scope.stand_down_message().expect("a stand-down sentence");
520        assert!(
521            message.contains("did you mean 'packages/web'?"),
522            "{message}"
523        );
524    }
525
526    #[test]
527    fn a_malformed_key_or_ref_is_invalid_input() {
528        let temp = tempfile::tempdir().expect("tempdir");
529        for map in [
530            [("./packages/web", "HEAD")],
531            [("packages/web", "-malformed")],
532        ] {
533            std::fs::create_dir_all(temp.path().join("packages/web")).expect("package");
534            let config = config_with_map(temp.path(), &map);
535            let workspaces = [WorkspaceInfo {
536                root: temp.path().join("packages/web"),
537                name: "web".to_owned(),
538                is_internal_dependency: false,
539            }];
540            assert!(
541                ChangeScope::resolve(ChangeScopeRequest::default(), &config, &workspaces).is_err(),
542                "{map:?}"
543            );
544        }
545    }
546
547    #[test]
548    fn the_run_memo_resolves_the_map_once() {
549        let temp = tempfile::tempdir().expect("tempdir");
550        let config = unknown_workspace_map(temp.path());
551        let cache = PackageBaselineCache::new();
552        assert!(!cache.is_resolved());
553        assert!(cache.request_outcome().is_none());
554        let request = ChangeScopeRequest {
555            cache: Some(&cache),
556            ..ChangeScopeRequest::default()
557        };
558        ChangeScope::resolve(request, &config, &[]).expect("first resolution");
559        assert!(cache.is_resolved());
560        let later_config = config_with_map(temp.path(), &[]);
561        let later = ChangeScope::resolve(
562            ChangeScopeRequest {
563                cache: Some(&cache),
564                ..ChangeScopeRequest::default()
565            },
566            &config,
567            &[],
568        )
569        .expect("memo hit");
570        assert_eq!(later.request_outcome(), cache.request_outcome().as_ref());
571        let empty = ChangeScope::resolve(ChangeScopeRequest::default(), &later_config, &[])
572            .expect("no map, full scope");
573        assert!(empty.scope_reason().is_none());
574        assert!(empty.request_outcome().is_none());
575    }
576}