Skip to content

Commit

Permalink
refactor(tui): extract function execute_command
Browse files Browse the repository at this point in the history
  • Loading branch information
Eliot00 committed Dec 11, 2021
1 parent 812ba91 commit 0a22096
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 7 deletions.
33 changes: 33 additions & 0 deletions quake_tui/src/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::app::{App, MainWidget};

pub fn execute_command(command: &str, app: &mut App) -> Result<(), String> {
match command {
"quit" => app.shutdown(),
"listAll" => app.main_widget = MainWidget::EntryTypes,
_ => return Err(format!("Unknown command: {}", command)),
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::execute_command;
use crate::app::App;

#[test]
fn test_command_quit() {
let mut app = App::new();

assert!(app.running());
execute_command("quit", &mut app).unwrap();
assert!(!app.running());
}

#[test]
fn test_unknown_command() {
let mut app = App::new();

let result = execute_command("nonexistent", &mut app);
assert_eq!(result, Err("Unknown command: nonexistent".to_string()));
}
}
12 changes: 5 additions & 7 deletions quake_tui/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
mod app;
mod command;
mod ui;

use crate::app::{App, MainWidget, Mode};
use crate::app::{App, Mode};
use crate::command::execute_command;
use crossterm::{
event::{self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode},
execute,
Expand Down Expand Up @@ -38,7 +40,7 @@ pub fn tui_main_loop() -> Result<(), Box<dyn Error>> {
Ok(())
}

fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<()> {
fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> Result<(), Box<dyn Error>> {
// TODO: refactor
while app.running() {
terminal.draw(|f| {
Expand All @@ -55,11 +57,7 @@ fn run_app<B: Backend>(terminal: &mut Terminal<B>, mut app: App) -> io::Result<(
Mode::Command => match key.code {
KeyCode::Enter => {
let command: String = app.command.drain(..).collect();
match command.as_str() {
"quit" => app.shutdown(),
"listAll" => app.main_widget = MainWidget::EntryTypes,
_ => {}
}
execute_command(&command, &mut app)?;
app.mode = Mode::Normal;
}
KeyCode::Char(c) => {
Expand Down

0 comments on commit 0a22096

Please sign in to comment.