humble_cli/
config.rs

1use std::path::PathBuf;
2
3use anyhow::{anyhow, Context};
4
5#[derive(Debug)]
6pub struct Config {
7    pub session_key: String,
8}
9
10pub fn get_config() -> Result<Config, anyhow::Error> {
11    let file_name = get_config_file_name()?;
12    let session_key = std::fs::read_to_string(&file_name).with_context(|| {
13        format!(
14            "failed to read the session key from `{}` file",
15            &file_name.to_str().unwrap()
16        )
17    })?;
18
19    let session_key = session_key.trim_end().to_owned();
20
21    Ok(Config { session_key })
22}
23
24pub fn set_config(config: Config) -> Result<(), anyhow::Error> {
25    let file_name = get_config_file_name()?;
26
27    std::fs::write(file_name, config.session_key)?;
28
29    Ok(())
30}
31
32fn get_config_file_name() -> anyhow::Result<PathBuf> {
33    let mut home = dirs::home_dir().ok_or_else(|| anyhow!("cannot find the home directory"))?;
34    home.push(".humble-cli-key");
35    Ok(home)
36}