Add new `rustik-diff` crate

28fe7a9e5fe23b2bccb24c1c5d9e01ee8f4a2772
Alexis Sellier committed ago 1 parent 41390c54
Cargo.lock +10 -0
110 110
111 111
[[package]]
112 112
name = "rustik"
113 113
version = "0.1.0"
114 114
dependencies = [
115 +
 "rustik-diff",
115 116
 "rustik-highlight",
116 117
 "rustik-tui",
117 118
]
118 119
120 +
[[package]]
121 +
name = "rustik-diff"
122 +
version = "0.1.0"
123 +
dependencies = [
124 +
 "rustik-highlight",
125 +
 "rustik-tui",
126 +
 "rustik-tui-termion",
127 +
]
128 +
119 129
[[package]]
120 130
name = "rustik-highlight"
121 131
version = "0.1.0"
122 132
dependencies = [
123 133
 "microserde",
Cargo.toml +5 -1
1 1
[workspace]
2 2
members = [
3 +
  "crates/diff",
3 4
  "crates/highlight",
4 5
  "crates/tui",
5 6
  "crates/tui-core",
6 7
  "crates/tui-termion",
7 8
  "crates/tui-widgets"
17 18
edition.workspace = true
18 19
license.workspace = true
19 20
20 21
[features]
21 22
default = []
23 +
diff = ["dep:rustik-diff"]
22 24
highlight = ["dep:rustik-highlight"]
23 25
widgets = ["rustik-tui/widgets"]
24 -
all = ["highlight", "widgets"]
26 +
all = ["diff", "highlight", "widgets"]
25 27
26 28
[dependencies]
29 +
rustik-diff = { workspace = true, optional = true }
27 30
rustik-highlight = { workspace = true, optional = true }
28 31
rustik-tui = { workspace = true }
29 32
30 33
[lints]
31 34
workspace = true
38 41
[workspace.dependencies]
39 42
onig = { package = "onig-regset", version = "6.7.0", default-features = false }
40 43
serde = { package = "microserde", version = "0.1.13" }
41 44
termion = "4"
42 45
rustik-highlight = { path = "crates/highlight", version = "0.1.0" }
46 +
rustik-diff = { path = "crates/diff", version = "0.1.0" }
43 47
rustik-tui = { path = "crates/tui", version = "0.1.0" }
44 48
rustik-tui-core = { path = "crates/tui-core", version = "0.1.0" }
45 49
rustik-tui-widgets = { path = "crates/tui-widgets", version = "0.1.0" }
46 50
rustik-tui-termion = { path = "crates/tui-termion", version = "0.1.0" }
47 51
STYLE +11 -0
56 56
* Start modules with `//!` documentation that states the module's role.
57 57
* Document all top-level types, functions, constants, and struct/enum fields with `///`.
58 58
* Replace magic numbers with named constants near related constants.
59 59
* Document constants by explaining the architectural or representation limit they encode.
60 60
* Never write documentation that refers to the current context in which the code is written.
61 +
* Avoid refering to specific code symbols unless it's a checkable link like [`symbol`].
61 62
62 63
RE-USE
63 64
64 65
* Always look for functions in the standard library that you can re-use, instead of implementing your own.
65 66
77 78
78 79
MODULES
79 80
80 81
* For large modules, group related declarations with simple ASCII section banners such as `// Constants //` or `// Error Handling //`.
81 82
* Keep imports and sub-modules at the top, then constants, then types, then functions.
83 +
84 +
FUNCTIONS
85 +
86 +
* Prefer methods on types to free functions.
87 +
* Avoid private helpers that are only used once.
88 +
89 +
TESTS
90 +
91 +
* Use `unwrap` in tests, not `expect`.
92 +
* Define tests in a module called `tests`.
crates/diff/Cargo.toml added +16 -0
1 +
[package]
2 +
name = "rustik-diff"
3 +
description = "Pure diff renderer and Git diff pager for Rustik."
4 +
documentation = "https://docs.rs/rustik-diff"
5 +
homepage = "https://crates.io/crates/rustik-diff"
6 +
version.workspace = true
7 +
edition.workspace = true
8 +
license.workspace = true
9 +
10 +
[dependencies]
11 +
rustik-highlight.workspace = true
12 +
rustik-tui = { workspace = true, features = ["widgets"] }
13 +
rustik-tui-termion.workspace = true
14 +
15 +
[lints]
16 +
workspace = true
crates/diff/README.md added +7 -0
1 +
# rustik-diff
2 +
3 +
Pure unified-diff parsing and terminal-buffer rendering for Rustik.
4 +
5 +
## License
6 +
7 +
MIT.
crates/diff/src/bin/rustik-diff.rs added +252 -0
1 +
//! Binary entry point for the `rustik-diff` pager.
2 +
3 +
use std::env;
4 +
use std::ffi::OsString;
5 +
use std::io::{self, IsTerminal as _, Read as _, Write as _};
6 +
use std::path::Path;
7 +
use std::process::{Command, ExitCode, Output};
8 +
use std::sync::mpsc;
9 +
use std::thread;
10 +
11 +
use rustik_diff::{
12 +
    BuiltinHighlighter, Decode, DecodeError, DiffAction, DiffDocument, DiffOptions, DiffViewer,
13 +
    ViewChange,
14 +
};
15 +
use rustik_diff::{HighlightRequest, HighlightResult};
16 +
use rustik_tui as tui;
17 +
use rustik_tui::{
18 +
    Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Scroll, Style, Terminal,
19 +
};
20 +
use rustik_tui_termion as tui_termion;
21 +
22 +
/// Default static render width for non-terminal output.
23 +
const STATIC_COLS: usize = 100;
24 +
/// Maximum static render rows for non-terminal output.
25 +
const STATIC_MAX_ROWS: usize = 10_000;
26 +
27 +
/// Terminal backend used by the interactive viewer.
28 +
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::StdoutScreen>>;
29 +
30 +
/// Program entry point.
31 +
fn main() -> ExitCode {
32 +
    match run(env::args_os().skip(1).collect()) {
33 +
        Ok(()) => ExitCode::SUCCESS,
34 +
        Err(error) => {
35 +
            let _ = writeln!(io::stderr(), "rustik-diff: {error}");
36 +
            ExitCode::FAILURE
37 +
        }
38 +
    }
39 +
}
40 +
41 +
/// Runs the binary with forwarded Git arguments.
42 +
fn run(args: Vec<OsString>) -> Result<(), Error> {
43 +
    if io::stdin().is_terminal() {
44 +
        let output = git_diff_in(&args, Path::new("."))?;
45 +
        if !output.status.success() {
46 +
            io::stderr().write_all(&output.stderr)?;
47 +
            return Err(Error::Git(output.status.code().unwrap_or(1)));
48 +
        }
49 +
        return run_or_forward(&output.stdout);
50 +
    }
51 +
    let mut input = Vec::new();
52 +
    io::stdin().read_to_end(&mut input)?;
53 +
54 +
    run_or_forward(&input)
55 +
}
56 +
57 +
/// Renders diff input or passes non-diff data through unchanged.
58 +
fn run_or_forward(input: &[u8]) -> Result<(), Error> {
59 +
    if !contains_diff(input) {
60 +
        io::stdout().write_all(input)?;
61 +
        return Ok(());
62 +
    }
63 +
    let text = std::str::from_utf8(input).map_err(|error| Error::Input(error.to_string()))?;
64 +
    let document = DiffDocument::decode_str(text)?;
65 +
66 +
    if !io::stdout().is_terminal() {
67 +
        let viewer = DiffViewer::new(document, DiffOptions::default());
68 +
        let rows = viewer.content_rows(STATIC_COLS).min(STATIC_MAX_ROWS);
69 +
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, rows));
70 +
71 +
        tui_termion::term::write_to_stdout(&viewer, constraints)?;
72 +
        return Ok(());
73 +
    }
74 +
    let backend = tui_termion::term::screen()?;
75 +
    let mut terminal = Terminal::new(backend)?;
76 +
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
77 +
78 +
    terminal.clear()?;
79 +
    terminal.set_cursor_visible(false)?;
80 +
81 +
    let result = terminal_loop(&mut terminal, &mut viewer);
82 +
    let cursor = terminal.set_cursor_visible(true);
83 +
84 +
    result.and(cursor).map_err(Error::Io)
85 +
}
86 +
87 +
/// Runs the terminal event loop.
88 +
fn terminal_loop(terminal: &mut DiffTerminal, viewer: &mut DiffViewer) -> io::Result<()> {
89 +
    let (events_tx, events_rx) = mpsc::channel();
90 +
    TerminalEvent::spawn_input_worker(events_tx.clone());
91 +
92 +
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx);
93 +
    let mut session = TerminalSession {
94 +
        terminal,
95 +
        viewer,
96 +
        highlights_tx,
97 +
    };
98 +
    session.redraw()?;
99 +
100 +
    while let Ok(event) = events_rx.recv() {
101 +
        match event {
102 +
            TerminalEvent::Input(event) => {
103 +
                let event = event?;
104 +
                let area = body_area(session.terminal.area());
105 +
                match handle_input(event, session.viewer, area) {
106 +
                    Control::Quit => break,
107 +
                    Control::Redraw => session.redraw()?,
108 +
                    Control::Continue | Control::Wait => {}
109 +
                }
110 +
            }
111 +
            TerminalEvent::Highlights(results) => {
112 +
                if session.viewer.apply_highlights(results) {
113 +
                    session.redraw()?;
114 +
                }
115 +
            }
116 +
        }
117 +
    }
118 +
    Ok(())
119 +
}
120 +
121 +
/// Interactive terminal session state.
122 +
struct TerminalSession<'a> {
123 +
    /// Terminal frame target.
124 +
    terminal: &'a mut DiffTerminal,
125 +
    /// Diff viewer state.
126 +
    viewer: &'a mut DiffViewer,
127 +
    /// Visible-row highlight request channel.
128 +
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
129 +
}
130 +
131 +
impl TerminalSession<'_> {
132 +
    /// Draws a frame and requests highlights for visible rows.
133 +
    fn redraw(&mut self) -> io::Result<()> {
134 +
        self.draw_frame()?;
135 +
        self.request_visible_highlights();
136 +
        Ok(())
137 +
    }
138 +
139 +
    /// Requests highlight work for currently visible rows.
140 +
    fn request_visible_highlights(&mut self) {
141 +
        let area = body_area(self.terminal.area());
142 +
        let requests = self.viewer.visible_highlight_requests(area);
143 +
        if !requests.is_empty() {
144 +
            let _ = self.highlights_tx.send(requests);
145 +
        }
146 +
    }
147 +
148 +
    /// Draws one terminal frame without scheduling highlight work.
149 +
    fn draw_frame(&mut self) -> io::Result<()> {
150 +
        self.terminal.draw(|frame| {
151 +
            let body = body_area(frame.area);
152 +
            frame.render_widget(&*self.viewer, body);
153 +
            draw_status(frame);
154 +
        })
155 +
    }
