grit-lib 0.5.21

Core library for the grit Git implementation
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! User-defined and built-in diff function-name matching.
//!
//! This module implements the subset of Git's `userdiff` behavior needed for
//! hunk-header function context extraction.
//!
//! POSIX extended patterns from Git config are translated to Rust [`regex`] syntax
//! (including bracket classes like `[[:alpha:]]`). Matchers for built-in drivers are
//! compiled once and cached. Rust's regex engine uses leftmost-first alternation; GNU
//! `grep -E` uses leftmost-longest. Git's built-in funcname patterns are written so
//! this difference does not change hunk headers for the shipped drivers.

use crate::attributes::{collect_attrs_for_path, AttrValue, MacroTable};
use crate::config::ConfigSet;
use regex::{Regex, RegexBuilder};
use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};

/// Built-in diff driver funcname patterns (same strings as Git's userdiff builtin drivers).
const BUILTIN_PATTERN_DEFS: &[(&str, &str, bool)] = &[
    (
        "ada",
        r"!^(.*[ 	])?(is[ 	]+new|renames|is[ 	]+separate)([ 	].*)?$
!^[ 	]*with[ 	].*$
^[ 	]*((procedure|function)[ 	]+.*)$
^[ 	]*((package|protected|task)[ 	]+.*)$",
        true,
    ),
    (
        "bash",
        r"^[ 	]*((([a-zA-Z_][a-zA-Z0-9_]*[ 	]*\([ 	]*\))|(function[ 	]+[a-zA-Z_][a-zA-Z0-9_]*(([ 	]*\([ 	]*\))|([ 	]+)))).*$)",
        false,
    ),
    (
        "bibtex",
        r#"(@[a-zA-Z]{1,}[ 	]*\{{0,1}[ 	]*[^ 	"@',\#}{~%]*).*$"#,
        false,
    ),
    (
        "cpp",
        r"!^[ 	]*[A-Za-z_][A-Za-z_0-9]*:[[:space:]]*($|/[/*])
^((::[[:space:]]*)?[A-Za-z_].*)$",
        false,
    ),
    (
        "csharp",
        r"!(^|[ 	]+)(do|while|for|foreach|if|else|new|default|return|switch|case|throw|catch|using|lock|fixed)([ 	(]+|$)
^[ 	]*(([][[:alnum:]@_.](<[][[:alnum:]@_, 	<>]+>)?)+([ 	]+([][[:alnum:]@_.](<[][[:alnum:]@_, 	<>]+>)?)+)+[ 	]*\([^;]*)$
^[ 	]*(([][[:alnum:]@_.](<[][[:alnum:]@_, 	<>]+>)?)+([ 	]+([][[:alnum:]@_.](<[][[:alnum:]@_, 	<>]+>)?)+)+[^;=:,()]*)$
^[ 	]*(((static|public|internal|private|protected|new|unsafe|sealed|abstract|partial)[ 	]+)*(class|enum|interface|struct|record)[ 	]+.*)$
^[ 	]*(namespace[ 	]+.*)$",
        false,
    ),
    (
        "css",
        r"![:;][[:space:]]*$
^[:[@.#]?[_a-z0-9].*$",
        true,
    ),
    (
        "dts",
        r"!;
!=
^[ 	]*((/[ 	]*\{|&?[a-zA-Z_]).*)",
        false,
    ),
    (
        "elixir",
        r"^[ 	]*((def(macro|module|impl|protocol|p)?|test)[ 	].*)$",
        false,
    ),
    (
        "fortran",
        r#"!^([C*]|[ 	]*!)
!^[ 	]*MODULE[ 	]+PROCEDURE[ 	]
^[ 	]*((END[ 	]+)?(PROGRAM|MODULE|BLOCK[ 	]+DATA|([^!'" 	]+[ 	]+)*(SUBROUTINE|FUNCTION))[ 	]+[A-Z].*)$"#,
        true,
    ),
    (
        "fountain",
        r"^((\.[^.]|(int|ext|est|int\.?/ext|i/e)[. ]).*)$",
        true,
    ),
    (
        "golang",
        r"^[ 	]*(func[ 	]*.*(\{[ 	]*)?)
^[ 	]*(type[ 	].*(struct|interface)[ 	]*(\{[ 	]*)?)",
        false,
    ),
    ("html", r"^[ 	]*(<[Hh][1-6]([ 	].*)?>.*)$", false),
    ("ini", r"^[ 	]*\[[^]]+\]", false),
    (
        "java",
        r"!^[ 	]*(catch|do|for|if|instanceof|new|return|switch|throw|while)
^[ 	]*(([a-z-]+[ 	]+)*(class|enum|interface|record)[ 	]+.*)$
^[ 	]*(([A-Za-z_<>&][][?&<>.,A-Za-z_0-9]*[ 	]+)+[A-Za-z_][A-Za-z_0-9]*[ 	]*\([^;]*)$",
        false,
    ),
    (
        "kotlin",
        r"^[ 	]*(([a-z]+[ 	]+)*(fun|class|interface)[ 	]+.*)$",
        false,
    ),
    ("markdown", r"^ {0,3}#{1,6}[ 	].*", false),
    (
        "matlab",
        r"^[[:space:]]*((classdef|function)[[:space:]].*)$|^(%%%?|##)[[:space:]].*$",
        false,
    ),
    (
        "objc",
        r"!^[ 	]*(do|for|if|else|return|switch|while)
^[ 	]*([-+][ 	]*\([ 	]*[A-Za-z_][A-Za-z_0-9* 	]*\)[ 	]*[A-Za-z_].*)$
^[ 	]*(([A-Za-z_][A-Za-z_0-9]*[ 	]+)+[A-Za-z_][A-Za-z_0-9]*[ 	]*\([^;]*)$
^(@(implementation|interface|protocol)[ 	].*)$",
        false,
    ),
    (
        "pascal",
        r"^(((class[ 	]+)?(procedure|function)|constructor|destructor|interface|implementation|initialization|finalization)[ 	]*.*)$
^(.*=[ 	]*(class|record).*)$",
        false,
    ),
    (
        "perl",
        r"^package .*
^sub [[:alnum:]_':]+[ 	]*(\([^)]*\)[ 	]*)?(:[^;#]*)?(\{[ 	]*)?(#.*)?$
^(BEGIN|END|INIT|CHECK|UNITCHECK|AUTOLOAD|DESTROY)[ 	]*(\{[ 	]*)?(#.*)?$
^=head[0-9] .*",
        false,
    ),
    (
        "php",
        r"^[	 ]*(((public|protected|private|static|abstract|final)[	 ]+)*function.*)$
^[	 ]*((((final|abstract)[	 ]+)?class|enum|interface|trait).*)$",
        false,
    ),
    ("python", r"^[ 	]*((class|(async[ 	]+)?def)[ 	].*)$", false),
    (
        "r",
        r"^[ 	]*([a-zA-z][a-zA-Z0-9_.]*[ 	]*(<-|=)[ 	]*function.*)$",
        false,
    ),
    ("ruby", r"^[ 	]*((class|module|def)[ 	].*)$", false),
    (
        "rust",
        r#"^[	 ]*((pub(\([^\)]+\))?[	 ]+)?((async|const|unsafe|extern([	 ]+"[^"]+"))[	 ]+)?(struct|enum|union|mod|trait|fn|impl|macro_rules!)[< 	]+[^;]*)$"#,
        false,
    ),
    (
        "scheme",
        r"^[	 ]*(\(((define|def(struct|syntax|class|method|rules|record|proto|alias)?)[-*/ 	]|(library|module|struct|class)[*+ 	]).*)$",
        false,
    ),
    (
        "tex",
        r"^(\\((sub)*section|chapter|part)\*{0,1}\{.*)$",
        false,
    ),
];

#[derive(Debug, Clone)]
struct FuncRule {
    matcher: RuleMatcher,
    negate: bool,
}

#[derive(Debug, Clone)]
enum RuleMatcher {
    Rust(Regex),
}

#[derive(Debug, Clone)]
struct BuiltinPattern {
    pattern: String,
    ignore_case: bool,
}

// hygiene: immutable built-in diff funcname matchers, initialized once
static BUILTIN_FUNCNAME_MATCHERS: OnceLock<BTreeMap<String, Arc<FuncnameMatcher>>> =
    OnceLock::new();

/// Compiled function-name matcher used for diff hunk headers.
#[derive(Debug, Clone)]
pub struct FuncnameMatcher {
    rules: Vec<FuncRule>,
}

impl FuncnameMatcher {
    /// Match a source line against configured funcname rules.
    ///
    /// Returns the text to show after the hunk header when matched.
    #[must_use]
    pub fn match_line(&self, line: &str) -> Option<String> {
        let mut text = line;
        if let Some(stripped) = text.strip_suffix('\n') {
            text = stripped;
            if let Some(stripped_cr) = text.strip_suffix('\r') {
                text = stripped_cr;
            }
        }

        for rule in &self.rules {
            let matched_text = match &rule.matcher {
                RuleMatcher::Rust(regex) => {
                    if let Some(caps) = regex.captures(text) {
                        caps.get(1)
                            .or_else(|| caps.get(0))
                            .map(|m| m.as_str())
                            .unwrap_or_default()
                            .trim_end_matches(char::is_whitespace)
                            .to_owned()
                    } else if regex.is_match(text) {
                        text.trim_end_matches(char::is_whitespace).to_owned()
                    } else {
                        continue;
                    }
                }
            };
            if rule.negate {
                return None;
            }
            return Some(matched_text.trim_end().to_owned());
        }
        None
    }
}

/// Resolve a function-name matcher for `rel_path` from parsed `.gitattributes` rules + config.
///
/// Returns `Ok(None)` when no diff driver is configured for the path.
pub fn matcher_for_path_parsed(
    config: &ConfigSet,
    rules: &[crate::attributes::AttrRule],
    macros: &MacroTable,
    rel_path: &str,
    ignore_case: bool,
) -> Result<Option<FuncnameMatcher>, String> {
    let map = collect_attrs_for_path(rules, macros, rel_path, ignore_case);
    let Some(AttrValue::Value(driver)) = map.get("diff") else {
        return Ok(None);
    };
    matcher_for_driver(config, driver.as_str())
}

/// Resolve a function-name matcher for a named diff driver.
///
/// Returns `Ok(None)` when the driver has no built-in or configured funcname
/// pattern.
pub fn matcher_for_driver(
    config: &ConfigSet,
    driver: &str,
) -> Result<Option<FuncnameMatcher>, String> {
    if let Some(pattern) = config.get(&format!("diff.{driver}.xfuncname")) {
        return compile_matcher(&pattern, true, false).map(Some);
    }
    if let Some(pattern) = config.get(&format!("diff.{driver}.funcname")) {
        return compile_matcher(&pattern, false, false).map(Some);
    }
    if let Some(matcher) = cached_builtin_matcher(driver) {
        return Ok(Some((*matcher).clone()));
    }
    Ok(None)
}

fn cached_builtin_matcher(driver: &str) -> Option<Arc<FuncnameMatcher>> {
    let map = BUILTIN_FUNCNAME_MATCHERS.get_or_init(|| {
        builtin_patterns()
            .clone()
            .into_iter()
            .map(|(name, builtin)| {
                let matcher = compile_matcher(&builtin.pattern, true, builtin.ignore_case)
                    .unwrap_or_else(|e| panic!("built-in userdiff driver {name}: {e}"));
                (name, Arc::new(matcher))
            })
            .collect()
    });
    map.get(driver).cloned()
}

fn compile_matcher(
    pattern: &str,
    extended: bool,
    ignore_case: bool,
) -> Result<FuncnameMatcher, String> {
    let lines: Vec<&str> = pattern.split('\n').collect();
    if lines.is_empty() {
        return Ok(FuncnameMatcher { rules: Vec::new() });
    }

    let mut rules = Vec::with_capacity(lines.len());
    for (idx, raw) in lines.iter().enumerate() {
        let mut line = *raw;
        let negate = line.starts_with('!');
        if negate {
            if idx == lines.len() - 1 {
                return Err(format!("Last expression must not be negated: {line}"));
            }
            line = &line[1..];
        }

        let posix_pattern = if extended {
            line.to_owned()
        } else {
            bre_to_ere(line)
        };

        let matcher = compile_posix_ere_rule(&posix_pattern, ignore_case, line)?;
        rules.push(FuncRule { matcher, negate });
    }

    Ok(FuncnameMatcher { rules })
}

fn builtin_patterns() -> &'static BTreeMap<String, BuiltinPattern> {
    // hygiene: immutable built-in diff funcname patterns, initialized once
    static BUILTIN_PATTERNS: OnceLock<BTreeMap<String, BuiltinPattern>> = OnceLock::new();
    BUILTIN_PATTERNS.get_or_init(parse_builtin_patterns)
}

fn parse_builtin_patterns() -> BTreeMap<String, BuiltinPattern> {
    BUILTIN_PATTERN_DEFS
        .iter()
        .filter(|(name, _, _)| !name.is_empty() && *name != "default")
        .map(|(name, pattern, ignore_case)| {
            (
                (*name).to_owned(),
                BuiltinPattern {
                    pattern: (*pattern).to_owned(),
                    ignore_case: *ignore_case,
                },
            )
        })
        .collect()
}

fn bre_to_ere(pattern: &str) -> String {
    let mut result = String::with_capacity(pattern.len());
    let chars: Vec<char> = pattern.chars().collect();
    let mut i = 0usize;
    let mut in_bracket = false;

    while i < chars.len() {
        if in_bracket {
            if chars[i] == ']' && i > 0 {
                result.push(']');
                in_bracket = false;
                i += 1;
            } else if chars[i] == '[' {
                result.push('[');
                i += 1;
            } else if chars[i] == '\\' {
                // Preserve literal backslashes inside character classes.
                // Rust `regex` understands POSIX classes like `[:alnum:]`,
                // so we only need to escape unknown escapes.
                if i + 1 < chars.len() {
                    let next = chars[i + 1];
                    if next.is_ascii_alphabetic() {
                        result.push('\\');
                        result.push('\\');
                        result.push(next);
                        i += 2;
                    } else {
                        result.push('\\');
                        result.push(next);
                        i += 2;
                    }
                } else {
                    result.push('\\');
                    i += 1;
                }
            } else {
                result.push(chars[i]);
                i += 1;
            }
        } else if chars[i] == '[' {
            result.push('[');
            in_bracket = true;
            i += 1;
            if i < chars.len() && (chars[i] == '^' || chars[i] == '!') {
                result.push(chars[i]);
                i += 1;
            }
            if i < chars.len() && chars[i] == ']' {
                result.push(']');
                i += 1;
            }
        } else if chars[i] == '\\' && i + 1 < chars.len() {
            match chars[i + 1] {
                '+' | '?' | '{' | '}' | '(' | ')' | '|' => {
                    result.push(chars[i + 1]);
                    i += 2;
                }
                _ => {
                    result.push(chars[i]);
                    result.push(chars[i + 1]);
                    i += 2;
                }
            }
        } else if matches!(chars[i], '+' | '?' | '{' | '}' | '(' | ')' | '|') {
            result.push('\\');
            result.push(chars[i]);
            i += 1;
        } else {
            result.push(chars[i]);
            i += 1;
        }
    }

    result
}

/// Translate a validated POSIX ERE (as Git uses for `xfuncname`) into Rust `regex` syntax.
///
/// Returns `None` when the pattern is not valid POSIX ERE (e.g. an unterminated `[` class).
fn posix_ere_to_rust_regex(pattern: &str) -> Option<String> {
    let mut out = String::with_capacity(pattern.len() + 16);
    let chars: Vec<char> = pattern.chars().collect();
    let mut i = 0usize;
    while i < chars.len() {
        if chars[i] == '[' {
            let (translated, consumed) = translate_posix_bracket(&chars[i..])?;
            out.push_str(&translated);
            i += consumed;
        } else if chars[i] == '\\' && i + 1 < chars.len() {
            out.push(chars[i]);
            out.push(chars[i + 1]);
            i += 2;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    Some(out)
}

/// Translate one POSIX bracket expression starting at `[`; returns Rust class + bytes consumed.
fn translate_posix_bracket(src: &[char]) -> Option<(String, usize)> {
    debug_assert!(src.first() == Some(&'['));
    let mut out = String::from("[");
    let mut i = 1usize;
    if i < src.len() && (src[i] == '^' || src[i] == '!') {
        out.push(src[i]);
        i += 1;
    }
    if i < src.len() && src[i] == ']' {
        out.push(']');
        i += 1;
    }
    while i < src.len() {
        if src[i] == ']' {
            out.push(']');
            return Some((out, i + 1));
        }
        if src[i] == '[' && i + 2 < src.len() && src[i + 1] == ':' {
            let start = i;
            i += 2;
            while i + 1 < src.len() {
                if src[i] == ':' && src[i + 1] == ']' {
                    i += 2;
                    break;
                }
                i += 1;
            }
            for ch in &src[start..i] {
                out.push(*ch);
            }
            continue;
        }
        if src[i] == '\\' && i + 1 < src.len() {
            out.push('\\');
            out.push(src[i + 1]);
            i += 2;
            continue;
        }
        let ch = src[i];
        if matches!(ch, '[' | ']' | '\\') {
            out.push('\\');
        }
        out.push(ch);
        i += 1;
    }
    None
}

/// Compile-check a POSIX ERE without shelling out to `grep`.
fn validate_posix_ere(pattern: &str, ignore_case: bool) -> Result<(), regex::Error> {
    let Some(rust_pattern) = posix_ere_to_rust_regex(pattern) else {
        return Err(regex::Error::Syntax(
            "unterminated bracket expression".into(),
        ));
    };
    RegexBuilder::new(&rust_pattern)
        .case_insensitive(ignore_case)
        .build()
        .map(|_| ())
}

/// Compile a POSIX ERE matcher rule after validation.
fn compile_posix_ere_rule(
    pattern: &str,
    ignore_case: bool,
    line: &str,
) -> Result<RuleMatcher, String> {
    validate_posix_ere(pattern, ignore_case)
        .map_err(|_| format!("Invalid regexp to look for hunk header: {line}"))?;
    let rust_pattern = posix_ere_to_rust_regex(pattern)
        .ok_or_else(|| format!("Invalid regexp to look for hunk header: {line}"))?;
    RegexBuilder::new(&rust_pattern)
        .case_insensitive(ignore_case)
        .build()
        .map_err(|_| format!("Invalid regexp to look for hunk header: {line}"))
        .map(RuleMatcher::Rust)
}

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

    use crate::config::{ConfigFile, ConfigScope, ConfigSet};

    fn config_with_xfuncname(driver: &str, pattern: &str) -> ConfigSet {
        let snippet = format!("[diff \"{driver}\"]\n\txfuncname = {pattern}\n");
        let file = ConfigFile::parse(Path::new(".git/config"), &snippet, ConfigScope::Local)
            .expect("parse config snippet");
        let mut set = ConfigSet::new();
        set.merge(&file);
        set
    }

    #[test]
    fn unterminated_posix_bracket_class_is_rejected() {
        let err = compile_matcher("[a", true, false).unwrap_err();
        assert!(err.contains("Invalid regexp"), "unexpected error: {err}");
        let cfg = config_with_xfuncname("probe", "[a");
        let err = matcher_for_driver(&cfg, "probe").unwrap_err();
        assert!(err.contains("Invalid regexp"), "unexpected error: {err}");
    }

    #[test]
    fn all_builtin_userdiff_drivers_compile_and_cache() {
        let config = ConfigSet::default();
        for (name, _, _) in BUILTIN_PATTERN_DEFS {
            if name.is_empty() || *name == "default" {
                continue;
            }
            let matcher = matcher_for_driver(&config, name)
                .unwrap_or_else(|e| panic!("driver {name}: {e}"))
                .unwrap_or_else(|| panic!("driver {name} missing builtin matcher"));
            assert!(
                cached_builtin_matcher(name).is_some(),
                "driver {name} must be cached"
            );
            let _ = matcher.match_line(" \n");
        }
    }
}