Skip to main content

uv_workspace/
workspace.rs

1//! Resolve the current [`ProjectWorkspace`] or [`Workspace`].
2
3use std::assert_matches;
4use std::borrow::Cow;
5use std::collections::{BTreeMap, BTreeSet};
6use std::error::Error;
7use std::fmt;
8use std::fmt::Display;
9use std::hash::BuildHasherDefault;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use uv_distribution_types::RequirementScope;
13
14use glob::{GlobError, MatchOptions, Pattern, PatternError, glob};
15use itertools::Itertools;
16use rustc_hash::{FxHashSet, FxHasher};
17use tracing::{debug, trace, warn};
18
19use uv_cache::Cache;
20use uv_configuration::{ActiveEnvironment, DependencyGroupsWithDefaults, ExcludeDependency};
21use uv_distribution_types::{Index, MinimumLibcVersion, Requirement, RequirementSource};
22use uv_fs::{CWD, Simplified, normalize_path, read_venv_redirect};
23use uv_macros::DebugNoInline;
24use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, GroupName, PackageName};
25use uv_once_map::OnceMap;
26use uv_pep440::VersionSpecifiers;
27use uv_pep508::{MarkerTree, VerbatimUrl};
28use uv_pypi_types::{ConflictError, Conflicts, SupportedEnvironments, VerbatimParsedUrl};
29use uv_static::EnvVars;
30use uv_warnings::warn_user_once;
31
32use crate::dependency_groups::{DependencyGroupError, FlatDependencyGroup, FlatDependencyGroups};
33use crate::pyproject::{
34    BuildConstraintDependency, OverrideDependency, Project, PyProjectToml, PyprojectTomlError,
35    Source, Sources, ToolUvSources, ToolUvWorkspace, WorkspaceReference,
36};
37
38/// The workspace project environment selected by configuration and command-line options.
39#[derive(Debug)]
40pub enum ProjectEnvironmentSelection {
41    /// Use the workspace's default project environment.
42    Default,
43    /// A path selected by `UV_PROJECT_ENVIRONMENT`.
44    Override(PathBuf),
45    /// The active virtual environment selected by `VIRTUAL_ENV` and `--active`.
46    Active(PathBuf),
47}
48
49impl ProjectEnvironmentSelection {
50    /// Select the project environment for a workspace rooted at `install_path`.
51    pub fn from_install_path(install_path: &Path, active: ActiveEnvironment) -> Self {
52        /// Resolve the `UV_PROJECT_ENVIRONMENT` value, if any.
53        fn from_project_environment_variable(install_path: &Path) -> Option<PathBuf> {
54            let value = std::env::var_os(EnvVars::UV_PROJECT_ENVIRONMENT)?;
55            if value.is_empty() {
56                return None;
57            }
58            let path = PathBuf::from(value);
59            Some(if path.is_absolute() {
60                path
61            } else {
62                install_path.join(path)
63            })
64        }
65
66        /// Resolve the `VIRTUAL_ENV` variable, if any.
67        fn from_virtual_env_variable() -> Option<PathBuf> {
68            let value = std::env::var_os(EnvVars::VIRTUAL_ENV)?;
69            if value.is_empty() {
70                return None;
71            }
72            let path = PathBuf::from(value);
73            Some(if path.is_absolute() {
74                path
75            } else {
76                // Unlike `UV_PROJECT_ENVIRONMENT`, resolve this against the current directory.
77                CWD.join(path)
78            })
79        }
80
81        let selection = from_project_environment_variable(install_path)
82            .map(Self::Override)
83            .unwrap_or(Self::Default);
84        let project_environment_path = selection
85            .explicit_path()
86            .map_or_else(|| install_path.join(".venv"), Path::to_path_buf);
87
88        if let Some(from_virtual_env) = from_virtual_env_variable() {
89            let matches_project =
90                uv_fs::is_same_file_allow_missing(&from_virtual_env, &project_environment_path)
91                    .unwrap_or(false)
92                    || read_venv_redirect(&project_environment_path).is_ok_and(|target| {
93                        uv_fs::is_same_file_allow_missing(&from_virtual_env, &target)
94                            .unwrap_or(false)
95                    });
96            match active {
97                ActiveEnvironment::Prefer => {
98                    if !matches_project {
99                        debug!(
100                            "Using active virtual environment `{}` instead of project environment `{}`",
101                            from_virtual_env.user_display(),
102                            project_environment_path.user_display()
103                        );
104                    }
105                    return Self::Active(from_virtual_env);
106                }
107                ActiveEnvironment::Ignore => {}
108                ActiveEnvironment::Warn if !matches_project => {
109                    warn_user_once!(
110                        "`VIRTUAL_ENV={}` does not match the project environment path `{}` and will be ignored; use `--active` to target the active environment instead",
111                        from_virtual_env.user_display(),
112                        project_environment_path.user_display()
113                    );
114                }
115                ActiveEnvironment::Warn => {}
116            }
117        } else if active == ActiveEnvironment::Prefer {
118            debug!(
119                "Use of the active virtual environment was requested, but `VIRTUAL_ENV` is not set"
120            );
121        }
122
123        selection
124    }
125
126    /// Returns `true` if the workspace's default project environment was selected.
127    pub fn is_default(&self) -> bool {
128        matches!(self, Self::Default)
129    }
130
131    /// Returns the explicitly selected environment path, if any.
132    pub fn explicit_path(&self) -> Option<&Path> {
133        match self {
134            Self::Default => None,
135            Self::Override(path) | Self::Active(path) => Some(path),
136        }
137    }
138}
139
140type WorkspaceMembers = Arc<BTreeMap<PackageName, WorkspaceMember>>;
141type FxOnceMap<K, V> = OnceMap<K, V, BuildHasherDefault<FxHasher>>;
142type CachedWorkspaceResult = Result<CachedWorkspace, WorkspaceError>;
143
144/// A workspace and the project at the cache key's path, if it is a project root.
145#[derive(Debug, Clone)]
146struct CachedWorkspace {
147    workspace: Arc<Workspace>,
148    /// `None` for a virtual workspace root without a project.
149    project_name: Option<PackageName>,
150}
151
152/// Cache for workspace discovery.
153///
154/// Avoid re-reading the `pyproject.toml` files in a workspace for each member by caching the
155/// workspace members by their workspace root.
156///
157/// The cache is indexed both by the workspace root and by the path of each workspace member.
158///
159/// The cache makes assumptions about [`DiscoveryOptions`]:
160/// * `stop_discovery_at` is only used for isolation workspaces in the cache. Otherwise, we avoid
161///   traversing into an external cache if `cache` is accidentally included in the workspace member
162///   glob.
163/// * Only [`MemberDiscovery::All`] results are stored. Successful results can be reused for
164///   [`MemberDiscovery::Existing`], which discovers the same members when none are missing.
165#[derive(Debug, Default, Clone)]
166pub struct WorkspaceCache {
167    workspaces: Arc<FxOnceMap<PathBuf, CachedWorkspaceResult>>,
168}
169
170impl WorkspaceCache {
171    /// Insert a workspace discovery into the cache that may have succeeded or failed.
172    ///
173    /// Once an error is inserted, it will be returned to all future callers that query the failed
174    /// query path.
175    fn insert(&self, result: Result<Arc<Workspace>, WorkspaceError>, install_path: &Path) {
176        match result {
177            Ok(workspace) => {
178                let mut root_project_name = None;
179                for (name, package) in workspace.packages.iter() {
180                    // Publish the root once below, even when it is also a project member.
181                    if package.root == workspace.install_path {
182                        root_project_name = Some(name.clone());
183                        continue;
184                    }
185                    // Historically, upward workspace discovery stopped at an intermediate
186                    // `pyproject.toml`, so don't map this member to the outer workspace in that
187                    // case.
188                    // See: <https://github.com/astral-sh/uv/issues/19916>
189                    if has_intermediate_pyproject(&workspace.install_path, &package.root) {
190                        continue;
191                    }
192                    self.workspaces.done(
193                        package.root.clone(),
194                        Ok(CachedWorkspace {
195                            workspace: workspace.clone(),
196                            project_name: Some(name.clone()),
197                        }),
198                    );
199                }
200                self.workspaces.done(
201                    workspace.install_path.clone(),
202                    Ok(CachedWorkspace {
203                        workspace,
204                        project_name: root_project_name,
205                    }),
206                );
207            }
208            Err(err) => {
209                self.workspaces.done(install_path.to_path_buf(), Err(err));
210            }
211        }
212    }
213
214    /// Register workspace discovery for a root, or wait for an in-flight discovery.
215    ///
216    /// Calling this function ensures that - given a workspace root - the discovery is only done by
217    /// one thread.
218    async fn register_or_wait(
219        &self,
220        workspace_root: &PathBuf,
221    ) -> Option<Result<Arc<Workspace>, WorkspaceError>> {
222        self.workspaces
223            .register_or_wait(workspace_root)
224            .await
225            .map(|result| result.map(|cached| cached.workspace))
226    }
227
228    /// Get the cached workspace, if any, from the path to the workspace root or to a member root.
229    ///
230    /// A successful complete discovery can satisfy [`MemberDiscovery::Existing`]. Cached errors
231    /// cannot, since `Existing` intentionally tolerates missing workspace members.
232    fn get(
233        &self,
234        path: &Path,
235        member_discovery: &MemberDiscovery,
236    ) -> Option<CachedWorkspaceResult> {
237        match member_discovery {
238            MemberDiscovery::All => self.workspaces.get(path),
239            MemberDiscovery::Existing => match self.workspaces.get(path) {
240                Some(Ok(workspace)) => Some(Ok(workspace)),
241                Some(Err(_)) | None => None,
242            },
243            MemberDiscovery::None | MemberDiscovery::Ignore(_) => None,
244        }
245    }
246
247    /// Remove all cached workspace entries for the given workspace root. Used before modifying the
248    /// workspace.
249    ///
250    /// Contract: There are no parallel workspace operations, this is the only thread operating on
251    /// workspaces.
252    fn invalidate_workspace(&self, workspace: &Workspace) {
253        if let Some(Ok(cached)) = self.workspaces.remove(workspace.install_path()) {
254            for member in cached.workspace.packages.values() {
255                self.workspaces.remove(&member.root);
256            }
257        }
258    }
259}
260
261/// Returns `true` when a `pyproject.toml` sits between the member project directory and the
262/// workspace root.
263fn has_intermediate_pyproject(workspace_root: &Path, project_dir: &Path) -> bool {
264    if project_dir == workspace_root {
265        return false;
266    }
267
268    let Ok(_) = project_dir.strip_prefix(workspace_root) else {
269        return false;
270    };
271
272    project_dir
273        .ancestors()
274        .skip(1)
275        .take_while(|ancestor| *ancestor != workspace_root)
276        .any(|ancestor| ancestor.join("pyproject.toml").is_file())
277}
278
279#[derive(Debug, Clone)]
280pub struct WorkspaceError(Arc<WorkspaceErrorKind>);
281
282impl AsRef<WorkspaceErrorKind> for WorkspaceError {
283    fn as_ref(&self) -> &WorkspaceErrorKind {
284        &self.0
285    }
286}
287
288impl<T> From<T> for WorkspaceError
289where
290    T: Into<WorkspaceErrorKind>,
291{
292    fn from(error: T) -> Self {
293        Self(Arc::new(error.into()))
294    }
295}
296
297impl Display for WorkspaceError {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        Display::fmt(&self.0, f)
300    }
301}
302
303impl Error for WorkspaceError {
304    fn source(&self) -> Option<&(dyn Error + 'static)> {
305        self.0.source()
306    }
307}
308
309#[derive(thiserror::Error, DebugNoInline)]
310pub enum WorkspaceErrorKind {
311    // Workspace structure errors.
312    #[error("No `pyproject.toml` found in current directory or any parent directory")]
313    MissingPyprojectToml,
314    #[error("Workspace member `{}` is missing a `pyproject.toml` (matches: `{}`)", _0.simplified_display(), _1)]
315    MissingPyprojectTomlMember(PathBuf, String),
316    #[error("No `project` table found in: {}", _0.simplified_display())]
317    MissingProject(PathBuf),
318    #[error("No workspace found for: {}", _0.simplified_display())]
319    MissingWorkspace(PathBuf),
320    #[error("The project is marked as unmanaged: {}", _0.simplified_display())]
321    NonWorkspace(PathBuf),
322    #[error("Nested workspaces are not supported, but workspace member has a `tool.uv.workspace` table: {}", _0.simplified_display())]
323    NestedWorkspace(PathBuf),
324    #[error("The workspace does not have a member {}: {}", _0, _1.simplified_display())]
325    NoSuchMember(PackageName, PathBuf),
326    #[error("Two workspace members are both named `{name}`: `{}` and `{}`", first.simplified_display(), second.simplified_display())]
327    DuplicatePackage {
328        name: PackageName,
329        first: PathBuf,
330        second: PathBuf,
331    },
332    #[error("`pyproject.toml` section is declared as dynamic, but must be static: `{0}`")]
333    DynamicNotAllowed(&'static str),
334    #[error(
335        "Workspace member `{}` was requested as both `editable = true` and `editable = false`",
336        _0
337    )]
338    EditableConflict(PackageName),
339    #[error("Failed to find directories for glob `{0}`")]
340    Pattern(String, #[source] PatternError),
341    // Syntax and other errors.
342    #[error("Directory walking failed for `tool.uv.workspace.members` glob `{0}`")]
343    GlobWalk(String, #[source] GlobError),
344    #[error(transparent)]
345    Io(#[from] std::io::Error),
346    #[error("Failed to parse: {}", _0.user_display())]
347    Toml(PathBuf, #[source] Box<PyprojectTomlError>),
348    #[error(transparent)]
349    Conflicts(#[from] ConflictError),
350    // On Windows and Unix, this is not a regular IO failure, but requires e.g. `current_dir` to
351    // fail.
352    #[error("Failed to normalize workspace member path")]
353    Normalize(#[source] std::io::Error),
354}
355
356/// An error selecting the default dependency groups for a project.
357#[derive(Debug, thiserror::Error)]
358pub enum DefaultGroupsError {
359    #[error("Package `{0}` not found in workspace")]
360    MissingPackage(PackageName),
361    #[error(
362        "Default group `{0}` (from `tool.uv.default-groups`) is not defined in the project's `dependency-groups` table"
363    )]
364    MissingGroup(GroupName),
365}
366
367#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
368pub enum MemberDiscovery {
369    /// Discover all workspace members.
370    #[default]
371    All,
372    /// Discover workspace members that are present, but ignore missing members.
373    Existing,
374    /// Don't discover any workspace members.
375    None,
376    /// Discover workspace members, but ignore the given paths.
377    Ignore(BTreeSet<PathBuf>),
378}
379
380#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
381pub struct DiscoveryOptions {
382    /// The path to stop discovery at.
383    ///
384    /// Assumption: This is only used for directories in the cache to avoid them escaping the cache.
385    /// If you want to use it for other cases too, you need to also update the cache handling in
386    /// the workspace discovery glob walking.
387    pub stop_discovery_at: Option<PathBuf>,
388    /// The strategy to use when discovering workspace members.
389    pub members: MemberDiscovery,
390}
391
392/// The declaration contributing a workspace Python requirement.
393#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
394pub enum RequiresPythonDeclaration {
395    /// A member's project requirement or dependency group requirement.
396    Member(PackageName, Option<GroupName>),
397    /// A dependency group on a workspace root without a `[project]` table.
398    Workspace(GroupName),
399}
400
401impl std::fmt::Display for RequiresPythonDeclaration {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        match self {
404            Self::Member(package, Some(group)) => write!(f, "{package}:{group}"),
405            Self::Member(package, None) => package.fmt(f),
406            Self::Workspace(group) => write!(f, "workspace:{group}"),
407        }
408    }
409}
410
411pub type RequiresPythonSources = BTreeMap<RequiresPythonDeclaration, VersionSpecifiers>;
412
413pub type Editability = Option<bool>;
414
415/// A workspace, consisting of a root directory and members. See [`ProjectWorkspace`].
416#[derive(Debug, Clone)]
417#[cfg_attr(test, derive(serde::Serialize))]
418pub struct Workspace {
419    /// The path to the workspace root.
420    ///
421    /// The workspace root is the directory containing the top level `pyproject.toml` with
422    /// the `uv.tool.workspace`, or the `pyproject.toml` in an implicit single workspace project.
423    install_path: PathBuf,
424    /// The members of the workspace.
425    packages: WorkspaceMembers,
426    /// The workspace members that are required by other members, and whether they were requested
427    /// as editable.
428    required_members: BTreeMap<PackageName, Editability>,
429    /// The sources table from the workspace `pyproject.toml`.
430    ///
431    /// This table is overridden by the project sources.
432    sources: BTreeMap<PackageName, Sources>,
433    /// The index table from the workspace `pyproject.toml`.
434    ///
435    /// This table is overridden by the project indexes.
436    indexes: Vec<Index>,
437    /// The `pyproject.toml` of the workspace root.
438    pyproject_toml: PyProjectToml,
439}
440
441impl Workspace {
442    /// Find the workspace containing the given path.
443    ///
444    /// Unlike the [`ProjectWorkspace`] discovery, this does not require a current project. It also
445    /// always uses absolute path, i.e., this method only supports discovering the main workspace.
446    ///
447    /// Steps of workspace discovery: Start by looking at the closest `pyproject.toml`:
448    /// * If it's an explicit workspace root: Collect workspace from this root, we're done.
449    /// * If it's also not a project: Error, must be either a workspace root or a project.
450    /// * Otherwise, try to find an explicit workspace root above:
451    ///   * If an explicit workspace root exists: Collect workspace from this root, we're done.
452    ///   * If there is no explicit workspace: We have a single project workspace, we're done.
453    ///
454    /// Note that there are two kinds of workspace roots: projects, and non-project roots.
455    /// The non-project roots lack a `[project]` table, and so are not themselves projects, as in:
456    /// ```toml
457    /// [tool.uv.workspace]
458    /// members = ["packages/*"]
459    ///
460    /// [tool.uv]
461    /// dev-dependencies = ["ruff"]
462    /// ```
463    pub async fn discover(
464        path: &Path,
465        options: &DiscoveryOptions,
466        cache: &Cache,
467        workspace_cache: &WorkspaceCache,
468    ) -> Result<Arc<Self>, WorkspaceError> {
469        let path = std::path::absolute(path)
470            .map_err(WorkspaceErrorKind::Normalize)?
471            .clone();
472        let path = normalize_path(&path);
473
474        let project_path = path
475            .ancestors()
476            .find(|path| path.join("pyproject.toml").is_file())
477            .ok_or(WorkspaceErrorKind::MissingPyprojectToml)?
478            .to_path_buf();
479
480        // Fast path: The workspace was already fully discovered.
481        // It's possible that there are two separate discoveries for the same workspace going on
482        // at the same time from different roots, both failing this check. These cases are fine, we
483        // synchronize them after finding the workspace root and allow only one of them to perform
484        // the full discovery.
485        if let Some(workspace) = workspace_cache.get(&project_path, &options.members) {
486            return workspace.map(|cached| cached.workspace);
487        }
488
489        let pyproject_path = project_path.join("pyproject.toml");
490        let contents = fs_err::tokio::read_to_string(&pyproject_path).await?;
491        let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
492            .map_err(|err| WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err)))?;
493
494        // Check if the project is explicitly marked as unmanaged.
495        if pyproject_toml
496            .tool
497            .as_ref()
498            .and_then(|tool| tool.uv.as_ref())
499            .and_then(|uv| uv.managed)
500            == Some(false)
501        {
502            debug!(
503                "Project `{}` is marked as unmanaged",
504                project_path.simplified_display()
505            );
506            return Err(WorkspaceError::from(WorkspaceErrorKind::NonWorkspace(
507                project_path,
508            )));
509        }
510
511        // Check if the current project is also an explicit workspace root.
512        let explicit_root = pyproject_toml
513            .tool
514            .as_ref()
515            .and_then(|tool| tool.uv.as_ref())
516            .and_then(|uv| uv.workspace.as_ref())
517            .map(|workspace| {
518                (
519                    project_path.clone(),
520                    workspace.clone(),
521                    pyproject_toml.clone(),
522                )
523            });
524
525        let (workspace_root, workspace_definition, workspace_pyproject_toml) =
526            if let Some(workspace) = explicit_root {
527                // We have found the explicit root immediately.
528                workspace
529            } else if pyproject_toml.project.is_none() {
530                // Without a project, it can't be an implicit root
531                return Err(WorkspaceError::from(WorkspaceErrorKind::MissingProject(
532                    pyproject_path,
533                )));
534            } else if let Some(workspace) = find_workspace(&project_path, options, cache).await? {
535                // We have found an explicit root above.
536                workspace
537            } else {
538                // Support implicit single project workspaces.
539                (
540                    project_path.clone(),
541                    ToolUvWorkspace::default(),
542                    pyproject_toml.clone(),
543                )
544            };
545
546        if options.members == MemberDiscovery::All {
547            // Ensure that workspace discovery runs only once for any given workspace root.
548            // If two threads start at different packages at the same time, they only read their
549            // package `pyproject.toml` and the workspace root `pyproject.toml` before arriving
550            // here. At this point, only one thread can continue and the other waits, then uses the
551            // cached workspace.
552            if let Some(workspace) = workspace_cache.register_or_wait(&workspace_root).await {
553                return workspace;
554            }
555        }
556
557        debug!(
558            "Found workspace root: {}",
559            workspace_root.simplified_display()
560        );
561
562        // Unlike in `ProjectWorkspace` discovery, we might be in a non-project root without
563        // being in any specific project.
564        let current_project = pyproject_toml
565            .project
566            .clone()
567            .map(|project| WorkspaceMember {
568                root: project_path,
569                project,
570                pyproject_toml,
571            });
572
573        let result = Self::build(
574            workspace_root.clone(),
575            workspace_definition,
576            workspace_pyproject_toml,
577            current_project,
578            options,
579            cache,
580        )
581        .await;
582        if options.members == MemberDiscovery::All {
583            workspace_cache.insert(result.clone(), &workspace_root);
584        }
585        result
586    }
587
588    /// Set the current project to the given workspace member.
589    ///
590    /// Returns `None` if the package is not part of the workspace.
591    fn with_current_project(
592        self: Arc<Self>,
593        package_name: PackageName,
594    ) -> Option<ProjectWorkspace> {
595        let member = self.packages.get(&package_name)?;
596        Some(ProjectWorkspace {
597            project_root: member.root().clone(),
598            project_name: package_name,
599            workspace: self,
600        })
601    }
602
603    /// Set the [`ProjectWorkspace`] for a given workspace member.
604    ///
605    /// Assumes that the project name is unchanged in the updated [`PyProjectToml`], and that the
606    /// caller holds the only reference to this workspace (to avoid a situation where another part
607    /// of uv still holds a reference to the old workspace structure).
608    fn update_member(
609        self: Arc<Self>,
610        package_name: &PackageName,
611        pyproject_toml: PyProjectToml,
612    ) -> Result<Option<Arc<Self>>, WorkspaceError> {
613        debug_assert_eq!(
614            Arc::strong_count(&self),
615            1,
616            "cannot modify workspace still in use",
617        );
618
619        let slf = Arc::unwrap_or_clone(self);
620        let mut packages = slf.packages;
621
622        let Some(member) = Arc::make_mut(&mut packages).get_mut(package_name) else {
623            return Ok(None);
624        };
625
626        if member.root == slf.install_path {
627            // If the member is also the workspace root, update _both_ the member entry and the
628            // root `pyproject.toml`.
629            let workspace_pyproject_toml = pyproject_toml.clone();
630
631            // Refresh the workspace sources.
632            let workspace_sources = workspace_pyproject_toml
633                .tool
634                .clone()
635                .and_then(|tool| tool.uv)
636                .and_then(|uv| uv.sources)
637                .map(ToolUvSources::into_inner)
638                .unwrap_or_default();
639
640            // Set the `pyproject.toml` for the member.
641            member.pyproject_toml = pyproject_toml;
642
643            // Recompute required_members with the updated data
644            let required_members = Self::collect_required_members(
645                &packages,
646                &workspace_sources,
647                &workspace_pyproject_toml,
648            )?;
649
650            let workspace = Self {
651                pyproject_toml: workspace_pyproject_toml,
652                sources: workspace_sources,
653                packages,
654                required_members,
655                ..slf
656            };
657            Ok(Some(Arc::new(workspace)))
658        } else {
659            // Set the `pyproject.toml` for the member.
660            member.pyproject_toml = pyproject_toml;
661
662            // Recompute required_members with the updated member data
663            let required_members =
664                Self::collect_required_members(&packages, &slf.sources, &slf.pyproject_toml)?;
665
666            let workspace = Self {
667                packages,
668                required_members,
669                ..slf
670            };
671            Ok(Some(Arc::new(workspace)))
672        }
673    }
674
675    /// Returns `true` if the workspace has a non-project root.
676    pub fn is_non_project(&self) -> bool {
677        !self
678            .packages
679            .values()
680            .any(|member| *member.root() == self.install_path)
681    }
682
683    /// Returns the set of all workspace members.
684    pub fn members_requirements(&self) -> impl Iterator<Item = Requirement> + '_ {
685        self.packages.iter().filter_map(|(name, member)| {
686            let url = VerbatimUrl::from_absolute_path(&member.root).expect("path is valid URL");
687            Some(Requirement {
688                name: member.pyproject_toml.project.as_ref()?.name.clone(),
689                extras: Box::new([]),
690                groups: Box::new([]),
691                marker: MarkerTree::TRUE,
692                source: if member
693                    .pyproject_toml()
694                    .is_package(!self.is_required_member(name))
695                {
696                    RequirementSource::Directory {
697                        install_path: member.root.clone().into_boxed_path(),
698                        editable: Some(
699                            self.required_members
700                                .get(name)
701                                .copied()
702                                .flatten()
703                                .unwrap_or(true),
704                        ),
705                        r#virtual: Some(false),
706                        url,
707                    }
708                } else {
709                    RequirementSource::Directory {
710                        install_path: member.root.clone().into_boxed_path(),
711                        editable: Some(false),
712                        r#virtual: Some(true),
713                        url,
714                    }
715                },
716                scope: RequirementScope::Global,
717                origin: None,
718            })
719        })
720    }
721
722    /// The workspace members that are required my another member of the workspace.
723    pub fn required_members(&self) -> &BTreeMap<PackageName, Editability> {
724        &self.required_members
725    }
726
727    /// Compute the workspace members that are required by another member of the workspace, and
728    /// determine whether they should be installed as editable or non-editable.
729    ///
730    /// N.B. this checks if a workspace member is required by inspecting `tool.uv.source` entries,
731    /// but does not actually check if the source is _used_, which could result in false positives
732    /// but is easier to compute.
733    fn collect_required_members(
734        packages: &BTreeMap<PackageName, WorkspaceMember>,
735        sources: &BTreeMap<PackageName, Sources>,
736        pyproject_toml: &PyProjectToml,
737    ) -> Result<BTreeMap<PackageName, Editability>, WorkspaceError> {
738        let mut required_members = BTreeMap::new();
739
740        for (package, sources) in sources
741            .iter()
742            .filter(|(name, _)| {
743                pyproject_toml
744                    .project
745                    .as_ref()
746                    .is_none_or(|project| project.name != **name)
747            })
748            .chain(
749                packages
750                    .iter()
751                    .filter_map(|(name, member)| {
752                        member
753                            .pyproject_toml
754                            .tool
755                            .as_ref()
756                            .and_then(|tool| tool.uv.as_ref())
757                            .and_then(|uv| uv.sources.as_ref())
758                            .map(ToolUvSources::inner)
759                            .map(move |sources| {
760                                sources
761                                    .iter()
762                                    .filter(move |(source_name, _)| name != *source_name)
763                            })
764                    })
765                    .flatten(),
766            )
767        {
768            for source in sources.iter() {
769                let Source::Workspace {
770                    workspace: WorkspaceReference::Bool(true),
771                    editable,
772                    ..
773                } = &source
774                else {
775                    continue;
776                };
777                let existing = required_members.insert(package.clone(), *editable);
778                if let Some(Some(existing)) = existing {
779                    if let Some(editable) = editable {
780                        // If there are conflicting `editable` values, raise an error.
781                        if existing != *editable {
782                            return Err(WorkspaceError::from(
783                                WorkspaceErrorKind::EditableConflict(package.clone()),
784                            ));
785                        }
786                    }
787                }
788            }
789        }
790
791        Ok(required_members)
792    }
793
794    /// Whether a given workspace member is required by another member.
795    fn is_required_member(&self, name: &PackageName) -> bool {
796        self.required_members().contains_key(name)
797    }
798
799    /// Returns the set of all workspace member dependency groups.
800    pub fn group_requirements(&self) -> impl Iterator<Item = Requirement> + '_ {
801        self.packages.iter().filter_map(|(name, member)| {
802            let url = VerbatimUrl::from_absolute_path(&member.root).expect("path is valid URL");
803
804            let groups = {
805                let mut groups = member
806                    .pyproject_toml
807                    .dependency_groups
808                    .as_ref()
809                    .map(|groups| groups.keys().cloned().collect::<Vec<_>>())
810                    .unwrap_or_default();
811                if member
812                    .pyproject_toml
813                    .tool
814                    .as_ref()
815                    .and_then(|tool| tool.uv.as_ref())
816                    .and_then(|uv| uv.dev_dependencies.as_ref())
817                    .is_some()
818                {
819                    groups.push(DEV_DEPENDENCIES.clone());
820                    groups.sort_unstable();
821                }
822                groups
823            };
824            if groups.is_empty() {
825                return None;
826            }
827
828            let value = self.required_members.get(name);
829            let is_required_member = value.is_some();
830            let editability = value.copied().flatten();
831
832            Some(Requirement {
833                name: member.pyproject_toml.project.as_ref()?.name.clone(),
834                extras: Box::new([]),
835                groups: groups.into_boxed_slice(),
836                marker: MarkerTree::TRUE,
837                source: if member.pyproject_toml().is_package(!is_required_member) {
838                    RequirementSource::Directory {
839                        install_path: member.root.clone().into_boxed_path(),
840                        editable: Some(editability.unwrap_or(true)),
841                        r#virtual: Some(false),
842                        url,
843                    }
844                } else {
845                    RequirementSource::Directory {
846                        install_path: member.root.clone().into_boxed_path(),
847                        editable: Some(false),
848                        r#virtual: Some(true),
849                        url,
850                    }
851                },
852                scope: RequirementScope::Global,
853                origin: None,
854            })
855        })
856    }
857
858    /// Returns the set of supported environments for the workspace.
859    pub fn environments(&self) -> Option<&SupportedEnvironments> {
860        self.pyproject_toml
861            .tool
862            .as_ref()
863            .and_then(|tool| tool.uv.as_ref())
864            .and_then(|uv| uv.environments.as_ref())
865    }
866
867    /// Returns the set of required platforms for the workspace.
868    pub fn required_environments(&self) -> Option<&SupportedEnvironments> {
869        self.pyproject_toml
870            .tool
871            .as_ref()
872            .and_then(|tool| tool.uv.as_ref())
873            .and_then(|uv| uv.required_environments.as_ref())
874    }
875
876    /// Returns the workspace's libc baselines and exclusions.
877    pub fn minimum_libc_version(&self) -> Option<MinimumLibcVersion> {
878        self.pyproject_toml
879            .tool
880            .as_ref()
881            .and_then(|tool| tool.uv.as_ref())
882            .and_then(|uv| uv.minimum_libc_version)
883    }
884
885    /// Returns the set of conflicts for the workspace.
886    pub fn conflicts(&self) -> Result<Conflicts, WorkspaceError> {
887        let mut conflicting = Conflicts::empty();
888        if self.is_non_project()
889            && let Some(root_conflicts) = self
890                .pyproject_toml
891                .tool
892                .as_ref()
893                .and_then(|tool| tool.uv.as_ref())
894                .and_then(|uv| uv.conflicts.as_ref())
895        {
896            let mut root_conflicts = root_conflicts.to_conflicts()?;
897            conflicting.append(&mut root_conflicts);
898        }
899        for member in self.packages.values() {
900            conflicting.append(&mut member.pyproject_toml.conflicts()?);
901        }
902        Ok(conflicting)
903    }
904
905    /// Returns Python requirements from workspace members and selected workspace-root groups.
906    pub fn requires_python(
907        &self,
908        groups: &DependencyGroupsWithDefaults,
909    ) -> Result<RequiresPythonSources, DependencyGroupError> {
910        let mut requires = RequiresPythonSources::new();
911        for (name, member) in self.packages() {
912            // Get the top-level requires-python for this package, which is always active
913            //
914            // Arguably we could check groups.prod() to disable this, since, the requires-python
915            // of the project is *technically* not relevant if you're doing `--only-group`, but,
916            // that would be a big surprising change, so let's *not* do that until someone asks!
917            let top_requires = member
918                .pyproject_toml()
919                .project
920                .as_ref()
921                .and_then(|project| project.requires_python.as_ref())
922                .map(|requires_python| {
923                    (
924                        RequiresPythonDeclaration::Member(name.to_owned(), None),
925                        requires_python.clone(),
926                    )
927                });
928            requires.extend(top_requires);
929
930            // Get the requires-python for each enabled group on this package
931            // We need to do full flattening here because include-group can transfer requires-python
932            let dependency_groups =
933                FlatDependencyGroups::from_pyproject_toml(member.root(), &member.pyproject_toml)?;
934            let group_requires =
935                dependency_groups
936                    .into_iter()
937                    .filter_map(move |(group_name, flat_group)| {
938                        if groups.contains(&group_name) {
939                            flat_group.requires_python.map(|requires_python| {
940                                (
941                                    RequiresPythonDeclaration::Member(
942                                        name.to_owned(),
943                                        Some(group_name),
944                                    ),
945                                    requires_python,
946                                )
947                            })
948                        } else {
949                            None
950                        }
951                    });
952            requires.extend(group_requires);
953        }
954        for (group, flat_group) in self.workspace_dependency_groups()? {
955            if groups.contains(&group)
956                && let Some(requires_python) = flat_group.requires_python
957            {
958                requires.insert(RequiresPythonDeclaration::Workspace(group), requires_python);
959            }
960        }
961        Ok(requires)
962    }
963
964    /// Returns any requirements that are exclusive to the workspace root, i.e., not included in
965    /// any of the workspace members.
966    ///
967    /// For now, there are no such requirements.
968    pub fn requirements(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
969        Vec::new()
970    }
971
972    /// Returns any dependency groups that are exclusive to the workspace root, i.e., not included
973    /// in any of the workspace members.
974    ///
975    /// For workspaces with non-`[project]` roots, returns the dependency groups defined in the
976    /// corresponding `pyproject.toml`.
977    ///
978    /// Otherwise, returns an empty list.
979    pub fn workspace_dependency_groups(
980        &self,
981    ) -> Result<BTreeMap<GroupName, FlatDependencyGroup>, DependencyGroupError> {
982        if self
983            .packages
984            .values()
985            .any(|member| *member.root() == self.install_path)
986        {
987            // If the workspace has an explicit root, the root is a member, so we don't need to
988            // include any root-only requirements.
989            Ok(BTreeMap::default())
990        } else {
991            // Otherwise, return the dependency groups in the non-project workspace root.
992            let dependency_groups = FlatDependencyGroups::from_pyproject_toml(
993                &self.install_path,
994                &self.pyproject_toml,
995            )?;
996            Ok(dependency_groups.into_inner())
997        }
998    }
999
1000    /// Returns the set of overrides for the workspace.
1001    pub fn overrides(&self) -> Vec<OverrideDependency> {
1002        let Some(overrides) = self
1003            .pyproject_toml
1004            .tool
1005            .as_ref()
1006            .and_then(|tool| tool.uv.as_ref())
1007            .and_then(|uv| uv.override_dependencies.as_ref())
1008        else {
1009            return vec![];
1010        };
1011        overrides.clone()
1012    }
1013
1014    /// Returns the set of dependency exclusions for the workspace.
1015    pub fn exclude_dependencies(&self) -> Vec<ExcludeDependency> {
1016        let Some(excludes) = self
1017            .pyproject_toml
1018            .tool
1019            .as_ref()
1020            .and_then(|tool| tool.uv.as_ref())
1021            .and_then(|uv| uv.exclude_dependencies.as_ref())
1022        else {
1023            return vec![];
1024        };
1025        excludes.clone()
1026    }
1027
1028    /// Returns the set of constraints for the workspace.
1029    pub fn constraints(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
1030        let Some(constraints) = self
1031            .pyproject_toml
1032            .tool
1033            .as_ref()
1034            .and_then(|tool| tool.uv.as_ref())
1035            .and_then(|uv| uv.constraint_dependencies.as_ref())
1036        else {
1037            return vec![];
1038        };
1039        constraints.clone()
1040    }
1041
1042    /// Returns the set of build constraints for the workspace.
1043    pub fn build_constraints(&self) -> Vec<BuildConstraintDependency> {
1044        let Some(build_constraints) = self
1045            .pyproject_toml
1046            .tool
1047            .as_ref()
1048            .and_then(|tool| tool.uv.as_ref())
1049            .and_then(|uv| uv.build_constraint_dependencies.as_ref())
1050        else {
1051            return vec![];
1052        };
1053        build_constraints.clone()
1054    }
1055
1056    /// The path to the workspace root, the directory containing the top level `pyproject.toml` with
1057    /// the `uv.tool.workspace`, or the `pyproject.toml` in an implicit single workspace project.
1058    pub fn install_path(&self) -> &PathBuf {
1059        &self.install_path
1060    }
1061
1062    /// The workspace project environment selection.
1063    ///
1064    /// If `UV_PROJECT_ENVIRONMENT` is set, it will take precedence. If a relative path is provided,
1065    /// it is resolved relative to the install path.
1066    ///
1067    /// If `active` is [`ActiveEnvironment::Prefer`], the `VIRTUAL_ENV` variable will be preferred.
1068    /// If it is [`ActiveEnvironment::Ignore`], warnings about mismatches between the active
1069    /// environment and the project environment will be silenced.
1070    pub fn environment_selection(&self, active: ActiveEnvironment) -> ProjectEnvironmentSelection {
1071        ProjectEnvironmentSelection::from_install_path(&self.install_path, active)
1072    }
1073
1074    /// The members of the workspace.
1075    pub fn packages(&self) -> &BTreeMap<PackageName, WorkspaceMember> {
1076        &self.packages
1077    }
1078
1079    /// The sources table from the workspace `pyproject.toml`.
1080    pub fn sources(&self) -> &BTreeMap<PackageName, Sources> {
1081        &self.sources
1082    }
1083
1084    /// The index table from the workspace `pyproject.toml`.
1085    pub fn indexes(&self) -> &[Index] {
1086        &self.indexes
1087    }
1088
1089    /// The `pyproject.toml` of the workspace.
1090    pub fn pyproject_toml(&self) -> &PyProjectToml {
1091        &self.pyproject_toml
1092    }
1093
1094    /// Return the default dependency groups for the workspace root.
1095    pub fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1096        self.pyproject_toml.default_groups()
1097    }
1098
1099    /// Returns `true` if the path is excluded by the workspace.
1100    pub fn excludes(&self, project_path: &Path) -> Result<bool, WorkspaceError> {
1101        if let Some(workspace) = self
1102            .pyproject_toml
1103            .tool
1104            .as_ref()
1105            .and_then(|tool| tool.uv.as_ref())
1106            .and_then(|uv| uv.workspace.as_ref())
1107        {
1108            is_excluded_from_workspace(project_path, &self.install_path, workspace)
1109        } else {
1110            Ok(false)
1111        }
1112    }
1113
1114    /// Returns `true` if the path is included by the workspace.
1115    pub fn includes(&self, project_path: &Path) -> Result<bool, WorkspaceError> {
1116        if let Some(workspace) = self
1117            .pyproject_toml
1118            .tool
1119            .as_ref()
1120            .and_then(|tool| tool.uv.as_ref())
1121            .and_then(|uv| uv.workspace.as_ref())
1122        {
1123            is_included_in_workspace(project_path, &self.install_path, workspace)
1124        } else {
1125            Ok(false)
1126        }
1127    }
1128
1129    /// Collect the workspace member projects and build the workspace object.
1130    async fn build(
1131        workspace_root: PathBuf,
1132        workspace_definition: ToolUvWorkspace,
1133        workspace_pyproject_toml: PyProjectToml,
1134        current_project: Option<WorkspaceMember>,
1135        options: &DiscoveryOptions,
1136        cache: &Cache,
1137    ) -> Result<Arc<Self>, WorkspaceError> {
1138        trace!(
1139            "Discovering workspace members for: {}",
1140            &workspace_root.simplified_display()
1141        );
1142        let workspace_members = Self::collect_members_only(
1143            &workspace_root,
1144            &workspace_definition,
1145            &workspace_pyproject_toml,
1146            options,
1147            cache,
1148        )
1149        .await?;
1150        let mut workspace_members = Arc::new(workspace_members);
1151
1152        // For the cases such as `MemberDiscovery::None`, add the current project if missing.
1153        if let Some(root_member) = current_project
1154            && !workspace_members.contains_key(&root_member.project.name)
1155        {
1156            assert_matches!(
1157                options.members,
1158                MemberDiscovery::None | MemberDiscovery::Ignore(_)
1159            );
1160            debug!(
1161                "Adding current workspace member: {}",
1162                root_member.root.simplified_display()
1163            );
1164
1165            Arc::make_mut(&mut workspace_members)
1166                .insert(root_member.project.name.clone(), root_member);
1167        }
1168
1169        let workspace_sources = workspace_pyproject_toml
1170            .tool
1171            .clone()
1172            .and_then(|tool| tool.uv)
1173            .and_then(|uv| uv.sources)
1174            .map(ToolUvSources::into_inner)
1175            .unwrap_or_default();
1176
1177        let workspace_indexes = workspace_pyproject_toml
1178            .tool
1179            .clone()
1180            .and_then(|tool| tool.uv)
1181            .and_then(|uv| uv.index)
1182            .unwrap_or_default();
1183
1184        let required_members = Self::collect_required_members(
1185            &workspace_members,
1186            &workspace_sources,
1187            &workspace_pyproject_toml,
1188        )?;
1189
1190        let dev_dependencies_members = workspace_members
1191            .values()
1192            .filter_map(|member| {
1193                member
1194                    .pyproject_toml
1195                    .tool
1196                    .as_ref()
1197                    .and_then(|tool| tool.uv.as_ref())
1198                    .and_then(|uv| uv.dev_dependencies.as_ref())
1199                    .map(|_| format!("`{}`", member.root().join("pyproject.toml").user_display()))
1200            })
1201            .join(", ");
1202        if !dev_dependencies_members.is_empty() {
1203            warn_user_once!(
1204                "The `tool.uv.dev-dependencies` field (used in {}) is deprecated and will be removed in a future release; use `dependency-groups.dev` instead",
1205                dev_dependencies_members
1206            );
1207        }
1208
1209        let workspace = Self {
1210            install_path: workspace_root,
1211            packages: workspace_members,
1212            required_members,
1213            sources: workspace_sources,
1214            indexes: workspace_indexes,
1215            pyproject_toml: workspace_pyproject_toml,
1216        };
1217        Ok(Arc::new(workspace))
1218    }
1219
1220    async fn collect_members_only(
1221        workspace_root: &PathBuf,
1222        workspace_definition: &ToolUvWorkspace,
1223        workspace_pyproject_toml: &PyProjectToml,
1224        options: &DiscoveryOptions,
1225        cache: &Cache,
1226    ) -> Result<BTreeMap<PackageName, WorkspaceMember>, WorkspaceError> {
1227        let mut workspace_members = BTreeMap::new();
1228        // Avoid reading a `pyproject.toml` more than once.
1229        let mut seen = FxHashSet::default();
1230
1231        let external_cache_root = options
1232            .stop_discovery_at
1233            .is_none()
1234            .then(|| {
1235                // We may receive an uninitialized cache with a relative cache root.
1236                let cache_root = if cache.root().is_absolute() {
1237                    cache.root().to_path_buf()
1238                } else {
1239                    CWD.join(cache.root())
1240                };
1241                normalize_path(&cache_root).into_owned()
1242            })
1243            .filter(|cache_root| !workspace_root.starts_with(cache_root));
1244
1245        // Add the project at the workspace root, if it exists and if it's distinct from the current
1246        // project. If it is the current project, it is added as such in the next step.
1247        if let Some(project) = &workspace_pyproject_toml.project {
1248            debug!(
1249                "Adding root workspace member: {}",
1250                workspace_root.simplified_display()
1251            );
1252
1253            seen.insert(workspace_root.clone());
1254            workspace_members.insert(
1255                project.name.clone(),
1256                WorkspaceMember {
1257                    root: workspace_root.clone(),
1258                    project: project.clone(),
1259                    pyproject_toml: workspace_pyproject_toml.clone(),
1260                },
1261            );
1262        }
1263
1264        // Prepare exclusions only after finding a member that is not explicitly ignored.
1265        let mut exclusions = None;
1266
1267        // Add all other workspace members.
1268        for member_glob in workspace_definition.members.as_deref().unwrap_or_default() {
1269            // Normalize the member glob to remove leading `./` and other relative path components
1270            let normalized_glob = normalize_path(Path::new(member_glob.as_str()));
1271            let absolute_glob = PathBuf::from(glob::Pattern::escape(
1272                workspace_root.simplified().to_string_lossy().as_ref(),
1273            ))
1274            .join(normalized_glob.as_ref())
1275            .to_string_lossy()
1276            .to_string();
1277            for member_root in glob(&absolute_glob)
1278                .map_err(|err| WorkspaceErrorKind::Pattern(absolute_glob.clone(), err))?
1279            {
1280                let member_root = member_root
1281                    .map_err(|err| WorkspaceErrorKind::GlobWalk(absolute_glob.clone(), err))?;
1282                if external_cache_root
1283                    .as_ref()
1284                    .is_some_and(|cache_root| member_root.starts_with(cache_root))
1285                {
1286                    debug!(
1287                        "Ignoring cache directory while discovering workspace members: {}",
1288                        member_root.simplified_display()
1289                    );
1290                    continue;
1291                }
1292                if !seen.insert(member_root.clone()) {
1293                    continue;
1294                }
1295                let member_root =
1296                    std::path::absolute(&member_root).map_err(WorkspaceErrorKind::Normalize)?;
1297
1298                // If the directory is explicitly ignored, skip it.
1299                let skip = match &options.members {
1300                    MemberDiscovery::All | MemberDiscovery::Existing => false,
1301                    MemberDiscovery::None => true,
1302                    MemberDiscovery::Ignore(ignore) => ignore.contains(member_root.as_path()),
1303                };
1304                if skip {
1305                    debug!(
1306                        "Ignoring workspace member: {}",
1307                        member_root.simplified_display()
1308                    );
1309                    continue;
1310                }
1311
1312                // If the member is excluded, ignore it.
1313                if exclusions
1314                    .get_or_insert_with(|| {
1315                        WorkspaceExclusions::new(workspace_root, workspace_definition)
1316                    })
1317                    .as_ref()
1318                    .map_err(WorkspaceError::clone)?
1319                    .matches(&member_root)
1320                {
1321                    debug!(
1322                        "Ignoring workspace member: {}",
1323                        member_root.simplified_display()
1324                    );
1325                    continue;
1326                }
1327
1328                trace!(
1329                    "Processing workspace member: {}",
1330                    member_root.user_display()
1331                );
1332
1333                // Read the member `pyproject.toml`.
1334                let pyproject_path = member_root.join("pyproject.toml");
1335                let contents = match fs_err::tokio::read_to_string(&pyproject_path).await {
1336                    Ok(contents) => contents,
1337                    Err(err) => {
1338                        let metadata = match fs_err::metadata(&member_root) {
1339                            Ok(metadata) => metadata,
1340                            Err(err)
1341                                if matches!(options.members, MemberDiscovery::Existing)
1342                                    && err.kind() == std::io::ErrorKind::NotFound =>
1343                            {
1344                                debug!(
1345                                    "Ignoring missing workspace member: {}",
1346                                    member_root.simplified_display()
1347                                );
1348                                continue;
1349                            }
1350                            Err(err) => return Err(err.into()),
1351                        };
1352                        if !metadata.is_dir() {
1353                            warn!(
1354                                "Ignoring non-directory workspace member: {}",
1355                                member_root.simplified_display()
1356                            );
1357                            continue;
1358                        }
1359
1360                        // A directory exists, but it doesn't contain a `pyproject.toml`.
1361                        if err.kind() == std::io::ErrorKind::NotFound {
1362                            // If the directory is hidden, skip it.
1363                            if member_root
1364                                .file_name()
1365                                .is_some_and(|name| name.as_encoded_bytes().starts_with(b"."))
1366                            {
1367                                debug!(
1368                                    "Ignoring hidden workspace member: {}",
1369                                    member_root.simplified_display()
1370                                );
1371                                continue;
1372                            }
1373
1374                            // If the directory only contains gitignored files
1375                            // (e.g., `__pycache__`), skip it.
1376                            if has_only_gitignored_files(&member_root) {
1377                                debug!(
1378                                    "Ignoring workspace member with only gitignored files: {}",
1379                                    member_root.simplified_display()
1380                                );
1381                                continue;
1382                            }
1383
1384                            if matches!(options.members, MemberDiscovery::Existing) {
1385                                debug!(
1386                                    "Ignoring missing workspace member: {}",
1387                                    member_root.simplified_display()
1388                                );
1389                                continue;
1390                            }
1391
1392                            return Err(WorkspaceError::from(
1393                                WorkspaceErrorKind::MissingPyprojectTomlMember(
1394                                    member_root,
1395                                    member_glob.to_string(),
1396                                ),
1397                            ));
1398                        }
1399
1400                        return Err(err.into());
1401                    }
1402                };
1403                let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
1404                    .map_err(|err| {
1405                        WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err))
1406                    })?;
1407
1408                // Check if the current project is explicitly marked as unmanaged.
1409                if pyproject_toml
1410                    .tool
1411                    .as_ref()
1412                    .and_then(|tool| tool.uv.as_ref())
1413                    .and_then(|uv| uv.managed)
1414                    == Some(false)
1415                {
1416                    if let Some(project) = pyproject_toml.project.as_ref() {
1417                        debug!(
1418                            "Project `{}` is marked as unmanaged; omitting from workspace members",
1419                            project.name
1420                        );
1421                    } else {
1422                        debug!(
1423                            "Workspace member at `{}` is marked as unmanaged; omitting from workspace members",
1424                            member_root.simplified_display()
1425                        );
1426                    }
1427                    continue;
1428                }
1429
1430                // Extract the package name.
1431                let Some(project) = pyproject_toml.project.clone() else {
1432                    return Err(WorkspaceError::from(WorkspaceErrorKind::MissingProject(
1433                        pyproject_path,
1434                    )));
1435                };
1436
1437                debug!(
1438                    "Adding discovered workspace member: {}",
1439                    member_root.simplified_display()
1440                );
1441
1442                if let Some(existing) = workspace_members.insert(
1443                    project.name.clone(),
1444                    WorkspaceMember {
1445                        root: member_root.clone(),
1446                        project,
1447                        pyproject_toml,
1448                    },
1449                ) {
1450                    return Err(WorkspaceError::from(WorkspaceErrorKind::DuplicatePackage {
1451                        name: existing.project.name,
1452                        first: existing.root.clone(),
1453                        second: member_root,
1454                    }));
1455                }
1456            }
1457        }
1458
1459        // Test for nested workspaces.
1460        for member in workspace_members.values() {
1461            if member.root() != workspace_root
1462                && member
1463                    .pyproject_toml
1464                    .tool
1465                    .as_ref()
1466                    .and_then(|tool| tool.uv.as_ref())
1467                    .and_then(|uv| uv.workspace.as_ref())
1468                    .is_some()
1469            {
1470                return Err(WorkspaceError::from(WorkspaceErrorKind::NestedWorkspace(
1471                    member.root.clone(),
1472                )));
1473            }
1474        }
1475        Ok(workspace_members)
1476    }
1477}
1478
1479/// A project in a workspace.
1480#[derive(Debug, Clone, PartialEq)]
1481#[cfg_attr(test, derive(serde::Serialize))]
1482pub struct WorkspaceMember {
1483    /// The path to the project root.
1484    root: PathBuf,
1485    /// The `[project]` table, from the `pyproject.toml` of the project found at
1486    /// `<root>/pyproject.toml`.
1487    project: Project,
1488    /// The `pyproject.toml` of the project, found at `<root>/pyproject.toml`.
1489    pyproject_toml: PyProjectToml,
1490}
1491
1492impl WorkspaceMember {
1493    /// The path to the project root.
1494    pub fn root(&self) -> &PathBuf {
1495        &self.root
1496    }
1497
1498    /// The `[project]` table, from the `pyproject.toml` of the project found at
1499    /// `<root>/pyproject.toml`.
1500    pub fn project(&self) -> &Project {
1501        &self.project
1502    }
1503
1504    /// The `pyproject.toml` of the project, found at `<root>/pyproject.toml`.
1505    pub fn pyproject_toml(&self) -> &PyProjectToml {
1506        &self.pyproject_toml
1507    }
1508
1509    /// Return the default dependency groups for this workspace member.
1510    ///
1511    /// Returns an error if an explicitly configured group is not declared by the member.
1512    pub fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1513        self.pyproject_toml.default_groups()
1514    }
1515}
1516
1517/// The current project and the workspace it is part of, with all of the workspace members.
1518///
1519/// # Structure
1520///
1521/// The workspace root is a directory with a `pyproject.toml`, all members need to be below that
1522/// directory. The workspace root defines members and exclusions. All packages below it must either
1523/// be a member or excluded. The workspace root can be a package itself or a virtual manifest.
1524///
1525/// For a simple single package project, the workspace root is implicitly the current project root
1526/// and the workspace has only this single member. Otherwise, a workspace root is declared through
1527/// a `tool.uv.workspace` section.
1528///
1529/// A workspace itself does not declare dependencies, instead one member is the current project used
1530/// as main requirement.
1531///
1532/// Each member is a directory with a `pyproject.toml` that contains a `[project]` section. Each
1533/// member is a Python package, with a name, a version and dependencies. Workspace members can
1534/// depend on other workspace members (`foo = { workspace = true }`). You can consider the
1535/// workspace another package source or index, similar to `--find-links`.
1536///
1537/// # Usage
1538///
1539/// There a two main usage patterns: A root package and helpers, and the flat workspace.
1540///
1541/// Root package and helpers:
1542///
1543/// ```text
1544/// albatross
1545/// ├── packages
1546/// │   ├── provider_a
1547/// │   │   ├── pyproject.toml
1548/// │   │   └── src
1549/// │   │       └── provider_a
1550/// │   │           ├── __init__.py
1551/// │   │           └── foo.py
1552/// │   └── provider_b
1553/// │       ├── pyproject.toml
1554/// │       └── src
1555/// │           └── provider_b
1556/// │               ├── __init__.py
1557/// │               └── bar.py
1558/// ├── pyproject.toml
1559/// ├── Readme.md
1560/// ├── uv.lock
1561/// └── src
1562///     └── albatross
1563///         ├── __init__.py
1564///         └── main.py
1565/// ```
1566///
1567/// Flat workspace:
1568///
1569/// ```text
1570/// albatross
1571/// ├── packages
1572/// │   ├── albatross
1573/// │   │   ├── pyproject.toml
1574/// │   │   └── src
1575/// │   │       └── albatross
1576/// │   │           ├── __init__.py
1577/// │   │           └── main.py
1578/// │   ├── provider_a
1579/// │   │   ├── pyproject.toml
1580/// │   │   └── src
1581/// │   │       └── provider_a
1582/// │   │           ├── __init__.py
1583/// │   │           └── foo.py
1584/// │   └── provider_b
1585/// │       ├── pyproject.toml
1586/// │       └── src
1587/// │           └── provider_b
1588/// │               ├── __init__.py
1589/// │               └── bar.py
1590/// ├── pyproject.toml
1591/// ├── Readme.md
1592/// └── uv.lock
1593/// ```
1594#[derive(Debug, Clone)]
1595#[cfg_attr(test, derive(serde::Serialize))]
1596pub struct ProjectWorkspace {
1597    /// The path to the project root.
1598    project_root: PathBuf,
1599    /// The name of the package.
1600    project_name: PackageName,
1601    /// The workspace the project is part of.
1602    workspace: Arc<Workspace>,
1603}
1604
1605impl ProjectWorkspace {
1606    fn from_cache(
1607        project_root: &Path,
1608        options: &DiscoveryOptions,
1609        cache: &WorkspaceCache,
1610    ) -> Result<Option<Self>, WorkspaceError> {
1611        let cached = match cache.get(project_root, &options.members) {
1612            Some(Ok(cached)) => cached,
1613            Some(Err(error)) => return Err(error),
1614            None => return Ok(None),
1615        };
1616        let Some(project_name) = cached.project_name else {
1617            return Ok(None);
1618        };
1619
1620        Ok(Some(Self {
1621            project_root: project_root.to_path_buf(),
1622            project_name,
1623            workspace: cached.workspace,
1624        }))
1625    }
1626
1627    /// Find the current project and workspace, given the current directory.
1628    ///
1629    /// `stop_discovery_at` must be either `None` or an ancestor of the current directory. If set,
1630    /// only directories between the current path and `stop_discovery_at` are considered.
1631    pub async fn discover(
1632        path: &Path,
1633        options: &DiscoveryOptions,
1634        cache: &Cache,
1635        workspace_cache: &WorkspaceCache,
1636    ) -> Result<Self, WorkspaceError> {
1637        assert!(
1638            path.is_absolute(),
1639            "project workspace discovery with relative path"
1640        );
1641        let project_root = path
1642            .ancestors()
1643            .take_while(|path| {
1644                // Only walk up the given directory, if any.
1645                options
1646                    .stop_discovery_at
1647                    .as_deref()
1648                    .and_then(Path::parent)
1649                    .is_none_or(|stop_discovery_at| stop_discovery_at != *path)
1650            })
1651            .find(|path| path.join("pyproject.toml").is_file())
1652            .ok_or_else(|| WorkspaceErrorKind::MissingPyprojectToml)?;
1653
1654        debug!("Found project root: {}", project_root.simplified_display());
1655
1656        Self::from_project_root(project_root, options, cache, workspace_cache).await
1657    }
1658
1659    /// Discover the workspace starting from the directory containing the `pyproject.toml`.
1660    async fn from_project_root(
1661        project_root: &Path,
1662        options: &DiscoveryOptions,
1663        cache: &Cache,
1664        workspace_cache: &WorkspaceCache,
1665    ) -> Result<Self, WorkspaceError> {
1666        if let Some(project) = Self::from_cache(project_root, options, workspace_cache)? {
1667            return Ok(project);
1668        }
1669
1670        // Read the current `pyproject.toml`.
1671        let pyproject_path = project_root.join("pyproject.toml");
1672
1673        let contents = fs_err::tokio::read_to_string(&pyproject_path).await?;
1674        let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
1675            .map_err(|err| WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err)))?;
1676
1677        // It must have a `[project]` table.
1678        let project = pyproject_toml
1679            .project
1680            .clone()
1681            .ok_or_else(|| WorkspaceErrorKind::MissingProject(pyproject_path))?;
1682
1683        Self::from_project(
1684            project_root,
1685            &project,
1686            &pyproject_toml,
1687            options,
1688            cache,
1689            workspace_cache,
1690        )
1691        .await
1692    }
1693
1694    /// If the current directory contains a `pyproject.toml` with a `project` table, discover the
1695    /// workspace and return it, otherwise it is a dynamic path dependency and we return `Ok(None)`.
1696    pub async fn from_maybe_project_root(
1697        project_root: &Path,
1698        options: &DiscoveryOptions,
1699        cache: &Cache,
1700        workspace_cache: &WorkspaceCache,
1701    ) -> Result<Option<Self>, WorkspaceError> {
1702        if let Some(project) = Self::from_cache(project_root, options, workspace_cache)? {
1703            return Ok(Some(project));
1704        }
1705
1706        // Read the `pyproject.toml`.
1707        let pyproject_path = project_root.join("pyproject.toml");
1708        let Ok(contents) = fs_err::tokio::read_to_string(&pyproject_path).await else {
1709            // No `pyproject.toml`, but there may still be a `setup.py` or `setup.cfg`.
1710            return Ok(None);
1711        };
1712        let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
1713            .map_err(|err| WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err)))?;
1714
1715        // Extract the `[project]` metadata.
1716        let Some(project) = pyproject_toml.project.clone() else {
1717            // We have to build to get the metadata.
1718            return Ok(None);
1719        };
1720
1721        // Keep uncached workspace discovery out of the cache-hit future.
1722        match Box::pin(Self::from_project(
1723            project_root,
1724            &project,
1725            &pyproject_toml,
1726            options,
1727            cache,
1728            workspace_cache,
1729        ))
1730        .await
1731        {
1732            Ok(workspace) => Ok(Some(workspace)),
1733            Err(error) if matches!(error.as_ref(), WorkspaceErrorKind::NonWorkspace(_)) => Ok(None),
1734            Err(err) => Err(err),
1735        }
1736    }
1737
1738    /// Returns the directory containing the closest `pyproject.toml` that defines the current
1739    /// project.
1740    pub fn project_root(&self) -> &Path {
1741        &self.project_root
1742    }
1743
1744    /// Returns the [`PackageName`] of the current project.
1745    pub fn project_name(&self) -> &PackageName {
1746        &self.project_name
1747    }
1748
1749    /// Returns the [`Workspace`] containing the current project.
1750    pub fn workspace(&self) -> &Workspace {
1751        &self.workspace
1752    }
1753
1754    /// Returns the current project as a [`WorkspaceMember`].
1755    pub fn current_project(&self) -> &WorkspaceMember {
1756        &self.workspace().packages[&self.project_name]
1757    }
1758
1759    /// Return the default dependency groups for the current project.
1760    fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1761        self.current_project().default_groups()
1762    }
1763
1764    /// Set the `pyproject.toml` for the current project.
1765    ///
1766    /// Assumes that the project name is unchanged in the updated [`PyProjectToml`].
1767    fn update_member(self, pyproject_toml: PyProjectToml) -> Result<Option<Self>, WorkspaceError> {
1768        let Some(workspace) =
1769            Workspace::update_member(self.workspace, &self.project_name, pyproject_toml)?
1770        else {
1771            return Ok(None);
1772        };
1773        Ok(Some(Self { workspace, ..self }))
1774    }
1775
1776    /// Find the workspace for a project.
1777    async fn from_project(
1778        install_path: &Path,
1779        project: &Project,
1780        project_pyproject_toml: &PyProjectToml,
1781        options: &DiscoveryOptions,
1782        cache: &Cache,
1783        workspace_cache: &WorkspaceCache,
1784    ) -> Result<Self, WorkspaceError> {
1785        let project_path = std::path::absolute(install_path)
1786            .map_err(WorkspaceErrorKind::Normalize)?
1787            .clone();
1788        let project_path = normalize_path(&project_path);
1789
1790        // Check if workspaces are explicitly disabled for the project.
1791        if project_pyproject_toml
1792            .tool
1793            .as_ref()
1794            .and_then(|tool| tool.uv.as_ref())
1795            .and_then(|uv| uv.managed)
1796            == Some(false)
1797        {
1798            debug!("Project `{}` is marked as unmanaged", project.name);
1799            return Err(WorkspaceError::from(WorkspaceErrorKind::NonWorkspace(
1800                project_path.to_path_buf(),
1801            )));
1802        }
1803
1804        if let Some(project) = Self::from_cache(&project_path, options, workspace_cache)? {
1805            return Ok(project);
1806        }
1807
1808        // Check if the current project is also an explicit workspace root.
1809        let mut workspace = project_pyproject_toml
1810            .tool
1811            .as_ref()
1812            .and_then(|tool| tool.uv.as_ref())
1813            .and_then(|uv| uv.workspace.as_ref())
1814            .map(|workspace| {
1815                (
1816                    project_path.to_path_buf(),
1817                    workspace.clone(),
1818                    project_pyproject_toml.clone(),
1819                )
1820            });
1821
1822        if workspace.is_none() {
1823            // The project isn't an explicit workspace root, check if we're a regular workspace
1824            // member by looking for an explicit workspace root above.
1825            workspace = find_workspace(&project_path, options, cache).await?;
1826        }
1827
1828        let current_project = WorkspaceMember {
1829            root: project_path.to_path_buf(),
1830            project: project.clone(),
1831            pyproject_toml: project_pyproject_toml.clone(),
1832        };
1833
1834        let Some((workspace_root, workspace_definition, workspace_pyproject_toml)) = workspace
1835        else {
1836            // The project isn't an explicit workspace root, but there's also no workspace root
1837            // above it, so the project is an implicit workspace root identical to the project root.
1838            debug!("No workspace root found, using project root");
1839
1840            let current_project_as_members = Arc::new(BTreeMap::from_iter([(
1841                project.name.clone(),
1842                current_project,
1843            )]));
1844            let workspace_sources = BTreeMap::default();
1845            let required_members = Workspace::collect_required_members(
1846                &current_project_as_members,
1847                &workspace_sources,
1848                project_pyproject_toml,
1849            )?;
1850
1851            let workspace = Workspace {
1852                install_path: project_path.to_path_buf(),
1853                packages: current_project_as_members,
1854                required_members,
1855                // There may be package sources, but we don't need to duplicate them into the
1856                // workspace sources.
1857                sources: workspace_sources,
1858                indexes: Vec::default(),
1859                pyproject_toml: project_pyproject_toml.clone(),
1860            };
1861            let workspace = Arc::new(workspace);
1862            if options.members == MemberDiscovery::All {
1863                workspace_cache.insert(Ok(workspace.clone()), &project_path);
1864            }
1865            return Ok(Self {
1866                project_root: project_path.to_path_buf(),
1867                project_name: project.name.clone(),
1868                workspace,
1869            });
1870        };
1871
1872        if options.members == MemberDiscovery::All {
1873            // Ensure that workspace discovery runs only once for any given workspace root.
1874            if let Some(workspace) = workspace_cache.register_or_wait(&workspace_root).await {
1875                return workspace.map(|workspace| Self {
1876                    project_root: project_path.to_path_buf(),
1877                    project_name: project.name.clone(),
1878                    workspace,
1879                });
1880            }
1881        }
1882
1883        debug!(
1884            "Found workspace root: {}",
1885            workspace_root.simplified_display()
1886        );
1887
1888        let result = Workspace::build(
1889            workspace_root.clone(),
1890            workspace_definition,
1891            workspace_pyproject_toml,
1892            Some(current_project),
1893            options,
1894            cache,
1895        )
1896        .await;
1897        if options.members == MemberDiscovery::All {
1898            workspace_cache.insert(result.clone(), &workspace_root);
1899        }
1900
1901        Ok(Self {
1902            project_root: project_path.to_path_buf(),
1903            project_name: project.name.clone(),
1904            workspace: result?,
1905        })
1906    }
1907}
1908
1909/// Find the workspace root above the current project, if any.
1910async fn find_workspace(
1911    project_root: &Path,
1912    options: &DiscoveryOptions,
1913    cache: &Cache,
1914) -> Result<Option<(PathBuf, ToolUvWorkspace, PyProjectToml)>, WorkspaceError> {
1915    let external_cache_root = if options.stop_discovery_at.is_none() {
1916        // We may receive an uninitialized cache with a relative cache root.
1917        let cache_root = if cache.root().is_absolute() {
1918            cache.root().to_path_buf()
1919        } else {
1920            CWD.join(cache.root())
1921        };
1922        Some(normalize_path(&cache_root).into_owned())
1923    } else {
1924        None
1925    };
1926    // Avoid panicking in the odd (unsupported) case that uv is running inside the cache dir.
1927    if let Some(cache_root) = external_cache_root
1928        && project_root.starts_with(cache_root)
1929    {
1930        debug!(
1931            "Project is contained in cache directory: {}",
1932            project_root.simplified_display()
1933        );
1934        return Ok(None);
1935    }
1936
1937    // Skip 1 to ignore the current project itself.
1938    for workspace_root in project_root
1939        .ancestors()
1940        .take_while(|path| {
1941            // Only walk up the given directory, if any.
1942            options
1943                .stop_discovery_at
1944                .as_deref()
1945                .and_then(Path::parent)
1946                .is_none_or(|stop_discovery_at| stop_discovery_at != *path)
1947        })
1948        .skip(1)
1949    {
1950        let pyproject_path = workspace_root.join("pyproject.toml");
1951        if !pyproject_path.is_file() {
1952            continue;
1953        }
1954        trace!(
1955            "Found `pyproject.toml` at: {}",
1956            pyproject_path.simplified_display()
1957        );
1958
1959        // Read the `pyproject.toml`.
1960        let contents = fs_err::tokio::read_to_string(&pyproject_path).await?;
1961        let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
1962            .map_err(|err| WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err)))?;
1963
1964        return if let Some(workspace) = pyproject_toml
1965            .tool
1966            .as_ref()
1967            .and_then(|tool| tool.uv.as_ref())
1968            .and_then(|uv| uv.workspace.as_ref())
1969        {
1970            if !is_included_in_workspace(project_root, workspace_root, workspace)? {
1971                debug!(
1972                    "Found workspace root `{}`, but project is not included",
1973                    workspace_root.simplified_display()
1974                );
1975                return Ok(None);
1976            }
1977
1978            if is_excluded_from_workspace(project_root, workspace_root, workspace)? {
1979                debug!(
1980                    "Found workspace root `{}`, but project is excluded",
1981                    workspace_root.simplified_display()
1982                );
1983                return Ok(None);
1984            }
1985
1986            // We found a workspace root.
1987            Ok(Some((
1988                workspace_root.to_path_buf(),
1989                workspace.clone(),
1990                pyproject_toml,
1991            )))
1992        } else if pyproject_toml.project.is_some() {
1993            // We're in a directory of another project, e.g. tests or examples.
1994            // Example:
1995            // ```
1996            // albatross
1997            // ├── examples
1998            // │   └── bird-feeder [CURRENT DIRECTORY]
1999            // │       ├── pyproject.toml
2000            // │       └── src
2001            // │           └── bird_feeder
2002            // │               └── __init__.py
2003            // ├── pyproject.toml
2004            // └── src
2005            //     └── albatross
2006            //         └── __init__.py
2007            // ```
2008            // The current project is the example (non-workspace) `bird-feeder` in `albatross`,
2009            // we ignore all `albatross` is doing and any potential workspace it might be
2010            // contained in.
2011            debug!(
2012                "Project is contained in non-workspace project: {}",
2013                workspace_root.simplified_display()
2014            );
2015            Ok(None)
2016        } else {
2017            // We require that a `project.toml` file either declares a workspace or a project.
2018            warn!(
2019                "`pyproject.toml` does not contain a `project` table: {}",
2020                pyproject_path.simplified_display()
2021            );
2022            Ok(None)
2023        };
2024    }
2025
2026    Ok(None)
2027}
2028
2029/// Check if a directory only contains files that are ignored.
2030///
2031/// Returns `true` if walking the directory while respecting `.gitignore` and `.ignore` rules
2032/// yields no files, indicating that any files present (e.g., `__pycache__`) are all ignored.
2033fn has_only_gitignored_files(path: &Path) -> bool {
2034    let walker = ignore::WalkBuilder::new(path)
2035        .hidden(false)
2036        .parents(true)
2037        .ignore(true)
2038        .git_ignore(true)
2039        .git_global(true)
2040        .git_exclude(true)
2041        .build();
2042
2043    for entry in walker {
2044        let Ok(entry) = entry else {
2045            // If we can't read an entry, assume non-ignored content exists.
2046            return false;
2047        };
2048
2049        // Skip directories.
2050        if entry.path().is_dir() {
2051            continue;
2052        }
2053
2054        // A non-ignored entry exists.
2055        return false;
2056    }
2057
2058    true
2059}
2060
2061/// Check if we're in the `tool.uv.workspace.excluded` of a workspace.
2062fn is_excluded_from_workspace(
2063    project_path: &Path,
2064    workspace_root: &Path,
2065    workspace: &ToolUvWorkspace,
2066) -> Result<bool, WorkspaceError> {
2067    Ok(WorkspaceExclusions::new(workspace_root, workspace)?.matches(project_path))
2068}
2069
2070/// Compiled workspace exclusion patterns.
2071#[derive(Debug)]
2072struct WorkspaceExclusions<'workspace> {
2073    workspace_root: &'workspace Path,
2074    patterns: Vec<WorkspaceExclusion<'workspace>>,
2075}
2076
2077/// A workspace exclusion that can reuse its parsed pattern or requires normalization.
2078#[derive(Debug)]
2079enum WorkspaceExclusion<'workspace> {
2080    Relative(&'workspace Pattern),
2081    Absolute(Pattern),
2082}
2083
2084impl<'workspace> WorkspaceExclusions<'workspace> {
2085    /// Compile the normalized workspace exclusion patterns.
2086    fn new(
2087        workspace_root: &'workspace Path,
2088        workspace: &'workspace ToolUvWorkspace,
2089    ) -> Result<Self, WorkspaceError> {
2090        let patterns = workspace
2091            .exclude
2092            .iter()
2093            .flatten()
2094            .map(|exclude_glob| Self::compile_pattern(workspace_root, exclude_glob))
2095            .collect::<Result<_, _>>()?;
2096
2097        Ok(Self {
2098            workspace_root,
2099            patterns,
2100        })
2101    }
2102
2103    /// Return whether any workspace exclusion matches the project path.
2104    fn matches(&self, project_path: &Path) -> bool {
2105        let relative_path = project_path
2106            .simplified()
2107            .strip_prefix(self.workspace_root.simplified())
2108            .ok();
2109
2110        self.patterns.iter().any(|pattern| match pattern {
2111            WorkspaceExclusion::Relative(pattern) => {
2112                relative_path.is_some_and(|relative_path| pattern.matches_path(relative_path))
2113            }
2114            WorkspaceExclusion::Absolute(pattern) => pattern.matches_path(project_path),
2115        })
2116    }
2117
2118    /// Reuse an already compiled relative pattern or compile its normalized absolute equivalent.
2119    fn compile_pattern(
2120        workspace_root: &Path,
2121        exclude_glob: &'workspace Pattern,
2122    ) -> Result<WorkspaceExclusion<'workspace>, WorkspaceError> {
2123        // Normalize the exclude glob to remove leading `./` and other relative path components.
2124        let normalized_glob = normalize_path(Path::new(exclude_glob.as_str()));
2125        if matches!(&normalized_glob, Cow::Borrowed(_)) && normalized_glob.is_relative() {
2126            return Ok(WorkspaceExclusion::Relative(exclude_glob));
2127        }
2128
2129        let absolute_glob = PathBuf::from(Pattern::escape(
2130            workspace_root.simplified().to_string_lossy().as_ref(),
2131        ))
2132        .join(normalized_glob.as_ref());
2133        let absolute_glob = absolute_glob.to_string_lossy();
2134        Pattern::new(&absolute_glob)
2135            .map(WorkspaceExclusion::Absolute)
2136            .map_err(|err| WorkspaceErrorKind::Pattern(absolute_glob.to_string(), err).into())
2137    }
2138}
2139
2140/// Check if we're in the `tool.uv.workspace.members` of a workspace.
2141fn is_included_in_workspace(
2142    project_path: &Path,
2143    workspace_root: &Path,
2144    workspace: &ToolUvWorkspace,
2145) -> Result<bool, WorkspaceError> {
2146    let options = MatchOptions {
2147        require_literal_separator: true,
2148        ..MatchOptions::new()
2149    };
2150    for member_glob in workspace.members.iter().flatten() {
2151        // Normalize the member glob to remove leading `./` and other relative path components
2152        let normalized_glob = normalize_path(Path::new(member_glob.as_str()));
2153        let absolute_glob = PathBuf::from(glob::Pattern::escape(
2154            workspace_root.simplified().to_string_lossy().as_ref(),
2155        ))
2156        .join(normalized_glob);
2157        let absolute_glob = absolute_glob.to_string_lossy();
2158        let include_pattern = glob::Pattern::new(&absolute_glob)
2159            .map_err(|err| WorkspaceErrorKind::Pattern(absolute_glob.to_string(), err))?;
2160        if include_pattern.matches_path_with(project_path, options) {
2161            return Ok(true);
2162        }
2163    }
2164    Ok(false)
2165}
2166
2167/// A project that can be discovered.
2168///
2169/// The project could be a package within a workspace, a real workspace root, or a non-project
2170/// workspace root, which can define its own dev dependencies.
2171#[derive(Debug, Clone)]
2172pub enum VirtualProject {
2173    /// A project (which could be a workspace root or member).
2174    Project(ProjectWorkspace),
2175    /// A non-project workspace root.
2176    NonProject(Arc<Workspace>),
2177}
2178
2179impl VirtualProject {
2180    /// Find the current project or virtual workspace root, given the current directory.
2181    ///
2182    /// Similar to calling [`ProjectWorkspace::discover`] with a fallback to [`Workspace::discover`],
2183    /// but avoids rereading the `pyproject.toml` (and relying on error-handling as control flow).
2184    ///
2185    /// This method requires an absolute path and panics otherwise, i.e. this method only supports
2186    /// discovering the main workspace.
2187    pub async fn discover(
2188        path: &Path,
2189        options: &DiscoveryOptions,
2190        cache: &Cache,
2191        workspace_cache: &WorkspaceCache,
2192    ) -> Result<Self, WorkspaceError> {
2193        assert!(
2194            path.is_absolute(),
2195            "virtual project discovery with relative path"
2196        );
2197        let project_root = path
2198            .ancestors()
2199            .take_while(|path| {
2200                // Only walk up the given directory, if any.
2201                options
2202                    .stop_discovery_at
2203                    .as_deref()
2204                    .and_then(Path::parent)
2205                    .is_none_or(|stop_discovery_at| stop_discovery_at != *path)
2206            })
2207            .find(|path| path.join("pyproject.toml").is_file())
2208            .ok_or(WorkspaceErrorKind::MissingPyprojectToml)?;
2209
2210        debug!("Found project root: {}", project_root.simplified_display());
2211
2212        // Fast path: The workspace is already cached.
2213        if let Some(cached) = workspace_cache.get(project_root, &options.members) {
2214            let cached = cached?;
2215            let virtual_project = if let Some(project_name) = cached.project_name {
2216                Self::Project(ProjectWorkspace {
2217                    project_root: project_root.to_path_buf(),
2218                    project_name,
2219                    workspace: cached.workspace,
2220                })
2221            } else {
2222                Self::NonProject(cached.workspace)
2223            };
2224            return Ok(virtual_project);
2225        }
2226
2227        // Read the current `pyproject.toml`.
2228        let pyproject_path = project_root.join("pyproject.toml");
2229        let contents = fs_err::tokio::read_to_string(&pyproject_path).await?;
2230        let pyproject_toml = PyProjectToml::from_string(contents, &pyproject_path)
2231            .map_err(|err| WorkspaceErrorKind::Toml(pyproject_path.clone(), Box::new(err)))?;
2232
2233        if let Some(project) = pyproject_toml.project.as_ref() {
2234            // If the `pyproject.toml` contains a `[project]` table, it's a project.
2235            let project = ProjectWorkspace::from_project(
2236                project_root,
2237                project,
2238                &pyproject_toml,
2239                options,
2240                cache,
2241                workspace_cache,
2242            )
2243            .await?;
2244            Ok(Self::Project(project))
2245        } else if let Some(workspace) = pyproject_toml
2246            .tool
2247            .as_ref()
2248            .and_then(|tool| tool.uv.as_ref())
2249            .and_then(|uv| uv.workspace.as_ref())
2250        {
2251            // Otherwise, if it contains a `tool.uv.workspace` table, it's a non-project workspace
2252            // root.
2253            let project_path = std::path::absolute(project_root)
2254                .map_err(WorkspaceErrorKind::Normalize)?
2255                .clone();
2256
2257            let result = Workspace::build(
2258                project_path.clone(),
2259                workspace.clone(),
2260                pyproject_toml,
2261                None,
2262                options,
2263                cache,
2264            )
2265            .await;
2266            if options.members == MemberDiscovery::All {
2267                workspace_cache.insert(result.clone(), &project_path);
2268            }
2269            Ok(Self::NonProject(result?))
2270        } else {
2271            // Otherwise it's a pyproject.toml that maybe contains dependency-groups
2272            // that we want to treat like a project/workspace to handle those uniformly
2273            let project_path = std::path::absolute(project_root)
2274                .map_err(WorkspaceErrorKind::Normalize)?
2275                .clone();
2276
2277            let result = Workspace::build(
2278                project_path.clone(),
2279                ToolUvWorkspace::default(),
2280                pyproject_toml,
2281                None,
2282                options,
2283                cache,
2284            )
2285            .await;
2286            if options.members == MemberDiscovery::All {
2287                workspace_cache.insert(result.clone(), &project_path);
2288            }
2289            Ok(Self::NonProject(result?))
2290        }
2291    }
2292
2293    /// Discover a project workspace with the member package.
2294    pub async fn discover_with_package(
2295        path: &Path,
2296        options: &DiscoveryOptions,
2297        cache: &Cache,
2298        workspace_cache: &WorkspaceCache,
2299        package: PackageName,
2300    ) -> Result<Self, WorkspaceError> {
2301        let workspace = Workspace::discover(path, options, cache, workspace_cache).await?;
2302        let Some(project_workspace) =
2303            Workspace::with_current_project(workspace.clone(), package.clone())
2304        else {
2305            return Err(WorkspaceError::from(WorkspaceErrorKind::NoSuchMember(
2306                package,
2307                workspace.install_path.clone(),
2308            )));
2309        };
2310        Ok(Self::Project(project_workspace))
2311    }
2312
2313    /// Update the `pyproject.toml` for the current project.
2314    ///
2315    /// Assumes that the project name is unchanged in the updated [`PyProjectToml`].
2316    ///
2317    /// Contract: There are no parallel workspace operations, this is the only thread operating on
2318    /// workspaces.
2319    ///
2320    /// The [`WorkspaceCache`] is passed to ensure the caller doesn't forget to clear it.
2321    pub fn update_member(
2322        self,
2323        pyproject_toml: PyProjectToml,
2324        workspace_cache: &WorkspaceCache,
2325    ) -> Result<Option<Self>, WorkspaceError> {
2326        // Our modifying operations run on a single workspace, clear that workspace.
2327        workspace_cache.invalidate_workspace(self.workspace());
2328        Ok(match self {
2329            Self::Project(project) => {
2330                let Some(project) = project.update_member(pyproject_toml)? else {
2331                    return Ok(None);
2332                };
2333                Some(Self::Project(project))
2334            }
2335            Self::NonProject(workspace) => {
2336                debug_assert_eq!(
2337                    Arc::strong_count(&workspace),
2338                    1,
2339                    "cannot modify workspace still in use",
2340                );
2341
2342                let workspace = Arc::unwrap_or_clone(workspace);
2343                // If this is a non-project workspace root, then by definition the root isn't a
2344                // member, so we can just update the top-level `pyproject.toml`.
2345                let workspace = Workspace {
2346                    pyproject_toml,
2347                    ..workspace
2348                };
2349                Some(Self::NonProject(Arc::new(workspace)))
2350            }
2351        })
2352    }
2353
2354    /// Return the root of the project.
2355    pub fn root(&self) -> &Path {
2356        match self {
2357            Self::Project(project) => project.project_root(),
2358            Self::NonProject(workspace) => workspace.install_path(),
2359        }
2360    }
2361
2362    /// Return the [`PyProjectToml`] of the project.
2363    pub fn pyproject_toml(&self) -> &PyProjectToml {
2364        match self {
2365            Self::Project(project) => project.current_project().pyproject_toml(),
2366            Self::NonProject(workspace) => &workspace.pyproject_toml,
2367        }
2368    }
2369
2370    /// Return the default dependency groups for the current project.
2371    pub fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
2372        match self {
2373            Self::Project(project) => project.default_groups(),
2374            Self::NonProject(workspace) => workspace.default_groups(),
2375        }
2376    }
2377
2378    /// Return the default dependency groups for a package selection.
2379    ///
2380    /// A single selected package uses that member's defaults. With zero or multiple packages,
2381    /// use the current project's defaults. Every selected package must belong to the workspace.
2382    pub fn default_groups_for_packages(
2383        &self,
2384        packages: &[PackageName],
2385    ) -> Result<DefaultGroups, DefaultGroupsError> {
2386        if let [name] = packages {
2387            self.workspace()
2388                .packages()
2389                .get(name)
2390                .ok_or_else(|| DefaultGroupsError::MissingPackage(name.clone()))?
2391                .default_groups()
2392        } else {
2393            for name in packages {
2394                if !self.workspace().packages().contains_key(name) {
2395                    return Err(DefaultGroupsError::MissingPackage(name.clone()));
2396                }
2397            }
2398            self.default_groups()
2399        }
2400    }
2401
2402    /// Return the [`Workspace`] of the project.
2403    pub fn workspace(&self) -> &Workspace {
2404        match self {
2405            Self::Project(project) => project.workspace(),
2406            Self::NonProject(workspace) => workspace,
2407        }
2408    }
2409
2410    /// Return the [`PackageName`] of the project, if available.
2411    pub fn project_name(&self) -> Option<&PackageName> {
2412        match self {
2413            Self::Project(project) => Some(project.project_name()),
2414            Self::NonProject(_) => None,
2415        }
2416    }
2417
2418    /// Returns `true` if the project is a virtual workspace root.
2419    pub fn is_non_project(&self) -> bool {
2420        matches!(self, Self::NonProject(_))
2421    }
2422}
2423
2424#[cfg(test)]
2425#[cfg(unix)] // Avoid path escaping for the unit tests
2426mod tests {
2427    use std::collections::BTreeMap;
2428    use std::env;
2429    use std::path::Path;
2430    use std::str::FromStr;
2431    use std::sync::Arc;
2432
2433    use anyhow::{Result, bail};
2434    use assert_fs::fixture::ChildPath;
2435    use assert_fs::prelude::*;
2436    use insta::{assert_json_snapshot, assert_snapshot};
2437
2438    use uv_cache::Cache;
2439    use uv_normalize::{GroupName, PackageName};
2440    use uv_pypi_types::DependencyGroupSpecifier;
2441
2442    use crate::pyproject::PyProjectToml;
2443    use crate::workspace::{
2444        DiscoveryOptions, MemberDiscovery, ProjectWorkspace, VirtualProject, Workspace,
2445    };
2446    use crate::{WorkspaceCache, WorkspaceError};
2447
2448    async fn workspace_test(folder: &str) -> (ProjectWorkspace, String) {
2449        let root_dir = env::current_dir()
2450            .unwrap()
2451            .parent()
2452            .unwrap()
2453            .parent()
2454            .unwrap()
2455            .join("test")
2456            .join("workspaces");
2457        let cache = Cache::from_path(root_dir.join(".uv_cache"));
2458        let project = ProjectWorkspace::discover(
2459            &root_dir.join(folder),
2460            &DiscoveryOptions::default(),
2461            &cache,
2462            &WorkspaceCache::default(),
2463        )
2464        .await
2465        .unwrap();
2466        let root_escaped = regex::escape(root_dir.to_string_lossy().as_ref());
2467        (project, root_escaped)
2468    }
2469
2470    async fn temporary_test(
2471        folder: &Path,
2472    ) -> Result<(ProjectWorkspace, String), (WorkspaceError, String)> {
2473        let root_escaped = regex::escape(folder.to_string_lossy().as_ref());
2474        let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
2475        let project = ProjectWorkspace::discover(
2476            folder,
2477            &DiscoveryOptions::default(),
2478            &cache,
2479            &WorkspaceCache::default(),
2480        )
2481        .await
2482        .map_err(|error| (error, root_escaped.clone()))?;
2483
2484        Ok((project, root_escaped))
2485    }
2486
2487    #[tokio::test]
2488    async fn albatross_in_example() {
2489        let (project, root_escaped) =
2490            workspace_test("albatross-in-example/examples/bird-feeder").await;
2491        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
2492        insta::with_settings!({filters => filters}, {
2493        assert_json_snapshot!(
2494            project,
2495            {
2496                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
2497            },
2498            @r#"
2499        {
2500          "project_root": "[ROOT]/albatross-in-example/examples/bird-feeder",
2501          "project_name": "bird-feeder",
2502          "workspace": {
2503            "install_path": "[ROOT]/albatross-in-example/examples/bird-feeder",
2504            "packages": {
2505              "bird-feeder": {
2506                "root": "[ROOT]/albatross-in-example/examples/bird-feeder",
2507                "project": {
2508                  "name": "bird-feeder",
2509                  "version": "1.0.0",
2510                  "requires-python": ">=3.12",
2511                  "dependencies": [
2512                    "iniconfig>=2,<3"
2513                  ],
2514                  "optional-dependencies": null
2515                },
2516                "pyproject_toml": "[PYPROJECT_TOML]"
2517              }
2518            },
2519            "required_members": {},
2520            "sources": {},
2521            "indexes": [],
2522            "pyproject_toml": {
2523              "project": {
2524                "name": "bird-feeder",
2525                "version": "1.0.0",
2526                "requires-python": ">=3.12",
2527                "dependencies": [
2528                  "iniconfig>=2,<3"
2529                ],
2530                "optional-dependencies": null
2531              },
2532              "tool": null,
2533              "dependency-groups": null
2534            }
2535          }
2536        }
2537        "#);
2538        });
2539    }
2540
2541    #[tokio::test]
2542    async fn albatross_project_in_excluded() {
2543        let (project, root_escaped) =
2544            workspace_test("albatross-project-in-excluded/excluded/bird-feeder").await;
2545        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
2546        insta::with_settings!({filters => filters}, {
2547            assert_json_snapshot!(
2548            project,
2549            {
2550                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
2551            },
2552            @r#"
2553            {
2554              "project_root": "[ROOT]/albatross-project-in-excluded/excluded/bird-feeder",
2555              "project_name": "bird-feeder",
2556              "workspace": {
2557                "install_path": "[ROOT]/albatross-project-in-excluded/excluded/bird-feeder",
2558                "packages": {
2559                  "bird-feeder": {
2560                    "root": "[ROOT]/albatross-project-in-excluded/excluded/bird-feeder",
2561                    "project": {
2562                      "name": "bird-feeder",
2563                      "version": "1.0.0",
2564                      "requires-python": ">=3.12",
2565                      "dependencies": [
2566                        "iniconfig>=2,<3"
2567                      ],
2568                      "optional-dependencies": null
2569                    },
2570                    "pyproject_toml": "[PYPROJECT_TOML]"
2571                  }
2572                },
2573                "required_members": {},
2574                "sources": {},
2575                "indexes": [],
2576                "pyproject_toml": {
2577                  "project": {
2578                    "name": "bird-feeder",
2579                    "version": "1.0.0",
2580                    "requires-python": ">=3.12",
2581                    "dependencies": [
2582                      "iniconfig>=2,<3"
2583                    ],
2584                    "optional-dependencies": null
2585                  },
2586                  "tool": null,
2587                  "dependency-groups": null
2588                }
2589              }
2590            }
2591            "#);
2592        });
2593    }
2594
2595    #[tokio::test]
2596    async fn albatross_root_workspace() {
2597        let (project, root_escaped) = workspace_test("albatross-root-workspace").await;
2598        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
2599        insta::with_settings!({filters => filters}, {
2600            assert_json_snapshot!(
2601            project,
2602            {
2603                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
2604            },
2605            @r#"
2606            {
2607              "project_root": "[ROOT]/albatross-root-workspace",
2608              "project_name": "albatross",
2609              "workspace": {
2610                "install_path": "[ROOT]/albatross-root-workspace",
2611                "packages": {
2612                  "albatross": {
2613                    "root": "[ROOT]/albatross-root-workspace",
2614                    "project": {
2615                      "name": "albatross",
2616                      "version": "0.1.0",
2617                      "requires-python": ">=3.12",
2618                      "dependencies": [
2619                        "bird-feeder",
2620                        "iniconfig>=2,<3"
2621                      ],
2622                      "optional-dependencies": null
2623                    },
2624                    "pyproject_toml": "[PYPROJECT_TOML]"
2625                  },
2626                  "bird-feeder": {
2627                    "root": "[ROOT]/albatross-root-workspace/packages/bird-feeder",
2628                    "project": {
2629                      "name": "bird-feeder",
2630                      "version": "1.0.0",
2631                      "requires-python": ">=3.8",
2632                      "dependencies": [
2633                        "iniconfig>=2,<3",
2634                        "seeds"
2635                      ],
2636                      "optional-dependencies": null
2637                    },
2638                    "pyproject_toml": "[PYPROJECT_TOML]"
2639                  },
2640                  "seeds": {
2641                    "root": "[ROOT]/albatross-root-workspace/packages/seeds",
2642                    "project": {
2643                      "name": "seeds",
2644                      "version": "1.0.0",
2645                      "requires-python": ">=3.12",
2646                      "dependencies": [
2647                        "idna==3.6"
2648                      ],
2649                      "optional-dependencies": null
2650                    },
2651                    "pyproject_toml": "[PYPROJECT_TOML]"
2652                  }
2653                },
2654                "required_members": {
2655                  "bird-feeder": null,
2656                  "seeds": null
2657                },
2658                "sources": {
2659                  "bird-feeder": [
2660                    {
2661                      "workspace": true,
2662                      "editable": null,
2663                      "extra": null,
2664                      "group": null
2665                    }
2666                  ]
2667                },
2668                "indexes": [],
2669                "pyproject_toml": {
2670                  "project": {
2671                    "name": "albatross",
2672                    "version": "0.1.0",
2673                    "requires-python": ">=3.12",
2674                    "dependencies": [
2675                      "bird-feeder",
2676                      "iniconfig>=2,<3"
2677                    ],
2678                    "optional-dependencies": null
2679                  },
2680                  "tool": {
2681                    "uv": {
2682                      "sources": {
2683                        "bird-feeder": [
2684                          {
2685                            "workspace": true,
2686                            "editable": null,
2687                            "extra": null,
2688                            "group": null
2689                          }
2690                        ]
2691                      },
2692                      "index": null,
2693                      "proxy-index": null,
2694                      "workspace": {
2695                        "members": [
2696                          "packages/*"
2697                        ],
2698                        "exclude": null
2699                      },
2700                      "managed": null,
2701                      "package": null,
2702                      "default-groups": null,
2703                      "dependency-groups": null,
2704                      "dev-dependencies": null,
2705                      "override-dependencies": null,
2706                      "exclude-dependencies": null,
2707                      "constraint-dependencies": null,
2708                      "build-constraint-dependencies": null,
2709                      "environments": null,
2710                      "required-environments": null,
2711                      "minimum-libc-version": null,
2712                      "conflicts": null,
2713                      "build-backend": null
2714                    }
2715                  },
2716                  "dependency-groups": null
2717                }
2718              }
2719            }
2720            "#);
2721        });
2722    }
2723
2724    #[tokio::test]
2725    async fn albatross_virtual_workspace() {
2726        let (project, root_escaped) =
2727            workspace_test("albatross-virtual-workspace/packages/albatross").await;
2728        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
2729        insta::with_settings!({filters => filters}, {
2730            assert_json_snapshot!(
2731            project,
2732            {
2733                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
2734            },
2735            @r#"
2736            {
2737              "project_root": "[ROOT]/albatross-virtual-workspace/packages/albatross",
2738              "project_name": "albatross",
2739              "workspace": {
2740                "install_path": "[ROOT]/albatross-virtual-workspace",
2741                "packages": {
2742                  "albatross": {
2743                    "root": "[ROOT]/albatross-virtual-workspace/packages/albatross",
2744                    "project": {
2745                      "name": "albatross",
2746                      "version": "0.1.0",
2747                      "requires-python": ">=3.12",
2748                      "dependencies": [
2749                        "bird-feeder",
2750                        "iniconfig>=2,<3"
2751                      ],
2752                      "optional-dependencies": null
2753                    },
2754                    "pyproject_toml": "[PYPROJECT_TOML]"
2755                  },
2756                  "bird-feeder": {
2757                    "root": "[ROOT]/albatross-virtual-workspace/packages/bird-feeder",
2758                    "project": {
2759                      "name": "bird-feeder",
2760                      "version": "1.0.0",
2761                      "requires-python": ">=3.12",
2762                      "dependencies": [
2763                        "anyio>=4.3.0,<5",
2764                        "seeds"
2765                      ],
2766                      "optional-dependencies": null
2767                    },
2768                    "pyproject_toml": "[PYPROJECT_TOML]"
2769                  },
2770                  "seeds": {
2771                    "root": "[ROOT]/albatross-virtual-workspace/packages/seeds",
2772                    "project": {
2773                      "name": "seeds",
2774                      "version": "1.0.0",
2775                      "requires-python": ">=3.12",
2776                      "dependencies": [
2777                        "idna==3.6"
2778                      ],
2779                      "optional-dependencies": null
2780                    },
2781                    "pyproject_toml": "[PYPROJECT_TOML]"
2782                  }
2783                },
2784                "required_members": {
2785                  "bird-feeder": null,
2786                  "seeds": null
2787                },
2788                "sources": {},
2789                "indexes": [],
2790                "pyproject_toml": {
2791                  "project": null,
2792                  "tool": {
2793                    "uv": {
2794                      "sources": null,
2795                      "index": null,
2796                      "proxy-index": null,
2797                      "workspace": {
2798                        "members": [
2799                          "packages/*"
2800                        ],
2801                        "exclude": null
2802                      },
2803                      "managed": null,
2804                      "package": null,
2805                      "default-groups": null,
2806                      "dependency-groups": null,
2807                      "dev-dependencies": null,
2808                      "override-dependencies": null,
2809                      "exclude-dependencies": null,
2810                      "constraint-dependencies": null,
2811                      "build-constraint-dependencies": null,
2812                      "environments": null,
2813                      "required-environments": null,
2814                      "minimum-libc-version": null,
2815                      "conflicts": null,
2816                      "build-backend": null
2817                    }
2818                  },
2819                  "dependency-groups": null
2820                }
2821              }
2822            }
2823            "#);
2824        });
2825    }
2826
2827    #[tokio::test]
2828    async fn workspace_cache_reuses_workspace_for_member() -> Result<()> {
2829        let root = tempfile::TempDir::new()?;
2830        let root = ChildPath::new(root.path());
2831
2832        root.child("pyproject.toml").write_str(
2833            r#"
2834            [project]
2835            name = "albatross"
2836            version = "0.1.0"
2837            requires-python = ">=3.12"
2838
2839            [tool.uv.workspace]
2840            members = ["packages/*"]
2841            "#,
2842        )?;
2843
2844        root.child("packages")
2845            .child("seeds")
2846            .child("pyproject.toml")
2847            .write_str(
2848                r#"
2849            [project]
2850            name = "seeds"
2851            version = "1.0.0"
2852            requires-python = ">=3.12"
2853            "#,
2854            )?;
2855
2856        let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
2857        let workspace_cache = WorkspaceCache::default();
2858        let root_workspace = Workspace::discover(
2859            root.as_ref(),
2860            &DiscoveryOptions::default(),
2861            &cache,
2862            &workspace_cache,
2863        )
2864        .await?;
2865        let member_workspace = Workspace::discover(
2866            root.child("packages").child("seeds").as_ref(),
2867            &DiscoveryOptions::default(),
2868            &cache,
2869            &workspace_cache,
2870        )
2871        .await?;
2872
2873        assert!(Arc::ptr_eq(&root_workspace, &member_workspace));
2874
2875        root.child("pyproject.toml")
2876            .write_str("not valid toml >.<")?;
2877        let member_project = ProjectWorkspace::from_maybe_project_root(
2878            root.child("packages").child("seeds").as_ref(),
2879            &DiscoveryOptions::default(),
2880            &cache,
2881            &workspace_cache,
2882        )
2883        .await?
2884        .expect("cached workspace member ignores invalid change in the meantime");
2885
2886        assert!(Arc::ptr_eq(&root_workspace, &member_project.workspace));
2887        assert_eq!(
2888            member_project.project_name(),
2889            &PackageName::from_str("seeds")?
2890        );
2891
2892        let root_project = ProjectWorkspace::discover(
2893            root.as_ref(),
2894            &DiscoveryOptions::default(),
2895            &cache,
2896            &workspace_cache,
2897        )
2898        .await?;
2899
2900        assert!(Arc::ptr_eq(&root_workspace, &root_project.workspace));
2901        assert_eq!(
2902            root_project.project_name(),
2903            &PackageName::from_str("albatross")?
2904        );
2905
2906        Ok(())
2907    }
2908
2909    /// A cached virtual root must not acquire the name of one of its members.
2910    #[tokio::test]
2911    async fn workspace_cache_preserves_virtual_root() -> Result<()> {
2912        let root = tempfile::TempDir::new()?;
2913        let root = ChildPath::new(root.path());
2914
2915        root.child("pyproject.toml").write_str(
2916            r#"
2917            [tool.uv.workspace]
2918            members = ["packages/*"]
2919            "#,
2920        )?;
2921
2922        root.child("packages")
2923            .child("seeds")
2924            .child("pyproject.toml")
2925            .write_str(
2926                r#"
2927            [project]
2928            name = "seeds"
2929            version = "1.0.0"
2930            requires-python = ">=3.12"
2931            "#,
2932            )?;
2933
2934        let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
2935        let workspace_cache = WorkspaceCache::default();
2936        let root_workspace = Workspace::discover(
2937            root.as_ref(),
2938            &DiscoveryOptions::default(),
2939            &cache,
2940            &workspace_cache,
2941        )
2942        .await?;
2943
2944        root.child("pyproject.toml")
2945            .write_str("not valid toml >.<")?;
2946        let virtual_root = VirtualProject::discover(
2947            root.as_ref(),
2948            &DiscoveryOptions::default(),
2949            &cache,
2950            &workspace_cache,
2951        )
2952        .await?;
2953
2954        match virtual_root {
2955            VirtualProject::NonProject(workspace) => {
2956                assert!(Arc::ptr_eq(&root_workspace, &workspace));
2957            }
2958            VirtualProject::Project(_) => bail!("expected a cached virtual workspace root"),
2959        }
2960        assert!(
2961            ProjectWorkspace::from_cache(
2962                root.as_ref(),
2963                &DiscoveryOptions::default(),
2964                &workspace_cache,
2965            )?
2966            .is_none()
2967        );
2968
2969        let member = VirtualProject::discover(
2970            root.child("packages").child("seeds").as_ref(),
2971            &DiscoveryOptions::default(),
2972            &cache,
2973            &workspace_cache,
2974        )
2975        .await?;
2976
2977        match member {
2978            VirtualProject::Project(project) => {
2979                assert!(Arc::ptr_eq(&root_workspace, &project.workspace));
2980                assert_eq!(project.project_name(), &PackageName::from_str("seeds")?);
2981            }
2982            VirtualProject::NonProject(_) => bail!("expected a cached workspace member project"),
2983        }
2984
2985        Ok(())
2986    }
2987
2988    #[tokio::test]
2989    async fn workspace_cache_does_not_store_partial_discovery() -> Result<()> {
2990        let root = tempfile::TempDir::new()?;
2991        let root = ChildPath::new(root.path());
2992
2993        root.child("pyproject.toml").write_str(
2994            r#"
2995            [project]
2996            name = "albatross"
2997            version = "0.1.0"
2998            requires-python = ">=3.12"
2999
3000            [tool.uv.workspace]
3001            members = ["packages/*"]
3002            "#,
3003        )?;
3004
3005        root.child("packages")
3006            .child("seeds")
3007            .child("pyproject.toml")
3008            .write_str(
3009                r#"
3010            [project]
3011            name = "seeds"
3012            version = "1.0.0"
3013            requires-python = ">=3.12"
3014            "#,
3015            )?;
3016
3017        let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
3018        let workspace_cache = WorkspaceCache::default();
3019        let partial_options = DiscoveryOptions {
3020            members: MemberDiscovery::None,
3021            ..DiscoveryOptions::default()
3022        };
3023        let partial_project =
3024            ProjectWorkspace::discover(root.as_ref(), &partial_options, &cache, &workspace_cache)
3025                .await?;
3026
3027        assert_eq!(partial_project.workspace().packages().len(), 1);
3028
3029        let member_project = ProjectWorkspace::discover(
3030            root.child("packages").child("seeds").as_ref(),
3031            &DiscoveryOptions::default(),
3032            &cache,
3033            &workspace_cache,
3034        )
3035        .await?;
3036        let seeds = PackageName::from_str("seeds")?;
3037
3038        assert_eq!(member_project.project_name(), &seeds);
3039        assert_eq!(member_project.workspace().packages().len(), 2);
3040        assert!(member_project.workspace().packages().contains_key(&seeds));
3041
3042        Ok(())
3043    }
3044
3045    #[tokio::test]
3046    async fn albatross_just_project() {
3047        let (project, root_escaped) = workspace_test("albatross-just-project").await;
3048        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3049        insta::with_settings!({filters => filters}, {
3050            assert_json_snapshot!(
3051            project,
3052            {
3053                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3054            },
3055            @r#"
3056            {
3057              "project_root": "[ROOT]/albatross-just-project",
3058              "project_name": "albatross",
3059              "workspace": {
3060                "install_path": "[ROOT]/albatross-just-project",
3061                "packages": {
3062                  "albatross": {
3063                    "root": "[ROOT]/albatross-just-project",
3064                    "project": {
3065                      "name": "albatross",
3066                      "version": "0.1.0",
3067                      "requires-python": ">=3.12",
3068                      "dependencies": [
3069                        "iniconfig>=2,<3"
3070                      ],
3071                      "optional-dependencies": null
3072                    },
3073                    "pyproject_toml": "[PYPROJECT_TOML]"
3074                  }
3075                },
3076                "required_members": {},
3077                "sources": {},
3078                "indexes": [],
3079                "pyproject_toml": {
3080                  "project": {
3081                    "name": "albatross",
3082                    "version": "0.1.0",
3083                    "requires-python": ">=3.12",
3084                    "dependencies": [
3085                      "iniconfig>=2,<3"
3086                    ],
3087                    "optional-dependencies": null
3088                  },
3089                  "tool": null,
3090                  "dependency-groups": null
3091                }
3092              }
3093            }
3094            "#);
3095        });
3096    }
3097
3098    #[tokio::test]
3099    async fn exclude_package() -> Result<()> {
3100        let root = tempfile::TempDir::new()?;
3101        let root = ChildPath::new(root.path());
3102
3103        // Create the root.
3104        root.child("pyproject.toml").write_str(
3105            r#"
3106            [project]
3107            name = "albatross"
3108            version = "0.1.0"
3109            requires-python = ">=3.12"
3110            dependencies = ["tqdm>=4,<5"]
3111
3112            [tool.uv.workspace]
3113            members = ["packages/*"]
3114            exclude = ["packages/bird-feeder"]
3115
3116            [build-system]
3117            requires = ["hatchling"]
3118            build-backend = "hatchling.build"
3119            "#,
3120        )?;
3121        root.child("albatross").child("__init__.py").touch()?;
3122
3123        // Create an included package (`seeds`).
3124        root.child("packages")
3125            .child("seeds")
3126            .child("pyproject.toml")
3127            .write_str(
3128                r#"
3129            [project]
3130            name = "seeds"
3131            version = "1.0.0"
3132            requires-python = ">=3.12"
3133            dependencies = ["idna==3.6"]
3134
3135            [build-system]
3136            requires = ["hatchling"]
3137            build-backend = "hatchling.build"
3138            "#,
3139            )?;
3140        root.child("packages")
3141            .child("seeds")
3142            .child("seeds")
3143            .child("__init__.py")
3144            .touch()?;
3145
3146        // Create an excluded package (`bird-feeder`).
3147        root.child("packages")
3148            .child("bird-feeder")
3149            .child("pyproject.toml")
3150            .write_str(
3151                r#"
3152            [project]
3153            name = "bird-feeder"
3154            version = "1.0.0"
3155            requires-python = ">=3.12"
3156            dependencies = ["anyio>=4.3.0,<5"]
3157
3158            [build-system]
3159            requires = ["hatchling"]
3160            build-backend = "hatchling.build"
3161            "#,
3162            )?;
3163        root.child("packages")
3164            .child("bird-feeder")
3165            .child("bird_feeder")
3166            .child("__init__.py")
3167            .touch()?;
3168
3169        let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3170        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3171        insta::with_settings!({filters => filters}, {
3172            assert_json_snapshot!(
3173            project,
3174            {
3175                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3176            },
3177            @r#"
3178            {
3179              "project_root": "[ROOT]",
3180              "project_name": "albatross",
3181              "workspace": {
3182                "install_path": "[ROOT]",
3183                "packages": {
3184                  "albatross": {
3185                    "root": "[ROOT]",
3186                    "project": {
3187                      "name": "albatross",
3188                      "version": "0.1.0",
3189                      "requires-python": ">=3.12",
3190                      "dependencies": [
3191                        "tqdm>=4,<5"
3192                      ],
3193                      "optional-dependencies": null
3194                    },
3195                    "pyproject_toml": "[PYPROJECT_TOML]"
3196                  },
3197                  "seeds": {
3198                    "root": "[ROOT]/packages/seeds",
3199                    "project": {
3200                      "name": "seeds",
3201                      "version": "1.0.0",
3202                      "requires-python": ">=3.12",
3203                      "dependencies": [
3204                        "idna==3.6"
3205                      ],
3206                      "optional-dependencies": null
3207                    },
3208                    "pyproject_toml": "[PYPROJECT_TOML]"
3209                  }
3210                },
3211                "required_members": {},
3212                "sources": {},
3213                "indexes": [],
3214                "pyproject_toml": {
3215                  "project": {
3216                    "name": "albatross",
3217                    "version": "0.1.0",
3218                    "requires-python": ">=3.12",
3219                    "dependencies": [
3220                      "tqdm>=4,<5"
3221                    ],
3222                    "optional-dependencies": null
3223                  },
3224                  "tool": {
3225                    "uv": {
3226                      "sources": null,
3227                      "index": null,
3228                      "proxy-index": null,
3229                      "workspace": {
3230                        "members": [
3231                          "packages/*"
3232                        ],
3233                        "exclude": [
3234                          "packages/bird-feeder"
3235                        ]
3236                      },
3237                      "managed": null,
3238                      "package": null,
3239                      "default-groups": null,
3240                      "dependency-groups": null,
3241                      "dev-dependencies": null,
3242                      "override-dependencies": null,
3243                      "exclude-dependencies": null,
3244                      "constraint-dependencies": null,
3245                      "build-constraint-dependencies": null,
3246                      "environments": null,
3247                      "required-environments": null,
3248                      "minimum-libc-version": null,
3249                      "conflicts": null,
3250                      "build-backend": null
3251                    }
3252                  },
3253                  "dependency-groups": null
3254                }
3255              }
3256            }
3257            "#);
3258        });
3259
3260        // Rewrite the members to both include and exclude `bird-feeder` by name.
3261        root.child("pyproject.toml").write_str(
3262            r#"
3263            [project]
3264            name = "albatross"
3265            version = "0.1.0"
3266            requires-python = ">=3.12"
3267            dependencies = ["tqdm>=4,<5"]
3268
3269            [tool.uv.workspace]
3270            members = ["packages/seeds", "packages/bird-feeder"]
3271            exclude = ["packages/bird-feeder"]
3272
3273            [build-system]
3274            requires = ["hatchling"]
3275            build-backend = "hatchling.build"
3276            "#,
3277        )?;
3278
3279        // `bird-feeder` should still be excluded.
3280        let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3281        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3282        insta::with_settings!({filters => filters}, {
3283            assert_json_snapshot!(
3284            project,
3285            {
3286                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3287            },
3288            @r#"
3289            {
3290              "project_root": "[ROOT]",
3291              "project_name": "albatross",
3292              "workspace": {
3293                "install_path": "[ROOT]",
3294                "packages": {
3295                  "albatross": {
3296                    "root": "[ROOT]",
3297                    "project": {
3298                      "name": "albatross",
3299                      "version": "0.1.0",
3300                      "requires-python": ">=3.12",
3301                      "dependencies": [
3302                        "tqdm>=4,<5"
3303                      ],
3304                      "optional-dependencies": null
3305                    },
3306                    "pyproject_toml": "[PYPROJECT_TOML]"
3307                  },
3308                  "seeds": {
3309                    "root": "[ROOT]/packages/seeds",
3310                    "project": {
3311                      "name": "seeds",
3312                      "version": "1.0.0",
3313                      "requires-python": ">=3.12",
3314                      "dependencies": [
3315                        "idna==3.6"
3316                      ],
3317                      "optional-dependencies": null
3318                    },
3319                    "pyproject_toml": "[PYPROJECT_TOML]"
3320                  }
3321                },
3322                "required_members": {},
3323                "sources": {},
3324                "indexes": [],
3325                "pyproject_toml": {
3326                  "project": {
3327                    "name": "albatross",
3328                    "version": "0.1.0",
3329                    "requires-python": ">=3.12",
3330                    "dependencies": [
3331                      "tqdm>=4,<5"
3332                    ],
3333                    "optional-dependencies": null
3334                  },
3335                  "tool": {
3336                    "uv": {
3337                      "sources": null,
3338                      "index": null,
3339                      "proxy-index": null,
3340                      "workspace": {
3341                        "members": [
3342                          "packages/seeds",
3343                          "packages/bird-feeder"
3344                        ],
3345                        "exclude": [
3346                          "packages/bird-feeder"
3347                        ]
3348                      },
3349                      "managed": null,
3350                      "package": null,
3351                      "default-groups": null,
3352                      "dependency-groups": null,
3353                      "dev-dependencies": null,
3354                      "override-dependencies": null,
3355                      "exclude-dependencies": null,
3356                      "constraint-dependencies": null,
3357                      "build-constraint-dependencies": null,
3358                      "environments": null,
3359                      "required-environments": null,
3360                      "minimum-libc-version": null,
3361                      "conflicts": null,
3362                      "build-backend": null
3363                    }
3364                  },
3365                  "dependency-groups": null
3366                }
3367              }
3368            }
3369            "#);
3370        });
3371
3372        // Rewrite the exclusion to use the top-level directory (`packages`).
3373        root.child("pyproject.toml").write_str(
3374            r#"
3375            [project]
3376            name = "albatross"
3377            version = "0.1.0"
3378            requires-python = ">=3.12"
3379            dependencies = ["tqdm>=4,<5"]
3380
3381            [tool.uv.workspace]
3382            members = ["packages/seeds", "packages/bird-feeder"]
3383            exclude = ["packages"]
3384
3385            [build-system]
3386            requires = ["hatchling"]
3387            build-backend = "hatchling.build"
3388            "#,
3389        )?;
3390
3391        // `bird-feeder` should now be included.
3392        let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3393        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3394        insta::with_settings!({filters => filters}, {
3395            assert_json_snapshot!(
3396            project,
3397            {
3398                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3399            },
3400            @r#"
3401            {
3402              "project_root": "[ROOT]",
3403              "project_name": "albatross",
3404              "workspace": {
3405                "install_path": "[ROOT]",
3406                "packages": {
3407                  "albatross": {
3408                    "root": "[ROOT]",
3409                    "project": {
3410                      "name": "albatross",
3411                      "version": "0.1.0",
3412                      "requires-python": ">=3.12",
3413                      "dependencies": [
3414                        "tqdm>=4,<5"
3415                      ],
3416                      "optional-dependencies": null
3417                    },
3418                    "pyproject_toml": "[PYPROJECT_TOML]"
3419                  },
3420                  "bird-feeder": {
3421                    "root": "[ROOT]/packages/bird-feeder",
3422                    "project": {
3423                      "name": "bird-feeder",
3424                      "version": "1.0.0",
3425                      "requires-python": ">=3.12",
3426                      "dependencies": [
3427                        "anyio>=4.3.0,<5"
3428                      ],
3429                      "optional-dependencies": null
3430                    },
3431                    "pyproject_toml": "[PYPROJECT_TOML]"
3432                  },
3433                  "seeds": {
3434                    "root": "[ROOT]/packages/seeds",
3435                    "project": {
3436                      "name": "seeds",
3437                      "version": "1.0.0",
3438                      "requires-python": ">=3.12",
3439                      "dependencies": [
3440                        "idna==3.6"
3441                      ],
3442                      "optional-dependencies": null
3443                    },
3444                    "pyproject_toml": "[PYPROJECT_TOML]"
3445                  }
3446                },
3447                "required_members": {},
3448                "sources": {},
3449                "indexes": [],
3450                "pyproject_toml": {
3451                  "project": {
3452                    "name": "albatross",
3453                    "version": "0.1.0",
3454                    "requires-python": ">=3.12",
3455                    "dependencies": [
3456                      "tqdm>=4,<5"
3457                    ],
3458                    "optional-dependencies": null
3459                  },
3460                  "tool": {
3461                    "uv": {
3462                      "sources": null,
3463                      "index": null,
3464                      "proxy-index": null,
3465                      "workspace": {
3466                        "members": [
3467                          "packages/seeds",
3468                          "packages/bird-feeder"
3469                        ],
3470                        "exclude": [
3471                          "packages"
3472                        ]
3473                      },
3474                      "managed": null,
3475                      "package": null,
3476                      "default-groups": null,
3477                      "dependency-groups": null,
3478                      "dev-dependencies": null,
3479                      "override-dependencies": null,
3480                      "exclude-dependencies": null,
3481                      "constraint-dependencies": null,
3482                      "build-constraint-dependencies": null,
3483                      "environments": null,
3484                      "required-environments": null,
3485                      "minimum-libc-version": null,
3486                      "conflicts": null,
3487                      "build-backend": null
3488                    }
3489                  },
3490                  "dependency-groups": null
3491                }
3492              }
3493            }
3494            "#);
3495        });
3496
3497        // Rewrite the exclusion to use the top-level directory with a glob (`packages/*`).
3498        root.child("pyproject.toml").write_str(
3499            r#"
3500            [project]
3501            name = "albatross"
3502            version = "0.1.0"
3503            requires-python = ">=3.12"
3504            dependencies = ["tqdm>=4,<5"]
3505
3506            [tool.uv.workspace]
3507            members = ["packages/seeds", "packages/bird-feeder"]
3508            exclude = ["packages/*"]
3509
3510            [build-system]
3511            requires = ["hatchling"]
3512            build-backend = "hatchling.build"
3513            "#,
3514        )?;
3515
3516        // `bird-feeder` and `seeds` should now be excluded.
3517        let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3518        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3519        insta::with_settings!({filters => filters}, {
3520            assert_json_snapshot!(
3521            project,
3522            {
3523                ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3524            },
3525            @r#"
3526            {
3527              "project_root": "[ROOT]",
3528              "project_name": "albatross",
3529              "workspace": {
3530                "install_path": "[ROOT]",
3531                "packages": {
3532                  "albatross": {
3533                    "root": "[ROOT]",
3534                    "project": {
3535                      "name": "albatross",
3536                      "version": "0.1.0",
3537                      "requires-python": ">=3.12",
3538                      "dependencies": [
3539                        "tqdm>=4,<5"
3540                      ],
3541                      "optional-dependencies": null
3542                    },
3543                    "pyproject_toml": "[PYPROJECT_TOML]"
3544                  }
3545                },
3546                "required_members": {},
3547                "sources": {},
3548                "indexes": [],
3549                "pyproject_toml": {
3550                  "project": {
3551                    "name": "albatross",
3552                    "version": "0.1.0",
3553                    "requires-python": ">=3.12",
3554                    "dependencies": [
3555                      "tqdm>=4,<5"
3556                    ],
3557                    "optional-dependencies": null
3558                  },
3559                  "tool": {
3560                    "uv": {
3561                      "sources": null,
3562                      "index": null,
3563                      "proxy-index": null,
3564                      "workspace": {
3565                        "members": [
3566                          "packages/seeds",
3567                          "packages/bird-feeder"
3568                        ],
3569                        "exclude": [
3570                          "packages/*"
3571                        ]
3572                      },
3573                      "managed": null,
3574                      "package": null,
3575                      "default-groups": null,
3576                      "dependency-groups": null,
3577                      "dev-dependencies": null,
3578                      "override-dependencies": null,
3579                      "exclude-dependencies": null,
3580                      "constraint-dependencies": null,
3581                      "build-constraint-dependencies": null,
3582                      "environments": null,
3583                      "required-environments": null,
3584                      "minimum-libc-version": null,
3585                      "conflicts": null,
3586                      "build-backend": null
3587                    }
3588                  },
3589                  "dependency-groups": null
3590                }
3591              }
3592            }
3593            "#);
3594        });
3595
3596        Ok(())
3597    }
3598
3599    #[tokio::test]
3600    async fn exclude_package_with_normalized_glob_and_escaped_root() -> Result<()> {
3601        let temp_dir = tempfile::TempDir::new()?;
3602        let temp_dir_root = ChildPath::new(temp_dir.path());
3603        let root = temp_dir_root.child("workspace[glob]?");
3604
3605        root.child("pyproject.toml").write_str(
3606            r#"
3607            [project]
3608            name = "albatross"
3609            version = "0.1.0"
3610            requires-python = ">=3.12"
3611
3612            [tool.uv.workspace]
3613            members = ["./packages/*", "../external-*"]
3614            exclude = [
3615                "packages/excluded-borrowed-*",
3616                "./ignored/../packages/excluded",
3617                "./packages/./excluded-glob-*",
3618                "../external-excluded",
3619            ]
3620            "#,
3621        )?;
3622
3623        for member in [
3624            "included",
3625            "excluded",
3626            "excluded-glob-one",
3627            "excluded-borrowed-one",
3628        ] {
3629            root.child("packages")
3630                .child(member)
3631                .child("pyproject.toml")
3632                .write_str(&format!(
3633                    r#"
3634                    [project]
3635                    name = "{member}"
3636                    version = "0.1.0"
3637                    requires-python = ">=3.12"
3638                    "#,
3639                ))?;
3640        }
3641
3642        for member in ["external-included", "external-excluded"] {
3643            temp_dir_root
3644                .child(member)
3645                .child("pyproject.toml")
3646                .write_str(&format!(
3647                    r#"
3648                    [project]
3649                    name = "{member}"
3650                    version = "0.1.0"
3651                    requires-python = ">=3.12"
3652                    "#,
3653                ))?;
3654        }
3655
3656        let (project, _) = temporary_test(root.as_ref())
3657            .await
3658            .map_err(|(error, _)| error)?;
3659        assert_json_snapshot!(
3660            project.workspace().packages().keys().collect::<Vec<_>>(),
3661            @r#"
3662        [
3663          "albatross",
3664          "external-included",
3665          "included"
3666        ]
3667        "#
3668        );
3669
3670        Ok(())
3671    }
3672
3673    #[test]
3674    fn read_dependency_groups() {
3675        let toml = r#"
3676[dependency-groups]
3677foo = ["a", {include-group = "bar"}]
3678bar = ["b"]
3679future = [{include-group = "bar", unknown = "value"}]
3680"#;
3681
3682        let result = PyProjectToml::from_string(toml.to_string(), "pyproject.toml")
3683            .expect("Deserialization should succeed");
3684
3685        let groups = result
3686            .dependency_groups
3687            .expect("`dependency-groups` should be present");
3688        let foo = groups
3689            .get(&GroupName::from_str("foo").unwrap())
3690            .expect("Group `foo` should be present");
3691        assert_eq!(
3692            foo,
3693            &[
3694                DependencyGroupSpecifier::Requirement("a".to_string()),
3695                DependencyGroupSpecifier::IncludeGroup {
3696                    include_group: GroupName::from_str("bar").unwrap(),
3697                }
3698            ]
3699        );
3700
3701        let bar = groups
3702            .get(&GroupName::from_str("bar").unwrap())
3703            .expect("Group `bar` should be present");
3704        assert_eq!(
3705            bar,
3706            &[DependencyGroupSpecifier::Requirement("b".to_string())]
3707        );
3708
3709        let future = groups
3710            .get(&GroupName::from_str("future").unwrap())
3711            .expect("Group `future` should be present");
3712        assert_eq!(
3713            future,
3714            &[DependencyGroupSpecifier::Object(BTreeMap::from([
3715                ("include-group".to_string(), "bar".to_string()),
3716                ("unknown".to_string(), "value".to_string()),
3717            ]))]
3718        );
3719    }
3720
3721    #[test]
3722    fn reject_colliding_optional_dependency_names() {
3723        let err = PyProjectToml::from_string(
3724            r#"
3725[project]
3726name = "example"
3727version = "1.0.0"
3728
3729[project.optional-dependencies]
3730foo-bar = ["anyio"]
3731foo_bar = ["iniconfig"]
3732"#
3733            .to_string(),
3734            "pyproject.toml",
3735        )
3736        .unwrap_err();
3737
3738        assert_snapshot!(err.to_string(), @r#"
3739        TOML parse error at line 6, column 1
3740          |
3741        6 | [project.optional-dependencies]
3742          | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3743        duplicate normalized extra name `foo-bar`
3744        "#);
3745    }
3746
3747    #[tokio::test]
3748    async fn nested_workspace() -> Result<()> {
3749        let root = tempfile::TempDir::new()?;
3750        let root = ChildPath::new(root.path());
3751
3752        // Create the root.
3753        root.child("pyproject.toml").write_str(
3754            r#"
3755            [project]
3756            name = "albatross"
3757            version = "0.1.0"
3758            requires-python = ">=3.12"
3759            dependencies = ["tqdm>=4,<5"]
3760
3761            [tool.uv.workspace]
3762            members = ["packages/*"]
3763            "#,
3764        )?;
3765
3766        // Create an included package (`seeds`).
3767        root.child("packages")
3768            .child("seeds")
3769            .child("pyproject.toml")
3770            .write_str(
3771                r#"
3772            [project]
3773            name = "seeds"
3774            version = "1.0.0"
3775            requires-python = ">=3.12"
3776            dependencies = ["idna==3.6"]
3777
3778            [tool.uv.workspace]
3779            members = ["nested_packages/*"]
3780            "#,
3781            )?;
3782
3783        let (error, root_escaped) = temporary_test(root.as_ref()).await.unwrap_err();
3784        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3785        insta::with_settings!({filters => filters}, {
3786            assert_snapshot!(
3787                error,
3788            @"Nested workspaces are not supported, but workspace member has a `tool.uv.workspace` table: [ROOT]/packages/seeds");
3789        });
3790
3791        Ok(())
3792    }
3793
3794    #[tokio::test]
3795    async fn duplicate_names() -> Result<()> {
3796        let root = tempfile::TempDir::new()?;
3797        let root = ChildPath::new(root.path());
3798
3799        // Create the root.
3800        root.child("pyproject.toml").write_str(
3801            r#"
3802            [project]
3803            name = "albatross"
3804            version = "0.1.0"
3805            requires-python = ">=3.12"
3806            dependencies = ["tqdm>=4,<5"]
3807
3808            [tool.uv.workspace]
3809            members = ["packages/*"]
3810            "#,
3811        )?;
3812
3813        // Create an included package (`seeds`).
3814        root.child("packages")
3815            .child("seeds")
3816            .child("pyproject.toml")
3817            .write_str(
3818                r#"
3819            [project]
3820            name = "seeds"
3821            version = "1.0.0"
3822            requires-python = ">=3.12"
3823            dependencies = ["idna==3.6"]
3824
3825            [tool.uv.workspace]
3826            members = ["nested_packages/*"]
3827            "#,
3828            )?;
3829
3830        // Create an included package (`seeds2`).
3831        root.child("packages")
3832            .child("seeds2")
3833            .child("pyproject.toml")
3834            .write_str(
3835                r#"
3836            [project]
3837            name = "seeds"
3838            version = "1.0.0"
3839            requires-python = ">=3.12"
3840            dependencies = ["idna==3.6"]
3841
3842            [tool.uv.workspace]
3843            members = ["nested_packages/*"]
3844            "#,
3845            )?;
3846
3847        let (error, root_escaped) = temporary_test(root.as_ref()).await.unwrap_err();
3848        let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3849        insta::with_settings!({filters => filters}, {
3850            assert_snapshot!(
3851                error,
3852            @"Two workspace members are both named `seeds`: `[ROOT]/packages/seeds` and `[ROOT]/packages/seeds2`");
3853        });
3854
3855        Ok(())
3856    }
3857}