Skip to main content

uv_settings/
settings.rs

1#[cfg(feature = "schemars")]
2use std::borrow::Cow;
3use std::{fmt::Debug, num::NonZeroUsize, path::Path, path::PathBuf};
4
5use serde::{Deserialize, Serialize};
6
7use uv_cache_info::CacheKey;
8use uv_configuration::{
9    AddBoundsKind, AnnotationStyle, BuildIsolation, ExcludeDependency, ExcludeNewerPackage,
10    ForkStrategy, IndexStrategy, KeyringProviderType, PackageNameSpecifier, PrereleaseMode,
11    PrereleasePackage, ProxyUrl, Reinstall, RequiredVersion, ResolutionMode, TargetTriple,
12    TrustedHost, TrustedPublishing, Upgrade, serialize_exclude_newer_package_with_spans,
13};
14use uv_distribution_types::{
15    ConfigSettings, ExcludeNewerOverride, ExcludeNewerSpan, ExcludeNewerValue, ExtraBuildVariables,
16    Index, IndexLocations, IndexUrl, IndexUrlError, MinimumLibcVersion, Origin,
17    PackageConfigSettings, PipExtraIndex, PipFindLinks, PipIndex, ProxyIndex,
18    ProxyIndexConfigError, StaticMetadata,
19};
20use uv_install_wheel::LinkMode;
21use uv_macros::{CombineOptions, DeserializeUntagged, OptionsMetadata};
22use uv_normalize::{ExtraName, PackageName, PipGroupName};
23use uv_pep508::Requirement;
24use uv_preview::{MaybePreviewFeature, Preview};
25use uv_pypi_types::{SupportedEnvironments, VerbatimParsedUrl};
26use uv_python_types::{PythonDownloadMirrors, PythonDownloads, PythonPreference, PythonVersion};
27use uv_redacted::SafeUrl;
28use uv_torch::TorchMode;
29use uv_workspace::pyproject::{
30    BuildConstraintDependency, ExtraBuildDependencies, OverrideDependency,
31};
32
33use crate::{EnvironmentOptions, FilesystemOptions};
34
35/// A `pyproject.toml` with an (optional) `[tool.uv]` section.
36#[allow(dead_code)]
37#[derive(Debug, Clone, Default, Deserialize)]
38pub(crate) struct PyProjectToml {
39    pub(crate) tool: Option<Tools>,
40}
41
42/// A `[tool]` section.
43#[allow(dead_code)]
44#[derive(Debug, Clone, Default, Deserialize)]
45pub(crate) struct Tools {
46    pub(crate) uv: Option<Options>,
47}
48
49/// A `pyproject.toml` with an (optional) `[tool.uv.required-version]`.
50#[derive(Debug, Clone, Default, Deserialize)]
51pub(crate) struct PyProjectRequiredVersionToml {
52    pub(crate) tool: Option<RequiredVersionTools>,
53}
54
55/// A `[tool]` section containing only the fields required for `required-version` discovery.
56#[derive(Debug, Clone, Default, Deserialize)]
57pub(crate) struct RequiredVersionTools {
58    pub(crate) uv: Option<RequiredVersionOptions>,
59}
60
61/// The minimal `[tool.uv]` subset required to enforce `required-version` before full parsing.
62#[derive(Debug, Clone, Default, Deserialize)]
63#[serde(rename_all = "kebab-case")]
64pub(crate) struct RequiredVersionOptions {
65    pub(crate) required_version: Option<RequiredVersion>,
66}
67
68/// A `uv.toml` containing only the fields required for `required-version` discovery.
69#[derive(Debug, Clone, Default, Deserialize)]
70#[serde(rename_all = "kebab-case")]
71pub(crate) struct UvRequiredVersionToml {
72    pub(crate) required_version: Option<RequiredVersion>,
73}
74
75/// A `[tool.uv]` section.
76#[allow(dead_code)]
77#[derive(Debug, Clone, Default, Deserialize, CombineOptions, OptionsMetadata)]
78#[serde(try_from = "OptionsWire", rename_all = "kebab-case")]
79#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
80#[cfg_attr(feature = "schemars", schemars(!try_from))]
81pub struct Options {
82    #[serde(flatten)]
83    pub globals: GlobalOptions,
84
85    #[serde(flatten)]
86    pub top_level: ResolverInstallerSchema,
87
88    #[serde(flatten)]
89    pub install_mirrors: PythonInstallMirrors,
90
91    #[serde(flatten)]
92    pub publish: PublishOptions,
93
94    #[serde(flatten)]
95    pub add: AddOptions,
96
97    #[option_group]
98    pub audit: Option<AuditOptions>,
99
100    #[option_group]
101    pub pip: Option<PipOptions>,
102
103    /// The keys to consider when caching builds for the project.
104    ///
105    /// Cache keys enable you to specify the files or directories that should trigger a rebuild when
106    /// modified. By default, uv will rebuild a project whenever the `pyproject.toml`, `setup.py`,
107    /// or `setup.cfg` files in the project directory are modified, or if a `src` directory is
108    /// added or removed, i.e.:
109    ///
110    /// ```toml
111    /// cache-keys = [{ file = "pyproject.toml" }, { file = "setup.py" }, { file = "setup.cfg" }, { dir = "src" }]
112    /// ```
113    ///
114    /// As an example: if a project uses dynamic metadata to read its dependencies from a
115    /// `requirements.txt` file, you can specify `cache-keys = [{ file = "requirements.txt" }, { file = "pyproject.toml" }]`
116    /// to ensure that the project is rebuilt whenever the `requirements.txt` file is modified (in
117    /// addition to watching the `pyproject.toml`).
118    ///
119    /// Globs are supported, following the syntax of the [`glob`](https://docs.rs/glob/0.3.1/glob/struct.Pattern.html)
120    /// crate. For example, to invalidate the cache whenever a `.toml` file in the project directory
121    /// or any of its subdirectories is modified, you can specify `cache-keys = [{ file = "**/*.toml" }]`.
122    /// Note that the use of globs can be expensive, as uv may need to walk the filesystem to
123    /// determine whether any files have changed.
124    ///
125    /// Cache keys can also include version control information. For example, if a project uses
126    /// `setuptools_scm` to read its version from a Git commit, you can specify `cache-keys = [{ git = { commit = true } }, { file = "pyproject.toml" }]`
127    /// to include the current Git commit hash in the cache key (in addition to the
128    /// `pyproject.toml`). Git tags are also supported via `cache-keys = [{ git = { commit = true, tags = true } }]`.
129    ///
130    /// Cache keys can also include environment variables. For example, if a project relies on
131    /// `MACOSX_DEPLOYMENT_TARGET` or other environment variables to determine its behavior, you can
132    /// specify `cache-keys = [{ env = "MACOSX_DEPLOYMENT_TARGET" }]` to invalidate the cache
133    /// whenever the environment variable changes.
134    ///
135    /// Cache keys only affect the project defined by the `pyproject.toml` in which they're
136    /// specified (as opposed to, e.g., affecting all members in a workspace), and all paths and
137    /// globs are interpreted as relative to the project directory.
138    #[option(
139        default = r#"[{ file = "pyproject.toml" }, { file = "setup.py" }, { file = "setup.cfg" }]"#,
140        value_type = "list[dict]",
141        example = r#"
142            cache-keys = [{ file = "pyproject.toml" }, { file = "requirements.txt" }, { git = { commit = true } }]
143        "#
144    )]
145    pub cache_keys: Option<Vec<CacheKey>>,
146
147    // NOTE(charlie): These fields are shared with `ToolUv` in
148    // `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
149    // They're respected in both `pyproject.toml` and `uv.toml` files.
150    #[cfg_attr(feature = "schemars", schemars(skip))]
151    pub override_dependencies: Option<Vec<OverrideDependency>>,
152
153    #[cfg_attr(feature = "schemars", schemars(skip))]
154    pub exclude_dependencies: Option<Vec<ExcludeDependency>>,
155
156    #[cfg_attr(feature = "schemars", schemars(skip))]
157    pub constraint_dependencies: Option<Vec<Requirement<VerbatimParsedUrl>>>,
158
159    #[cfg_attr(feature = "schemars", schemars(skip))]
160    pub build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
161
162    #[cfg_attr(feature = "schemars", schemars(skip))]
163    pub environments: Option<SupportedEnvironments>,
164
165    #[cfg_attr(feature = "schemars", schemars(skip))]
166    pub required_environments: Option<SupportedEnvironments>,
167
168    #[cfg_attr(feature = "schemars", schemars(skip))]
169    pub minimum_libc_version: Option<MinimumLibcVersion>,
170
171    // NOTE(charlie): These fields should be kept in-sync with `ToolUv` in
172    // `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
173    // They're only respected in `pyproject.toml` files, and should be rejected in `uv.toml` files.
174    #[cfg_attr(feature = "schemars", schemars(skip))]
175    pub(crate) conflicts: Option<serde::de::IgnoredAny>,
176
177    #[cfg_attr(feature = "schemars", schemars(skip))]
178    pub(crate) workspace: Option<serde::de::IgnoredAny>,
179
180    #[cfg_attr(feature = "schemars", schemars(skip))]
181    pub(crate) sources: Option<serde::de::IgnoredAny>,
182
183    #[cfg_attr(feature = "schemars", schemars(skip))]
184    pub(crate) dev_dependencies: Option<serde::de::IgnoredAny>,
185
186    #[cfg_attr(feature = "schemars", schemars(skip))]
187    pub(crate) default_groups: Option<serde::de::IgnoredAny>,
188
189    #[cfg_attr(feature = "schemars", schemars(skip))]
190    pub(crate) dependency_groups: Option<serde::de::IgnoredAny>,
191
192    #[cfg_attr(feature = "schemars", schemars(skip))]
193    pub(crate) managed: Option<serde::de::IgnoredAny>,
194
195    #[cfg_attr(feature = "schemars", schemars(skip))]
196    pub(crate) r#package: Option<serde::de::IgnoredAny>,
197
198    #[cfg_attr(feature = "schemars", schemars(skip))]
199    pub(crate) build_backend: Option<serde::de::IgnoredAny>,
200}
201
202impl Options {
203    /// Construct an [`Options`] with the given global and top-level settings.
204    pub fn simple(globals: GlobalOptions, top_level: ResolverInstallerSchema) -> Self {
205        Self {
206            globals,
207            top_level,
208            ..Default::default()
209        }
210    }
211
212    /// Set the [`Origin`] on all indexes without an existing origin.
213    #[must_use]
214    pub(crate) fn with_origin(mut self, origin: Origin) -> Self {
215        if let Some(indexes) = &mut self.top_level.index {
216            for index in indexes {
217                index.origin.get_or_insert(origin);
218            }
219        }
220        if let Some(index_url) = &mut self.top_level.index_url {
221            index_url.try_set_origin(origin);
222        }
223        if let Some(extra_index_urls) = &mut self.top_level.extra_index_url {
224            for index_url in extra_index_urls {
225                index_url.try_set_origin(origin);
226            }
227        }
228        if let Some(pip) = &mut self.pip {
229            if let Some(indexes) = &mut pip.index {
230                for index in indexes {
231                    index.origin.get_or_insert(origin);
232                }
233            }
234            if let Some(index_url) = &mut pip.index_url {
235                index_url.try_set_origin(origin);
236            }
237            if let Some(extra_index_urls) = &mut pip.extra_index_url {
238                for index_url in extra_index_urls {
239                    index_url.try_set_origin(origin);
240                }
241            }
242        }
243        self
244    }
245
246    /// Resolve the [`Options`] relative to the given root directory.
247    pub(crate) fn relative_to(self, root_dir: &Path) -> Result<Self, IndexUrlError> {
248        Ok(Self {
249            top_level: self.top_level.relative_to(root_dir)?,
250            pip: self.pip.map(|pip| pip.relative_to(root_dir)).transpose()?,
251            ..self
252        })
253    }
254}
255
256/// Global settings, relevant to all invocations.
257#[derive(Debug, Clone, Default, Deserialize, CombineOptions, OptionsMetadata)]
258#[serde(try_from = "GlobalOptionsWire", rename_all = "kebab-case")]
259#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
260#[cfg_attr(feature = "schemars", schemars(!try_from))]
261pub struct GlobalOptions {
262    /// Enforce a requirement on the version of uv.
263    ///
264    /// If the version of uv does not meet the requirement at runtime, uv will exit
265    /// with an error.
266    ///
267    /// Accepts a [PEP 440](https://peps.python.org/pep-0440/) specifier, like `==0.5.0` or `>=0.5.0`.
268    #[option(
269        default = "null",
270        value_type = "str",
271        example = r#"
272            required-version = ">=0.5.0"
273        "#
274    )]
275    pub required_version: Option<RequiredVersion>,
276    /// Whether to load TLS certificates from the platform's native certificate store.
277    ///
278    /// By default, uv uses bundled Mozilla root certificates. When enabled, this loads
279    /// certificates from the platform's native certificate store instead.
280    #[option(
281        default = "false",
282        value_type = "bool",
283        uv_toml_only = true,
284        example = r#"
285            system-certs = true
286        "#
287    )]
288    pub system_certs: Option<bool>,
289    /// Whether to load TLS certificates from the platform's native certificate store.
290    ///
291    /// By default, uv uses bundled Mozilla root certificates. When enabled, this loads
292    /// certificates from the platform's native certificate store instead.
293    ///
294    /// (Deprecated: use `system-certs` instead.)
295    #[deprecated(note = "use `system-certs` instead")]
296    #[option(
297        default = "false",
298        value_type = "bool",
299        uv_toml_only = true,
300        example = r#"
301            native-tls = true
302        "#
303    )]
304    pub native_tls: Option<bool>,
305    /// Disable network access, relying only on locally cached data and locally available files.
306    #[option(
307        default = "false",
308        value_type = "bool",
309        example = r#"
310            offline = true
311        "#
312    )]
313    pub offline: Option<bool>,
314    /// Avoid reading from or writing to the cache, instead using a temporary directory for the
315    /// duration of the operation.
316    #[option(
317        default = "false",
318        value_type = "bool",
319        example = r#"
320            no-cache = true
321        "#
322    )]
323    pub no_cache: Option<bool>,
324    /// Path to the cache directory.
325    ///
326    /// Defaults to `$XDG_CACHE_HOME/uv` or `$HOME/.cache/uv` on Linux and macOS, and
327    /// `%LOCALAPPDATA%\uv\cache` on Windows.
328    #[option(
329        default = "None",
330        value_type = "str",
331        uv_toml_only = true,
332        example = r#"
333            cache-dir = "./.uv_cache"
334        "#
335    )]
336    pub cache_dir: Option<PathBuf>,
337
338    /// The user's preview configuration.
339    #[serde(flatten)]
340    pub preview: Option<PreviewOption>,
341
342    /// Whether to prefer using Python installations that are already present on the system, or
343    /// those that are downloaded and installed by uv.
344    #[option(
345        default = "\"managed\"",
346        value_type = "str",
347        example = r#"
348            python-preference = "managed"
349        "#,
350        possible_values = true
351    )]
352    pub python_preference: Option<PythonPreference>,
353    /// Whether to allow Python downloads.
354    #[option(
355        default = "\"automatic\"",
356        value_type = "str",
357        example = r#"
358            python-downloads = "manual"
359        "#,
360        possible_values = true
361    )]
362    pub python_downloads: Option<PythonDownloads>,
363    /// The maximum number of in-flight concurrent downloads that uv will perform at any given
364    /// time.
365    #[option(
366        default = "50",
367        value_type = "int",
368        example = r#"
369            concurrent-downloads = 4
370        "#
371    )]
372    pub concurrent_downloads: Option<NonZeroUsize>,
373    /// The maximum number of source distributions that uv will build concurrently at any given
374    /// time.
375    ///
376    /// Defaults to the number of available CPU cores.
377    #[option(
378        default = "None",
379        value_type = "int",
380        example = r#"
381            concurrent-builds = 4
382        "#
383    )]
384    pub concurrent_builds: Option<NonZeroUsize>,
385    /// The number of threads used when installing and unzipping packages.
386    ///
387    /// Defaults to the number of available CPU cores.
388    #[option(
389        default = "None",
390        value_type = "int",
391        example = r#"
392            concurrent-installs = 4
393        "#
394    )]
395    pub concurrent_installs: Option<NonZeroUsize>,
396    /// The URL of the HTTP proxy to use.
397    #[option(
398        default = "None",
399        value_type = "str",
400        uv_toml_only = true,
401        example = r#"
402            http-proxy = "http://proxy.example.com"
403        "#
404    )]
405    pub http_proxy: Option<ProxyUrl>,
406    /// The URL of the HTTPS proxy to use.
407    #[option(
408        default = "None",
409        value_type = "str",
410        uv_toml_only = true,
411        example = r#"
412            https-proxy = "https://proxy.example.com"
413        "#
414    )]
415    pub https_proxy: Option<ProxyUrl>,
416    /// A list of hosts to exclude from proxying.
417    #[option(
418        default = "None",
419        value_type = "list[str]",
420        uv_toml_only = true,
421        example = r#"
422            no-proxy = ["localhost", "127.0.0.1"]
423        "#
424    )]
425    pub no_proxy: Option<Vec<String>>,
426    /// Allow insecure connections to host.
427    ///
428    /// Expects to receive either a hostname (e.g., `localhost`), a host-port pair (e.g.,
429    /// `localhost:8080`), or a URL (e.g., `https://localhost`).
430    ///
431    /// WARNING: Hosts included in this list will not be verified against the system's certificate
432    /// store. Only use `--allow-insecure-host` in a secure network with verified sources, as it
433    /// bypasses SSL verification and could expose you to MITM attacks.
434    #[option(
435        default = "[]",
436        value_type = "list[str]",
437        example = r#"
438            allow-insecure-host = ["localhost:8080"]
439        "#
440    )]
441    pub allow_insecure_host: Option<Vec<TrustedHost>>,
442}
443
444/// Like [`GlobalOptions`], but with any `#[serde(flatten)]` fields inlined.
445/// This improves line/column information in error messages.
446#[derive(Debug, Clone, Default, Deserialize)]
447#[serde(rename_all = "kebab-case")]
448struct GlobalOptionsWire {
449    required_version: Option<RequiredVersion>,
450    system_certs: Option<bool>,
451    native_tls: Option<bool>,
452    offline: Option<bool>,
453    no_cache: Option<bool>,
454    cache_dir: Option<PathBuf>,
455
456    preview: Option<bool>,
457    preview_features: Option<PreviewFeaturesOption>,
458
459    python_preference: Option<PythonPreference>,
460    python_downloads: Option<PythonDownloads>,
461    concurrent_downloads: Option<NonZeroUsize>,
462    concurrent_builds: Option<NonZeroUsize>,
463    concurrent_installs: Option<NonZeroUsize>,
464    http_proxy: Option<ProxyUrl>,
465    https_proxy: Option<ProxyUrl>,
466    no_proxy: Option<Vec<String>>,
467    allow_insecure_host: Option<Vec<TrustedHost>>,
468}
469
470impl TryFrom<GlobalOptionsWire> for GlobalOptions {
471    type Error = &'static str;
472
473    #[allow(deprecated)]
474    fn try_from(value: GlobalOptionsWire) -> Result<Self, Self::Error> {
475        let GlobalOptionsWire {
476            required_version,
477            system_certs,
478            native_tls,
479            offline,
480            no_cache,
481            cache_dir,
482            preview,
483            preview_features,
484            python_preference,
485            python_downloads,
486            concurrent_downloads,
487            concurrent_builds,
488            concurrent_installs,
489            http_proxy,
490            https_proxy,
491            no_proxy,
492            allow_insecure_host,
493        } = value;
494
495        Ok(Self {
496            required_version,
497            system_certs,
498            native_tls,
499            offline,
500            no_cache,
501            cache_dir,
502            preview: PreviewOption::try_from(preview, preview_features)?,
503            python_preference,
504            python_downloads,
505            concurrent_downloads,
506            concurrent_builds,
507            concurrent_installs,
508            http_proxy,
509            https_proxy,
510            no_proxy,
511            allow_insecure_host,
512        })
513    }
514}
515
516/// Resolve registry indexes and find-links relative to the given root directory.
517fn rebase_indexes(
518    root_dir: &Path,
519    indexes: &mut Option<Vec<Index>>,
520    index_url: &mut Option<PipIndex>,
521    extra_index_urls: &mut Option<Vec<PipExtraIndex>>,
522    find_links: &mut Option<Vec<PipFindLinks>>,
523) -> Result<(), IndexUrlError> {
524    *indexes = indexes
525        .take()
526        .map(|indexes| {
527            indexes
528                .into_iter()
529                .map(|index| index.relative_to(root_dir))
530                .collect::<Result<Vec<_>, _>>()
531        })
532        .transpose()?;
533    *index_url = index_url
534        .take()
535        .map(|index| index.relative_to(root_dir))
536        .transpose()?;
537    *extra_index_urls = extra_index_urls
538        .take()
539        .map(|indexes| {
540            indexes
541                .into_iter()
542                .map(|index| index.relative_to(root_dir))
543                .collect::<Result<Vec<_>, _>>()
544        })
545        .transpose()?;
546    *find_links = find_links
547        .take()
548        .map(|find_links| {
549            find_links
550                .into_iter()
551                .map(|find_link| find_link.relative_to(root_dir))
552                .collect::<Result<Vec<_>, _>>()
553        })
554        .transpose()?;
555
556    Ok(())
557}
558
559/// Settings relevant to all installer operations.
560#[derive(Debug, Clone, Default, CombineOptions)]
561pub struct InstallerOptions {
562    index: Option<Vec<Index>>,
563    proxy_index: Option<Vec<ProxyIndex>>,
564    index_url: Option<PipIndex>,
565    extra_index_url: Option<Vec<PipExtraIndex>>,
566    no_index: Option<bool>,
567    find_links: Option<Vec<PipFindLinks>>,
568    index_strategy: Option<IndexStrategy>,
569    keyring_provider: Option<KeyringProviderType>,
570    config_settings: Option<ConfigSettings>,
571    exclude_newer: Option<ExcludeNewerOverride>,
572    link_mode: Option<LinkMode>,
573    compile_bytecode: Option<bool>,
574    reinstall: Option<Reinstall>,
575    build_isolation: Option<BuildIsolation>,
576    no_build: Option<bool>,
577    no_build_package: Option<Vec<PackageName>>,
578    no_binary: Option<bool>,
579    no_binary_package: Option<Vec<PackageName>>,
580    no_sources: Option<bool>,
581    no_sources_package: Option<Vec<PackageName>>,
582}
583
584/// Settings shared by all operations that use package indexes.
585#[derive(Debug, Clone, Default, CombineOptions)]
586pub struct IndexOptions {
587    pub index: Option<Vec<Index>>,
588    pub proxy_index: Option<Vec<ProxyIndex>>,
589    pub index_url: Option<PipIndex>,
590    pub extra_index_url: Option<Vec<PipExtraIndex>>,
591    pub no_index: Option<bool>,
592    pub find_links: Option<Vec<PipFindLinks>>,
593}
594
595impl IndexOptions {
596    /// Resolve the [`IndexOptions`] relative to the given root directory.
597    pub fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> {
598        rebase_indexes(
599            root_dir,
600            &mut self.index,
601            &mut self.index_url,
602            &mut self.extra_index_url,
603            &mut self.find_links,
604        )?;
605
606        Ok(self)
607    }
608}
609
610impl TryFrom<IndexOptions> for IndexLocations {
611    type Error = ProxyIndexConfigError;
612
613    fn try_from(value: IndexOptions) -> Result<Self, Self::Error> {
614        let IndexOptions {
615            index,
616            proxy_index,
617            index_url,
618            extra_index_url,
619            no_index,
620            find_links,
621        } = value;
622
623        Self::new(
624            index
625                .into_iter()
626                .flatten()
627                .chain(extra_index_url.into_iter().flatten().map(Index::from))
628                .chain(index_url.into_iter().map(Index::from))
629                .collect(),
630            proxy_index.into_iter().flatten().collect(),
631            find_links.into_iter().flatten().map(Index::from).collect(),
632            no_index.unwrap_or_default(),
633        )
634    }
635}
636
637impl From<IndexOptions> for PipOptions {
638    fn from(value: IndexOptions) -> Self {
639        let IndexOptions {
640            index,
641            proxy_index,
642            index_url,
643            extra_index_url,
644            no_index,
645            find_links,
646        } = value;
647
648        Self {
649            index,
650            proxy_index,
651            index_url,
652            extra_index_url,
653            no_index,
654            find_links,
655            ..Self::default()
656        }
657    }
658}
659
660/// Settings relevant to all resolver operations.
661#[derive(Debug, Clone, Default, CombineOptions)]
662pub struct ResolverOptions {
663    pub indexes: IndexOptions,
664    pub index_strategy: Option<IndexStrategy>,
665    pub keyring_provider: Option<KeyringProviderType>,
666    pub resolution: Option<ResolutionMode>,
667    pub prerelease: Option<PrereleaseMode>,
668    pub prerelease_package: Option<PrereleasePackage>,
669    pub fork_strategy: Option<ForkStrategy>,
670    pub dependency_metadata: Option<Vec<StaticMetadata>>,
671    pub config_settings: Option<ConfigSettings>,
672    pub config_settings_package: Option<PackageConfigSettings>,
673    pub exclude_newer: Option<ExcludeNewerOverride>,
674    pub exclude_newer_package: Option<ExcludeNewerPackage>,
675    pub link_mode: Option<LinkMode>,
676    pub torch_backend: Option<TorchMode>,
677    pub upgrade: Option<Upgrade>,
678    pub require_build_hashes: Option<bool>,
679    pub build_isolation: Option<BuildIsolation>,
680    pub no_build: Option<bool>,
681    pub no_build_package: Option<Vec<PackageName>>,
682    pub no_binary: Option<bool>,
683    pub no_binary_package: Option<Vec<PackageName>>,
684    pub extra_build_dependencies: Option<ExtraBuildDependencies>,
685    pub extra_build_variables: Option<ExtraBuildVariables>,
686    pub no_sources: Option<bool>,
687    pub no_sources_package: Option<Vec<PackageName>>,
688}
689
690impl ResolverOptions {
691    /// Resolve the [`ResolverOptions`] relative to the given root directory.
692    pub fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> {
693        self.indexes = self.indexes.relative_to(root_dir)?;
694        Ok(self)
695    }
696}
697
698/// Shared settings, relevant to all operations that must resolve and install dependencies. The
699/// union of [`InstallerOptions`] and [`ResolverOptions`].
700#[derive(Debug, Clone, Default, CombineOptions)]
701pub struct ResolverInstallerOptions {
702    pub indexes: IndexOptions,
703    pub index_strategy: Option<IndexStrategy>,
704    pub keyring_provider: Option<KeyringProviderType>,
705    pub resolution: Option<ResolutionMode>,
706    pub prerelease: Option<PrereleaseMode>,
707    pub prerelease_package: Option<PrereleasePackage>,
708    pub fork_strategy: Option<ForkStrategy>,
709    pub dependency_metadata: Option<Vec<StaticMetadata>>,
710    pub config_settings: Option<ConfigSettings>,
711    pub config_settings_package: Option<PackageConfigSettings>,
712    pub require_build_hashes: Option<bool>,
713    pub build_isolation: Option<BuildIsolation>,
714    pub extra_build_dependencies: Option<ExtraBuildDependencies>,
715    pub extra_build_variables: Option<ExtraBuildVariables>,
716    pub exclude_newer: Option<ExcludeNewerOverride>,
717    pub exclude_newer_package: Option<ExcludeNewerPackage>,
718    pub link_mode: Option<LinkMode>,
719    pub torch_backend: Option<TorchMode>,
720    pub compile_bytecode: Option<bool>,
721    pub no_sources: Option<bool>,
722    pub no_sources_package: Option<Vec<PackageName>>,
723    pub upgrade: Option<Upgrade>,
724    pub reinstall: Option<Reinstall>,
725    pub no_build: Option<bool>,
726    pub no_build_package: Option<Vec<PackageName>>,
727    pub no_binary: Option<bool>,
728    pub no_binary_package: Option<Vec<PackageName>>,
729}
730
731impl ResolverInstallerOptions {
732    /// Resolve the [`ResolverInstallerOptions`] relative to the given root directory.
733    pub fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> {
734        self.indexes = self.indexes.relative_to(root_dir)?;
735        Ok(self)
736    }
737}
738
739impl From<ResolverInstallerSchema> for ResolverInstallerOptions {
740    fn from(value: ResolverInstallerSchema) -> Self {
741        let ResolverInstallerSchema {
742            index,
743            proxy_index,
744            index_url,
745            extra_index_url,
746            no_index,
747            find_links,
748            index_strategy,
749            keyring_provider,
750            resolution,
751            prerelease,
752            prerelease_package,
753            fork_strategy,
754            dependency_metadata,
755            config_settings,
756            config_settings_package,
757            require_build_hashes,
758            no_build_isolation,
759            no_build_isolation_package,
760            extra_build_dependencies,
761            extra_build_variables,
762            exclude_newer,
763            exclude_newer_package,
764            link_mode,
765            torch_backend,
766            compile_bytecode,
767            no_sources,
768            no_sources_package,
769            upgrade,
770            upgrade_package,
771            reinstall,
772            reinstall_package,
773            no_build,
774            no_build_package,
775            no_binary,
776            no_binary_package,
777        } = value;
778        Self {
779            indexes: IndexOptions {
780                index,
781                proxy_index,
782                index_url,
783                extra_index_url,
784                no_index,
785                find_links,
786            },
787            index_strategy,
788            keyring_provider,
789            resolution,
790            prerelease,
791            prerelease_package,
792            fork_strategy,
793            dependency_metadata,
794            config_settings,
795            config_settings_package,
796            require_build_hashes,
797            build_isolation: BuildIsolation::from_args(
798                no_build_isolation,
799                no_build_isolation_package.into_iter().flatten().collect(),
800            ),
801            extra_build_dependencies,
802            extra_build_variables,
803            exclude_newer,
804            exclude_newer_package,
805            link_mode,
806            torch_backend,
807            compile_bytecode,
808            no_sources,
809            no_sources_package,
810            upgrade: Upgrade::from_args(
811                upgrade,
812                upgrade_package
813                    .into_iter()
814                    .flatten()
815                    .map(Into::into)
816                    .collect(),
817                Vec::new(),
818            ),
819            reinstall: Reinstall::from_args(reinstall, reinstall_package.unwrap_or_default()),
820            no_build,
821            no_build_package,
822            no_binary,
823            no_binary_package,
824        }
825    }
826}
827
828impl ResolverInstallerSchema {
829    /// Resolve the [`ResolverInstallerSchema`] relative to the given root directory.
830    fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> {
831        rebase_indexes(
832            root_dir,
833            &mut self.index,
834            &mut self.index_url,
835            &mut self.extra_index_url,
836            &mut self.find_links,
837        )?;
838
839        Ok(self)
840    }
841}
842
843/// The JSON schema for the `[tool.uv]` section of a `pyproject.toml` file.
844#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
845#[serde(rename_all = "kebab-case")]
846#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
847pub struct ResolverInstallerSchema {
848    /// The package indexes to use when resolving dependencies.
849    ///
850    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
851    /// (the simple repository API), or a local directory laid out in the same format.
852    ///
853    /// Indexes are considered in the order in which they're defined, such that the first-defined
854    /// index has the highest priority. Further, the indexes provided by this setting are given
855    /// higher priority than any indexes specified via [`index_url`](#index-url) or
856    /// [`extra_index_url`](#extra-index-url). uv will only consider the first index that contains
857    /// a given package, unless an alternative [index strategy](#index-strategy) is specified.
858    ///
859    /// If an index is marked as `explicit = true`, it will be used exclusively for those
860    /// dependencies that select it explicitly via `[tool.uv.sources]`, as in:
861    ///
862    /// ```toml
863    /// [[tool.uv.index]]
864    /// name = "pytorch"
865    /// url = "https://download.pytorch.org/whl/cu130"
866    /// explicit = true
867    ///
868    /// [tool.uv.sources]
869    /// torch = { index = "pytorch" }
870    /// ```
871    ///
872    /// If an index is marked as `default = true`, it will be moved to the end of the prioritized list, such that it is
873    /// given the lowest priority when resolving packages. Additionally, marking an index as default will disable the
874    /// PyPI default index.
875    #[option(
876        default = "\"[]\"",
877        value_type = "dict",
878        example = r#"
879            [[tool.uv.index]]
880            name = "pytorch"
881            url = "https://download.pytorch.org/whl/cu130"
882        "#
883    )]
884    pub index: Option<Vec<Index>>,
885    /// The proxy indexes to use when resolving and downloading packages.
886    ///
887    /// `proxy-for` names a configured upstream index, `url` sets the proxy's Simple API URL, and
888    /// `artifact-base-url` sets its package download URL prefix. uv records upstream URLs in
889    /// lockfiles.
890    #[option(
891        default = "\"[]\"",
892        value_type = "dict",
893        example = r#"
894            [[tool.uv.index]]
895            name = "pypi"
896            url = "https://pypi.org/simple/"
897            default = true
898
899            [[tool.uv.proxy-index]]
900            name = "socket"
901            url = "https://proxy.example.com/simple/"
902            artifact-base-url = "https://proxy.example.com/files/"
903            proxy-for = "pypi"
904        "#
905    )]
906    pub proxy_index: Option<Vec<ProxyIndex>>,
907    /// The URL of the Python package index (by default: <https://pypi.org/simple>).
908    ///
909    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
910    /// (the simple repository API), or a local directory laid out in the same format.
911    ///
912    /// The index provided by this setting is given lower priority than any indexes specified via
913    /// [`extra_index_url`](#extra-index-url) or [`index`](#index).
914    ///
915    /// (Deprecated: use `index` instead.)
916    #[option(
917        default = "\"https://pypi.org/simple\"",
918        value_type = "str",
919        example = r#"
920            index-url = "https://test.pypi.org/simple"
921        "#
922    )]
923    pub index_url: Option<PipIndex>,
924    /// Extra URLs of package indexes to use, in addition to `--index-url`.
925    ///
926    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
927    /// (the simple repository API), or a local directory laid out in the same format.
928    ///
929    /// All indexes provided via this flag take priority over the index specified by
930    /// [`index_url`](#index-url) or [`index`](#index) with `default = true`. When multiple indexes
931    /// are provided, earlier values take priority.
932    ///
933    /// To control uv's resolution strategy when multiple indexes are present, see
934    /// [`index_strategy`](#index-strategy).
935    ///
936    /// (Deprecated: use `index` instead.)
937    #[option(
938        default = "[]",
939        value_type = "list[str]",
940        example = r#"
941            extra-index-url = ["https://download.pytorch.org/whl/cpu"]
942        "#
943    )]
944    pub extra_index_url: Option<Vec<PipExtraIndex>>,
945    /// Ignore all registry indexes (e.g., PyPI), instead relying on direct URL dependencies and
946    /// those provided via `--find-links`.
947    #[option(
948        default = "false",
949        value_type = "bool",
950        example = r#"
951            no-index = true
952        "#
953    )]
954    pub no_index: Option<bool>,
955    /// Locations to search for candidate distributions, in addition to those found in the registry
956    /// indexes.
957    ///
958    /// If a path, the target must be a directory that contains packages as wheel files (`.whl`) or
959    /// source distributions (e.g., `.tar.gz` or `.zip`) at the top level.
960    ///
961    /// If a URL, the page must contain a flat list of links to package files adhering to the
962    /// formats described above.
963    #[option(
964        default = "[]",
965        value_type = "list[str]",
966        example = r#"
967            find-links = ["https://download.pytorch.org/whl/torch_stable.html"]
968        "#
969    )]
970    pub find_links: Option<Vec<PipFindLinks>>,
971    /// The strategy to use when resolving against multiple index URLs.
972    ///
973    /// By default, uv will stop at the first index on which a given package is available, and
974    /// limit resolutions to those present on that first index (`first-index`). This prevents
975    /// "dependency confusion" attacks, whereby an attacker can upload a malicious package under the
976    /// same name to an alternate index.
977    #[option(
978        default = "\"first-index\"",
979        value_type = "str",
980        example = r#"
981            index-strategy = "unsafe-best-match"
982        "#,
983        possible_values = true
984    )]
985    pub index_strategy: Option<IndexStrategy>,
986    /// Attempt to use `keyring` for authentication for index URLs.
987    ///
988    /// At present, only `--keyring-provider subprocess` is supported, which configures uv to
989    /// use the `keyring` CLI to handle authentication.
990    #[option(
991        default = "\"disabled\"",
992        value_type = "str",
993        example = r#"
994            keyring-provider = "subprocess"
995        "#
996    )]
997    pub keyring_provider: Option<KeyringProviderType>,
998    /// The strategy to use when selecting between the different compatible versions for a given
999    /// package requirement.
1000    ///
1001    /// By default, uv will use the latest compatible version of each package (`highest`).
1002    #[option(
1003        default = "\"highest\"",
1004        value_type = "str",
1005        example = r#"
1006            resolution = "lowest-direct"
1007        "#,
1008        possible_values = true
1009    )]
1010    pub resolution: Option<ResolutionMode>,
1011    /// The strategy to use when considering pre-release versions.
1012    ///
1013    /// By default, uv will prefer stable candidates, falling back to pre-releases only after every
1014    /// stable candidate that satisfies the active constraints is rejected
1015    /// (`if-necessary`).
1016    #[option(
1017        default = "\"if-necessary\"",
1018        value_type = "str",
1019        example = r#"
1020            prerelease = "allow"
1021        "#,
1022        possible_values = true
1023    )]
1024    pub prerelease: Option<PrereleaseMode>,
1025    /// The strategy to use when considering pre-release versions for specific packages.
1026    ///
1027    /// Package-specific modes take precedence over the global [`prerelease`](#prerelease) mode.
1028    /// Accepts a dictionary mapping package names to any supported pre-release mode.
1029    #[option(
1030        default = "{}",
1031        value_type = "dict",
1032        example = r#"
1033            prerelease-package = { numpy = "allow", scipy = "disallow" }
1034        "#
1035    )]
1036    pub prerelease_package: Option<PrereleasePackage>,
1037    /// The strategy to use when selecting multiple versions of a given package across Python
1038    /// versions and platforms.
1039    ///
1040    /// By default, uv will optimize for selecting the latest version of each package for each
1041    /// supported Python version (`requires-python`), while minimizing the number of selected
1042    /// versions across platforms.
1043    ///
1044    /// Under `fewest`, uv will minimize the number of selected versions for each package,
1045    /// preferring older versions that are compatible with a wider range of supported Python
1046    /// versions or platforms.
1047    #[option(
1048        default = "\"requires-python\"",
1049        value_type = "str",
1050        example = r#"
1051            fork-strategy = "fewest"
1052        "#,
1053        possible_values = true
1054    )]
1055    pub fork_strategy: Option<ForkStrategy>,
1056    /// Pre-defined static metadata for dependencies of the project (direct or transitive). When
1057    /// provided, enables the resolver to use the specified metadata instead of querying the
1058    /// registry or building the relevant package from source.
1059    ///
1060    /// Metadata should be provided in adherence with the [Metadata 2.3](https://packaging.python.org/en/latest/specifications/core-metadata/)
1061    /// standard, though only the following fields are respected:
1062    ///
1063    /// - `name`: The name of the package.
1064    /// - (Optional) `version`: The version of the package. If omitted, the metadata will be applied
1065    ///   to all versions of the package.
1066    /// - (Optional) `requires-dist`: The dependencies of the package (e.g., `werkzeug>=0.14`).
1067    /// - (Optional) `requires-python`: The Python version required by the package (e.g., `>=3.10`).
1068    /// - (Optional) `provides-extra`: The extras provided by the package.
1069    #[option(
1070        default = r#"[]"#,
1071        value_type = "list[dict]",
1072        example = r#"
1073            dependency-metadata = [
1074                { name = "flask", version = "1.0.0", requires-dist = ["werkzeug"], requires-python = ">=3.6" },
1075            ]
1076        "#
1077    )]
1078    pub dependency_metadata: Option<Vec<StaticMetadata>>,
1079    /// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend,
1080    /// specified as `KEY=VALUE` pairs.
1081    #[option(
1082        default = "{}",
1083        value_type = "dict",
1084        example = r#"
1085            config-settings = { editable_mode = "compat" }
1086        "#
1087    )]
1088    pub config_settings: Option<ConfigSettings>,
1089    /// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend for specific packages,
1090    /// specified as `KEY=VALUE` pairs.
1091    ///
1092    /// Accepts a map from package names to string key-value pairs.
1093    #[option(
1094        default = "{}",
1095        value_type = "dict",
1096        example = r#"
1097            config-settings-package = { numpy = { editable_mode = "compat" } }
1098        "#
1099    )]
1100    pub config_settings_package: Option<PackageConfigSettings>,
1101    /// Disable isolation when building source distributions.
1102    ///
1103    /// Assumes that build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
1104    /// are already installed.
1105    #[option(
1106        default = "false",
1107        value_type = "bool",
1108        example = r#"
1109            no-build-isolation = true
1110        "#
1111    )]
1112    pub no_build_isolation: Option<bool>,
1113
1114    /// Require hashes for all build dependencies.
1115    ///
1116    /// uv checks hashes provided in `build-constraint-dependencies` when downloading build
1117    /// dependencies. Enable this setting to require a hash for every build dependency, including
1118    /// transitive dependencies. You can also provide hashes as URL fragments in
1119    /// `build-system.requires`. Hashes returned by a build backend do not count.
1120    ///
1121    /// Hashes are not required for the `uv_build` backend bundled in uv. When build isolation is
1122    /// disabled, build dependencies must already be installed and their hashes are not checked.
1123    /// Already-installed packages and previously built wheels are not checked.
1124    ///
1125    /// This setting also applies to `uv pip` commands, where it can be overridden in `[tool.uv.pip]`.
1126    #[option(
1127        default = "false",
1128        value_type = "bool",
1129        example = "require-build-hashes = true"
1130    )]
1131    pub require_build_hashes: Option<bool>,
1132
1133    /// Disable isolation when building source distributions for a specific package.
1134    ///
1135    /// Assumes that the packages' build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
1136    /// are already installed.
1137    #[option(
1138        default = "[]",
1139        value_type = "list[str]",
1140        example = r#"
1141        no-build-isolation-package = ["package1", "package2"]
1142    "#
1143    )]
1144    pub no_build_isolation_package: Option<Vec<PackageName>>,
1145    /// Additional build dependencies for packages.
1146    ///
1147    /// This allows extending the PEP 517 build environment for the project's dependencies with
1148    /// additional packages. This is useful for packages that assume the presence of packages like
1149    /// `pip`, and do not declare them as build dependencies.
1150    #[option(
1151        default = "[]",
1152        value_type = "dict",
1153        example = r#"
1154            extra-build-dependencies = { pytest = ["setuptools"] }
1155        "#
1156    )]
1157    pub extra_build_dependencies: Option<ExtraBuildDependencies>,
1158    /// Extra environment variables to set when building certain packages.
1159    ///
1160    /// Environment variables will be added to the environment when building the
1161    /// specified packages.
1162    #[option(
1163        default = r#"{}"#,
1164        value_type = r#"dict[str, dict[str, str]]"#,
1165        example = r#"
1166            extra-build-variables = { flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" } }
1167        "#
1168    )]
1169    pub extra_build_variables: Option<ExtraBuildVariables>,
1170    /// Limit candidate packages to those that were uploaded prior to the given date.
1171    ///
1172    /// The date is compared against the upload time of each individual distribution artifact
1173    /// (i.e., when each file was uploaded to the package index), not the release date of the
1174    /// package version.
1175    ///
1176    /// Accepts RFC 3339 timestamps (e.g., `2006-12-02T02:07:43Z`), a "friendly" duration (e.g.,
1177    /// `24 hours`, `1 week`, `30 days`), or an ISO 8601 duration (e.g., `PT24H`, `P7D`, `P30D`).
1178    ///
1179    /// Durations do not respect semantics of the local time zone and are always resolved to a fixed
1180    /// number of seconds assuming that a day is 24 hours (e.g., DST transitions are ignored).
1181    /// Calendar units such as months and years are not allowed.
1182    ///
1183    /// Set to `false` to disable `exclude-newer`.
1184    #[option(
1185        default = "None",
1186        value_type = "str | false",
1187        example = r#"
1188            exclude-newer = "2006-12-02T02:07:43Z"
1189        "#
1190    )]
1191    pub exclude_newer: Option<ExcludeNewerOverride>,
1192    /// Limit candidate packages for specific packages to those that were uploaded prior to the
1193    /// given date.
1194    ///
1195    /// Accepts a dictionary format of `PACKAGE = "DATE"` pairs, where `DATE` is an RFC 3339
1196    /// timestamp (e.g., `2006-12-02T02:07:43Z`), a "friendly" duration (e.g., `24 hours`, `1 week`,
1197    /// `30 days`), or a ISO 8601 duration (e.g., `PT24H`, `P7D`, `P30D`).
1198    ///
1199    /// Durations do not respect semantics of the local time zone and are always resolved to a fixed
1200    /// number of seconds assuming that a day is 24 hours (e.g., DST transitions are ignored).
1201    /// Calendar units such as months and years are not allowed.
1202    ///
1203    /// Set a package to `false` to exempt it from the global [`exclude-newer`](#exclude-newer)
1204    /// constraint entirely.
1205    #[option(
1206        default = "None",
1207        value_type = "dict",
1208        example = r#"
1209            exclude-newer-package = { tqdm = "2022-04-04T00:00:00Z", markupsafe = false }
1210        "#
1211    )]
1212    pub exclude_newer_package: Option<ExcludeNewerPackage>,
1213    /// The method to use when installing packages from the global cache.
1214    ///
1215    /// Defaults to `clone` (also known as Copy-on-Write) on macOS and Linux, and `hardlink` on
1216    /// Windows.
1217    ///
1218    /// WARNING: The use of symlink link mode is discouraged, as they create tight coupling between
1219    /// the cache and the target environment. For example, clearing the cache (`uv cache clean`)
1220    /// will break all installed packages by way of removing the underlying source files. Use
1221    /// symlinks with caution.
1222    #[option(
1223        default = "\"clone\" (macOS, Linux) or \"hardlink\" (Windows)",
1224        value_type = "str",
1225        example = r#"
1226            link-mode = "copy"
1227        "#,
1228        possible_values = true
1229    )]
1230    pub link_mode: Option<LinkMode>,
1231    /// Compile Python files to bytecode after installation.
1232    ///
1233    /// By default, uv does not compile Python (`.py`) files to bytecode (`__pycache__/*.pyc`);
1234    /// instead, compilation is performed lazily the first time a module is imported. For use-cases
1235    /// in which start time is critical, such as CLI applications and Docker containers, this option
1236    /// can be enabled to trade longer installation times for faster start times.
1237    ///
1238    /// When enabled, uv will process the entire site-packages directory (including packages that
1239    /// are not being modified by the current operation) for consistency. Like pip, it will also
1240    /// ignore errors.
1241    #[option(
1242        default = "false",
1243        value_type = "bool",
1244        example = r#"
1245            compile-bytecode = true
1246        "#
1247    )]
1248    pub compile_bytecode: Option<bool>,
1249    /// Ignore the `tool.uv.sources` table when resolving dependencies. Used to lock against the
1250    /// standards-compliant, publishable package metadata, as opposed to using any local or Git
1251    /// sources.
1252    #[option(
1253        default = "false",
1254        value_type = "bool",
1255        example = r#"
1256            no-sources = true
1257        "#
1258    )]
1259    pub no_sources: Option<bool>,
1260    /// Ignore `tool.uv.sources` for the specified packages.
1261    #[option(
1262        default = "[]",
1263        value_type = "list[str]",
1264        example = r#"
1265            no-sources-package = ["ruff"]
1266        "#
1267    )]
1268    pub no_sources_package: Option<Vec<PackageName>>,
1269    /// Allow package upgrades, ignoring pinned versions in any existing output file.
1270    #[option(
1271        default = "false",
1272        value_type = "bool",
1273        example = r#"
1274            upgrade = true
1275        "#
1276    )]
1277    pub upgrade: Option<bool>,
1278    /// Allow upgrades for a specific package, ignoring pinned versions in any existing output
1279    /// file.
1280    ///
1281    /// Accepts both standalone package names (`ruff`) and version specifiers (`ruff<0.5.0`).
1282    #[option(
1283        default = "[]",
1284        value_type = "list[str]",
1285        example = r#"
1286            upgrade-package = ["ruff"]
1287        "#
1288    )]
1289    pub upgrade_package: Option<Vec<Requirement<VerbatimParsedUrl>>>,
1290    /// Reinstall all packages, regardless of whether they're already installed. Implies `refresh`.
1291    #[option(
1292        default = "false",
1293        value_type = "bool",
1294        example = r#"
1295            reinstall = true
1296        "#
1297    )]
1298    pub reinstall: Option<bool>,
1299    /// Reinstall a specific package, regardless of whether it's already installed. Implies
1300    /// `refresh-package`.
1301    #[option(
1302        default = "[]",
1303        value_type = "list[str]",
1304        example = r#"
1305            reinstall-package = ["ruff"]
1306        "#
1307    )]
1308    pub reinstall_package: Option<Vec<PackageName>>,
1309    /// Don't build source distributions.
1310    ///
1311    /// When enabled, uv will reuse cached wheels from previously built source distributions, but
1312    /// operations that require building a source distribution will exit with an error. First-party
1313    /// packages, such as projects in the workspace, will still be built. uv will also still build
1314    /// editable requirements, and their build backends may run arbitrary Python code.
1315    #[option(
1316        default = "false",
1317        value_type = "bool",
1318        example = r#"
1319            no-build = true
1320        "#
1321    )]
1322    pub no_build: Option<bool>,
1323    /// Don't build source distributions for a specific package.
1324    ///
1325    /// First-party packages, such as projects in the workspace, will still be built.
1326    #[option(
1327        default = "[]",
1328        value_type = "list[str]",
1329        example = r#"
1330            no-build-package = ["ruff"]
1331        "#
1332    )]
1333    pub no_build_package: Option<Vec<PackageName>>,
1334    /// Don't install pre-built wheels.
1335    ///
1336    /// The given packages will be built and installed from source. The resolver will still use
1337    /// pre-built wheels to extract package metadata, if available.
1338    #[option(
1339        default = "false",
1340        value_type = "bool",
1341        example = r#"
1342            no-binary = true
1343        "#
1344    )]
1345    pub no_binary: Option<bool>,
1346    /// Don't install pre-built wheels for a specific package.
1347    #[option(
1348        default = "[]",
1349        value_type = "list[str]",
1350        example = r#"
1351            no-binary-package = ["ruff"]
1352        "#
1353    )]
1354    pub no_binary_package: Option<Vec<PackageName>>,
1355    /// The backend to use when fetching packages in the PyTorch ecosystem.
1356    ///
1357    /// When set, uv will ignore the configured index URLs for packages in the PyTorch ecosystem,
1358    /// and will instead use the defined backend.
1359    ///
1360    /// For example, when set to `cpu`, uv will use the CPU-only PyTorch index; when set to `cu126`,
1361    /// uv will use the PyTorch index for CUDA 12.6.
1362    ///
1363    /// The `auto` mode will attempt to detect the appropriate PyTorch index based on the currently
1364    /// installed CUDA drivers.
1365    ///
1366    /// This setting is only respected by `uv pip` commands.
1367    ///
1368    /// This option is in preview and may change in any future release.
1369    #[option(
1370        default = "null",
1371        value_type = "str",
1372        example = r#"
1373            torch-backend = "auto"
1374        "#
1375    )]
1376    pub torch_backend: Option<TorchMode>,
1377}
1378
1379/// Shared settings, relevant to all operations that might create managed python installations.
1380#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
1381#[serde(rename_all = "kebab-case")]
1382#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1383pub struct PythonInstallMirrors {
1384    /// Mirror URL for downloading managed Python installations.
1385    ///
1386    /// By default, managed Python installations are downloaded from [`python-build-standalone`](https://github.com/astral-sh/python-build-standalone).
1387    /// This variable can be set to a mirror URL to use a different source for Python installations.
1388    /// The provided URL will replace `https://github.com/astral-sh/python-build-standalone/releases/download` in, e.g., `https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz`.
1389    ///
1390    /// Distributions can be read from a local directory by using the `file://` URL scheme.
1391    #[option(
1392        default = "None",
1393        value_type = "str",
1394        uv_toml_only = true,
1395        example = r#"
1396            python-install-mirror = "https://github.com/astral-sh/python-build-standalone/releases/download"
1397        "#
1398    )]
1399    pub python_install_mirror: Option<String>,
1400    /// Mirror URL to use for downloading managed PyPy installations.
1401    ///
1402    /// By default, managed PyPy installations are downloaded from [downloads.python.org](https://downloads.python.org/).
1403    /// This variable can be set to a mirror URL to use a different source for PyPy installations.
1404    /// The provided URL will replace `https://downloads.python.org/pypy` in, e.g., `https://downloads.python.org/pypy/pypy3.8-v7.3.7-osx64.tar.bz2`.
1405    ///
1406    /// Distributions can be read from a
1407    /// local directory by using the `file://` URL scheme.
1408    #[option(
1409        default = "None",
1410        value_type = "str",
1411        uv_toml_only = true,
1412        example = r#"
1413            pypy-install-mirror = "https://downloads.python.org/pypy"
1414        "#
1415    )]
1416    pub pypy_install_mirror: Option<String>,
1417    /// Mirror URL to use for downloading managed GraalPy installations.
1418    ///
1419    /// By default, managed GraalPy installations are downloaded from [GitHub](https://github.com/oracle/graalpython/releases).
1420    /// This variable can be set to a mirror URL to use a different source for GraalPy installations.
1421    /// The provided URL will replace `https://github.com/oracle/graalpython/releases/download` in, e.g., `https://github.com/oracle/graalpython/releases/download/graal-24.2.2/graalpy-24.2.2-macos-aarch64.tar.gz`.
1422    ///
1423    /// Distributions can be read from a local directory by using the `file://` URL scheme.
1424    #[option(
1425        default = "None",
1426        value_type = "str",
1427        uv_toml_only = true,
1428        example = r#"
1429            graalpy-install-mirror = "https://github.com/oracle/graalpython/releases/download"
1430        "#
1431    )]
1432    pub graalpy_install_mirror: Option<String>,
1433    /// Mirror URL to use for downloading managed Pyodide installations.
1434    ///
1435    /// By default, managed Pyodide installations are downloaded from [GitHub](https://github.com/pyodide/pyodide/releases).
1436    /// This variable can be set to a mirror URL to use a different source for Pyodide installations.
1437    /// The provided URL will replace `https://github.com/pyodide/pyodide/releases/download` in, e.g., `https://github.com/pyodide/pyodide/releases/download/0.29.5/xbuildenv-0.29.5.tar.gz`.
1438    ///
1439    /// Distributions can be read from a local directory by using the `file://` URL scheme.
1440    #[option(
1441        default = "None",
1442        value_type = "str",
1443        uv_toml_only = true,
1444        example = r#"
1445            pyodide-install-mirror = "https://github.com/pyodide/pyodide/releases/download"
1446        "#
1447    )]
1448    pub pyodide_install_mirror: Option<String>,
1449
1450    /// URL pointing to JSON of custom Python installations.
1451    #[option(
1452        default = "None",
1453        value_type = "str",
1454        uv_toml_only = true,
1455        example = r#"
1456            python-downloads-json-url = "/etc/uv/python-downloads.json"
1457        "#
1458    )]
1459    pub python_downloads_json_url: Option<String>,
1460}
1461
1462impl PythonInstallMirrors {
1463    /// Return the mirrors to use for managed Python downloads.
1464    pub fn mirrors(&self) -> PythonDownloadMirrors<'_> {
1465        PythonDownloadMirrors {
1466            cpython: self.python_install_mirror.as_deref(),
1467            pypy: self.pypy_install_mirror.as_deref(),
1468            graalpy: self.graalpy_install_mirror.as_deref(),
1469            pyodide: self.pyodide_install_mirror.as_deref(),
1470        }
1471    }
1472
1473    #[must_use]
1474    pub fn combine(self, other: Self) -> Self {
1475        Self {
1476            python_install_mirror: self.python_install_mirror.or(other.python_install_mirror),
1477            pypy_install_mirror: self.pypy_install_mirror.or(other.pypy_install_mirror),
1478            graalpy_install_mirror: self.graalpy_install_mirror.or(other.graalpy_install_mirror),
1479            pyodide_install_mirror: self.pyodide_install_mirror.or(other.pyodide_install_mirror),
1480            python_downloads_json_url: self
1481                .python_downloads_json_url
1482                .or(other.python_downloads_json_url),
1483        }
1484    }
1485}
1486
1487/// Settings that are specific to the `uv pip` command-line interface.
1488///
1489/// These values will be ignored when running commands outside the `uv pip` namespace (e.g.,
1490/// `uv lock`, `uvx`).
1491#[derive(Debug, Clone, Default, Deserialize, CombineOptions, OptionsMetadata)]
1492#[serde(deny_unknown_fields, rename_all = "kebab-case")]
1493#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1494pub struct PipOptions {
1495    /// The Python interpreter into which packages should be installed.
1496    ///
1497    /// By default, uv installs into the virtual environment in the current working directory or
1498    /// any parent directory. The `--python` option allows you to specify a different interpreter,
1499    /// which is intended for use in continuous integration (CI) environments or other automated
1500    /// workflows.
1501    ///
1502    /// Supported formats:
1503    /// - `3.10` looks for an installed Python 3.10 in the registry on Windows (see
1504    ///   `py --list-paths`), or `python3.10` on Linux and macOS.
1505    /// - `python3.10` or `python.exe` looks for a binary with the given name in `PATH`.
1506    /// - `/home/ferris/.local/bin/python3.10` uses the exact Python at the given path.
1507    #[option(
1508        default = "None",
1509        value_type = "str",
1510        example = r#"
1511            python = "3.10"
1512        "#
1513    )]
1514    pub python: Option<String>,
1515    /// Install packages into the system Python environment.
1516    ///
1517    /// By default, uv installs into the virtual environment in the current working directory or
1518    /// any parent directory. The `--system` option instructs uv to instead use the first Python
1519    /// found in the system `PATH`.
1520    ///
1521    /// WARNING: `--system` is intended for use in continuous integration (CI) environments and
1522    /// should be used with caution, as it can modify the system Python installation.
1523    #[option(
1524        default = "false",
1525        value_type = "bool",
1526        example = r#"
1527            system = true
1528        "#
1529    )]
1530    pub system: Option<bool>,
1531    /// Allow uv to modify an `EXTERNALLY-MANAGED` Python installation.
1532    ///
1533    /// WARNING: `--break-system-packages` is intended for use in continuous integration (CI)
1534    /// environments, when installing into Python installations that are managed by an external
1535    /// package manager, like `apt`. It should be used with caution, as such Python installations
1536    /// explicitly recommend against modifications by other package managers (like uv or pip).
1537    #[option(
1538        default = "false",
1539        value_type = "bool",
1540        example = r#"
1541            break-system-packages = true
1542        "#
1543    )]
1544    pub break_system_packages: Option<bool>,
1545    /// Install packages into the specified directory, rather than into the virtual or system Python
1546    /// environment. The packages will be installed at the top-level of the directory.
1547    #[option(
1548        default = "None",
1549        value_type = "str",
1550        example = r#"
1551            target = "./target"
1552        "#
1553    )]
1554    pub target: Option<PathBuf>,
1555    /// Install packages into `lib`, `bin`, and other top-level folders under the specified
1556    /// directory, as if a virtual environment were present at that location.
1557    ///
1558    /// In general, prefer the use of `--python` to install into an alternate environment, as
1559    /// scripts and other artifacts installed via `--prefix` will reference the installing
1560    /// interpreter, rather than any interpreter added to the `--prefix` directory, rendering them
1561    /// non-portable.
1562    #[option(
1563        default = "None",
1564        value_type = "str",
1565        example = r#"
1566            prefix = "./prefix"
1567        "#
1568    )]
1569    pub prefix: Option<PathBuf>,
1570    #[serde(skip)]
1571    #[cfg_attr(feature = "schemars", schemars(skip))]
1572    pub index: Option<Vec<Index>>,
1573    #[serde(skip)]
1574    #[cfg_attr(feature = "schemars", schemars(skip))]
1575    pub proxy_index: Option<Vec<ProxyIndex>>,
1576    /// The URL of the Python package index (by default: <https://pypi.org/simple>).
1577    ///
1578    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
1579    /// (the simple repository API), or a local directory laid out in the same format.
1580    ///
1581    /// The index provided by this setting is given lower priority than any indexes specified via
1582    /// [`extra_index_url`](#extra-index-url).
1583    #[option(
1584        default = "\"https://pypi.org/simple\"",
1585        value_type = "str",
1586        example = r#"
1587            index-url = "https://test.pypi.org/simple"
1588        "#
1589    )]
1590    pub index_url: Option<PipIndex>,
1591    /// Extra URLs of package indexes to use, in addition to `--index-url`.
1592    ///
1593    /// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
1594    /// (the simple repository API), or a local directory laid out in the same format.
1595    ///
1596    /// All indexes provided via this flag take priority over the index specified by
1597    /// [`index_url`](#index-url). When multiple indexes are provided, earlier values take priority.
1598    ///
1599    /// To control uv's resolution strategy when multiple indexes are present, see
1600    /// [`index_strategy`](#index-strategy).
1601    #[option(
1602        default = "[]",
1603        value_type = "list[str]",
1604        example = r#"
1605            extra-index-url = ["https://download.pytorch.org/whl/cpu"]
1606        "#
1607    )]
1608    pub extra_index_url: Option<Vec<PipExtraIndex>>,
1609    /// Ignore all registry indexes (e.g., PyPI), instead relying on direct URL dependencies and
1610    /// those provided via `--find-links`.
1611    #[option(
1612        default = "false",
1613        value_type = "bool",
1614        example = r#"
1615            no-index = true
1616        "#
1617    )]
1618    pub no_index: Option<bool>,
1619    /// Locations to search for candidate distributions, in addition to those found in the registry
1620    /// indexes.
1621    ///
1622    /// If a path, the target must be a directory that contains packages as wheel files (`.whl`) or
1623    /// source distributions (e.g., `.tar.gz` or `.zip`) at the top level.
1624    ///
1625    /// If a URL, the page must contain a flat list of links to package files adhering to the
1626    /// formats described above.
1627    #[option(
1628        default = "[]",
1629        value_type = "list[str]",
1630        example = r#"
1631            find-links = ["https://download.pytorch.org/whl/torch_stable.html"]
1632        "#
1633    )]
1634    pub find_links: Option<Vec<PipFindLinks>>,
1635    /// The strategy to use when resolving against multiple index URLs.
1636    ///
1637    /// By default, uv will stop at the first index on which a given package is available, and
1638    /// limit resolutions to those present on that first index (`first-index`). This prevents
1639    /// "dependency confusion" attacks, whereby an attacker can upload a malicious package under the
1640    /// same name to an alternate index.
1641    #[option(
1642        default = "\"first-index\"",
1643        value_type = "str",
1644        example = r#"
1645            index-strategy = "unsafe-best-match"
1646        "#,
1647        possible_values = true
1648    )]
1649    pub index_strategy: Option<IndexStrategy>,
1650    /// Attempt to use `keyring` for authentication for index URLs.
1651    ///
1652    /// At present, only `--keyring-provider subprocess` is supported, which configures uv to
1653    /// use the `keyring` CLI to handle authentication.
1654    #[option(
1655        default = "disabled",
1656        value_type = "str",
1657        example = r#"
1658            keyring-provider = "subprocess"
1659        "#
1660    )]
1661    pub keyring_provider: Option<KeyringProviderType>,
1662    /// Don't build source distributions.
1663    ///
1664    /// When enabled, uv will reuse cached wheels from previously built source distributions, but
1665    /// operations that require building a source distribution will exit with an error. uv may
1666    /// still build editable requirements, and their build backends may run arbitrary Python code.
1667    ///
1668    /// Alias for `--only-binary :all:`.
1669    #[option(
1670        default = "false",
1671        value_type = "bool",
1672        example = r#"
1673            no-build = true
1674        "#
1675    )]
1676    pub no_build: Option<bool>,
1677    /// Don't install pre-built wheels.
1678    ///
1679    /// The given packages will be built and installed from source. The resolver will still use
1680    /// pre-built wheels to extract package metadata, if available.
1681    ///
1682    /// Multiple packages may be provided. Disable binaries for all packages with `:all:`.
1683    /// Clear previously specified packages with `:none:`.
1684    #[option(
1685        default = "[]",
1686        value_type = "list[str]",
1687        example = r#"
1688            no-binary = ["ruff"]
1689        "#
1690    )]
1691    pub no_binary: Option<Vec<PackageNameSpecifier>>,
1692    /// Only use pre-built wheels; don't build source distributions.
1693    ///
1694    /// When enabled, uv will reuse cached wheels from previously built source distributions, but
1695    /// operations that require building a source distribution for the given packages will exit
1696    /// with an error. uv may still build editable requirements, and their build backends may run
1697    /// arbitrary Python code.
1698    ///
1699    /// Multiple packages may be provided. Disable binaries for all packages with `:all:`.
1700    /// Clear previously specified packages with `:none:`.
1701    #[option(
1702        default = "[]",
1703        value_type = "list[str]",
1704        example = r#"
1705            only-binary = ["ruff"]
1706        "#
1707    )]
1708    pub only_binary: Option<Vec<PackageNameSpecifier>>,
1709    /// Disable isolation when building source distributions.
1710    ///
1711    /// Assumes that build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
1712    /// are already installed.
1713    #[option(
1714        default = "false",
1715        value_type = "bool",
1716        example = r#"
1717            no-build-isolation = true
1718        "#
1719    )]
1720    pub no_build_isolation: Option<bool>,
1721    /// Require hashes for all build dependencies in `uv pip` commands.
1722    ///
1723    /// Overrides `require-build-hashes` in `[tool.uv]`. This does not require hashes for runtime
1724    /// dependencies; use `require-hashes` for those.
1725    #[option(
1726        default = "false",
1727        value_type = "bool",
1728        example = r#"
1729            require-build-hashes = true
1730        "#
1731    )]
1732    pub require_build_hashes: Option<bool>,
1733    /// Disable isolation when building source distributions for a specific package.
1734    ///
1735    /// Assumes that the packages' build dependencies specified by [PEP 518](https://peps.python.org/pep-0518/)
1736    /// are already installed.
1737    #[option(
1738        default = "[]",
1739        value_type = "list[str]",
1740        example = r#"
1741            no-build-isolation-package = ["package1", "package2"]
1742        "#
1743    )]
1744    pub no_build_isolation_package: Option<Vec<PackageName>>,
1745    /// Additional build dependencies for packages.
1746    ///
1747    /// This allows extending the PEP 517 build environment for the project's dependencies with
1748    /// additional packages. This is useful for packages that assume the presence of packages like
1749    /// `pip`, and do not declare them as build dependencies.
1750    #[option(
1751        default = "[]",
1752        value_type = "dict",
1753        example = r#"
1754            extra-build-dependencies = { pytest = ["setuptools"] }
1755        "#
1756    )]
1757    pub extra_build_dependencies: Option<ExtraBuildDependencies>,
1758    /// Extra environment variables to set when building certain packages.
1759    ///
1760    /// Environment variables will be added to the environment when building the
1761    /// specified packages.
1762    #[option(
1763        default = r#"{}"#,
1764        value_type = r#"dict[str, dict[str, str]]"#,
1765        example = r#"
1766            extra-build-variables = { flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" } }
1767        "#
1768    )]
1769    pub extra_build_variables: Option<ExtraBuildVariables>,
1770    /// Validate the Python environment, to detect packages with missing dependencies and other
1771    /// issues.
1772    #[option(
1773        default = "false",
1774        value_type = "bool",
1775        example = r#"
1776            strict = true
1777        "#
1778    )]
1779    pub strict: Option<bool>,
1780    /// Include optional dependencies from the specified extra; may be provided more than once.
1781    ///
1782    /// Only applies to `pyproject.toml`, `setup.py`, and `setup.cfg` sources.
1783    #[option(
1784        default = "[]",
1785        value_type = "list[str]",
1786        example = r#"
1787            extra = ["dev", "docs"]
1788        "#
1789    )]
1790    pub extra: Option<Vec<ExtraName>>,
1791    /// Include all optional dependencies.
1792    ///
1793    /// Only applies to `pyproject.toml`, `setup.py`, and `setup.cfg` sources.
1794    #[option(
1795        default = "false",
1796        value_type = "bool",
1797        example = r#"
1798            all-extras = true
1799        "#
1800    )]
1801    pub all_extras: Option<bool>,
1802    /// Exclude the specified optional dependencies if `all-extras` is supplied.
1803    #[option(
1804        default = "[]",
1805        value_type = "list[str]",
1806        example = r#"
1807            all-extras = true
1808            no-extra = ["dev", "docs"]
1809        "#
1810    )]
1811    pub no_extra: Option<Vec<ExtraName>>,
1812    /// Ignore package dependencies, instead only add those packages explicitly listed
1813    /// on the command line to the resulting requirements file.
1814    #[option(
1815        default = "false",
1816        value_type = "bool",
1817        example = r#"
1818            no-deps = true
1819        "#
1820    )]
1821    pub no_deps: Option<bool>,
1822    /// Include the following dependency groups.
1823    #[option(
1824        default = "None",
1825        value_type = "list[str]",
1826        example = r#"
1827            group = ["dev", "docs"]
1828        "#
1829    )]
1830    pub group: Option<Vec<PipGroupName>>,
1831    /// Allow `uv pip sync` with empty requirements, which will clear the environment of all
1832    /// packages.
1833    #[option(
1834        default = "false",
1835        value_type = "bool",
1836        example = r#"
1837            allow-empty-requirements = true
1838        "#
1839    )]
1840    pub allow_empty_requirements: Option<bool>,
1841    /// The strategy to use when selecting between the different compatible versions for a given
1842    /// package requirement.
1843    ///
1844    /// By default, uv will use the latest compatible version of each package (`highest`).
1845    #[option(
1846        default = "\"highest\"",
1847        value_type = "str",
1848        example = r#"
1849            resolution = "lowest-direct"
1850        "#,
1851        possible_values = true
1852    )]
1853    pub resolution: Option<ResolutionMode>,
1854    /// The strategy to use when considering pre-release versions.
1855    ///
1856    /// By default, uv will prefer stable candidates, falling back to pre-releases only after every
1857    /// stable candidate that satisfies the active constraints is rejected
1858    /// (`if-necessary`).
1859    #[option(
1860        default = "\"if-necessary\"",
1861        value_type = "str",
1862        example = r#"
1863            prerelease = "allow"
1864        "#,
1865        possible_values = true
1866    )]
1867    pub prerelease: Option<PrereleaseMode>,
1868    #[serde(skip)]
1869    #[cfg_attr(feature = "schemars", schemars(skip))]
1870    pub prerelease_package: Option<PrereleasePackage>,
1871    /// The strategy to use when selecting multiple versions of a given package across Python
1872    /// versions and platforms.
1873    ///
1874    /// By default, uv will optimize for selecting the latest version of each package for each
1875    /// supported Python version (`requires-python`), while minimizing the number of selected
1876    /// versions across platforms.
1877    ///
1878    /// Under `fewest`, uv will minimize the number of selected versions for each package,
1879    /// preferring older versions that are compatible with a wider range of supported Python
1880    /// versions or platforms.
1881    #[option(
1882        default = "\"requires-python\"",
1883        value_type = "str",
1884        example = r#"
1885            fork-strategy = "fewest"
1886        "#,
1887        possible_values = true
1888    )]
1889    pub fork_strategy: Option<ForkStrategy>,
1890    /// Pre-defined static metadata for dependencies of the project (direct or transitive). When
1891    /// provided, enables the resolver to use the specified metadata instead of querying the
1892    /// registry or building the relevant package from source.
1893    ///
1894    /// Metadata should be provided in adherence with the [Metadata 2.3](https://packaging.python.org/en/latest/specifications/core-metadata/)
1895    /// standard, though only the following fields are respected:
1896    ///
1897    /// - `name`: The name of the package.
1898    /// - (Optional) `version`: The version of the package. If omitted, the metadata will be applied
1899    ///   to all versions of the package.
1900    /// - (Optional) `requires-dist`: The dependencies of the package (e.g., `werkzeug>=0.14`).
1901    /// - (Optional) `requires-python`: The Python version required by the package (e.g., `>=3.10`).
1902    /// - (Optional) `provides-extra`: The extras provided by the package.
1903    #[option(
1904        default = r#"[]"#,
1905        value_type = "list[dict]",
1906        example = r#"
1907            dependency-metadata = [
1908                { name = "flask", version = "1.0.0", requires-dist = ["werkzeug"], requires-python = ">=3.6" },
1909            ]
1910        "#
1911    )]
1912    pub dependency_metadata: Option<Vec<StaticMetadata>>,
1913    /// Write the requirements generated by `uv pip compile` to the given `requirements.txt` file.
1914    ///
1915    /// If the file already exists, the existing versions will be preferred when resolving
1916    /// dependencies, unless `--upgrade` is also specified.
1917    #[option(
1918        default = "None",
1919        value_type = "str",
1920        example = r#"
1921            output-file = "requirements.txt"
1922        "#
1923    )]
1924    pub output_file: Option<PathBuf>,
1925    /// Include extras in the output file.
1926    ///
1927    /// By default, uv strips extras, as any packages pulled in by the extras are already included
1928    /// as dependencies in the output file directly. Further, output files generated with
1929    /// `--no-strip-extras` cannot be used as constraints files in `install` and `sync` invocations.
1930    #[option(
1931        default = "false",
1932        value_type = "bool",
1933        example = r#"
1934            no-strip-extras = true
1935        "#
1936    )]
1937    pub no_strip_extras: Option<bool>,
1938    /// Include environment markers in the output file generated by `uv pip compile`.
1939    ///
1940    /// By default, uv strips environment markers, as the resolution generated by `compile` is
1941    /// only guaranteed to be correct for the target environment.
1942    #[option(
1943        default = "false",
1944        value_type = "bool",
1945        example = r#"
1946            no-strip-markers = true
1947        "#
1948    )]
1949    pub no_strip_markers: Option<bool>,
1950    /// Exclude comment annotations indicating the source of each package from the output file
1951    /// generated by `uv pip compile`.
1952    #[option(
1953        default = "false",
1954        value_type = "bool",
1955        example = r#"
1956            no-annotate = true
1957        "#
1958    )]
1959    pub no_annotate: Option<bool>,
1960    /// Exclude the comment header at the top of output file generated by `uv pip compile`.
1961    #[option(
1962        default = r#"false"#,
1963        value_type = "bool",
1964        example = r#"
1965            no-header = true
1966        "#
1967    )]
1968    pub no_header: Option<bool>,
1969    /// The header comment to include at the top of the output file generated by `uv pip compile`.
1970    ///
1971    /// Used to reflect custom build scripts and commands that wrap `uv pip compile`.
1972    #[option(
1973        default = "None",
1974        value_type = "str",
1975        example = r#"
1976            custom-compile-command = "./custom-uv-compile.sh"
1977        "#
1978    )]
1979    pub custom_compile_command: Option<String>,
1980    /// Include distribution hashes in the output file.
1981    #[option(
1982        default = "false",
1983        value_type = "bool",
1984        example = r#"
1985            generate-hashes = true
1986        "#
1987    )]
1988    pub generate_hashes: Option<bool>,
1989    /// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend,
1990    /// specified as `KEY=VALUE` pairs.
1991    #[option(
1992        default = "{}",
1993        value_type = "dict",
1994        example = r#"
1995            config-settings = { editable_mode = "compat" }
1996        "#
1997    )]
1998    pub config_settings: Option<ConfigSettings>,
1999    /// Settings to pass to the [PEP 517](https://peps.python.org/pep-0517/) build backend for specific packages,
2000    /// specified as `KEY=VALUE` pairs.
2001    #[option(
2002        default = "{}",
2003        value_type = "dict",
2004        example = r#"
2005            config-settings-package = { numpy = { editable_mode = "compat" } }
2006        "#
2007    )]
2008    pub config_settings_package: Option<PackageConfigSettings>,
2009    /// The minimum Python version that should be supported by the resolved requirements (e.g.,
2010    /// `3.8` or `3.8.17`).
2011    ///
2012    /// If a patch version is omitted, the minimum patch version is assumed. For example, `3.8` is
2013    /// mapped to `3.8.0`.
2014    #[option(
2015        default = "None",
2016        value_type = "str",
2017        example = r#"
2018            python-version = "3.8"
2019        "#
2020    )]
2021    pub python_version: Option<PythonVersion>,
2022    /// The platform for which requirements should be resolved.
2023    ///
2024    /// Represented as a "target triple", a string that describes the target platform in terms of
2025    /// its CPU, vendor, and operating system name, like `x86_64-unknown-linux-gnu` or
2026    /// `aarch64-apple-darwin`.
2027    #[option(
2028        default = "None",
2029        value_type = "str",
2030        example = r#"
2031            python-platform = "x86_64-unknown-linux-gnu"
2032        "#
2033    )]
2034    pub python_platform: Option<TargetTriple>,
2035    /// Perform a universal resolution, attempting to generate a single `requirements.txt` output
2036    /// file that is compatible with all operating systems, architectures, and Python
2037    /// implementations.
2038    ///
2039    /// In universal mode, the current Python version (or user-provided `--python-version`) will be
2040    /// treated as a lower bound. For example, `--universal --python-version 3.7` would produce a
2041    /// universal resolution for Python 3.7 and later.
2042    #[option(
2043        default = "false",
2044        value_type = "bool",
2045        example = r#"
2046            universal = true
2047        "#
2048    )]
2049    pub universal: Option<bool>,
2050    /// Limit candidate packages to those that were uploaded prior to a given point in time.
2051    ///
2052    /// The date is compared against the upload time of each individual distribution artifact
2053    /// (i.e., when each file was uploaded to the package index), not the release date of the
2054    /// package version.
2055    ///
2056    /// Accepts RFC 3339 timestamps (e.g., `2006-12-02T02:07:43Z`), a "friendly" duration (e.g.,
2057    /// `24 hours`, `1 week`, `30 days`), or an ISO 8601 duration (e.g., `PT24H`, `P7D`, `P30D`).
2058    ///
2059    /// Durations do not respect semantics of the local time zone and are always resolved to a fixed
2060    /// number of seconds assuming that a day is 24 hours (e.g., DST transitions are ignored).
2061    /// Calendar units such as months and years are not allowed.
2062    ///
2063    /// Set to `false` to disable `exclude-newer`.
2064    #[option(
2065        default = "None",
2066        value_type = "str | false",
2067        example = r#"
2068            exclude-newer = "2006-12-02T02:07:43Z"
2069        "#
2070    )]
2071    pub exclude_newer: Option<ExcludeNewerOverride>,
2072    /// Limit candidate packages for specific packages to those that were uploaded prior to the given date.
2073    ///
2074    /// Accepts a dictionary format of `PACKAGE = "DATE"` pairs, where `DATE` is an RFC 3339
2075    /// timestamp (e.g., `2006-12-02T02:07:43Z`), a "friendly" duration (e.g., `24 hours`, `1 week`,
2076    /// `30 days`), or a ISO 8601 duration (e.g., `PT24H`, `P7D`, `P30D`).
2077    ///
2078    /// Durations do not respect semantics of the local time zone and are always resolved to a fixed
2079    /// number of seconds assuming that a day is 24 hours (e.g., DST transitions are ignored).
2080    /// Calendar units such as months and years are not allowed.
2081    ///
2082    /// Set a package to `false` to exempt it from the global [`exclude-newer`](#exclude-newer)
2083    /// constraint entirely.
2084    #[option(
2085        default = "None",
2086        value_type = "dict",
2087        example = r#"
2088            exclude-newer-package = { tqdm = "2022-04-04T00:00:00Z", markupsafe = false }
2089        "#
2090    )]
2091    pub exclude_newer_package: Option<ExcludeNewerPackage>,
2092    /// Specify a package to omit from the output resolution. Its dependencies will still be
2093    /// included in the resolution. Equivalent to pip-compile's `--unsafe-package` option.
2094    #[option(
2095        default = "[]",
2096        value_type = "list[str]",
2097        example = r#"
2098            no-emit-package = ["ruff"]
2099        "#
2100    )]
2101    pub no_emit_package: Option<Vec<PackageName>>,
2102    /// Include `--index-url` and `--extra-index-url` entries in the output file generated by `uv pip compile`.
2103    #[option(
2104        default = "false",
2105        value_type = "bool",
2106        example = r#"
2107            emit-index-url = true
2108        "#
2109    )]
2110    pub emit_index_url: Option<bool>,
2111    /// Include `--find-links` entries in the output file generated by `uv pip compile`.
2112    #[option(
2113        default = "false",
2114        value_type = "bool",
2115        example = r#"
2116            emit-find-links = true
2117        "#
2118    )]
2119    pub emit_find_links: Option<bool>,
2120    /// Include `--no-binary` and `--only-binary` entries in the output file generated by `uv pip compile`.
2121    #[option(
2122        default = "false",
2123        value_type = "bool",
2124        example = r#"
2125            emit-build-options = true
2126        "#
2127    )]
2128    pub emit_build_options: Option<bool>,
2129    /// Whether to emit a marker string indicating the conditions under which the set of pinned
2130    /// dependencies is valid.
2131    ///
2132    /// The pinned dependencies may be valid even when the marker expression is
2133    /// false, but when the expression is true, the requirements are known to
2134    /// be correct.
2135    #[option(
2136        default = "false",
2137        value_type = "bool",
2138        example = r#"
2139            emit-marker-expression = true
2140        "#
2141    )]
2142    pub emit_marker_expression: Option<bool>,
2143    /// Include comment annotations indicating the index used to resolve each package (e.g.,
2144    /// `# from https://pypi.org/simple`).
2145    #[option(
2146        default = "false",
2147        value_type = "bool",
2148        example = r#"
2149            emit-index-annotation = true
2150        "#
2151    )]
2152    pub emit_index_annotation: Option<bool>,
2153    /// The style of the annotation comments included in the output file, used to indicate the
2154    /// source of each package.
2155    #[option(
2156        default = "\"split\"",
2157        value_type = "str",
2158        example = r#"
2159            annotation-style = "line"
2160        "#,
2161        possible_values = true
2162    )]
2163    pub annotation_style: Option<AnnotationStyle>,
2164    /// The method to use when installing packages from the global cache.
2165    ///
2166    /// Defaults to `clone` (also known as Copy-on-Write) on macOS and Linux, and `hardlink` on
2167    /// Windows.
2168    ///
2169    /// WARNING: The use of symlink link mode is discouraged, as they create tight coupling between
2170    /// the cache and the target environment. For example, clearing the cache (`uv cache clean`)
2171    /// will break all installed packages by way of removing the underlying source files. Use
2172    /// symlinks with caution.
2173    #[option(
2174        default = "\"clone\" (macOS, Linux) or \"hardlink\" (Windows)",
2175        value_type = "str",
2176        example = r#"
2177            link-mode = "copy"
2178        "#,
2179        possible_values = true
2180    )]
2181    pub link_mode: Option<LinkMode>,
2182    /// Compile Python files to bytecode after installation.
2183    ///
2184    /// By default, uv does not compile Python (`.py`) files to bytecode (`__pycache__/*.pyc`);
2185    /// instead, compilation is performed lazily the first time a module is imported. For use-cases
2186    /// in which start time is critical, such as CLI applications and Docker containers, this option
2187    /// can be enabled to trade longer installation times for faster start times.
2188    ///
2189    /// When enabled, uv will process the entire site-packages directory (including packages that
2190    /// are not being modified by the current operation) for consistency. Like pip, it will also
2191    /// ignore errors.
2192    #[option(
2193        default = "false",
2194        value_type = "bool",
2195        example = r#"
2196            compile-bytecode = true
2197        "#
2198    )]
2199    pub compile_bytecode: Option<bool>,
2200    /// Require a matching hash for each requirement.
2201    ///
2202    /// Hash-checking mode is all or nothing. If enabled, _all_ requirements must be provided
2203    /// with a corresponding hash or set of hashes. Additionally, if enabled, _all_ requirements
2204    /// must either be pinned to exact versions (e.g., `==1.0.0`), or be specified via direct URL.
2205    ///
2206    /// Hash-checking mode introduces a number of additional constraints:
2207    ///
2208    /// - Git dependencies are not supported.
2209    /// - Editable installations are not supported.
2210    /// - Local dependencies are not supported, unless they point to a specific wheel (`.whl`) or
2211    ///   source archive (`.zip`, `.tar.gz`), as opposed to a directory.
2212    #[option(
2213        default = "false",
2214        value_type = "bool",
2215        example = r#"
2216            require-hashes = true
2217        "#
2218    )]
2219    pub require_hashes: Option<bool>,
2220    /// Validate any hashes provided in the requirements file.
2221    ///
2222    /// Unlike `--require-hashes`, `--verify-hashes` does not require that all requirements have
2223    /// hashes; instead, it will limit itself to verifying the hashes of those requirements that do
2224    /// include them.
2225    #[option(
2226        default = "true",
2227        value_type = "bool",
2228        example = r#"
2229            verify-hashes = true
2230        "#
2231    )]
2232    pub verify_hashes: Option<bool>,
2233    /// Ignore the `tool.uv.sources` table when resolving dependencies. Used to lock against the
2234    /// standards-compliant, publishable package metadata, as opposed to using any local or Git
2235    /// sources.
2236    #[option(
2237        default = "false",
2238        value_type = "bool",
2239        example = r#"
2240            no-sources = true
2241        "#
2242    )]
2243    pub no_sources: Option<bool>,
2244    /// Ignore `tool.uv.sources` for the specified packages.
2245    #[option(
2246        default = "[]",
2247        value_type = "list[str]",
2248        example = r#"
2249            no-sources-package = ["ruff"]
2250        "#
2251    )]
2252    pub no_sources_package: Option<Vec<PackageName>>,
2253    /// Allow package upgrades, ignoring pinned versions in any existing output file.
2254    #[option(
2255        default = "false",
2256        value_type = "bool",
2257        example = r#"
2258            upgrade = true
2259        "#
2260    )]
2261    pub upgrade: Option<bool>,
2262    /// Allow upgrades for a specific package, ignoring pinned versions in any existing output
2263    /// file.
2264    ///
2265    /// Accepts both standalone package names (`ruff`) and version specifiers (`ruff<0.5.0`).
2266    #[option(
2267        default = "[]",
2268        value_type = "list[str]",
2269        example = r#"
2270            upgrade-package = ["ruff"]
2271        "#
2272    )]
2273    pub upgrade_package: Option<Vec<Requirement<VerbatimParsedUrl>>>,
2274    /// Reinstall all packages, regardless of whether they're already installed. Implies `refresh`.
2275    #[option(
2276        default = "false",
2277        value_type = "bool",
2278        example = r#"
2279            reinstall = true
2280        "#
2281    )]
2282    pub reinstall: Option<bool>,
2283    /// Reinstall a specific package, regardless of whether it's already installed. Implies
2284    /// `refresh-package`.
2285    #[option(
2286        default = "[]",
2287        value_type = "list[str]",
2288        example = r#"
2289            reinstall-package = ["ruff"]
2290        "#
2291    )]
2292    pub reinstall_package: Option<Vec<PackageName>>,
2293    /// The backend to use when fetching packages in the PyTorch ecosystem.
2294    ///
2295    /// When set, uv will ignore the configured index URLs for packages in the PyTorch ecosystem,
2296    /// and will instead use the defined backend.
2297    ///
2298    /// For example, when set to `cpu`, uv will use the CPU-only PyTorch index; when set to `cu126`,
2299    /// uv will use the PyTorch index for CUDA 12.6.
2300    ///
2301    /// The `auto` mode will attempt to detect the appropriate PyTorch index based on the currently
2302    /// installed CUDA drivers.
2303    ///
2304    /// This setting is only respected by `uv pip` commands.
2305    ///
2306    /// This option is in preview and may change in any future release.
2307    #[option(
2308        default = "null",
2309        value_type = "str",
2310        example = r#"
2311            torch-backend = "auto"
2312        "#
2313    )]
2314    pub torch_backend: Option<TorchMode>,
2315}
2316
2317impl PipOptions {
2318    /// Resolve the [`PipOptions`] relative to the given root directory.
2319    fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> {
2320        rebase_indexes(
2321            root_dir,
2322            &mut self.index,
2323            &mut self.index_url,
2324            &mut self.extra_index_url,
2325            &mut self.find_links,
2326        )?;
2327
2328        Ok(self)
2329    }
2330}
2331
2332impl From<ResolverInstallerSchema> for ResolverOptions {
2333    fn from(value: ResolverInstallerSchema) -> Self {
2334        Self {
2335            indexes: IndexOptions {
2336                index: value.index,
2337                proxy_index: value.proxy_index,
2338                index_url: value.index_url,
2339                extra_index_url: value.extra_index_url,
2340                no_index: value.no_index,
2341                find_links: value.find_links,
2342            },
2343            index_strategy: value.index_strategy,
2344            keyring_provider: value.keyring_provider,
2345            resolution: value.resolution,
2346            prerelease: value.prerelease,
2347            prerelease_package: value.prerelease_package,
2348            fork_strategy: value.fork_strategy,
2349            dependency_metadata: value.dependency_metadata,
2350            config_settings: value.config_settings,
2351            config_settings_package: value.config_settings_package,
2352            require_build_hashes: value.require_build_hashes,
2353            exclude_newer: value.exclude_newer,
2354            exclude_newer_package: value.exclude_newer_package,
2355            link_mode: value.link_mode,
2356            upgrade: Upgrade::from_args(
2357                value.upgrade,
2358                value
2359                    .upgrade_package
2360                    .into_iter()
2361                    .flatten()
2362                    .map(Into::into)
2363                    .collect(),
2364                Vec::new(),
2365            ),
2366            no_build: value.no_build,
2367            no_build_package: value.no_build_package,
2368            no_binary: value.no_binary,
2369            no_binary_package: value.no_binary_package,
2370            build_isolation: BuildIsolation::from_args(
2371                value.no_build_isolation,
2372                value.no_build_isolation_package.unwrap_or_default(),
2373            ),
2374            extra_build_dependencies: value.extra_build_dependencies,
2375            extra_build_variables: value.extra_build_variables,
2376            no_sources: value.no_sources,
2377            no_sources_package: value.no_sources_package,
2378            torch_backend: value.torch_backend,
2379        }
2380    }
2381}
2382
2383impl From<ResolverInstallerSchema> for InstallerOptions {
2384    fn from(value: ResolverInstallerSchema) -> Self {
2385        Self {
2386            index: value.index,
2387            proxy_index: value.proxy_index,
2388            index_url: value.index_url,
2389            extra_index_url: value.extra_index_url,
2390            no_index: value.no_index,
2391            find_links: value.find_links,
2392            index_strategy: value.index_strategy,
2393            keyring_provider: value.keyring_provider,
2394            config_settings: value.config_settings,
2395            exclude_newer: value.exclude_newer,
2396            link_mode: value.link_mode,
2397            compile_bytecode: value.compile_bytecode,
2398            reinstall: Reinstall::from_args(
2399                value.reinstall,
2400                value.reinstall_package.unwrap_or_default(),
2401            ),
2402            build_isolation: BuildIsolation::from_args(
2403                value.no_build_isolation,
2404                value.no_build_isolation_package.unwrap_or_default(),
2405            ),
2406            no_build: value.no_build,
2407            no_build_package: value.no_build_package,
2408            no_binary: value.no_binary,
2409            no_binary_package: value.no_binary_package,
2410            no_sources: value.no_sources,
2411            no_sources_package: value.no_sources_package,
2412        }
2413    }
2414}
2415
2416/// The options persisted alongside an installed tool.
2417///
2418/// A mirror of [`ResolverInstallerSchema`], without upgrades and reinstalls, which shouldn't be
2419/// persisted in a tool receipt.
2420#[derive(
2421    Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, CombineOptions, OptionsMetadata,
2422)]
2423#[serde(deny_unknown_fields, rename_all = "kebab-case")]
2424#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2425pub struct ToolOptions {
2426    index: Option<Vec<Index>>,
2427    proxy_index: Option<Vec<ProxyIndex>>,
2428    index_url: Option<PipIndex>,
2429    extra_index_url: Option<Vec<PipExtraIndex>>,
2430    no_index: Option<bool>,
2431    find_links: Option<Vec<PipFindLinks>>,
2432    index_strategy: Option<IndexStrategy>,
2433    keyring_provider: Option<KeyringProviderType>,
2434    resolution: Option<ResolutionMode>,
2435    prerelease: Option<PrereleaseMode>,
2436    prerelease_package: Option<PrereleasePackage>,
2437    fork_strategy: Option<ForkStrategy>,
2438    dependency_metadata: Option<Vec<StaticMetadata>>,
2439    config_settings: Option<ConfigSettings>,
2440    config_settings_package: Option<PackageConfigSettings>,
2441    build_isolation: Option<BuildIsolation>,
2442    require_build_hashes: Option<bool>,
2443    extra_build_dependencies: Option<ExtraBuildDependencies>,
2444    extra_build_variables: Option<ExtraBuildVariables>,
2445    exclude_newer: Option<ExcludeNewerOverride>,
2446    exclude_newer_package: Option<ExcludeNewerPackage>,
2447    link_mode: Option<LinkMode>,
2448    compile_bytecode: Option<bool>,
2449    no_sources: Option<bool>,
2450    no_sources_package: Option<Vec<PackageName>>,
2451    no_build: Option<bool>,
2452    no_build_package: Option<Vec<PackageName>>,
2453    no_binary: Option<bool>,
2454    no_binary_package: Option<Vec<PackageName>>,
2455    torch_backend: Option<TorchMode>,
2456}
2457
2458/// The on-disk representation of [`ToolOptions`] in a tool receipt.
2459#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2460#[serde(deny_unknown_fields, rename_all = "kebab-case")]
2461pub struct ToolOptionsWire {
2462    index: Option<Vec<Index>>,
2463    proxy_index: Option<Vec<ProxyIndex>>,
2464    index_url: Option<PipIndex>,
2465    extra_index_url: Option<Vec<PipExtraIndex>>,
2466    no_index: Option<bool>,
2467    find_links: Option<Vec<PipFindLinks>>,
2468    index_strategy: Option<IndexStrategy>,
2469    keyring_provider: Option<KeyringProviderType>,
2470    resolution: Option<ResolutionMode>,
2471    prerelease: Option<PrereleaseMode>,
2472    prerelease_package: Option<PrereleasePackage>,
2473    fork_strategy: Option<ForkStrategy>,
2474    dependency_metadata: Option<Vec<StaticMetadata>>,
2475    config_settings: Option<ConfigSettings>,
2476    config_settings_package: Option<PackageConfigSettings>,
2477    build_isolation: Option<BuildIsolation>,
2478    require_build_hashes: Option<bool>,
2479    extra_build_dependencies: Option<ExtraBuildDependencies>,
2480    extra_build_variables: Option<ExtraBuildVariables>,
2481    exclude_newer: Option<ExcludeNewerOverride>,
2482    exclude_newer_span: Option<ExcludeNewerSpan>,
2483    #[serde(serialize_with = "serialize_exclude_newer_package_with_spans")]
2484    exclude_newer_package: Option<ExcludeNewerPackage>,
2485    link_mode: Option<LinkMode>,
2486    compile_bytecode: Option<bool>,
2487    no_sources: Option<bool>,
2488    no_sources_package: Option<Vec<PackageName>>,
2489    no_build: Option<bool>,
2490    no_build_package: Option<Vec<PackageName>>,
2491    no_binary: Option<bool>,
2492    no_binary_package: Option<Vec<PackageName>>,
2493    torch_backend: Option<TorchMode>,
2494}
2495
2496impl From<ResolverInstallerOptions> for ToolOptions {
2497    fn from(value: ResolverInstallerOptions) -> Self {
2498        Self {
2499            index: value.indexes.index.map(|indexes| {
2500                indexes
2501                    .into_iter()
2502                    .map(Index::with_promoted_auth_policy)
2503                    .collect()
2504            }),
2505            proxy_index: value.indexes.proxy_index.map(|proxies| {
2506                proxies
2507                    .into_iter()
2508                    .map(ProxyIndex::with_promoted_auth_policy)
2509                    .collect()
2510            }),
2511            index_url: value.indexes.index_url,
2512            extra_index_url: value.indexes.extra_index_url,
2513            no_index: value.indexes.no_index,
2514            find_links: value.indexes.find_links,
2515            index_strategy: value.index_strategy,
2516            keyring_provider: value.keyring_provider,
2517            resolution: value.resolution,
2518            prerelease: value.prerelease,
2519            prerelease_package: value.prerelease_package,
2520            fork_strategy: value.fork_strategy,
2521            dependency_metadata: value.dependency_metadata,
2522            config_settings: value.config_settings,
2523            config_settings_package: value.config_settings_package,
2524            build_isolation: value.build_isolation,
2525            require_build_hashes: value.require_build_hashes,
2526            extra_build_dependencies: value.extra_build_dependencies,
2527            extra_build_variables: value.extra_build_variables,
2528            exclude_newer: value.exclude_newer,
2529            exclude_newer_package: value.exclude_newer_package,
2530            link_mode: value.link_mode,
2531            compile_bytecode: value.compile_bytecode,
2532            no_sources: value.no_sources,
2533            no_sources_package: value.no_sources_package,
2534            no_build: value.no_build,
2535            no_build_package: value.no_build_package,
2536            no_binary: value.no_binary,
2537            no_binary_package: value.no_binary_package,
2538            torch_backend: value.torch_backend,
2539        }
2540    }
2541}
2542
2543impl From<ToolOptionsWire> for ToolOptions {
2544    fn from(value: ToolOptionsWire) -> Self {
2545        let exclude_newer = value
2546            .exclude_newer
2547            .map(|exclude_newer| match exclude_newer {
2548                ExcludeNewerOverride::Disabled => ExcludeNewerOverride::Disabled,
2549                ExcludeNewerOverride::Enabled(exclude_newer) => {
2550                    let exclude_newer = *exclude_newer;
2551                    if let Some(span) = value.exclude_newer_span
2552                        && exclude_newer.span().is_none()
2553                    {
2554                        ExcludeNewerValue::relative(span).into()
2555                    } else {
2556                        exclude_newer.into()
2557                    }
2558                }
2559            });
2560
2561        Self {
2562            index: value.index,
2563            proxy_index: value.proxy_index,
2564            index_url: value.index_url,
2565            extra_index_url: value.extra_index_url,
2566            no_index: value.no_index,
2567            find_links: value.find_links,
2568            index_strategy: value.index_strategy,
2569            keyring_provider: value.keyring_provider,
2570            resolution: value.resolution,
2571            prerelease: value.prerelease,
2572            prerelease_package: value.prerelease_package,
2573            fork_strategy: value.fork_strategy,
2574            dependency_metadata: value.dependency_metadata,
2575            config_settings: value.config_settings,
2576            config_settings_package: value.config_settings_package,
2577            build_isolation: value.build_isolation,
2578            require_build_hashes: value.require_build_hashes,
2579            extra_build_dependencies: value.extra_build_dependencies,
2580            extra_build_variables: value.extra_build_variables,
2581            exclude_newer,
2582            exclude_newer_package: value.exclude_newer_package,
2583            link_mode: value.link_mode,
2584            compile_bytecode: value.compile_bytecode,
2585            no_sources: value.no_sources,
2586            no_sources_package: value.no_sources_package,
2587            no_build: value.no_build,
2588            no_build_package: value.no_build_package,
2589            no_binary: value.no_binary,
2590            no_binary_package: value.no_binary_package,
2591            torch_backend: value.torch_backend,
2592        }
2593    }
2594}
2595
2596impl From<ToolOptions> for ToolOptionsWire {
2597    fn from(value: ToolOptions) -> Self {
2598        let (exclude_newer, exclude_newer_span) = match &value.exclude_newer {
2599            Some(ExcludeNewerOverride::Disabled) => (Some(ExcludeNewerOverride::Disabled), None),
2600            Some(ExcludeNewerOverride::Enabled(value)) => match value.as_ref() {
2601                ExcludeNewerValue::Absolute(_) => {
2602                    (Some(ExcludeNewerOverride::Enabled(value.clone())), None)
2603                }
2604                ExcludeNewerValue::Relative(span) => (
2605                    Some(ExcludeNewerValue::absolute(value.timestamp()).into()),
2606                    Some(*span),
2607                ),
2608            },
2609            None => (None, None),
2610        };
2611
2612        Self {
2613            index: value.index,
2614            proxy_index: value.proxy_index,
2615            index_url: value.index_url,
2616            extra_index_url: value.extra_index_url,
2617            no_index: value.no_index,
2618            find_links: value.find_links,
2619            index_strategy: value.index_strategy,
2620            keyring_provider: value.keyring_provider,
2621            resolution: value.resolution,
2622            prerelease: value.prerelease,
2623            prerelease_package: value.prerelease_package,
2624            fork_strategy: value.fork_strategy,
2625            dependency_metadata: value.dependency_metadata,
2626            config_settings: value.config_settings,
2627            config_settings_package: value.config_settings_package,
2628            build_isolation: value.build_isolation,
2629            require_build_hashes: value.require_build_hashes,
2630            extra_build_dependencies: value.extra_build_dependencies,
2631            extra_build_variables: value.extra_build_variables,
2632            exclude_newer,
2633            exclude_newer_span,
2634            exclude_newer_package: value.exclude_newer_package,
2635            link_mode: value.link_mode,
2636            compile_bytecode: value.compile_bytecode,
2637            no_sources: value.no_sources,
2638            no_sources_package: value.no_sources_package,
2639            no_build: value.no_build,
2640            no_build_package: value.no_build_package,
2641            no_binary: value.no_binary,
2642            no_binary_package: value.no_binary_package,
2643            torch_backend: value.torch_backend,
2644        }
2645    }
2646}
2647
2648impl From<ToolOptions> for ResolverInstallerOptions {
2649    fn from(value: ToolOptions) -> Self {
2650        Self {
2651            indexes: IndexOptions {
2652                index: value.index,
2653                proxy_index: value.proxy_index,
2654                index_url: value.index_url,
2655                extra_index_url: value.extra_index_url,
2656                no_index: value.no_index,
2657                find_links: value.find_links,
2658            },
2659            index_strategy: value.index_strategy,
2660            keyring_provider: value.keyring_provider,
2661            resolution: value.resolution,
2662            prerelease: value.prerelease,
2663            prerelease_package: value.prerelease_package,
2664            fork_strategy: value.fork_strategy,
2665            dependency_metadata: value.dependency_metadata,
2666            config_settings: value.config_settings,
2667            config_settings_package: value.config_settings_package,
2668            build_isolation: value.build_isolation,
2669            require_build_hashes: value.require_build_hashes,
2670            extra_build_dependencies: value.extra_build_dependencies,
2671            extra_build_variables: value.extra_build_variables,
2672            exclude_newer: value.exclude_newer,
2673            exclude_newer_package: value.exclude_newer_package,
2674            link_mode: value.link_mode,
2675            compile_bytecode: value.compile_bytecode,
2676            no_sources: value.no_sources,
2677            no_sources_package: value.no_sources_package,
2678            upgrade: None,
2679            reinstall: None,
2680            no_build: value.no_build,
2681            no_build_package: value.no_build_package,
2682            no_binary: value.no_binary,
2683            no_binary_package: value.no_binary_package,
2684            torch_backend: value.torch_backend,
2685        }
2686    }
2687}
2688
2689/// Like [`Options]`, but with any `#[serde(flatten)]` fields inlined. This leads to far, far
2690/// better error messages when deserializing.
2691#[derive(Debug, Clone, Default, Deserialize)]
2692#[serde(rename_all = "kebab-case", deny_unknown_fields)]
2693struct OptionsWire {
2694    // #[serde(flatten)]
2695    // globals: GlobalOptions
2696    required_version: Option<RequiredVersion>,
2697    system_certs: Option<bool>,
2698    native_tls: Option<bool>,
2699    offline: Option<bool>,
2700    no_cache: Option<bool>,
2701    cache_dir: Option<PathBuf>,
2702    preview: Option<bool>,
2703    preview_features: Option<PreviewFeaturesOption>,
2704    python_preference: Option<PythonPreference>,
2705    python_downloads: Option<PythonDownloads>,
2706    concurrent_downloads: Option<NonZeroUsize>,
2707    concurrent_builds: Option<NonZeroUsize>,
2708    concurrent_installs: Option<NonZeroUsize>,
2709
2710    // #[serde(flatten)]
2711    // top_level: ResolverInstallerOptions
2712    index: Option<Vec<Index>>,
2713    proxy_index: Option<Vec<ProxyIndex>>,
2714    index_url: Option<PipIndex>,
2715    extra_index_url: Option<Vec<PipExtraIndex>>,
2716    no_index: Option<bool>,
2717    find_links: Option<Vec<PipFindLinks>>,
2718    index_strategy: Option<IndexStrategy>,
2719    keyring_provider: Option<KeyringProviderType>,
2720    http_proxy: Option<ProxyUrl>,
2721    https_proxy: Option<ProxyUrl>,
2722    no_proxy: Option<Vec<String>>,
2723    allow_insecure_host: Option<Vec<TrustedHost>>,
2724    resolution: Option<ResolutionMode>,
2725    prerelease: Option<PrereleaseMode>,
2726    prerelease_package: Option<PrereleasePackage>,
2727    fork_strategy: Option<ForkStrategy>,
2728    dependency_metadata: Option<Vec<StaticMetadata>>,
2729    config_settings: Option<ConfigSettings>,
2730    config_settings_package: Option<PackageConfigSettings>,
2731    no_build_isolation: Option<bool>,
2732    require_build_hashes: Option<bool>,
2733    no_build_isolation_package: Option<Vec<PackageName>>,
2734    extra_build_dependencies: Option<ExtraBuildDependencies>,
2735    extra_build_variables: Option<ExtraBuildVariables>,
2736    exclude_newer: Option<ExcludeNewerOverride>,
2737    exclude_newer_package: Option<ExcludeNewerPackage>,
2738    link_mode: Option<LinkMode>,
2739    compile_bytecode: Option<bool>,
2740    no_sources: Option<bool>,
2741    no_sources_package: Option<Vec<PackageName>>,
2742    upgrade: Option<bool>,
2743    upgrade_package: Option<Vec<Requirement<VerbatimParsedUrl>>>,
2744    reinstall: Option<bool>,
2745    reinstall_package: Option<Vec<PackageName>>,
2746    no_build: Option<bool>,
2747    no_build_package: Option<Vec<PackageName>>,
2748    no_binary: Option<bool>,
2749    no_binary_package: Option<Vec<PackageName>>,
2750    torch_backend: Option<TorchMode>,
2751
2752    // #[serde(flatten)]
2753    // install_mirror: PythonInstallMirrors,
2754    python_install_mirror: Option<String>,
2755    pypy_install_mirror: Option<String>,
2756    graalpy_install_mirror: Option<String>,
2757    pyodide_install_mirror: Option<String>,
2758    python_downloads_json_url: Option<String>,
2759
2760    // #[serde(flatten)]
2761    // publish: PublishOptions
2762    publish_url: Option<SafeUrl>,
2763    trusted_publishing: Option<TrustedPublishing>,
2764    check_url: Option<IndexUrl>,
2765
2766    // #[serde(flatten)]
2767    // add: AddOptions
2768    add_bounds: Option<AddBoundsKind>,
2769
2770    audit: Option<AuditOptions>,
2771    pip: Option<PipOptions>,
2772    cache_keys: Option<Vec<CacheKey>>,
2773
2774    // NOTE(charlie): These fields are shared with `ToolUv` in
2775    // `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
2776    // They're respected in both `pyproject.toml` and `uv.toml` files.
2777    override_dependencies: Option<Vec<OverrideDependency>>,
2778    exclude_dependencies: Option<Vec<ExcludeDependency>>,
2779    constraint_dependencies: Option<Vec<Requirement<VerbatimParsedUrl>>>,
2780    build_constraint_dependencies: Option<Vec<BuildConstraintDependency>>,
2781    environments: Option<SupportedEnvironments>,
2782    required_environments: Option<SupportedEnvironments>,
2783    minimum_libc_version: Option<MinimumLibcVersion>,
2784
2785    // NOTE(charlie): These fields should be kept in-sync with `ToolUv` in
2786    // `crates/uv-workspace/src/pyproject.rs`. The documentation lives on that struct.
2787    // They're only respected in `pyproject.toml` files, and should be rejected in `uv.toml` files.
2788    conflicts: Option<serde::de::IgnoredAny>,
2789    workspace: Option<serde::de::IgnoredAny>,
2790    sources: Option<serde::de::IgnoredAny>,
2791    managed: Option<serde::de::IgnoredAny>,
2792    r#package: Option<serde::de::IgnoredAny>,
2793    default_groups: Option<serde::de::IgnoredAny>,
2794    dependency_groups: Option<serde::de::IgnoredAny>,
2795    dev_dependencies: Option<serde::de::IgnoredAny>,
2796
2797    // Build backend
2798    build_backend: Option<serde::de::IgnoredAny>,
2799}
2800
2801impl TryFrom<OptionsWire> for Options {
2802    type Error = &'static str;
2803
2804    #[allow(deprecated)]
2805    fn try_from(value: OptionsWire) -> Result<Self, Self::Error> {
2806        let OptionsWire {
2807            required_version,
2808            system_certs,
2809            native_tls,
2810            offline,
2811            no_cache,
2812            cache_dir,
2813            preview,
2814            preview_features,
2815            python_preference,
2816            python_downloads,
2817            python_install_mirror,
2818            pypy_install_mirror,
2819            graalpy_install_mirror,
2820            pyodide_install_mirror,
2821            python_downloads_json_url,
2822            concurrent_downloads,
2823            concurrent_builds,
2824            concurrent_installs,
2825            index,
2826            proxy_index,
2827            index_url,
2828            extra_index_url,
2829            no_index,
2830            find_links,
2831            index_strategy,
2832            keyring_provider,
2833            http_proxy,
2834            https_proxy,
2835            no_proxy,
2836            allow_insecure_host,
2837            resolution,
2838            prerelease,
2839            prerelease_package,
2840            fork_strategy,
2841            dependency_metadata,
2842            config_settings,
2843            config_settings_package,
2844            no_build_isolation,
2845            require_build_hashes,
2846            no_build_isolation_package,
2847            exclude_newer,
2848            exclude_newer_package,
2849            link_mode,
2850            compile_bytecode,
2851            no_sources,
2852            no_sources_package,
2853            upgrade,
2854            upgrade_package,
2855            reinstall,
2856            reinstall_package,
2857            no_build,
2858            no_build_package,
2859            no_binary,
2860            no_binary_package,
2861            torch_backend,
2862            audit,
2863            pip,
2864            cache_keys,
2865            override_dependencies,
2866            exclude_dependencies,
2867            constraint_dependencies,
2868            build_constraint_dependencies,
2869            environments,
2870            required_environments,
2871            minimum_libc_version,
2872            conflicts,
2873            publish_url,
2874            trusted_publishing,
2875            check_url,
2876            workspace,
2877            sources,
2878            default_groups,
2879            dependency_groups,
2880            extra_build_dependencies,
2881            extra_build_variables,
2882            dev_dependencies,
2883            managed,
2884            package,
2885            add_bounds: bounds,
2886            // Used by the build backend
2887            build_backend,
2888        } = value;
2889
2890        Ok(Self {
2891            globals: GlobalOptions {
2892                required_version,
2893                system_certs,
2894                native_tls,
2895                offline,
2896                no_cache,
2897                cache_dir,
2898                preview: PreviewOption::try_from(preview, preview_features)?,
2899                python_preference,
2900                python_downloads,
2901                concurrent_downloads,
2902                concurrent_builds,
2903                concurrent_installs,
2904                http_proxy,
2905                https_proxy,
2906                no_proxy,
2907                // Used twice for backwards compatibility
2908                allow_insecure_host: allow_insecure_host.clone(),
2909            },
2910            top_level: ResolverInstallerSchema {
2911                index,
2912                proxy_index,
2913                index_url,
2914                extra_index_url,
2915                no_index,
2916                find_links,
2917                index_strategy,
2918                keyring_provider,
2919                resolution,
2920                prerelease,
2921                prerelease_package,
2922                fork_strategy,
2923                dependency_metadata,
2924                config_settings,
2925                config_settings_package,
2926                no_build_isolation,
2927                require_build_hashes,
2928                no_build_isolation_package,
2929                extra_build_dependencies,
2930                extra_build_variables,
2931                exclude_newer,
2932                exclude_newer_package,
2933                link_mode,
2934                compile_bytecode,
2935                no_sources,
2936                no_sources_package,
2937                upgrade,
2938                upgrade_package,
2939                reinstall,
2940                reinstall_package,
2941                no_build,
2942                no_build_package,
2943                no_binary,
2944                no_binary_package,
2945                torch_backend,
2946            },
2947            pip,
2948            cache_keys,
2949            build_backend,
2950            override_dependencies,
2951            exclude_dependencies,
2952            constraint_dependencies,
2953            build_constraint_dependencies,
2954            environments,
2955            required_environments,
2956            minimum_libc_version,
2957            install_mirrors: PythonInstallMirrors {
2958                python_install_mirror,
2959                pypy_install_mirror,
2960                graalpy_install_mirror,
2961                pyodide_install_mirror,
2962                python_downloads_json_url,
2963            },
2964            conflicts,
2965            publish: PublishOptions {
2966                publish_url,
2967                trusted_publishing,
2968                check_url,
2969            },
2970            add: AddOptions { add_bounds: bounds },
2971            audit,
2972            workspace,
2973            sources,
2974            dev_dependencies,
2975            default_groups,
2976            dependency_groups,
2977            managed,
2978            package,
2979        })
2980    }
2981}
2982
2983#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
2984#[serde(rename_all = "kebab-case")]
2985#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2986pub struct PublishOptions {
2987    /// The URL for publishing packages to the Python package index (by default:
2988    /// <https://upload.pypi.org/legacy/>).
2989    #[option(
2990        default = "\"https://upload.pypi.org/legacy/\"",
2991        value_type = "str",
2992        example = r#"
2993            publish-url = "https://test.pypi.org/legacy/"
2994        "#
2995    )]
2996    pub publish_url: Option<SafeUrl>,
2997
2998    /// Configure trusted publishing.
2999    ///
3000    /// By default, uv checks for trusted publishing when running in a supported environment, but
3001    /// ignores it if it isn't configured.
3002    ///
3003    /// uv's supported environments for trusted publishing include GitHub Actions and GitLab CI/CD.
3004    #[option(
3005        default = "automatic",
3006        value_type = "str",
3007        example = r#"
3008            trusted-publishing = "always"
3009        "#
3010    )]
3011    pub trusted_publishing: Option<TrustedPublishing>,
3012
3013    /// Check an index URL for existing files to skip duplicate uploads.
3014    ///
3015    /// This option allows retrying publishing that failed after only some, but not all files have
3016    /// been uploaded, and handles error due to parallel uploads of the same file.
3017    ///
3018    /// Before uploading, the index is checked. If the exact same file already exists in the index,
3019    /// the file will not be uploaded. If an error occurred during the upload, the index is checked
3020    /// again, to handle cases where the identical file was uploaded twice in parallel.
3021    ///
3022    /// The exact behavior will vary based on the index. When uploading to PyPI, uploading the same
3023    /// file succeeds even without `--check-url`, while most other indexes error.
3024    ///
3025    /// The index must provide one of the supported hashes (SHA-256, SHA-384, or SHA-512).
3026    #[option(
3027        default = "None",
3028        value_type = "str",
3029        example = r#"
3030            check-url = "https://test.pypi.org/simple"
3031        "#
3032    )]
3033    pub check_url: Option<IndexUrl>,
3034}
3035
3036#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
3037#[serde(rename_all = "kebab-case")]
3038#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3039pub struct AddOptions {
3040    /// The default version specifier when adding a dependency.
3041    ///
3042    /// When adding a dependency to the project, if no constraint or URL is provided, a constraint
3043    /// is added based on the latest compatible version of the package. By default, a lower bound
3044    /// constraint is used, e.g., `>=1.2.3`.
3045    ///
3046    /// When `--frozen` is provided, no resolution is performed, and dependencies are always added
3047    /// without constraints.
3048    ///
3049    /// This option is in preview and may change in any future release.
3050    #[option(
3051        default = "\"lower\"",
3052        value_type = "str",
3053        example = r#"
3054            add-bounds = "major"
3055        "#,
3056        possible_values = true
3057    )]
3058    pub add_bounds: Option<AddBoundsKind>,
3059}
3060
3061#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, CombineOptions, OptionsMetadata)]
3062#[serde(rename_all = "kebab-case")]
3063#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3064pub struct AuditOptions {
3065    /// Whether to run the automatic malware check during sync operations.
3066    #[option(
3067        default = "false",
3068        value_type = "bool",
3069        example = r#"
3070            malware-check = true
3071        "#
3072    )]
3073    pub malware_check: Option<bool>,
3074
3075    /// The vulnerability service URL to use for automatic malware checks.
3076    #[option(
3077        default = "\"https://api.osv.dev/\"",
3078        value_type = "str",
3079        example = r#"
3080            malware-check-url = "https://example.com"
3081        "#
3082    )]
3083    pub malware_check_url: Option<SafeUrl>,
3084
3085    /// A list of vulnerability IDs to ignore during auditing.
3086    ///
3087    /// Vulnerabilities matching any of the provided IDs (including aliases) will be excluded from
3088    /// the audit results.
3089    #[option(
3090        default = "[]",
3091        value_type = "list[str]",
3092        example = r#"
3093            ignore = ["PYSEC-2022-43017", "GHSA-5239-wwwm-4pmq"]
3094        "#
3095    )]
3096    pub ignore: Option<Vec<String>>,
3097
3098    /// A list of vulnerability IDs to ignore during auditing, but only while no fix is available.
3099    ///
3100    /// Vulnerabilities matching any of the provided IDs (including aliases) will be excluded from
3101    /// the audit results as long as they have no known fix versions. Once a fix version becomes
3102    /// available, the vulnerability will be reported again.
3103    #[option(
3104        default = "[]",
3105        value_type = "list[str]",
3106        example = r#"
3107            ignore-until-fixed = ["PYSEC-2022-43017"]
3108        "#
3109    )]
3110    pub ignore_until_fixed: Option<Vec<String>>,
3111}
3112
3113#[derive(Debug, Clone)]
3114pub struct MalwareCheckSettings {
3115    /// Whether the malware check is enabled.
3116    pub enabled: bool,
3117    /// The OSV-shaped service URL to use for malware checks.
3118    pub malware_check_url: Option<SafeUrl>,
3119}
3120
3121impl MalwareCheckSettings {
3122    pub fn resolve(
3123        filesystem: Option<&FilesystemOptions>,
3124        environment: &EnvironmentOptions,
3125    ) -> Self {
3126        let audit = filesystem.and_then(|options| options.audit.as_ref());
3127
3128        Self {
3129            enabled: environment
3130                .malware_check
3131                .value
3132                .or(audit.and_then(|audit| audit.malware_check))
3133                .unwrap_or_default(),
3134            malware_check_url: environment
3135                .malware_check_url
3136                .clone()
3137                .or_else(|| audit.and_then(|audit| audit.malware_check_url.clone())),
3138        }
3139    }
3140}
3141
3142/// Represents the `preview-features` configuration option.
3143#[derive(Debug, Clone, DeserializeUntagged)]
3144#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3145#[cfg_attr(feature = "schemars", schemars(untagged))]
3146#[serde(expecting = "a boolean or a list of preview feature names")]
3147pub enum PreviewFeaturesOption {
3148    #[untagged(bool)]
3149    Toggle(bool),
3150    #[untagged(seq)]
3151    Features(Vec<MaybePreviewFeature>),
3152}
3153
3154#[expect(
3155    dead_code,
3156    reason = "Fields are only used by the OptionsMetadata and JsonSchema derives"
3157)]
3158#[derive(OptionsMetadata)]
3159#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3160#[cfg_attr(feature = "schemars", schemars(rename_all = "kebab-case"))]
3161struct PreviewOptionsDefinition {
3162    // This legacy setting remains supported and included in the JSON schema, but is omitted from
3163    // option metadata so the generated settings reference documents only `preview-features`.
3164    /// Whether to enable all experimental, preview features.
3165    ///
3166    /// Use `preview-features` instead.
3167    #[deprecated(note = "use `preview-features` instead")]
3168    preview: Option<bool>,
3169    /// Whether to enable specific or all experimental preview features.
3170    ///
3171    /// Unknown feature names are ignored with a warning.
3172    #[option(
3173        default = "false",
3174        value_type = "bool | list[str]",
3175        example = r#"
3176            preview-features = true
3177            # or
3178            preview-features = ["json-output"]
3179        "#
3180    )]
3181    preview_features: Option<PreviewFeaturesOption>,
3182}
3183
3184/// Represents the user's preview configuration from either `preview` or `preview-features`.
3185#[derive(Debug, Clone)]
3186pub enum PreviewOption {
3187    /// Whether to enable all experimental, preview features.
3188    Preview(bool),
3189    /// Whether to enable specific or all experimental preview features.
3190    PreviewFeatures(PreviewFeaturesOption),
3191}
3192
3193impl uv_options_metadata::OptionsMetadata for PreviewOption {
3194    fn record(visit: &mut dyn uv_options_metadata::Visit) {
3195        <PreviewOptionsDefinition as uv_options_metadata::OptionsMetadata>::record(visit);
3196    }
3197}
3198
3199#[cfg(feature = "schemars")]
3200struct ConflictingPreviewOptions;
3201
3202#[cfg(feature = "schemars")]
3203impl schemars::JsonSchema for ConflictingPreviewOptions {
3204    fn schema_name() -> Cow<'static, str> {
3205        Cow::Borrowed("ConflictingPreviewOptions")
3206    }
3207
3208    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
3209        schemars::json_schema!({
3210            "type": "object",
3211            "properties": {
3212                "preview": {},
3213                "preview-features": {},
3214            },
3215            "required": ["preview", "preview-features"],
3216        })
3217    }
3218}
3219
3220#[cfg(feature = "schemars")]
3221impl schemars::JsonSchema for PreviewOption {
3222    fn schema_name() -> Cow<'static, str> {
3223        Cow::Borrowed("PreviewOption")
3224    }
3225
3226    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
3227        let mut schema = <PreviewOptionsDefinition as schemars::JsonSchema>::json_schema(generator);
3228        // Keep this constraint in a referenced schema to avoid a fastjsonschema code-generation
3229        // bug. See: https://github.com/astral-sh/uv/pull/20547.
3230        schema.insert(
3231            "not".to_string(),
3232            generator
3233                .subschema_for::<ConflictingPreviewOptions>()
3234                .into(),
3235        );
3236        schema
3237    }
3238}
3239
3240impl PreviewOption {
3241    fn try_from(
3242        preview: Option<bool>,
3243        preview_features: Option<PreviewFeaturesOption>,
3244    ) -> Result<Option<Self>, &'static str> {
3245        match (preview, preview_features) {
3246            (Some(_), Some(_)) => Err("cannot specify both `preview` and `preview-features`"),
3247            (Some(b), None) => Ok(Some(Self::Preview(b))),
3248            (None, Some(features)) => Ok(Some(Self::PreviewFeatures(features))),
3249            (None, None) => Ok(None),
3250        }
3251    }
3252
3253    /// Resolve the preview configuration, warning and ignoring unknown feature names.
3254    pub fn resolve(&self) -> Preview {
3255        use PreviewFeaturesOption::{Features, Toggle};
3256
3257        match self {
3258            Self::Preview(false) | Self::PreviewFeatures(Toggle(false)) => Preview::default(),
3259            Self::Preview(true) | Self::PreviewFeatures(Toggle(true)) => Preview::all(),
3260            Self::PreviewFeatures(Features(features)) => Preview::from_feature_names(features),
3261        }
3262    }
3263}