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