Skip to content

Commit bcd2539

Browse files
committed
Improve error handling in codefile.rs and others
1 parent 13802f7 commit bcd2539

File tree

3 files changed

+56
-72
lines changed

3 files changed

+56
-72
lines changed

src/file_parser/codefile.rs

Lines changed: 51 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use eyre::Result;
2+
13
use super::language::*;
24
use std::path::PathBuf;
35

@@ -20,43 +22,42 @@ impl Default for CodeFile {
2022
}
2123

2224
impl CodeFile {
23-
pub fn from_dir() -> Self {
25+
pub fn from_file(path: &str) -> Result<Self> {
26+
let path = PathBuf::from(&path);
27+
let (_file_name, mut code_file) =
28+
Self::is_valid_file(&path).ok_or_else(|| eyre::eyre!("Invalid file"))?;
29+
let code = std::fs::read_to_string(&path)?;
30+
31+
let (question_title, parsed_code) = Self::parse_code(&code, code_file.language)?;
32+
33+
code_file.question_title = question_title;
34+
code_file.code = parsed_code;
35+
36+
Ok(code_file)
37+
}
38+
39+
pub fn from_dir() -> Result<Self> {
2440
let mut code_file: Option<CodeFile> = None;
25-
let Ok(files) = std::fs::read_dir("./") else {
26-
eprintln!("Error reading the current directory!");
27-
std::process::exit(1);
28-
};
29-
for file in files {
30-
let Ok(file) = file else {
31-
// Bad path
32-
continue
33-
};
41+
for file in std::fs::read_dir(".")?.filter_map(|f| f.ok()) {
3442
let path = file.path();
35-
let Some(valid_file) = Self::is_valid_file(&path) else {continue};
36-
let file_name = valid_file.0;
37-
code_file = Some(valid_file.1);
38-
39-
if file_name.starts_with("main") {
40-
break;
43+
if let Some((file_name, code_file_)) = Self::is_valid_file(&path) {
44+
code_file = Some(code_file_);
45+
if file_name.starts_with("main") {
46+
break;
47+
}
4148
}
4249
}
43-
let mut code_file = code_file.unwrap_or_else(|| {
44-
eprintln!("No code file found! Try creating a file named with proper extension",);
45-
std::process::exit(1);
46-
});
47-
let Ok(code) = std::fs::read_to_string(&code_file.path) else {
48-
eprintln!("Error reading the code file!");
49-
std::process::exit(1);
50-
};
51-
52-
let parsed_file = Self::parse_code(&code, code_file.language);
53-
let Ok((question_title, parsed_code)) = parsed_file else{
54-
eprintln!("Error parsing the code file!\n{}", parsed_file.unwrap_err());
55-
std::process::exit(1);
56-
};
50+
let mut code_file = code_file.ok_or_else(|| {
51+
eyre::eyre!("No code file found! Try creating a file named with proper extension")
52+
})?;
53+
let code = std::fs::read_to_string(&code_file.path)?;
54+
55+
let (question_title, parsed_code) = Self::parse_code(&code, code_file.language)?;
56+
5757
code_file.question_title = question_title;
5858
code_file.code = parsed_code;
59-
code_file
59+
60+
Ok(code_file)
6061
}
6162

6263
fn is_valid_file<'a>(path: &'a std::path::PathBuf) -> Option<(&'a str, Self)> {
@@ -75,9 +76,7 @@ impl CodeFile {
7576
))
7677
}
7778

78-
fn parse_code(code: &str, language: Language) -> Result<(String, String), &str> {
79-
let question_title: String;
80-
let parsed_code: String;
79+
fn parse_code(code: &str, language: Language) -> Result<(String, String)> {
8180
let start = code
8281
.find("#LCSTART")
8382
.map(|idx| idx + code[idx..].find('\n').unwrap_or(0))
@@ -87,40 +86,26 @@ impl CodeFile {
8786
.unwrap_or(0);
8887

8988
let end = code.find("#LCEND").unwrap_or(code.len());
90-
if let Some(problem) = code.find("leetcode.com/problems/") {
91-
let problem = (&code[problem..]).split_whitespace().next().unwrap();
92-
let problem = problem.split('/').skip(2).next().unwrap();
93-
question_title = problem.to_string();
94-
} else {
95-
return Err("No leetcode problem found in the code file. Please add the problem link in the code file using comments.");
96-
}
97-
let code = code[start..end].trim();
98-
let code = code
89+
let question_title = code[code.find("leetcode.com/problems/").ok_or_else(|| {
90+
eyre::eyre!(
91+
"No leetcode problem found in the code file. \
92+
Please add the problem link in the code file using comments."
93+
)
94+
})?..]
95+
.split_whitespace()
96+
.next()
97+
.expect("Should be Some since the find method succeed")
98+
.split('/')
99+
.skip(2)
100+
.next()
101+
.ok_or_else(|| eyre::eyre!("Invalid link, expected question identifier"))?
102+
.to_string();
103+
let parsed_code = code[start..end]
104+
.trim()
99105
.trim_end_matches(language.inline_comment_start())
100-
.trim_end();
101-
parsed_code = code.to_string();
106+
.trim_end()
107+
.to_string();
102108

103109
Ok((question_title, parsed_code))
104110
}
105-
106-
pub fn from_file(path: &str) -> Self {
107-
let path = PathBuf::from(&path);
108-
let Some(file) = Self::is_valid_file(&path) else {
109-
eprintln!("Invalid file!");
110-
std::process::exit(1);
111-
};
112-
let (_, mut valid_file) = file;
113-
let Ok(code) = std::fs::read_to_string(&path) else {
114-
eprintln!("Error while reading file {}!", path.display());
115-
std::process::exit(1);
116-
};
117-
let parsed_file = Self::parse_code(&code, valid_file.language);
118-
let Ok((question_title, parsed_code)) = parsed_file else{
119-
eprintln!("Error parsing the code file!\n{}", parsed_file.unwrap_err());
120-
std::process::exit(1);
121-
};
122-
valid_file.question_title = question_title;
123-
valid_file.code = parsed_code;
124-
valid_file
125-
}
126111
}

src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,9 @@ fn main() -> Result<()> {
7070
}
7171
Some(Commands::FastSubmit { filename }) => {
7272
let code_file = if let Some(path) = filename {
73-
CodeFile::from_file(&path)
73+
CodeFile::from_file(&path)?
7474
} else {
75-
CodeFile::from_dir()
75+
CodeFile::from_dir()?
7676
};
7777

7878
submit(&lc, code_file)?;

src/utils.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,16 @@ use crate::handlers::utils::{ExecutionResult, SubmissionResult};
44

55
use eyre::{bail, Result};
66

7-
use std::process::ExitCode;
8-
7+
/// The first element of the return tuple indicates whether the answer is correct.
98
pub(crate) fn execute_testcases(
109
filename: Option<String>,
1110
testcases: Option<String>,
1211
lc: &LeetCode<Authorized>,
1312
) -> Result<(bool, CodeFile)> {
1413
let code_file = if let Some(path) = filename {
15-
CodeFile::from_file(&path)
14+
CodeFile::from_file(&path)?
1615
} else {
17-
CodeFile::from_dir()
16+
CodeFile::from_dir()?
1817
};
1918

2019
match testcases {

0 commit comments

Comments
 (0)