Skip to content
Closed
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ repository = "https://github.com/altsem/gitu"
name = "show"
harness = false

[[bench]]
name = "ui"
harness = false

[dev-dependencies]
pretty_assertions = "1.4.1"
temp-dir = "0.1.16"
Expand Down
45 changes: 45 additions & 0 deletions benches/ui.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::rc::Rc;
use std::sync::Arc;

use criterion::{Criterion, criterion_group, criterion_main};
use git2::Repository;
use gitu::app::App;
use gitu::cli::{Args, Commands};
use gitu::config;
use gitu::term::TermBackend;
use ratatui::{Terminal, backend::TestBackend, layout::Size};

const REFERENCE: &str = "f4de01c0a12794d7b42a77b2138aa64119b90ea5";

/// Times a redraw of an already-built screen, leaving repo access, diff
/// parsing and item creation out of the measurement.
fn bench_redraw(c: &mut Criterion, name: &str, size: Size) {
c.bench_function(name, |b| {
let mut term = Terminal::new(TermBackend::Test {
backend: TestBackend::new(size.width, size.height),
events: vec![],
})
.unwrap();

let args = Args {
command: Some(Commands::Show {
reference: REFERENCE.into(),
}),
..Default::default()
};

let config = Arc::new(config::init_config(args.config.clone()).unwrap());
let repo = Rc::new(Repository::open_from_env().unwrap());
let mut app = App::create(repo, size, &args, config, false).unwrap();

b.iter(|| app.redraw_now(&mut term).unwrap());
});
}

fn ui(c: &mut Criterion) {
// The whole diff at once, so that per-row costs dominate.
bench_redraw(c, "ui/40x1000", Size::new(40, 1000));
}

criterion_group!(benches, ui);
criterion_main!(benches);
19 changes: 8 additions & 11 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ pub(crate) struct State {
inhibit_close_menu: bool,
}

