Skip to main content

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