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
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use crate::{LeetUpError, Result};
use serde::{de::DeserializeOwned, Deserialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;

type LangInjectCode = HashMap<String, InjectCode>;
type PickHookConfig = HashMap<String, PickHook>;

#[derive(Debug, Deserialize)]
pub struct Config {
    #[serde(skip)]
    pub urls: Urls,
    pub inject_code: Option<LangInjectCode>,
    pub pick_hook: Option<PickHookConfig>,
}

impl Config {
    pub fn get<P: AsRef<Path>>(path: P) -> Self {
        let base = "https://leetcode.com";
        let urls = Urls {
            base: base.to_owned(),
            api: format!("{}/api", base),
            graphql: format!("{}/graphql", base),
            problems: format!("{}/problems/", base),
            problems_all: format!("{}/api/problems/all", base),
            github_login: format!("{}/accounts/github/login/?next=%2F", base),
            github_login_request: "https://github.com/login".to_string(),
            github_session_request: "https://github.com/session".to_string(),
            test: format!("{}/problems/$slug/interpret_solution/", base),
            submit: format!("{}/problems/$slug/submit/", base),
            submissions: format!("{}/api/submissions/$slug", base),
            submission: format!("{}/submissions/detail/$id", base),
            verify: format!("{}/submissions/detail/$id/check/", base),
        };

        let mut config: Result<Config> = Config::get_config(path);

        if let Ok(ref mut config) = config {
            config.urls = urls.clone();
        }

        let config = config.unwrap_or(Config {
            urls,
            inject_code: None,
            pick_hook: None,
        });

        config
    }

    fn get_config<P: AsRef<Path>, T: DeserializeOwned>(path: P) -> Result<T> {
        let mut buf = String::new();
        let mut file = File::open(path)?;
        file.read_to_string(&mut buf)?;

        serde_json::from_str(&buf).map_err(LeetUpError::Serde)
    }
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum Either {
    Sequence(Vec<String>),
    String(String),
}

impl ToString for Either {
    fn to_string(&self) -> String {
        match self {
            Either::String(s) => s.to_owned(),
            Either::Sequence(v) => v.join("\n"),
        }
    }
}

#[derive(Debug, Default, Deserialize, Clone)]
pub struct Urls {
    pub base: String,
    pub api: String,
    pub graphql: String,
    pub problems: String,
    pub problems_all: String,
    pub github_login: String,
    pub github_login_request: String,
    pub github_session_request: String,
    pub test: String,
    pub submit: String,
    pub submissions: String,
    pub submission: String,
    pub verify: String,
}

#[derive(Debug, Deserialize)]
pub struct InjectCode {
    pub before_code: Option<Either>,
    pub before_code_exclude: Option<Either>,
    pub after_code: Option<Either>,
    pub before_function_definition: Option<Either>,
}

/// Make code generation more flexible with capabilities to run scripts before
/// and after generation.
///
/// Provide the ability to change filenames through certain pre-defined transformation actions.
#[derive(Debug, Deserialize)]
pub struct PickHook {
    working_dir: Option<String>,
    script: Option<PickHookScript>,
}

impl PickHook {
    pub fn working_dir(&self) -> Option<&str> {
        self.working_dir.as_ref().map(String::as_ref)
    }

    pub fn script_pre_generation(&self) -> Option<&Either> {
        match self.script.as_ref() {
            Some(script) => script.pre_generation.as_ref(),
            None => None,
        }
    }

    pub fn script_post_generation(&self) -> Option<&Either> {
        match self.script.as_ref() {
            Some(script) => script.post_generation.as_ref(),
            None => None,
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct PickHookScript {
    pre_generation: Option<Either>,
    post_generation: Option<Either>,
}

#[test]
fn test_config() {
    use std::io::Write;

    let data_dir = tempfile::tempdir().unwrap();
    let data = serde_json::json!({
        "inject_code": {},
        "urls": {
            "base": vec![""]
        },
        "pick_hook": {}
    });
    let file_path = data_dir.path().join("config.json");

    let mut file = std::fs::File::create(&file_path).unwrap();
    file.write(data.to_string().as_bytes()).unwrap();

    let config: Config = Config::get(&file_path);
    assert!(config.inject_code.is_some());
    assert!(config.urls.base.len() > 0);
    assert!(config.pick_hook.is_some());
    drop(file);
    data_dir.close().unwrap();
}