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