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
use std::env;
use std::fs;
use std::path::Path;
use config::{Config, ConfigError, Environment, File};
use log::warn;
use serde::Deserialize;
use url::Url;
#[derive(Debug, Clone, Deserialize)]
pub struct Server {
pub port: u32,
pub domain: String,
pub ip: String,
pub proxy_has_tls: bool,
pub workers: Option<usize>,
}
impl Server {
#[cfg(not(tarpaulin_include))]
pub fn get_ip(&self) -> String {
format!("{}:{}", self.ip, self.port)
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
pub debug: bool,
pub cache: Option<String>,
pub server: Server,
pub source_code: String,
}
#[cfg(not(tarpaulin_include))]
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let mut s = Config::new();
#[cfg(test)]
s.set_default("database.pool", 2.to_string())
.expect("Couldn't get the number of CPUs");
const CURRENT_DIR: &str = "./config/default.toml";
const ETC: &str = "/etc/libmedium/config.toml";
if let Ok(path) = env::var("LIBMEDIUM") {
s.merge(File::with_name(&path))?;
} else if Path::new(CURRENT_DIR).exists() {
s.merge(File::with_name(CURRENT_DIR))?;
} else if Path::new(ETC).exists() {
s.merge(File::with_name(ETC))?;
} else {
log::warn!("configuration file not found");
}
s.merge(Environment::with_prefix("PAGES").separator("__"))?;
check_url(&s);
match env::var("PORT") {
Ok(val) => {
s.set("server.port", val).unwrap();
}
Err(e) => warn!("couldn't interpret PORT: {}", e),
}
let mut settings: Settings = s.try_into()?;
if settings.cache.is_none() {
let tmp = env::temp_dir().join("libmedium_cache_path");
if !tmp.exists() {
fs::create_dir_all(&tmp).unwrap()
}
settings.cache = Some(tmp.to_str().unwrap().to_string())
}
let cache_path = settings.cache.as_ref().unwrap();
let cache_path = Path::new(&cache_path);
if !cache_path.exists() {
fs::create_dir(&cache_path).unwrap();
}
if !cache_path.is_dir() {
panic!(
"Cache path {} must be a directory",
&settings.cache.as_ref().unwrap()
);
}
Ok(settings)
}
}
#[cfg(not(tarpaulin_include))]
fn check_url(s: &Config) {
let url = s
.get::<String>("source_code")
.expect("Couldn't access source_code");
Url::parse(&url).expect("Please enter a URL for source_code in settings");
}