Skip to main content

uv_workspace/
pyproject.rs

1//! Reads the following fields from `pyproject.toml`:
2//!
3//! * `project.{dependencies,optional-dependencies}`
4//! * `tool.uv.sources`
5//! * `tool.uv.workspace`
6//!
7//! Then lowers them into a dependency specification.
8
9use std::borrow::Cow;
10use std::collections::BTreeMap;
11use std::fmt::Formatter;
12use std::ops::Deref;
13use std::path::{Path, PathBuf};
14use std::str::FromStr;
15
16use glob::Pattern;
17use rustc_hash::{FxBuildHasher, FxHashSet};
18use serde::{Deserialize, Deserializer, Serialize};
19use thiserror::Error;
20use tracing::instrument;
21use uv_build_backend::BuildBackendSettings;
22use uv_configuration::{ExcludeDependency, GitLfsSetting, Override};
23use uv_distribution_types::{
24    Index, IndexName, MinimumLibcVersion, NameRequirementSpecification, RequirementSource,
25};
26use uv_fs::{PortablePathBuf, try_relative_to_if};
27use uv_macros::{DeserializeUntagged, OptionsMetadata};
28use uv_normalize::{DEV_DEPENDENCIES, DefaultGroups, ExtraName, GroupName, PackageName};
29use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
30use uv_pep440::{Version, VersionSpecifiers};
31use uv_pep508::MarkerTree;
32use uv_pypi_types::{
33    ConflictError, Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments,
34    VerbatimParsedUrl,
35};
36use uv_redacted::SafeUrl;
37use uv_redacted::policy::Raw;
38use uv_toml::deserialize_unique_map;
39
40use crate::DefaultGroupsError;
41
42#[derive(Error, Debug)]
43pub enum PyprojectTomlError {
44    #[error(transparent)]
45    Toml(#[from] toml::de::Error),
46    #[error("Failed to parse `tool.uv.sources`")]
47    Source(
48        #[from]
49        #[source]
50        SourceError,
51    ),
52    #[error(
53        "`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
54    )]
55    MissingName,
56    #[error(
57        "`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
58    )]
59    MissingVersion,
60}
61
62fn deserialize_optional_dependencies<'de, D, V>(
63    deserializer: D,
64) -> Result<Option<BTreeMap<ExtraName, V>>, D::Error>
65where
66    D: Deserializer<'de>,
67    V: Deserialize<'de>,
68{
69    deserialize_unique_map(deserializer, |key: &ExtraName| {
70        format!("duplicate normalized extra name `{key}`")
71    })
72    .map(Some)
73}
74
75/// A `pyproject.toml` as specified in PEP 517.
76#[derive(Deserialize, Debug, Clone)]
77#[cfg_attr(test, derive(Serialize))]
78#[serde(rename_all = "kebab-case")]
79pub struct PyProjectToml {
80    /// PEP 621-compliant project metadata.
81    pub project: Option<Project>,
82    /// Tool-specific metadata.
83    pub tool: Option<Tool>,
84    /// Non-project dependency groups, as defined in PEP 735.
85    pub dependency_groups: Option<DependencyGroups>,
86    /// The raw unserialized document.
87    #[serde(skip)]
88    pub raw: String,
89
90    /// Used to determine whether a `build-system` section is present.
91    #[serde(default, skip_serializing)]
92    build_system: Option<serde::de::IgnoredAny>,
93}
94
95impl PyProjectToml {
96    /// Return whether this manifest explicitly defines a workspace root.
97    pub fn is_workspace_root(&self) -> bool {
98        self.tool
99            .as_ref()
100            .and_then(|tool| tool.uv.as_ref())
101            .is_some_and(|uv| uv.workspace.is_some())
102    }
103
104    /// Return explicitly configured default groups without validating the group names.
105    ///
106    /// `None` means the setting is absent, so uv uses `dev`; an empty list disables defaults.
107    pub fn configured_default_groups(&self) -> Option<&DefaultGroups> {
108        self.tool
109            .as_ref()
110            .and_then(|tool| tool.uv.as_ref())
111            .and_then(|uv| uv.default_groups.as_ref())
112    }
113
114    /// Return the default dependency groups, validating explicitly configured group names.
115    pub(crate) fn default_groups(&self) -> Result<DefaultGroups, DefaultGroupsError> {
116        if let Some(defaults) = self.configured_default_groups() {
117            if let DefaultGroups::List(defaults) = defaults {
118                for group in defaults {
119                    if !self
120                        .dependency_groups
121                        .as_ref()
122                        .is_some_and(|groups| groups.contains_key(group))
123                    {
124                        return Err(DefaultGroupsError::MissingGroup(group.clone()));
125                    }
126                }
127            }
128            Ok(defaults.clone())
129        } else {
130            Ok(DefaultGroups::from_groups(vec![DEV_DEPENDENCIES.clone()]))
131        }
132    }
133
134    /// Parse a `PyProjectToml` from a raw TOML string.
135    #[instrument("toml::from_str workspace", skip_all, fields(path = %_path.as_ref().display()))]
136    pub fn from_string(raw: String, _path: impl AsRef<Path>) -> Result<Self, PyprojectTomlError> {
137        let pyproject: Self = match toml::from_str(&raw) {
138            Ok(pyproject) => pyproject,
139            Err(error) => {
140                // Preserve the more specific source error if both parses would fail.
141                let sources = toml::from_str::<PyProjectTomlSourcesWire>(&raw)
142                    .map_err(PyprojectTomlError::Toml)?
143                    .tool
144                    .and_then(|tool| tool.uv)
145                    .and_then(|uv| uv.sources);
146                if let Some(sources) = sources {
147                    ToolUvSources::try_from(sources)?;
148                }
149                return Err(PyprojectTomlError::Toml(error));
150            }
151        };
152
153        Ok(Self { raw, ..pyproject })
154    }
155
156    /// Returns `true` if the project should be considered a Python package, as opposed to a
157    /// non-package ("virtual") project.
158    pub fn is_package(&self, require_build_system: bool) -> bool {
159        // If `tool.uv.package` is set, defer to that explicit setting.
160        if let Some(is_package) = self.tool_uv_package() {
161            return is_package;
162        }
163
164        // Otherwise, a project is assumed to be a package if `build-system` is present.
165        self.build_system.is_some() || !require_build_system
166    }
167
168    /// Returns the value of `tool.uv.package` if set.
169    fn tool_uv_package(&self) -> Option<bool> {
170        self.tool
171            .as_ref()
172            .and_then(|tool| tool.uv.as_ref())
173            .and_then(|uv| uv.package)
174    }
175
176    /// Returns whether the project manifest contains any script table.
177    pub fn has_scripts(&self) -> bool {
178        if let Some(ref project) = self.project {
179            project.gui_scripts.is_some() || project.scripts.is_some()
180        } else {
181            false
182        }
183    }
184
185    /// Returns the set of conflicts for the project.
186    pub(crate) fn conflicts(&self) -> Result<Conflicts, ConflictError> {
187        let empty = Conflicts::empty();
188        let Some(project) = self.project.as_ref() else {
189            return Ok(empty);
190        };
191        let Some(tool) = self.tool.as_ref() else {
192            return Ok(empty);
193        };
194        let Some(tooluv) = tool.uv.as_ref() else {
195            return Ok(empty);
196        };
197        let Some(conflicting) = tooluv.conflicts.as_ref() else {
198            return Ok(empty);
199        };
200        conflicting.to_conflicts_with_package_name(&project.name)
201    }
202}
203
204// Ignore raw document in comparison.
205impl PartialEq for PyProjectToml {
206    fn eq(&self, other: &Self) -> bool {
207        self.project.eq(&other.project) && self.tool.eq(&other.tool)
208    }
209}
210
211impl Eq for PyProjectToml {}
212
213impl AsRef<[u8]> for PyProjectToml {
214    fn as_ref(&self) -> &[u8] {
215        self.raw.as_bytes()
216    }
217}
218
219/// PEP 621 project metadata (`project`).
220///
221/// See <https://packaging.python.org/en/latest/specifications/pyproject-toml>.
222#[derive(Deserialize, Debug, Clone, PartialEq)]
223#[cfg_attr(test, derive(Serialize))]
224#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
225pub struct Project {
226    /// The name of the project
227    pub name: PackageName,
228    /// The version of the project
229    version: Option<Version>,
230    /// The Python versions this project is compatible with.
231    pub(crate) requires_python: Option<VersionSpecifiers>,
232    /// The dependencies of the project.
233    pub dependencies: Option<Vec<String>>,
234    /// The optional dependencies of the project.
235    pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
236
237    /// Used to determine whether a `gui-scripts` section is present.
238    #[serde(default, skip_serializing)]
239    gui_scripts: Option<serde::de::IgnoredAny>,
240    /// Used to determine whether a `scripts` section is present.
241    #[serde(default, skip_serializing)]
242    scripts: Option<serde::de::IgnoredAny>,
243}
244
245#[derive(Deserialize, Debug)]
246#[serde(rename_all = "kebab-case")]
247struct ProjectWire {
248    name: Option<PackageName>,
249    version: Option<Version>,
250    dynamic: Option<Vec<String>>,
251    requires_python: Option<VersionSpecifiers>,
252    dependencies: Option<Vec<String>>,
253    #[serde(default, deserialize_with = "deserialize_optional_dependencies")]
254    optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
255    gui_scripts: Option<serde::de::IgnoredAny>,
256    scripts: Option<serde::de::IgnoredAny>,
257}
258
259impl TryFrom<ProjectWire> for Project {
260    type Error = PyprojectTomlError;
261
262    fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
263        // If `[project.name]` is not present, show a dedicated error message.
264        let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
265
266        // If `[project.version]` is not present (or listed in `[project.dynamic]`), show a dedicated error message.
267        if value.version.is_none()
268            && !value
269                .dynamic
270                .as_ref()
271                .is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
272        {
273            return Err(PyprojectTomlError::MissingVersion);
274        }
275
276        Ok(Self {
277            name,
278            version: value.version,
279            requires_python: value.requires_python,
280            dependencies: value.dependencies,
281            optional_dependencies: value.optional_dependencies,
282            gui_scripts: value.gui_scripts,
283            scripts: value.scripts,
284        })
285    }
286}
287
288#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
289#[cfg_attr(test, derive(Serialize))]
290#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
291pub struct Tool {
292    pub uv: Option<Box<ToolUv>>,
293}
294
295/// Validates the `tool.uv.index` field.
296///
297/// This custom deserializer function checks for:
298/// - Duplicate index names
299/// - Multiple indexes marked as default
300fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
301where
302    D: Deserializer<'de>,
303{
304    let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
305    if let Some(indexes) = indexes.as_ref() {
306        let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
307        let mut seen_default = false;
308        for index in indexes {
309            if let Some(name) = index.name.as_ref() {
310                if !seen_names.insert(name) {
311                    return Err(serde::de::Error::custom(format!(
312                        "duplicate index name `{name}`"
313                    )));
314                }
315            }
316            if index.default {
317                if seen_default {
318                    return Err(serde::de::Error::custom(
319                        "found multiple indexes with `default = true`; only one index may be marked as default",
320                    ));
321                }
322                seen_default = true;
323            }
324        }
325    }
326    Ok(indexes)
327}
328
329/// An override dependency before source lowering.
330pub type OverrideDependency = Override<uv_pep508::Requirement<VerbatimParsedUrl>>;
331
332/// A build constraint, optionally accompanied by archive hashes.
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, DeserializeUntagged)]
334#[serde(
335    untagged,
336    expecting = "a requirement string or a table with requirement and hashes"
337)]
338#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
339pub enum BuildConstraintDependency {
340    /// A PEP 508 requirement without additional hashes.
341    #[untagged(string)]
342    Requirement(uv_pep508::Requirement<VerbatimParsedUrl>),
343    /// A PEP 508 requirement and its archive hashes.
344    WithHashes {
345        requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
346        hashes: Vec<String>,
347    },
348}
349
350impl BuildConstraintDependency {
351    /// Return the requirement and any hashes attached to it.
352    pub fn into_parts(self) -> (uv_pep508::Requirement<VerbatimParsedUrl>, Vec<String>) {
353        match self {
354            Self::Requirement(requirement) => (requirement, Vec::new()),
355            Self::WithHashes {
356                requirement,
357                hashes,
358            } => (requirement, hashes),
359        }
360    }
361}
362
363impl From<BuildConstraintDependency> for NameRequirementSpecification {
364    fn from(value: BuildConstraintDependency) -> Self {
365        let (requirement, hashes) = value.into_parts();
366        Self {
367            requirement: requirement.into(),
368            hashes,
369        }
370    }
371}
372
373// NOTE(charlie): When adding fields to this struct, mark them as ignored on `Options` in
374// `crates/uv-settings/src/settings.rs`.
375#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
376#[cfg_attr(test, derive(Serialize))]
377#[serde(rename_all = "kebab-case")]
378#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
379pub struct ToolUv {
380    /// The sources to use when resolving dependencies.
381    ///
382    /// `tool.uv.sources` enriches the dependency metadata with additional sources, incorporated
383    /// during development. A dependency source can be a Git repository, a URL, a local path, or an
384    /// alternative registry.
385    ///
386    /// See [Dependencies](../concepts/projects/dependencies.md) for more.
387    #[option(
388        default = "{}",
389        value_type = "dict",
390        example = r#"
391            [tool.uv.sources]
392            httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
393            pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
394            pydantic = { path = "/path/to/pydantic", editable = true }
395        "#
396    )]
397    pub sources: Option<ToolUvSources>,
398
399    /// The indexes to use when resolving dependencies.
400    ///
401    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
402    /// (the simple repository API), or a local directory laid out in the same format.
403    ///
404    /// Indexes are considered in the order in which they're defined, such that the first-defined
405    /// index has the highest priority. Further, the indexes provided by this setting are given
406    /// higher priority than any indexes specified via [`index_url`](#index-url) or
407    /// [`extra_index_url`](#extra-index-url). uv will only consider the first index that contains
408    /// a given package, unless an alternative [index strategy](#index-strategy) is specified.
409    ///
410    /// If an index is marked as `explicit = true`, it will be used exclusively for the
411    /// dependencies that select it explicitly via `[tool.uv.sources]`, as in:
412    ///
413    /// ```toml
414    /// [[tool.uv.index]]
415    /// name = "pytorch"
416    /// url = "https://download.pytorch.org/whl/cu130"
417    /// explicit = true
418    ///
419    /// [tool.uv.sources]
420    /// torch = { index = "pytorch" }
421    /// ```
422    ///
423    /// If an index is marked as `default = true`, it will be moved to the end of the prioritized list, such that it is
424    /// given the lowest priority when resolving packages. Additionally, marking an index as default will disable the
425    /// PyPI default index.
426    #[option(
427        default = "[]",
428        value_type = "dict",
429        example = r#"
430            [[tool.uv.index]]
431            name = "pytorch"
432            url = "https://download.pytorch.org/whl/cu130"
433        "#
434    )]
435    #[serde(deserialize_with = "deserialize_index_vec", default)]
436    pub index: Option<Vec<Index>>,
437
438    /// The workspace definition for the project, if any.
439    #[option_group]
440    pub(crate) workspace: Option<ToolUvWorkspace>,
441
442    /// Whether the project is managed by uv. If `false`, uv will ignore the project when
443    /// `uv run` is invoked.
444    #[option(
445        default = r#"true"#,
446        value_type = "bool",
447        example = r#"
448            managed = false
449        "#
450    )]
451    pub(crate) managed: Option<bool>,
452
453    /// Whether the project should be considered a Python package, or a non-package ("virtual")
454    /// project.
455    ///
456    /// Packages are built and installed into the virtual environment in editable mode and thus
457    /// require a build backend, while virtual projects are _not_ built or installed; instead, only
458    /// their dependencies are included in the virtual environment.
459    ///
460    /// Creating a package requires that a `build-system` is present in the `pyproject.toml`, and
461    /// that the project adheres to a structure that adheres to the build backend's expectations
462    /// (e.g., a `src` layout).
463    #[option(
464        default = r#"true"#,
465        value_type = "bool",
466        example = r#"
467            package = false
468        "#
469    )]
470    package: Option<bool>,
471
472    /// The list of `dependency-groups` to install by default.
473    ///
474    /// Can also be the literal `"all"` to default enable all groups.
475    #[option(
476        default = r#"["dev"]"#,
477        value_type = r#"str | list[str]"#,
478        example = r#"
479            default-groups = ["docs"]
480        "#
481    )]
482    default_groups: Option<DefaultGroups>,
483
484    /// Additional settings for `dependency-groups`.
485    ///
486    /// Currently this can only be used to add `requires-python` constraints
487    /// to dependency groups (typically to inform uv that your dev tooling
488    /// has a higher python requirement than your actual project).
489    ///
490    /// This cannot be used to define dependency groups, use the top-level
491    /// `[dependency-groups]` table for that.
492    #[option(
493        default = "[]",
494        value_type = "dict",
495        example = r#"
496            [tool.uv.dependency-groups]
497            my-group = {requires-python = ">=3.12"}
498        "#
499    )]
500    pub(crate) dependency_groups: Option<ToolUvDependencyGroups>,
501
502    /// The project's development dependencies.
503    ///
504    /// Development dependencies will be installed by default in `uv run` and `uv sync`, but will
505    /// not appear in the project's published metadata.
506    ///
507    /// Use of this field is not recommend anymore. Instead, use the `dependency-groups.dev` field
508    /// which is a standardized way to declare development dependencies. The contents of
509    /// `tool.uv.dev-dependencies` and `dependency-groups.dev` are combined to determine the final
510    /// requirements of the `dev` dependency group.
511    #[cfg_attr(
512        feature = "schemars",
513        schemars(
514            with = "Option<Vec<String>>",
515            description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
516        )
517    )]
518    #[option(
519        default = "[]",
520        value_type = "list[str]",
521        example = r#"
522            dev-dependencies = ["ruff==0.5.0"]
523        "#
524    )]
525    pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
526
527    /// Overrides to apply when resolving the project's dependencies.
528    ///
529    /// Overrides are used to force selection of a specific version of a package, regardless of the
530    /// version requested by any other package, and regardless of whether choosing that version
531    /// would typically constitute an invalid resolution.
532    ///
533    /// While constraints are _additive_, in that they're combined with the requirements of the
534    /// constituent packages, overrides are _absolute_, in that they completely replace the
535    /// requirements of any constituent packages.
536    ///
537    /// Including a package as an override will _not_ trigger installation of the package on its
538    /// own; instead, the package must be requested elsewhere in the project's first-party or
539    /// transitive dependencies.
540    ///
541    /// Overrides can be limited to the dependencies declared by a specific package version by
542    /// using a table with `package` and `dependencies`. The `package` table identifies the package
543    /// whose dependencies will be overridden by `name` and, optionally, `version`. If `version` is
544    /// omitted, the overrides apply to all versions of that package. Requirements in `dependencies`
545    /// replace dependencies with the same name and add dependencies that are not declared by the
546    /// package. Dependencies not listed in `dependencies` are left unchanged.
547    ///
548    /// Scoped overrides currently support registry version specifiers only. Direct URL and path
549    /// sources, including Git sources, and explicit indexes are not supported.
550    ///
551    /// !!! note
552    ///     In `uv lock`, `uv sync`, and `uv run`, uv will only read `override-dependencies` from
553    ///     the `pyproject.toml` at the workspace root, and will ignore any declarations in other
554    ///     workspace members or `uv.toml` files.
555    #[option(
556        default = "[]",
557        value_type = "list[str | dict]",
558        example = r#"
559            override-dependencies = [
560                # Always install Werkzeug 2.3.0.
561                "werkzeug==2.3.0",
562                # Use itsdangerous 2.1.2 when requested by Flask 3.0.0.
563                { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous==2.1.2"] },
564            ]
565        "#
566    )]
567    pub(crate) override_dependencies: Option<Vec<OverrideDependency>>,
568
569    /// Dependencies to exclude when resolving the project's dependencies.
570    ///
571    /// Excludes are used to prevent a package from being selected during resolution,
572    /// regardless of whether it's requested by any other package. When a package is excluded,
573    /// it will be omitted from the dependency list entirely.
574    ///
575    /// Including a package as an exclusion will prevent it from being installed, even if
576    /// it's requested by transitive dependencies. This can be useful for removing optional
577    /// dependencies or working around packages with broken dependencies.
578    ///
579    /// Exclusions can be limited to the dependencies declared by a specific package version by
580    /// using a table with `package` and `dependencies`. The `package` table identifies the package
581    /// whose dependencies will be excluded by `name` and, optionally, `version`. If `version` is
582    /// omitted, the exclusions apply to all versions of that package. A version-specific entry
583    /// takes precedence over an all-versions entry.
584    ///
585    /// !!! note
586    ///     In `uv lock`, `uv sync`, and `uv run`, uv will only read `exclude-dependencies` from
587    ///     the `pyproject.toml` at the workspace root, and will ignore any declarations in other
588    ///     workspace members or `uv.toml` files.
589    #[option(
590        default = "[]",
591        value_type = "list[str | dict]",
592        example = r#"
593            # Exclude Werkzeug from being installed, even if transitive dependencies request it.
594            exclude-dependencies = [
595                "werkzeug",
596                { package = { name = "flask", version = "3.0.0" }, dependencies = ["itsdangerous"] },
597            ]
598        "#
599    )]
600    pub(crate) exclude_dependencies: Option<Vec<ExcludeDependency>>,
601
602    /// Constraints to apply when resolving the project's dependencies.
603    ///
604    /// Constraints are used to restrict the versions of dependencies that are selected during
605    /// resolution.
606    ///
607    /// Including a package as a constraint will _not_ trigger installation of the package on its
608    /// own; instead, the package must be requested elsewhere in the project's first-party or
609    /// transitive dependencies.
610    ///
611    /// !!! note
612    ///     In `uv lock`, `uv sync`, and `uv run`, uv will only read `constraint-dependencies` from
613    ///     the `pyproject.toml` at the workspace root, and will ignore any declarations in other
614    ///     workspace members or `uv.toml` files.
615    #[cfg_attr(
616        feature = "schemars",
617        schemars(
618            with = "Option<Vec<String>>",
619            description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
620        )
621    )]
622    #[option(
623        default = "[]",
624        value_type = "list[str]",
625        example = r#"
626            # Ensure that the grpcio version is always less than 1.65, if it's requested by a
627            # direct or transitive dependency.
628            constraint-dependencies = ["grpcio<1.65"]
629        "#
630    )]
631    pub(crate) constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
632
633    /// Constraints to apply when solving build dependencies.
634    ///
635    /// Build constraints are used to restrict the versions of build dependencies that are selected
636    /// when building a package during resolution or installation.
637    ///
638    /// Including a package as a constraint will _not_ trigger installation of the package during
639    /// a build; instead, the package must be requested elsewhere in the project's build dependency
640    /// graph.
641    ///
642    /// !!! note
643    ///     In `uv lock`, `uv sync`, and `uv run`, uv will only read `build-constraint-dependencies` from
644    ///     the `pyproject.toml` at the workspace root, and will ignore any declarations in other
645    ///     workspace members or `uv.toml` files.
646    ///
647    /// Hashes can be included to verify downloaded build dependency archives. To provide hashes,
648    /// use a table with `requirement` and `hashes`. uv records these hashes in `uv.lock`.
649    #[option(
650        default = "[]",
651        value_type = "list[str | dict]",
652        example = r#"
653            # Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
654            # on setuptools.
655            build-constraint-dependencies = ["setuptools==60.0.0"]
656        "#
657    )]
658    pub(crate) build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
659
660    /// A list of supported environments against which to resolve dependencies.
661    ///
662    /// By default, uv will resolve for all possible environments during a `uv lock` operation.
663    /// However, you can restrict the set of supported environments to improve performance and avoid
664    /// unsatisfiable branches in the solution space.
665    ///
666    /// These environments will also be respected when `uv pip compile` is invoked with the
667    /// `--universal` flag.
668    #[cfg_attr(
669        feature = "schemars",
670        schemars(
671            with = "Option<Vec<String>>",
672            description = "A list of environment markers, e.g., `python_version >= '3.6'`."
673        )
674    )]
675    #[option(
676        default = "[]",
677        value_type = "str | list[str]",
678        example = r#"
679            # Resolve for macOS, but not for Linux or Windows.
680            environments = ["sys_platform == 'darwin'"]
681        "#
682    )]
683    pub(crate) environments: Option<SupportedEnvironments>,
684
685    /// A list of required platforms, for packages that lack source distributions.
686    ///
687    /// When a package does not have a source distribution, its availability will be limited to
688    /// the platforms supported by its built distributions (wheels). For example, if a package only
689    /// publishes wheels for Linux, then it won't be installable on macOS or Windows.
690    ///
691    /// By default, uv requires each package to include at least one wheel that is compatible with
692    /// the designated Python version. The `required-environments` setting can be used to ensure that
693    /// the resulting resolution contains wheels for specific platforms, or fails if no such wheels
694    /// are available.
695    ///
696    /// While the `environments` setting _limits_ the set of environments that uv will consider when
697    /// resolving dependencies, `required-environments` _expands_ the set of platforms that uv _must_
698    /// support when resolving dependencies.
699    ///
700    /// For example, `environments = ["sys_platform == 'darwin'"]` would limit uv to solving for
701    /// macOS (and ignoring Linux and Windows). On the other hand, `required-environments = ["sys_platform == 'darwin'"]`
702    /// would _require_ that any package without a source distribution include a wheel for macOS in
703    /// order to be installable.
704    #[cfg_attr(
705        feature = "schemars",
706        schemars(
707            with = "Option<Vec<String>>",
708            description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
709        )
710    )]
711    #[option(
712        default = "[]",
713        value_type = "str | list[str]",
714        example = r#"
715            # Require that the package is available on the following platforms:
716            required-environments = [
717                # macOS on Apple Silicon (ARM)
718                "sys_platform == 'darwin' and platform_machine == 'arm64'",
719                # Linux on x86_64 (Intel/AMD)
720                "sys_platform == 'linux' and platform_machine == 'x86_64'",
721                # Windows on x86_64 (Intel/AMD)
722                "sys_platform == 'win32' and platform_machine == 'AMD64'",
723            ]
724        "#
725    )]
726    pub(crate) required_environments: Option<SupportedEnvironments>,
727
728    /// The minimum libc versions to support when resolving for Linux.
729    ///
730    /// During universal resolution, wheels must support the configured libc versions to satisfy
731    /// `required-environments`. For example, `{ glibc = "2.31" }` accepts `manylinux_2_17` wheels
732    /// as coverage, but not `manylinux_2_34` wheels. Both are retained in the lockfile so installation
733    /// can select the best wheel for the current machine. An omitted libc is not required.
734    ///
735    /// Use `required-environments` to specify the Linux architectures to support. Each configured
736    /// libc version needs compatible wheels for those environments. Generic Linux wheels do not
737    /// constrain libc and can satisfy either implementation. Packages with a usable source
738    /// distribution can still be selected.
739    ///
740    /// This setting is respected by `uv lock` and `uv pip compile --universal`.
741    ///
742    /// This option is in preview and may change in any future release. Use
743    /// `--preview-features minimum-libc-version` or configure
744    /// `preview-features = ["minimum-libc-version"]` to disable the warning.
745    #[option(
746        default = "None",
747        value_type = "dict[str, str]",
748        example = r#"
749            preview-features = ["minimum-libc-version"]
750            required-environments = [
751                "sys_platform == 'linux' and platform_machine == 'x86_64'",
752                "sys_platform == 'linux' and platform_machine == 'aarch64'",
753            ]
754            minimum-libc-version = { glibc = "2.31" }
755        "#
756    )]
757    pub(crate) minimum_libc_version: Option<MinimumLibcVersion>,
758
759    /// Declare collections of extras or dependency groups that are conflicting
760    /// (i.e., mutually exclusive).
761    ///
762    /// It's useful to declare conflicts when two or more extras have mutually
763    /// incompatible dependencies. For example, extra `foo` might depend
764    /// on `numpy==2.0.0` while extra `bar` depends on `numpy==2.1.0`. While these
765    /// dependencies conflict, it may be the case that users are not expected to
766    /// activate both `foo` and `bar` at the same time, making it possible to
767    /// generate a universal resolution for the project despite the incompatibility.
768    ///
769    /// By making such conflicts explicit, uv can generate a universal resolution
770    /// for a project, taking into account that certain combinations of extras and
771    /// groups are mutually exclusive. In exchange, installation will fail if a
772    /// user attempts to activate both conflicting extras.
773    #[cfg_attr(
774        feature = "schemars",
775        schemars(description = "A list of sets of conflicting groups or extras.")
776    )]
777    #[option(
778        default = r#"[]"#,
779        value_type = "list[list[dict]]",
780        example = r#"
781            # Require that `package[extra1]` and `package[extra2]` are resolved
782            # in different forks so that they cannot conflict with one another.
783            conflicts = [
784                [
785                    { extra = "extra1" },
786                    { extra = "extra2" },
787                ]
788            ]
789
790            # Require that the dependency groups `group1` and `group2`
791            # are resolved in different forks so that they cannot conflict
792            # with one another.
793            conflicts = [
794                [
795                    { group = "group1" },
796                    { group = "group2" },
797                ]
798            ]
799        "#
800    )]
801    pub(crate) conflicts: Option<SchemaConflicts>,
802
803    // Only exists on this type for schema and docs generation, the build backend settings are
804    // never merged in a workspace and read separately by the backend code.
805    /// Configuration for the uv build backend.
806    ///
807    /// Note that those settings only apply when using the `uv_build` backend, other build backends
808    /// (such as hatchling) have their own configuration.
809    #[option_group]
810    build_backend: Option<BuildBackendSettingsSchema>,
811}
812
813#[derive(Default, Debug, Clone, PartialEq, Eq)]
814#[cfg_attr(test, derive(Serialize))]
815#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
816pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
817
818#[derive(Deserialize, Debug)]
819#[serde(rename_all = "kebab-case")]
820struct PyProjectTomlSourcesWire {
821    tool: Option<ToolSourcesWire>,
822}
823
824#[derive(Deserialize, Debug)]
825struct ToolSourcesWire {
826    uv: Option<ToolUvSourcesOnlyWire>,
827}
828
829#[derive(Deserialize, Debug)]
830#[serde(rename_all = "kebab-case")]
831struct ToolUvSourcesOnlyWire {
832    sources: Option<ToolUvSourcesWire>,
833}
834
835#[derive(Default, Debug, Clone, PartialEq, Eq)]
836struct ToolUvSourcesWire(BTreeMap<PackageName, SourcesWire>);
837
838impl ToolUvSources {
839    /// Returns the underlying `BTreeMap` of package names to sources.
840    pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
841        &self.0
842    }
843
844    /// Convert the [`ToolUvSources`] into its inner `BTreeMap`.
845    #[must_use]
846    pub(crate) fn into_inner(self) -> BTreeMap<PackageName, Sources> {
847        self.0
848    }
849}
850
851impl TryFrom<ToolUvSourcesWire> for ToolUvSources {
852    type Error = SourceError;
853
854    fn try_from(wire: ToolUvSourcesWire) -> Result<Self, Self::Error> {
855        wire.0
856            .into_iter()
857            .map(|(name, sources)| Sources::try_from(sources).map(|sources| (name, sources)))
858            .collect::<Result<BTreeMap<_, _>, _>>()
859            .map(Self)
860    }
861}
862
863/// Ensure that all keys in the TOML table are unique.
864impl<'de> serde::de::Deserialize<'de> for ToolUvSourcesWire {
865    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
866    where
867        D: Deserializer<'de>,
868    {
869        deserialize_unique_map(deserializer, |key: &PackageName| {
870            format!("duplicate sources for package `{key}`")
871        })
872        .map(ToolUvSourcesWire)
873    }
874}
875
876/// Ensure that all keys in the TOML table are unique.
877impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
878    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
879    where
880        D: Deserializer<'de>,
881    {
882        deserialize_unique_map(deserializer, |key: &PackageName| {
883            format!("duplicate sources for package `{key}`")
884        })
885        .map(ToolUvSources)
886    }
887}
888
889#[derive(Default, Debug, Clone, PartialEq, Eq)]
890#[cfg_attr(test, derive(Serialize))]
891#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
892pub(crate) struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
893
894impl ToolUvDependencyGroups {
895    /// Returns the underlying `BTreeMap` of group names to settings.
896    pub(crate) fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
897        &self.0
898    }
899}
900
901/// Ensure that all keys in the TOML table are unique.
902impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
903    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
904    where
905        D: Deserializer<'de>,
906    {
907        deserialize_unique_map(deserializer, |key: &GroupName| {
908            format!("duplicate settings for dependency group `{key}`")
909        })
910        .map(ToolUvDependencyGroups)
911    }
912}
913
914#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
915#[cfg_attr(test, derive(Serialize))]
916#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
917#[serde(rename_all = "kebab-case")]
918pub(crate) struct DependencyGroupSettings {
919    /// Version of python to require when installing this group
920    #[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
921    pub(crate) requires_python: Option<VersionSpecifiers>,
922}
923
924#[derive(Debug, Clone, PartialEq, Eq, Serialize, DeserializeUntagged)]
925#[serde(
926    untagged,
927    expecting = "a requirement string or a table with requirement and match-runtime"
928)]
929#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
930enum ExtraBuildDependencyWire {
931    #[untagged(string)]
932    Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
933    #[serde(rename_all = "kebab-case")]
934    Annotated {
935        requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
936        match_runtime: bool,
937    },
938}
939
940#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
941#[serde(
942    deny_unknown_fields,
943    from = "ExtraBuildDependencyWire",
944    into = "ExtraBuildDependencyWire"
945)]
946#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
947pub struct ExtraBuildDependency {
948    pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
949    pub match_runtime: bool,
950}
951
952impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
953    fn from(value: ExtraBuildDependency) -> Self {
954        value.requirement
955    }
956}
957
958impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
959    fn from(wire: ExtraBuildDependencyWire) -> Self {
960        match wire {
961            ExtraBuildDependencyWire::Unannotated(requirement) => Self {
962                requirement,
963                match_runtime: false,
964            },
965            ExtraBuildDependencyWire::Annotated {
966                requirement,
967                match_runtime,
968            } => Self {
969                requirement,
970                match_runtime,
971            },
972        }
973    }
974}
975
976impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
977    fn from(item: ExtraBuildDependency) -> Self {
978        Self::Annotated {
979            requirement: item.requirement,
980            match_runtime: item.match_runtime,
981        }
982    }
983}
984
985#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
986#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
987pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
988
989impl std::ops::Deref for ExtraBuildDependencies {
990    type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
991
992    fn deref(&self) -> &Self::Target {
993        &self.0
994    }
995}
996
997impl std::ops::DerefMut for ExtraBuildDependencies {
998    fn deref_mut(&mut self) -> &mut Self::Target {
999        &mut self.0
1000    }
1001}
1002
1003impl IntoIterator for ExtraBuildDependencies {
1004    type Item = (PackageName, Vec<ExtraBuildDependency>);
1005    type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
1006
1007    fn into_iter(self) -> Self::IntoIter {
1008        self.0.into_iter()
1009    }
1010}
1011
1012impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
1013    fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
1014        iter: T,
1015    ) -> Self {
1016        Self(iter.into_iter().collect())
1017    }
1018}
1019
1020/// Ensure that all keys in the TOML table are unique.
1021impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
1022    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1023    where
1024        D: Deserializer<'de>,
1025    {
1026        deserialize_unique_map(deserializer, |key: &PackageName| {
1027            format!("duplicate extra-build-dependencies for `{key}`")
1028        })
1029        .map(ExtraBuildDependencies)
1030    }
1031}
1032
1033#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
1034#[cfg_attr(test, derive(Serialize))]
1035#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1036#[serde(rename_all = "kebab-case", deny_unknown_fields)]
1037pub(crate) struct ToolUvWorkspace {
1038    /// Packages to include as workspace members.
1039    ///
1040    /// Supports both globs and explicit paths.
1041    ///
1042    /// For more information on the glob syntax, refer to the [`glob` documentation](https://docs.rs/glob/latest/glob/struct.Pattern.html).
1043    #[option(
1044        default = "[]",
1045        value_type = "list[str]",
1046        example = r#"
1047            members = ["member1", "path/to/member2", "libs/*"]
1048        "#
1049    )]
1050    pub(crate) members: Option<Vec<SerdePattern>>,
1051    /// Packages to exclude as workspace members. If a package matches both `members` and
1052    /// `exclude`, it will be excluded.
1053    ///
1054    /// Supports both globs and explicit paths.
1055    ///
1056    /// For more information on the glob syntax, refer to the [`glob` documentation](https://docs.rs/glob/latest/glob/struct.Pattern.html).
1057    #[option(
1058        default = "[]",
1059        value_type = "list[str]",
1060        example = r#"
1061            exclude = ["member1", "path/to/member2", "libs/*"]
1062        "#
1063    )]
1064    pub(crate) exclude: Option<Vec<SerdePattern>>,
1065}
1066
1067/// (De)serialize globs as strings.
1068#[derive(Debug, Clone, PartialEq, Eq)]
1069pub(crate) struct SerdePattern(Pattern);
1070
1071impl serde::ser::Serialize for SerdePattern {
1072    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1073    where
1074        S: serde::ser::Serializer,
1075    {
1076        self.0.as_str().serialize(serializer)
1077    }
1078}
1079
1080impl<'de> serde::Deserialize<'de> for SerdePattern {
1081    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1082        struct Visitor;
1083
1084        impl serde::de::Visitor<'_> for Visitor {
1085            type Value = SerdePattern;
1086
1087            fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
1088                f.write_str("a string")
1089            }
1090
1091            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
1092                Pattern::from_str(v)
1093                    .map(SerdePattern)
1094                    .map_err(serde::de::Error::custom)
1095            }
1096        }
1097
1098        deserializer.deserialize_str(Visitor)
1099    }
1100}
1101
1102#[cfg(feature = "schemars")]
1103impl schemars::JsonSchema for SerdePattern {
1104    fn schema_name() -> Cow<'static, str> {
1105        Cow::Borrowed("SerdePattern")
1106    }
1107
1108    fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
1109        <String as schemars::JsonSchema>::json_schema(generator)
1110    }
1111}
1112
1113impl Deref for SerdePattern {
1114    type Target = Pattern;
1115
1116    fn deref(&self) -> &Self::Target {
1117        &self.0
1118    }
1119}
1120
1121#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1122#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1123#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
1124pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
1125
1126impl Sources {
1127    /// Return an [`Iterator`] over the sources.
1128    ///
1129    /// If the iterator contains multiple entries, they will always use disjoint markers.
1130    ///
1131    /// The iterator will contain at most one registry source.
1132    pub fn iter(&self) -> impl Iterator<Item = &Source> {
1133        self.0.iter()
1134    }
1135}
1136
1137impl FromIterator<Source> for Sources {
1138    fn from_iter<T: IntoIterator<Item = Source>>(iter: T) -> Self {
1139        Self(iter.into_iter().collect())
1140    }
1141}
1142
1143impl IntoIterator for Sources {
1144    type Item = Source;
1145    type IntoIter = std::vec::IntoIter<Source>;
1146
1147    fn into_iter(self) -> Self::IntoIter {
1148        self.0.into_iter()
1149    }
1150}
1151
1152#[derive(Debug, Clone, PartialEq, Eq, DeserializeUntagged)]
1153#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1154#[serde(expecting = "a single source (as a map) or list of sources")]
1155enum SourcesWire {
1156    #[untagged(map)]
1157    One(Source),
1158    #[untagged(seq)]
1159    Many(Vec<Source>),
1160}
1161
1162impl TryFrom<SourcesWire> for Sources {
1163    type Error = SourceError;
1164
1165    fn try_from(wire: SourcesWire) -> Result<Self, Self::Error> {
1166        match wire {
1167            SourcesWire::One(source) => Ok(Self(vec![source])),
1168            SourcesWire::Many(sources) => {
1169                for [lhs, rhs] in sources.array_windows() {
1170                    if lhs.extra() != rhs.extra() {
1171                        continue;
1172                    }
1173                    if lhs.group() != rhs.group() {
1174                        continue;
1175                    }
1176
1177                    let lhs = lhs.marker();
1178                    let rhs = rhs.marker();
1179                    if !lhs.is_disjoint(rhs) {
1180                        let Some(left) = lhs.contents().map(|contents| contents.to_string()) else {
1181                            return Err(SourceError::MissingMarkers);
1182                        };
1183
1184                        let Some(right) = rhs.contents().map(|contents| contents.to_string())
1185                        else {
1186                            return Err(SourceError::MissingMarkers);
1187                        };
1188
1189                        let hint = lhs.negate().and(rhs);
1190                        let hint = hint
1191                            .contents()
1192                            .map(|contents| contents.to_string())
1193                            .unwrap_or_else(|| "true".to_string());
1194
1195                        return Err(SourceError::OverlappingMarkers(left, right, hint));
1196                    }
1197                }
1198
1199                // Ensure that there is at least one source.
1200                if sources.is_empty() {
1201                    return Err(SourceError::EmptySources);
1202                }
1203
1204                Ok(Self(sources))
1205            }
1206        }
1207    }
1208}
1209
1210/// A `tool.uv.sources` value.
1211#[derive(Serialize, Debug, Clone, PartialEq, Eq)]
1212#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1213#[serde(rename_all = "kebab-case", untagged, deny_unknown_fields)]
1214pub enum Source {
1215    /// A remote Git repository, available over HTTPS or SSH.
1216    ///
1217    /// Example:
1218    /// ```toml
1219    /// flask = { git = "https://github.com/pallets/flask", tag = "3.0.0" }
1220    /// ```
1221    Git {
1222        /// The repository URL (without the `git+` prefix).
1223        git: SafeUrl<Raw>,
1224        /// The path to the directory with the `pyproject.toml`, if it's not in the repository root.
1225        subdirectory: Option<PortablePathBuf>,
1226        /// The path to the archive within the repository.
1227        path: Option<PortablePathBuf>,
1228        // Only one of the three may be used; we'll validate this later and emit a custom error.
1229        rev: Option<String>,
1230        tag: Option<String>,
1231        branch: Option<String>,
1232        /// Whether to use Git LFS when cloning the repository.
1233        lfs: Option<bool>,
1234        #[serde(
1235            skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1236            serialize_with = "uv_pep508::marker::ser::serialize",
1237            default
1238        )]
1239        marker: MarkerTree,
1240        extra: Option<ExtraName>,
1241        group: Option<GroupName>,
1242    },
1243    /// A remote `http://` or `https://` URL, either a wheel (`.whl`) or a source distribution
1244    /// (`.zip`, `.tar.gz`).
1245    ///
1246    /// Example:
1247    /// ```toml
1248    /// flask = { url = "https://files.pythonhosted.org/packages/61/80/ffe1da13ad9300f87c93af113edd0638c75138c42a0994becfacac078c06/flask-3.0.3-py3-none-any.whl" }
1249    /// ```
1250    Url {
1251        url: SafeUrl<Raw>,
1252        /// For source distributions, the path to the directory with the `pyproject.toml`, if it's
1253        /// not in the archive root.
1254        subdirectory: Option<PortablePathBuf>,
1255        #[serde(
1256            skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1257            serialize_with = "uv_pep508::marker::ser::serialize",
1258            default
1259        )]
1260        marker: MarkerTree,
1261        extra: Option<ExtraName>,
1262        group: Option<GroupName>,
1263    },
1264    /// The path to a dependency, either a wheel (a `.whl` file), source distribution (a `.zip` or
1265    /// `.tar.gz` file), or source tree (i.e., a directory containing a `pyproject.toml` or
1266    /// `setup.py` file in the root).
1267    Path {
1268        path: PortablePathBuf,
1269        /// `false` by default.
1270        editable: Option<bool>,
1271        /// Whether to treat the dependency as a buildable Python package (`true`) or as a virtual
1272        /// package (`false`). If `false`, the package will not be built or installed, but its
1273        /// dependencies will be included in the virtual environment.
1274        ///
1275        /// When omitted, the package status is inferred based on the presence of a `[build-system]`
1276        /// in the project's `pyproject.toml`.
1277        package: Option<bool>,
1278        #[serde(
1279            skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1280            serialize_with = "uv_pep508::marker::ser::serialize",
1281            default
1282        )]
1283        marker: MarkerTree,
1284        extra: Option<ExtraName>,
1285        group: Option<GroupName>,
1286    },
1287    /// A dependency pinned to a specific index, e.g., `torch` after setting `torch` to `https://download.pytorch.org/whl/cu118`.
1288    Registry {
1289        index: IndexName,
1290        #[serde(
1291            skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1292            serialize_with = "uv_pep508::marker::ser::serialize",
1293            default
1294        )]
1295        marker: MarkerTree,
1296        extra: Option<ExtraName>,
1297        group: Option<GroupName>,
1298    },
1299    /// A dependency on another package in the workspace.
1300    Workspace {
1301        /// `true` selects the current workspace. A string selects another workspace discovered
1302        /// from the given path.
1303        ///
1304        /// When set to `false`, the package will be fetched from the remote index, rather than
1305        /// included as a workspace package.
1306        workspace: WorkspaceReference,
1307        /// Whether the package should be installed as editable. Defaults to `true`.
1308        editable: Option<bool>,
1309        #[serde(
1310            skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1311            serialize_with = "uv_pep508::marker::ser::serialize",
1312            default
1313        )]
1314        marker: MarkerTree,
1315        extra: Option<ExtraName>,
1316        group: Option<GroupName>,
1317    },
1318}
1319
1320/// A reference to either the current workspace or a workspace discovered from a path.
1321#[derive(Serialize, DeserializeUntagged, Debug, Clone, PartialEq, Eq)]
1322#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))]
1323#[serde(untagged)]
1324pub enum WorkspaceReference {
1325    #[untagged(bool)]
1326    Bool(bool),
1327    #[untagged(string)]
1328    Path(PortablePathBuf),
1329}
1330
1331/// A custom deserialization implementation for [`Source`]. This is roughly equivalent to
1332/// `#[serde(untagged)]`, but provides more detailed error messages.
1333impl<'de> Deserialize<'de> for Source {
1334    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1335    where
1336        D: Deserializer<'de>,
1337    {
1338        #[derive(Deserialize, Debug, Clone)]
1339        #[serde(rename_all = "kebab-case", deny_unknown_fields)]
1340        struct CatchAll {
1341            git: Option<SafeUrl>,
1342            subdirectory: Option<PortablePathBuf>,
1343            rev: Option<String>,
1344            tag: Option<String>,
1345            branch: Option<String>,
1346            lfs: Option<bool>,
1347            url: Option<SafeUrl>,
1348            path: Option<PortablePathBuf>,
1349            editable: Option<bool>,
1350            package: Option<bool>,
1351            index: Option<IndexName>,
1352            workspace: Option<WorkspaceReference>,
1353            #[serde(
1354                skip_serializing_if = "uv_pep508::marker::ser::is_empty",
1355                serialize_with = "uv_pep508::marker::ser::serialize",
1356                default
1357            )]
1358            marker: MarkerTree,
1359            extra: Option<ExtraName>,
1360            group: Option<GroupName>,
1361        }
1362
1363        // Attempt to deserialize as `CatchAll`.
1364        let CatchAll {
1365            git,
1366            subdirectory,
1367            rev,
1368            tag,
1369            branch,
1370            lfs,
1371            url,
1372            path,
1373            editable,
1374            package,
1375            index,
1376            workspace,
1377            marker,
1378            extra,
1379            group,
1380        } = CatchAll::deserialize(deserializer)?;
1381
1382        // If both `extra` and `group` are set, return an error.
1383        if extra.is_some() && group.is_some() {
1384            return Err(serde::de::Error::custom(
1385                "cannot specify both `extra` and `group`",
1386            ));
1387        }
1388
1389        // If the `git` field is set, we're dealing with a Git source.
1390        if let Some(git) = git {
1391            if index.is_some() {
1392                return Err(serde::de::Error::custom(
1393                    "cannot specify both `git` and `index`",
1394                ));
1395            }
1396            if workspace.is_some() {
1397                return Err(serde::de::Error::custom(
1398                    "cannot specify both `git` and `workspace`",
1399                ));
1400            }
1401            if url.is_some() {
1402                return Err(serde::de::Error::custom(
1403                    "cannot specify both `git` and `url`",
1404                ));
1405            }
1406            if editable.is_some() {
1407                return Err(serde::de::Error::custom(
1408                    "cannot specify both `git` and `editable`",
1409                ));
1410            }
1411            if package.is_some() {
1412                return Err(serde::de::Error::custom(
1413                    "cannot specify both `git` and `package`",
1414                ));
1415            }
1416            if subdirectory.is_some() && path.is_some() {
1417                return Err(serde::de::Error::custom(
1418                    "cannot specify both `subdirectory` and `path`",
1419                ));
1420            }
1421
1422            // At most one of `rev`, `tag`, or `branch` may be set.
1423            match (rev.as_ref(), tag.as_ref(), branch.as_ref()) {
1424                (None, None, None) => {}
1425                (Some(_), None, None) => {}
1426                (None, Some(_), None) => {}
1427                (None, None, Some(_)) => {}
1428                _ => {
1429                    return Err(serde::de::Error::custom(
1430                        "expected at most one of `rev`, `tag`, or `branch`",
1431                    ));
1432                }
1433            }
1434
1435            // If the user prefixed the URL with `git+`, strip it.
1436            let git = if let Some(git) = git.as_str().strip_prefix("git+") {
1437                SafeUrl::parse(git).map_err(serde::de::Error::custom)?
1438            } else {
1439                git
1440            };
1441
1442            return Ok(Self::Git {
1443                git: git.with_policy(Raw),
1444                subdirectory,
1445                path,
1446                rev,
1447                tag,
1448                branch,
1449                lfs,
1450                marker,
1451                extra,
1452                group,
1453            });
1454        }
1455
1456        // If the `url` field is set, we're dealing with a URL source.
1457        if let Some(url) = url {
1458            if index.is_some() {
1459                return Err(serde::de::Error::custom(
1460                    "cannot specify both `url` and `index`",
1461                ));
1462            }
1463            if workspace.is_some() {
1464                return Err(serde::de::Error::custom(
1465                    "cannot specify both `url` and `workspace`",
1466                ));
1467            }
1468            if path.is_some() {
1469                return Err(serde::de::Error::custom(
1470                    "cannot specify both `url` and `path`",
1471                ));
1472            }
1473            if git.is_some() {
1474                return Err(serde::de::Error::custom(
1475                    "cannot specify both `url` and `git`",
1476                ));
1477            }
1478            if rev.is_some() {
1479                return Err(serde::de::Error::custom(
1480                    "cannot specify both `url` and `rev`",
1481                ));
1482            }
1483            if tag.is_some() {
1484                return Err(serde::de::Error::custom(
1485                    "cannot specify both `url` and `tag`",
1486                ));
1487            }
1488            if branch.is_some() {
1489                return Err(serde::de::Error::custom(
1490                    "cannot specify both `url` and `branch`",
1491                ));
1492            }
1493            if editable.is_some() {
1494                return Err(serde::de::Error::custom(
1495                    "cannot specify both `url` and `editable`",
1496                ));
1497            }
1498            if package.is_some() {
1499                return Err(serde::de::Error::custom(
1500                    "cannot specify both `url` and `package`",
1501                ));
1502            }
1503
1504            return Ok(Self::Url {
1505                url: url.with_policy(Raw),
1506                subdirectory,
1507                marker,
1508                extra,
1509                group,
1510            });
1511        }
1512
1513        // If the `path` field is set, we're dealing with a path source.
1514        if let Some(path) = path {
1515            if index.is_some() {
1516                return Err(serde::de::Error::custom(
1517                    "cannot specify both `path` and `index`",
1518                ));
1519            }
1520            if workspace.is_some() {
1521                return Err(serde::de::Error::custom(
1522                    "cannot specify both `path` and `workspace`",
1523                ));
1524            }
1525            if git.is_some() {
1526                return Err(serde::de::Error::custom(
1527                    "cannot specify both `path` and `git`",
1528                ));
1529            }
1530            if url.is_some() {
1531                return Err(serde::de::Error::custom(
1532                    "cannot specify both `path` and `url`",
1533                ));
1534            }
1535            if rev.is_some() {
1536                return Err(serde::de::Error::custom(
1537                    "cannot specify both `path` and `rev`",
1538                ));
1539            }
1540            if tag.is_some() {
1541                return Err(serde::de::Error::custom(
1542                    "cannot specify both `path` and `tag`",
1543                ));
1544            }
1545            if branch.is_some() {
1546                return Err(serde::de::Error::custom(
1547                    "cannot specify both `path` and `branch`",
1548                ));
1549            }
1550
1551            // A project must be packaged in order to be installed as editable.
1552            if editable == Some(true) && package == Some(false) {
1553                return Err(serde::de::Error::custom(
1554                    "cannot specify both `editable = true` and `package = false`",
1555                ));
1556            }
1557
1558            return Ok(Self::Path {
1559                path,
1560                editable,
1561                package,
1562                marker,
1563                extra,
1564                group,
1565            });
1566        }
1567
1568        // If the `index` field is set, we're dealing with a registry source.
1569        if let Some(index) = index {
1570            if workspace.is_some() {
1571                return Err(serde::de::Error::custom(
1572                    "cannot specify both `index` and `workspace`",
1573                ));
1574            }
1575            if git.is_some() {
1576                return Err(serde::de::Error::custom(
1577                    "cannot specify both `index` and `git`",
1578                ));
1579            }
1580            if url.is_some() {
1581                return Err(serde::de::Error::custom(
1582                    "cannot specify both `index` and `url`",
1583                ));
1584            }
1585            if path.is_some() {
1586                return Err(serde::de::Error::custom(
1587                    "cannot specify both `index` and `path`",
1588                ));
1589            }
1590            if rev.is_some() {
1591                return Err(serde::de::Error::custom(
1592                    "cannot specify both `index` and `rev`",
1593                ));
1594            }
1595            if tag.is_some() {
1596                return Err(serde::de::Error::custom(
1597                    "cannot specify both `index` and `tag`",
1598                ));
1599            }
1600            if branch.is_some() {
1601                return Err(serde::de::Error::custom(
1602                    "cannot specify both `index` and `branch`",
1603                ));
1604            }
1605            if editable.is_some() {
1606                return Err(serde::de::Error::custom(
1607                    "cannot specify both `index` and `editable`",
1608                ));
1609            }
1610            if package.is_some() {
1611                return Err(serde::de::Error::custom(
1612                    "cannot specify both `index` and `package`",
1613                ));
1614            }
1615
1616            return Ok(Self::Registry {
1617                index,
1618                marker,
1619                extra,
1620                group,
1621            });
1622        }
1623
1624        // If the `workspace` field is set, we're dealing with a workspace source.
1625        if let Some(workspace) = workspace {
1626            if index.is_some() {
1627                return Err(serde::de::Error::custom(
1628                    "cannot specify both `workspace` and `index`",
1629                ));
1630            }
1631            if git.is_some() {
1632                return Err(serde::de::Error::custom(
1633                    "cannot specify both `workspace` and `git`",
1634                ));
1635            }
1636            if url.is_some() {
1637                return Err(serde::de::Error::custom(
1638                    "cannot specify both `workspace` and `url`",
1639                ));
1640            }
1641            if path.is_some() {
1642                return Err(serde::de::Error::custom(
1643                    "cannot specify both `workspace` and `path`",
1644                ));
1645            }
1646            if rev.is_some() {
1647                return Err(serde::de::Error::custom(
1648                    "cannot specify both `workspace` and `rev`",
1649                ));
1650            }
1651            if tag.is_some() {
1652                return Err(serde::de::Error::custom(
1653                    "cannot specify both `workspace` and `tag`",
1654                ));
1655            }
1656            if branch.is_some() {
1657                return Err(serde::de::Error::custom(
1658                    "cannot specify both `workspace` and `branch`",
1659                ));
1660            }
1661            if package.is_some() {
1662                return Err(serde::de::Error::custom(
1663                    "cannot specify both `workspace` and `package`",
1664                ));
1665            }
1666
1667            return Ok(Self::Workspace {
1668                workspace,
1669                editable,
1670                marker,
1671                extra,
1672                group,
1673            });
1674        }
1675
1676        // If none of the fields are set, we're dealing with an error.
1677        Err(serde::de::Error::custom(
1678            "expected one of `git`, `url`, `path`, `index`, or `workspace`",
1679        ))
1680    }
1681}
1682
1683#[derive(Error, Debug)]
1684pub enum SourceError {
1685    #[error("Failed to resolve Git reference: `{0}`")]
1686    UnresolvedReference(String),
1687    #[error("Workspace dependency `{0}` must refer to local directory, not a Git repository")]
1688    WorkspacePackageGit(String),
1689    #[error("Workspace dependency `{0}` must refer to local directory, not a URL")]
1690    WorkspacePackageUrl(String),
1691    #[error("Workspace dependency `{0}` must refer to local directory, not a file")]
1692    WorkspacePackageFile(String),
1693    #[error(
1694        "`{0}` did not resolve to a Git repository, but a Git reference (`--rev {1}`) was provided."
1695    )]
1696    UnusedRev(String, String),
1697    #[error(
1698        "`{0}` did not resolve to a Git repository, but a Git reference (`--tag {1}`) was provided."
1699    )]
1700    UnusedTag(String, String),
1701    #[error(
1702        "`{0}` did not resolve to a Git repository, but a Git reference (`--branch {1}`) was provided."
1703    )]
1704    UnusedBranch(String, String),
1705    #[error(
1706        "`{0}` did not resolve to a Git repository, but a Git extension (`--lfs`) was provided."
1707    )]
1708    UnusedLfs(String),
1709    #[error(
1710        "`{0}` did not resolve to a local directory, but the `--editable` flag was provided. Editable installs are only supported for local directories."
1711    )]
1712    UnusedEditable(String),
1713    #[error("Failed to resolve absolute path")]
1714    Absolute(#[from] std::io::Error),
1715    #[error("Path contains invalid characters: {}", _0.display())]
1716    NonUtf8Path(PathBuf),
1717    #[error("Source markers must be disjoint, but the following markers overlap: `{0}` and `{1}`.")]
1718    OverlappingMarkers(String, String, String),
1719    #[error(
1720        "When multiple sources are provided, each source must include a platform marker (e.g., `marker = \"sys_platform == 'linux'\"`)"
1721    )]
1722    MissingMarkers,
1723    #[error("Must provide at least one source")]
1724    EmptySources,
1725}
1726
1727impl uv_errors::Hinted for SourceError {
1728    fn hints(&self) -> uv_errors::Hints<'_> {
1729        match self {
1730            Self::OverlappingMarkers(_, rhs, replacement) => {
1731                uv_errors::Hints::from(format!("replace `{rhs}` with `{replacement}`"))
1732            }
1733            _ => uv_errors::Hints::none(),
1734        }
1735    }
1736}
1737
1738impl Source {
1739    pub fn from_requirement(
1740        name: &PackageName,
1741        source: RequirementSource,
1742        workspace: bool,
1743        editable: Option<bool>,
1744        index: Option<IndexName>,
1745        rev: Option<String>,
1746        tag: Option<String>,
1747        branch: Option<String>,
1748        lfs: GitLfsSetting,
1749        root: &Path,
1750        existing_sources: Option<&BTreeMap<PackageName, Sources>>,
1751    ) -> Result<Option<Self>, SourceError> {
1752        // If the user specified a Git reference for a non-Git source, try existing Git sources before erroring.
1753        if !matches!(
1754            source,
1755            RequirementSource::GitDirectory { .. } | RequirementSource::GitPath { .. }
1756        ) && (branch.is_some()
1757            || tag.is_some()
1758            || rev.is_some()
1759            || matches!(lfs, GitLfsSetting::Enabled { .. }))
1760        {
1761            if let Some(sources) = existing_sources
1762                && let Some(package_sources) = sources.get(name)
1763            {
1764                for existing_source in package_sources.iter() {
1765                    if let Self::Git {
1766                        git,
1767                        subdirectory,
1768                        path,
1769                        marker,
1770                        extra,
1771                        group,
1772                        ..
1773                    } = existing_source
1774                    {
1775                        return Ok(Some(Self::Git {
1776                            git: git.clone(),
1777                            subdirectory: subdirectory.clone(),
1778                            rev,
1779                            tag,
1780                            branch,
1781                            lfs: lfs.into(),
1782                            marker: *marker,
1783                            path: path.clone(),
1784                            extra: extra.clone(),
1785                            group: group.clone(),
1786                        }));
1787                    }
1788                }
1789            }
1790            if let Some(rev) = rev {
1791                return Err(SourceError::UnusedRev(name.to_string(), rev));
1792            }
1793            if let Some(tag) = tag {
1794                return Err(SourceError::UnusedTag(name.to_string(), tag));
1795            }
1796            if let Some(branch) = branch {
1797                return Err(SourceError::UnusedBranch(name.to_string(), branch));
1798            }
1799            if matches!(lfs, GitLfsSetting::Enabled { from_env: false }) {
1800                return Err(SourceError::UnusedLfs(name.to_string()));
1801            }
1802        }
1803
1804        // If we resolved a non-path source, and user specified an `--editable` flag, error.
1805        if !workspace {
1806            if !matches!(source, RequirementSource::Directory { .. }) {
1807                if editable == Some(true) {
1808                    return Err(SourceError::UnusedEditable(name.to_string()));
1809                }
1810            }
1811        }
1812
1813        // If the source is a workspace package, error if the user tried to specify a source.
1814        if workspace {
1815            return match source {
1816                RequirementSource::Registry { .. } | RequirementSource::Directory { .. } => {
1817                    Ok(Some(Self::Workspace {
1818                        workspace: WorkspaceReference::Bool(true),
1819                        editable,
1820                        marker: MarkerTree::TRUE,
1821                        extra: None,
1822                        group: None,
1823                    }))
1824                }
1825                RequirementSource::Url { .. } => {
1826                    Err(SourceError::WorkspacePackageUrl(name.to_string()))
1827                }
1828                RequirementSource::GitDirectory { .. } => {
1829                    Err(SourceError::WorkspacePackageGit(name.to_string()))
1830                }
1831                RequirementSource::GitPath { .. } => {
1832                    Err(SourceError::WorkspacePackageGit(name.to_string()))
1833                }
1834                RequirementSource::Path { .. } => {
1835                    Err(SourceError::WorkspacePackageFile(name.to_string()))
1836                }
1837            };
1838        }
1839
1840        let source = match source {
1841            RequirementSource::Registry { index: Some(_), .. } => {
1842                return Ok(None);
1843            }
1844            RequirementSource::Registry { index: None, .. } if let Some(index) = index => {
1845                Self::Registry {
1846                    index,
1847                    marker: MarkerTree::TRUE,
1848                    extra: None,
1849                    group: None,
1850                }
1851            }
1852            RequirementSource::Registry { index: None, .. } => return Ok(None),
1853            RequirementSource::Path {
1854                install_path, url, ..
1855            } => Self::Path {
1856                editable: None,
1857                package: None,
1858                path: PortablePathBuf::from(
1859                    try_relative_to_if(&install_path, root, url.prefers_relative())
1860                        .map_err(SourceError::Absolute)?
1861                        .into_boxed_path(),
1862                ),
1863                marker: MarkerTree::TRUE,
1864                extra: None,
1865                group: None,
1866            },
1867            RequirementSource::Directory {
1868                install_path,
1869                editable: is_editable,
1870                url,
1871                ..
1872            } => Self::Path {
1873                editable: editable.or(is_editable),
1874                package: None,
1875                path: PortablePathBuf::from(
1876                    try_relative_to_if(&install_path, root, url.prefers_relative())
1877                        .map_err(SourceError::Absolute)?
1878                        .into_boxed_path(),
1879                ),
1880                marker: MarkerTree::TRUE,
1881                extra: None,
1882                group: None,
1883            },
1884            RequirementSource::Url {
1885                location,
1886                subdirectory,
1887                ..
1888            } => Self::Url {
1889                url: location,
1890                subdirectory: subdirectory.map(PortablePathBuf::from),
1891                marker: MarkerTree::TRUE,
1892                extra: None,
1893                group: None,
1894            },
1895            RequirementSource::GitDirectory {
1896                git, subdirectory, ..
1897            } => {
1898                if rev.is_none() && tag.is_none() && branch.is_none() {
1899                    let rev = git.reference().as_str().map(str::to_owned);
1900                    Self::Git {
1901                        rev,
1902                        tag,
1903                        branch,
1904                        lfs: lfs.into(),
1905                        git: git.url().clone().with_policy(Raw),
1906                        subdirectory: subdirectory.map(PortablePathBuf::from),
1907                        path: None,
1908                        marker: MarkerTree::TRUE,
1909                        extra: None,
1910                        group: None,
1911                    }
1912                } else {
1913                    Self::Git {
1914                        rev,
1915                        tag,
1916                        branch,
1917                        lfs: lfs.into(),
1918                        git: git.url().clone().with_policy(Raw),
1919                        subdirectory: subdirectory.map(PortablePathBuf::from),
1920                        path: None,
1921                        marker: MarkerTree::TRUE,
1922                        extra: None,
1923                        group: None,
1924                    }
1925                }
1926            }
1927            RequirementSource::GitPath {
1928                git, install_path, ..
1929            } => {
1930                if rev.is_none() && tag.is_none() && branch.is_none() {
1931                    let rev = git.reference().as_str().map(str::to_owned);
1932                    Self::Git {
1933                        rev,
1934                        tag,
1935                        branch,
1936                        lfs: lfs.into(),
1937                        git: git.url().clone().with_policy(Raw),
1938                        subdirectory: None,
1939                        path: Some(PortablePathBuf::from(install_path.as_path())),
1940                        marker: MarkerTree::TRUE,
1941                        extra: None,
1942                        group: None,
1943                    }
1944                } else {
1945                    Self::Git {
1946                        rev,
1947                        tag,
1948                        branch,
1949                        lfs: lfs.into(),
1950                        git: git.url().clone().with_policy(Raw),
1951                        subdirectory: None,
1952                        path: Some(PortablePathBuf::from(install_path.as_path())),
1953                        marker: MarkerTree::TRUE,
1954                        extra: None,
1955                        group: None,
1956                    }
1957                }
1958            }
1959        };
1960
1961        Ok(Some(source))
1962    }
1963
1964    /// Return the [`MarkerTree`] for the source.
1965    pub fn marker(&self) -> MarkerTree {
1966        match self {
1967            Self::Git { marker, .. } => *marker,
1968            Self::Url { marker, .. } => *marker,
1969            Self::Path { marker, .. } => *marker,
1970            Self::Registry { marker, .. } => *marker,
1971            Self::Workspace { marker, .. } => *marker,
1972        }
1973    }
1974
1975    /// Return the extra name for the source.
1976    pub fn extra(&self) -> Option<&ExtraName> {
1977        match self {
1978            Self::Git { extra, .. } => extra.as_ref(),
1979            Self::Url { extra, .. } => extra.as_ref(),
1980            Self::Path { extra, .. } => extra.as_ref(),
1981            Self::Registry { extra, .. } => extra.as_ref(),
1982            Self::Workspace { extra, .. } => extra.as_ref(),
1983        }
1984    }
1985
1986    /// Return the dependency group name for the source.
1987    pub fn group(&self) -> Option<&GroupName> {
1988        match self {
1989            Self::Git { group, .. } => group.as_ref(),
1990            Self::Url { group, .. } => group.as_ref(),
1991            Self::Path { group, .. } => group.as_ref(),
1992            Self::Registry { group, .. } => group.as_ref(),
1993            Self::Workspace { group, .. } => group.as_ref(),
1994        }
1995    }
1996}
1997
1998/// The type of a dependency in a `pyproject.toml`.
1999#[derive(Debug, Clone, PartialEq, Eq)]
2000pub enum DependencyType {
2001    /// A dependency in `project.dependencies`.
2002    Production,
2003    /// A dependency in `tool.uv.dev-dependencies`.
2004    Dev,
2005    /// A dependency in `project.optional-dependencies.{0}`.
2006    Optional(ExtraName),
2007    /// A dependency in `dependency-groups.{0}`.
2008    Group(GroupName),
2009}
2010
2011impl DependencyType {
2012    /// Return the TOML table name(s) for this dependency type.
2013    pub fn toml_table_name(&self) -> Cow<'_, str> {
2014        match self {
2015            Self::Production => Cow::Borrowed("`project.dependencies`"),
2016            Self::Dev => {
2017                Cow::Borrowed("`tool.uv.dev-dependencies` or `tool.uv.dependency-groups.dev`")
2018            }
2019            Self::Optional(extra) => Cow::Owned(format!("`project.optional-dependencies.{extra}`")),
2020            Self::Group(group) => Cow::Owned(format!("`dependency-groups.{group}`")),
2021        }
2022    }
2023}
2024
2025#[derive(Debug, Clone, PartialEq, Eq)]
2026#[cfg_attr(test, derive(Serialize))]
2027pub(crate) struct BuildBackendSettingsSchema;
2028
2029impl<'de> Deserialize<'de> for BuildBackendSettingsSchema {
2030    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
2031    where
2032        D: Deserializer<'de>,
2033    {
2034        Ok(Self)
2035    }
2036}
2037
2038#[cfg(feature = "schemars")]
2039impl schemars::JsonSchema for BuildBackendSettingsSchema {
2040    fn schema_name() -> Cow<'static, str> {
2041        BuildBackendSettings::schema_name()
2042    }
2043
2044    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2045        BuildBackendSettings::json_schema(generator)
2046    }
2047}
2048
2049impl OptionsMetadata for BuildBackendSettingsSchema {
2050    fn record(visit: &mut dyn Visit) {
2051        BuildBackendSettings::record(visit);
2052    }
2053
2054    fn documentation() -> Option<&'static str> {
2055        BuildBackendSettings::documentation()
2056    }
2057
2058    fn metadata() -> OptionSet
2059    where
2060        Self: Sized + 'static,
2061    {
2062        BuildBackendSettings::metadata()
2063    }
2064}
2065
2066#[cfg(test)]
2067mod deserialization_tests {
2068    use std::io::{self, Read};
2069
2070    use serde::Deserialize;
2071
2072    use super::{BuildConstraintDependency, ExtraBuildDependency};
2073
2074    #[derive(Debug, Deserialize)]
2075    struct BuildConstraint {
2076        dependency: BuildConstraintDependency,
2077    }
2078
2079    #[derive(Debug, Deserialize)]
2080    struct ExtraBuild {
2081        dependency: ExtraBuildDependency,
2082    }
2083
2084    #[test]
2085    fn build_dependency_retains_read_errors() {
2086        struct FailedRead;
2087
2088        impl Read for FailedRead {
2089            fn read(&mut self, _buffer: &mut [u8]) -> io::Result<usize> {
2090                Err(io::Error::other("metadata read failed"))
2091            }
2092        }
2093
2094        let reader = br#"{"requirement":"setuptools","hashes":["#
2095            .as_slice()
2096            .chain(FailedRead);
2097        assert!(
2098            serde_json::from_reader::<_, BuildConstraintDependency>(reader)
2099                .unwrap_err()
2100                .is_io()
2101        );
2102        let reader = br#"{"requirement":"torch","match-runtime":"#
2103            .as_slice()
2104            .chain(FailedRead);
2105        assert!(
2106            serde_json::from_reader::<_, ExtraBuildDependency>(reader)
2107                .unwrap_err()
2108                .is_io()
2109        );
2110    }
2111
2112    #[test]
2113    fn build_constraint_representations() -> anyhow::Result<()> {
2114        let bare: BuildConstraint = toml::from_str(r#"dependency = "setuptools>=75""#)?;
2115        let annotated: BuildConstraint = toml::from_str(
2116            r#"dependency = { requirement = "setuptools>=75", hashes = ["sha256:abc"], ignored = true }"#,
2117        )?;
2118        assert!(
2119            toml::from_str::<BuildConstraint>(r#"dependency = ["setuptools>=75", ["sha256:abc"]]"#)
2120                .is_err()
2121        );
2122        let (bare_requirement, bare_hashes) = bare.dependency.into_parts();
2123        let (requirement, hashes) = annotated.dependency.into_parts();
2124        assert_eq!(bare_requirement, requirement);
2125        assert!(bare_hashes.is_empty());
2126        assert_eq!(hashes, ["sha256:abc"]);
2127        Ok(())
2128    }
2129
2130    #[test]
2131    fn extra_build_dependency_representations() -> anyhow::Result<()> {
2132        let bare: ExtraBuild = toml::from_str(r#"dependency = "torch>=2""#)?;
2133        let annotated: ExtraBuild = toml::from_str(
2134            r#"dependency = { requirement = "torch>=2", match-runtime = true, ignored = true }"#,
2135        )?;
2136        assert!(toml::from_str::<ExtraBuild>(r#"dependency = ["torch>=2", true]"#).is_err());
2137        assert_eq!(
2138            bare.dependency.requirement,
2139            annotated.dependency.requirement
2140        );
2141        assert!(!bare.dependency.match_runtime);
2142        assert!(annotated.dependency.match_runtime);
2143        Ok(())
2144    }
2145
2146    #[test]
2147    fn build_constraint_requires_hashes() {
2148        insta::assert_snapshot!(
2149            toml::from_str::<BuildConstraint>(r#"dependency = { requirement = "setuptools>=75" }"#).unwrap_err(),
2150            @r#"
2151        TOML parse error at line 1, column 14
2152          |
2153        1 | dependency = { requirement = "setuptools>=75" }
2154          |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2155        missing field `hashes`
2156        "#
2157        );
2158    }
2159
2160    #[test]
2161    fn extra_build_dependency_requires_match_runtime() {
2162        insta::assert_snapshot!(
2163            toml::from_str::<ExtraBuild>(r#"dependency = { requirement = "torch>=2" }"#).unwrap_err(),
2164            @r#"
2165        TOML parse error at line 1, column 14
2166          |
2167        1 | dependency = { requirement = "torch>=2" }
2168          |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2169        missing field `match-runtime`
2170        "#
2171        );
2172    }
2173}