Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat(result): flatten results
  • Loading branch information
clearloop committed Dec 19, 2023
commit 1e6c6666b90fe7bf9bbfa835ffa9743edb81443d
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/cmds/edit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Edit command
use super::Command;
use crate::Error;
use crate::{Error, Result};
use anyhow::anyhow;
use async_trait::async_trait;
use clap::{Arg, ArgMatches, Command as ClapCommand};
Expand Down Expand Up @@ -48,7 +48,7 @@ impl Command for EditCommand {
}

/// `edit` handler
async fn handler(m: &ArgMatches) -> Result<(), crate::Error> {
async fn handler(m: &ArgMatches) -> Result<()> {
use crate::{cache::models::Question, Cache};
use std::fs::File;
use std::io::Write;
Expand Down
4 changes: 2 additions & 2 deletions src/cmds/exec.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Exec command
use super::Command;
use crate::Error;
use crate::{Error, Result};
use async_trait::async_trait;
use clap::{Arg, ArgMatches, Command as ClapCommand};

Expand Down Expand Up @@ -39,7 +39,7 @@ impl Command for ExecCommand {
}

/// `exec` handler
async fn handler(m: &ArgMatches) -> Result<(), crate::Error> {
async fn handler(m: &ArgMatches) -> Result<()> {
use crate::cache::{Cache, Run};

let id: i32 = *m.get_one::<i32>("id").ok_or(Error::NoneError)?;
Expand Down
4 changes: 2 additions & 2 deletions src/cmds/test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Test command
use super::Command;
use crate::Error;
use crate::{Error, Result};
use async_trait::async_trait;
use clap::{Arg, ArgMatches, Command as ClapCommand};

Expand Down Expand Up @@ -45,7 +45,7 @@ impl Command for TestCommand {
}

/// `test` handler
async fn handler(m: &ArgMatches) -> Result<(), Error> {
async fn handler(m: &ArgMatches) -> Result<()> {
use crate::cache::{Cache, Run};
let id: i32 = *m.get_one::<i32>("id").ok_or(Error::NoneError)?;
let testcase = m.get_one::<String>("testcase");
Expand Down
10 changes: 5 additions & 5 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
//! + Use `leetcode config` to update it
use crate::{
config::{code::Code, cookies::Cookies, storage::Storage, sys::Sys},
Error,
Error, Result,
};
use serde::{Deserialize, Serialize};
use std::{fs, path::Path};
Expand All @@ -28,14 +28,14 @@ pub struct Config {
}

impl Config {
fn write_default(p: impl AsRef<Path>) -> Result<(), crate::Error> {
fn write_default(p: impl AsRef<Path>) -> Result<()> {
fs::write(p.as_ref(), toml::ser::to_string_pretty(&Self::default())?)?;

Ok(())
}

/// Locate lc's config file
pub fn locate() -> Result<Config, crate::Error> {
pub fn locate() -> Result<Config> {
let conf = Self::root()?.join("leetcode.toml");

if !conf.is_file() {
Expand All @@ -54,7 +54,7 @@ impl Config {
}

/// Get root path of leetcode-cli
pub fn root() -> Result<std::path::PathBuf, Error> {
pub fn root() -> Result<std::path::PathBuf> {
let dir = dirs::home_dir().ok_or(Error::NoneError)?.join(".leetcode");
if !dir.is_dir() {
info!("Generate root dir at {:?}.", &dir);
Expand All @@ -65,7 +65,7 @@ impl Config {
}

/// Sync new config to config.toml
pub fn sync(&self) -> Result<(), Error> {
pub fn sync(&self) -> Result<()> {
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
10 changes: 5 additions & 5 deletions src/config/storage.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Storage in config.
use crate::Error;
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::{fs, path::PathBuf};

Expand Down Expand Up @@ -27,7 +27,7 @@ impl Default for Storage {

impl Storage {
/// convert root path
pub fn root(&self) -> Result<String, Error> {
pub fn root(&self) -> Result<String> {
let home = dirs::home_dir()
.ok_or(Error::NoneError)?
.to_string_lossy()
Expand All @@ -37,7 +37,7 @@ impl Storage {
}

/// get cache path
pub fn cache(&self) -> Result<String, crate::Error> {
pub fn cache(&self) -> Result<String> {
let root = PathBuf::from(self.root()?);
if !root.exists() {
info!("Generate cache dir at {:?}.", &root);
Expand All @@ -48,7 +48,7 @@ impl Storage {
}

/// get code path
pub fn code(&self) -> Result<String, crate::Error> {
pub fn code(&self) -> Result<String> {
let root = &self.root()?;
let p = PathBuf::from(root).join(&self.code);
if !PathBuf::from(&p).exists() {
Expand All @@ -59,7 +59,7 @@ impl Storage {
}

/// get scripts path
pub fn scripts(mut self) -> Result<String, crate::Error> {
pub fn scripts(mut self) -> Result<String> {
let root = &self.root()?;
if self.scripts.is_none() {
self.scripts = Some("scripts".into());
Expand Down
3 changes: 3 additions & 0 deletions src/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ const CONFIG: &str = "~/.leetcode/leetcode.tmp.toml";
#[cfg(not(debug_assertions))]
const CONFIG: &str = "~/.leetcode/leetcode_tmp.toml";

/// Leetcode result.
pub type Result<T> = std::result::Result<T, Error>;

/// Leetcode cli errors
#[derive(thiserror::Error, Debug)]
pub enum Error {
Expand Down
20 changes: 11 additions & 9 deletions src/helper.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
//! A set of helper traits
pub use self::digit::Digit;
pub use self::file::{code_path, load_script, test_cases_path};
pub use self::filter::{filter, squash};
pub use self::html::HTML;
pub use self::{
digit::Digit,
file::{code_path, load_script, test_cases_path},
filter::{filter, squash},
html::HTML,
};

/// Convert i32 to specific digits string.
mod digit {
Expand Down Expand Up @@ -78,7 +80,7 @@ mod filter {
}

/// Squash questions and ids
pub fn squash(ps: &mut Vec<Problem>, ids: Vec<String>) -> Result<(), crate::Error> {
pub fn squash(ps: &mut Vec<Problem>, ids: Vec<String>) -> crate::Result<()> {
use std::collections::HashMap;

let mut map: HashMap<String, bool> = HashMap::new();
Expand Down Expand Up @@ -164,7 +166,7 @@ mod html {

mod file {
/// Convert file suffix from language type
pub fn suffix(l: &str) -> Result<&'static str, crate::Error> {
pub fn suffix(l: &str) -> crate::Result<&'static str> {
match l {
"bash" => Ok("sh"),
"c" => Ok("c"),
Expand All @@ -191,7 +193,7 @@ mod file {
use crate::{cache::models::Problem, Error};

/// Generate test cases path by fid
pub fn test_cases_path(problem: &Problem) -> Result<String, Error> {
pub fn test_cases_path(problem: &Problem) -> crate::Result<String> {
let conf = crate::config::Config::locate()?;
let mut path = format!("{}/{}.tests.dat", conf.storage.code()?, conf.code.pick);

Expand All @@ -201,7 +203,7 @@ mod file {
}

/// Generate code path by fid
pub fn code_path(problem: &Problem, l: Option<String>) -> Result<String, Error> {
pub fn code_path(problem: &Problem, l: Option<String>) -> crate::Result<String> {
let conf = crate::config::Config::locate()?;
let mut lang = conf.code.lang;
if l.is_some() {
Expand All @@ -222,7 +224,7 @@ mod file {
}

/// Load python scripts
pub fn load_script(module: &str) -> Result<String, crate::Error> {
pub fn load_script(module: &str) -> crate::Result<String> {
use std::fs::File;
use std::io::Read;
let conf = crate::config::Config::locate()?;
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,4 +248,4 @@ pub mod pym;
// re-exports
pub use cache::Cache;
pub use config::Config;
pub use err::Error;
pub use err::{Error, Result};
10 changes: 5 additions & 5 deletions src/plugins/chrome.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{cache, Error};
use crate::{cache, Error, Result};
use anyhow::anyhow;
use diesel::prelude::*;
use keyring::Entry;
Expand Down Expand Up @@ -41,7 +41,7 @@ impl std::string::ToString for Ident {
}

/// Get cookies from chrome storage
pub fn cookies() -> Result<Ident, crate::Error> {
pub fn cookies() -> Result<Ident> {
let ccfg = crate::config::Config::locate()?.cookies;
if !ccfg.csrf.is_empty() && !ccfg.session.is_empty() {
return Ok(Ident {
Expand Down Expand Up @@ -70,7 +70,7 @@ pub fn cookies() -> Result<Ident, crate::Error> {

debug!("res {:?}", &res);
if res.is_empty() {
return Err(crate::Error::CookieError);
return Err(Error::CookieError);
}

// Get system password
Expand All @@ -95,7 +95,7 @@ pub fn cookies() -> Result<Ident, crate::Error> {
}

/// Decode cookies from chrome
fn decode_cookies(pass: &str, v: Vec<u8>) -> Result<String, crate::Error> {
fn decode_cookies(pass: &str, v: Vec<u8>) -> Result<String> {
let mut key = [0_u8; 16];
match std::env::consts::OS {
"macos" => {
Expand Down Expand Up @@ -125,7 +125,7 @@ fn decode_cookies(pass: &str, v: Vec<u8>) -> Result<String, crate::Error> {
}

/// Decrypt chrome cookie value with aes-128-cbc
fn chrome_decrypt(v: Vec<u8>, key: [u8; 16]) -> Result<String, crate::Error> {
fn chrome_decrypt(v: Vec<u8>, key: [u8; 16]) -> Result<String> {
// <space>: \u16
let iv = vec![32_u8; 16];
let mut decrypter = symm::Crypter::new(
Expand Down
21 changes: 10 additions & 11 deletions src/plugins/leetcode.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use self::req::{Json, Mode, Req};
use crate::{
config::{self, Config},
err::Error,
// plugins::chrome,
Result,
};
use reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Expand All @@ -20,7 +19,7 @@ pub struct LeetCode {

impl LeetCode {
/// Parse reqwest headers
fn headers(mut headers: HeaderMap, ts: Vec<(&str, &str)>) -> Result<HeaderMap, Error> {
fn headers(mut headers: HeaderMap, ts: Vec<(&str, &str)>) -> Result<HeaderMap> {
for (k, v) in ts.into_iter() {
let name = HeaderName::from_str(k)?;
let value = HeaderValue::from_str(v)?;
Expand All @@ -31,7 +30,7 @@ impl LeetCode {
}

/// New LeetCode client
pub fn new() -> Result<LeetCode, crate::Error> {
pub fn new() -> Result<LeetCode> {
let conf = config::Config::locate()?;
let (cookie, csrf) = if conf.cookies.csrf.is_empty() || conf.cookies.session.is_empty() {
let cookies = super::chrome::cookies()?;
Expand Down Expand Up @@ -62,7 +61,7 @@ impl LeetCode {
}

/// Get category problems
pub async fn get_category_problems(self, category: &str) -> Result<Response, Error> {
pub async fn get_category_problems(self, category: &str) -> Result<Response> {
trace!("Requesting {} problems...", &category);
let url = &self.conf.sys.urls.problems(category);

Expand All @@ -79,7 +78,7 @@ impl LeetCode {
.await
}

pub async fn get_question_ids_by_tag(self, slug: &str) -> Result<Response, Error> {
pub async fn get_question_ids_by_tag(self, slug: &str) -> Result<Response> {
trace!("Requesting {} ref problems...", &slug);
let url = &self.conf.sys.urls.graphql;
let mut json: Json = HashMap::new();
Expand Down Expand Up @@ -112,7 +111,7 @@ impl LeetCode {
.await
}

pub async fn get_user_info(self) -> Result<Response, Error> {
pub async fn get_user_info(self) -> Result<Response> {
trace!("Requesting user info...");
let url = &self.conf.sys.urls.graphql;
let mut json: Json = HashMap::new();
Expand Down Expand Up @@ -142,7 +141,7 @@ impl LeetCode {
}

/// Get daily problem
pub async fn get_question_daily(self) -> Result<Response, Error> {
pub async fn get_question_daily(self) -> Result<Response> {
trace!("Requesting daily problem...");
let url = &self.conf.sys.urls.graphql;
let mut json: Json = HashMap::new();
Expand Down Expand Up @@ -175,7 +174,7 @@ impl LeetCode {
}

/// Get specific problem detail
pub async fn get_question_detail(self, slug: &str) -> Result<Response, Error> {
pub async fn get_question_detail(self, slug: &str) -> Result<Response> {
trace!("Requesting {} detail...", &slug);
let refer = self.conf.sys.urls.problem(slug);
let mut json: Json = HashMap::new();
Expand Down Expand Up @@ -219,7 +218,7 @@ impl LeetCode {
}

/// Send code to judge
pub async fn run_code(self, j: Json, url: String, refer: String) -> Result<Response, Error> {
pub async fn run_code(self, j: Json, url: String, refer: String) -> Result<Response> {
info!("Sending code to judge...");
Req {
default_headers: self.default_headers,
Expand All @@ -235,7 +234,7 @@ impl LeetCode {
}

/// Get the result of submission / testing
pub async fn verify_result(self, id: String) -> Result<Response, Error> {
pub async fn verify_result(self, id: String) -> Result<Response> {
trace!("Verifying result...");
let url = self.conf.sys.urls.verify(&id);

Expand Down
Loading