capy-cli 0.10.0

The command-line interface for the Capy web framework.
Documentation
use crate::dev::{
    buffer::{OutputBuffer, DEFAULT_LIMIT},
    events::{Control, DevEvent, Status},
    supervisor::Definition,
};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};

pub struct Context {
    pub definition: Definition,
    pub output: OutputBuffer,
    pub status: Status,
}
pub struct App {
    pub contexts: Vec<Context>,
    pub selected: usize,
    pub stream: OutputBuffer,
    pub stream_mode: bool,
    pub search_input: Option<String>,
    pub feedback: String,
    pub height: usize,
    pub name: String,
    pub path: String,
}
impl App {
    pub fn new(
        definitions: Vec<Definition>,
        name: String,
        path: String,
        stream_mode: bool,
    ) -> Self {
        Self {
            contexts: definitions
                .into_iter()
                .map(|definition| Context {
                    definition,
                    output: OutputBuffer::new(DEFAULT_LIMIT),
                    status: Status::Starting,
                })
                .collect(),
            selected: 0,
            stream: OutputBuffer::new(DEFAULT_LIMIT),
            stream_mode,
            search_input: None,
            feedback: String::new(),
            height: 1,
            name,
            path,
        }
    }
    pub fn event(&mut self, event: DevEvent) {
        match event {
            DevEvent::Output(line) => {
                if let Some(context) = self
                    .contexts
                    .iter_mut()
                    .find(|c| c.definition.id == line.source)
                {
                    context.output.push(line.clone());
                    self.stream.push(line);
                }
            }
            DevEvent::Status { id, status } => {
                if let Some(context) = self.contexts.iter_mut().find(|c| c.definition.id == id) {
                    context.status = status;
                }
            }
        }
    }
    pub fn output(&self) -> &OutputBuffer {
        if self.stream_mode {
            &self.stream
        } else {
            &self.contexts[self.selected].output
        }
    }
    pub fn output_mut(&mut self) -> &mut OutputBuffer {
        if self.stream_mode {
            &mut self.stream
        } else {
            &mut self.contexts[self.selected].output
        }
    }
    pub fn key(&mut self, key: KeyEvent) -> Option<Control> {
        if key.kind == KeyEventKind::Release {
            return None;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return Some(Control::Shutdown);
        }
        if let Some(input) = &mut self.search_input {
            match key.code {
                KeyCode::Esc => {
                    self.search_input = None;
                    self.feedback.clear();
                }
                KeyCode::Enter => {
                    let query = self.search_input.take().unwrap_or_default();
                    self.output_mut().query = query;
                    let found = self.output_mut().search(true, true);
                    self.feedback = if found {
                        "n next · N previous · / edit search"
                    } else {
                        "No matches · / edit search"
                    }
                    .into();
                }
                KeyCode::Backspace => {
                    input.pop();
                }
                KeyCode::Char(c)
                    if !key
                        .modifiers
                        .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
                        && input.len() < 1024 =>
                {
                    input.push(c)
                }
                _ => {}
            }
            return None;
        }
        self.feedback.clear();
        let height = self.height;
        match key.code {
            KeyCode::Char('q') => return Some(Control::Shutdown),
            KeyCode::Char(c @ '1'..='9') => {
                let index = (c as u8 - b'1') as usize;
                if index < self.contexts.len() {
                    self.selected = index;
                    self.stream_mode = false;
                }
            }
            KeyCode::Up | KeyCode::Char('k') => self.output_mut().scroll(-1, height),
            KeyCode::Down | KeyCode::Char('j') => self.output_mut().scroll(1, height),
            KeyCode::Left => {
                self.output_mut().horizontal = self.output().horizontal.saturating_sub(4);
            }
            KeyCode::Right => {
                self.output_mut().horizontal = self.output().horizontal.saturating_add(4);
            }
            KeyCode::PageUp => self.output_mut().scroll(-(height as isize), height),
            KeyCode::PageDown => self.output_mut().scroll(height as isize, height),
            KeyCode::Char('g') | KeyCode::Home => self.output_mut().top(),
            KeyCode::Char('G') | KeyCode::End => self.output_mut().follow(),
            KeyCode::Char('c') => self.output_mut().clear(),
            KeyCode::Char('/') => self.search_input = Some(self.output().query.clone()),
            KeyCode::Char(c @ ('n' | 'N')) => {
                if !self.output_mut().search(c == 'n', false) {
                    self.feedback = "No matches · / search".into();
                }
            }
            KeyCode::Char('s') => self.stream_mode = true,
            KeyCode::Char('t') => self.stream_mode = false,
            KeyCode::Char('r') => {
                let context = &self.contexts[self.selected];
                if self.stream_mode {
                    self.feedback = "Select a context with 1–9 or t to restart".into();
                } else if context.definition.restartable {
                    return Some(Control::Restart(context.definition.id));
                } else {
                    self.feedback = format!(
                        "{} is a source and cannot be restarted",
                        context.definition.name
                    );
                }
            }
            _ => {}
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dev::{events::OutputStream, output::Decoder};
    use std::sync::Arc;
    fn app() -> App {
        App::new(
            (0..4)
                .map(|id| Definition {
                    id,
                    name: format!("source{id}"),
                    command: "test".into(),
                    url: None,
                    restartable: id != 1,
                })
                .collect(),
            "test".into(),
            "/test".into(),
            false,
        )
    }
    fn key(app: &mut App, code: KeyCode) -> Option<Control> {
        app.key(KeyEvent::new(code, KeyModifiers::NONE))
    }
    #[test]
    fn contexts_are_dynamic_independent_and_aggregate_in_event_order() {
        let mut app = app();
        for (id, text) in [(0, "server"), (2, "frontend"), (1, "log")] {
            app.event(DevEvent::Output(Arc::new(Decoder::default().line(
                id,
                OutputStream::Stdout,
                text,
            ))));
        }
        assert_eq!(
            app.stream
                .lines
                .iter()
                .map(|l| l.text.as_str())
                .collect::<Vec<_>>(),
            ["server", "frontend", "log"]
        );
        assert_eq!(app.contexts[0].output.lines.len(), 1);
        key(&mut app, KeyCode::Char('2'));
        assert_eq!(app.selected, 1);
        key(&mut app, KeyCode::Char('c'));
        assert!(app.output().lines.is_empty());
        assert_eq!(app.contexts[0].output.lines.len(), 1);
        assert_eq!(app.stream.lines.len(), 3);
        key(&mut app, KeyCode::Char('4'));
        assert_eq!(app.selected, 3);
        key(&mut app, KeyCode::Char('9'));
        assert_eq!(app.selected, 3);
        key(&mut app, KeyCode::Char('s'));
        assert!(app.stream_mode);
        key(&mut app, KeyCode::Char('t'));
        assert!(!app.stream_mode);
    }
    #[test]
    fn stream_and_contexts_remain_bounded_independently() {
        let mut app = app();
        for i in 0..DEFAULT_LIMIT + 2 {
            app.event(DevEvent::Output(Arc::new(Decoder::default().line(
                i % 2,
                OutputStream::Stdout,
                &i.to_string(),
            ))));
        }
        assert_eq!(app.stream.lines.len(), DEFAULT_LIMIT);
        assert_eq!(app.stream.lines.front().unwrap().text, "2");
        assert_eq!(app.contexts[0].output.lines.len(), 2501);
        assert_eq!(app.contexts[1].output.lines.len(), 2501);
        app.height = 10;
        key(&mut app, KeyCode::PageUp);
        let position = app.output().start(10);
        key(&mut app, KeyCode::Char('2'));
        assert!(app.output().anchor.is_none());
        key(&mut app, KeyCode::Char('1'));
        assert_eq!(app.output().start(10), position);
    }

    #[test]
    fn search_typing_never_dispatches_shortcuts() {
        let mut app = app();
        key(&mut app, KeyCode::Char('/'));
        for c in "qrs123".chars() {
            assert!(key(&mut app, KeyCode::Char(c)).is_none());
        }
        assert_eq!(app.search_input.as_deref(), Some("qrs123"));
        assert_eq!(app.selected, 0);
        key(&mut app, KeyCode::Enter);
        assert_eq!(app.output().query, "qrs123");
        key(&mut app, KeyCode::Char('2'));
        assert!(app.output().query.is_empty());
        assert!(key(&mut app, KeyCode::Char('r')).is_none());
        assert!(app.feedback.contains("cannot be restarted"));
        key(&mut app, KeyCode::Char('1'));
        assert_eq!(key(&mut app, KeyCode::Char('r')), Some(Control::Restart(0)));
    }
    #[test]
    fn state_transitions_and_ctrl_c_during_search() {
        let mut app = app();
        for status in [
            Status::Running { pid: Some(123) },
            Status::Restarting,
            Status::Failed { code: Some(42) },
            Status::Stopped,
        ] {
            app.event(DevEvent::Status {
                id: 0,
                status: status.clone(),
            });
            assert_eq!(app.contexts[0].status, status);
        }
        key(&mut app, KeyCode::Char('/'));
        assert_eq!(
            app.key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)),
            Some(Control::Shutdown)
        );
    }
}