grit-lib 0.5.32

Core library for the grit Git implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Unified diff hunk body emission (independent layout; Git-compatible boundaries).
//!
//! Line breaks in the source text are tracked per logical line so patch lines can
//! preserve CRLF bodies and `\ No newline at end of file` markers match Git.

use crate::diff::core::is_func_line;
use crate::userdiff::FuncnameMatcher;

/// How a source line ended before the next line (or EOF).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineEnding {
    Lf,
    CrLf,
    Missing,
}

/// One logical line of a side, without the `\n` separator (a CRLF line keeps its `\r`).
#[derive(Clone, Copy, Debug)]
pub struct SourceLine<'a> {
    pub body: &'a str,
    pub ending: LineEnding,
}

impl<'a> SourceLine<'a> {
    /// The line held by `record`, a line with its `\n` when it has one.
    fn from_record(record: &'a str) -> Self {
        match record.strip_suffix('\n') {
            Some(body) => Self {
                body,
                ending: if body.ends_with('\r') {
                    LineEnding::CrLf
                } else {
                    LineEnding::Lf
                },
            },
            None => Self {
                body: record,
                ending: LineEnding::Missing,
            },
        }
    }
}

/// All logical lines of one file version, borrowed from its text.
///
/// Each line is kept as its record: the body followed by the `\n` that ends it, if any. Git
/// compares whole records, so they double as compare keys without a second table.
#[derive(Clone, Debug)]
pub struct LineSide<'a> {
    records: Vec<&'a str>,
}

impl<'a> LineSide<'a> {
    /// Split `text` into lines, preserving `\r` in bodies and final incomplete lines.
    #[must_use]
    pub fn from_text(text: &'a str) -> Self {
        let bytes = text.as_bytes();
        let mut records = Vec::with_capacity(memchr::memchr_iter(b'\n', bytes).count() + 1);
        let mut start = 0usize;
        for i in memchr::memchr_iter(b'\n', bytes) {
            records.push(&text[start..=i]);
            start = i + 1;
        }
        if start < text.len() {
            records.push(&text[start..]);
        }
        Self { records }
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.records.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.records.is_empty()
    }

    #[must_use]
    pub fn line(&self, index: usize) -> SourceLine<'a> {
        SourceLine::from_record(self.records[index])
    }

    /// Every line in order.
    pub fn lines(&self) -> impl ExactSizeIterator<Item = SourceLine<'a>> + '_ {
        self.records
            .iter()
            .map(|record| SourceLine::from_record(record))
    }

    /// Every line with its `\n`, when it has one: the bytes Git compares lines by, so a line
    /// ending in a newline never matches the same body at EOF without one.
    #[must_use]
    pub fn records(&self) -> &[&'a str] {
        &self.records
    }
}

/// Token for line-based diff alignment (Git compares full records including newline).
///
/// A line terminated with LF/CRLF must not match the same body at EOF without a newline.
/// The diff pipeline borrows these bytes straight from the source text; this owned form is the
/// reference the tests compare against.
#[cfg(test)]
#[must_use]
pub(crate) fn line_diff_token(line: &SourceLine) -> String {
    match line.ending {
        LineEnding::Missing => line.body.to_string(),
        LineEnding::Lf | LineEnding::CrLf => {
            let mut s = String::with_capacity(line.body.len() + 1);
            s.push_str(line.body);
            s.push('\n');
            s
        }
    }
}

/// When line-based diff finds no edits but the raw texts differ, Git still emits
/// hunks for lines whose bodies match but [`LineEnding`] differs (notably EOF).
#[must_use]
pub fn line_ending_only_edits(before: &LineSide, after: &LineSide) -> Vec<EditSpan> {
    if before.len() != after.len() {
        return Vec::new();
    }
    let mut edits = Vec::new();
    for i in 0..before.len() {
        let bl = before.line(i);
        let al = after.line(i);
        if bl.body != al.body {
            return Vec::new();
        }
        if bl.ending != al.ending {
            edits.push(EditSpan {
                before_start: i as i64,
                before_len: 1,
                after_start: i as i64,
                after_len: 1,
                skip_in_output: false,
            });
        }
    }
    edits
}

/// One contiguous edit between two sides (insert / delete / replace).
#[derive(Clone, Debug)]
pub struct EditSpan {
    pub before_start: i64,
    pub before_len: i64,
    pub after_start: i64,
    pub after_len: i64,
    pub skip_in_output: bool,
}

/// Parameters for hunk grouping and emission.
#[derive(Clone, Copy, Debug)]
pub struct UnifiedEmitOptions {
    pub context_lines: usize,
    pub inter_hunk_context: usize,
    pub function_context: bool,
}

