Skip to content

fix: clippy warning for rust 1.61 stable and feat: upgrade dep version #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 21 additions & 21 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ path = "src/bin/lc.rs"
name = "leetcode-cli"
version = "0.3.11"
authors = ["clearloop <cdr.today@foxmail.com>"]
edition = "2018"
edition = "2021"
description = "Leet your code in command-line."
repository = "https://github.com/clearloop/leetcode-cli"
license = "MIT"
Expand All @@ -16,38 +16,38 @@ keywords = ["cli", "games", "leetcode"]
readme = './README.md'

[dependencies]
async-trait = "0.1.41"
tokio = "0.2.22"
clap = "2.33.0"
colored = "1.9.1"
dirs = "2.0.2"
env_logger = "0.7.1"
escaper = "0.1.0"
keyring = "0.8.0"
log = "0.4"
openssl = "0.10.26"
pyo3 = { version = "0.8.5", optional = true }
rand = "0.7.2"
serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0.44"
toml = "0.5.5"
regex = "1"
async-trait = "0.1.56"
tokio = { version = "1", features = ["full"] }
clap = { version = "3.2.8", features = ["cargo"] }
colored = "2.0.0"
dirs = "4.0.0"
env_logger = "0.9.0"
escaper = "0.1.1"
keyring = "1.1.2"
log = "0.4.17"
openssl = "0.10.40"
pyo3 = { version = "0.16.5", optional = true }
rand = "0.8.5"
serde = { version = "1.0.138", features = ["derive"] }
serde_json = "1.0.82"
toml = "0.5.9"
regex = "1.5.6"

[dependencies.diesel]
version = "1.4.3"
version = "1.4.8"
features = ["sqlite"]

[dependencies.reqwest]
version = "0.10.3"
version = "0.11.11"
features = ["gzip", "json"]

[dev-dependencies.cargo-husky]
version = "1"
version = "1.5.0"
default-features = false
features = ["precommit-hook", "user-hooks"]

[features]
pym = ["pyo3"]

[target.'cfg(target_family = "unix")'.dependencies]
nix = "0.17.0"
nix = "0.24.1"
3 changes: 1 addition & 2 deletions src/bin/lc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ use leetcode_cli::cli;
use tokio::runtime::Builder;