156 +
}
157 +
158 +
/// Event delivered to the terminal loop.
159 +
enum TerminalEvent {
160 +
    /// Terminal input event.
161 +
    Input(io::Result<Event<()>>),
162 +
    /// Background highlight results.
163 +
    Highlights(Vec<HighlightResult>),
164 +
}
165 +
166 +
impl TerminalEvent {
167 +
    /// Spawns the blocking input reader.
168 +
    fn spawn_input_worker(tx: mpsc::Sender<Self>) {
169 +
        thread::spawn(move || {
170 +
            for event in tui_termion::term::events() {
171 +
                if tx.send(Self::Input(event)).is_err() {
172 +
                    break;
173 +
                }
174 +
            }
175 +
        });
176 +
    }
177 +
178 +
    /// Spawns the visible-row highlight worker.
179 +
    fn spawn_highlight_worker(tx: mpsc::Sender<Self>) -> mpsc::Sender<Vec<HighlightRequest>> {
180 +
        let (requests_tx, requests_rx) = mpsc::channel::<Vec<HighlightRequest>>();
181 +
        thread::spawn(move || {
182 +
            let mut highlighter = BuiltinHighlighter::default();
183 +
            while let Ok(requests) = requests_rx.recv() {
184 +
                if requests.is_empty() {
185 +
                    continue;
186 +
                }
187 +
                let results = highlighter.highlight_requests(requests).collect();
188 +
                if tx.send(Self::Highlights(results)).is_err() {
189 +
                    break;
190 +
                }
191 +
            }
192 +
        });
193 +
        requests_tx
194 +
    }
195 +
}
196 +
197 +
/// Returns the body area, leaving one row for status when possible.
198 +
fn body_area(area: Rect) -> Rect {
199 +
    Rect::new(area.x, area.y, area.cols, area.rows.saturating_sub(1))
200 +
}
201 +
202 +
/// Draws the bottom status row.
203 +
fn draw_status(frame: &mut tui::Frame<'_>) {
204 +
    let area = frame.area;
205 +
    if area.rows == 0 {
206 +
        return;
207 +
    }
208 +
    let status = Line::new(Label::new("rustik-diff").fg(Color::Fixed(244)))
209 +
        .style(Style::default().bg(Color::Fixed(236)));
210 +
    let row = Rect::new(area.x, area.bottom().saturating_sub(1), area.cols, 1);
211 +
212 +
    frame.render_widget(status, row);
213 +
}
214 +
215 +
/// Applies one input event to the viewer.
216 +
fn handle_input(event: Event<()>, viewer: &mut DiffViewer, area: Rect) -> Control {
217 +
    let action = match event {
218 +
        Event::Key(Key::Char('q')) => return Control::Quit,
219 +
        Event::Key(Key::Esc) => {
220 +
            if viewer.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
221 +
                return Control::Redraw;
222 +
            }
223 +
            return Control::Quit;
224 +
        }
225 +
        Event::Key(Key::Char('j') | Key::Down) => DiffAction::Scroll(Scroll::Lines(1)),
226 +
        Event::Key(Key::Char('k') | Key::Up) => DiffAction::Scroll(Scroll::Lines(-1)),
227 +
        Event::Key(Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
228 +
        Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
229 +
        Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
230 +
        Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
231 +
        Event::Key(Key::Char('n')) => DiffAction::FocusNext,
232 +
        Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
233 +
        Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
234 +
        Event::Mouse(Mouse::Press {
235 +
            button: MouseButton::WheelDown,
236 +
            ..
237 +
        }) => DiffAction::Scroll(Scroll::Lines(3)),
238 +
        Event::Mouse(Mouse::Press {
239 +
            button: MouseButton::WheelUp,
240 +
            ..
241 +
        }) => DiffAction::Scroll(Scroll::Lines(-3)),
242 +
        Event::Resize(_) => DiffAction::Resize,
243 +
        _ => return Control::Continue,
244 +
    };
245 +
    viewer.apply(action, area);
246 +
    Control::Redraw
247 +
}
248 +
249 +
/// Returns whether byte input contains a Git patch.
250 +
fn contains_diff(input: &[u8]) -> bool {
251 +
    input
252 +
        .windows(b"
+0 -0
+0 -0
crates/diff/src/decode.rs added +138 -0
1 +
//! Unified diff decoder.
2 +
//!
3 +
//! Streaming [`Decode`] implementations for [`HunkHeader`], [`DiffLine`],
4 +
//! [`Hunk`], [`FileDiff`], and [`DiffDocument`]. Hunks are read by their
5 +
//! header counts (matching radicle-cli's `unified_diff` shape) so callers
6 +
//! can pull a hunk at a time without arbitrary peek-ahead. File and
7 +
//! document boundaries are detected with [`BufRead::fill_buf`] since
8 +
//! rustik-diff has no libgit2 layer to do it for us.
9 +
//!
10 +
//! [`Decode::decode_str`] is a thin string entry point — it just wraps the
11 +
//! input in [`io::Cursor`] and runs the streaming decoder.
12 +
13 +
use std::io::{self, BufRead};
14 +
use std::path::PathBuf;
15 +
use std::str::FromStr;
16 +
17 +
use crate::document::{
18 +
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
19 +
    FileMode, Hunk, HunkHeader, HunkId, Oid, RowId,
20 +
};
21 +
22 +
/// Decodes a value from unified diff text.
23 +
///
24 +
/// The default `decode_str`/`decode_bytes` adapters route through `decode`
25 +
/// so a single [`BufRead`]-based implementation covers all input shapes.
26 +
pub trait Decode: Sized {
27 +
    /// Reads and decodes a value from a buffered input stream.
28 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError>;
29 +
30 +
    /// Reads and decodes a value, returning `Ok(None)` at clean end-of-input.
31 +
    /// Anything else, including a partial value followed by EOF surfaces as
32 +
    /// `Err`.
33 +
    fn try_decode(input: &mut impl BufRead) -> Result<Option<Self>, DecodeError> {
34 +
        match Self::decode(input) {
35 +
            Ok(value) => Ok(Some(value)),
36 +
            Err(error) if error.is_eof() => Ok(None),
37 +
            Err(error) => Err(error),
38 +
        }
39 +
    }
40 +
41 +
    /// Decodes a value from a UTF-8 string.
42 +
    fn decode_str(input: &str) -> Result<Self, DecodeError> {
43 +
        Self::decode_bytes(input.as_bytes())
44 +
    }
45 +
46 +
    /// Decodes a value from raw UTF-8 bytes.
47 +
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
48 +
        let mut reader = io::BufReader::new(input);
49 +
        Self::decode(&mut reader)
50 +
    }
51 +
}
52 +
53 +
impl Decode for HunkHeader {
54 +
    /// Reads a hunk header line from the input stream.
55 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
56 +
        let mut stream = Stream::new(input);
57 +
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
58 +
        HunkHeader::decode_line(&line.text).map_err(|error| error.at_line(line.line_no))
59 +
    }
60 +
}
61 +
62 +
impl Decode for DiffLine {
63 +
    /// Reads one hunk-body line from the input stream.
64 +
    ///
65 +
    /// The returned [`DiffLine`] uses a zero row id; callers should
66 +
    /// assign a stable ID.
67 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
68 +
        let mut stream = Stream::new(input);
69 +
        let line = stream.read_line()?.ok_or_else(DecodeError::eof)?;
70 +
        line.decode_diff_line(RowId::new(0))
71 +
    }
72 +
}
73 +
74 +
impl Decode for Hunk {
75 +
    /// Reads a complete hunk from the input stream.
76 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
77 +
        Stream::new(input).decode_hunk()
78 +
    }
79 +
}
80 +
81 +
impl Decode for FileDiff {
82 +
    /// Reads one file diff from the input stream.
83 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
84 +
        let mut stream = Stream::new(input);
85 +
        if !stream.has_more()? {
86 +
            return Err(DecodeError::eof());
87 +
        }
88 +
        stream.decode_file(FileId::new(0))
89 +
    }
90 +
}
91 +
92 +
impl Decode for DiffDocument {
93 +
    /// Reads a full diff document from the input stream.
94 +
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
95 +
        Stream::new(input).decode_document()
96 +
    }
