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