-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.rs
53 lines (50 loc) · 1.68 KB
/
config.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
use {
std::io,
serde::Deserialize,
tokio::io::AsyncReadExt as _,
wheel::fs::File,
};
#[cfg(unix)] use futures::{
pin_mut,
stream::{
self,
StreamExt as _,
},
};
#[cfg(windows)] use directories::ProjectDirs;
#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
#[error(transparent)] Io(#[from] io::Error),
#[error(transparent)] Json(#[from] serde_json::Error),
#[cfg(windows)] #[error(transparent)] Wheel(#[from] wheel::Error),
#[cfg(unix)]
#[error("config file missing, create at $XDG_CONFIG_DIRS/fidera/client-config.json")]
MissingConfig,
#[cfg(windows)]
#[error("user folder not found")]
MissingHomeDir,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct Config {
pub(crate) api_key: String,
}
impl Config {
pub(crate) async fn new() -> Result<Config, Error> {
let mut file = {
#[cfg(unix)] {
let dirs = stream::iter(xdg_basedir::get_config_home().into_iter().chain(xdg_basedir::get_config_dirs()));
let files = dirs.filter_map(|cfg_dir| async move { File::open(cfg_dir.join("fidera/client-config.json")).await.ok() });
pin_mut!(files);
files.next().await.ok_or(Error::MissingConfig)?
}
#[cfg(windows)] {
let config_path = ProjectDirs::from("org", "Gefolge", "sil").ok_or(Error::MissingHomeDir)?.config_dir().join("client-config.json");
File::open(&config_path).await?
}
};
let mut buf = String::default();
file.read_to_string(&mut buf).await?;
Ok(serde_json::from_str(&buf)?) //TODO use async-json instead
}
}