Skip to main content

uv_static/
lib.rs

1pub use env_vars::*;
2pub use known_stdlib::*;
3
4mod env_vars;
5mod known_stdlib;
6
7use std::borrow::Cow;
8
9use thiserror::Error;
10
11/// The implementation used to read and write tar archives.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13pub enum TarBackend {
14    #[default]
15    TarCodec,
16    TokioTar,
17}
18
19impl TarBackend {
20    /// Select the tar implementation, allowing users to enable the legacy backend.
21    pub fn from_env() -> Self {
22        if matches!(
23            parse_boolish_environment_variable(EnvVars::UV_LEGACY_TAR_BACKEND),
24            Ok(Some(true))
25        ) {
26            Self::TokioTar
27        } else {
28            Self::TarCodec
29        }
30    }
31}
32
33/// The base URL for the default Astral mirror.
34const ASTRAL_MIRROR_BASE_URL: &str = "https://releases.astral.sh";
35
36/// Read the user-configured Astral mirror URL from the environment, if set.
37pub fn astral_mirror_url_from_env() -> Option<String> {
38    std::env::var_os(EnvVars::UV_ASTRAL_MIRROR_URL).and_then(|url| {
39        if url.as_os_str().is_empty() {
40            None
41        } else {
42            Some(url.to_string_lossy().into_owned())
43        }
44    })
45}
46
47/// Return the effective Astral mirror base URL, using the default mirror when unset.
48pub fn astral_mirror_base_url(astral_mirror_url: Option<&str>) -> Cow<'_, str> {
49    custom_astral_mirror_url(astral_mirror_url)
50        .map(|url| Cow::Borrowed(url.trim_end_matches('/')))
51        .unwrap_or(Cow::Borrowed(ASTRAL_MIRROR_BASE_URL))
52}
53
54/// Return a user-configured Astral mirror URL, treating empty values as unset.
55pub fn custom_astral_mirror_url(astral_mirror_url: Option<&str>) -> Option<&str> {
56    astral_mirror_url.filter(|url| !url.is_empty())
57}
58
59#[derive(Debug, Error)]
60#[error("Failed to parse environment variable `{name}` with invalid value `{value}`: {err}")]
61pub struct InvalidEnvironmentVariable {
62    pub name: String,
63    pub value: String,
64    pub err: String,
65}
66
67/// Parse a boolean environment variable.
68///
69/// Adapted from Clap's `BoolishValueParser` which is dual licensed under the MIT and Apache-2.0.
70pub fn parse_boolish_environment_variable(
71    name: &'static str,
72) -> Result<Option<bool>, InvalidEnvironmentVariable> {
73    // See `clap_builder/src/util/str_to_bool.rs`
74    // We want to match Clap's accepted values
75
76    // True values are `y`, `yes`, `t`, `true`, `on`, and `1`.
77    const TRUE_LITERALS: [&str; 6] = ["y", "yes", "t", "true", "on", "1"];
78
79    // False values are `n`, `no`, `f`, `false`, `off`, and `0`.
80    const FALSE_LITERALS: [&str; 6] = ["n", "no", "f", "false", "off", "0"];
81
82    // Converts a string literal representation of truth to true or false.
83    //
84    // `false` values are `n`, `no`, `f`, `false`, `off`, and `0` (case insensitive).
85    //
86    // Any other value will be considered as `true`.
87    fn str_to_bool(val: impl AsRef<str>) -> Option<bool> {
88        let pat: &str = &val.as_ref().to_ascii_lowercase();
89        if TRUE_LITERALS.contains(&pat) {
90            Some(true)
91        } else if FALSE_LITERALS.contains(&pat) {
92            Some(false)
93        } else {
94            None
95        }
96    }
97
98    let Some(value) = std::env::var_os(name) else {
99        return Ok(None);
100    };
101
102    let Some(value) = value.to_str() else {
103        return Err(InvalidEnvironmentVariable {
104            name: name.to_string(),
105            value: value.to_string_lossy().to_string(),
106            err: "expected a valid UTF-8 string".to_string(),
107        });
108    };
109
110    let Some(value) = str_to_bool(value) else {
111        return Err(InvalidEnvironmentVariable {
112            name: name.to_string(),
113            value: value.to_string(),
114            err: "expected a boolish value".to_string(),
115        });
116    };
117
118    Ok(Some(value))
119}