#env #temp #directory #guard #drop #env-var

tmp_env

A crate which lets you create temporary environment and be automatically restored/cleaned when not needed

2 releases

0.1.1 Jun 16, 2021
0.1.0 Jun 9, 2021

#496 in Configuration

Download history 442/week @ 2024-07-28 353/week @ 2024-08-04 689/week @ 2024-08-11 407/week @ 2024-08-18 417/week @ 2024-08-25 922/week @ 2024-09-01 424/week @ 2024-09-08 242/week @ 2024-09-15 659/week @ 2024-09-22 371/week @ 2024-09-29 183/week @ 2024-10-06 255/week @ 2024-10-13 90/week @ 2024-10-20 130/week @ 2024-10-27 140/week @ 2024-11-03 237/week @ 2024-11-10

623 downloads per month
Used in 2 crates

Custom license

11KB
132 lines

tmp_env

Version Documentation

tmp_env is a crate which lets you create temporary environment and be automatically cleaned when not needed.

For example sometimes you need to change the current directory or set environment variables to launch a process but you don't need this temporary environment for the rest of your program. Then you will use tmp_env to create environment variable using tmp_env::set_var instead of std::env::set_var to get from tmp_env::set_var a datastructure which will automatically restore the corresponding environment variable when dropped.

Install

Put this dependency in your Cargo.toml

tmp_env = "0.1"

Usage

  • To temporary change the current directory:
{
    let _tmp_current_dir = tmp_env::set_current_dir("src").expect("should set the new current_dir");
    let current_dir = std::env::current_dir().expect("cannot get current dir from std env");
    assert!(current_dir.ends_with("src"));
}
let current_dir = std::env::current_dir().expect("cannot get current dir from std env");
assert!(!current_dir.ends_with("src"));
  • To temporary set an environment variable:
{
    let _tmp_env = tmp_env::set_var("TEST_TMP_ENV", "myvalue");
    assert_eq!(std::env::var("TEST_TMP_ENV"), Ok(String::from("myvalue")));
}
// Because guard `_tmp_env` is dropped then the environment variable is also automatically unset (not restored because no previous value was set)
assert!(std::env::var("TEST_TMP_ENV").is_err());
  • To temporary create a directory
{
    let tmp_dir = tmp_env::create_temp_dir().expect("cannot create temp dir"); // When tmp_dir is dropped this temporary dir will be removed
    assert!(std::fs::metadata(&*tmp_dir).is_ok());
}
// The temporary directory is now removed

Dependencies

~310KB