Skip to content
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

Add snapshot test using insta #2411

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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
45 changes: 45 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -66,6 +66,8 @@ which = "7.0"

[dev-dependencies]
env_logger = "0.11"
git2-testing = { path = "./git2-testing" }
insta = { version = "1.41.0", features = ["filters"] }
pretty_assertions = "1.4"
tempfile = "3"

275 changes: 275 additions & 0 deletions src/gitui.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
use std::{cell::RefCell, time::Instant};

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, 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,
};

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

impl Gitui {
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 (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),
tx_git,
tx_app,
input.clone(),
theme,
key_config.clone(),
)?;

Ok(Self {
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>(
&self,
terminal: &mut ratatui::Terminal<B>,
) -> std::io::Result<()> {
draw(terminal, &self.app)
}

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

#[cfg(test)]
fn input_event(
&mut self,
code: KeyCode,
modifiers: KeyModifiers,
) {
let event = crossterm::event::KeyEvent::new(code, modifiers);
self.app
.event(crate::input::InputEvent::Input(
crossterm::event::Event::Key(event),
))
.unwrap();
}

#[cfg(test)]
fn wait_for_async_git_notification(
&self,
expected: AsyncGitNotification,
) {
loop {
let actual = self
.rx_git
.recv_timeout(std::time::Duration::from_millis(100))
.unwrap();

if actual == expected {
break;
}
}
}

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

#[cfg(test)]
mod tests {
use std::path::PathBuf;

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, keys::KeyConfig, ui::style::Theme,
AsyncNotification, Updater,
};

// Macro adapted from: https://insta.rs/docs/cmd/
macro_rules! apply_common_filters {
{} => {
let mut settings = insta::Settings::clone_current();
// MacOS Temp Folder
settings.add_filter(r" *\[…\]\S+?/T/\S+", "[TEMP_FILE]");
// Linux Temp Folder
settings.add_filter(r" */tmp/\.tmp\S+", "[TEMP_FILE]");
// Windows Temp folder
settings.add_filter(r" *\[…\].*/Local/Temp/\S+", "[TEMP_FILE]");
// Commit ids that follow a vertical bar
settings.add_filter(r"│[a-z0-9]{7} ", "│[AAAAA] ");
let _bound = settings.bind_to_scope();
}
}

#[test]
fn gitui_starts() {
apply_common_filters!();

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, 12)).unwrap();

gitui.draw(&mut terminal).unwrap();

assert_snapshot!("app_loading", terminal.backend());

let event =
AsyncNotification::Git(AsyncGitNotification::Status);
gitui.update_async(event);

gitui.draw(&mut terminal).unwrap();

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,
);

gitui.wait_for_async_git_notification(
AsyncGitNotification::Log,
);

gitui.update();

gitui.draw(&mut terminal).unwrap();

assert_snapshot!(
"app_log_tab_showing_one_commit",
terminal.backend()
);
}
}
120 changes: 13 additions & 107 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -32,6 +32,7 @@ mod bug_report;
mod clipboard;
mod cmdbar;
mod components;
mod gitui;
mod input;
mod keys;
mod notify_mutex;
@@ -49,33 +50,27 @@ mod watcher;
use crate::{app::App, args::process_cmdline};
use 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, process,
time::{Duration, Instant},
};
use ui::style::Theme;
use watcher::RepoWatcher;

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

