runandlog 0.3.1

CLI / TUI that runs the shell commands in a Markdown file and writes the results back
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Terminal UI. Pick a cell, run it, and read the result in place.

use std::io;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

use ratatui::DefaultTerminal;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block, Borders, Paragraph};
use runandlog_core::{Canceller, ExecOutcome};

use crate::session::Session;

// The run/draw loop needs a terminal and cannot be covered by automated tests, so
// the tests live in runandlog-core (parse, exec, render) and in session (write-back).

/// Interval between input polls and redraws.
const TICK: Duration = Duration::from_millis(100);
const SPINNER: [char; 4] = ['|', '/', '-', '\\'];
const PAGE_LINES: usize = 10;

/// Opens the TUI.
pub fn run(session: Session) -> io::Result<()> {
    let terminal = ratatui::init();
    let result = App::new(session).run(terminal);
    ratatui::restore();
    result
}

/// Whether a "run all" batch may go on to the next cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Batch {
    Continue,
    Stop,
}

/// Whether a key press means "quit".
fn is_quit_key(key: KeyEvent) -> bool {
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => true,
        KeyCode::Char('c') => key.modifiers.contains(KeyModifiers::CONTROL),
        _ => false,
    }
}

/// Whether a key press means "stop the running command".
///
/// Only Ctrl-C. `q` and `Esc` keep their documented meaning of quitting once the
/// command has finished, which is what you want for a command that is merely slow;
/// Ctrl-C is the way out of one that will never finish.
fn is_cancel_key(key: KeyEvent) -> bool {
    key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL)
}

/// What the marker of a cell says, telling apart a first run from a repeat.
///
/// Both are the same width so that the highlighted markers line up down the
/// column, whichever cells happen to carry a result.
fn run_label(has_result: bool) -> &'static str {
    if has_result { "Re-run" } else { "Run   " }
}

/// The lines to draw, plus the line range occupied by each cell.
struct Rendered {
    lines: Vec<Line<'static>>,
    /// (first line, one past the last line) for each cell.
    spans: Vec<(usize, usize)>,
}

struct App {
    session: Session,
    selected: usize,
    scroll: usize,
    /// Height of the body area. Used to adjust the scroll position.
    viewport: usize,
    status: String,
    /// The cell being run (0-based) and the spinner phase.
    running: Option<(usize, usize)>,
    quit: bool,
}

impl App {
    fn new(session: Session) -> App {
        let status = if session.is_empty() {
            "No runnable cells. Press q to quit.".to_string()
        } else {
            "Enter/r: run  a: run all  j/k: move  R: reload  q: quit".to_string()
        };
        App {
            session,
            selected: 0,
            scroll: 0,
            viewport: 1,
            status,
            running: None,
            quit: false,
        }
    }

    fn run(mut self, mut terminal: DefaultTerminal) -> io::Result<()> {
        while !self.quit {
            self.redraw(&mut terminal)?;
            self.handle_events(&mut terminal)?;
        }
        Ok(())
    }

