1use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::fmt::Formatter;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14use std::str::FromStr;
15
16use glob::Pattern;
17use rustc_hash::{FxBuildHasher, FxHashSet};
18use serde::de::SeqAccess;
19use serde::{Deserialize, Deserializer, Serialize};
20use thiserror::Error;
21use tracing::instrument;
22use uv_build_backend::BuildBackendSettings;
23use uv_configuration::{ExcludeDependency, GitLfsSetting, Override};
24use uv_distribution_types::{Index, IndexName, NameRequirementSpecification, RequirementSource};
25use uv_fs::{PortablePathBuf, try_relative_to_if};
26use uv_git_types::GitReference;
27use uv_macros::OptionsMetadata;
28use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, ExtraName, GroupName, PackageName};
29use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
30use uv_pep440::{Version, VersionSpecifiers};
31use uv_pep508::MarkerTree;
32use uv_pypi_types::{
33 ConflictError, Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments,
34 VerbatimParsedUrl,
35};
36use uv_redacted::DisplaySafeUrl;
37use uv_toml::deserialize_unique_map;
38
39use crate::DefaultGroupsError;
40
41#[derive(Error, Debug)]
42pub enum PyprojectTomlError {
43 #[error(transparent)]
44 Toml(#[from] toml::de::Error),
45 #[error("Failed to parse `tool.uv.sources`")]
46 Source(
47 #[from]
48 #[source]
49 SourceError,
50 ),
51 #[error(
52 "`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
53 )]
54 MissingName,
55 #[error(
56 "`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
57 )]
58 MissingVersion,
59}
60
61fn deserialize_optional_dependencies<'de, D, V>(
62 deserializer: D,
63) -> Result<Option<BTreeMap<ExtraName, V>>, D::Error>
64where
65 D: Deserializer<'de>,
66 V: Deserialize<'de>,
67{
68 deserialize_unique_map(deserializer, |key: &ExtraName| {
69 format!("duplicate normalized extra name `{key}`")
70 })
71 .map(Some)
72}
73
74#[derive(Deserialize, Debug, Clone)]
76#[cfg_attr(test, derive(Serialize))]
77#[serde(rename_all = "kebab-case")]
78pub struct PyProjectToml {
79 pub project: Option<Project>,
81 pub tool: Option<Tool>,
83 pub dependency_groups: Option<DependencyGroups>,
85 #[serde(skip)]
87 pub raw: String,
88
89 #[serde(default, skip_serializing)]
91 build_system: Option<serde::de::IgnoredAny>,
92}
93
94impl PyProjectToml {
95 pub(crate) fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
97 if let Some(defaults) = self
98 .tool
99 .as_ref()
100 .and_then(|tool| tool.uv.as_ref().and_then(|uv| uv.default_groups.as_ref()))
101 {
102 if let DefaultGroups::List(defaults) = defaults {
103 for group in defaults {
104 if !self
105 .dependency_groups
106 .as_ref()
107 .is_some_and(|groups| groups.contains_key(group))
108 {
109 return Err(DefaultGroupsError::MissingGroup(group.clone()));
110 }
111 }
112 }
113 Ok(defaults.clone())
114 } else {
115 Ok(DefaultGroups::List(vec![DEV_DEPENDENCIES.clone()]))
116 }
117 }
118
119 #[instrument("toml::from_str workspace", skip_all, fields(path = %_path.as_ref().display()))]
121 pub fn from_string(raw: String, _path: impl AsRef<Path>) -> Result<Self, PyprojectTomlError> {
122 let pyproject: Self = match toml::from_str(&raw) {
123 Ok(pyproject) => pyproject,
124 Err(error) => {
125 let sources = toml::from_str::<PyProjectTomlSourcesWire>(&raw)
127 .map_err(PyprojectTomlError::Toml)?
128 .tool
129 .and_then(|tool| tool.uv)
130 .and_then(|uv| uv.sources);
131 if let Some(sources) = sources {
132 ToolUvSources::try_from(sources)?;
133 }
134 return Err(PyprojectTomlError::Toml(error));
135 }
136 };
137
138 Ok(Self { raw, ..pyproject })
139 }
140
141 pub fn is_package(&self, require_build_system: bool) -> bool {
144 if let Some(is_package) = self.tool_uv_package() {
146 return is_package;
147 }
148
149 self.build_system.is_some() || !require_build_system
151 }
152
153 fn tool_uv_package(&self) -> Option<bool> {
155 self.tool
156 .as_ref()
157 .and_then(|tool| tool.uv.as_ref())
158 .and_then(|uv| uv.package)
159 }
160
161 pub fn has_scripts(&self) -> bool {
163 if let Some(ref project) = self.project {
164 project.gui_scripts.is_some() || project.scripts.is_some()
165 } else {
166 false
167 }
168 }
169
170 pub(crate) fn conflicts(&self) -> Result<Conflicts, ConflictError> {
172 let empty = Conflicts::empty();
173 let Some(project) = self.project.as_ref() else {
174 return Ok(empty);
175 };
176 let Some(tool) = self.tool.as_ref() else {
177 return Ok(empty);
178 };
179 let Some(tooluv) = tool.uv.as_ref() else {
180 return Ok(empty);
181 };
182 let Some(conflicting) = tooluv.conflicts.as_ref() else {
183 return Ok(empty);
184 };
185 conflicting.to_conflicts_with_package_name(&project.name)
186 }
187}
188
189impl PartialEq for PyProjectToml {
191 fn eq(&self, other: &Self) -> bool {
192 self.project.eq(&other.project) && self.tool.eq(&other.tool)
193 }
194}
195
196impl Eq for PyProjectToml {}
197
198impl AsRef<[u8]> for PyProjectToml {
199 fn as_ref(&self) -> &[u8] {
200 self.raw.as_bytes()
201 }
202}
203
204#[derive(Deserialize, Debug, Clone, PartialEq)]
208#[cfg_attr(test, derive(Serialize))]
209#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
210pub struct Project {
211 pub name: PackageName,
213 version: Option<Version>,
215 pub(crate) requires_python: Option<VersionSpecifiers>,
217 pub dependencies: Option<Vec<String>>,
219 pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
221
222 #[serde(default, skip_serializing)]
224 gui_scripts: Option<serde::de::IgnoredAny>,
225 #[serde(default, skip_serializing)]
227 scripts: Option<serde::de::IgnoredAny>,
228}
229
230#[derive(Deserialize, Debug)]
231#[serde(rename_all = "kebab-case")]
232struct ProjectWire {
233 name: Option<PackageName>,
234 version: Option<Version>,
235 dynamic: Option<Vec<String>>,
236 requires_python: Option<VersionSpecifiers>,
237 dependencies: Option<Vec<String>>,
238 #[serde(default, deserialize_with = "deserialize_optional_dependencies")]
239 optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
240 gui_scripts: Option<serde::de::IgnoredAny>,
241 scripts: Option<serde::de::IgnoredAny>,
242}
243
244impl TryFrom<ProjectWire> for Project {
245 type Error = PyprojectTomlError;
246
247 fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
248 let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
250
251 if value.version.is_none()
253 && !value
254 .dynamic
255 .as_ref()
256 .is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
257 {
258 return Err(PyprojectTomlError::MissingVersion);
259 }
260
261 Ok(Self {
262 name,
263 version: value.version,
264 requires_python: value.requires_python,
265 dependencies: value.dependencies,
266 optional_dependencies: value.optional_dependencies,
267 gui_scripts: value.gui_scripts,
268 scripts: value.scripts,
269 })
270 }
271}
272
273#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
274#[cfg_attr(test, derive(Serialize))]
275#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
276pub struct Tool {
277 pub uv: Option<ToolUv>,
278}
279
280fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
286where
287 D: Deserializer<'de>,
288{
289 let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
290 if let Some(indexes) = indexes.as_ref() {
291 let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
292 let mut seen_default = false;
293 for index in indexes {
294 if let Some(name) = index.name.as_ref() {
295 if !seen_names.insert(name) {
296 return Err(serde::de::Error::custom(format!(
297 "duplicate index name `{name}`"
298 )));
299 }
300 }
301 if index.default {
302 if seen_default {
303 return Err(serde::de::Error::custom(
304 "found multiple indexes with `default = true`; only one index may be marked as default",
305 ));
306 }
307 seen_default = true;
308 }
309 }
310 }
311 Ok(indexes)
312}
313
314pub type OverrideDependency = Override<uv_pep508::Requirement<VerbatimParsedUrl>>;
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(untagged)]
320#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
321pub enum BuildConstraintDependency {
322 Requirement(uv_pep508::Requirement<VerbatimParsedUrl>),
324 WithHashes {
326 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
327 hashes: Vec<String>,
328 },
329}
330
331impl BuildConstraintDependency {
332 pub fn into_parts(self) -> (uv_pep508::Requirement<VerbatimParsedUrl>, Vec<String>) {
334 match self {
335 Self::Requirement(requirement) => (requirement, Vec::new()),
336 Self::WithHashes {
337 requirement,
338 hashes,
339 } => (requirement, hashes),
340 }
341 }
342}
343
344impl From<BuildConstraintDependency> for NameRequirementSpecification {
345 fn from(value: BuildConstraintDependency) -> Self {
346 let (requirement, hashes) = value.into_parts();
347 Self {
348 requirement: requirement.into(),
349 hashes,
350 }
351 }
352}
353
354#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
357#[cfg_attr(test, derive(Serialize))]
358#[serde(rename_all = "kebab-case")]
359#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
360pub struct ToolUv {
361 #[option(
369 default = "{}",
370 value_type = "dict",
371 example = r#"
372 [tool.uv.sources]
373 httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
374 pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
375 pydantic = { path = "/path/to/pydantic", editable = true }
376 "#
377 )]
378 pub sources: Option<ToolUvSources>,
379
380 #[option(
408 default = "[]",
409 value_type = "dict",
410 example = r#"
411 [[tool.uv.index]]
412 name = "pytorch"
413 url = "https://download.pytorch.org/whl/cu130"
414 "#
415 )]
416 #[serde(deserialize_with = "deserialize_index_vec", default)]
417 pub index: Option<Vec<Index>>,
418
419 #[option_group]
421 pub(crate) workspace: Option<ToolUvWorkspace>,
422
423 #[option(
426 default = r#"true"#,
427 value_type = "bool",
428 example = r#"
429 managed = false
430 "#
431 )]
432 pub(crate) managed: Option<bool>,
433
434 #[option(
445 default = r#"true"#,
446 value_type = "bool",
447 example = r#"
448 package = false
449 "#
450 )]
451 package: Option<bool>,
452
453 #[option(
457 default = r#"["dev"]"#,
458 value_type = r#"str | list[str]"#,
459 example = r#"
460 default-groups = ["docs"]
461 "#
462 )]
463 default_groups: Option<DefaultGroups>,
464
465 #[option(
474 default = "[]",
475 value_type = "dict",
476 example = r#"
477 [tool.uv.dependency-groups]
478 my-group = {requires-python = ">=3.12"}
479 "#
480 )]
481 pub(crate) dependency_groups: Option<ToolUvDependencyGroups>,
482
483 #[cfg_attr(
493 feature = "schemars",
494 schemars(
495 with = "Option<Vec<String>>",
496 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
497 )
498 )]
499 #[option(
500 default = "[]",
501 value_type = "list[str]",
502 example = r#"
503 dev-dependencies = ["ruff==0.5.0"]
504 "#
505 )]
506 pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
507
508 #[option(
537 default = "[]",
538 value_type = "list[str | dict]",
539 example = r#"
540 override-dependencies = [
541 # Always install Werkzeug 2.3.0.
542 "werkzeug==2.3.0",
543 # Use itsdangerous 2.1.2 when requested by Flask 3.0.0.
544 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous==2.1.2"] },
545 ]
546 "#
547 )]
548 pub(crate) override_dependencies: Option<Vec<OverrideDependency>>,
549
550 #[option(
571 default = "[]",
572 value_type = "list[str | dict]",
573 example = r#"
574 # Exclude Werkzeug from being installed, even if transitive dependencies request it.
575 exclude-dependencies = [
576 "werkzeug",
577 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous"] },
578 ]
579 "#
580 )]
581 pub(crate) exclude_dependencies: Option<Vec<ExcludeDependency>>,
582
583 #[cfg_attr(
597 feature = "schemars",
598 schemars(
599 with = "Option<Vec<String>>",
600 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
601 )
602 )]
603 #[option(
604 default = "[]",
605 value_type = "list[str]",
606 example = r#"
607 # Ensure that the grpcio version is always less than 1.65, if it's requested by a
608 # direct or transitive dependency.
609 constraint-dependencies = ["grpcio<1.65"]
610 "#
611 )]
612 pub(crate) constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
613
614 #[option(
631 default = "[]",
632 value_type = "list[str | dict]",
633 example = r#"
634 # Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
635 # on setuptools.
636 build-constraint-dependencies = ["setuptools==60.0.0"]
637 "#
638 )]
639 pub(crate) build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
640
641 #[cfg_attr(
650 feature = "schemars",
651 schemars(
652 with = "Option<Vec<String>>",
653 description = "A list of environment markers, e.g., `python_version >= '3.6'`."
654 )
655 )]
656 #[option(
657 default = "[]",
658 value_type = "str | list[str]",
659 example = r#"
660 # Resolve for macOS, but not for Linux or Windows.
661 environments = ["sys_platform == 'darwin'"]
662 "#
663 )]
664 pub(crate) environments: Option<SupportedEnvironments>,
665
666 #[cfg_attr(
686 feature = "schemars",
687 schemars(
688 with = "Option<Vec<String>>",
689 description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
690 )
691 )]
692 #[option(
693 default = "[]",
694 value_type = "str | list[str]",
695 example = r#"
696 # Require that the package is available on the following platforms:
697 required-environments = [
698 # macOS on Apple Silicon (ARM)
699 "sys_platform == 'darwin' and platform_machine == 'arm64'",
700 # Linux on x86_64 (Intel/AMD)
701 "sys_platform == 'linux' and platform_machine == 'x86_64'",
702 # Windows on x86_64 (Intel/AMD)
703 "sys_platform == 'win32' and platform_machine == 'AMD64'",
704 ]
705 "#
706 )]
707 pub(crate) required_environments: Option<SupportedEnvironments>,
708
709 #[cfg_attr(
724 feature = "schemars",
725 schemars(description = "A list of sets of conflicting groups or extras.")
726 )]
727 #[option(
728 default = r#"[]"#,
729 value_type = "list[list[dict]]",
730 example = r#"
731 # Require that `package[extra1]` and `package[extra2]` are resolved
732 # in different forks so that they cannot conflict with one another.
733 conflicts = [
734 [
735 { extra = "extra1" },
736 { extra = "extra2" },
737 ]
738 ]
739
740 # Require that the dependency groups `group1` and `group2`
741 # are resolved in different forks so that they cannot conflict
742 # with one another.
743 conflicts = [
744 [
745 { group = "group1" },
746 { group = "group2" },
747 ]
748 ]
749 "#
750 )]
751 pub(crate) conflicts: Option<SchemaConflicts>,
752
753 #[option_group]
760 build_backend: Option<BuildBackendSettingsSchema>,
761}
762
763#[derive(Default, Debug, Clone, PartialEq, Eq)]
764#[cfg_attr(test, derive(Serialize))]
765#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
766pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
767
768#[derive(Deserialize, Debug)]
769#[serde(rename_all = "kebab-case")]
770struct PyProjectTomlSourcesWire {
771 tool: Option<ToolSourcesWire>,
772}
773
774#[derive(Deserialize, Debug)]
775struct ToolSourcesWire {
776 uv: Option<ToolUvSourcesOnlyWire>,
777}
778
779#[derive(Deserialize, Debug)]
780#[serde(rename_all = "kebab-case")]
781struct ToolUvSourcesOnlyWire {
782 sources: Option<ToolUvSourcesWire>,
783}
784
785#[derive(Default, Debug, Clone, PartialEq, Eq)]
786struct ToolUvSourcesWire(BTreeMap<PackageName, SourcesWire>);
787
788impl ToolUvSources {
789 pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
791 &self.0
792 }
793
794 #[must_use]
796 pub(crate) fn into_inner(self) -> BTreeMap<PackageName, Sources> {
797 self.0
798 }
799}
800
801impl TryFrom<ToolUvSourcesWire> for ToolUvSources {
802 type Error = SourceError;
803
804 fn try_from(wire: ToolUvSourcesWire) -> Result<Self, Self::Error> {
805 wire.0
806 .into_iter()
807 .map(|(name, sources)| Sources::try_from(sources).map(|sources| (name, sources)))
808 .collect::<Result<BTreeMap<_, _>, _>>()
809 .map(Self)
810 }
811}
812
813impl<'de> serde::de::Deserialize<'de> for ToolUvSourcesWire {
815 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
816 where
817 D: Deserializer<'de>,
818 {
819 deserialize_unique_map(deserializer, |key: &PackageName| {
820 format!("duplicate sources for package `{key}`")
821 })
822 .map(ToolUvSourcesWire)
823 }
824}
825
826impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
828 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
829 where
830 D: Deserializer<'de>,
831 {
832 deserialize_unique_map(deserializer, |key: &PackageName| {
833 format!("duplicate sources for package `{key}`")
834 })
835 .map(ToolUvSources)
836 }
837}
838
839#[derive(Default, Debug, Clone, PartialEq, Eq)]
840#[cfg_attr(test, derive(Serialize))]
841#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
842pub(crate) struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
843
844impl ToolUvDependencyGroups {
845 pub(crate) fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
847 &self.0
848 }
849}
850
851impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
853 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
854 where
855 D: Deserializer<'de>,
856 {
857 deserialize_unique_map(deserializer, |key: &GroupName| {
858 format!("duplicate settings for dependency group `{key}`")
859 })
860 .map(ToolUvDependencyGroups)
861 }
862}
863
864#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
865#[cfg_attr(test, derive(Serialize))]
866#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
867#[serde(rename_all = "kebab-case")]
868pub(crate) struct DependencyGroupSettings {
869 #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
871 pub(crate) requires_python: Option<VersionSpecifiers>,
872}
873
874#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
875#[serde(untagged, rename_all = "kebab-case")]
876#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
877enum ExtraBuildDependencyWire {
878 Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
879 #[serde(rename_all = "kebab-case")]
880 Annotated {
881 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
882 match_runtime: bool,
883 },
884}
885
886#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
887#[serde(
888 deny_unknown_fields,
889 from = "ExtraBuildDependencyWire",
890 into = "ExtraBuildDependencyWire"
891)]
892#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
893pub struct ExtraBuildDependency {
894 pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
895 pub match_runtime: bool,
896}
897
898impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
899 fn from(value: ExtraBuildDependency) -> Self {
900 value.requirement
901 }
902}
903
904impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
905 fn from(wire: ExtraBuildDependencyWire) -> Self {
906 match wire {
907 ExtraBuildDependencyWire::Unannotated(requirement) => Self {
908 requirement,
909 match_runtime: false,
910 },
911 ExtraBuildDependencyWire::Annotated {
912 requirement,
913 match_runtime,
914 } => Self {
915 requirement,
916 match_runtime,
917 },
918 }
919 }
920}
921
922impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
923 fn from(item: ExtraBuildDependency) -> Self {
924 Self::Annotated {
925 requirement: item.requirement,
926 match_runtime: item.match_runtime,
927 }
928 }
929}
930
931#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
932#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
933pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
934
935impl std::ops::Deref for ExtraBuildDependencies {
936 type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
937
938 fn deref(&self) -> &Self::Target {
939 &self.0
940 }
941}
942
943impl std::ops::DerefMut for ExtraBuildDependencies {
944 fn deref_mut(&mut self) -> &mut Self::Target {
945 &mut self.0
946 }
947}
948
949impl IntoIterator for ExtraBuildDependencies {
950 type Item = (PackageName, Vec<ExtraBuildDependency>);
951 type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
952
953 fn into_iter(self) -> Self::IntoIter {
954 self.0.into_iter()
955 }
956}
957
958impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
959 fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
960 iter: T,
961 ) -> Self {
962 Self(iter.into_iter().collect())
963 }
964}
965
966impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
968 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
969 where
970 D: Deserializer<'de>,
971 {
972 deserialize_unique_map(deserializer, |key: &PackageName| {
973 format!("duplicate extra-build-dependencies for `{key}`")
974 })
975 .map(ExtraBuildDependencies)
976 }
977}
978
979#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
980#[cfg_attr(test, derive(Serialize))]
981#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
982#[serde(rename_all = "kebab-case", deny_unknown_fields)]
983pub(crate) struct ToolUvWorkspace {
984 #[option(
990 default = "[]",
991 value_type = "list[str]",
992 example = r#"
993 members = ["member1", "path/to/member2", "libs/*"]
994 "#
995 )]
996 pub(crate) members: Option<Vec<SerdePattern>>,
997 #[option(
1004 default = "[]",
1005 value_type = "list[str]",
1006 example = r#"
1007 exclude = ["member1", "path/to/member2", "libs/*"]
1008 "#
1009 )]
1010 pub(crate) exclude: Option<Vec<SerdePattern>>,
1011}
1012
1013#[derive(Debug, Clone, PartialEq, Eq)]
1015pub(crate) struct SerdePattern(Pattern);
1016
1017impl serde::ser::Serialize for SerdePattern {
1018 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1019 where
1020 S: serde::ser::Serializer,
1021 {
1022 self.0.as_str().serialize(serializer)
1023 }
1024}
1025
1026impl<'de> serde::Deserialize<'de> for SerdePattern {
1027 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1028 struct Visitor;
1029
1030 impl serde::de::Visitor<'_> for Visitor {
1031 type Value = SerdePattern;
1032
1033 fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1034 f.write_str("a string")
1035 }
1036
1037 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
1038 Pattern::from_str(v)
1039 .map(SerdePattern)
1040 .map_err(serde::de::Error::custom)
1041 }
1042 }
1043
1044 deserializer.deserialize_str(Visitor)
1045 }
1046}
1047
1048#[cfg(feature = "schemars")]
1049impl schemars::JsonSchema for SerdePattern {
1050 fn schema_name() -> Cow<'static, str> {
1051 Cow::Borrowed("SerdePattern")
1052 }
1053
1054 fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
1055 <String as schemars::JsonSchema>::json_schema(generator)
1056 }
1057}
1058
1059impl Deref for SerdePattern {
1060 type Target = Pattern;
1061
1062 fn deref(&self) -> &Self::Target {
1063 &self.0
1064 }
1065}
1066
1067#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1068#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1069#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
1070pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
1071
1072impl Sources {
1073 pub fn iter(&self) -> impl Iterator<Item = &Source> {
1079 self.0.iter()
1080 }
1081}
1082
1083impl FromIterator<Source> for Sources {
1084 fn from_iter<T: IntoIterator<Item = Source>>(iter: T) -> Self {
1085 Self(iter.into_iter().collect())
1086 }
1087}
1088
1089impl IntoIterator for Sources {
1090 type Item = Source;
1091 type IntoIter = std::vec::IntoIter<Source>;
1092
1093 fn into_iter(self) -> Self::IntoIter {
1094 self.0.into_iter()
1095 }
1096}
1097
1098#[derive(Debug, Clone, PartialEq, Eq)]
1099#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1100enum SourcesWire {
1101 One(Source),
1102 Many(Vec<Source>),
1103}
1104
1105impl<'de> serde::de::Deserialize<'de> for SourcesWire {
1106 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1107 where
1108 D: Deserializer<'de>,
1109 {
1110 struct Visitor;
1111
1112 impl<'de> serde::de::Visitor<'de> for Visitor {
1113 type Value = SourcesWire;
1114
1115 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1116 formatter.write_str("a single source (as a map) or list of sources")
1117 }
1118
1119 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1120 where
1121 A: SeqAccess<'de>,
1122 {
1123 let sources = serde::de::Deserialize::deserialize(
1124 serde::de::value::SeqAccessDeserializer::new(seq),
1125 )?;
1126 Ok(SourcesWire::Many(sources))
1127 }
1128
1129 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
1130 where
1131 M: serde::de::MapAccess<'de>,
1132 {
1133 let source = serde::de::Deserialize::deserialize(
1134 serde::de::value::MapAccessDeserializer::new(&mut map),
1135 )?;
1136 Ok(SourcesWire::One(source))
1137 }
1138 }
1139
1140 deserializer.deserialize_any(Visitor)
1141 }
1142}
1143
1144impl TryFrom<SourcesWire> for Sources {
1145 type Error = SourceError;
1146
1147 fn try_from(wire: SourcesWire) -> Result<Self, Self::Error> {
1148 match wire {
1149 SourcesWire::One(source) => Ok(Self(vec![source])),
1150 SourcesWire::Many(sources) => {
1151 for [lhs, rhs] in sources.array_windows() {
1152 if lhs.extra() != rhs.extra() {
1153 continue;
1154 }
1155 if lhs.group() != rhs.group() {
1156 continue;
1157 }
1158
1159 let lhs = lhs.marker();
1160 let rhs = rhs.marker();
1161 if !lhs.is_disjoint(rhs) {
1162 let Some(left) = lhs.contents().map(|contents| contents.to_string()) else {
1163 return Err(SourceError::MissingMarkers);
1164 };
1165
1166 let Some(right) = rhs.contents().map(|contents| contents.to_string())
1167 else {
1168 return Err(SourceError::MissingMarkers);
1169 };
1170
1171 let hint = lhs.negate().and(rhs);
1172 let hint = hint
1173 .contents()
1174 .map(|contents| contents.to_string())
1175 .unwrap_or_else(|| "true".to_string());
1176
1177 return Err(SourceError::OverlappingMarkers(left, right, hint));
1178 }
1179 }
1180
1181 if sources.is_empty() {
1183 return Err(SourceError::EmptySources);
1184 }
1185
1186 Ok(Self(sources))
1187 }
1188 }
1189 }
1190}
1191
1192#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
1194#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1195#[serde(rename_all = "kebab-case", untagged, deny_unknown_fields)]
1196pub enum Source {
1197 Git {
1204 git: DisplaySafeUrl,
1206 subdirectory: Option<PortablePathBuf>,
1208 path: Option<PortablePathBuf>,
1210 rev: Option<String>,
1212 tag: Option<String>,
1213 branch: Option<String>,
1214 lfs: Option<bool>,
1216 #[serde(
1217 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1218 serialize_with = "uv_pep508::marker::ser::serialize",
1219 default
1220 )]
1221 marker: MarkerTree,
1222 extra: Option<ExtraName>,
1223 group: Option<GroupName>,
1224 },
1225 Url {
1233 url: DisplaySafeUrl,
1234 subdirectory: Option<PortablePathBuf>,
1237 #[serde(
1238 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1239 serialize_with = "uv_pep508::marker::ser::serialize",
1240 default
1241 )]
1242 marker: MarkerTree,
1243 extra: Option<ExtraName>,
1244 group: Option<GroupName>,
1245 },
1246 Path {
1250 path: PortablePathBuf,
1251 editable: Option<bool>,
1253 package: Option<bool>,
1260 #[serde(
1261 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1262 serialize_with = "uv_pep508::marker::ser::serialize",
1263 default
1264 )]
1265 marker: MarkerTree,
1266 extra: Option<ExtraName>,
1267 group: Option<GroupName>,
1268 },
1269 Registry {
1271 index: IndexName,
1272 #[serde(
1273 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1274 serialize_with = "uv_pep508::marker::ser::serialize",
1275 default
1276 )]
1277 marker: MarkerTree,
1278 extra: Option<ExtraName>,
1279 group: Option<GroupName>,
1280 },
1281 Workspace {
1283 workspace: WorkspaceReference,
1289 editable: Option<bool>,
1291 #[serde(
1292 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1293 serialize_with = "uv_pep508::marker::ser::serialize",
1294 default
1295 )]
1296 marker: MarkerTree,
1297 extra: Option<ExtraName>,
1298 group: Option<GroupName>,
1299 },
1300}
1301
1302#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1304#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1305#[serde(untagged)]
1306pub enum WorkspaceReference {
1307 Bool(bool),
1308 Path(PortablePathBuf),
1309}
1310
1311impl<'de> Deserialize<'de> for Source {
1314 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1315 where
1316 D: Deserializer<'de>,
1317 {
1318 #[derive(Deserialize, Debug, Clone)]
1319 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
1320 struct CatchAll {
1321 git: Option<DisplaySafeUrl>,
1322 subdirectory: Option<PortablePathBuf>,
1323 rev: Option<String>,
1324 tag: Option<String>,
1325 branch: Option<String>,
1326 lfs: Option<bool>,
1327 url: Option<DisplaySafeUrl>,
1328 path: Option<PortablePathBuf>,
1329 editable: Option<bool>,
1330 package: Option<bool>,
1331 index: Option<IndexName>,
1332 workspace: Option<WorkspaceReference>,
1333 #[serde(
1334 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1335 serialize_with = "uv_pep508::marker::ser::serialize",
1336 default
1337 )]
1338 marker: MarkerTree,
1339 extra: Option<ExtraName>,
1340 group: Option<GroupName>,
1341 }
1342
1343 let CatchAll {
1345 git,
1346 subdirectory,
1347 rev,
1348 tag,
1349 branch,
1350 lfs,
1351 url,
1352 path,
1353 editable,
1354 package,
1355 index,
1356 workspace,
1357 marker,
1358 extra,
1359 group,
1360 } = CatchAll::deserialize(deserializer)?;
1361
1362 if extra.is_some() && group.is_some() {
1364 return Err(serde::de::Error::custom(
1365 "cannot specify both `extra` and `group`",
1366 ));
1367 }
1368
1369 if let Some(git) = git {
1371 if index.is_some() {
1372 return Err(serde::de::Error::custom(
1373 "cannot specify both `git` and `index`",
1374 ));
1375 }
1376 if workspace.is_some() {
1377 return Err(serde::de::Error::custom(
1378 "cannot specify both `git` and `workspace`",
1379 ));
1380 }
1381 if url.is_some() {
1382 return Err(serde::de::Error::custom(
1383 "cannot specify both `git` and `url`",
1384 ));
1385 }
1386 if editable.is_some() {
1387 return Err(serde::de::Error::custom(
1388 "cannot specify both `git` and `editable`",
1389 ));
1390 }
1391 if package.is_some() {
1392 return Err(serde::de::Error::custom(
1393 "cannot specify both `git` and `package`",
1394 ));
1395 }
1396 if subdirectory.is_some() && path.is_some() {
1397 return Err(serde::de::Error::custom(
1398 "cannot specify both `subdirectory` and `path`",
1399 ));
1400 }
1401
1402 match (rev.as_ref(), tag.as_ref(), branch.as_ref()) {
1404 (None, None, None) => {}
1405 (Some(_), None, None) => {}
1406 (None, Some(_), None) => {}
1407 (None, None, Some(_)) => {}
1408 _ => {
1409 return Err(serde::de::Error::custom(
1410 "expected at most one of `rev`, `tag`, or `branch`",
1411 ));
1412 }
1413 }
1414
1415 let git = if let Some(git) = git.as_str().strip_prefix("git+") {
1417 DisplaySafeUrl::parse(git).map_err(serde::de::Error::custom)?
1418 } else {
1419 git
1420 };
1421
1422 return Ok(Self::Git {
1423 git,
1424 subdirectory,
1425 path,
1426 rev,
1427 tag,
1428 branch,
1429 lfs,
1430 marker,
1431 extra,
1432 group,
1433 });
1434 }
1435
1436 if let Some(url) = url {
1438 if index.is_some() {
1439 return Err(serde::de::Error::custom(
1440 "cannot specify both `url` and `index`",
1441 ));
1442 }
1443 if workspace.is_some() {
1444 return Err(serde::de::Error::custom(
1445 "cannot specify both `url` and `workspace`",
1446 ));
1447 }
1448 if path.is_some() {
1449 return Err(serde::de::Error::custom(
1450 "cannot specify both `url` and `path`",
1451 ));
1452 }
1453 if git.is_some() {
1454 return Err(serde::de::Error::custom(
1455 "cannot specify both `url` and `git`",
1456 ));
1457 }
1458 if rev.is_some() {
1459 return Err(serde::de::Error::custom(
1460 "cannot specify both `url` and `rev`",
1461 ));
1462 }
1463 if tag.is_some() {
1464 return Err(serde::de::Error::custom(
1465 "cannot specify both `url` and `tag`",
1466 ));
1467 }
1468 if branch.is_some() {
1469 return Err(serde::de::Error::custom(
1470 "cannot specify both `url` and `branch`",
1471 ));
1472 }
1473 if editable.is_some() {
1474 return Err(serde::de::Error::custom(
1475 "cannot specify both `url` and `editable`",
1476 ));
1477 }
1478 if package.is_some() {
1479 return Err(serde::de::Error::custom(
1480 "cannot specify both `url` and `package`",
1481 ));
1482 }
1483
1484 return Ok(Self::Url {
1485 url,
1486 subdirectory,
1487 marker,
1488 extra,
1489 group,
1490 });
1491 }
1492
1493 if let Some(path) = path {
1495 if index.is_some() {
1496 return Err(serde::de::Error::custom(
1497 "cannot specify both `path` and `index`",
1498 ));
1499 }
1500 if workspace.is_some() {
1501 return Err(serde::de::Error::custom(
1502 "cannot specify both `path` and `workspace`",
1503 ));
1504 }
1505 if git.is_some() {
1506 return Err(serde::de::Error::custom(
1507 "cannot specify both `path` and `git`",
1508 ));
1509 }
1510 if url.is_some() {
1511 return Err(serde::de::Error::custom(
1512 "cannot specify both `path` and `url`",
1513 ));
1514 }
1515 if rev.is_some() {
1516 return Err(serde::de::Error::custom(
1517 "cannot specify both `path` and `rev`",
1518 ));
1519 }
1520 if tag.is_some() {
1521 return Err(serde::de::Error::custom(
1522 "cannot specify both `path` and `tag`",
1523 ));
1524 }
1525 if branch.is_some() {
1526 return Err(serde::de::Error::custom(
1527 "cannot specify both `path` and `branch`",
1528 ));
1529 }
1530
1531 if editable == Some(true) && package == Some(false) {
1533 return Err(serde::de::Error::custom(
1534 "cannot specify both `editable = true` and `package = false`",
1535 ));
1536 }
1537
1538 return Ok(Self::Path {
1539 path,
1540 editable,
1541 package,
1542 marker,
1543 extra,
1544 group,
1545 });
1546 }
1547
1548 if let Some(index) = index {
1550 if workspace.is_some() {
1551 return Err(serde::de::Error::custom(
1552 "cannot specify both `index` and `workspace`",
1553 ));
1554 }
1555 if git.is_some() {
1556 return Err(serde::de::Error::custom(
1557 "cannot specify both `index` and `git`",
1558 ));
1559 }
1560 if url.is_some() {
1561 return Err(serde::de::Error::custom(
1562 "cannot specify both `index` and `url`",
1563 ));
1564 }
1565 if path.is_some() {
1566 return Err(serde::de::Error::custom(
1567 "cannot specify both `index` and `path`",
1568 ));
1569 }
1570 if rev.is_some() {
1571 return Err(serde::de::Error::custom(
1572 "cannot specify both `index` and `rev`",
1573 ));
1574 }
1575 if tag.is_some() {
1576 return Err(serde::de::Error::custom(
1577 "cannot specify both `index` and `tag`",
1578 ));
1579 }
1580 if branch.is_some() {
1581 return Err(serde::de::Error::custom(
1582 "cannot specify both `index` and `branch`",
1583 ));
1584 }
1585 if editable.is_some() {
1586 return Err(serde::de::Error::custom(
1587 "cannot specify both `index` and `editable`",
1588 ));
1589 }
1590 if package.is_some() {
1591 return Err(serde::de::Error::custom(
1592 "cannot specify both `index` and `package`",
1593 ));
1594 }
1595
1596 return Ok(Self::Registry {
1597 index,
1598 marker,
1599 extra,
1600 group,
1601 });
1602 }
1603
1604 if let Some(workspace) = workspace {
1606 if index.is_some() {
1607 return Err(serde::de::Error::custom(
1608 "cannot specify both `workspace` and `index`",
1609 ));
1610 }
1611 if git.is_some() {
1612 return Err(serde::de::Error::custom(
1613 "cannot specify both `workspace` and `git`",
1614 ));
1615 }
1616 if url.is_some() {
1617 return Err(serde::de::Error::custom(
1618 "cannot specify both `workspace` and `url`",
1619 ));
1620 }
1621 if path.is_some() {
1622 return Err(serde::de::Error::custom(
1623 "cannot specify both `workspace` and `path`",
1624 ));
1625 }
1626 if rev.is_some() {
1627 return Err(serde::de::Error::custom(
1628 "cannot specify both `workspace` and `rev`",
1629 ));
1630 }
1631 if tag.is_some() {
1632 return Err(serde::de::Error::custom(
1633 "cannot specify both `workspace` and `tag`",
1634 ));
1635 }
1636 if branch.is_some() {
1637 return Err(serde::de::Error::custom(
1638 "cannot specify both `workspace` and `branch`",
1639 ));
1640 }
1641 if package.is_some() {
1642 return Err(serde::de::Error::custom(
1643 "cannot specify both `workspace` and `package`",
1644 ));
1645 }
1646
1647 return Ok(Self::Workspace {
1648 workspace,
1649 editable,
1650 marker,
1651 extra,
1652 group,
1653 });
1654 }
1655
1656 Err(serde::de::Error::custom(
1658 "expected one of `git`, `url`, `path`, `index`, or `workspace`",
1659 ))
1660 }
1661}
1662
1663#[derive(Error, Debug)]
1664pub enum SourceError {
1665 #[error("Failed to resolve Git reference: `{0}`")]
1666 UnresolvedReference(String),
1667 #[error("Workspace dependency `{0}` must refer to local directory, not a Git repository")]
1668 WorkspacePackageGit(String),
1669 #[error("Workspace dependency `{0}` must refer to local directory, not a URL")]
1670 WorkspacePackageUrl(String),
1671 #[error("Workspace dependency `{0}` must refer to local directory, not a file")]
1672 WorkspacePackageFile(String),
1673 #[error(
1674 "`{0}` did not resolve to a Git repository, but a Git reference (`--rev {1}`) was provided."
1675 )]
1676 UnusedRev(String, String),
1677 #[error(
1678 "`{0}` did not resolve to a Git repository, but a Git reference (`--tag {1}`) was provided."
1679 )]
1680 UnusedTag(String, String),
1681 #[error(
1682 "`{0}` did not resolve to a Git repository, but a Git reference (`--branch {1}`) was provided."
1683 )]
1684 UnusedBranch(String, String),
1685 #[error(
1686 "`{0}` did not resolve to a Git repository, but a Git extension (`--lfs`) was provided."
1687 )]
1688 UnusedLfs(String),
1689 #[error(
1690 "`{0}` did not resolve to a local directory, but the `--editable` flag was provided. Editable installs are only supported for local directories."
1691 )]
1692 UnusedEditable(String),
1693 #[error("Failed to resolve absolute path")]
1694 Absolute(#[from] std::io::Error),
1695 #[error("Path contains invalid characters: `{}`", _0.display())]
1696 NonUtf8Path(PathBuf),
1697 #[error("Source markers must be disjoint, but the following markers overlap: `{0}` and `{1}`.")]
1698 OverlappingMarkers(String, String, String),
1699 #[error(
1700 "When multiple sources are provided, each source must include a platform marker (e.g., `marker = \"sys_platform == 'linux'\"`)"
1701 )]
1702 MissingMarkers,
1703 #[error("Must provide at least one source")]
1704 EmptySources,
1705}
1706
1707impl uv_errors::Hinted for SourceError {
1708 fn hints(&self) -> uv_errors::Hints<'_> {
1709 match self {
1710 Self::OverlappingMarkers(_, rhs, replacement) => {
1711 uv_errors::Hints::from(format!("replace `{rhs}` with `{replacement}`"))
1712 }
1713 _ => uv_errors::Hints::none(),
1714 }
1715 }
1716}
1717
1718impl Source {
1719 pub fn from_requirement(
1720 name: &PackageName,
1721 source: RequirementSource,
1722 workspace: bool,
1723 editable: Option<bool>,
1724 index: Option<IndexName>,
1725 rev: Option<String>,
1726 tag: Option<String>,
1727 branch: Option<String>,
1728 lfs: GitLfsSetting,
1729 root: &Path,
1730 existing_sources: Option<&BTreeMap<PackageName, Sources>>,
1731 ) -> Result<Option<Self>, SourceError> {
1732 if !matches!(
1734 source,
1735 RequirementSource::GitDirectory { .. } | RequirementSource::GitPath { .. }
1736 ) && (branch.is_some()
1737 || tag.is_some()
1738 || rev.is_some()
1739 || matches!(lfs, GitLfsSetting::Enabled { .. }))
1740 {
1741 if let Some(sources) = existing_sources
1742 && let Some(package_sources) = sources.get(name)
1743 {
1744 for existing_source in package_sources.iter() {
1745 if let Self::Git {
1746 git,
1747 subdirectory,
1748 path,
1749 marker,
1750 extra,
1751 group,
1752 ..
1753 } = existing_source
1754 {
1755 return Ok(Some(Self::Git {
1756 git: git.clone(),
1757 subdirectory: subdirectory.clone(),
1758 rev,
1759 tag,
1760 branch,
1761 lfs: lfs.into(),
1762 marker: *marker,
1763 path: path.clone(),
1764 extra: extra.clone(),
1765 group: group.clone(),
1766 }));
1767 }
1768 }
1769 }
1770 if let Some(rev) = rev {
1771 return Err(SourceError::UnusedRev(name.to_string(), rev));
1772 }
1773 if let Some(tag) = tag {
1774 return Err(SourceError::UnusedTag(name.to_string(), tag));
1775 }
1776 if let Some(branch) = branch {
1777 return Err(SourceError::UnusedBranch(name.to_string(), branch));
1778 }
1779 if matches!(lfs, GitLfsSetting::Enabled { from_env: false }) {
1780 return Err(SourceError::UnusedLfs(name.to_string()));
1781 }
1782 }
1783
1784 if !workspace {
1786 if !matches!(source, RequirementSource::Directory { .. }) {
1787 if editable == Some(true) {
1788 return Err(SourceError::UnusedEditable(name.to_string()));
1789 }
1790 }
1791 }
1792
1793 if workspace {
1795 return match source {
1796 RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => {
1797 Ok(Some(Self::Workspace {
1798 workspace: WorkspaceReference::Bool(true),
1799 editable,
1800 marker: MarkerTree::TRUE,
1801 extra: None,
1802 group: None,
1803 }))
1804 }
1805 RequirementSource::Url { .. } => {
1806 Err(SourceError::WorkspacePackageUrl(name.to_string()))
1807 }
1808 RequirementSource::GitDirectory { .. } => {
1809 Err(SourceError::WorkspacePackageGit(name.to_string()))
1810 }
1811 RequirementSource::GitPath { .. } => {
1812 Err(SourceError::WorkspacePackageGit(name.to_string()))
1813 }
1814 RequirementSource::Path { .. } => {
1815 Err(SourceError::WorkspacePackageFile(name.to_string()))
1816 }
1817 };
1818 }
1819
1820 let source = match source {
1821 RequirementSource::Registry { index: Some(_), .. } => {
1822 return Ok(None);
1823 }
1824 RequirementSource::Registry { index: None, .. } if let Some(index) = index => {
1825 Self::Registry {
1826 index,
1827 marker: MarkerTree::TRUE,
1828 extra: None,
1829 group: None,
1830 }
1831 }
1832 RequirementSource::Registry { index: None, .. } => return Ok(None),
1833 RequirementSource::Path {
1834 install_path, url, ..
1835 } => Self::Path {
1836 editable: None,
1837 package: None,
1838 path: PortablePathBuf::from(
1839 try_relative_to_if(&install_path, root, url.prefers_relative())
1840 .map_err(SourceError::Absolute)?
1841 .into_boxed_path(),
1842 ),
1843 marker: MarkerTree::TRUE,
1844 extra: None,
1845 group: None,
1846 },
1847 RequirementSource::Directory {
1848 install_path,
1849 editable: is_editable,
1850 url,
1851 ..
1852 } => Self::Path {
1853 editable: editable.or(is_editable),
1854 package: None,
1855 path: PortablePathBuf::from(
1856 try_relative_to_if(&install_path, root, url.prefers_relative())
1857 .map_err(SourceError::Absolute)?
1858 .into_boxed_path(),
1859 ),
1860 marker: MarkerTree::TRUE,
1861 extra: None,
1862 group: None,
1863 },
1864 RequirementSource::Url {
1865 location,
1866 subdirectory,
1867 ..
1868 } => Self::Url {
1869 url: location,
1870 subdirectory: subdirectory.map(PortablePathBuf::from),
1871 marker: MarkerTree::TRUE,
1872 extra: None,
1873 group: None,
1874 },
1875 RequirementSource::GitDirectory {
1876 git, subdirectory, ..
1877 } => {
1878 if rev.is_none() && tag.is_none() && branch.is_none() {
1879 let rev = match git.reference() {
1880 GitReference::Branch(rev) => Some(rev),
1881 GitReference::Tag(rev) => Some(rev),
1882 GitReference::BranchOrTag(rev) => Some(rev),
1883 GitReference::BranchOrTagOrCommit(rev) => Some(rev),
1884 GitReference::NamedRef(rev) => Some(rev),
1885 GitReference::DefaultBranch => None,
1886 };
1887 Self::Git {
1888 rev: rev.cloned(),
1889 tag,
1890 branch,
1891 lfs: lfs.into(),
1892 git: git.url().clone(),
1893 subdirectory: subdirectory.map(PortablePathBuf::from),
1894 path: None,
1895 marker: MarkerTree::TRUE,
1896 extra: None,
1897 group: None,
1898 }
1899 } else {
1900 Self::Git {
1901 rev,
1902 tag,
1903 branch,
1904 lfs: lfs.into(),
1905 git: git.url().clone(),
1906 subdirectory: subdirectory.map(PortablePathBuf::from),
1907 path: None,
1908 marker: MarkerTree::TRUE,
1909 extra: None,
1910 group: None,
1911 }
1912 }
1913 }
1914 RequirementSource::GitPath {
1915 git, install_path, ..
1916 } => {
1917 if rev.is_none() && tag.is_none() && branch.is_none() {
1918 let rev = match git.reference() {
1919 GitReference::Branch(rev) => Some(rev),
1920 GitReference::Tag(rev) => Some(rev),
1921 GitReference::BranchOrTag(rev) => Some(rev),
1922 GitReference::BranchOrTagOrCommit(rev) => Some(rev),
1923 GitReference::NamedRef(rev) => Some(rev),
1924 GitReference::DefaultBranch => None,
1925 };
1926 Self::Git {
1927 rev: rev.cloned(),
1928 tag,
1929 branch,
1930 lfs: lfs.into(),
1931 git: git.url().clone(),
1932 subdirectory: None,
1933 path: Some(PortablePathBuf::from(install_path.as_path())),
1934 marker: MarkerTree::TRUE,
1935 extra: None,
1936 group: None,
1937 }
1938 } else {
1939 Self::Git {
1940 rev,
1941 tag,
1942 branch,
1943 lfs: lfs.into(),
1944 git: git.url().clone(),
1945 subdirectory: None,
1946 path: Some(PortablePathBuf::from(install_path.as_path())),
1947 marker: MarkerTree::TRUE,
1948 extra: None,
1949 group: None,
1950 }
1951 }
1952 }
1953 };
1954
1955 Ok(Some(source))
1956 }
1957
1958 pub fn marker(&self) -> MarkerTree {
1960 match self {
1961 Self::Git { marker, .. } => *marker,
1962 Self::Url { marker, .. } => *marker,
1963 Self::Path { marker, .. } => *marker,
1964 Self::Registry { marker, .. } => *marker,
1965 Self::Workspace { marker, .. } => *marker,
1966 }
1967 }
1968
1969 pub fn extra(&self) -> Option<&ExtraName> {
1971 match self {
1972 Self::Git { extra, .. } => extra.as_ref(),
1973 Self::Url { extra, .. } => extra.as_ref(),
1974 Self::Path { extra, .. } => extra.as_ref(),
1975 Self::Registry { extra, .. } => extra.as_ref(),
1976 Self::Workspace { extra, .. } => extra.as_ref(),
1977 }
1978 }
1979
1980 pub fn group(&self) -> Option<&GroupName> {
1982 match self {
1983 Self::Git { group, .. } => group.as_ref(),
1984 Self::Url { group, .. } => group.as_ref(),
1985 Self::Path { group, .. } => group.as_ref(),
1986 Self::Registry { group, .. } => group.as_ref(),
1987 Self::Workspace { group, .. } => group.as_ref(),
1988 }
1989 }
1990}
1991
1992#[derive(Debug, Clone, PartialEq, Eq)]
1994pub enum DependencyType {
1995 Production,
1997 Dev,
1999 Optional(ExtraName),
2001 Group(GroupName),
2003}
2004
2005impl DependencyType {
2006 pub fn toml_table_name(&self) -> Cow<'_, str> {
2008 match self {
2009 Self::Production => Cow::Borrowed("`project.dependencies`"),
2010 Self::Dev => {
2011 Cow::Borrowed("`tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`")
2012 }
2013 Self::Optional(extra) => Cow::Owned(format!("`project.optional-dependencies.{extra}`")),
2014 Self::Group(group) => Cow::Owned(format!("`dependency-groups.{group}`")),
2015 }
2016 }
2017}
2018
2019#[derive(Debug, Clone, PartialEq, Eq)]
2020#[cfg_attr(test, derive(Serialize))]
2021pub(crate) struct BuildBackendSettingsSchema;
2022
2023impl<'de> Deserialize<'de> for BuildBackendSettingsSchema {
2024 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
2025 where
2026 D: Deserializer<'de>,
2027 {
2028 Ok(Self)
2029 }
2030}
2031
2032#[cfg(feature = "schemars")]
2033impl schemars::JsonSchema for BuildBackendSettingsSchema {
2034 fn schema_name() -> Cow<'static, str> {
2035 BuildBackendSettings::schema_name()
2036 }
2037
2038 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2039 BuildBackendSettings::json_schema(generator)
2040 }
2041}
2042
2043impl OptionsMetadata for BuildBackendSettingsSchema {
2044 fn record(visit: &mut dyn Visit) {
2045 BuildBackendSettings::record(visit);
2046 }
2047
2048 fn documentation() -> Option<&'static str> {
2049 BuildBackendSettings::documentation()
2050 }
2051
2052 fn metadata() -> OptionSet
2053 where
2054 Self: Sized + 'static,
2055 {
2056 BuildBackendSettings::metadata()
2057 }
2058}