@@ -144,7 +139,6 @@ fn main() -> Result<()> {

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

let updater = if cliargs.notify_watcher {
Updater::NotifyWatcher
@@ -157,8 +151,7 @@ fn main() -> Result<()> {
app_start,
repo_path.clone(),
theme.clone(),
key_config.clone(),
&input,
&key_config,
updater,
&mut terminal,
)?;
@@ -178,105 +171,15 @@ fn run_app(
app_start: Instant,
repo: RepoPath,
theme: Theme,
key_config: KeyConfig,
input: &Input,
key_config: &KeyConfig,
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 first_update = true;
let mut gitui = Gitui::new(repo, theme, key_config, updater)?;

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

loop {
let event = if first_update {
first_update = false;
QueueEvent::Notify
} else {
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<()> {
@@ -300,7 +203,10 @@ fn shutdown_terminal() {
}
}

fn draw(terminal: &mut Terminal, app: &App) -> io::Result<()> {
fn draw<B: ratatui::backend::Backend>(
terminal: &mut ratatui::Terminal<B>,
app: &App,
) -> io::Result<()> {
if app.requires_redraw() {
terminal.clear()?;
}
17 changes: 17 additions & 0 deletions src/snapshots/gitui__gitui__tests__app_loading.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
source: src/gitui.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Unstaged Changes──────────────────────────────────────────┐┌Diff: ────────────────────────────────────────────────────┐"
"│Loading ... ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────{master}┘│ │"
"┌Staged Changes────────────────────────────────────────────┐│ │"
"│Loading ... ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────────────┘└──────────────────────────────────────────────────────────┘"
" "
17 changes: 17 additions & 0 deletions src/snapshots/gitui__gitui__tests__app_loading_finished.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
source: src/gitui.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Unstaged Changes──────────────────────────────────────────┐┌Diff: ────────────────────────────────────────────────────┐"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────{master}┘│ │"
"┌Staged Changes────────────────────────────────────────────┐│ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────────────┘└──────────────────────────────────────────────────────────┘"
"Branches [b] Push [p] Fetch [⇧F] Pull [f] Undo Commit [⇧U] Submodules [⇧S] Nav [↑↓→←] Diff [→] To stage [w] more [.]"
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
source: src/gitui.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Commit 1/1────────────────────────────────────────────────────────────────────────────────────────────────────────────┐"
"│[AAAAA] <1m ago name initial █"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘"
"Scroll [↑↓] Mark [˽] Details [⏎] Branches [b] Compare [⇧C] Copy Hash [y] Tag [t] Checkout [⇧S] Tags [⇧T] more [.]"
45 changes: 45 additions & 0 deletions src/snapshots/gitui__tests__app_loading.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
source: src/main.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Unstaged Changes──────────────────────────────────────────┐┌Diff: ────────────────────────────────────────────────────┐"
"│Loading ... ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────{master}┘│ │"
"┌Staged Changes────────────────────────────────────────────┐│ │"
"│Loading ... ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────────────┘└──────────────────────────────────────────────────────────┘"
" "
45 changes: 45 additions & 0 deletions src/snapshots/gitui__tests__app_loading_finished.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
source: src/main.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Unstaged Changes──────────────────────────────────────────┐┌Diff: ────────────────────────────────────────────────────┐"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────{master}┘│ │"
"┌Staged Changes────────────────────────────────────────────┐│ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"│ ││ │"
"└──────────────────────────────────────────────────────────┘└──────────────────────────────────────────────────────────┘"
"Branches [b] Push [p] Fetch [⇧F] Pull [f] Undo Commit [⇧U] Submodules [⇧S] Nav [↑↓→←] Diff [→] To stage [w] more [.]"
45 changes: 45 additions & 0 deletions src/snapshots/gitui__tests__app_log_tab_showing_one_commit.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
source: src/main.rs
expression: terminal.backend()
snapshot_kind: text
---
" Status [1] | Log [2] | Files [3] | Stashing [4] | Stashes [5][TEMP_FILE] "
" ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── "
"┌Commit 1/1────────────────────────────────────────────────────────────────────────────────────────────────────────────┐"
"│[AAAAA] <1m ago name initial █"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"│ ║"
"└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘"
"Scroll [↑↓] Mark [˽] Details [⏎] Branches [b] Compare [⇧C] Copy Hash [y] Tag [t] Checkout [⇧S] Tags [⇧T] more [.]"
9 changes: 3 additions & 6 deletions src/spinner.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use ratatui::{backend::Backend, Terminal};
use std::{cell::Cell, char, io};

// static SPINNER_CHARS: &[char] = &['◢', '◣', '◤', '◥'];
@@ -39,9 +36,9 @@ impl Spinner {
}

/// draws or removes spinner char depending on `pending` state
pub fn draw(
pub fn draw<B: ratatui::backend::Backend>(
&self,
terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
terminal: &mut Terminal<B>,
) -> io::Result<()> {
let idx = self.idx;