Skip to main content

leetcode_cli/config/
mod.rs

1//! Soft-link with `config.toml`
2//!
3//! leetcode-cli will generate a `leetcode.toml` by default,
4//! if you wanna change to it, you can:
5//!
6//! + Edit leetcode.toml at `~/.leetcode/leetcode.toml` directly
7//! + Use `leetcode config` to update it
8use crate::{
9    Error, Result,
10    config::{code::Code, cookies::Cookies, storage::Storage, sys::Sys},
11};
12use serde::{Deserialize, Serialize};
13use std::{fs, path::Path, str::FromStr};
14
15mod code;
16mod cookies;
17mod storage;
18mod sys;
19
20pub use cookies::LeetcodeSite;
21
22/// Sync with `~/.leetcode/leetcode.toml`
23#[derive(Clone, Debug, Default, Deserialize, Serialize)]
24pub struct Config {
25    #[serde(default, skip_serializing)]
26    pub sys: Sys,
27    pub code: Code,
28    pub cookies: Cookies,
29    pub storage: Storage,
30}
31
32impl Config {
33    fn write_default(p: impl AsRef<Path>) -> Result<()> {
34        fs::write(p.as_ref(), toml::ser::to_string_pretty(&Self::default())?)?;
35
36        Ok(())
37    }
38
39    /// Locate lc's config file
40    pub fn locate() -> Result<Config> {
41        let conf = Self::root()?.join("leetcode.toml");
42
43        if !conf.is_file() {
44            Self::write_default(&conf)?;
45        }
46
47        fs::read_to_string(&conf)?
48            .parse::<Config>()
49            .inspect_err(|_| {
50                let _ = Self::write_default(conf.with_file_name("leetcode.tmp.toml"));
51            })
52    }
53
54    /// Get root path of leetcode-cli
55    pub fn root() -> Result<std::path::PathBuf> {
56        let dir = dirs::home_dir().ok_or(Error::NoneError)?.join(".leetcode");
57        if !dir.is_dir() {
58            info!("Generate root dir at {:?}.", dir);
59            fs::DirBuilder::new().recursive(true).create(&dir)?;
60        }
61
62        Ok(dir)
63    }
64
65    /// Sync new config to config.toml
66    pub fn sync(&self) -> Result<()> {
67        let home = dirs::home_dir().ok_or(Error::NoneError)?;
68        let conf = home.join(".leetcode/leetcode.toml");
69        fs::write(conf, toml::ser::to_string_pretty(&self)?)?;
70
71        Ok(())
72    }
73}
74
75impl FromStr for Config {
76    type Err = Error;
77
78    /// Parses `leetcode.toml`, applying the environment overrides on top of it.
79    fn from_str(s: &str) -> Result<Self> {
80        let mut config: Config = toml::from_str(s)?;
81
82        config.code = config.code.with_env_override();
83        config.cookies = config.cookies.with_env_override();
84
85        if let cookies::LeetcodeSite::LeetcodeCn = config.cookies.site {
86            config.sys.urls = sys::Urls::new_with_leetcode_cn();
87        }
88
89        Ok(config)
90    }
91}