Skip to content

feat(env::var): add remove_var function #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,17 @@ assert!(!current_dir.ends_with("src"));
assert!(std::env::var("TEST_TMP_ENV").is_err());
```

- To temporary create a directory
- To temporary remove an environment variable:

```rust
{
let _tmp_env = tmp_env::remove_var("TEST_TMP_ENV");
assert!(std::env::var("TEST_TMP_ENV").is_err());
}
// The environment variable is now restored
```

- To temporary create a directory:

```rust
{
Expand Down
39 changes: 39 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,26 @@ pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) -> CurrentEnv
CurrentEnv(key.to_owned(), previous_val)
}

/// Removes the environment variable k for the currently running process.
/// It returns a datastructure to keep the environment variable removed. When dropped the environment variable is restored
/// ```
/// std::env::set_var("TEST_TMP_ENV", "myvalue");
/// assert_eq!(std::env::var("TEST_TMP_ENV"), Ok(String::from("myvalue")));
/// {
/// let _tmp_env = tmp_env::remove_var("TEST_TMP_ENV");
/// assert!(std::env::var("TEST_TMP_ENV").is_err());
/// }
/// // Because guard is dropped then the environment variable is also automatically restored
/// tmp_env::remove_var("TEST_TMP_ENV");
/// assert_eq!(std::env::var("TEST_TMP_ENV"), Ok(String::from("myvalue")));
/// ```
pub fn remove_var<K: AsRef<OsStr>>(key: K) -> CurrentEnv {
let key = key.as_ref();
let previous_val = std::env::var(key).ok();
std::env::remove_var(key);
CurrentEnv(key.to_owned(), previous_val)
}

impl Drop for CurrentEnv {
fn drop(&mut self) {
match self.1.take() {
Expand Down Expand Up @@ -174,6 +194,25 @@ mod tests {
);
}

#[test]
fn test_remove_env() {
let _tmp_env = remove_var("TEST_TMP_ENV");
assert!(std::env::var("TEST_TMP_ENV").is_err());
}

#[test]
fn test_remove_env_with_previous_value() {
std::env::set_var("TEST_TMP_ENV_PREVIOUS", "previous_value");
{
let _tmp_env = remove_var("TEST_TMP_ENV_PREVIOUS");
assert!(std::env::var("TEST_TMP_ENV_PREVIOUS").is_err());
}
assert_eq!(
std::env::var("TEST_TMP_ENV_PREVIOUS"),
Ok(String::from("previous_value"))
);
}

#[test]
fn test_current_dir() {
{
Expand Down