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