Skip to main content

uv_settings/
lib.rs

1use std::num::NonZeroUsize;
2use std::ops::Deref;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::time::Duration;
6use tracing::info_span;
7use uv_client::{DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, DEFAULT_READ_TIMEOUT_UPLOAD};
8use uv_configuration::{RequiredVersion, RequirementsInput, RequirementsInputError};
9use uv_dirs::{system_config_file, user_config_dir};
10use uv_distribution_types::{IndexUrlError, Origin};
11use uv_flags::EnvironmentFlags;
12use uv_fs::Simplified;
13use uv_normalize::{GroupName, PackageName};
14use uv_pep440::Version;
15use uv_python_types::PythonArchitecture;
16use uv_redacted::DisplaySafeUrl;
17use uv_static::{EnvVars, InvalidEnvironmentVariable, parse_boolish_environment_variable};
18use uv_torch::AmdGpuArchitecture;
19use uv_warnings::warn_user;
20
21pub use crate::combine::*;
22pub use crate::resolved::*;
23pub use crate::settings::*;
24
25mod combine;
26mod resolved;
27mod settings;
28
29/// The [`Options`] as loaded from a configuration file on disk.
30#[derive(Debug, Clone)]
31pub struct FilesystemOptions(Options);
32
33impl FilesystemOptions {
34    /// Convert the [`FilesystemOptions`] into [`Options`].
35    pub fn into_options(self) -> Options {
36        self.0
37    }
38
39    /// Resolve the [`FilesystemOptions`] relative to the given root directory.
40    pub fn relative_to(self, root_dir: &Path) -> Result<Self, IndexUrlError> {
41        Ok(Self(self.0.relative_to(root_dir)?))
42    }
43}
44
45impl Deref for FilesystemOptions {
46    type Target = Options;
47
48    fn deref(&self) -> &Self::Target {
49        &self.0
50    }
51}
52
53impl FilesystemOptions {
54    /// Load the user [`FilesystemOptions`].
55    pub fn user() -> Result<Option<Self>, Error> {
56        let Some(dir) = user_config_dir() else {
57            return Ok(None);
58        };
59        let root = dir.join("uv");
60        let file = root.join("uv.toml");
61
62        tracing::debug!("Searching for user configuration in: {}", file.display());
63        match read_file(&file) {
64            Ok(options) => {
65                tracing::debug!("Found user configuration in: {}", file.display());
66                validate_uv_toml(&file, &options)?;
67                Ok(Some(Self(options.with_origin(Origin::User))))
68            }
69            Err(Error::Io(err))
70                if matches!(
71                    err.kind(),
72                    std::io::ErrorKind::NotFound
73                        | std::io::ErrorKind::NotADirectory
74                        | std::io::ErrorKind::PermissionDenied
75                ) =>
76            {
77                Ok(None)
78            }
79            Err(err) => Err(err),
80        }
81    }
82
83    pub fn system() -> Result<Option<Self>, Error> {
84        if parse_boolish_environment_variable(EnvVars::UV_NO_SYSTEM_CONFIG)? == Some(true) {
85            return Ok(None);
86        }
87
88        let Some(file) = system_config_file() else {
89            return Ok(None);
90        };
91
92        tracing::debug!("Found system configuration in: {}", file.display());
93        let options = read_file(&file)?;
94        validate_uv_toml(&file, &options)?;
95        Ok(Some(Self(options.with_origin(Origin::System))))
96    }
97
98    /// Find the [`FilesystemOptions`] for the given path.
99    ///
100    /// The search starts at the given path and goes up the directory tree until a `uv.toml` file or
101    /// `pyproject.toml` file is found.
102    pub fn find(path: &Path) -> Result<Option<Self>, Error> {
103        for ancestor in path.ancestors() {
104            match Self::from_directory(ancestor) {
105                Ok(Some(options)) => {
106                    return Ok(Some(options));
107                }
108                Ok(None) => {
109                    // Continue traversing the directory tree.
110                }
111                Err(Error::PyprojectToml(path, err)) => {
112                    // If we see an invalid `pyproject.toml`, warn but continue.
113                    warn_user!(
114                        "Failed to parse `{}` during settings discovery:\n{}",
115                        path.user_display().cyan(),
116                        textwrap::indent(&err.to_string(), "  ")
117                    );
118                }
119                Err(err) => {
120                    // Otherwise, warn and stop.
121                    return Err(err);
122                }
123            }
124        }
125        Ok(None)
126    }
127
128    /// Load a [`FilesystemOptions`] from a directory, preferring a `uv.toml` file over a
129    /// `pyproject.toml` file.
130    fn from_directory(dir: &Path) -> Result<Option<Self>, Error> {
131        // Read a `uv.toml` file in the current directory.
132        let path = dir.join("uv.toml");
133        match fs_err::read_to_string(&path) {
134            Ok(content) => {
135                let options =
136                    info_span!("toml::from_str filesystem options uv.toml", path = %path.display())
137                        .in_scope(|| toml::from_str::<Options>(&content))
138                        .map_err(|err| {
139                            check_uv_toml_required_version(
140                                &path,
141                                &content,
142                                Error::UvToml(path.clone(), Box::new(err)),
143                            )
144                        })?
145                        .relative_to(&std::path::absolute(dir)?)?;
146
147                // If the directory also contains a `[tool.uv]` table in a `pyproject.toml` file,
148                // warn.
149                let pyproject = dir.join("pyproject.toml");
150                if let Ok(content) = fs_err::read_to_string(&pyproject) {
151                    let result = info_span!("toml::from_str filesystem options pyproject.toml", path = %pyproject.display())
152                        .in_scope(|| toml::from_str::<PyProjectToml>(&content)).ok();
153                    if let Some(options) =
154                        result.and_then(|pyproject| pyproject.tool.and_then(|tool| tool.uv))
155                    {
156                        warn_uv_toml_masked_fields(&options);
157                    }
158                }
159
160                tracing::debug!("Found workspace configuration at `{}`", path.display());
161                validate_uv_toml(&path, &options)?;
162                return Ok(Some(Self(options.with_origin(Origin::Project))));
163            }
164            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
165            Err(err) => return Err(err.into()),
166        }
167
168        // Read a `pyproject.toml` file in the current directory.
169        let path = dir.join("pyproject.toml");
170        match fs_err::read_to_string(&path) {
171            Ok(content) => {
172                // Parse, but skip any `pyproject.toml` that doesn't have a `[tool.uv]` section.
173                let pyproject =
174                    info_span!("toml::from_str filesystem options pyproject.toml", path = %path.display())
175                        .in_scope(|| toml::from_str::<PyProjectToml>(&content))
176                        .map_err(|err| {
177                            check_pyproject_required_version(&path, &content, err)
178                        })?;
179                let Some(tool) = pyproject.tool else {
180                    tracing::debug!(
181                        "Skipping `pyproject.toml` in `{}` (no `[tool]` section)",
182                        dir.display()
183                    );
184                    return Ok(None);
185                };
186                let Some(options) = tool.uv else {
187                    tracing::debug!(
188                        "Skipping `pyproject.toml` in `{}` (no `[tool.uv]` section)",
189                        dir.display()
190                    );
191                    return Ok(None);
192                };
193
194                let options = options.relative_to(&std::path::absolute(dir)?)?;
195
196                tracing::debug!("Found workspace configuration at `{}`", path.display());
197                return Ok(Some(Self(options)));
198            }
199            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
200            Err(err) => return Err(err.into()),
201        }
202
203        Ok(None)
204    }
205
206    /// Load a [`FilesystemOptions`] from a `uv.toml` file.
207    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
208        let path = path.as_ref();
209        tracing::debug!("Reading user configuration from: {}", path.display());
210
211        let options = read_file(path)?;
212        validate_uv_toml(path, &options)?;
213        Ok(Self(options))
214    }
215}
216
217impl From<Options> for FilesystemOptions {
218    fn from(options: Options) -> Self {
219        Self(options)
220    }
221}
222
223/// Load [`Options`] from a `uv.toml` file.
224fn read_file(path: &Path) -> Result<Options, Error> {
225    let content = fs_err::read_to_string(path)?;
226    let options = info_span!("toml::from_str filesystem options uv.toml", path = %path.display())
227        .in_scope(|| toml::from_str::<Options>(&content))
228        .map_err(|err| {
229            check_uv_toml_required_version(
230                path,
231                &content,
232                Error::UvToml(path.to_path_buf(), Box::new(err)),
233            )
234        })?;
235    let options = if let Some(parent) = std::path::absolute(path)?.parent() {
236        options.relative_to(parent)?
237    } else {
238        options
239    };
240    Ok(options)
241}
242
243/// If `required_version` is set and incompatible with the running uv, return the corresponding
244/// [`Error::RequiredVersion`].
245fn required_version_mismatch(required_version: Option<RequiredVersion>) -> Option<Error> {
246    let required_version = required_version?;
247    let package_version = Version::from_str(uv_version::version())
248        .expect("uv crate version to be a valid PEP 440 version");
249    if required_version.contains(&package_version) {
250        None
251    } else {
252        Some(Error::RequiredVersion {
253            required_version,
254            package_version,
255        })
256    }
257}
258
259/// On a `pyproject.toml` settings parse error, check whether `tool.uv.required-version` should
260/// take precedence over that error.
261fn check_pyproject_required_version(path: &Path, content: &str, source: toml::de::Error) -> Error {
262    let fallback = || Error::PyprojectToml(path.to_path_buf(), Box::new(source));
263    let Ok(pyproject) = info_span!(
264        "toml::from_str filesystem required-version pyproject.toml",
265        path = %path.display()
266    )
267    .in_scope(|| toml::from_str::<PyProjectRequiredVersionToml>(content)) else {
268        return fallback();
269    };
270
271    let required_version = pyproject
272        .tool
273        .and_then(|tool| tool.uv)
274        .and_then(|uv| uv.required_version);
275    required_version_mismatch(required_version).unwrap_or_else(fallback)
276}
277
278/// On a `uv.toml` settings parse or schema error, check whether top-level `required-version`
279/// should take precedence over that error.
280fn check_uv_toml_required_version(path: &Path, content: &str, source: Error) -> Error {
281    let Ok(uv_toml) = info_span!(
282        "toml::from_str filesystem required-version uv.toml",
283        path = %path.display()
284    )
285    .in_scope(|| toml::from_str::<UvRequiredVersionToml>(content)) else {
286        return source;
287    };
288    required_version_mismatch(uv_toml.required_version).unwrap_or(source)
289}
290
291/// Validate that an [`Options`] schema is compatible with `uv.toml`.
292fn validate_uv_toml(path: &Path, options: &Options) -> Result<(), Error> {
293    // A `required-version` mismatch takes precedence over a schema error.
294    if let Some(err) = required_version_mismatch(options.globals.required_version.clone()) {
295        return Err(err);
296    }
297    let Options {
298        globals: _,
299        top_level: _,
300        install_mirrors: _,
301        publish: _,
302        add: _,
303        audit: _,
304        pip: _,
305        cache_keys: _,
306        override_dependencies: _,
307        exclude_dependencies: _,
308        constraint_dependencies: _,
309        build_constraint_dependencies: _,
310        environments,
311        required_environments,
312        minimum_libc_version,
313        conflicts,
314        workspace,
315        sources,
316        dev_dependencies,
317        default_groups,
318        dependency_groups,
319        managed,
320        package,
321        build_backend,
322    } = options;
323    // The `uv.toml` format is not allowed to include any of the following, which are
324    // permitted by the schema since they _can_ be included in `pyproject.toml` files
325    // (and we want to use `deny_unknown_fields`).
326    if conflicts.is_some() {
327        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "conflicts"));
328    }
329    if workspace.is_some() {
330        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "workspace"));
331    }
332    if sources.is_some() {
333        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "sources"));
334    }
335    if dev_dependencies.is_some() {
336        return Err(Error::PyprojectOnlyField(
337            path.to_path_buf(),
338            "dev-dependencies",
339        ));
340    }
341    if default_groups.is_some() {
342        return Err(Error::PyprojectOnlyField(
343            path.to_path_buf(),
344            "default-groups",
345        ));
346    }
347    if dependency_groups.is_some() {
348        return Err(Error::PyprojectOnlyField(
349            path.to_path_buf(),
350            "dependency-groups",
351        ));
352    }
353    if managed.is_some() {
354        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "managed"));
355    }
356    if package.is_some() {
357        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "package"));
358    }
359    if build_backend.is_some() {
360        return Err(Error::PyprojectOnlyField(
361            path.to_path_buf(),
362            "build-backend",
363        ));
364    }
365    if environments.is_some() {
366        return Err(Error::PyprojectOnlyField(
367            path.to_path_buf(),
368            "environments",
369        ));
370    }
371    if required_environments.is_some() {
372        return Err(Error::PyprojectOnlyField(
373            path.to_path_buf(),
374            "required-environments",
375        ));
376    }
377    if minimum_libc_version.is_some() {
378        return Err(Error::PyprojectOnlyField(
379            path.to_path_buf(),
380            "minimum-libc-version",
381        ));
382    }
383    Ok(())
384}
385
386/// Validate that an [`Options`] contains no fields that `uv.toml` would mask
387///
388/// This is essentially the inverse of [`validate_uv_toml`].
389#[allow(deprecated)]
390fn warn_uv_toml_masked_fields(options: &Options) {
391    let Options {
392        globals:
393            GlobalOptions {
394                required_version,
395                system_certs,
396                native_tls,
397                offline,
398                no_cache,
399                cache_dir,
400                preview,
401                python_preference,
402                python_downloads,
403                concurrent_downloads,
404                concurrent_builds,
405                concurrent_installs,
406                allow_insecure_host,
407                http_proxy,
408                https_proxy,
409                no_proxy,
410            },
411        top_level:
412            ResolverInstallerSchema {
413                index,
414                index_url,
415                extra_index_url,
416                no_index,
417                find_links,
418                index_strategy,
419                keyring_provider,
420                resolution,
421                prerelease,
422                prerelease_package,
423                fork_strategy,
424                dependency_metadata,
425                config_settings,
426                config_settings_package,
427                no_build_isolation,
428                no_build_isolation_package,
429                extra_build_dependencies,
430                extra_build_variables,
431                exclude_newer,
432                exclude_newer_package,
433                link_mode,
434                compile_bytecode,
435                no_sources,
436                no_sources_package: _,
437                require_build_hashes: _,
438                upgrade,
439                upgrade_package,
440                reinstall,
441                reinstall_package,
442                no_build,
443                no_build_package,
444                no_binary,
445                no_binary_package,
446                torch_backend,
447            },
448        install_mirrors:
449            PythonInstallMirrors {
450                python_install_mirror,
451                pypy_install_mirror,
452                graalpy_install_mirror,
453                pyodide_install_mirror,
454                python_downloads_json_url,
455            },
456        publish:
457            PublishOptions {
458                publish_url,
459                trusted_publishing,
460                check_url,
461            },
462        add: AddOptions { add_bounds },
463        audit: _,
464        pip,
465        cache_keys,
466        override_dependencies,
467        exclude_dependencies,
468        constraint_dependencies,
469        build_constraint_dependencies,
470        environments: _,
471        required_environments: _,
472        minimum_libc_version: _,
473        conflicts: _,
474        workspace: _,
475        sources: _,
476        dev_dependencies: _,
477        default_groups: _,
478        dependency_groups: _,
479        managed: _,
480        package: _,
481        build_backend: _,
482    } = options;
483
484    let mut masked_fields = vec![];
485
486    if required_version.is_some() {
487        masked_fields.push("required-version");
488    }
489    if system_certs.is_some() {
490        masked_fields.push("system-certs");
491    }
492    if native_tls.is_some() {
493        masked_fields.push("native-tls");
494    }
495    if offline.is_some() {
496        masked_fields.push("offline");
497    }
498    if no_cache.is_some() {
499        masked_fields.push("no-cache");
500    }
501    if cache_dir.is_some() {
502        masked_fields.push("cache-dir");
503    }
504    match preview {
505        Some(PreviewOption::Preview(_)) => masked_fields.push("preview"),
506        Some(PreviewOption::PreviewFeatures(_)) => masked_fields.push("preview-features"),
507        None => (),
508    }
509    if python_preference.is_some() {
510        masked_fields.push("python-preference");
511    }
512    if python_downloads.is_some() {
513        masked_fields.push("python-downloads");
514    }
515    if concurrent_downloads.is_some() {
516        masked_fields.push("concurrent-downloads");
517    }
518    if concurrent_builds.is_some() {
519        masked_fields.push("concurrent-builds");
520    }
521    if concurrent_installs.is_some() {
522        masked_fields.push("concurrent-installs");
523    }
524    if allow_insecure_host.is_some() {
525        masked_fields.push("allow-insecure-host");
526    }
527    if http_proxy.is_some() {
528        masked_fields.push("http-proxy");
529    }
530    if https_proxy.is_some() {
531        masked_fields.push("https-proxy");
532    }
533    if no_proxy.is_some() {
534        masked_fields.push("no-proxy");
535    }
536    if index.is_some() {
537        masked_fields.push("index");
538    }
539    if index_url.is_some() {
540        masked_fields.push("index-url");
541    }
542    if extra_index_url.is_some() {
543        masked_fields.push("extra-index-url");
544    }
545    if no_index.is_some() {
546        masked_fields.push("no-index");
547    }
548    if find_links.is_some() {
549        masked_fields.push("find-links");
550    }
551    if index_strategy.is_some() {
552        masked_fields.push("index-strategy");
553    }
554    if keyring_provider.is_some() {
555        masked_fields.push("keyring-provider");
556    }
557    if resolution.is_some() {
558        masked_fields.push("resolution");
559    }
560    if prerelease.is_some() {
561        masked_fields.push("prerelease");
562    }
563    if prerelease_package.is_some() {
564        masked_fields.push("prerelease-package");
565    }
566    if fork_strategy.is_some() {
567        masked_fields.push("fork-strategy");
568    }
569    if dependency_metadata.is_some() {
570        masked_fields.push("dependency-metadata");
571    }
572    if config_settings.is_some() {
573        masked_fields.push("config-settings");
574    }
575    if config_settings_package.is_some() {
576        masked_fields.push("config-settings-package");
577    }
578    if no_build_isolation.is_some() {
579        masked_fields.push("no-build-isolation");
580    }
581    if no_build_isolation_package.is_some() {
582        masked_fields.push("no-build-isolation-package");
583    }
584    if extra_build_dependencies.is_some() {
585        masked_fields.push("extra-build-dependencies");
586    }
587    if extra_build_variables.is_some() {
588        masked_fields.push("extra-build-variables");
589    }
590    if exclude_newer.is_some() {
591        masked_fields.push("exclude-newer");
592    }
593    if exclude_newer_package.is_some() {
594        masked_fields.push("exclude-newer-package");
595    }
596    if link_mode.is_some() {
597        masked_fields.push("link-mode");
598    }
599    if compile_bytecode.is_some() {
600        masked_fields.push("compile-bytecode");
601    }
602    if no_sources.is_some() {
603        masked_fields.push("no-sources");
604    }
605    if upgrade.is_some() {
606        masked_fields.push("upgrade");
607    }
608    if upgrade_package.is_some() {
609        masked_fields.push("upgrade-package");
610    }
611    if reinstall.is_some() {
612        masked_fields.push("reinstall");
613    }
614    if reinstall_package.is_some() {
615        masked_fields.push("reinstall-package");
616    }
617    if no_build.is_some() {
618        masked_fields.push("no-build");
619    }
620    if no_build_package.is_some() {
621        masked_fields.push("no-build-package");
622    }
623    if no_binary.is_some() {
624        masked_fields.push("no-binary");
625    }
626    if no_binary_package.is_some() {
627        masked_fields.push("no-binary-package");
628    }
629    if torch_backend.is_some() {
630        masked_fields.push("torch-backend");
631    }
632    if python_install_mirror.is_some() {
633        masked_fields.push("python-install-mirror");
634    }
635    if pypy_install_mirror.is_some() {
636        masked_fields.push("pypy-install-mirror");
637    }
638    if graalpy_install_mirror.is_some() {
639        masked_fields.push("graalpy-install-mirror");
640    }
641    if pyodide_install_mirror.is_some() {
642        masked_fields.push("pyodide-install-mirror");
643    }
644    if python_downloads_json_url.is_some() {
645        masked_fields.push("python-downloads-json-url");
646    }
647    if publish_url.is_some() {
648        masked_fields.push("publish-url");
649    }
650    if trusted_publishing.is_some() {
651        masked_fields.push("trusted-publishing");
652    }
653    if check_url.is_some() {
654        masked_fields.push("check-url");
655    }
656    if add_bounds.is_some() {
657        masked_fields.push("add-bounds");
658    }
659    if pip.is_some() {
660        masked_fields.push("pip");
661    }
662    if cache_keys.is_some() {
663        masked_fields.push("cache_keys");
664    }
665    if override_dependencies.is_some() {
666        masked_fields.push("override-dependencies");
667    }
668    if exclude_dependencies.is_some() {
669        masked_fields.push("exclude-dependencies");
670    }
671    if constraint_dependencies.is_some() {
672        masked_fields.push("constraint-dependencies");
673    }
674    if build_constraint_dependencies.is_some() {
675        masked_fields.push("build-constraint-dependencies");
676    }
677    if !masked_fields.is_empty() {
678        let field_listing = masked_fields.join("\n- ");
679        warn_user!(
680            "Found both a `uv.toml` file and a `[tool.uv]` section in an adjacent `pyproject.toml`. The following fields from `[tool.uv]` will be ignored in favor of the `uv.toml` file:\n- {}",
681            field_listing,
682        );
683    }
684}
685
686#[derive(thiserror::Error, Debug)]
687pub enum Error {
688    #[error(transparent)]
689    Io(#[from] std::io::Error),
690
691    #[error(transparent)]
692    Index(#[from] uv_distribution_types::IndexUrlError),
693
694    #[error("Failed to parse: {}", _0.user_display())]
695    PyprojectToml(PathBuf, #[source] Box<toml::de::Error>),
696
697    #[error("Failed to parse: {}", _0.user_display())]
698    UvToml(PathBuf, #[source] Box<toml::de::Error>),
699
700    #[error("Failed to parse `{}`. The `{}` field is not allowed in a `uv.toml` file. `{}` is only applicable in the context of a project, and should be placed in a `pyproject.toml` file instead.", _0.user_display(), _1, _1
701    )]
702    PyprojectOnlyField(PathBuf, &'static str),
703
704    #[error(
705        "Required uv version `{required_version}` does not match the running version `{package_version}`"
706    )]
707    RequiredVersion {
708        required_version: RequiredVersion,
709        package_version: Version,
710    },
711
712    #[error(transparent)]
713    InvalidEnvironmentVariable(#[from] InvalidEnvironmentVariable),
714}
715
716#[derive(Copy, Clone, Debug)]
717pub struct Concurrency {
718    pub downloads: Option<NonZeroUsize>,
719    pub builds: Option<NonZeroUsize>,
720    pub installs: Option<NonZeroUsize>,
721    pub cache_reads: Option<NonZeroUsize>,
722}
723
724/// A boolean flag parsed from an environment variable.
725///
726/// Stores both the value and the environment variable name for use in error messages.
727#[derive(Debug, Clone, Copy)]
728pub struct EnvFlag {
729    pub value: Option<bool>,
730    pub env_var: &'static str,
731}
732
733impl EnvFlag {
734    /// Create a new [`EnvFlag`] by parsing the given environment variable.
735    fn new(env_var: &'static str) -> Result<Self, Error> {
736        Ok(Self {
737            value: parse_boolish_environment_variable(env_var)?,
738            env_var,
739        })
740    }
741}
742
743/// Options loaded from environment variables.
744///
745/// This is currently a subset of all respected environment variables, most are parsed via Clap at
746/// the CLI level, however there are limited semantics in that context.
747#[derive(Debug, Clone)]
748pub struct EnvironmentOptions {
749    pub ruff_path: Option<PathBuf>,
750    pub ty_path: Option<PathBuf>,
751    pub skip_wheel_filename_check: Option<bool>,
752    pub require_metadata_range_requests: Option<bool>,
753    pub hide_build_output: Option<bool>,
754    pub python_arch: Option<PythonArchitecture>,
755    pub require_build_hashes: Option<bool>,
756    pub python_install_bin: Option<bool>,
757    pub python_install_registry: Option<bool>,
758    pub python_no_registry: EnvFlag,
759    pub install_mirrors: PythonInstallMirrors,
760    pub log_context: Option<bool>,
761    pub lfs: Option<bool>,
762    pub cuda_driver_version: Option<Version>,
763    pub amd_gpu_architecture: Option<AmdGpuArchitecture>,
764    pub http_connect_timeout: Duration,
765    pub http_read_timeout: Duration,
766    /// There's no upload timeout in reqwest, instead we have to use a read timeout as upload
767    /// timeout.
768    pub http_read_timeout_upload: Duration,
769    pub http_retries: u32,
770    pub concurrency: Concurrency,
771    #[cfg(feature = "tracing-durations-export")]
772    pub tracing_durations_file: Option<PathBuf>,
773    pub frozen: EnvFlag,
774    pub locked: EnvFlag,
775    pub offline: EnvFlag,
776    pub no_cache: EnvFlag,
777    pub no_sync: EnvFlag,
778    pub managed_python: EnvFlag,
779    pub no_managed_python: EnvFlag,
780    pub native_tls: EnvFlag,
781    pub system_certs: EnvFlag,
782    pub preview: EnvFlag,
783    pub isolated: EnvFlag,
784    pub no_progress: EnvFlag,
785    pub no_installer_metadata: EnvFlag,
786    pub dev: EnvFlag,
787    pub no_dev: EnvFlag,
788    pub show_resolution: EnvFlag,
789    pub no_editable: EnvFlag,
790    pub no_install_project: EnvFlag,
791    pub no_install_workspace: EnvFlag,
792    pub no_install_local: EnvFlag,
793    pub only_install_project: EnvFlag,
794    pub only_install_workspace: EnvFlag,
795    pub only_install_local: EnvFlag,
796    pub no_env_file: EnvFlag,
797    pub no_group: Option<Vec<GroupName>>,
798    pub constraints: Option<Vec<RequirementsInput>>,
799    pub overrides: Option<Vec<RequirementsInput>>,
800    pub excludes: Option<Vec<RequirementsInput>>,
801    pub build_constraints: Option<Vec<RequirementsInput>>,
802    pub no_binary_package: Option<Vec<PackageName>>,
803    pub no_build_package: Option<Vec<PackageName>>,
804    pub no_sources_package: Option<Vec<PackageName>>,
805    pub venv_seed: EnvFlag,
806    pub venv_clear: EnvFlag,
807    pub venv_relocatable: EnvFlag,
808    pub init_bare: EnvFlag,
809    pub malware_check: EnvFlag,
810    pub malware_check_url: Option<DisplaySafeUrl>,
811    #[cfg(unix)]
812    pub run_rlimit_nofile: Option<u32>,
813}
814
815impl EnvironmentOptions {
816    /// Create a new [`EnvironmentOptions`] from environment variables.
817    pub fn new() -> Result<Self, Error> {
818        // Timeout options, matching https://doc.rust-lang.org/nightly/cargo/reference/config.html#httptimeout
819        // `UV_REQUEST_TIMEOUT` is provided for backwards compatibility with v0.1.6
820        let http_read_timeout = parse_integer_environment_variable(
821            EnvVars::UV_HTTP_TIMEOUT,
822            Some("value should be an integer number of seconds"),
823        )?
824        .or(parse_integer_environment_variable(
825            EnvVars::UV_REQUEST_TIMEOUT,
826            Some("value should be an integer number of seconds"),
827        )?)
828        .or(parse_integer_environment_variable(
829            EnvVars::HTTP_TIMEOUT,
830            Some("value should be an integer number of seconds"),
831        )?)
832        .map(Duration::from_secs);
833
834        // Ignore the deprecated `UV_NATIVE_TLS` variable when its replacement is set.
835        let system_certs = EnvFlag::new(EnvVars::UV_SYSTEM_CERTS)?;
836        let native_tls = if system_certs.value.is_some() {
837            EnvFlag {
838                value: None,
839                env_var: EnvVars::UV_NATIVE_TLS,
840            }
841        } else {
842            EnvFlag::new(EnvVars::UV_NATIVE_TLS)?
843        };
844
845        Ok(Self {
846            require_build_hashes: parse_boolish_environment_variable(
847                EnvVars::UV_REQUIRE_BUILD_HASHES,
848            )?,
849            ruff_path: parse_path_environment_variable(EnvVars::RUFF),
850            ty_path: parse_path_environment_variable(EnvVars::TY),
851            skip_wheel_filename_check: parse_boolish_environment_variable(
852                EnvVars::UV_SKIP_WHEEL_FILENAME_CHECK,
853            )?,
854            require_metadata_range_requests: parse_boolish_environment_variable(
855                EnvVars::UV_REQUIRE_METADATA_RANGE_REQUESTS,
856            )?,
857            hide_build_output: parse_boolish_environment_variable(EnvVars::UV_HIDE_BUILD_OUTPUT)?,
858            python_arch: parse_typed_environment_variable(EnvVars::UV_PYTHON_ARCH, None)?,
859            python_install_bin: parse_boolish_environment_variable(EnvVars::UV_PYTHON_INSTALL_BIN)?,
860            python_install_registry: parse_boolish_environment_variable(
861                EnvVars::UV_PYTHON_INSTALL_REGISTRY,
862            )?,
863            python_no_registry: EnvFlag::new(EnvVars::UV_PYTHON_NO_REGISTRY)?,
864            concurrency: Concurrency {
865                downloads: parse_integer_environment_variable(
866                    EnvVars::UV_CONCURRENT_DOWNLOADS,
867                    None,
868                )?,
869                builds: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_BUILDS, None)?,
870                installs: parse_integer_environment_variable(
871                    EnvVars::UV_CONCURRENT_INSTALLS,
872                    None,
873                )?,
874                cache_reads: parse_integer_environment_variable(
875                    EnvVars::UV_CONCURRENT_CACHE_READS,
876                    None,
877                )?,
878            },
879            install_mirrors: PythonInstallMirrors {
880                python_install_mirror: parse_string_environment_variable(
881                    EnvVars::UV_PYTHON_INSTALL_MIRROR,
882                )?,
883                pypy_install_mirror: parse_string_environment_variable(
884                    EnvVars::UV_PYPY_INSTALL_MIRROR,
885                )?,
886                graalpy_install_mirror: parse_string_environment_variable(
887                    EnvVars::UV_GRAALPY_INSTALL_MIRROR,
888                )?,
889                pyodide_install_mirror: parse_string_environment_variable(
890                    EnvVars::UV_PYODIDE_INSTALL_MIRROR,
891                )?,
892                python_downloads_json_url: parse_string_environment_variable(
893                    EnvVars::UV_PYTHON_DOWNLOADS_JSON_URL,
894                )?,
895            },
896            log_context: parse_boolish_environment_variable(EnvVars::UV_LOG_CONTEXT)?,
897            lfs: parse_boolish_environment_variable(EnvVars::UV_GIT_LFS)?,
898            cuda_driver_version: parse_typed_environment_variable(
899                EnvVars::UV_CUDA_DRIVER_VERSION,
900                None,
901            )?,
902            amd_gpu_architecture: parse_typed_environment_variable(
903                EnvVars::UV_AMD_GPU_ARCHITECTURE,
904                None,
905            )?,
906            http_read_timeout_upload: parse_integer_environment_variable(
907                EnvVars::UV_UPLOAD_HTTP_TIMEOUT,
908                Some("value should be an integer number of seconds"),
909            )?
910            .map(Duration::from_secs)
911            .or(http_read_timeout)
912            .unwrap_or(DEFAULT_READ_TIMEOUT_UPLOAD),
913            http_read_timeout: http_read_timeout.unwrap_or(DEFAULT_READ_TIMEOUT),
914            http_connect_timeout: parse_integer_environment_variable(
915                EnvVars::UV_HTTP_CONNECT_TIMEOUT,
916                Some("value should be an integer number of seconds"),
917            )?
918            .map(Duration::from_secs)
919            .unwrap_or(DEFAULT_CONNECT_TIMEOUT),
920            http_retries: parse_integer_environment_variable(EnvVars::UV_HTTP_RETRIES, None)?
921                .unwrap_or(uv_client::DEFAULT_RETRIES),
922            #[cfg(feature = "tracing-durations-export")]
923            tracing_durations_file: parse_path_environment_variable(
924                EnvVars::TRACING_DURATIONS_FILE,
925            ),
926            frozen: EnvFlag::new(EnvVars::UV_FROZEN)?,
927            locked: EnvFlag::new(EnvVars::UV_LOCKED)?,
928            offline: EnvFlag::new(EnvVars::UV_OFFLINE)?,
929            no_cache: EnvFlag::new(EnvVars::UV_NO_CACHE)?,
930            no_sync: EnvFlag::new(EnvVars::UV_NO_SYNC)?,
931            managed_python: EnvFlag::new(EnvVars::UV_MANAGED_PYTHON)?,
932            no_managed_python: EnvFlag::new(EnvVars::UV_NO_MANAGED_PYTHON)?,
933            native_tls,
934            system_certs,
935            preview: EnvFlag::new(EnvVars::UV_PREVIEW)?,
936            isolated: EnvFlag::new(EnvVars::UV_ISOLATED)?,
937            no_progress: EnvFlag::new(EnvVars::UV_NO_PROGRESS)?,
938            no_installer_metadata: EnvFlag::new(EnvVars::UV_NO_INSTALLER_METADATA)?,
939            dev: EnvFlag::new(EnvVars::UV_DEV)?,
940            no_dev: EnvFlag::new(EnvVars::UV_NO_DEV)?,
941            show_resolution: EnvFlag::new(EnvVars::UV_SHOW_RESOLUTION)?,
942            no_editable: EnvFlag::new(EnvVars::UV_NO_EDITABLE)?,
943            no_install_project: EnvFlag::new(EnvVars::UV_NO_INSTALL_PROJECT)?,
944            no_install_workspace: EnvFlag::new(EnvVars::UV_NO_INSTALL_WORKSPACE)?,
945            no_install_local: EnvFlag::new(EnvVars::UV_NO_INSTALL_LOCAL)?,
946            only_install_project: EnvFlag::new(EnvVars::UV_ONLY_INSTALL_PROJECT)?,
947            only_install_workspace: EnvFlag::new(EnvVars::UV_ONLY_INSTALL_WORKSPACE)?,
948            only_install_local: EnvFlag::new(EnvVars::UV_ONLY_INSTALL_LOCAL)?,
949            no_env_file: EnvFlag::new(EnvVars::UV_NO_ENV_FILE)?,
950            no_group: parse_name_list_environment_variable(EnvVars::UV_NO_GROUP)?,
951            constraints: parse_path_list_environment_variable(EnvVars::UV_CONSTRAINT)?,
952            overrides: parse_path_list_environment_variable(EnvVars::UV_OVERRIDE)?,
953            excludes: parse_path_list_environment_variable(EnvVars::UV_EXCLUDE)?,
954            build_constraints: parse_path_list_environment_variable(EnvVars::UV_BUILD_CONSTRAINT)?,
955            no_binary_package: parse_name_list_environment_variable(EnvVars::UV_NO_BINARY_PACKAGE)?,
956            no_build_package: parse_name_list_environment_variable(EnvVars::UV_NO_BUILD_PACKAGE)?,
957            no_sources_package: parse_name_list_environment_variable(
958                EnvVars::UV_NO_SOURCES_PACKAGE,
959            )?,
960            venv_seed: EnvFlag::new(EnvVars::UV_VENV_SEED)?,
961            venv_clear: EnvFlag::new(EnvVars::UV_VENV_CLEAR)?,
962            venv_relocatable: EnvFlag::new(EnvVars::UV_VENV_RELOCATABLE)?,
963            init_bare: EnvFlag::new(EnvVars::UV_INIT_BARE)?,
964            malware_check: EnvFlag::new(EnvVars::UV_MALWARE_CHECK)?,
965            malware_check_url: parse_string_environment_variable(EnvVars::UV_MALWARE_CHECK_URL)?
966                .map(|value| {
967                    value.parse::<DisplaySafeUrl>().map_err(|err| {
968                        Error::InvalidEnvironmentVariable(InvalidEnvironmentVariable {
969                            name: EnvVars::UV_MALWARE_CHECK_URL.to_string(),
970                            value,
971                            err: err.to_string(),
972                        })
973                    })
974                })
975                .transpose()?,
976            #[cfg(unix)]
977            run_rlimit_nofile: parse_integer_environment_variable(
978                EnvVars::UV_RUN_RLIMIT_NOFILE,
979                None,
980            )?,
981        })
982    }
983}
984
985/// Parse a string environment variable.
986fn parse_string_environment_variable(name: &'static str) -> Result<Option<String>, Error> {
987    match std::env::var(name) {
988        Ok(v) => {
989            if v.is_empty() {
990                Ok(None)
991            } else {
992                Ok(Some(v))
993            }
994        }
995        Err(e) => match e {
996            std::env::VarError::NotPresent => Ok(None),
997            std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable(
998                InvalidEnvironmentVariable {
999                    name: name.to_string(),
1000                    value: err.to_string_lossy().to_string(),
1001                    err: "expected a valid UTF-8 string".to_string(),
1002                },
1003            )),
1004        },
1005    }
1006}
1007
1008/// Parse an environment variable containing a whitespace-delimited list of names.
1009fn parse_name_list_environment_variable<T>(name: &'static str) -> Result<Option<Vec<T>>, Error>
1010where
1011    T: FromStr,
1012    <T as FromStr>::Err: std::fmt::Display,
1013{
1014    let Some(value) = parse_string_environment_variable(name)? else {
1015        return Ok(None);
1016    };
1017
1018    let names = value
1019        .split_whitespace()
1020        .map(|entry| {
1021            entry.parse::<T>().map_err(|err| {
1022                Error::InvalidEnvironmentVariable(InvalidEnvironmentVariable {
1023                    name: name.to_string(),
1024                    value: value.clone(),
1025                    err: err.to_string(),
1026                })
1027            })
1028        })
1029        .collect::<Result<Vec<_>, _>>()?;
1030
1031    if names.is_empty() {
1032        Ok(None)
1033    } else {
1034        Ok(Some(names))
1035    }
1036}
1037
1038/// Parse an environment variable containing a whitespace-delimited list of requirements inputs.
1039fn parse_path_list_environment_variable(
1040    name: &'static str,
1041) -> Result<Option<Vec<RequirementsInput>>, Error> {
1042    let Some(value) = parse_string_environment_variable(name)? else {
1043        return Ok(None);
1044    };
1045
1046    let inputs = value
1047        .split_whitespace()
1048        .map(|entry| {
1049            entry.parse().map_err(|err: RequirementsInputError| {
1050                Error::InvalidEnvironmentVariable(InvalidEnvironmentVariable {
1051                    name: name.to_string(),
1052                    value: value.clone(),
1053                    err: err.to_string(),
1054                })
1055            })
1056        })
1057        .collect::<Result<Vec<_>, _>>()?;
1058
1059    if inputs.is_empty() {
1060        Ok(None)
1061    } else {
1062        Ok(Some(inputs))
1063    }
1064}
1065
1066fn parse_typed_environment_variable<T>(
1067    name: &'static str,
1068    help: Option<&str>,
1069) -> Result<Option<T>, Error>
1070where
1071    T: std::str::FromStr,
1072    <T as std::str::FromStr>::Err: std::fmt::Display,
1073{
1074    let value = match std::env::var(name) {
1075        Ok(v) => v,
1076        Err(e) => {
1077            return match e {
1078                std::env::VarError::NotPresent => Ok(None),
1079                std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable(
1080                    InvalidEnvironmentVariable {
1081                        name: name.to_string(),
1082                        value: err.to_string_lossy().to_string(),
1083                        err: "expected a valid UTF-8 string".to_string(),
1084                    },
1085                )),
1086            };
1087        }
1088    };
1089    if value.is_empty() {
1090        return Ok(None);
1091    }
1092
1093    match value.parse::<T>() {
1094        Ok(v) => Ok(Some(v)),
1095        Err(err) => Err(Error::InvalidEnvironmentVariable(
1096            InvalidEnvironmentVariable {
1097                name: name.to_string(),
1098                value,
1099                err: if let Some(help) = help {
1100                    format!("{err}; {help}")
1101                } else {
1102                    err.to_string()
1103                },
1104            },
1105        )),
1106    }
1107}
1108
1109fn parse_integer_environment_variable<T>(
1110    name: &'static str,
1111    help: Option<&str>,
1112) -> Result<Option<T>, Error>
1113where
1114    T: std::str::FromStr + Copy,
1115    <T as std::str::FromStr>::Err: std::fmt::Display,
1116{
1117    let value = match std::env::var(name) {
1118        Ok(v) => v,
1119        Err(e) => {
1120            return match e {
1121                std::env::VarError::NotPresent => Ok(None),
1122                std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable(
1123                    InvalidEnvironmentVariable {
1124                        name: name.to_string(),
1125                        value: err.to_string_lossy().to_string(),
1126                        err: "expected a valid UTF-8 string".to_string(),
1127                    },
1128                )),
1129            };
1130        }
1131    };
1132    if value.is_empty() {
1133        return Ok(None);
1134    }
1135
1136    match value.parse::<T>() {
1137        Ok(v) => Ok(Some(v)),
1138        Err(err) => Err(Error::InvalidEnvironmentVariable(
1139            InvalidEnvironmentVariable {
1140                name: name.to_string(),
1141                value,
1142                err: if let Some(help) = help {
1143                    format!("{err}; {help}")
1144                } else {
1145                    err.to_string()
1146                },
1147            },
1148        )),
1149    }
1150}
1151
1152/// Parse a path environment variable.
1153fn parse_path_environment_variable(name: &'static str) -> Option<PathBuf> {
1154    let value = std::env::var_os(name)?;
1155
1156    if value.is_empty() {
1157        return None;
1158    }
1159
1160    Some(PathBuf::from(value))
1161}
1162
1163/// Populate the [`EnvironmentFlags`] from the given [`EnvironmentOptions`].
1164impl From<&EnvironmentOptions> for EnvironmentFlags {
1165    fn from(options: &EnvironmentOptions) -> Self {
1166        let mut flags = Self::empty();
1167        if options.skip_wheel_filename_check == Some(true) {
1168            flags.insert(Self::SKIP_WHEEL_FILENAME_CHECK);
1169        }
1170        if options.hide_build_output == Some(true) {
1171            flags.insert(Self::HIDE_BUILD_OUTPUT);
1172        }
1173        flags
1174    }
1175}