grep: stop modifying buffer in show_line()
[alt-git.git] / grep.c
blob70af01d1c1198448053b923c14c485fc6578ecf8
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "object-store.h"
5 #include "userdiff.h"
6 #include "xdiff-interface.h"
7 #include "diff.h"
8 #include "diffcore.h"
9 #include "commit.h"
10 #include "quote.h"
11 #include "help.h"
13 static int grep_source_load(struct grep_source *gs);
14 static int grep_source_is_binary(struct grep_source *gs,
15 struct index_state *istate);
17 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
19 fwrite(buf, size, 1, stdout);
22 static struct grep_opt grep_defaults = {
23 .relative = 1,
24 .pathname = 1,
25 .max_depth = -1,
26 .pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED,
27 .colors = {
28 [GREP_COLOR_CONTEXT] = "",
29 [GREP_COLOR_FILENAME] = "",
30 [GREP_COLOR_FUNCTION] = "",
31 [GREP_COLOR_LINENO] = "",
32 [GREP_COLOR_COLUMNNO] = "",
33 [GREP_COLOR_MATCH_CONTEXT] = GIT_COLOR_BOLD_RED,
34 [GREP_COLOR_MATCH_SELECTED] = GIT_COLOR_BOLD_RED,
35 [GREP_COLOR_SELECTED] = "",
36 [GREP_COLOR_SEP] = GIT_COLOR_CYAN,
38 .only_matching = 0,
39 .color = -1,
40 .output = std_output,
43 static const char *color_grep_slots[] = {
44 [GREP_COLOR_CONTEXT] = "context",
45 [GREP_COLOR_FILENAME] = "filename",
46 [GREP_COLOR_FUNCTION] = "function",
47 [GREP_COLOR_LINENO] = "lineNumber",
48 [GREP_COLOR_COLUMNNO] = "column",
49 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
50 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
51 [GREP_COLOR_SELECTED] = "selected",
52 [GREP_COLOR_SEP] = "separator",
55 static int parse_pattern_type_arg(const char *opt, const char *arg)
57 if (!strcmp(arg, "default"))
58 return GREP_PATTERN_TYPE_UNSPECIFIED;
59 else if (!strcmp(arg, "basic"))
60 return GREP_PATTERN_TYPE_BRE;
61 else if (!strcmp(arg, "extended"))
62 return GREP_PATTERN_TYPE_ERE;
63 else if (!strcmp(arg, "fixed"))
64 return GREP_PATTERN_TYPE_FIXED;
65 else if (!strcmp(arg, "perl"))
66 return GREP_PATTERN_TYPE_PCRE;
67 die("bad %s argument: %s", opt, arg);
70 define_list_config_array_extra(color_grep_slots, {"match"});
73 * Read the configuration file once and store it in
74 * the grep_defaults template.
76 int grep_config(const char *var, const char *value, void *cb)
78 struct grep_opt *opt = &grep_defaults;
79 const char *slot;
81 if (userdiff_config(var, value) < 0)
82 return -1;
85 * The instance of grep_opt that we set up here is copied by
86 * grep_init() to be used by each individual invocation.
87 * When populating a new field of this structure here, be
88 * sure to think about ownership -- e.g., you might need to
89 * override the shallow copy in grep_init() with a deep copy.
92 if (!strcmp(var, "grep.extendedregexp")) {
93 opt->extended_regexp_option = git_config_bool(var, value);
94 return 0;
97 if (!strcmp(var, "grep.patterntype")) {
98 opt->pattern_type_option = parse_pattern_type_arg(var, value);
99 return 0;
102 if (!strcmp(var, "grep.linenumber")) {
103 opt->linenum = git_config_bool(var, value);
104 return 0;
106 if (!strcmp(var, "grep.column")) {
107 opt->columnnum = git_config_bool(var, value);
108 return 0;
111 if (!strcmp(var, "grep.fullname")) {
112 opt->relative = !git_config_bool(var, value);
113 return 0;
116 if (!strcmp(var, "color.grep"))
117 opt->color = git_config_colorbool(var, value);
118 if (!strcmp(var, "color.grep.match")) {
119 if (grep_config("color.grep.matchcontext", value, cb) < 0)
120 return -1;
121 if (grep_config("color.grep.matchselected", value, cb) < 0)
122 return -1;
123 } else if (skip_prefix(var, "color.grep.", &slot)) {
124 int i = LOOKUP_CONFIG(color_grep_slots, slot);
125 char *color;
127 if (i < 0)
128 return -1;
129 color = opt->colors[i];
130 if (!value)
131 return config_error_nonbool(var);
132 return color_parse(value, color);
134 return 0;
138 * Initialize one instance of grep_opt and copy the
139 * default values from the template we read the configuration
140 * information in an earlier call to git_config(grep_config).
142 void grep_init(struct grep_opt *opt, struct repository *repo, const char *prefix)
144 *opt = grep_defaults;
146 opt->repo = repo;
147 opt->prefix = prefix;
148 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
149 opt->pattern_tail = &opt->pattern_list;
150 opt->header_tail = &opt->header_list;
153 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
156 * When committing to the pattern type by setting the relevant
157 * fields in grep_opt it's generally not necessary to zero out
158 * the fields we're not choosing, since they won't have been
159 * set by anything. The extended_regexp_option field is the
160 * only exception to this.
162 * This is because in the process of parsing grep.patternType
163 * & grep.extendedRegexp we set opt->pattern_type_option and
164 * opt->extended_regexp_option, respectively. We then
165 * internally use opt->extended_regexp_option to see if we're
166 * compiling an ERE. It must be unset if that's not actually
167 * the case.
169 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
170 opt->extended_regexp_option)
171 opt->extended_regexp_option = 0;
173 switch (pattern_type) {
174 case GREP_PATTERN_TYPE_UNSPECIFIED:
175 /* fall through */
177 case GREP_PATTERN_TYPE_BRE:
178 break;
180 case GREP_PATTERN_TYPE_ERE:
181 opt->extended_regexp_option = 1;
182 break;
184 case GREP_PATTERN_TYPE_FIXED:
185 opt->fixed = 1;
186 break;
188 case GREP_PATTERN_TYPE_PCRE:
189 opt->pcre2 = 1;
190 break;
194 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
196 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
197 grep_set_pattern_type_option(pattern_type, opt);
198 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
199 grep_set_pattern_type_option(opt->pattern_type_option, opt);
200 else if (opt->extended_regexp_option)
202 * This branch *must* happen after setting from the
203 * opt->pattern_type_option above, we don't want
204 * grep.extendedRegexp to override grep.patternType!
206 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
209 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
210 const char *origin, int no,
211 enum grep_pat_token t,
212 enum grep_header_field field)
214 struct grep_pat *p = xcalloc(1, sizeof(*p));
215 p->pattern = xmemdupz(pat, patlen);
216 p->patternlen = patlen;
217 p->origin = origin;
218 p->no = no;
219 p->token = t;
220 p->field = field;
221 return p;
224 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
226 **tail = p;
227 *tail = &p->next;
228 p->next = NULL;
230 switch (p->token) {
231 case GREP_PATTERN: /* atom */
232 case GREP_PATTERN_HEAD:
233 case GREP_PATTERN_BODY:
234 for (;;) {
235 struct grep_pat *new_pat;
236 size_t len = 0;
237 char *cp = p->pattern + p->patternlen, *nl = NULL;
238 while (++len <= p->patternlen) {
239 if (*(--cp) == '\n') {
240 nl = cp;
241 break;
244 if (!nl)
245 break;
246 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
247 p->no, p->token, p->field);
248 new_pat->next = p->next;
249 if (!p->next)
250 *tail = &new_pat->next;
251 p->next = new_pat;
252 *nl = '\0';
253 p->patternlen -= len;
255 break;
256 default:
257 break;
261 void append_header_grep_pattern(struct grep_opt *opt,
262 enum grep_header_field field, const char *pat)
264 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
265 GREP_PATTERN_HEAD, field);
266 if (field == GREP_HEADER_REFLOG)
267 opt->use_reflog_filter = 1;
268 do_append_grep_pat(&opt->header_tail, p);
271 void append_grep_pattern(struct grep_opt *opt, const char *pat,
272 const char *origin, int no, enum grep_pat_token t)
274 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
277 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
278 const char *origin, int no, enum grep_pat_token t)
280 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
281 do_append_grep_pat(&opt->pattern_tail, p);
284 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
286 struct grep_pat *pat;
287 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
288 *ret = *opt;
290 ret->pattern_list = NULL;
291 ret->pattern_tail = &ret->pattern_list;
293 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
295 if(pat->token == GREP_PATTERN_HEAD)
296 append_header_grep_pattern(ret, pat->field,
297 pat->pattern);
298 else
299 append_grep_pat(ret, pat->pattern, pat->patternlen,
300 pat->origin, pat->no, pat->token);
303 return ret;
306 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
307 const char *error)
309 char where[1024];
311 if (p->no)
312 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
313 else if (p->origin)
314 xsnprintf(where, sizeof(where), "%s, ", p->origin);
315 else
316 where[0] = 0;
318 die("%s'%s': %s", where, p->pattern, error);
321 static int is_fixed(const char *s, size_t len)
323 size_t i;
325 for (i = 0; i < len; i++) {
326 if (is_regex_special(s[i]))
327 return 0;
330 return 1;
333 #ifdef USE_LIBPCRE2
334 #define GREP_PCRE2_DEBUG_MALLOC 0
336 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
338 void *pointer = malloc(size);
339 #if GREP_PCRE2_DEBUG_MALLOC
340 static int count = 1;
341 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
342 #endif
343 return pointer;
346 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
348 #if GREP_PCRE2_DEBUG_MALLOC
349 static int count = 1;
350 if (pointer)
351 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
352 #endif
353 free(pointer);
356 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
358 int error;
359 PCRE2_UCHAR errbuf[256];
360 PCRE2_SIZE erroffset;
361 int options = PCRE2_MULTILINE;
362 int jitret;
363 int patinforet;
364 size_t jitsizearg;
367 * Call pcre2_general_context_create() before calling any
368 * other pcre2_*(). It sets up our malloc()/free() functions
369 * with which everything else is allocated.
371 p->pcre2_general_context = pcre2_general_context_create(
372 pcre2_malloc, pcre2_free, NULL);
373 if (!p->pcre2_general_context)
374 die("Couldn't allocate PCRE2 general context");
376 if (opt->ignore_case) {
377 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
378 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
379 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
380 pcre2_set_character_tables(p->pcre2_compile_context,
381 p->pcre2_tables);
383 options |= PCRE2_CASELESS;
385 if (!opt->ignore_locale && is_utf8_locale() && has_non_ascii(p->pattern) &&
386 !(!opt->ignore_case && (p->fixed || p->is_fixed)))
387 options |= (PCRE2_UTF | PCRE2_MATCH_INVALID_UTF);
389 #ifdef GIT_PCRE2_VERSION_10_36_OR_HIGHER
390 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
391 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
392 options |= PCRE2_NO_START_OPTIMIZE;
393 #endif
395 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
396 p->patternlen, options, &error, &erroffset,
397 p->pcre2_compile_context);
399 if (p->pcre2_pattern) {
400 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
401 if (!p->pcre2_match_data)
402 die("Couldn't allocate PCRE2 match data");
403 } else {
404 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
405 compile_regexp_failed(p, (const char *)&errbuf);
408 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
409 if (p->pcre2_jit_on) {
410 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
411 if (jitret)
412 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
415 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
416 * tells us whether the library itself supports JIT,
417 * but to see whether we're going to be actually using
418 * JIT we need to extract PCRE2_INFO_JITSIZE from the
419 * pattern *after* we do pcre2_jit_compile() above.
421 * This is because if the pattern contains the
422 * (*NO_JIT) verb (see pcre2syntax(3))
423 * pcre2_jit_compile() will exit early with 0. If we
424 * then proceed to call pcre2_jit_match() further down
425 * the line instead of pcre2_match() we'll either
426 * segfault (pre PCRE 10.31) or run into a fatal error
427 * (post PCRE2 10.31)
429 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
430 if (patinforet)
431 BUG("pcre2_pattern_info() failed: %d", patinforet);
432 if (jitsizearg == 0) {
433 p->pcre2_jit_on = 0;
434 return;
439 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
440 regmatch_t *match, int eflags)
442 int ret, flags = 0;
443 PCRE2_SIZE *ovector;
444 PCRE2_UCHAR errbuf[256];
446 if (eflags & REG_NOTBOL)
447 flags |= PCRE2_NOTBOL;
449 if (p->pcre2_jit_on)
450 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
451 eol - line, 0, flags, p->pcre2_match_data,
452 NULL);
453 else
454 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
455 eol - line, 0, flags, p->pcre2_match_data,
456 NULL);
458 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
459 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
460 die("%s failed with error code %d: %s",
461 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
462 errbuf);
464 if (ret > 0) {
465 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
466 ret = 0;
467 match->rm_so = (int)ovector[0];
468 match->rm_eo = (int)ovector[1];
471 return ret;
474 static void free_pcre2_pattern(struct grep_pat *p)
476 pcre2_compile_context_free(p->pcre2_compile_context);
477 pcre2_code_free(p->pcre2_pattern);
478 pcre2_match_data_free(p->pcre2_match_data);
479 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
480 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
481 #else
482 free((void *)p->pcre2_tables);
483 #endif
484 pcre2_general_context_free(p->pcre2_general_context);
486 #else /* !USE_LIBPCRE2 */
487 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
489 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
492 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
493 regmatch_t *match, int eflags)
495 return 1;
498 static void free_pcre2_pattern(struct grep_pat *p)
502 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
504 struct strbuf sb = STRBUF_INIT;
505 int err;
506 int regflags = 0;
508 basic_regex_quote_buf(&sb, p->pattern);
509 if (opt->ignore_case)
510 regflags |= REG_ICASE;
511 err = regcomp(&p->regexp, sb.buf, regflags);
512 strbuf_release(&sb);
513 if (err) {
514 char errbuf[1024];
515 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
516 compile_regexp_failed(p, errbuf);
519 #endif /* !USE_LIBPCRE2 */
521 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
523 int err;
524 int regflags = REG_NEWLINE;
526 p->word_regexp = opt->word_regexp;
527 p->ignore_case = opt->ignore_case;
528 p->fixed = opt->fixed;
530 if (memchr(p->pattern, 0, p->patternlen) && !opt->pcre2)
531 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
533 p->is_fixed = is_fixed(p->pattern, p->patternlen);
534 #ifdef USE_LIBPCRE2
535 if (!p->fixed && !p->is_fixed) {
536 const char *no_jit = "(*NO_JIT)";
537 const int no_jit_len = strlen(no_jit);
538 if (starts_with(p->pattern, no_jit) &&
539 is_fixed(p->pattern + no_jit_len,
540 p->patternlen - no_jit_len))
541 p->is_fixed = 1;
543 #endif
544 if (p->fixed || p->is_fixed) {
545 #ifdef USE_LIBPCRE2
546 if (p->is_fixed) {
547 compile_pcre2_pattern(p, opt);
548 } else {
550 * E.g. t7811-grep-open.sh relies on the
551 * pattern being restored.
553 char *old_pattern = p->pattern;
554 size_t old_patternlen = p->patternlen;
555 struct strbuf sb = STRBUF_INIT;
558 * There is the PCRE2_LITERAL flag, but it's
559 * only in PCRE v2 10.30 and later. Needing to
560 * ifdef our way around that and dealing with
561 * it + PCRE2_MULTILINE being an error is more
562 * complex than just quoting this ourselves.
564 strbuf_add(&sb, "\\Q", 2);
565 strbuf_add(&sb, p->pattern, p->patternlen);
566 strbuf_add(&sb, "\\E", 2);
568 p->pattern = sb.buf;
569 p->patternlen = sb.len;
570 compile_pcre2_pattern(p, opt);
571 p->pattern = old_pattern;
572 p->patternlen = old_patternlen;
573 strbuf_release(&sb);
575 #else /* !USE_LIBPCRE2 */
576 compile_fixed_regexp(p, opt);
577 #endif /* !USE_LIBPCRE2 */
578 return;
581 if (opt->pcre2) {
582 compile_pcre2_pattern(p, opt);
583 return;
586 if (p->ignore_case)
587 regflags |= REG_ICASE;
588 if (opt->extended_regexp_option)
589 regflags |= REG_EXTENDED;
590 err = regcomp(&p->regexp, p->pattern, regflags);
591 if (err) {
592 char errbuf[1024];
593 regerror(err, &p->regexp, errbuf, 1024);
594 compile_regexp_failed(p, errbuf);
598 static struct grep_expr *compile_pattern_or(struct grep_pat **);
599 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
601 struct grep_pat *p;
602 struct grep_expr *x;
604 p = *list;
605 if (!p)
606 return NULL;
607 switch (p->token) {
608 case GREP_PATTERN: /* atom */
609 case GREP_PATTERN_HEAD:
610 case GREP_PATTERN_BODY:
611 CALLOC_ARRAY(x, 1);
612 x->node = GREP_NODE_ATOM;
613 x->u.atom = p;
614 *list = p->next;
615 return x;
616 case GREP_OPEN_PAREN:
617 *list = p->next;
618 x = compile_pattern_or(list);
619 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
620 die("unmatched parenthesis");
621 *list = (*list)->next;
622 return x;
623 default:
624 return NULL;
628 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
630 struct grep_pat *p;
631 struct grep_expr *x;
633 p = *list;
634 if (!p)
635 return NULL;
636 switch (p->token) {
637 case GREP_NOT:
638 if (!p->next)
639 die("--not not followed by pattern expression");
640 *list = p->next;
641 CALLOC_ARRAY(x, 1);
642 x->node = GREP_NODE_NOT;
643 x->u.unary = compile_pattern_not(list);
644 if (!x->u.unary)
645 die("--not followed by non pattern expression");
646 return x;
647 default:
648 return compile_pattern_atom(list);
652 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
654 struct grep_pat *p;
655 struct grep_expr *x, *y, *z;
657 x = compile_pattern_not(list);
658 p = *list;
659 if (p && p->token == GREP_AND) {
660 if (!x)
661 die("--and not preceded by pattern expression");
662 if (!p->next)
663 die("--and not followed by pattern expression");
664 *list = p->next;
665 y = compile_pattern_and(list);
666 if (!y)
667 die("--and not followed by pattern expression");
668 CALLOC_ARRAY(z, 1);
669 z->node = GREP_NODE_AND;
670 z->u.binary.left = x;
671 z->u.binary.right = y;
672 return z;
674 return x;
677 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
679 struct grep_pat *p;
680 struct grep_expr *x, *y, *z;
682 x = compile_pattern_and(list);
683 p = *list;
684 if (x && p && p->token != GREP_CLOSE_PAREN) {
685 y = compile_pattern_or(list);
686 if (!y)
687 die("not a pattern expression %s", p->pattern);
688 CALLOC_ARRAY(z, 1);
689 z->node = GREP_NODE_OR;
690 z->u.binary.left = x;
691 z->u.binary.right = y;
692 return z;
694 return x;
697 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
699 return compile_pattern_or(list);
702 static struct grep_expr *grep_true_expr(void)
704 struct grep_expr *z = xcalloc(1, sizeof(*z));
705 z->node = GREP_NODE_TRUE;
706 return z;
709 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
711 struct grep_expr *z = xcalloc(1, sizeof(*z));
712 z->node = GREP_NODE_OR;
713 z->u.binary.left = left;
714 z->u.binary.right = right;
715 return z;
718 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
720 struct grep_pat *p;
721 struct grep_expr *header_expr;
722 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
723 enum grep_header_field fld;
725 if (!opt->header_list)
726 return NULL;
728 for (p = opt->header_list; p; p = p->next) {
729 if (p->token != GREP_PATTERN_HEAD)
730 BUG("a non-header pattern in grep header list.");
731 if (p->field < GREP_HEADER_FIELD_MIN ||
732 GREP_HEADER_FIELD_MAX <= p->field)
733 BUG("unknown header field %d", p->field);
734 compile_regexp(p, opt);
737 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
738 header_group[fld] = NULL;
740 for (p = opt->header_list; p; p = p->next) {
741 struct grep_expr *h;
742 struct grep_pat *pp = p;
744 h = compile_pattern_atom(&pp);
745 if (!h || pp != p->next)
746 BUG("malformed header expr");
747 if (!header_group[p->field]) {
748 header_group[p->field] = h;
749 continue;
751 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
754 header_expr = NULL;
756 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
757 if (!header_group[fld])
758 continue;
759 if (!header_expr)
760 header_expr = grep_true_expr();
761 header_expr = grep_or_expr(header_group[fld], header_expr);
763 return header_expr;
766 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
768 struct grep_expr *z = x;
770 while (x) {
771 assert(x->node == GREP_NODE_OR);
772 if (x->u.binary.right &&
773 x->u.binary.right->node == GREP_NODE_TRUE) {
774 x->u.binary.right = y;
775 break;
777 x = x->u.binary.right;
779 return z;
782 void compile_grep_patterns(struct grep_opt *opt)
784 struct grep_pat *p;
785 struct grep_expr *header_expr = prep_header_patterns(opt);
787 for (p = opt->pattern_list; p; p = p->next) {
788 switch (p->token) {
789 case GREP_PATTERN: /* atom */
790 case GREP_PATTERN_HEAD:
791 case GREP_PATTERN_BODY:
792 compile_regexp(p, opt);
793 break;
794 default:
795 opt->extended = 1;
796 break;
800 if (opt->all_match || header_expr)
801 opt->extended = 1;
802 else if (!opt->extended)
803 return;
805 p = opt->pattern_list;
806 if (p)
807 opt->pattern_expression = compile_pattern_expr(&p);
808 if (p)
809 die("incomplete pattern expression: %s", p->pattern);
811 if (!header_expr)
812 return;
814 if (!opt->pattern_expression)
815 opt->pattern_expression = header_expr;
816 else if (opt->all_match)
817 opt->pattern_expression = grep_splice_or(header_expr,
818 opt->pattern_expression);
819 else
820 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
821 header_expr);
822 opt->all_match = 1;
825 static void free_pattern_expr(struct grep_expr *x)
827 switch (x->node) {
828 case GREP_NODE_TRUE:
829 case GREP_NODE_ATOM:
830 break;
831 case GREP_NODE_NOT:
832 free_pattern_expr(x->u.unary);
833 break;
834 case GREP_NODE_AND:
835 case GREP_NODE_OR:
836 free_pattern_expr(x->u.binary.left);
837 free_pattern_expr(x->u.binary.right);
838 break;
840 free(x);
843 void free_grep_patterns(struct grep_opt *opt)
845 struct grep_pat *p, *n;
847 for (p = opt->pattern_list; p; p = n) {
848 n = p->next;
849 switch (p->token) {
850 case GREP_PATTERN: /* atom */
851 case GREP_PATTERN_HEAD:
852 case GREP_PATTERN_BODY:
853 if (p->pcre2_pattern)
854 free_pcre2_pattern(p);
855 else
856 regfree(&p->regexp);
857 free(p->pattern);
858 break;
859 default:
860 break;
862 free(p);
865 if (!opt->extended)
866 return;
867 free_pattern_expr(opt->pattern_expression);
870 static char *end_of_line(char *cp, unsigned long *left)
872 unsigned long l = *left;
873 while (l && *cp != '\n') {
874 l--;
875 cp++;
877 *left = l;
878 return cp;
881 static int word_char(char ch)
883 return isalnum(ch) || ch == '_';
886 static void output_color(struct grep_opt *opt, const void *data, size_t size,
887 const char *color)
889 if (want_color(opt->color) && color && color[0]) {
890 opt->output(opt, color, strlen(color));
891 opt->output(opt, data, size);
892 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
893 } else
894 opt->output(opt, data, size);
897 static void output_sep(struct grep_opt *opt, char sign)
899 if (opt->null_following_name)
900 opt->output(opt, "\0", 1);
901 else
902 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
905 static void show_name(struct grep_opt *opt, const char *name)
907 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
908 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
911 static int patmatch(struct grep_pat *p, char *line, char *eol,
912 regmatch_t *match, int eflags)
914 int hit;
916 if (p->pcre2_pattern)
917 hit = !pcre2match(p, line, eol, match, eflags);
918 else
919 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
920 eflags);
922 return hit;
925 static void strip_timestamp(char *bol, char **eol_p)
927 char *eol = *eol_p;
929 while (bol < --eol) {
930 if (*eol != '>')
931 continue;
932 *eol_p = ++eol;
933 break;
937 static struct {
938 const char *field;
939 size_t len;
940 } header_field[] = {
941 { "author ", 7 },
942 { "committer ", 10 },
943 { "reflog ", 7 },
946 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
947 enum grep_context ctx,
948 regmatch_t *pmatch, int eflags)
950 int hit = 0;
951 const char *start = bol;
953 if ((p->token != GREP_PATTERN) &&
954 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
955 return 0;
957 if (p->token == GREP_PATTERN_HEAD) {
958 const char *field;
959 size_t len;
960 assert(p->field < ARRAY_SIZE(header_field));
961 field = header_field[p->field].field;
962 len = header_field[p->field].len;
963 if (strncmp(bol, field, len))
964 return 0;
965 bol += len;
966 switch (p->field) {
967 case GREP_HEADER_AUTHOR:
968 case GREP_HEADER_COMMITTER:
969 strip_timestamp(bol, &eol);
970 break;
971 default:
972 break;
976 again:
977 hit = patmatch(p, bol, eol, pmatch, eflags);
979 if (hit && p->word_regexp) {
980 if ((pmatch[0].rm_so < 0) ||
981 (eol - bol) < pmatch[0].rm_so ||
982 (pmatch[0].rm_eo < 0) ||
983 (eol - bol) < pmatch[0].rm_eo)
984 die("regexp returned nonsense");
986 /* Match beginning must be either beginning of the
987 * line, or at word boundary (i.e. the last char must
988 * not be a word char). Similarly, match end must be
989 * either end of the line, or at word boundary
990 * (i.e. the next char must not be a word char).
992 if ( ((pmatch[0].rm_so == 0) ||
993 !word_char(bol[pmatch[0].rm_so-1])) &&
994 ((pmatch[0].rm_eo == (eol-bol)) ||
995 !word_char(bol[pmatch[0].rm_eo])) )
997 else
998 hit = 0;
1000 /* Words consist of at least one character. */
1001 if (pmatch->rm_so == pmatch->rm_eo)
1002 hit = 0;
1004 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1005 /* There could be more than one match on the
1006 * line, and the first match might not be
1007 * strict word match. But later ones could be!
1008 * Forward to the next possible start, i.e. the
1009 * next position following a non-word char.
1011 bol = pmatch[0].rm_so + bol + 1;
1012 while (word_char(bol[-1]) && bol < eol)
1013 bol++;
1014 eflags |= REG_NOTBOL;
1015 if (bol < eol)
1016 goto again;
1019 if (hit) {
1020 pmatch[0].rm_so += bol - start;
1021 pmatch[0].rm_eo += bol - start;
1023 return hit;
1026 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
1027 char *eol, enum grep_context ctx, ssize_t *col,
1028 ssize_t *icol, int collect_hits)
1030 int h = 0;
1032 if (!x)
1033 die("Not a valid grep expression");
1034 switch (x->node) {
1035 case GREP_NODE_TRUE:
1036 h = 1;
1037 break;
1038 case GREP_NODE_ATOM:
1040 regmatch_t tmp;
1041 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1042 &tmp, 0);
1043 if (h && (*col < 0 || tmp.rm_so < *col))
1044 *col = tmp.rm_so;
1046 break;
1047 case GREP_NODE_NOT:
1049 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1051 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1053 break;
1054 case GREP_NODE_AND:
1055 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1056 icol, 0);
1057 if (h || opt->columnnum) {
1059 * Don't short-circuit AND when given --column, since a
1060 * NOT earlier in the tree may turn this into an OR. In
1061 * this case, see the below comment.
1063 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1064 ctx, col, icol, 0);
1066 break;
1067 case GREP_NODE_OR:
1068 if (!(collect_hits || opt->columnnum)) {
1070 * Don't short-circuit OR when given --column (or
1071 * collecting hits) to ensure we don't skip a later
1072 * child that would produce an earlier match.
1074 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1075 ctx, col, icol, 0) ||
1076 match_expr_eval(opt, x->u.binary.right, bol,
1077 eol, ctx, col, icol, 0));
1079 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1080 icol, 0);
1081 if (collect_hits)
1082 x->u.binary.left->hit |= h;
1083 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1084 icol, collect_hits);
1085 break;
1086 default:
1087 die("Unexpected node type (internal error) %d", x->node);
1089 if (collect_hits)
1090 x->hit |= h;
1091 return h;
1094 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1095 enum grep_context ctx, ssize_t *col,
1096 ssize_t *icol, int collect_hits)
1098 struct grep_expr *x = opt->pattern_expression;
1099 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1102 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1103 ssize_t *col, ssize_t *icol,
1104 enum grep_context ctx, int collect_hits)
1106 struct grep_pat *p;
1107 int hit = 0;
1109 if (opt->extended)
1110 return match_expr(opt, bol, eol, ctx, col, icol,
1111 collect_hits);
1113 /* we do not call with collect_hits without being extended */
1114 for (p = opt->pattern_list; p; p = p->next) {
1115 regmatch_t tmp;
1116 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1117 hit |= 1;
1118 if (!opt->columnnum) {
1120 * Without --column, any single match on a line
1121 * is enough to know that it needs to be
1122 * printed. With --column, scan _all_ patterns
1123 * to find the earliest.
1125 break;
1127 if (*col < 0 || tmp.rm_so < *col)
1128 *col = tmp.rm_so;
1131 return hit;
1134 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1135 enum grep_context ctx,
1136 regmatch_t *pmatch, int eflags)
1138 regmatch_t match;
1140 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1141 return 0;
1142 if (match.rm_so < 0 || match.rm_eo < 0)
1143 return 0;
1144 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1145 if (match.rm_so > pmatch->rm_so)
1146 return 1;
1147 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1148 return 1;
1150 pmatch->rm_so = match.rm_so;
1151 pmatch->rm_eo = match.rm_eo;
1152 return 1;
1155 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1156 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1158 struct grep_pat *p;
1159 int hit = 0;
1161 pmatch->rm_so = pmatch->rm_eo = -1;
1162 if (bol < eol) {
1163 for (p = opt->pattern_list; p; p = p->next) {
1164 switch (p->token) {
1165 case GREP_PATTERN: /* atom */
1166 case GREP_PATTERN_HEAD:
1167 case GREP_PATTERN_BODY:
1168 hit |= match_next_pattern(p, bol, eol, ctx,
1169 pmatch, eflags);
1170 break;
1171 default:
1172 break;
1176 return hit;
1179 static void show_line_header(struct grep_opt *opt, const char *name,
1180 unsigned lno, ssize_t cno, char sign)
1182 if (opt->heading && opt->last_shown == 0) {
1183 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1184 opt->output(opt, "\n", 1);
1186 opt->last_shown = lno;
1188 if (!opt->heading && opt->pathname) {
1189 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1190 output_sep(opt, sign);
1192 if (opt->linenum) {
1193 char buf[32];
1194 xsnprintf(buf, sizeof(buf), "%d", lno);
1195 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1196 output_sep(opt, sign);
1199 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1200 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1201 * being called with a context line.
1203 if (opt->columnnum && cno) {
1204 char buf[32];
1205 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1206 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1207 output_sep(opt, sign);
1211 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1212 const char *name, unsigned lno, ssize_t cno, char sign)
1214 int rest = eol - bol;
1215 const char *match_color = NULL;
1216 const char *line_color = NULL;
1218 if (opt->file_break && opt->last_shown == 0) {
1219 if (opt->show_hunk_mark)
1220 opt->output(opt, "\n", 1);
1221 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1222 if (opt->last_shown == 0) {
1223 if (opt->show_hunk_mark) {
1224 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1225 opt->output(opt, "\n", 1);
1227 } else if (lno > opt->last_shown + 1) {
1228 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1229 opt->output(opt, "\n", 1);
1232 if (!opt->only_matching) {
1234 * In case the line we're being called with contains more than
1235 * one match, leave printing each header to the loop below.
1237 show_line_header(opt, name, lno, cno, sign);
1239 if (opt->color || opt->only_matching) {
1240 regmatch_t match;
1241 enum grep_context ctx = GREP_CONTEXT_BODY;
1242 int eflags = 0;
1244 if (opt->color) {
1245 if (sign == ':')
1246 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1247 else
1248 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1249 if (sign == ':')
1250 line_color = opt->colors[GREP_COLOR_SELECTED];
1251 else if (sign == '-')
1252 line_color = opt->colors[GREP_COLOR_CONTEXT];
1253 else if (sign == '=')
1254 line_color = opt->colors[GREP_COLOR_FUNCTION];
1256 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1257 if (match.rm_so == match.rm_eo)
1258 break;
1260 if (opt->only_matching)
1261 show_line_header(opt, name, lno, cno, sign);
1262 else
1263 output_color(opt, bol, match.rm_so, line_color);
1264 output_color(opt, bol + match.rm_so,
1265 match.rm_eo - match.rm_so, match_color);
1266 if (opt->only_matching)
1267 opt->output(opt, "\n", 1);
1268 bol += match.rm_eo;
1269 cno += match.rm_eo;
1270 rest -= match.rm_eo;
1271 eflags = REG_NOTBOL;
1274 if (!opt->only_matching) {
1275 output_color(opt, bol, rest, line_color);
1276 opt->output(opt, "\n", 1);
1280 int grep_use_locks;
1283 * This lock protects access to the gitattributes machinery, which is
1284 * not thread-safe.
1286 pthread_mutex_t grep_attr_mutex;
1288 static inline void grep_attr_lock(void)
1290 if (grep_use_locks)
1291 pthread_mutex_lock(&grep_attr_mutex);
1294 static inline void grep_attr_unlock(void)
1296 if (grep_use_locks)
1297 pthread_mutex_unlock(&grep_attr_mutex);
1300 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1302 xdemitconf_t *xecfg = opt->priv;
1303 if (xecfg && !xecfg->find_func) {
1304 grep_source_load_driver(gs, opt->repo->index);
1305 if (gs->driver->funcname.pattern) {
1306 const struct userdiff_funcname *pe = &gs->driver->funcname;
1307 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1308 } else {
1309 xecfg = opt->priv = NULL;
1313 if (xecfg) {
1314 char buf[1];
1315 return xecfg->find_func(bol, eol - bol, buf, 1,
1316 xecfg->find_func_priv) >= 0;
1319 if (bol == eol)
1320 return 0;
1321 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1322 return 1;
1323 return 0;
1326 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1327 char *bol, unsigned lno)
1329 while (bol > gs->buf) {
1330 char *eol = --bol;
1332 while (bol > gs->buf && bol[-1] != '\n')
1333 bol--;
1334 lno--;
1336 if (lno <= opt->last_shown)
1337 break;
1339 if (match_funcname(opt, gs, bol, eol)) {
1340 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1341 break;
1346 static int is_empty_line(const char *bol, const char *eol);
1348 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1349 char *bol, char *end, unsigned lno)
1351 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1352 int funcname_needed = !!opt->funcname, comment_needed = 0;
1354 if (opt->pre_context < lno)
1355 from = lno - opt->pre_context;
1356 if (from <= opt->last_shown)
1357 from = opt->last_shown + 1;
1358 orig_from = from;
1359 if (opt->funcbody) {
1360 if (match_funcname(opt, gs, bol, end))
1361 comment_needed = 1;
1362 else
1363 funcname_needed = 1;
1364 from = opt->last_shown + 1;
1367 /* Rewind. */
1368 while (bol > gs->buf && cur > from) {
1369 char *next_bol = bol;
1370 char *eol = --bol;
1372 while (bol > gs->buf && bol[-1] != '\n')
1373 bol--;
1374 cur--;
1375 if (comment_needed && (is_empty_line(bol, eol) ||
1376 match_funcname(opt, gs, bol, eol))) {
1377 comment_needed = 0;
1378 from = orig_from;
1379 if (cur < from) {
1380 cur++;
1381 bol = next_bol;
1382 break;
1385 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1386 funcname_lno = cur;
1387 funcname_needed = 0;
1388 if (opt->funcbody)
1389 comment_needed = 1;
1390 else
1391 from = orig_from;
1395 /* We need to look even further back to find a function signature. */
1396 if (opt->funcname && funcname_needed)
1397 show_funcname_line(opt, gs, bol, cur);
1399 /* Back forward. */
1400 while (cur < lno) {
1401 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1403 while (*eol != '\n')
1404 eol++;
1405 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1406 bol = eol + 1;
1407 cur++;
1411 static int should_lookahead(struct grep_opt *opt)
1413 struct grep_pat *p;
1415 if (opt->extended)
1416 return 0; /* punt for too complex stuff */
1417 if (opt->invert)
1418 return 0;
1419 for (p = opt->pattern_list; p; p = p->next) {
1420 if (p->token != GREP_PATTERN)
1421 return 0; /* punt for "header only" and stuff */
1423 return 1;
1426 static int look_ahead(struct grep_opt *opt,
1427 unsigned long *left_p,
1428 unsigned *lno_p,
1429 char **bol_p)
1431 unsigned lno = *lno_p;
1432 char *bol = *bol_p;
1433 struct grep_pat *p;
1434 char *sp, *last_bol;
1435 regoff_t earliest = -1;
1437 for (p = opt->pattern_list; p; p = p->next) {
1438 int hit;
1439 regmatch_t m;
1441 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1442 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1443 continue;
1444 if (earliest < 0 || m.rm_so < earliest)
1445 earliest = m.rm_so;
1448 if (earliest < 0) {
1449 *bol_p = bol + *left_p;
1450 *left_p = 0;
1451 return 1;
1453 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1454 ; /* find the beginning of the line */
1455 last_bol = sp;
1457 for (sp = bol; sp < last_bol; sp++) {
1458 if (*sp == '\n')
1459 lno++;
1461 *left_p -= last_bol - bol;
1462 *bol_p = last_bol;
1463 *lno_p = lno;
1464 return 0;
1467 static int fill_textconv_grep(struct repository *r,
1468 struct userdiff_driver *driver,
1469 struct grep_source *gs)
1471 struct diff_filespec *df;
1472 char *buf;
1473 size_t size;
1475 if (!driver || !driver->textconv)
1476 return grep_source_load(gs);
1479 * The textconv interface is intimately tied to diff_filespecs, so we
1480 * have to pretend to be one. If we could unify the grep_source
1481 * and diff_filespec structs, this mess could just go away.
1483 df = alloc_filespec(gs->path);
1484 switch (gs->type) {
1485 case GREP_SOURCE_OID:
1486 fill_filespec(df, gs->identifier, 1, 0100644);
1487 break;
1488 case GREP_SOURCE_FILE:
1489 fill_filespec(df, null_oid(), 0, 0100644);
1490 break;
1491 default:
1492 BUG("attempt to textconv something without a path?");
1496 * fill_textconv is not remotely thread-safe; it modifies the global
1497 * diff tempfile structure, writes to the_repo's odb and might
1498 * internally call thread-unsafe functions such as the
1499 * prepare_packed_git() lazy-initializator. Because of the last two, we
1500 * must ensure mutual exclusion between this call and the object reading
1501 * API, thus we use obj_read_lock() here.
1503 * TODO: allowing text conversion to run in parallel with object
1504 * reading operations might increase performance in the multithreaded
1505 * non-worktreee git-grep with --textconv.
1507 obj_read_lock();
1508 size = fill_textconv(r, driver, df, &buf);
1509 obj_read_unlock();
1510 free_filespec(df);
1513 * The normal fill_textconv usage by the diff machinery would just keep
1514 * the textconv'd buf separate from the diff_filespec. But much of the
1515 * grep code passes around a grep_source and assumes that its "buf"
1516 * pointer is the beginning of the thing we are searching. So let's
1517 * install our textconv'd version into the grep_source, taking care not
1518 * to leak any existing buffer.
1520 grep_source_clear_data(gs);
1521 gs->buf = buf;
1522 gs->size = size;
1524 return 0;
1527 static int is_empty_line(const char *bol, const char *eol)
1529 while (bol < eol && isspace(*bol))
1530 bol++;
1531 return bol == eol;
1534 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1536 char *bol;
1537 char *peek_bol = NULL;
1538 unsigned long left;
1539 unsigned lno = 1;
1540 unsigned last_hit = 0;
1541 int binary_match_only = 0;
1542 unsigned count = 0;
1543 int try_lookahead = 0;
1544 int show_function = 0;
1545 struct userdiff_driver *textconv = NULL;
1546 enum grep_context ctx = GREP_CONTEXT_HEAD;
1547 xdemitconf_t xecfg;
1549 if (!opt->status_only && gs->name == NULL)
1550 BUG("grep call which could print a name requires "
1551 "grep_source.name be non-NULL");
1553 if (!opt->output)
1554 opt->output = std_output;
1556 if (opt->pre_context || opt->post_context || opt->file_break ||
1557 opt->funcbody) {
1558 /* Show hunk marks, except for the first file. */
1559 if (opt->last_shown)
1560 opt->show_hunk_mark = 1;
1562 * If we're using threads then we can't easily identify
1563 * the first file. Always put hunk marks in that case
1564 * and skip the very first one later in work_done().
1566 if (opt->output != std_output)
1567 opt->show_hunk_mark = 1;
1569 opt->last_shown = 0;
1571 if (opt->allow_textconv) {
1572 grep_source_load_driver(gs, opt->repo->index);
1574 * We might set up the shared textconv cache data here, which
1575 * is not thread-safe. Also, get_oid_with_context() and
1576 * parse_object() might be internally called. As they are not
1577 * currently thread-safe and might be racy with object reading,
1578 * obj_read_lock() must be called.
1580 grep_attr_lock();
1581 obj_read_lock();
1582 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1583 obj_read_unlock();
1584 grep_attr_unlock();
1588 * We know the result of a textconv is text, so we only have to care
1589 * about binary handling if we are not using it.
1591 if (!textconv) {
1592 switch (opt->binary) {
1593 case GREP_BINARY_DEFAULT:
1594 if (grep_source_is_binary(gs, opt->repo->index))
1595 binary_match_only = 1;
1596 break;
1597 case GREP_BINARY_NOMATCH:
1598 if (grep_source_is_binary(gs, opt->repo->index))
1599 return 0; /* Assume unmatch */
1600 break;
1601 case GREP_BINARY_TEXT:
1602 break;
1603 default:
1604 BUG("unknown binary handling mode");
1608 memset(&xecfg, 0, sizeof(xecfg));
1609 opt->priv = &xecfg;
1611 try_lookahead = should_lookahead(opt);
1613 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1614 return 0;
1616 bol = gs->buf;
1617 left = gs->size;
1618 while (left) {
1619 char *eol, ch;
1620 int hit;
1621 ssize_t cno;
1622 ssize_t col = -1, icol = -1;
1625 * look_ahead() skips quickly to the line that possibly
1626 * has the next hit; don't call it if we need to do
1627 * something more than just skipping the current line
1628 * in response to an unmatch for the current line. E.g.
1629 * inside a post-context window, we will show the current
1630 * line as a context around the previous hit when it
1631 * doesn't hit.
1633 if (try_lookahead
1634 && !(last_hit
1635 && (show_function ||
1636 lno <= last_hit + opt->post_context))
1637 && look_ahead(opt, &left, &lno, &bol))
1638 break;
1639 eol = end_of_line(bol, &left);
1640 ch = *eol;
1641 *eol = 0;
1643 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1644 ctx = GREP_CONTEXT_BODY;
1646 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1647 *eol = ch;
1649 if (collect_hits)
1650 goto next_line;
1652 /* "grep -v -e foo -e bla" should list lines
1653 * that do not have either, so inversion should
1654 * be done outside.
1656 if (opt->invert)
1657 hit = !hit;
1658 if (opt->unmatch_name_only) {
1659 if (hit)
1660 return 0;
1661 goto next_line;
1663 if (hit) {
1664 count++;
1665 if (opt->status_only)
1666 return 1;
1667 if (opt->name_only) {
1668 show_name(opt, gs->name);
1669 return 1;
1671 if (opt->count)
1672 goto next_line;
1673 if (binary_match_only) {
1674 opt->output(opt, "Binary file ", 12);
1675 output_color(opt, gs->name, strlen(gs->name),
1676 opt->colors[GREP_COLOR_FILENAME]);
1677 opt->output(opt, " matches\n", 9);
1678 return 1;
1680 /* Hit at this line. If we haven't shown the
1681 * pre-context lines, we would need to show them.
1683 if (opt->pre_context || opt->funcbody)
1684 show_pre_context(opt, gs, bol, eol, lno);
1685 else if (opt->funcname)
1686 show_funcname_line(opt, gs, bol, lno);
1687 cno = opt->invert ? icol : col;
1688 if (cno < 0) {
1690 * A negative cno indicates that there was no
1691 * match on the line. We are thus inverted and
1692 * being asked to show all lines that _don't_
1693 * match a given expression. Therefore, set cno
1694 * to 0 to suggest the whole line matches.
1696 cno = 0;
1698 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1699 last_hit = lno;
1700 if (opt->funcbody)
1701 show_function = 1;
1702 goto next_line;
1704 if (show_function && (!peek_bol || peek_bol < bol)) {
1705 unsigned long peek_left = left;
1706 char *peek_eol = eol;
1709 * Trailing empty lines are not interesting.
1710 * Peek past them to see if they belong to the
1711 * body of the current function.
1713 peek_bol = bol;
1714 while (is_empty_line(peek_bol, peek_eol)) {
1715 peek_bol = peek_eol + 1;
1716 peek_eol = end_of_line(peek_bol, &peek_left);
1719 if (match_funcname(opt, gs, peek_bol, peek_eol))
1720 show_function = 0;
1722 if (show_function ||
1723 (last_hit && lno <= last_hit + opt->post_context)) {
1724 /* If the last hit is within the post context,
1725 * we need to show this line.
1727 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1730 next_line:
1731 bol = eol + 1;
1732 if (!left)
1733 break;
1734 left--;
1735 lno++;
1738 if (collect_hits)
1739 return 0;
1741 if (opt->status_only)
1742 return opt->unmatch_name_only;
1743 if (opt->unmatch_name_only) {
1744 /* We did not see any hit, so we want to show this */
1745 show_name(opt, gs->name);
1746 return 1;
1749 xdiff_clear_find_func(&xecfg);
1750 opt->priv = NULL;
1752 /* NEEDSWORK:
1753 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1754 * which feels mostly useless but sometimes useful. Maybe
1755 * make it another option? For now suppress them.
1757 if (opt->count && count) {
1758 char buf[32];
1759 if (opt->pathname) {
1760 output_color(opt, gs->name, strlen(gs->name),
1761 opt->colors[GREP_COLOR_FILENAME]);
1762 output_sep(opt, ':');
1764 xsnprintf(buf, sizeof(buf), "%u\n", count);
1765 opt->output(opt, buf, strlen(buf));
1766 return 1;
1768 return !!last_hit;
1771 static void clr_hit_marker(struct grep_expr *x)
1773 /* All-hit markers are meaningful only at the very top level
1774 * OR node.
1776 while (1) {
1777 x->hit = 0;
1778 if (x->node != GREP_NODE_OR)
1779 return;
1780 x->u.binary.left->hit = 0;
1781 x = x->u.binary.right;
1785 static int chk_hit_marker(struct grep_expr *x)
1787 /* Top level nodes have hit markers. See if they all are hits */
1788 while (1) {
1789 if (x->node != GREP_NODE_OR)
1790 return x->hit;
1791 if (!x->u.binary.left->hit)
1792 return 0;
1793 x = x->u.binary.right;
1797 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1800 * we do not have to do the two-pass grep when we do not check
1801 * buffer-wide "all-match".
1803 if (!opt->all_match)
1804 return grep_source_1(opt, gs, 0);
1806 /* Otherwise the toplevel "or" terms hit a bit differently.
1807 * We first clear hit markers from them.
1809 clr_hit_marker(opt->pattern_expression);
1810 grep_source_1(opt, gs, 1);
1812 if (!chk_hit_marker(opt->pattern_expression))
1813 return 0;
1815 return grep_source_1(opt, gs, 0);
1818 static void grep_source_init_buf(struct grep_source *gs, char *buf,
1819 unsigned long size)
1821 gs->type = GREP_SOURCE_BUF;
1822 gs->name = NULL;
1823 gs->path = NULL;
1824 gs->buf = buf;
1825 gs->size = size;
1826 gs->driver = NULL;
1827 gs->identifier = NULL;
1830 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1832 struct grep_source gs;
1833 int r;
1835 grep_source_init_buf(&gs, buf, size);
1837 r = grep_source(opt, &gs);
1839 grep_source_clear(&gs);
1840 return r;
1843 void grep_source_init_file(struct grep_source *gs, const char *name,
1844 const char *path)
1846 gs->type = GREP_SOURCE_FILE;
1847 gs->name = xstrdup_or_null(name);
1848 gs->path = xstrdup_or_null(path);
1849 gs->buf = NULL;
1850 gs->size = 0;
1851 gs->driver = NULL;
1852 gs->identifier = xstrdup(path);
1855 void grep_source_init_oid(struct grep_source *gs, const char *name,
1856 const char *path, const struct object_id *oid,
1857 struct repository *repo)
1859 gs->type = GREP_SOURCE_OID;
1860 gs->name = xstrdup_or_null(name);
1861 gs->path = xstrdup_or_null(path);
1862 gs->buf = NULL;
1863 gs->size = 0;
1864 gs->driver = NULL;
1865 gs->identifier = oiddup(oid);
1866 gs->repo = repo;
1869 void grep_source_clear(struct grep_source *gs)
1871 FREE_AND_NULL(gs->name);
1872 FREE_AND_NULL(gs->path);
1873 FREE_AND_NULL(gs->identifier);
1874 grep_source_clear_data(gs);
1877 void grep_source_clear_data(struct grep_source *gs)
1879 switch (gs->type) {
1880 case GREP_SOURCE_FILE:
1881 case GREP_SOURCE_OID:
1882 FREE_AND_NULL(gs->buf);
1883 gs->size = 0;
1884 break;
1885 case GREP_SOURCE_BUF:
1886 /* leave user-provided buf intact */
1887 break;
1891 static int grep_source_load_oid(struct grep_source *gs)
1893 enum object_type type;
1895 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1896 &gs->size);
1897 if (!gs->buf)
1898 return error(_("'%s': unable to read %s"),
1899 gs->name,
1900 oid_to_hex(gs->identifier));
1901 return 0;
1904 static int grep_source_load_file(struct grep_source *gs)
1906 const char *filename = gs->identifier;
1907 struct stat st;
1908 char *data;
1909 size_t size;
1910 int i;
1912 if (lstat(filename, &st) < 0) {
1913 err_ret:
1914 if (errno != ENOENT)
1915 error_errno(_("failed to stat '%s'"), filename);
1916 return -1;
1918 if (!S_ISREG(st.st_mode))
1919 return -1;
1920 size = xsize_t(st.st_size);
1921 i = open(filename, O_RDONLY);
1922 if (i < 0)
1923 goto err_ret;
1924 data = xmallocz(size);
1925 if (st.st_size != read_in_full(i, data, size)) {
1926 error_errno(_("'%s': short read"), filename);
1927 close(i);
1928 free(data);
1929 return -1;
1931 close(i);
1933 gs->buf = data;
1934 gs->size = size;
1935 return 0;
1938 static int grep_source_load(struct grep_source *gs)
1940 if (gs->buf)
1941 return 0;
1943 switch (gs->type) {
1944 case GREP_SOURCE_FILE:
1945 return grep_source_load_file(gs);
1946 case GREP_SOURCE_OID:
1947 return grep_source_load_oid(gs);
1948 case GREP_SOURCE_BUF:
1949 return gs->buf ? 0 : -1;
1951 BUG("invalid grep_source type to load");
1954 void grep_source_load_driver(struct grep_source *gs,
1955 struct index_state *istate)
1957 if (gs->driver)
1958 return;
1960 grep_attr_lock();
1961 if (gs->path)
1962 gs->driver = userdiff_find_by_path(istate, gs->path);
1963 if (!gs->driver)
1964 gs->driver = userdiff_find_by_name("default");
1965 grep_attr_unlock();
1968 static int grep_source_is_binary(struct grep_source *gs,
1969 struct index_state *istate)
1971 grep_source_load_driver(gs, istate);
1972 if (gs->driver->binary != -1)
1973 return gs->driver->binary;
1975 if (!grep_source_load(gs))
1976 return buffer_is_binary(gs->buf, gs->size);
1978 return 0;