Skip to content

Commit f13eab7

Browse files
authored
Merge pull request #12 from nozwock/string
Split long query strings
2 parents a98b2bc + c8ea3b0 commit f13eab7

File tree

5 files changed

+104
-38
lines changed

5 files changed

+104
-38
lines changed

src/file_parser/codefile.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,11 @@ impl CodeFile {
7979
fn parse_code(code: &str, language: Language) -> Result<(String, String)> {
8080
let start = code
8181
.find("#LCSTART")
82-
.map(|idx| idx + code[idx..].find('\n').unwrap_or(0))
82+
.map(|idx| idx + code[idx..].find('\n').unwrap_or_default())
8383
// This returning None means the user
8484
// wants to submit a practically empty file,
8585
// but hey we don't judge!
86-
.unwrap_or(0);
86+
.unwrap_or_default();
8787

8888
let end = code.find("#LCEND").unwrap_or(code.len());
8989
let question_title = code[code.find("leetcode.com/problems/").ok_or_else(|| {

src/handlers/helpers.rs

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use colored::Colorize;
2+
use eyre::Result;
23
use serde::{Deserialize, Serialize};
34

45
#[derive(Debug, Serialize)]
@@ -72,39 +73,29 @@ pub(crate) struct BoilerPlateCode {
7273

7374
use super::super::file_parser::language::Language;
7475
impl BoilerPlateCode {
75-
pub(crate) fn save_code(&self, filename: &str, title_slug: &str) {
76-
let language = Language::from_slug(&self.langSlug).unwrap_or_else(|| {
77-
eprintln!("Error: Unable to identify language of code file!");
78-
std::process::exit(1);
79-
});
80-
let Ok(mut file) = std::fs::File::create(filename) else{
81-
eprintln!("Error: Unable to create file");
82-
std::process::exit(1);
83-
};
76+
pub(crate) fn save_code(&self, filename: &str, title_slug: &str) -> Result<()> {
77+
let language = Language::from_slug(&self.langSlug)
78+
.ok_or_else(|| eyre::eyre!("Unable to identify language of code file!"))?;
79+
let mut file = std::fs::File::create(filename)?;
8480
let comment = format!(
8581
" {} #LCEND https://leetcode.com/problems/{}/",
8682
language.inline_comment_start(),
8783
title_slug.to_lowercase().trim().replace(" ", "-")
8884
);
85+
8986
// write code into file along with the comment
90-
if let Err(_) = std::io::Write::write_all(&mut file, self.code.as_bytes()) {
91-
eprintln!("Error: Unable to write code into file");
92-
std::process::exit(1);
93-
}
94-
if let Err(_) = std::io::Write::write_all(&mut file, comment.as_bytes()) {
95-
eprintln!("Error: Unable to write code into file");
96-
std::process::exit(1);
97-
}
87+
std::io::Write::write_all(&mut file, self.code.as_bytes())?;
88+
std::io::Write::write_all(&mut file, comment.as_bytes())?;
89+
90+
Ok(())
9891
}
9992
pub(crate) fn is_supported(&self) -> bool {
10093
Language::from_slug(&self.langSlug).is_some()
10194
}
102-
pub(crate) fn extension(&self) -> String {
103-
let language = Language::from_slug(&self.langSlug).unwrap_or_else(|| {
104-
eprintln!("Error: Unable to identify language of code file!");
105-
std::process::exit(1);
106-
});
107-
language.extension().to_owned()
95+
pub(crate) fn extension(&self) -> Result<String> {
96+
let language = Language::from_slug(&self.langSlug)
97+
.ok_or_else(|| eyre::eyre!("Unable to identify language of code file!"))?;
98+
Ok(language.extension().to_owned())
10899
}
109100
}
110101

src/handlers/leetcode/api/question.rs

Lines changed: 76 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,34 @@ impl LeetCode<Authorized> {
77
let url = "https://leetcode.com/graphql";
88
let client = &self.client;
99
let query = GraphqlRequest {
10-
query: "\n query questionOfToday {\n activeDailyCodingChallengeQuestion {\n date\n userStatus\n link\n question {\n acRate\n difficulty\n freqBar\n frontendQuestionId: questionFrontendId\n isFavor\n paidOnly: isPaidOnly\n status\n title\n titleSlug\n hasVideoSolution\n hasSolution\n topicTags {\n name\n id\n slug\n }\n }\n }\n}\n ".to_string(),
10+
query: r#"
11+
query questionOfToday {
12+
activeDailyCodingChallengeQuestion {
13+
date
14+
userStatus
15+
link
16+
question {
17+
acRate
18+
difficulty
19+
freqBar
20+
frontendQuestionId: questionFrontendId
21+
isFavor
22+
paidOnly: isPaidOnly
23+
status
24+
title
25+
titleSlug
26+
hasVideoSolution
27+
hasSolution
28+
topicTags {
29+
name
30+
id
31+
slug
32+
}
33+
}
34+
}
35+
}
36+
"#
37+
.to_string(),
1138
variables: "{}".to_string(),
1239
};
1340

@@ -52,8 +79,17 @@ impl LeetCode<Authorized> {
5279
let client = &self.client;
5380
let url = "https://leetcode.com/graphql";
5481
let query = GraphqlRequest {
55-
query: "query questionContent($titleSlug: String!) { question(titleSlug: $titleSlug) { content mysqlSchemas }}".to_string(),
56-
variables: serde_json::to_string(&Variables { titleSlug: title_slug.to_string() }).unwrap(),
82+
query: r#"
83+
query questionContent($titleSlug: String!) {
84+
question(titleSlug: $titleSlug) {
85+
content mysqlSchemas
86+
}
87+
}
88+
"#
89+
.to_string(),
90+
variables: serde_json::to_string(&Variables {
91+
titleSlug: title_slug.to_string(),
92+
})?,
5793
};
5894

5995
let data = client.post(url).json(&query).send()?;
@@ -67,7 +103,21 @@ impl LeetCode<Authorized> {
67103
data: QuestionWrapper,
68104
}
69105

70-
let query = "\n query questionEditorData($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n questionId\n questionFrontendId\n codeSnippets {\n lang\n langSlug\n code\n }\n envInfo\n enableRunCode\n }\n}\n ";
106+
let query = r#"
107+
query questionEditorData($titleSlug: String!) {
108+
question(titleSlug: $titleSlug) {
109+
questionId
110+
questionFrontendId
111+
codeSnippets {
112+
lang
113+
langSlug
114+
code
115+
}
116+
envInfo
117+
enableRunCode
118+
}
119+
}
120+
"#;
71121
let varibales = serde_json::to_string(&Variables {
72122
titleSlug: title_slug.to_string(),
73123
})?;
@@ -121,15 +171,15 @@ impl LeetCode<Authorized> {
121171
};
122172

123173
let mut input = String::new();
124-
println!("Filename (main.{}) : ", &(boiler_code.extension()));
174+
println!("Filename (main.{}) : ", &(boiler_code.extension()?));
125175
std::io::stdin().read_line(&mut input)?;
126176
let input = input.trim();
127177
let filename = if input.is_empty() {
128-
format!("main.{}", boiler_code.extension())
178+
format!("main.{}", boiler_code.extension()?)
129179
} else {
130180
input.to_string()
131181
};
132-
boiler_code.save_code(&filename, &title_slug);
182+
boiler_code.save_code(&filename, &title_slug)?;
133183

134184
Ok(data.json::<Data>().map(|op| op.data.question)?)
135185
}
@@ -139,8 +189,25 @@ impl LeetCode<Authorized> {
139189
let url = "https://leetcode.com/graphql";
140190

141191
let query = GraphqlRequest {
142-
query: "\n query consolePanelConfig($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n questionId\n questionFrontendId\n questionTitle\n enableDebugger\n enableRunCode\n enableSubmit\n enableTestMode\n exampleTestcaseList\n metaData\n }\n}\n".to_string(),
143-
variables: serde_json::to_string(&Variables { titleSlug: title_slug.to_string() }).unwrap(),
192+
query: r#"
193+
query consolePanelConfig($titleSlug: String!) {
194+
question(titleSlug: $titleSlug) {
195+
questionId
196+
questionFrontendId
197+
questionTitle
198+
enableDebugger
199+
enableRunCode
200+
enableSubmit
201+
enableTestMode
202+
exampleTestcaseList
203+
metaData
204+
}
205+
}
206+
"#
207+
.to_string(),
208+
variables: serde_json::to_string(&Variables {
209+
titleSlug: title_slug.to_string(),
210+
})?,
144211
};
145212
let data = client
146213
.post(url)

src/handlers/leetcode/api/submit.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ impl LeetCode<Authorized> {
3434
question_id,
3535
typed_code,
3636
};
37-
let data = client.post(&url).json(&submission).send()?.json::<SubmissionID>().wrap_err("Failed to fetch submission id from LeetCode, Check your submissions manually on leetcode")?;
37+
let data = client.post(&url).json(&submission).send()?.json::<SubmissionID>().wrap_err(
38+
"Failed to fetch submission id from LeetCode, Check your submissions manually on leetcode"
39+
)?;
3840

3941
println!("Evaluating solution...");
4042
let submission_id = data.submission_id;

src/main.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,15 @@ fn main() -> Result<()> {
4444
}
4545
Some(Commands::Question { question_name }) => {
4646
let question_name = if let Some(idx) = question_name.find("leetcode.com/problems/") {
47-
let problem = (&question_name[idx..]).split_whitespace().next().unwrap();
48-
let problem = problem.split('/').skip(2).next().unwrap();
49-
problem
47+
let question_title = question_name[idx..]
48+
.split_whitespace()
49+
.next()
50+
.expect("Should be Some since the find method succeed")
51+
.split('/')
52+
.skip(2)
53+
.next()
54+
.ok_or_else(|| eyre::eyre!("Invalid link, expected question identifier"))?;
55+
question_title
5056
} else {
5157
&question_name
5258
};

0 commit comments

Comments
 (0)