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