Skip to main content

fallow_api/
analysis_context.rs

1//! Shared programmatic analysis context resolution.
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, OnceLock};
6
7use fallow_config::{ResolvedConfig, WorkspaceInfo};
8use fallow_engine::change_scope::{
9    ChangeScope, ChangeScopeOwner, ChangeScopeRequest, PackageBaselineCache,
10};
11use fallow_engine::workspace_scope::{WorkspaceScope, WorkspaceScopeError, WorkspaceScopeMode};
12use fallow_output::{DiffIndex, MAX_DIFF_BYTES, RequestName, RequestOutcome, RequestOutcomes};
13use fallow_types::path_util::is_absolute_path_any_platform;
14use rustc_hash::FxHashSet;
15
16use crate::{AnalysisOptions, ProgrammaticError};
17
18type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
19
20/// Resolved common programmatic analysis context.
21///
22/// This owns validation, root/config/diff resolution, production overrides,
23/// the workspace selection, and the per-call thread pool shared by programmatic
24/// analysis families. API runtimes and engine-backed runners use it directly.
25///
26/// The workspace selection resolves against the workspaces of the analysis
27/// session (see `workspace_roots_for_session`). These workspaces include the
28/// `workspaces.patterns` of the loaded config, so the context does not resolve
29/// the selection before the config loads.
30pub struct ProgrammaticAnalysisContext {
31    pub(crate) root: PathBuf,
32    pub(crate) config_path: Option<PathBuf>,
33    pub(crate) allow_remote_extends: bool,
34    pub(crate) no_cache: bool,
35    pub(crate) threads: usize,
36    pub(crate) pool: rayon::ThreadPool,
37    pub(crate) diff: Option<DiffIndex>,
38    /// What became of the diff request, for the envelope's `request_outcomes`.
39    pub(crate) diff_request: Option<RequestOutcome>,
40    pub(crate) production_override: Option<bool>,
41    /// The changed-since ref the call narrows by: the caller's own, or the
42    /// ambient one when it resolved. `None` when an ambient ref stood down.
43    pub(crate) changed_since: Option<String>,
44    /// What became of the changed-since request, set once it resolved or
45    /// stood down.
46    pub(crate) changed_since_request: OnceLock<RequestOutcome>,
47    /// The changed files of the resolved ref, normalized like the CLI's.
48    pub(crate) changed_since_files: OnceLock<FxHashSet<PathBuf>>,
49    /// Who owns the change scope of the call's analyses. Audit owns it, so
50    /// its sections never read `workspaces.changedSince`.
51    pub(crate) change_scope_owner: ChangeScopeOwner,
52    /// The caller turned `workspaces.changedSince` off for this call.
53    pub(crate) no_package_baselines: bool,
54    /// The package map as the call's first analysis resolved it. Later
55    /// analyses of the call reuse it, and its outcome is the call's
56    /// `package-baselines` request outcome.
57    pub(crate) package_baselines: PackageBaselineCache,
58    /// The changed files the call's analyses kept, over every analysis that
59    /// measured: the `scope_size` of the `changed-since` entry.
60    pub(crate) changed_since_analyzed: Mutex<Option<FxHashSet<PathBuf>>>,
61    pub(crate) workspace: Option<Vec<String>>,
62    pub(crate) changed_workspaces: Option<String>,
63    pub(crate) explain: bool,
64    pub(crate) cancellation: Option<Arc<AtomicBool>>,
65}
66
67/// Resolve common programmatic analysis options once for a concrete runtime.
68///
69/// # Errors
70///
71/// Returns a structured programmatic error for invalid roots, configs, thread
72/// counts, workspace scopes, or explicit diff files.
73pub fn resolve_programmatic_analysis_context(
74    options: &AnalysisOptions,
75) -> ProgrammaticResult<ProgrammaticAnalysisContext> {
76    validate_analysis_option_shape(options)?;
77    let root = resolve_analysis_root(options.root.as_deref())?;
78    validate_analysis_config_path(options.config_path.as_deref())?;
79    let threads = options.threads.unwrap_or_else(default_threads);
80    let pool = fallow_engine::thread_pool::worker_pool_builder(threads)
81        .build()
82        .map_err(|err| {
83            ProgrammaticError::new(format!("failed to build analysis thread pool: {err}"), 2)
84                .with_code("FALLOW_THREAD_POOL_INIT_FAILED")
85                .with_context("analysis.threads")
86        })?;
87    let (diff, diff_request) = resolve_diff(options, &root)?;
88    let changed_since_request = OnceLock::new();
89    let changed_since_files = OnceLock::new();
90    let changed_since =
91        resolve_changed_since(options, &root, &changed_since_request, &changed_since_files);
92    Ok(ProgrammaticAnalysisContext {
93        root,
94        config_path: options.config_path.clone(),
95        allow_remote_extends: options.allow_remote_extends,
96        no_cache: options.no_cache,
97        threads,
98        pool,
99        diff,
100        diff_request,
101        production_override: options
102            .production_override
103            .or_else(|| options.production.then_some(true)),
104        changed_since,
105        changed_since_request,
106        changed_since_files,
107        change_scope_owner: ChangeScopeOwner::Run,
108        no_package_baselines: options.no_package_baselines,
109        package_baselines: PackageBaselineCache::new(),
110        changed_since_analyzed: Mutex::new(None),
111        workspace: options.workspace.clone(),
112        changed_workspaces: options.changed_workspaces.clone(),
113        explain: options.explain,
114        cancellation: options.cancellation.clone(),
115    })
116}
117
118fn validate_analysis_option_shape(options: &AnalysisOptions) -> ProgrammaticResult<()> {
119    if options.threads == Some(0) {
120        return Err(
121            ProgrammaticError::new("`threads` must be greater than 0", 2)
122                .with_code("FALLOW_INVALID_THREADS")
123                .with_context("analysis.threads"),
124        );
125    }
126    if options.workspace.is_some() && options.changed_workspaces.is_some() {
127        return Err(ProgrammaticError::new(
128            "`workspace` and `changed_workspaces` are mutually exclusive",
129            2,
130        )
131        .with_code("FALLOW_MUTUALLY_EXCLUSIVE_SCOPE")
132        .with_context("analysis.workspace"));
133    }
134    Ok(())
135}
136
137pub fn resolve_analysis_root(root: Option<&Path>) -> ProgrammaticResult<PathBuf> {
138    let root = match root {
139        Some(root) => root.to_path_buf(),
140        None => std::env::current_dir().map_err(|err| {
141            ProgrammaticError::new(
142                format!("failed to resolve current working directory: {err}"),
143                2,
144            )
145            .with_code("FALLOW_CWD_UNAVAILABLE")
146            .with_context("analysis.root")
147        })?,
148    };
149    fallow_engine::validate::validate_root(&root).map_err(|err| {
150        ProgrammaticError::new(err, 2)
151            .with_code("FALLOW_INVALID_ROOT")
152            .with_context("analysis.root")
153    })
154}
155
156pub fn validate_analysis_config_path(config_path: Option<&Path>) -> ProgrammaticResult<()> {
157    if let Some(config_path) = config_path
158        && !config_path.exists()
159    {
160        return Err(ProgrammaticError::new(
161            format!("config file does not exist: {}", config_path.display()),
162            2,
163        )
164        .with_code("FALLOW_INVALID_CONFIG_PATH")
165        .with_context("analysis.configPath"));
166    }
167    Ok(())
168}
169
170impl ProgrammaticAnalysisContext {
171    /// Run work inside the per-call Rayon pool.
172    pub fn install<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
173        self.pool.install(f)
174    }
175
176    /// Resolved analysis root.
177    #[must_use]
178    pub fn root(&self) -> &Path {
179        &self.root
180    }
181
182    /// Config path supplied by the caller, if any.
183    #[must_use]
184    pub fn config_path(&self) -> &Option<PathBuf> {
185        &self.config_path
186    }
187
188    /// Whether this call permits remote config inheritance.
189    #[must_use]
190    pub const fn allow_remote_extends(&self) -> bool {
191        self.allow_remote_extends
192    }
193
194    /// Whether parser cache use is disabled for this call.
195    #[must_use]
196    pub const fn no_cache(&self) -> bool {
197        self.no_cache
198    }
199
200    /// Effective parser thread count for this call.
201    #[must_use]
202    pub const fn threads(&self) -> usize {
203        self.threads
204    }
205
206    /// Parsed diff for this call, explicit or ambient, if one applied.
207    #[must_use]
208    pub const fn diff_index(&self) -> Option<&DiffIndex> {
209        self.diff.as_ref()
210    }
211
212    /// The call's `request_outcomes`, or `None` when it was asked for nothing.
213    ///
214    /// Carries the `diff-filter` entry, which is the one request this context
215    /// resolves and can stand down. Same object as the CLI publishes for the
216    /// same diff.
217    #[must_use]
218    pub fn request_outcomes(&self) -> Option<RequestOutcomes> {
219        let mut requests = RequestOutcomes::new();
220        requests.insert_if(RequestName::ChangedSince, self.changed_since_outcome());
221        requests.insert_if(RequestName::DiffFilter, self.diff_request.clone());
222        requests.insert_if(
223            RequestName::PackageBaselines,
224            self.package_baselines.request_outcome(),
225        );
226        requests.into_option()
227    }
228
229    /// The `changed-since` entry, with the measured scope when the ref applied
230    /// and an analysis measured it, as the CLI publishes it.
231    fn changed_since_outcome(&self) -> Option<RequestOutcome> {
232        let outcome = self.changed_since_request.get()?.clone();
233        let size = self
234            .changed_since_analyzed
235            .lock()
236            .ok()
237            .and_then(|analyzed| analyzed.as_ref().map(|files| files.len() as u64));
238        Some(match size {
239            Some(size) if outcome.status == fallow_output::RequestStatus::Applied => {
240                RequestOutcome {
241                    scope_size: Some(size),
242                    ..outcome
243                }
244            }
245            _ => outcome,
246        })
247    }
248
249    /// Add the changed files an analysis kept to the call's analyzed changed
250    /// files. Does nothing when no ref resolved.
251    pub(crate) fn measure_changed_since_scope<'a>(
252        &self,
253        analyzed: impl IntoIterator<Item = &'a Path>,
254    ) {
255        let Some(changed) = self.changed_since_files.get() else {
256            return;
257        };
258        let Ok(mut union) = self.changed_since_analyzed.lock() else {
259            return;
260        };
261        union.get_or_insert_with(FxHashSet::default).extend(
262            analyzed
263                .into_iter()
264                .map(dunce::simplified)
265                .filter(|path| changed.contains(*path))
266                .map(Path::to_path_buf),
267        );
268    }
269
270    /// Record the resolved changed files of the call's ref, and the `applied`
271    /// entry, once.
272    fn record_changed_since_applied(&self, git_ref: &str, files: &FxHashSet<PathBuf>) {
273        let _ = self.changed_since_files.set(
274            files
275                .iter()
276                .map(|path| dunce::simplified(path).to_path_buf())
277                .collect(),
278        );
279        let _ = self
280            .changed_since_request
281            .set(RequestOutcome::applied(RequestName::ChangedSince, git_ref));
282    }
283
284    /// Record that an engine runner narrowed by the call's ref, with the
285    /// changed files it kept. For a runner that resolves the ref itself.
286    pub(crate) fn record_changed_since_from_runner(&self, kept: Option<&[PathBuf]>) {
287        let (Some(git_ref), Some(kept)) = (self.changed_since.as_deref(), kept) else {
288            return;
289        };
290        if self.changed_since_files.get().is_none() {
291            let files: FxHashSet<PathBuf> = kept.iter().cloned().collect();
292            self.record_changed_since_applied(git_ref, &files);
293        }
294        self.measure_changed_since_scope(kept.iter().map(PathBuf::as_path));
295    }
296
297    /// Explicit production override supplied by the caller.
298    #[must_use]
299    pub const fn production_override(&self) -> Option<bool> {
300        self.production_override
301    }
302
303    /// Git ref used to scope changed files.
304    #[must_use]
305    pub fn changed_since(&self) -> Option<&str> {
306        self.changed_since.as_deref()
307    }
308
309    /// Hand the change scope of this call's analyses to the caller.
310    #[must_use]
311    pub(crate) const fn with_change_scope_owner(mut self, owner: ChangeScopeOwner) -> Self {
312        self.change_scope_owner = owner;
313        self
314    }
315
316    /// Resolve the change scope of one analysis in this call.
317    ///
318    /// `files` is the changed-file set of the analysis: the call's resolved
319    /// ref, or a set that the caller supplied. A requested ref that stood
320    /// down still suppresses the package map, as on the CLI.
321    pub(crate) fn change_scope(
322        &self,
323        files: Option<&FxHashSet<PathBuf>>,
324        config: &ResolvedConfig,
325        workspaces: &[WorkspaceInfo],
326    ) -> ProgrammaticResult<ChangeScope> {
327        let request = ChangeScopeRequest {
328            owner: self.change_scope_owner,
329            global_ref: self.changed_since.is_some() || self.changed_since_request.get().is_some(),
330            files,
331            cache: Some(&self.package_baselines),
332            no_package_baselines: self.no_package_baselines,
333        };
334        ChangeScope::resolve(request, config, workspaces).map_err(|err| {
335            ProgrammaticError::new(format!("workspace baseline error: {err}"), 2)
336                .with_code("FALLOW_PACKAGE_BASELINE_FAILED")
337                .with_context("analysis.workspaces.changedSince")
338        })
339    }
340
341    /// Workspace filter patterns supplied by the caller.
342    #[must_use]
343    pub fn workspace(&self) -> Option<&[String]> {
344        self.workspace.as_deref()
345    }
346
347    /// Git ref used to scope changed workspaces.
348    #[must_use]
349    pub fn changed_workspaces(&self) -> Option<&str> {
350        self.changed_workspaces.as_deref()
351    }
352
353    /// Whether API JSON should include explanatory metadata.
354    #[must_use]
355    pub const fn explain_enabled(&self) -> bool {
356        self.explain
357    }
358
359    /// The caller's cancellation token for this analysis, if it supplied one.
360    #[must_use]
361    pub fn cancellation(&self) -> Option<&Arc<AtomicBool>> {
362        self.cancellation.as_ref()
363    }
364
365    /// Whether the caller has asked this analysis to stop.
366    #[must_use]
367    pub fn is_cancelled(&self) -> bool {
368        self.cancellation
369            .as_ref()
370            .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
371    }
372
373    /// Stop the analysis at a stage boundary once the caller has cancelled it.
374    ///
375    /// `stage` names the work that has not been started, so the error says how
376    /// far the run got rather than only that it was stopped.
377    ///
378    /// # Errors
379    ///
380    /// Returns a `FALLOW_CANCELLED` programmatic error when the caller's token
381    /// is set. Cancellation is always an error, never an empty success: an
382    /// empty report reads downstream as a clean project.
383    pub fn ensure_not_cancelled(&self, stage: &str) -> ProgrammaticResult<()> {
384        if self.is_cancelled() {
385            return Err(cancelled_error(stage));
386        }
387        Ok(())
388    }
389}
390
391/// Stop before any work starts when the caller's token is already set.
392///
393/// Runtimes that never build a [`ProgrammaticAnalysisContext`] read the token
394/// straight off the options with this.
395///
396/// # Errors
397///
398/// Returns a `FALLOW_CANCELLED` programmatic error when the token is set.
399pub fn ensure_options_not_cancelled(
400    options: &AnalysisOptions,
401    stage: &str,
402) -> ProgrammaticResult<()> {
403    if options
404        .cancellation
405        .as_ref()
406        .is_some_and(|cancelled| cancelled.load(Ordering::SeqCst))
407    {
408        return Err(cancelled_error(stage));
409    }
410    Ok(())
411}
412
413/// The single `FALLOW_CANCELLED` error shape for the programmatic API.
414///
415/// `stage` names the work the run never started, so the error says how far it
416/// got and not only that it stopped.
417#[must_use]
418pub fn cancelled_error(stage: &str) -> ProgrammaticError {
419    cancelled_error_message(&format!("analysis was cancelled before {stage}"))
420}
421
422/// A `FALLOW_CANCELLED` error carrying a message a lower layer already built.
423#[must_use]
424pub fn cancelled_error_message(message: &str) -> ProgrammaticError {
425    ProgrammaticError::new(message, 2)
426        .with_code("FALLOW_CANCELLED")
427        .with_context("analysis.cancellation")
428}
429
430fn default_threads() -> usize {
431    std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
432}
433
434/// Resolve the call's diff from its two sources, which fail differently.
435///
436/// An explicit `diff_file` is the caller's own argument, so a bad file is a
437/// `FALLOW_INVALID_DIFF_FILE` error. An ambient `FALLOW_DIFF_FILE` comes from
438/// the environment the caller inherited, so a bad file stands down: no diff,
439/// full scope, and a `not-applied` outcome with the CLI's reason token and
440/// sentence. A readable patch from either source stands down when its paths
441/// cannot be placed. An explicit source remains authoritative in that case.
442fn resolve_diff(
443    options: &AnalysisOptions,
444    root: &Path,
445) -> ProgrammaticResult<(Option<DiffIndex>, Option<RequestOutcome>)> {
446    if let Some(path) = options.diff_file.as_deref() {
447        let index = load_explicit_diff_file(path, root)?;
448        let label = format!("diffFile {}", path.display());
449        return Ok(
450            match fallow_engine::diff_source::place_diff(
451                index,
452                root,
453                &fallow_engine::diff_source::diff_base_candidates(root),
454                &label,
455            ) {
456                Ok(index) => {
457                    let request = diff_applied(label, &index);
458                    (Some(index), Some(request))
459                }
460                Err(stand_down) => {
461                    let (reason, message) = stand_down.into_parts();
462                    let request = RequestOutcome::not_applied(
463                        RequestName::DiffFilter,
464                        label,
465                        reason,
466                        message,
467                    );
468                    (None, Some(request))
469                }
470            },
471        );
472    }
473    let Some(path) = options.ambient_diff_file.as_deref() else {
474        return Ok((None, None));
475    };
476    Ok(load_ambient_diff_file(path, root))
477}
478
479/// Load and place an ambient diff the way the CLI loads `$FALLOW_DIFF_FILE`,
480/// with the same label, so both routes publish the same outcome object.
481fn load_ambient_diff_file(path: &Path, root: &Path) -> (Option<DiffIndex>, Option<RequestOutcome>) {
482    let abs = if path.is_absolute() {
483        path.to_path_buf()
484    } else {
485        root.join(path)
486    };
487    let label = format!("$FALLOW_DIFF_FILE {}", abs.display());
488    let placed = fallow_engine::diff_source::read_diff_file(&abs, &label).and_then(|text| {
489        fallow_engine::diff_source::place_diff(
490            DiffIndex::from_unified_diff(&text),
491            root,
492            &fallow_engine::diff_source::diff_base_candidates(root),
493            &label,
494        )
495    });
496    match placed {
497        Ok(index) => {
498            let request = diff_applied(label, &index);
499            (Some(index), Some(request))
500        }
501        Err(stand_down) => {
502            let (reason, message) = stand_down.into_parts();
503            let request =
504                RequestOutcome::not_applied(RequestName::DiffFilter, label, reason, message);
505            (None, Some(request))
506        }
507    }
508}
509
510/// An applied diff filter, sized like the CLI's (see
511/// [`DiffIndex::filter_scope_size`]).
512fn diff_applied(label: String, index: &DiffIndex) -> RequestOutcome {
513    RequestOutcome::applied_with_scope_size(
514        RequestName::DiffFilter,
515        label,
516        index.filter_scope_size() as u64,
517    )
518}
519
520fn load_explicit_diff_file(path: &Path, root: &Path) -> ProgrammaticResult<DiffIndex> {
521    if path == Path::new("-") {
522        return Err(ProgrammaticError::new(
523            "`diff_file` does not support stdin; pass a file path",
524            2,
525        )
526        .with_code("FALLOW_INVALID_DIFF_FILE")
527        .with_context("analysis.diffFile"));
528    }
529    let abs = if is_absolute_path_any_platform(path) {
530        path.to_path_buf()
531    } else {
532        root.join(path)
533    };
534    let meta = std::fs::metadata(&abs).map_err(|err| {
535        ProgrammaticError::new(
536            format!(
537                "diff file does not exist or cannot be read: {} ({err})",
538                abs.display()
539            ),
540            2,
541        )
542        .with_code("FALLOW_INVALID_DIFF_FILE")
543        .with_context("analysis.diffFile")
544    })?;
545    if !meta.is_file() {
546        return Err(ProgrammaticError::new(
547            format!("diff path is not a file: {}", abs.display()),
548            2,
549        )
550        .with_code("FALLOW_INVALID_DIFF_FILE")
551        .with_context("analysis.diffFile"));
552    }
553    if meta.len() > MAX_DIFF_BYTES {
554        return Err(ProgrammaticError::new(
555            format!(
556                "diff file is {} bytes, above the {MAX_DIFF_BYTES} byte limit: {}",
557                meta.len(),
558                abs.display()
559            ),
560            2,
561        )
562        .with_code("FALLOW_INVALID_DIFF_FILE")
563        .with_context("analysis.diffFile"));
564    }
565    let text = std::fs::read_to_string(&abs).map_err(|err| {
566        ProgrammaticError::new(
567            format!("failed to read diff file {}: {err}", abs.display()),
568            2,
569        )
570        .with_code("FALLOW_INVALID_DIFF_FILE")
571        .with_context("analysis.diffFile")
572    })?;
573    Ok(DiffIndex::from_unified_diff(&text))
574}
575
576/// Resolve the call's changed-since ref once, when it comes from the
577/// environment.
578///
579/// The two sources fail differently, like the two diff sources. An explicit
580/// `changed_since` is the caller's own argument, so a ref that does not
581/// resolve fails the call later, in [`changed_files_for_run`]. An ambient
582/// `FALLOW_CHANGED_SINCE` comes from the environment the caller inherited, so
583/// a ref that does not resolve stands down here: the call runs at full scope
584/// and publishes `not-applied` with the CLI's reason token and sentence.
585fn resolve_changed_since(
586    options: &AnalysisOptions,
587    root: &Path,
588    request: &OnceLock<RequestOutcome>,
589    files: &OnceLock<FxHashSet<PathBuf>>,
590) -> Option<String> {
591    if let Some(git_ref) = options.changed_since.as_deref() {
592        return Some(git_ref.to_owned());
593    }
594    let git_ref = options.ambient_changed_since.as_deref()?;
595    match fallow_engine::changed_files::changed_files(root, git_ref) {
596        Ok(changed) => {
597            let _ = files.set(
598                changed
599                    .iter()
600                    .map(|path| dunce::simplified(path).to_path_buf())
601                    .collect(),
602            );
603            let _ = request.set(RequestOutcome::applied(RequestName::ChangedSince, git_ref));
604            Some(git_ref.to_owned())
605        }
606        Err(err) => {
607            let _ = request.set(RequestOutcome::not_applied(
608                RequestName::ChangedSince,
609                git_ref,
610                err.reason(),
611                err.changed_since_message(git_ref),
612            ));
613            None
614        }
615    }
616}
617
618pub fn changed_files_for_run(
619    resolved: &ProgrammaticAnalysisContext,
620) -> ProgrammaticResult<Option<FxHashSet<PathBuf>>> {
621    let Some(git_ref) = resolved.changed_since.as_deref() else {
622        return Ok(None);
623    };
624    fallow_engine::changed_files::changed_files(&resolved.root, git_ref)
625        .inspect(|files| resolved.record_changed_since_applied(git_ref, files))
626        .map(Some)
627        .map_err(|err| {
628            ProgrammaticError::new(
629                format!(
630                    "failed to resolve changed files for ref `{git_ref}`: {}",
631                    err.describe()
632                ),
633                2,
634            )
635            .with_code("FALLOW_CHANGED_FILES_FAILED")
636            .with_context("analysis.changedSince")
637        })
638}
639
640/// Check the workspace selection of the call against the session workspaces,
641/// for a route that reads the whole project but still rejects a selection
642/// that names no workspace.
643pub fn validate_workspace_selection(
644    resolved: &ProgrammaticAnalysisContext,
645    workspaces: &[WorkspaceInfo],
646) -> ProgrammaticResult<()> {
647    workspace_roots_for_session(resolved, workspaces).map(|_| ())
648}
649
650pub fn workspace_roots_for_session(
651    resolved: &ProgrammaticAnalysisContext,
652    workspaces: &[WorkspaceInfo],
653) -> ProgrammaticResult<Option<WorkspaceScope>> {
654    resolve_workspace_scope_from_workspaces(
655        &resolved.root,
656        resolved.workspace.as_deref(),
657        resolved.changed_workspaces.as_deref(),
658        workspaces,
659    )
660}
661
662fn resolve_workspace_scope_from_workspaces(
663    root: &Path,
664    workspace: Option<&[String]>,
665    changed_workspaces: Option<&str>,
666    workspaces: &[WorkspaceInfo],
667) -> ProgrammaticResult<Option<WorkspaceScope>> {
668    fallow_engine::workspace_scope::resolve_workspace_scope(
669        root,
670        workspace,
671        changed_workspaces,
672        workspaces,
673    )
674    .map_err(map_workspace_scope_error)
675}
676
677fn map_workspace_scope_error(err: WorkspaceScopeError) -> ProgrammaticError {
678    match err {
679        WorkspaceScopeError::NoWorkspaces {
680            mode,
681            patterns,
682            git_ref,
683        } => map_no_workspaces_error(mode, &patterns, git_ref.as_deref()),
684        WorkspaceScopeError::InvalidPattern { pattern, message } => ProgrammaticError::new(
685            format!("invalid `workspace` pattern '{pattern}': {message}"),
686            2,
687        )
688        .with_code("FALLOW_INVALID_WORKSPACE_PATTERN")
689        .with_context("analysis.workspace"),
690        WorkspaceScopeError::UnmatchedPatterns {
691            patterns,
692            available,
693        } => ProgrammaticError::new(
694            format!(
695                "`workspace` matched no workspace for pattern{}: {}. Available: {available}",
696                if patterns.len() == 1 { "" } else { "s" },
697                quote_owned_patterns(&patterns),
698            ),
699            2,
700        )
701        .with_code("FALLOW_WORKSPACE_PATTERN_UNMATCHED")
702        .with_context("analysis.workspace"),
703        WorkspaceScopeError::EmptyAfterExclusions { .. } => {
704            ProgrammaticError::new("`workspace` excluded every discovered workspace", 2)
705                .with_code("FALLOW_WORKSPACE_SCOPE_EMPTY")
706                .with_context("analysis.workspace")
707        }
708        WorkspaceScopeError::ChangedWorkspacesFailed { git_ref, message } => {
709            ProgrammaticError::new(
710                format!("failed to resolve changed workspaces for ref `{git_ref}`: {message}"),
711                2,
712            )
713            .with_code("FALLOW_CHANGED_WORKSPACES_FAILED")
714            .with_context("analysis.changedWorkspaces")
715        }
716        WorkspaceScopeError::MutuallyExclusive => ProgrammaticError::new(
717            "`workspace` and `changed_workspaces` are mutually exclusive",
718            2,
719        )
720        .with_code("FALLOW_MUTUALLY_EXCLUSIVE_SCOPE")
721        .with_context("analysis.workspace"),
722    }
723}
724
725fn map_no_workspaces_error(
726    mode: WorkspaceScopeMode,
727    patterns: &[String],
728    git_ref: Option<&str>,
729) -> ProgrammaticError {
730    match mode {
731        WorkspaceScopeMode::Workspace => ProgrammaticError::new(
732            format!(
733                "`workspace` {} specified but no workspaces found. Ensure root package.json has a \"workspaces\" field, pnpm-workspace.yaml exists, tsconfig.json has \"references\", or the project sets \"workspaces.patterns\" in the fallow config.",
734                quote_owned_patterns(patterns)
735            ),
736            2,
737        )
738        .with_code("FALLOW_WORKSPACES_NOT_FOUND")
739        .with_context("analysis.workspace"),
740        WorkspaceScopeMode::ChangedWorkspaces => {
741            let git_ref = git_ref.unwrap_or_default();
742            ProgrammaticError::new(
743                format!(
744                    "`changed_workspaces` '{git_ref}' specified but no workspaces found. Ensure root package.json has a \"workspaces\" field, pnpm-workspace.yaml exists, tsconfig.json has \"references\", or the project sets \"workspaces.patterns\" in the fallow config."
745                ),
746                2,
747            )
748            .with_code("FALLOW_WORKSPACES_NOT_FOUND")
749            .with_context("analysis.changedWorkspaces")
750        }
751    }
752}
753
754fn quote_owned_patterns(patterns: &[String]) -> String {
755    patterns
756        .iter()
757        .map(|pattern| format!("'{pattern}'"))
758        .collect::<Vec<_>>()
759        .join(", ")
760}
761
762#[cfg(test)]
763mod tests {
764    use std::process::Command;
765
766    use crate::AnalysisOptions;
767
768    const STACK_PROBE_ENV: &str = "FALLOW_API_STACK_PROBE_CHILD";
769    const STACK_PROBE_TEST: &str =
770        "analysis_context::tests::programmatic_pool_survives_deep_worker_stack_probe";
771
772    // A stack overflow aborts the whole process, so the probe re-runs this
773    // test binary as a child and asserts on its exit status; the same pattern
774    // guards the CLI global pool in crates/cli/src/rayon_pool.rs. The child
775    // drops RUST_MIN_STACK (pinned to 16 MiB in .cargo/config.toml, and
776    // inherited by default-sized rayon workers) so the probe still fails if
777    // the pool loses its explicit stack_size.
778    #[test]
779    fn programmatic_pool_survives_deep_worker_stack_probe() {
780        if std::env::var_os(STACK_PROBE_ENV).is_some() {
781            run_stack_probe_child();
782            return;
783        }
784
785        let current_exe = std::env::current_exe().expect("current test binary should be known");
786        let output = Command::new(current_exe)
787            .arg("--exact")
788            .arg(STACK_PROBE_TEST)
789            .arg("--nocapture")
790            .env(STACK_PROBE_ENV, "1")
791            .env_remove("RUST_MIN_STACK")
792            .output()
793            .expect("stack probe child should start");
794
795        assert!(
796            output.status.success(),
797            "stack probe child failed with status {:?}\nstdout:\n{}\nstderr:\n{}",
798            output.status.code(),
799            String::from_utf8_lossy(&output.stdout),
800            String::from_utf8_lossy(&output.stderr)
801        );
802    }
803
804    fn run_stack_probe_child() {
805        let root = tempfile::tempdir().expect("stack probe needs a temp analysis root");
806        let options = AnalysisOptions {
807            root: Some(root.path().to_path_buf()),
808            threads: Some(1),
809            ..AnalysisOptions::default()
810        };
811        let context = super::resolve_programmatic_analysis_context(&options)
812            .expect("stack probe context should resolve");
813        assert_eq!(context.install(|| consume_stack(5_000)), 5_000);
814    }
815
816    #[inline(never)]
817    fn consume_stack(depth: usize) -> usize {
818        let frame = [0_u8; 2048];
819        std::hint::black_box(&frame);
820        if depth == 0 {
821            usize::from(frame[0])
822        } else {
823            1 + consume_stack(depth - 1)
824        }
825    }
826
827    #[test]
828    fn no_workspaces_error_names_the_config_key() {
829        for (mode, git_ref) in [
830            (super::WorkspaceScopeMode::Workspace, None),
831            (super::WorkspaceScopeMode::ChangedWorkspaces, Some("main")),
832        ] {
833            let err = super::map_no_workspaces_error(mode, &["web".to_owned()], git_ref);
834            assert!(
835                err.message
836                    .contains("\"workspaces.patterns\" in the fallow config"),
837                "{}",
838                err.message
839            );
840        }
841    }
842}