Skip to content

Latest commit

 

History

History
410 lines (310 loc) · 10.6 KB

File metadata and controls

410 lines (310 loc) · 10.6 KB

RustyDiff Documentation Index

This document provides a comprehensive guide to the RustyDiff codebase documentation.

Crate-Level 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.

Module Documentation

Core Modules

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 structures

    • DiffType: Enum for diff format (GitDiff, GNUDiff)
    • DiffOutput: Raw diff output with metadata
    • LineType: Type of change (Added, Deleted, Context)
    • Line: Single line in a diff
    • Hunk: Block of changes
    • DiffResult: Complete parsed diff
  • utils (src/diff/utils.rs): Execute diff commands

    • run_diff(): Main entry point with fallback strategy
    • git_diff(): Execute git diff
    • standard_diff(): Execute standard diff
  • parser (src/diff/parser.rs): Parse unified diff format

    • parse_unified_diff(): Main parsing function
    • parse_file_headers(): Extract file names
    • parse_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 state

    • App: 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 handling

    • handle_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 rendering

    • render(): Main rendering orchestrator
    • render_header(): Display file information
    • render_content(): Display scrollable diff
    • render_footer(): Display keybindings
    • build_diff_lines(): Create styled diff lines
    • style_diff_line(): Apply colors and highlighting
    • format_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 highlighting
    • highlight_line_content(): Highlight a single line
    • syntect_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 point
  • setup_terminal(): Enable raw mode, enter alternate screen
  • restore_terminal(): Disable raw mode, leave alternate screen
  • run_app(): Main event loop

Keybindings

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

Data Structures

DiffResult

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 result
  • add_hunk(): Add a hunk
  • has_changes(): Check if any changes exist

Hunk

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 hunk
  • add_line(): Add a line to the hunk

Line

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 file
  • Deleted: Line exists only in old file
  • Context: Line exists in both files

App

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()

Color Scheme

Terminal Colors

  • 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)

Diff Colors

  • Red (#470000): Deleted line background
  • Green (#004708): Added line background
  • White: Context line text
  • Cyan: Hunk header

Architecture Patterns

Non-Blocking Event Handling

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
}

Viewport-Aware Rendering

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 Highlighting with Diff Integration

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,
};

Fallback Strategies

Multiple fallbacks ensure robust operation:

  1. Diff Execution: Git diff → GNU diff
  2. Syntax Highlighting: Language-specific → Generic coloring
  3. Color Transparency: Use diff color if syntax color is transparent

Module Interactions

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()

Code Documentation Access

In Source Files

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

Via Cargo Doc

Generate and view HTML documentation:

cargo doc --open

This 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

Development Workflow

Understanding the Code

  1. Start with lib.rs: Understand overall architecture
  2. Read main.rs: See how components are orchestrated
  3. Explore modules: Dive into specific functionality
  4. Review data structures: Understand how data flows

Adding New Features

  1. Check module documentation for extension points
  2. Follow established patterns (see "Architecture Patterns")
  3. Add documentation comments to new code
  4. Run cargo doc to ensure documentation builds

Debugging

  1. Check error messages for context
  2. Refer to module documentation for expected behavior
  3. Look at test cases for usage examples
  4. Review comments in related functions

External Resources

Dependencies

  • ratatui: Terminal rendering library
  • crossterm: Terminal control
  • syntect: Syntax highlighting
  • clap: CLI argument parsing
  • anyhow: Error handling

Rust Documentation

Quick Reference

Building

cargo build --release

Running

./target/release/rustydiff file1 file2

Testing

cargo test

Documentation

cargo doc --open

Linting

cargo clippy

Summary

RustyDiff is well-documented across multiple levels:

  1. Crate Level (lib.rs): Architecture, design patterns, usage
  2. Module Level (<mod-name>.rs files): Module purposes and organization
  3. Function Level (/// comments): How to use each function
  4. 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.