Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f4db1ca

Browse files
feat(async): upgrade to async reqwest
1 parent 739eeaf commit f4db1ca

File tree

14 files changed

+114
-148
lines changed

14 files changed

+114
-148
lines changed

‎Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ keywords = ["cli", "games", "leetcode"]
1616
readme = './README.md'
1717

1818
[dependencies]
19+
tokio = "0.2.22"
1920
clap = "2.33.0"
2021
colored = "1.9.1"
2122
dirs = "2.0.2"
@@ -37,7 +38,7 @@ features = ["sqlite"]
3738

3839
[dependencies.reqwest]
3940
version = "0.10.3"
40-
features = ["blocking", "gzip", "json"]
41+
features = ["gzip", "json"]
4142

4243
[dev-dependencies.cargo-husky]
4344
version = "1"

‎SUBSTRATE.md

Lines changed: 0 additions & 47 deletions
This file was deleted.

‎spec.md

Lines changed: 0 additions & 30 deletions
This file was deleted.

‎src/cache/mod.rs

Lines changed: 55 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ impl Cache {
4646
}
4747

4848
/// ref to download probems
49-
pub fn update(self) -> Result<(), Error> {
50-
self.download_problems()?;
49+
pub asyncfn update(self) -> Result<(), Error> {
50+
self.download_problems().await?;
5151
Ok(())
5252
}
5353

@@ -59,12 +59,18 @@ impl Cache {
5959
}
6060

6161
/// Download leetcode problems to db
62-
pub fn download_problems(self) -> Result<Vec<Problem>, Error> {
62+
pub asyncfn download_problems(self) -> Result<Vec<Problem>, Error> {
6363
info!("Fetching leetcode problems...");
6464
let mut ps: Vec<Problem> = vec![];
6565

6666
for i in &self.0.conf.sys.categories.to_owned() {
67-
let json = self.0.clone().get_category_problems(&i)?.json()?;
67+
let json = self
68+
.0
69+
.clone()
70+
.get_category_problems(&i)
71+
.await?
72+
.json()
73+
.await?;
6874
parser::problem(&mut ps, json)?;
6975
}
7076

@@ -100,7 +106,7 @@ impl Cache {
100106

101107
/// Get question
102108
#[allow(clippy::useless_let_if_seq)]
103-
pub fn get_question(&self, rfid: i32) -> Result<Question, Error> {
109+
pub asyncfn get_question(&self, rfid: i32) -> Result<Question, Error> {
104110
let target: Problem = problems.filter(fid.eq(rfid)).first(&self.conn()?)?;
105111

106112
let ids = match target.level {
@@ -133,7 +139,13 @@ impl Cache {
133139
if !target.desc.is_empty() {
134140
rdesc = serde_json::from_str(&target.desc)?;
135141
} else {
136-
let json: Value = self.0.clone().get_question_detail(&target.slug)?.json()?;
142+
let json: Value = self
143+
.0
144+
.clone()
145+
.get_question_detail(&target.slug)
146+
.await?
147+
.json()
148+
.await?;
137149
debug!("{:#?}", &json);
138150
parser::desc(&mut rdesc, json)?;
139151

@@ -147,7 +159,7 @@ impl Cache {
147159
Ok(rdesc)
148160
}
149161

150-
pub fn get_tagged_questions(self, rslug: &str) -> Result<Vec<String>, Error> {
162+
pub asyncfn get_tagged_questions(self, rslug: &str) -> Result<Vec<String>, Error> {
151163
trace!("Geting {} questions...", &rslug);
152164
let ids: Vec<String>;
153165
let rtag = tags
@@ -157,7 +169,14 @@ impl Cache {
157169
trace!("Got {} questions from local cache...", &rslug);
158170
ids = serde_json::from_str(&t.refs)?;
159171
} else {
160-
ids = parser::tags(self.clone().0.get_question_ids_by_tag(&rslug)?.json()?)?;
172+
ids = parser::tags(
173+
self.clone()
174+
.0
175+
.get_question_ids_by_tag(&rslug)
176+
.await?
177+
.json()
178+
.await?,
179+
)?;
161180
let t = Tag {
162181
r#tag: rslug.to_string(),
163182
r#refs: serde_json::to_string(&ids)?,
@@ -176,7 +195,7 @@ impl Cache {
176195
}
177196

178197
/// run_code data
179-
fn pre_run_code(
198+
asyncfn pre_run_code(
180199
&self,
181200
run: Run,
182201
rfid: i32,
@@ -188,11 +207,11 @@ impl Cache {
188207
use std::io::Read;
189208

190209
let p = &self.get_problem(rfid)?;
191-
if p.desc.is_empty() {
192-
trace!("Problem description does not exist, pull desc and exec again...");
193-
self.get_question(rfid)?;
194-
return self.pre_run_code(run, rfid, testcase);
195-
}
210+
// if p.desc.is_empty() {
211+
// trace!("Problem description does not exist, pull desc and exec again...");
212+
// self.get_question(rfid).await?;
213+
// return self.pre_run_code(run, rfid, testcase).await;
214+
// }
196215

197216
let d: Question = serde_json::from_str(&p.desc)?;
198217
let conf = &self.0.conf;
@@ -231,15 +250,21 @@ impl Cache {
231250
}
232251

233252
/// TODO: The real delay
234-
fn recur_verify(&self, rid: String) -> Result<VerifyResult, Error> {
253+
asyncfn recur_verify(&self, rid: String) -> Result<VerifyResult, Error> {
235254
use serde_json::{from_str, Error as SJError};
236255
use std::time::Duration;
237256

238257
trace!("Run veriy recursion...");
239258
std::thread::sleep(Duration::from_micros(3000));
240259

241260
// debug resp raw text
242-
let debug_raw = self.clone().0.verify_result(rid.clone())?.text()?;
261+
let debug_raw = self
262+
.clone()
263+
.0
264+
.verify_result(rid.clone())
265+
.await?
266+
.text()
267+
.await?;
243268
debug!("debug resp raw text: \n{:#?}", &debug_raw);
244269
if debug_raw.is_empty() {
245270
return Err(Error::CookieError);
@@ -249,35 +274,37 @@ impl Cache {
249274
let debug_json: Result<VerifyResult, SJError> = from_str(&debug_raw);
250275
debug!("debug json deserializing: \n{:#?}", &debug_json);
251276

252-
let mut res = debug_json?;
253-
res = match res.state.as_str() {
254-
"SUCCESS" => res,
255-
_ => self.recur_verify(rid)?,
256-
};
277+
// let mut res = debug_json?;
278+
// res = match res.state.as_str() {
279+
// "SUCCESS" => res,
280+
// _ => self.recur_verify(rid).await?,
281+
// };
257282

258-
Ok(res)
283+
Ok(debug_json?)
259284
}
260285

261286
/// Exec problem filter —— Test or Submit
262-
pub fn exec_problem(
287+
pub asyncfn exec_problem(
263288
&self,
264289
rfid: i32,
265290
run: Run,
266291
testcase: Option<String>,
267292
) -> Result<VerifyResult, Error> {
268293
trace!("Exec problem filter —— Test or Submit");
269-
let pre = self.pre_run_code(run.clone(), rfid, testcase)?;
294+
let pre = self.pre_run_code(run.clone(), rfid, testcase).await?;
270295
let json = pre.0;
271296

272297
let run_res: RunCode = self
273298
.0
274299
.clone()
275-
.run_code(json.clone(), pre.1[0].clone(), pre.1[1].clone())?
276-
.json()?;
300+
.run_code(json.clone(), pre.1[0].clone(), pre.1[1].clone())
301+
.await?
302+
.json()
303+
.await?;
277304

278305
let mut res = match run {
279-
Run::Test => self.recur_verify(run_res.interpret_id)?,
280-
Run::Submit => self.recur_verify(run_res.submission_id.to_string())?,
306+
Run::Test => self.recur_verify(run_res.interpret_id).await?,
307+
Run::Submit => self.recur_verify(run_res.submission_id.to_string()).await?,
281308
};
282309

283310
res.name = json.get("name")?.to_string();

‎src/cli.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::{
88
flag::{Debug, Flag},
99
};
1010
use clap::{crate_name, crate_version, App, AppSettings};
11+
use tokio::runtime::Builder;
1112

1213
/// Get maches
1314
pub fn main() -> Result<(), Error> {
@@ -35,14 +36,15 @@ pub fn main() -> Result<(), Error> {
3536
.init();
3637
}
3738

39+
let mut runtime = Builder::new().build().unwrap();
3840
match m.subcommand() {
39-
("data", Some(sub_m)) => Ok(DataCommand::handler(sub_m)?),
40-
("edit", Some(sub_m)) => Ok(EditCommand::handler(sub_m)?),
41-
("exec", Some(sub_m)) => Ok(ExecCommand::handler(sub_m)?),
42-
("list", Some(sub_m)) => Ok(ListCommand::handler(sub_m)?),
43-
("pick", Some(sub_m)) => Ok(PickCommand::handler(sub_m)?),
44-
("stat", Some(sub_m)) => Ok(StatCommand::handler(sub_m)?),
45-
("test", Some(sub_m)) => Ok(TestCommand::handler(sub_m)?),
41+
("data", Some(sub_m)) => Ok(DataCommand::handler(sub_m,&mut runtime)?),
42+
("edit", Some(sub_m)) => Ok(EditCommand::handler(sub_m,&mut runtime)?),
43+
("exec", Some(sub_m)) => Ok(ExecCommand::handler(sub_m,&mut runtime)?),
44+
("list", Some(sub_m)) => Ok(ListCommand::handler(sub_m,&mut runtime)?),
45+
("pick", Some(sub_m)) => Ok(PickCommand::handler(sub_m,&mut runtime)?),
46+
("stat", Some(sub_m)) => Ok(StatCommand::handler(sub_m,&mut runtime)?),
47+
("test", Some(sub_m)) => Ok(TestCommand::handler(sub_m,&mut runtime)?),
4648
_ => Err(Error::MatchError),
4749
}
4850
}

‎src/cmds/data.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use super::Command;
33
use crate::{cache::Cache, helper::Digit};
44
use clap::{App, Arg, ArgMatches, SubCommand};
55
use colored::Colorize;
6+
use tokio::runtime::Runtime;
67

78
/// Abstract `data` command
89
///
@@ -44,7 +45,7 @@ impl Command for DataCommand {
4445
}
4546

4647
/// `data` handler
47-
fn handler(m: &ArgMatches) -> Result<(), crate::err::Error> {
48+
fn handler(m: &ArgMatches,runtime:&mutRuntime) -> Result<(), crate::err::Error> {
4849
use std::fs::File;
4950
use std::path::Path;
5051

@@ -78,7 +79,7 @@ impl Command for DataCommand {
7879

7980
if m.is_present("update") {
8081
flags += 1;
81-
cache.update()?;
82+
runtime.block_on(cache.update())?;
8283
println!("{}", "ok!".bright_green());
8384
}
8485

‎src/cmds/edit.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Edit command
22
use super::Command;
33
use clap::{App, ArgMatches};
4+
use tokio::runtime::Runtime;
45

56
/// Abstract `edit` command
67
///
@@ -43,7 +44,7 @@ impl Command for EditCommand {
4344
}
4445

4546
/// `edit` handler
46-
fn handler(m: &ArgMatches) -> Result<(), crate::Error> {
47+
fn handler(m: &ArgMatches,runtime:&mutRuntime) -> Result<(), crate::Error> {
4748
use crate::{cache::models::Question, Cache};
4849
use std::fs::File;
4950
use std::io::Write;
@@ -65,7 +66,7 @@ impl Command for EditCommand {
6566
if !Path::new(&path).exists() {
6667
let mut qr = serde_json::from_str(&target.desc);
6768
if qr.is_err() {
68-
qr = Ok(cache.get_question(id)?);
69+
qr = Ok(runtime.block_on(cache.get_question(id))?);
6970
}
7071

7172
let question: Question = qr?;

‎src/cmds/exec.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! Exec command
22
use super::Command;
33
use clap::{App, ArgMatches};
4+
use tokio::runtime::Runtime;
45

56
/// Abstract Exec Command
67
///
@@ -36,12 +37,12 @@ impl Command for ExecCommand {
3637
}
3738

3839
/// `exec` handler
39-
fn handler(m: &ArgMatches) -> Result<(), crate::Error> {
40+
fn handler(m: &ArgMatches,runtime:&mutRuntime) -> Result<(), crate::Error> {
4041
use crate::cache::{Cache, Run};
4142

4243
let id: i32 = m.value_of("id")?.parse()?;
4344
let cache = Cache::new()?;
44-
let res = cache.exec_problem(id, Run::Submit, None)?;
45+
let res = runtime.block_on(cache.exec_problem(id, Run::Submit, None))?;
4546

4647
println!("{}", res);
4748
Ok(())

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /