Skip to content

Commit ea12b66

Browse files
committed
refactor: .rustfmt changes, code cleaning
1 parent 1fd194e commit ea12b66

9 files changed

Lines changed: 138 additions & 143 deletions

File tree

.rustfmt.toml

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,22 @@
22
indent_style = "Block"
33
unstable_features = true
44
max_width = 80
5+
use_small_heuristics = "Max"
56
color = "Always"
67
format_strings = true
78
space_after_colon = true
89

910
# structs
10-
struct_field_align_threshold = 20
11-
struct_lit_single_line = false
11+
struct_field_align_threshold = 30
12+
struct_lit_single_line = true
1213
use_field_init_shorthand = true
1314

1415

1516
# Functions
1617
fn_params_layout = "Compressed"
1718
fn_call_width = 80
1819
brace_style = "PreferSameLine"
19-
empty_item_single_line = false
20+
empty_item_single_line = true
2021

2122
# imports
2223
imports_granularity = "Crate"
@@ -38,5 +39,8 @@ overflow_delimited_expr = true
3839
comment_width = 80
3940
wrap_comments = true
4041
format_code_in_doc_comments = true
41-
4242
normalize_comments = true
43+
44+
# if
45+
single_line_if_else_max_width = 80
46+
single_line_let_else_max_width = 80

src/code_signature.rs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use core::panic;
22

33
use leetcoderustapi::ProgrammingLanguage;
4+
use thiserror;
45

