Skip to content

Commit

Permalink
Change env var getters to error recoverably
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
inquisitivecrystal committed Jul 6, 2021
1 parent d5a406b commit f2c0f29
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions library/std/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,8 @@ impl fmt::Debug for VarsOs {
/// Errors if the environment variable is not present.
/// Errors if the environment variable is not valid Unicode. If this is not desired, consider using
/// [`var_os`].
///
/// # 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.
/// 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
///
Expand All @@ -219,18 +215,18 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
}

/// Fetches the environment variable `key` from the current process, returning
/// [`None`] if the variable isn't set.
///
/// # 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.
/// [`None`] if the variable isn't set or there's another error.
///
/// 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,
/// 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
///
/// ```
Expand All @@ -248,8 +244,7 @@ pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
}

fn _var_os(key: &OsStr) -> Option<OsString> {
os_imp::getenv(key)
.unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
os_imp::getenv(key).ok()?
}

/// The error type for operations interacting with environment variables.
Expand Down

0 comments on commit f2c0f29

Please sign in to comment.