Extract exercise struct to encapsulate path logic

This commit is contained in:
Chris Pearce
2019-04-11 21:41:24 +01:00
parent 04d1d4c00e
commit d01a71f7de
6 changed files with 151 additions and 128 deletions

View File

@@ -1,9 +1,11 @@
use crate::exercise::{Exercise, ExerciseList};
use crate::run::run;
use crate::verify::verify;
use clap::{crate_version, App, Arg, SubCommand};
use notify::DebouncedEvent;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::ffi::OsStr;
use std::fs;
use std::io::BufRead;
use std::path::Path;
use std::sync::mpsc::channel;
@@ -13,8 +15,8 @@ use syntect::highlighting::{Style, ThemeSet};
use syntect::parsing::SyntaxSet;
use syntect::util::as_24_bit_terminal_escaped;
mod exercise;
mod run;
mod util;
mod verify;
fn main() {
@@ -56,16 +58,33 @@ fn main() {
std::process::exit(1);
}
if let Some(matches) = matches.subcommand_matches("run") {
run(matches.clone()).unwrap_or_else(|_| std::process::exit(1));
let toml_str = &fs::read_to_string("info.toml").unwrap();
let exercises = toml::from_str::<ExerciseList>(toml_str).unwrap().exercises;
if let Some(ref matches) = matches.subcommand_matches("run") {
let filename = matches.value_of("file").unwrap_or_else(|| {
println!("Please supply a file name!");
std::process::exit(1);
});
let filepath = Path::new(filename).canonicalize().unwrap();
let exercise = exercises
.iter()
.find(|e| filepath.ends_with(&e.path))
.unwrap_or_else(|| {
println!("No exercise found for your file name!");
std::process::exit(1)
});
run(&exercise).unwrap_or_else(|_| std::process::exit(1));
}
if matches.subcommand_matches("verify").is_some() {
verify(None).unwrap_or_else(|_| std::process::exit(1));
verify(&exercises).unwrap_or_else(|_| std::process::exit(1));
}
if matches.subcommand_matches("watch").is_some() {
watch().unwrap();
watch(&exercises).unwrap();
}
if matches.subcommand_name().is_none() {
@@ -81,13 +100,13 @@ fn main() {
println!("\x1b[0m");
}
fn watch() -> notify::Result<()> {
fn watch(exercises: &[Exercise]) -> notify::Result<()> {
let (tx, rx) = channel();
let mut watcher: RecommendedWatcher = Watcher::new(tx, Duration::from_secs(2))?;
watcher.watch(Path::new("./exercises"), RecursiveMode::Recursive)?;
let _ignored = verify(None);
let _ignored = verify(exercises.iter());
loop {
match rx.recv() {
@@ -95,7 +114,11 @@ fn watch() -> notify::Result<()> {
DebouncedEvent::Create(b) | DebouncedEvent::Chmod(b) | DebouncedEvent::Write(b) => {
if b.extension() == Some(OsStr::new("rs")) {
println!("----------**********----------\n");
let _ignored = verify(Some(b.as_path().to_str().unwrap()));
let filepath = b.as_path().canonicalize().unwrap();
let exercise = exercises
.iter()
.skip_while(|e| !filepath.ends_with(&e.path));
let _ignored = verify(exercise);
}
}
_ => {}