Change env var getters to error recoverably

Before this, `std`'s env var getter functions would panic on
receiving certain invalid inputs. This commit makes them
return a `None` or `Err` instead.
This commit is contained in:
Aris Merchant 2021-06-09 00:40:31 -07:00
parent d5a406bb66
commit f2c0f29248

View File

@ -188,12 +188,8 @@ impl fmt::Debug for VarsOs {
/// Errors if the environment variable is not present. /// Errors if the environment variable is not present.
/// Errors if the environment variable is not valid Unicode. If this is not desired, consider using /// Errors if the environment variable is not valid Unicode. If this is not desired, consider using
/// [`var_os`]. /// [`var_os`].
/// /// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`.
/// # Panics /// May error when the value contains the NUL character.
///
/// This function may panic if `key` is empty, contains an ASCII equals sign
/// `'='` or the NUL character `'\0'`, or when the value contains the NUL
/// character.
/// ///
/// # Examples /// # Examples
/// ///
@ -219,18 +215,18 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
} }
/// Fetches the environment variable `key` from the current process, returning /// Fetches the environment variable `key` from the current process, returning
/// [`None`] if the variable isn't set. /// [`None`] if the variable isn't set or there's another error.
///
/// # Panics
///
/// This function may panic if `key` is empty, contains an ASCII equals sign
/// `'='` or the NUL character `'\0'`, or when the value contains the NUL
/// character.
/// ///
/// Note that the method will not check if the environment variable /// Note that the method will not check if the environment variable
/// is valid Unicode. If you want to have an error on invalid UTF-8, /// is valid Unicode. If you want to have an error on invalid UTF-8,
/// use the [`var`] function instead. /// use the [`var`] function instead.
/// ///
/// # Errors
///
/// Errors if the variable isn't set.
/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`.
/// May error when the value contains the NUL character.
///
/// # Examples /// # Examples
/// ///
/// ``` /// ```
@ -248,8 +244,7 @@ pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
} }
fn _var_os(key: &OsStr) -> Option<OsString> { fn _var_os(key: &OsStr) -> Option<OsString> {
os_imp::getenv(key) os_imp::getenv(key).ok()?
.unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
} }
/// The error type for operations interacting with environment variables. /// The error type for operations interacting with environment variables.