/// Write one patch line (`-`, `+`, or ` `) including Git's no-newline marker when needed.
pub fn write_patch_line(out: &mut String, prefix: char, line: &SourceLine) {
    out.push(prefix);
    out.push_str(line.body);
    out.push('\n');
    if line.ending == LineEnding::Missing {
        out.push_str("\\ No newline at end of file\n");
    }
}

fn format_hunk_side(start0: i64, count: i64) -> String {
    let shown_start = if count == 0 { start0 } else { start0 + 1 };
    if count == 1 {
        format!("{shown_start}")
    } else {
        format!("{shown_start},{count}")
    }
}

/// Emit unified hunk bodies for precomputed edit spans (Myers / xdiff ops path).
pub fn emit_unified_body_from_edits(
    before: &LineSide,
    after: &LineSide,
    edits: &[EditSpan],
    options: UnifiedEmitOptions,
    funcname_matcher: Option<&FuncnameMatcher>,
) -> String {
    use std::fmt::Write as _;

    if edits.is_empty() {
        return String::new();
    }
    let before_len = before.len() as i64;
    let after_len = after.len() as i64;
    let ctxlen = options.context_lines as i64;
    let interhunk = options.inter_hunk_context as i64;
    let max_common = ctxlen.saturating_add(ctxlen).saturating_add(interhunk);
    let max_ignorable = ctxlen;

    let before_body = |i: i64| -> &str {
        if i < 0 || i as usize >= before.len() {
            return "";
        }
        before.line(i as usize).body
    };
    let next_hunk = |start: usize| -> Option<(usize, usize)> {
        let mut scr = start;
        let mut xchp = start;
        while xchp < edits.len() && edits[xchp].skip_in_output {
            let next = xchp + 1;
            if next >= edits.len()
                || edits[next].before_start - (edits[xchp].before_start + edits[xchp].before_len)
                    >= max_ignorable
            {
                scr = next;
            }
            xchp = next;
        }
        if scr >= edits.len() {
            return None;
        }

        let mut lx = scr;
        let mut ignored_after: i64 = 0;
        let mut prev = scr;
        let mut idx = scr + 1;
        while idx < edits.len() {
            let cur = &edits[idx];
            let prev_e = &edits[prev];
            let distance = cur.before_start - (prev_e.before_start + prev_e.before_len);
            if distance > max_common {
                break;
            }
            if distance < max_ignorable && (!cur.skip_in_output || lx == prev) {
                lx = idx;
                ignored_after = 0;
            } else if distance < max_ignorable && cur.skip_in_output {
                ignored_after += cur.after_len;
            } else if lx != prev
                && cur.before_start + ignored_after
                    - (edits[lx].before_start + edits[lx].before_len)
                    > max_common
            {
                break;
            } else if !cur.skip_in_output {
                lx = idx;
                ignored_after = 0;
            } else {
                ignored_after += cur.after_len;
            }
            prev = idx;
            idx += 1;
        }
        Some((scr, lx))
    };

    let is_func = |body: &str| is_func_line(body, funcname_matcher);
    // Nearest function line of the old side from `start` toward `limit` (exclusive).
    let func_line_toward = |start: i64, limit: i64| -> Option<i64> {
        let step = if start > limit { -1 } else { 1 };
        let mut l = start;
        while l != limit && (0..before_len).contains(&l) {
            if is_func(before_body(l)) {
                return Some(l);
            }
            l += step;
        }
        None
    };
    let is_blank = |body: &str| body.bytes().all(|b| b.is_ascii_whitespace() || b == 0x0b);

    let mut out = String::new();
    let mut cursor = 0usize;
    while cursor < edits.len() {
        let Some((mut first_idx, mut last_idx)) = next_hunk(cursor) else {
            break;
        };

        let (mut b_start, mut a_start);
        let mut rewind_from = cursor;
        loop {
            let first = &edits[first_idx];
            b_start = (first.before_start - ctxlen).max(0);
            a_start = (first.after_start - ctxlen).max(0);
            if !options.function_context {
                break;
            }
            let mut anchor = first.before_start;
            if anchor >= before_len {
                // An appended block that brings its own function needs no earlier context.
                let adds_function =
                    (first.after_start..after_len).any(|i| is_func(after.line(i as usize).body));
                if adds_function {
                    break;
                }
                anchor = before_len - 1;
            }
            let mut func_start = func_line_toward(anchor, -1).unwrap_or(-1);
            while func_start > 0
                && !is_blank(before_body(func_start - 1))
                && !is_func(before_body(func_start - 1))
            {
                func_start -= 1;
            }
            let func_start = func_start.max(0);
            if func_start >= b_start {
                break;
            }
            a_start = (a_start - (b_start - func_start)).max(0);
            b_start = func_start;
            // Show ignorable changes that the widened context now reaches into.
            let reached = (rewind_from..first_idx).find(|&i| {
                let e = &edits[i];
                e.before_start + e.before_len > b_start || e.after_start + e.after_len > a_start
            });
            match reached {
                Some(i) => {
                    first_idx = i;
                    rewind_from = i;
                }
                None => break,
            }
        }

        let (mut b_end, mut a_end);
        loop {
            let last = &edits[last_idx];
            let last_before_end = last.before_start + last.before_len;
            let last_after_end = last.after_start + last.after_len;
            let post = ctxlen
                .min(before_len - last_before_end)
                .min(after_len - last_after_end);
            b_end = last_before_end + post;
            a_end = last_after_end + post;
            if !options.function_context {
                break;
            }
            let func_end = match func_line_toward(last_before_end, before_len) {
                Some(mut end) => {
                    while end > 0 && is_blank(before_body(end - 1)) {
                        end -= 1;
                    }
                    end
                }
                None => before_len,
            };
            if func_end > b_end {
                a_end = (a_end + (func_end - b_end)).min(after_len);
                b_end = func_end;
            }
            // Pull the next change in when it starts inside the widened hunk or within the same
            // function.
            let Some(next) = edits.get(last_idx + 1) else {
                break;
            };
            let next_start = next.before_start.min(before_len - 1);
            if next_start - ctxlen <= b_end || func_line_toward(next_start, b_end).is_none() {
                last_idx += 1;
                continue;
            }
            break;
        }
        let first = &edits[first_idx];
        let last = &edits[last_idx];

        let _ = writeln!(
            out,
            "@@ -{} +{} @@",
            format_hunk_side(b_start, b_end - b_start),
            format_hunk_side(a_start, a_end - a_start)
        );

        let mut a_cur = a_start;
        while a_cur < first.after_start {
            write_patch_line(&mut out, ' ', &after.line(a_cur as usize));
            a_cur += 1;
        }

        let mut b_cur = first.before_start;
        let mut a_cur = first.after_start;
        let mut k = first_idx;
        loop {
            let e = &edits[k];
            while b_cur < e.before_start && a_cur < e.after_start {
                write_patch_line(&mut out, ' ', &after.line(a_cur as usize));
                b_cur += 1;
                a_cur += 1;
            }
            let mut r = e.before_start;
            while r < e.before_start + e.before_len {
                write_patch_line(&mut out, '-', &before.line(r as usize));
                r += 1;
            }
            let mut a = e.after_start;
            while a < e.after_start + e.after_len {
                write_patch_line(&mut out, '+', &after.line(a as usize));
                a += 1;
            }
            if k == last_idx {
                break;
            }
            b_cur = e.before_start + e.before_len;
            a_cur = e.after_start + e.after_len;
            k += 1;
        }

        let mut a_tail = last.after_start + last.after_len;
        while a_tail < a_end {
            write_patch_line(&mut out, ' ', &after.line(a_tail as usize));
            a_tail += 1;
        }

        cursor = last_idx + 1;
    }

    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn split_preserves_crlf_in_body() {
        let side = LineSide::from_text("a\r\nb");
        assert_eq!(side.len(), 2);
        assert_eq!(side.line(0).body, "a\r");
        assert_eq!(side.line(0).ending, LineEnding::CrLf);
        assert_eq!(side.line(1).body, "b");
        assert_eq!(side.line(1).ending, LineEnding::Missing);
        assert_eq!(side.records(), ["a\r\n", "b"]);
    }

    #[test]
    fn patch_line_marks_missing_newline() {
        let line = SourceLine {
            body: "x".into(),
            ending: LineEnding::Missing,
        };
        let mut out = String::new();
        write_patch_line(&mut out, '-', &line);
        assert!(out.contains("\\ No newline at end of file"));
    }

    #[test]
    fn eof_newline_only_change_yields_replace_hunk() {
        let before = LineSide::from_text("one");
        let after = LineSide::from_text("one\n");
        let edits = line_ending_only_edits(&before, &after);
        assert_eq!(edits.len(), 1);
        let body = emit_unified_body_from_edits(
            &before,
            &after,
            &edits,
            UnifiedEmitOptions {
                context_lines: 3,
                inter_hunk_context: 0,
                function_context: false,
            },
            None,
        );
        assert!(body.contains("-one\n"));
        assert!(body.contains("+one\n"));
        assert!(body.contains("\\ No newline at end of file"));
    }

    #[test]
    fn line_diff_token_distinguishes_eof_from_terminated() {
        let no_nl = LineSide::from_text("a\nb");
        let with_nl = LineSide::from_text("a\nb\n");
        assert_ne!(
            line_diff_token(&no_nl.line(1)),
            line_diff_token(&with_nl.line(1))
        );
    }
}