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::{
25 Index, IndexName, MinimumLibcVersion, NameRequirementSpecification, RequirementSource,
26};
27use uv_fs::{PortablePathBuf, try_relative_to_if};
28use uv_git_types::GitReference;
29use uv_macros::OptionsMetadata;
30use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, ExtraName, GroupName, PackageName};
31use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
32use uv_pep440::{Version, VersionSpecifiers};
33use uv_pep508::MarkerTree;
34use uv_pypi_types::{
35 ConflictError, Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments,
36 VerbatimParsedUrl,
37};
38use uv_redacted::DisplaySafeUrl;
39use uv_toml::deserialize_unique_map;
40
41use crate::DefaultGroupsError;
42
43#[derive(Error, Debug)]
44pub enum PyprojectTomlError {
45 #[error(transparent)]
46 Toml(#[from] toml::de::Error),
47 #[error("Failed to parse `tool.uv.sources`")]
48 Source(
49 #[from]
50 #[source]
51 SourceError,
52 ),
53 #[error(
54 "`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
55 )]
56 MissingName,
57 #[error(
58 "`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
59 )]
60 MissingVersion,
61}
62
63fn deserialize_optional_dependencies<'de, D, V>(
64 deserializer: D,
65) -> Result<Option<BTreeMap<ExtraName, V>>, D::Error>
66where
67 D: Deserializer<'de>,
68 V: Deserialize<'de>,
69{
70 deserialize_unique_map(deserializer, |key: &ExtraName| {
71 format!("duplicate normalized extra name `{key}`")
72 })
73 .map(Some)
74}
75
76#[derive(Deserialize, Debug, Clone)]
78#[cfg_attr(test, derive(Serialize))]
79#[serde(rename_all = "kebab-case")]
80pub struct PyProjectToml {
81 pub project: Option<Project>,
83 pub tool: Option<Tool>,
85 pub dependency_groups: Option<DependencyGroups>,
87 #[serde(skip)]
89 pub raw: String,
90
91 #[serde(default, skip_serializing)]
93 build_system: Option<serde::de::IgnoredAny>,
94}
95
96impl PyProjectToml {
97 pub fn configured_default_groups(&self) -> Option<&DefaultGroups> {
101 self.tool
102 .as_ref()
103 .and_then(|tool| tool.uv.as_ref())
104 .and_then(|uv| uv.default_groups.as_ref())
105 }
106
107 pub(crate) fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
109 if let Some(defaults) = self.configured_default_groups() {
110 if let DefaultGroups::List(defaults) = defaults {
111 for group in defaults {
112 if !self
113 .dependency_groups
114 .as_ref()
115 .is_some_and(|groups| groups.contains_key(group))
116 {
117 return Err(DefaultGroupsError::MissingGroup(group.clone()));
118 }
119 }
120 }
121 Ok(defaults.clone())
122 } else {
123 Ok(DefaultGroups::from_groups(vec![DEV_DEPENDENCIES.clone()]))
124 }
125 }
126
127 #[instrument("toml::from_str workspace", skip_all, fields(path = %_path.as_ref().display()))]
129 pub fn from_string(raw: String, _path: impl AsRef<Path>) -> Result<Self, PyprojectTomlError> {
130 let pyproject: Self = match toml::from_str(&raw) {
131 Ok(pyproject) => pyproject,
132 Err(error) => {
133 let sources = toml::from_str::<PyProjectTomlSourcesWire>(&raw)
135 .map_err(PyprojectTomlError::Toml)?
136 .tool
137 .and_then(|tool| tool.uv)
138 .and_then(|uv| uv.sources);
139 if let Some(sources) = sources {
140 ToolUvSources::try_from(sources)?;
141 }
142 return Err(PyprojectTomlError::Toml(error));
143 }
144 };
145
146 Ok(Self { raw, ..pyproject })
147 }
148
149 pub fn is_package(&self, require_build_system: bool) -> bool {
152 if let Some(is_package) = self.tool_uv_package() {
154 return is_package;
155 }
156
157 self.build_system.is_some() || !require_build_system
159 }
160
161 fn tool_uv_package(&self) -> Option<bool> {
163 self.tool
164 .as_ref()
165 .and_then(|tool| tool.uv.as_ref())
166 .and_then(|uv| uv.package)
167 }
168
169 pub fn has_scripts(&self) -> bool {
171 if let Some(ref project) = self.project {
172 project.gui_scripts.is_some() || project.scripts.is_some()
173 } else {
174 false
175 }
176 }
177
178 pub(crate) fn conflicts(&self) -> Result<Conflicts, ConflictError> {
180 let empty = Conflicts::empty();
181 let Some(project) = self.project.as_ref() else {
182 return Ok(empty);
183 };
184 let Some(tool) = self.tool.as_ref() else {
185 return Ok(empty);
186 };
187 let Some(tooluv) = tool.uv.as_ref() else {
188 return Ok(empty);
189 };
190 let Some(conflicting) = tooluv.conflicts.as_ref() else {
191 return Ok(empty);
192 };
193 conflicting.to_conflicts_with_package_name(&project.name)
194 }
195}
196
197impl PartialEq for PyProjectToml {
199 fn eq(&self, other: &Self) -> bool {
200 self.project.eq(&other.project) && self.tool.eq(&other.tool)
201 }
202}
203
204impl Eq for PyProjectToml {}
205
206impl AsRef<[u8]> for PyProjectToml {
207 fn as_ref(&self) -> &[u8] {
208 self.raw.as_bytes()
209 }
210}
211
212#[derive(Deserialize, Debug, Clone, PartialEq)]
216#[cfg_attr(test, derive(Serialize))]
217#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
218pub struct Project {
219 pub name: PackageName,
221 version: Option<Version>,
223 pub(crate) requires_python: Option<VersionSpecifiers>,
225 pub dependencies: Option<Vec<String>>,
227 pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
229
230 #[serde(default, skip_serializing)]
232 gui_scripts: Option<serde::de::IgnoredAny>,
233 #[serde(default, skip_serializing)]
235 scripts: Option<serde::de::IgnoredAny>,
236}
237
238#[derive(Deserialize, Debug)]
239#[serde(rename_all = "kebab-case")]
240struct ProjectWire {
241 name: Option<PackageName>,
242 version: Option<Version>,
243 dynamic: Option<Vec<String>>,
244 requires_python: Option<VersionSpecifiers>,
245 dependencies: Option<Vec<String>>,
246 #[serde(default, deserialize_with = "deserialize_optional_dependencies")]
247 optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
248 gui_scripts: Option<serde::de::IgnoredAny>,
249 scripts: Option<serde::de::IgnoredAny>,
250}
251
252impl TryFrom<ProjectWire> for Project {
253 type Error = PyprojectTomlError;
254
255 fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
256 let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
258
259 if value.version.is_none()
261 && !value
262 .dynamic
263 .as_ref()
264 .is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
265 {
266 return Err(PyprojectTomlError::MissingVersion);
267 }
268
269 Ok(Self {
270 name,
271 version: value.version,
272 requires_python: value.requires_python,
273 dependencies: value.dependencies,
274 optional_dependencies: value.optional_dependencies,
275 gui_scripts: value.gui_scripts,
276 scripts: value.scripts,
277 })
278 }
279}
280
281#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
282#[cfg_attr(test, derive(Serialize))]
283#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
284pub struct Tool {
285 pub uv: Option<ToolUv>,
286}
287
288fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
294where
295 D: Deserializer<'de>,
296{
297 let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
298 if let Some(indexes) = indexes.as_ref() {
299 let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
300 let mut seen_default = false;
301 for index in indexes {
302 if let Some(name) = index.name.as_ref() {
303 if !seen_names.insert(name) {
304 return Err(serde::de::Error::custom(format!(
305 "duplicate index name `{name}`"
306 )));
307 }
308 }
309 if index.default {
310 if seen_default {
311 return Err(serde::de::Error::custom(
312 "found multiple indexes with `default = true`; only one index may be marked as default",
313 ));
314 }
315 seen_default = true;
316 }
317 }
318 }
319 Ok(indexes)
320}
321
322pub type OverrideDependency = Override<uv_pep508::Requirement<VerbatimParsedUrl>>;
324
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(untagged)]
328#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
329pub enum BuildConstraintDependency {
330 Requirement(uv_pep508::Requirement<VerbatimParsedUrl>),
332 WithHashes {
334 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
335 hashes: Vec<String>,
336 },
337}
338
339impl BuildConstraintDependency {
340 pub fn into_parts(self) -> (uv_pep508::Requirement<VerbatimParsedUrl>, Vec<String>) {
342 match self {
343 Self::Requirement(requirement) => (requirement, Vec::new()),
344 Self::WithHashes {
345 requirement,
346 hashes,
347 } => (requirement, hashes),
348 }
349 }
350}
351
352impl From<BuildConstraintDependency> for NameRequirementSpecification {
353 fn from(value: BuildConstraintDependency) -> Self {
354 let (requirement, hashes) = value.into_parts();
355 Self {
356 requirement: requirement.into(),
357 hashes,
358 }
359 }
360}
361
362#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
365#[cfg_attr(test, derive(Serialize))]
366#[serde(rename_all = "kebab-case")]
367#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
368pub struct ToolUv {
369 #[option(
377 default = "{}",
378 value_type = "dict",
379 example = r#"
380 [tool.uv.sources]
381 httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
382 pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
383 pydantic = { path = "/path/to/pydantic", editable = true }
384 "#
385 )]
386 pub sources: Option<ToolUvSources>,
387
388 #[option(
416 default = "[]",
417 value_type = "dict",
418 example = r#"
419 [[tool.uv.index]]
420 name = "pytorch"
421 url = "https://download.pytorch.org/whl/cu130"
422 "#
423 )]
424 #[serde(deserialize_with = "deserialize_index_vec", default)]
425 pub index: Option<Vec<Index>>,
426
427 #[option_group]
429 pub(crate) workspace: Option<ToolUvWorkspace>,
430
431 #[option(
434 default = r#"true"#,
435 value_type = "bool",
436 example = r#"
437 managed = false
438 "#
439 )]
440 pub(crate) managed: Option<bool>,
441
442 #[option(
453 default = r#"true"#,
454 value_type = "bool",
455 example = r#"
456 package = false
457 "#
458 )]
459 package: Option<bool>,
460
461 #[option(
465 default = r#"["dev"]"#,
466 value_type = r#"str | list[str]"#,
467 example = r#"
468 default-groups = ["docs"]
469 "#
470 )]
471 default_groups: Option<DefaultGroups>,
472
473 #[option(
482 default = "[]",
483 value_type = "dict",
484 example = r#"
485 [tool.uv.dependency-groups]
486 my-group = {requires-python = ">=3.12"}
487 "#
488 )]
489 pub(crate) dependency_groups: Option<ToolUvDependencyGroups>,
490
491 #[cfg_attr(
501 feature = "schemars",
502 schemars(
503 with = "Option<Vec<String>>",
504 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
505 )
506 )]
507 #[option(
508 default = "[]",
509 value_type = "list[str]",
510 example = r#"
511 dev-dependencies = ["ruff==0.5.0"]
512 "#
513 )]
514 pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
515
516 #[option(
545 default = "[]",
546 value_type = "list[str | dict]",
547 example = r#"
548 override-dependencies = [
549 # Always install Werkzeug 2.3.0.
550 "werkzeug==2.3.0",
551 # Use itsdangerous 2.1.2 when requested by Flask 3.0.0.
552 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous==2.1.2"] },
553 ]
554 "#
555 )]
556 pub(crate) override_dependencies: Option<Vec<OverrideDependency>>,
557
558 #[option(
579 default = "[]",
580 value_type = "list[str | dict]",
581 example = r#"
582 # Exclude Werkzeug from being installed, even if transitive dependencies request it.
583 exclude-dependencies = [
584 "werkzeug",
585 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous"] },
586 ]
587 "#
588 )]
589 pub(crate) exclude_dependencies: Option<Vec<ExcludeDependency>>,
590
591 #[cfg_attr(
605 feature = "schemars",
606 schemars(
607 with = "Option<Vec<String>>",
608 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
609 )
610 )]
611 #[option(
612 default = "[]",
613 value_type = "list[str]",
614 example = r#"
615 # Ensure that the grpcio version is always less than 1.65, if it's requested by a
616 # direct or transitive dependency.
617 constraint-dependencies = ["grpcio<1.65"]
618 "#
619 )]
620 pub(crate) constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
621
622 #[option(
639 default = "[]",
640 value_type = "list[str | dict]",
641 example = r#"
642 # Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
643 # on setuptools.
644 build-constraint-dependencies = ["setuptools==60.0.0"]
645 "#
646 )]
647 pub(crate) build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
648
649 #[cfg_attr(
658 feature = "schemars",
659 schemars(
660 with = "Option<Vec<String>>",
661 description = "A list of environment markers, e.g., `python_version >= '3.6'`."
662 )
663 )]
664 #[option(
665 default = "[]",
666 value_type = "str | list[str]",
667 example = r#"
668 # Resolve for macOS, but not for Linux or Windows.
669 environments = ["sys_platform == 'darwin'"]
670 "#
671 )]
672 pub(crate) environments: Option<SupportedEnvironments>,
673
674 #[cfg_attr(
694 feature = "schemars",
695 schemars(
696 with = "Option<Vec<String>>",
697 description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
698 )
699 )]
700 #[option(
701 default = "[]",
702 value_type = "str | list[str]",
703 example = r#"
704 # Require that the package is available on the following platforms:
705 required-environments = [
706 # macOS on Apple Silicon (ARM)
707 "sys_platform == 'darwin' and platform_machine == 'arm64'",
708 # Linux on x86_64 (Intel/AMD)
709 "sys_platform == 'linux' and platform_machine == 'x86_64'",
710 # Windows on x86_64 (Intel/AMD)
711 "sys_platform == 'win32' and platform_machine == 'AMD64'",
712 ]
713 "#
714 )]
715 pub(crate) required_environments: Option<SupportedEnvironments>,
716
717 #[option(
735 default = "None",
736 value_type = "dict[str, str]",
737 example = r#"
738 preview-features = ["minimum-libc-version"]
739 required-environments = [
740 "sys_platform == 'linux' and platform_machine == 'x86_64'",
741 "sys_platform == 'linux' and platform_machine == 'aarch64'",
742 ]
743 minimum-libc-version = { glibc = "2.31" }
744 "#
745 )]
746 pub(crate) minimum_libc_version: Option<MinimumLibcVersion>,
747
748 #[cfg_attr(
763 feature = "schemars",
764 schemars(description = "A list of sets of conflicting groups or extras.")
765 )]
766 #[option(
767 default = r#"[]"#,
768 value_type = "list[list[dict]]",
769 example = r#"
770 # Require that `package[extra1]` and `package[extra2]` are resolved
771 # in different forks so that they cannot conflict with one another.
772 conflicts = [
773 [
774 { extra = "extra1" },
775 { extra = "extra2" },
776 ]
777 ]
778
779 # Require that the dependency groups `group1` and `group2`
780 # are resolved in different forks so that they cannot conflict
781 # with one another.
782 conflicts = [
783 [
784 { group = "group1" },
785 { group = "group2" },
786 ]
787 ]
788 "#
789 )]
790 pub(crate) conflicts: Option<SchemaConflicts>,
791
792 #[option_group]
799 build_backend: Option<BuildBackendSettingsSchema>,
800}
801
802#[derive(Default, Debug, Clone, PartialEq, Eq)]
803#[cfg_attr(test, derive(Serialize))]
804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
805pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
806
807#[derive(Deserialize, Debug)]
808#[serde(rename_all = "kebab-case")]
809struct PyProjectTomlSourcesWire {
810 tool: Option<ToolSourcesWire>,
811}
812
813#[derive(Deserialize, Debug)]
814struct ToolSourcesWire {
815 uv: Option<ToolUvSourcesOnlyWire>,
816}
817
818#[derive(Deserialize, Debug)]
819#[serde(rename_all = "kebab-case")]
820struct ToolUvSourcesOnlyWire {
821 sources: Option<ToolUvSourcesWire>,
822}
823
824#[derive(Default, Debug, Clone, PartialEq, Eq)]
825struct ToolUvSourcesWire(BTreeMap<PackageName, SourcesWire>);
826
827impl ToolUvSources {
828 pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
830 &self.0
831 }
832
833 #[must_use]
835 pub(crate) fn into_inner(self) -> BTreeMap<PackageName, Sources> {
836 self.0
837 }
838}
839
840impl TryFrom<ToolUvSourcesWire> for ToolUvSources {
841 type Error = SourceError;
842
843 fn try_from(wire: ToolUvSourcesWire) -> Result<Self, Self::Error> {
844 wire.0
845 .into_iter()
846 .map(|(name, sources)| Sources::try_from(sources).map(|sources| (name, sources)))
847 .collect::<Result<BTreeMap<_, _>, _>>()
848 .map(Self)
849 }
850}
851
852impl<'de> serde::de::Deserialize<'de> for ToolUvSourcesWire {
854 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
855 where
856 D: Deserializer<'de>,
857 {
858 deserialize_unique_map(deserializer, |key: &PackageName| {
859 format!("duplicate sources for package `{key}`")
860 })
861 .map(ToolUvSourcesWire)
862 }
863}
864
865impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
867 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
868 where
869 D: Deserializer<'de>,
870 {
871 deserialize_unique_map(deserializer, |key: &PackageName| {
872 format!("duplicate sources for package `{key}`")
873 })
874 .map(ToolUvSources)
875 }
876}
877
878#[derive(Default, Debug, Clone, PartialEq, Eq)]
879#[cfg_attr(test, derive(Serialize))]
880#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
881pub(crate) struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
882
883impl ToolUvDependencyGroups {
884 pub(crate) fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
886 &self.0
887 }
888}
889
890impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
892 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
893 where
894 D: Deserializer<'de>,
895 {
896 deserialize_unique_map(deserializer, |key: &GroupName| {
897 format!("duplicate settings for dependency group `{key}`")
898 })
899 .map(ToolUvDependencyGroups)
900 }
901}
902
903#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
904#[cfg_attr(test, derive(Serialize))]
905#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
906#[serde(rename_all = "kebab-case")]
907pub(crate) struct DependencyGroupSettings {
908 #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
910 pub(crate) requires_python: Option<VersionSpecifiers>,
911}
912
913#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
914#[serde(untagged, rename_all = "kebab-case")]
915#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
916enum ExtraBuildDependencyWire {
917 Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
918 #[serde(rename_all = "kebab-case")]
919 Annotated {
920 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
921 match_runtime: bool,
922 },
923}
924
925#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
926#[serde(
927 deny_unknown_fields,
928 from = "ExtraBuildDependencyWire",
929 into = "ExtraBuildDependencyWire"
930)]
931#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
932pub struct ExtraBuildDependency {
933 pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
934 pub match_runtime: bool,
935}
936
937impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
938 fn from(value: ExtraBuildDependency) -> Self {
939 value.requirement
940 }
941}
942
943impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
944 fn from(wire: ExtraBuildDependencyWire) -> Self {
945 match wire {
946 ExtraBuildDependencyWire::Unannotated(requirement) => Self {
947 requirement,
948 match_runtime: false,
949 },
950 ExtraBuildDependencyWire::Annotated {
951 requirement,
952 match_runtime,
953 } => Self {
954 requirement,
955 match_runtime,
956 },
957 }
958 }
959}
960
961impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
962 fn from(item: ExtraBuildDependency) -> Self {
963 Self::Annotated {
964 requirement: item.requirement,
965 match_runtime: item.match_runtime,
966 }
967 }
968}
969
970#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
971#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
972pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
973
974impl std::ops::Deref for ExtraBuildDependencies {
975 type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
976
977 fn deref(&self) -> &Self::Target {
978 &self.0
979 }
980}
981
982impl std::ops::DerefMut for ExtraBuildDependencies {
983 fn deref_mut(&mut self) -> &mut Self::Target {
984 &mut self.0
985 }
986}
987
988impl IntoIterator for ExtraBuildDependencies {
989 type Item = (PackageName, Vec<ExtraBuildDependency>);
990 type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
991
992 fn into_iter(self) -> Self::IntoIter {
993 self.0.into_iter()
994 }
995}
996
997impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
998 fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
999 iter: T,
1000 ) -> Self {
1001 Self(iter.into_iter().collect())
1002 }
1003}
1004
1005impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
1007 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1008 where
1009 D: Deserializer<'de>,
1010 {
1011 deserialize_unique_map(deserializer, |key: &PackageName| {
1012 format!("duplicate extra-build-dependencies for `{key}`")
1013 })
1014 .map(ExtraBuildDependencies)
1015 }
1016}
1017
1018#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
1019#[cfg_attr(test, derive(Serialize))]
1020#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1021#[serde(rename_all = "kebab-case", deny_unknown_fields)]
1022pub(crate) struct ToolUvWorkspace {
1023 #[option(
1029 default = "[]",
1030 value_type = "list[str]",
1031 example = r#"
1032 members = ["member1", "path/to/member2", "libs/*"]
1033 "#
1034 )]
1035 pub(crate) members: Option<Vec<SerdePattern>>,
1036 #[option(
1043 default = "[]",
1044 value_type = "list[str]",
1045 example = r#"
1046 exclude = ["member1", "path/to/member2", "libs/*"]
1047 "#
1048 )]
1049 pub(crate) exclude: Option<Vec<SerdePattern>>,
1050}
1051
1052#[derive(Debug, Clone, PartialEq, Eq)]
1054pub(crate) struct SerdePattern(Pattern);
1055
1056impl serde::ser::Serialize for SerdePattern {
1057 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1058 where
1059 S: serde::ser::Serializer,
1060 {
1061 self.0.as_str().serialize(serializer)
1062 }
1063}
1064
1065impl<'de> serde::Deserialize<'de> for SerdePattern {
1066 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1067 struct Visitor;
1068
1069 impl serde::de::Visitor<'_> for Visitor {
1070 type Value = SerdePattern;
1071
1072 fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1073 f.write_str("a string")
1074 }
1075
1076 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
1077 Pattern::from_str(v)
1078 .map(SerdePattern)
1079 .map_err(serde::de::Error::custom)
1080 }
1081 }
1082
1083 deserializer.deserialize_str(Visitor)
1084 }
1085}
1086
1087#[cfg(feature = "schemars")]
1088impl schemars::JsonSchema for SerdePattern {
1089 fn schema_name() -> Cow<'static, str> {
1090 Cow::Borrowed("SerdePattern")
1091 }
1092
1093 fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
1094 <String as schemars::JsonSchema>::json_schema(generator)
1095 }
1096}
1097
1098impl Deref for SerdePattern {
1099 type Target = Pattern;
1100
1101 fn deref(&self) -> &Self::Target {
1102 &self.0
1103 }
1104}
1105
1106#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1108#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
1109pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
1110
1111impl Sources {
1112 pub fn iter(&self) -> impl Iterator<Item = &Source> {
1118 self.0.iter()
1119 }
1120}
1121
1122impl FromIterator<Source> for Sources {
1123 fn from_iter<T: IntoIterator<Item = Source>>(iter: T) -> Self {
1124 Self(iter.into_iter().collect())
1125 }
1126}
1127
1128impl IntoIterator for Sources {
1129 type Item = Source;
1130 type IntoIter = std::vec::IntoIter<Source>;
1131
1132 fn into_iter(self) -> Self::IntoIter {
1133 self.0.into_iter()
1134 }
1135}
1136
1137#[derive(Debug, Clone, PartialEq, Eq)]
1138#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1139enum SourcesWire {
1140 One(Source),
1141 Many(Vec<Source>),
1142}
1143
1144impl<'de> serde::de::Deserialize<'de> for SourcesWire {
1145 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1146 where
1147 D: Deserializer<'de>,
1148 {
1149 struct Visitor;
1150
1151 impl<'de> serde::de::Visitor<'de> for Visitor {
1152 type Value = SourcesWire;
1153
1154 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1155 formatter.write_str("a single source (as a map) or list of sources")
1156 }
1157
1158 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1159 where
1160 A: SeqAccess<'de>,
1161 {
1162 let sources = serde::de::Deserialize::deserialize(
1163 serde::de::value::SeqAccessDeserializer::new(seq),
1164 )?;
1165 Ok(SourcesWire::Many(sources))
1166 }
1167
1168 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
1169 where
1170 M: serde::de::MapAccess<'de>,
1171 {
1172 let source = serde::de::Deserialize::deserialize(
1173 serde::de::value::MapAccessDeserializer::new(&mut map),
1174 )?;
1175 Ok(SourcesWire::One(source))
1176 }
1177 }
1178
1179 deserializer.deserialize_any(Visitor)
1180 }
1181}
1182
1183impl TryFrom<SourcesWire> for Sources {
1184 type Error = SourceError;
1185
1186 fn try_from(wire: SourcesWire) -> Result<Self, Self::Error> {
1187 match wire {
1188 SourcesWire::One(source) => Ok(Self(vec![source])),
1189 SourcesWire::Many(sources) => {
1190 for [lhs, rhs] in sources.array_windows() {
1191 if lhs.extra() != rhs.extra() {
1192 continue;
1193 }
1194 if lhs.group() != rhs.group() {
1195 continue;
1196 }
1197
1198 let lhs = lhs.marker();
1199 let rhs = rhs.marker();
1200 if !lhs.is_disjoint(rhs) {
1201 let Some(left) = lhs.contents().map(|contents| contents.to_string()) else {
1202 return Err(SourceError::MissingMarkers);
1203 };
1204
1205 let Some(right) = rhs.contents().map(|contents| contents.to_string())
1206 else {
1207 return Err(SourceError::MissingMarkers);
1208 };
1209
1210 let hint = lhs.negate().and(rhs);
1211 let hint = hint
1212 .contents()
1213 .map(|contents| contents.to_string())
1214 .unwrap_or_else(|| "true".to_string());
1215
1216 return Err(SourceError::OverlappingMarkers(left, right, hint));
1217 }
1218 }
1219
1220 if sources.is_empty() {
1222 return Err(SourceError::EmptySources);
1223 }
1224
1225 Ok(Self(sources))
1226 }
1227 }
1228 }
1229}
1230
1231#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
1233#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1234#[serde(rename_all = "kebab-case", untagged, deny_unknown_fields)]
1235pub enum Source {
1236 Git {
1243 git: DisplaySafeUrl,
1245 subdirectory: Option<PortablePathBuf>,
1247 path: Option<PortablePathBuf>,
1249 rev: Option<String>,
1251 tag: Option<String>,
1252 branch: Option<String>,
1253 lfs: Option<bool>,
1255 #[serde(
1256 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1257 serialize_with = "uv_pep508::marker::ser::serialize",
1258 default
1259 )]
1260 marker: MarkerTree,
1261 extra: Option<ExtraName>,
1262 group: Option<GroupName>,
1263 },
1264 Url {
1272 url: DisplaySafeUrl,
1273 subdirectory: Option<PortablePathBuf>,
1276 #[serde(
1277 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1278 serialize_with = "uv_pep508::marker::ser::serialize",
1279 default
1280 )]
1281 marker: MarkerTree,
1282 extra: Option<ExtraName>,
1283 group: Option<GroupName>,
1284 },
1285 Path {
1289 path: PortablePathBuf,
1290 editable: Option<bool>,
1292 package: Option<bool>,
1299 #[serde(
1300 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1301 serialize_with = "uv_pep508::marker::ser::serialize",
1302 default
1303 )]
1304 marker: MarkerTree,
1305 extra: Option<ExtraName>,
1306 group: Option<GroupName>,
1307 },
1308 Registry {
1310 index: IndexName,
1311 #[serde(
1312 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1313 serialize_with = "uv_pep508::marker::ser::serialize",
1314 default
1315 )]
1316 marker: MarkerTree,
1317 extra: Option<ExtraName>,
1318 group: Option<GroupName>,
1319 },
1320 Workspace {
1322 workspace: WorkspaceReference,
1328 editable: Option<bool>,
1330 #[serde(
1331 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1332 serialize_with = "uv_pep508::marker::ser::serialize",
1333 default
1334 )]
1335 marker: MarkerTree,
1336 extra: Option<ExtraName>,
1337 group: Option<GroupName>,
1338 },
1339}
1340
1341#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1343#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1344#[serde(untagged)]
1345pub enum WorkspaceReference {
1346 Bool(bool),
1347 Path(PortablePathBuf),
1348}
1349
1350impl<'de> Deserialize<'de> for Source {
1353 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1354 where
1355 D: Deserializer<'de>,
1356 {
1357 #[derive(Deserialize, Debug, Clone)]
1358 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
1359 struct CatchAll {
1360 git: Option<DisplaySafeUrl>,
1361 subdirectory: Option<PortablePathBuf>,
1362 rev: Option<String>,
1363 tag: Option<String>,
1364 branch: Option<String>,
1365 lfs: Option<bool>,
1366 url: Option<DisplaySafeUrl>,
1367 path: Option<PortablePathBuf>,
1368 editable: Option<bool>,
1369 package: Option<bool>,
1370 index: Option<IndexName>,
1371 workspace: Option<WorkspaceReference>,
1372 #[serde(
1373 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1374 serialize_with = "uv_pep508::marker::ser::serialize",
1375 default
1376 )]
1377 marker: MarkerTree,
1378 extra: Option<ExtraName>,
1379 group: Option<GroupName>,
1380 }
1381
1382 let CatchAll {
1384 git,
1385 subdirectory,
1386 rev,
1387 tag,
1388 branch,
1389 lfs,
1390 url,
1391 path,
1392 editable,
1393 package,
1394 index,
1395 workspace,
1396 marker,
1397 extra,
1398 group,
1399 } = CatchAll::deserialize(deserializer)?;
1400
1401 if extra.is_some() && group.is_some() {
1403 return Err(serde::de::Error::custom(
1404 "cannot specify both `extra` and `group`",
1405 ));
1406 }
1407
1408 if let Some(git) = git {
1410 if index.is_some() {
1411 return Err(serde::de::Error::custom(
1412 "cannot specify both `git` and `index`",
1413 ));
1414 }
1415 if workspace.is_some() {
1416 return Err(serde::de::Error::custom(
1417 "cannot specify both `git` and `workspace`",
1418 ));
1419 }
1420 if url.is_some() {
1421 return Err(serde::de::Error::custom(
1422 "cannot specify both `git` and `url`",
1423 ));
1424 }
1425 if editable.is_some() {
1426 return Err(serde::de::Error::custom(
1427 "cannot specify both `git` and `editable`",
1428 ));
1429 }
1430 if package.is_some() {
1431 return Err(serde::de::Error::custom(
1432 "cannot specify both `git` and `package`",
1433 ));
1434 }
1435 if subdirectory.is_some() && path.is_some() {
1436 return Err(serde::de::Error::custom(
1437 "cannot specify both `subdirectory` and `path`",
1438 ));
1439 }
1440
1441 match (rev.as_ref(), tag.as_ref(), branch.as_ref()) {
1443 (None, None, None) => {}
1444 (Some(_), None, None) => {}
1445 (None, Some(_), None) => {}
1446 (None, None, Some(_)) => {}
1447 _ => {
1448 return Err(serde::de::Error::custom(
1449 "expected at most one of `rev`, `tag`, or `branch`",
1450 ));
1451 }
1452 }
1453
1454 let git = if let Some(git) = git.as_str().strip_prefix("git+") {
1456 DisplaySafeUrl::parse(git).map_err(serde::de::Error::custom)?
1457 } else {
1458 git
1459 };
1460
1461 return Ok(Self::Git {
1462 git,
1463 subdirectory,
1464 path,
1465 rev,
1466 tag,
1467 branch,
1468 lfs,
1469 marker,
1470 extra,
1471 group,
1472 });
1473 }
1474
1475 if let Some(url) = url {
1477 if index.is_some() {
1478 return Err(serde::de::Error::custom(
1479 "cannot specify both `url` and `index`",
1480 ));
1481 }
1482 if workspace.is_some() {
1483 return Err(serde::de::Error::custom(
1484 "cannot specify both `url` and `workspace`",
1485 ));
1486 }
1487 if path.is_some() {
1488 return Err(serde::de::Error::custom(
1489 "cannot specify both `url` and `path`",
1490 ));
1491 }
1492 if git.is_some() {
1493 return Err(serde::de::Error::custom(
1494 "cannot specify both `url` and `git`",
1495 ));
1496 }
1497 if rev.is_some() {
1498 return Err(serde::de::Error::custom(
1499 "cannot specify both `url` and `rev`",
1500 ));
1501 }
1502 if tag.is_some() {
1503 return Err(serde::de::Error::custom(
1504 "cannot specify both `url` and `tag`",
1505 ));
1506 }
1507 if branch.is_some() {
1508 return Err(serde::de::Error::custom(
1509 "cannot specify both `url` and `branch`",
1510 ));
1511 }
1512 if editable.is_some() {
1513 return Err(serde::de::Error::custom(
1514 "cannot specify both `url` and `editable`",
1515 ));
1516 }
1517 if package.is_some() {
1518 return Err(serde::de::Error::custom(
1519 "cannot specify both `url` and `package`",
1520 ));
1521 }
1522
1523 return Ok(Self::Url {
1524 url,
1525 subdirectory,
1526 marker,
1527 extra,
1528 group,
1529 });
1530 }
1531
1532 if let Some(path) = path {
1534 if index.is_some() {
1535 return Err(serde::de::Error::custom(
1536 "cannot specify both `path` and `index`",
1537 ));
1538 }
1539 if workspace.is_some() {
1540 return Err(serde::de::Error::custom(
1541 "cannot specify both `path` and `workspace`",
1542 ));
1543 }
1544 if git.is_some() {
1545 return Err(serde::de::Error::custom(
1546 "cannot specify both `path` and `git`",
1547 ));
1548 }
1549 if url.is_some() {
1550 return Err(serde::de::Error::custom(
1551 "cannot specify both `path` and `url`",
1552 ));
1553 }
1554 if rev.is_some() {
1555 return Err(serde::de::Error::custom(
1556 "cannot specify both `path` and `rev`",
1557 ));
1558 }
1559 if tag.is_some() {
1560 return Err(serde::de::Error::custom(
1561 "cannot specify both `path` and `tag`",
1562 ));
1563 }
1564 if branch.is_some() {
1565 return Err(serde::de::Error::custom(
1566 "cannot specify both `path` and `branch`",
1567 ));
1568 }
1569
1570 if editable == Some(true) && package == Some(false) {
1572 return Err(serde::de::Error::custom(
1573 "cannot specify both `editable = true` and `package = false`",
1574 ));
1575 }
1576
1577 return Ok(Self::Path {
1578 path,
1579 editable,
1580 package,
1581 marker,
1582 extra,
1583 group,
1584 });
1585 }
1586
1587 if let Some(index) = index {
1589 if workspace.is_some() {
1590 return Err(serde::de::Error::custom(
1591 "cannot specify both `index` and `workspace`",
1592 ));
1593 }
1594 if git.is_some() {
1595 return Err(serde::de::Error::custom(
1596 "cannot specify both `index` and `git`",
1597 ));
1598 }
1599 if url.is_some() {
1600 return Err(serde::de::Error::custom(
1601 "cannot specify both `index` and `url`",
1602 ));
1603 }
1604 if path.is_some() {
1605 return Err(serde::de::Error::custom(
1606 "cannot specify both `index` and `path`",
1607 ));
1608 }
1609 if rev.is_some() {
1610 return Err(serde::de::Error::custom(
1611 "cannot specify both `index` and `rev`",
1612 ));
1613 }
1614 if tag.is_some() {
1615 return Err(serde::de::Error::custom(
1616 "cannot specify both `index` and `tag`",
1617 ));
1618 }
1619 if branch.is_some() {
1620 return Err(serde::de::Error::custom(
1621 "cannot specify both `index` and `branch`",
1622 ));
1623 }
1624 if editable.is_some() {
1625 return Err(serde::de::Error::custom(
1626 "cannot specify both `index` and `editable`",
1627 ));
1628 }
1629 if package.is_some() {
1630 return Err(serde::de::Error::custom(
1631 "cannot specify both `index` and `package`",
1632 ));
1633 }
1634
1635 return Ok(Self::Registry {
1636 index,
1637 marker,
1638 extra,
1639 group,
1640 });
1641 }
1642
1643 if let Some(workspace) = workspace {
1645 if index.is_some() {
1646 return Err(serde::de::Error::custom(
1647 "cannot specify both `workspace` and `index`",
1648 ));
1649 }
1650 if git.is_some() {
1651 return Err(serde::de::Error::custom(
1652 "cannot specify both `workspace` and `git`",
1653 ));
1654 }
1655 if url.is_some() {
1656 return Err(serde::de::Error::custom(
1657 "cannot specify both `workspace` and `url`",
1658 ));
1659 }
1660 if path.is_some() {
1661 return Err(serde::de::Error::custom(
1662 "cannot specify both `workspace` and `path`",
1663 ));
1664 }
1665 if rev.is_some() {
1666 return Err(serde::de::Error::custom(
1667 "cannot specify both `workspace` and `rev`",
1668 ));
1669 }
1670 if tag.is_some() {
1671 return Err(serde::de::Error::custom(
1672 "cannot specify both `workspace` and `tag`",
1673 ));
1674 }
1675 if branch.is_some() {
1676 return Err(serde::de::Error::custom(
1677 "cannot specify both `workspace` and `branch`",
1678 ));
1679 }
1680 if package.is_some() {
1681 return Err(serde::de::Error::custom(
1682 "cannot specify both `workspace` and `package`",
1683 ));
1684 }
1685
1686 return Ok(Self::Workspace {
1687 workspace,
1688 editable,
1689 marker,
1690 extra,
1691 group,
1692 });
1693 }
1694
1695 Err(serde::de::Error::custom(
1697 "expected one of `git`, `url`, `path`, `index`, or `workspace`",
1698 ))
1699 }
1700}
1701
1702#[derive(Error, Debug)]
1703pub enum SourceError {
1704 #[error("Failed to resolve Git reference: `{0}`")]
1705 UnresolvedReference(String),
1706 #[error("Workspace dependency `{0}` must refer to local directory, not a Git repository")]
1707 WorkspacePackageGit(String),
1708 #[error("Workspace dependency `{0}` must refer to local directory, not a URL")]
1709 WorkspacePackageUrl(String),
1710 #[error("Workspace dependency `{0}` must refer to local directory, not a file")]
1711 WorkspacePackageFile(String),
1712 #[error(
1713 "`{0}` did not resolve to a Git repository, but a Git reference (`--rev {1}`) was provided."
1714 )]
1715 UnusedRev(String, String),
1716 #[error(
1717 "`{0}` did not resolve to a Git repository, but a Git reference (`--tag {1}`) was provided."
1718 )]
1719 UnusedTag(String, String),
1720 #[error(
1721 "`{0}` did not resolve to a Git repository, but a Git reference (`--branch {1}`) was provided."
1722 )]
1723 UnusedBranch(String, String),
1724 #[error(
1725 "`{0}` did not resolve to a Git repository, but a Git extension (`--lfs`) was provided."
1726 )]
1727 UnusedLfs(String),
1728 #[error(
1729 "`{0}` did not resolve to a local directory, but the `--editable` flag was provided. Editable installs are only supported for local directories."
1730 )]
1731 UnusedEditable(String),
1732 #[error("Failed to resolve absolute path")]
1733 Absolute(#[from] std::io::Error),
1734 #[error("Path contains invalid characters: {}", _0.display())]
1735 NonUtf8Path(PathBuf),
1736 #[error("Source markers must be disjoint, but the following markers overlap: `{0}` and `{1}`.")]
1737 OverlappingMarkers(String, String, String),
1738 #[error(
1739 "When multiple sources are provided, each source must include a platform marker (e.g., `marker = \"sys_platform == 'linux'\"`)"
1740 )]
1741 MissingMarkers,
1742 #[error("Must provide at least one source")]
1743 EmptySources,
1744}
1745
1746impl uv_errors::Hinted for SourceError {
1747 fn hints(&self) -> uv_errors::Hints<'_> {
1748 match self {
1749 Self::OverlappingMarkers(_, rhs, replacement) => {
1750 uv_errors::Hints::from(format!("replace `{rhs}` with `{replacement}`"))
1751 }
1752 _ => uv_errors::Hints::none(),
1753 }
1754 }
1755}
1756
1757impl Source {
1758 pub fn from_requirement(
1759 name: &PackageName,
1760 source: RequirementSource,
1761 workspace: bool,
1762 editable: Option<bool>,
1763 index: Option<IndexName>,
1764 rev: Option<String>,
1765 tag: Option<String>,
1766 branch: Option<String>,
1767 lfs: GitLfsSetting,
1768 root: &Path,
1769 existing_sources: Option<&BTreeMap<PackageName, Sources>>,
1770 ) -> Result<Option<Self>, SourceError> {
1771 if !matches!(
1773 source,
1774 RequirementSource::GitDirectory { .. } | RequirementSource::GitPath { .. }
1775 ) && (branch.is_some()
1776 || tag.is_some()
1777 || rev.is_some()
1778 || matches!(lfs, GitLfsSetting::Enabled { .. }))
1779 {
1780 if let Some(sources) = existing_sources
1781 && let Some(package_sources) = sources.get(name)
1782 {
1783 for existing_source in package_sources.iter() {
1784 if let Self::Git {
1785 git,
1786 subdirectory,
1787 path,
1788 marker,
1789 extra,
1790 group,
1791 ..
1792 } = existing_source
1793 {
1794 return Ok(Some(Self::Git {
1795 git: git.clone(),
1796 subdirectory: subdirectory.clone(),
1797 rev,
1798 tag,
1799 branch,
1800 lfs: lfs.into(),
1801 marker: *marker,
1802 path: path.clone(),
1803 extra: extra.clone(),
1804 group: group.clone(),
1805 }));
1806 }
1807 }
1808 }
1809 if let Some(rev) = rev {
1810 return Err(SourceError::UnusedRev(name.to_string(), rev));
1811 }
1812 if let Some(tag) = tag {
1813 return Err(SourceError::UnusedTag(name.to_string(), tag));
1814 }
1815 if let Some(branch) = branch {
1816 return Err(SourceError::UnusedBranch(name.to_string(), branch));
1817 }
1818 if matches!(lfs, GitLfsSetting::Enabled { from_env: false }) {
1819 return Err(SourceError::UnusedLfs(name.to_string()));
1820 }
1821 }
1822
1823 if !workspace {
1825 if !matches!(source, RequirementSource::Directory { .. }) {
1826 if editable == Some(true) {
1827 return Err(SourceError::UnusedEditable(name.to_string()));
1828 }
1829 }
1830 }
1831
1832 if workspace {
1834 return match source {
1835 RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => {
1836 Ok(Some(Self::Workspace {
1837 workspace: WorkspaceReference::Bool(true),
1838 editable,
1839 marker: MarkerTree::TRUE,
1840 extra: None,
1841 group: None,
1842 }))
1843 }
1844 RequirementSource::Url { .. } => {
1845 Err(SourceError::WorkspacePackageUrl(name.to_string()))
1846 }
1847 RequirementSource::GitDirectory { .. } => {
1848 Err(SourceError::WorkspacePackageGit(name.to_string()))
1849 }
1850 RequirementSource::GitPath { .. } => {
1851 Err(SourceError::WorkspacePackageGit(name.to_string()))
1852 }
1853 RequirementSource::Path { .. } => {
1854 Err(SourceError::WorkspacePackageFile(name.to_string()))
1855 }
1856 };
1857 }
1858
1859 let source = match source {
1860 RequirementSource::Registry { index: Some(_), .. } => {
1861 return Ok(None);
1862 }
1863 RequirementSource::Registry { index: None, .. } if let Some(index) = index => {
1864 Self::Registry {
1865 index,
1866 marker: MarkerTree::TRUE,
1867 extra: None,
1868 group: None,
1869 }
1870 }
1871 RequirementSource::Registry { index: None, .. } => return Ok(None),
1872 RequirementSource::Path {
1873 install_path, url, ..
1874 } => Self::Path {
1875 editable: None,
1876 package: None,
1877 path: PortablePathBuf::from(
1878 try_relative_to_if(&install_path, root, url.prefers_relative())
1879 .map_err(SourceError::Absolute)?
1880 .into_boxed_path(),
1881 ),
1882 marker: MarkerTree::TRUE,
1883 extra: None,
1884 group: None,
1885 },
1886 RequirementSource::Directory {
1887 install_path,
1888 editable: is_editable,
1889 url,
1890 ..
1891 } => Self::Path {
1892 editable: editable.or(is_editable),
1893 package: None,
1894 path: PortablePathBuf::from(
1895 try_relative_to_if(&install_path, root, url.prefers_relative())
1896 .map_err(SourceError::Absolute)?
1897 .into_boxed_path(),
1898 ),
1899 marker: MarkerTree::TRUE,
1900 extra: None,
1901 group: None,
1902 },
1903 RequirementSource::Url {
1904 location,
1905 subdirectory,
1906 ..
1907 } => Self::Url {
1908 url: location,
1909 subdirectory: subdirectory.map(PortablePathBuf::from),
1910 marker: MarkerTree::TRUE,
1911 extra: None,
1912 group: None,
1913 },
1914 RequirementSource::GitDirectory {
1915 git, subdirectory, ..
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: subdirectory.map(PortablePathBuf::from),
1933 path: None,
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: subdirectory.map(PortablePathBuf::from),
1946 path: None,
1947 marker: MarkerTree::TRUE,
1948 extra: None,
1949 group: None,
1950 }
1951 }
1952 }
1953 RequirementSource::GitPath {
1954 git, install_path, ..
1955 } => {
1956 if rev.is_none() && tag.is_none() && branch.is_none() {
1957 let rev = match git.reference() {
1958 GitReference::Branch(rev) => Some(rev),
1959 GitReference::Tag(rev) => Some(rev),
1960 GitReference::BranchOrTag(rev) => Some(rev),
1961 GitReference::BranchOrTagOrCommit(rev) => Some(rev),
1962 GitReference::NamedRef(rev) => Some(rev),
1963 GitReference::DefaultBranch => None,
1964 };
1965 Self::Git {
1966 rev: rev.cloned(),
1967 tag,
1968 branch,
1969 lfs: lfs.into(),
1970 git: git.url().clone(),
1971 subdirectory: None,
1972 path: Some(PortablePathBuf::from(install_path.as_path())),
1973 marker: MarkerTree::TRUE,
1974 extra: None,
1975 group: None,
1976 }
1977 } else {
1978 Self::Git {
1979 rev,
1980 tag,
1981 branch,
1982 lfs: lfs.into(),
1983 git: git.url().clone(),
1984 subdirectory: None,
1985 path: Some(PortablePathBuf::from(install_path.as_path())),
1986 marker: MarkerTree::TRUE,
1987 extra: None,
1988 group: None,
1989 }
1990 }
1991 }
1992 };
1993
1994 Ok(Some(source))
1995 }
1996
1997 pub fn marker(&self) -> MarkerTree {
1999 match self {
2000 Self::Git { marker, .. } => *marker,
2001 Self::Url { marker, .. } => *marker,
2002 Self::Path { marker, .. } => *marker,
2003 Self::Registry { marker, .. } => *marker,
2004 Self::Workspace { marker, .. } => *marker,
2005 }
2006 }
2007
2008 pub fn extra(&self) -> Option<&ExtraName> {
2010 match self {
2011 Self::Git { extra, .. } => extra.as_ref(),
2012 Self::Url { extra, .. } => extra.as_ref(),
2013 Self::Path { extra, .. } => extra.as_ref(),
2014 Self::Registry { extra, .. } => extra.as_ref(),
2015 Self::Workspace { extra, .. } => extra.as_ref(),
2016 }
2017 }
2018
2019 pub fn group(&self) -> Option<&GroupName> {
2021 match self {
2022 Self::Git { group, .. } => group.as_ref(),
2023 Self::Url { group, .. } => group.as_ref(),
2024 Self::Path { group, .. } => group.as_ref(),
2025 Self::Registry { group, .. } => group.as_ref(),
2026 Self::Workspace { group, .. } => group.as_ref(),
2027 }
2028 }
2029}
2030
2031#[derive(Debug, Clone, PartialEq, Eq)]
2033pub enum DependencyType {
2034 Production,
2036 Dev,
2038 Optional(ExtraName),
2040 Group(GroupName),
2042}
2043
2044impl DependencyType {
2045 pub fn toml_table_name(&self) -> Cow<'_, str> {
2047 match self {
2048 Self::Production => Cow::Borrowed("`project.dependencies`"),
2049 Self::Dev => {
2050 Cow::Borrowed("`tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`")
2051 }
2052 Self::Optional(extra) => Cow::Owned(format!("`project.optional-dependencies.{extra}`")),
2053 Self::Group(group) => Cow::Owned(format!("`dependency-groups.{group}`")),
2054 }
2055 }
2056}
2057
2058#[derive(Debug, Clone, PartialEq, Eq)]
2059#[cfg_attr(test, derive(Serialize))]
2060pub(crate) struct BuildBackendSettingsSchema;
2061
2062impl<'de> Deserialize<'de> for BuildBackendSettingsSchema {
2063 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
2064 where
2065 D: Deserializer<'de>,
2066 {
2067 Ok(Self)
2068 }
2069}
2070
2071#[cfg(feature = "schemars")]
2072impl schemars::JsonSchema for BuildBackendSettingsSchema {
2073 fn schema_name() -> Cow<'static, str> {
2074 BuildBackendSettings::schema_name()
2075 }
2076
2077 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2078 BuildBackendSettings::json_schema(generator)
2079 }
2080}
2081
2082impl OptionsMetadata for BuildBackendSettingsSchema {
2083 fn record(visit: &mut dyn Visit) {
2084 BuildBackendSettings::record(visit);
2085 }
2086
2087 fn documentation() -> Option<&'static str> {
2088 BuildBackendSettings::documentation()
2089 }
2090
2091 fn metadata() -> OptionSet
2092 where
2093 Self: Sized + 'static,
2094 {
2095 BuildBackendSettings::metadata()
2096 }
2097}