This document provides a comprehensive guide to the RustyDiff codebase documentation.
The entire project is documented at the crate level in src/lib.rs. This file contains:
- Project Overview: What RustyDiff is and its key features
- Architecture Diagram: Visual representation of module relationships
- Data Flow: How information flows through the application
- Module Documentation: Purpose and responsibilities of each module
- Execution Flow: Step-by-step application startup process
- Dependencies: External crates and their purposes
- Usage Examples: How to use RustyDiff as a library and CLI tool
- Design Patterns: Non-blocking events, viewport rendering, fallback strategies
- Performance Considerations: Optimization strategies and typical performance
- Terminal Compatibility: Supported platforms and requirements
- Building and Installation: How to build from source
- Development Guide: Project structure and testing
Access: Run cargo doc --open to view HTML documentation including this file.
Handles file comparison and diff parsing.
Key Responsibilities:
- Execute diff commands (git or GNU diff)
- Parse unified diff format
- Organize changes into hunks and lines
Submodules:
-
models (
src/diff/models.rs): Data structuresDiffType: Enum for diff format (GitDiff, GNUDiff)DiffOutput: Raw diff output with metadataLineType: Type of change (Added, Deleted, Context)Line: Single line in a diffHunk: Block of changesDiffResult: Complete parsed diff
-
utils (
src/diff/utils.rs): Execute diff commandsrun_diff(): Main entry point with fallback strategygit_diff(): Execute git diffstandard_diff(): Execute standard diff
-
parser (
src/diff/parser.rs): Parse unified diff formatparse_unified_diff(): Main parsing functionparse_file_headers(): Extract file namesparse_hunk(): Parse individual hunks
Data Flow:
Files → run_diff() → Raw output → parse_unified_diff() → DiffResult
Implements the terminal user interface.
Key Responsibilities:
- Manage application state
- Handle keyboard input
- Render terminal display
- Manage scrolling and navigation
Submodules:
-
app (
src/ui/app.rs): Application stateApp: Main state container- Scrolling methods (scroll_up, scroll_down, etc.)
- Navigation methods (jump_to_next_hunk, jump_to_prev_hunk)
- Viewport management
-
events (
src/ui/events.rs): Keyboard input handlinghandle_events(): Main event polling (non-blocking)handle_key_event(): Process specific key presses- Supports vim-style and traditional keybindings
-
renderers (
src/ui/renderers.rs): Terminal renderingrender(): Main rendering orchestratorrender_header(): Display file informationrender_content(): Display scrollable diffrender_footer(): Display keybindingsbuild_diff_lines(): Create styled diff linesstyle_diff_line(): Apply colors and highlightingformat_line_numbers(): Format line number display
Layout:
Header (3 lines: file names)
│
Content (scrollable: syntax-highlighted diff)
│
Footer (3 lines: keybindings)
Provides syntax highlighting for source code.
Key Responsibilities:
- Detect programming language from file extension
- Apply language-specific syntax highlighting
- Convert syntax colors to terminal-compatible colors
- Integrate highlighting with diff colors
Submodules:
- highlighter (
src/syntax/highlighter.rs): Apply highlightinghighlight_line_content(): Highlight a single linesyntect_to_ratatui_color(): Color space conversion
Features:
- Language detection via file extension
- Multiple theme support (using Syntect)
- Diff-aware coloring (red for deletions, green for additions)
- Transparent color fallback
Entry point for the binary application.
Key Responsibilities:
- Parse command-line arguments
- Setup and restore terminal
- Orchestrate main event loop
- Handle application lifecycle
Key Functions:
main(): Application entry pointsetup_terminal(): Enable raw mode, enter alternate screenrestore_terminal(): Disable raw mode, leave alternate screenrun_app(): Main event loop
| Key(s) | Action |
|---|---|
q, Esc |
Quit the application |
Ctrl+C |
Quit (force) |
j, ↓ |
Scroll down one line |
k, ↑ |
Scroll up one line |
Ctrl+D |
Scroll down half page |
Ctrl+U |
Scroll up half page |
Ctrl+F, PageDown |
Scroll down full page |
Ctrl+B, PageUp |
Scroll up full page |
n |
Jump to next hunk |
p |
Jump to previous hunk |
The main output from the parser.
pub struct DiffResult {
pub old_file: String,
pub new_file: String,
pub hunks: Vec<Hunk>,
}Methods:
new(): Create new resultadd_hunk(): Add a hunkhas_changes(): Check if any changes exist
A contiguous block of changes.
pub struct Hunk {
pub old_start: usize,
pub old_count: usize,
pub new_start: usize,
pub new_count: usize,
pub lines: Vec<Line>,
}Methods:
new(): Create new hunkadd_line(): Add a line to the hunk
A single line in a hunk.
pub struct Line {
pub line_type: LineType,
pub content: String,
pub old_line_num: Option<usize>,
pub new_line_num: Option<usize>,
}Line Types:
Added: Line exists only in new fileDeleted: Line exists only in old fileContext: Line exists in both files
The main application state.
pub struct App {
pub diff_result: DiffResult,
pub scroll_offset: usize,
pub should_quit: bool,
pub syntax_set: SyntaxSet,
pub theme: Theme,
pub viewport_height: usize,
pub hunk_positions: Vec<usize>,
}Methods:
- Scrolling:
scroll_up(),scroll_down(),scroll_*_page() - Navigation:
jump_to_next_hunk(),jump_to_prev_hunk() - State:
quit(),set_viewport_height(),get_file_extension()
- Header: Blue, bold
- Added Lines: Green
+prefix + dark green background - Deleted Lines: Red
-prefix + dark red background - Context Lines: White text (default)
- Hunk Headers: Cyan, bold
- Line Numbers: Dark gray
- Footer: Yellow, bold
- Syntax Highlighting: Theme-dependent (base16-mocha.dark)
- Red (
#470000): Deleted line background - Green (
#004708): Added line background - White: Context line text
- Cyan: Hunk header
Events are polled with a 100ms timeout to balance responsiveness and CPU usage:
loop {
terminal.draw(|frame| render(frame, &mut app))?;
handle_events(&mut app)?; // Non-blocking with timeout
}Only visible lines are rendered for efficiency:
let start = app.scroll_offset;
let end = start + viewport_height;
let visible_lines = all_lines[start..end].to_vec();Syntax colors are combined with diff colors:
let fg_color = syntect_to_ratatui_color(syntax_color);
let bg_color = match line_type {
Deleted => Color::Rgb(71, 0, 0), // Dark red
Added => Color::Rgb(0, 71, 8), // Dark green
Context => Color::Reset,
};Multiple fallbacks ensure robust operation:
- Diff Execution: Git diff → GNU diff
- Syntax Highlighting: Language-specific → Generic coloring
- Color Transparency: Use diff color if syntax color is transparent
main.rs
├─ diff::utils::run_diff()
│ └─ Executes system diff command
├─ diff::parser::parse_unified_diff()
│ └─ Parses raw diff output
└─ ui::app::App::new()
├─ ui::renderers::render()
│ └─ syntax::highlighter::highlight_line_content()
└─ ui::events::handle_events()
Each module, function, and struct has documentation comments:
- Module-level:
//!comments at the top of each file - Public items:
///doc comments on structs, enums, and functions - Code examples: Many doc comments include usage examples
- Errors: Error conditions are documented
Generate and view HTML documentation:
cargo doc --openThis generates documentation from:
- Crate-level doc in
src/lib.rs - Module-level docs in each
src/<mod-name>.rs - Item-level docs on public types and functions
- Start with lib.rs: Understand overall architecture
- Read main.rs: See how components are orchestrated
- Explore modules: Dive into specific functionality
- Review data structures: Understand how data flows
- Check module documentation for extension points
- Follow established patterns (see "Architecture Patterns")
- Add documentation comments to new code
- Run
cargo docto ensure documentation builds
- Check error messages for context
- Refer to module documentation for expected behavior
- Look at test cases for usage examples
- Review comments in related functions
- ratatui: Terminal rendering library
- crossterm: Terminal control
- syntect: Syntax highlighting
- clap: CLI argument parsing
- anyhow: Error handling
cargo build --release./target/release/rustydiff file1 file2cargo testcargo doc --opencargo clippyRustyDiff is well-documented across multiple levels:
- Crate Level (
lib.rs): Architecture, design patterns, usage - Module Level (
<mod-name>.rsfiles): Module purposes and organization - Function Level (
///comments): How to use each function - Inline (comments): Why code makes specific decisions
All documentation is accessible via:
- Source code comments
cargo doc --open(HTML format)- This index file
For questions or clarifications, refer to the module documentation in the source code, which includes examples and detailed explanations of behavior.