Skip to content
Merged
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
8 changes: 5 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,19 @@ Rust 1.100 (edition 2024), pinned in `mise.toml` and `rust-version` in `Cargo.to

## Architecture

gitrat is a terminal UI (TUI) for staging, viewing diffs, and committing — a lightweight alternative to `git add -p`. It has no library crates, only a single binary.
gitrat is a terminal UI (TUI) for staging, viewing diffs, and committing — a lightweight alternative to `git add -p`. `src/lib.rs` exposes every module as a library so integration tests can use it; `src/main.rs` is the binary (CLI + event loop).

**Tests** live in `tests/` (one file per module: `git.rs`, `diff.rs`, `ui.rs`, `app.rs`, `theme.rs`), not in inline `#[cfg(test)]` modules. `tests/common/mod.rs` has `TempRepo`, which creates throwaway git repositories. Anything a test needs must be `pub`.

**Data flow:**
1. `git.rs` — `Repo` (found via `git rev-parse --show-toplevel`) runs every git command from the repo root with stdin closed, `GIT_TERMINAL_PROMPT=0` and `GIT_OPTIONAL_LOCKS=0`. Parses `git status --porcelain=v1 -z --branch` into `Status { branch, files }`, builds diffs (`--no-color --no-ext-diff`, capped at 20k lines, control chars sanitized), and exposes stage/unstage/revert/remove/commit/push returning `GitResult<_>` (`Result<_, String>` with a readable message). Has integration tests that create temporary repositories.
1. `git.rs` — `Repo` (found via `git rev-parse --show-toplevel`) runs every git command from the repo root with stdin closed, `GIT_TERMINAL_PROMPT=0` and `GIT_OPTIONAL_LOCKS=0`. Parses `git status --porcelain=v1 -z --branch` into `Status { branch, files }`, builds diffs (`--no-color --no-ext-diff`, capped at 20k lines, control chars sanitized), and exposes stage/unstage/revert/remove/commit/push returning `GitResult<_>` (`Result<_, String>` with a readable message).
2. `types.rs` — plain data types: `FileEntry` (path, optional rename origin, raw `XY` status chars, `FileStatus`).
2b. `diff.rs` — turns raw `DiffSection`s into a `DiffView` of `Row`s (`RowKind`, old/new line numbers, styled `Seg`s). Hides git headers (keeps notes like "new file"/"renamed from"), syntax-highlights with syntect + two-face (bat's syntaxes), and marks changed words via a token-level LCS between paired removed/added lines. Caps: 20k rows, highlighting off above 8k rows or 1k-byte lines.
2c. `theme.rs` — `Theme` palette (diff backgrounds, accents, syntax theme OneHalfDark/GitHub). `--theme auto` uses `COLORFGBG`, then the OS setting (macOS `AppleInterfaceStyle`, Windows `AppsUseLightTheme`, GNOME `color-scheme`). Truecolor if `COLORTERM`/`WT_SESSION`/`TERM_PROGRAM` says so, else hand-picked xterm-256 fallbacks.
3. `app.rs` — `App` owns UI state: files, selection (kept by path across refreshes), `DiffView` + scroll (rebuilt only when the raw diff changes), `Mode` (`Normal`, `Input`, `Confirm`, `Help`), commit input, transient `Message`. `tick()` collects background push results, expires messages and auto-refreshes every 3 s.
4. `ui.rs` — render function; reads `App` (and records panel rects for mouse hit-testing). 30/70 side-by-side layout, stacked below 80 columns. Diff rows: `old new ± code` gutter, full-width tinted backgrounds, hunk header bars. Syntax tokens using the theme's default foreground render as `Color::Reset` so text stays readable if light/dark detection is wrong.
5. `terminal.rs` — raw mode, alternate screen, bracketed paste, focus events, optional mouse capture, and a panic hook that restores the terminal.
6. `main.rs` — clap CLI (`[PATH]`, `--no-mouse`, `--theme`), repo discovery before entering the TUI, poll-based event loop (250 ms tick).
6. `main.rs` — binary entry point using the `gitrat` lib: clap CLI (`[PATH]`, `--no-mouse`, `--theme`), repo discovery before entering the TUI, poll-based event loop (250 ms tick).
7. `event_handler.rs` — key/mouse/paste dispatch per `Mode`.

**Key behaviors:**
Expand Down
20 changes: 1 addition & 19 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,27 +511,9 @@ impl App {
}

/// Removes the last whitespace-separated word (and trailing spaces) from `text`.
fn delete_last_word(text: &mut String) {
pub fn delete_last_word(text: &mut String) {
let trimmed = text.trim_end_matches(' ').len();
text.truncate(trimmed);
let cut = text.rfind(' ').map_or(0, |i| i + 1);
text.truncate(cut);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn deletes_last_word() {
let mut text = "fix: ação rápida ".to_string();
delete_last_word(&mut text);
assert_eq!(text, "fix: ação ");
delete_last_word(&mut text);
assert_eq!(text, "fix: ");
delete_last_word(&mut text);
assert_eq!(text, "");
delete_last_word(&mut text);
assert_eq!(text, "");
}
}
138 changes: 2 additions & 136 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -490,11 +490,11 @@ fn tokens(text: &str) -> Vec<Range<usize>> {
}

/// Byte ranges inside a line.
type Ranges = Vec<Range<usize>>;
pub type Ranges = Vec<Range<usize>>;

/// Byte ranges that differ between `old` and `new`, from a token-level longest
/// common subsequence, or `None` if the lines are too different to be worth it.
fn changed_ranges(old: &str, new: &str) -> Option<(Ranges, Ranges)> {
pub fn changed_ranges(old: &str, new: &str) -> Option<(Ranges, Ranges)> {
let ot = tokens(old);
let nt = tokens(new);
if ot.len() > MAX_WORD_DIFF_TOKENS || nt.len() > MAX_WORD_DIFF_TOKENS {
Expand Down Expand Up @@ -638,137 +638,3 @@ fn split_emphasis(pieces: &[(Style, &str)], emph: &[Range<usize>]) -> Vec<Seg> {

segs
}

#[cfg(test)]
mod tests {
use super::*;

fn section(text: &str) -> Vec<DiffSection> {
vec![DiffSection {
title: None,
text: text.to_string(),
}]
}

fn plain(row: &Row) -> String {
row.segs.iter().map(|s| s.text.as_str()).collect()
}

#[test]
fn parses_rows_and_line_numbers() {
let text = "diff --git a/x.txt b/x.txt\nindex 1..2 100644\n--- a/x.txt\n+++ b/x.txt\n@@ -10,3 +10,3 @@ fn main() {\n ctx\n-old\n+new\n ctx2\n\\ No newline at end of file\n";
let view = build(&section(text), "x.txt", &Theme::new(true, true));

let kinds: Vec<RowKind> = view.rows.iter().map(|r| r.kind).collect();
assert_eq!(
kinds,
vec![
RowKind::Hunk,
RowKind::Context,
RowKind::Removed,
RowKind::Added,
RowKind::Context,
RowKind::Info,
]
);
assert_eq!(view.rows[0].segs[0].text, "lines 10–12");
assert_eq!(view.rows[0].segs[1].text, "fn main() {");
assert_eq!((view.rows[1].old, view.rows[1].new), (Some(10), Some(10)));
assert_eq!((view.rows[2].old, view.rows[2].new), (Some(11), None));
assert_eq!((view.rows[3].old, view.rows[3].new), (None, Some(11)));
assert_eq!((view.rows[4].old, view.rows[4].new), (Some(12), Some(12)));
assert_eq!((view.added, view.removed, view.max_line_no), (1, 1, 12));
}

#[test]
fn content_that_looks_like_headers_stays_code() {
let text = "diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n--- x\n+++ y\n";
let view = build(&section(text), "x", &Theme::new(true, true));
assert_eq!(view.rows[1].kind, RowKind::Removed);
assert_eq!(plain(&view.rows[1]), "-- x");
assert_eq!(view.rows[2].kind, RowKind::Added);
}

#[test]
fn header_notes() {
let text = "diff --git a/n b/n\nnew file mode 100644\nindex 0..1\nBinary files /dev/null and b/n differ\n";
let view = build(&section(text), "n", &Theme::new(true, true));
let notes: Vec<String> = view.rows.iter().map(plain).collect();
assert_eq!(notes, vec!["new file", "binary file changed"]);
}

fn changed_words(old: &str, new: &str) -> Option<(Vec<String>, Vec<String>)> {
changed_ranges(old, new).map(|(o, n)| {
(
o.into_iter().map(|r| old[r].to_string()).collect(),
n.into_iter().map(|r| new[r].to_string()).collect(),
)
})
}

#[test]
fn word_level_emphasis() {
assert_eq!(
changed_words(
"#[derive(Debug, Clone, PartialEq)]",
"#[derive(Debug, Clone, Copy, PartialEq, Eq)]",
),
Some((vec![], vec!["Copy, ".into(), ", Eq".into()]))
);
assert_eq!(
changed_words(
"/// File has been deleted from the working tree.",
"/// File has been deleted from the working tree (not staged).",
),
Some((vec![], vec![" (not staged)".into()]))
);

assert!(changed_words("completely different", "nothing alike here!").is_none());
assert!(changed_words("same", "same").is_none());
}

#[test]
fn highlights_rust_and_marks_emphasis() {
let text = "@@ -1 +1 @@\n-let x = 1;\n+let x = 2;\n";
let view = build(&section(text), "src/main.rs", &Theme::new(true, true));
let added = &view.rows[2];
assert!(added.segs.len() > 1, "expected syntax colours: {added:?}");
let emph: String = added
.segs
.iter()
.filter(|s| s.emph)
.map(|s| s.text.as_str())
.collect();
assert_eq!(emph, "2");
assert_eq!(plain(added), "let x = 2;");
}

#[test]
fn sections_and_empty_sections() {
let sections = vec![
DiffSection {
title: Some("Staged changes".into()),
text: "@@ -1 +1 @@\n-a\n+b\n".into(),
},
DiffSection {
title: Some("Unstaged changes".into()),
text: String::new(),
},
];
let view = build(&sections, "f", &Theme::new(false, false));
let kinds: Vec<RowKind> = view.rows.iter().map(|r| r.kind).collect();
assert_eq!(kinds[0], RowKind::Section);
assert!(kinds.contains(&RowKind::Info));
assert_eq!(kinds.iter().filter(|k| **k == RowKind::Section).count(), 2);
}

#[test]
fn combined_conflict_diff() {
let text = "diff --cc f\n@@@ -1,1 -1,1 +1,5 @@@\n++<<<<<<< ours\n +a\n++=======\n+ b\n++>>>>>>> theirs\n";
let view = build(&section(text), "f", &Theme::new(true, false));
assert_eq!(view.rows[0].kind, RowKind::Hunk);
assert_eq!(plain(&view.rows[1]), "<<<<<<< ours");
assert!(view.rows[1..].iter().all(|r| r.kind == RowKind::Added));
assert_eq!(view.rows[5].new, Some(5));
}
}
Loading
Loading