fn main() {
if let Err(err) = Builder::new()
.basic_scheduler()
if let Err(err) = Builder::new_multi_thread()
.enable_all()
.build()
.expect("Build tokio runtime failed")
Expand Down
97 changes: 52 additions & 45 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ use self::sql::*;
use crate::{cfg, err::Error, plugins::LeetCode};
use colored::Colorize;
use diesel::prelude::*;
use reqwest::Response;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use reqwest::Response;

/// sqlite connection
pub fn conn(p: String) -> SqliteConnection {
Expand Down Expand Up @@ -60,32 +60,27 @@ impl Cache {
Ok(())
}

async fn get_user_info(&self) -> Result<(String,bool), Error> {
let user = parser::user(
self.clone().0
.get_user_info().await?
.json().await?
);
async fn get_user_info(&self) -> Result<(String, bool), Error> {
let user = parser::user(self.clone().0.get_user_info().await?.json().await?);
match user {
None => Err(Error::NoneError),
Some(None) => Err(Error::CookieError),
Some(Some((s,b))) => Ok((s,b))
Some(Some((s, b))) => Ok((s, b)),
}
}

async fn is_session_bad(&self) -> bool {
// i.e. self.get_user_info().contains_err(Error::CookieError)
match self.get_user_info().await {
Err(Error::CookieError) => true,
_ => false
}
matches!(self.get_user_info().await, Err(Error::CookieError))
}

async fn resp_to_json<T: DeserializeOwned>(&self, resp: Response) -> Result<T, Error> {
let maybe_json: Result<T,_> = resp.json().await;
let maybe_json: Result<T, _> = resp.json().await;
if maybe_json.is_err() && self.is_session_bad().await {
Err(Error::CookieError)
} else { Ok(maybe_json?) }
} else {
Ok(maybe_json?)
}
}

/// Download leetcode problems to db
Expand Down Expand Up @@ -123,16 +118,17 @@ impl Cache {
Ok(p)
}

/// Get daily problem
/// Get daily problem
pub async fn get_daily_problem_id(&self) -> Result<i32, Error> {
parser::daily(
self.clone()
.0
.get_question_daily()
.await?
.json() // does not require LEETCODE_SESSION
.await?
).ok_or(Error::NoneError)
.await?,
)
.ok_or(Error::NoneError)
}

/// Get problems from cache
Expand Down Expand Up @@ -179,13 +175,14 @@ impl Cache {
debug!("{:#?}", &json);
match parser::desc(&mut rdesc, json) {
None => return Err(Error::NoneError),
Some(false) => return
if self.is_session_bad().await {
Some(false) => {
return if self.is_session_bad().await {
Err(Error::CookieError)
} else {
Err(Error::PremiumError)
},
Some(true) => ()
}
}
Some(true) => (),
}

// update the question
Expand Down Expand Up @@ -215,7 +212,8 @@ impl Cache {
.await?
.json()
.await?,
).ok_or(Error::NoneError)?;
)
.ok_or(Error::NoneError)?;
let t = Tag {
r#tag: rslug.to_string(),
r#refs: serde_json::to_string(&ids)?,
Expand Down Expand Up @@ -258,22 +256,20 @@ impl Cache {
let mut code: String = "".to_string();

let maybe_file_testcases: Option<String> = test_cases_path(&p)
.map(|filename| {
let mut tests = "".to_string();
File::open(filename)
.and_then(|mut file_descriptor| file_descriptor.read_to_string(&mut tests))
.map(|_| Some(tests))
.unwrap_or(None)
})
.unwrap_or(None);
.map(|filename| {
let mut tests = "".to_string();
File::open(filename)
.and_then(|mut file_descriptor| file_descriptor.read_to_string(&mut tests))
.map(|_| Some(tests))
.unwrap_or(None)
})
.unwrap_or(None);

// Takes test cases using following priority
// 1. cli parameter
// 2. test cases from the file
// 3. sample test case from the task
let testcase = testcase
.or(maybe_file_testcases)
.unwrap_or(d.case);
let testcase = testcase.or(maybe_file_testcases).unwrap_or(d.case);

File::open(code_path(&p, None)?)?.read_to_string(&mut code)?;

Expand All @@ -286,18 +282,31 @@ impl Cache {
json.insert("data_input", testcase);

let url = match run {
Run::Test => conf.sys.urls.get("test").ok_or(Error::NoneError)?.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").ok_or(Error::NoneError)?.replace("$slug", &p.slug)
conf.sys
.urls
.get("submit")
.ok_or(Error::NoneError)?
.replace("$slug", &p.slug)
}
};

Ok((
json,
[
url,
conf.sys.urls.get("problems").ok_or(Error::NoneError)?.replace("$slug", &p.slug),
conf.sys
.urls
.get("problems")
.ok_or(Error::NoneError)?
.replace("$slug", &p.slug),
],
))
}
Expand All @@ -309,13 +318,9 @@ impl Cache {
trace!("Run veriy recursion...");
std::thread::sleep(Duration::from_micros(3000));

let json: VerifyResult = self.resp_to_json(
self
.clone()
.0
.verify_result(rid.clone())
.await?
).await?;
let json: VerifyResult = self
.resp_to_json(self.clone().0.verify_result(rid.clone()).await?)
.await?;

Ok(json)
}
Expand Down Expand Up @@ -343,8 +348,10 @@ impl Cache {
// Check if leetcode accepted the Run request
if match run {
Run::Test => run_res.interpret_id.is_empty(),
Run::Submit => run_res.submission_id == 0
} { return Err(Error::CookieError) }
Run::Submit => run_res.submission_id == 0,
} {
return Err(Error::CookieError);
}

let mut res: VerifyResult = VerifyResult::default();
while res.state != "SUCCESS" {
Expand Down
27 changes: 16 additions & 11 deletions src/cache/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ impl std::fmt::Display for Problem {
1 => {
id.push_str(&SPACE.repeat(2));
id.push_str(&self.fid.to_string());
id.push_str(&SPACE.to_string());
id.push_str(SPACE);
}
2 => {
id.push_str(&SPACE.to_string());
id.push_str(SPACE);
id.push_str(&self.fid.to_string());
id.push_str(&SPACE.to_string());
id.push_str(SPACE);
}
3 => {
id.push_str(&SPACE.to_string());
id.push_str(SPACE);
id.push_str(&self.fid.to_string());
}
4 => {
Expand Down Expand Up @@ -268,7 +268,7 @@ impl std::fmt::Display for VerifyResult {
&"Runtime: ".before_spaces(7).dimmed(),
&self.status.status_runtime.dimmed(),
&"\nYour input:".after_spaces(4),
&self.data_input.replace("\n", "↩ "),
&self.data_input.replace('\n', "↩ "),
&"\nOutput:".after_spaces(8),
ca,
&"\nExpected:".after_spaces(6),
Expand Down Expand Up @@ -342,7 +342,7 @@ impl std::fmt::Display for VerifyResult {
" Runtime: ".dimmed(),
&self.status.status_runtime.dimmed(),
&"\nYour input:".after_spaces(4),
&self.data_input.replace("\n", "↩ "),
&self.data_input.replace('\n', "↩ "),
&"\nOutput:".after_spaces(8),
ca,
&"\nExpected:".after_spaces(6),
Expand Down Expand Up @@ -373,7 +373,7 @@ impl std::fmt::Display for VerifyResult {
.bold()
.yellow(),
&"Last case:".after_spaces(5).dimmed(),
&self.submit.last_testcase.replace("\n", "↩ ").dimmed(),
&self.submit.last_testcase.replace('\n', "↩ ").dimmed(),
&"\nOutput:".after_spaces(8),
self.code_output[0],
&"\nExpected:".after_spaces(6),
Expand All @@ -385,15 +385,20 @@ impl std::fmt::Display for VerifyResult {
"\n{}\n\n{}{}\n",
&self.status.status_msg.yellow().bold(),
&"Last case:".after_spaces(5).dimmed(),
&self.data_input.replace("\n", "↩ "),
&self.data_input.replace('\n', "↩ "),
)?,
// Output Timeout Exceeded
//
// TODO: 13 and 14 might have some different,
// if anybody reach this, welcome to fix this!
13 | 14 => write!(f, "\n{}\n", &self.status.status_msg.yellow().bold(),)?,
// Runtime error
15 => write!(f, "\n{}\n{}\n'", &self.status.status_msg.red().bold(), &self.status.runtime_error)?,
15 => write!(
f,
"\n{}\n{}\n'",
&self.status.status_msg.red().bold(),
&self.status.runtime_error
)?,
// Compile Error
20 => write!(
f,
Expand Down Expand Up @@ -436,7 +441,7 @@ impl std::fmt::Display for VerifyResult {
f,
"{}{}",
&"Stdout:".after_spaces(8).purple(),
&self.std_output.replace("\n", &"\n".after_spaces(15))
&self.std_output.replace('\n', &"\n".after_spaces(15))
)
} else {
write!(f, "")
Expand Down Expand Up @@ -495,7 +500,7 @@ mod verify {
#[serde(default)]
pub status_runtime: String,
#[serde(default)]
pub runtime_error: String
pub runtime_error: String,
}

#[derive(Debug, Default, Deserialize)]
Expand Down
9 changes: 6 additions & 3 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
//!
//! + Edit leetcode.toml at `~/.leetcode/leetcode.toml` directly
//! + Use `leetcode config` to update it
use crate::Error;
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
Expand Down Expand Up @@ -150,8 +150,11 @@ pub struct Storage {
impl Storage {
/// convert root path
pub fn root(&self) -> Result<String, Error> {
let home = dirs::home_dir().ok_or(Error::NoneError)?.to_string_lossy().to_string();
let path = self.root.replace("~", &home);
let home = dirs::home_dir()
.ok_or(Error::NoneError)?
.to_string_lossy()
.to_string();
let path = self.root.replace('~', &home);
Ok(path)
}

Expand Down
Loading