uv_settings/
lib.rs

1use std::num::NonZeroUsize;
2use std::ops::Deref;
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use uv_dirs::{system_config_file, user_config_dir};
7use uv_flags::EnvironmentFlags;
8use uv_fs::Simplified;
9use uv_static::EnvVars;
10use uv_warnings::warn_user;
11
12pub use crate::combine::*;
13pub use crate::settings::*;
14
15mod combine;
16mod settings;
17
18/// The [`Options`] as loaded from a configuration file on disk.
19#[derive(Debug, Clone)]
20pub struct FilesystemOptions(Options);
21
22impl FilesystemOptions {
23    /// Convert the [`FilesystemOptions`] into [`Options`].
24    pub fn into_options(self) -> Options {
25        self.0
26    }
27}
28
29impl Deref for FilesystemOptions {
30    type Target = Options;
31
32    fn deref(&self) -> &Self::Target {
33        &self.0
34    }
35}
36
37impl FilesystemOptions {
38    /// Load the user [`FilesystemOptions`].
39    pub fn user() -> Result<Option<Self>, Error> {
40        let Some(dir) = user_config_dir() else {
41            return Ok(None);
42        };
43        let root = dir.join("uv");
44        let file = root.join("uv.toml");
45
46        tracing::debug!("Searching for user configuration in: `{}`", file.display());
47        match read_file(&file) {
48            Ok(options) => {
49                tracing::debug!("Found user configuration in: `{}`", file.display());
50                validate_uv_toml(&file, &options)?;
51                Ok(Some(Self(options)))
52            }
53            Err(Error::Io(err))
54                if matches!(
55                    err.kind(),
56                    std::io::ErrorKind::NotFound
57                        | std::io::ErrorKind::NotADirectory
58                        | std::io::ErrorKind::PermissionDenied
59                ) =>
60            {
61                Ok(None)
62            }
63            Err(err) => Err(err),
64        }
65    }
66
67    pub fn system() -> Result<Option<Self>, Error> {
68        let Some(file) = system_config_file() else {
69            return Ok(None);
70        };
71
72        tracing::debug!("Found system configuration in: `{}`", file.display());
73        let options = read_file(&file)?;
74        validate_uv_toml(&file, &options)?;
75        Ok(Some(Self(options)))
76    }
77
78    /// Find the [`FilesystemOptions`] for the given path.
79    ///
80    /// The search starts at the given path and goes up the directory tree until a `uv.toml` file or
81    /// `pyproject.toml` file is found.
82    pub fn find(path: &Path) -> Result<Option<Self>, Error> {
83        for ancestor in path.ancestors() {
84            match Self::from_directory(ancestor) {
85                Ok(Some(options)) => {
86                    return Ok(Some(options));
87                }
88                Ok(None) => {
89                    // Continue traversing the directory tree.
90                }
91                Err(Error::PyprojectToml(path, err)) => {
92                    // If we see an invalid `pyproject.toml`, warn but continue.
93                    warn_user!(
94                        "Failed to parse `{}` during settings discovery:\n{}",
95                        path.user_display().cyan(),
96                        textwrap::indent(&err.to_string(), "  ")
97                    );
98                }
99                Err(err) => {
100                    // Otherwise, warn and stop.
101                    return Err(err);
102                }
103            }
104        }
105        Ok(None)
106    }
107
108    /// Load a [`FilesystemOptions`] from a directory, preferring a `uv.toml` file over a
109    /// `pyproject.toml` file.
110    pub fn from_directory(dir: &Path) -> Result<Option<Self>, Error> {
111        // Read a `uv.toml` file in the current directory.
112        let path = dir.join("uv.toml");
113        match fs_err::read_to_string(&path) {
114            Ok(content) => {
115                let options = toml::from_str::<Options>(&content)
116                    .map_err(|err| Error::UvToml(path.clone(), Box::new(err)))?
117                    .relative_to(&std::path::absolute(dir)?)?;
118
119                // If the directory also contains a `[tool.uv]` table in a `pyproject.toml` file,
120                // warn.
121                let pyproject = dir.join("pyproject.toml");
122                if let Some(pyproject) = fs_err::read_to_string(pyproject)
123                    .ok()
124                    .and_then(|content| toml::from_str::<PyProjectToml>(&content).ok())
125                {
126                    if let Some(options) = pyproject.tool.as_ref().and_then(|tool| tool.uv.as_ref())
127                    {
128                        warn_uv_toml_masked_fields(options);
129                    }
130                }
131
132                tracing::debug!("Found workspace configuration at `{}`", path.display());
133                validate_uv_toml(&path, &options)?;
134                return Ok(Some(Self(options)));
135            }
136            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
137            Err(err) => return Err(err.into()),
138        }
139
140        // Read a `pyproject.toml` file in the current directory.
141        let path = dir.join("pyproject.toml");
142        match fs_err::read_to_string(&path) {
143            Ok(content) => {
144                // Parse, but skip any `pyproject.toml` that doesn't have a `[tool.uv]` section.
145                let pyproject: PyProjectToml = toml::from_str(&content)
146                    .map_err(|err| Error::PyprojectToml(path.clone(), Box::new(err)))?;
147                let Some(tool) = pyproject.tool else {
148                    tracing::debug!(
149                        "Skipping `pyproject.toml` in `{}` (no `[tool]` section)",
150                        dir.display()
151                    );
152                    return Ok(None);
153                };
154                let Some(options) = tool.uv else {
155                    tracing::debug!(
156                        "Skipping `pyproject.toml` in `{}` (no `[tool.uv]` section)",
157                        dir.display()
158                    );
159                    return Ok(None);
160                };
161
162                let options = options.relative_to(&std::path::absolute(dir)?)?;
163
164                tracing::debug!("Found workspace configuration at `{}`", path.display());
165                return Ok(Some(Self(options)));
166            }
167            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
168            Err(err) => return Err(err.into()),
169        }
170
171        Ok(None)
172    }
173
174    /// Load a [`FilesystemOptions`] from a `uv.toml` file.
175    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
176        let path = path.as_ref();
177        tracing::debug!("Reading user configuration from: `{}`", path.display());
178
179        let options = read_file(path)?;
180        validate_uv_toml(path, &options)?;
181        Ok(Self(options))
182    }
183}
184
185impl From<Options> for FilesystemOptions {
186    fn from(options: Options) -> Self {
187        Self(options)
188    }
189}
190
191/// Load [`Options`] from a `uv.toml` file.
192fn read_file(path: &Path) -> Result<Options, Error> {
193    let content = fs_err::read_to_string(path)?;
194    let options = toml::from_str::<Options>(&content)
195        .map_err(|err| Error::UvToml(path.to_path_buf(), Box::new(err)))?;
196    let options = if let Some(parent) = std::path::absolute(path)?.parent() {
197        options.relative_to(parent)?
198    } else {
199        options
200    };
201    Ok(options)
202}
203
204/// Validate that an [`Options`] schema is compatible with `uv.toml`.
205fn validate_uv_toml(path: &Path, options: &Options) -> Result<(), Error> {
206    let Options {
207        globals: _,
208        top_level: _,
209        install_mirrors: _,
210        publish: _,
211        add: _,
212        pip: _,
213        cache_keys: _,
214        override_dependencies: _,
215        exclude_dependencies: _,
216        constraint_dependencies: _,
217        build_constraint_dependencies: _,
218        environments,
219        required_environments,
220        conflicts,
221        workspace,
222        sources,
223        dev_dependencies,
224        default_groups,
225        dependency_groups,
226        managed,
227        package,
228        build_backend,
229    } = options;
230    // The `uv.toml` format is not allowed to include any of the following, which are
231    // permitted by the schema since they _can_ be included in `pyproject.toml` files
232    // (and we want to use `deny_unknown_fields`).
233    if conflicts.is_some() {
234        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "conflicts"));
235    }
236    if workspace.is_some() {
237        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "workspace"));
238    }
239    if sources.is_some() {
240        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "sources"));
241    }
242    if dev_dependencies.is_some() {
243        return Err(Error::PyprojectOnlyField(
244            path.to_path_buf(),
245            "dev-dependencies",
246        ));
247    }
248    if default_groups.is_some() {
249        return Err(Error::PyprojectOnlyField(
250            path.to_path_buf(),
251            "default-groups",
252        ));
253    }
254    if dependency_groups.is_some() {
255        return Err(Error::PyprojectOnlyField(
256            path.to_path_buf(),
257            "dependency-groups",
258        ));
259    }
260    if managed.is_some() {
261        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "managed"));
262    }
263    if package.is_some() {
264        return Err(Error::PyprojectOnlyField(path.to_path_buf(), "package"));
265    }
266    if build_backend.is_some() {
267        return Err(Error::PyprojectOnlyField(
268            path.to_path_buf(),
269            "build-backend",
270        ));
271    }
272    if environments.is_some() {
273        return Err(Error::PyprojectOnlyField(
274            path.to_path_buf(),
275            "environments",
276        ));
277    }
278    if required_environments.is_some() {
279        return Err(Error::PyprojectOnlyField(
280            path.to_path_buf(),
281            "required-environments",
282        ));
283    }
284    Ok(())
285}
286
287/// Validate that an [`Options`] contains no fields that `uv.toml` would mask
288///
289/// This is essentially the inverse of [`validate_uv_toml`].
290fn warn_uv_toml_masked_fields(options: &Options) {
291    let Options {
292        globals:
293            GlobalOptions {
294                required_version,
295                native_tls,
296                offline,
297                no_cache,
298                cache_dir,
299                preview,
300                python_preference,
301                python_downloads,
302                concurrent_downloads,
303                concurrent_builds,
304                concurrent_installs,
305                allow_insecure_host,
306            },
307        top_level:
308            ResolverInstallerSchema {
309                index,
310                index_url,
311                extra_index_url,
312                no_index,
313                find_links,
314                index_strategy,
315                keyring_provider,
316                resolution,
317                prerelease,
318                fork_strategy,
319                dependency_metadata,
320                config_settings,
321                config_settings_package,
322                no_build_isolation,
323                no_build_isolation_package,
324                extra_build_dependencies,
325                extra_build_variables,
326                exclude_newer,
327                exclude_newer_package,
328                link_mode,
329                compile_bytecode,
330                no_sources,
331                upgrade,
332                upgrade_package,
333                reinstall,
334                reinstall_package,
335                no_build,
336                no_build_package,
337                no_binary,
338                no_binary_package,
339                torch_backend,
340            },
341        install_mirrors:
342            PythonInstallMirrors {
343                python_install_mirror,
344                pypy_install_mirror,
345                python_downloads_json_url,
346            },
347        publish:
348            PublishOptions {
349                publish_url,
350                trusted_publishing,
351                check_url,
352            },
353        add: AddOptions { add_bounds },
354        pip,
355        cache_keys,
356        override_dependencies,
357        exclude_dependencies,
358        constraint_dependencies,
359        build_constraint_dependencies,
360        environments: _,
361        required_environments: _,
362        conflicts: _,
363        workspace: _,
364        sources: _,
365        dev_dependencies: _,
366        default_groups: _,
367        dependency_groups: _,
368        managed: _,
369        package: _,
370        build_backend: _,
371    } = options;
372
373    let mut masked_fields = vec![];
374
375    if required_version.is_some() {
376        masked_fields.push("required-version");
377    }
378    if native_tls.is_some() {
379        masked_fields.push("native-tls");
380    }
381    if offline.is_some() {
382        masked_fields.push("offline");
383    }
384    if no_cache.is_some() {
385        masked_fields.push("no-cache");
386    }
387    if cache_dir.is_some() {
388        masked_fields.push("cache-dir");
389    }
390    if preview.is_some() {
391        masked_fields.push("preview");
392    }
393    if python_preference.is_some() {
394        masked_fields.push("python-preference");
395    }
396    if python_downloads.is_some() {
397        masked_fields.push("python-downloads");
398    }
399    if concurrent_downloads.is_some() {
400        masked_fields.push("concurrent-downloads");
401    }
402    if concurrent_builds.is_some() {
403        masked_fields.push("concurrent-builds");
404    }
405    if concurrent_installs.is_some() {
406        masked_fields.push("concurrent-installs");
407    }
408    if allow_insecure_host.is_some() {
409        masked_fields.push("allow-insecure-host");
410    }
411    if index.is_some() {
412        masked_fields.push("index");
413    }
414    if index_url.is_some() {
415        masked_fields.push("index-url");
416    }
417    if extra_index_url.is_some() {
418        masked_fields.push("extra-index-url");
419    }
420    if no_index.is_some() {
421        masked_fields.push("no-index");
422    }
423    if find_links.is_some() {
424        masked_fields.push("find-links");
425    }
426    if index_strategy.is_some() {
427        masked_fields.push("index-strategy");
428    }
429    if keyring_provider.is_some() {
430        masked_fields.push("keyring-provider");
431    }
432    if resolution.is_some() {
433        masked_fields.push("resolution");
434    }
435    if prerelease.is_some() {
436        masked_fields.push("prerelease");
437    }
438    if fork_strategy.is_some() {
439        masked_fields.push("fork-strategy");
440    }
441    if dependency_metadata.is_some() {
442        masked_fields.push("dependency-metadata");
443    }
444    if config_settings.is_some() {
445        masked_fields.push("config-settings");
446    }
447    if config_settings_package.is_some() {
448        masked_fields.push("config-settings-package");
449    }
450    if no_build_isolation.is_some() {
451        masked_fields.push("no-build-isolation");
452    }
453    if no_build_isolation_package.is_some() {
454        masked_fields.push("no-build-isolation-package");
455    }
456    if extra_build_dependencies.is_some() {
457        masked_fields.push("extra-build-dependencies");
458    }
459    if extra_build_variables.is_some() {
460        masked_fields.push("extra-build-variables");
461    }
462    if exclude_newer.is_some() {
463        masked_fields.push("exclude-newer");
464    }
465    if exclude_newer_package.is_some() {
466        masked_fields.push("exclude-newer-package");
467    }
468    if link_mode.is_some() {
469        masked_fields.push("link-mode");
470    }
471    if compile_bytecode.is_some() {
472        masked_fields.push("compile-bytecode");
473    }
474    if no_sources.is_some() {
475        masked_fields.push("no-sources");
476    }
477    if upgrade.is_some() {
478        masked_fields.push("upgrade");
479    }
480    if upgrade_package.is_some() {
481        masked_fields.push("upgrade-package");
482    }
483    if reinstall.is_some() {
484        masked_fields.push("reinstall");
485    }
486    if reinstall_package.is_some() {
487        masked_fields.push("reinstall-package");
488    }
489    if no_build.is_some() {
490        masked_fields.push("no-build");
491    }
492    if no_build_package.is_some() {
493        masked_fields.push("no-build-package");
494    }
495    if no_binary.is_some() {
496        masked_fields.push("no-binary");
497    }
498    if no_binary_package.is_some() {
499        masked_fields.push("no-binary-package");
500    }
501    if torch_backend.is_some() {
502        masked_fields.push("torch-backend");
503    }
504    if python_install_mirror.is_some() {
505        masked_fields.push("python-install-mirror");
506    }
507    if pypy_install_mirror.is_some() {
508        masked_fields.push("pypy-install-mirror");
509    }
510    if python_downloads_json_url.is_some() {
511        masked_fields.push("python-downloads-json-url");
512    }
513    if publish_url.is_some() {
514        masked_fields.push("publish-url");
515    }
516    if trusted_publishing.is_some() {
517        masked_fields.push("trusted-publishing");
518    }
519    if check_url.is_some() {
520        masked_fields.push("check-url");
521    }
522    if add_bounds.is_some() {
523        masked_fields.push("add-bounds");
524    }
525    if pip.is_some() {
526        masked_fields.push("pip");
527    }
528    if cache_keys.is_some() {
529        masked_fields.push("cache_keys");
530    }
531    if override_dependencies.is_some() {
532        masked_fields.push("override-dependencies");
533    }
534    if exclude_dependencies.is_some() {
535        masked_fields.push("exclude-dependencies");
536    }
537    if constraint_dependencies.is_some() {
538        masked_fields.push("constraint-dependencies");
539    }
540    if build_constraint_dependencies.is_some() {
541        masked_fields.push("build-constraint-dependencies");
542    }
543    if !masked_fields.is_empty() {
544        let field_listing = masked_fields.join("\n- ");
545        warn_user!(
546            "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- {}",
547            field_listing,
548        );
549    }
550}
551
552#[derive(thiserror::Error, Debug)]
553pub enum Error {
554    #[error(transparent)]
555    Io(#[from] std::io::Error),
556
557    #[error(transparent)]
558    Index(#[from] uv_distribution_types::IndexUrlError),
559
560    #[error("Failed to parse: `{}`", _0.user_display())]
561    PyprojectToml(PathBuf, #[source] Box<toml::de::Error>),
562
563    #[error("Failed to parse: `{}`", _0.user_display())]
564    UvToml(PathBuf, #[source] Box<toml::de::Error>),
565
566    #[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
567    )]
568    PyprojectOnlyField(PathBuf, &'static str),
569
570    #[error("Failed to parse environment variable `{name}` with invalid value `{value}`: {err}")]
571    InvalidEnvironmentVariable {
572        name: String,
573        value: String,
574        err: String,
575    },
576}
577
578#[derive(Copy, Clone, Debug)]
579pub struct Concurrency {
580    pub downloads: Option<NonZeroUsize>,
581    pub builds: Option<NonZeroUsize>,
582    pub installs: Option<NonZeroUsize>,
583}
584
585/// Options loaded from environment variables.
586///
587/// This is currently a subset of all respected environment variables, most are parsed via Clap at
588/// the CLI level, however there are limited semantics in that context.
589#[derive(Debug, Clone)]
590pub struct EnvironmentOptions {
591    pub skip_wheel_filename_check: Option<bool>,
592    pub hide_build_output: Option<bool>,
593    pub python_install_bin: Option<bool>,
594    pub python_install_registry: Option<bool>,
595    pub install_mirrors: PythonInstallMirrors,
596    pub log_context: Option<bool>,
597    pub lfs: Option<bool>,
598    pub http_timeout: Duration,
599    pub http_retries: u32,
600    pub upload_http_timeout: Duration,
601    pub concurrency: Concurrency,
602    #[cfg(feature = "tracing-durations-export")]
603    pub tracing_durations_file: Option<PathBuf>,
604}
605
606impl EnvironmentOptions {
607    /// Create a new [`EnvironmentOptions`] from environment variables.
608    pub fn new() -> Result<Self, Error> {
609        // Timeout options, matching https://doc.rust-lang.org/nightly/cargo/reference/config.html#httptimeout
610        // `UV_REQUEST_TIMEOUT` is provided for backwards compatibility with v0.1.6
611        let http_timeout = parse_integer_environment_variable(EnvVars::UV_HTTP_TIMEOUT)?
612            .or(parse_integer_environment_variable(
613                EnvVars::UV_REQUEST_TIMEOUT,
614            )?)
615            .or(parse_integer_environment_variable(EnvVars::HTTP_TIMEOUT)?)
616            .map(Duration::from_secs);
617
618        Ok(Self {
619            skip_wheel_filename_check: parse_boolish_environment_variable(
620                EnvVars::UV_SKIP_WHEEL_FILENAME_CHECK,
621            )?,
622            hide_build_output: parse_boolish_environment_variable(EnvVars::UV_HIDE_BUILD_OUTPUT)?,
623            python_install_bin: parse_boolish_environment_variable(EnvVars::UV_PYTHON_INSTALL_BIN)?,
624            python_install_registry: parse_boolish_environment_variable(
625                EnvVars::UV_PYTHON_INSTALL_REGISTRY,
626            )?,
627            concurrency: Concurrency {
628                downloads: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_DOWNLOADS)?,
629                builds: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_BUILDS)?,
630                installs: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_INSTALLS)?,
631            },
632            install_mirrors: PythonInstallMirrors {
633                python_install_mirror: parse_string_environment_variable(
634                    EnvVars::UV_PYTHON_INSTALL_MIRROR,
635                )?,
636                pypy_install_mirror: parse_string_environment_variable(
637                    EnvVars::UV_PYPY_INSTALL_MIRROR,
638                )?,
639                python_downloads_json_url: parse_string_environment_variable(
640                    EnvVars::UV_PYTHON_DOWNLOADS_JSON_URL,
641                )?,
642            },
643            log_context: parse_boolish_environment_variable(EnvVars::UV_LOG_CONTEXT)?,
644            lfs: parse_boolish_environment_variable(EnvVars::UV_GIT_LFS)?,
645            upload_http_timeout: parse_integer_environment_variable(
646                EnvVars::UV_UPLOAD_HTTP_TIMEOUT,
647            )?
648            .map(Duration::from_secs)
649            .or(http_timeout)
650            .unwrap_or(Duration::from_secs(15 * 60)),
651            http_timeout: http_timeout.unwrap_or(Duration::from_secs(30)),
652            http_retries: parse_integer_environment_variable(EnvVars::UV_HTTP_RETRIES)?
653                .unwrap_or(uv_client::DEFAULT_RETRIES),
654            #[cfg(feature = "tracing-durations-export")]
655            tracing_durations_file: parse_path_environment_variable(
656                EnvVars::TRACING_DURATIONS_FILE,
657            ),
658        })
659    }
660}
661
662/// Parse a boolean environment variable.
663///
664/// Adapted from Clap's `BoolishValueParser` which is dual licensed under the MIT and Apache-2.0.
665fn parse_boolish_environment_variable(name: &'static str) -> Result<Option<bool>, Error> {
666    // See `clap_builder/src/util/str_to_bool.rs`
667    // We want to match Clap's accepted values
668
669    // True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
670    const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
671
672    // False values are `n`, `no`, `f`, `false`, `off`, and `0`.
673    const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
674
675    // Converts a string literal representation of truth to true or false.
676    //
677    // `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
678    //
679    // Any other value will be considered as `true`.
680    fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
681        let pat: &str = &val.as_ref().to_lowercase();
682        if TRUE_LITERALS.contains(&pat) {
683            Some(true)
684        } else if FALSE_LITERALS.contains(&pat) {
685            Some(false)
686        } else {
687            None
688        }
689    }
690
691    let Some(value) = std::env::var_os(name) else {
692        return Ok(None);
693    };
694
695    let Some(value) = value.to_str() else {
696        return Err(Error::InvalidEnvironmentVariable {
697            name: name.to_string(),
698            value: value.to_string_lossy().to_string(),
699            err: "expected a valid UTF-8 string".to_string(),
700        });
701    };
702
703    let Some(value) = str_to_bool(value) else {
704        return Err(Error::InvalidEnvironmentVariable {
705            name: name.to_string(),
706            value: value.to_string(),
707            err: "expected a boolish value".to_string(),
708        });
709    };
710
711    Ok(Some(value))
712}
713
714/// Parse a string environment variable.
715fn parse_string_environment_variable(name: &'static str) -> Result<Option<String>, Error> {
716    match std::env::var(name) {
717        Ok(v) => {
718            if v.is_empty() {
719                Ok(None)
720            } else {
721                Ok(Some(v))
722            }
723        }
724        Err(e) => match e {
725            std::env::VarError::NotPresent => Ok(None),
726            std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
727                name: name.to_string(),
728                value: err.to_string_lossy().to_string(),
729                err: "expected a valid UTF-8 string".to_string(),
730            }),
731        },
732    }
733}
734
735fn parse_integer_environment_variable<T>(name: &'static str) -> Result<Option<T>, Error>
736where
737    T: std::str::FromStr + Copy,
738    <T as std::str::FromStr>::Err: std::fmt::Display,
739{
740    let value = match std::env::var(name) {
741        Ok(v) => v,
742        Err(e) => {
743            return match e {
744                std::env::VarError::NotPresent => Ok(None),
745                std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
746                    name: name.to_string(),
747                    value: err.to_string_lossy().to_string(),
748                    err: "expected a valid UTF-8 string".to_string(),
749                }),
750            };
751        }
752    };
753    if value.is_empty() {
754        return Ok(None);
755    }
756
757    match value.parse::<T>() {
758        Ok(v) => Ok(Some(v)),
759        Err(err) => Err(Error::InvalidEnvironmentVariable {
760            name: name.to_string(),
761            value,
762            err: err.to_string(),
763        }),
764    }
765}
766
767#[cfg(feature = "tracing-durations-export")]
768/// Parse a path environment variable.
769fn parse_path_environment_variable(name: &'static str) -> Option<PathBuf> {
770    let value = std::env::var_os(name)?;
771
772    if value.is_empty() {
773        return None;
774    }
775
776    Some(PathBuf::from(value))
777}
778
779/// Populate the [`EnvironmentFlags`] from the given [`EnvironmentOptions`].
780impl From<&EnvironmentOptions> for EnvironmentFlags {
781    fn from(options: &EnvironmentOptions) -> Self {
782        let mut flags = Self::empty();
783        if options.skip_wheel_filename_check == Some(true) {
784            flags.insert(Self::SKIP_WHEEL_FILENAME_CHECK);
785        }
786        if options.hide_build_output == Some(true) {
787            flags.insert(Self::HIDE_BUILD_OUTPUT);
788        }
789        flags
790    }
791}