The eleventh batch
[git/gitster.git] / grep.c
blobe95cded4149d33d33a9d2027939df4eefba535d1
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "gettext.h"
4 #include "grep.h"
5 #include "hex.h"
6 #include "object-store-ll.h"
7 #include "pretty.h"
8 #include "userdiff.h"
9 #include "xdiff-interface.h"
10 #include "diff.h"
11 #include "diffcore.h"
12 #include "quote.h"
13 #include "help.h"
15 static int grep_source_load(struct grep_source *gs);
16 static int grep_source_is_binary(struct grep_source *gs,
17 struct index_state *istate);
19 static void std_output(struct grep_opt *opt UNUSED, const void *buf, size_t size)
21 fwrite(buf, size, 1, stdout);
24 static const char *color_grep_slots[] = {
25 [GREP_COLOR_CONTEXT] = "context",
26 [GREP_COLOR_FILENAME] = "filename",
27 [GREP_COLOR_FUNCTION] = "function",
28 [GREP_COLOR_LINENO] = "lineNumber",
29 [GREP_COLOR_COLUMNNO] = "column",
30 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
31 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
32 [GREP_COLOR_SELECTED] = "selected",
33 [GREP_COLOR_SEP] = "separator",
36 static int parse_pattern_type_arg(const char *opt, const char *arg)
38 if (!strcmp(arg, "default"))
39 return GREP_PATTERN_TYPE_UNSPECIFIED;
40 else if (!strcmp(arg, "basic"))
41 return GREP_PATTERN_TYPE_BRE;
42 else if (!strcmp(arg, "extended"))
43 return GREP_PATTERN_TYPE_ERE;
44 else if (!strcmp(arg, "fixed"))
45 return GREP_PATTERN_TYPE_FIXED;
46 else if (!strcmp(arg, "perl"))
47 return GREP_PATTERN_TYPE_PCRE;
48 die("bad %s argument: %s", opt, arg);
51 define_list_config_array_extra(color_grep_slots, {"match"});
54 * Read the configuration file once and store it in
55 * the grep_defaults template.
57 int grep_config(const char *var, const char *value,
58 const struct config_context *ctx, void *cb)
60 struct grep_opt *opt = cb;
61 const char *slot;
63 if (userdiff_config(var, value) < 0)
64 return -1;
66 if (!strcmp(var, "grep.extendedregexp")) {
67 opt->extended_regexp_option = git_config_bool(var, value);
68 return 0;
71 if (!strcmp(var, "grep.patterntype")) {
72 opt->pattern_type_option = parse_pattern_type_arg(var, value);
73 return 0;
76 if (!strcmp(var, "grep.linenumber")) {
77 opt->linenum = git_config_bool(var, value);
78 return 0;
80 if (!strcmp(var, "grep.column")) {
81 opt->columnnum = git_config_bool(var, value);
82 return 0;
85 if (!strcmp(var, "grep.fullname")) {
86 opt->relative = !git_config_bool(var, value);
87 return 0;
90 if (!strcmp(var, "color.grep"))
91 opt->color = git_config_colorbool(var, value);
92 if (!strcmp(var, "color.grep.match")) {
93 if (grep_config("color.grep.matchcontext", value, ctx, cb) < 0)
94 return -1;
95 if (grep_config("color.grep.matchselected", value, ctx, cb) < 0)
96 return -1;
97 } else if (skip_prefix(var, "color.grep.", &slot)) {
98 int i = LOOKUP_CONFIG(color_grep_slots, slot);
99 char *color;
101 if (i < 0)
102 return -1;
103 color = opt->colors[i];
104 if (!value)
105 return config_error_nonbool(var);
106 return color_parse(value, color);
108 return 0;
111 void grep_init(struct grep_opt *opt, struct repository *repo)
113 struct grep_opt blank = GREP_OPT_INIT;
114 memcpy(opt, &blank, sizeof(*opt));
116 opt->repo = repo;
117 opt->pattern_tail = &opt->pattern_list;
118 opt->header_tail = &opt->header_list;
121 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
122 const char *origin, int no,
123 enum grep_pat_token t,
124 enum grep_header_field field)
126 struct grep_pat *p = xcalloc(1, sizeof(*p));
127 p->pattern = xmemdupz(pat, patlen);
128 p->patternlen = patlen;
129 p->origin = origin;
130 p->no = no;
131 p->token = t;
132 p->field = field;
133 return p;
136 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
138 **tail = p;
139 *tail = &p->next;
140 p->next = NULL;
142 switch (p->token) {
143 case GREP_PATTERN: /* atom */
144 case GREP_PATTERN_HEAD:
145 case GREP_PATTERN_BODY:
146 for (;;) {
147 struct grep_pat *new_pat;
148 size_t len = 0;
149 char *cp = p->pattern + p->patternlen, *nl = NULL;
150 while (++len <= p->patternlen) {
151 if (*(--cp) == '\n') {
152 nl = cp;
153 break;
156 if (!nl)
157 break;
158 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
159 p->no, p->token, p->field);
160 new_pat->next = p->next;
161 if (!p->next)
162 *tail = &new_pat->next;
163 p->next = new_pat;
164 *nl = '\0';
165 p->patternlen -= len;
167 break;
168 default:
169 break;
173 void append_header_grep_pattern(struct grep_opt *opt,
174 enum grep_header_field field, const char *pat)
176 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
177 GREP_PATTERN_HEAD, field);
178 if (field == GREP_HEADER_REFLOG)
179 opt->use_reflog_filter = 1;
180 do_append_grep_pat(&opt->header_tail, p);
183 void append_grep_pattern(struct grep_opt *opt, const char *pat,
184 const char *origin, int no, enum grep_pat_token t)
186 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
189 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
190 const char *origin, int no, enum grep_pat_token t)
192 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
193 do_append_grep_pat(&opt->pattern_tail, p);
196 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
198 struct grep_pat *pat;
199 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
200 *ret = *opt;
202 ret->pattern_list = NULL;
203 ret->pattern_tail = &ret->pattern_list;
205 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
207 if(pat->token == GREP_PATTERN_HEAD)
208 append_header_grep_pattern(ret, pat->field,
209 pat->pattern);
210 else
211 append_grep_pat(ret, pat->pattern, pat->patternlen,
212 pat->origin, pat->no, pat->token);
215 return ret;
218 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
219 const char *error)
221 char where[1024];
223 if (p->no)
224 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
225 else if (p->origin)
226 xsnprintf(where, sizeof(where), "%s, ", p->origin);
227 else
228 where[0] = 0;
230 die("%s'%s': %s", where, p->pattern, error);
233 static int is_fixed(const char *s, size_t len)
235 size_t i;
237 for (i = 0; i < len; i++) {
238 if (is_regex_special(s[i]))
239 return 0;
242 return 1;
245 #ifdef USE_LIBPCRE2
246 #define GREP_PCRE2_DEBUG_MALLOC 0
248 static void *pcre2_malloc(PCRE2_SIZE size, void *memory_data UNUSED)
250 void *pointer = malloc(size);
251 #if GREP_PCRE2_DEBUG_MALLOC
252 static int count = 1;
253 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
254 #endif
255 return pointer;
258 static void pcre2_free(void *pointer, void *memory_data UNUSED)
260 #if GREP_PCRE2_DEBUG_MALLOC
261 static int count = 1;
262 if (pointer)
263 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
264 #endif
265 free(pointer);
268 static int pcre2_jit_functional(void)
270 static int jit_working = -1;
271 pcre2_code *code;
272 size_t off;
273 int err;
275 if (jit_working != -1)
276 return jit_working;
279 * Try to JIT compile a simple pattern to probe if the JIT is
280 * working in general. It might fail for systems where creating
281 * memory mappings for runtime code generation is restricted.
283 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
284 if (!code)
285 return 0;
287 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
288 pcre2_code_free(code);
290 return jit_working;
293 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
295 int error;
296 PCRE2_UCHAR errbuf[256];
297 PCRE2_SIZE erroffset;
298 int options = PCRE2_MULTILINE;
299 int jitret;
300 int patinforet;
301 size_t jitsizearg;
302 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
305 * Call pcre2_general_context_create() before calling any
306 * other pcre2_*(). It sets up our malloc()/free() functions
307 * with which everything else is allocated.
309 p->pcre2_general_context = pcre2_general_context_create(
310 pcre2_malloc, pcre2_free, NULL);
311 if (!p->pcre2_general_context)
312 die("Couldn't allocate PCRE2 general context");
314 if (opt->ignore_case) {
315 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
316 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
317 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
318 pcre2_set_character_tables(p->pcre2_compile_context,
319 p->pcre2_tables);
321 options |= PCRE2_CASELESS;
323 if (!opt->ignore_locale && is_utf8_locale() && !literal)
324 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
326 #ifndef GIT_PCRE2_VERSION_10_35_OR_HIGHER
328 * Work around a JIT bug related to invalid Unicode character handling
329 * fixed in 10.35:
330 * https://github.com/PCRE2Project/pcre2/commit/c21bd977547d
332 options &= ~PCRE2_UCP;
333 #endif
335 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
336 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
337 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
338 options |= PCRE2_NO_START_OPTIMIZE;
339 #endif
341 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
342 p->patternlen, options, &error, &erroffset,
343 p->pcre2_compile_context);
345 if (p->pcre2_pattern) {
346 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
347 if (!p->pcre2_match_data)
348 die("Couldn't allocate PCRE2 match data");
349 } else {
350 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
351 compile_regexp_failed(p, (const char *)&errbuf);
354 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
355 if (p->pcre2_jit_on) {
356 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
357 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
359 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
360 * indicated JIT support, the library might still
361 * fail to generate JIT code for various reasons,
362 * e.g. when SELinux's 'deny_execmem' or PaX's
363 * MPROTECT prevent creating W|X memory mappings.
365 * Instead of faling hard, fall back to interpreter
366 * mode, just as if the pattern was prefixed with
367 * '(*NO_JIT)'.
369 p->pcre2_jit_on = 0;
370 return;
371 } else if (jitret) {
372 int need_clip = p->patternlen > 64;
373 int clip_len = need_clip ? 64 : p->patternlen;
374 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
375 clip_len, p->pattern, need_clip ? "..." : "", jitret,
376 pcre2_jit_functional()
377 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
378 : "");
382 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
383 * tells us whether the library itself supports JIT,
384 * but to see whether we're going to be actually using
385 * JIT we need to extract PCRE2_INFO_JITSIZE from the
386 * pattern *after* we do pcre2_jit_compile() above.
388 * This is because if the pattern contains the
389 * (*NO_JIT) verb (see pcre2syntax(3))
390 * pcre2_jit_compile() will exit early with 0. If we
391 * then proceed to call pcre2_jit_match() further down
392 * the line instead of pcre2_match() we'll either
393 * segfault (pre PCRE 10.31) or run into a fatal error
394 * (post PCRE2 10.31)
396 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
397 if (patinforet)
398 BUG("pcre2_pattern_info() failed: %d", patinforet);
399 if (jitsizearg == 0) {
400 p->pcre2_jit_on = 0;
401 return;
406 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
407 regmatch_t *match, int eflags)
409 int ret, flags = 0;
410 PCRE2_SIZE *ovector;
411 PCRE2_UCHAR errbuf[256];
413 if (eflags & REG_NOTBOL)
414 flags |= PCRE2_NOTBOL;
416 if (p->pcre2_jit_on)
417 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
418 eol - line, 0, flags, p->pcre2_match_data,
419 NULL);
420 else
421 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
422 eol - line, 0, flags, p->pcre2_match_data,
423 NULL);
425 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
426 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
427 die("%s failed with error code %d: %s",
428 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
429 errbuf);
431 if (ret > 0) {
432 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
433 ret = 0;
434 match->rm_so = (int)ovector[0];
435 match->rm_eo = (int)ovector[1];
438 return ret;
441 static void free_pcre2_pattern(struct grep_pat *p)
443 pcre2_compile_context_free(p->pcre2_compile_context);
444 pcre2_code_free(p->pcre2_pattern);
445 pcre2_match_data_free(p->pcre2_match_data);
446 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
447 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
448 #else
449 free((void *)p->pcre2_tables);
450 #endif
451 pcre2_general_context_free(p->pcre2_general_context);
453 #else /* !USE_LIBPCRE2 */
454 static void compile_pcre2_pattern(struct grep_pat *p UNUSED,
455 const struct grep_opt *opt UNUSED)
457 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
460 static int pcre2match(struct grep_pat *p UNUSED, const char *line UNUSED,
461 const char *eol UNUSED, regmatch_t *match UNUSED,
462 int eflags UNUSED)
464 return 1;
467 static void free_pcre2_pattern(struct grep_pat *p UNUSED)
471 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
473 struct strbuf sb = STRBUF_INIT;
474 int err;
475 int regflags = 0;
477 basic_regex_quote_buf(&sb, p->pattern);
478 if (opt->ignore_case)
479 regflags |= REG_ICASE;
480 err = regcomp(&p->regexp, sb.buf, regflags);
481 strbuf_release(&sb);
482 if (err) {
483 char errbuf[1024];
484 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
485 compile_regexp_failed(p, errbuf);
488 #endif /* !USE_LIBPCRE2 */
490 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
492 int err;
493 int regflags = REG_NEWLINE;
495 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
496 opt->pattern_type_option = (opt->extended_regexp_option
497 ? GREP_PATTERN_TYPE_ERE
498 : GREP_PATTERN_TYPE_BRE);
500 p->word_regexp = opt->word_regexp;
501 p->ignore_case = opt->ignore_case;
502 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
504 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
505 memchr(p->pattern, 0, p->patternlen))
506 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
508 p->is_fixed = is_fixed(p->pattern, p->patternlen);
509 #ifdef USE_LIBPCRE2
510 if (!p->fixed && !p->is_fixed) {
511 const char *no_jit = "(*NO_JIT)";
512 const int no_jit_len = strlen(no_jit);
513 if (starts_with(p->pattern, no_jit) &&
514 is_fixed(p->pattern + no_jit_len,
515 p->patternlen - no_jit_len))
516 p->is_fixed = 1;
518 #endif
519 if (p->fixed || p->is_fixed) {
520 #ifdef USE_LIBPCRE2
521 if (p->is_fixed) {
522 compile_pcre2_pattern(p, opt);
523 } else {
525 * E.g. t7811-grep-open.sh relies on the
526 * pattern being restored.
528 char *old_pattern = p->pattern;
529 size_t old_patternlen = p->patternlen;
530 struct strbuf sb = STRBUF_INIT;
533 * There is the PCRE2_LITERAL flag, but it's
534 * only in PCRE v2 10.30 and later. Needing to
535 * ifdef our way around that and dealing with
536 * it + PCRE2_MULTILINE being an error is more
537 * complex than just quoting this ourselves.
539 strbuf_add(&sb, "\\Q", 2);
540 strbuf_add(&sb, p->pattern, p->patternlen);
541 strbuf_add(&sb, "\\E", 2);
543 p->pattern = sb.buf;
544 p->patternlen = sb.len;
545 compile_pcre2_pattern(p, opt);
546 p->pattern = old_pattern;
547 p->patternlen = old_patternlen;
548 strbuf_release(&sb);
550 #else /* !USE_LIBPCRE2 */
551 compile_fixed_regexp(p, opt);
552 #endif /* !USE_LIBPCRE2 */
553 return;
556 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
557 compile_pcre2_pattern(p, opt);
558 return;
561 if (p->ignore_case)
562 regflags |= REG_ICASE;
563 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
564 regflags |= REG_EXTENDED;
565 err = regcomp(&p->regexp, p->pattern, regflags);
566 if (err) {
567 char errbuf[1024];
568 regerror(err, &p->regexp, errbuf, 1024);
569 compile_regexp_failed(p, errbuf);
573 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
575 struct grep_expr *z = xcalloc(1, sizeof(*z));
576 z->node = GREP_NODE_NOT;
577 z->u.unary = expr;
578 return z;
581 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
582 struct grep_expr *left,
583 struct grep_expr *right)
585 struct grep_expr *z = xcalloc(1, sizeof(*z));
586 z->node = kind;
587 z->u.binary.left = left;
588 z->u.binary.right = right;
589 return z;
592 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
594 return grep_binexp(GREP_NODE_OR, left, right);
597 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
599 return grep_binexp(GREP_NODE_AND, left, right);
602 static struct grep_expr *compile_pattern_or(struct grep_pat **);
603 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
605 struct grep_pat *p;
606 struct grep_expr *x;
608 p = *list;
609 if (!p)
610 return NULL;
611 switch (p->token) {
612 case GREP_PATTERN: /* atom */
613 case GREP_PATTERN_HEAD:
614 case GREP_PATTERN_BODY:
615 CALLOC_ARRAY(x, 1);
616 x->node = GREP_NODE_ATOM;
617 x->u.atom = p;
618 *list = p->next;
619 return x;
620 case GREP_OPEN_PAREN:
621 *list = p->next;
622 x = compile_pattern_or(list);
623 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
624 die("unmatched ( for expression group");
625 *list = (*list)->next;
626 return x;
627 default:
628 return NULL;
632 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
634 struct grep_pat *p;
635 struct grep_expr *x;
637 p = *list;
638 if (!p)
639 return NULL;
640 switch (p->token) {
641 case GREP_NOT:
642 if (!p->next)
643 die("--not not followed by pattern expression");
644 *list = p->next;
645 x = compile_pattern_not(list);
646 if (!x)
647 die("--not followed by non pattern expression");
648 return grep_not_expr(x);
649 default:
650 return compile_pattern_atom(list);
654 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
656 struct grep_pat *p;
657 struct grep_expr *x, *y;
659 x = compile_pattern_not(list);
660 p = *list;
661 if (p && p->token == GREP_AND) {
662 if (!x)
663 die("--and not preceded by pattern expression");
664 if (!p->next)
665 die("--and not followed by pattern expression");
666 *list = p->next;
667 y = compile_pattern_and(list);
668 if (!y)
669 die("--and not followed by pattern expression");
670 return grep_and_expr(x, y);
672 return x;
675 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
677 struct grep_pat *p;
678 struct grep_expr *x, *y;
680 x = compile_pattern_and(list);
681 p = *list;
682 if (x && p && p->token != GREP_CLOSE_PAREN) {
683 y = compile_pattern_or(list);
684 if (!y)
685 die("not a pattern expression %s", p->pattern);
686 return grep_or_expr(x, y);
688 return x;
691 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
693 return compile_pattern_or(list);
696 static struct grep_expr *grep_true_expr(void)
698 struct grep_expr *z = xcalloc(1, sizeof(*z));
699 z->node = GREP_NODE_TRUE;
700 return z;
703 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
705 struct grep_pat *p;
706 struct grep_expr *header_expr;
707 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
708 enum grep_header_field fld;
710 if (!opt->header_list)
711 return NULL;
713 for (p = opt->header_list; p; p = p->next) {
714 if (p->token != GREP_PATTERN_HEAD)
715 BUG("a non-header pattern in grep header list.");
716 if (p->field < GREP_HEADER_FIELD_MIN ||
717 GREP_HEADER_FIELD_MAX <= p->field)
718 BUG("unknown header field %d", p->field);
719 compile_regexp(p, opt);
722 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
723 header_group[fld] = NULL;
725 for (p = opt->header_list; p; p = p->next) {
726 struct grep_expr *h;
727 struct grep_pat *pp = p;
729 h = compile_pattern_atom(&pp);
730 if (!h || pp != p->next)
731 BUG("malformed header expr");
732 if (!header_group[p->field]) {
733 header_group[p->field] = h;
734 continue;
736 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
739 header_expr = NULL;
741 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
742 if (!header_group[fld])
743 continue;
744 if (!header_expr)
745 header_expr = grep_true_expr();
746 header_expr = grep_or_expr(header_group[fld], header_expr);
748 return header_expr;
751 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
753 struct grep_expr *z = x;
755 while (x) {
756 assert(x->node == GREP_NODE_OR);
757 if (x->u.binary.right &&
758 x->u.binary.right->node == GREP_NODE_TRUE) {
759 free(x->u.binary.right);
760 x->u.binary.right = y;
761 break;
763 x = x->u.binary.right;
765 return z;
768 void compile_grep_patterns(struct grep_opt *opt)
770 struct grep_pat *p;
771 struct grep_expr *header_expr = prep_header_patterns(opt);
772 int extended = 0;
774 for (p = opt->pattern_list; p; p = p->next) {
775 switch (p->token) {
776 case GREP_PATTERN: /* atom */
777 case GREP_PATTERN_HEAD:
778 case GREP_PATTERN_BODY:
779 compile_regexp(p, opt);
780 break;
781 default:
782 extended = 1;
783 break;
787 if (opt->all_match || opt->no_body_match || header_expr)
788 extended = 1;
789 else if (!extended)
790 return;
792 p = opt->pattern_list;
793 if (p)
794 opt->pattern_expression = compile_pattern_expr(&p);
795 if (p)
796 die("incomplete pattern expression group: %s", p->pattern);
798 if (opt->no_body_match && opt->pattern_expression)
799 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
801 if (!header_expr)
802 return;
804 if (!opt->pattern_expression)
805 opt->pattern_expression = header_expr;
806 else if (opt->all_match)
807 opt->pattern_expression = grep_splice_or(header_expr,
808 opt->pattern_expression);
809 else
810 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
811 header_expr);
812 opt->all_match = 1;
815 static void free_pattern_expr(struct grep_expr *x)
817 switch (x->node) {
818 case GREP_NODE_TRUE:
819 case GREP_NODE_ATOM:
820 break;
821 case GREP_NODE_NOT:
822 free_pattern_expr(x->u.unary);
823 break;
824 case GREP_NODE_AND:
825 case GREP_NODE_OR:
826 free_pattern_expr(x->u.binary.left);
827 free_pattern_expr(x->u.binary.right);
828 break;
830 free(x);
833 static void free_grep_pat(struct grep_pat *pattern)
835 struct grep_pat *p, *n;
837 for (p = pattern; p; p = n) {
838 n = p->next;
839 switch (p->token) {
840 case GREP_PATTERN: /* atom */
841 case GREP_PATTERN_HEAD:
842 case GREP_PATTERN_BODY:
843 if (p->pcre2_pattern)
844 free_pcre2_pattern(p);
845 else
846 regfree(&p->regexp);
847 break;
848 default:
849 break;
851 free(p->pattern);
852 free(p);
856 void free_grep_patterns(struct grep_opt *opt)
858 free_grep_pat(opt->pattern_list);
859 free_grep_pat(opt->header_list);
861 if (opt->pattern_expression)
862 free_pattern_expr(opt->pattern_expression);
865 static const char *end_of_line(const char *cp, unsigned long *left)
867 unsigned long l = *left;
868 while (l && *cp != '\n') {
869 l--;
870 cp++;
872 *left = l;
873 return cp;
876 static int word_char(char ch)
878 return isalnum(ch) || ch == '_';
881 static void output_color(struct grep_opt *opt, const void *data, size_t size,
882 const char *color)
884 if (want_color(opt->color) && color && color[0]) {
885 opt->output(opt, color, strlen(color));
886 opt->output(opt, data, size);
887 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
888 } else
889 opt->output(opt, data, size);
892 static void output_sep(struct grep_opt *opt, char sign)
894 if (opt->null_following_name)
895 opt->output(opt, "\0", 1);
896 else
897 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
900 static void show_name(struct grep_opt *opt, const char *name)
902 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
903 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
906 static int patmatch(struct grep_pat *p,
907 const char *line, const char *eol,
908 regmatch_t *match, int eflags)
910 if (p->pcre2_pattern)
911 return !pcre2match(p, line, eol, match, eflags);
913 switch (regexec_buf(&p->regexp, line, eol - line, 1, match, eflags)) {
914 case 0:
915 return 1;
916 case REG_NOMATCH:
917 return 0;
918 default:
919 return -1;
923 static void strip_timestamp(const char *bol, const char **eol_p)
925 const char *eol = *eol_p;
927 while (bol < --eol) {
928 if (*eol != '>')
929 continue;
930 *eol_p = ++eol;
931 break;
935 static struct {
936 const char *field;
937 size_t len;
938 } header_field[] = {
939 { "author ", 7 },
940 { "committer ", 10 },
941 { "reflog ", 7 },
944 static int headerless_match_one_pattern(struct grep_pat *p,
945 const char *bol, const char *eol,
946 enum grep_context ctx,
947 regmatch_t *pmatch, int eflags)
949 int hit = 0;
950 const char *start = bol;
952 if ((p->token != GREP_PATTERN) &&
953 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
954 return 0;
956 again:
957 hit = patmatch(p, bol, eol, pmatch, eflags);
958 if (hit < 0)
959 hit = 0;
961 if (hit && p->word_regexp) {
962 if ((pmatch[0].rm_so < 0) ||
963 (eol - bol) < pmatch[0].rm_so ||
964 (pmatch[0].rm_eo < 0) ||
965 (eol - bol) < pmatch[0].rm_eo)
966 die("regexp returned nonsense");
968 /* Match beginning must be either beginning of the
969 * line, or at word boundary (i.e. the last char must
970 * not be a word char). Similarly, match end must be
971 * either end of the line, or at word boundary
972 * (i.e. the next char must not be a word char).
974 if ( ((pmatch[0].rm_so == 0) ||
975 !word_char(bol[pmatch[0].rm_so-1])) &&
976 ((pmatch[0].rm_eo == (eol-bol)) ||
977 !word_char(bol[pmatch[0].rm_eo])) )
979 else
980 hit = 0;
982 /* Words consist of at least one character. */
983 if (pmatch->rm_so == pmatch->rm_eo)
984 hit = 0;
986 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
987 /* There could be more than one match on the
988 * line, and the first match might not be
989 * strict word match. But later ones could be!
990 * Forward to the next possible start, i.e. the
991 * next position following a non-word char.
993 bol = pmatch[0].rm_so + bol + 1;
994 while (word_char(bol[-1]) && bol < eol)
995 bol++;
996 eflags |= REG_NOTBOL;
997 if (bol < eol)
998 goto again;
1001 if (hit) {
1002 pmatch[0].rm_so += bol - start;
1003 pmatch[0].rm_eo += bol - start;
1005 return hit;
1008 static int match_one_pattern(struct grep_pat *p,
1009 const char *bol, const char *eol,
1010 enum grep_context ctx, regmatch_t *pmatch,
1011 int eflags)
1013 const char *field;
1014 size_t len;
1016 if (p->token == GREP_PATTERN_HEAD) {
1017 assert(p->field < ARRAY_SIZE(header_field));
1018 field = header_field[p->field].field;
1019 len = header_field[p->field].len;
1020 if (strncmp(bol, field, len))
1021 return 0;
1022 bol += len;
1024 switch (p->field) {
1025 case GREP_HEADER_AUTHOR:
1026 case GREP_HEADER_COMMITTER:
1027 strip_timestamp(bol, &eol);
1028 break;
1029 default:
1030 break;
1034 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1038 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1039 const char *bol, const char *eol,
1040 enum grep_context ctx, ssize_t *col,
1041 ssize_t *icol, int collect_hits)
1043 int h = 0;
1045 switch (x->node) {
1046 case GREP_NODE_TRUE:
1047 h = 1;
1048 break;
1049 case GREP_NODE_ATOM:
1051 regmatch_t tmp;
1052 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1053 &tmp, 0);
1054 if (h && (*col < 0 || tmp.rm_so < *col))
1055 *col = tmp.rm_so;
1057 if (x->u.atom->token == GREP_PATTERN_BODY)
1058 opt->body_hit |= h;
1059 break;
1060 case GREP_NODE_NOT:
1062 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1064 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1066 break;
1067 case GREP_NODE_AND:
1068 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1069 icol, 0);
1070 if (h || opt->columnnum) {
1072 * Don't short-circuit AND when given --column, since a
1073 * NOT earlier in the tree may turn this into an OR. In
1074 * this case, see the below comment.
1076 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1077 ctx, col, icol, 0);
1079 break;
1080 case GREP_NODE_OR:
1081 if (!(collect_hits || opt->columnnum)) {
1083 * Don't short-circuit OR when given --column (or
1084 * collecting hits) to ensure we don't skip a later
1085 * child that would produce an earlier match.
1087 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1088 ctx, col, icol, 0) ||
1089 match_expr_eval(opt, x->u.binary.right, bol,
1090 eol, ctx, col, icol, 0));
1092 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1093 icol, 0);
1094 if (collect_hits)
1095 x->u.binary.left->hit |= h;
1096 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1097 icol, collect_hits);
1098 break;
1099 default:
1100 die("Unexpected node type (internal error) %d", x->node);
1102 if (collect_hits)
1103 x->hit |= h;
1104 return h;
1107 static int match_expr(struct grep_opt *opt,
1108 const char *bol, const char *eol,
1109 enum grep_context ctx, ssize_t *col,
1110 ssize_t *icol, int collect_hits)
1112 struct grep_expr *x = opt->pattern_expression;
1113 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1116 static int match_line(struct grep_opt *opt,
1117 const char *bol, const char *eol,
1118 ssize_t *col, ssize_t *icol,
1119 enum grep_context ctx, int collect_hits)
1121 struct grep_pat *p;
1122 int hit = 0;
1124 if (opt->pattern_expression)
1125 return match_expr(opt, bol, eol, ctx, col, icol,
1126 collect_hits);
1128 /* we do not call with collect_hits without being extended */
1129 for (p = opt->pattern_list; p; p = p->next) {
1130 regmatch_t tmp;
1131 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1132 hit |= 1;
1133 if (!opt->columnnum) {
1135 * Without --column, any single match on a line
1136 * is enough to know that it needs to be
1137 * printed. With --column, scan _all_ patterns
1138 * to find the earliest.
1140 break;
1142 if (*col < 0 || tmp.rm_so < *col)
1143 *col = tmp.rm_so;
1146 return hit;
1149 static int match_next_pattern(struct grep_pat *p,
1150 const char *bol, const char *eol,
1151 enum grep_context ctx,
1152 regmatch_t *pmatch, int eflags)
1154 regmatch_t match;
1156 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1157 return 0;
1158 if (match.rm_so < 0 || match.rm_eo < 0)
1159 return 0;
1160 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1161 if (match.rm_so > pmatch->rm_so)
1162 return 1;
1163 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1164 return 1;
1166 pmatch->rm_so = match.rm_so;
1167 pmatch->rm_eo = match.rm_eo;
1168 return 1;
1171 int grep_next_match(struct grep_opt *opt,
1172 const char *bol, const char *eol,
1173 enum grep_context ctx, regmatch_t *pmatch,
1174 enum grep_header_field field, int eflags)
1176 struct grep_pat *p;
1177 int hit = 0;
1179 pmatch->rm_so = pmatch->rm_eo = -1;
1180 if (bol < eol) {
1181 for (p = ((ctx == GREP_CONTEXT_HEAD)
1182 ? opt->header_list : opt->pattern_list);
1183 p; p = p->next) {
1184 switch (p->token) {
1185 case GREP_PATTERN_HEAD:
1186 if ((field != GREP_HEADER_FIELD_MAX) &&
1187 (p->field != field))
1188 continue;
1189 /* fall thru */
1190 case GREP_PATTERN: /* atom */
1191 case GREP_PATTERN_BODY:
1192 hit |= match_next_pattern(p, bol, eol, ctx,
1193 pmatch, eflags);
1194 break;
1195 default:
1196 break;
1200 return hit;
1203 static void show_line_header(struct grep_opt *opt, const char *name,
1204 unsigned lno, ssize_t cno, char sign)
1206 if (opt->heading && opt->last_shown == 0) {
1207 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1208 opt->output(opt, "\n", 1);
1210 opt->last_shown = lno;
1212 if (!opt->heading && opt->pathname) {
1213 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1214 output_sep(opt, sign);
1216 if (opt->linenum) {
1217 char buf[32];
1218 xsnprintf(buf, sizeof(buf), "%d", lno);
1219 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1220 output_sep(opt, sign);
1223 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1224 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1225 * being called with a context line.
1227 if (opt->columnnum && cno) {
1228 char buf[32];
1229 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1230 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1231 output_sep(opt, sign);
1235 static void show_line(struct grep_opt *opt,
1236 const char *bol, const char *eol,
1237 const char *name, unsigned lno, ssize_t cno, char sign)
1239 int rest = eol - bol;
1240 const char *match_color = NULL;
1241 const char *line_color = NULL;
1243 if (opt->file_break && opt->last_shown == 0) {
1244 if (opt->show_hunk_mark)
1245 opt->output(opt, "\n", 1);
1246 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1247 if (opt->last_shown == 0) {
1248 if (opt->show_hunk_mark) {
1249 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1250 opt->output(opt, "\n", 1);
1252 } else if (lno > opt->last_shown + 1) {
1253 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1254 opt->output(opt, "\n", 1);
1257 if (!opt->only_matching) {
1259 * In case the line we're being called with contains more than
1260 * one match, leave printing each header to the loop below.
1262 show_line_header(opt, name, lno, cno, sign);
1264 if (opt->color || opt->only_matching) {
1265 regmatch_t match;
1266 enum grep_context ctx = GREP_CONTEXT_BODY;
1267 int eflags = 0;
1269 if (opt->color) {
1270 if (sign == ':')
1271 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1272 else
1273 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1274 if (sign == ':')
1275 line_color = opt->colors[GREP_COLOR_SELECTED];
1276 else if (sign == '-')
1277 line_color = opt->colors[GREP_COLOR_CONTEXT];
1278 else if (sign == '=')
1279 line_color = opt->colors[GREP_COLOR_FUNCTION];
1281 while (grep_next_match(opt, bol, eol, ctx, &match,
1282 GREP_HEADER_FIELD_MAX, eflags)) {
1283 if (match.rm_so == match.rm_eo)
1284 break;
1286 if (opt->only_matching)
1287 show_line_header(opt, name, lno, cno, sign);
1288 else
1289 output_color(opt, bol, match.rm_so, line_color);
1290 output_color(opt, bol + match.rm_so,
1291 match.rm_eo - match.rm_so, match_color);
1292 if (opt->only_matching)
1293 opt->output(opt, "\n", 1);
1294 bol += match.rm_eo;
1295 cno += match.rm_eo;
1296 rest -= match.rm_eo;
1297 eflags = REG_NOTBOL;
1300 if (!opt->only_matching) {
1301 output_color(opt, bol, rest, line_color);
1302 opt->output(opt, "\n", 1);
1306 int grep_use_locks;
1309 * This lock protects access to the gitattributes machinery, which is
1310 * not thread-safe.
1312 pthread_mutex_t grep_attr_mutex;
1314 static inline void grep_attr_lock(void)
1316 if (grep_use_locks)
1317 pthread_mutex_lock(&grep_attr_mutex);
1320 static inline void grep_attr_unlock(void)
1322 if (grep_use_locks)
1323 pthread_mutex_unlock(&grep_attr_mutex);
1326 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1327 const char *bol, const char *eol)
1329 xdemitconf_t *xecfg = opt->priv;
1330 if (xecfg && !xecfg->find_func) {
1331 grep_source_load_driver(gs, opt->repo->index);
1332 if (gs->driver->funcname.pattern) {
1333 const struct userdiff_funcname *pe = &gs->driver->funcname;
1334 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1335 } else {
1336 xecfg = opt->priv = NULL;
1340 if (xecfg) {
1341 char buf[1];
1342 return xecfg->find_func(bol, eol - bol, buf, 1,
1343 xecfg->find_func_priv) >= 0;
1346 if (bol == eol)
1347 return 0;
1348 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1349 return 1;
1350 return 0;
1353 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1354 const char *bol, unsigned lno)
1356 while (bol > gs->buf) {
1357 const char *eol = --bol;
1359 while (bol > gs->buf && bol[-1] != '\n')
1360 bol--;
1361 lno--;
1363 if (lno <= opt->last_shown)
1364 break;
1366 if (match_funcname(opt, gs, bol, eol)) {
1367 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1368 break;
1373 static int is_empty_line(const char *bol, const char *eol);
1375 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1376 const char *bol, const char *end, unsigned lno)
1378 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1379 int funcname_needed = !!opt->funcname, comment_needed = 0;
1381 if (opt->pre_context < lno)
1382 from = lno - opt->pre_context;
1383 if (from <= opt->last_shown)
1384 from = opt->last_shown + 1;
1385 orig_from = from;
1386 if (opt->funcbody) {
1387 if (match_funcname(opt, gs, bol, end))
1388 comment_needed = 1;
1389 else
1390 funcname_needed = 1;
1391 from = opt->last_shown + 1;
1394 /* Rewind. */
1395 while (bol > gs->buf && cur > from) {
1396 const char *next_bol = bol;
1397 const char *eol = --bol;
1399 while (bol > gs->buf && bol[-1] != '\n')
1400 bol--;
1401 cur--;
1402 if (comment_needed && (is_empty_line(bol, eol) ||
1403 match_funcname(opt, gs, bol, eol))) {
1404 comment_needed = 0;
1405 from = orig_from;
1406 if (cur < from) {
1407 cur++;
1408 bol = next_bol;
1409 break;
1412 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1413 funcname_lno = cur;
1414 funcname_needed = 0;
1415 if (opt->funcbody)
1416 comment_needed = 1;
1417 else
1418 from = orig_from;
1422 /* We need to look even further back to find a function signature. */
1423 if (opt->funcname && funcname_needed)
1424 show_funcname_line(opt, gs, bol, cur);
1426 /* Back forward. */
1427 while (cur < lno) {
1428 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1430 while (*eol != '\n')
1431 eol++;
1432 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1433 bol = eol + 1;
1434 cur++;
1438 static int should_lookahead(struct grep_opt *opt)
1440 struct grep_pat *p;
1442 if (opt->pattern_expression)
1443 return 0; /* punt for too complex stuff */
1444 if (opt->invert)
1445 return 0;
1446 for (p = opt->pattern_list; p; p = p->next) {
1447 if (p->token != GREP_PATTERN)
1448 return 0; /* punt for "header only" and stuff */
1450 return 1;
1453 static int look_ahead(struct grep_opt *opt,
1454 unsigned long *left_p,
1455 unsigned *lno_p,
1456 const char **bol_p)
1458 unsigned lno = *lno_p;
1459 const char *bol = *bol_p;
1460 struct grep_pat *p;
1461 const char *sp, *last_bol;
1462 regoff_t earliest = -1;
1464 for (p = opt->pattern_list; p; p = p->next) {
1465 int hit;
1466 regmatch_t m;
1468 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1469 if (hit < 0)
1470 return -1;
1471 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1472 continue;
1473 if (earliest < 0 || m.rm_so < earliest)
1474 earliest = m.rm_so;
1477 if (earliest < 0) {
1478 *bol_p = bol + *left_p;
1479 *left_p = 0;
1480 return 1;
1482 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1483 ; /* find the beginning of the line */
1484 last_bol = sp;
1486 for (sp = bol; sp < last_bol; sp++) {
1487 if (*sp == '\n')
1488 lno++;
1490 *left_p -= last_bol - bol;
1491 *bol_p = last_bol;
1492 *lno_p = lno;
1493 return 0;
1496 static int fill_textconv_grep(struct repository *r,
1497 struct userdiff_driver *driver,
1498 struct grep_source *gs)
1500 struct diff_filespec *df;
1501 char *buf;
1502 size_t size;
1504 if (!driver || !driver->textconv)
1505 return grep_source_load(gs);
1508 * The textconv interface is intimately tied to diff_filespecs, so we
1509 * have to pretend to be one. If we could unify the grep_source
1510 * and diff_filespec structs, this mess could just go away.
1512 df = alloc_filespec(gs->path);
1513 switch (gs->type) {
1514 case GREP_SOURCE_OID:
1515 fill_filespec(df, gs->identifier, 1, 0100644);
1516 break;
1517 case GREP_SOURCE_FILE:
1518 fill_filespec(df, null_oid(), 0, 0100644);
1519 break;
1520 default:
1521 BUG("attempt to textconv something without a path?");
1525 * fill_textconv is not remotely thread-safe; it modifies the global
1526 * diff tempfile structure, writes to the_repo's odb and might
1527 * internally call thread-unsafe functions such as the
1528 * prepare_packed_git() lazy-initializator. Because of the last two, we
1529 * must ensure mutual exclusion between this call and the object reading
1530 * API, thus we use obj_read_lock() here.
1532 * TODO: allowing text conversion to run in parallel with object
1533 * reading operations might increase performance in the multithreaded
1534 * non-worktreee git-grep with --textconv.
1536 obj_read_lock();
1537 size = fill_textconv(r, driver, df, &buf);
1538 obj_read_unlock();
1539 free_filespec(df);
1542 * The normal fill_textconv usage by the diff machinery would just keep
1543 * the textconv'd buf separate from the diff_filespec. But much of the
1544 * grep code passes around a grep_source and assumes that its "buf"
1545 * pointer is the beginning of the thing we are searching. So let's
1546 * install our textconv'd version into the grep_source, taking care not
1547 * to leak any existing buffer.
1549 grep_source_clear_data(gs);
1550 gs->buf = buf;
1551 gs->size = size;
1553 return 0;
1556 static int is_empty_line(const char *bol, const char *eol)
1558 while (bol < eol && isspace(*bol))
1559 bol++;
1560 return bol == eol;
1563 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1565 const char *bol;
1566 const char *peek_bol = NULL;
1567 unsigned long left;
1568 unsigned lno = 1;
1569 unsigned last_hit = 0;
1570 int binary_match_only = 0;
1571 unsigned count = 0;
1572 int try_lookahead = 0;
1573 int show_function = 0;
1574 struct userdiff_driver *textconv = NULL;
1575 enum grep_context ctx = GREP_CONTEXT_HEAD;
1576 xdemitconf_t xecfg;
1578 if (!opt->status_only && gs->name == NULL)
1579 BUG("grep call which could print a name requires "
1580 "grep_source.name be non-NULL");
1582 if (!opt->output)
1583 opt->output = std_output;
1585 if (opt->pre_context || opt->post_context || opt->file_break ||
1586 opt->funcbody) {
1587 /* Show hunk marks, except for the first file. */
1588 if (opt->last_shown)
1589 opt->show_hunk_mark = 1;
1591 * If we're using threads then we can't easily identify
1592 * the first file. Always put hunk marks in that case
1593 * and skip the very first one later in work_done().
1595 if (opt->output != std_output)
1596 opt->show_hunk_mark = 1;
1598 opt->last_shown = 0;
1600 if (opt->allow_textconv) {
1601 grep_source_load_driver(gs, opt->repo->index);
1603 * We might set up the shared textconv cache data here, which
1604 * is not thread-safe. Also, get_oid_with_context() and
1605 * parse_object() might be internally called. As they are not
1606 * currently thread-safe and might be racy with object reading,
1607 * obj_read_lock() must be called.
1609 grep_attr_lock();
1610 obj_read_lock();
1611 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1612 obj_read_unlock();
1613 grep_attr_unlock();
1617 * We know the result of a textconv is text, so we only have to care
1618 * about binary handling if we are not using it.
1620 if (!textconv) {
1621 switch (opt->binary) {
1622 case GREP_BINARY_DEFAULT:
1623 if (grep_source_is_binary(gs, opt->repo->index))
1624 binary_match_only = 1;
1625 break;
1626 case GREP_BINARY_NOMATCH:
1627 if (grep_source_is_binary(gs, opt->repo->index))
1628 return 0; /* Assume unmatch */
1629 break;
1630 case GREP_BINARY_TEXT:
1631 break;
1632 default:
1633 BUG("unknown binary handling mode");
1637 memset(&xecfg, 0, sizeof(xecfg));
1638 opt->priv = &xecfg;
1640 try_lookahead = should_lookahead(opt);
1642 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1643 return 0;
1645 bol = gs->buf;
1646 left = gs->size;
1647 while (left) {
1648 const char *eol;
1649 int hit;
1650 ssize_t cno;
1651 ssize_t col = -1, icol = -1;
1654 * look_ahead() skips quickly to the line that possibly
1655 * has the next hit; don't call it if we need to do
1656 * something more than just skipping the current line
1657 * in response to an unmatch for the current line. E.g.
1658 * inside a post-context window, we will show the current
1659 * line as a context around the previous hit when it
1660 * doesn't hit.
1662 if (try_lookahead
1663 && !(last_hit
1664 && (show_function ||
1665 lno <= last_hit + opt->post_context))) {
1666 hit = look_ahead(opt, &left, &lno, &bol);
1667 if (hit < 0)
1668 try_lookahead = 0;
1669 else if (hit)
1670 break;
1672 eol = end_of_line(bol, &left);
1674 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1675 ctx = GREP_CONTEXT_BODY;
1677 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1679 if (collect_hits)
1680 goto next_line;
1682 /* "grep -v -e foo -e bla" should list lines
1683 * that do not have either, so inversion should
1684 * be done outside.
1686 if (opt->invert)
1687 hit = !hit;
1688 if (opt->unmatch_name_only) {
1689 if (hit)
1690 return 0;
1691 goto next_line;
1693 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1694 count++;
1695 if (opt->status_only)
1696 return 1;
1697 if (opt->name_only) {
1698 show_name(opt, gs->name);
1699 return 1;
1701 if (opt->count)
1702 goto next_line;
1703 if (binary_match_only) {
1704 opt->output(opt, "Binary file ", 12);
1705 output_color(opt, gs->name, strlen(gs->name),
1706 opt->colors[GREP_COLOR_FILENAME]);
1707 opt->output(opt, " matches\n", 9);
1708 return 1;
1710 /* Hit at this line. If we haven't shown the
1711 * pre-context lines, we would need to show them.
1713 if (opt->pre_context || opt->funcbody)
1714 show_pre_context(opt, gs, bol, eol, lno);
1715 else if (opt->funcname)
1716 show_funcname_line(opt, gs, bol, lno);
1717 cno = opt->invert ? icol : col;
1718 if (cno < 0) {
1720 * A negative cno indicates that there was no
1721 * match on the line. We are thus inverted and
1722 * being asked to show all lines that _don't_
1723 * match a given expression. Therefore, set cno
1724 * to 0 to suggest the whole line matches.
1726 cno = 0;
1728 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1729 last_hit = lno;
1730 if (opt->funcbody)
1731 show_function = 1;
1732 goto next_line;
1734 if (show_function && (!peek_bol || peek_bol < bol)) {
1735 unsigned long peek_left = left;
1736 const char *peek_eol = eol;
1739 * Trailing empty lines are not interesting.
1740 * Peek past them to see if they belong to the
1741 * body of the current function.
1743 peek_bol = bol;
1744 while (is_empty_line(peek_bol, peek_eol)) {
1745 peek_bol = peek_eol + 1;
1746 peek_eol = end_of_line(peek_bol, &peek_left);
1749 if (peek_bol >= gs->buf + gs->size ||
1750 match_funcname(opt, gs, peek_bol, peek_eol))
1751 show_function = 0;
1753 if (show_function ||
1754 (last_hit && lno <= last_hit + opt->post_context)) {
1755 /* If the last hit is within the post context,
1756 * we need to show this line.
1758 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1761 next_line:
1762 bol = eol + 1;
1763 if (!left)
1764 break;
1765 left--;
1766 lno++;
1769 if (collect_hits)
1770 return 0;
1772 if (opt->status_only)
1773 return opt->unmatch_name_only;
1774 if (opt->unmatch_name_only) {
1775 /* We did not see any hit, so we want to show this */
1776 show_name(opt, gs->name);
1777 return 1;
1780 xdiff_clear_find_func(&xecfg);
1781 opt->priv = NULL;
1783 /* NEEDSWORK:
1784 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1785 * which feels mostly useless but sometimes useful. Maybe
1786 * make it another option? For now suppress them.
1788 if (opt->count && count) {
1789 char buf[32];
1790 if (opt->pathname) {
1791 output_color(opt, gs->name, strlen(gs->name),
1792 opt->colors[GREP_COLOR_FILENAME]);
1793 output_sep(opt, ':');
1795 xsnprintf(buf, sizeof(buf), "%u\n", count);
1796 opt->output(opt, buf, strlen(buf));
1797 return 1;
1799 return !!last_hit;
1802 static void clr_hit_marker(struct grep_expr *x)
1804 /* All-hit markers are meaningful only at the very top level
1805 * OR node.
1807 while (1) {
1808 x->hit = 0;
1809 if (x->node != GREP_NODE_OR)
1810 return;
1811 x->u.binary.left->hit = 0;
1812 x = x->u.binary.right;
1816 static int chk_hit_marker(struct grep_expr *x)
1818 /* Top level nodes have hit markers. See if they all are hits */
1819 while (1) {
1820 if (x->node != GREP_NODE_OR)
1821 return x->hit;
1822 if (!x->u.binary.left->hit)
1823 return 0;
1824 x = x->u.binary.right;
1828 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1831 * we do not have to do the two-pass grep when we do not check
1832 * buffer-wide "all-match".
1834 if (!opt->all_match && !opt->no_body_match)
1835 return grep_source_1(opt, gs, 0);
1837 /* Otherwise the toplevel "or" terms hit a bit differently.
1838 * We first clear hit markers from them.
1840 clr_hit_marker(opt->pattern_expression);
1841 opt->body_hit = 0;
1842 grep_source_1(opt, gs, 1);
1844 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1845 return 0;
1846 if (opt->no_body_match && opt->body_hit)
1847 return 0;
1849 return grep_source_1(opt, gs, 0);
1852 static void grep_source_init_buf(struct grep_source *gs,
1853 const char *buf,
1854 unsigned long size)
1856 gs->type = GREP_SOURCE_BUF;
1857 gs->name = NULL;
1858 gs->path = NULL;
1859 gs->buf = buf;
1860 gs->size = size;
1861 gs->driver = NULL;
1862 gs->identifier = NULL;
1865 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1867 struct grep_source gs;
1868 int r;
1870 grep_source_init_buf(&gs, buf, size);
1872 r = grep_source(opt, &gs);
1874 grep_source_clear(&gs);
1875 return r;
1878 void grep_source_init_file(struct grep_source *gs, const char *name,
1879 const char *path)
1881 gs->type = GREP_SOURCE_FILE;
1882 gs->name = xstrdup_or_null(name);
1883 gs->path = xstrdup_or_null(path);
1884 gs->buf = NULL;
1885 gs->size = 0;
1886 gs->driver = NULL;
1887 gs->identifier = xstrdup(path);
1890 void grep_source_init_oid(struct grep_source *gs, const char *name,
1891 const char *path, const struct object_id *oid,
1892 struct repository *repo)
1894 gs->type = GREP_SOURCE_OID;
1895 gs->name = xstrdup_or_null(name);
1896 gs->path = xstrdup_or_null(path);
1897 gs->buf = NULL;
1898 gs->size = 0;
1899 gs->driver = NULL;
1900 gs->identifier = oiddup(oid);
1901 gs->repo = repo;
1904 void grep_source_clear(struct grep_source *gs)
1906 FREE_AND_NULL(gs->name);
1907 FREE_AND_NULL(gs->path);
1908 FREE_AND_NULL(gs->identifier);
1909 grep_source_clear_data(gs);
1912 void grep_source_clear_data(struct grep_source *gs)
1914 switch (gs->type) {
1915 case GREP_SOURCE_FILE:
1916 case GREP_SOURCE_OID:
1917 /* these types own the buffer */
1918 free((char *)gs->buf);
1919 gs->buf = NULL;
1920 gs->size = 0;
1921 break;
1922 case GREP_SOURCE_BUF:
1923 /* leave user-provided buf intact */
1924 break;
1928 static int grep_source_load_oid(struct grep_source *gs)
1930 enum object_type type;
1932 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1933 &gs->size);
1934 if (!gs->buf)
1935 return error(_("'%s': unable to read %s"),
1936 gs->name,
1937 oid_to_hex(gs->identifier));
1938 return 0;
1941 static int grep_source_load_file(struct grep_source *gs)
1943 const char *filename = gs->identifier;
1944 struct stat st;
1945 char *data;
1946 size_t size;
1947 int i;
1949 if (lstat(filename, &st) < 0) {
1950 err_ret:
1951 if (errno != ENOENT)
1952 error_errno(_("failed to stat '%s'"), filename);
1953 return -1;
1955 if (!S_ISREG(st.st_mode))
1956 return -1;
1957 size = xsize_t(st.st_size);
1958 i = open(filename, O_RDONLY);
1959 if (i < 0)
1960 goto err_ret;
1961 data = xmallocz(size);
1962 if (st.st_size != read_in_full(i, data, size)) {
1963 error_errno(_("'%s': short read"), filename);
1964 close(i);
1965 free(data);
1966 return -1;
1968 close(i);
1970 gs->buf = data;
1971 gs->size = size;
1972 return 0;
1975 static int grep_source_load(struct grep_source *gs)
1977 if (gs->buf)
1978 return 0;
1980 switch (gs->type) {
1981 case GREP_SOURCE_FILE:
1982 return grep_source_load_file(gs);
1983 case GREP_SOURCE_OID:
1984 return grep_source_load_oid(gs);
1985 case GREP_SOURCE_BUF:
1986 return gs->buf ? 0 : -1;
1988 BUG("invalid grep_source type to load");
1991 void grep_source_load_driver(struct grep_source *gs,
1992 struct index_state *istate)
1994 if (gs->driver)
1995 return;
1997 grep_attr_lock();
1998 if (gs->path)
1999 gs->driver = userdiff_find_by_path(istate, gs->path);
2000 if (!gs->driver)
2001 gs->driver = userdiff_find_by_name("default");
2002 grep_attr_unlock();
2005 static int grep_source_is_binary(struct grep_source *gs,
2006 struct index_state *istate)
2008 grep_source_load_driver(gs, istate);
2009 if (gs->driver->binary != -1)
2010 return gs->driver->binary;
2012 if (!grep_source_load(gs))
2013 return buffer_is_binary(gs->buf, gs->size);
2015 return 0;