Skip to content

Add diff subcommand to visualize working tree changes - #123

Merged
unhappychoice merged 4 commits into
unhappychoice:mainfrom
viniciussoares:vini/diff
Dec 16, 2025
Merged

unhappychoice merged 4 commits into
unhappychoice:mainfrom
viniciussoares:vini/diff

Conversation

@viniciussoares

@viniciussoares viniciussoares commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Add a new diff subcommand 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 changes

Closes #52

Summary by CodeRabbit

Release Notes

  • New Features

    • Added "Working Tree Diff View" feature to visualize current repository changes
    • New diff subcommand: gitlogue diff displays staged changes; gitlogue diff --unstaged displays unstaged changes
    • Supports theme, background, speed, and loop playback options for diff visualization
  • Documentation

    • Updated README with new diff feature and usage examples
    • Expanded usage guide with diff command documentation and examples

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 12, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This 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

Cohort / File(s) Summary
Documentation Updates
README.md, docs/usage.md
Added feature entry for Working Tree Diff View; expanded usage examples with gitlogue diff commands (staged/unstaged variants); added comprehensive diff command documentation with options and use cases.
Core Diff Functionality
src/git.rs
Introduced DiffMode enum (Staged/Unstaged) and get_working_tree_diff() to extract working-tree changes. Implemented staged and unstaged change extractors comparing HEAD/index/working-directory with FileChange entry generation. Added unified diff extraction, blob/index content retrieval, hunk formatting, and comprehensive test coverage.
CLI Integration & Command Dispatch
src/main.rs
Added Diff subcommand with options (unstaged, speed, theme, background, loop_playback, ignore, speed_rule); implemented handler resolving repository, computing diff metadata, loading theme, merging speed rules, and initializing UI. Updated Theme::load signature to accept String instead of reference. Changed top-level command matching to use reference-based pattern.
Animation & Rendering
src/animation.rs, src/panes/status_bar.rs
Conditional animation logic for working-tree diffs: simplified intro sequence (diff stat, pause, summary) bypassing time-travel; skip commit/push animations. Status bar conditionally displays "working" for working-tree hash and omits date line for non-commits.
UI State Management
src/ui.rs
Added optional diff_mode field to UI struct and public setter. Extended WaitingForNext logic: when diff_mode is set, refresh working-tree diff; otherwise, follow standard commit progression.
Lifetime Annotation
src/widgets/selectable_paragraph.rs
Updated Widget impl lifetime from impl<'a> Widget for SelectableParagraph<'a> to impl Widget for SelectableParagraph<\_>.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • src/git.rs: High-density logic with staged/unstaged extraction, blob/index content handling, hunk formatting, and comprehensive test coverage—requires careful review of diff logic correctness.
  • src/animation.rs: Conditional branching affecting core animation flow requires validation that working-tree and commit paths remain functionally separate and correct.
  • src/main.rs: New command variant and Theme::load signature change—verify wiring of all Diff options and backward compatibility of Theme::load call sites.
  • src/ui.rs: Conditional refresh logic in WaitingForNext state—ensure integration with existing commit progression logic.
  • Cross-file integration: Theme::load signature change and DiffMode usage across multiple files—verify consistent application.

Possibly Related PRs

Suggested Reviewers

  • unhappychoice

Poem

🐰 A diff without commit, oh what a delight!
Working-tree changes sparkle in plain sight,
No time-travel needed, just peek at the stage,
Staged or unstaged—the choice fills the page!
A rabbit's best wish: see changes before the push! 🌱

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: adding a new diff subcommand to visualize working tree changes, which is the primary objective of the PR.
Linked Issues check ✅ Passed The PR fully implements issue #52 requirements: it enables viewing git diff content for uncommitted changes with both staged (default) and unstaged modes.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the diff subcommand feature. Minor adjustments to animation, UI state, status bar, and widget lifetime annotations all support the core feature without introducing unrelated functionality.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 shared const WORKING_TREE_HASH: &str = "working-tree"; (likely in src/git.rs) and reference it here.

src/main.rs (1)

159-190: Missing --ignore-file option in Diff subcommand.

The main Args struct includes an --ignore-file option (lines 133-138) to load patterns from a file, but the Diff subcommand only has --ignore for inline patterns. This inconsistency may confuse users expecting feature parity.

Consider adding the --ignore-file option:

         #[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 in get_workdir_content.

The method checks file size but doesn't explicitly detect binary files. The get_blob_content_from_tree (line 962) and get_index_content_from (line 1059) both check blob.is_binary() before returning content, but get_workdir_content relies solely on read_to_string failing for binary files.

This works because read_to_string will 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7545577 and 47e4f14.

📒 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 in Widget impl 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 the diff command 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-start diff examples look good.

src/ui.rs (1)

23-24: diff_mode plumbing 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 (showing git diff --stat and 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 --unstaged flag
  • 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 ignore init_ignore_patterns errors, which is consistent with the main flow (line 394).


267-267: Remove verification request—Theme::load signature is &str, not String.

The signature at src/theme/mod.rs:72 is pub fn load(name: &str) -> Result<Self>, which accepts a string reference. The original change from Theme::load(&name) to Theme::load(name) is valid since Rust's auto-deref coercion allows passing owned or borrowed types where &str is expected. The signature was not changed to accept String as 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] on Staged, providing sensible defaults. The PartialEq derive enables comparison in tests and elsewhere.


777-800: LGTM - Clean public API for working tree diffs.

The get_working_tree_diff method provides a clear interface that:

  • Takes DiffMode to select staged vs unstaged
  • Returns well-formed CommitMetadata with 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_content method 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 TestRepo helper:

  • Uses RAII pattern with Drop for 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.

Comment thread README.md
Comment on lines +65 to +71
🎬 **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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Comment thread src/ui.rs
Comment on lines +203 to +219
// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find . -name "ui.rs" -type f | head -5

Repository: unhappychoice/gitlogue

Length of output: 77


🏁 Script executed:

wc -l src/ui.rs

Repository: unhappychoice/gitlogue

Length of output: 79


🏁 Script executed:

sed -n '190,250p' src/ui.rs | cat -n

Repository: unhappychoice/gitlogue

Length of output: 4093


🏁 Script executed:

rg "enum DiffMode|struct DiffMode" -A 5

Repository: unhappychoice/gitlogue

Length of output: 278


🏁 Script executed:

rg "loop_playback" -B 2 -A 2

Repository: unhappychoice/gitlogue

Length of output: 4268


🏁 Script executed:

# Check DiffMode definition more thoroughly
rg "enum DiffMode" -A 10

Repository: 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 -50

Repository: 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 -n

Repository: 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 2

Repository: 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 2

Repository: 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.

Suggested change
// 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 unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 DiffMode functionality
  • Clean integration with existing CommitMetadata structure
  • 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 --path option availability for the diff subcommand

LGTM! 👍

@unhappychoice
unhappychoice merged commit 7805317 into unhappychoice:main Dec 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: show the content of git diff

2 participants