diff --git a/.github/workflows/clippy.yml b/.github/workflows/clippy.yml index e46eb6d..004dc18 100644 --- a/.github/workflows/clippy.yml +++ b/.github/workflows/clippy.yml @@ -16,10 +16,8 @@ jobs: - uses: actions/checkout@v1 - uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2021-05-16 components: clippy - override: true + toolchain: stable - uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} - args: --all-features diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index cbc1370..3f22989 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -18,8 +18,7 @@ jobs: - name: Set nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: nightly-2021-05-16 - override: true + toolchain: stable - name: Environment run: | if [[ "$(uname)" == 'Darwin' ]]; then @@ -30,6 +29,6 @@ jobs: sudo apt-get install -y libsqlite3-dev libdbus-1-dev fi - name: Build - run: cargo build --all-features -vv + run: cargo build - name: Run tests - run: cargo test --all-features -vv + run: cargo test diff --git a/Cargo.toml b/Cargo.toml index 69758ac..f2dc5aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ path = "src/bin/lc.rs" [package] name = "leetcode-cli" -version = "0.3.9" +version = "0.3.10" authors = ["clearloop "] edition = "2018" description = "Leet your code in command-line." diff --git a/README.md b/README.md index 736dd12..faa092c 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,6 @@ [![gitter](https://img.shields.io/gitter/room/odditypark/leetcode-cli)](https://gitter.im/Odditypark/leetcode-cli) [![LICENSE](https://img.shields.io/crates/l/leetcode-cli.svg)](https://choosealicense.com/licenses/mit/) -## Features - -+ [x] the edit flow —— solution files will generate automatically! -+ [x] support Python script to filter questions -+ [ ] doc support, `lc-rs` can compile the annotation of your solutions to Markdown! -+ [ ] support local signal to keep coding as longer as you want - ## Installing ```sh @@ -26,21 +19,12 @@ cargo install leetcode-cli ``` -### `error[E0554]` - -If this happens when compiling the program, it means that the package cannot be compiled with stable Rust. To fix this, install Rust Nightly and try the following: - -```sh -rustup install nightly -cargo +nightly install leetcode-cli -``` - ## Usage **Make sure you have logged in to `leetcode.com` with `Chrome`**. See [Cookies](#cookies) for why you need to do this first. ```sh -leetcode 0.3.9 +leetcode 0.3.10 May the Code be with You 👻 USAGE: diff --git a/rust-toolchain b/rust-toolchain deleted file mode 100644 index 59923ad..0000000 --- a/rust-toolchain +++ /dev/null @@ -1 +0,0 @@ -nightly-2021-05-16 \ No newline at end of file diff --git a/src/cache/mod.rs b/src/cache/mod.rs index 8ad0f82..5c15277 100644 --- a/src/cache/mod.rs +++ b/src/cache/mod.rs @@ -67,11 +67,11 @@ impl Cache { let json = self .0 .clone() - .get_category_problems(&i) + .get_category_problems(i) .await? .json() .await?; - parser::problem(&mut ps, json)?; + parser::problem(&mut ps, json).ok_or(Error::NoneError)?; } diesel::replace_into(problems) @@ -135,7 +135,7 @@ impl Cache { .json() .await?; debug!("{:#?}", &json); - parser::desc(&mut rdesc, json)?; + parser::desc(&mut rdesc, json).ok_or(Error::NoneError)?; // update the question let sdesc = serde_json::to_string(&rdesc)?; @@ -160,11 +160,11 @@ impl Cache { ids = parser::tags( self.clone() .0 - .get_question_ids_by_tag(&rslug) + .get_question_ids_by_tag(rslug) .await? .json() .await?, - )?; + ).ok_or(Error::NoneError)?; let t = Tag { r#tag: rslug.to_string(), r#refs: serde_json::to_string(&ids)?, @@ -235,10 +235,10 @@ impl Cache { json.insert("data_input", testcase); let url = match run { - Run::Test => conf.sys.urls.get("test")?.replace("$slug", &p.slug), + Run::Test => conf.sys.urls.get("test").ok_or(Error::NoneError)?.replace("$slug", &p.slug), Run::Submit => { json.insert("judge_type", "large".to_string()); - conf.sys.urls.get("submit")?.replace("$slug", &p.slug) + conf.sys.urls.get("submit").ok_or(Error::NoneError)?.replace("$slug", &p.slug) } }; @@ -246,7 +246,7 @@ impl Cache { json, [ url, - conf.sys.urls.get("problems")?.replace("$slug", &p.slug), + conf.sys.urls.get("problems").ok_or(Error::NoneError)?.replace("$slug", &p.slug), ], )) } @@ -308,8 +308,8 @@ impl Cache { } trace!("Recur verify result {:#?}", res); - res.name = json.get("name")?.to_string(); - res.data_input = json.get("data_input")?.to_string(); + res.name = json.get("name").ok_or(Error::NoneError)?.to_string(); + res.data_input = json.get("data_input").ok_or(Error::NoneError)?.to_string(); res.result_type = run; Ok(res) } diff --git a/src/cache/models.rs b/src/cache/models.rs index d098d0e..2624233 100644 --- a/src/cache/models.rs +++ b/src/cache/models.rs @@ -209,14 +209,14 @@ pub struct VerifyResult { pub data_input: String, #[serde(skip)] pub result_type: Run, - #[serde(default)] - lang: String, + // #[serde(default)] + // lang: String, #[serde(default)] pretty_lang: String, - #[serde(default)] - submission_id: String, - #[serde(default)] - run_success: bool, + // #[serde(default)] + // submission_id: String, + // #[serde(default)] + // run_success: bool, #[serde(default)] correct_answer: bool, #[serde(default, deserialize_with = "ssr")] @@ -229,8 +229,8 @@ pub struct VerifyResult { std_output: String, // flatten - #[serde(flatten, default)] - info: VerifyInfo, + // #[serde(flatten, default)] + // info: VerifyInfo, #[serde(flatten, default)] status: VerifyStatus, #[serde(flatten, default)] @@ -462,15 +462,15 @@ mod verify { pub compare_result: String, } - #[derive(Debug, Default, Deserialize)] - pub struct VerifyInfo { - #[serde(default)] - memory: i64, - #[serde(default)] - elapsed_time: i64, - #[serde(default)] - task_finish_time: i64, - } + // #[derive(Debug, Default, Deserialize)] + // pub struct VerifyInfo { + // #[serde(default)] + // memory: i64, + // #[serde(default)] + // elapsed_time: i64, + // #[serde(default)] + // task_finish_time: i64, + // } #[derive(Debug, Default, Deserialize)] pub struct Analyse { @@ -500,30 +500,30 @@ mod verify { #[derive(Debug, Default, Deserialize)] pub struct CompileError { - #[serde(default)] - compile_error: String, + // #[serde(default)] + // compile_error: String, #[serde(default)] pub full_compile_error: String, } #[derive(Debug, Default, Deserialize)] pub struct Expected { - #[serde(default)] - expected_status_code: i32, - #[serde(default)] - expected_lang: String, - #[serde(default)] - expected_run_success: bool, - #[serde(default)] - expected_status_runtime: String, - #[serde(default)] - expected_memory: i64, - #[serde(default, deserialize_with = "ssr")] - expected_code_output: Vec, - #[serde(default)] - expected_elapsed_time: i64, - #[serde(default)] - expected_task_finish_time: i64, + // #[serde(default)] + // expected_status_code: i32, + // #[serde(default)] + // expected_lang: String, + // #[serde(default)] + // expected_run_success: bool, + // #[serde(default)] + // expected_status_runtime: String, + // #[serde(default)] + // expected_memory: i64, + // #[serde(default, deserialize_with = "ssr")] + // expected_code_output: Vec, + // #[serde(default)] + // expected_elapsed_time: i64, + // #[serde(default)] + // expected_task_finish_time: i64, #[serde(default, deserialize_with = "ssr")] pub expected_code_answer: Vec, } diff --git a/src/cache/parser.rs b/src/cache/parser.rs index 1b3f25c..5a6f521 100644 --- a/src/cache/parser.rs +++ b/src/cache/parser.rs @@ -1,10 +1,9 @@ //! Sub-Module for parsing resp data use super::models::*; -use crate::err::Error; use serde_json::Value; /// problem parser -pub fn problem(problems: &mut Vec, v: Value) -> Result<(), Error> { +pub fn problem(problems: &mut Vec, v: Value) -> Option<()> { let pairs = v.get("stat_status_pairs")?.as_array()?; for p in pairs { let stat = p.get("stat")?.as_object()?; @@ -26,11 +25,11 @@ pub fn problem(problems: &mut Vec, v: Value) -> Result<(), Error> { }); } - Ok(()) + Some(()) } /// desc parser -pub fn desc(q: &mut Question, v: Value) -> Result<(), Error> { +pub fn desc(q: &mut Question, v: Value) -> Option<()> { let o = &v .as_object()? .get("data")? @@ -40,14 +39,14 @@ pub fn desc(q: &mut Question, v: Value) -> Result<(), Error> { *q = Question { content: o.get("content")?.as_str().unwrap_or("").to_string(), - stats: serde_json::from_str(o.get("stats")?.as_str()?)?, - defs: serde_json::from_str(o.get("codeDefinition")?.as_str()?)?, + stats: serde_json::from_str(o.get("stats")?.as_str()?).ok()?, + defs: serde_json::from_str(o.get("codeDefinition")?.as_str()?).ok()?, case: o.get("sampleTestCase")?.as_str()?.to_string(), all_cases: o.get("exampleTestcases") .unwrap_or(o.get("sampleTestCase")?) // soft fail to the sampleTestCase .as_str()? .to_string(), - metadata: serde_json::from_str(o.get("metaData")?.as_str()?)?, + metadata: serde_json::from_str(o.get("metaData")?.as_str()?).ok()?, test: o.get("enableRunCode")?.as_bool()?, t_content: o .get("translatedContent")? @@ -56,16 +55,16 @@ pub fn desc(q: &mut Question, v: Value) -> Result<(), Error> { .to_string(), }; - Ok(()) + Some(()) } /// tag parser -pub fn tags(v: Value) -> Result, Error> { +pub fn tags(v: Value) -> Option> { trace!("Parse tags..."); let tag = v.as_object()?.get("data")?.as_object()?.get("topicTag")?; if tag.is_null() { - return Ok(vec![]); + return Some(vec![]); } let arr = tag.as_object()?.get("questions")?.as_array()?; @@ -75,7 +74,7 @@ pub fn tags(v: Value) -> Result, Error> { res.push(q.as_object()?.get("questionId")?.as_str()?.to_string()) } - Ok(res) + Some(res) } pub use ss::ssr; diff --git a/src/cfg.rs b/src/cfg.rs index 4684c4a..ba57d59 100644 --- a/src/cfg.rs +++ b/src/cfg.rs @@ -7,6 +7,7 @@ //! + Use `leetcode config` to update it use serde::{Deserialize, Serialize}; use std::{collections::HashMap, fs, path::PathBuf}; +use crate::Error; const DEFAULT_CONFIG: &str = r#" # usually you don't wanna change those @@ -81,8 +82,8 @@ pub struct Config { impl Config { /// Sync new config to config.toml - pub fn sync(&self) -> Result<(), crate::Error> { - let home = dirs::home_dir()?; + pub fn sync(&self) -> Result<(), Error> { + let home = dirs::home_dir().ok_or(Error::NoneError)?; let conf = home.join(".leetcode/leetcode.toml"); fs::write(conf, toml::ser::to_string_pretty(&self)?)?; @@ -148,8 +149,8 @@ pub struct Storage { impl Storage { /// convert root path - pub fn root(&self) -> Result { - let home = dirs::home_dir()?.to_string_lossy().to_string(); + pub fn root(&self) -> Result { + let home = dirs::home_dir().ok_or(Error::NoneError)?.to_string_lossy().to_string(); let path = self.root.replace("~", &home); Ok(path) } @@ -178,11 +179,11 @@ impl Storage { pub fn scripts(mut self) -> Result { let root = &self.root()?; if self.scripts.is_none() { - let tmp = toml::from_str::(&DEFAULT_CONFIG)?; - self.scripts = Some(tmp.storage.scripts?); + let tmp = toml::from_str::(DEFAULT_CONFIG)?; + self.scripts = Some(tmp.storage.scripts.ok_or(Error::NoneError)?); } - let p = PathBuf::from(root).join(&self.scripts?); + let p = PathBuf::from(root).join(&self.scripts.ok_or(Error::NoneError)?); if !PathBuf::from(&p).exists() { std::fs::create_dir(&p)? } @@ -203,8 +204,8 @@ pub fn locate() -> Result { } /// Get root path of leetcode-cli -pub fn root() -> Result { - let dir = dirs::home_dir()?.join(".leetcode"); +pub fn root() -> Result { + let dir = dirs::home_dir().ok_or(Error::NoneError)?.join(".leetcode"); if !dir.is_dir() { info!("Generate root dir at {:?}.", &dir); fs::DirBuilder::new().recursive(true).create(&dir)?; diff --git a/src/cli.rs b/src/cli.rs index f47cbca..df86b7b 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -10,18 +10,16 @@ use crate::{ use clap::{crate_name, crate_version, App, AppSettings}; /// This should be called before calling any cli method or printing any output. -pub fn reset_signal_pipe_handler() -> Result<(), ()> { +pub fn reset_signal_pipe_handler() { #[cfg(target_family = "unix")] { use nix::sys::signal; unsafe { - signal::signal(signal::Signal::SIGPIPE, signal::SigHandler::SigDfl) - .map_err(|e| println!("{:?}", e))?; + let _ = signal::signal(signal::Signal::SIGPIPE, signal::SigHandler::SigDfl) + .map_err(|e| println!("{:?}", e)); } } - - Ok(()) } /// Get maches diff --git a/src/cmds/data.rs b/src/cmds/data.rs index 10584d9..0ec57bf 100644 --- a/src/cmds/data.rs +++ b/src/cmds/data.rs @@ -1,6 +1,6 @@ //! Cache managger use super::Command; -use crate::{cache::Cache, helper::Digit}; +use crate::{cache::Cache, helper::Digit, Error}; use async_trait::async_trait; use clap::{App, Arg, ArgMatches, SubCommand}; use colored::Colorize; @@ -46,7 +46,7 @@ impl Command for DataCommand { } /// `data` handler - async fn handler(m: &ArgMatches<'_>) -> Result<(), crate::err::Error> { + async fn handler(m: &ArgMatches<'_>) -> Result<(), Error> { use std::fs::File; use std::path::Path; @@ -58,7 +58,7 @@ impl Command for DataCommand { let out = format!( " {}{}", Path::new(&path) - .file_name()? + .file_name().ok_or(Error::NoneError)? .to_string_lossy() .to_string() .digit(65 - (len.len() as i32)) diff --git a/src/cmds/edit.rs b/src/cmds/edit.rs index 1edf7d6..21285fb 100644 --- a/src/cmds/edit.rs +++ b/src/cmds/edit.rs @@ -1,4 +1,5 @@ //! Edit command +use crate::Error; use super::Command; use async_trait::async_trait; use clap::{App, ArgMatches}; @@ -51,14 +52,14 @@ impl Command for EditCommand { use std::io::Write; use std::path::Path; - let id: i32 = m.value_of("id")?.parse()?; + let id: i32 = m.value_of("id").ok_or(Error::NoneError)?.parse()?; let cache = Cache::new()?; let target = cache.get_problem(id)?; let mut conf = cache.to_owned().0.conf; // condition language if m.is_present("lang") { - conf.code.lang = m.value_of("lang")?.to_string(); + conf.code.lang = m.value_of("lang").ok_or(Error::NoneError)?.to_string(); conf.sync()?; } diff --git a/src/cmds/exec.rs b/src/cmds/exec.rs index 9755bf5..755fd37 100644 --- a/src/cmds/exec.rs +++ b/src/cmds/exec.rs @@ -1,4 +1,5 @@ //! Exec command +use crate::Error; use super::Command; use async_trait::async_trait; use clap::{App, ArgMatches}; @@ -41,7 +42,7 @@ impl Command for ExecCommand { async fn handler(m: &ArgMatches<'_>) -> Result<(), crate::Error> { use crate::cache::{Cache, Run}; - let id: i32 = m.value_of("id")?.parse()?; + let id: i32 = m.value_of("id").ok_or(Error::NoneError)?.parse()?; let cache = Cache::new()?; let res = cache.exec_problem(id, Run::Submit, None).await?; diff --git a/src/cmds/list.rs b/src/cmds/list.rs index 15b1d8e..b7a9b1e 100644 --- a/src/cmds/list.rs +++ b/src/cmds/list.rs @@ -168,14 +168,13 @@ impl Command for ListCommand { // filter query if m.is_present("query") { - let query = m.value_of("query")?; + let query = m.value_of("query").ok_or(Error::NoneError)?; crate::helper::filter(&mut ps, query.to_string()); } // filter range if m.is_present("range") { - let range: Vec<_> = m.values_of("range")?.collect(); - let num_range: Vec = range + let num_range: Vec = m.values_of("range").ok_or(Error::NoneError)? .into_iter() .map(|x| x.parse::().unwrap_or(0)) .collect(); diff --git a/src/cmds/pick.rs b/src/cmds/pick.rs index 58cfc70..4771733 100644 --- a/src/cmds/pick.rs +++ b/src/cmds/pick.rs @@ -105,7 +105,7 @@ impl Command for PickCommand { // query filter if m.is_present("query") { - let query = m.value_of("query")?; + let query = m.value_of("query").ok_or(Error::NoneError)?; crate::helper::filter(&mut problems, query.to_string()); } @@ -120,7 +120,7 @@ impl Command for PickCommand { let r = cache.get_question(fid).await; if r.is_err() { - let e = r.err()?; + let e = r.err().ok_or(Error::NoneError)?; eprintln!("{:?}", &e); if let Error::FeatureError(_) | Error::NetworkError(_) = e { Self::handler(m).await?; diff --git a/src/cmds/test.rs b/src/cmds/test.rs index aab826b..37c0e7f 100644 --- a/src/cmds/test.rs +++ b/src/cmds/test.rs @@ -1,4 +1,5 @@ //! Test command +use crate::Error; use super::Command; use async_trait::async_trait; use clap::{App, ArgMatches}; @@ -44,9 +45,9 @@ impl Command for TestCommand { } /// `test` handler - async fn handler(m: &ArgMatches<'_>) -> Result<(), crate::Error> { + async fn handler(m: &ArgMatches<'_>) -> Result<(), Error> { use crate::cache::{Cache, Run}; - let id: i32 = m.value_of("id")?.parse()?; + let id: i32 = m.value_of("id").ok_or(Error::NoneError)?.parse()?; let testcase = m.value_of("testcase"); let case_str: Option; match testcase { diff --git a/src/err.rs b/src/err.rs index 8344d1b..8fd9b57 100644 --- a/src/err.rs +++ b/src/err.rs @@ -16,6 +16,7 @@ pub enum Error { CookieError, DecryptError, SilentError, + NoneError, } impl std::fmt::Debug for Error { @@ -44,6 +45,10 @@ impl std::fmt::Debug for Error { Error::DecryptError => write!(f, "{} openssl decrypt failed", e), Error::ScriptError(s) => write!(f, "{} {}", e, s), Error::SilentError => write!(f, ""), + Error::NoneError => write!(f, + "json from response parse failed, please open a new issue at: {}.", + "https://github.com/clearloop/leetcode-cli/".underline(), + ) } } } @@ -88,7 +93,7 @@ impl std::convert::From for Error { fn from(err: toml::de::Error) -> Self { Error::ParseError(format!( "{}, {}{}{}{}{}{}{}{}", - err.to_string(), + err, "Parse config file failed, ", "leetcode-cli has just generated a new leetcode.toml at ", "~/.leetcode/leetcode_tmp.toml,".green().bold().underline(), @@ -114,19 +119,6 @@ impl std::convert::From for Error { } } -// options -impl std::convert::From for Error { - fn from(_: std::option::NoneError) -> Self { - Error::ParseError(format!( - "{}{}{}{}", - "json from response parse failed, ", - "please open a new issue at: ", - "https://github.com/clearloop/leetcode-cli/".underline(), - "." - )) - } -} - // openssl impl std::convert::From for Error { fn from(_: openssl::error::ErrorStack) -> Self { diff --git a/src/helper.rs b/src/helper.rs index 0de5722..5d8d746 100644 --- a/src/helper.rs +++ b/src/helper.rs @@ -277,7 +277,7 @@ mod file { } } - use crate::cache::models::Problem; + use crate::{cache::models::Problem, Error}; /// Generate test casese path by fid pub fn test_cases_path(target: &Problem) -> Result { @@ -300,7 +300,7 @@ mod file { let conf = crate::cfg::locate()?; let mut lang = conf.code.lang; if l.is_some() { - lang = l?; + lang = l.ok_or(Error::NoneError)?; } let mut path = format!( diff --git a/src/lib.rs b/src/lib.rs index 02e110f..e97fb6e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,20 +4,7 @@ //! [![Crates.io](https://img.shields.io/crates/d/leetcode-cli.svg)](https://crates.io/crates/leetcode-cli) //! [![LICENSE](https://img.shields.io/crates/l/leetcode-cli.svg)](https://choosealicense.com/licenses/mit/) //! -//! ## Contributors -//! + [@hulufi](https://github.com/hulufei) -//! + [@ldm0](https://github.com/ldm0) -//! + [@Raees678](https://github.com/Raees678) -//! + [@clearloop](https://github.com/clearloop) -//! -//! ## Features -//! -//! + [x] the edit flow —— solution files will generate automatically! -//! + [x] support python script to filter questions -//! + [ ] doc support, `lc-rs` can compile the annotation of your solutions to markdown! -//! + [ ] support local signal to keep coding as longer as you want. -//! -//! ## Building +//! ## Installing //! //! ```sh //! cargo install leetcode-cli @@ -28,7 +15,7 @@ //! **Please make sure you have logined in `leetcode.com` with `chrome`**, more info plz checkout [this](#cookies) //! //! ```sh -//! leetcode 0.3.9 +//! leetcode 0.3.10 //! May the Code be with You 👻 //! //! USAGE: @@ -241,7 +228,6 @@ //! //! [pr]: https://github.com/clearloop/leetcode-cli/pulls //! [#1]: https://github.com/clearloop/leetcode-cli/issues/1 -#![feature(try_trait)] #[macro_use] extern crate log; #[macro_use] diff --git a/src/plugins/chrome.rs b/src/plugins/chrome.rs index cbce780..8922b7a 100644 --- a/src/plugins/chrome.rs +++ b/src/plugins/chrome.rs @@ -1,4 +1,4 @@ -use crate::cache; +use crate::{cache, Error}; use diesel::prelude::*; use keyring::Keyring; use openssl::{hash, pkcs5, symm}; @@ -21,6 +21,7 @@ mod schema { #[derive(Queryable, Debug, Clone)] struct Cookies { pub encrypted_value: Vec, + #[allow(dead_code)] pub host_key: String, pub name: String, } @@ -52,7 +53,7 @@ pub fn cookies() -> Result { use self::schema::cookies::dsl::*; trace!("Derive cookies from google chrome..."); - let home = dirs::home_dir()?; + let home = dirs::home_dir().ok_or(Error::NoneError)?; let p = match std::env::consts::OS { "macos" => home.join("Library/Application Support/Google/Chrome/Default/Cookies"), "linux" => home.join(".config/google-chrome/Default/Cookies"), @@ -67,7 +68,7 @@ pub fn cookies() -> Result { .expect("Loading cookies from google chrome failed."); debug!("res {:?}", &res); - if res.len() == (0 as usize) { + if res.is_empty() { return Err(crate::Error::CookieError); } @@ -77,15 +78,15 @@ pub fn cookies() -> Result { // Decode cookies let mut m: HashMap = HashMap::new(); - for c in res.to_owned() { + for c in res { if (c.name == "csrftoken") || (c.name == "LEETCODE_SESSION") { m.insert(c.name, decode_cookies(&pass, c.encrypted_value)?); } } Ok(Ident { - csrf: m.get("csrftoken")?.to_string(), - session: m.get("LEETCODE_SESSION")?.to_string(), + csrf: m.get("csrftoken").ok_or(Error::NoneError)?.to_string(), + session: m.get("LEETCODE_SESSION").ok_or(Error::NoneError)?.to_string(), }) } diff --git a/src/plugins/leetcode.rs b/src/plugins/leetcode.rs index c6d2d1a..7143d6c 100644 --- a/src/plugins/leetcode.rs +++ b/src/plugins/leetcode.rs @@ -72,7 +72,7 @@ impl LeetCode { .conf .sys .urls - .get("problems")? + .get("problems").ok_or(Error::NoneError)? .replace("$category", category); Req { @@ -90,10 +90,10 @@ impl LeetCode { pub async fn get_question_ids_by_tag(self, slug: &str) -> Result { trace!("Requesting {} ref problems...", &slug); - let url = &self.conf.sys.urls.get("graphql")?; + let url = &self.conf.sys.urls.get("graphql").ok_or(Error::NoneError)?; let mut json: Json = HashMap::new(); json.insert("operationName", "getTopicTag".to_string()); - json.insert("variables", r#"{"slug": "$slug"}"#.replace("$slug", &slug)); + json.insert("variables", r#"{"slug": "$slug"}"#.replace("$slug", slug)); json.insert( "query", vec![ @@ -110,7 +110,7 @@ impl LeetCode { Req { default_headers: self.default_headers, - refer: Some((&self.conf.sys.urls.get("tag")?).replace("$slug", slug)), + refer: Some((self.conf.sys.urls.get("tag").ok_or(Error::NoneError)?).replace("$slug", slug)), info: false, json: Some(json), mode: Mode::Post, @@ -124,7 +124,7 @@ impl LeetCode { /// Get specific problem detail pub async fn get_question_detail(self, slug: &str) -> Result { trace!("Requesting {} detail...", &slug); - let refer = self.conf.sys.urls.get("problems")?.replace("$slug", slug); + let refer = self.conf.sys.urls.get("problems").ok_or(Error::NoneError)?.replace("$slug", slug); let mut json: Json = HashMap::new(); json.insert( "query", @@ -147,7 +147,7 @@ impl LeetCode { json.insert( "variables", - r#"{"titleSlug": "$titleSlug"}"#.replace("$titleSlug", &slug), + r#"{"titleSlug": "$titleSlug"}"#.replace("$titleSlug", slug), ); json.insert("operationName", "getQuestionDetail".to_string()); @@ -184,7 +184,7 @@ impl LeetCode { /// Get the result of submission / testing pub async fn verify_result(self, id: String) -> Result { trace!("Verifying result..."); - let url = self.conf.sys.urls.get("verify")?.replace("$id", &id); + let url = self.conf.sys.urls.get("verify").ok_or(Error::NoneError)?.replace("$id", &id); Req { default_headers: self.default_headers, refer: None,