Repository navigation
Add diff subcommand to visualize working tree changes - #123
Conversation
WalkthroughThis PR introduces a "Working Tree Diff View" feature enabling display of uncommitted git changes (staged/unstaged). It adds a new diff subcommand, implements working-tree change extraction with git-based diffing, conditionally alters animations and UI rendering for non-commit states, and expands documentation. Changes
Sequence DiagramsequenceDiagram
participant User
participant CLI as main.rs
participant Repo as GitRepository
participant Anim as AnimationEngine
participant UI as UI/Renderer
participant SB as StatusBar
User->>CLI: gitlogue diff [--unstaged]
CLI->>Repo: get_working_tree_diff(mode)
Repo->>Repo: extract_staged/unstaged_changes()
Repo-->>CLI: CommitMetadata (working-tree)
CLI->>Anim: load_commit(metadata)
alt is_working_tree (hash == "working-tree")
Anim->>Anim: Run simplified intro<br/>(git diff --stat, pause, summary)
Anim->>Anim: Skip commit/push animations
else Real commit
Anim->>Anim: Time-travel animation +<br/>detailed intro sequence
Anim->>Anim: Run commit/push animations
end
Anim->>UI: Update with file changes
UI->>SB: Render status (hash_display, date)
SB->>SB: For working-tree:<br/>hash="working", no date
SB-->>UI: Rendered frame
UI-->>User: Display diff visualization
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly Related PRs
Suggested Reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/panes/status_bar.rs (1)
27-53: Nice UX improvement; consider centralizing the"working-tree"sentinel.
The conditional hash/date rendering is solid. To reduce cross-file coupling/typos, consider a sharedconst WORKING_TREE_HASH: &str = "working-tree";(likely insrc/git.rs) and reference it here.src/main.rs (1)
159-190: Missing--ignore-fileoption in Diff subcommand.The main
Argsstruct includes an--ignore-fileoption (lines 133-138) to load patterns from a file, but theDiffsubcommand only has--ignorefor inline patterns. This inconsistency may confuse users expecting feature parity.Consider adding the
--ignore-fileoption:#[arg(short = 'i', long = "ignore", value_name = "PATTERN", action = clap::ArgAction::Append, help = "Ignore files matching pattern (gitignore syntax)")] ignore: Vec<String>, + + #[arg(long = "ignore-file", value_name = "PATH", + help = "Path to file containing ignore patterns (one per line, like .gitignore)")] + ignore_file: Option<PathBuf>, #[arg(long = "speed-rule", value_name = "PATTERN:MS", action = clap::ArgAction::Append, help = "Set typing speed for files matching pattern (e.g., '*.java:50')")] speed_rule: Vec<String>,src/git.rs (1)
1066-1082: Consider handling binary files inget_workdir_content.The method checks file size but doesn't explicitly detect binary files. The
get_blob_content_from_tree(line 962) andget_index_content_from(line 1059) both checkblob.is_binary()before returning content, butget_workdir_contentrelies solely onread_to_stringfailing for binary files.This works because
read_to_stringwill fail on invalid UTF-8, but the behavior is implicit. The current approach is acceptable since binary files won't parse as UTF-8, but you might want to add a comment clarifying this./// Get file content from working directory. /// /// Returns `None` if: /// - Path is not provided /// - Repository is bare (no working directory) - /// - File cannot be read (missing, permissions, binary/non-UTF8) + /// - File cannot be read (missing, permissions, or contains invalid UTF-8/binary content) /// - File size exceeds MAX_BLOB_SIZE (500KB) fn get_workdir_content(&self, path: Option<&std::path::Path>) -> Option<String> {
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
README.md(2 hunks)docs/usage.md(2 hunks)src/animation.rs(2 hunks)src/git.rs(5 hunks)src/main.rs(5 hunks)src/panes/status_bar.rs(1 hunks)src/ui.rs(4 hunks)src/widgets/selectable_paragraph.rs(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main.rs (4)
src/config.rs (1)
load(63-75)src/git.rs (3)
open(303-314)init_ignore_patterns(84-104)new(1227-1255)src/animation.rs (3)
parse(21-31)new(85-99)new(260-293)src/ui.rs (1)
new(57-90)
🔇 Additional comments (14)
src/widgets/selectable_paragraph.rs (1)
181-181: Lifetime elision inWidgetimpl is fine / more idiomatic.
impl Widget for SelectableParagraph<'_>should be equivalent to the prior generic lifetime impl and shouldn’t change behavior.docs/usage.md (2)
10-11: ToC update looks correct.
313-359: All documented options for thediffcommand match the actual CLI implementation. The options table is accurate, including the bool forms (--background[=BOOL]and--loop[=BOOL]) which correctly support both flag-only usage (e.g.,--background) and explicit value syntax (e.g.,--background=false).README.md (1)
110-115: Quick-startdiffexamples look good.src/ui.rs (1)
23-24:diff_modeplumbing looks clean.
Field + setter are straightforward and keep the UI API simple.Also applies to: 51-52, 88-95
src/animation.rs (2)
357-411: LGTM - Working-tree intro animation is well-structured.The conditional branching based on
metadata.hash == "working-tree"cleanly separates the simplified working-tree intro (showinggit diff --statand a summary) from the time-travel animation for real commits. The emoji-based output provides good visual feedback for the diff mode.
553-620: LGTM - Correctly skips commit/push animation for working-tree mode.The conditional ensures working-tree diffs only show a final pause rather than the git commit/push sequence, which makes semantic sense since uncommitted changes shouldn't be animated as being committed.
src/main.rs (2)
279-348: LGTM - Diff subcommand handler is well-implemented.The handler correctly:
- Validates repository path and opens the repo
- Selects diff mode based on
--unstagedflag- Handles empty changes gracefully with early return
- Merges CLI ignore patterns with config patterns
- Applies theme and background settings consistently
- Conditionally passes repo reference based on loop mode
Minor observation: Line 308 uses
.ok()to silently ignoreinit_ignore_patternserrors, which is consistent with the main flow (line 394).
267-267: Remove verification request—Theme::loadsignature is&str, notString.The signature at
src/theme/mod.rs:72ispub fn load(name: &str) -> Result<Self>, which accepts a string reference. The original change fromTheme::load(&name)toTheme::load(name)is valid since Rust's auto-deref coercion allows passing owned or borrowed types where&stris expected. The signature was not changed to acceptStringas indicated in the AI summary.Likely an incorrect or invalid review comment.
src/git.rs (5)
21-27: LGTM - DiffMode enum is well-designed.The enum correctly uses
#[derive(Default)]with#[default]onStaged, providing sensible defaults. ThePartialEqderive enables comparison in tests and elsewhere.
777-800: LGTM - Clean public API for working tree diffs.The
get_working_tree_diffmethod provides a clear interface that:
- Takes
DiffModeto select staged vs unstaged- Returns well-formed
CommitMetadatawith sentinel values- Uses consistent "working-tree" hash that animation.rs checks
879-951: LGTM - Good refactoring with generic content retrieval.The
extract_changes_from_diff_with_contentmethod cleanly abstracts the common diff extraction logic, accepting a closure for content retrieval. This avoids code duplication between staged and unstaged paths while maintaining type safety.
1214-1256: LGTM - Robust test infrastructure.The
TestRepohelper:
- Uses RAII pattern with
Dropfor automatic cleanup- Generates unique paths using PID, timestamp, and atomic counter to avoid collisions
- Properly configures git user for commits
1258-1272: LGTM - Good edge case coverage for empty repository.Tests verify behavior in an empty repo (no HEAD) for both staged and unstaged modes, ensuring the methods don't panic and return empty changes.
| 🎬 **Commit Replay as Animation** — Realistic typing, cursor movement, deletions, and file operations | ||
| 🔍 **Working Tree Diff View** — Visualize staged/unstaged changes before committing | ||
| 🎨 **Tree-sitter Syntax Highlighting** — 29 languages supported | ||
| 🌳 **Project File Tree** — Directory structure with change statistics | ||
| 🖥️ **Screensaver Mode** — Endless random commit playback | ||
| 🎭 **Themes** — 9 built-in themes + full customization support | ||
| ⚡ **Fast & Lightweight** — Built with Rust for performance |
There was a problem hiding this comment.
Potential doc inconsistency: supported language count (29 vs 26).
README now says 29 languages, but docs/usage.md still says 26—worth aligning to avoid confusion.
🤖 Prompt for AI Agents
In README.md around lines 65 to 71, the supported language count is listed as 29
while docs/usage.md still states 26; update the docs to be consistent by
verifying the actual number of languages supported and then change the outdated
count (either README or docs/usage.md) so both files report the same correct
number, and run a quick grep or check of the tree-sitter language list to ensure
the number matches the implemented set before committing.
| // Handle diff mode looping | ||
| if let Some(diff_mode) = self.diff_mode { | ||
| if let Some(repo) = self.repo { | ||
| // Refresh the working tree diff | ||
| match repo.get_working_tree_diff(diff_mode) { | ||
| Ok(metadata) if !metadata.changes.is_empty() => { | ||
| self.load_commit(metadata); | ||
| } | ||
| _ => { | ||
| // No more changes, finish | ||
| self.state = UIState::Finished; | ||
| } | ||
| } | ||
| } else { | ||
| self.state = UIState::Finished; | ||
| } | ||
| } else if let Some(repo) = self.repo { |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -name "ui.rs" -type f | head -5Repository: unhappychoice/gitlogue
Length of output: 77
🏁 Script executed:
wc -l src/ui.rsRepository: unhappychoice/gitlogue
Length of output: 79
🏁 Script executed:
sed -n '190,250p' src/ui.rs | cat -nRepository: unhappychoice/gitlogue
Length of output: 4093
🏁 Script executed:
rg "enum DiffMode|struct DiffMode" -A 5Repository: unhappychoice/gitlogue
Length of output: 278
🏁 Script executed:
rg "loop_playback" -B 2 -A 2Repository: unhappychoice/gitlogue
Length of output: 4268
🏁 Script executed:
# Check DiffMode definition more thoroughly
rg "enum DiffMode" -A 10Repository: unhappychoice/gitlogue
Length of output: 509
🏁 Script executed:
# Check the UI struct definition to see the type of diff_mode field
rg "struct UI" -A 30 | head -50Repository: unhappychoice/gitlogue
Length of output: 1216
🏁 Script executed:
# Check if DiffMode derives Copy
rg "DiffMode" -B 5 | grep -A 5 "derive\|Copy\|Clone"Repository: unhappychoice/gitlogue
Length of output: 220
🏁 Script executed:
# Get broader context to understand the UIState::WaitingForNext handler
sed -n '195,260p' src/ui.rs | cat -nRepository: unhappychoice/gitlogue
Length of output: 4487
🏁 Script executed:
# Check how diff_mode is set/initialized
rg "diff_mode\s*=" src/ui.rs -B 2 -A 2Repository: unhappychoice/gitlogue
Length of output: 224
🏁 Script executed:
# Check the UI constructor to see if diff_mode parameter exists
sed -n '1,150p' src/ui.rs | grep -A 50 "pub fn new"Repository: unhappychoice/gitlogue
Length of output: 1611
🏁 Script executed:
# Also check if there are any other references to diff_mode in ui.rs
rg "diff_mode" src/ui.rs -B 2 -A 2Repository: unhappychoice/gitlogue
Length of output: 950
Add loop_playback check in diff-mode branch to prevent continuous replay without --loop flag.
The diff-mode code path (lines 10–24) doesn't check self.loop_playback before calling self.load_commit(), while the regular commit path does (line 46). This causes diff-mode to replay continuously even when --loop wasn't requested. Add a loop_playback check:
if let Some(diff_mode) = self.diff_mode {
if let Some(repo) = self.repo {
// Refresh the working tree diff
match repo.get_working_tree_diff(diff_mode) {
Ok(metadata) if !metadata.changes.is_empty() => {
- self.load_commit(metadata);
+ if self.loop_playback {
+ self.load_commit(metadata);
+ } else {
+ // Play once: finish after initial playback
+ self.state = UIState::Finished;
+ }
}
_ => {
// No more changes, finish
self.state = UIState::Finished;
}
}
} else {
self.state = UIState::Finished;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Handle diff mode looping | |
| if let Some(diff_mode) = self.diff_mode { | |
| if let Some(repo) = self.repo { | |
| // Refresh the working tree diff | |
| match repo.get_working_tree_diff(diff_mode) { | |
| Ok(metadata) if !metadata.changes.is_empty() => { | |
| self.load_commit(metadata); | |
| } | |
| _ => { | |
| // No more changes, finish | |
| self.state = UIState::Finished; | |
| } | |
| } | |
| } else { | |
| self.state = UIState::Finished; | |
| } | |
| } else if let Some(repo) = self.repo { | |
| // Handle diff mode looping | |
| if let Some(diff_mode) = self.diff_mode { | |
| if let Some(repo) = self.repo { | |
| // Refresh the working tree diff | |
| match repo.get_working_tree_diff(diff_mode) { | |
| Ok(metadata) if !metadata.changes.is_empty() => { | |
| if self.loop_playback { | |
| self.load_commit(metadata); | |
| } else { | |
| // Play once: finish after initial playback | |
| self.state = UIState::Finished; | |
| } | |
| } | |
| _ => { | |
| // No more changes, finish | |
| self.state = UIState::Finished; | |
| } | |
| } | |
| } else { | |
| self.state = UIState::Finished; | |
| } | |
| } else if let Some(repo) = self.repo { |
🤖 Prompt for AI Agents
In src/ui.rs around lines 203 to 219, the diff-mode branch calls
self.load_commit() unconditionally causing continuous replay; update the branch
to mirror the regular commit path by checking self.loop_playback before calling
self.load_commit(): if self.loop_playback is true then call self.load_commit(),
otherwise set self.state = UIState::Finished; ensure the repo existence handling
remains the same and no other behavior is changed.
unhappychoice
left a comment
There was a problem hiding this comment.
Thanks for this great contribution! 🎉
The diff subcommand is a useful addition that allows users to visualize staged/unstaged changes before committing.
Good points:
- Comprehensive test coverage for the new
DiffModefunctionality - Clean integration with existing
CommitMetadatastructure - Well-documented in both README and usage.md
- Proper reuse of existing options (
--theme,--speed,--loop, etc.)
Minor suggestions for future improvements:
- Consider extracting
"working-tree"magic string to a constant - Document
--pathoption availability for the diff subcommand
LGTM! 👍
Add a new
diffsubcommand that allows users to visualize staged or unstaged working tree changes as animations, similar to how gitlogue animates commit history.gitlogue diff- View staged changes (default)gitlogue diff --unstaged- View unstaged changesCloses #52
Summary by CodeRabbit
Release Notes
New Features
diffsubcommand:gitlogue diffdisplays staged changes;gitlogue diff --unstageddisplays unstaged changesDocumentation
✏️ Tip: You can customize this high-level summary in your review settings.