1use crate::error::ObjectError;
28use std::borrow::Cow;
29use std::sync::Arc;
30
31use regex_automata::meta::{self, Regex};
32use regex_automata::nfa::thompson::WhichCaptures;
33use regex_automata::util::syntax;
34use regex_automata::MatchKind;
35
36use crate::config::mailmap::{map_contact_table, parse_contact, MailmapTable};
37use crate::error::{Error, Result};
38use crate::objects::{ObjectId, ObjectKind};
39use crate::repo::Repository;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub(crate) struct Pattern(String);
44
45impl Pattern {
46 #[must_use]
47 #[allow(dead_code)] pub(crate) fn new(raw: impl Into<String>) -> Self {
49 Self(raw.into())
50 }
51
52 #[must_use]
54 pub(crate) fn as_str(&self) -> &str {
55 &self.0
56 }
57}
58
59impl From<String> for Pattern {
60 fn from(s: String) -> Self {
61 Self(s)
62 }
63}
64
65impl From<&str> for Pattern {
66 fn from(s: &str) -> Self {
67 Self(s.to_owned())
68 }
69}
70
71#[derive(Debug, thiserror::Error)]
73#[non_exhaustive]
74pub enum CommitFilterError {
75 #[error("invalid commit filter pattern `{pattern}`: {detail}")]
77 InvalidPattern {
78 pattern: String,
80 detail: String,
82 },
83}
84
85#[derive(Debug, Clone)]
87pub struct CommitFilter {
88 inner: Arc<CommitFilterInner>,
89}
90
91#[derive(Debug)]
92struct CommitFilterInner {
93 author: Option<Regex>,
94 committer: Option<Regex>,
95 grep: Vec<Regex>,
96 all_match: bool,
97 invert_grep: bool,
98 mailmap: Option<MailmapTable>,
99}
100
101impl CommitFilter {
102 #[must_use]
104 pub fn is_active(&self) -> bool {
105 let i = &self.inner;
106 i.author.is_some() || i.committer.is_some() || !i.grep.is_empty()
107 }
108
109 #[must_use]
114 pub(crate) fn needs_full_commit_bytes(&self) -> bool {
115 !self.inner.grep.is_empty()
116 }
117
118 pub(crate) fn matches(&self, repo: &Repository, oid: ObjectId) -> Result<bool> {
124 let object = repo.odb().read(&oid)?;
125 if object.kind != ObjectKind::Commit {
126 return Err(Error::Object(ObjectError::Corrupt {
127 detail: format!("expected commit object for {oid}, found {:?}", object.kind),
128 }));
129 }
130 Ok(self.matches_bytes(&object.data))
131 }
132
133 pub(crate) fn matches_bytes(&self, raw: &[u8]) -> bool {
135 let inner = &self.inner;
136 let headers = scan_commit_headers(raw);
137
138 if let Some(re) = &inner.author {
139 let ident = ident_for_pattern_match(headers.author, inner.mailmap.as_ref());
140 if !re.is_match(ident.as_ref()) {
141 return false;
142 }
143 }
144
145 if let Some(re) = &inner.committer {
146 let ident = ident_for_pattern_match(headers.committer, inner.mailmap.as_ref());
147 if !re.is_match(ident.as_ref()) {
148 return false;
149 }
150 }
151
152 if !inner.grep.is_empty() {
153 let body = commit_message_body(raw);
154 let grep_ok = if inner.all_match {
155 inner.grep.iter().all(|re| re.is_match(body))
156 } else {
157 inner.grep.iter().any(|re| re.is_match(body))
158 };
159 let grep_ok = if inner.invert_grep { !grep_ok } else { grep_ok };
160 if !grep_ok {
161 return false;
162 }
163 }
164
165 true
166 }
167}
168
169#[derive(Debug, Clone, Default)]
171pub struct CommitFilterBuilder {
172 author: Vec<Pattern>,
173 committer: Vec<Pattern>,
174 grep: Vec<Pattern>,
175 ignore_case: bool,
176 all_match: bool,
177 invert_grep: bool,
178 fixed_strings: bool,
179 mailmap: Option<MailmapTable>,
180}
181
182impl CommitFilterBuilder {
183 #[must_use]
185 pub fn new() -> Self {
186 Self::default()
187 }
188
189 #[must_use]
191 pub fn author(mut self, pattern: impl Into<String>) -> Self {
192 self.author.push(Pattern(pattern.into()));
193 self
194 }
195
196 #[must_use]
198 pub fn committer(mut self, pattern: impl Into<String>) -> Self {
199 self.committer.push(Pattern(pattern.into()));
200 self
201 }
202
203 #[must_use]
205 pub fn grep(mut self, pattern: impl Into<String>) -> Self {
206 self.grep.push(Pattern(pattern.into()));
207 self
208 }
209
210 #[must_use]
212 pub fn ignore_case(mut self, yes: bool) -> Self {
213 self.ignore_case = yes;
214 self
215 }
216
217 #[must_use]
219 pub fn all_match(mut self, yes: bool) -> Self {
220 self.all_match = yes;
221 self
222 }
223
224 #[must_use]
226 pub fn invert_grep(mut self, yes: bool) -> Self {
227 self.invert_grep = yes;
228 self
229 }
230
231 #[must_use]
233 pub fn fixed_strings(mut self, yes: bool) -> Self {
234 self.fixed_strings = yes;
235 self
236 }
237
238 #[must_use]
240 pub fn mailmap(mut self, table: MailmapTable) -> Self {
241 self.mailmap = Some(table);
242 self
243 }
244
245 pub fn build(self) -> std::result::Result<CommitFilter, CommitFilterError> {
251 let compile = |patterns: &[Pattern], group| {
252 compile_patterns(patterns, group, self.ignore_case, self.fixed_strings)
253 };
254 let author = compile(&self.author, PatternGroup::Identity)?;
255 let committer = compile(&self.committer, PatternGroup::Identity)?;
256 let mut grep = Vec::with_capacity(self.grep.len());
257 for pat in &self.grep {
258 grep.extend(compile(std::slice::from_ref(pat), PatternGroup::Message)?);
259 }
260 Ok(CommitFilter {
261 inner: Arc::new(CommitFilterInner {
262 author,
263 committer,
264 grep,
265 all_match: self.all_match,
266 invert_grep: self.invert_grep,
267 mailmap: self.mailmap,
268 }),
269 })
270 }
271}
272
273struct CommitHeaderFields<'a> {
274 author: Option<&'a [u8]>,
275 committer: Option<&'a [u8]>,
276}
277
278fn commit_message_body(raw: &[u8]) -> &[u8] {
279 raw.windows(2)
280 .position(|w| w == b"\n\n")
281 .map(|pos| &raw[pos + 2..])
282 .unwrap_or(&[])
283}
284
285fn scan_commit_headers(raw: &[u8]) -> CommitHeaderFields<'_> {
286 let mut author = None;
287 let mut committer = None;
288 let mut line_start = 0usize;
289 for (i, &b) in raw.iter().enumerate() {
290 if b == b'\n' {
291 if line_start == i {
292 break;
293 }
294 let line = &raw[line_start..i];
295 if let Some(rest) = line.strip_prefix(b"author ") {
296 author = Some(rest);
297 } else if let Some(rest) = line.strip_prefix(b"committer ") {
298 committer = Some(rest);
299 }
300 line_start = i + 1;
301 }
302 }
303 CommitHeaderFields { author, committer }
304}
305
306fn trim_end_ascii_ws(ident: &[u8]) -> &[u8] {
307 let end = ident
308 .iter()
309 .rposition(|&b| b != b' ' && b != b'\t')
310 .map_or(0, |i| i + 1);
311 &ident[..end]
312}
313
314fn ident_without_timestamp_bytes(ident: &[u8]) -> &[u8] {
315 let Some(gt) = ident.iter().rposition(|&b| b == b'>') else {
316 return trim_end_ascii_ws(ident);
317 };
318 trim_end_ascii_ws(&ident[..=gt])
319}
320
321fn ident_for_pattern_match<'a>(
323 ident: Option<&'a [u8]>,
324 mailmap: Option<&MailmapTable>,
325) -> Cow<'a, [u8]> {
326 let Some(ident) = ident else {
327 return Cow::Borrowed(b"");
328 };
329 let bare = ident_without_timestamp_bytes(ident);
330 let Some(table) = mailmap else {
331 return Cow::Borrowed(bare);
332 };
333 let Ok(bare_str) = std::str::from_utf8(bare) else {
335 return Cow::Borrowed(bare);
336 };
337 let (name, email) = parse_contact(bare_str);
338 let (name, email) = map_contact_table(name.as_deref(), email.as_deref(), table);
339 if email.is_empty() {
340 Cow::Owned(name.into_bytes())
341 } else if name.is_empty() {
342 Cow::Owned(format!("<{email}>").into_bytes())
343 } else {
344 Cow::Owned(format!("{name} <{email}>").into_bytes())
345 }
346}
347
348const MATCHER_POOL_CAPACITY: usize = 8;
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354enum PatternGroup {
355 Identity,
357 Message,
359}
360
361fn compile_patterns(
366 patterns: &[Pattern],
367 group: PatternGroup,
368 ignore_case: bool,
369 fixed_strings: bool,
370) -> std::result::Result<Option<Regex>, CommitFilterError> {
371 if patterns.is_empty() {
372 return Ok(None);
373 }
374 let rust_patterns = patterns
375 .iter()
376 .map(|pat| pattern_to_rust_regex(pat.as_str(), ignore_case, fixed_strings))
377 .collect::<std::result::Result<Vec<_>, _>>()?;
378 meta::Builder::new()
379 .configure(
380 meta::Config::new()
381 .nfa_size_limit(Some(10 * (1 << 20)))
382 .hybrid_cache_capacity(2 * (1 << 20))
383 .match_kind(match group {
384 PatternGroup::Identity => MatchKind::All,
385 PatternGroup::Message => MatchKind::LeftmostFirst,
386 })
387 .utf8_empty(false)
388 .which_captures(WhichCaptures::None)
389 .pool_capacity(MATCHER_POOL_CAPACITY),
390 )
391 .syntax(
392 syntax::Config::new()
393 .utf8(false)
394 .case_insensitive(ignore_case)
395 .multi_line(group == PatternGroup::Message),
396 )
397 .build_many(&rust_patterns)
398 .map(Some)
399 .map_err(|e| {
400 let failed = e.pattern().map_or(0, |id| id.as_usize());
401 CommitFilterError::InvalidPattern {
402 pattern: patterns
403 .get(failed)
404 .map_or_else(String::new, |p| p.as_str().to_owned()),
405 detail: e.to_string(),
406 }
407 })
408}
409
410const BRE_DOT: &str = r"(?-u:[\x00-\x09\x0B-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF][\x80-\xBF]|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF][\x80-\xBF]|[\xF1-\xF3][\x80-\xBF][\x80-\xBF][\x80-\xBF]|\xF4[\x80-\x8F][\x80-\xBF][\x80-\xBF])";
416
417fn pattern_to_rust_regex(
418 pattern: &str,
419 _ignore_case: bool,
420 fixed_strings: bool,
421) -> std::result::Result<String, CommitFilterError> {
422 if fixed_strings {
423 return Ok(regex::escape(pattern));
424 }
425 bre_translate_to_rust_regex(pattern).map_err(|detail| CommitFilterError::InvalidPattern {
426 pattern: pattern.to_owned(),
427 detail,
428 })
429}
430
431pub(crate) fn bre_translate_to_rust_regex(pattern: &str) -> std::result::Result<String, String> {
433 let mut out = String::with_capacity(pattern.len() + 8);
434 let chars: Vec<char> = pattern.chars().collect();
435 let mut i = 0usize;
436 let mut in_bracket = false;
437
438 while i < chars.len() {
439 if in_bracket {
440 if chars[i] == ']' && i > 0 {
441 out.push(']');
442 in_bracket = false;
443 i += 1;
444 } else if chars[i] == '[' {
445 out.push('[');
446 i += 1;
447 } else if chars[i] == '\\' {
448 if i + 1 < chars.len() {
449 let next = chars[i + 1];
450 out.push('\\');
451 out.push(next);
452 i += 2;
453 } else {
454 out.push('\\');
455 i += 1;
456 }
457 } else {
458 out.push(chars[i]);
459 i += 1;
460 }
461 continue;
462 }
463
464 if chars[i] == '[' {
465 out.push('[');
466 in_bracket = true;
467 i += 1;
468 if i < chars.len() && (chars[i] == '^' || chars[i] == '!') {
469 out.push(chars[i]);
470 i += 1;
471 }
472 if i < chars.len() && chars[i] == ']' {
473 out.push(']');
474 i += 1;
475 }
476 continue;
477 }
478
479 if chars[i] == '\\' && i + 1 < chars.len() {
480 match chars[i + 1] {
481 '(' => {
482 out.push('(');
483 i += 2;
484 }
485 ')' => {
486 out.push(')');
487 i += 2;
488 }
489 '|' => {
490 out.push('|');
491 i += 2;
492 }
493 '+' => {
494 out.push('+');
495 i += 2;
496 }
497 '?' => {
498 out.push('?');
499 i += 2;
500 }
501 '{' => {
502 out.push('{');
503 i += 2;
504 }
505 '}' => {
506 out.push('}');
507 i += 2;
508 }
509 _ => {
510 out.push('\\');
511 out.push(chars[i + 1]);
512 i += 2;
513 }
514 }
515 continue;
516 }
517
518 if matches!(chars[i], '(' | ')' | '|' | '+' | '?' | '{' | '}') {
519 out.push('\\');
520 out.push(chars[i]);
521 i += 1;
522 continue;
523 }
524
525 if chars[i] == '.' {
526 out.push_str(BRE_DOT);
527 i += 1;
528 continue;
529 }
530
531 out.push(chars[i]);
532 i += 1;
533 }
534
535 if in_bracket {
536 return Err("unterminated bracket expression".to_owned());
537 }
538
539 Ok(out)
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545
546 #[test]
547 fn bre_metachars_become_literals_or_operators() {
548 assert_eq!(
549 bre_translate_to_rust_regex("fix(parser)").unwrap(),
550 r"fix\(parser\)"
551 );
552 assert_eq!(bre_translate_to_rust_regex("a+b").unwrap(), r"a\+b");
553 assert_eq!(bre_translate_to_rust_regex(r"\(x\|y\)").unwrap(), "(x|y)");
554 }
555
556 #[test]
557 fn bre_dot_matches_like_unicode_dot_on_any_bytes() {
558 let haystacks: &[&[u8]] = &[
559 b"",
560 b"a",
561 b"\n",
562 b"\n\n",
563 b"ab",
564 b"axb",
565 b"a\nb",
566 b"Jos\xc3\xa9",
567 b"a\xc3\xa9b",
568 b"a\xe2\x82\xacb",
569 b"a\xf0\x9f\x98\x80b",
570 b"a\xf4\x8f\xbf\xbfb",
571 b"a\xf4\x90\x80\x80b",
572 b"a\xed\x9f\xbfb",
573 b"a\xed\xa0\x80b",
574 b"a\xc0\x80b",
575 b"a\xc1\xbfb",
576 b"a\xe0\x80\xafb",
577 b"a\xf0\x80\x80\xafb",
578 b"a\xf5\x80\x80\x80b",
579 b"a\xffb",
580 b"a\x80b",
581 b"a\xc3b",
582 b"\xc3",
583 b"\xff\n\xfe",
584 b"x\x00y",
585 b"a\rb",
586 ];
587 let patterns = [
588 ".",
589 "..",
590 "a.b",
591 "^.$",
592 "^a.*b$",
593 ".\\{2\\}",
594 "a.\\{1,3\\}b",
595 "^J.s.$",
596 "[.]",
597 "a\\.b",
598 ];
599 for ignore_case in [false, true] {
600 for group in [PatternGroup::Identity, PatternGroup::Message] {
601 let multi_line = group == PatternGroup::Message;
602 for pat in patterns {
603 let ours = compile_patterns(&[Pattern::new(pat)], group, ignore_case, false)
604 .unwrap()
605 .unwrap();
606 let unicode_dot = bre_translate_to_rust_regex(pat)
607 .unwrap()
608 .replace(BRE_DOT, ".");
609 let reference = regex::bytes::RegexBuilder::new(&unicode_dot)
610 .case_insensitive(ignore_case)
611 .multi_line(multi_line)
612 .build()
613 .unwrap();
614 for hay in haystacks {
615 assert_eq!(
616 ours.is_match(*hay),
617 reference.is_match(hay),
618 "pattern {pat:?} on {hay:?} (ignore_case={ignore_case}, multi_line={multi_line})"
619 );
620 }
621 }
622 }
623 }
624 }
625
626 #[test]
627 fn dot_patterns_filter_identities_and_grep_lines() {
628 let filter = CommitFilterBuilder::new().author("^Jos.$").build().unwrap();
629 let named = |ident: &[u8]| {
630 let mut raw = b"tree t\nauthor ".to_vec();
631 raw.extend_from_slice(ident);
632 raw.extend_from_slice(b" 1 +0000\ncommitter C <c> 1 +0000\n\nm\n");
633 raw
634 };
635 assert!(!filter.matches_bytes(&named(b"Jos\xc3\xa9 <j@x>")));
636 let filter = CommitFilterBuilder::new()
637 .author("^Jos. <")
638 .build()
639 .unwrap();
640 assert!(filter.matches_bytes(&named(b"Jos\xc3\xa9 <j@x>")));
641 assert!(!filter.matches_bytes(&named(b"Jos\xff <j@x>")));
642 assert!(!filter.matches_bytes(&named(b"Jos <j@x>")));
643
644 let grep = CommitFilterBuilder::new()
645 .grep("^fix.$")
646 .ignore_case(true)
647 .build()
648 .unwrap();
649 let msg = |body: &[u8]| {
650 let mut raw = b"tree t\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\n".to_vec();
651 raw.extend_from_slice(body);
652 raw
653 };
654 assert!(grep.matches_bytes(&msg(b"subject\n\nFIX!\n")));
655 assert!(!grep.matches_bytes(&msg(b"fix\n!\n")));
656 }
657
658 #[test]
659 fn invalid_pattern_names_the_failing_pattern() {
660 let err = CommitFilterBuilder::new()
661 .author("ok")
662 .author("a\\{2")
663 .build()
664 .unwrap_err();
665 let CommitFilterError::InvalidPattern { pattern, .. } = err;
666 assert_eq!(pattern, "a\\{2");
667 }
668
669 #[test]
670 fn bre_bracket_class_preserved() {
671 assert_eq!(bre_translate_to_rust_regex("[ab]").unwrap(), "[ab]");
672 assert_eq!(bre_translate_to_rust_regex("[^ab]").unwrap(), "[^ab]");
673 }
674
675 #[test]
676 fn matcher_author_or_and_grep() {
677 let filter = CommitFilterBuilder::new()
678 .author("Alice")
679 .grep("fix")
680 .build()
681 .unwrap();
682 let commit =
683 b"tree abc\nauthor Alice <a@b.c> 1 +0000\ncommitter Alice <a@b.c> 1 +0000\n\nfix bug\n";
684 assert!(filter.matches_bytes(commit));
685 let other =
686 b"tree abc\nauthor Bob <b@b.c> 1 +0000\ncommitter Bob <b@b.c> 1 +0000\n\nfix bug\n";
687 assert!(!filter.matches_bytes(other));
688 }
689
690 #[test]
691 fn grep_all_match_and_invert() {
692 let both = CommitFilterBuilder::new()
693 .grep("fix")
694 .grep("bug")
695 .all_match(true)
696 .build()
697 .unwrap();
698 let msg = b"tree t\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\nfix bug\n";
699 assert!(both.matches_bytes(msg));
700 let partial = b"tree t\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\nother only\n";
701 assert!(!both.matches_bytes(partial));
702
703 let invert = CommitFilterBuilder::new()
704 .grep("fix")
705 .invert_grep(true)
706 .build()
707 .unwrap();
708 assert!(!invert.matches_bytes(msg));
709 assert!(invert.matches_bytes(partial));
710 }
711
712 #[test]
713 fn fixed_strings_escape_regex() {
714 let filter = CommitFilterBuilder::new()
715 .grep("a+b")
716 .fixed_strings(true)
717 .build()
718 .unwrap();
719 let hit = b"tree t\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\ncontains a+b\n";
720 assert!(filter.matches_bytes(hit));
721 let miss = b"tree t\nauthor A <a> 1 +0000\ncommitter A <a> 1 +0000\n\naaaab\n";
722 assert!(!filter.matches_bytes(miss));
723 }
724
725 #[test]
726 fn non_utf8_author_name_matches_email_pattern() {
727 let filter = CommitFilterBuilder::new()
728 .author("alice@example.com")
729 .build()
730 .unwrap();
731 let commit = b"tree abc\nauthor \xFFAlice <alice@example.com> 1 +0000\ncommitter C <c@x.com> 1 +0000\n\nm\n";
732 assert!(filter.matches_bytes(commit));
733 }
734
735 #[test]
736 fn mailmap_applied_to_author_match() {
737 let mut table = MailmapTable::default();
738 crate::config::mailmap::read_mailmap_string(
739 &mut table,
740 "Proper Name <proper@email.com> <old@email.com>",
741 );
742 let filter = CommitFilterBuilder::new()
743 .author("Proper Name")
744 .mailmap(table)
745 .build()
746 .unwrap();
747 let raw = b"tree t\nauthor Wrong <old@email.com> 1 +0000\ncommitter Wrong <old@email.com> 1 +0000\n\nm\n";
748 assert!(filter.matches_bytes(raw));
749 }
750}