leetcode_tui_config/
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
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
use super::theme::Theme;
use crate::utils::{get_config_dir, get_config_file_path};
use color_eyre::Result;
use leetcode_tui_shared::RoCell;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::prelude::*;
use std::{fs::create_dir_all, path::PathBuf};
pub static CONFIG: RoCell<Config> = RoCell::new();

pub fn init() -> Result<()> {
    CONFIG.init({
        let config_file = get_config_file_path();
        if !config_file.exists() {
            Config::create_default_config(&config_file);
            Config::create_default_solution_dir();
            println!(
                "Please fill in leetcode_sesion and csrftoken in config file @ {}!",
                config_file.display()
            );
            std::process::exit(0);
        }
        let contents = std::fs::read_to_string(&config_file)?;
        toml::from_str(&contents)?
    });
    Ok(())
}

fn get_solutions_dir_path() -> PathBuf {
    get_config_dir().join("solutions")
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct Config {
    pub csrftoken: String,
    pub lc_session: String,
    #[serde(default)]
    pub db: Database,
    #[serde(default = "get_solutions_dir_path")]
    pub solutions_dir: PathBuf,
    #[serde(default)]
    pub theme: Theme,
}

impl Config {
    fn create_default_solution_dir() {
        create_dir_all(get_solutions_dir_path()).unwrap();
    }

    fn create_default_config(config_file: &PathBuf) {
        let config_dir = config_file.as_path().parent().expect(&format!(
            "Cannot get parent of the file path: {}",
            config_file.display()
        ));
        create_dir_all(config_dir)
            .expect(format!("Cannot create config directory @ {}", config_dir.display()).as_str());
        let default_config = Self::default();
        let default_config_str =
            toml::to_string(&default_config).expect("Cannot serialize default config to string.");
        let mut file = File::create(&config_file)
            .expect(format!("Cannot create file @ {}", config_file.display()).as_str());
        file.write_all(default_config_str.as_bytes()).expect(
            format!(
                "Cannot write to the config file @ {}",
                config_file.display()
            )
            .as_str(),
        );
    }
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Database {
    pub path: PathBuf,
}

impl Default for Database {
    fn default() -> Self {
        Self {
            path: get_config_dir().join("questions.db"),
        }
    }
}