Skip to main content

fallow_engine/
flag_report.rs

1//! One entry point that builds the `fallow flags --retirement` report.
2//!
3//! The CLI and the programmatic API (and through it the MCP server) call this
4//! function, so the two surfaces run the same steps in the same order: group
5//! the sites into rows, measure the age, apply the vendor export, compute the
6//! age gate, then filter, sort and limit the rows.
7
8use std::path::Path;
9
10use fallow_config::WorkspaceInfo;
11use fallow_types::flag_retirement::{FlagAgeMode, FlagRetirementReport, RetirementFlagKind};
12use fallow_types::workspace::WorkspaceDiagnosticKind;
13use rustc_hash::{FxHashMap, FxHashSet};
14
15use crate::clock::AnalysisClock;
16use crate::flag_age::{FlagAgeRequest, PickaxeProgress, apply_flag_ages};
17use crate::flag_retirement::{
18    AGE_GATE_AGE_OFF, AGE_GATE_NO_HISTORY, RetirementOptions, RetirementSiteInput, aggregate_flags,
19    finish_report, max_age_gate, relative,
20};
21use crate::flag_vendor::{SiteLocation, VendorExport, VendorMatch, apply_vendor_state};
22
23/// Inputs of one retirement report.
24pub struct RetirementRequest<'a> {
25    /// Project root. Paths in the report are relative to it.
26    pub root: &'a Path,
27    /// Workspaces of the project, for the flag identity.
28    pub workspaces: &'a [WorkspaceInfo],
29    /// Every flag site of the project, also outside the scope of the run.
30    pub sites: Vec<RetirementSiteInput>,
31    /// Whether a file is in the scope of the run.
32    pub in_scope: &'a dyn Fn(&Path) -> bool,
33    /// Whether the run covers the whole project. Only such a run adds
34    /// `vendor-only` rows.
35    pub whole_project: bool,
36    /// How to measure flag age.
37    pub age_mode: FlagAgeMode,
38    /// Directory for the age cache, or `None` to run without the cache.
39    pub cache_dir: Option<&'a Path>,
40    /// Receives pickaxe progress.
41    pub progress: Option<&'a (dyn Fn(PickaxeProgress) + Sync)>,
42    /// The `--flag-state` export, if any.
43    pub vendor_export: Option<&'a VendorExport>,
44    /// `flags.vendorKeyPrefix`.
45    pub vendor_key_prefix: Option<&'a str>,
46    /// `--max-flag-age`, in days.
47    pub max_flag_age: Option<u64>,
48    /// Filters, order and limit of the rows.
49    pub options: RetirementOptions,
50}
51
52/// A retirement report and the reasons that ages are missing.
53pub struct RetirementBuild {
54    /// The report.
55    pub report: FlagRetirementReport,
56    /// Why no age was measured, when git history was not available.
57    pub diagnostics: Vec<WorkspaceDiagnosticKind>,
58}
59
60/// Build the retirement report.
61#[must_use]
62pub fn build_retirement_report(request: RetirementRequest<'_>) -> RetirementBuild {
63    let root = request.root;
64    let code_flag_names: FxHashSet<String> = request
65        .sites
66        .iter()
67        .map(|site| site.flag_name.clone())
68        .collect();
69    let project_sdk_labels: FxHashSet<String> = request
70        .sites
71        .iter()
72        .filter(|site| site.kind == RetirementFlagKind::SdkCall)
73        .filter_map(|site| site.sdk_name.clone())
74        .collect();
75    let mut sites = request.sites;
76    let hidden_sdk_labels = hide_unconfirmed_sdk_names(&mut sites, root);
77    let mut rows = aggregate_flags(sites, root, request.workspaces, request.in_scope);
78    let age = apply_flag_ages(
79        &mut rows,
80        &FlagAgeRequest {
81            root,
82            mode: request.age_mode,
83            cache_dir: request.cache_dir,
84            progress: request.progress,
85        },
86    );
87    let vendor_state = request.vendor_export.map(|export| {
88        apply_vendor_state(
89            &mut rows,
90            &VendorMatch {
91                export,
92                key_prefix: request.vendor_key_prefix,
93                code_flag_names: &code_flag_names,
94                project_sdk_labels: &project_sdk_labels,
95                hidden_sdk_labels: &hidden_sdk_labels,
96                add_vendor_only: request.whole_project,
97                clock_epoch_secs: AnalysisClock::for_repo(root).epoch_secs(),
98            },
99        )
100    });
101    let skip_reason = if request.age_mode == FlagAgeMode::Off {
102        Some(AGE_GATE_AGE_OFF)
103    } else if age.generated_at_clock.is_none() {
104        Some(AGE_GATE_NO_HISTORY)
105    } else {
106        None
107    };
108    let max_flag_age = request
109        .max_flag_age
110        .map(|days| max_age_gate(&rows, days, skip_reason));
111    let mut report = finish_report(
112        rows,
113        request.age_mode,
114        age.generated_at_clock,
115        &request.options,
116    );
117    report.vendor_state = vendor_state;
118    report.max_flag_age = max_flag_age;
119    RetirementBuild {
120        report,
121        diagnostics: age.diagnostics,
122    }
123}
124
125/// The `(flag name, SDK name)` pairs that at least one confirmed SDK call
126/// reads. A flag import in the file of the call confirms it.
127fn confirmed_sdk_flags(sites: &[RetirementSiteInput]) -> FxHashSet<(String, String)> {
128    sites
129        .iter()
130        .filter(|site| site.kind == RetirementFlagKind::SdkCall && !site.facts.unconfirmed_sdk())
131        .filter_map(|site| {
132            site.sdk_name
133                .clone()
134                .map(|sdk| (site.flag_name.clone(), sdk))
135        })
136        .collect()
137}
138
139/// Remove the SDK name of each SDK call whose flag and SDK no confirmed
140/// call reads. The name is only the default provider of a generic method
141/// such as `isEnabled`, so the report must not name it. The rows group on
142/// the name that the report shows, so two such calls of one flag with
143/// different default providers give one row. Returns the removed name of
144/// each call, keyed by its location, because the vendor-state match still
145/// uses it.
146fn hide_unconfirmed_sdk_names(
147    sites: &mut [RetirementSiteInput],
148    root: &Path,
149) -> FxHashMap<SiteLocation, String> {
150    let confirmed = confirmed_sdk_flags(sites);
151    let mut hidden = FxHashMap::default();
152    for site in sites
153        .iter_mut()
154        .filter(|site| site.kind == RetirementFlagKind::SdkCall)
155    {
156        let is_confirmed = site
157            .sdk_name
158            .as_ref()
159            .is_none_or(|sdk| confirmed.contains(&(site.flag_name.clone(), sdk.clone())));
160        if is_confirmed {
161            continue;
162        }
163        if let Some(sdk) = site.sdk_name.take() {
164            hidden.insert((relative(&site.path, root), site.line, site.col), sdk);
165        }
166    }
167    hidden
168}