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::{Deserialize, Deserializer, Serialize};
19use thiserror::Error;
20use tracing::instrument;
21use uv_build_backend::BuildBackendSettings;
22use uv_configuration::{ExcludeDependency, GitLfsSetting, Override};
23use uv_distribution_types::{
24 Index, IndexName, MinimumLibcVersion, NameRequirementSpecification, RequirementSource,
25};
26use uv_fs::{PortablePathBuf, try_relative_to_if};
27use uv_macros::{DeserializeUntagged, OptionsMetadata};
28use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, ExtraName, GroupName, PackageName};
29use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
30use uv_pep440::{Version, VersionSpecifiers};
31use uv_pep508::MarkerTree;
32use uv_pypi_types::{
33 ConflictError, Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments,
34 VerbatimParsedUrl,
35};
36use uv_redacted::SafeUrl;
37use uv_redacted::policy::Raw;
38use uv_toml::deserialize_unique_map;
39
40use crate::DefaultGroupsError;
41
42#[derive(Error, Debug)]
43pub enum PyprojectTomlError {
44 #[error(transparent)]
45 Toml(#[from] toml::de::Error),
46 #[error("Failed to parse `tool.uv.sources`")]
47 Source(
48 #[from]
49 #[source]
50 SourceError,
51 ),
52 #[error(
53 "`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
54 )]
55 MissingName,
56 #[error(
57 "`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
58 )]
59 MissingVersion,
60}
61
62fn deserialize_optional_dependencies<'de, D, V>(
63 deserializer: D,
64) -> Result<Option<BTreeMap<ExtraName, V>>, D::Error>
65where
66 D: Deserializer<'de>,
67 V: Deserialize<'de>,
68{
69 deserialize_unique_map(deserializer, |key: &ExtraName| {
70 format!("duplicate normalized extra name `{key}`")
71 })
72 .map(Some)
73}
74
75#[derive(Deserialize, Debug, Clone)]
77#[cfg_attr(test, derive(Serialize))]
78#[serde(rename_all = "kebab-case")]
79pub struct PyProjectToml {
80 pub project: Option<Project>,
82 pub tool: Option<Tool>,
84 pub dependency_groups: Option<DependencyGroups>,
86 #[serde(skip)]
88 pub raw: String,
89
90 #[serde(default, skip_serializing)]
92 build_system: Option<serde::de::IgnoredAny>,
93}
94
95impl PyProjectToml {
96 pub fn is_workspace_root(&self) -> bool {
98 self.tool
99 .as_ref()
100 .and_then(|tool| tool.uv.as_ref())
101 .is_some_and(|uv| uv.workspace.is_some())
102 }
103
104 pub fn configured_default_groups(&self) -> Option<&DefaultGroups> {
108 self.tool
109 .as_ref()
110 .and_then(|tool| tool.uv.as_ref())
111 .and_then(|uv| uv.default_groups.as_ref())
112 }
113
114 pub(crate) fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
116 if let Some(defaults) = self.configured_default_groups() {
117 if let DefaultGroups::List(defaults) = defaults {
118 for group in defaults {
119 if !self
120 .dependency_groups
121 .as_ref()
122 .is_some_and(|groups| groups.contains_key(group))
123 {
124 return Err(DefaultGroupsError::MissingGroup(group.clone()));
125 }
126 }
127 }
128 Ok(defaults.clone())
129 } else {
130 Ok(DefaultGroups::from_groups(vec![DEV_DEPENDENCIES.clone()]))
131 }
132 }
133
134 #[instrument("toml::from_str workspace", skip_all, fields(path = %_path.as_ref().display()))]
136 pub fn from_string(raw: String, _path: impl AsRef<Path>) -> Result<Self, PyprojectTomlError> {
137 let pyproject: Self = match toml::from_str(&raw) {
138 Ok(pyproject) => pyproject,
139 Err(error) => {
140 let sources = toml::from_str::<PyProjectTomlSourcesWire>(&raw)
142 .map_err(PyprojectTomlError::Toml)?
143 .tool
144 .and_then(|tool| tool.uv)
145 .and_then(|uv| uv.sources);
146 if let Some(sources) = sources {
147 ToolUvSources::try_from(sources)?;
148 }
149 return Err(PyprojectTomlError::Toml(error));
150 }
151 };
152
153 Ok(Self { raw, ..pyproject })
154 }
155
156 pub fn is_package(&self, require_build_system: bool) -> bool {
159 if let Some(is_package) = self.tool_uv_package() {
161 return is_package;
162 }
163
164 self.build_system.is_some() || !require_build_system
166 }
167
168 fn tool_uv_package(&self) -> Option<bool> {
170 self.tool
171 .as_ref()
172 .and_then(|tool| tool.uv.as_ref())
173 .and_then(|uv| uv.package)
174 }
175
176 pub fn has_scripts(&self) -> bool {
178 if let Some(ref project) = self.project {
179 project.gui_scripts.is_some() || project.scripts.is_some()
180 } else {
181 false
182 }
183 }
184
185 pub(crate) fn conflicts(&self) -> Result<Conflicts, ConflictError> {
187 let empty = Conflicts::empty();
188 let Some(project) = self.project.as_ref() else {
189 return Ok(empty);
190 };
191 let Some(tool) = self.tool.as_ref() else {
192 return Ok(empty);
193 };
194 let Some(tooluv) = tool.uv.as_ref() else {
195 return Ok(empty);
196 };
197 let Some(conflicting) = tooluv.conflicts.as_ref() else {
198 return Ok(empty);
199 };
200 conflicting.to_conflicts_with_package_name(&project.name)
201 }
202}
203
204impl PartialEq for PyProjectToml {
206 fn eq(&self, other: &Self) -> bool {
207 self.project.eq(&other.project) && self.tool.eq(&other.tool)
208 }
209}
210
211impl Eq for PyProjectToml {}
212
213impl AsRef<[u8]> for PyProjectToml {
214 fn as_ref(&self) -> &[u8] {
215 self.raw.as_bytes()
216 }
217}
218
219#[derive(Deserialize, Debug, Clone, PartialEq)]
223#[cfg_attr(test, derive(Serialize))]
224#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
225pub struct Project {
226 pub name: PackageName,
228 version: Option<Version>,
230 pub(crate) requires_python: Option<VersionSpecifiers>,
232 pub dependencies: Option<Vec<String>>,
234 pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
236
237 #[serde(default, skip_serializing)]
239 gui_scripts: Option<serde::de::IgnoredAny>,
240 #[serde(default, skip_serializing)]
242 scripts: Option<serde::de::IgnoredAny>,
243}
244
245#[derive(Deserialize, Debug)]
246#[serde(rename_all = "kebab-case")]
247struct ProjectWire {
248 name: Option<PackageName>,
249 version: Option<Version>,
250 dynamic: Option<Vec<String>>,
251 requires_python: Option<VersionSpecifiers>,
252 dependencies: Option<Vec<String>>,
253 #[serde(default, deserialize_with = "deserialize_optional_dependencies")]
254 optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
255 gui_scripts: Option<serde::de::IgnoredAny>,
256 scripts: Option<serde::de::IgnoredAny>,
257}
258
259impl TryFrom<ProjectWire> for Project {
260 type Error = PyprojectTomlError;
261
262 fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
263 let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
265
266 if value.version.is_none()
268 && !value
269 .dynamic
270 .as_ref()
271 .is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
272 {
273 return Err(PyprojectTomlError::MissingVersion);
274 }
275
276 Ok(Self {
277 name,
278 version: value.version,
279 requires_python: value.requires_python,
280 dependencies: value.dependencies,
281 optional_dependencies: value.optional_dependencies,
282 gui_scripts: value.gui_scripts,
283 scripts: value.scripts,
284 })
285 }
286}
287
288#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
289#[cfg_attr(test, derive(Serialize))]
290#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
291pub struct Tool {
292 pub uv: Option<Box<ToolUv>>,
293}
294
295fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
301where
302 D: Deserializer<'de>,
303{
304 let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
305 if let Some(indexes) = indexes.as_ref() {
306 let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
307 let mut seen_default = false;
308 for index in indexes {
309 if let Some(name) = index.name.as_ref() {
310 if !seen_names.insert(name) {
311 return Err(serde::de::Error::custom(format!(
312 "duplicate index name `{name}`"
313 )));
314 }
315 }
316 if index.default {
317 if seen_default {
318 return Err(serde::de::Error::custom(
319 "found multiple indexes with `default = true`; only one index may be marked as default",
320 ));
321 }
322 seen_default = true;
323 }
324 }
325 }
326 Ok(indexes)
327}
328
329pub type OverrideDependency = Override<uv_pep508::Requirement<VerbatimParsedUrl>>;
331
332#[derive(Debug, Clone, PartialEq, Eq, Serialize, DeserializeUntagged)]
334#[serde(
335 untagged,
336 expecting = "a requirement string or a table with requirement and hashes"
337)]
338#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
339pub enum BuildConstraintDependency {
340 #[untagged(string)]
342 Requirement(uv_pep508::Requirement<VerbatimParsedUrl>),
343 WithHashes {
345 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
346 hashes: Vec<String>,
347 },
348}
349
350impl BuildConstraintDependency {
351 pub fn into_parts(self) -> (uv_pep508::Requirement<VerbatimParsedUrl>, Vec<String>) {
353 match self {
354 Self::Requirement(requirement) => (requirement, Vec::new()),
355 Self::WithHashes {
356 requirement,
357 hashes,
358 } => (requirement, hashes),
359 }
360 }
361}
362
363impl From<BuildConstraintDependency> for NameRequirementSpecification {
364 fn from(value: BuildConstraintDependency) -> Self {
365 let (requirement, hashes) = value.into_parts();
366 Self {
367 requirement: requirement.into(),
368 hashes,
369 }
370 }
371}
372
373#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
376#[cfg_attr(test, derive(Serialize))]
377#[serde(rename_all = "kebab-case")]
378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
379pub struct ToolUv {
380 #[option(
388 default = "{}",
389 value_type = "dict",
390 example = r#"
391 [tool.uv.sources]
392 httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
393 pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
394 pydantic = { path = "/path/to/pydantic", editable = true }
395 "#
396 )]
397 pub sources: Option<ToolUvSources>,
398
399 #[option(
427 default = "[]",
428 value_type = "dict",
429 example = r#"
430 [[tool.uv.index]]
431 name = "pytorch"
432 url = "https://download.pytorch.org/whl/cu130"
433 "#
434 )]
435 #[serde(deserialize_with = "deserialize_index_vec", default)]
436 pub index: Option<Vec<Index>>,
437
438 #[option_group]
440 pub(crate) workspace: Option<ToolUvWorkspace>,
441
442 #[option(
445 default = r#"true"#,
446 value_type = "bool",
447 example = r#"
448 managed = false
449 "#
450 )]
451 pub(crate) managed: Option<bool>,
452
453 #[option(
464 default = r#"true"#,
465 value_type = "bool",
466 example = r#"
467 package = false
468 "#
469 )]
470 package: Option<bool>,
471
472 #[option(
476 default = r#"["dev"]"#,
477 value_type = r#"str | list[str]"#,
478 example = r#"
479 default-groups = ["docs"]
480 "#
481 )]
482 default_groups: Option<DefaultGroups>,
483
484 #[option(
493 default = "[]",
494 value_type = "dict",
495 example = r#"
496 [tool.uv.dependency-groups]
497 my-group = {requires-python = ">=3.12"}
498 "#
499 )]
500 pub(crate) dependency_groups: Option<ToolUvDependencyGroups>,
501
502 #[cfg_attr(
512 feature = "schemars",
513 schemars(
514 with = "Option<Vec<String>>",
515 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
516 )
517 )]
518 #[option(
519 default = "[]",
520 value_type = "list[str]",
521 example = r#"
522 dev-dependencies = ["ruff==0.5.0"]
523 "#
524 )]
525 pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
526
527 #[option(
556 default = "[]",
557 value_type = "list[str | dict]",
558 example = r#"
559 override-dependencies = [
560 # Always install Werkzeug 2.3.0.
561 "werkzeug==2.3.0",
562 # Use itsdangerous 2.1.2 when requested by Flask 3.0.0.
563 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous==2.1.2"] },
564 ]
565 "#
566 )]
567 pub(crate) override_dependencies: Option<Vec<OverrideDependency>>,
568
569 #[option(
590 default = "[]",
591 value_type = "list[str | dict]",
592 example = r#"
593 # Exclude Werkzeug from being installed, even if transitive dependencies request it.
594 exclude-dependencies = [
595 "werkzeug",
596 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous"] },
597 ]
598 "#
599 )]
600 pub(crate) exclude_dependencies: Option<Vec<ExcludeDependency>>,
601
602 #[cfg_attr(
616 feature = "schemars",
617 schemars(
618 with = "Option<Vec<String>>",
619 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
620 )
621 )]
622 #[option(
623 default = "[]",
624 value_type = "list[str]",
625 example = r#"
626 # Ensure that the grpcio version is always less than 1.65, if it's requested by a
627 # direct or transitive dependency.
628 constraint-dependencies = ["grpcio<1.65"]
629 "#
630 )]
631 pub(crate) constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
632
633 #[option(
650 default = "[]",
651 value_type = "list[str | dict]",
652 example = r#"
653 # Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
654 # on setuptools.
655 build-constraint-dependencies = ["setuptools==60.0.0"]
656 "#
657 )]
658 pub(crate) build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
659
660 #[cfg_attr(
669 feature = "schemars",
670 schemars(
671 with = "Option<Vec<String>>",
672 description = "A list of environment markers, e.g., `python_version >= '3.6'`."
673 )
674 )]
675 #[option(
676 default = "[]",
677 value_type = "str | list[str]",
678 example = r#"
679 # Resolve for macOS, but not for Linux or Windows.
680 environments = ["sys_platform == 'darwin'"]
681 "#
682 )]
683 pub(crate) environments: Option<SupportedEnvironments>,
684
685 #[cfg_attr(
705 feature = "schemars",
706 schemars(
707 with = "Option<Vec<String>>",
708 description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
709 )
710 )]
711 #[option(
712 default = "[]",
713 value_type = "str | list[str]",
714 example = r#"
715 # Require that the package is available on the following platforms:
716 required-environments = [
717 # macOS on Apple Silicon (ARM)
718 "sys_platform == 'darwin' and platform_machine == 'arm64'",
719 # Linux on x86_64 (Intel/AMD)
720 "sys_platform == 'linux' and platform_machine == 'x86_64'",
721 # Windows on x86_64 (Intel/AMD)
722 "sys_platform == 'win32' and platform_machine == 'AMD64'",
723 ]
724 "#
725 )]
726 pub(crate) required_environments: Option<SupportedEnvironments>,
727
728 #[option(
746 default = "None",
747 value_type = "dict[str, str]",
748 example = r#"
749 preview-features = ["minimum-libc-version"]
750 required-environments = [
751 "sys_platform == 'linux' and platform_machine == 'x86_64'",
752 "sys_platform == 'linux' and platform_machine == 'aarch64'",
753 ]
754 minimum-libc-version = { glibc = "2.31" }
755 "#
756 )]
757 pub(crate) minimum_libc_version: Option<MinimumLibcVersion>,
758
759 #[cfg_attr(
774 feature = "schemars",
775 schemars(description = "A list of sets of conflicting groups or extras.")
776 )]
777 #[option(
778 default = r#"[]"#,
779 value_type = "list[list[dict]]",
780 example = r#"
781 # Require that `package[extra1]` and `package[extra2]` are resolved
782 # in different forks so that they cannot conflict with one another.
783 conflicts = [
784 [
785 { extra = "extra1" },
786 { extra = "extra2" },
787 ]
788 ]
789
790 # Require that the dependency groups `group1` and `group2`
791 # are resolved in different forks so that they cannot conflict
792 # with one another.
793 conflicts = [
794 [
795 { group = "group1" },
796 { group = "group2" },
797 ]
798 ]
799 "#
800 )]
801 pub(crate) conflicts: Option<SchemaConflicts>,
802
803 #[option_group]
810 build_backend: Option<BuildBackendSettingsSchema>,
811}
812
813#[derive(Default, Debug, Clone, PartialEq, Eq)]
814#[cfg_attr(test, derive(Serialize))]
815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
816pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
817
818#[derive(Deserialize, Debug)]
819#[serde(rename_all = "kebab-case")]
820struct PyProjectTomlSourcesWire {
821 tool: Option<ToolSourcesWire>,
822}
823
824#[derive(Deserialize, Debug)]
825struct ToolSourcesWire {
826 uv: Option<ToolUvSourcesOnlyWire>,
827}
828
829#[derive(Deserialize, Debug)]
830#[serde(rename_all = "kebab-case")]
831struct ToolUvSourcesOnlyWire {
832 sources: Option<ToolUvSourcesWire>,
833}
834
835#[derive(Default, Debug, Clone, PartialEq, Eq)]
836struct ToolUvSourcesWire(BTreeMap<PackageName, SourcesWire>);
837
838impl ToolUvSources {
839 pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
841 &self.0
842 }
843
844 #[must_use]
846 pub(crate) fn into_inner(self) -> BTreeMap<PackageName, Sources> {
847 self.0
848 }
849}
850
851impl TryFrom<ToolUvSourcesWire> for ToolUvSources {
852 type Error = SourceError;
853
854 fn try_from(wire: ToolUvSourcesWire) -> Result<Self, Self::Error> {
855 wire.0
856 .into_iter()
857 .map(|(name, sources)| Sources::try_from(sources).map(|sources| (name, sources)))
858 .collect::<Result<BTreeMap<_, _>, _>>()
859 .map(Self)
860 }
861}
862
863impl<'de> serde::de::Deserialize<'de> for ToolUvSourcesWire {
865 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
866 where
867 D: Deserializer<'de>,
868 {
869 deserialize_unique_map(deserializer, |key: &PackageName| {
870 format!("duplicate sources for package `{key}`")
871 })
872 .map(ToolUvSourcesWire)
873 }
874}
875
876impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
878 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
879 where
880 D: Deserializer<'de>,
881 {
882 deserialize_unique_map(deserializer, |key: &PackageName| {
883 format!("duplicate sources for package `{key}`")
884 })
885 .map(ToolUvSources)
886 }
887}
888
889#[derive(Default, Debug, Clone, PartialEq, Eq)]
890#[cfg_attr(test, derive(Serialize))]
891#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
892pub(crate) struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
893
894impl ToolUvDependencyGroups {
895 pub(crate) fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
897 &self.0
898 }
899}
900
901impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
903 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
904 where
905 D: Deserializer<'de>,
906 {
907 deserialize_unique_map(deserializer, |key: &GroupName| {
908 format!("duplicate settings for dependency group `{key}`")
909 })
910 .map(ToolUvDependencyGroups)
911 }
912}
913
914#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
915#[cfg_attr(test, derive(Serialize))]
916#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
917#[serde(rename_all = "kebab-case")]
918pub(crate) struct DependencyGroupSettings {
919 #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
921 pub(crate) requires_python: Option<VersionSpecifiers>,
922}
923
924#[derive(Debug, Clone, PartialEq, Eq, Serialize, DeserializeUntagged)]
925#[serde(
926 untagged,
927 expecting = "a requirement string or a table with requirement and match-runtime"
928)]
929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
930enum ExtraBuildDependencyWire {
931 #[untagged(string)]
932 Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
933 #[serde(rename_all = "kebab-case")]
934 Annotated {
935 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
936 match_runtime: bool,
937 },
938}
939
940#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
941#[serde(
942 deny_unknown_fields,
943 from = "ExtraBuildDependencyWire",
944 into = "ExtraBuildDependencyWire"
945)]
946#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
947pub struct ExtraBuildDependency {
948 pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
949 pub match_runtime: bool,
950}
951
952impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
953 fn from(value: ExtraBuildDependency) -> Self {
954 value.requirement
955 }
956}
957
958impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
959 fn from(wire: ExtraBuildDependencyWire) -> Self {
960 match wire {
961 ExtraBuildDependencyWire::Unannotated(requirement) => Self {
962 requirement,
963 match_runtime: false,
964 },
965 ExtraBuildDependencyWire::Annotated {
966 requirement,
967 match_runtime,
968 } => Self {
969 requirement,
970 match_runtime,
971 },
972 }
973 }
974}
975
976impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
977 fn from(item: ExtraBuildDependency) -> Self {
978 Self::Annotated {
979 requirement: item.requirement,
980 match_runtime: item.match_runtime,
981 }
982 }
983}
984
985#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
986#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
987pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
988
989impl std::ops::Deref for ExtraBuildDependencies {
990 type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
991
992 fn deref(&self) -> &Self::Target {
993 &self.0
994 }
995}
996
997impl std::ops::DerefMut for ExtraBuildDependencies {
998 fn deref_mut(&mut self) -> &mut Self::Target {
999 &mut self.0
1000 }
1001}
1002
1003impl IntoIterator for ExtraBuildDependencies {
1004 type Item = (PackageName, Vec<ExtraBuildDependency>);
1005 type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
1006
1007 fn into_iter(self) -> Self::IntoIter {
1008 self.0.into_iter()
1009 }
1010}
1011
1012impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
1013 fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
1014 iter: T,
1015 ) -> Self {
1016 Self(iter.into_iter().collect())
1017 }
1018}
1019
1020impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
1022 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1023 where
1024 D: Deserializer<'de>,
1025 {
1026 deserialize_unique_map(deserializer, |key: &PackageName| {
1027 format!("duplicate extra-build-dependencies for `{key}`")
1028 })
1029 .map(ExtraBuildDependencies)
1030 }
1031}
1032
1033#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
1034#[cfg_attr(test, derive(Serialize))]
1035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1036#[serde(rename_all = "kebab-case", deny_unknown_fields)]
1037pub(crate) struct ToolUvWorkspace {
1038 #[option(
1044 default = "[]",
1045 value_type = "list[str]",
1046 example = r#"
1047 members = ["member1", "path/to/member2", "libs/*"]
1048 "#
1049 )]
1050 pub(crate) members: Option<Vec<SerdePattern>>,
1051 #[option(
1058 default = "[]",
1059 value_type = "list[str]",
1060 example = r#"
1061 exclude = ["member1", "path/to/member2", "libs/*"]
1062 "#
1063 )]
1064 pub(crate) exclude: Option<Vec<SerdePattern>>,
1065}
1066
1067#[derive(Debug, Clone, PartialEq, Eq)]
1069pub(crate) struct SerdePattern(Pattern);
1070
1071impl serde::ser::Serialize for SerdePattern {
1072 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1073 where
1074 S: serde::ser::Serializer,
1075 {
1076 self.0.as_str().serialize(serializer)
1077 }
1078}
1079
1080impl<'de> serde::Deserialize<'de> for SerdePattern {
1081 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1082 struct Visitor;
1083
1084 impl serde::de::Visitor<'_> for Visitor {
1085 type Value = SerdePattern;
1086
1087 fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1088 f.write_str("a string")
1089 }
1090
1091 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
1092 Pattern::from_str(v)
1093 .map(SerdePattern)
1094 .map_err(serde::de::Error::custom)
1095 }
1096 }
1097
1098 deserializer.deserialize_str(Visitor)
1099 }
1100}
1101
1102#[cfg(feature = "schemars")]
1103impl schemars::JsonSchema for SerdePattern {
1104 fn schema_name() -> Cow<'static, str> {
1105 Cow::Borrowed("SerdePattern")
1106 }
1107
1108 fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
1109 <String as schemars::JsonSchema>::json_schema(generator)
1110 }
1111}
1112
1113impl Deref for SerdePattern {
1114 type Target = Pattern;
1115
1116 fn deref(&self) -> &Self::Target {
1117 &self.0
1118 }
1119}
1120
1121#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1123#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
1124pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
1125
1126impl Sources {
1127 pub fn iter(&self) -> impl Iterator<Item = &Source> {
1133 self.0.iter()
1134 }
1135}
1136
1137impl FromIterator<Source> for Sources {
1138 fn from_iter<T: IntoIterator<Item = Source>>(iter: T) -> Self {
1139 Self(iter.into_iter().collect())
1140 }
1141}
1142
1143impl IntoIterator for Sources {
1144 type Item = Source;
1145 type IntoIter = std::vec::IntoIter<Source>;
1146
1147 fn into_iter(self) -> Self::IntoIter {
1148 self.0.into_iter()
1149 }
1150}
1151
1152#[derive(Debug, Clone, PartialEq, Eq, DeserializeUntagged)]
1153#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1154#[serde(expecting = "a single source (as a map) or list of sources")]
1155enum SourcesWire {
1156 #[untagged(map)]
1157 One(Source),
1158 #[untagged(seq)]
1159 Many(Vec<Source>),
1160}
1161
1162impl TryFrom<SourcesWire> for Sources {
1163 type Error = SourceError;
1164
1165 fn try_from(wire: SourcesWire) -> Result<Self, Self::Error> {
1166 match wire {
1167 SourcesWire::One(source) => Ok(Self(vec![source])),
1168 SourcesWire::Many(sources) => {
1169 for [lhs, rhs] in sources.array_windows() {
1170 if lhs.extra() != rhs.extra() {
1171 continue;
1172 }
1173 if lhs.group() != rhs.group() {
1174 continue;
1175 }
1176
1177 let lhs = lhs.marker();
1178 let rhs = rhs.marker();
1179 if !lhs.is_disjoint(rhs) {
1180 let Some(left) = lhs.contents().map(|contents| contents.to_string()) else {
1181 return Err(SourceError::MissingMarkers);
1182 };
1183
1184 let Some(right) = rhs.contents().map(|contents| contents.to_string())
1185 else {
1186 return Err(SourceError::MissingMarkers);
1187 };
1188
1189 let hint = lhs.negate().and(rhs);
1190 let hint = hint
1191 .contents()
1192 .map(|contents| contents.to_string())
1193 .unwrap_or_else(|| "true".to_string());
1194
1195 return Err(SourceError::OverlappingMarkers(left, right, hint));
1196 }
1197 }
1198
1199 if sources.is_empty() {
1201 return Err(SourceError::EmptySources);
1202 }
1203
1204 Ok(Self(sources))
1205 }
1206 }
1207 }
1208}
1209
1210#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
1212#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1213#[serde(rename_all = "kebab-case", untagged, deny_unknown_fields)]
1214pub enum Source {
1215 Git {
1222 git: SafeUrl<Raw>,
1224 subdirectory: Option<PortablePathBuf>,
1226 path: Option<PortablePathBuf>,
1228 rev: Option<String>,
1230 tag: Option<String>,
1231 branch: Option<String>,
1232 lfs: Option<bool>,
1234 #[serde(
1235 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1236 serialize_with = "uv_pep508::marker::ser::serialize",
1237 default
1238 )]
1239 marker: MarkerTree,
1240 extra: Option<ExtraName>,
1241 group: Option<GroupName>,
1242 },
1243 Url {
1251 url: SafeUrl<Raw>,
1252 subdirectory: Option<PortablePathBuf>,
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 Path {
1268 path: PortablePathBuf,
1269 editable: Option<bool>,
1271 package: Option<bool>,
1278 #[serde(
1279 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1280 serialize_with = "uv_pep508::marker::ser::serialize",
1281 default
1282 )]
1283 marker: MarkerTree,
1284 extra: Option<ExtraName>,
1285 group: Option<GroupName>,
1286 },
1287 Registry {
1289 index: IndexName,
1290 #[serde(
1291 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1292 serialize_with = "uv_pep508::marker::ser::serialize",
1293 default
1294 )]
1295 marker: MarkerTree,
1296 extra: Option<ExtraName>,
1297 group: Option<GroupName>,
1298 },
1299 Workspace {
1301 workspace: WorkspaceReference,
1307 editable: Option<bool>,
1309 #[serde(
1310 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1311 serialize_with = "uv_pep508::marker::ser::serialize",
1312 default
1313 )]
1314 marker: MarkerTree,
1315 extra: Option<ExtraName>,
1316 group: Option<GroupName>,
1317 },
1318}
1319
1320#[derive(Serialize, DeserializeUntagged, Debug, Clone, PartialEq, Eq)]
1322#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1323#[serde(untagged)]
1324pub enum WorkspaceReference {
1325 #[untagged(bool)]
1326 Bool(bool),
1327 #[untagged(string)]
1328 Path(PortablePathBuf),
1329}
1330
1331impl<'de> Deserialize<'de> for Source {
1334 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1335 where
1336 D: Deserializer<'de>,
1337 {
1338 #[derive(Deserialize, Debug, Clone)]
1339 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
1340 struct CatchAll {
1341 git: Option<SafeUrl>,
1342 subdirectory: Option<PortablePathBuf>,
1343 rev: Option<String>,
1344 tag: Option<String>,
1345 branch: Option<String>,
1346 lfs: Option<bool>,
1347 url: Option<SafeUrl>,
1348 path: Option<PortablePathBuf>,
1349 editable: Option<bool>,
1350 package: Option<bool>,
1351 index: Option<IndexName>,
1352 workspace: Option<WorkspaceReference>,
1353 #[serde(
1354 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1355 serialize_with = "uv_pep508::marker::ser::serialize",
1356 default
1357 )]
1358 marker: MarkerTree,
1359 extra: Option<ExtraName>,
1360 group: Option<GroupName>,
1361 }
1362
1363 let CatchAll {
1365 git,
1366 subdirectory,
1367 rev,
1368 tag,
1369 branch,
1370 lfs,
1371 url,
1372 path,
1373 editable,
1374 package,
1375 index,
1376 workspace,
1377 marker,
1378 extra,
1379 group,
1380 } = CatchAll::deserialize(deserializer)?;
1381
1382 if extra.is_some() && group.is_some() {
1384 return Err(serde::de::Error::custom(
1385 "cannot specify both `extra` and `group`",
1386 ));
1387 }
1388
1389 if let Some(git) = git {
1391 if index.is_some() {
1392 return Err(serde::de::Error::custom(
1393 "cannot specify both `git` and `index`",
1394 ));
1395 }
1396 if workspace.is_some() {
1397 return Err(serde::de::Error::custom(
1398 "cannot specify both `git` and `workspace`",
1399 ));
1400 }
1401 if url.is_some() {
1402 return Err(serde::de::Error::custom(
1403 "cannot specify both `git` and `url`",
1404 ));
1405 }
1406 if editable.is_some() {
1407 return Err(serde::de::Error::custom(
1408 "cannot specify both `git` and `editable`",
1409 ));
1410 }
1411 if package.is_some() {
1412 return Err(serde::de::Error::custom(
1413 "cannot specify both `git` and `package`",
1414 ));
1415 }
1416 if subdirectory.is_some() && path.is_some() {
1417 return Err(serde::de::Error::custom(
1418 "cannot specify both `subdirectory` and `path`",
1419 ));
1420 }
1421
1422 match (rev.as_ref(), tag.as_ref(), branch.as_ref()) {
1424 (None, None, None) => {}
1425 (Some(_), None, None) => {}
1426 (None, Some(_), None) => {}
1427 (None, None, Some(_)) => {}
1428 _ => {
1429 return Err(serde::de::Error::custom(
1430 "expected at most one of `rev`, `tag`, or `branch`",
1431 ));
1432 }
1433 }
1434
1435 let git = if let Some(git) = git.as_str().strip_prefix("git+") {
1437 SafeUrl::parse(git).map_err(serde::de::Error::custom)?
1438 } else {
1439 git
1440 };
1441
1442 return Ok(Self::Git {
1443 git: git.with_policy(Raw),
1444 subdirectory,
1445 path,
1446 rev,
1447 tag,
1448 branch,
1449 lfs,
1450 marker,
1451 extra,
1452 group,
1453 });
1454 }
1455
1456 if let Some(url) = url {
1458 if index.is_some() {
1459 return Err(serde::de::Error::custom(
1460 "cannot specify both `url` and `index`",
1461 ));
1462 }
1463 if workspace.is_some() {
1464 return Err(serde::de::Error::custom(
1465 "cannot specify both `url` and `workspace`",
1466 ));
1467 }
1468 if path.is_some() {
1469 return Err(serde::de::Error::custom(
1470 "cannot specify both `url` and `path`",
1471 ));
1472 }
1473 if git.is_some() {
1474 return Err(serde::de::Error::custom(
1475 "cannot specify both `url` and `git`",
1476 ));
1477 }
1478 if rev.is_some() {
1479 return Err(serde::de::Error::custom(
1480 "cannot specify both `url` and `rev`",
1481 ));
1482 }
1483 if tag.is_some() {
1484 return Err(serde::de::Error::custom(
1485 "cannot specify both `url` and `tag`",
1486 ));
1487 }
1488 if branch.is_some() {
1489 return Err(serde::de::Error::custom(
1490 "cannot specify both `url` and `branch`",
1491 ));
1492 }
1493 if editable.is_some() {
1494 return Err(serde::de::Error::custom(
1495 "cannot specify both `url` and `editable`",
1496 ));
1497 }
1498 if package.is_some() {
1499 return Err(serde::de::Error::custom(
1500 "cannot specify both `url` and `package`",
1501 ));
1502 }
1503
1504 return Ok(Self::Url {
1505 url: url.with_policy(Raw),
1506 subdirectory,
1507 marker,
1508 extra,
1509 group,
1510 });
1511 }
1512
1513 if let Some(path) = path {
1515 if index.is_some() {
1516 return Err(serde::de::Error::custom(
1517 "cannot specify both `path` and `index`",
1518 ));
1519 }
1520 if workspace.is_some() {
1521 return Err(serde::de::Error::custom(
1522 "cannot specify both `path` and `workspace`",
1523 ));
1524 }
1525 if git.is_some() {
1526 return Err(serde::de::Error::custom(
1527 "cannot specify both `path` and `git`",
1528 ));
1529 }
1530 if url.is_some() {
1531 return Err(serde::de::Error::custom(
1532 "cannot specify both `path` and `url`",
1533 ));
1534 }
1535 if rev.is_some() {
1536 return Err(serde::de::Error::custom(
1537 "cannot specify both `path` and `rev`",
1538 ));
1539 }
1540 if tag.is_some() {
1541 return Err(serde::de::Error::custom(
1542 "cannot specify both `path` and `tag`",
1543 ));
1544 }
1545 if branch.is_some() {
1546 return Err(serde::de::Error::custom(
1547 "cannot specify both `path` and `branch`",
1548 ));
1549 }
1550
1551 if editable == Some(true) && package == Some(false) {
1553 return Err(serde::de::Error::custom(
1554 "cannot specify both `editable = true` and `package = false`",
1555 ));
1556 }
1557
1558 return Ok(Self::Path {
1559 path,
1560 editable,
1561 package,
1562 marker,
1563 extra,
1564 group,
1565 });
1566 }
1567
1568 if let Some(index) = index {
1570 if workspace.is_some() {
1571 return Err(serde::de::Error::custom(
1572 "cannot specify both `index` and `workspace`",
1573 ));
1574 }
1575 if git.is_some() {
1576 return Err(serde::de::Error::custom(
1577 "cannot specify both `index` and `git`",
1578 ));
1579 }
1580 if url.is_some() {
1581 return Err(serde::de::Error::custom(
1582 "cannot specify both `index` and `url`",
1583 ));
1584 }
1585 if path.is_some() {
1586 return Err(serde::de::Error::custom(
1587 "cannot specify both `index` and `path`",
1588 ));
1589 }
1590 if rev.is_some() {
1591 return Err(serde::de::Error::custom(
1592 "cannot specify both `index` and `rev`",
1593 ));
1594 }
1595 if tag.is_some() {
1596 return Err(serde::de::Error::custom(
1597 "cannot specify both `index` and `tag`",
1598 ));
1599 }
1600 if branch.is_some() {
1601 return Err(serde::de::Error::custom(
1602 "cannot specify both `index` and `branch`",
1603 ));
1604 }
1605 if editable.is_some() {
1606 return Err(serde::de::Error::custom(
1607 "cannot specify both `index` and `editable`",
1608 ));
1609 }
1610 if package.is_some() {
1611 return Err(serde::de::Error::custom(
1612 "cannot specify both `index` and `package`",
1613 ));
1614 }
1615
1616 return Ok(Self::Registry {
1617 index,
1618 marker,
1619 extra,
1620 group,
1621 });
1622 }
1623
1624 if let Some(workspace) = workspace {
1626 if index.is_some() {
1627 return Err(serde::de::Error::custom(
1628 "cannot specify both `workspace` and `index`",
1629 ));
1630 }
1631 if git.is_some() {
1632 return Err(serde::de::Error::custom(
1633 "cannot specify both `workspace` and `git`",
1634 ));
1635 }
1636 if url.is_some() {
1637 return Err(serde::de::Error::custom(
1638 "cannot specify both `workspace` and `url`",
1639 ));
1640 }
1641 if path.is_some() {
1642 return Err(serde::de::Error::custom(
1643 "cannot specify both `workspace` and `path`",
1644 ));
1645 }
1646 if rev.is_some() {
1647 return Err(serde::de::Error::custom(
1648 "cannot specify both `workspace` and `rev`",
1649 ));
1650 }
1651 if tag.is_some() {
1652 return Err(serde::de::Error::custom(
1653 "cannot specify both `workspace` and `tag`",
1654 ));
1655 }
1656 if branch.is_some() {
1657 return Err(serde::de::Error::custom(
1658 "cannot specify both `workspace` and `branch`",
1659 ));
1660 }
1661 if package.is_some() {
1662 return Err(serde::de::Error::custom(
1663 "cannot specify both `workspace` and `package`",
1664 ));
1665 }
1666
1667 return Ok(Self::Workspace {
1668 workspace,
1669 editable,
1670 marker,
1671 extra,
1672 group,
1673 });
1674 }
1675
1676 Err(serde::de::Error::custom(
1678 "expected one of `git`, `url`, `path`, `index`, or `workspace`",
1679 ))
1680 }
1681}
1682
1683#[derive(Error, Debug)]
1684pub enum SourceError {
1685 #[error("Failed to resolve Git reference: `{0}`")]
1686 UnresolvedReference(String),
1687 #[error("Workspace dependency `{0}` must refer to local directory, not a Git repository")]
1688 WorkspacePackageGit(String),
1689 #[error("Workspace dependency `{0}` must refer to local directory, not a URL")]
1690 WorkspacePackageUrl(String),
1691 #[error("Workspace dependency `{0}` must refer to local directory, not a file")]
1692 WorkspacePackageFile(String),
1693 #[error(
1694 "`{0}` did not resolve to a Git repository, but a Git reference (`--rev {1}`) was provided."
1695 )]
1696 UnusedRev(String, String),
1697 #[error(
1698 "`{0}` did not resolve to a Git repository, but a Git reference (`--tag {1}`) was provided."
1699 )]
1700 UnusedTag(String, String),
1701 #[error(
1702 "`{0}` did not resolve to a Git repository, but a Git reference (`--branch {1}`) was provided."
1703 )]
1704 UnusedBranch(String, String),
1705 #[error(
1706 "`{0}` did not resolve to a Git repository, but a Git extension (`--lfs`) was provided."
1707 )]
1708 UnusedLfs(String),
1709 #[error(
1710 "`{0}` did not resolve to a local directory, but the `--editable` flag was provided. Editable installs are only supported for local directories."
1711 )]
1712 UnusedEditable(String),
1713 #[error("Failed to resolve absolute path")]
1714 Absolute(#[from] std::io::Error),
1715 #[error("Path contains invalid characters: {}", _0.display())]
1716 NonUtf8Path(PathBuf),
1717 #[error("Source markers must be disjoint, but the following markers overlap: `{0}` and `{1}`.")]
1718 OverlappingMarkers(String, String, String),
1719 #[error(
1720 "When multiple sources are provided, each source must include a platform marker (e.g., `marker = \"sys_platform == 'linux'\"`)"
1721 )]
1722 MissingMarkers,
1723 #[error("Must provide at least one source")]
1724 EmptySources,
1725}
1726
1727impl uv_errors::Hinted for SourceError {
1728 fn hints(&self) -> uv_errors::Hints<'_> {
1729 match self {
1730 Self::OverlappingMarkers(_, rhs, replacement) => {
1731 uv_errors::Hints::from(format!("replace `{rhs}` with `{replacement}`"))
1732 }
1733 _ => uv_errors::Hints::none(),
1734 }
1735 }
1736}
1737
1738impl Source {
1739 pub fn from_requirement(
1740 name: &PackageName,
1741 source: RequirementSource,
1742 workspace: bool,
1743 editable: Option<bool>,
1744 index: Option<IndexName>,
1745 rev: Option<String>,
1746 tag: Option<String>,
1747 branch: Option<String>,
1748 lfs: GitLfsSetting,
1749 root: &Path,
1750 existing_sources: Option<&BTreeMap<PackageName, Sources>>,
1751 ) -> Result<Option<Self>, SourceError> {
1752 if !matches!(
1754 source,
1755 RequirementSource::GitDirectory { .. } | RequirementSource::GitPath { .. }
1756 ) && (branch.is_some()
1757 || tag.is_some()
1758 || rev.is_some()
1759 || matches!(lfs, GitLfsSetting::Enabled { .. }))
1760 {
1761 if let Some(sources) = existing_sources
1762 && let Some(package_sources) = sources.get(name)
1763 {
1764 for existing_source in package_sources.iter() {
1765 if let Self::Git {
1766 git,
1767 subdirectory,
1768 path,
1769 marker,
1770 extra,
1771 group,
1772 ..
1773 } = existing_source
1774 {
1775 return Ok(Some(Self::Git {
1776 git: git.clone(),
1777 subdirectory: subdirectory.clone(),
1778 rev,
1779 tag,
1780 branch,
1781 lfs: lfs.into(),
1782 marker: *marker,
1783 path: path.clone(),
1784 extra: extra.clone(),
1785 group: group.clone(),
1786 }));
1787 }
1788 }
1789 }
1790 if let Some(rev) = rev {
1791 return Err(SourceError::UnusedRev(name.to_string(), rev));
1792 }
1793 if let Some(tag) = tag {
1794 return Err(SourceError::UnusedTag(name.to_string(), tag));
1795 }
1796 if let Some(branch) = branch {
1797 return Err(SourceError::UnusedBranch(name.to_string(), branch));
1798 }
1799 if matches!(lfs, GitLfsSetting::Enabled { from_env: false }) {
1800 return Err(SourceError::UnusedLfs(name.to_string()));
1801 }
1802 }
1803
1804 if !workspace {
1806 if !matches!(source, RequirementSource::Directory { .. }) {
1807 if editable == Some(true) {
1808 return Err(SourceError::UnusedEditable(name.to_string()));
1809 }
1810 }
1811 }
1812
1813 if workspace {
1815 return match source {
1816 RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => {
1817 Ok(Some(Self::Workspace {
1818 workspace: WorkspaceReference::Bool(true),
1819 editable,
1820 marker: MarkerTree::TRUE,
1821 extra: None,
1822 group: None,
1823 }))
1824 }
1825 RequirementSource::Url { .. } => {
1826 Err(SourceError::WorkspacePackageUrl(name.to_string()))
1827 }
1828 RequirementSource::GitDirectory { .. } => {
1829 Err(SourceError::WorkspacePackageGit(name.to_string()))
1830 }
1831 RequirementSource::GitPath { .. } => {
1832 Err(SourceError::WorkspacePackageGit(name.to_string()))
1833 }
1834 RequirementSource::Path { .. } => {
1835 Err(SourceError::WorkspacePackageFile(name.to_string()))
1836 }
1837 };
1838 }
1839
1840 let source = match source {
1841 RequirementSource::Registry { index: Some(_), .. } => {
1842 return Ok(None);
1843 }
1844 RequirementSource::Registry { index: None, .. } if let Some(index) = index => {
1845 Self::Registry {
1846 index,
1847 marker: MarkerTree::TRUE,
1848 extra: None,
1849 group: None,
1850 }
1851 }
1852 RequirementSource::Registry { index: None, .. } => return Ok(None),
1853 RequirementSource::Path {
1854 install_path, url, ..
1855 } => Self::Path {
1856 editable: None,
1857 package: None,
1858 path: PortablePathBuf::from(
1859 try_relative_to_if(&install_path, root, url.prefers_relative())
1860 .map_err(SourceError::Absolute)?
1861 .into_boxed_path(),
1862 ),
1863 marker: MarkerTree::TRUE,
1864 extra: None,
1865 group: None,
1866 },
1867 RequirementSource::Directory {
1868 install_path,
1869 editable: is_editable,
1870 url,
1871 ..
1872 } => Self::Path {
1873 editable: editable.or(is_editable),
1874 package: None,
1875 path: PortablePathBuf::from(
1876 try_relative_to_if(&install_path, root, url.prefers_relative())
1877 .map_err(SourceError::Absolute)?
1878 .into_boxed_path(),
1879 ),
1880 marker: MarkerTree::TRUE,
1881 extra: None,
1882 group: None,
1883 },
1884 RequirementSource::Url {
1885 location,
1886 subdirectory,
1887 ..
1888 } => Self::Url {
1889 url: location,
1890 subdirectory: subdirectory.map(PortablePathBuf::from),
1891 marker: MarkerTree::TRUE,
1892 extra: None,
1893 group: None,
1894 },
1895 RequirementSource::GitDirectory {
1896 git, subdirectory, ..
1897 } => {
1898 if rev.is_none() && tag.is_none() && branch.is_none() {
1899 let rev = git.reference().as_str().map(str::to_owned);
1900 Self::Git {
1901 rev,
1902 tag,
1903 branch,
1904 lfs: lfs.into(),
1905 git: git.url().clone().with_policy(Raw),
1906 subdirectory: subdirectory.map(PortablePathBuf::from),
1907 path: None,
1908 marker: MarkerTree::TRUE,
1909 extra: None,
1910 group: None,
1911 }
1912 } else {
1913 Self::Git {
1914 rev,
1915 tag,
1916 branch,
1917 lfs: lfs.into(),
1918 git: git.url().clone().with_policy(Raw),
1919 subdirectory: subdirectory.map(PortablePathBuf::from),
1920 path: None,
1921 marker: MarkerTree::TRUE,
1922 extra: None,
1923 group: None,
1924 }
1925 }
1926 }
1927 RequirementSource::GitPath {
1928 git, install_path, ..
1929 } => {
1930 if rev.is_none() && tag.is_none() && branch.is_none() {
1931 let rev = git.reference().as_str().map(str::to_owned);
1932 Self::Git {
1933 rev,
1934 tag,
1935 branch,
1936 lfs: lfs.into(),
1937 git: git.url().clone().with_policy(Raw),
1938 subdirectory: None,
1939 path: Some(PortablePathBuf::from(install_path.as_path())),
1940 marker: MarkerTree::TRUE,
1941 extra: None,
1942 group: None,
1943 }
1944 } else {
1945 Self::Git {
1946 rev,
1947 tag,
1948 branch,
1949 lfs: lfs.into(),
1950 git: git.url().clone().with_policy(Raw),
1951 subdirectory: None,
1952 path: Some(PortablePathBuf::from(install_path.as_path())),
1953 marker: MarkerTree::TRUE,
1954 extra: None,
1955 group: None,
1956 }
1957 }
1958 }
1959 };
1960
1961 Ok(Some(source))
1962 }
1963
1964 pub fn marker(&self) -> MarkerTree {
1966 match self {
1967 Self::Git { marker, .. } => *marker,
1968 Self::Url { marker, .. } => *marker,
1969 Self::Path { marker, .. } => *marker,
1970 Self::Registry { marker, .. } => *marker,
1971 Self::Workspace { marker, .. } => *marker,
1972 }
1973 }
1974
1975 pub fn extra(&self) -> Option<&ExtraName> {
1977 match self {
1978 Self::Git { extra, .. } => extra.as_ref(),
1979 Self::Url { extra, .. } => extra.as_ref(),
1980 Self::Path { extra, .. } => extra.as_ref(),
1981 Self::Registry { extra, .. } => extra.as_ref(),
1982 Self::Workspace { extra, .. } => extra.as_ref(),
1983 }
1984 }
1985
1986 pub fn group(&self) -> Option<&GroupName> {
1988 match self {
1989 Self::Git { group, .. } => group.as_ref(),
1990 Self::Url { group, .. } => group.as_ref(),
1991 Self::Path { group, .. } => group.as_ref(),
1992 Self::Registry { group, .. } => group.as_ref(),
1993 Self::Workspace { group, .. } => group.as_ref(),
1994 }
1995 }
1996}
1997
1998#[derive(Debug, Clone, PartialEq, Eq)]
2000pub enum DependencyType {
2001 Production,
2003 Dev,
2005 Optional(ExtraName),
2007 Group(GroupName),
2009}
2010
2011impl DependencyType {
2012 pub fn toml_table_name(&self) -> Cow<'_, str> {
2014 match self {
2015 Self::Production => Cow::Borrowed("`project.dependencies`"),
2016 Self::Dev => {
2017 Cow::Borrowed("`tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`")
2018 }
2019 Self::Optional(extra) => Cow::Owned(format!("`project.optional-dependencies.{extra}`")),
2020 Self::Group(group) => Cow::Owned(format!("`dependency-groups.{group}`")),
2021 }
2022 }
2023}
2024
2025#[derive(Debug, Clone, PartialEq, Eq)]
2026#[cfg_attr(test, derive(Serialize))]
2027pub(crate) struct BuildBackendSettingsSchema;
2028
2029impl<'de> Deserialize<'de> for BuildBackendSettingsSchema {
2030 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
2031 where
2032 D: Deserializer<'de>,
2033 {
2034 Ok(Self)
2035 }
2036}
2037
2038#[cfg(feature = "schemars")]
2039impl schemars::JsonSchema for BuildBackendSettingsSchema {
2040 fn schema_name() -> Cow<'static, str> {
2041 BuildBackendSettings::schema_name()
2042 }
2043
2044 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2045 BuildBackendSettings::json_schema(generator)
2046 }
2047}
2048
2049impl OptionsMetadata for BuildBackendSettingsSchema {
2050 fn record(visit: &mut dyn Visit) {
2051 BuildBackendSettings::record(visit);
2052 }
2053
2054 fn documentation() -> Option<&'static str> {
2055 BuildBackendSettings::documentation()
2056 }
2057
2058 fn metadata() -> OptionSet
2059 where
2060 Self: Sized + 'static,
2061 {
2062 BuildBackendSettings::metadata()
2063 }
2064}
2065
2066#[cfg(test)]
2067mod deserialization_tests {
2068 use std::io::{self, Read};
2069
2070 use serde::Deserialize;
2071
2072 use super::{BuildConstraintDependency, ExtraBuildDependency};
2073
2074 #[derive(Debug, Deserialize)]
2075 struct BuildConstraint {
2076 dependency: BuildConstraintDependency,
2077 }
2078
2079 #[derive(Debug, Deserialize)]
2080 struct ExtraBuild {
2081 dependency: ExtraBuildDependency,
2082 }
2083
2084 #[test]
2085 fn build_dependency_retains_read_errors() {
2086 struct FailedRead;
2087
2088 impl Read for FailedRead {
2089 fn read(&mut self, _buffer: &mut [u8]) -> io::Result<usize> {
2090 Err(io::Error::other("metadata read failed"))
2091 }
2092 }
2093
2094 let reader = br#"{"requirement":"setuptools","hashes":["#
2095 .as_slice()
2096 .chain(FailedRead);
2097 assert!(
2098 serde_json::from_reader::<_, BuildConstraintDependency>(reader)
2099 .unwrap_err()
2100 .is_io()
2101 );
2102 let reader = br#"{"requirement":"torch","match-runtime":"#
2103 .as_slice()
2104 .chain(FailedRead);
2105 assert!(
2106 serde_json::from_reader::<_, ExtraBuildDependency>(reader)
2107 .unwrap_err()
2108 .is_io()
2109 );
2110 }
2111
2112 #[test]
2113 fn build_constraint_representations() -> anyhow::Result<()> {
2114 let bare: BuildConstraint = toml::from_str(r#"dependency = "setuptools>=75""#)?;
2115 let annotated: BuildConstraint = toml::from_str(
2116 r#"dependency = { requirement = "setuptools>=75", hashes = ["sha256:abc"], ignored = true }"#,
2117 )?;
2118 assert!(
2119 toml::from_str::<BuildConstraint>(r#"dependency = ["setuptools>=75", ["sha256:abc"]]"#)
2120 .is_err()
2121 );
2122 let (bare_requirement, bare_hashes) = bare.dependency.into_parts();
2123 let (requirement, hashes) = annotated.dependency.into_parts();
2124 assert_eq!(bare_requirement, requirement);
2125 assert!(bare_hashes.is_empty());
2126 assert_eq!(hashes, ["sha256:abc"]);
2127 Ok(())
2128 }
2129
2130 #[test]
2131 fn extra_build_dependency_representations() -> anyhow::Result<()> {
2132 let bare: ExtraBuild = toml::from_str(r#"dependency = "torch>=2""#)?;
2133 let annotated: ExtraBuild = toml::from_str(
2134 r#"dependency = { requirement = "torch>=2", match-runtime = true, ignored = true }"#,
2135 )?;
2136 assert!(toml::from_str::<ExtraBuild>(r#"dependency = ["torch>=2", true]"#).is_err());
2137 assert_eq!(
2138 bare.dependency.requirement,
2139 annotated.dependency.requirement
2140 );
2141 assert!(!bare.dependency.match_runtime);
2142 assert!(annotated.dependency.match_runtime);
2143 Ok(())
2144 }
2145
2146 #[test]
2147 fn build_constraint_requires_hashes() {
2148 insta::assert_snapshot!(
2149 toml::from_str::<BuildConstraint>(r#"dependency = { requirement = "setuptools>=75" }"#).unwrap_err(),
2150 @r#"
2151 TOML parse error at line 1, column 14
2152 |
2153 1 | dependency = { requirement = "setuptools>=75" }
2154 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2155 missing field `hashes`
2156 "#
2157 );
2158 }
2159
2160 #[test]
2161 fn extra_build_dependency_requires_match_runtime() {
2162 insta::assert_snapshot!(
2163 toml::from_str::<ExtraBuild>(r#"dependency = { requirement = "torch>=2" }"#).unwrap_err(),
2164 @r#"
2165 TOML parse error at line 1, column 14
2166 |
2167 1 | dependency = { requirement = "torch>=2" }
2168 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2169 missing field `match-runtime`
2170 "#
2171 );
2172 }
2173}