replace-object.h: move read_replace_refs declaration from cache.h to here
[git.git] / grep.c
blob68e9328dfd49708e871cabb878801d9e0fffaa6b
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "hex.h"
5 #include "object-store.h"
6 #include "userdiff.h"
7 #include "xdiff-interface.h"
8 #include "diff.h"
9 #include "diffcore.h"
10 #include "commit.h"
11 #include "quote.h"
12 #include "help.h"
14 static int grep_source_load(struct grep_source *gs);
15 static int grep_source_is_binary(struct grep_source *gs,
16 struct index_state *istate);
18 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
20 fwrite(buf, size, 1, stdout);
23 static const char *color_grep_slots[] = {
24 [GREP_COLOR_CONTEXT] = "context",
25 [GREP_COLOR_FILENAME] = "filename",
26 [GREP_COLOR_FUNCTION] = "function",
27 [GREP_COLOR_LINENO] = "lineNumber",
28 [GREP_COLOR_COLUMNNO] = "column",
29 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
30 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
31 [GREP_COLOR_SELECTED] = "selected",
32 [GREP_COLOR_SEP] = "separator",
35 static int parse_pattern_type_arg(const char *opt, const char *arg)
37 if (!strcmp(arg, "default"))
38 return GREP_PATTERN_TYPE_UNSPECIFIED;
39 else if (!strcmp(arg, "basic"))
40 return GREP_PATTERN_TYPE_BRE;
41 else if (!strcmp(arg, "extended"))
42 return GREP_PATTERN_TYPE_ERE;
43 else if (!strcmp(arg, "fixed"))
44 return GREP_PATTERN_TYPE_FIXED;
45 else if (!strcmp(arg, "perl"))
46 return GREP_PATTERN_TYPE_PCRE;
47 die("bad %s argument: %s", opt, arg);
50 define_list_config_array_extra(color_grep_slots, {"match"});
53 * Read the configuration file once and store it in
54 * the grep_defaults template.
56 int grep_config(const char *var, const char *value, void *cb)
58 struct grep_opt *opt = cb;
59 const char *slot;
61 if (userdiff_config(var, value) < 0)
62 return -1;
64 if (!strcmp(var, "grep.extendedregexp")) {
65 opt->extended_regexp_option = git_config_bool(var, value);
66 return 0;
69 if (!strcmp(var, "grep.patterntype")) {
70 opt->pattern_type_option = parse_pattern_type_arg(var, value);
71 return 0;
74 if (!strcmp(var, "grep.linenumber")) {
75 opt->linenum = git_config_bool(var, value);
76 return 0;
78 if (!strcmp(var, "grep.column")) {
79 opt->columnnum = git_config_bool(var, value);
80 return 0;
83 if (!strcmp(var, "grep.fullname")) {
84 opt->relative = !git_config_bool(var, value);
85 return 0;
88 if (!strcmp(var, "color.grep"))
89 opt->color = git_config_colorbool(var, value);
90 if (!strcmp(var, "color.grep.match")) {
91 if (grep_config("color.grep.matchcontext", value, cb) < 0)
92 return -1;
93 if (grep_config("color.grep.matchselected", value, cb) < 0)
94 return -1;
95 } else if (skip_prefix(var, "color.grep.", &slot)) {
96 int i = LOOKUP_CONFIG(color_grep_slots, slot);
97 char *color;
99 if (i < 0)
100 return -1;
101 color = opt->colors[i];
102 if (!value)
103 return config_error_nonbool(var);
104 return color_parse(value, color);
106 return 0;
109 void grep_init(struct grep_opt *opt, struct repository *repo)
111 struct grep_opt blank = GREP_OPT_INIT;
112 memcpy(opt, &blank, sizeof(*opt));
114 opt->repo = repo;
115 opt->pattern_tail = &opt->pattern_list;
116 opt->header_tail = &opt->header_list;
119 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
120 const char *origin, int no,
121 enum grep_pat_token t,
122 enum grep_header_field field)
124 struct grep_pat *p = xcalloc(1, sizeof(*p));
125 p->pattern = xmemdupz(pat, patlen);
126 p->patternlen = patlen;
127 p->origin = origin;
128 p->no = no;
129 p->token = t;
130 p->field = field;
131 return p;
134 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
136 **tail = p;
137 *tail = &p->next;
138 p->next = NULL;
140 switch (p->token) {
141 case GREP_PATTERN: /* atom */
142 case GREP_PATTERN_HEAD:
143 case GREP_PATTERN_BODY:
144 for (;;) {
145 struct grep_pat *new_pat;
146 size_t len = 0;
147 char *cp = p->pattern + p->patternlen, *nl = NULL;
148 while (++len <= p->patternlen) {
149 if (*(--cp) == '\n') {
150 nl = cp;
151 break;
154 if (!nl)
155 break;
156 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
157 p->no, p->token, p->field);
158 new_pat->next = p->next;
159 if (!p->next)
160 *tail = &new_pat->next;
161 p->next = new_pat;
162 *nl = '\0';
163 p->patternlen -= len;
165 break;
166 default:
167 break;
171 void append_header_grep_pattern(struct grep_opt *opt,
172 enum grep_header_field field, const char *pat)
174 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
175 GREP_PATTERN_HEAD, field);
176 if (field == GREP_HEADER_REFLOG)
177 opt->use_reflog_filter = 1;
178 do_append_grep_pat(&opt->header_tail, p);
181 void append_grep_pattern(struct grep_opt *opt, const char *pat,
182 const char *origin, int no, enum grep_pat_token t)
184 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
187 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
188 const char *origin, int no, enum grep_pat_token t)
190 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
191 do_append_grep_pat(&opt->pattern_tail, p);
194 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
196 struct grep_pat *pat;
197 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
198 *ret = *opt;
200 ret->pattern_list = NULL;
201 ret->pattern_tail = &ret->pattern_list;
203 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
205 if(pat->token == GREP_PATTERN_HEAD)
206 append_header_grep_pattern(ret, pat->field,
207 pat->pattern);
208 else
209 append_grep_pat(ret, pat->pattern, pat->patternlen,
210 pat->origin, pat->no, pat->token);
213 return ret;
216 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
217 const char *error)
219 char where[1024];
221 if (p->no)
222 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
223 else if (p->origin)
224 xsnprintf(where, sizeof(where), "%s, ", p->origin);
225 else
226 where[0] = 0;
228 die("%s'%s': %s", where, p->pattern, error);
231 static int is_fixed(const char *s, size_t len)
233 size_t i;
235 for (i = 0; i < len; i++) {
236 if (is_regex_special(s[i]))
237 return 0;
240 return 1;
243 #ifdef USE_LIBPCRE2
244 #define GREP_PCRE2_DEBUG_MALLOC 0
246 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
248 void *pointer = malloc(size);
249 #if GREP_PCRE2_DEBUG_MALLOC
250 static int count = 1;
251 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
252 #endif
253 return pointer;
256 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
258 #if GREP_PCRE2_DEBUG_MALLOC
259 static int count = 1;
260 if (pointer)
261 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
262 #endif
263 free(pointer);
266 static int pcre2_jit_functional(void)
268 static int jit_working = -1;
269 pcre2_code *code;
270 size_t off;
271 int err;
273 if (jit_working != -1)
274 return jit_working;
277 * Try to JIT compile a simple pattern to probe if the JIT is
278 * working in general. It might fail for systems where creating
279 * memory mappings for runtime code generation is restricted.
281 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
282 if (!code)
283 return 0;
285 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
286 pcre2_code_free(code);
288 return jit_working;
291 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
293 int error;
294 PCRE2_UCHAR errbuf[256];
295 PCRE2_SIZE erroffset;
296 int options = PCRE2_MULTILINE;
297 int jitret;
298 int patinforet;
299 size_t jitsizearg;
300 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
303 * Call pcre2_general_context_create() before calling any
304 * other pcre2_*(). It sets up our malloc()/free() functions
305 * with which everything else is allocated.
307 p->pcre2_general_context = pcre2_general_context_create(
308 pcre2_malloc, pcre2_free, NULL);
309 if (!p->pcre2_general_context)
310 die("Couldn't allocate PCRE2 general context");
312 if (opt->ignore_case) {
313 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
314 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
315 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
316 pcre2_set_character_tables(p->pcre2_compile_context,
317 p->pcre2_tables);
319 options |= PCRE2_CASELESS;
321 if (!opt->ignore_locale && is_utf8_locale() && !literal)
322 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
324 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
325 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
326 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
327 options |= PCRE2_NO_START_OPTIMIZE;
328 #endif
330 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
331 p->patternlen, options, &error, &erroffset,
332 p->pcre2_compile_context);
334 if (p->pcre2_pattern) {
335 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
336 if (!p->pcre2_match_data)
337 die("Couldn't allocate PCRE2 match data");
338 } else {
339 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
340 compile_regexp_failed(p, (const char *)&errbuf);
343 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
344 if (p->pcre2_jit_on) {
345 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
346 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
348 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
349 * indicated JIT support, the library might still
350 * fail to generate JIT code for various reasons,
351 * e.g. when SELinux's 'deny_execmem' or PaX's
352 * MPROTECT prevent creating W|X memory mappings.
354 * Instead of faling hard, fall back to interpreter
355 * mode, just as if the pattern was prefixed with
356 * '(*NO_JIT)'.
358 p->pcre2_jit_on = 0;
359 return;
360 } else if (jitret) {
361 int need_clip = p->patternlen > 64;
362 int clip_len = need_clip ? 64 : p->patternlen;
363 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
364 clip_len, p->pattern, need_clip ? "..." : "", jitret,
365 pcre2_jit_functional()
366 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
367 : "");
371 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
372 * tells us whether the library itself supports JIT,
373 * but to see whether we're going to be actually using
374 * JIT we need to extract PCRE2_INFO_JITSIZE from the
375 * pattern *after* we do pcre2_jit_compile() above.
377 * This is because if the pattern contains the
378 * (*NO_JIT) verb (see pcre2syntax(3))
379 * pcre2_jit_compile() will exit early with 0. If we
380 * then proceed to call pcre2_jit_match() further down
381 * the line instead of pcre2_match() we'll either
382 * segfault (pre PCRE 10.31) or run into a fatal error
383 * (post PCRE2 10.31)
385 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
386 if (patinforet)
387 BUG("pcre2_pattern_info() failed: %d", patinforet);
388 if (jitsizearg == 0) {
389 p->pcre2_jit_on = 0;
390 return;
395 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
396 regmatch_t *match, int eflags)
398 int ret, flags = 0;
399 PCRE2_SIZE *ovector;
400 PCRE2_UCHAR errbuf[256];
402 if (eflags & REG_NOTBOL)
403 flags |= PCRE2_NOTBOL;
405 if (p->pcre2_jit_on)
406 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
407 eol - line, 0, flags, p->pcre2_match_data,
408 NULL);
409 else
410 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
411 eol - line, 0, flags, p->pcre2_match_data,
412 NULL);
414 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
415 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
416 die("%s failed with error code %d: %s",
417 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
418 errbuf);
420 if (ret > 0) {
421 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
422 ret = 0;
423 match->rm_so = (int)ovector[0];
424 match->rm_eo = (int)ovector[1];
427 return ret;
430 static void free_pcre2_pattern(struct grep_pat *p)
432 pcre2_compile_context_free(p->pcre2_compile_context);
433 pcre2_code_free(p->pcre2_pattern);
434 pcre2_match_data_free(p->pcre2_match_data);
435 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
436 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
437 #else
438 free((void *)p->pcre2_tables);
439 #endif
440 pcre2_general_context_free(p->pcre2_general_context);
442 #else /* !USE_LIBPCRE2 */
443 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
445 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
448 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
449 regmatch_t *match, int eflags)
451 return 1;
454 static void free_pcre2_pattern(struct grep_pat *p)
458 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
460 struct strbuf sb = STRBUF_INIT;
461 int err;
462 int regflags = 0;
464 basic_regex_quote_buf(&sb, p->pattern);
465 if (opt->ignore_case)
466 regflags |= REG_ICASE;
467 err = regcomp(&p->regexp, sb.buf, regflags);
468 strbuf_release(&sb);
469 if (err) {
470 char errbuf[1024];
471 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
472 compile_regexp_failed(p, errbuf);
475 #endif /* !USE_LIBPCRE2 */
477 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
479 int err;
480 int regflags = REG_NEWLINE;
482 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
483 opt->pattern_type_option = (opt->extended_regexp_option
484 ? GREP_PATTERN_TYPE_ERE
485 : GREP_PATTERN_TYPE_BRE);
487 p->word_regexp = opt->word_regexp;
488 p->ignore_case = opt->ignore_case;
489 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
491 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
492 memchr(p->pattern, 0, p->patternlen))
493 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
495 p->is_fixed = is_fixed(p->pattern, p->patternlen);
496 #ifdef USE_LIBPCRE2
497 if (!p->fixed && !p->is_fixed) {
498 const char *no_jit = "(*NO_JIT)";
499 const int no_jit_len = strlen(no_jit);
500 if (starts_with(p->pattern, no_jit) &&
501 is_fixed(p->pattern + no_jit_len,
502 p->patternlen - no_jit_len))
503 p->is_fixed = 1;
505 #endif
506 if (p->fixed || p->is_fixed) {
507 #ifdef USE_LIBPCRE2
508 if (p->is_fixed) {
509 compile_pcre2_pattern(p, opt);
510 } else {
512 * E.g. t7811-grep-open.sh relies on the
513 * pattern being restored.
515 char *old_pattern = p->pattern;
516 size_t old_patternlen = p->patternlen;
517 struct strbuf sb = STRBUF_INIT;
520 * There is the PCRE2_LITERAL flag, but it's
521 * only in PCRE v2 10.30 and later. Needing to
522 * ifdef our way around that and dealing with
523 * it + PCRE2_MULTILINE being an error is more
524 * complex than just quoting this ourselves.
526 strbuf_add(&sb, "\\Q", 2);
527 strbuf_add(&sb, p->pattern, p->patternlen);
528 strbuf_add(&sb, "\\E", 2);
530 p->pattern = sb.buf;
531 p->patternlen = sb.len;
532 compile_pcre2_pattern(p, opt);
533 p->pattern = old_pattern;
534 p->patternlen = old_patternlen;
535 strbuf_release(&sb);
537 #else /* !USE_LIBPCRE2 */
538 compile_fixed_regexp(p, opt);
539 #endif /* !USE_LIBPCRE2 */
540 return;
543 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
544 compile_pcre2_pattern(p, opt);
545 return;
548 if (p->ignore_case)
549 regflags |= REG_ICASE;
550 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
551 regflags |= REG_EXTENDED;
552 err = regcomp(&p->regexp, p->pattern, regflags);
553 if (err) {
554 char errbuf[1024];
555 regerror(err, &p->regexp, errbuf, 1024);
556 compile_regexp_failed(p, errbuf);
560 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
562 struct grep_expr *z = xcalloc(1, sizeof(*z));
563 z->node = GREP_NODE_NOT;
564 z->u.unary = expr;
565 return z;
568 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
569 struct grep_expr *left,
570 struct grep_expr *right)
572 struct grep_expr *z = xcalloc(1, sizeof(*z));
573 z->node = kind;
574 z->u.binary.left = left;
575 z->u.binary.right = right;
576 return z;
579 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
581 return grep_binexp(GREP_NODE_OR, left, right);
584 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
586 return grep_binexp(GREP_NODE_AND, left, right);
589 static struct grep_expr *compile_pattern_or(struct grep_pat **);
590 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
592 struct grep_pat *p;
593 struct grep_expr *x;
595 p = *list;
596 if (!p)
597 return NULL;
598 switch (p->token) {
599 case GREP_PATTERN: /* atom */
600 case GREP_PATTERN_HEAD:
601 case GREP_PATTERN_BODY:
602 CALLOC_ARRAY(x, 1);
603 x->node = GREP_NODE_ATOM;
604 x->u.atom = p;
605 *list = p->next;
606 return x;
607 case GREP_OPEN_PAREN:
608 *list = p->next;
609 x = compile_pattern_or(list);
610 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
611 die("unmatched parenthesis");
612 *list = (*list)->next;
613 return x;
614 default:
615 return NULL;
619 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
621 struct grep_pat *p;
622 struct grep_expr *x;
624 p = *list;
625 if (!p)
626 return NULL;
627 switch (p->token) {
628 case GREP_NOT:
629 if (!p->next)
630 die("--not not followed by pattern expression");
631 *list = p->next;
632 x = compile_pattern_not(list);
633 if (!x)
634 die("--not followed by non pattern expression");
635 return grep_not_expr(x);
636 default:
637 return compile_pattern_atom(list);
641 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
643 struct grep_pat *p;
644 struct grep_expr *x, *y;
646 x = compile_pattern_not(list);
647 p = *list;
648 if (p && p->token == GREP_AND) {
649 if (!x)
650 die("--and not preceded by pattern expression");
651 if (!p->next)
652 die("--and not followed by pattern expression");
653 *list = p->next;
654 y = compile_pattern_and(list);
655 if (!y)
656 die("--and not followed by pattern expression");
657 return grep_and_expr(x, y);
659 return x;
662 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
664 struct grep_pat *p;
665 struct grep_expr *x, *y;
667 x = compile_pattern_and(list);
668 p = *list;
669 if (x && p && p->token != GREP_CLOSE_PAREN) {
670 y = compile_pattern_or(list);
671 if (!y)
672 die("not a pattern expression %s", p->pattern);
673 return grep_or_expr(x, y);
675 return x;
678 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
680 return compile_pattern_or(list);
683 static struct grep_expr *grep_true_expr(void)
685 struct grep_expr *z = xcalloc(1, sizeof(*z));
686 z->node = GREP_NODE_TRUE;
687 return z;
690 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
692 struct grep_pat *p;
693 struct grep_expr *header_expr;
694 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
695 enum grep_header_field fld;
697 if (!opt->header_list)
698 return NULL;
700 for (p = opt->header_list; p; p = p->next) {
701 if (p->token != GREP_PATTERN_HEAD)
702 BUG("a non-header pattern in grep header list.");
703 if (p->field < GREP_HEADER_FIELD_MIN ||
704 GREP_HEADER_FIELD_MAX <= p->field)
705 BUG("unknown header field %d", p->field);
706 compile_regexp(p, opt);
709 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
710 header_group[fld] = NULL;
712 for (p = opt->header_list; p; p = p->next) {
713 struct grep_expr *h;
714 struct grep_pat *pp = p;
716 h = compile_pattern_atom(&pp);
717 if (!h || pp != p->next)
718 BUG("malformed header expr");
719 if (!header_group[p->field]) {
720 header_group[p->field] = h;
721 continue;
723 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
726 header_expr = NULL;
728 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
729 if (!header_group[fld])
730 continue;
731 if (!header_expr)
732 header_expr = grep_true_expr();
733 header_expr = grep_or_expr(header_group[fld], header_expr);
735 return header_expr;
738 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
740 struct grep_expr *z = x;
742 while (x) {
743 assert(x->node == GREP_NODE_OR);
744 if (x->u.binary.right &&
745 x->u.binary.right->node == GREP_NODE_TRUE) {
746 x->u.binary.right = y;
747 break;
749 x = x->u.binary.right;
751 return z;
754 void compile_grep_patterns(struct grep_opt *opt)
756 struct grep_pat *p;
757 struct grep_expr *header_expr = prep_header_patterns(opt);
758 int extended = 0;
760 for (p = opt->pattern_list; p; p = p->next) {
761 switch (p->token) {
762 case GREP_PATTERN: /* atom */
763 case GREP_PATTERN_HEAD:
764 case GREP_PATTERN_BODY:
765 compile_regexp(p, opt);
766 break;
767 default:
768 extended = 1;
769 break;
773 if (opt->all_match || opt->no_body_match || header_expr)
774 extended = 1;
775 else if (!extended)
776 return;
778 p = opt->pattern_list;
779 if (p)
780 opt->pattern_expression = compile_pattern_expr(&p);
781 if (p)
782 die("incomplete pattern expression: %s", p->pattern);
784 if (opt->no_body_match && opt->pattern_expression)
785 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
787 if (!header_expr)
788 return;
790 if (!opt->pattern_expression)
791 opt->pattern_expression = header_expr;
792 else if (opt->all_match)
793 opt->pattern_expression = grep_splice_or(header_expr,
794 opt->pattern_expression);
795 else
796 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
797 header_expr);
798 opt->all_match = 1;
801 static void free_pattern_expr(struct grep_expr *x)
803 switch (x->node) {
804 case GREP_NODE_TRUE:
805 case GREP_NODE_ATOM:
806 break;
807 case GREP_NODE_NOT:
808 free_pattern_expr(x->u.unary);
809 break;
810 case GREP_NODE_AND:
811 case GREP_NODE_OR:
812 free_pattern_expr(x->u.binary.left);
813 free_pattern_expr(x->u.binary.right);
814 break;
816 free(x);
819 static void free_grep_pat(struct grep_pat *pattern)
821 struct grep_pat *p, *n;
823 for (p = pattern; p; p = n) {
824 n = p->next;
825 switch (p->token) {
826 case GREP_PATTERN: /* atom */
827 case GREP_PATTERN_HEAD:
828 case GREP_PATTERN_BODY:
829 if (p->pcre2_pattern)
830 free_pcre2_pattern(p);
831 else
832 regfree(&p->regexp);
833 free(p->pattern);
834 break;
835 default:
836 break;
838 free(p);
842 void free_grep_patterns(struct grep_opt *opt)
844 free_grep_pat(opt->pattern_list);
845 free_grep_pat(opt->header_list);
847 if (opt->pattern_expression)
848 free_pattern_expr(opt->pattern_expression);
851 static const char *end_of_line(const char *cp, unsigned long *left)
853 unsigned long l = *left;
854 while (l && *cp != '\n') {
855 l--;
856 cp++;
858 *left = l;
859 return cp;
862 static int word_char(char ch)
864 return isalnum(ch) || ch == '_';
867 static void output_color(struct grep_opt *opt, const void *data, size_t size,
868 const char *color)
870 if (want_color(opt->color) && color && color[0]) {
871 opt->output(opt, color, strlen(color));
872 opt->output(opt, data, size);
873 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
874 } else
875 opt->output(opt, data, size);
878 static void output_sep(struct grep_opt *opt, char sign)
880 if (opt->null_following_name)
881 opt->output(opt, "\0", 1);
882 else
883 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
886 static void show_name(struct grep_opt *opt, const char *name)
888 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
889 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
892 static int patmatch(struct grep_pat *p,
893 const char *line, const char *eol,
894 regmatch_t *match, int eflags)
896 int hit;
898 if (p->pcre2_pattern)
899 hit = !pcre2match(p, line, eol, match, eflags);
900 else
901 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
902 eflags);
904 return hit;
907 static void strip_timestamp(const char *bol, const char **eol_p)
909 const char *eol = *eol_p;
911 while (bol < --eol) {
912 if (*eol != '>')
913 continue;
914 *eol_p = ++eol;
915 break;
919 static struct {
920 const char *field;
921 size_t len;
922 } header_field[] = {
923 { "author ", 7 },
924 { "committer ", 10 },
925 { "reflog ", 7 },
928 static int headerless_match_one_pattern(struct grep_pat *p,
929 const char *bol, const char *eol,
930 enum grep_context ctx,
931 regmatch_t *pmatch, int eflags)
933 int hit = 0;
934 const char *start = bol;
936 if ((p->token != GREP_PATTERN) &&
937 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
938 return 0;
940 again:
941 hit = patmatch(p, bol, eol, pmatch, eflags);
943 if (hit && p->word_regexp) {
944 if ((pmatch[0].rm_so < 0) ||
945 (eol - bol) < pmatch[0].rm_so ||
946 (pmatch[0].rm_eo < 0) ||
947 (eol - bol) < pmatch[0].rm_eo)
948 die("regexp returned nonsense");
950 /* Match beginning must be either beginning of the
951 * line, or at word boundary (i.e. the last char must
952 * not be a word char). Similarly, match end must be
953 * either end of the line, or at word boundary
954 * (i.e. the next char must not be a word char).
956 if ( ((pmatch[0].rm_so == 0) ||
957 !word_char(bol[pmatch[0].rm_so-1])) &&
958 ((pmatch[0].rm_eo == (eol-bol)) ||
959 !word_char(bol[pmatch[0].rm_eo])) )
961 else
962 hit = 0;
964 /* Words consist of at least one character. */
965 if (pmatch->rm_so == pmatch->rm_eo)
966 hit = 0;
968 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
969 /* There could be more than one match on the
970 * line, and the first match might not be
971 * strict word match. But later ones could be!
972 * Forward to the next possible start, i.e. the
973 * next position following a non-word char.
975 bol = pmatch[0].rm_so + bol + 1;
976 while (word_char(bol[-1]) && bol < eol)
977 bol++;
978 eflags |= REG_NOTBOL;
979 if (bol < eol)
980 goto again;
983 if (hit) {
984 pmatch[0].rm_so += bol - start;
985 pmatch[0].rm_eo += bol - start;
987 return hit;
990 static int match_one_pattern(struct grep_pat *p,
991 const char *bol, const char *eol,
992 enum grep_context ctx, regmatch_t *pmatch,
993 int eflags)
995 const char *field;
996 size_t len;
998 if (p->token == GREP_PATTERN_HEAD) {
999 assert(p->field < ARRAY_SIZE(header_field));
1000 field = header_field[p->field].field;
1001 len = header_field[p->field].len;
1002 if (strncmp(bol, field, len))
1003 return 0;
1004 bol += len;
1006 switch (p->field) {
1007 case GREP_HEADER_AUTHOR:
1008 case GREP_HEADER_COMMITTER:
1009 strip_timestamp(bol, &eol);
1010 break;
1011 default:
1012 break;
1016 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1020 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1021 const char *bol, const char *eol,
1022 enum grep_context ctx, ssize_t *col,
1023 ssize_t *icol, int collect_hits)
1025 int h = 0;
1027 switch (x->node) {
1028 case GREP_NODE_TRUE:
1029 h = 1;
1030 break;
1031 case GREP_NODE_ATOM:
1033 regmatch_t tmp;
1034 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1035 &tmp, 0);
1036 if (h && (*col < 0 || tmp.rm_so < *col))
1037 *col = tmp.rm_so;
1039 if (x->u.atom->token == GREP_PATTERN_BODY)
1040 opt->body_hit |= h;
1041 break;
1042 case GREP_NODE_NOT:
1044 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1046 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1048 break;
1049 case GREP_NODE_AND:
1050 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1051 icol, 0);
1052 if (h || opt->columnnum) {
1054 * Don't short-circuit AND when given --column, since a
1055 * NOT earlier in the tree may turn this into an OR. In
1056 * this case, see the below comment.
1058 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1059 ctx, col, icol, 0);
1061 break;
1062 case GREP_NODE_OR:
1063 if (!(collect_hits || opt->columnnum)) {
1065 * Don't short-circuit OR when given --column (or
1066 * collecting hits) to ensure we don't skip a later
1067 * child that would produce an earlier match.
1069 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1070 ctx, col, icol, 0) ||
1071 match_expr_eval(opt, x->u.binary.right, bol,
1072 eol, ctx, col, icol, 0));
1074 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1075 icol, 0);
1076 if (collect_hits)
1077 x->u.binary.left->hit |= h;
1078 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1079 icol, collect_hits);
1080 break;
1081 default:
1082 die("Unexpected node type (internal error) %d", x->node);
1084 if (collect_hits)
1085 x->hit |= h;
1086 return h;
1089 static int match_expr(struct grep_opt *opt,
1090 const char *bol, const char *eol,
1091 enum grep_context ctx, ssize_t *col,
1092 ssize_t *icol, int collect_hits)
1094 struct grep_expr *x = opt->pattern_expression;
1095 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1098 static int match_line(struct grep_opt *opt,
1099 const char *bol, const char *eol,
1100 ssize_t *col, ssize_t *icol,
1101 enum grep_context ctx, int collect_hits)
1103 struct grep_pat *p;
1104 int hit = 0;
1106 if (opt->pattern_expression)
1107 return match_expr(opt, bol, eol, ctx, col, icol,
1108 collect_hits);
1110 /* we do not call with collect_hits without being extended */
1111 for (p = opt->pattern_list; p; p = p->next) {
1112 regmatch_t tmp;
1113 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1114 hit |= 1;
1115 if (!opt->columnnum) {
1117 * Without --column, any single match on a line
1118 * is enough to know that it needs to be
1119 * printed. With --column, scan _all_ patterns
1120 * to find the earliest.
1122 break;
1124 if (*col < 0 || tmp.rm_so < *col)
1125 *col = tmp.rm_so;
1128 return hit;
1131 static int match_next_pattern(struct grep_pat *p,
1132 const char *bol, const char *eol,
1133 enum grep_context ctx,
1134 regmatch_t *pmatch, int eflags)
1136 regmatch_t match;
1138 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1139 return 0;
1140 if (match.rm_so < 0 || match.rm_eo < 0)
1141 return 0;
1142 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1143 if (match.rm_so > pmatch->rm_so)
1144 return 1;
1145 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1146 return 1;
1148 pmatch->rm_so = match.rm_so;
1149 pmatch->rm_eo = match.rm_eo;
1150 return 1;
1153 int grep_next_match(struct grep_opt *opt,
1154 const char *bol, const char *eol,
1155 enum grep_context ctx, regmatch_t *pmatch,
1156 enum grep_header_field field, 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 = ((ctx == GREP_CONTEXT_HEAD)
1164 ? opt->header_list : opt->pattern_list);
1165 p; p = p->next) {
1166 switch (p->token) {
1167 case GREP_PATTERN_HEAD:
1168 if ((field != GREP_HEADER_FIELD_MAX) &&
1169 (p->field != field))
1170 continue;
1171 /* fall thru */
1172 case GREP_PATTERN: /* atom */
1173 case GREP_PATTERN_BODY:
1174 hit |= match_next_pattern(p, bol, eol, ctx,
1175 pmatch, eflags);
1176 break;
1177 default:
1178 break;
1182 return hit;
1185 static void show_line_header(struct grep_opt *opt, const char *name,
1186 unsigned lno, ssize_t cno, char sign)
1188 if (opt->heading && opt->last_shown == 0) {
1189 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1190 opt->output(opt, "\n", 1);
1192 opt->last_shown = lno;
1194 if (!opt->heading && opt->pathname) {
1195 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1196 output_sep(opt, sign);
1198 if (opt->linenum) {
1199 char buf[32];
1200 xsnprintf(buf, sizeof(buf), "%d", lno);
1201 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1202 output_sep(opt, sign);
1205 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1206 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1207 * being called with a context line.
1209 if (opt->columnnum && cno) {
1210 char buf[32];
1211 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1212 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1213 output_sep(opt, sign);
1217 static void show_line(struct grep_opt *opt,
1218 const char *bol, const char *eol,
1219 const char *name, unsigned lno, ssize_t cno, char sign)
1221 int rest = eol - bol;
1222 const char *match_color = NULL;
1223 const char *line_color = NULL;
1225 if (opt->file_break && opt->last_shown == 0) {
1226 if (opt->show_hunk_mark)
1227 opt->output(opt, "\n", 1);
1228 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1229 if (opt->last_shown == 0) {
1230 if (opt->show_hunk_mark) {
1231 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1232 opt->output(opt, "\n", 1);
1234 } else if (lno > opt->last_shown + 1) {
1235 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1236 opt->output(opt, "\n", 1);
1239 if (!opt->only_matching) {
1241 * In case the line we're being called with contains more than
1242 * one match, leave printing each header to the loop below.
1244 show_line_header(opt, name, lno, cno, sign);
1246 if (opt->color || opt->only_matching) {
1247 regmatch_t match;
1248 enum grep_context ctx = GREP_CONTEXT_BODY;
1249 int eflags = 0;
1251 if (opt->color) {
1252 if (sign == ':')
1253 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1254 else
1255 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1256 if (sign == ':')
1257 line_color = opt->colors[GREP_COLOR_SELECTED];
1258 else if (sign == '-')
1259 line_color = opt->colors[GREP_COLOR_CONTEXT];
1260 else if (sign == '=')
1261 line_color = opt->colors[GREP_COLOR_FUNCTION];
1263 while (grep_next_match(opt, bol, eol, ctx, &match,
1264 GREP_HEADER_FIELD_MAX, eflags)) {
1265 if (match.rm_so == match.rm_eo)
1266 break;
1268 if (opt->only_matching)
1269 show_line_header(opt, name, lno, cno, sign);
1270 else
1271 output_color(opt, bol, match.rm_so, line_color);
1272 output_color(opt, bol + match.rm_so,
1273 match.rm_eo - match.rm_so, match_color);
1274 if (opt->only_matching)
1275 opt->output(opt, "\n", 1);
1276 bol += match.rm_eo;
1277 cno += match.rm_eo;
1278 rest -= match.rm_eo;
1279 eflags = REG_NOTBOL;
1282 if (!opt->only_matching) {
1283 output_color(opt, bol, rest, line_color);
1284 opt->output(opt, "\n", 1);
1288 int grep_use_locks;
1291 * This lock protects access to the gitattributes machinery, which is
1292 * not thread-safe.
1294 pthread_mutex_t grep_attr_mutex;
1296 static inline void grep_attr_lock(void)
1298 if (grep_use_locks)
1299 pthread_mutex_lock(&grep_attr_mutex);
1302 static inline void grep_attr_unlock(void)
1304 if (grep_use_locks)
1305 pthread_mutex_unlock(&grep_attr_mutex);
1308 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1309 const char *bol, const char *eol)
1311 xdemitconf_t *xecfg = opt->priv;
1312 if (xecfg && !xecfg->find_func) {
1313 grep_source_load_driver(gs, opt->repo->index);
1314 if (gs->driver->funcname.pattern) {
1315 const struct userdiff_funcname *pe = &gs->driver->funcname;
1316 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1317 } else {
1318 xecfg = opt->priv = NULL;
1322 if (xecfg) {
1323 char buf[1];
1324 return xecfg->find_func(bol, eol - bol, buf, 1,
1325 xecfg->find_func_priv) >= 0;
1328 if (bol == eol)
1329 return 0;
1330 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1331 return 1;
1332 return 0;
1335 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1336 const char *bol, unsigned lno)
1338 while (bol > gs->buf) {
1339 const char *eol = --bol;
1341 while (bol > gs->buf && bol[-1] != '\n')
1342 bol--;
1343 lno--;
1345 if (lno <= opt->last_shown)
1346 break;
1348 if (match_funcname(opt, gs, bol, eol)) {
1349 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1350 break;
1355 static int is_empty_line(const char *bol, const char *eol);
1357 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1358 const char *bol, const char *end, unsigned lno)
1360 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1361 int funcname_needed = !!opt->funcname, comment_needed = 0;
1363 if (opt->pre_context < lno)
1364 from = lno - opt->pre_context;
1365 if (from <= opt->last_shown)
1366 from = opt->last_shown + 1;
1367 orig_from = from;
1368 if (opt->funcbody) {
1369 if (match_funcname(opt, gs, bol, end))
1370 comment_needed = 1;
1371 else
1372 funcname_needed = 1;
1373 from = opt->last_shown + 1;
1376 /* Rewind. */
1377 while (bol > gs->buf && cur > from) {
1378 const char *next_bol = bol;
1379 const char *eol = --bol;
1381 while (bol > gs->buf && bol[-1] != '\n')
1382 bol--;
1383 cur--;
1384 if (comment_needed && (is_empty_line(bol, eol) ||
1385 match_funcname(opt, gs, bol, eol))) {
1386 comment_needed = 0;
1387 from = orig_from;
1388 if (cur < from) {
1389 cur++;
1390 bol = next_bol;
1391 break;
1394 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1395 funcname_lno = cur;
1396 funcname_needed = 0;
1397 if (opt->funcbody)
1398 comment_needed = 1;
1399 else
1400 from = orig_from;
1404 /* We need to look even further back to find a function signature. */
1405 if (opt->funcname && funcname_needed)
1406 show_funcname_line(opt, gs, bol, cur);
1408 /* Back forward. */
1409 while (cur < lno) {
1410 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1412 while (*eol != '\n')
1413 eol++;
1414 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1415 bol = eol + 1;
1416 cur++;
1420 static int should_lookahead(struct grep_opt *opt)
1422 struct grep_pat *p;
1424 if (opt->pattern_expression)
1425 return 0; /* punt for too complex stuff */
1426 if (opt->invert)
1427 return 0;
1428 for (p = opt->pattern_list; p; p = p->next) {
1429 if (p->token != GREP_PATTERN)
1430 return 0; /* punt for "header only" and stuff */
1432 return 1;
1435 static int look_ahead(struct grep_opt *opt,
1436 unsigned long *left_p,
1437 unsigned *lno_p,
1438 const char **bol_p)
1440 unsigned lno = *lno_p;
1441 const char *bol = *bol_p;
1442 struct grep_pat *p;
1443 const char *sp, *last_bol;
1444 regoff_t earliest = -1;
1446 for (p = opt->pattern_list; p; p = p->next) {
1447 int hit;
1448 regmatch_t m;
1450 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1451 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1452 continue;
1453 if (earliest < 0 || m.rm_so < earliest)
1454 earliest = m.rm_so;
1457 if (earliest < 0) {
1458 *bol_p = bol + *left_p;
1459 *left_p = 0;
1460 return 1;
1462 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1463 ; /* find the beginning of the line */
1464 last_bol = sp;
1466 for (sp = bol; sp < last_bol; sp++) {
1467 if (*sp == '\n')
1468 lno++;
1470 *left_p -= last_bol - bol;
1471 *bol_p = last_bol;
1472 *lno_p = lno;
1473 return 0;
1476 static int fill_textconv_grep(struct repository *r,
1477 struct userdiff_driver *driver,
1478 struct grep_source *gs)
1480 struct diff_filespec *df;
1481 char *buf;
1482 size_t size;
1484 if (!driver || !driver->textconv)
1485 return grep_source_load(gs);
1488 * The textconv interface is intimately tied to diff_filespecs, so we
1489 * have to pretend to be one. If we could unify the grep_source
1490 * and diff_filespec structs, this mess could just go away.
1492 df = alloc_filespec(gs->path);
1493 switch (gs->type) {
1494 case GREP_SOURCE_OID:
1495 fill_filespec(df, gs->identifier, 1, 0100644);
1496 break;
1497 case GREP_SOURCE_FILE:
1498 fill_filespec(df, null_oid(), 0, 0100644);
1499 break;
1500 default:
1501 BUG("attempt to textconv something without a path?");
1505 * fill_textconv is not remotely thread-safe; it modifies the global
1506 * diff tempfile structure, writes to the_repo's odb and might
1507 * internally call thread-unsafe functions such as the
1508 * prepare_packed_git() lazy-initializator. Because of the last two, we
1509 * must ensure mutual exclusion between this call and the object reading
1510 * API, thus we use obj_read_lock() here.
1512 * TODO: allowing text conversion to run in parallel with object
1513 * reading operations might increase performance in the multithreaded
1514 * non-worktreee git-grep with --textconv.
1516 obj_read_lock();
1517 size = fill_textconv(r, driver, df, &buf);
1518 obj_read_unlock();
1519 free_filespec(df);
1522 * The normal fill_textconv usage by the diff machinery would just keep
1523 * the textconv'd buf separate from the diff_filespec. But much of the
1524 * grep code passes around a grep_source and assumes that its "buf"
1525 * pointer is the beginning of the thing we are searching. So let's
1526 * install our textconv'd version into the grep_source, taking care not
1527 * to leak any existing buffer.
1529 grep_source_clear_data(gs);
1530 gs->buf = buf;
1531 gs->size = size;
1533 return 0;
1536 static int is_empty_line(const char *bol, const char *eol)
1538 while (bol < eol && isspace(*bol))
1539 bol++;
1540 return bol == eol;
1543 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1545 const char *bol;
1546 const char *peek_bol = NULL;
1547 unsigned long left;
1548 unsigned lno = 1;
1549 unsigned last_hit = 0;
1550 int binary_match_only = 0;
1551 unsigned count = 0;
1552 int try_lookahead = 0;
1553 int show_function = 0;
1554 struct userdiff_driver *textconv = NULL;
1555 enum grep_context ctx = GREP_CONTEXT_HEAD;
1556 xdemitconf_t xecfg;
1558 if (!opt->status_only && gs->name == NULL)
1559 BUG("grep call which could print a name requires "
1560 "grep_source.name be non-NULL");
1562 if (!opt->output)
1563 opt->output = std_output;
1565 if (opt->pre_context || opt->post_context || opt->file_break ||
1566 opt->funcbody) {
1567 /* Show hunk marks, except for the first file. */
1568 if (opt->last_shown)
1569 opt->show_hunk_mark = 1;
1571 * If we're using threads then we can't easily identify
1572 * the first file. Always put hunk marks in that case
1573 * and skip the very first one later in work_done().
1575 if (opt->output != std_output)
1576 opt->show_hunk_mark = 1;
1578 opt->last_shown = 0;
1580 if (opt->allow_textconv) {
1581 grep_source_load_driver(gs, opt->repo->index);
1583 * We might set up the shared textconv cache data here, which
1584 * is not thread-safe. Also, get_oid_with_context() and
1585 * parse_object() might be internally called. As they are not
1586 * currently thread-safe and might be racy with object reading,
1587 * obj_read_lock() must be called.
1589 grep_attr_lock();
1590 obj_read_lock();
1591 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1592 obj_read_unlock();
1593 grep_attr_unlock();
1597 * We know the result of a textconv is text, so we only have to care
1598 * about binary handling if we are not using it.
1600 if (!textconv) {
1601 switch (opt->binary) {
1602 case GREP_BINARY_DEFAULT:
1603 if (grep_source_is_binary(gs, opt->repo->index))
1604 binary_match_only = 1;
1605 break;
1606 case GREP_BINARY_NOMATCH:
1607 if (grep_source_is_binary(gs, opt->repo->index))
1608 return 0; /* Assume unmatch */
1609 break;
1610 case GREP_BINARY_TEXT:
1611 break;
1612 default:
1613 BUG("unknown binary handling mode");
1617 memset(&xecfg, 0, sizeof(xecfg));
1618 opt->priv = &xecfg;
1620 try_lookahead = should_lookahead(opt);
1622 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1623 return 0;
1625 bol = gs->buf;
1626 left = gs->size;
1627 while (left) {
1628 const char *eol;
1629 int hit;
1630 ssize_t cno;
1631 ssize_t col = -1, icol = -1;
1634 * look_ahead() skips quickly to the line that possibly
1635 * has the next hit; don't call it if we need to do
1636 * something more than just skipping the current line
1637 * in response to an unmatch for the current line. E.g.
1638 * inside a post-context window, we will show the current
1639 * line as a context around the previous hit when it
1640 * doesn't hit.
1642 if (try_lookahead
1643 && !(last_hit
1644 && (show_function ||
1645 lno <= last_hit + opt->post_context))
1646 && look_ahead(opt, &left, &lno, &bol))
1647 break;
1648 eol = end_of_line(bol, &left);
1650 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1651 ctx = GREP_CONTEXT_BODY;
1653 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1655 if (collect_hits)
1656 goto next_line;
1658 /* "grep -v -e foo -e bla" should list lines
1659 * that do not have either, so inversion should
1660 * be done outside.
1662 if (opt->invert)
1663 hit = !hit;
1664 if (opt->unmatch_name_only) {
1665 if (hit)
1666 return 0;
1667 goto next_line;
1669 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1670 count++;
1671 if (opt->status_only)
1672 return 1;
1673 if (opt->name_only) {
1674 show_name(opt, gs->name);
1675 return 1;
1677 if (opt->count)
1678 goto next_line;
1679 if (binary_match_only) {
1680 opt->output(opt, "Binary file ", 12);
1681 output_color(opt, gs->name, strlen(gs->name),
1682 opt->colors[GREP_COLOR_FILENAME]);
1683 opt->output(opt, " matches\n", 9);
1684 return 1;
1686 /* Hit at this line. If we haven't shown the
1687 * pre-context lines, we would need to show them.
1689 if (opt->pre_context || opt->funcbody)
1690 show_pre_context(opt, gs, bol, eol, lno);
1691 else if (opt->funcname)
1692 show_funcname_line(opt, gs, bol, lno);
1693 cno = opt->invert ? icol : col;
1694 if (cno < 0) {
1696 * A negative cno indicates that there was no
1697 * match on the line. We are thus inverted and
1698 * being asked to show all lines that _don't_
1699 * match a given expression. Therefore, set cno
1700 * to 0 to suggest the whole line matches.
1702 cno = 0;
1704 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1705 last_hit = lno;
1706 if (opt->funcbody)
1707 show_function = 1;
1708 goto next_line;
1710 if (show_function && (!peek_bol || peek_bol < bol)) {
1711 unsigned long peek_left = left;
1712 const char *peek_eol = eol;
1715 * Trailing empty lines are not interesting.
1716 * Peek past them to see if they belong to the
1717 * body of the current function.
1719 peek_bol = bol;
1720 while (is_empty_line(peek_bol, peek_eol)) {
1721 peek_bol = peek_eol + 1;
1722 peek_eol = end_of_line(peek_bol, &peek_left);
1725 if (match_funcname(opt, gs, peek_bol, peek_eol))
1726 show_function = 0;
1728 if (show_function ||
1729 (last_hit && lno <= last_hit + opt->post_context)) {
1730 /* If the last hit is within the post context,
1731 * we need to show this line.
1733 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1736 next_line:
1737 bol = eol + 1;
1738 if (!left)
1739 break;
1740 left--;
1741 lno++;
1744 if (collect_hits)
1745 return 0;
1747 if (opt->status_only)
1748 return opt->unmatch_name_only;
1749 if (opt->unmatch_name_only) {
1750 /* We did not see any hit, so we want to show this */
1751 show_name(opt, gs->name);
1752 return 1;
1755 xdiff_clear_find_func(&xecfg);
1756 opt->priv = NULL;
1758 /* NEEDSWORK:
1759 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1760 * which feels mostly useless but sometimes useful. Maybe
1761 * make it another option? For now suppress them.
1763 if (opt->count && count) {
1764 char buf[32];
1765 if (opt->pathname) {
1766 output_color(opt, gs->name, strlen(gs->name),
1767 opt->colors[GREP_COLOR_FILENAME]);
1768 output_sep(opt, ':');
1770 xsnprintf(buf, sizeof(buf), "%u\n", count);
1771 opt->output(opt, buf, strlen(buf));
1772 return 1;
1774 return !!last_hit;
1777 static void clr_hit_marker(struct grep_expr *x)
1779 /* All-hit markers are meaningful only at the very top level
1780 * OR node.
1782 while (1) {
1783 x->hit = 0;
1784 if (x->node != GREP_NODE_OR)
1785 return;
1786 x->u.binary.left->hit = 0;
1787 x = x->u.binary.right;
1791 static int chk_hit_marker(struct grep_expr *x)
1793 /* Top level nodes have hit markers. See if they all are hits */
1794 while (1) {
1795 if (x->node != GREP_NODE_OR)
1796 return x->hit;
1797 if (!x->u.binary.left->hit)
1798 return 0;
1799 x = x->u.binary.right;
1803 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1806 * we do not have to do the two-pass grep when we do not check
1807 * buffer-wide "all-match".
1809 if (!opt->all_match && !opt->no_body_match)
1810 return grep_source_1(opt, gs, 0);
1812 /* Otherwise the toplevel "or" terms hit a bit differently.
1813 * We first clear hit markers from them.
1815 clr_hit_marker(opt->pattern_expression);
1816 opt->body_hit = 0;
1817 grep_source_1(opt, gs, 1);
1819 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1820 return 0;
1821 if (opt->no_body_match && opt->body_hit)
1822 return 0;
1824 return grep_source_1(opt, gs, 0);
1827 static void grep_source_init_buf(struct grep_source *gs,
1828 const char *buf,
1829 unsigned long size)
1831 gs->type = GREP_SOURCE_BUF;
1832 gs->name = NULL;
1833 gs->path = NULL;
1834 gs->buf = buf;
1835 gs->size = size;
1836 gs->driver = NULL;
1837 gs->identifier = NULL;
1840 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1842 struct grep_source gs;
1843 int r;
1845 grep_source_init_buf(&gs, buf, size);
1847 r = grep_source(opt, &gs);
1849 grep_source_clear(&gs);
1850 return r;
1853 void grep_source_init_file(struct grep_source *gs, const char *name,
1854 const char *path)
1856 gs->type = GREP_SOURCE_FILE;
1857 gs->name = xstrdup_or_null(name);
1858 gs->path = xstrdup_or_null(path);
1859 gs->buf = NULL;
1860 gs->size = 0;
1861 gs->driver = NULL;
1862 gs->identifier = xstrdup(path);
1865 void grep_source_init_oid(struct grep_source *gs, const char *name,
1866 const char *path, const struct object_id *oid,
1867 struct repository *repo)
1869 gs->type = GREP_SOURCE_OID;
1870 gs->name = xstrdup_or_null(name);
1871 gs->path = xstrdup_or_null(path);
1872 gs->buf = NULL;
1873 gs->size = 0;
1874 gs->driver = NULL;
1875 gs->identifier = oiddup(oid);
1876 gs->repo = repo;
1879 void grep_source_clear(struct grep_source *gs)
1881 FREE_AND_NULL(gs->name);
1882 FREE_AND_NULL(gs->path);
1883 FREE_AND_NULL(gs->identifier);
1884 grep_source_clear_data(gs);
1887 void grep_source_clear_data(struct grep_source *gs)
1889 switch (gs->type) {
1890 case GREP_SOURCE_FILE:
1891 case GREP_SOURCE_OID:
1892 /* these types own the buffer */
1893 free((char *)gs->buf);
1894 gs->buf = NULL;
1895 gs->size = 0;
1896 break;
1897 case GREP_SOURCE_BUF:
1898 /* leave user-provided buf intact */
1899 break;
1903 static int grep_source_load_oid(struct grep_source *gs)
1905 enum object_type type;
1907 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1908 &gs->size);
1909 if (!gs->buf)
1910 return error(_("'%s': unable to read %s"),
1911 gs->name,
1912 oid_to_hex(gs->identifier));
1913 return 0;
1916 static int grep_source_load_file(struct grep_source *gs)
1918 const char *filename = gs->identifier;
1919 struct stat st;
1920 char *data;
1921 size_t size;
1922 int i;
1924 if (lstat(filename, &st) < 0) {
1925 err_ret:
1926 if (errno != ENOENT)
1927 error_errno(_("failed to stat '%s'"), filename);
1928 return -1;
1930 if (!S_ISREG(st.st_mode))
1931 return -1;
1932 size = xsize_t(st.st_size);
1933 i = open(filename, O_RDONLY);
1934 if (i < 0)
1935 goto err_ret;
1936 data = xmallocz(size);
1937 if (st.st_size != read_in_full(i, data, size)) {
1938 error_errno(_("'%s': short read"), filename);
1939 close(i);
1940 free(data);
1941 return -1;
1943 close(i);
1945 gs->buf = data;
1946 gs->size = size;
1947 return 0;
1950 static int grep_source_load(struct grep_source *gs)
1952 if (gs->buf)
1953 return 0;
1955 switch (gs->type) {
1956 case GREP_SOURCE_FILE:
1957 return grep_source_load_file(gs);
1958 case GREP_SOURCE_OID:
1959 return grep_source_load_oid(gs);
1960 case GREP_SOURCE_BUF:
1961 return gs->buf ? 0 : -1;
1963 BUG("invalid grep_source type to load");
1966 void grep_source_load_driver(struct grep_source *gs,
1967 struct index_state *istate)
1969 if (gs->driver)
1970 return;
1972 grep_attr_lock();
1973 if (gs->path)
1974 gs->driver = userdiff_find_by_path(istate, gs->path);
1975 if (!gs->driver)
1976 gs->driver = userdiff_find_by_name("default");
1977 grep_attr_unlock();
1980 static int grep_source_is_binary(struct grep_source *gs,
1981 struct index_state *istate)
1983 grep_source_load_driver(gs, istate);
1984 if (gs->driver->binary != -1)
1985 return gs->driver->binary;
1987 if (!grep_source_load(gs))
1988 return buffer_is_binary(gs->buf, gs->size);
1990 return 0;