smbcloud_utils/
lib.rs

1use {
2    anyhow::{anyhow, Result},
3    log::debug,
4    regex::Regex,
5    smbcloud_model::project::Config,
6    std::{fs::OpenOptions, io::Write},
7};
8
9pub mod config;
10pub mod write_config;
11
12pub fn email_validation(input: &str) -> Result<(), &'static str> {
13    let email_regex = Regex::new(
14        r"^([a-z0-9_+]([a-z0-9_+.]*[a-z0-9_+])?)@([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})",
15    )
16    .unwrap();
17
18    if email_regex.is_match(input) {
19        Ok(())
20    } else {
21        Err("Username must be an email address.")
22    }
23}
24
25pub async fn get_config() -> Result<Config> {
26    match home::home_dir() {
27        Some(mut path) => {
28            path.push(".smb/config.json");
29            if !path.exists() {
30                let config = Config {
31                    current_project: None,
32                    current_auth_app: None,
33                };
34                return Ok(config);
35            }
36            let config_string = std::fs::read_to_string(path).map_err(|e| {
37                debug!("Error while reading config file: {}", &e);
38                anyhow!("Error while reading config file. Are you logged in?")
39            })?;
40            let config: Config = serde_json::from_str(&config_string).map_err(|e| {
41                debug!("Error while parsing config: {}", &e);
42                anyhow!("Error while parsing config. Are you logged in?")
43            })?;
44
45            Ok(config)
46        }
47        None => {
48            let config = Config {
49                current_project: None,
50                current_auth_app: None,
51            };
52            Ok(config)
53        }
54    }
55}
56
57pub fn write_config(config: Config) -> Result<Config> {
58    match home::home_dir() {
59        Some(path) => {
60            debug!("{}", path.to_str().unwrap());
61            let mut file = OpenOptions::new()
62                .create(true)
63                .truncate(true)
64                .write(true)
65                .open([path.to_str().unwrap(), "/.smb/config.json"].join(""))?;
66            let json = serde_json::to_string(&config)?;
67            file.write_all(json.as_bytes())?;
68
69            Ok(config)
70        }
71        None => Err(anyhow!("Error getting home directory.")),
72    }
73}