-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.rs
80 lines (75 loc) · 2.53 KB
/
example.rs
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
use encrypt_config::{Config, NormalSource, PersistSource, SecretSource};
use serde::{Deserialize, Serialize};
#[derive(Default, NormalSource)]
struct NormalConfig {
count: usize,
}
#[derive(Default, Serialize, Deserialize, PersistSource)]
#[cfg_attr(feature = "default_config_dir", source(name = "persist_config.json"))]
#[cfg_attr(
not(feature = "default_config_dir"),
source(path = const_str::concat!(encrypt_config::TEST_OUT_DIR, "/persist_config.json"))
)]
struct PersistConfig {
name: String,
age: usize,
}
#[derive(Default, Serialize, Deserialize, SecretSource)]
#[cfg_attr(
feature = "default_config_dir",
source(name = "secret_config", keyring_entry = "secret")
)]
#[cfg_attr(
not(feature = "default_config_dir"),
source(path = const_str::concat!(encrypt_config::TEST_OUT_DIR, "/secret_config"), keyring_entry = "secret")
)]
struct SecretConfig {
password: String,
}
fn main() {
// clean before test
let files = vec![PersistConfig::path(), SecretConfig::path()];
for file in &files {
std::fs::remove_file(file).ok();
}
{
let cfg: Config<3> = Config::default();
{
let normal = cfg.get::<NormalConfig>();
// default value
assert_eq!(normal.count, 0);
}
{
let mut normal = cfg.get_mut::<NormalConfig>();
normal.count = 42;
assert_eq!(normal.count, 42);
}
{
let mut persist = cfg.get_mut::<PersistConfig>();
persist.name = "Louis".to_string();
persist.age = 22;
let mut secret = cfg.get_mut::<SecretConfig>();
secret.password = "123456".to_string();
}
// Changes will be saved automatically as Config dropped
}
{
// Assume this is a new config in the next start
let cfg: Config<3> = Config::default();
{
// normal config will not be saved
assert_eq!(cfg.get::<NormalConfig>().count, 0);
// persist config will be saved
assert_eq!(cfg.get::<PersistConfig>().name, "Louis");
// secret config will be encrypted
assert_eq!(cfg.get::<SecretConfig>().password, "123456");
}
// The secret config file should not be able to load directly
let encrypted_file = std::fs::File::open(SecretConfig::path()).unwrap();
assert!(serde_json::from_reader::<_, SecretConfig>(encrypted_file).is_err());
}
// clean after test
for file in files {
std::fs::remove_file(file).ok();
}
}