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