Skip to content

feat: implement Git repository and commit loading - #14

Merged
unhappychoice merged 4 commits into
mainfrom
feat/git-repository-loading
Nov 8, 2025
Merged

unhappychoice merged 4 commits into
mainfrom
feat/git-repository-loading

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Nov 8, 2025 •

Copy link
Copy Markdown
Owner

Summary

Implement Git repository operations, commit loading, and comprehensive diff parsing using git2.

This PR combines implementations for:

Changes

Git Module (src/git.rs)

Core structures:

  • GitRepository: repository operations
  • CommitMetadata: commit information with hash, author, date, message, and file changes
  • FileChange: file-level changes with path, status, binary flag, and structured hunks
  • FileStatus: A/D/M/R/C/U status indicators
  • DiffHunk: hunk information with line numbers and structured line changes
  • LineChange: individual line changes (addition/deletion/context) with content and line numbers

Features:

  • open(): open repository from path
  • get_commit(): load commit by hash (supports both short and full hashes)
  • random_commit(): select random non-merge commit
  • extract_changes(): comprehensive diff parsing with:
    • Line-by-line change extraction
    • Hunk parsing with old/new line tracking
    • Binary file detection
    • Renamed file handling
    • Full diff text preservation

Main (src/main.rs)

  • Load repository and display commit metadata
  • Support single-commit mode with specific hash
  • Support random commit mode with metadata display
  • Display file changes with status indicators
  • Show structured change information:
    • File count and status summary
    • Hunk statistics (additions/deletions/context)
    • Binary/rename indicators
  • Display raw diff output

Error Handling

  • Invalid repository paths
  • Non-existent commits
  • Invalid commit hashes
  • Binary files (graceful skip)

Test plan

  • cargo build succeeds
  • Random commit selection works
  • Specific commit loading works with short hash
  • Specific commit loading works with full hash
  • Error handling for invalid commit hashes
  • Non-merge commits are correctly filtered
  • File changes extracted with correct status
  • Diff hunks parsed correctly
  • Line-by-line changes tracked properly
  • Binary files handled gracefully
  • Added/modified/deleted files all work

Example output

$ cargo run -- --commit 2841866
git-logue v0.1.0
Repository: /home/owner/.ghq/github.com/unhappychoice/git-logue
Speed: 30ms per character

Single-commit mode: 2841866
  Hash:    284186678cbbd2b0b9bbd203a11f3ca1c8f6ef68
  Author:  Yuji Ueki
  Date:    2025-11-08 21:54:58
  Message: feat: implement CLI argument parsing
  ...

  Files changed: 1
    M src/main.rs

  Structured changes:
    File: src/main.rs
      Hunks: 1
        Hunk #1: @@ -1,6 +1,79 @@
          Lines: 80 total (+74 -1 context:5)

  Raw diff:
  diff --git a/src/main.rs b/src/main.rs
  ...

Resolves #4
Resolves #5

🤖 Generated with Claude Code

Add git module with GitRepository struct:
- Open Git repository from path
- Load commit by hash (supports both short and full hashes)
- Select random non-merge commits
- Extract commit metadata (hash, author, date, message)
- Graceful error handling for invalid repos and commits

Update main.rs to:
- Load repository and display commit metadata
- Support single-commit mode with specific hash
- Support random commit mode

Resolves #4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 8, 2025 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@unhappychoice has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0c03d and 7f5db95.

📒 Files selected for processing (2)
  • src/git.rs (1 hunks)
  • src/main.rs (2 hunks)

Walkthrough

A new Git module (src/git.rs) introduces Git repository utilities with struct GitRepository and CommitMetadata. Methods enable opening repositories, fetching commits by hash, and selecting random commits. Main.rs integrates this module to load commits in both single and multi-commit execution paths.

Changes

Cohort / File(s) Summary
New Git module
src/git.rs
Introduces GitRepository struct wrapping git2::Repository with methods: open() to initialize a repo, get_commit() to retrieve commit metadata by hash, and random_commit() to select a non-merge commit from HEAD history. Includes CommitMetadata struct (hash, author, date, message) and internal extract_metadata() helper to convert git2 commits.
Main integration
src/main.rs
Adds mod git declaration and imports GitRepository. Refactors commit handling: single-commit mode now uses repo.get_commit(commit_hash), multi-commit mode uses repo.random_commit(). Adds print_commit_info() helper function to format and display commit metadata. Includes minor formatting improvement (blank line after speed printout).

Sequence Diagram

