Skip to content

Add snapshot test using insta #2411

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Extract main loop into Gitui::run_main_loop
  • Loading branch information
cruessler committed May 3, 2025
commit e985305108033a5ad433cd98adede558d318b4d6
153 changes: 135 additions & 18 deletions src/gitui.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,59 @@
use std::{cell::RefCell, path::PathBuf};
use std::{cell::RefCell, time::Instant};

use asyncgit::{sync::RepoPath, AsyncGitNotification};
use crossbeam_channel::{unbounded, Receiver};
use anyhow::Result;
use asyncgit::{
sync::{utils::repo_work_dir, RepoPath},
AsyncGitNotification,
};
use crossbeam_channel::{never, tick, unbounded, Receiver};
use scopetime::scope_time;

#[cfg(test)]
use crossterm::event::{KeyCode, KeyModifiers};

use crate::{
app::App, draw, input::Input, keys::KeyConfig, ui::style::Theme,
AsyncAppNotification,
app::{App, QuitState},
draw,
input::{Input, InputEvent, InputState},
keys::KeyConfig,
select_event,
spinner::Spinner,
ui::style::Theme,
watcher::RepoWatcher,
AsyncAppNotification, AsyncNotification, QueueEvent, Updater,
SPINNER_INTERVAL, TICK_INTERVAL,
};