97 +
}
98 +
99 +
/// Streaming decoder over a buffered input stream.
100 +
///
101 +
/// Stores the reader, a line counter, and per-document ID counters used while
102 +
/// building a [`DiffDocument`]. Each decode call (`Hunk` or `FileDiff`) starts
103 +
/// from a fresh stream, so IDs begin at zero and callers that combine pieces
104 +
/// must renumber as needed.
105 +
struct Stream<R> {
106 +
    /// Buffered source of unified diff text.
107 +
    reader: R,
108 +
    /// Number of physical input lines already consumed.
109 +
    line_no: usize,
110 +
    /// Hunk ID to assign to the next decoded hunk.
111 +
    next_hunk_id: usize,
112 +
    /// Row ID to assign to the next decoded hunk-body line.
113 +
    next_row_id: usize,
114 +
}
115 +
116 +
/// One physical line read from the stream, with its 1-based line number.
117 +
struct ReadLine {
118 +
    /// 1-based physical input line number.
119 +
    line_no: usize,
120 +
    /// Line contents without trailing line endings.
121 +
    text: String,
122 +
}
123 +
124 +
impl<R: BufRead> Stream<R> {
125 +
    /// Creates a new streaming decoder.
126 +
    fn new(reader: R) -> Self {
127 +
        Self {
128 +
            reader,
129 +
            line_no: 0,
130 +
            next_hunk_id: 0,
131 +
            next_row_id: 0,
132 +
        }
133 +
    }
134 +
135 +
    /// Decodes a full document from the remaining input.
136 +
    fn decode_document(&mut self) -> Result<DiffDocument, DecodeError> {
137 +
        let mut preamble = Vec::new();
138 +
        while self.has_more()? && !self.peek_starts_with(b"
{ +0 -0
+0 -0
=> break, +0 -0
a.rs +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
a +0 -0
a +0 -0
a +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/document.rs added +650 -0
1 +
//! Unified diff document model.
2 +
//!
3 +
//! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`)
4 +
//! that callers consume. The decoder that produces these values lives in
5 +
//! [`crate::decode`]; `document` is intentionally model-only.
6 +
7 +
use std::fmt;
8 +
use std::io;
9 +
use std::num::ParseIntError;
10 +
use std::path::PathBuf;
11 +
use std::str::FromStr;
12 +
13 +
/// Stable identifier for a file section in one diff document.
14 +
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
15 +
pub struct FileId(usize);
16 +
17 +
/// Stable identifier for a hunk in one diff document.
18 +
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
19 +
pub struct HunkId(usize);
20 +
21 +
/// Stable identifier for a rendered hunk row in one diff document.
22 +
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
23 +
pub struct RowId(usize);
24 +
25 +
/// Object identifier as it appears in a Git diff header.
26 +
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
27 +
pub struct Oid(String);
28 +
29 +
impl FileId {
30 +
    /// Wraps a raw index as a [`FileId`].
31 +
    pub const fn new(index: usize) -> Self {
32 +
        Self(index)
33 +
    }
34 +
}
35 +
36 +
impl HunkId {
37 +
    /// Wraps a raw index as a [`HunkId`].
38 +
    pub const fn new(index: usize) -> Self {
39 +
        Self(index)
40 +
    }
41 +
}
42 +
43 +
impl RowId {
44 +
    /// Wraps a raw index as a [`RowId`].
45 +
    pub const fn new(index: usize) -> Self {
46 +
        Self(index)
47 +
    }
48 +
}
49 +
50 +
impl Oid {
51 +
    /// Returns the object identifier text.
52 +
    pub fn as_str(&self) -> &str {
53 +
        &self.0
54 +
    }
55 +
}
56 +
57 +
impl FromStr for Oid {
58 +
    type Err = OidError;
59 +
60 +
    fn from_str(input: &str) -> Result<Self, Self::Err> {
61 +
        if input.is_empty() {
62 +
            return Err(OidError);
63 +
        }
64 +
        if !input.bytes().all(|byte| byte.is_ascii_hexdigit()) {
65 +
            return Err(OidError);
66 +
        }
67 +
        Ok(Self(input.to_owned()))
68 +
    }
69 +
}
70 +
71 +
impl fmt::Display for Oid {
72 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 +
        f.write_str(&self.0)
74 +
    }
75 +
}
76 +
77 +
/// Error returned when a diff object identifier is malformed.
78 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
79 +
pub struct OidError;
80 +
81 +
impl fmt::Display for OidError {
82 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 +
        f.write_str("object id must be non-empty hexadecimal text")
84 +
    }
85 +
}
86 +
87 +
impl std::error::Error for OidError {}
88 +
89 +
impl std::ops::Deref for FileId {
90 +
    type Target = usize;
91 +
    fn deref(&self) -> &usize {
92 +
        &self.0
93 +
    }
94 +
}
95 +
96 +
impl std::ops::Deref for HunkId {
97 +
    type Target = usize;
98 +
    fn deref(&self) -> &usize {
99 +
        &self.0
100 +
    }
101 +
}
102 +
103 +
impl std::ops::Deref for RowId {
104 +
    type Target = usize;
105 +
    fn deref(&self) -> &usize {
106 +
        &self.0
107 +
    }
108 +
}
109 +
110 +
/// A complete unified diff document.
111 +
#[derive(Clone, Debug, Default, Eq, PartialEq)]
112 +
pub struct DiffDocument {
113 +
    /// Lines before the first `diff --git` section.
114 +
    pub preamble: Vec<String>,
115 +
    /// File diffs in input order.
116 +
    pub files: Vec<FileDiff>,
117 +
}
118 +
119 +
/// A single file section in a unified diff.
120 +
#[derive(Clone, Debug, Eq, PartialEq)]
121 +
pub struct FileDiff {
122 +
    /// Stable file identifier.
123 +
    pub id: FileId,
124 +
    /// Metadata and raw header lines for this file.
125 +
    pub header: FileHeader,
126 +
    /// Hunks in input order.
127 +
    pub hunks: Vec<Hunk>,
128 +
}
129 +
130 +
/// Metadata lines that introduce a file section in a Git patch.
131 +
#[derive(Clone, Debug, Eq, PartialEq)]
132 +
pub struct FileHeader {
133 +
    /// Classified kind of file change.
134 +
    pub kind: FileKind,
135 +
    /// Path on the old side of the diff, when present.
136 +
    pub old_path: Option<PathBuf>,
137 +
    /// Path on the new side of the diff, when present.
138 +
    pub new_path: Option<PathBuf>,
139 +
    /// File mode on the old side of the diff, when present.
140 +
    pub old_mode: Option<FileMode>,
141 +
    /// File mode on the new side of the diff, when present.
142 +
    pub new_mode: Option<FileMode>,
143 +
    /// Object id on the old side of the diff, when present.
144 +
    pub old_oid: Option<Oid>,
145 +
    /// Object id on the new side of the diff, when present.
146 +
    pub new_oid: Option<Oid>,
147 +
    /// Raw header lines preserved for callers that need exact metadata.
148 +
    pub raw: Vec<String>,
149 +
}
150 +
151 +
/// File mode in a Git diff, parsed from the octal value Git records.
152 +
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
153 +
pub enum FileMode {
154 +
    /// Regular file (`100644`).
155 +
    Blob,
156 +
    /// Executable regular file (`100755`).
157 +
    BlobExecutable,
158 +
    /// Symbolic link (`120000`).
159 +
    Link,
160 +
    /// Submodule reference, i.e. a Git commit (`160000`).
161 +
    Commit,
162 +
    /// Directory tree (`040000`).
163 +
    Tree,
164 +
    /// Any other mode, preserved as the original octal value.
165 +
    Other(u32),
166 +
}
167 +
168 +
/// Kind of file-level change described by a patch file header.
169 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
170 +
pub enum FileKind {
171 +
    /// Existing file content changed.
172 +
    Modified,
173 +
    /// New file was added.
174 +
    Added,
175 +
    /// Existing file was deleted.
176 +
    Deleted,
177 +
    /// Existing file was renamed.
178 +
    Renamed,
179 +
    /// Existing file was copied.
180 +
    Copied,
181 +
    /// File mode changed without a more specific content kind.
182 +
    ModeChanged,
183 +
    /// File contains binary patch data or a binary comparison marker.
184 +
    Binary,
185 +
}
186 +
187 +
/// Aggregate statistics for one [`FileDiff`].
188 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
189 +
pub struct FileStats {
190 +
    /// Total addition lines across all hunks in the file.
191 +
    pub additions: usize,
192 +
    /// Total deletion lines across all hunks in the file.
193 +
    pub deletions: usize,
194 +
}
195 +
196 +
/// Aggregate statistics for one [`DiffDocument`].
197 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
198 +
pub struct Stats {
199 +
    /// Number of file sections in the document.
200 +
    pub files_changed: usize,
201 +
    /// Total addition lines across all files.
202 +
    pub insertions: usize,
203 +
    /// Total deletion lines across all files.
204 +
    pub deletions: usize,
205 +
}
206 +
207 +
/// A unified diff hunk and its body lines.
208 +
#[derive(Clone, Debug, Eq, PartialEq)]
209 +
pub struct Hunk {
210 +
    /// Stable hunk identifier.
211 +
    pub id: HunkId,
212 +
    /// Parsed hunk header.
213 +
    pub header: HunkHeader,
214 +
    /// Lines contained in the hunk body.
215 +
    pub lines: Vec<DiffLine>,
216 +
}
217 +
218 +
/// Metadata from a unified diff hunk header.
219 +
///
220 +
/// Example: `@@ -24,8 +24,6 @@ fn main`.
221 +
#[derive(Clone, Debug, Default, Eq, PartialEq)]
222 +
pub struct HunkHeader {
223 +
    /// Starting line number on the old side of the diff.
224 +
    pub old_line_no: u32,
225 +
    /// Number of old-side lines covered by the hunk.
226 +
    pub old_size: u32,
227 +
    /// Starting line number on the new side of the diff.
228 +
    pub new_line_no: u32,
229 +
    /// Number of new-side lines covered by the hunk.
230 +
    pub new_size: u32,
231 +
    /// Optional trailing hunk context text.
232 +
    pub text: String,
233 +
}
234 +
235 +
/// A single line in a unified diff hunk.
236 +
#[derive(Clone, Debug, Eq, PartialEq)]
237 +
pub struct DiffLine {
238 +
    /// Stable row identifier.
239 +
    pub id: RowId,
240 +
    /// Line role inside the hunk.
241 +
    pub kind: DiffLineKind,
242 +
    /// Line text without the leading diff marker.
243 +
    pub text: String,
244 +
}
245 +
246 +
/// Role of a line inside a unified diff hunk.
247 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
248 +
pub enum DiffLineKind {
249 +
    /// Unchanged context line.
250 +
    Context,
251 +
    /// Added line.
252 +
    Addition,
253 +
    /// Deleted line.
254 +
    Deletion,
255 +
    /// Marker for a file without a trailing newline.
256 +
    NoNewline,
257 +
}
258 +
259 +
/// Error produced while decoding a unified diff.
260 +
#[derive(Clone, Debug, Eq, PartialEq)]
261 +
pub struct DecodeError {
262 +
    /// One-based input line number where decoding failed.
263 +
    pub line: usize,
264 +
    /// Human-readable failure message.
265 +
    pub message: String,
266 +
    /// Whether this error represents a clean end-of-input signal.
267 +
    is_eof: bool,
268 +
}
269 +
270 +
impl DiffDocument {
271 +
    /// Returns whether the document contains no changed files.
272 +
    pub fn is_empty(&self) -> bool {
273 +
        self.files.is_empty()
274 +
    }
275 +
276 +
    /// Returns the totals of files changed, insertions, and deletions.
277 +
    pub fn stats(&self) -> Stats {
278 +
        let mut stats = Stats {
279 +
            files_changed: self.files.len(),
280 +
            ..Stats::default()
281 +
        };
282 +
        for file in &self.files {
283 +
            let file_stats = file.stats();
284 +
            stats.insertions += file_stats.additions;
285 +
            stats.deletions += file_stats.deletions;
286 +
        }
287 +
        stats
288 +
    }
289 +
}
290 +
291 +
impl FileHeader {
292 +
    /// Returns the path callers should usually show for this file.
293 +
    pub fn display_path(&self) -> Option<&PathBuf> {
294 +
        self.new_path.as_ref().or(self.old_path.as_ref())
295 +
    }
296 +
}
297 +
298 +
impl FileMode {
299 +
    /// Returns the octal mode value Git records on the wire.
300 +
    pub const fn as_octal(self) -> u32 {
301 +
        match self {
302 +
            Self::Blob => 0o100644,
303 +
            Self::BlobExecutable => 0o100755,
304 +
            Self::Link => 0o120000,
305 +
            Self::Commit => 0o160000,
306 +
            Self::Tree => 0o040000,
307 +
            Self::Other(value) => value,
308 +
        }
309 +
    }
310 +
311 +
    /// Builds a [`FileMode`] from an octal value, mapping known modes.
312 +
    pub const fn from_octal(value: u32) -> Self {
313 +
        match value {
314 +
            0o100644 => Self::Blob,
315 +
            0o100755 => Self::BlobExecutable,
316 +
            0o120000 => Self::Link,
317 +
            0o160000 => Self::Commit,
318 +
            0o040000 => Self::Tree,
319 +
            other => Self::Other(other),
320 +
        }
321 +
    }
322 +
323 +
    /// Parses an octal mode token from a Git diff header (e.g. `"100644"`).
324 +
    pub fn parse(input: &str) -> Option<Self> {
325 +
        u32::from_str_radix(input.trim(), 8)
326 +
            .ok()
327 +
            .map(Self::from_octal)
328 +
    }
329 +
}
330 +
331 +
impl fmt::Display for FileMode {
332 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
333 +
        write!(f, "{:o}", self.as_octal())
334 +
    }
335 +
}
336 +
337 +
impl DecodeError {
338 +
    /// Creates a decode error at a one-based line number.
339 +
    pub fn new(line: usize, message: impl Into<String>) -> Self {
340 +
        Self {
341 +
            line,
342 +
            message: message.into(),
343 +
            is_eof: false,
344 +
        }
345 +
    }
346 +
347 +
    /// Creates an end-of-input error used to signal a clean EOF to streaming
348 +
    /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`.
349 +
    pub fn eof() -> Self {
350 +
        Self {
351 +
            line: 0,
352 +
            message: "unexpected end of file".to_owned(),
353 +
            is_eof: true,
354 +
        }
355 +
    }
356 +
357 +
    /// Returns whether this error represents end of input rather than a
358 +
    /// malformed patch.
359 +
    pub fn is_eof(&self) -> bool {
360 +
        self.is_eof
361 +
    }
362 +
363 +
    /// Returns a copy of this error with a line number when the error has none.
364 +
    pub(crate) fn at_line(mut self, line: usize) -> Self {
365 +
        if self.line == 0 {
366 +
            self.line = line;
367 +
        }
368 +
        self
369 +
    }
370 +
}
371 +
372 +
impl fmt::Display for DecodeError {
373 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374 +
        if self.line == 0 {
375 +
            f.write_str(&self.message)
376 +
        } else {
377 +
            write!(f, "line {}: {}", self.line, self.message)
378 +
        }
379 +
    }
380 +
}
381 +
382 +
impl std::error::Error for DecodeError {}
383 +
384 +
impl From<ParseIntError> for DecodeError {
385 +
    fn from(error: ParseIntError) -> Self {
386 +
        Self::new(0, error.to_string())
387 +
    }
388 +
}
389 +
390 +
impl From<io::Error> for DecodeError {
391 +
    fn from(error: io::Error) -> Self {
392 +
        Self {
393 +
            line: 0,
394 +
            message: error.to_string(),
395 +
            is_eof: error.kind() == io::ErrorKind::UnexpectedEof,
396 +
        }
397 +
    }
398 +
}
399 +
400 +
impl fmt::Display for FileKind {
401 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 +
        let name = match self {
403 +
            Self::Modified => "modified",
404 +
            Self::Added => "added",
405 +
            Self::Deleted => "deleted",
406 +
            Self::Renamed => "renamed",
407 +
            Self::Copied => "copied",
408 +
            Self::ModeChanged => "mode changed",
409 +
            Self::Binary => "binary",
410 +
        };
411 +
        f.write_str(name)
412 +
    }
413 +
}
414 +
415 +
impl DiffLineKind {
416 +
    /// Returns how many old-side lines this kind contributes to a hunk.
417 +
    pub const fn old_len(self) -> u32 {
418 +
        match self {
419 +
            Self::Context | Self::Deletion => 1,
420 +
            Self::Addition | Self::NoNewline => 0,
421 +
        }
422 +
    }
423 +
424 +
    /// Returns how many new-side lines this kind contributes to a hunk.
425 +
    pub const fn new_len(self) -> u32 {
426 +
        match self {
427 +
            Self::Context | Self::Addition => 1,
428 +
            Self::Deletion | Self::NoNewline => 0,
429 +
        }
430 +
    }
431 +
}
432 +
433 +
impl HunkHeader {
434 +
    /// Returns a copy with old and new line numbers shifted by the deltas.
435 +
    pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self {
436 +
        Self {
437 +
            old_line_no: Self::add_delta(self.old_line_no, old_delta),
438 +
            new_line_no: Self::add_delta(self.new_line_no, new_delta),
439 +
            ..self.clone()
440 +
        }
441 +
    }
442 +
443 +
    /// Adds a signed delta to an unsigned line number with saturation.
444 +
    fn add_delta(line: u32, delta: i32) -> u32 {
445 +
        if delta.is_negative() {
446 +
            line.saturating_sub(delta.unsigned_abs())
447 +
        } else {
448 +
            line.saturating_add(delta.unsigned_abs())
449 +
        }
450 +
    }
451 +
}
452 +
453 +
impl Hunk {
454 +
    /// Returns the number of old-side lines covered by the hunk body.
455 +
    pub fn old_size(&self) -> u32 {
456 +
        self.sizes().old
457 +
    }
458 +
459 +
    /// Returns the number of new-side lines covered by the hunk body.
460 +
    pub fn new_size(&self) -> u32 {
461 +
        self.sizes().new
462 +
    }
463 +
464 +
    /// Counts addition and deletion lines in this hunk.
465 +
    pub fn stats(&self) -> FileStats {
466 +
        let mut stats = FileStats::default();
467 +
        for line in &self.lines {
468 +
            match line.kind {
469 +
                DiffLineKind::Addition => stats.additions += 1,
470 +
                DiffLineKind::Deletion => stats.deletions += 1,
471 +
                DiffLineKind::Context | DiffLineKind::NoNewline => {}
472 +
            }
473 +
        }
474 +
        stats
475 +
    }
476 +
477 +
    /// Returns the net line offset introduced by applying this hunk.
478 +
    pub fn delta(&self) -> i32 {
479 +
        let sizes = self.sizes();
480 +
        let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX);
481 +
        let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX);
482 +
        new_size - old_size
483 +
    }
484 +
485 +
    /// Splits this hunk into context-separated change groups, each with its
486 +
    /// own recomputed header. Returns `None` when the hunk has fewer than two
487 +
    /// change groups (nothing to split).
488 +
    pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> {
489 +
        let groups = self.change_groups();
490 +
        if groups.len() < 2 {
491 +
            return None;
492 +
        }
493 +
        Some((0..groups.len()).map(move |index| {
494 +
            let group = groups[index];
495 +
            let start = if index == 0 {
496 +
                0
497 +
            } else {
498 +
                groups[index - 1].split_context_before(group)
499 +
            };
500 +
            let end = groups
501 +
                .get(index + 1)
502 +
                .map_or(self.lines.len(), |next| group.split_context_before(*next));
503 +
            self.segment(start, end)
504 +
        }))
505 +
    }
506 +
507 +
    /// Returns half-open ranges of contiguous non-context lines.
508 +
    fn change_groups(&self) -> Vec<ChangeGroup> {
509 +
        let mut groups = Vec::new();
510 +
        let mut current = None;
511 +
512 +
        for (index, line) in self.lines.iter().enumerate() {
513 +
            if matches!(line.kind, DiffLineKind::Context) {
514 +
                if let Some(start) = current.take() {
515 +
                    groups.push(ChangeGroup { start, end: index });
516 +
                }
517 +
            } else if current.is_none() {
518 +
                current = Some(index);
519 +
            }
520 +
        }
521 +
        if let Some(start) = current {
522 +
            groups.push(ChangeGroup {
523 +
                start,
524 +
                end: self.lines.len(),
525 +
            });
526 +
        }
527 +
        groups
528 +
    }
529 +
530 +
    /// Returns one hunk segment with line numbers and sizes recomputed.
531 +
    fn segment(&self, start: usize, end: usize) -> Self {
532 +
        let lines = self.lines[start..end].to_vec();
533 +
        let old_delta = self.lines[..start]
534 +
            .iter()
535 +
            .map(|l| l.kind.old_len())
536 +
            .sum::<u32>();
537 +
        let new_delta = self.lines[..start]
538 +
            .iter()
539 +
            .map(|l| l.kind.new_len())
540 +
            .sum::<u32>();
541 +
        let sizes = HunkSizes::from_lines(&lines);
542 +
543 +
        Self {
544 +
            id: self.id,
545 +
            header: HunkHeader {
546 +
                old_line_no: self.header.old_line_no.saturating_add(old_delta),
547 +
                old_size: sizes.old,
548 +
                new_line_no: self.header.new_line_no.saturating_add(new_delta),
549 +
                new_size: sizes.new,
550 +
                text: self.header.text.clone(),
551 +
            },
552 +
            lines,
553 +
        }
554 +
    }
555 +
556 +
    /// Returns old-side and new-side body sizes.
557 +
    fn sizes(&self) -> HunkSizes {
558 +
        HunkSizes::from_lines(&self.lines)
559 +
    }
560 +
}
561 +
562 +
/// Old-side and new-side line counts for a hunk body.
563 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
564 +
struct HunkSizes {
565 +
    /// Old-side line count.
566 +
    old: u32,
567 +
    /// New-side line count.
568 +
    new: u32,
569 +
}
570 +
571 +
impl HunkSizes {
572 +
    /// Counts old-side and new-side contributions across diff lines.
573 +
    fn from_lines(lines: &[DiffLine]) -> Self {
574 +
        let mut sizes = Self::default();
575 +
        for line in lines {
576 +
            sizes.old += line.kind.old_len();
577 +
            sizes.new += line.kind.new_len();
578 +
        }
579 +
        sizes
580 +
    }
581 +
}
582 +
583 +
impl FileDiff {
584 +
    /// Returns the sum of addition and deletion lines across all hunks.
585 +
    pub fn stats(&self) -> FileStats {
586 +
        let mut total = FileStats::default();
587 +
        for hunk in &self.hunks {
588 +
            let hunk_stats = hunk.stats();
589 +
            total.additions += hunk_stats.additions;
590 +
            total.deletions += hunk_stats.deletions;
591 +
        }
592 +
        total
593 +
    }
594 +
595 +
    /// Returns a copy containing only the hunks at the given indexes.
596 +
    pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self {
597 +
        Self {
598 +
            id: self.id,
599 +
            header: self.header.clone(),
600 +
            hunks: hunks
601 +
                .into_iter()
602 +
                .filter_map(|ix| self.hunks.get(ix).cloned())
603 +
                .collect(),
604 +
        }
605 +
    }
606 +
}
607 +
608 +
impl DiffDocument {
609 +
    /// Returns a single-file document with the given hunks, suitable for
610 +
    /// `git apply`. The preamble is dropped.
611 +
    pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self {
612 +
        Self {
613 +
            preamble: Vec::new(),
614 +
            files: vec![FileDiff {
615 +
                id: file.id,
616 +
                header: file.header.clone(),
617 +
                hunks: hunks.into_iter().collect(),
618 +
            }],
619 +
        }
620 +
    }
621 +
}
622 +
623 +
/// Half-open range of non-context lines inside a hunk.
624 +
#[derive(Clone, Copy, Debug)]
625 +
struct ChangeGroup {
626 +
    /// First changed line index.
627 +
    start: usize,
628 +
    /// One past the final changed line index.
629 +
    end: usize,
630 +
}
631 +
632 +
impl ChangeGroup {
633 +
    /// Returns the split point in the context before `next`.
634 +
    const fn split_context_before(self, next: Self) -> usize {
635 +
        self.end + (next.start - self.end) / 2
636 +
    }
637 +
}
638 +
639 +
#[cfg(test)]
640 +
#[allow(clippy::unwrap_used)]
641 +
mod tests {
642 +
    use super::*;
643 +
    use crate::Decode;
644 +
645 +
    fn parse_patch(input: &str) -> DiffDocument {
646 +
        DiffDocument::decode_str(input).unwrap()
647 +
    }
648 +
649 +
    const PATCH: &str = "\
650 +
a.txt +0 -0
a +0 -0
crates/diff/src/encode.rs added +97 -0
1 +
//! Unified diff encoder.
2 +
//!
3 +
//! Mirror image of [`crate::decode`]: takes a [`DiffDocument`] tree and emits
4 +
//! Git-style unified-diff text. Round-tripping `decode` → `encode` is
5 +
//! byte-for-byte for any document the decoder accepted, including the
6 +
//! preamble and the raw header lines preserved on each [`crate::FileHeader`].
7 +
8 +
use std::io::{self, Write};
9 +
10 +
use crate::document::{DiffDocument, DiffLine, DiffLineKind, FileDiff, Hunk, HunkHeader};
11 +
12 +
/// Encodes a value as unified-diff text.
13 +
pub trait Encode {
14 +
    /// Writes the unified-diff representation to `out`.
15 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()>;
16 +
17 +
    /// Returns the unified-diff representation as a `String`.
18 +
    fn to_unified_string(&self) -> io::Result<String> {
19 +
        let mut out = Vec::new();
20 +
        self.encode(&mut out)?;
21 +
        String::from_utf8(out).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
22 +
    }
23 +
}
24 +
25 +
impl Encode for DiffDocument {
26 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
27 +
        for line in &self.preamble {
28 +
            writeln!(out, "{line}")?;
29 +
        }
30 +
        for file in &self.files {
31 +
            file.encode(out)?;
32 +
        }
33 +
        Ok(())
34 +
    }
35 +
}
36 +
37 +
impl Encode for FileDiff {
38 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
39 +
        for line in &self.header.raw {
40 +
            writeln!(out, "{line}")?;
41 +
        }
42 +
        for hunk in &self.hunks {
43 +
            hunk.encode(out)?;
44 +
        }
45 +
        Ok(())
46 +
    }
47 +
}
48 +
49 +
impl Encode for Hunk {
50 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
51 +
        self.header.encode(out)?;
52 +
        for line in &self.lines {
53 +
            line.encode(out)?;
54 +
        }
55 +
        Ok(())
56 +
    }
57 +
}
58 +
59 +
impl Encode for HunkHeader {
60 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
61 +
        let old = if self.old_size == 1 {
62 +
            self.old_line_no.to_string()
63 +
        } else {
64 +
            format!("{},{}", self.old_line_no, self.old_size)
65 +
        };
66 +
        let new = if self.new_size == 1 {
67 +
            self.new_line_no.to_string()
68 +
        } else {
69 +
            format!("{},{}", self.new_line_no, self.new_size)
70 +
        };
71 +
        if self.text.is_empty() {
72 +
            writeln!(out, "@@ -{old} +{new} @@")
73 +
        } else {
74 +
            writeln!(out, "@@ -{old} +{new} @@ {}", self.text)
75 +
        }
76 +
    }
77 +
}
78 +
79 +
impl Encode for DiffLine {
80 +
    fn encode(&self, out: &mut impl Write) -> io::Result<()> {
81 +
        match self.kind {
82 +
            DiffLineKind::Context => writeln!(out, " {}", self.text),
83 +
            DiffLineKind::Addition => writeln!(out, "+{}", self.text),
84 +
            DiffLineKind::Deletion => writeln!(out, "-{}", self.text),
85 +
            DiffLineKind::NoNewline => writeln!(out, "\\ No newline at end of file"),
86 +
        }
87 +
    }
88 +
}
89 +
90 +
#[cfg(test)]
91 +
#[allow(clippy::expect_used)]
92 +
mod tests {
93 +
    use super::*;
94 +
    use crate::{Decode, DiffDocument, HunkHeader};
95 +
96 +
    const PATCH: &str = "\
97 +
a.txt +0 -0
b.txt +0 -0
crates/diff/src/highlight.rs added +267 -0
1 +
//! Highlight request and result protocol for diff rendering.
2 +
3 +
use std::collections::hash_map::DefaultHasher;
4 +
use std::hash::{Hash, Hasher as _};
5 +
use std::path::PathBuf;
6 +
7 +
use rustik_highlight as syntax;
8 +
use rustik_tui as tui;
9 +
use rustik_tui::{Color, Label, Line, Style};
10 +
11 +
use crate::{FileId, HunkId, RowId};
12 +
13 +
/// Built-in fallback theme name.
14 +
const BUILTIN_THEME_NAME: &str = "rustik";
15 +
16 +
/// Built-in syntax theme JSON.
17 +
const BUILTIN_THEME: &str = include_str!("rustik.json");
18 +
19 +
/// Side of the diff used as syntax-highlighting source context.
20 +
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
21 +
pub enum DiffSide {
22 +
    /// Old side of a deleted or context line.
23 +
    Old,
24 +
    /// New side of an added or context line.
25 +
    New,
26 +
}
27 +
28 +
/// Cache key for one highlighted diff row.
29 +
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
30 +
pub struct HighlightKey {
31 +
    /// File containing the row.
32 +
    pub file: FileId,
33 +
    /// Hunk containing the row.
34 +
    pub hunk: HunkId,
35 +
    /// Row to highlight.
36 +
    pub row: RowId,
37 +
    /// Diff side to highlight.
38 +
    pub side: DiffSide,
39 +
    /// One-based source line number.
40 +
    pub source_line: u32,
41 +
    /// Hash of the row text.
42 +
    pub text_hash: u64,
43 +
    /// Syntax key or `auto`.
44 +
    pub syntax: String,
45 +
    /// Theme key.
46 +
    pub theme: String,
47 +
}
48 +
49 +
/// Request sent from a visible diff viewport to a highlighter.
50 +
#[derive(Clone, Debug, Eq, PartialEq)]
51 +
pub struct HighlightRequest {
52 +
    /// Stable cache key for this request.
53 +
    pub key: HighlightKey,
54 +
    /// Source path used for syntax inference.
55 +
    pub path: Option<PathBuf>,
56 +
    /// Source text without a trailing line terminator.
57 +
    pub text: String,
58 +
}
59 +
60 +
/// Highlighted line returned by a worker.
61 +
#[derive(Clone, Debug)]
62 +
pub struct HighlightResult {
63 +
    /// Cache key copied from the original request.
64 +
    pub key: HighlightKey,
65 +
    /// Renderable highlighted line.
66 +
    pub line: tui::Line,
67 +
}
68 +
69 +
/// Pure built-in highlighter for visible diff rows.
70 +
#[derive(Debug)]
71 +
pub struct BuiltinHighlighter {
72 +
    /// Grammar and theme registry.
73 +
    registry: syntax::Registry,
74 +
    /// Reusable line scratch buffer.
75 +
    line: syntax::LineBuffer,
76 +
}
77 +
78 +
impl HighlightKey {
79 +
    /// Creates a key for a row of source text.
80 +
    pub fn new(input: HighlightKeyInput<'_>) -> Self {
81 +
        let mut hasher = DefaultHasher::new();
82 +
        input.text.hash(&mut hasher);
83 +
84 +
        Self {
85 +
            file: input.file,
86 +
            hunk: input.hunk,
87 +
            row: input.row,
88 +
            side: input.side,
89 +
            source_line: input.source_line,
90 +
            text_hash: hasher.finish(),
91 +
            syntax: input.syntax.unwrap_or("auto").to_owned(),
92 +
            theme: input.theme.to_owned(),
93 +
        }
94 +
    }
95 +
}
96 +
97 +
impl BuiltinHighlighter {
98 +
    /// Loads the built-in grammar and theme support.
99 +
    pub fn new() -> Result<Self, syntax::Error> {
100 +
        let mut registry = syntax::Registry::with_builtin_syntaxes();
101 +
        registry.add_theme_json(BUILTIN_THEME)?;
102 +
        Ok(Self {
103 +
            registry,
104 +
            line: syntax::LineBuffer::default(),
105 +
        })
106 +
    }
107 +
108 +
    /// Highlights one request.
109 +
    pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
110 +
        let line = self.highlight_line(&request);
111 +
        HighlightResult {
112 +
            key: request.key,
113 +
            line,
114 +
        }
115 +
    }
116 +
117 +
    /// Highlights multiple requests.
118 +
    pub fn highlight_requests<'a, I>(
119 +
        &'a mut self,
120 +
        requests: I,
121 +
    ) -> impl Iterator<Item = HighlightResult> + 'a
122 +
    where
123 +
        I: IntoIterator<Item = HighlightRequest> + 'a,
124 +
    {
125 +
        requests.into_iter().map(|request| self.highlight(request))
126 +
    }
127 +
128 +
    /// Highlights a request into a TUI line.
129 +
    fn highlight_line(&mut self, request: &HighlightRequest) -> Line {
130 +
        let Ok(grammar) = self.registry.query(syntax::GrammarQuery {
131 +
            syntax: (request.key.syntax != "auto").then_some(request.key.syntax.as_str()),
132 +
            path: request.path.as_deref(),
133 +
            first_line: Some(&request.text),
134 +
        }) else {
135 +
            return Line::new(request.text.clone());
136 +
        };
137 +
        let theme_name = if request.key.theme == "auto" {
138 +
            BUILTIN_THEME_NAME
139 +
        } else {
140 +
            &request.key.theme
141 +
        };
142 +
        let Ok(theme) = self.registry.theme_by_name(theme_name) else {
143 +
            return Line::new(request.text.clone());
144 +
        };
145 +
        let mut state = syntax::LineState::default();
146 +
        self.line.clear();
147 +
        let (_, spans) = self
148 +
            .line
149 +
            .highlight(grammar, theme, &mut state, &request.text);
150 +
151 +
        if request.text.is_empty() || spans.is_empty() {
152 +
            return Line::new(request.text.clone());
153 +
        }
154 +
        let mut line = Line::blank();
155 +
        let mut cursor = 0;
156 +
157 +
        for span in spans {
158 +
            if cursor < span.start {
159 +
                line.push(Label::new(&request.text[cursor..span.start]));
160 +
            }
161 +
            if span.start < span.end {
162 +
                line.push(
163 +
                    Label::new(&request.text[span.start..span.end]).style(span.style.tui_style()),
164 +
                );
165 +
            }
166 +
            cursor = span.end;
167 +
        }
168 +
        if cursor < request.text.len() {
169 +
            line.push(Label::new(&request.text[cursor..]));
170 +
        }
171 +
        line
172 +
    }
173 +
}
174 +
175 +
impl Default for BuiltinHighlighter {
176 +
    fn default() -> Self {
177 +
        Self::new().unwrap_or_else(|_| Self {
178 +
            registry: syntax::Registry::with_builtin_syntaxes(),
179 +
            line: syntax::LineBuffer::default(),
180 +
        })
181 +
    }
182 +
}
183 +
184 +
/// Input fields used to create a [`HighlightKey`].
185 +
#[derive(Clone, Copy, Debug)]
186 +
pub struct HighlightKeyInput<'a> {
187 +
    /// File containing the row.
188 +
    pub file: FileId,
189 +
    /// Hunk containing the row.
190 +
    pub hunk: HunkId,
191 +
    /// Row to highlight.
192 +
    pub row: RowId,
193 +
    /// Diff side to highlight.
194 +
    pub side: DiffSide,
195 +
    /// One-based source line number.
196 +
    pub source_line: u32,
197 +
    /// Source text.
198 +
    pub text: &'a str,
199 +
    /// Optional syntax override.
200 +
    pub syntax: Option<&'a str>,
201 +
    /// Theme name.
202 +
    pub theme: &'a str,
203 +
}
204 +
205 +
/// Converts syntax styles into TUI styles.
206 +
trait SyntaxStyleExt {
207 +
    /// Converts this syntax style into a TUI style.
208 +
    fn tui_style(self) -> Style;
209 +
}
210 +
211 +
impl SyntaxStyleExt for syntax::Style {
212 +
    fn tui_style(self) -> Style {
213 +
        let mut out = Style::default();
214 +
        if let Some(color) = self.foreground {
215 +
            out = out.fg(Color::RGB(color.r, color.g, color.b));
216 +
        }
217 +
        if self.font_style.contains(syntax::FontStyle::BOLD) {
218 +
            out = out.bold();
219 +
        }
220 +
        if self.font_style.contains(syntax::FontStyle::ITALIC) {
221 +
            out = out.italic();
222 +
        }
223 +
        if self.font_style.contains(syntax::FontStyle::UNDERLINE) {
224 +
            out = out.underline();
225 +
        }
226 +
        if self.font_style.contains(syntax::FontStyle::STRIKETHROUGH) {
227 +
            out = out.strikethrough();
228 +
        }
229 +
        out
230 +
    }
231 +
}
232 +
233 +
#[cfg(test)]
234 +
#[allow(clippy::expect_used)]
235 +
mod tests {
236 +
    use super::*;
237 +
238 +
    #[test]
239 +
    fn builtin_highlighter_renders_json_with_styles() {
240 +
        let mut highlighter = BuiltinHighlighter::new().expect("highlighter loads");
241 +
        let request = HighlightRequest {
242 +
            key: HighlightKey::new(HighlightKeyInput {
243 +
                file: FileId::new(0),
244 +
                hunk: HunkId::new(0),
245 +
                row: RowId::new(0),
246 +
                side: DiffSide::New,
247 +
                source_line: 1,
248 +
                text: "{\"ok\": true}",
249 +
                syntax: Some("json"),
250 +
                theme: "rustik",
251 +
            }),
252 +
            path: Some(PathBuf::from("data.json")),
253 +
            text: "{\"ok\": true}".to_owned(),
254 +
        };
255 +
256 +
        let result = highlighter.highlight(request);
257 +
258 +
        assert_eq!(result.line.to_string(), "{\"ok\": true}");
259 +
        assert!(
260 +
            result
261 +
                .line
262 +
                .labels()
263 +
                .iter()
264 +
                .any(|label| label.paint().style().fg_color() != Color::Unset)
265 +
        );
266 +
    }
267 +
}
crates/diff/src/lib.rs added +28 -0
1 +
//! Unified diff parsing and terminal-buffer rendering.
2 +
//!
3 +
//! The library side is intentionally I/O-free: it parses or accepts patch data,
4 +
//! owns read-only viewer state, and writes frames into a
5 +
//! [`rustik_tui::Buffer`]. The `rustik-diff` binary owns Git, stdin/stdout,
6 +
//! terminals, events, and background workers.
7 +
#![deny(unsafe_code)]
8 +
#![warn(missing_docs)]
9 +
#![warn(clippy::unwrap_used)]
10 +
11 +
mod document;
12 +
mod highlight;
13 +
mod renderer;
14 +
15 +
pub mod decode;
16 +
pub mod encode;
17 +
18 +
pub use decode::Decode;
19 +
pub use document::{
20 +
    DecodeError, DiffDocument, DiffLine, DiffLineKind, FileDiff, FileHeader, FileId, FileKind,
21 +
    FileMode, FileStats, Hunk, HunkHeader, HunkId, Oid, OidError, RowId, Stats,
22 +
};
23 +
pub use encode::Encode;
24 +
pub use highlight::{
25 +
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
26 +
    HighlightResult,
27 +
};
28 +
pub use renderer::{DiffAction, DiffFocus, DiffOptions, DiffState, DiffViewer, ViewChange};
crates/diff/src/renderer.rs added +887 -0
1 +
//! Read-only diff viewer state and buffer renderer.
2 +
3 +
use std::collections::{BTreeMap, BTreeSet};
4 +
use std::path::PathBuf;
5 +
6 +
use rustik_tui as tui;
7 +
use tui::{
8 +
    Buffer, Cell, Color, Constraint, HStack, Label, Line, Placement, Rect, Scroll, ScrollView,
9 +
    ScrollbarStyle, Size, Style, Table, TableOptions, VStack, View, Viewport, Widget, colors,
10 +
};
11 +
12 +
use crate::highlight::{HighlightKeyInput, HighlightResult};
13 +
use crate::{
14 +
    DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind, HighlightKey,
15 +
    HighlightRequest, HunkId, RowId,
16 +
};
17 +
18 +
/// Minimum width before the renderer attempts table-style diff rows.
19 +
const MIN_RENDER_COLS: usize = 12;
20 +
/// Width of old and new line number cells.
21 +
const LINE_NUMBER_WIDTH: usize = 5;
22 +
/// Width of the hunk marker cell.
23 +
const MARKER_WIDTH: usize = 3;
24 +
/// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track).
25 +
const SCROLLBAR_TRACK: &str = "🮘";
26 +
/// Scrollbar thumb glyph.
27 +
const SCROLLBAR_THUMB: &str = "▓";
28 +
/// File-card divider glyph (used between header/hunks and between hunks).
29 +
const DIVIDER: &str = "─";
30 +
/// Sticky file-header divider glyph.
31 +
const STICKY_DIVIDER: &str = "╴";
32 +
/// Pending file marker.
33 +
const FILE_MARKER: &str = "○";
34 +
/// Rename arrow.
35 +
const RENAME_ARROW: &str = "->";
36 +
/// Missing trailing newline marker.
37 +
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
38 +
/// Default highlight lookahead after the visible viewport.
39 +
const DEFAULT_HIGHLIGHT_LOOKAHEAD: usize = 4;
40 +
/// Default syntax theme name stored in highlight keys.
41 +
const DEFAULT_THEME: &str = "rustik";
42 +
43 +
/// Mutable read-only diff viewport state.
44 +
#[derive(Clone, Debug, Default, Eq, PartialEq)]
45 +
pub struct DiffState {
46 +
    /// First visible row in the rendered document.
47 +
    pub scroll: usize,
48 +
    /// Currently focused file or hunk.
49 +
    pub focus: Option<DiffFocus>,
50 +
    /// Collapsed file sections.
51 +
    pub collapsed_files: BTreeSet<FileId>,
52 +
}
53 +
54 +
/// Focus target inside a diff document.
55 +
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
56 +
pub enum DiffFocus {
57 +
    /// Focus a file header.
58 +
    File(FileId),
59 +
    /// Focus a hunk header.
60 +
    Hunk(HunkId),
61 +
}
62 +
63 +
/// Viewer action accepted by [`DiffViewer::apply`].
64 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
65 +
pub enum DiffAction {
66 +
    /// Scroll the viewport.
67 +
    Scroll(Scroll),
68 +
    /// Clamp scroll after a terminal resize.
69 +
    Resize,
70 +
    /// Focus the next file or hunk target.
71 +
    FocusNext,
72 +
    /// Focus the previous file or hunk target.
73 +
    FocusPrevious,
74 +
    /// Focus the next hunk target.
75 +
    NextHunk,
76 +
    /// Focus the previous hunk target.
77 +
    PreviousHunk,
78 +
    /// Toggle the focused file between collapsed and expanded states.
79 +
    ToggleFocusedFile,
80 +
    /// Collapse the focused file, or report no change if it is already collapsed.
81 +
    CollapseFocusedFile,
82 +
}
83 +
84 +
/// Result of applying a viewer action.
85 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86 +
pub enum ViewChange {
87 +
    /// The action changed viewer state.
88 +
    Changed,
89 +
    /// The action left viewer state unchanged.
90 +
    Unchanged,
91 +
}
92 +
93 +
/// Diff viewer options.
94 +
#[derive(Clone, Debug)]
95 +
pub struct DiffOptions {
96 +
    /// Number of rows after the visible viewport to request for highlighting.
97 +
    pub highlight_lookahead: usize,
98 +
    /// Optional syntax override stored in highlight requests.
99 +
    pub syntax: Option<String>,
100 +
    /// Theme name stored in highlight requests.
101 +
    pub theme: String,
102 +
}
103 +
104 +
/// Pure diff viewer that renders into a caller-owned buffer.
105 +
#[derive(Clone, Debug)]
106 +
pub struct DiffViewer {
107 +
    /// Diff document being viewed.
108 +
    document: DiffDocument,
109 +
    /// Viewer options.
110 +
    options: DiffOptions,
111 +
    /// Mutable viewport state.
112 +
    state: DiffState,
113 +
    /// Highlighted row cache.
114 +
    highlights: BTreeMap<HighlightKey, Line>,
115 +
    /// Requests already handed to a worker.
116 +
    pending_highlights: BTreeSet<HighlightKey>,
117 +
}
118 +
119 +
/// One rendered row before viewport projection.
120 +
#[derive(Clone, Debug)]
121 +
struct RenderRow {
122 +
    /// Renderable line.
123 +
    line: Line,
124 +
    /// Row role used by scrolling, focus, and highlighting.
125 +
    meta: RowMeta,
126 +
}
127 +
128 +
/// Metadata attached to one rendered row.
129 +
#[derive(Clone, Debug, Eq, PartialEq)]
130 +
enum RowMeta {
131 +
    /// Preamble row.
132 +
    Preamble,
133 +
    /// File-card top border.
134 +
    FileTop(FileId),
135 +
    /// File-card header.
136 +
    FileHeader(FileId),
137 +
    /// File-card header divider.
138 +
    FileDivider(FileId),
139 +
    /// File-card hunk divider.
140 +
    HunkDivider(FileId),
141 +
    /// Hunk header.
142 +
    HunkHeader(FileId, HunkId),
143 +
    /// Diff source row.
144 +
    DiffLine(DiffLineMeta),
145 +
    /// File-card bottom border.
146 +
    FileBottom(FileId),
147 +
}
148 +
149 +
/// Metadata for one source row.
150 +
#[derive(Clone, Debug, Eq, PartialEq)]
151 +
struct DiffLineMeta {
152 +
    /// File containing the row.
153 +
    file: FileId,
154 +
    /// Hunk containing the row.
155 +
    hunk: HunkId,
156 +
    /// Row identifier.
157 +
    row: RowId,
158 +
    /// Source side used for highlighting.
159 +
    side: DiffSide,
160 +
    /// One-based source line number.
161 +
    source_line: u32,
162 +
    /// Source text.
163 +
    text: String,
164 +
    /// Source path.
165 +
    path: Option<PathBuf>,
166 +
}
167 +
168 +
impl Default for DiffOptions {
169 +
    fn default() -> Self {
170 +
        Self {
171 +
            highlight_lookahead: DEFAULT_HIGHLIGHT_LOOKAHEAD,
172 +
            syntax: None,
173 +
            theme: DEFAULT_THEME.to_owned(),
174 +
        }
175 +
    }
176 +
}
177 +
178 +
impl DiffViewer {
179 +
    /// Creates a viewer with plain initial rendering state.
180 +
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
181 +
        Self {
182 +
            document,
183 +
            options,
184 +
            state: DiffState::default(),
185 +
            highlights: BTreeMap::new(),
186 +
            pending_highlights: BTreeSet::new(),
187 +
        }
188 +
    }
189 +
190 +
    /// Returns the viewed document.
191 +
    pub const fn document(&self) -> &DiffDocument {
192 +
        &self.document
193 +
    }
194 +
195 +
    /// Returns the viewer state.
196 +
    pub const fn state(&self) -> &DiffState {
197 +
        &self.state
198 +
    }
199 +
200 +
    /// Returns the viewer state mutably.
201 +
    pub fn state_mut(&mut self) -> &mut DiffState {
202 +
        &mut self.state
203 +
    }
204 +
205 +
    /// Renders the current frame into `buf`.
206 +
    pub fn render(&self, area: Rect, buf: &mut Buffer) {
207 +
        if area.is_empty() {
208 +
            return;
209 +
        }
210 +
        let body_cols = ScrollView::body_cols(area);
211 +
        let rows = self.render_rows(body_cols);
212 +
        let sticky =
213 +
            Self::sticky_rows(&rows, self.state.scroll, area.rows, body_cols).collect::<Vec<_>>();
214 +
        let lines = rows.into_iter().map(|row| row.line);
215 +
216 +
        ScrollView::from_lines(lines)
217 +
            .offset(self.state.scroll)
218 +
            .sticky(sticky)
219 +
            .scrollbar(Self::scrollbar_style())
220 +
            .render(area, buf);
221 +
    }
222 +
223 +
    /// Returns the number of rendered rows at a given terminal width.
224 +
    pub fn content_rows(&self, cols: usize) -> usize {
225 +
        self.render_rows(ScrollView::body_cols(Rect::new(0, 0, cols, 1)))
226 +
            .len()
227 +
    }
228 +
229 +
    /// Applies an action to the viewer state.
230 +
    pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
231 +
        let before = self.state.clone();
232 +
        let body_cols = ScrollView::body_cols(area);
233 +
        let rows = self.render_rows(body_cols);
234 +
        let body_rows = self.body_rows(&rows, self.state.scroll, area.rows);
235 +
236 +
        match action {
237 +
            DiffAction::Scroll(scroll) => {
238 +
                let mut viewport = Viewport::from_offset(self.state.scroll);
239 +
                viewport.scroll(scroll, rows.len(), body_rows);
240 +
                self.state.scroll = viewport.offset;
241 +
            }
242 +
            DiffAction::Resize => {
243 +
                let mut viewport = Viewport::from_offset(self.state.scroll);
244 +
                viewport.clamp(rows.len(), body_rows);
245 +
                self.state.scroll = viewport.offset;
246 +
            }
247 +
            DiffAction::FocusNext => self.focus_relative(&rows, body_rows, 1, FocusFilter::Any),
248 +
            DiffAction::FocusPrevious => {
249 +
                self.focus_relative(&rows, body_rows, -1, FocusFilter::Any)
250 +
            }
251 +
            DiffAction::NextHunk => self.focus_relative(&rows, body_rows, 1, FocusFilter::Hunk),
252 +
            DiffAction::PreviousHunk => {
253 +
                self.focus_relative(&rows, body_rows, -1, FocusFilter::Hunk)
254 +
            }
255 +
            DiffAction::ToggleFocusedFile => self.toggle_focused_file(),
256 +
            DiffAction::CollapseFocusedFile => self.collapse_focused_file(),
257 +
        }
258 +
        let body_rows = self.body_rows(&rows, self.state.scroll, area.rows);
259 +
        self.state.scroll = View::new(self.state.scroll, rows.len(), body_rows).offset;
260 +
261 +
        if self.state == before {
262 +
            ViewChange::Unchanged
263 +
        } else {
264 +
            ViewChange::Changed
265 +
        }
266 +
    }
267 +
268 +
    /// Returns the body height visible after subtracting any sticky header rows.
269 +
    fn body_rows(&self, rows: &[RenderRow], scroll: usize, area_rows: usize) -> usize {
270 +
        area_rows.saturating_sub(Self::sticky_row_count(rows, scroll, area_rows))
271 +
    }
272 +
273 +
    /// Returns highlight requests for visible source rows plus configured lookahead.
274 +
    pub fn visible_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
275 +
        let rows = self.render_rows(ScrollView::body_cols(area));
276 +
        let view = View::new(self.state.scroll, rows.len(), area.rows);
277 +
        let take = area.rows.saturating_add(self.options.highlight_lookahead);
278 +
        let mut requests = Vec::new();
279 +
280 +
        for row in rows.iter().skip(view.offset).take(take) {
281 +
            let RowMeta::DiffLine(meta) = &row.meta else {
282 +
                continue;
283 +
            };
284 +
            let key = HighlightKey::new(HighlightKeyInput {
285 +
                file: meta.file,
286 +
                hunk: meta.hunk,
287 +
                row: meta.row,
288 +
                side: meta.side,
289 +
                source_line: meta.source_line,
290 +
                text: &meta.text,
291 +
                syntax: self.options.syntax.as_deref(),
292 +
                theme: &self.options.theme,
293 +
            });
294 +
            if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
295 +
                continue;
296 +
            }
297 +
            self.pending_highlights.insert(key.clone());
298 +
            requests.push(HighlightRequest {
299 +
                key,
300 +
                path: meta.path.clone(),
301 +
                text: meta.text.clone(),
302 +
            });
303 +
        }
304 +
        requests
305 +
    }
306 +
307 +
    /// Merges highlighted rows and returns whether a redraw is needed.
308 +
    pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
309 +
        let mut changed = false;
310 +
        for result in results {
311 +
            self.pending_highlights.remove(&result.key);
312 +
            self.highlights.insert(result.key, result.line);
313 +
            changed = true;
314 +
        }
315 +
        changed
316 +
    }
317 +
318 +
    /// Builds all render rows for a width.
319 +
    fn render_rows(&self, cols: usize) -> Vec<RenderRow> {
320 +
        let cols = cols.max(MIN_RENDER_COLS);
321 +
        let mut rows = Vec::new();
322 +
323 +
        for line in &self.document.preamble {
324 +
            rows.push(RenderRow {
325 +
                line: Line::new(line.clone()).style(Style::default().fg(colors::rgb::DIM)),
326 +
                meta: RowMeta::Preamble,
327 +
            });
328 +
        }
329 +
        for file in &self.document.files {
330 +
            self.push_file_rows(file, cols, &mut rows);
331 +
        }
332 +
        rows
333 +
    }
334 +
335 +
    /// Adds one file card to render rows.
336 +
    fn push_file_rows(&self, file: &FileDiff, cols: usize, rows: &mut Vec<RenderRow>) {
337 +
        let border = Self::file_border(self.state.focus == Some(DiffFocus::File(file.id)));
338 +
        let collapsed = self.state.collapsed_files.contains(&file.id);
339 +
        let child_cols = cols.saturating_sub(4);
340 +
        let mut stack = VStack::default().border(Some(border)).padding(1);
341 +
        let mut metas = Vec::new();
342 +
343 +
        metas.push(RowMeta::FileTop(file.id));
344 +
        stack.push(file.header_line(child_cols));
345 +
        metas.push(RowMeta::FileHeader(file.id));
346 +
        if !collapsed && !file.hunks.is_empty() {
347 +
            stack = stack.divider_cell(Cell::new(DIVIDER, border.style()));
348 +
            metas.push(RowMeta::FileDivider(file.id));
349 +
            for (index, hunk) in file.hunks.iter().enumerate() {
350 +
                if index > 0 {
351 +
                    stack = stack.divider_cell(Cell::new(DIVIDER, border.style()));
352 +
                    metas.push(RowMeta::HunkDivider(file.id));
353 +
                }
354 +
                stack.push(hunk.header_line());
355 +
                metas.push(RowMeta::HunkHeader(file.id, hunk.id));
356 +
                for row in self.hunk_rows(file, hunk, child_cols) {
357 +
                    stack.push(row.line);
358 +
                    metas.push(row.meta);
359 +
                }
360 +
            }
361 +
        }
362 +
        metas.push(RowMeta::FileBottom(file.id));
363 +
364 +
        rows.extend(
365 +
            stack
366 +
                .lines(Constraint::tight(cols))
367 +
                .into_iter()
368 +
                .zip(metas)
369 +
                .map(|(line, meta)| RenderRow { line, meta }),
370 +
        );
371 +
    }
372 +
373 +
    /// Returns sticky file-header rows for the current offset.
374 +
    fn sticky_rows<'a>(
375 +
        rows: &'a [RenderRow],
376 +
        scroll: usize,
377 +
        visible_rows: usize,
378 +
        cols: usize,
379 +
    ) -> impl Iterator<Item = Line> + 'a {
380 +
        Self::sticky_row_start(rows, scroll, visible_rows)
381 +
            .into_iter()
382 +
            .flat_map(move |start| {
383 +
                rows.iter()
384 +
                    .skip(start)
385 +
                    .take(3)
386 +
                    .enumerate()
387 +
                    .map(move |(index, row)| {
388 +
                        if index == 2 {
389 +
                            Self::sticky_divider(cols)
390 +
                        } else {
391 +
                            row.line.clone()
392 +
                        }
393 +
                    })
394 +
            })
395 +
    }
396 +
397 +
    /// Returns the number of sticky rows for the current offset.
398 +
    fn sticky_row_count(rows: &[RenderRow], scroll: usize, visible_rows: usize) -> usize {
399 +
        Self::sticky_row_start(rows, scroll, visible_rows).map_or(0, |_| 3)
400 +
    }
401 +
402 +
    /// Returns the first sticky row index for the current offset.
403 +
    fn sticky_row_start(rows: &[RenderRow], scroll: usize, visible_rows: usize) -> Option<usize> {
404 +
        let scroll = scroll.min(rows.len().saturating_sub(visible_rows));
405 +
        if scroll == 0 {
406 +
            return None;
407 +
        }
408 +
        let file = rows.get(scroll).and_then(|row| row.meta.file())?;
409 +
        let start = rows
410 +
            .iter()
411 +
            .position(|row| row.meta == RowMeta::FileTop(file))?;
412 +
        if scroll <= start.saturating_add(2) {
413 +
            return None;
414 +
        }
415 +
        Some(start)
416 +
    }
417 +
418 +
    /// Focuses a target relative to the current focus.
419 +
    fn focus_relative(
420 +
        &mut self,
421 +
        rows: &[RenderRow],
422 +
        visible_rows: usize,
423 +
        delta: isize,
424 +
        filter: FocusFilter,
425 +
    ) {
426 +
        let target_count = filter.targets(rows).count();
427 +
        if target_count == 0 {
428 +
            return;
429 +
        }
430 +
        let current = self.state.focus.and_then(|focus| {
431 +
            filter
432 +
                .targets(rows)
433 +
                .position(|target| target.focus == focus)
434 +
        });
435 +
        let next = match (current, delta.is_negative()) {
436 +
            (Some(index), true) => index.saturating_sub(1),
437 +
            (Some(index), false) => index.saturating_add(1).min(target_count - 1),
438 +
            (None, true) => target_count - 1,
439 +
            (None, false) => 0,
440 +
        };
441 +
        let Some(target) = filter.targets(rows).nth(next) else {
442 +
            return;
443 +
        };
444 +
445 +
        self.state.focus = Some(target.focus);
446 +
        let mut viewport = Viewport::from_offset(self.state.scroll);
447 +
448 +
        viewport.scroll_to_row(target.row, rows.len(), visible_rows, Placement::Minimal);
449 +
        self.state.scroll = viewport.offset;
450 +
    }
451 +
452 +
    /// Toggles the file containing the current focus.
453 +
    fn toggle_focused_file(&mut self) {
454 +
        let Some(file) = self.focused_file() else {
455 +
            return;
456 +
        };
457 +
        if !self.state.collapsed_files.remove(&file) {
458 +
            self.state.collapsed_files.insert(file);
459 +
            self.state.focus = Some(DiffFocus::File(file));
460 +
        }
461 +
    }
462 +
463 +
    /// Collapses the file containing the current focus.
464 +
    fn collapse_focused_file(&mut self) {
465 +
        let Some(file) = self.focused_file() else {
466 +
            return;
467 +
        };
468 +
        self.state.collapsed_files.insert(file);
469 +
        self.state.focus = Some(DiffFocus::File(file));
470 +
    }
471 +
472 +
    /// Returns the file containing the current focus.
473 +
    fn focused_file(&self) -> Option<FileId> {
474 +
        match self.state.focus? {
475 +
            DiffFocus::File(file) => Some(file),
476 +
            DiffFocus::Hunk(hunk) => self
477 +
                .document
478 +
                .files
479 +
                .iter()
480 +
                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
481 +
                .map(|file| file.id),
482 +
        }
483 +
    }
484 +
485 +
    /// Returns hunk table rows.
486 +
    fn hunk_rows(
487 +
        &self,
488 +
        file: &FileDiff,
489 +
        hunk: &crate::Hunk,
490 +
        inner: usize,
491 +
    ) -> impl Iterator<Item = RenderRow> {
492 +
        let mut table = Table::new(TableOptions {
493 +
            spacing: 0,
494 +
            ..TableOptions::default()
495 +
        });
496 +
        let mut metas = Vec::with_capacity(hunk.lines.len());
497 +
        let mut old_line = hunk.header.old_line_no;
498 +
        let mut new_line = hunk.header.new_line_no;
499 +
500 +
        for line in &hunk.lines {
501 +
            let meta = self.push_hunk_row(
502 +
                &mut table,
503 +
                file,
504 +
                hunk.id,
505 +
                line,
506 +
                &mut old_line,
507 +
                &mut new_line,
508 +
            );
509 +
            metas.push(meta);
510 +
        }
511 +
512 +
        table
513 +
            .lines(Constraint::tight(inner))
514 +
            .into_iter()
515 +
            .zip(metas)
516 +
            .map(|(line, meta)| RenderRow { line, meta })
517 +
    }
518 +
519 +
    /// Pushes a single hunk row onto the table and returns its metadata.
520 +
    fn push_hunk_row(
521 +
        &self,
522 +
        table: &mut Table<4, Line>,
523 +
        file: &FileDiff,
524 +
        hunk: HunkId,
525 +
        line: &DiffLine,
526 +
        old_line: &mut u32,
527 +
        new_line: &mut u32,
528 +
    ) -> RowMeta {
529 +
        match line.kind {
530 +
            DiffLineKind::Addition => {
531 +
                let source_line = *new_line;
532 +
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::New, source_line);
533 +
                let row = [
534 +
                    Self::blank_number(colors::rgb::POSITIVE),
535 +
                    Self::number_cell(
536 +
                        source_line,
537 +
                        colors::rgb::POSITIVE_LIGHT,
538 +
                        colors::rgb::POSITIVE,
539 +
                    ),
540 +
                    Self::marker_cell(" + ", colors::rgb::POSITIVE_LIGHT),
541 +
                    self.highlighted_or_plain(&meta),
542 +
                ];
543 +
                table.push_styled(row, Style::default().bg(colors::rgb::POSITIVE_DARK));
544 +
                *new_line = new_line.saturating_add(1);
545 +
                RowMeta::DiffLine(meta)
546 +
            }
547 +
            DiffLineKind::Deletion => {
548 +
                let source_line = *old_line;
549 +
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::Old, source_line);
550 +
                let row = [
551 +
                    Self::number_cell(
552 +
                        source_line,
553 +
                        colors::rgb::NEGATIVE_LIGHT,
554 +
                        colors::rgb::NEGATIVE,
555 +
                    ),
556 +
                    Self::blank_number(colors::rgb::NEGATIVE),
557 +
                    Self::marker_cell(" - ", colors::rgb::NEGATIVE_LIGHT),
558 +
                    self.highlighted_or_plain(&meta),
559 +
                ];
560 +
                table.push_styled(row, Style::default().bg(colors::rgb::NEGATIVE_DARK).dim());
561 +
                *old_line = old_line.saturating_add(1);
562 +
                RowMeta::DiffLine(meta)
563 +
            }
564 +
            DiffLineKind::Context => {
565 +
                let source_line = *new_line;
566 +
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::New, source_line);
567 +
                let row = [
568 +
                    Self::number_cell(*old_line, colors::rgb::DIM, colors::rgb::FAINT),
569 +
                    Self::number_cell(source_line, colors::rgb::DIM, colors::rgb::FAINT),
570 +
                    Self::marker_cell("   ", Color::Unset),
571 +
                    self.highlighted_or_plain(&meta),
572 +
                ];
573 +
                table.push(row);
574 +
                *old_line = old_line.saturating_add(1);
575 +
                *new_line = new_line.saturating_add(1);
576 +
                RowMeta::DiffLine(meta)
577 +
            }
578 +
            DiffLineKind::NoNewline => {
579 +
                let row = [
580 +
                    Line::blank().padded(LINE_NUMBER_WIDTH),
581 +
                    Line::blank().padded(LINE_NUMBER_WIDTH),
582 +
                    Self::marker_cell("   ", Color::Unset),
583 +
                    Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
584 +
                ];
585 +
                table.push(row);
586 +
                RowMeta::DiffLine(DiffLineMeta::new(
587 +
                    file,
588 +
                    hunk,
589 +
                    line,
590 +
                    DiffSide::New,
591 +
                    *new_line,
592 +
                ))
593 +
            }
594 +
        }
595 +
    }
596 +
597 +
    /// Returns a highlighted line from cache or plain text when no result has arrived.
598 +
    fn highlighted_or_plain(&self, meta: &DiffLineMeta) -> Line {
599 +
        let key = HighlightKey::new(HighlightKeyInput {
600 +
            file: meta.file,
601 +
            hunk: meta.hunk,
602 +
            row: meta.row,
603 +
            side: meta.side,
604 +
            source_line: meta.source_line,
605 +
            text: &meta.text,
606 +
            syntax: self.options.syntax.as_deref(),
607 +
            theme: &self.options.theme,
608 +
        });
609 +
        self.highlights
610 +
            .get(&key)
611 +
            .cloned()
612 +
            .unwrap_or_else(|| Line::new(meta.text.clone()))
613 +
    }
614 +
615 +
    /// Returns a line-number cell.
616 +
    fn number_cell(value: u32, foreground: Color, background: Color) -> Line {
617 +
        Line::new(Label::new(&value.to_string()).fg(foreground).bg(background))
618 +
            .padded(LINE_NUMBER_WIDTH)
619 +
    }
620 +
621 +
    /// Returns a blank line-number cell.
622 +
    fn blank_number(background: Color) -> Line {
623 +
        Line::new(Label::space().bg(background)).padded(LINE_NUMBER_WIDTH)
624 +
    }
625 +
626 +
    /// Returns a marker cell.
627 +
    fn marker_cell(marker: &str, foreground: Color) -> Line {
628 +
        Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH)
629 +
    }
630 +
631 +
    /// Returns the border for a file card.
632 +
    fn file_border(focused: bool) -> tui::Border {
633 +
        if focused {
634 +
            tui::Border::new(colors::fixed::DIM)
635 +
        } else {
636 +
            tui::Border::new(colors::FAINT)
637 +
        }
638 +
    }
639 +
640 +
    /// Returns a sticky divider line that matches a bordered file card's width.
641 +
    fn sticky_divider(cols: usize) -> Line {
642 +
        tui::Border::new(colors::FAINT).divider(cols.saturating_sub(2), STICKY_DIVIDER)
643 +
    }
644 +
645 +
    /// Returns the diff scrollbar style.
646 +
    fn scrollbar_style() -> ScrollbarStyle {
647 +
        ScrollbarStyle::new(
648 +
            Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
649 +
            Cell::new(SCROLLBAR_THUMB, Style::default().fg(colors::fixed::DIM)),
650 +
        )
651 +
    }
652 +
}
653 +
654 +
impl Widget for DiffViewer {
655 +
    fn size(&self, parent: Constraint) -> Size {
656 +
        let cols = if parent.max.cols == usize::MAX {
657 +
            MIN_RENDER_COLS
658 +
        } else {
659 +
            parent.max.cols
660 +
        };
661 +
662 +
        Size::new(cols, self.content_rows(cols)).constrain(parent)
663 +
    }
664 +
665 +
    fn render(&self, area: Rect, buf: &mut Buffer) {
666 +
        Self::render(self, area, buf);
667 +
    }
668 +
}
669 +
670 +
impl RowMeta {
671 +
    /// Returns the containing file for row kinds that belong to a file card.
672 +
    fn file(&self) -> Option<FileId> {
673 +
        match self {
674 +
            Self::FileTop(file)
675 +
            | Self::FileHeader(file)
676 +
            | Self::FileDivider(file)
677 +
            | Self::HunkDivider(file)
678 +
            | Self::HunkHeader(file, _)
679 +
            | Self::FileBottom(file) => Some(*file),
680 +
            Self::DiffLine(meta) => Some(meta.file),
681 +
            Self::Preamble => None,
682 +
        }
683 +
    }
684 +
}
685 +
686 +
/// Focus target with its rendered row.
687 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
688 +
struct FocusTarget {
689 +
    /// Focus value.
690 +
    focus: DiffFocus,
691 +
    /// Rendered row index.
692 +
    row: usize,
693 +
}
694 +
695 +
/// Focus target filter.
696 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
697 +
enum FocusFilter {
698 +
    /// File and hunk targets.
699 +
    Any,
700 +
    /// Hunk targets only.
701 +
    Hunk,
702 +
}
703 +
704 +
impl FocusFilter {
705 +
    /// Returns focusable targets from render rows.
706 +
    fn targets<'a>(self, rows: &'a [RenderRow]) -> impl Iterator<Item = FocusTarget> + 'a {
707 +
        rows.iter()
708 +
            .enumerate()
709 +
            .filter_map(move |(row, render_row)| match render_row.meta {
710 +
                RowMeta::FileHeader(file) if self == Self::Any => Some(FocusTarget {
711 +
                    focus: DiffFocus::File(file),
712 +
                    row,
713 +
                }),
714 +
                RowMeta::HunkHeader(_, hunk) => Some(FocusTarget {
715 +
                    focus: DiffFocus::Hunk(hunk),
716 +
                    row,
717 +
                }),
718 +
                _ => None,
719 +
            })
720 +
    }
721 +
}
722 +
723 +
impl FileDiff {
724 +
    /// Returns the source path for a file side.
725 +
    fn source_path(&self, side: DiffSide) -> Option<PathBuf> {
726 +
        match side {
727 +
            DiffSide::Old => self
728 +
                .header
729 +
                .old_path
730 +
                .clone()
731 +
                .or_else(|| self.header.new_path.clone()),
732 +
            DiffSide::New => self
733 +
                .header
734 +
                .new_path
735 +
                .clone()
736 +
                .or_else(|| self.header.old_path.clone()),
737 +
        }
738 +
    }
739 +
740 +
    /// Returns a file header line.
741 +
    fn header_line(&self, cols: usize) -> Line {
742 +
        let mut left = Line::blank();
743 +
        left.push(Label::new(FILE_MARKER).fg(colors::fixed::DIM));
744 +
        left.push(Label::space());
745 +
        left = left.extend(self.path_line());
746 +
747 +
        if let Some(badge) = self.badge() {
748 +
            left.push(Label::space());
749 +
            left.push(badge);
750 +
        }
751 +
        let mut header = HStack::default().child(left).spacer();
752 +
        let stats = self.stats();
753 +
754 +
        if let Some(side) = Self::diffstat_line(stats.additions, stats.deletions) {
755 +
            header = header.child(side);
756 +
        }
757 +
        header.to_line(Constraint::tight(cols))
758 +
    }
759 +
760 +
    /// Returns the file path display line.
761 +
    fn path_line(&self) -> Line {
762 +
        match self.header.kind {
763 +
            FileKind::Renamed | FileKind::Copied => Line::spaced([
764 +
                Label::from(Self::display_path(self.header.old_path.as_ref())),
765 +
                Label::from(RENAME_ARROW),
766 +
                Label::from(Self::display_path(self.header.new_path.as_ref())),
767 +
            ]),
768 +
            _ => Line::new(Self::display_path(self.header.display_path())),
769 +
        }
770 +
    }
771 +
772 +
    /// Returns an additions-first diffstat line.
773 +
    fn diffstat_line(additions: usize, deletions: usize) -> Option<Line> {
774 +
        if additions == 0 && deletions == 0 {
775 +
            return None;
776 +
        }
777 +
        let mut line = Line::blank();
778 +
        if additions > 0 {
779 +
            line.push(Label::new(&format!("+{additions}")).fg(colors::rgb::POSITIVE_LIGHT));
780 +
        }
781 +
        if deletions > 0 {
782 +
            if additions > 0 {
783 +
                line.push(Label::space());
784 +
            }
785 +
            line.push(Label::new(&format!("-{deletions}")).fg(colors::rgb::NEGATIVE_LIGHT));
786 +
        }
787 +
        Some(line)
788 +
    }
789 +
790 +
    /// Returns a file-kind badge.
791 +
    fn badge(&self) -> Option<Label> {
792 +
        match self.header.kind {
793 +
            FileKind::Added => Some(Self::change_badge(
794 +
                "created",
795 +
                colors::rgb::POSITIVE_LIGHT,
796 +
                colors::rgb::POSITIVE_DARK,
797 +
            )),
798 +
            FileKind::Deleted => Some(Self::change_badge(
799 +
                "deleted",
800 +
                colors::rgb::NEGATIVE_LIGHT,
801 +
                colors::rgb::NEGATIVE_DARK,
802 +
            )),
803 +
            FileKind::Renamed => Some(Self::change_badge("moved", Color::Blue, Color::Fixed(236))),
804 +
            FileKind::Copied => Some(Self::change_badge("copied", Color::Blue, Color::Fixed(236))),
805 +
            FileKind::ModeChanged => Some(Self::change_badge(
806 +
                "mode changed",
807 +
                Color::Blue,
808 +
                Color::Fixed(236),
809 +
            )),
810 +
            FileKind::Binary => Some(Self::change_badge(
811 +
                "binary",
812 +
                Color::Yellow,
813 +
                Color::Fixed(236),
814 +
            )),
815 +
            FileKind::Modified => None,
816 +
        }
817 +
    }
818 +
819 +
    /// Returns a small colored badge.
820 +
    fn change_badge(text: &str, foreground: Color, background: Color) -> Label {
821 +
        Label::new(&format!(" {text} "))
822 +
            .fg(foreground)
823 +
            .bg(background)
824 +
    }
825 +
826 +
    /// Returns a display path or placeholder.
827 +
    fn display_path(path: Option<&PathBuf>) -> String {
828 +
        path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
829 +
    }
830 +
}
831 +
832 +
impl crate::Hunk {
833 +
    /// Returns a hunk header line.
834 +
    fn header_line(&self) -> Line {
835 +
        Line::spaced([
836 +
            Label::new(&format!("hunk {}", *self.id + 1)).fg(colors::fixed::DIM),
837 +
            Label::new(&self.header_text()).fg(colors::fixed::FAINT),
838 +
        ])
839 +
    }
840 +
841 +
    /// Returns the stable hunk header prefix and trailing text.
842 +
    fn header_text(&self) -> String {
843 +
        let header = &self.header;
844 +
        let prefix = format!(
845 +
            "@@ -{},{} +{},{} @@",
846 +
            header.old_line_no, header.old_size, header.new_line_no, header.new_size
847 +
        );
848 +
        if header.text.is_empty() {
849 +
            prefix
850 +
        } else {
851 +
            format!("{prefix} {}", header.text)
852 +
        }
853 +
    }
854 +
}
855 +
856 +
impl DiffLineMeta {
857 +
    /// Creates metadata for a source row.
858 +
    fn new(
859 +
        file: &FileDiff,
860 +
        hunk: HunkId,
861 +
        line: &DiffLine,
862 +
        side: DiffSide,
863 +
        source_line: u32,
864 +
    ) -> Self {
865 +
        Self {
866 +
            file: file.id,
867 +
            hunk,
868 +
            row: line.id,
869 +
            side,
870 +
            source_line,
871 +
            text: line.text.clone(),
872 +
            path: file.source_path(side),
873 +
        }
874 +
    }
875 +
}
876 +
877 +
#[cfg(test)]
878 +
#[allow(clippy::expect_used)]
879 +
mod tests {
880 +
    use super::*;
881 +
    use crate::Decode;
882 +
    use crate::DiffDocument;
883 +
884 +
    fn sample_viewer() -> DiffViewer {
885 +
        let document = DiffDocument::decode_str(
886 +
            "\
887 +
a.rs +0 -0
crates/diff/src/rustik.json added +28 -0
1 +
{
2 +
  "name": "rustik",
3 +
  "settings": [
4 +
    {
5 +
      "settings": {
6 +
        "foreground": "#c9d1d9"
7 +
      }
8 +
    },
9 +
    {
10 +
      "scope": "string",
11 +
      "settings": {
12 +
        "foreground": "#a5d6ff"
13 +
      }
14 +
    },
15 +
    {
16 +
      "scope": "constant",
17 +
      "settings": {
18 +
        "foreground": "#79c0ff"
19 +
      }
20 +
    },
21 +
    {
22 +
      "scope": "punctuation",
23 +
      "settings": {
24 +
        "foreground": "#8b949e"
25 +
      }
26 +
    }
27 +
  ]
28 +
}
src/lib.rs +5 -1
1 -
//! Umbrella crate that re-exports the `rustik-tui` facade crate.
1 +
//! Umbrella crate that re-exports Rustik facade crates.
2 2
//!
3 3
//! Use `rustik::tui::*` for the full facade API. Enable `widgets` to forward
4 4
//! to `rustik-tui`’s optional `widgets` feature, or `highlight` to re-export
5 5
//! the `rustik-highlight` parser/highlighter crate.
6 6
//!
9 9
#![warn(clippy::unwrap_used)]
10 10
11 11
/// Re-export of the facade crate.
12 12
pub use rustik_tui as tui;
13 13
14 +
/// Re-export of the unified diff parser and renderer crate.
15 +
#[cfg(feature = "diff")]
16 +
pub use rustik_diff as diff;
17 +
14 18
/// Re-export of the TextMate grammar parser and highlighter crate.
15 19
#[cfg(feature = "highlight")]
16 20
pub use rustik_highlight as highlight;