Skip to main content

uv_workspace/
pyproject.rs

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