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
203
204
205
206
207
208
209
use std::env;
use std::path::Path;
use std::sync::Arc;
use config::{Config, ConfigError, Environment, File};
use derive_more::Display;
#[cfg(not(test))]
use log::{error, warn};
#[cfg(test)]
use std::{println as warn, println as error};
use serde::Deserialize;
use serde::Serialize;
use url::Url;
use crate::errors::*;
use crate::page::Page;
#[derive(Debug, Clone, Deserialize)]
pub struct Server {
pub port: u32,
pub ip: String,
pub workers: Option<usize>,
pub cookie_secret: String,
pub domain: String,
}
impl Server {
#[cfg(not(tarpaulin_include))]
pub fn get_ip(&self) -> String {
format!("{}:{}", self.ip, self.port)
}
}
#[derive(Deserialize, Serialize, Display, Eq, PartialEq, Clone, Debug)]
#[serde(rename_all = "lowercase")]
pub enum DBType {
#[display(fmt = "postgres")]
Postgres,
}
impl DBType {
fn from_url(url: &Url) -> Result<Self, ConfigError> {
match url.scheme() {
"postgres" => Ok(Self::Postgres),
_ => Err(ConfigError::Message("Unknown database type".into())),
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Database {
pub url: String,
pub pool: u32,
pub database_type: DBType,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Settings {
pub allow_registration: bool,
pub debug: bool,
pub server: Server,
pub source_code: String,
pub pages: Vec<Arc<Page>>,
pub database: Database,
}
#[cfg(not(tarpaulin_include))]
impl Settings {
pub fn new() -> ServiceResult<Self> {
let mut s = Config::builder();
const CURRENT_DIR: &str = "./config/default.toml";
const ETC: &str = "/etc/static-pages/config.toml";
let mut read_file = false;
if Path::new(ETC).exists() {
s = s.add_source(File::with_name(ETC));
read_file = true;
}
if Path::new(CURRENT_DIR).exists() {
s = s.add_source(File::with_name(CURRENT_DIR));
read_file = true;
}
if let Ok(path) = env::var("PAGES_CONFIG") {
s = s.add_source(File::with_name(&path));
read_file = true;
}
if !read_file {
warn!("configuration file not found");
}
s = s.add_source(Environment::with_prefix("PAGES").separator("__"));
match env::var("PORT") {
Ok(val) => {
s = s.set_override("server.port", val).unwrap();
}
Err(e) => warn!("couldn't interpret PORT: {}", e),
}
if let Ok(val) = env::var("DATABASE_URL") {
let url = Url::parse(&val).expect("couldn't parse Database URL");
s = s.set_override("database.url", url.to_string()).unwrap();
let database_type = DBType::from_url(&url).unwrap();
s = s
.set_override("database.database_type", database_type.to_string())
.unwrap();
}
let intermediate_config = s.build_cloned().unwrap();
s = s
.set_override(
"database.url",
format!(
r"postgres://{}:{}@{}:{}/{}",
intermediate_config
.get::<String>("database.username")
.expect("Couldn't access database username"),
intermediate_config
.get::<String>("database.password")
.expect("Couldn't access database password"),
intermediate_config
.get::<String>("database.hostname")
.expect("Couldn't access database hostname"),
intermediate_config
.get::<String>("database.port")
.expect("Couldn't access database port"),
intermediate_config
.get::<String>("database.name")
.expect("Couldn't access database name")
),
)
.expect("Couldn't set database url");
let settings = s.build()?.try_deserialize::<Settings>()?;
settings.check_url();
Ok(settings)
}
pub fn init(&self) {
for (index, page) in self.pages.iter().enumerate() {
Url::parse(&page.repo).unwrap();
let path = Path::new(&page.path);
if path.exists() && path.is_file() {
panic!("Path is a file, should be a directory: {:?}", page);
}
if !path.exists() {
std::fs::create_dir_all(&path).unwrap();
}
for (index2, page2) in self.pages.iter().enumerate() {
if index2 == index {
continue;
}
if page.secret == page2.secret {
error!("{}", ServiceError::SecretTaken(page.clone(), page2.clone()));
} else if page.repo == page2.repo {
error!(
"{}",
ServiceError::DuplicateRepositoryURL(page.clone(), page2.clone(),)
);
} else if page.path == page2.path {
error!("{}", ServiceError::PathTaken(page.clone(), page2.clone()));
}
}
if let Err(e) = page.update(&page.branch) {
error!("{e}");
}
}
}
#[cfg(not(tarpaulin_include))]
fn check_url(&self) {
Url::parse(&self.source_code).expect("Please enter a URL for source_code in settings");
}
}