Skip to main content

fallow_api/runtime/
feature_flags.rs

1use std::path::Path;
2use std::time::Instant;
3
4use fallow_engine::flag_report::{RetirementRequest, build_retirement_report};
5use fallow_engine::flag_retirement::{RetirementFacts, RetirementOptions};
6use fallow_engine::flag_vendor::{VendorExport, load_flag_state};
7
8use fallow_config::PlannedAnalysis;
9use fallow_engine::session::AnalysisSession;
10use fallow_output::{
11    DiffIndex, FEATURE_FLAGS_SCHEMA_VERSION, FeatureFlagsOutputInput, build_feature_flags_output,
12    feature_flags_meta,
13};
14use fallow_types::results::FeatureFlag;
15
16use crate::{
17    AnalysisOptions, FeatureFlagsOptions, FeatureFlagsProgrammaticOutput, ProgrammaticError,
18    analysis_context::{
19        ProgrammaticAnalysisContext, changed_files_for_run, resolve_programmatic_analysis_context,
20        workspace_roots_for_session,
21    },
22    run::{ProgrammaticEntry, resolve_programmatic_run},
23};
24
25use super::ProgrammaticResult;
26
27/// Run feature-flag analysis and return typed API output before JSON.
28///
29/// # Errors
30///
31/// Returns a structured programmatic error for invalid options, config load
32/// failures, git changed-file failures, or analysis failures, and
33/// `FALLOW_CANCELLED` when the caller's cancellation token is set. The scan
34/// observes the token at its entry, on both sides of the parse loop, and at
35/// the stage boundaries of the dead-code correlation behind it.
36pub fn run_feature_flags(
37    options: &FeatureFlagsOptions,
38) -> ProgrammaticResult<FeatureFlagsProgrammaticOutput> {
39    let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
40    resolved.install(|| run_feature_flags_inner(options, &resolved))
41}
42
43fn run_feature_flags_inner(
44    options: &FeatureFlagsOptions,
45    resolved: &ProgrammaticAnalysisContext,
46) -> ProgrammaticResult<FeatureFlagsProgrammaticOutput> {
47    let start = Instant::now();
48    let vendor_export = load_vendor_export(options, &resolved.root)?;
49    resolved.ensure_not_cancelled("config load and file discovery")?;
50    let session = load_feature_flags_session(resolved, &options.analysis)?;
51    let scan = if options.retirement.is_some() {
52        fallow_engine::flags::analyze_feature_flags_for_retirement(&session)
53    } else {
54        fallow_engine::flags::analyze_feature_flags_with_session(&session)
55            .map(|analysis| (analysis, RetirementFacts::default()))
56    };
57    let (analysis, retirement_facts) = scan.map_err(|err| {
58        super::dead_code::map_engine_error(
59            &err,
60            "feature-flag analysis failed",
61            "FALLOW_FEATURE_FLAGS_FAILED",
62            "feature-flags",
63        )
64    })?;
65    if analysis.files_scanned == 0 {
66        return Err(ProgrammaticError::new("no files discovered", 2)
67            .with_code("FALLOW_NO_FILES_DISCOVERED")
68            .with_context("feature-flags"));
69    }
70
71    let scope = feature_flags_scope(resolved, &session)?;
72    let all_flags = if options.retirement.is_some() {
73        analysis.flags.clone()
74    } else {
75        Vec::new()
76    };
77    let mut flags = analysis.flags;
78    flags.retain(|flag| scope.contains(&flag.path, session.root()));
79    let mut workspace_diagnostics = session.current_workspace_diagnostics();
80    let retirement = options.retirement.as_ref().map(|retirement| {
81        let build = build_retirement_report(RetirementRequest {
82            root: session.root(),
83            workspaces: session.workspaces(),
84            sites: retirement_facts.sites_for(&all_flags),
85            in_scope: &|path| scope.contains(path, session.root()),
86            whole_project: scope.is_whole_project(),
87            age_mode: retirement.flag_age,
88            cache_dir: (!resolved.no_cache).then_some(session.config().cache_dir.as_path()),
89            progress: None,
90            vendor_export: vendor_export.as_ref(),
91            vendor_key_prefix: session.config().flags.vendor_key_prefix.as_deref(),
92            max_flag_age: retirement.max_flag_age,
93            options: RetirementOptions {
94                sort: retirement.sort,
95                min_age_days: retirement.min_age_days,
96                reasons: retirement.reasons.clone(),
97                top: options.top,
98            },
99        });
100        workspace_diagnostics.extend(build.diagnostics.into_iter().map(|kind| {
101            fallow_config::WorkspaceDiagnostic::new(
102                session.root(),
103                session.root().to_path_buf(),
104                kind,
105            )
106        }));
107        build.report
108    });
109    sort_and_limit_feature_flags(&mut flags, options.top);
110
111    let output = build_feature_flags_output(FeatureFlagsOutputInput {
112        schema_version: FEATURE_FLAGS_SCHEMA_VERSION,
113        version: env!("CARGO_PKG_VERSION").to_string(),
114        elapsed: start.elapsed(),
115        flags: &flags,
116        root: session.root(),
117        // Read live, like the dead-code route: the parse stage records
118        // `source-read-failure` and `source-parse-degraded` after the session
119        // captured its walk snapshot, and both are reasons a flag is missing.
120        workspace_diagnostics,
121        // The diff this route resolved and applied above, or the reason it
122        // stood down. This route filters flags by the diff, unlike the CLI
123        // `flags` command, so an applied entry states a real narrowing.
124        request_outcomes: resolved.request_outcomes(),
125        meta: resolved.explain_enabled().then(feature_flags_meta),
126        retirement,
127    });
128
129    Ok(FeatureFlagsProgrammaticOutput {
130        output,
131        telemetry_analysis_run_id: None,
132    })
133}
134
135/// Open the session of a feature flags run. The run validates the config,
136/// external plugins included, as the other routes do.
137fn load_feature_flags_session(
138    resolved: &ProgrammaticAnalysisContext,
139    analysis: &AnalysisOptions,
140) -> ProgrammaticResult<AnalysisSession> {
141    let run = resolve_programmatic_run(analysis, &ProgrammaticEntry::FeatureFlags)?;
142    let session = crate::run::runnable(&run, PlannedAnalysis::DeadCode)?.open_session();
143    Ok(super::dead_code::attach_cancellation(session, resolved))
144}
145
146/// The files a flags run reports on, from the workspace, changed-since and
147/// diff options.
148struct FeatureFlagsScope<'a> {
149    workspace_roots: Option<Vec<std::path::PathBuf>>,
150    changed_files: Option<rustc_hash::FxHashSet<std::path::PathBuf>>,
151    diff: Option<&'a DiffIndex>,
152}
153
154impl FeatureFlagsScope<'_> {
155    fn is_whole_project(&self) -> bool {
156        self.workspace_roots.is_none() && self.changed_files.is_none() && self.diff.is_none()
157    }
158
159    fn contains(&self, path: &Path, root: &Path) -> bool {
160        self.workspace_roots
161            .as_ref()
162            .is_none_or(|roots| roots.iter().any(|workspace| path.starts_with(workspace)))
163            && self
164                .changed_files
165                .as_ref()
166                .is_none_or(|changed| changed.contains(path))
167            && self.diff.as_ref().is_none_or(|diff| {
168                diff.key_for(path, root)
169                    .is_none_or(|rel| diff.touches_file(&rel))
170            })
171    }
172}
173
174fn feature_flags_scope<'a>(
175    resolved: &'a ProgrammaticAnalysisContext,
176    session: &AnalysisSession,
177) -> ProgrammaticResult<FeatureFlagsScope<'a>> {
178    let workspace_roots = workspace_roots_for_session(resolved, session.workspaces())?;
179    let changed_files = changed_files_for_run(resolved)?;
180    if changed_files.is_some() {
181        resolved
182            .measure_changed_since_scope(session.files().iter().map(|file| file.path.as_path()));
183    }
184    Ok(FeatureFlagsScope {
185        workspace_roots,
186        changed_files,
187        diff: resolved.diff_index(),
188    })
189}
190
191/// Read the vendor export before the analysis, so an invalid file fails
192/// fast.
193fn load_vendor_export(
194    options: &FeatureFlagsOptions,
195    root: &Path,
196) -> ProgrammaticResult<Option<VendorExport>> {
197    let Some(path) = options
198        .retirement
199        .as_ref()
200        .and_then(|retirement| retirement.flag_state.as_deref())
201    else {
202        return Ok(None);
203    };
204    load_flag_state(path, root).map(Some).map_err(|error| {
205        ProgrammaticError::new(error.message, 2)
206            .with_code("FALLOW_FLAG_STATE_INVALID")
207            .with_help(error.help)
208            .with_context("feature-flags.retirement.flagState")
209    })
210}
211
212fn sort_and_limit_feature_flags(flags: &mut Vec<FeatureFlag>, top: Option<usize>) {
213    flags.sort_by(|a, b| {
214        a.path
215            .cmp(&b.path)
216            .then(a.line.cmp(&b.line))
217            .then(a.flag_name.cmp(&b.flag_name))
218    });
219
220    if let Some(top) = top {
221        flags.truncate(top);
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn production_override_gives_the_rules_of_production_mode() {
231        let project = tempfile::tempdir().expect("temp dir");
232        std::fs::write(project.path().join("package.json"), r#"{"name":"flags"}"#)
233            .expect("package");
234        let analysis = AnalysisOptions {
235            root: Some(project.path().to_path_buf()),
236            production_override: Some(true),
237            ..AnalysisOptions::default()
238        };
239        let resolved = resolve_programmatic_analysis_context(&analysis).expect("context resolves");
240
241        let session = load_feature_flags_session(&resolved, &analysis).expect("session loads");
242
243        assert!(session.config().production);
244        assert_eq!(
245            session.config().rules.unused_dev_dependencies,
246            fallow_config::Severity::Off,
247            "production mode turns unused-dev-dependencies off, as `--production` does"
248        );
249    }
250}