    fn redraw(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        let rendered = self.render_lines();
        terminal.draw(|frame| {
            let areas = Layout::vertical([
                Constraint::Length(1),
                Constraint::Min(1),
                Constraint::Length(1),
            ])
            .split(frame.area());

            let header = Line::from(vec![
                Span::styled("File: ", Style::default().fg(Color::DarkGray)),
                Span::styled(
                    self.session.path().display().to_string(),
                    Style::default().add_modifier(Modifier::BOLD),
                ),
            ]);
            frame.render_widget(Paragraph::new(header), areas[0]);

            // The body height is what is left after the top and bottom borders.
            self.viewport = (areas[1].height.saturating_sub(2) as usize).max(1);
            self.adjust_scroll(&rendered);

            let body = Paragraph::new(Text::from(rendered.lines.clone()))
                .block(Block::default().borders(Borders::TOP | Borders::BOTTOM))
                .scroll((self.scroll as u16, 0));
            frame.render_widget(body, areas[1]);

            let status = match self.running {
                Some((index, phase)) => format!(
                    "{} running cell {}",
                    SPINNER[phase % SPINNER.len()],
                    index + 1
                ),
                None => self.status.clone(),
            };
            frame.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    status,
                    Style::default().fg(Color::DarkGray),
                ))),
                areas[2],
            );
        })?;
        Ok(())
    }

    /// Builds the lines to display.
    fn render_lines(&self) -> Rendered {
        let mut lines = Vec::new();
        let mut spans = Vec::new();
        let doc = self.session.doc();

        for cell in &doc.cells {
            let start = lines.len();
            let selected = cell.index == self.selected;
            let marker_style = if selected {
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::Green)
            };
            lines.push(Line::from(vec![
                Span::styled(
                    format!(
                        " [{}] > {} ",
                        cell.display_number(),
                        run_label(doc.result_text(cell).is_some())
                    ),
                    marker_style,
                ),
                Span::styled(
                    match &cell.out_file {
                        Some(path) => format!("  -> {path}"),
                        None => String::new(),
                    },
                    Style::default().fg(Color::DarkGray),
                ),
            ]));
            for command in cell.command.lines() {
                lines.push(Line::from(vec![
                    Span::styled("   > ", Style::default().fg(Color::DarkGray)),
                    Span::raw(command.to_string()),
                ]));
            }
            if let Some(result) = doc.result_text(cell) {
                lines.push(Line::from(""));
                for line in result.lines() {
                    lines.push(Line::from(Span::styled(
                        format!("   {line}"),
                        Style::default().fg(Color::Gray),
                    )));
                }
            }
            lines.push(Line::from(""));
            spans.push((start, lines.len()));
        }

        if lines.is_empty() {
            lines.push(Line::from(Span::styled(
                "  No shell / sh / bash / zsh code block found.",
                Style::default().fg(Color::DarkGray),
            )));
        }
        Rendered { lines, spans }
    }

    /// Nudges the scroll position so the selected cell stays on screen.
    fn adjust_scroll(&mut self, rendered: &Rendered) {
        if let Some(&(start, end)) = rendered.spans.get(self.selected) {
            if start < self.scroll {
                self.scroll = start;
            } else if end > self.scroll + self.viewport {
                // For a cell taller than the viewport, prefer its top over its bottom.
                self.scroll = end.saturating_sub(self.viewport).min(start);
            }
        }
        self.scroll = self.scroll.min(rendered.lines.len().saturating_sub(1));
    }

    fn handle_events(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        if !event::poll(TICK)? {
            return Ok(());
        }
        if let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            self.handle_key(key, terminal)?;
        }
        Ok(())
    }

    fn handle_key(&mut self, key: KeyEvent, terminal: &mut DefaultTerminal) -> io::Result<()> {
        if is_quit_key(key) {
            self.quit = true;
            return Ok(());
        }
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => self.select(1),
            KeyCode::Char('k') | KeyCode::Up => self.select(-1),
            KeyCode::Char('g') | KeyCode::Home => {
                self.selected = 0;
                self.scroll = 0;
            }
            KeyCode::Char('G') | KeyCode::End => {
                self.selected = self.session.len().saturating_sub(1);
            }
            KeyCode::PageDown => self.scroll = self.scroll.saturating_add(PAGE_LINES),
            KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(PAGE_LINES),
            KeyCode::Char('R') => self.reload(),
            KeyCode::Enter | KeyCode::Char('r') => {
                if !self.session.is_empty() {
                    self.execute(self.selected, terminal)?;
                }
            }
            KeyCode::Char('a') => {
                for index in 0..self.session.len() {
                    if self.quit {
                        break;
                    }
                    self.selected = index;
                    if self.execute(index, terminal)? == Batch::Stop {
                        break;
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    fn select(&mut self, delta: isize) {
        if self.session.is_empty() {
            return;
        }
        let last = self.session.len() - 1;
        self.selected = self.selected.saturating_add_signed(delta).min(last);
    }

    fn reload(&mut self) {
        match self.session.reload() {
            Ok(()) => {
                self.selected = self.selected.min(self.session.len().saturating_sub(1));
                self.status = "Reloaded.".to_string();
            }
            Err(error) => self.status = format!("Reload failed: {error}"),
        }
    }

    /// Runs one cell. The run goes to a worker thread so the screen keeps
    /// updating while it is in flight.
    ///
    /// The return value tells a "run all" batch whether it may continue.
    fn execute(&mut self, index: usize, terminal: &mut DefaultTerminal) -> io::Result<Batch> {
        let command = self.session.command_of(index);
        let options = self.session.exec_options();
        // One per run: a cancelled cell must not leave the next one unable to start.
        let canceller = Canceller::new();
        let worker_canceller = canceller.clone();
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            let _ = tx.send(runandlog_core::run_cancellable(
                &command,
                &options,
                &worker_canceller,
            ));
        });

        let outcome = self.wait_for(index, rx, terminal, &canceller);
        self.running = None;
        match outcome {
            Ok(Ok(outcome)) => match self.session.apply_outcome(index, &outcome) {
                Ok(()) => {
                    self.status = format!("Cell {} done ({})", index + 1, outcome.status_text());
                }
                Err(error) => {
                    // The write was refused, which usually means the file changed
                    // underneath us. Carrying on would run the *old* commands held in
                    // memory -- including ones the file no longer contains -- so stop
                    // the batch and pick the file back up from disk.
                    self.status = format!("Writing the result failed: {error}");
                    self.reload_after_conflict();
                    return Ok(Batch::Stop);
                }
            },
            Ok(Err(error)) => self.status = format!("The run failed: {error}"),
            Err(error) => return Err(error),
        }
        Ok(Batch::Continue)
    }

    /// Re-reads the file after a refused write, keeping the status text that
    /// explains why the write was refused.
    fn reload_after_conflict(&mut self) {
        if self.session.reload().is_ok() {
            self.selected = self.selected.min(self.session.len().saturating_sub(1));
        }
    }

    /// Handles keys pressed while a command is running.
    ///
    /// Only quitting and cancelling are honoured here; everything else is
    /// discarded, since keys pressed during the run would otherwise all fire at
    /// once when it finishes.
    ///
    /// The quit keys are the same ones the normal event loop takes, so that the
    /// documented "q quits after the command finishes" holds while one is running.
    /// Ctrl-C does not wait: raw mode means the terminal never turns it into a
    /// signal, and the command sits in a process group of its own anyway, so this
    /// is the only thing that can reach a command that hangs.
    fn drain_events_while_running(&mut self, canceller: &Canceller) -> io::Result<()> {
        while event::poll(Duration::ZERO)? {
            if let Event::Key(key) = event::read()?
                && key.kind == KeyEventKind::Press
            {
                if is_cancel_key(key) {
                    canceller.cancel();
                    self.quit = true;
                } else if is_quit_key(key) {
                    // Quit after the command finishes; its result still gets written back.
                    self.quit = true;
                }
            }
        }
        Ok(())
    }

    /// Waits for the run to finish, spinning the spinner and redrawing meanwhile.
    fn wait_for(
        &mut self,
        index: usize,
        rx: mpsc::Receiver<io::Result<ExecOutcome>>,
        terminal: &mut DefaultTerminal,
        canceller: &Canceller,
    ) -> io::Result<io::Result<ExecOutcome>> {
        let mut phase = 0;
        loop {
            match rx.recv_timeout(TICK) {
                Ok(result) => {
                    // Drain here too. A cell that finishes inside one TICK would
                    // otherwise return without ever looking at the terminal, so during
                    // "run all" over fast cells a queued q / Esc / Ctrl-C would not be
                    // seen until the whole batch had run.
                    self.drain_events_while_running(canceller)?;
                    return Ok(result);
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    phase += 1;
                    self.running = Some((index, phase));
                    self.redraw(terminal)?;
                    self.drain_events_while_running(canceller)?;
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    return Ok(Err(io::Error::other("the worker thread died unexpectedly")));
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
        KeyEvent::new(code, modifiers)
    }

    #[test]
    fn recognises_the_documented_quit_keys() {
        assert!(is_quit_key(key(KeyCode::Char('q'), KeyModifiers::NONE)));
        assert!(is_quit_key(key(KeyCode::Esc, KeyModifiers::NONE)));
        assert!(is_quit_key(key(KeyCode::Char('c'), KeyModifiers::CONTROL)));
    }

    #[test]
    fn a_cell_that_already_ran_says_so() {
        assert_eq!(run_label(true).trim(), "Re-run");
        assert_eq!(run_label(false).trim(), "Run");
        // Equal widths keep the markers aligned down the column.
        assert_eq!(run_label(true).len(), run_label(false).len());
    }

    #[test]
    fn a_plain_c_is_not_a_quit_key() {
        assert!(!is_quit_key(key(KeyCode::Char('c'), KeyModifiers::NONE)));
        assert!(!is_quit_key(key(KeyCode::Char('r'), KeyModifiers::NONE)));
        assert!(!is_quit_key(key(KeyCode::Char('a'), KeyModifiers::NONE)));
    }
}