Skip to main content

grit_lib/diff/
text.rs

1//! Unified diff text for two in-memory sides, configured by one [`UnifiedDiffOptions`].
2//!
3//! [`unified_diff`] renders the same bytes as `git diff --no-index` from the `---` line on, and
4//! [`line_change_counts`] counts the `+` / `-` lines of that patch without rendering it.
5
6use crate::quote_path::format_diff_path_with_prefix;
7use crate::userdiff::FuncnameMatcher;
8
9use super::core::{
10    blank_line_ignorable, compacted_line_ops_for_options, count_line_changes_with_options,
11    extract_function_context, imara_unified_hunk_slices, patience_compacted_line_ops,
12    unified_body_from_ops, unified_hunk_body_for_diff_options,
13};
14use super::detail::LineStat;
15use super::options::{DiffAlgorithm, DiffOptions};
16use super::unified_emit::{LineSide, UnifiedEmitOptions};
17use super::WhitespaceMode;
18
19/// Marker line Git writes after a patch line whose source line has no trailing newline.
20const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file\n";
21
22/// One side's `---` / `+++` header label in [`UnifiedDiffOptions`].
23#[non_exhaustive]
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum DiffLabel<'a> {
26    /// `/dev/null`: this side does not exist (an added or deleted file).
27    DevNull,
28    /// `prefix` followed by `path` (for example `a/` and `src/lib.rs`).
29    ///
30    /// The whole label is C-quoted when the path needs it (see [`PathQuoting`]), and a tab is
31    /// appended when the path contains a space, exactly as Git writes it.
32    Path {
33        /// Side prefix, usually `a/` or `b/`; empty for `--no-prefix` output.
34        prefix: &'a str,
35        /// Repository-relative or filesystem path of this side.
36        path: &'a str,
37    },
38    /// Written as given, with no quoting.
39    Verbatim(&'a str),
40}
41
42/// How [`DiffLabel::Path`] labels quote unusual path bytes (Git's `core.quotePath`).
43#[non_exhaustive]
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum PathQuoting {
46    /// Quote control characters, `"`, `\` and every byte above `0x7f` (`core.quotePath=true`,
47    /// Git's default).
48    #[default]
49    EscapeNonAscii,
50    /// Quote control characters, `"` and `\`, but keep non-ASCII bytes as they are
51    /// (`core.quotePath=false`).
52    KeepNonAscii,
53}
54
55/// Whether patches carry Git's `\ No newline at end of file` marker lines.
56#[non_exhaustive]
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum NoNewlineMarker {
59    /// Write the marker after each patch line whose source line lacks a newline (Git's output).
60    #[default]
61    Emit,
62    /// Leave the markers out, for display that does not need to round-trip through `git apply`.
63    Omit,
64}
65
66/// Git's indent heuristic for placing a change whose boundaries are ambiguous.
67#[non_exhaustive]
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum IndentHeuristic {
70    /// Slide ambiguous change groups to the most readable position (Git's default).
71    #[default]
72    Enabled,
73    /// Keep plain change compaction (`--no-indent-heuristic`).
74    Disabled,
75}
76
77/// How far each hunk reaches beyond its changed lines.
78#[non_exhaustive]
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub enum HunkExtent {
81    /// [`UnifiedDiffOptions::context_lines`] unchanged lines on each side (Git `-U`).
82    #[default]
83    Context,
84    /// The whole enclosing function, found with the function-name rules (Git `-W`).
85    Function,
86}
87
88/// Everything that shapes a unified diff of two text sides.
89///
90/// [`Default`] matches `git diff --no-index` with no options, except that no `---` / `+++`
91/// labels are set, so the output starts at the first `@@` hunk header. Set labels with
92/// [`with_paths`](Self::with_paths) or [`with_labels`](Self::with_labels).
93///
94/// # Examples
95///
96/// ```
97/// use grit_lib::diff::{unified_diff, DiffAlgorithm, UnifiedDiffOptions};
98///
99/// let options = UnifiedDiffOptions::new()
100///     .with_paths("greeting.txt", "greeting.txt")
101///     .with_algorithm(DiffAlgorithm::Histogram)
102///     .with_context_lines(1);
103/// let patch = unified_diff("hello\nworld\n", "hello\nthere\n", &options);
104/// assert_eq!(
105///     patch,
106///     "--- a/greeting.txt\n+++ b/greeting.txt\n@@ -1,2 +1,2 @@\n hello\n-world\n+there\n"
107/// );
108/// ```
109#[non_exhaustive]
110#[derive(Debug, Clone)]
111pub struct UnifiedDiffOptions<'a> {
112    /// Label for the `---` line; `None` omits the line.
113    pub old_label: Option<DiffLabel<'a>>,
114    /// Label for the `+++` line; `None` omits the line.
115    pub new_label: Option<DiffLabel<'a>>,
116    /// Quoting for [`DiffLabel::Path`] labels.
117    pub path_quoting: PathQuoting,
118    /// Unchanged lines kept around each change (Git `-U`, default 3).
119    pub context_lines: usize,
120    /// Extra unchanged lines allowed between two changes before they split into separate hunks
121    /// (Git `--inter-hunk-context`, default 0).
122    pub inter_hunk_context: usize,
123    /// Function-name rules for the text after each `@@ … @@` header and for
124    /// [`HunkExtent::Function`]. `None` uses Git's default rule: the
125    /// nearest earlier line that starts with a letter, `_` or `$`.
126    pub funcname: Option<&'a FuncnameMatcher>,
127    /// Line alignment algorithm. Ignored when [`anchors`](Self::anchors) is non-empty, because
128    /// anchored diffs always use patience alignment, as in Git.
129    pub algorithm: DiffAlgorithm,
130    /// Placement of changes whose boundaries are ambiguous.
131    pub indent_heuristic: IndentHeuristic,
132    /// How far hunks reach: context lines, or the whole enclosing function (`-W`).
133    pub extent: HunkExtent,
134    /// `--anchored` prefixes: a line that starts with one of them and occurs exactly once on
135    /// each side is kept as unchanged context instead of appearing as a move.
136    pub anchors: Vec<String>,
137    /// Whitespace rules for comparing lines (`-w`, `-b`, `--ignore-space-at-eol`,
138    /// `--ignore-blank-lines`). Patch lines always show the original text.
139    pub whitespace: WhitespaceMode,
140    /// Whether `\ No newline at end of file` markers are written.
141    pub no_newline_marker: NoNewlineMarker,
142}
143
144impl Default for UnifiedDiffOptions<'_> {
145    fn default() -> Self {
146        Self {
147            old_label: None,
148            new_label: None,
149            path_quoting: PathQuoting::default(),
150            context_lines: 3,
151            inter_hunk_context: 0,
152            funcname: None,
153            algorithm: DiffAlgorithm::default(),
154            indent_heuristic: IndentHeuristic::default(),
155            extent: HunkExtent::default(),
156            anchors: Vec::new(),
157            whitespace: WhitespaceMode::default(),
158            no_newline_marker: NoNewlineMarker::default(),
159        }
160    }
161}
162
163impl<'a> UnifiedDiffOptions<'a> {
164    /// Same as [`Default::default`]: Git's defaults with no header labels.
165    #[must_use]
166    pub fn new() -> Self {
167        Self::default()
168    }
169
170    /// Label the sides `a/<old_path>` and `b/<new_path>`, as `git diff` does.
171    #[must_use]
172    pub fn with_paths(self, old_path: &'a str, new_path: &'a str) -> Self {
173        self.with_labels(
174            DiffLabel::Path {
175                prefix: "a/",
176                path: old_path,
177            },
178            DiffLabel::Path {
179                prefix: "b/",
180                path: new_path,
181            },
182        )
183    }
184
185    /// Set both `---` / `+++` labels.
186    #[must_use]
187    pub fn with_labels(mut self, old: DiffLabel<'a>, new: DiffLabel<'a>) -> Self {
188        self.old_label = Some(old);
189        self.new_label = Some(new);
190        self
191    }
192
193    /// Set how path labels quote unusual bytes.
194    #[must_use]
195    pub fn with_path_quoting(mut self, path_quoting: PathQuoting) -> Self {
196        self.path_quoting = path_quoting;
197        self
198    }
199
200    /// Set the context line count (`-U`).
201    #[must_use]
202    pub fn with_context_lines(mut self, context_lines: usize) -> Self {
203        self.context_lines = context_lines;
204        self
205    }
206
207    /// Set the inter-hunk context (`--inter-hunk-context`).
208    #[must_use]
209    pub fn with_inter_hunk_context(mut self, inter_hunk_context: usize) -> Self {
210        self.inter_hunk_context = inter_hunk_context;
211        self
212    }
213
214    /// Use `matcher` for hunk-header function names and function context.
215    #[must_use]
216    pub fn with_funcname(mut self, matcher: &'a FuncnameMatcher) -> Self {
217        self.funcname = Some(matcher);
218        self
219    }
220
221    /// Set the line alignment algorithm.
222    #[must_use]
223    pub fn with_algorithm(mut self, algorithm: DiffAlgorithm) -> Self {
224        self.algorithm = algorithm;
225        self
226    }
227
228    /// Set the indent heuristic.
229    #[must_use]
230    pub fn with_indent_heuristic(mut self, indent_heuristic: IndentHeuristic) -> Self {
231        self.indent_heuristic = indent_heuristic;
232        self
233    }
234
235    /// Set how far hunks reach (`HunkExtent::Function` is Git's `-W`).
236    #[must_use]
237    pub fn with_extent(mut self, extent: HunkExtent) -> Self {
238        self.extent = extent;
239        self
240    }
241
242    /// Replace the `--anchored` prefixes.
243    #[must_use]
244    pub fn with_anchors<I, S>(mut self, anchors: I) -> Self
245    where
246        I: IntoIterator<Item = S>,
247        S: Into<String>,
248    {
249        self.anchors = anchors.into_iter().map(Into::into).collect();
250        self
251    }
252
253    /// Set the whitespace comparison rules.
254    #[must_use]
255    pub fn with_whitespace(mut self, whitespace: WhitespaceMode) -> Self {
256        self.whitespace = whitespace;
257        self
258    }
259
260    /// Choose whether `\ No newline at end of file` markers are written.
261    #[must_use]
262    pub fn with_no_newline_marker(mut self, marker: NoNewlineMarker) -> Self {
263        self.no_newline_marker = marker;
264        self
265    }
266
267    /// The line-alignment subset, in the form the tree and structured diff engines take.
268    fn line_options(&self) -> DiffOptions {
269        DiffOptions {
270            context_lines: self.context_lines,
271            inter_hunk_context: self.inter_hunk_context,
272            algorithm: self.algorithm,
273            indent_heuristic: self.indent_heuristic == IndentHeuristic::Enabled,
274            whitespace: self.whitespace,
275            function_context: self.extent == HunkExtent::Function,
276            ..DiffOptions::default()
277        }
278    }
279
280    fn emit_options(&self) -> UnifiedEmitOptions {
281        UnifiedEmitOptions {
282            context_lines: self.context_lines,
283            inter_hunk_context: self.inter_hunk_context,
284            function_context: self.extent == HunkExtent::Function,
285        }
286    }
287
288    /// Whether counts must come from rendered hunks: anchors change the alignment, and
289    /// `--ignore-blank-lines` drops changes only when hunks are emitted.
290    fn needs_rendered_counts(&self) -> bool {
291        !self.anchors.is_empty() || self.whitespace.ignore_blank_lines
292    }
293}
294
295/// Carries the line settings of a repository diff (context, inter-hunk context, algorithm,
296/// indent heuristic, whitespace rules and `-W`) over to a text diff. Labels, function-name
297/// rules and anchors stay at their defaults.
298impl From<&DiffOptions> for UnifiedDiffOptions<'_> {
299    fn from(options: &DiffOptions) -> Self {
300        Self {
301            context_lines: options.context_lines,
302            inter_hunk_context: options.inter_hunk_context,
303            algorithm: options.algorithm,
304            indent_heuristic: if options.indent_heuristic {
305                IndentHeuristic::Enabled
306            } else {
307                IndentHeuristic::Disabled
308            },
309            extent: if options.function_context {
310                HunkExtent::Function
311            } else {
312                HunkExtent::Context
313            },
314            whitespace: options.whitespace,
315            ..Self::default()
316        }
317    }
318}
319
320/// Unified diff of two text sides.
321///
322/// Writes the `---` / `+++` lines for the labels that are set, then one `@@` hunk per group of
323/// changes, with function names after the hunk headers. The bytes match `git diff --no-index`
324/// with the same options from the `---` line on.
325///
326/// Returns an empty string when no hunk survives: the sides are equal, or every difference is
327/// ignored by [`UnifiedDiffOptions::whitespace`].
328///
329/// # Examples
330///
331/// ```
332/// use grit_lib::diff::{unified_diff, UnifiedDiffOptions, WhitespaceMode};
333///
334/// let options = UnifiedDiffOptions::new().with_whitespace(WhitespaceMode::ignore_space_change());
335/// assert!(unified_diff("a  b\n", "a b\n", &options).is_empty());
336/// assert_eq!(
337///     unified_diff("one\n", "one\ntwo", &UnifiedDiffOptions::new()),
338///     "@@ -1 +1,2 @@\n one\n+two\n\\ No newline at end of file\n"
339/// );
340/// ```
341#[must_use]
342pub fn unified_diff(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> String {
343    let body = hunk_body(old, new, options);
344    if body.is_empty() {
345        return String::new();
346    }
347    let mut out = String::with_capacity(body.len() + 128);
348    if let Some(label) = &options.old_label {
349        push_label_line(&mut out, "--- ", label, options.path_quoting);
350    }
351    if let Some(label) = &options.new_label {
352        push_label_line(&mut out, "+++ ", label, options.path_quoting);
353    }
354    push_hunks_with_funcnames(&mut out, &body, old, options.funcname);
355    if options.no_newline_marker == NoNewlineMarker::Omit {
356        // Patch lines always carry a ` `, `+` or `-` prefix, so only a whole line equal to the
357        // marker is an annotation; source text that reads like the marker must survive.
358        out = out
359            .split_inclusive('\n')
360            .filter(|line| *line != NO_NEWLINE_MARKER)
361            .collect();
362    }
363    out
364}
365
366/// Lines added and removed by the patch [`unified_diff`] renders for the same options.
367///
368/// Labels, function-name rules and markers do not change the counts. For the common case (no
369/// anchors and no `--ignore-blank-lines`) no patch text is built.
370///
371/// # Examples
372///
373/// ```
374/// use grit_lib::diff::{line_change_counts, UnifiedDiffOptions};
375///
376/// let stat = line_change_counts("a\nb\nc\n", "a\nB\nc\nd\n", &UnifiedDiffOptions::new());
377/// assert_eq!((stat.insertions, stat.deletions), (2, 1));
378/// ```
379#[must_use]
380pub fn line_change_counts(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> LineStat {
381    if !options.needs_rendered_counts() {
382        let (insertions, deletions) =
383            count_line_changes_with_options(old, new, &options.line_options());
384        return LineStat {
385            insertions,
386            deletions,
387        };
388    }
389    hunk_body(old, new, options)
390        .lines()
391        .fold(LineStat::default(), |mut stat, line| {
392            match line.as_bytes().first() {
393                Some(b'+') => stat.insertions += 1,
394                Some(b'-') => stat.deletions += 1,
395                _ => {}
396            }
397            stat
398        })
399}
400
401/// Hunks only (`@@` headers without function names), with no-newline markers.
402fn hunk_body(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> String {
403    if options.anchors.is_empty() && options.extent == HunkExtent::Context {
404        return unified_hunk_body_for_diff_options(old, new, &options.line_options());
405    }
406    let before = LineSide::from_text(old);
407    let after = LineSide::from_text(new);
408    let ops = if options.anchors.is_empty() {
409        compacted_line_ops_for_options(old, new, &options.line_options())
410    } else {
411        let anchored: Vec<bool> = after
412            .lines()
413            .map(|line| {
414                options
415                    .anchors
416                    .iter()
417                    .any(|anchor| line.body.starts_with(anchor.as_str()))
418            })
419            .collect();
420        patience_compacted_line_ops(
421            &before,
422            &after,
423            options.indent_heuristic == IndentHeuristic::Enabled,
424            options.whitespace,
425            &anchored,
426        )
427    };
428    let ws = options.whitespace;
429    unified_body_from_ops(
430        &before,
431        &after,
432        &ops,
433        ws,
434        options.emit_options(),
435        options.funcname,
436        ws.ignore_blank_lines.then(|| blank_line_ignorable(ws)),
437    )
438}
439
440fn push_label_line(out: &mut String, lead: &str, label: &DiffLabel<'_>, quoting: PathQuoting) {
441    out.push_str(lead);
442    match *label {
443        DiffLabel::DevNull => out.push_str("/dev/null"),
444        DiffLabel::Verbatim(text) => out.push_str(text),
445        DiffLabel::Path { prefix, path } => {
446            let quote_non_ascii = quoting == PathQuoting::EscapeNonAscii;
447            out.push_str(&format_diff_path_with_prefix(prefix, path, quote_non_ascii));
448            if path.contains(' ') {
449                out.push('\t');
450            }
451        }
452    }
453    out.push('\n');
454}
455
456/// Append `body`'s hunks, adding the enclosing function name after each `@@ … @@` header.
457fn push_hunks_with_funcnames(
458    out: &mut String,
459    body: &str,
460    old: &str,
461    funcname: Option<&FuncnameMatcher>,
462) {
463    let old_lines: Vec<&str> = old.lines().collect();
464    for hunk in imara_unified_hunk_slices(body) {
465        let Some((header, rest)) = hunk.split_once('\n') else {
466            out.push_str(hunk);
467            continue;
468        };
469        out.push_str(header);
470        if let Some(name) = extract_function_context(header, &old_lines, funcname, None) {
471            out.push(' ');
472            out.push_str(&name);
473        }
474        out.push('\n');
475        out.push_str(rest);
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482
483    #[test]
484    fn default_has_git_defaults_and_no_labels() {
485        let options = UnifiedDiffOptions::default();
486        assert_eq!(options.context_lines, 3);
487        assert_eq!(options.inter_hunk_context, 0);
488        assert_eq!(options.algorithm, DiffAlgorithm::Myers);
489        assert_eq!(options.indent_heuristic, IndentHeuristic::Enabled);
490        assert_eq!(options.extent, HunkExtent::Context);
491        assert!(options.old_label.is_none() && options.new_label.is_none());
492        assert_eq!(options.no_newline_marker, NoNewlineMarker::Emit);
493        assert_eq!(options.path_quoting, PathQuoting::EscapeNonAscii);
494    }
495
496    #[test]
497    fn labels_quote_and_tab_like_git() {
498        let mut out = String::new();
499        let label = DiffLabel::Path {
500            prefix: "a/",
501            path: "my file",
502        };
503        push_label_line(&mut out, "--- ", &label, PathQuoting::EscapeNonAscii);
504        push_label_line(
505            &mut out,
506            "+++ ",
507            &DiffLabel::DevNull,
508            PathQuoting::default(),
509        );
510        push_label_line(
511            &mut out,
512            "+++ ",
513            &DiffLabel::Verbatim("x y"),
514            PathQuoting::default(),
515        );
516        assert_eq!(out, "--- a/my file\t\n+++ /dev/null\n+++ x y\n");
517
518        let mut quoted = String::new();
519        let label = DiffLabel::Path {
520            prefix: "b/",
521            path: "caf\u{e9}",
522        };
523        push_label_line(&mut quoted, "+++ ", &label, PathQuoting::EscapeNonAscii);
524        assert_eq!(quoted, "+++ \"b/caf\\303\\251\"\n");
525        let mut kept = String::new();
526        push_label_line(&mut kept, "+++ ", &label, PathQuoting::KeepNonAscii);
527        assert_eq!(kept, "+++ b/caf\u{e9}\n");
528    }
529
530    #[test]
531    fn omit_marker_drops_no_newline_lines() {
532        let options = UnifiedDiffOptions::new().with_no_newline_marker(NoNewlineMarker::Omit);
533        assert_eq!(unified_diff("a", "b", &options), "@@ -1 +1 @@\n-a\n+b\n");
534    }
535
536    #[test]
537    fn omit_marker_keeps_source_lines_that_read_like_the_marker() {
538        let omit = UnifiedDiffOptions::new().with_no_newline_marker(NoNewlineMarker::Omit);
539        let marker = "\\ No newline at end of file";
540        let cases = [
541            (
542                format!("{marker}\nold\n"),
543                format!("{marker}\nnew\n"),
544                format!("@@ -1,2 +1,2 @@\n {marker}\n-old\n+new\n"),
545            ),
546            (
547                "a\n".to_owned(),
548                format!("a\n{marker}\n"),
549                format!("@@ -1 +1,2 @@\n a\n+{marker}\n"),
550            ),
551            (
552                format!("a\n{marker}\n"),
553                "a\n".to_owned(),
554                format!("@@ -1,2 +1 @@\n a\n-{marker}\n"),
555            ),
556            (
557                format!("{marker}\nx"),
558                format!("{marker}\ny"),
559                format!("@@ -1,2 +1,2 @@\n {marker}\n-x\n+y\n"),
560            ),
561        ];
562        for (old, new, expected) in cases {
563            assert_eq!(
564                unified_diff(&old, &new, &omit),
565                expected,
566                "{old:?} -> {new:?}"
567            );
568        }
569    }
570
571    #[test]
572    fn equal_sides_render_nothing_even_with_labels() {
573        let options = UnifiedDiffOptions::new().with_paths("f", "f");
574        assert_eq!(unified_diff("same\n", "same\n", &options), "");
575    }
576
577    #[test]
578    fn from_diff_options_carries_line_settings() {
579        let diff = DiffOptions::default()
580            .with_context_lines(1)
581            .with_inter_hunk_context(4)
582            .with_algorithm(DiffAlgorithm::Patience)
583            .with_indent_heuristic(false)
584            .with_whitespace(WhitespaceMode::ignore_all_space());
585        let options = UnifiedDiffOptions::from(&diff);
586        assert_eq!(options.context_lines, 1);
587        assert_eq!(options.inter_hunk_context, 4);
588        assert_eq!(options.algorithm, DiffAlgorithm::Patience);
589        assert_eq!(options.indent_heuristic, IndentHeuristic::Disabled);
590        assert_eq!(options.whitespace, WhitespaceMode::ignore_all_space());
591        assert!(options.old_label.is_none());
592    }
593
594    #[test]
595    fn anchored_counts_follow_rendered_patch() {
596        let old = "a\nb\nc\n";
597        let new = "c\na\nb\n";
598        let anchored = UnifiedDiffOptions::new().with_anchors(["c"]);
599        let stat = line_change_counts(old, new, &anchored);
600        assert_eq!((stat.insertions, stat.deletions), (2, 2));
601        assert_eq!(
602            unified_diff(old, new, &anchored),
603            "@@ -1,3 +1,3 @@\n-a\n-b\n c\n+a\n+b\n"
604        );
605        let plain = line_change_counts(old, new, &UnifiedDiffOptions::new());
606        assert_eq!((plain.insertions, plain.deletions), (1, 1));
607    }
608}