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 [`validated_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            },
340        install_mirrors:
341            PythonInstallMirrors {
342                python_install_mirror,
343                pypy_install_mirror,
344                python_downloads_json_url,
345            },
346        publish:
347            PublishOptions {
348                publish_url,
349                trusted_publishing,
350                check_url,
351            },
352        add: AddOptions { add_bounds },
353        pip,
354        cache_keys,
355        override_dependencies,
356        exclude_dependencies,
357        constraint_dependencies,
358        build_constraint_dependencies,
359        environments: _,
360        required_environments: _,
361        conflicts: _,
362        workspace: _,
363        sources: _,
364        dev_dependencies: _,
365        default_groups: _,
366        dependency_groups: _,
367        managed: _,
368        package: _,
369        build_backend: _,
370    } = options;
371
372    let mut masked_fields = vec![];
373
374    if required_version.is_some() {
375        masked_fields.push("required-version");
376    }
377    if native_tls.is_some() {
378        masked_fields.push("native-tls");
379    }
380    if offline.is_some() {
381        masked_fields.push("offline");
382    }
383    if no_cache.is_some() {
384        masked_fields.push("no-cache");
385    }
386    if cache_dir.is_some() {
387        masked_fields.push("cache-dir");
388    }
389    if preview.is_some() {
390        masked_fields.push("preview");
391    }
392    if python_preference.is_some() {
393        masked_fields.push("python-preference");
394    }
395    if python_downloads.is_some() {
396        masked_fields.push("python-downloads");
397    }
398    if concurrent_downloads.is_some() {
399        masked_fields.push("concurrent-downloads");
400    }
401    if concurrent_builds.is_some() {
402        masked_fields.push("concurrent-builds");
403    }
404    if concurrent_installs.is_some() {
405        masked_fields.push("concurrent-installs");
406    }
407    if allow_insecure_host.is_some() {
408        masked_fields.push("allow-insecure-host");
409    }
410    if index.is_some() {
411        masked_fields.push("index");
412    }
413    if index_url.is_some() {
414        masked_fields.push("index-url");
415    }
416    if extra_index_url.is_some() {
417        masked_fields.push("extra-index-url");
418    }
419    if no_index.is_some() {
420        masked_fields.push("no-index");
421    }
422    if find_links.is_some() {
423        masked_fields.push("find-links");
424    }
425    if index_strategy.is_some() {
426        masked_fields.push("index-strategy");
427    }
428    if keyring_provider.is_some() {
429        masked_fields.push("keyring-provider");
430    }
431    if resolution.is_some() {
432        masked_fields.push("resolution");
433    }
434    if prerelease.is_some() {
435        masked_fields.push("prerelease");
436    }
437    if fork_strategy.is_some() {
438        masked_fields.push("fork-strategy");
439    }
440    if dependency_metadata.is_some() {
441        masked_fields.push("dependency-metadata");
442    }
443    if config_settings.is_some() {
444        masked_fields.push("config-settings");
445    }
446    if config_settings_package.is_some() {
447        masked_fields.push("config-settings-package");
448    }
449    if no_build_isolation.is_some() {
450        masked_fields.push("no-build-isolation");
451    }
452    if no_build_isolation_package.is_some() {
453        masked_fields.push("no-build-isolation-package");
454    }
455    if extra_build_dependencies.is_some() {
456        masked_fields.push("extra-build-dependencies");
457    }
458    if extra_build_variables.is_some() {
459        masked_fields.push("extra-build-variables");
460    }
461    if exclude_newer.is_some() {
462        masked_fields.push("exclude-newer");
463    }
464    if exclude_newer_package.is_some() {
465        masked_fields.push("exclude-newer-package");
466    }
467    if link_mode.is_some() {
468        masked_fields.push("link-mode");
469    }
470    if compile_bytecode.is_some() {
471        masked_fields.push("compile-bytecode");
472    }
473    if no_sources.is_some() {
474        masked_fields.push("no-sources");
475    }
476    if upgrade.is_some() {
477        masked_fields.push("upgrade");
478    }
479    if upgrade_package.is_some() {
480        masked_fields.push("upgrade-package");
481    }
482    if reinstall.is_some() {
483        masked_fields.push("reinstall");
484    }
485    if reinstall_package.is_some() {
486        masked_fields.push("reinstall-package");
487    }
488    if no_build.is_some() {
489        masked_fields.push("no-build");
490    }
491    if no_build_package.is_some() {
492        masked_fields.push("no-build-package");
493    }
494    if no_binary.is_some() {
495        masked_fields.push("no-binary");
496    }
497    if no_binary_package.is_some() {
498        masked_fields.push("no-binary-package");
499    }
500    if python_install_mirror.is_some() {
501        masked_fields.push("python-install-mirror");
502    }
503    if pypy_install_mirror.is_some() {
504        masked_fields.push("pypy-install-mirror");
505    }
506    if python_downloads_json_url.is_some() {
507        masked_fields.push("python-downloads-json-url");
508    }
509    if publish_url.is_some() {
510        masked_fields.push("publish-url");
511    }
512    if trusted_publishing.is_some() {
513        masked_fields.push("trusted-publishing");
514    }
515    if check_url.is_some() {
516        masked_fields.push("check-url");
517    }
518    if add_bounds.is_some() {
519        masked_fields.push("add-bounds");
520    }
521    if pip.is_some() {
522        masked_fields.push("pip");
523    }
524    if cache_keys.is_some() {
525        masked_fields.push("cache_keys");
526    }
527    if override_dependencies.is_some() {
528        masked_fields.push("override-dependencies");
529    }
530    if exclude_dependencies.is_some() {
531        masked_fields.push("exclude-dependencies");
532    }
533    if constraint_dependencies.is_some() {
534        masked_fields.push("constraint-dependencies");
535    }
536    if build_constraint_dependencies.is_some() {
537        masked_fields.push("build-constraint-dependencies");
538    }
539    if !masked_fields.is_empty() {
540        let field_listing = masked_fields.join("\n- ");
541        warn_user!(
542            "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- {}",
543            field_listing,
544        );
545    }
546}
547
548#[derive(thiserror::Error, Debug)]
549pub enum Error {
550    #[error(transparent)]
551    Io(#[from] std::io::Error),
552
553    #[error(transparent)]
554    Index(#[from] uv_distribution_types::IndexUrlError),
555
556    #[error("Failed to parse: `{}`", _0.user_display())]
557    PyprojectToml(PathBuf, #[source] Box<toml::de::Error>),
558
559    #[error("Failed to parse: `{}`", _0.user_display())]
560    UvToml(PathBuf, #[source] Box<toml::de::Error>),
561
562    #[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
563    )]
564    PyprojectOnlyField(PathBuf, &'static str),
565
566    #[error("Failed to parse environment variable `{name}` with invalid value `{value}`: {err}")]
567    InvalidEnvironmentVariable {
568        name: String,
569        value: String,
570        err: String,
571    },
572}
573
574#[derive(Copy, Clone, Debug)]
575pub struct Concurrency {
576    pub downloads: Option<NonZeroUsize>,
577    pub builds: Option<NonZeroUsize>,
578    pub installs: Option<NonZeroUsize>,
579}
580
581/// Options loaded from environment variables.
582///
583/// This is currently a subset of all respected environment variables, most are parsed via Clap at
584/// the CLI level, however there are limited semantics in that context.
585#[derive(Debug, Clone)]
586pub struct EnvironmentOptions {
587    pub skip_wheel_filename_check: Option<bool>,
588    pub hide_build_output: Option<bool>,
589    pub python_install_bin: Option<bool>,
590    pub python_install_registry: Option<bool>,
591    pub install_mirrors: PythonInstallMirrors,
592    pub log_context: Option<bool>,
593    pub http_timeout: Duration,
594    pub http_retries: u32,
595    pub upload_http_timeout: Duration,
596    pub concurrency: Concurrency,
597    #[cfg(feature = "tracing-durations-export")]
598    pub tracing_durations_file: Option<PathBuf>,
599}
600
601impl EnvironmentOptions {
602    /// Create a new [`EnvironmentOptions`] from environment variables.
603    pub fn new() -> Result<Self, Error> {
604        // Timeout options, matching https://doc.rust-lang.org/nightly/cargo/reference/config.html#httptimeout
605        // `UV_REQUEST_TIMEOUT` is provided for backwards compatibility with v0.1.6
606        let http_timeout = parse_integer_environment_variable(EnvVars::UV_HTTP_TIMEOUT)?
607            .or(parse_integer_environment_variable(
608                EnvVars::UV_REQUEST_TIMEOUT,
609            )?)
610            .or(parse_integer_environment_variable(EnvVars::HTTP_TIMEOUT)?)
611            .map(Duration::from_secs);
612
613        Ok(Self {
614            skip_wheel_filename_check: parse_boolish_environment_variable(
615                EnvVars::UV_SKIP_WHEEL_FILENAME_CHECK,
616            )?,
617            hide_build_output: parse_boolish_environment_variable(EnvVars::UV_HIDE_BUILD_OUTPUT)?,
618            python_install_bin: parse_boolish_environment_variable(EnvVars::UV_PYTHON_INSTALL_BIN)?,
619            python_install_registry: parse_boolish_environment_variable(
620                EnvVars::UV_PYTHON_INSTALL_REGISTRY,
621            )?,
622            concurrency: Concurrency {
623                downloads: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_DOWNLOADS)?,
624                builds: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_BUILDS)?,
625                installs: parse_integer_environment_variable(EnvVars::UV_CONCURRENT_INSTALLS)?,
626            },
627            install_mirrors: PythonInstallMirrors {
628                python_install_mirror: parse_string_environment_variable(
629                    EnvVars::UV_PYTHON_INSTALL_MIRROR,
630                )?,
631                pypy_install_mirror: parse_string_environment_variable(
632                    EnvVars::UV_PYPY_INSTALL_MIRROR,
633                )?,
634                python_downloads_json_url: parse_string_environment_variable(
635                    EnvVars::UV_PYTHON_DOWNLOADS_JSON_URL,
636                )?,
637            },
638            log_context: parse_boolish_environment_variable(EnvVars::UV_LOG_CONTEXT)?,
639            upload_http_timeout: parse_integer_environment_variable(
640                EnvVars::UV_UPLOAD_HTTP_TIMEOUT,
641            )?
642            .map(Duration::from_secs)
643            .or(http_timeout)
644            .unwrap_or(Duration::from_secs(15 * 60)),
645            http_timeout: http_timeout.unwrap_or(Duration::from_secs(30)),
646            http_retries: parse_integer_environment_variable(EnvVars::UV_HTTP_RETRIES)?
647                .unwrap_or(uv_client::DEFAULT_RETRIES),
648            #[cfg(feature = "tracing-durations-export")]
649            tracing_durations_file: parse_path_environment_variable(
650                EnvVars::TRACING_DURATIONS_FILE,
651            ),
652        })
653    }
654}
655
656/// Parse a boolean environment variable.
657///
658/// Adapted from Clap's `BoolishValueParser` which is dual licensed under the MIT and Apache-2.0.
659fn parse_boolish_environment_variable(name: &'static str) -> Result<Option<bool>, Error> {
660    // See `clap_builder/src/util/str_to_bool.rs`
661    // We want to match Clap's accepted values
662
663    // True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
664    const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
665
666    // False values are `n`, `no`, `f`, `false`, `off`, and `0`.
667    const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
668
669    // Converts a string literal representation of truth to true or false.
670    //
671    // `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
672    //
673    // Any other value will be considered as `true`.
674    fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
675        let pat: &str = &val.as_ref().to_lowercase();
676        if TRUE_LITERALS.contains(&pat) {
677            Some(true)
678        } else if FALSE_LITERALS.contains(&pat) {
679            Some(false)
680        } else {
681            None
682        }
683    }
684
685    let Some(value) = std::env::var_os(name) else {
686        return Ok(None);
687    };
688
689    let Some(value) = value.to_str() else {
690        return Err(Error::InvalidEnvironmentVariable {
691            name: name.to_string(),
692            value: value.to_string_lossy().to_string(),
693            err: "expected a valid UTF-8 string".to_string(),
694        });
695    };
696
697    let Some(value) = str_to_bool(value) else {
698        return Err(Error::InvalidEnvironmentVariable {
699            name: name.to_string(),
700            value: value.to_string(),
701            err: "expected a boolish value".to_string(),
702        });
703    };
704
705    Ok(Some(value))
706}
707
708/// Parse a string environment variable.
709fn parse_string_environment_variable(name: &'static str) -> Result<Option<String>, Error> {
710    match std::env::var(name) {
711        Ok(v) => {
712            if v.is_empty() {
713                Ok(None)
714            } else {
715                Ok(Some(v))
716            }
717        }
718        Err(e) => match e {
719            std::env::VarError::NotPresent => Ok(None),
720            std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
721                name: name.to_string(),
722                value: err.to_string_lossy().to_string(),
723                err: "expected a valid UTF-8 string".to_string(),
724            }),
725        },
726    }
727}
728
729fn parse_integer_environment_variable<T>(name: &'static str) -> Result<Option<T>, Error>
730where
731    T: std::str::FromStr + Copy,
732    <T as std::str::FromStr>::Err: std::fmt::Display,
733{
734    let value = match std::env::var(name) {
735        Ok(v) => v,
736        Err(e) => {
737            return match e {
738                std::env::VarError::NotPresent => Ok(None),
739                std::env::VarError::NotUnicode(err) => Err(Error::InvalidEnvironmentVariable {
740                    name: name.to_string(),
741                    value: err.to_string_lossy().to_string(),
742                    err: "expected a valid UTF-8 string".to_string(),
743                }),
744            };
745        }
746    };
747    if value.is_empty() {
748        return Ok(None);
749    }
750
751    match value.parse::<T>() {
752        Ok(v) => Ok(Some(v)),
753        Err(err) => Err(Error::InvalidEnvironmentVariable {
754            name: name.to_string(),
755            value,
756            err: err.to_string(),
757        }),
758    }
759}
760
761#[cfg(feature = "tracing-durations-export")]
762/// Parse a path environment variable.
763fn parse_path_environment_variable(name: &'static str) -> Option<PathBuf> {
764    let value = std::env::var_os(name)?;
765
766    if value.is_empty() {
767        return None;
768    }
769
770    Some(PathBuf::from(value))
771}
772
773/// Populate the [`EnvironmentFlags`] from the given [`EnvironmentOptions`].
774impl From<&EnvironmentOptions> for EnvironmentFlags {
775    fn from(options: &EnvironmentOptions) -> Self {
776        let mut flags = Self::empty();
777        if options.skip_wheel_filename_check == Some(true) {
778            flags.insert(Self::SKIP_WHEEL_FILENAME_CHECK);
779        }
780        if options.hide_build_output == Some(true) {
781            flags.insert(Self::HIDE_BUILD_OUTPUT);
782        }
783        flags
784    }
785}