1use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::fmt::Formatter;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14use std::str::FromStr;
15
16use glob::Pattern;
17use rustc_hash::{FxBuildHasher, FxHashSet};
18use serde::de::SeqAccess;
19use serde::{Deserialize, Deserializer, Serialize};
20use thiserror::Error;
21use tracing::instrument;
22use uv_build_backend::BuildBackendSettings;
23use uv_configuration::{ExcludeDependency, GitLfsSetting, Override};
24use uv_distribution_types::{
25 Index, IndexName, MinimumLibcVersion, NameRequirementSpecification, RequirementSource,
26};
27use uv_fs::{PortablePathBuf, try_relative_to_if};
28use uv_macros::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<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, Deserialize)]
335#[serde(untagged)]
336#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
337pub enum BuildConstraintDependency {
338 Requirement(uv_pep508::Requirement<VerbatimParsedUrl>),
340 WithHashes {
342 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
343 hashes: Vec<String>,
344 },
345}
346
347impl BuildConstraintDependency {
348 pub fn into_parts(self) -> (uv_pep508::Requirement<VerbatimParsedUrl>, Vec<String>) {
350 match self {
351 Self::Requirement(requirement) => (requirement, Vec::new()),
352 Self::WithHashes {
353 requirement,
354 hashes,
355 } => (requirement, hashes),
356 }
357 }
358}
359
360impl From<BuildConstraintDependency> for NameRequirementSpecification {
361 fn from(value: BuildConstraintDependency) -> Self {
362 let (requirement, hashes) = value.into_parts();
363 Self {
364 requirement: requirement.into(),
365 hashes,
366 }
367 }
368}
369
370#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
373#[cfg_attr(test, derive(Serialize))]
374#[serde(rename_all = "kebab-case")]
375#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
376pub struct ToolUv {
377 #[option(
385 default = "{}",
386 value_type = "dict",
387 example = r#"
388 [tool.uv.sources]
389 httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
390 pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
391 pydantic = { path = "/path/to/pydantic", editable = true }
392 "#
393 )]
394 pub sources: Option<ToolUvSources>,
395
396 #[option(
424 default = "[]",
425 value_type = "dict",
426 example = r#"
427 [[tool.uv.index]]
428 name = "pytorch"
429 url = "https://download.pytorch.org/whl/cu130"
430 "#
431 )]
432 #[serde(deserialize_with = "deserialize_index_vec", default)]
433 pub index: Option<Vec<Index>>,
434
435 #[option_group]
437 pub(crate) workspace: Option<ToolUvWorkspace>,
438
439 #[option(
442 default = r#"true"#,
443 value_type = "bool",
444 example = r#"
445 managed = false
446 "#
447 )]
448 pub(crate) managed: Option<bool>,
449
450 #[option(
461 default = r#"true"#,
462 value_type = "bool",
463 example = r#"
464 package = false
465 "#
466 )]
467 package: Option<bool>,
468
469 #[option(
473 default = r#"["dev"]"#,
474 value_type = r#"str | list[str]"#,
475 example = r#"
476 default-groups = ["docs"]
477 "#
478 )]
479 default_groups: Option<DefaultGroups>,
480
481 #[option(
490 default = "[]",
491 value_type = "dict",
492 example = r#"
493 [tool.uv.dependency-groups]
494 my-group = {requires-python = ">=3.12"}
495 "#
496 )]
497 pub(crate) dependency_groups: Option<ToolUvDependencyGroups>,
498
499 #[cfg_attr(
509 feature = "schemars",
510 schemars(
511 with = "Option<Vec<String>>",
512 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
513 )
514 )]
515 #[option(
516 default = "[]",
517 value_type = "list[str]",
518 example = r#"
519 dev-dependencies = ["ruff==0.5.0"]
520 "#
521 )]
522 pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
523
524 #[option(
553 default = "[]",
554 value_type = "list[str | dict]",
555 example = r#"
556 override-dependencies = [
557 # Always install Werkzeug 2.3.0.
558 "werkzeug==2.3.0",
559 # Use itsdangerous 2.1.2 when requested by Flask 3.0.0.
560 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous==2.1.2"] },
561 ]
562 "#
563 )]
564 pub(crate) override_dependencies: Option<Vec<OverrideDependency>>,
565
566 #[option(
587 default = "[]",
588 value_type = "list[str | dict]",
589 example = r#"
590 # Exclude Werkzeug from being installed, even if transitive dependencies request it.
591 exclude-dependencies = [
592 "werkzeug",
593 { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous"] },
594 ]
595 "#
596 )]
597 pub(crate) exclude_dependencies: Option<Vec<ExcludeDependency>>,
598
599 #[cfg_attr(
613 feature = "schemars",
614 schemars(
615 with = "Option<Vec<String>>",
616 description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
617 )
618 )]
619 #[option(
620 default = "[]",
621 value_type = "list[str]",
622 example = r#"
623 # Ensure that the grpcio version is always less than 1.65, if it's requested by a
624 # direct or transitive dependency.
625 constraint-dependencies = ["grpcio<1.65"]
626 "#
627 )]
628 pub(crate) constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
629
630 #[option(
647 default = "[]",
648 value_type = "list[str | dict]",
649 example = r#"
650 # Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
651 # on setuptools.
652 build-constraint-dependencies = ["setuptools==60.0.0"]
653 "#
654 )]
655 pub(crate) build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
656
657 #[cfg_attr(
666 feature = "schemars",
667 schemars(
668 with = "Option<Vec<String>>",
669 description = "A list of environment markers, e.g., `python_version >= '3.6'`."
670 )
671 )]
672 #[option(
673 default = "[]",
674 value_type = "str | list[str]",
675 example = r#"
676 # Resolve for macOS, but not for Linux or Windows.
677 environments = ["sys_platform == 'darwin'"]
678 "#
679 )]
680 pub(crate) environments: Option<SupportedEnvironments>,
681
682 #[cfg_attr(
702 feature = "schemars",
703 schemars(
704 with = "Option<Vec<String>>",
705 description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
706 )
707 )]
708 #[option(
709 default = "[]",
710 value_type = "str | list[str]",
711 example = r#"
712 # Require that the package is available on the following platforms:
713 required-environments = [
714 # macOS on Apple Silicon (ARM)
715 "sys_platform == 'darwin' and platform_machine == 'arm64'",
716 # Linux on x86_64 (Intel/AMD)
717 "sys_platform == 'linux' and platform_machine == 'x86_64'",
718 # Windows on x86_64 (Intel/AMD)
719 "sys_platform == 'win32' and platform_machine == 'AMD64'",
720 ]
721 "#
722 )]
723 pub(crate) required_environments: Option<SupportedEnvironments>,
724
725 #[option(
743 default = "None",
744 value_type = "dict[str, str]",
745 example = r#"
746 preview-features = ["minimum-libc-version"]
747 required-environments = [
748 "sys_platform == 'linux' and platform_machine == 'x86_64'",
749 "sys_platform == 'linux' and platform_machine == 'aarch64'",
750 ]
751 minimum-libc-version = { glibc = "2.31" }
752 "#
753 )]
754 pub(crate) minimum_libc_version: Option<MinimumLibcVersion>,
755
756 #[cfg_attr(
771 feature = "schemars",
772 schemars(description = "A list of sets of conflicting groups or extras.")
773 )]
774 #[option(
775 default = r#"[]"#,
776 value_type = "list[list[dict]]",
777 example = r#"
778 # Require that `package[extra1]` and `package[extra2]` are resolved
779 # in different forks so that they cannot conflict with one another.
780 conflicts = [
781 [
782 { extra = "extra1" },
783 { extra = "extra2" },
784 ]
785 ]
786
787 # Require that the dependency groups `group1` and `group2`
788 # are resolved in different forks so that they cannot conflict
789 # with one another.
790 conflicts = [
791 [
792 { group = "group1" },
793 { group = "group2" },
794 ]
795 ]
796 "#
797 )]
798 pub(crate) conflicts: Option<SchemaConflicts>,
799
800 #[option_group]
807 build_backend: Option<BuildBackendSettingsSchema>,
808}
809
810#[derive(Default, Debug, Clone, PartialEq, Eq)]
811#[cfg_attr(test, derive(Serialize))]
812#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
813pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
814
815#[derive(Deserialize, Debug)]
816#[serde(rename_all = "kebab-case")]
817struct PyProjectTomlSourcesWire {
818 tool: Option<ToolSourcesWire>,
819}
820
821#[derive(Deserialize, Debug)]
822struct ToolSourcesWire {
823 uv: Option<ToolUvSourcesOnlyWire>,
824}
825
826#[derive(Deserialize, Debug)]
827#[serde(rename_all = "kebab-case")]
828struct ToolUvSourcesOnlyWire {
829 sources: Option<ToolUvSourcesWire>,
830}
831
832#[derive(Default, Debug, Clone, PartialEq, Eq)]
833struct ToolUvSourcesWire(BTreeMap<PackageName, SourcesWire>);
834
835impl ToolUvSources {
836 pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
838 &self.0
839 }
840
841 #[must_use]
843 pub(crate) fn into_inner(self) -> BTreeMap<PackageName, Sources> {
844 self.0
845 }
846}
847
848impl TryFrom<ToolUvSourcesWire> for ToolUvSources {
849 type Error = SourceError;
850
851 fn try_from(wire: ToolUvSourcesWire) -> Result<Self, Self::Error> {
852 wire.0
853 .into_iter()
854 .map(|(name, sources)| Sources::try_from(sources).map(|sources| (name, sources)))
855 .collect::<Result<BTreeMap<_, _>, _>>()
856 .map(Self)
857 }
858}
859
860impl<'de> serde::de::Deserialize<'de> for ToolUvSourcesWire {
862 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
863 where
864 D: Deserializer<'de>,
865 {
866 deserialize_unique_map(deserializer, |key: &PackageName| {
867 format!("duplicate sources for package `{key}`")
868 })
869 .map(ToolUvSourcesWire)
870 }
871}
872
873impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
875 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
876 where
877 D: Deserializer<'de>,
878 {
879 deserialize_unique_map(deserializer, |key: &PackageName| {
880 format!("duplicate sources for package `{key}`")
881 })
882 .map(ToolUvSources)
883 }
884}
885
886#[derive(Default, Debug, Clone, PartialEq, Eq)]
887#[cfg_attr(test, derive(Serialize))]
888#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
889pub(crate) struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
890
891impl ToolUvDependencyGroups {
892 pub(crate) fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
894 &self.0
895 }
896}
897
898impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
900 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
901 where
902 D: Deserializer<'de>,
903 {
904 deserialize_unique_map(deserializer, |key: &GroupName| {
905 format!("duplicate settings for dependency group `{key}`")
906 })
907 .map(ToolUvDependencyGroups)
908 }
909}
910
911#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
912#[cfg_attr(test, derive(Serialize))]
913#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
914#[serde(rename_all = "kebab-case")]
915pub(crate) struct DependencyGroupSettings {
916 #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
918 pub(crate) requires_python: Option<VersionSpecifiers>,
919}
920
921#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
922#[serde(untagged, rename_all = "kebab-case")]
923#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
924enum ExtraBuildDependencyWire {
925 Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
926 #[serde(rename_all = "kebab-case")]
927 Annotated {
928 requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
929 match_runtime: bool,
930 },
931}
932
933#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
934#[serde(
935 deny_unknown_fields,
936 from = "ExtraBuildDependencyWire",
937 into = "ExtraBuildDependencyWire"
938)]
939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
940pub struct ExtraBuildDependency {
941 pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
942 pub match_runtime: bool,
943}
944
945impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
946 fn from(value: ExtraBuildDependency) -> Self {
947 value.requirement
948 }
949}
950
951impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
952 fn from(wire: ExtraBuildDependencyWire) -> Self {
953 match wire {
954 ExtraBuildDependencyWire::Unannotated(requirement) => Self {
955 requirement,
956 match_runtime: false,
957 },
958 ExtraBuildDependencyWire::Annotated {
959 requirement,
960 match_runtime,
961 } => Self {
962 requirement,
963 match_runtime,
964 },
965 }
966 }
967}
968
969impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
970 fn from(item: ExtraBuildDependency) -> Self {
971 Self::Annotated {
972 requirement: item.requirement,
973 match_runtime: item.match_runtime,
974 }
975 }
976}
977
978#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
979#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
980pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
981
982impl std::ops::Deref for ExtraBuildDependencies {
983 type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
984
985 fn deref(&self) -> &Self::Target {
986 &self.0
987 }
988}
989
990impl std::ops::DerefMut for ExtraBuildDependencies {
991 fn deref_mut(&mut self) -> &mut Self::Target {
992 &mut self.0
993 }
994}
995
996impl IntoIterator for ExtraBuildDependencies {
997 type Item = (PackageName, Vec<ExtraBuildDependency>);
998 type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
999
1000 fn into_iter(self) -> Self::IntoIter {
1001 self.0.into_iter()
1002 }
1003}
1004
1005impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
1006 fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
1007 iter: T,
1008 ) -> Self {
1009 Self(iter.into_iter().collect())
1010 }
1011}
1012
1013impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
1015 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1016 where
1017 D: Deserializer<'de>,
1018 {
1019 deserialize_unique_map(deserializer, |key: &PackageName| {
1020 format!("duplicate extra-build-dependencies for `{key}`")
1021 })
1022 .map(ExtraBuildDependencies)
1023 }
1024}
1025
1026#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
1027#[cfg_attr(test, derive(Serialize))]
1028#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1029#[serde(rename_all = "kebab-case", deny_unknown_fields)]
1030pub(crate) struct ToolUvWorkspace {
1031 #[option(
1037 default = "[]",
1038 value_type = "list[str]",
1039 example = r#"
1040 members = ["member1", "path/to/member2", "libs/*"]
1041 "#
1042 )]
1043 pub(crate) members: Option<Vec<SerdePattern>>,
1044 #[option(
1051 default = "[]",
1052 value_type = "list[str]",
1053 example = r#"
1054 exclude = ["member1", "path/to/member2", "libs/*"]
1055 "#
1056 )]
1057 pub(crate) exclude: Option<Vec<SerdePattern>>,
1058}
1059
1060#[derive(Debug, Clone, PartialEq, Eq)]
1062pub(crate) struct SerdePattern(Pattern);
1063
1064impl serde::ser::Serialize for SerdePattern {
1065 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1066 where
1067 S: serde::ser::Serializer,
1068 {
1069 self.0.as_str().serialize(serializer)
1070 }
1071}
1072
1073impl<'de> serde::Deserialize<'de> for SerdePattern {
1074 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1075 struct Visitor;
1076
1077 impl serde::de::Visitor<'_> for Visitor {
1078 type Value = SerdePattern;
1079
1080 fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1081 f.write_str("a string")
1082 }
1083
1084 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
1085 Pattern::from_str(v)
1086 .map(SerdePattern)
1087 .map_err(serde::de::Error::custom)
1088 }
1089 }
1090
1091 deserializer.deserialize_str(Visitor)
1092 }
1093}
1094
1095#[cfg(feature = "schemars")]
1096impl schemars::JsonSchema for SerdePattern {
1097 fn schema_name() -> Cow<'static, str> {
1098 Cow::Borrowed("SerdePattern")
1099 }
1100
1101 fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
1102 <String as schemars::JsonSchema>::json_schema(generator)
1103 }
1104}
1105
1106impl Deref for SerdePattern {
1107 type Target = Pattern;
1108
1109 fn deref(&self) -> &Self::Target {
1110 &self.0
1111 }
1112}
1113
1114#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1115#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1116#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
1117pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
1118
1119impl Sources {
1120 pub fn iter(&self) -> impl Iterator<Item = &Source> {
1126 self.0.iter()
1127 }
1128}
1129
1130impl FromIterator<Source> for Sources {
1131 fn from_iter<T: IntoIterator<Item = Source>>(iter: T) -> Self {
1132 Self(iter.into_iter().collect())
1133 }
1134}
1135
1136impl IntoIterator for Sources {
1137 type Item = Source;
1138 type IntoIter = std::vec::IntoIter<Source>;
1139
1140 fn into_iter(self) -> Self::IntoIter {
1141 self.0.into_iter()
1142 }
1143}
1144
1145#[derive(Debug, Clone, PartialEq, Eq)]
1146#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1147enum SourcesWire {
1148 One(Source),
1149 Many(Vec<Source>),
1150}
1151
1152impl<'de> serde::de::Deserialize<'de> for SourcesWire {
1153 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1154 where
1155 D: Deserializer<'de>,
1156 {
1157 struct Visitor;
1158
1159 impl<'de> serde::de::Visitor<'de> for Visitor {
1160 type Value = SourcesWire;
1161
1162 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1163 formatter.write_str("a single source (as a map) or list of sources")
1164 }
1165
1166 fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
1167 where
1168 A: SeqAccess<'de>,
1169 {
1170 let sources = serde::de::Deserialize::deserialize(
1171 serde::de::value::SeqAccessDeserializer::new(seq),
1172 )?;
1173 Ok(SourcesWire::Many(sources))
1174 }
1175
1176 fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
1177 where
1178 M: serde::de::MapAccess<'de>,
1179 {
1180 let source = serde::de::Deserialize::deserialize(
1181 serde::de::value::MapAccessDeserializer::new(&mut map),
1182 )?;
1183 Ok(SourcesWire::One(source))
1184 }
1185 }
1186
1187 deserializer.deserialize_any(Visitor)
1188 }
1189}
1190
1191impl TryFrom<SourcesWire> for Sources {
1192 type Error = SourceError;
1193
1194 fn try_from(wire: SourcesWire) -> Result<Self, Self::Error> {
1195 match wire {
1196 SourcesWire::One(source) => Ok(Self(vec![source])),
1197 SourcesWire::Many(sources) => {
1198 for [lhs, rhs] in sources.array_windows() {
1199 if lhs.extra() != rhs.extra() {
1200 continue;
1201 }
1202 if lhs.group() != rhs.group() {
1203 continue;
1204 }
1205
1206 let lhs = lhs.marker();
1207 let rhs = rhs.marker();
1208 if !lhs.is_disjoint(rhs) {
1209 let Some(left) = lhs.contents().map(|contents| contents.to_string()) else {
1210 return Err(SourceError::MissingMarkers);
1211 };
1212
1213 let Some(right) = rhs.contents().map(|contents| contents.to_string())
1214 else {
1215 return Err(SourceError::MissingMarkers);
1216 };
1217
1218 let hint = lhs.negate().and(rhs);
1219 let hint = hint
1220 .contents()
1221 .map(|contents| contents.to_string())
1222 .unwrap_or_else(|| "true".to_string());
1223
1224 return Err(SourceError::OverlappingMarkers(left, right, hint));
1225 }
1226 }
1227
1228 if sources.is_empty() {
1230 return Err(SourceError::EmptySources);
1231 }
1232
1233 Ok(Self(sources))
1234 }
1235 }
1236 }
1237}
1238
1239#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
1241#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1242#[serde(rename_all = "kebab-case", untagged, deny_unknown_fields)]
1243pub enum Source {
1244 Git {
1251 git: SafeUrl<Raw>,
1253 subdirectory: Option<PortablePathBuf>,
1255 path: Option<PortablePathBuf>,
1257 rev: Option<String>,
1259 tag: Option<String>,
1260 branch: Option<String>,
1261 lfs: Option<bool>,
1263 #[serde(
1264 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1265 serialize_with = "uv_pep508::marker::ser::serialize",
1266 default
1267 )]
1268 marker: MarkerTree,
1269 extra: Option<ExtraName>,
1270 group: Option<GroupName>,
1271 },
1272 Url {
1280 url: SafeUrl<Raw>,
1281 subdirectory: Option<PortablePathBuf>,
1284 #[serde(
1285 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1286 serialize_with = "uv_pep508::marker::ser::serialize",
1287 default
1288 )]
1289 marker: MarkerTree,
1290 extra: Option<ExtraName>,
1291 group: Option<GroupName>,
1292 },
1293 Path {
1297 path: PortablePathBuf,
1298 editable: Option<bool>,
1300 package: Option<bool>,
1307 #[serde(
1308 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1309 serialize_with = "uv_pep508::marker::ser::serialize",
1310 default
1311 )]
1312 marker: MarkerTree,
1313 extra: Option<ExtraName>,
1314 group: Option<GroupName>,
1315 },
1316 Registry {
1318 index: IndexName,
1319 #[serde(
1320 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1321 serialize_with = "uv_pep508::marker::ser::serialize",
1322 default
1323 )]
1324 marker: MarkerTree,
1325 extra: Option<ExtraName>,
1326 group: Option<GroupName>,
1327 },
1328 Workspace {
1330 workspace: WorkspaceReference,
1336 editable: Option<bool>,
1338 #[serde(
1339 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1340 serialize_with = "uv_pep508::marker::ser::serialize",
1341 default
1342 )]
1343 marker: MarkerTree,
1344 extra: Option<ExtraName>,
1345 group: Option<GroupName>,
1346 },
1347}
1348
1349#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1351#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1352#[serde(untagged)]
1353pub enum WorkspaceReference {
1354 Bool(bool),
1355 Path(PortablePathBuf),
1356}
1357
1358impl<'de> Deserialize<'de> for Source {
1361 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1362 where
1363 D: Deserializer<'de>,
1364 {
1365 #[derive(Deserialize, Debug, Clone)]
1366 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
1367 struct CatchAll {
1368 git: Option<SafeUrl>,
1369 subdirectory: Option<PortablePathBuf>,
1370 rev: Option<String>,
1371 tag: Option<String>,
1372 branch: Option<String>,
1373 lfs: Option<bool>,
1374 url: Option<SafeUrl>,
1375 path: Option<PortablePathBuf>,
1376 editable: Option<bool>,
1377 package: Option<bool>,
1378 index: Option<IndexName>,
1379 workspace: Option<WorkspaceReference>,
1380 #[serde(
1381 skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1382 serialize_with = "uv_pep508::marker::ser::serialize",
1383 default
1384 )]
1385 marker: MarkerTree,
1386 extra: Option<ExtraName>,
1387 group: Option<GroupName>,
1388 }
1389
1390 let CatchAll {
1392 git,
1393 subdirectory,
1394 rev,
1395 tag,
1396 branch,
1397 lfs,
1398 url,
1399 path,
1400 editable,
1401 package,
1402 index,
1403 workspace,
1404 marker,
1405 extra,
1406 group,
1407 } = CatchAll::deserialize(deserializer)?;
1408
1409 if extra.is_some() && group.is_some() {
1411 return Err(serde::de::Error::custom(
1412 "cannot specify both `extra` and `group`",
1413 ));
1414 }
1415
1416 if let Some(git) = git {
1418 if index.is_some() {
1419 return Err(serde::de::Error::custom(
1420 "cannot specify both `git` and `index`",
1421 ));
1422 }
1423 if workspace.is_some() {
1424 return Err(serde::de::Error::custom(
1425 "cannot specify both `git` and `workspace`",
1426 ));
1427 }
1428 if url.is_some() {
1429 return Err(serde::de::Error::custom(
1430 "cannot specify both `git` and `url`",
1431 ));
1432 }
1433 if editable.is_some() {
1434 return Err(serde::de::Error::custom(
1435 "cannot specify both `git` and `editable`",
1436 ));
1437 }
1438 if package.is_some() {
1439 return Err(serde::de::Error::custom(
1440 "cannot specify both `git` and `package`",
1441 ));
1442 }
1443 if subdirectory.is_some() && path.is_some() {
1444 return Err(serde::de::Error::custom(
1445 "cannot specify both `subdirectory` and `path`",
1446 ));
1447 }
1448
1449 match (rev.as_ref(), tag.as_ref(), branch.as_ref()) {
1451 (None, None, None) => {}
1452 (Some(_), None, None) => {}
1453 (None, Some(_), None) => {}
1454 (None, None, Some(_)) => {}
1455 _ => {
1456 return Err(serde::de::Error::custom(
1457 "expected at most one of `rev`, `tag`, or `branch`",
1458 ));
1459 }
1460 }
1461
1462 let git = if let Some(git) = git.as_str().strip_prefix("git+") {
1464 SafeUrl::parse(git).map_err(serde::de::Error::custom)?
1465 } else {
1466 git
1467 };
1468
1469 return Ok(Self::Git {
1470 git: git.with_policy(Raw),
1471 subdirectory,
1472 path,
1473 rev,
1474 tag,
1475 branch,
1476 lfs,
1477 marker,
1478 extra,
1479 group,
1480 });
1481 }
1482
1483 if let Some(url) = url {
1485 if index.is_some() {
1486 return Err(serde::de::Error::custom(
1487 "cannot specify both `url` and `index`",
1488 ));
1489 }
1490 if workspace.is_some() {
1491 return Err(serde::de::Error::custom(
1492 "cannot specify both `url` and `workspace`",
1493 ));
1494 }
1495 if path.is_some() {
1496 return Err(serde::de::Error::custom(
1497 "cannot specify both `url` and `path`",
1498 ));
1499 }
1500 if git.is_some() {
1501 return Err(serde::de::Error::custom(
1502 "cannot specify both `url` and `git`",
1503 ));
1504 }
1505 if rev.is_some() {
1506 return Err(serde::de::Error::custom(
1507 "cannot specify both `url` and `rev`",
1508 ));
1509 }
1510 if tag.is_some() {
1511 return Err(serde::de::Error::custom(
1512 "cannot specify both `url` and `tag`",
1513 ));
1514 }
1515 if branch.is_some() {
1516 return Err(serde::de::Error::custom(
1517 "cannot specify both `url` and `branch`",
1518 ));
1519 }
1520 if editable.is_some() {
1521 return Err(serde::de::Error::custom(
1522 "cannot specify both `url` and `editable`",
1523 ));
1524 }
1525 if package.is_some() {
1526 return Err(serde::de::Error::custom(
1527 "cannot specify both `url` and `package`",
1528 ));
1529 }
1530
1531 return Ok(Self::Url {
1532 url: url.with_policy(Raw),
1533 subdirectory,
1534 marker,
1535 extra,
1536 group,
1537 });
1538 }
1539
1540 if let Some(path) = path {
1542 if index.is_some() {
1543 return Err(serde::de::Error::custom(
1544 "cannot specify both `path` and `index`",
1545 ));
1546 }
1547 if workspace.is_some() {
1548 return Err(serde::de::Error::custom(
1549 "cannot specify both `path` and `workspace`",
1550 ));
1551 }
1552 if git.is_some() {
1553 return Err(serde::de::Error::custom(
1554 "cannot specify both `path` and `git`",
1555 ));
1556 }
1557 if url.is_some() {
1558 return Err(serde::de::Error::custom(
1559 "cannot specify both `path` and `url`",
1560 ));
1561 }
1562 if rev.is_some() {
1563 return Err(serde::de::Error::custom(
1564 "cannot specify both `path` and `rev`",
1565 ));
1566 }
1567 if tag.is_some() {
1568 return Err(serde::de::Error::custom(
1569 "cannot specify both `path` and `tag`",
1570 ));
1571 }
1572 if branch.is_some() {
1573 return Err(serde::de::Error::custom(
1574 "cannot specify both `path` and `branch`",
1575 ));
1576 }
1577
1578 if editable == Some(true) && package == Some(false) {
1580 return Err(serde::de::Error::custom(
1581 "cannot specify both `editable = true` and `package = false`",
1582 ));
1583 }
1584
1585 return Ok(Self::Path {
1586 path,
1587 editable,
1588 package,
1589 marker,
1590 extra,
1591 group,
1592 });
1593 }
1594
1595 if let Some(index) = index {
1597 if workspace.is_some() {
1598 return Err(serde::de::Error::custom(
1599 "cannot specify both `index` and `workspace`",
1600 ));
1601 }
1602 if git.is_some() {
1603 return Err(serde::de::Error::custom(
1604 "cannot specify both `index` and `git`",
1605 ));
1606 }
1607 if url.is_some() {
1608 return Err(serde::de::Error::custom(
1609 "cannot specify both `index` and `url`",
1610 ));
1611 }
1612 if path.is_some() {
1613 return Err(serde::de::Error::custom(
1614 "cannot specify both `index` and `path`",
1615 ));
1616 }
1617 if rev.is_some() {
1618 return Err(serde::de::Error::custom(
1619 "cannot specify both `index` and `rev`",
1620 ));
1621 }
1622 if tag.is_some() {
1623 return Err(serde::de::Error::custom(
1624 "cannot specify both `index` and `tag`",
1625 ));
1626 }
1627 if branch.is_some() {
1628 return Err(serde::de::Error::custom(
1629 "cannot specify both `index` and `branch`",
1630 ));
1631 }
1632 if editable.is_some() {
1633 return Err(serde::de::Error::custom(
1634 "cannot specify both `index` and `editable`",
1635 ));
1636 }
1637 if package.is_some() {
1638 return Err(serde::de::Error::custom(
1639 "cannot specify both `index` and `package`",
1640 ));
1641 }
1642
1643 return Ok(Self::Registry {
1644 index,
1645 marker,
1646 extra,
1647 group,
1648 });
1649 }
1650
1651 if let Some(workspace) = workspace {
1653 if index.is_some() {
1654 return Err(serde::de::Error::custom(
1655 "cannot specify both `workspace` and `index`",
1656 ));
1657 }
1658 if git.is_some() {
1659 return Err(serde::de::Error::custom(
1660 "cannot specify both `workspace` and `git`",
1661 ));
1662 }
1663 if url.is_some() {
1664 return Err(serde::de::Error::custom(
1665 "cannot specify both `workspace` and `url`",
1666 ));
1667 }
1668 if path.is_some() {
1669 return Err(serde::de::Error::custom(
1670 "cannot specify both `workspace` and `path`",
1671 ));
1672 }
1673 if rev.is_some() {
1674 return Err(serde::de::Error::custom(
1675 "cannot specify both `workspace` and `rev`",
1676 ));
1677 }
1678 if tag.is_some() {
1679 return Err(serde::de::Error::custom(
1680 "cannot specify both `workspace` and `tag`",
1681 ));
1682 }
1683 if branch.is_some() {
1684 return Err(serde::de::Error::custom(
1685 "cannot specify both `workspace` and `branch`",
1686 ));
1687 }
1688 if package.is_some() {
1689 return Err(serde::de::Error::custom(
1690 "cannot specify both `workspace` and `package`",
1691 ));
1692 }
1693
1694 return Ok(Self::Workspace {
1695 workspace,
1696 editable,
1697 marker,
1698 extra,
1699 group,
1700 });
1701 }
1702
1703 Err(serde::de::Error::custom(
1705 "expected one of `git`, `url`, `path`, `index`, or `workspace`",
1706 ))
1707 }
1708}
1709
1710#[derive(Error, Debug)]
1711pub enum SourceError {
1712 #[error("Failed to resolve Git reference: `{0}`")]
1713 UnresolvedReference(String),
1714 #[error("Workspace dependency `{0}` must refer to local directory, not a Git repository")]
1715 WorkspacePackageGit(String),
1716 #[error("Workspace dependency `{0}` must refer to local directory, not a URL")]
1717 WorkspacePackageUrl(String),
1718 #[error("Workspace dependency `{0}` must refer to local directory, not a file")]
1719 WorkspacePackageFile(String),
1720 #[error(
1721 "`{0}` did not resolve to a Git repository, but a Git reference (`--rev {1}`) was provided."
1722 )]
1723 UnusedRev(String, String),
1724 #[error(
1725 "`{0}` did not resolve to a Git repository, but a Git reference (`--tag {1}`) was provided."
1726 )]
1727 UnusedTag(String, String),
1728 #[error(
1729 "`{0}` did not resolve to a Git repository, but a Git reference (`--branch {1}`) was provided."
1730 )]
1731 UnusedBranch(String, String),
1732 #[error(
1733 "`{0}` did not resolve to a Git repository, but a Git extension (`--lfs`) was provided."
1734 )]
1735 UnusedLfs(String),
1736 #[error(
1737 "`{0}` did not resolve to a local directory, but the `--editable` flag was provided. Editable installs are only supported for local directories."
1738 )]
1739 UnusedEditable(String),
1740 #[error("Failed to resolve absolute path")]
1741 Absolute(#[from] std::io::Error),
1742 #[error("Path contains invalid characters: {}", _0.display())]
1743 NonUtf8Path(PathBuf),
1744 #[error("Source markers must be disjoint, but the following markers overlap: `{0}` and `{1}`.")]
1745 OverlappingMarkers(String, String, String),
1746 #[error(
1747 "When multiple sources are provided, each source must include a platform marker (e.g., `marker = \"sys_platform == 'linux'\"`)"
1748 )]
1749 MissingMarkers,
1750 #[error("Must provide at least one source")]
1751 EmptySources,
1752}
1753
1754impl uv_errors::Hinted for SourceError {
1755 fn hints(&self) -> uv_errors::Hints<'_> {
1756 match self {
1757 Self::OverlappingMarkers(_, rhs, replacement) => {
1758 uv_errors::Hints::from(format!("replace `{rhs}` with `{replacement}`"))
1759 }
1760 _ => uv_errors::Hints::none(),
1761 }
1762 }
1763}
1764
1765impl Source {
1766 pub fn from_requirement(
1767 name: &PackageName,
1768 source: RequirementSource,
1769 workspace: bool,
1770 editable: Option<bool>,
1771 index: Option<IndexName>,
1772 rev: Option<String>,
1773 tag: Option<String>,
1774 branch: Option<String>,
1775 lfs: GitLfsSetting,
1776 root: &Path,
1777 existing_sources: Option<&BTreeMap<PackageName, Sources>>,
1778 ) -> Result<Option<Self>, SourceError> {
1779 if !matches!(
1781 source,
1782 RequirementSource::GitDirectory { .. } | RequirementSource::GitPath { .. }
1783 ) && (branch.is_some()
1784 || tag.is_some()
1785 || rev.is_some()
1786 || matches!(lfs, GitLfsSetting::Enabled { .. }))
1787 {
1788 if let Some(sources) = existing_sources
1789 && let Some(package_sources) = sources.get(name)
1790 {
1791 for existing_source in package_sources.iter() {
1792 if let Self::Git {
1793 git,
1794 subdirectory,
1795 path,
1796 marker,
1797 extra,
1798 group,
1799 ..
1800 } = existing_source
1801 {
1802 return Ok(Some(Self::Git {
1803 git: git.clone(),
1804 subdirectory: subdirectory.clone(),
1805 rev,
1806 tag,
1807 branch,
1808 lfs: lfs.into(),
1809 marker: *marker,
1810 path: path.clone(),
1811 extra: extra.clone(),
1812 group: group.clone(),
1813 }));
1814 }
1815 }
1816 }
1817 if let Some(rev) = rev {
1818 return Err(SourceError::UnusedRev(name.to_string(), rev));
1819 }
1820 if let Some(tag) = tag {
1821 return Err(SourceError::UnusedTag(name.to_string(), tag));
1822 }
1823 if let Some(branch) = branch {
1824 return Err(SourceError::UnusedBranch(name.to_string(), branch));
1825 }
1826 if matches!(lfs, GitLfsSetting::Enabled { from_env: false }) {
1827 return Err(SourceError::UnusedLfs(name.to_string()));
1828 }
1829 }
1830
1831 if !workspace {
1833 if !matches!(source, RequirementSource::Directory { .. }) {
1834 if editable == Some(true) {
1835 return Err(SourceError::UnusedEditable(name.to_string()));
1836 }
1837 }
1838 }
1839
1840 if workspace {
1842 return match source {
1843 RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => {
1844 Ok(Some(Self::Workspace {
1845 workspace: WorkspaceReference::Bool(true),
1846 editable,
1847 marker: MarkerTree::TRUE,
1848 extra: None,
1849 group: None,
1850 }))
1851 }
1852 RequirementSource::Url { .. } => {
1853 Err(SourceError::WorkspacePackageUrl(name.to_string()))
1854 }
1855 RequirementSource::GitDirectory { .. } => {
1856 Err(SourceError::WorkspacePackageGit(name.to_string()))
1857 }
1858 RequirementSource::GitPath { .. } => {
1859 Err(SourceError::WorkspacePackageGit(name.to_string()))
1860 }
1861 RequirementSource::Path { .. } => {
1862 Err(SourceError::WorkspacePackageFile(name.to_string()))
1863 }
1864 };
1865 }
1866
1867 let source = match source {
1868 RequirementSource::Registry { index: Some(_), .. } => {
1869 return Ok(None);
1870 }
1871 RequirementSource::Registry { index: None, .. } if let Some(index) = index => {
1872 Self::Registry {
1873 index,
1874 marker: MarkerTree::TRUE,
1875 extra: None,
1876 group: None,
1877 }
1878 }
1879 RequirementSource::Registry { index: None, .. } => return Ok(None),
1880 RequirementSource::Path {
1881 install_path, url, ..
1882 } => Self::Path {
1883 editable: None,
1884 package: None,
1885 path: PortablePathBuf::from(
1886 try_relative_to_if(&install_path, root, url.prefers_relative())
1887 .map_err(SourceError::Absolute)?
1888 .into_boxed_path(),
1889 ),
1890 marker: MarkerTree::TRUE,
1891 extra: None,
1892 group: None,
1893 },
1894 RequirementSource::Directory {
1895 install_path,
1896 editable: is_editable,
1897 url,
1898 ..
1899 } => Self::Path {
1900 editable: editable.or(is_editable),
1901 package: None,
1902 path: PortablePathBuf::from(
1903 try_relative_to_if(&install_path, root, url.prefers_relative())
1904 .map_err(SourceError::Absolute)?
1905 .into_boxed_path(),
1906 ),
1907 marker: MarkerTree::TRUE,
1908 extra: None,
1909 group: None,
1910 },
1911 RequirementSource::Url {
1912 location,
1913 subdirectory,
1914 ..
1915 } => Self::Url {
1916 url: location,
1917 subdirectory: subdirectory.map(PortablePathBuf::from),
1918 marker: MarkerTree::TRUE,
1919 extra: None,
1920 group: None,
1921 },
1922 RequirementSource::GitDirectory {
1923 git, subdirectory, ..
1924 } => {
1925 if rev.is_none() && tag.is_none() && branch.is_none() {
1926 let rev = git.reference().as_str().map(str::to_owned);
1927 Self::Git {
1928 rev,
1929 tag,
1930 branch,
1931 lfs: lfs.into(),
1932 git: git.url().clone().with_policy(Raw),
1933 subdirectory: subdirectory.map(PortablePathBuf::from),
1934 path: None,
1935 marker: MarkerTree::TRUE,
1936 extra: None,
1937 group: None,
1938 }
1939 } else {
1940 Self::Git {
1941 rev,
1942 tag,
1943 branch,
1944 lfs: lfs.into(),
1945 git: git.url().clone().with_policy(Raw),
1946 subdirectory: subdirectory.map(PortablePathBuf::from),
1947 path: None,
1948 marker: MarkerTree::TRUE,
1949 extra: None,
1950 group: None,
1951 }
1952 }
1953 }
1954 RequirementSource::GitPath {
1955 git, install_path, ..
1956 } => {
1957 if rev.is_none() && tag.is_none() && branch.is_none() {
1958 let rev = git.reference().as_str().map(str::to_owned);
1959 Self::Git {
1960 rev,
1961 tag,
1962 branch,
1963 lfs: lfs.into(),
1964 git: git.url().clone().with_policy(Raw),
1965 subdirectory: None,
1966 path: Some(PortablePathBuf::from(install_path.as_path())),
1967 marker: MarkerTree::TRUE,
1968 extra: None,
1969 group: None,
1970 }
1971 } else {
1972 Self::Git {
1973 rev,
1974 tag,
1975 branch,
1976 lfs: lfs.into(),
1977 git: git.url().clone().with_policy(Raw),
1978 subdirectory: None,
1979 path: Some(PortablePathBuf::from(install_path.as_path())),
1980 marker: MarkerTree::TRUE,
1981 extra: None,
1982 group: None,
1983 }
1984 }
1985 }
1986 };
1987
1988 Ok(Some(source))
1989 }
1990
1991 pub fn marker(&self) -> MarkerTree {
1993 match self {
1994 Self::Git { marker, .. } => *marker,
1995 Self::Url { marker, .. } => *marker,
1996 Self::Path { marker, .. } => *marker,
1997 Self::Registry { marker, .. } => *marker,
1998 Self::Workspace { marker, .. } => *marker,
1999 }
2000 }
2001
2002 pub fn extra(&self) -> Option<&ExtraName> {
2004 match self {
2005 Self::Git { extra, .. } => extra.as_ref(),
2006 Self::Url { extra, .. } => extra.as_ref(),
2007 Self::Path { extra, .. } => extra.as_ref(),
2008 Self::Registry { extra, .. } => extra.as_ref(),
2009 Self::Workspace { extra, .. } => extra.as_ref(),
2010 }
2011 }
2012
2013 pub fn group(&self) -> Option<&GroupName> {
2015 match self {
2016 Self::Git { group, .. } => group.as_ref(),
2017 Self::Url { group, .. } => group.as_ref(),
2018 Self::Path { group, .. } => group.as_ref(),
2019 Self::Registry { group, .. } => group.as_ref(),
2020 Self::Workspace { group, .. } => group.as_ref(),
2021 }
2022 }
2023}
2024
2025#[derive(Debug, Clone, PartialEq, Eq)]
2027pub enum DependencyType {
2028 Production,
2030 Dev,
2032 Optional(ExtraName),
2034 Group(GroupName),
2036}
2037
2038impl DependencyType {
2039 pub fn toml_table_name(&self) -> Cow<'_, str> {
2041 match self {
2042 Self::Production => Cow::Borrowed("`project.dependencies`"),
2043 Self::Dev => {
2044 Cow::Borrowed("`tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`")
2045 }
2046 Self::Optional(extra) => Cow::Owned(format!("`project.optional-dependencies.{extra}`")),
2047 Self::Group(group) => Cow::Owned(format!("`dependency-groups.{group}`")),
2048 }
2049 }
2050}
2051
2052#[derive(Debug, Clone, PartialEq, Eq)]
2053#[cfg_attr(test, derive(Serialize))]
2054pub(crate) struct BuildBackendSettingsSchema;
2055
2056impl<'de> Deserialize<'de> for BuildBackendSettingsSchema {
2057 fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
2058 where
2059 D: Deserializer<'de>,
2060 {
2061 Ok(Self)
2062 }
2063}
2064
2065#[cfg(feature = "schemars")]
2066impl schemars::JsonSchema for BuildBackendSettingsSchema {
2067 fn schema_name() -> Cow<'static, str> {
2068 BuildBackendSettings::schema_name()
2069 }
2070
2071 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2072 BuildBackendSettings::json_schema(generator)
2073 }
2074}
2075
2076impl OptionsMetadata for BuildBackendSettingsSchema {
2077 fn record(visit: &mut dyn Visit) {
2078 BuildBackendSettings::record(visit);
2079 }
2080
2081 fn documentation() -> Option<&'static str> {
2082 BuildBackendSettings::documentation()
2083 }
2084
2085 fn metadata() -> OptionSet
2086 where
2087 Self: Sized + 'static,
2088 {
2089 BuildBackendSettings::metadata()
2090 }
2091}