sofe_cratesio_hyphen_test/
lib.rs

1use snafu::{ensure, Backtrace, ErrorCompat, ResultExt, Snafu};
2use std::{
3    fs,
4    path::{Path, PathBuf},
5};
6
7const CONFIG_DIRECTORY : &str = "";
8const USER_ID : i32 = 0;
9
10#[derive(Debug, Snafu)]
11pub enum Error {
12    #[snafu(display("Could not open config from {}: {}", filename.display(), source))]
13    OpenConfig {
14        filename: PathBuf,
15        source: std::io::Error,
16    },
17    #[snafu(display("Could not save config to {}: {}", filename.display(), source))]
18    SaveConfig {
19        filename: PathBuf,
20        source: std::io::Error,
21    },
22    #[snafu(display("The user id {} is invalid", user_id))]
23    UserIdInvalid { user_id: i32, backtrace: Backtrace },
24}
25
26pub type Result<T, E = Error> = std::result::Result<T, E>;
27
28pub fn log_in_user<P>(config_root: P, user_id: i32) -> Result<bool>
29where
30    P: AsRef<Path>,
31{
32    let config_root = config_root.as_ref();
33    let filename = &config_root.join("config.toml");
34
35    let config = fs::read(filename).context(OpenConfig { filename })?;
36    // Perform updates to config
37    fs::write(filename, config).context(SaveConfig { filename })?;
38
39    ensure!(user_id == 42, UserIdInvalid { user_id });
40
41    Ok(true)
42}
43
44pub fn log_in() {
45    match log_in_user(CONFIG_DIRECTORY, USER_ID) {
46        Ok(true) => println!("Logged in!"),
47        Ok(false) => println!("Not logged in!"),
48        Err(e) => {
49            eprintln!("An error occurred: {}", e);
50            if let Some(backtrace) = ErrorCompat::backtrace(&e) {
51                println!("{}", backtrace);
52            }
53        }
54    }
55}