struct Gitui {
pub(crate) struct Gitui {
app: crate::app::App,
_rx_git: Receiver<AsyncGitNotification>,
_rx_app: Receiver<AsyncAppNotification>,
rx_input: Receiver<InputEvent>,
rx_git: Receiver<AsyncGitNotification>,
rx_app: Receiver<AsyncAppNotification>,
rx_ticker: Receiver<Instant>,
rx_watcher: Receiver<()>,
}

impl Gitui {
fn new(path: RepoPath) -> Self {
pub(crate) fn new(
path: RepoPath,
theme: Theme,
key_config: &KeyConfig,
updater: Updater,
) -> Result<Self, anyhow::Error> {
let (tx_git, rx_git) = unbounded();
let (tx_app, rx_app) = unbounded();

let input = Input::new();

let theme = Theme::init(&PathBuf::new());
let key_config = KeyConfig::default();
let (rx_ticker, rx_watcher) = match updater {
Updater::NotifyWatcher => {
let repo_watcher =
RepoWatcher::new(repo_work_dir(&path)?.as_str());

(never(), repo_watcher.receiver())
}
Updater::Ticker => (tick(TICK_INTERVAL), never()),
};

let app = App::new(
RefCell::new(path),
Expand All @@ -35,11 +65,83 @@ impl Gitui {
)
.unwrap();

Self {
Ok(Self {
app,
_rx_git: rx_git,
_rx_app: rx_app,
rx_input: input.receiver(),
rx_git,
rx_app,
rx_ticker,
rx_watcher,
})
}

pub(crate) fn run_main_loop<B: ratatui::backend::Backend>(
&mut self,
terminal: &mut ratatui::Terminal<B>,
) -> Result<QuitState, anyhow::Error> {
let spinner_ticker = tick(SPINNER_INTERVAL);
let mut spinner = Spinner::default();

self.app.update()?;

loop {
let event = select_event(
&self.rx_input,
&self.rx_git,
&self.rx_app,
&self.rx_ticker,
&self.rx_watcher,
&spinner_ticker,
)?;

{
if matches!(event, QueueEvent::SpinnerUpdate) {
spinner.update();
spinner.draw(terminal)?;
continue;
}

scope_time!("loop");

match event {
QueueEvent::InputEvent(ev) => {
if matches!(
ev,
InputEvent::State(InputState::Polling)
) {
//Note: external ed closed, we need to re-hide cursor
terminal.hide_cursor()?;
}
self.app.event(ev)?;
}
QueueEvent::Tick | QueueEvent::Notify => {
self.app.update()?;
}
QueueEvent::AsyncEvent(ev) => {
if !matches!(
ev,
AsyncNotification::Git(
AsyncGitNotification::FinishUnchanged
)
) {
self.app.update_async(ev)?;
}
}
QueueEvent::SpinnerUpdate => unreachable!(),
}

self.draw(terminal);

spinner.set_state(self.app.any_work_pending());
spinner.draw(terminal)?;

if self.app.is_quit() {
break;
}
}
}

Ok(self.app.quit_state())
}

fn draw<B: ratatui::backend::Backend>(
Expand All @@ -49,10 +151,12 @@ impl Gitui {
draw(terminal, &self.app).unwrap();
}

#[cfg(test)]
fn update_async(&mut self, event: crate::AsyncNotification) {
self.app.update_async(event).unwrap();
}

#[cfg(test)]
fn input_event(
&mut self,
code: KeyCode,
Expand All @@ -66,22 +170,26 @@ impl Gitui {
.unwrap();
}

#[cfg(test)]
fn update(&mut self) {
self.app.update().unwrap();
}
}

#[cfg(test)]
mod tests {
use std::{thread::sleep, time::Duration};
use std::{path::PathBuf, thread::sleep, time::Duration};

use asyncgit::{sync::RepoPath, AsyncGitNotification};
use crossterm::event::{KeyCode, KeyModifiers};
use git2_testing::repo_init;
use insta::assert_snapshot;
use ratatui::{backend::TestBackend, Terminal};

use crate::{gitui::Gitui, AsyncNotification};
use crate::{
gitui::Gitui, keys::KeyConfig, ui::style::Theme,
AsyncNotification, Updater,
};

// Macro adapted from: https://insta.rs/docs/cmd/
macro_rules! apply_common_filters {
Expand All @@ -106,11 +214,16 @@ mod tests {
let (temp_dir, _repo) = repo_init();
let path: RepoPath = temp_dir.path().to_str().unwrap().into();

let theme = Theme::init(&PathBuf::new());
let key_config = KeyConfig::default();

let mut gitui =
Gitui::new(path, theme, &key_config, Updater::Ticker)
.unwrap();

let mut terminal =
Terminal::new(TestBackend::new(120, 40)).unwrap();

let mut gitui = Gitui::new(path);

gitui.draw(&mut terminal);

sleep(Duration::from_millis(500));
Expand All @@ -128,6 +241,10 @@ mod tests {
assert_snapshot!("app_loading_finished", terminal.backend());

gitui.input_event(KeyCode::Char('2'), KeyModifiers::empty());
gitui.input_event(
key_config.keys.tab_log.code,
key_config.keys.tab_log.modifiers,
);

sleep(Duration::from_millis(500));

Expand Down
107 changes: 7 additions & 100 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,34 +50,28 @@ mod watcher;
use crate::{app::App, args::process_cmdline};
use anyhow::{anyhow, bail, Result};
use app::QuitState;
use asyncgit::{
sync::{utils::repo_work_dir, RepoPath},
AsyncGitNotification,
};
use asyncgit::{sync::RepoPath, AsyncGitNotification};
use backtrace::Backtrace;
use crossbeam_channel::{never, tick, unbounded, Receiver, Select};
use crossbeam_channel::{Receiver, Select};
use crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen,
LeaveAlternateScreen,
},
ExecutableCommand,
};
use input::{Input, InputEvent, InputState};
use gitui::Gitui;
use input::InputEvent;
use keys::KeyConfig;
use ratatui::backend::CrosstermBackend;
use scopeguard::defer;
use scopetime::scope_time;
use spinner::Spinner;
use std::{
cell::RefCell,
io::{self, Stdout},
panic,
path::Path,
time::{Duration, Instant},
};
use ui::style::Theme;
use watcher::RepoWatcher;

type Terminal = ratatui::Terminal<CrosstermBackend<io::Stdout>>;

Expand Down Expand Up @@ -150,7 +144,6 @@ fn main() -> Result<()> {

let mut repo_path = cliargs.repo_path;
let mut terminal = start_terminal(io::stdout(), &repo_path)?;
let input = Input::new();

let updater = if cliargs.notify_watcher {
Updater::NotifyWatcher
Expand All @@ -164,7 +157,6 @@ fn main() -> Result<()> {
repo_path.clone(),
theme.clone(),
key_config.clone(),
&input,
updater,
&mut terminal,
)?;
Expand All @@ -185,100 +177,15 @@ fn run_app(
repo: RepoPath,
theme: Theme,
key_config: KeyConfig,
input: &Input,
updater: Updater,
terminal: &mut Terminal,
) -> Result<QuitState, anyhow::Error> {
let (tx_git, rx_git) = unbounded();
let (tx_app, rx_app) = unbounded();

let rx_input = input.receiver();

let (rx_ticker, rx_watcher) = match updater {
Updater::NotifyWatcher => {
let repo_watcher =
RepoWatcher::new(repo_work_dir(&repo)?.as_str());

(never(), repo_watcher.receiver())
}
Updater::Ticker => (tick(TICK_INTERVAL), never()),
};

let spinner_ticker = tick(SPINNER_INTERVAL);

let mut app = App::new(
RefCell::new(repo),
tx_git,
tx_app,
input.clone(),
theme,
key_config,
)?;

let mut spinner = Spinner::default();
let mut gitui =
Gitui::new(repo.clone(), theme, &key_config, updater)?;

log::trace!("app start: {} ms", app_start.elapsed().as_millis());

app.update()?;

loop {
let event = select_event(
&rx_input,
&rx_git,
&rx_app,
&rx_ticker,
&rx_watcher,
&spinner_ticker,
)?;

{
if matches!(event, QueueEvent::SpinnerUpdate) {
spinner.update();
spinner.draw(terminal)?;
continue;
}

scope_time!("loop");

match event {
QueueEvent::InputEvent(ev) => {
if matches!(
ev,
InputEvent::State(InputState::Polling)
) {
//Note: external ed closed, we need to re-hide cursor
terminal.hide_cursor()?;
}
app.event(ev)?;
}
QueueEvent::Tick | QueueEvent::Notify => {
app.update()?;
}
QueueEvent::AsyncEvent(ev) => {
if !matches!(
ev,
AsyncNotification::Git(
AsyncGitNotification::FinishUnchanged
)
) {
app.update_async(ev)?;
}
}
QueueEvent::SpinnerUpdate => unreachable!(),
}

draw(terminal, &app)?;

spinner.set_state(app.any_work_pending());
spinner.draw(terminal)?;

if app.is_quit() {
break;
}
}
}

Ok(app.quit_state())
gitui.run_main_loop(terminal)
}

fn setup_terminal() -> Result<()> {
Expand Down
Loading