1use 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#[derive(Debug)]
40pub enum ProjectEnvironmentSelection {
41 Default,
43 Override(PathBuf),
45 Active(PathBuf),
47}
48
49impl ProjectEnvironmentSelection {
50 pub fn from_install_path(install_path: &Path, active: ActiveEnvironment) -> Self {
52 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 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 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 pub fn is_default(&self) -> bool {
128 matches!(self, Self::Default)
129 }
130
131 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#[derive(Debug, Clone)]
146struct CachedWorkspace {
147 workspace: Arc<Workspace>,
148 project_name: Option<PackageName>,
150}
151
152#[derive(Debug, Default, Clone)]
166pub struct WorkspaceCache {
167 workspaces: Arc<FxOnceMap<PathBuf, CachedWorkspaceResult>>,
168}
169
170impl WorkspaceCache {
171 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 if package.root == workspace.install_path {
182 root_project_name = Some(name.clone());
183 continue;
184 }
185 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 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 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 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
261fn 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 #[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 #[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 #[error("Failed to normalize workspace member path")]
353 Normalize(#[source] std::io::Error),
354}
355
356#[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 #[default]
371 All,
372 Existing,
374 None,
376 Ignore(BTreeSet<PathBuf>),
378}
379
380#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
381pub struct DiscoveryOptions {
382 pub stop_discovery_at: Option<PathBuf>,
388 pub members: MemberDiscovery,
390}
391
392#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
394pub enum RequiresPythonDeclaration {
395 Member(PackageName, Option<GroupName>),
397 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#[derive(Debug, Clone)]
417#[cfg_attr(test, derive(serde::Serialize))]
418pub struct Workspace {
419 install_path: PathBuf,
424 packages: WorkspaceMembers,
426 required_members: BTreeMap<PackageName, Editability>,
429 sources: BTreeMap<PackageName, Sources>,
433 indexes: Vec<Index>,
437 pyproject_toml: PyProjectToml,
439}
440
441impl Workspace {
442 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 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 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 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 workspace
529 } else if pyproject_toml.project.is_none() {
530 return Err(WorkspaceError::from(WorkspaceErrorKind::MissingProject(
532 pyproject_path,
533 )));
534 } else if let Some(workspace) = find_workspace(&project_path, options, cache).await? {
535 workspace
537 } else {
538 (
540 project_path.clone(),
541 ToolUvWorkspace::default(),
542 pyproject_toml.clone(),
543 )
544 };
545
546 if options.members == MemberDiscovery::All {
547 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 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 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 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 let workspace_pyproject_toml = pyproject_toml.clone();
630
631 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 member.pyproject_toml = pyproject_toml;
642
643 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 member.pyproject_toml = pyproject_toml;
661
662 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 pub fn is_non_project(&self) -> bool {
677 !self
678 .packages
679 .values()
680 .any(|member| *member.root() == self.install_path)
681 }
682
683 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 pub fn required_members(&self) -> &BTreeMap<PackageName, Editability> {
724 &self.required_members
725 }
726
727 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 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 fn is_required_member(&self, name: &PackageName) -> bool {
796 self.required_members().contains_key(name)
797 }
798
799 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 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 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 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 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 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 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 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 pub fn requirements(&self) -> Vec<uv_pep508::Requirement<VerbatimParsedUrl>> {
969 Vec::new()
970 }
971
972 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 Ok(BTreeMap::default())
990 } else {
991 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 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 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 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 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 pub fn install_path(&self) -> &PathBuf {
1059 &self.install_path
1060 }
1061
1062 pub fn environment_selection(&self, active: ActiveEnvironment) -> ProjectEnvironmentSelection {
1071 ProjectEnvironmentSelection::from_install_path(&self.install_path, active)
1072 }
1073
1074 pub fn packages(&self) -> &BTreeMap<PackageName, WorkspaceMember> {
1076 &self.packages
1077 }
1078
1079 pub fn sources(&self) -> &BTreeMap<PackageName, Sources> {
1081 &self.sources
1082 }
1083
1084 pub fn indexes(&self) -> &[Index] {
1086 &self.indexes
1087 }
1088
1089 pub fn pyproject_toml(&self) -> &PyProjectToml {
1091 &self.pyproject_toml
1092 }
1093
1094 pub fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1096 self.pyproject_toml.default_groups()
1097 }
1098
1099 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 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 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 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 let mut seen = FxHashSet::default();
1230
1231 let external_cache_root = options
1232 .stop_discovery_at
1233 .is_none()
1234 .then(|| {
1235 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 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 let mut exclusions = None;
1266
1267 for member_glob in workspace_definition.members.as_deref().unwrap_or_default() {
1269 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 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 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 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 if err.kind() == std::io::ErrorKind::NotFound {
1362 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 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 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 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 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#[derive(Debug, Clone, PartialEq)]
1481#[cfg_attr(test, derive(serde::Serialize))]
1482pub struct WorkspaceMember {
1483 root: PathBuf,
1485 project: Project,
1488 pyproject_toml: PyProjectToml,
1490}
1491
1492impl WorkspaceMember {
1493 pub fn root(&self) -> &PathBuf {
1495 &self.root
1496 }
1497
1498 pub fn project(&self) -> &Project {
1501 &self.project
1502 }
1503
1504 pub fn pyproject_toml(&self) -> &PyProjectToml {
1506 &self.pyproject_toml
1507 }
1508
1509 pub fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1513 self.pyproject_toml.default_groups()
1514 }
1515}
1516
1517#[derive(Debug, Clone)]
1595#[cfg_attr(test, derive(serde::Serialize))]
1596pub struct ProjectWorkspace {
1597 project_root: PathBuf,
1599 project_name: PackageName,
1601 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 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 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 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 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 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 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 let pyproject_path = project_root.join("pyproject.toml");
1708 let Ok(contents) = fs_err::tokio::read_to_string(&pyproject_path).await else {
1709 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 let Some(project) = pyproject_toml.project.clone() else {
1717 return Ok(None);
1719 };
1720
1721 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 pub fn project_root(&self) -> &Path {
1741 &self.project_root
1742 }
1743
1744 pub fn project_name(&self) -> &PackageName {
1746 &self.project_name
1747 }
1748
1749 pub fn workspace(&self) -> &Workspace {
1751 &self.workspace
1752 }
1753
1754 pub fn current_project(&self) -> &WorkspaceMember {
1756 &self.workspace().packages[&self.project_name]
1757 }
1758
1759 fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
1761 self.current_project().default_groups()
1762 }
1763
1764 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 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 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 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 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 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 ¤t_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 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 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
1909async 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 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 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 for workspace_root in project_root
1939 .ancestors()
1940 .take_while(|path| {
1941 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 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 Ok(Some((
1988 workspace_root.to_path_buf(),
1989 workspace.clone(),
1990 pyproject_toml,
1991 )))
1992 } else if pyproject_toml.project.is_some() {
1993 debug!(
2012 "Project is contained in non-workspace project: {}",
2013 workspace_root.simplified_display()
2014 );
2015 Ok(None)
2016 } else {
2017 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
2029fn 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 return false;
2047 };
2048
2049 if entry.path().is_dir() {
2051 continue;
2052 }
2053
2054 return false;
2056 }
2057
2058 true
2059}
2060
2061fn 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#[derive(Debug)]
2072struct WorkspaceExclusions<'workspace> {
2073 workspace_root: &'workspace Path,
2074 patterns: Vec<WorkspaceExclusion<'workspace>>,
2075}
2076
2077#[derive(Debug)]
2079enum WorkspaceExclusion<'workspace> {
2080 Relative(&'workspace Pattern),
2081 Absolute(Pattern),
2082}
2083
2084impl<'workspace> WorkspaceExclusions<'workspace> {
2085 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 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 fn compile_pattern(
2120 workspace_root: &Path,
2121 exclude_glob: &'workspace Pattern,
2122 ) -> Result<WorkspaceExclusion<'workspace>, WorkspaceError> {
2123 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
2140fn 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 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#[derive(Debug, Clone)]
2172pub enum VirtualProject {
2173 Project(ProjectWorkspace),
2175 NonProject(Arc<Workspace>),
2177}
2178
2179impl VirtualProject {
2180 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 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 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 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 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 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 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 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 pub fn update_member(
2322 self,
2323 pyproject_toml: PyProjectToml,
2324 workspace_cache: &WorkspaceCache,
2325 ) -> Result<Option<Self>, WorkspaceError> {
2326 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 let workspace = Workspace {
2346 pyproject_toml,
2347 ..workspace
2348 };
2349 Some(Self::NonProject(Arc::new(workspace)))
2350 }
2351 })
2352 }
2353
2354 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 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 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 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 pub fn workspace(&self) -> &Workspace {
2404 match self {
2405 Self::Project(project) => project.workspace(),
2406 Self::NonProject(workspace) => workspace,
2407 }
2408 }
2409
2410 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 pub fn is_non_project(&self) -> bool {
2420 matches!(self, Self::NonProject(_))
2421 }
2422}
2423
2424#[cfg(test)]
2425#[cfg(unix)] mod 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 "workspace": {
2694 "members": [
2695 "packages/*"
2696 ],
2697 "exclude": null
2698 },
2699 "managed": null,
2700 "package": null,
2701 "default-groups": null,
2702 "dependency-groups": null,
2703 "dev-dependencies": null,
2704 "override-dependencies": null,
2705 "exclude-dependencies": null,
2706 "constraint-dependencies": null,
2707 "build-constraint-dependencies": null,
2708 "environments": null,
2709 "required-environments": null,
2710 "minimum-libc-version": null,
2711 "conflicts": null,
2712 "build-backend": null
2713 }
2714 },
2715 "dependency-groups": null
2716 }
2717 }
2718 }
2719 "#);
2720 });
2721 }
2722
2723 #[tokio::test]
2724 async fn albatross_virtual_workspace() {
2725 let (project, root_escaped) =
2726 workspace_test("albatross-virtual-workspace/packages/albatross").await;
2727 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
2728 insta::with_settings!({filters => filters}, {
2729 assert_json_snapshot!(
2730 project,
2731 {
2732 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
2733 },
2734 @r#"
2735 {
2736 "project_root": "[ROOT]/albatross-virtual-workspace/packages/albatross",
2737 "project_name": "albatross",
2738 "workspace": {
2739 "install_path": "[ROOT]/albatross-virtual-workspace",
2740 "packages": {
2741 "albatross": {
2742 "root": "[ROOT]/albatross-virtual-workspace/packages/albatross",
2743 "project": {
2744 "name": "albatross",
2745 "version": "0.1.0",
2746 "requires-python": ">=3.12",
2747 "dependencies": [
2748 "bird-feeder",
2749 "iniconfig>=2,<3"
2750 ],
2751 "optional-dependencies": null
2752 },
2753 "pyproject_toml": "[PYPROJECT_TOML]"
2754 },
2755 "bird-feeder": {
2756 "root": "[ROOT]/albatross-virtual-workspace/packages/bird-feeder",
2757 "project": {
2758 "name": "bird-feeder",
2759 "version": "1.0.0",
2760 "requires-python": ">=3.12",
2761 "dependencies": [
2762 "anyio>=4.3.0,<5",
2763 "seeds"
2764 ],
2765 "optional-dependencies": null
2766 },
2767 "pyproject_toml": "[PYPROJECT_TOML]"
2768 },
2769 "seeds": {
2770 "root": "[ROOT]/albatross-virtual-workspace/packages/seeds",
2771 "project": {
2772 "name": "seeds",
2773 "version": "1.0.0",
2774 "requires-python": ">=3.12",
2775 "dependencies": [
2776 "idna==3.6"
2777 ],
2778 "optional-dependencies": null
2779 },
2780 "pyproject_toml": "[PYPROJECT_TOML]"
2781 }
2782 },
2783 "required_members": {
2784 "bird-feeder": null,
2785 "seeds": null
2786 },
2787 "sources": {},
2788 "indexes": [],
2789 "pyproject_toml": {
2790 "project": null,
2791 "tool": {
2792 "uv": {
2793 "sources": null,
2794 "index": null,
2795 "workspace": {
2796 "members": [
2797 "packages/*"
2798 ],
2799 "exclude": null
2800 },
2801 "managed": null,
2802 "package": null,
2803 "default-groups": null,
2804 "dependency-groups": null,
2805 "dev-dependencies": null,
2806 "override-dependencies": null,
2807 "exclude-dependencies": null,
2808 "constraint-dependencies": null,
2809 "build-constraint-dependencies": null,
2810 "environments": null,
2811 "required-environments": null,
2812 "minimum-libc-version": null,
2813 "conflicts": null,
2814 "build-backend": null
2815 }
2816 },
2817 "dependency-groups": null
2818 }
2819 }
2820 }
2821 "#);
2822 });
2823 }
2824
2825 #[tokio::test]
2826 async fn workspace_cache_reuses_workspace_for_member() -> Result<()> {
2827 let root = tempfile::TempDir::new()?;
2828 let root = ChildPath::new(root.path());
2829
2830 root.child("pyproject.toml").write_str(
2831 r#"
2832 [project]
2833 name = "albatross"
2834 version = "0.1.0"
2835 requires-python = ">=3.12"
2836
2837 [tool.uv.workspace]
2838 members = ["packages/*"]
2839 "#,
2840 )?;
2841
2842 root.child("packages")
2843 .child("seeds")
2844 .child("pyproject.toml")
2845 .write_str(
2846 r#"
2847 [project]
2848 name = "seeds"
2849 version = "1.0.0"
2850 requires-python = ">=3.12"
2851 "#,
2852 )?;
2853
2854 let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
2855 let workspace_cache = WorkspaceCache::default();
2856 let root_workspace = Workspace::discover(
2857 root.as_ref(),
2858 &DiscoveryOptions::default(),
2859 &cache,
2860 &workspace_cache,
2861 )
2862 .await?;
2863 let member_workspace = Workspace::discover(
2864 root.child("packages").child("seeds").as_ref(),
2865 &DiscoveryOptions::default(),
2866 &cache,
2867 &workspace_cache,
2868 )
2869 .await?;
2870
2871 assert!(Arc::ptr_eq(&root_workspace, &member_workspace));
2872
2873 root.child("pyproject.toml")
2874 .write_str("not valid toml >.<")?;
2875 let member_project = ProjectWorkspace::from_maybe_project_root(
2876 root.child("packages").child("seeds").as_ref(),
2877 &DiscoveryOptions::default(),
2878 &cache,
2879 &workspace_cache,
2880 )
2881 .await?
2882 .expect("cached workspace member ignores invalid change in the meantime");
2883
2884 assert!(Arc::ptr_eq(&root_workspace, &member_project.workspace));
2885 assert_eq!(
2886 member_project.project_name(),
2887 &PackageName::from_str("seeds")?
2888 );
2889
2890 let root_project = ProjectWorkspace::discover(
2891 root.as_ref(),
2892 &DiscoveryOptions::default(),
2893 &cache,
2894 &workspace_cache,
2895 )
2896 .await?;
2897
2898 assert!(Arc::ptr_eq(&root_workspace, &root_project.workspace));
2899 assert_eq!(
2900 root_project.project_name(),
2901 &PackageName::from_str("albatross")?
2902 );
2903
2904 Ok(())
2905 }
2906
2907 #[tokio::test]
2909 async fn workspace_cache_preserves_virtual_root() -> Result<()> {
2910 let root = tempfile::TempDir::new()?;
2911 let root = ChildPath::new(root.path());
2912
2913 root.child("pyproject.toml").write_str(
2914 r#"
2915 [tool.uv.workspace]
2916 members = ["packages/*"]
2917 "#,
2918 )?;
2919
2920 root.child("packages")
2921 .child("seeds")
2922 .child("pyproject.toml")
2923 .write_str(
2924 r#"
2925 [project]
2926 name = "seeds"
2927 version = "1.0.0"
2928 requires-python = ">=3.12"
2929 "#,
2930 )?;
2931
2932 let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
2933 let workspace_cache = WorkspaceCache::default();
2934 let root_workspace = Workspace::discover(
2935 root.as_ref(),
2936 &DiscoveryOptions::default(),
2937 &cache,
2938 &workspace_cache,
2939 )
2940 .await?;
2941
2942 root.child("pyproject.toml")
2943 .write_str("not valid toml >.<")?;
2944 let virtual_root = VirtualProject::discover(
2945 root.as_ref(),
2946 &DiscoveryOptions::default(),
2947 &cache,
2948 &workspace_cache,
2949 )
2950 .await?;
2951
2952 match virtual_root {
2953 VirtualProject::NonProject(workspace) => {
2954 assert!(Arc::ptr_eq(&root_workspace, &workspace));
2955 }
2956 VirtualProject::Project(_) => bail!("expected a cached virtual workspace root"),
2957 }
2958 assert!(
2959 ProjectWorkspace::from_cache(
2960 root.as_ref(),
2961 &DiscoveryOptions::default(),
2962 &workspace_cache,
2963 )?
2964 .is_none()
2965 );
2966
2967 let member = VirtualProject::discover(
2968 root.child("packages").child("seeds").as_ref(),
2969 &DiscoveryOptions::default(),
2970 &cache,
2971 &workspace_cache,
2972 )
2973 .await?;
2974
2975 match member {
2976 VirtualProject::Project(project) => {
2977 assert!(Arc::ptr_eq(&root_workspace, &project.workspace));
2978 assert_eq!(project.project_name(), &PackageName::from_str("seeds")?);
2979 }
2980 VirtualProject::NonProject(_) => bail!("expected a cached workspace member project"),
2981 }
2982
2983 Ok(())
2984 }
2985
2986 #[tokio::test]
2987 async fn workspace_cache_does_not_store_partial_discovery() -> Result<()> {
2988 let root = tempfile::TempDir::new()?;
2989 let root = ChildPath::new(root.path());
2990
2991 root.child("pyproject.toml").write_str(
2992 r#"
2993 [project]
2994 name = "albatross"
2995 version = "0.1.0"
2996 requires-python = ">=3.12"
2997
2998 [tool.uv.workspace]
2999 members = ["packages/*"]
3000 "#,
3001 )?;
3002
3003 root.child("packages")
3004 .child("seeds")
3005 .child("pyproject.toml")
3006 .write_str(
3007 r#"
3008 [project]
3009 name = "seeds"
3010 version = "1.0.0"
3011 requires-python = ">=3.12"
3012 "#,
3013 )?;
3014
3015 let cache = Cache::from_path(env::temp_dir().join("uv-workspace-cache"));
3016 let workspace_cache = WorkspaceCache::default();
3017 let partial_options = DiscoveryOptions {
3018 members: MemberDiscovery::None,
3019 ..DiscoveryOptions::default()
3020 };
3021 let partial_project =
3022 ProjectWorkspace::discover(root.as_ref(), &partial_options, &cache, &workspace_cache)
3023 .await?;
3024
3025 assert_eq!(partial_project.workspace().packages().len(), 1);
3026
3027 let member_project = ProjectWorkspace::discover(
3028 root.child("packages").child("seeds").as_ref(),
3029 &DiscoveryOptions::default(),
3030 &cache,
3031 &workspace_cache,
3032 )
3033 .await?;
3034 let seeds = PackageName::from_str("seeds")?;
3035
3036 assert_eq!(member_project.project_name(), &seeds);
3037 assert_eq!(member_project.workspace().packages().len(), 2);
3038 assert!(member_project.workspace().packages().contains_key(&seeds));
3039
3040 Ok(())
3041 }
3042
3043 #[tokio::test]
3044 async fn albatross_just_project() {
3045 let (project, root_escaped) = workspace_test("albatross-just-project").await;
3046 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3047 insta::with_settings!({filters => filters}, {
3048 assert_json_snapshot!(
3049 project,
3050 {
3051 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3052 },
3053 @r#"
3054 {
3055 "project_root": "[ROOT]/albatross-just-project",
3056 "project_name": "albatross",
3057 "workspace": {
3058 "install_path": "[ROOT]/albatross-just-project",
3059 "packages": {
3060 "albatross": {
3061 "root": "[ROOT]/albatross-just-project",
3062 "project": {
3063 "name": "albatross",
3064 "version": "0.1.0",
3065 "requires-python": ">=3.12",
3066 "dependencies": [
3067 "iniconfig>=2,<3"
3068 ],
3069 "optional-dependencies": null
3070 },
3071 "pyproject_toml": "[PYPROJECT_TOML]"
3072 }
3073 },
3074 "required_members": {},
3075 "sources": {},
3076 "indexes": [],
3077 "pyproject_toml": {
3078 "project": {
3079 "name": "albatross",
3080 "version": "0.1.0",
3081 "requires-python": ">=3.12",
3082 "dependencies": [
3083 "iniconfig>=2,<3"
3084 ],
3085 "optional-dependencies": null
3086 },
3087 "tool": null,
3088 "dependency-groups": null
3089 }
3090 }
3091 }
3092 "#);
3093 });
3094 }
3095
3096 #[tokio::test]
3097 async fn exclude_package() -> Result<()> {
3098 let root = tempfile::TempDir::new()?;
3099 let root = ChildPath::new(root.path());
3100
3101 root.child("pyproject.toml").write_str(
3103 r#"
3104 [project]
3105 name = "albatross"
3106 version = "0.1.0"
3107 requires-python = ">=3.12"
3108 dependencies = ["tqdm>=4,<5"]
3109
3110 [tool.uv.workspace]
3111 members = ["packages/*"]
3112 exclude = ["packages/bird-feeder"]
3113
3114 [build-system]
3115 requires = ["hatchling"]
3116 build-backend = "hatchling.build"
3117 "#,
3118 )?;
3119 root.child("albatross").child("__init__.py").touch()?;
3120
3121 root.child("packages")
3123 .child("seeds")
3124 .child("pyproject.toml")
3125 .write_str(
3126 r#"
3127 [project]
3128 name = "seeds"
3129 version = "1.0.0"
3130 requires-python = ">=3.12"
3131 dependencies = ["idna==3.6"]
3132
3133 [build-system]
3134 requires = ["hatchling"]
3135 build-backend = "hatchling.build"
3136 "#,
3137 )?;
3138 root.child("packages")
3139 .child("seeds")
3140 .child("seeds")
3141 .child("__init__.py")
3142 .touch()?;
3143
3144 root.child("packages")
3146 .child("bird-feeder")
3147 .child("pyproject.toml")
3148 .write_str(
3149 r#"
3150 [project]
3151 name = "bird-feeder"
3152 version = "1.0.0"
3153 requires-python = ">=3.12"
3154 dependencies = ["anyio>=4.3.0,<5"]
3155
3156 [build-system]
3157 requires = ["hatchling"]
3158 build-backend = "hatchling.build"
3159 "#,
3160 )?;
3161 root.child("packages")
3162 .child("bird-feeder")
3163 .child("bird_feeder")
3164 .child("__init__.py")
3165 .touch()?;
3166
3167 let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3168 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3169 insta::with_settings!({filters => filters}, {
3170 assert_json_snapshot!(
3171 project,
3172 {
3173 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3174 },
3175 @r#"
3176 {
3177 "project_root": "[ROOT]",
3178 "project_name": "albatross",
3179 "workspace": {
3180 "install_path": "[ROOT]",
3181 "packages": {
3182 "albatross": {
3183 "root": "[ROOT]",
3184 "project": {
3185 "name": "albatross",
3186 "version": "0.1.0",
3187 "requires-python": ">=3.12",
3188 "dependencies": [
3189 "tqdm>=4,<5"
3190 ],
3191 "optional-dependencies": null
3192 },
3193 "pyproject_toml": "[PYPROJECT_TOML]"
3194 },
3195 "seeds": {
3196 "root": "[ROOT]/packages/seeds",
3197 "project": {
3198 "name": "seeds",
3199 "version": "1.0.0",
3200 "requires-python": ">=3.12",
3201 "dependencies": [
3202 "idna==3.6"
3203 ],
3204 "optional-dependencies": null
3205 },
3206 "pyproject_toml": "[PYPROJECT_TOML]"
3207 }
3208 },
3209 "required_members": {},
3210 "sources": {},
3211 "indexes": [],
3212 "pyproject_toml": {
3213 "project": {
3214 "name": "albatross",
3215 "version": "0.1.0",
3216 "requires-python": ">=3.12",
3217 "dependencies": [
3218 "tqdm>=4,<5"
3219 ],
3220 "optional-dependencies": null
3221 },
3222 "tool": {
3223 "uv": {
3224 "sources": null,
3225 "index": null,
3226 "workspace": {
3227 "members": [
3228 "packages/*"
3229 ],
3230 "exclude": [
3231 "packages/bird-feeder"
3232 ]
3233 },
3234 "managed": null,
3235 "package": null,
3236 "default-groups": null,
3237 "dependency-groups": null,
3238 "dev-dependencies": null,
3239 "override-dependencies": null,
3240 "exclude-dependencies": null,
3241 "constraint-dependencies": null,
3242 "build-constraint-dependencies": null,
3243 "environments": null,
3244 "required-environments": null,
3245 "minimum-libc-version": null,
3246 "conflicts": null,
3247 "build-backend": null
3248 }
3249 },
3250 "dependency-groups": null
3251 }
3252 }
3253 }
3254 "#);
3255 });
3256
3257 root.child("pyproject.toml").write_str(
3259 r#"
3260 [project]
3261 name = "albatross"
3262 version = "0.1.0"
3263 requires-python = ">=3.12"
3264 dependencies = ["tqdm>=4,<5"]
3265
3266 [tool.uv.workspace]
3267 members = ["packages/seeds", "packages/bird-feeder"]
3268 exclude = ["packages/bird-feeder"]
3269
3270 [build-system]
3271 requires = ["hatchling"]
3272 build-backend = "hatchling.build"
3273 "#,
3274 )?;
3275
3276 let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3278 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3279 insta::with_settings!({filters => filters}, {
3280 assert_json_snapshot!(
3281 project,
3282 {
3283 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3284 },
3285 @r#"
3286 {
3287 "project_root": "[ROOT]",
3288 "project_name": "albatross",
3289 "workspace": {
3290 "install_path": "[ROOT]",
3291 "packages": {
3292 "albatross": {
3293 "root": "[ROOT]",
3294 "project": {
3295 "name": "albatross",
3296 "version": "0.1.0",
3297 "requires-python": ">=3.12",
3298 "dependencies": [
3299 "tqdm>=4,<5"
3300 ],
3301 "optional-dependencies": null
3302 },
3303 "pyproject_toml": "[PYPROJECT_TOML]"
3304 },
3305 "seeds": {
3306 "root": "[ROOT]/packages/seeds",
3307 "project": {
3308 "name": "seeds",
3309 "version": "1.0.0",
3310 "requires-python": ">=3.12",
3311 "dependencies": [
3312 "idna==3.6"
3313 ],
3314 "optional-dependencies": null
3315 },
3316 "pyproject_toml": "[PYPROJECT_TOML]"
3317 }
3318 },
3319 "required_members": {},
3320 "sources": {},
3321 "indexes": [],
3322 "pyproject_toml": {
3323 "project": {
3324 "name": "albatross",
3325 "version": "0.1.0",
3326 "requires-python": ">=3.12",
3327 "dependencies": [
3328 "tqdm>=4,<5"
3329 ],
3330 "optional-dependencies": null
3331 },
3332 "tool": {
3333 "uv": {
3334 "sources": null,
3335 "index": null,
3336 "workspace": {
3337 "members": [
3338 "packages/seeds",
3339 "packages/bird-feeder"
3340 ],
3341 "exclude": [
3342 "packages/bird-feeder"
3343 ]
3344 },
3345 "managed": null,
3346 "package": null,
3347 "default-groups": null,
3348 "dependency-groups": null,
3349 "dev-dependencies": null,
3350 "override-dependencies": null,
3351 "exclude-dependencies": null,
3352 "constraint-dependencies": null,
3353 "build-constraint-dependencies": null,
3354 "environments": null,
3355 "required-environments": null,
3356 "minimum-libc-version": null,
3357 "conflicts": null,
3358 "build-backend": null
3359 }
3360 },
3361 "dependency-groups": null
3362 }
3363 }
3364 }
3365 "#);
3366 });
3367
3368 root.child("pyproject.toml").write_str(
3370 r#"
3371 [project]
3372 name = "albatross"
3373 version = "0.1.0"
3374 requires-python = ">=3.12"
3375 dependencies = ["tqdm>=4,<5"]
3376
3377 [tool.uv.workspace]
3378 members = ["packages/seeds", "packages/bird-feeder"]
3379 exclude = ["packages"]
3380
3381 [build-system]
3382 requires = ["hatchling"]
3383 build-backend = "hatchling.build"
3384 "#,
3385 )?;
3386
3387 let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3389 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3390 insta::with_settings!({filters => filters}, {
3391 assert_json_snapshot!(
3392 project,
3393 {
3394 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3395 },
3396 @r#"
3397 {
3398 "project_root": "[ROOT]",
3399 "project_name": "albatross",
3400 "workspace": {
3401 "install_path": "[ROOT]",
3402 "packages": {
3403 "albatross": {
3404 "root": "[ROOT]",
3405 "project": {
3406 "name": "albatross",
3407 "version": "0.1.0",
3408 "requires-python": ">=3.12",
3409 "dependencies": [
3410 "tqdm>=4,<5"
3411 ],
3412 "optional-dependencies": null
3413 },
3414 "pyproject_toml": "[PYPROJECT_TOML]"
3415 },
3416 "bird-feeder": {
3417 "root": "[ROOT]/packages/bird-feeder",
3418 "project": {
3419 "name": "bird-feeder",
3420 "version": "1.0.0",
3421 "requires-python": ">=3.12",
3422 "dependencies": [
3423 "anyio>=4.3.0,<5"
3424 ],
3425 "optional-dependencies": null
3426 },
3427 "pyproject_toml": "[PYPROJECT_TOML]"
3428 },
3429 "seeds": {
3430 "root": "[ROOT]/packages/seeds",
3431 "project": {
3432 "name": "seeds",
3433 "version": "1.0.0",
3434 "requires-python": ">=3.12",
3435 "dependencies": [
3436 "idna==3.6"
3437 ],
3438 "optional-dependencies": null
3439 },
3440 "pyproject_toml": "[PYPROJECT_TOML]"
3441 }
3442 },
3443 "required_members": {},
3444 "sources": {},
3445 "indexes": [],
3446 "pyproject_toml": {
3447 "project": {
3448 "name": "albatross",
3449 "version": "0.1.0",
3450 "requires-python": ">=3.12",
3451 "dependencies": [
3452 "tqdm>=4,<5"
3453 ],
3454 "optional-dependencies": null
3455 },
3456 "tool": {
3457 "uv": {
3458 "sources": null,
3459 "index": null,
3460 "workspace": {
3461 "members": [
3462 "packages/seeds",
3463 "packages/bird-feeder"
3464 ],
3465 "exclude": [
3466 "packages"
3467 ]
3468 },
3469 "managed": null,
3470 "package": null,
3471 "default-groups": null,
3472 "dependency-groups": null,
3473 "dev-dependencies": null,
3474 "override-dependencies": null,
3475 "exclude-dependencies": null,
3476 "constraint-dependencies": null,
3477 "build-constraint-dependencies": null,
3478 "environments": null,
3479 "required-environments": null,
3480 "minimum-libc-version": null,
3481 "conflicts": null,
3482 "build-backend": null
3483 }
3484 },
3485 "dependency-groups": null
3486 }
3487 }
3488 }
3489 "#);
3490 });
3491
3492 root.child("pyproject.toml").write_str(
3494 r#"
3495 [project]
3496 name = "albatross"
3497 version = "0.1.0"
3498 requires-python = ">=3.12"
3499 dependencies = ["tqdm>=4,<5"]
3500
3501 [tool.uv.workspace]
3502 members = ["packages/seeds", "packages/bird-feeder"]
3503 exclude = ["packages/*"]
3504
3505 [build-system]
3506 requires = ["hatchling"]
3507 build-backend = "hatchling.build"
3508 "#,
3509 )?;
3510
3511 let (project, root_escaped) = temporary_test(root.as_ref()).await.unwrap();
3513 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3514 insta::with_settings!({filters => filters}, {
3515 assert_json_snapshot!(
3516 project,
3517 {
3518 ".workspace.packages.*.pyproject_toml" => "[PYPROJECT_TOML]"
3519 },
3520 @r#"
3521 {
3522 "project_root": "[ROOT]",
3523 "project_name": "albatross",
3524 "workspace": {
3525 "install_path": "[ROOT]",
3526 "packages": {
3527 "albatross": {
3528 "root": "[ROOT]",
3529 "project": {
3530 "name": "albatross",
3531 "version": "0.1.0",
3532 "requires-python": ">=3.12",
3533 "dependencies": [
3534 "tqdm>=4,<5"
3535 ],
3536 "optional-dependencies": null
3537 },
3538 "pyproject_toml": "[PYPROJECT_TOML]"
3539 }
3540 },
3541 "required_members": {},
3542 "sources": {},
3543 "indexes": [],
3544 "pyproject_toml": {
3545 "project": {
3546 "name": "albatross",
3547 "version": "0.1.0",
3548 "requires-python": ">=3.12",
3549 "dependencies": [
3550 "tqdm>=4,<5"
3551 ],
3552 "optional-dependencies": null
3553 },
3554 "tool": {
3555 "uv": {
3556 "sources": null,
3557 "index": null,
3558 "workspace": {
3559 "members": [
3560 "packages/seeds",
3561 "packages/bird-feeder"
3562 ],
3563 "exclude": [
3564 "packages/*"
3565 ]
3566 },
3567 "managed": null,
3568 "package": null,
3569 "default-groups": null,
3570 "dependency-groups": null,
3571 "dev-dependencies": null,
3572 "override-dependencies": null,
3573 "exclude-dependencies": null,
3574 "constraint-dependencies": null,
3575 "build-constraint-dependencies": null,
3576 "environments": null,
3577 "required-environments": null,
3578 "minimum-libc-version": null,
3579 "conflicts": null,
3580 "build-backend": null
3581 }
3582 },
3583 "dependency-groups": null
3584 }
3585 }
3586 }
3587 "#);
3588 });
3589
3590 Ok(())
3591 }
3592
3593 #[tokio::test]
3594 async fn exclude_package_with_normalized_glob_and_escaped_root() -> Result<()> {
3595 let temp_dir = tempfile::TempDir::new()?;
3596 let temp_dir_root = ChildPath::new(temp_dir.path());
3597 let root = temp_dir_root.child("workspace[glob]?");
3598
3599 root.child("pyproject.toml").write_str(
3600 r#"
3601 [project]
3602 name = "albatross"
3603 version = "0.1.0"
3604 requires-python = ">=3.12"
3605
3606 [tool.uv.workspace]
3607 members = ["./packages/*", "../external-*"]
3608 exclude = [
3609 "packages/excluded-borrowed-*",
3610 "./ignored/../packages/excluded",
3611 "./packages/./excluded-glob-*",
3612 "../external-excluded",
3613 ]
3614 "#,
3615 )?;
3616
3617 for member in [
3618 "included",
3619 "excluded",
3620 "excluded-glob-one",
3621 "excluded-borrowed-one",
3622 ] {
3623 root.child("packages")
3624 .child(member)
3625 .child("pyproject.toml")
3626 .write_str(&format!(
3627 r#"
3628 [project]
3629 name = "{member}"
3630 version = "0.1.0"
3631 requires-python = ">=3.12"
3632 "#,
3633 ))?;
3634 }
3635
3636 for member in ["external-included", "external-excluded"] {
3637 temp_dir_root
3638 .child(member)
3639 .child("pyproject.toml")
3640 .write_str(&format!(
3641 r#"
3642 [project]
3643 name = "{member}"
3644 version = "0.1.0"
3645 requires-python = ">=3.12"
3646 "#,
3647 ))?;
3648 }
3649
3650 let (project, _) = temporary_test(root.as_ref())
3651 .await
3652 .map_err(|(error, _)| error)?;
3653 assert_json_snapshot!(
3654 project.workspace().packages().keys().collect::<Vec<_>>(),
3655 @r#"
3656 [
3657 "albatross",
3658 "external-included",
3659 "included"
3660 ]
3661 "#
3662 );
3663
3664 Ok(())
3665 }
3666
3667 #[test]
3668 fn read_dependency_groups() {
3669 let toml = r#"
3670[dependency-groups]
3671foo = ["a", {include-group = "bar"}]
3672bar = ["b"]
3673future = [{include-group = "bar", unknown = "value"}]
3674"#;
3675
3676 let result = PyProjectToml::from_string(toml.to_string(), "pyproject.toml")
3677 .expect("Deserialization should succeed");
3678
3679 let groups = result
3680 .dependency_groups
3681 .expect("`dependency-groups` should be present");
3682 let foo = groups
3683 .get(&GroupName::from_str("foo").unwrap())
3684 .expect("Group `foo` should be present");
3685 assert_eq!(
3686 foo,
3687 &[
3688 DependencyGroupSpecifier::Requirement("a".to_string()),
3689 DependencyGroupSpecifier::IncludeGroup {
3690 include_group: GroupName::from_str("bar").unwrap(),
3691 }
3692 ]
3693 );
3694
3695 let bar = groups
3696 .get(&GroupName::from_str("bar").unwrap())
3697 .expect("Group `bar` should be present");
3698 assert_eq!(
3699 bar,
3700 &[DependencyGroupSpecifier::Requirement("b".to_string())]
3701 );
3702
3703 let future = groups
3704 .get(&GroupName::from_str("future").unwrap())
3705 .expect("Group `future` should be present");
3706 assert_eq!(
3707 future,
3708 &[DependencyGroupSpecifier::Object(BTreeMap::from([
3709 ("include-group".to_string(), "bar".to_string()),
3710 ("unknown".to_string(), "value".to_string()),
3711 ]))]
3712 );
3713 }
3714
3715 #[test]
3716 fn reject_colliding_optional_dependency_names() {
3717 let err = PyProjectToml::from_string(
3718 r#"
3719[project]
3720name = "example"
3721version = "1.0.0"
3722
3723[project.optional-dependencies]
3724foo-bar = ["anyio"]
3725foo_bar = ["iniconfig"]
3726"#
3727 .to_string(),
3728 "pyproject.toml",
3729 )
3730 .unwrap_err();
3731
3732 assert_snapshot!(err.to_string(), @r#"
3733 TOML parse error at line 6, column 1
3734 |
3735 6 | [project.optional-dependencies]
3736 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3737 duplicate normalized extra name `foo-bar`
3738 "#);
3739 }
3740
3741 #[tokio::test]
3742 async fn nested_workspace() -> Result<()> {
3743 let root = tempfile::TempDir::new()?;
3744 let root = ChildPath::new(root.path());
3745
3746 root.child("pyproject.toml").write_str(
3748 r#"
3749 [project]
3750 name = "albatross"
3751 version = "0.1.0"
3752 requires-python = ">=3.12"
3753 dependencies = ["tqdm>=4,<5"]
3754
3755 [tool.uv.workspace]
3756 members = ["packages/*"]
3757 "#,
3758 )?;
3759
3760 root.child("packages")
3762 .child("seeds")
3763 .child("pyproject.toml")
3764 .write_str(
3765 r#"
3766 [project]
3767 name = "seeds"
3768 version = "1.0.0"
3769 requires-python = ">=3.12"
3770 dependencies = ["idna==3.6"]
3771
3772 [tool.uv.workspace]
3773 members = ["nested_packages/*"]
3774 "#,
3775 )?;
3776
3777 let (error, root_escaped) = temporary_test(root.as_ref()).await.unwrap_err();
3778 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3779 insta::with_settings!({filters => filters}, {
3780 assert_snapshot!(
3781 error,
3782 @"Nested workspaces are not supported, but workspace member has a `tool.uv.workspace` table: [ROOT]/packages/seeds");
3783 });
3784
3785 Ok(())
3786 }
3787
3788 #[tokio::test]
3789 async fn duplicate_names() -> Result<()> {
3790 let root = tempfile::TempDir::new()?;
3791 let root = ChildPath::new(root.path());
3792
3793 root.child("pyproject.toml").write_str(
3795 r#"
3796 [project]
3797 name = "albatross"
3798 version = "0.1.0"
3799 requires-python = ">=3.12"
3800 dependencies = ["tqdm>=4,<5"]
3801
3802 [tool.uv.workspace]
3803 members = ["packages/*"]
3804 "#,
3805 )?;
3806
3807 root.child("packages")
3809 .child("seeds")
3810 .child("pyproject.toml")
3811 .write_str(
3812 r#"
3813 [project]
3814 name = "seeds"
3815 version = "1.0.0"
3816 requires-python = ">=3.12"
3817 dependencies = ["idna==3.6"]
3818
3819 [tool.uv.workspace]
3820 members = ["nested_packages/*"]
3821 "#,
3822 )?;
3823
3824 root.child("packages")
3826 .child("seeds2")
3827 .child("pyproject.toml")
3828 .write_str(
3829 r#"
3830 [project]
3831 name = "seeds"
3832 version = "1.0.0"
3833 requires-python = ">=3.12"
3834 dependencies = ["idna==3.6"]
3835
3836 [tool.uv.workspace]
3837 members = ["nested_packages/*"]
3838 "#,
3839 )?;
3840
3841 let (error, root_escaped) = temporary_test(root.as_ref()).await.unwrap_err();
3842 let filters = vec![(root_escaped.as_str(), "[ROOT]")];
3843 insta::with_settings!({filters => filters}, {
3844 assert_snapshot!(
3845 error,
3846 @"Two workspace members are both named `seeds`: `[ROOT]/packages/seeds` and `[ROOT]/packages/seeds2`");
3847 });
3848
3849 Ok(())
3850 }
3851}