56
#[derive(Debug, Clone)]
67
pub struct CodeSignature {
@@ -10,6 +11,12 @@ pub struct CodeSignature {
1011
pub return_type: Option<String>,
1112
}
1213

14+
#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
15+
pub enum CodeSignatureError {
16+
#[error("Error parsing code signature")]
17+
ParseError,
18+
}
19+
1320
impl CodeSignature {
1421
pub fn new_function(name: String, params: Vec<String>) -> Self {
1522
Self {
@@ -31,21 +38,21 @@ impl CodeSignature {
3138

3239
pub fn parse_code_signature(
3340
lang: &ProgrammingLanguage, starter_code: &str,
34-
) -> Result<CodeSignature, String> {
41+
) -> Result<CodeSignature, CodeSignatureError> {
3542
match lang {
3643
ProgrammingLanguage::Python => {
3744
Self::parse_python_signature(&starter_code)
3845
},
3946
ProgrammingLanguage::Rust => {
4047
Self::parse_rust_signature(&starter_code)
4148
},
42-
_ => Err("Unsupported language".to_string()),
49+
_ => Err(CodeSignatureError::ParseError),
4350
}
4451
}
4552

4653
fn parse_python_signature(
4754
starter_code: &str,
48-
) -> Result<CodeSignature, String> {
55+
) -> Result<CodeSignature, CodeSignatureError> {
4956
if let Some(class_start) = starter_code.find("class ") {
5057
let class_end = starter_code[class_start..].find(':').unwrap_or(0)
5158
+ class_start;
@@ -83,12 +90,12 @@ impl CodeSignature {
8390
return Ok(CodeSignature::new_function(fn_name, parameters));
8491
}
8592

86-
Err("No function or class definition found in Python code".to_string())
93+
Err(CodeSignatureError::ParseError)
8794
}
8895

8996
fn parse_rust_signature(
9097
starter_code: &str,
91-
) -> Result<CodeSignature, String> {
98+
) -> Result<CodeSignature, CodeSignatureError> {
9299
if let Some(start) = starter_code.find("fn ") {
93100
let end = starter_code[start..].find('(').unwrap_or(0) + start;
94101
let fn_name = starter_code[start + 3..end].trim().to_string();
@@ -101,7 +108,7 @@ impl CodeSignature {
101108
.collect::<Vec<String>>();
102109
return Ok(CodeSignature::new_function(fn_name, parameters));
103110
}
104-
Err("No function definition found in Rust code".to_string())
111+
Err(CodeSignatureError::ParseError)
105112
}
106113

107114
pub fn resolve_declaration(

src/config.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ impl Default for RuntimeConfigSetup {
3131

3232
impl RuntimeConfigSetup {
3333
pub fn new() -> Self {
34-
let home_dir =
35-
dirs::home_dir().expect("Unable to determine home directory");
34+
let home_dir = dirs::home_dir().expect("no home directory");
3635
let config_dir = home_dir.join(".config/leetcode-cli");
3736
let config_file = config_dir.join("config.toml");
3837
let default_leetcode_dir = home_dir.join("leetcode");

src/leetcode_api_runner.rs

Lines changed: 39 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
use std::io;
1+
use std::{
2+
io,
3+
path::{
4+
Path,
5+
PathBuf,
6+
},
7+
};
28

39
use colored::Colorize;
410
use leetcoderustapi::{
@@ -39,19 +45,14 @@ impl LeetcodeApiRunner {
3945
})
4046
}
4147

42-
pub async fn get_problem_info(&self, id: u32) -> io::Result<String> {
43-
let pb = self.api.set_problem_by_id(id).await.unwrap();
48+
pub async fn get_problem_info(&self, id: u32) -> io::Result<()> {
49+
let pb = self.api.set_problem_by_id(id).await?;
4450

45-
let title = pb.description().unwrap().name.bold().cyan();
46-
let difficulty = match pb.difficulty().as_str() {
47-
"Easy" => "Easy".green(),
48-
"Medium" => "Medium".yellow(),
49-
"Hard" => "Hard".red(),
50-
_ => "Unknown".normal(),
51-
};
52-
let description = html2text(&pb.description().unwrap().content);
51+
let title = pb.description()?.name.bold().cyan();
52+
let difficulty = difficulty_color(&pb.difficulty());
53+
let description = html2text(&pb.description()?.content);
5354

54-
Ok(format!("{} {}: {}\n{}", id, difficulty, title, description))
55+
Ok(println!("{} {}: {}\n{}", id, difficulty, title, description))
5556
}
5657

5758
/// Fetches the problem name by its ID.
@@ -76,54 +77,48 @@ impl LeetcodeApiRunner {
7677

7778
pub async fn start_problem(
7879
&self, id: u32, lang: ProgrammingLanguage,
79-
) -> io::Result<String> {
80+
) -> io::Result<()> {
8081
let pb = self.api.set_problem_by_id(id).await?;
81-
let pb_desc = pb.description().unwrap();
82+
let pb_desc = pb.description()?;
8283
let pb_name = pb_desc.name.replace(" ", "_");
8384
let md_desc = html2md::parse_html(&pb_desc.content);
84-
let pb_dir = self.prepare_problem_directory(id, &pb_name, &lang)?;
85+
let (pb_dir, src_dir) =
86+
self.prepare_problem_dir(id, &pb_name, &lang)?;
8587

8688
let mut starter_code = self.get_starter_code(&lang, &pb)?;
8789
starter_code = inject_default_return_value(&starter_code, &lang);
8890

89-
let test_data =
90-
LeetcodeReadmeParser::new(&md_desc).parse().map_err(|e| {
91-
io::Error::new(io::ErrorKind::InvalidData, e.to_string())
92-
})?;
93-
let tests = TestGenerator::new(&starter_code, test_data)
94-
.run(&lang)
95-
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
91+
let test_data = LeetcodeReadmeParser::new(&md_desc).parse()?;
92+
let tests = TestGenerator::new(&starter_code, test_data).run(&lang)?;
9693

9794
let mut file_content = format!("{}\n\n{}", starter_code, tests);
9895
file_content = prefix_code(&file_content, &lang);
9996
file_content = postfix_code(&file_content, &lang);
10097
write_readme(&pb_dir, id, &pb_name, &md_desc)?;
101-
let src_dir = pb_dir.join("src");
102-
ensure_directory_exists(&src_dir)?;
10398
write_to_file(&src_dir, &get_file_name(&lang), &file_content)?;
10499

105-
Ok(format!(
106-
"Problem {}: {} has been created at {} with the {} programming \
107-
language.",
100+
Ok(println!(
101+
"{}: {} created at {} in {}.",
108102
id,
109-
pb_name,
103+
pb_name.green().bold(),
110104
pb_dir.display(),
111105
language_to_string(&lang)
112106
))
113107
}
114108

115109
/// Prepares the problem directory.
116-
fn prepare_problem_directory(
110+
fn prepare_problem_dir(
117111
&self, id: u32, pb_name: &str, language: &ProgrammingLanguage,
118-
) -> io::Result<std::path::PathBuf> {
112+
) -> io::Result<(PathBuf, PathBuf)> {
119113
let leetcode_dir = self.rcs.resolve_leetcode_dir()?;
120114
let problem_dir = leetcode_dir.join(format!("{}_{}", id, pb_name));
115+
let src_dir = problem_dir.join("src");
116+
121117
ensure_directory_exists(&problem_dir)?;
118+
ensure_directory_exists(&src_dir)?;
122119

123-
// Initialize language-specific project structure
124120
self.initialize_language_project(&problem_dir, pb_name, language)?;
125-
126-
Ok(problem_dir)
121+
Ok((problem_dir, src_dir))
127122
}
128123

129124
/// Generates starter code for the specified programming language.
@@ -154,41 +149,32 @@ impl LeetcodeApiRunner {
154149
}
155150

156151
pub async fn test_response(
157-
&self, id: u32, path_to_file: String,
158-
) -> io::Result<String> {
159-
let problem_info = self.api.set_problem_by_id(id).await.unwrap();
152+
&self, id: u32, path_to_file: &String,
153+
) -> io::Result<()> {
154+
let problem_info = self.api.set_problem_by_id(id).await?;
160155
let file_content = std::fs::read_to_string(&path_to_file)
161156
.expect("Unable to read the file");
162157
let language = get_language_from_extension(&path_to_file);
163158

164-
let test_response = problem_info
165-
.send_test(language, &file_content)
166-
.await
167-
.unwrap();
168-
Ok(format!("Test response for problem {}: {:#?}", id, test_response))
159+
let test_res = problem_info.send_test(language, &file_content).await?;
160+
Ok(println!("Test response for problem {}: {:?}", id, test_res))
169161
}
170162

171163
pub async fn submit_response(
172-
&self, id: u32, path_to_file: String,
173-
) -> io::Result<String> {
174-
let problem_info = self.api.set_problem_by_id(id).await.unwrap();
164+
&self, id: u32, path_to_file: &String,
165+
) -> io::Result<()> {
166+
let pb = self.api.set_problem_by_id(id).await?;
175167
let file_content = std::fs::read_to_string(&path_to_file)
176168
.expect("Unable to read the file");
177169
let language = get_language_from_extension(&path_to_file);
178170

179-
let test_response = problem_info
180-
.send_subm(language, &file_content)
181-
.await
182-
.unwrap();
183-
Ok(format!(
184-
"Here's your submit response for problem {}: {:#?}",
185-
id, test_response
186-
))
171+
let sub_res = pb.send_subm(language, &file_content).await?;
172+
Ok(println!("{}: submit result {:?}", id, sub_res))
187173
}
188174

189175
/// Initializes language-specific project structure.
190176
fn initialize_language_project(
191-
&self, problem_dir: &std::path::Path, pb_name: &str,
177+
&self, problem_dir: &Path, pb_name: &str,
192178
language: &ProgrammingLanguage,
193179
) -> io::Result<()> {
194180
use std::process::Command;

src/main.rs

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
1919
let api_runner = LeetcodeApiRunner::new(&rcs).await?;
2020

2121
match &cli.command {
22-
Commands::Info {
23-
id,
24-
} => {
22+
Commands::Info { id } => {
2523
let mut spin = spin_the_spinner("Fetching problem info...");
2624
let result = api_runner.get_problem_info(*id).await;
2725
spin.stop();
2826
match result {
29-
Ok(info) => println!("{}", info),
27+
Ok(_) => (),
3028
Err(e) => eprintln!("Error fetching problem info: {}", e),
3129
}
3230
},
33-
Commands::Start {
34-
id,
35-
language,
36-
} => {
31+
Commands::Start { id, language } => {
3732
let default_lang = rcs
3833
.config
3934
.default_language
@@ -61,33 +56,27 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6156
let start_problem = api_runner.start_problem(*id, lang).await;
6257
spin.stop();
6358
match start_problem {
64-
Ok(message) => println!("{}\n\nHappy coding :)", message),
59+
Ok(_) => println!("\n\nHappy coding :)"),
6560
Err(e) => eprintln!("Error starting problem: {}", e),
6661
}
6762
},
68-
Commands::Test {
69-
id,
70-
path_to_file,
71-
} => {
63+
Commands::Test { id, path_to_file } => {
7264
let mut spin = spin_the_spinner("Running tests...");
7365
let test_result =
74-
api_runner.test_response(*id, path_to_file.clone()).await;
66+
api_runner.test_response(*id, &path_to_file.clone()).await;
7567
spin.stop();
7668
match test_result {
77-
Ok(result) => println!("Test result: {}", result),
69+
Ok(_) => println!("Test result"),
7870
Err(e) => eprintln!("Error running tests: {}", e),
7971
}
8072
},
81-
Commands::Submit {
82-
id,
83-
path_to_file,
84-
} => {
73+
Commands::Submit { id, path_to_file } => {
8574
let mut spin = spin_the_spinner("Submitting solution...");
8675
let submit_result =
87-
api_runner.submit_response(*id, path_to_file.clone()).await;
76+
api_runner.submit_response(*id, &path_to_file.clone()).await;
8877
spin.stop();
8978
match submit_result {
90-
Ok(result) => println!("Submit result: {}", result),
79+
Ok(_) => println!("Submit result"),
9180
Err(e) => eprintln!("Error submitting solution: {}", e),
9281
}
9382
},

src/readme_parser.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,15 @@ pub enum LeetcodeReadmeParserError {
1717
EmptyReadme,
1818
}
1919

20+
impl From<LeetcodeReadmeParserError> for std::io::Error {
21+
fn from(e: LeetcodeReadmeParserError) -> Self {
22+
std::io::Error::new(std::io::ErrorKind::InvalidData, e)
23+
}
24+
}
25+
2026
impl LeetcodeReadmeParser {
2127
pub fn new(readme: &str) -> Self {
22-
LeetcodeReadmeParser {
23-
raw: readme.to_string(),
24-
}
28+
LeetcodeReadmeParser { raw: readme.to_string() }
2529
}
2630

2731
pub fn parse(&self) -> Result<ProblemTestData, LeetcodeReadmeParserError> {
@@ -36,10 +40,7 @@ impl LeetcodeReadmeParser {
3640
}
3741

3842
fn count_examples(&self) -> usize {
39-
self.raw
40-
.lines()
41-
.filter(|line| line.starts_with("**Example"))
42-
.count()
43+
self.raw.lines().filter(|line| line.starts_with("**Example")).count()
4344
}
4445

4546
fn extract_inputs(&self) -> Vec<String> {

0 commit comments

Comments
 (0)