1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::{
ffi::{OsStr, OsString},
fmt::Debug,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
pub struct CurrentDir(std::path::PathBuf);
impl Debug for CurrentDir {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
pub fn set_current_dir<P: AsRef<Path>>(path: P) -> Result<CurrentDir, std::io::Error> {
let current_dir = std::env::current_dir()?;
std::env::set_current_dir(&path)?;
Ok(CurrentDir(current_dir))
}
impl Drop for CurrentDir {
fn drop(&mut self) {
std::env::set_current_dir(&self.0).expect("cannot go back to the previous directory");
}
}
pub struct CurrentEnv(OsString, Option<String>);
impl Debug for CurrentEnv {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) -> CurrentEnv {
let key = key.as_ref();
let previous_val = std::env::var(key).ok();
std::env::set_var(key, value);
CurrentEnv(key.to_owned(), previous_val)
}
impl Drop for CurrentEnv {
fn drop(&mut self) {
match self.1.take() {
Some(previous_val) => std::env::set_var(&self.0, previous_val),
None => std::env::remove_var(&self.0),
}
}
}
pub struct TmpDir(pub(crate) PathBuf);
impl Deref for TmpDir {
type Target = PathBuf;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for TmpDir {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Debug for TmpDir {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
pub fn create_temp_dir() -> Result<TmpDir, std::io::Error> {
let tmp_dir = std::env::temp_dir();
let tmp_path = tmp_dir.join(random_path());
std::fs::create_dir(&tmp_path)?;
Ok(TmpDir(tmp_path))
}
impl Drop for TmpDir {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.0).expect("cannot delete the tmp dir")
}
}
fn random_path() -> PathBuf {
let rand_string: String = thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect();
PathBuf::from(rand_string)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_env() {
{
let _tmp_env = set_var("TEST_TMP_ENV", "myvalue");
assert_eq!(std::env::var("TEST_TMP_ENV"), Ok(String::from("myvalue")));
}
assert!(std::env::var("TEST_TMP_ENV").is_err());
set_var("TEST_TMP_ENV_DROPPED", "myvaluedropped");
assert!(std::env::var("TEST_TMP_ENV_DROPPED").is_err());
}
#[test]
fn test_env_with_previous_value() {
std::env::set_var("TEST_TMP_ENV_PREVIOUS", "previous_value");
{
let _tmp_env = set_var("TEST_TMP_ENV_PREVIOUS", "myvalue");
assert_eq!(
std::env::var("TEST_TMP_ENV_PREVIOUS"),
Ok(String::from("myvalue"))
);
}
assert_eq!(
std::env::var("TEST_TMP_ENV_PREVIOUS"),
Ok(String::from("previous_value"))
);
}
#[test]
fn test_current_dir() {
{
let _tmp_current_dir = 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"));
set_current_dir("target").expect("should set the new current_dir");
assert!(!current_dir.ends_with("target"));
}
#[test]
fn test_tmp_dir() {
#[allow(unused_assignments)]
let mut tmp_dir_created: Option<PathBuf> = None;
{
let tmp_dir = create_temp_dir().expect("cannot create temp dir");
tmp_dir_created = Some(tmp_dir.0.clone());
assert!(std::fs::metadata(&*tmp_dir).is_ok());
}
assert!(std::fs::metadata(tmp_dir_created.unwrap()).is_err());
}
}