Skip to main content

uv_workspace/
pyproject.rs

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