Skip to main content

fallow_engine/
workspace_scope.rs

1//! Workspace scoping owned by the engine boundary.
2
3use std::path::{Path, PathBuf};
4
5use fallow_config::{WorkspaceInfo, WorkspaceOwners};
6use globset::Glob;
7use rustc_hash::FxHashSet;
8
9/// User-facing workspace scope mode.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum WorkspaceScopeMode {
12    /// Explicit workspace package names, paths, or globs.
13    Workspace,
14    /// Git-derived changed workspace scope.
15    ChangedWorkspaces,
16}
17
18/// Typed workspace-scope failure. Surfaces decide their own wording.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum WorkspaceScopeError {
21    /// No workspace metadata exists for the requested scope.
22    NoWorkspaces {
23        /// Which scope mode was requested.
24        mode: WorkspaceScopeMode,
25        /// The workspace patterns the request carried.
26        patterns: Vec<String>,
27        /// The git ref for changed-workspace scoping, when that mode was used.
28        git_ref: Option<String>,
29    },
30    /// A pattern was neither an exact name/path nor a valid glob.
31    InvalidPattern {
32        /// The offending pattern as supplied.
33        pattern: String,
34        /// Glob-compilation error detail.
35        message: String,
36    },
37    /// One or more positive patterns matched no workspace.
38    UnmatchedPatterns {
39        /// The patterns that matched nothing.
40        patterns: Vec<String>,
41        /// Preformatted list of available workspace names for the error text.
42        available: String,
43    },
44    /// Negation removed every selected workspace.
45    EmptyAfterExclusions {
46        /// Preformatted description of the positive patterns (`<all>` when
47        /// none were given).
48        included: String,
49        /// Preformatted description of the exclusion patterns.
50        excluded: String,
51    },
52    /// Git failed while resolving changed workspaces.
53    ChangedWorkspacesFailed {
54        /// The git ref the changed-workspace resolution ran against.
55        git_ref: String,
56        /// Underlying git failure detail.
57        message: String,
58    },
59    /// Both workspace scope modes were requested.
60    MutuallyExclusive,
61}
62
63/// The files that `--workspace`, `--changed-workspaces` and a positional
64/// path select.
65///
66/// A file is in scope when the deepest root that holds it, over the
67/// selected and the excluded roots, is a selected root. A workspace that
68/// the selection does not name, below a selected root, is in scope.
69#[derive(Debug, Clone, Default)]
70pub struct WorkspaceScope {
71    selected: Vec<PathBuf>,
72    excluded: Vec<PathBuf>,
73    owners: WorkspaceOwners,
74}
75
76impl WorkspaceScope {
77    /// A scope of `selected` roots with no excluded root.
78    #[must_use]
79    fn from_roots(selected: Vec<PathBuf>) -> Self {
80        Self::new(selected, Vec::new())
81    }
82
83    fn new(selected: Vec<PathBuf>, excluded: Vec<PathBuf>) -> Self {
84        let owners = Self::owners_of(&selected, &excluded);
85        Self {
86            selected,
87            excluded,
88            owners,
89        }
90    }
91
92    /// The selected roots come first, so an owner below `selected.len()`
93    /// is a selected root, also for a root in both lists.
94    fn owners_of(selected: &[PathBuf], excluded: &[PathBuf]) -> WorkspaceOwners {
95        WorkspaceOwners::from_roots(selected.iter().chain(excluded).map(PathBuf::as_path))
96    }
97
98    /// `scope` with `root` added as a selected root, for the positional
99    /// path of a command. Without a root, `scope` comes back as it is.
100    #[must_use]
101    pub fn with_root(scope: Option<Self>, root: Option<&PathBuf>) -> Option<Self> {
102        let Some(root) = root else {
103            return scope;
104        };
105        let mut scope = scope.unwrap_or_default();
106        scope.selected.push(root.clone());
107        scope.owners = Self::owners_of(&scope.selected, &scope.excluded);
108        Some(scope)
109    }
110
111    /// Whether `path` is in scope.
112    #[must_use]
113    pub fn contains(&self, path: &Path) -> bool {
114        self.owners
115            .owner_of(path)
116            .is_some_and(|owner| owner < self.selected.len())
117    }
118
119    /// The selected roots, for output and for manifest paths. The
120    /// workspace roots come first, in sorted order.
121    #[must_use]
122    pub fn roots(&self) -> &[PathBuf] {
123        &self.selected
124    }
125}
126
127impl From<Vec<PathBuf>> for WorkspaceScope {
128    fn from(selected: Vec<PathBuf>) -> Self {
129        Self::from_roots(selected)
130    }
131}
132
133/// Resolve either explicit or changed workspace scope against discovered metadata.
134///
135/// # Errors
136///
137/// Returns a typed scope error when the selection is invalid or git cannot
138/// resolve changed files.
139pub fn resolve_workspace_scope(
140    root: &Path,
141    workspace: Option<&[String]>,
142    changed_workspaces: Option<&str>,
143    workspaces: &[WorkspaceInfo],
144) -> Result<Option<WorkspaceScope>, WorkspaceScopeError> {
145    match (workspace, changed_workspaces) {
146        (Some(patterns), None) => resolve_workspace_filter(root, patterns, workspaces).map(Some),
147        (None, Some(git_ref)) => resolve_changed_workspaces(root, git_ref, workspaces).map(Some),
148        (None, None) => Ok(None),
149        (Some(_), Some(_)) => Err(WorkspaceScopeError::MutuallyExclusive),
150    }
151}
152
153/// Resolve explicit workspace filters against known workspace metadata.
154///
155/// # Errors
156///
157/// Returns a typed scope error when no workspaces are available, a pattern is
158/// invalid, a positive pattern is unmatched, or negation excludes everything.
159fn resolve_workspace_filter(
160    root: &Path,
161    patterns: &[String],
162    workspaces: &[WorkspaceInfo],
163) -> Result<WorkspaceScope, WorkspaceScopeError> {
164    if workspaces.is_empty() {
165        return Err(WorkspaceScopeError::NoWorkspaces {
166            mode: WorkspaceScopeMode::Workspace,
167            patterns: patterns.to_vec(),
168            git_ref: None,
169        });
170    }
171
172    let rel_paths = workspace_relative_paths(root, workspaces);
173    let (positive, negative) = split_workspace_patterns(patterns);
174    let mut matched = match_positive_workspace_patterns(&positive, workspaces, &rel_paths)?;
175
176    let mut excluded_indices = FxHashSet::default();
177    for pattern in &negative {
178        for index in find_workspace_matches(pattern, workspaces, &rel_paths)? {
179            matched.remove(&index);
180            excluded_indices.insert(index);
181        }
182    }
183
184    if matched.is_empty() {
185        return Err(WorkspaceScopeError::EmptyAfterExclusions {
186            included: describe_included_patterns(&positive),
187            excluded: describe_excluded_patterns(&negative),
188        });
189    }
190
191    let roots_of = |indices: FxHashSet<usize>| {
192        let mut roots = indices
193            .into_iter()
194            .map(|index| workspaces[index].root.clone())
195            .collect::<Vec<_>>();
196        roots.sort();
197        roots
198    };
199    Ok(WorkspaceScope::new(
200        roots_of(matched),
201        roots_of(excluded_indices),
202    ))
203}
204
205/// Resolve workspace roots that contain files changed since `git_ref`.
206///
207/// # Errors
208///
209/// Returns a typed scope error when no workspaces are available or git fails.
210fn resolve_changed_workspaces(
211    root: &Path,
212    git_ref: &str,
213    workspaces: &[WorkspaceInfo],
214) -> Result<WorkspaceScope, WorkspaceScopeError> {
215    if workspaces.is_empty() {
216        return Err(WorkspaceScopeError::NoWorkspaces {
217            mode: WorkspaceScopeMode::ChangedWorkspaces,
218            patterns: Vec::new(),
219            git_ref: Some(git_ref.to_owned()),
220        });
221    }
222
223    let changed_files = crate::changed_files::changed_files(root, git_ref).map_err(|err| {
224        WorkspaceScopeError::ChangedWorkspacesFailed {
225            git_ref: git_ref.to_owned(),
226            message: err.describe(),
227        }
228    })?;
229    let mut roots = workspaces
230        .iter()
231        .filter(|workspace| {
232            changed_files
233                .iter()
234                .any(|file| file.starts_with(&workspace.root))
235        })
236        .map(|workspace| workspace.root.clone())
237        .collect::<Vec<_>>();
238    roots.sort();
239    Ok(WorkspaceScope::from_roots(roots))
240}
241
242fn match_positive_workspace_patterns(
243    positive: &[&str],
244    workspaces: &[WorkspaceInfo],
245    rel_paths: &[String],
246) -> Result<FxHashSet<usize>, WorkspaceScopeError> {
247    let mut matched = FxHashSet::default();
248    let mut unmatched = Vec::new();
249
250    if positive.is_empty() {
251        matched.extend(0..workspaces.len());
252    } else {
253        for pattern in positive {
254            let hits = find_workspace_matches(pattern, workspaces, rel_paths)?;
255            if hits.is_empty() {
256                unmatched.push((*pattern).to_owned());
257            }
258            matched.extend(hits);
259        }
260    }
261
262    if !unmatched.is_empty() {
263        return Err(WorkspaceScopeError::UnmatchedPatterns {
264            patterns: unmatched,
265            available: format_available_workspaces(workspaces),
266        });
267    }
268
269    Ok(matched)
270}
271
272fn find_workspace_matches(
273    pattern: &str,
274    workspaces: &[WorkspaceInfo],
275    rel_paths: &[String],
276) -> Result<Vec<usize>, WorkspaceScopeError> {
277    if let Some(index) = workspaces
278        .iter()
279        .position(|workspace| workspace.name == pattern)
280    {
281        return Ok(vec![index]);
282    }
283    if let Some(index) = rel_paths.iter().position(|path| path == pattern) {
284        return Ok(vec![index]);
285    }
286
287    let glob = Glob::new(pattern).map_err(|err| WorkspaceScopeError::InvalidPattern {
288        pattern: pattern.to_owned(),
289        message: err.to_string(),
290    })?;
291    let matcher = glob.compile_matcher();
292    Ok(workspaces
293        .iter()
294        .enumerate()
295        .filter_map(|(index, workspace)| {
296            (matcher.is_match(&workspace.name) || matcher.is_match(&rel_paths[index]))
297                .then_some(index)
298        })
299        .collect())
300}
301
302fn split_workspace_patterns(patterns: &[String]) -> (Vec<&str>, Vec<&str>) {
303    let mut positive = Vec::new();
304    let mut negative = Vec::new();
305    for pattern in patterns {
306        let trimmed = pattern.trim();
307        if trimmed.is_empty() {
308            continue;
309        }
310        if let Some(negative_pattern) = trimmed.strip_prefix('!') {
311            let negative_pattern = negative_pattern.trim();
312            if !negative_pattern.is_empty() {
313                negative.push(negative_pattern);
314            }
315        } else {
316            positive.push(trimmed);
317        }
318    }
319    (positive, negative)
320}
321
322fn workspace_relative_paths(root: &Path, workspaces: &[WorkspaceInfo]) -> Vec<String> {
323    workspaces
324        .iter()
325        .map(|workspace| relative_workspace_path(&workspace.root, root))
326        .collect()
327}
328
329fn relative_workspace_path(workspace_root: &Path, root: &Path) -> String {
330    workspace_root
331        .strip_prefix(root)
332        .unwrap_or(workspace_root)
333        .to_string_lossy()
334        .replace('\\', "/")
335}
336
337fn describe_included_patterns(positive: &[&str]) -> String {
338    if positive.is_empty() {
339        "<all>".to_owned()
340    } else {
341        quote_patterns(positive)
342    }
343}
344
345fn describe_excluded_patterns(negative: &[&str]) -> String {
346    quote_patterns(negative)
347}
348
349fn quote_patterns(patterns: &[&str]) -> String {
350    patterns
351        .iter()
352        .map(|pattern| format!("'{pattern}'"))
353        .collect::<Vec<_>>()
354        .join(", ")
355}
356
357fn format_available_workspaces(workspaces: &[WorkspaceInfo]) -> String {
358    const MAX_SHOWN: usize = 10;
359    let total = workspaces.len();
360    if total <= MAX_SHOWN {
361        return workspaces
362            .iter()
363            .map(|workspace| workspace.name.as_str())
364            .collect::<Vec<_>>()
365            .join(", ");
366    }
367    let shown = workspaces
368        .iter()
369        .take(MAX_SHOWN)
370        .map(|workspace| workspace.name.as_str())
371        .collect::<Vec<_>>()
372        .join(", ");
373    format!(
374        "{shown}, ... and {} more ({total} total)",
375        total - MAX_SHOWN
376    )
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    fn ws(name: &str, rel: &str) -> WorkspaceInfo {
384        WorkspaceInfo {
385            root: PathBuf::from("/project").join(rel),
386            name: name.to_owned(),
387            is_internal_dependency: false,
388        }
389    }
390
391    #[test]
392    fn workspace_filter_exact_name_short_circuits_glob_metachars() {
393        let workspaces = vec![ws("web-[staging]", "apps/web-staging")];
394        let roots = resolve_workspace_filter(
395            Path::new("/project"),
396            &["web-[staging]".to_owned()],
397            &workspaces,
398        )
399        .expect("resolve workspace");
400
401        assert_eq!(
402            roots.roots(),
403            vec![PathBuf::from("/project/apps/web-staging")]
404        );
405    }
406
407    #[test]
408    fn workspace_filter_globs_against_name_and_path() {
409        let workspaces = vec![
410            ws("@scope/ui", "packages/ui"),
411            ws("admin", "apps/admin"),
412            ws("web", "apps/web"),
413        ];
414        let roots =
415            resolve_workspace_filter(Path::new("/project"), &["apps/*".to_owned()], &workspaces)
416                .expect("resolve workspace");
417
418        assert_eq!(
419            roots.roots(),
420            vec![
421                PathBuf::from("/project/apps/admin"),
422                PathBuf::from("/project/apps/web")
423            ]
424        );
425
426        let roots =
427            resolve_workspace_filter(Path::new("/project"), &["@scope/*".to_owned()], &workspaces)
428                .expect("resolve workspace");
429        assert_eq!(roots.roots(), vec![PathBuf::from("/project/packages/ui")]);
430    }
431
432    #[test]
433    fn workspace_filter_reports_invalid_glob_after_no_literal_match() {
434        let workspaces = vec![ws("web", "apps/web")];
435        let err =
436            resolve_workspace_filter(Path::new("/project"), &["web-[bad".to_owned()], &workspaces)
437                .expect_err("invalid glob");
438
439        assert!(matches!(err, WorkspaceScopeError::InvalidPattern { .. }));
440    }
441
442    #[test]
443    fn workspace_filter_negation_can_exclude_selected_workspaces() {
444        let workspaces = vec![
445            ws("web", "apps/web"),
446            ws("docs", "apps/docs"),
447            ws("legacy", "apps/legacy"),
448        ];
449        let roots = resolve_workspace_filter(
450            Path::new("/project"),
451            &["apps/*".to_owned(), "!apps/legacy".to_owned()],
452            &workspaces,
453        )
454        .expect("resolve workspace");
455
456        assert_eq!(
457            roots.roots(),
458            vec![
459                PathBuf::from("/project/apps/docs"),
460                PathBuf::from("/project/apps/web")
461            ]
462        );
463    }
464
465    #[test]
466    fn workspace_filter_only_negation_starts_from_all_workspaces() {
467        let workspaces = vec![ws("web", "apps/web"), ws("legacy", "apps/legacy")];
468        let roots = resolve_workspace_filter(
469            Path::new("/project"),
470            &["!apps/legacy".to_owned()],
471            &workspaces,
472        )
473        .expect("resolve workspace");
474
475        assert_eq!(roots.roots(), vec![PathBuf::from("/project/apps/web")]);
476    }
477
478    #[test]
479    fn workspace_filter_reports_unmatched_patterns_with_available_list() {
480        let workspaces = vec![ws("web", "apps/web"), ws("docs", "apps/docs")];
481        let err =
482            resolve_workspace_filter(Path::new("/project"), &["missing".to_owned()], &workspaces)
483                .expect_err("unmatched pattern");
484
485        assert_eq!(
486            err,
487            WorkspaceScopeError::UnmatchedPatterns {
488                patterns: vec!["missing".to_owned()],
489                available: "web, docs".to_owned(),
490            }
491        );
492    }
493
494    #[test]
495    fn workspace_filter_reports_empty_after_exclusions() {
496        let workspaces = vec![ws("web", "apps/web")];
497        let err = resolve_workspace_filter(
498            Path::new("/project"),
499            &["!apps/web".to_owned()],
500            &workspaces,
501        )
502        .expect_err("empty selection");
503
504        assert_eq!(
505            err,
506            WorkspaceScopeError::EmptyAfterExclusions {
507                included: "<all>".to_owned(),
508                excluded: "'apps/web'".to_owned(),
509            }
510        );
511    }
512
513    #[test]
514    fn workspace_available_list_truncates_when_above_cap() {
515        let workspaces = (0..15)
516            .map(|index| ws(&format!("pkg-{index}"), &format!("packages/pkg-{index}")))
517            .collect::<Vec<_>>();
518
519        let rendered = format_available_workspaces(&workspaces);
520
521        assert!(rendered.starts_with("pkg-0, pkg-1,"));
522        assert!(rendered.contains("and 5 more"));
523        assert!(rendered.contains("15 total"));
524    }
525
526    #[test]
527    fn changed_workspace_scope_ignores_root_only_changes() {
528        let workspaces = vec![ws("ui", "packages/ui"), ws("api", "packages/api")];
529        let mut changed = FxHashSet::default();
530        changed.insert(PathBuf::from("/project/package.json"));
531        changed.insert(PathBuf::from("/project/pnpm-lock.yaml"));
532
533        let roots = roots_for_changed_files(&workspaces, &changed);
534
535        assert!(roots.is_empty());
536    }
537
538    #[test]
539    fn changed_workspace_scope_maps_files_to_workspace_roots() {
540        let workspaces = vec![
541            ws("ui", "packages/ui"),
542            ws("api", "packages/api"),
543            ws("cli", "packages/cli"),
544        ];
545        let mut changed = FxHashSet::default();
546        changed.insert(PathBuf::from("/project/packages/api/src/b.ts"));
547        changed.insert(PathBuf::from("/project/packages/ui/src/a.ts"));
548
549        let roots = roots_for_changed_files(&workspaces, &changed);
550
551        assert_eq!(
552            roots,
553            vec![
554                PathBuf::from("/project/packages/api"),
555                PathBuf::from("/project/packages/ui")
556            ]
557        );
558    }
559
560    fn roots_for_changed_files(
561        workspaces: &[WorkspaceInfo],
562        changed_files: &FxHashSet<PathBuf>,
563    ) -> Vec<PathBuf> {
564        let mut roots = workspaces
565            .iter()
566            .filter(|workspace| {
567                changed_files
568                    .iter()
569                    .any(|file| file.starts_with(&workspace.root))
570            })
571            .map(|workspace| workspace.root.clone())
572            .collect::<Vec<_>>();
573        roots.sort();
574        roots
575    }
576
577    fn nested_layout() -> Vec<WorkspaceInfo> {
578        vec![
579            ws("web", "apps/web"),
580            ws("plugin", "apps/web/plugin"),
581            ws("docs", "apps/docs"),
582        ]
583    }
584
585    fn scope_of(patterns: &[&str]) -> WorkspaceScope {
586        let patterns = patterns.iter().map(|p| (*p).to_owned()).collect::<Vec<_>>();
587        resolve_workspace_filter(Path::new("/project"), &patterns, &nested_layout()).expect("scope")
588    }
589
590    fn with_root(scope: WorkspaceScope, root: &str) -> WorkspaceScope {
591        WorkspaceScope::with_root(Some(scope), Some(&PathBuf::from(root))).expect("scope")
592    }
593
594    #[test]
595    fn an_excluded_nested_workspace_is_out_of_scope() {
596        let scope = scope_of(&["apps/web", "!apps/web/plugin"]);
597        assert!(scope.contains(Path::new("/project/apps/web/src/a.ts")));
598        assert!(!scope.contains(Path::new("/project/apps/web/plugin/src/a.ts")));
599        assert_eq!(scope.roots(), vec![PathBuf::from("/project/apps/web")]);
600    }
601
602    #[test]
603    fn an_unnamed_nested_workspace_below_a_selected_root_stays_in_scope() {
604        let scope = scope_of(&["apps/web"]);
605        assert!(scope.contains(Path::new("/project/apps/web/plugin/src/a.ts")));
606    }
607
608    #[test]
609    fn a_file_outside_every_selected_root_is_out_of_scope() {
610        let scope = scope_of(&["apps/web"]);
611        assert!(!scope.contains(Path::new("/project/apps/docs/src/a.ts")));
612        assert!(!scope.contains(Path::new("/project/src/root.ts")));
613    }
614
615    #[test]
616    fn a_sibling_with_the_same_name_prefix_is_out_of_scope() {
617        let scope = scope_of(&["apps/web"]);
618        assert!(!scope.contains(Path::new("/project/apps/web-admin/src/a.ts")));
619    }
620
621    #[test]
622    fn a_positional_path_below_an_excluded_workspace_is_in_scope() {
623        let scope = with_root(
624            scope_of(&["apps/web", "!apps/web/plugin"]),
625            "/project/apps/web/plugin/src",
626        );
627        assert!(scope.contains(Path::new("/project/apps/web/plugin/src/a.ts")));
628        assert!(!scope.contains(Path::new("/project/apps/web/plugin/test/a.ts")));
629    }
630
631    #[test]
632    fn a_positional_path_equal_to_an_excluded_root_is_in_scope() {
633        let scope = with_root(
634            scope_of(&["apps/web", "!apps/web/plugin"]),
635            "/project/apps/web/plugin",
636        );
637        assert!(scope.contains(Path::new("/project/apps/web/plugin/src/a.ts")));
638    }
639
640    #[test]
641    fn a_selected_workspace_below_an_excluded_parent_is_in_scope() {
642        let scope = scope_of(&["apps/web/plugin", "!apps/web"]);
643        assert!(scope.contains(Path::new("/project/apps/web/plugin/src/a.ts")));
644        assert!(!scope.contains(Path::new("/project/apps/web/src/a.ts")));
645    }
646
647    #[test]
648    fn a_positional_path_alone_is_a_scope() {
649        let path = PathBuf::from("/project/apps/web");
650        let scope = WorkspaceScope::with_root(None, Some(&path)).expect("scope");
651        assert!(scope.contains(Path::new("/project/apps/web/src/a.ts")));
652        assert!(WorkspaceScope::with_root(None, None).is_none());
653    }
654
655    #[test]
656    fn an_empty_scope_contains_nothing() {
657        assert!(!WorkspaceScope::default().contains(Path::new("/project/apps/web/src/a.ts")));
658    }
659}