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