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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
use oauth2::{ClientId, ClientSecret};
use std::sync::Arc;
use std::{collections::HashMap, env, path::PathBuf};
use std::{fs::File, io::Read, process::exit};
use structopt::StructOpt;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GithubOauthConfig {
pub client_id: ClientId,
pub client_secret: ClientSecret,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DiscordConfig {
pub client_id: ClientId,
pub client_secret: ClientSecret,
pub bot_token: String,
pub rcos_guild_id: String,
}
impl DiscordConfig {
pub fn rcos_guild_id(&self) -> u64 {
self.rcos_guild_id
.as_str()
.parse::<u64>()
.expect("Malformed RCOS Guild ID")
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
struct TelescopeConfig {
log_level: Option<String>,
github_credentials: Option<GithubOauthConfig>,
discord_config: Option<DiscordConfig>,
api_url: Option<String>,
jwt_secret: Option<String>,
profile: Option<HashMap<String, TelescopeConfig>>,
telescope_url: Option<String>,
}
#[derive(Serialize, Debug)]
pub struct ConcreteConfig {
log_level: String,
pub github_credentials: GithubOauthConfig,
pub discord_config: DiscordConfig,
pub api_url: String,
pub telescope_url: String,
pub jwt_secret: String,
}
impl TelescopeConfig {
fn make_concrete(&self, profile: Vec<String>) -> ConcreteConfig {
let mut scope = self;
for part in &profile {
if scope
.profile
.as_ref()
.map(|map| map.contains_key(part))
.unwrap_or(false)
{
scope = scope.profile.as_ref().unwrap().get(part).unwrap();
} else {
eprintln!(
"Profile path {:?} not found in config. missing part {}.",
profile, part
);
exit(1)
}
}
let profile_slice = &profile[..];
ConcreteConfig {
log_level: self
.reverse_lookup(profile_slice, |c| c.log_level.clone())
.expect("Could not resolve log level."),
github_credentials: self
.reverse_lookup(profile_slice, |c| c.github_credentials.clone())
.expect("Could not resolve GitHub OAuth credentials."),
discord_config: self
.reverse_lookup(profile_slice, |c| c.discord_config.clone())
.expect("Could not resolve Discord credentials"),
api_url: self
.reverse_lookup(profile_slice, |c| c.api_url.clone())
.expect("Could not resolve RCOS central API URL."),
jwt_secret: self
.reverse_lookup(profile_slice, |c| c.jwt_secret.clone())
.expect("Could not resolve JWT secret."),
telescope_url: self
.reverse_lookup(profile_slice, |c| c.telescope_url.clone())
.expect("Could not resolve Telescope URl."),
}
}
fn reverse_lookup<T: Clone>(
&self,
profile_slice: &[String],
extractor: impl Fn(&Self) -> Option<T> + Copy,
) -> Option<T> {
if profile_slice.len() >= 2 {
let child_path = &profile_slice[1..];
let child = self
.profile
.as_ref()
.unwrap()
.get(&profile_slice[0])
.unwrap();
child
.reverse_lookup(child_path, extractor)
.or(extractor(self))
} else if profile_slice.len() == 1 {
extractor(
self.profile
.as_ref()
.unwrap()
.get(&profile_slice[0])
.unwrap(),
)
.or(extractor(self))
} else {
extractor(self)
}
}
}
#[derive(Debug, Serialize, StructOpt)]
#[structopt(about = "The RCOS webapp", rename_all = "screaming-snake")]
struct CommandLine {
#[structopt(short = "c", long = "config", env, default_value = "config.toml")]
config_file: PathBuf,
#[structopt(short = "p", long = "profile", env)]
profile: Option<String>,
}
lazy_static! {
pub static ref CONFIG: Arc<ConcreteConfig> = Arc::new(cli());
}
pub fn init() {
let cfg: &ConcreteConfig = &*CONFIG;
env_logger::builder().parse_filters(&cfg.log_level).init();
info!("Starting up...");
info!("telescope {}", env!("CARGO_PKG_VERSION"));
trace!("Config: \n{}", serde_json::to_string_pretty(cfg).unwrap());
}
pub fn global_config() -> Arc<ConcreteConfig> {
CONFIG.clone()
}
fn cli() -> ConcreteConfig {
dotenv::dotenv().ok();
let commandline: CommandLine = CommandLine::from_args();
let mut confing_file_string = String::new();
File::open(&commandline.config_file)
.map_err(|e| {
eprintln!(
"Could not open config file at {}: {}",
commandline.config_file.display(),
e
);
e
})
.unwrap()
.read_to_string(&mut confing_file_string)
.map_err(|e| {
eprintln!(
"Could not read config file at {}: {}",
commandline.config_file.display(),
e
);
e
})
.unwrap();
let parsed = toml::from_str::<TelescopeConfig>(confing_file_string.as_str())
.map_err(|e| {
eprintln!("Error deserializing config file: {}", e);
e
})
.unwrap();
let profile_path: Vec<String> = commandline
.profile
.map(|s| s.split(".").map(|p| p.to_string()).collect())
.unwrap_or(Vec::new());
return parsed.make_concrete(profile_path);
}