sequenceDiagram
    participant main as main.rs
    participant git as git::GitRepository
    participant git2 as git2::Repository
    
    rect rgb(220, 240, 255)
    Note over main,git2: Initialization Phase
    main->>git: open(path)
    git->>git2: Repository::open()
    git2-->>git: Repository instance
    git-->>main: GitRepository
    end
    
    rect rgb(240, 220, 255)
    Note over main,git2: Single Commit Mode
    main->>git: get_commit(hash)
    git->>git2: find_commit(hash)
    git2-->>git: git2::Commit
    git->>git: extract_metadata(commit)
    git-->>main: CommitMetadata
    main->>main: print_commit_info()
    end
    
    rect rgb(240, 255, 220)
    Note over main,git2: Random Commit Mode
    main->>git: random_commit()
    git->>git2: revwalk from HEAD
    git2-->>git: commits (non-merge filtered)
    git->>git: select random commit
    git->>git: extract_metadata(commit)
    git-->>main: CommitMetadata
    main->>main: print_commit_info()
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • New isolated module: src/git.rs is self-contained with straightforward git2 wrapper logic; error handling follows standard Rust patterns
  • Lightweight integration: src/main.rs changes are minimal replacements with clear intent; helper function is uncomplicated
  • Attention areas:
    • Verify random_commit() filtering logic correctly excludes merge commits and handles edge cases (empty revwalk, no commits reachable from HEAD)
    • Confirm error context propagation in open() and get_commit() provides sufficient debugging information
    • Check that date conversion from git2 author time handles timezone correctly

Poem

🐰 Through git's vast history we hop,
Commits in hand, we'll never stop—
From hash to random, swift and true,
Metadata flows, a rabbit's breakthrough! 🌿

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: implement Git repository and commit loading' directly and clearly summarizes the main change: implementing Git repository operations and commit loading functionality via a new git module.
Linked Issues check ✅ Passed All coding requirements from issue #4 are met: repository opening via GitRepository::open(), commit loading by hash via get_commit(), random non-merge commit selection via random_commit(), and complete metadata extraction with graceful error handling.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #4 requirements: new git.rs module, GitRepository and CommitMetadata structs, commit loading APIs, and integration in main.rs for displaying commit metadata.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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: 1

🧹 Nitpick comments (3)
src/main.rs (1)

92-97: Consider handling multi-line commit messages.

Commit messages can span multiple lines. The current implementation prints the entire message on one line prefixed with "Message: ", which may look awkward for multi-line messages.

Consider either:

  • Showing only the first line (summary) of the message
  • Indenting continuation lines

Example for showing only the first line:

 fn print_commit_info(metadata: &git::CommitMetadata) {
     println!("  Hash:    {}", metadata.hash);
     println!("  Author:  {}", metadata.author);
     println!("  Date:    {}", metadata.date.format("%Y-%m-%d %H:%M:%S"));
-    println!("  Message: {}", metadata.message);
+    let summary = metadata.message.lines().next().unwrap_or("");
+    println!("  Message: {}", summary);
 }
src/git.rs (2)

38-41: Add error context for better debugging.

The error handling for revwalk() and push_head() lacks context, making it harder to diagnose issues.

