summaryrefslogtreecommitdiff
path: root/src/exercise.rs
blob: e85efe4cdd5a8d6c51cc5ed07758efc683f54ae9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use anyhow::{Context, Result};
use crossterm::style::{style, StyledContent, Stylize};
use std::{
    fmt::{self, Display, Formatter},
    fs,
    path::Path,
    process::{Command, Output},
};

use crate::{info_file::Mode, DEBUG_PROFILE};

pub struct TerminalFileLink<'a> {
    path: &'a str,
}

impl<'a> Display for TerminalFileLink<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Ok(Some(canonical_path)) = fs::canonicalize(self.path)
            .as_deref()
            .map(|path| path.to_str())
        {
            write!(
                f,
                "\x1b]8;;file://{}\x1b\\{}\x1b]8;;\x1b\\",
                canonical_path, self.path,
            )
        } else {
            write!(f, "{}", self.path,)
        }
    }
}

pub struct Exercise {
    // Exercise's unique name
    pub name: &'static str,
    // Exercise's path
    pub path: &'static str,
    // The mode of the exercise
    pub mode: Mode,
    // The hint text associated with the exercise
    pub hint: String,
    pub done: bool,
}

impl Exercise {
    fn cargo_cmd(&self, command: &str, args: &[&str]) -> Result<Output> {
        let mut cmd = Command::new("cargo");
        cmd.arg(command);

        // A hack to make `cargo run` work when developing Rustlings.
        if DEBUG_PROFILE && Path::new("tests").exists() {
            cmd.arg("--manifest-path").arg("dev/Cargo.toml");
        }

        cmd.arg("--color")
            .arg("always")
            .arg("-q")
            .arg("--bin")
            .arg(self.name)
            .args(args)
            .output()
            .context("Failed to run Cargo")
    }

    pub fn run(&self) -> Result<Output> {
        match self.mode {
            Mode::Run => self.cargo_cmd("run", &[]),
            Mode::Test => self.cargo_cmd(
                "test",
                &[
                    "--",
                    "--color",
                    "always",
                    "--nocapture",
                    "--format",
                    "pretty",
                ],
            ),
            Mode::Clippy => self.cargo_cmd(
                "clippy",
                &["--", "-D", "warnings", "-D", "clippy::float_cmp"],
            ),
        }
    }

    pub fn terminal_link(&self) -> StyledContent<TerminalFileLink<'_>> {
        style(TerminalFileLink { path: self.path })
            .underlined()
            .blue()
    }
}

impl Display for Exercise {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.path.fmt(f)
    }
}