pub(crate) struct App {
pub state: State,
pub struct App {
pub(crate) state: State,
}

impl App {
Expand Down Expand Up @@ -250,9 +250,7 @@ impl App {

pub fn redraw_now(&mut self, term: &mut Term) -> Res<()> {
if self.state.screens.last_mut().is_some() {
term.draw(|frame| ui::ui(frame, &mut self.state))
.map_err(Error::Term)?;

ui::ui(term.backend_mut(), &mut self.state)?;
self.state.needs_redraw = false;
};

Expand Down Expand Up @@ -383,11 +381,11 @@ impl App {
self.state.inhibit_close_menu = true;
}

pub fn screen_mut(&mut self) -> &mut Screen {
pub(crate) fn screen_mut(&mut self) -> &mut Screen {
self.state.screens.last_mut().expect("No screen")
}

pub fn screen(&self) -> &Screen {
pub(crate) fn screen(&self) -> &Screen {
self.state.screens.last().expect("No screen")
}

Expand Down Expand Up @@ -431,8 +429,7 @@ impl App {

let log_entry = self.state.current_cmd_log.push_cmd(&cmd);

term.draw(|frame| ui::ui(frame, &mut self.state))
.map_err(Error::Term)?;
ui::ui(term.backend_mut(), &mut self.state)?;

let mut child = cmd.spawn().map_err(Error::SpawnCmd)?;

Expand Down Expand Up @@ -562,11 +559,11 @@ impl App {
}
}

pub fn selected_rev(&self) -> Option<Rev> {
pub(crate) fn selected_rev(&self) -> Option<Rev> {
self.screen().get_selected_item().data.rev()
}

pub fn prompt(&mut self, term: &mut Term, params: &PromptParams) -> Res<String> {
pub(crate) fn prompt(&mut self, term: &mut Term, params: &PromptParams) -> Res<String> {
let prompt_text = if let Some(default) = (params.create_default_value)(self) {
format!("{} (default {}):", params.prompt, default).into()
} else {
Expand Down
42 changes: 0 additions & 42 deletions src/cmd_log.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::config::Config;
use itertools::Itertools;
use ratatui::text::Text;
use ratatui::text::{Line, Span};
use std::borrow::Cow;
use std::iter;
use std::process::Command;
Expand Down Expand Up @@ -52,15 +49,6 @@ impl CmdLog {
pub(crate) fn is_empty(&self) -> bool {
self.entries.is_empty()
}

pub(crate) fn format_log(&self, config: &Config) -> Text<'static> {
Text::from(
self.entries
.iter()
.flat_map(|cmd| format_log_entry(config, cmd))
.collect::<Vec<_>>(),
)
}
}

pub(crate) fn command_args(cmd: &Command) -> Cow<'static, str> {
Expand All @@ -70,36 +58,6 @@ pub(crate) fn command_args(cmd: &Command) -> Cow<'static, str> {
.into()
}

pub(crate) fn format_log_entry<'a>(
config: &Config,
log: &Arc<RwLock<CmdLogEntry>>,
) -> Vec<Line<'a>> {
match &*log.read().unwrap() {
CmdLogEntry::Cmd { args, out } => [Line::from(vec![
Span::styled(
if out.is_some() { "$ " } else { "Running: " },
&config.style.info_msg,
),
Span::styled(args.to_string(), &config.style.command),
])]
.into_iter()
.chain(out.iter().flat_map(|out| {
if out.is_empty() {
vec![]
} else {
Text::raw(out.to_string()).lines
}
}))
.collect::<Vec<_>>(),
CmdLogEntry::Error(err) => {
vec![Line::styled(format!("! {err}"), &config.style.error_msg)]
}
CmdLogEntry::Info(msg) => {
vec![Line::styled(format!("> {msg}"), &config.style.info_msg)]
}
}
}

pub(crate) enum CmdLogEntry {
Cmd {
args: Cow<'static, str>,
Expand Down
188 changes: 0 additions & 188 deletions src/items.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
use crate::Res;
use crate::config::Config;
use crate::error::Error;
use crate::git::diff::Diff;
use crate::gitu_diff::Status;
use crate::highlight;
use crate::item_data::ItemData;
use crate::item_data::Ref;
use crate::item_data::SectionHeader;
use git2::Oid;
use git2::Repository;
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::text::Span;
use regex::Regex;
use std::hash::DefaultHasher;
use std::hash::Hash;
Expand All @@ -30,188 +24,6 @@ pub(crate) struct Item {
pub(crate) data: ItemData,
}

impl Item {
pub fn to_line(&'_ self, config: &Config) -> Line<'_> {
match self.data.clone() {
ItemData::Raw(content) => Line::raw(content),
ItemData::AllUnstaged(count) => Line::from(vec![
Span::styled("Unstaged changes", &config.style.section_header),
Span::raw(format!(" ({count})")),
]),
ItemData::AllStaged(count) => Line::from(vec![
Span::styled("Staged changes", &config.style.section_header),
Span::raw(format!(" ({count})")),
]),
ItemData::AllUntracked(_) => {
Line::styled("Untracked files", &config.style.section_header)
}
ItemData::Reference { kind, prefix } => {
let (reference, style) = match kind {
Ref::Tag(tag) => (tag, &config.style.tag),
Ref::Head(branch) => (branch, &config.style.branch),
Ref::Remote(remote) => (remote, &config.style.remote),
};

Line::from(vec![Span::raw(prefix), Span::styled(reference, style)])
}
ItemData::Commit {
short_id,
associated_references,
summary,
..
} => Line::from_iter(itertools::intersperse(
iter::once(Span::styled(short_id, &config.style.hash))
.chain(
associated_references
.into_iter()
.map(|reference| match reference {
Ref::Tag(tag) => Span::styled(tag, &config.style.tag),
Ref::Head(branch) => Span::styled(branch, &config.style.branch),
Ref::Remote(remote) => Span::styled(remote, &config.style.remote),
}),
)
.chain([Span::raw(summary)]),
Span::raw(" "),
)),
ItemData::Untracked(path) => Line::styled(
path.to_string_lossy().into_owned(),
&config.style.file_header,
),
ItemData::Delta { diff, file_i, .. } => {
let file_diff = &diff.file_diffs[file_i];

let content = format!(
"{:8} {}",
format!("{:?}", file_diff.header.status).to_lowercase(),
match file_diff.header.status {
Status::Renamed | Status::Copied => format!(
"{} -> {}",
&file_diff.header.old_file.fmt(&diff.text),
&file_diff.header.new_file.fmt(&diff.text)
),
Status::Deleted => file_diff.header.old_file.fmt(&diff.text).to_string(),
Status::Added => file_diff.header.new_file.fmt(&diff.text).to_string(),
Status::Modified => file_diff.header.new_file.fmt(&diff.text).to_string(),
Status::Unmerged => file_diff.header.new_file.fmt(&diff.text).to_string(),
}
);

Line::styled(content, &config.style.file_header)
}
ItemData::Hunk {
diff,
file_i,
hunk_i,
} => {
let file_diff = &diff.file_diffs[file_i];
let hunk = &file_diff.hunks[hunk_i];
let content = &diff.text[hunk.header.range.clone()];

Line::styled(content.to_string(), &config.style.hunk_header)
}
ItemData::HunkLine {
diff,
file_i,
hunk_i,
line_range,
line_i,
} => {
let hunk_highlights =
highlight::highlight_hunk(self.id, config, &Rc::clone(&diff), file_i, hunk_i);

let hunk_content = &diff.hunk_content(file_i, hunk_i);
let hunk_line = &hunk_content[line_range.clone()];

let line_highlights = hunk_highlights.get_line_highlights(line_i);

Line::from_iter(line_highlights.iter().map(|(highlight_range, style)| {
Span::styled(
hunk_line[highlight_range.clone()].replace("\t", " "),
*style,
)
}))
}
ItemData::Stash { message, id, .. } => Line::from(vec![
Span::styled(format!("stash@{id}"), &config.style.hash),
Span::raw(format!(" {message}")),
]),
ItemData::Header(header) => {
let content = match header {
SectionHeader::Remote(remote) => format!("Remote {remote}"),
SectionHeader::Tags => "Tags".to_string(),
SectionHeader::Branches => "Branches".to_string(),
SectionHeader::NoBranch => "No branch".to_string(),
SectionHeader::OnBranch(branch) => format!("On branch {branch}"),
SectionHeader::Rebase(head, onto) => format!("Rebasing {head} onto {onto}"),
SectionHeader::Merge(head) => format!("Merging {head}"),
SectionHeader::Revert(head) => format!("Reverting {head}"),
SectionHeader::CherryPick(head) => format!("Cherry-picking {head}"),
SectionHeader::Stashes => "Stashes".to_string(),
SectionHeader::RecentCommits => "Recent commits".to_string(),
SectionHeader::Commit(oid) => format!("commit {oid}"),
SectionHeader::StashRef(stash_ref) => stash_ref,
SectionHeader::StagedChanges(count) => format!("Staged changes ({count})"),
SectionHeader::UnstagedChanges(count) => format!("Unstaged changes ({count})"),
SectionHeader::UntrackedFiles(count) => format!("Untracked files ({count})"),
SectionHeader::Blame(file, commit) => {
format!("Blame {file} @ {commit}")
}
};

Line::styled(content, &config.style.section_header)
}
ItemData::BranchStatus(upstream, ahead, behind) => {
let content = if ahead == 0 && behind == 0 {
format!("Your branch is up to date with '{upstream}'.")
} else if ahead > 0 && behind == 0 {
format!("Your branch is ahead of '{upstream}' by {ahead} commit(s).",)
} else if ahead == 0 && behind > 0 {
format!("Your branch is behind '{upstream}' by {behind} commit(s).",)
} else {
format!(
"Your branch and '{upstream}' have diverged,\nand have {ahead} and {behind} different commits each, respectively."
)
};

Line::raw(content)
}
ItemData::Error(err) => Line::raw(err),
ItemData::BlameHeader {
short_hash,
summary,
..
} => Line::from(vec![
Span::styled(format!("{:<8}", short_hash), &config.style.hash),
Span::raw(" "),
Span::raw(summary.clone()),
]),
ItemData::BlameCodeLine {
blame_file,
line_i,
line_num,
content,
..
} => {
let mut spans = vec![Span::styled(
format!("{:>4} ", line_num),
&config.style.blame.line_num,
)];

for (range, style) in blame_file.highlights.get_line_highlights(line_i) {
if !range.is_empty() && range.end <= content.len() {
spans.push(Span::styled(
content[range.clone()].replace('\t', " "),
*style,
));
}
}

Line::from(spans).style(Style::from(&config.style.blame.code_line))
}
}
}
}

pub(crate) fn create_diff_items(
diff: &Rc<Diff>,
depth: usize,
Expand Down
Loading
Loading