Apply this diff:

 pub fn random_commit(&self) -> Result<CommitMetadata> {
-    let mut revwalk = self.repo.revwalk()?;
-    revwalk.push_head()?;
+    let mut revwalk = self.repo.revwalk()
+        .context("Failed to create revision walker")?;
+    revwalk.push_head()
+        .context("Failed to push HEAD to revision walker")?;

56-61: Add error context for commit lookup.

Line 60's find_commit error lacks context. This is unlikely to fail since the OID was just selected from the repository, but adding context improves error messages.

     let oid = non_merge_commits
         .choose(&mut rand::thread_rng())
         .context("Failed to select random commit")?;
 
-    let commit = self.repo.find_commit(*oid)?;
+    let commit = self.repo.find_commit(*oid)
+        .context("Failed to load selected commit")?;
     Ok(Self::extract_metadata(&commit))
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a10b823 and 2b0c03d.

📒 Files selected for processing (2)
  • src/git.rs (1 hunks)
  • src/main.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/main.rs (1)
src/git.rs (1)
  • open (20-24)
🔇 Additional comments (7)
src/main.rs (2)

1-6: LGTM!

The module declaration and imports are correctly structured.


67-90: LGTM!

The integration with GitRepository is clean. Both single-commit and random-commit modes are handled correctly with appropriate error propagation.

src/git.rs (5)

1-5: LGTM!

All necessary imports are present and correctly organized.


7-17: LGTM!

The struct definitions are well-designed. Good encapsulation for GitRepository and appropriate public fields with useful derives for CommitMetadata.


19-24: LGTM!

The repository opening logic is correct with appropriate error context.


26-36: LGTM!

Using revparse_single correctly handles both short and full commit hashes. The error messages are clear and helpful.


64-79: DateTime API usage is valid for chrono 0.4.0.

The DateTime::from_timestamp() method is a documented, valid API in chrono with proper error handling. The deprecation concern does not apply to chrono 0.4.0. The code correctly uses .unwrap_or_else() to handle the fallback case. No changes are needed.

Comment thread src/git.rs
Comment on lines +42 to +50
let non_merge_commits: Vec<Oid> = revwalk
.filter_map(|oid| oid.ok())
.filter(|oid| {
self.repo
.find_commit(*oid)
.map(|c| c.parent_count() <= 1)
.unwrap_or(false)
})
.collect();

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

Silent error suppression in filter may hide issues.

Line 48 uses unwrap_or(false) which silently treats any error from find_commit as "not a non-merge commit". This could mask genuine errors like repository corruption.

Consider logging errors or using a more explicit error handling strategy.

Example with error context:

     let non_merge_commits: Vec<Oid> = revwalk
         .filter_map(|oid| oid.ok())
         .filter(|oid| {
-            self.repo
-                .find_commit(*oid)
-                .map(|c| c.parent_count() <= 1)
-                .unwrap_or(false)
+            match self.repo.find_commit(*oid) {
+                Ok(c) => c.parent_count() <= 1,
+                Err(_) => false, // Skip commits we can't load
+            }
         })
         .collect();
📝 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
let non_merge_commits: Vec<Oid> = revwalk
.filter_map(|oid| oid.ok())
.filter(|oid| {
self.repo
.find_commit(*oid)
.map(|c| c.parent_count() <= 1)
.unwrap_or(false)
})
.collect();
let non_merge_commits: Vec<Oid> = revwalk
.filter_map(|oid| oid.ok())
.filter(|oid| {
match self.repo.find_commit(*oid) {
Ok(c) => c.parent_count() <= 1,
Err(_) => false, // Skip commits we can't load
}
})
.collect();
🤖 Prompt for AI Agents
In src/git.rs around lines 42 to 50, the filter closure currently uses
unwrap_or(false) when self.repo.find_commit(...) fails, silently hiding
repository errors; replace the silent suppression with explicit error handling:
change the iterator pipeline to surface or log find_commit errors (e.g., use
filter_map(|oid| match self.repo.find_commit(oid) { Ok(c) => Some((oid,
c.parent_count() <= 1)), Err(e) => { log the error with context (or
return/propagate Err from the surrounding function) ; None } }) and then collect
only the Oids that passed, or alternatively change the surrounding function to
return Result and propagate the error instead of converting it to false. Ensure
logged messages include the oid and error details for debugging.

unhappychoice and others added 3 commits November 9, 2025 07:04
Enhance commit metadata to include file changes and diffs:
- Add FileStatus enum (A/D/M/R/C/U)
- Add FileChange struct with path, status, and diff
- Extract diff for each changed file using git2
- Display file changes list with status indicators
- Display full diff output for each file

Changes to git module:
- extract_changes(): extract file changes from commit diff
- FileChange includes full patch/diff text
- Support for commits with no parents (initial commit)

Changes to main.rs:
- Display file count and status summary
- Display full diff output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add comprehensive line-by-line change extraction:

New data structures:
- LineChangeType: Addition/Deletion/Context
- LineChange: individual line with type, content, and line numbers
- DiffHunk: hunk information with old/new start, line counts, and lines
- Enhanced FileChange with:
  - old_path (for renames)
  - is_binary flag
  - hunks: structured line-by-line changes
  - diff: raw diff text

Features:
- Parse diff hunks into structured data
- Track old and new line numbers for each change
- Identify additions, deletions, and context lines
- Handle binary files (skip parsing, show placeholder)
- Handle renamed files
- Extract all changes in animation-ready format

Display enhancements:
- Show file change summary with binary/rename indicators
- Display hunk statistics (additions/deletions/context)
- Show structured change information
- Maintain raw diff output

Resolves #5

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add complete file content (before/after) to FileChange:
- old_content: full file content before changes
- new_content: full file content after changes
- Extract content from git tree blobs
- Handle new files (old_content = None)
- Handle deleted files (new_content = None)
- Handle binary files (both = None)

This provides everything needed for animation:
1. Full file content to display
2. Line-by-line change information
3. Line numbers for each change
4. Hunk boundaries

Example output:
- New file: Old content: (none - new file), New content: 109 lines
- Modified file: Old content: 6 lines, New content: 79 lines
- Deleted file: Old content: N lines, New content: (none - deleted file)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
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.

Implement diff parsing and change extraction Implement Git repository and commit loading

1 participant