summaryrefslogtreecommitdiff
path: root/src/exercise.rs
diff options
context:
space:
mode:
authorChris Pearce <christopher.james.pearce@gmail.com>2019-04-11 21:41:24 +0100
committerChris Pearce <christopher.james.pearce@gmail.com>2019-04-12 08:58:25 +0100
commitd01a71f7de15f34922dc2a14a00436f466b84e87 (patch)
treef36483bfca95c7355bf46321a05050c8e7fdb988 /src/exercise.rs
parent04d1d4c00ee9c74d64734ef9880607599830286d (diff)
Extract exercise struct to encapsulate path logic
Diffstat (limited to 'src/exercise.rs')
-rw-r--r--src/exercise.rs72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/exercise.rs b/src/exercise.rs
new file mode 100644
index 0000000..577d428
--- /dev/null
+++ b/src/exercise.rs
@@ -0,0 +1,72 @@
+use std::fmt::{self, Display, Formatter};
+use std::fs::{remove_file};
+use std::path::{PathBuf};
+use std::process::{self, Command, Output};
+use serde::Deserialize;
+
+const RUSTC_COLOR_ARGS: &[&str] = &["--color", "always"];
+
+fn temp_file() -> String {
+ format!("./temp_{}", process::id())
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Mode {
+ Compile,
+ Test,
+}
+
+#[derive(Deserialize)]
+pub struct ExerciseList {
+ pub exercises: Vec<Exercise>,
+}
+
+#[derive(Deserialize)]
+pub struct Exercise {
+ pub path: PathBuf,
+ pub mode: Mode,
+}
+
+impl Exercise {
+ pub fn compile(&self) -> Output {
+ match self.mode {
+ Mode::Compile => Command::new("rustc")
+ .args(&[self.path.to_str().unwrap(), "-o", &temp_file()])
+ .args(RUSTC_COLOR_ARGS)
+ .output(),
+ Mode::Test => Command::new("rustc")
+ .args(&["--test", self.path.to_str().unwrap(), "-o", &temp_file()])
+ .args(RUSTC_COLOR_ARGS)
+ .output(),
+ }
+ .expect("Failed to run 'compile' command.")
+ }
+
+ pub fn run(&self) -> Output {
+ Command::new(&temp_file())
+ .output()
+ .expect("Failed to run 'run' command")
+ }
+
+ pub fn clean(&self) {
+ let _ignored = remove_file(&temp_file());
+ }
+}
+
+impl Display for Exercise {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ write!(f, "{}", self.path.to_str().unwrap())
+ }
+}
+
+#[test]
+fn test_clean() {
+ std::fs::File::create(&temp_file()).unwrap();
+ let exercise = Exercise {
+ path: PathBuf::from("example.rs"),
+ mode: Mode::Test,
+ };
+ exercise.clean();
+ assert!(!std::path::Path::new(&temp_file()).exists());
+}