leetcode/src/main.rs

63 lines
1.7 KiB
Rust
Raw Normal View History

2024-10-24 09:08:13 +08:00
use crate::fetch_problem::{Fetcher, ProblemManager};
2023-12-12 18:40:24 +08:00
use std::fs;
2024-01-12 23:07:53 +08:00
use std::io::Write;
2023-12-12 18:40:24 +08:00
use std::path::Path;
2024-01-12 23:07:53 +08:00
mod fetch_problem;
2023-12-12 18:40:24 +08:00
#[tokio::main]
2024-01-12 23:07:53 +08:00
async fn main() {
let manager = ProblemManager::scan().expect("Failed to scan mod file.");
let fetcher = Fetcher::new();
let args: Vec<String> = std::env::args().collect();
2024-01-25 10:36:29 +08:00
let id = args[1].parse::<u32>();
2024-01-12 23:07:53 +08:00
2024-01-25 10:36:29 +08:00
match id {
Ok(id) => {
if manager.problem_list.contains(&id) {
eprintln!("Problem {} exists.", id);
return;
}
2023-12-12 18:40:24 +08:00
2024-01-25 10:36:29 +08:00
println!("Try to get problem {}...", id);
2023-12-12 18:40:24 +08:00
2024-10-24 09:08:13 +08:00
let problem = fetcher
.get_problem(id)
.await
2024-01-25 10:36:29 +08:00
.expect(&*format!("Failed to get problem {}.", id));
2023-12-12 18:40:24 +08:00
2024-01-25 10:36:29 +08:00
let file_name = problem.get_filename();
println!("Get problem: {}.", file_name);
2024-10-24 09:08:13 +08:00
let content = problem
.get_file_content()
.expect("Failed to format file content");
2023-12-12 18:40:24 +08:00
2024-01-25 10:36:29 +08:00
write_file(&file_name, &content).expect("Failed to write problem file.");
}
Err(_) => {
eprintln!("Get operation needs a usize param.")
2024-01-12 23:07:53 +08:00
}
2023-12-12 18:40:24 +08:00
}
}
2024-01-12 23:07:53 +08:00
fn write_file(file_name: &String, file_content: &String) -> std::io::Result<()> {
2023-12-12 18:40:24 +08:00
let file_path = Path::new("./src/problem").join(format!("{}.rs", file_name));
let mut file = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
2024-01-12 23:07:53 +08:00
.open(&file_path)?;
2023-12-12 18:40:24 +08:00
2024-01-12 23:07:53 +08:00
file.write_all(file_content.as_bytes())?;
2023-12-12 18:40:24 +08:00
drop(file);
2024-01-12 23:07:53 +08:00
let mut mod_file = fs::OpenOptions::new()
.write(true)
.append(true)
.open("./src/problem/mod.rs")?;
write!(mod_file, "\nmod {};", file_name)
2024-10-24 09:08:13 +08:00
}