Skip to content

feat(err): wrap NoneError into Error #51

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 8 commits into from
Dec 12, 2021
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
4 changes: 1 addition & 3 deletions .github/workflows/clippy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
7 changes: 3 additions & 4 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ path = "src/bin/lc.rs"

[package]
name = "leetcode-cli"
version = "0.3.9"
version = "0.3.10"
authors = ["clearloop <[email protected]>"]
edition = "2018"
description = "Leet your code in command-line."
Expand Down
18 changes: 1 addition & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
1 change: 0 additions & 1 deletion rust-toolchain

This file was deleted.

20 changes: 10 additions & 10 deletions src/cache/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)?;
Expand All @@ -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)?,
Expand Down Expand Up @@ -235,18 +235,18 @@ 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)
}
};

Ok((
json,
[
url,
conf.sys.urls.get("problems")?.replace("$slug", &p.slug),
conf.sys.urls.get("problems").ok_or(Error::NoneError)?.replace("$slug", &p.slug),
],
))
}
Expand Down Expand Up @@ -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)
}
Expand Down
70 changes: 35 additions & 35 deletions src/cache/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand All @@ -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)]
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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<String>,
#[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<String>,
// #[serde(default)]
// expected_elapsed_time: i64,
// #[serde(default)]
// expected_task_finish_time: i64,
#[serde(default, deserialize_with = "ssr")]
pub expected_code_answer: Vec<String>,
}
Expand Down
21 changes: 10 additions & 11 deletions src/cache/parser.rs
Original file line number Diff line number Diff line change
@@ -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<Problem>, v: Value) -> Result<(), Error> {
pub fn problem(problems: &mut Vec<Problem>, v: Value) -> Option<()> {
let pairs = v.get("stat_status_pairs")?.as_array()?;
for p in pairs {
let stat = p.get("stat")?.as_object()?;
Expand All @@ -26,11 +25,11 @@ pub fn problem(problems: &mut Vec<Problem>, 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")?
Expand All @@ -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")?
Expand All @@ -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<Vec<String>, Error> {
pub fn tags(v: Value) -> Option<Vec<String>> {
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()?;
Expand All @@ -75,7 +74,7 @@ pub fn tags(v: Value) -> Result<Vec<String>, Error> {
res.push(q.as_object()?.get("questionId")?.as_str()?.to_string())
}

Ok(res)
Some(res)
}

pub use ss::ssr;
Expand Down
19 changes: 10 additions & 9 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)?)?;

Expand Down Expand Up @@ -148,8 +149,8 @@ pub struct Storage {

impl Storage {
/// convert root path
pub fn root(&self) -> Result<String, crate::Error> {
let home = dirs::home_dir()?.to_string_lossy().to_string();
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);
Ok(path)
}
Expand Down Expand Up @@ -178,11 +179,11 @@ impl Storage {
pub fn scripts(mut self) -> Result<String, crate::Error> {
let root = &self.root()?;
if self.scripts.is_none() {
let tmp = toml::from_str::<Config>(&DEFAULT_CONFIG)?;
self.scripts = Some(tmp.storage.scripts?);
let tmp = toml::from_str::<Config>(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)?
}
Expand All @@ -203,8 +204,8 @@ pub fn locate() -> Result<Config, crate::Error> {
}

/// Get root path of leetcode-cli
pub fn root() -> Result<std::path::PathBuf, crate::Error> {
let dir = dirs::home_dir()?.join(".leetcode");
pub fn root() -> Result<std::path::PathBuf, Error> {
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)?;
Expand Down
Loading