summaryrefslogtreecommitdiff
path: root/src/watch/state.rs
blob: 40f48effea874cb4e46417e5553d0d89814583c0 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use anyhow::Result;
use crossterm::{
    style::{Attribute, ContentStyle, Stylize},
    terminal::{Clear, ClearType},
    ExecutableCommand,
};
use notify_debouncer_mini::{DebounceEventResult, DebouncedEventKind};
use std::{
    fmt::Write as _,
    io::{self, StdoutLock, Write as _},
    sync::mpsc::Receiver,
    time::Duration,
};

use crate::{
    exercise::{Exercise, State},
    state_file::StateFile,
};

pub struct WatchState<'a> {
    writer: StdoutLock<'a>,
    rx: Receiver<DebounceEventResult>,
    exercises: &'a [Exercise],
    exercise: &'a Exercise,
    current_exercise_ind: usize,
    stdout: Option<Vec<u8>>,
    stderr: Option<Vec<u8>>,
    message: Option<String>,
    prompt: Vec<u8>,
}

impl<'a> WatchState<'a> {
    pub fn new(
        state_file: &StateFile,
        exercises: &'a [Exercise],
        rx: Receiver<DebounceEventResult>,
    ) -> Self {
        let current_exercise_ind = state_file.next_exercise_ind();
        let exercise = &exercises[current_exercise_ind];

        let writer = io::stdout().lock();

        let prompt = format!(
            "\n\n{}int/{}lear/{}uit? ",
            "h".bold(),
            "c".bold(),
            "q".bold()
        )
        .into_bytes();

        Self {
            writer,
            rx,
            exercises,
            exercise,
            current_exercise_ind,
            stdout: None,
            stderr: None,
            message: None,
            prompt,
        }
    }

    #[inline]
    pub fn into_writer(self) -> StdoutLock<'a> {
        self.writer
    }

    pub fn run_exercise(&mut self) -> Result<bool> {
        let output = self.exercise.run()?;

        if !output.status.success() {
            self.stdout = Some(output.stdout);
            self.stderr = Some(output.stderr);
            return Ok(false);
        }

        if let State::Pending(context) = self.exercise.state()? {
            let mut message = format!(
                "
You can keep working on this exercise or jump into the next one by removing the {} comment:

",
                "`I AM NOT DONE`".bold(),
            );

            for context_line in context {
                let formatted_line = if context_line.important {
                    context_line.line.bold()
                } else {
                    context_line.line.stylize()
                };

                writeln!(
                    message,
                    "{:>2} {}  {}",
                    ContentStyle {
                        foreground_color: Some(crossterm::style::Color::Blue),
                        background_color: None,
                        underline_color: None,
                        attributes: Attribute::Bold.into()
                    }
                    .apply(context_line.number),
                    "|".blue(),
                    formatted_line,
                )?;
            }

            self.stdout = Some(output.stdout);
            self.message = Some(message);
            return Ok(false);
        }

        Ok(true)
    }

    pub fn try_recv_event(&mut self) -> Result<()> {
        let Ok(events) = self.rx.recv_timeout(Duration::from_millis(100)) else {
            return Ok(());
        };

        if let Some(current_exercise_ind) = events?
            .iter()
            .filter_map(|event| {
                if event.kind != DebouncedEventKind::Any
                    || !event.path.extension().is_some_and(|ext| ext == "rs")
                {
                    return None;
                }

                self.exercises
                    .iter()
                    .position(|exercise| event.path.ends_with(&exercise.path))
            })
            .min()
        {
            self.current_exercise_ind = current_exercise_ind;
        } else {
            return Ok(());
        };

        while self.current_exercise_ind < self.exercises.len() {
            self.exercise = &self.exercises[self.current_exercise_ind];
            if !self.run_exercise()? {
                break;
            }

            self.current_exercise_ind += 1;
        }

        Ok(())
    }

    pub fn show_prompt(&mut self) -> io::Result<()> {
        self.writer.write_all(&self.prompt)?;
        self.writer.flush()
    }

    pub fn render(&mut self) -> io::Result<()> {
        self.writer.execute(Clear(ClearType::All))?;

        if let Some(stdout) = &self.stdout {
            self.writer.write_all(stdout)?;
        }

        if let Some(stderr) = &self.stderr {
            self.writer.write_all(stderr)?;
        }

        if let Some(message) = &self.message {
            self.writer.write_all(message.as_bytes())?;
        }

        self.show_prompt()
    }

    pub fn show_hint(&mut self) -> io::Result<()> {
        self.writer.write_all(self.exercise.hint.as_bytes())?;
        self.show_prompt()
    }

    pub fn handle_invalid_cmd(&mut self) -> io::Result<()> {
        self.writer.write_all(b"Invalid command")?;
        self.show_prompt()
    }
}