Merge branch 'jk/unused-post-2.40'
[git.git] / grep.c
blob25dc2ec78841b9e97103c267f37db665bb4d4149
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_35_OR_HIGHER
326 * Work around a JIT bug related to invalid Unicode character handling
327 * fixed in 10.35:
328 * https://github.com/PCRE2Project/pcre2/commit/c21bd977547d
330 options &= ~PCRE2_UCP;
331 #endif
333 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
334 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
335 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
336 options |= PCRE2_NO_START_OPTIMIZE;
337 #endif
339 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
340 p->patternlen, options, &error, &erroffset,
341 p->pcre2_compile_context);
343 if (p->pcre2_pattern) {
344 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
345 if (!p->pcre2_match_data)
346 die("Couldn't allocate PCRE2 match data");
347 } else {
348 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
349 compile_regexp_failed(p, (const char *)&errbuf);
352 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
353 if (p->pcre2_jit_on) {
354 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
355 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
357 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
358 * indicated JIT support, the library might still
359 * fail to generate JIT code for various reasons,
360 * e.g. when SELinux's 'deny_execmem' or PaX's
361 * MPROTECT prevent creating W|X memory mappings.
363 * Instead of faling hard, fall back to interpreter
364 * mode, just as if the pattern was prefixed with
365 * '(*NO_JIT)'.
367 p->pcre2_jit_on = 0;
368 return;
369 } else if (jitret) {
370 int need_clip = p->patternlen > 64;
371 int clip_len = need_clip ? 64 : p->patternlen;
372 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
373 clip_len, p->pattern, need_clip ? "..." : "", jitret,
374 pcre2_jit_functional()
375 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
376 : "");
380 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
381 * tells us whether the library itself supports JIT,
382 * but to see whether we're going to be actually using
383 * JIT we need to extract PCRE2_INFO_JITSIZE from the
384 * pattern *after* we do pcre2_jit_compile() above.
386 * This is because if the pattern contains the
387 * (*NO_JIT) verb (see pcre2syntax(3))
388 * pcre2_jit_compile() will exit early with 0. If we
389 * then proceed to call pcre2_jit_match() further down
390 * the line instead of pcre2_match() we'll either
391 * segfault (pre PCRE 10.31) or run into a fatal error
392 * (post PCRE2 10.31)
394 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
395 if (patinforet)
396 BUG("pcre2_pattern_info() failed: %d", patinforet);
397 if (jitsizearg == 0) {
398 p->pcre2_jit_on = 0;
399 return;
404 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
405 regmatch_t *match, int eflags)
407 int ret, flags = 0;
408 PCRE2_SIZE *ovector;
409 PCRE2_UCHAR errbuf[256];
411 if (eflags & REG_NOTBOL)
412 flags |= PCRE2_NOTBOL;
414 if (p->pcre2_jit_on)
415 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
416 eol - line, 0, flags, p->pcre2_match_data,
417 NULL);
418 else
419 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
420 eol - line, 0, flags, p->pcre2_match_data,
421 NULL);
423 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
424 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
425 die("%s failed with error code %d: %s",
426 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
427 errbuf);
429 if (ret > 0) {
430 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
431 ret = 0;
432 match->rm_so = (int)ovector[0];
433 match->rm_eo = (int)ovector[1];
436 return ret;
439 static void free_pcre2_pattern(struct grep_pat *p)
441 pcre2_compile_context_free(p->pcre2_compile_context);
442 pcre2_code_free(p->pcre2_pattern);
443 pcre2_match_data_free(p->pcre2_match_data);
444 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
445 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
446 #else
447 free((void *)p->pcre2_tables);
448 #endif
449 pcre2_general_context_free(p->pcre2_general_context);
451 #else /* !USE_LIBPCRE2 */
452 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
454 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
457 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
458 regmatch_t *match, int eflags)
460 return 1;
463 static void free_pcre2_pattern(struct grep_pat *p)
467 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
469 struct strbuf sb = STRBUF_INIT;
470 int err;
471 int regflags = 0;
473 basic_regex_quote_buf(&sb, p->pattern);
474 if (opt->ignore_case)
475 regflags |= REG_ICASE;
476 err = regcomp(&p->regexp, sb.buf, regflags);
477 strbuf_release(&sb);
478 if (err) {
479 char errbuf[1024];
480 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
481 compile_regexp_failed(p, errbuf);
484 #endif /* !USE_LIBPCRE2 */
486 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
488 int err;
489 int regflags = REG_NEWLINE;
491 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
492 opt->pattern_type_option = (opt->extended_regexp_option
493 ? GREP_PATTERN_TYPE_ERE
494 : GREP_PATTERN_TYPE_BRE);
496 p->word_regexp = opt->word_regexp;
497 p->ignore_case = opt->ignore_case;
498 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
500 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
501 memchr(p->pattern, 0, p->patternlen))
502 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
504 p->is_fixed = is_fixed(p->pattern, p->patternlen);
505 #ifdef USE_LIBPCRE2
506 if (!p->fixed && !p->is_fixed) {
507 const char *no_jit = "(*NO_JIT)";
508 const int no_jit_len = strlen(no_jit);
509 if (starts_with(p->pattern, no_jit) &&
510 is_fixed(p->pattern + no_jit_len,
511 p->patternlen - no_jit_len))
512 p->is_fixed = 1;
514 #endif
515 if (p->fixed || p->is_fixed) {
516 #ifdef USE_LIBPCRE2
517 if (p->is_fixed) {
518 compile_pcre2_pattern(p, opt);
519 } else {
521 * E.g. t7811-grep-open.sh relies on the
522 * pattern being restored.
524 char *old_pattern = p->pattern;
525 size_t old_patternlen = p->patternlen;
526 struct strbuf sb = STRBUF_INIT;
529 * There is the PCRE2_LITERAL flag, but it's
530 * only in PCRE v2 10.30 and later. Needing to
531 * ifdef our way around that and dealing with
532 * it + PCRE2_MULTILINE being an error is more
533 * complex than just quoting this ourselves.
535 strbuf_add(&sb, "\\Q", 2);
536 strbuf_add(&sb, p->pattern, p->patternlen);
537 strbuf_add(&sb, "\\E", 2);
539 p->pattern = sb.buf;
540 p->patternlen = sb.len;
541 compile_pcre2_pattern(p, opt);
542 p->pattern = old_pattern;
543 p->patternlen = old_patternlen;
544 strbuf_release(&sb);
546 #else /* !USE_LIBPCRE2 */
547 compile_fixed_regexp(p, opt);
548 #endif /* !USE_LIBPCRE2 */
549 return;
552 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
553 compile_pcre2_pattern(p, opt);
554 return;
557 if (p->ignore_case)
558 regflags |= REG_ICASE;
559 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
560 regflags |= REG_EXTENDED;
561 err = regcomp(&p->regexp, p->pattern, regflags);
562 if (err) {
563 char errbuf[1024];
564 regerror(err, &p->regexp, errbuf, 1024);
565 compile_regexp_failed(p, errbuf);
569 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
571 struct grep_expr *z = xcalloc(1, sizeof(*z));
572 z->node = GREP_NODE_NOT;
573 z->u.unary = expr;
574 return z;
577 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
578 struct grep_expr *left,
579 struct grep_expr *right)
581 struct grep_expr *z = xcalloc(1, sizeof(*z));
582 z->node = kind;
583 z->u.binary.left = left;
584 z->u.binary.right = right;
585 return z;
588 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
590 return grep_binexp(GREP_NODE_OR, left, right);
593 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
595 return grep_binexp(GREP_NODE_AND, left, right);
598 static struct grep_expr *compile_pattern_or(struct grep_pat **);
599 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
601 struct grep_pat *p;
602 struct grep_expr *x;
604 p = *list;
605 if (!p)
606 return NULL;
607 switch (p->token) {
608 case GREP_PATTERN: /* atom */
609 case GREP_PATTERN_HEAD:
610 case GREP_PATTERN_BODY:
611 CALLOC_ARRAY(x, 1);
612 x->node = GREP_NODE_ATOM;
613 x->u.atom = p;
614 *list = p->next;
615 return x;
616 case GREP_OPEN_PAREN:
617 *list = p->next;
618 x = compile_pattern_or(list);
619 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
620 die("unmatched parenthesis");
621 *list = (*list)->next;
622 return x;
623 default:
624 return NULL;
628 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
630 struct grep_pat *p;
631 struct grep_expr *x;
633 p = *list;
634 if (!p)
635 return NULL;
636 switch (p->token) {
637 case GREP_NOT:
638 if (!p->next)
639 die("--not not followed by pattern expression");
640 *list = p->next;
641 x = compile_pattern_not(list);
642 if (!x)
643 die("--not followed by non pattern expression");
644 return grep_not_expr(x);
645 default:
646 return compile_pattern_atom(list);
650 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
652 struct grep_pat *p;
653 struct grep_expr *x, *y;
655 x = compile_pattern_not(list);
656 p = *list;
657 if (p && p->token == GREP_AND) {
658 if (!x)
659 die("--and not preceded by pattern expression");
660 if (!p->next)
661 die("--and not followed by pattern expression");
662 *list = p->next;
663 y = compile_pattern_and(list);
664 if (!y)
665 die("--and not followed by pattern expression");
666 return grep_and_expr(x, y);
668 return x;
671 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
673 struct grep_pat *p;
674 struct grep_expr *x, *y;
676 x = compile_pattern_and(list);
677 p = *list;
678 if (x && p && p->token != GREP_CLOSE_PAREN) {
679 y = compile_pattern_or(list);
680 if (!y)
681 die("not a pattern expression %s", p->pattern);
682 return grep_or_expr(x, y);
684 return x;
687 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
689 return compile_pattern_or(list);
692 static struct grep_expr *grep_true_expr(void)
694 struct grep_expr *z = xcalloc(1, sizeof(*z));
695 z->node = GREP_NODE_TRUE;
696 return z;
699 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
701 struct grep_pat *p;
702 struct grep_expr *header_expr;
703 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
704 enum grep_header_field fld;
706 if (!opt->header_list)
707 return NULL;
709 for (p = opt->header_list; p; p = p->next) {
710 if (p->token != GREP_PATTERN_HEAD)
711 BUG("a non-header pattern in grep header list.");
712 if (p->field < GREP_HEADER_FIELD_MIN ||
713 GREP_HEADER_FIELD_MAX <= p->field)
714 BUG("unknown header field %d", p->field);
715 compile_regexp(p, opt);
718 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
719 header_group[fld] = NULL;
721 for (p = opt->header_list; p; p = p->next) {
722 struct grep_expr *h;
723 struct grep_pat *pp = p;
725 h = compile_pattern_atom(&pp);
726 if (!h || pp != p->next)
727 BUG("malformed header expr");
728 if (!header_group[p->field]) {
729 header_group[p->field] = h;
730 continue;
732 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
735 header_expr = NULL;
737 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
738 if (!header_group[fld])
739 continue;
740 if (!header_expr)
741 header_expr = grep_true_expr();
742 header_expr = grep_or_expr(header_group[fld], header_expr);
744 return header_expr;
747 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
749 struct grep_expr *z = x;
751 while (x) {
752 assert(x->node == GREP_NODE_OR);
753 if (x->u.binary.right &&
754 x->u.binary.right->node == GREP_NODE_TRUE) {
755 x->u.binary.right = y;
756 break;
758 x = x->u.binary.right;
760 return z;
763 void compile_grep_patterns(struct grep_opt *opt)
765 struct grep_pat *p;
766 struct grep_expr *header_expr = prep_header_patterns(opt);
767 int extended = 0;
769 for (p = opt->pattern_list; p; p = p->next) {
770 switch (p->token) {
771 case GREP_PATTERN: /* atom */
772 case GREP_PATTERN_HEAD:
773 case GREP_PATTERN_BODY:
774 compile_regexp(p, opt);
775 break;
776 default:
777 extended = 1;
778 break;
782 if (opt->all_match || opt->no_body_match || header_expr)
783 extended = 1;
784 else if (!extended)
785 return;
787 p = opt->pattern_list;
788 if (p)
789 opt->pattern_expression = compile_pattern_expr(&p);
790 if (p)
791 die("incomplete pattern expression: %s", p->pattern);
793 if (opt->no_body_match && opt->pattern_expression)
794 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
796 if (!header_expr)
797 return;
799 if (!opt->pattern_expression)
800 opt->pattern_expression = header_expr;
801 else if (opt->all_match)
802 opt->pattern_expression = grep_splice_or(header_expr,
803 opt->pattern_expression);
804 else
805 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
806 header_expr);
807 opt->all_match = 1;
810 static void free_pattern_expr(struct grep_expr *x)
812 switch (x->node) {
813 case GREP_NODE_TRUE:
814 case GREP_NODE_ATOM:
815 break;
816 case GREP_NODE_NOT:
817 free_pattern_expr(x->u.unary);
818 break;
819 case GREP_NODE_AND:
820 case GREP_NODE_OR:
821 free_pattern_expr(x->u.binary.left);
822 free_pattern_expr(x->u.binary.right);
823 break;
825 free(x);
828 static void free_grep_pat(struct grep_pat *pattern)
830 struct grep_pat *p, *n;
832 for (p = pattern; p; p = n) {
833 n = p->next;
834 switch (p->token) {
835 case GREP_PATTERN: /* atom */
836 case GREP_PATTERN_HEAD:
837 case GREP_PATTERN_BODY:
838 if (p->pcre2_pattern)
839 free_pcre2_pattern(p);
840 else
841 regfree(&p->regexp);
842 free(p->pattern);
843 break;
844 default:
845 break;
847 free(p);
851 void free_grep_patterns(struct grep_opt *opt)
853 free_grep_pat(opt->pattern_list);
854 free_grep_pat(opt->header_list);
856 if (opt->pattern_expression)
857 free_pattern_expr(opt->pattern_expression);
860 static const char *end_of_line(const char *cp, unsigned long *left)
862 unsigned long l = *left;
863 while (l && *cp != '\n') {
864 l--;
865 cp++;
867 *left = l;
868 return cp;
871 static int word_char(char ch)
873 return isalnum(ch) || ch == '_';
876 static void output_color(struct grep_opt *opt, const void *data, size_t size,
877 const char *color)
879 if (want_color(opt->color) && color && color[0]) {
880 opt->output(opt, color, strlen(color));
881 opt->output(opt, data, size);
882 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
883 } else
884 opt->output(opt, data, size);
887 static void output_sep(struct grep_opt *opt, char sign)
889 if (opt->null_following_name)
890 opt->output(opt, "\0", 1);
891 else
892 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
895 static void show_name(struct grep_opt *opt, const char *name)
897 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
898 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
901 static int patmatch(struct grep_pat *p,
902 const char *line, const char *eol,
903 regmatch_t *match, int eflags)
905 int hit;
907 if (p->pcre2_pattern)
908 hit = !pcre2match(p, line, eol, match, eflags);
909 else
910 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
911 eflags);
913 return hit;
916 static void strip_timestamp(const char *bol, const char **eol_p)
918 const char *eol = *eol_p;
920 while (bol < --eol) {
921 if (*eol != '>')
922 continue;
923 *eol_p = ++eol;
924 break;
928 static struct {
929 const char *field;
930 size_t len;
931 } header_field[] = {
932 { "author ", 7 },
933 { "committer ", 10 },
934 { "reflog ", 7 },
937 static int headerless_match_one_pattern(struct grep_pat *p,
938 const char *bol, const char *eol,
939 enum grep_context ctx,
940 regmatch_t *pmatch, int eflags)
942 int hit = 0;
943 const char *start = bol;
945 if ((p->token != GREP_PATTERN) &&
946 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
947 return 0;
949 again:
950 hit = patmatch(p, bol, eol, pmatch, eflags);
952 if (hit && p->word_regexp) {
953 if ((pmatch[0].rm_so < 0) ||
954 (eol - bol) < pmatch[0].rm_so ||
955 (pmatch[0].rm_eo < 0) ||
956 (eol - bol) < pmatch[0].rm_eo)
957 die("regexp returned nonsense");
959 /* Match beginning must be either beginning of the
960 * line, or at word boundary (i.e. the last char must
961 * not be a word char). Similarly, match end must be
962 * either end of the line, or at word boundary
963 * (i.e. the next char must not be a word char).
965 if ( ((pmatch[0].rm_so == 0) ||
966 !word_char(bol[pmatch[0].rm_so-1])) &&
967 ((pmatch[0].rm_eo == (eol-bol)) ||
968 !word_char(bol[pmatch[0].rm_eo])) )
970 else
971 hit = 0;
973 /* Words consist of at least one character. */
974 if (pmatch->rm_so == pmatch->rm_eo)
975 hit = 0;
977 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
978 /* There could be more than one match on the
979 * line, and the first match might not be
980 * strict word match. But later ones could be!
981 * Forward to the next possible start, i.e. the
982 * next position following a non-word char.
984 bol = pmatch[0].rm_so + bol + 1;
985 while (word_char(bol[-1]) && bol < eol)
986 bol++;
987 eflags |= REG_NOTBOL;
988 if (bol < eol)
989 goto again;
992 if (hit) {
993 pmatch[0].rm_so += bol - start;
994 pmatch[0].rm_eo += bol - start;
996 return hit;
999 static int match_one_pattern(struct grep_pat *p,
1000 const char *bol, const char *eol,
1001 enum grep_context ctx, regmatch_t *pmatch,
1002 int eflags)
1004 const char *field;
1005 size_t len;
1007 if (p->token == GREP_PATTERN_HEAD) {
1008 assert(p->field < ARRAY_SIZE(header_field));
1009 field = header_field[p->field].field;
1010 len = header_field[p->field].len;
1011 if (strncmp(bol, field, len))
1012 return 0;
1013 bol += len;
1015 switch (p->field) {
1016 case GREP_HEADER_AUTHOR:
1017 case GREP_HEADER_COMMITTER:
1018 strip_timestamp(bol, &eol);
1019 break;
1020 default:
1021 break;
1025 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1029 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1030 const char *bol, const char *eol,
1031 enum grep_context ctx, ssize_t *col,
1032 ssize_t *icol, int collect_hits)
1034 int h = 0;
1036 switch (x->node) {
1037 case GREP_NODE_TRUE:
1038 h = 1;
1039 break;
1040 case GREP_NODE_ATOM:
1042 regmatch_t tmp;
1043 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1044 &tmp, 0);
1045 if (h && (*col < 0 || tmp.rm_so < *col))
1046 *col = tmp.rm_so;
1048 if (x->u.atom->token == GREP_PATTERN_BODY)
1049 opt->body_hit |= h;
1050 break;
1051 case GREP_NODE_NOT:
1053 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1055 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1057 break;
1058 case GREP_NODE_AND:
1059 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1060 icol, 0);
1061 if (h || opt->columnnum) {
1063 * Don't short-circuit AND when given --column, since a
1064 * NOT earlier in the tree may turn this into an OR. In
1065 * this case, see the below comment.
1067 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1068 ctx, col, icol, 0);
1070 break;
1071 case GREP_NODE_OR:
1072 if (!(collect_hits || opt->columnnum)) {
1074 * Don't short-circuit OR when given --column (or
1075 * collecting hits) to ensure we don't skip a later
1076 * child that would produce an earlier match.
1078 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1079 ctx, col, icol, 0) ||
1080 match_expr_eval(opt, x->u.binary.right, bol,
1081 eol, ctx, col, icol, 0));
1083 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1084 icol, 0);
1085 if (collect_hits)
1086 x->u.binary.left->hit |= h;
1087 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1088 icol, collect_hits);
1089 break;
1090 default:
1091 die("Unexpected node type (internal error) %d", x->node);
1093 if (collect_hits)
1094 x->hit |= h;
1095 return h;
1098 static int match_expr(struct grep_opt *opt,
1099 const char *bol, const char *eol,
1100 enum grep_context ctx, ssize_t *col,
1101 ssize_t *icol, int collect_hits)
1103 struct grep_expr *x = opt->pattern_expression;
1104 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1107 static int match_line(struct grep_opt *opt,
1108 const char *bol, const char *eol,
1109 ssize_t *col, ssize_t *icol,
1110 enum grep_context ctx, int collect_hits)
1112 struct grep_pat *p;
1113 int hit = 0;
1115 if (opt->pattern_expression)
1116 return match_expr(opt, bol, eol, ctx, col, icol,
1117 collect_hits);
1119 /* we do not call with collect_hits without being extended */
1120 for (p = opt->pattern_list; p; p = p->next) {
1121 regmatch_t tmp;
1122 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1123 hit |= 1;
1124 if (!opt->columnnum) {
1126 * Without --column, any single match on a line
1127 * is enough to know that it needs to be
1128 * printed. With --column, scan _all_ patterns
1129 * to find the earliest.
1131 break;
1133 if (*col < 0 || tmp.rm_so < *col)
1134 *col = tmp.rm_so;
1137 return hit;
1140 static int match_next_pattern(struct grep_pat *p,
1141 const char *bol, const char *eol,
1142 enum grep_context ctx,
1143 regmatch_t *pmatch, int eflags)
1145 regmatch_t match;
1147 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1148 return 0;
1149 if (match.rm_so < 0 || match.rm_eo < 0)
1150 return 0;
1151 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1152 if (match.rm_so > pmatch->rm_so)
1153 return 1;
1154 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1155 return 1;
1157 pmatch->rm_so = match.rm_so;
1158 pmatch->rm_eo = match.rm_eo;
1159 return 1;
1162 int grep_next_match(struct grep_opt *opt,
1163 const char *bol, const char *eol,
1164 enum grep_context ctx, regmatch_t *pmatch,
1165 enum grep_header_field field, int eflags)
1167 struct grep_pat *p;
1168 int hit = 0;
1170 pmatch->rm_so = pmatch->rm_eo = -1;
1171 if (bol < eol) {
1172 for (p = ((ctx == GREP_CONTEXT_HEAD)
1173 ? opt->header_list : opt->pattern_list);
1174 p; p = p->next) {
1175 switch (p->token) {
1176 case GREP_PATTERN_HEAD:
1177 if ((field != GREP_HEADER_FIELD_MAX) &&
1178 (p->field != field))
1179 continue;
1180 /* fall thru */
1181 case GREP_PATTERN: /* atom */
1182 case GREP_PATTERN_BODY:
1183 hit |= match_next_pattern(p, bol, eol, ctx,
1184 pmatch, eflags);
1185 break;
1186 default:
1187 break;
1191 return hit;
1194 static void show_line_header(struct grep_opt *opt, const char *name,
1195 unsigned lno, ssize_t cno, char sign)
1197 if (opt->heading && opt->last_shown == 0) {
1198 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1199 opt->output(opt, "\n", 1);
1201 opt->last_shown = lno;
1203 if (!opt->heading && opt->pathname) {
1204 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1205 output_sep(opt, sign);
1207 if (opt->linenum) {
1208 char buf[32];
1209 xsnprintf(buf, sizeof(buf), "%d", lno);
1210 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1211 output_sep(opt, sign);
1214 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1215 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1216 * being called with a context line.
1218 if (opt->columnnum && cno) {
1219 char buf[32];
1220 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1221 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1222 output_sep(opt, sign);
1226 static void show_line(struct grep_opt *opt,
1227 const char *bol, const char *eol,
1228 const char *name, unsigned lno, ssize_t cno, char sign)
1230 int rest = eol - bol;
1231 const char *match_color = NULL;
1232 const char *line_color = NULL;
1234 if (opt->file_break && opt->last_shown == 0) {
1235 if (opt->show_hunk_mark)
1236 opt->output(opt, "\n", 1);
1237 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1238 if (opt->last_shown == 0) {
1239 if (opt->show_hunk_mark) {
1240 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1241 opt->output(opt, "\n", 1);
1243 } else if (lno > opt->last_shown + 1) {
1244 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1245 opt->output(opt, "\n", 1);
1248 if (!opt->only_matching) {
1250 * In case the line we're being called with contains more than
1251 * one match, leave printing each header to the loop below.
1253 show_line_header(opt, name, lno, cno, sign);
1255 if (opt->color || opt->only_matching) {
1256 regmatch_t match;
1257 enum grep_context ctx = GREP_CONTEXT_BODY;
1258 int eflags = 0;
1260 if (opt->color) {
1261 if (sign == ':')
1262 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1263 else
1264 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1265 if (sign == ':')
1266 line_color = opt->colors[GREP_COLOR_SELECTED];
1267 else if (sign == '-')
1268 line_color = opt->colors[GREP_COLOR_CONTEXT];
1269 else if (sign == '=')
1270 line_color = opt->colors[GREP_COLOR_FUNCTION];
1272 while (grep_next_match(opt, bol, eol, ctx, &match,
1273 GREP_HEADER_FIELD_MAX, eflags)) {
1274 if (match.rm_so == match.rm_eo)
1275 break;
1277 if (opt->only_matching)
1278 show_line_header(opt, name, lno, cno, sign);
1279 else
1280 output_color(opt, bol, match.rm_so, line_color);
1281 output_color(opt, bol + match.rm_so,
1282 match.rm_eo - match.rm_so, match_color);
1283 if (opt->only_matching)
1284 opt->output(opt, "\n", 1);
1285 bol += match.rm_eo;
1286 cno += match.rm_eo;
1287 rest -= match.rm_eo;
1288 eflags = REG_NOTBOL;
1291 if (!opt->only_matching) {
1292 output_color(opt, bol, rest, line_color);
1293 opt->output(opt, "\n", 1);
1297 int grep_use_locks;
1300 * This lock protects access to the gitattributes machinery, which is
1301 * not thread-safe.
1303 pthread_mutex_t grep_attr_mutex;
1305 static inline void grep_attr_lock(void)
1307 if (grep_use_locks)
1308 pthread_mutex_lock(&grep_attr_mutex);
1311 static inline void grep_attr_unlock(void)
1313 if (grep_use_locks)
1314 pthread_mutex_unlock(&grep_attr_mutex);
1317 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1318 const char *bol, const char *eol)
1320 xdemitconf_t *xecfg = opt->priv;
1321 if (xecfg && !xecfg->find_func) {
1322 grep_source_load_driver(gs, opt->repo->index);
1323 if (gs->driver->funcname.pattern) {
1324 const struct userdiff_funcname *pe = &gs->driver->funcname;
1325 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1326 } else {
1327 xecfg = opt->priv = NULL;
1331 if (xecfg) {
1332 char buf[1];
1333 return xecfg->find_func(bol, eol - bol, buf, 1,
1334 xecfg->find_func_priv) >= 0;
1337 if (bol == eol)
1338 return 0;
1339 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1340 return 1;
1341 return 0;
1344 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1345 const char *bol, unsigned lno)
1347 while (bol > gs->buf) {
1348 const char *eol = --bol;
1350 while (bol > gs->buf && bol[-1] != '\n')
1351 bol--;
1352 lno--;
1354 if (lno <= opt->last_shown)
1355 break;
1357 if (match_funcname(opt, gs, bol, eol)) {
1358 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1359 break;
1364 static int is_empty_line(const char *bol, const char *eol);
1366 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1367 const char *bol, const char *end, unsigned lno)
1369 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1370 int funcname_needed = !!opt->funcname, comment_needed = 0;
1372 if (opt->pre_context < lno)
1373 from = lno - opt->pre_context;
1374 if (from <= opt->last_shown)
1375 from = opt->last_shown + 1;
1376 orig_from = from;
1377 if (opt->funcbody) {
1378 if (match_funcname(opt, gs, bol, end))
1379 comment_needed = 1;
1380 else
1381 funcname_needed = 1;
1382 from = opt->last_shown + 1;
1385 /* Rewind. */
1386 while (bol > gs->buf && cur > from) {
1387 const char *next_bol = bol;
1388 const char *eol = --bol;
1390 while (bol > gs->buf && bol[-1] != '\n')
1391 bol--;
1392 cur--;
1393 if (comment_needed && (is_empty_line(bol, eol) ||
1394 match_funcname(opt, gs, bol, eol))) {
1395 comment_needed = 0;
1396 from = orig_from;
1397 if (cur < from) {
1398 cur++;
1399 bol = next_bol;
1400 break;
1403 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1404 funcname_lno = cur;
1405 funcname_needed = 0;
1406 if (opt->funcbody)
1407 comment_needed = 1;
1408 else
1409 from = orig_from;
1413 /* We need to look even further back to find a function signature. */
1414 if (opt->funcname && funcname_needed)
1415 show_funcname_line(opt, gs, bol, cur);
1417 /* Back forward. */
1418 while (cur < lno) {
1419 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1421 while (*eol != '\n')
1422 eol++;
1423 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1424 bol = eol + 1;
1425 cur++;
1429 static int should_lookahead(struct grep_opt *opt)
1431 struct grep_pat *p;
1433 if (opt->pattern_expression)
1434 return 0; /* punt for too complex stuff */
1435 if (opt->invert)
1436 return 0;
1437 for (p = opt->pattern_list; p; p = p->next) {
1438 if (p->token != GREP_PATTERN)
1439 return 0; /* punt for "header only" and stuff */
1441 return 1;
1444 static int look_ahead(struct grep_opt *opt,
1445 unsigned long *left_p,
1446 unsigned *lno_p,
1447 const char **bol_p)
1449 unsigned lno = *lno_p;
1450 const char *bol = *bol_p;
1451 struct grep_pat *p;
1452 const char *sp, *last_bol;
1453 regoff_t earliest = -1;
1455 for (p = opt->pattern_list; p; p = p->next) {
1456 int hit;
1457 regmatch_t m;
1459 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1460 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1461 continue;
1462 if (earliest < 0 || m.rm_so < earliest)
1463 earliest = m.rm_so;
1466 if (earliest < 0) {
1467 *bol_p = bol + *left_p;
1468 *left_p = 0;
1469 return 1;
1471 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1472 ; /* find the beginning of the line */
1473 last_bol = sp;
1475 for (sp = bol; sp < last_bol; sp++) {
1476 if (*sp == '\n')
1477 lno++;
1479 *left_p -= last_bol - bol;
1480 *bol_p = last_bol;
1481 *lno_p = lno;
1482 return 0;
1485 static int fill_textconv_grep(struct repository *r,
1486 struct userdiff_driver *driver,
1487 struct grep_source *gs)
1489 struct diff_filespec *df;
1490 char *buf;
1491 size_t size;
1493 if (!driver || !driver->textconv)
1494 return grep_source_load(gs);
1497 * The textconv interface is intimately tied to diff_filespecs, so we
1498 * have to pretend to be one. If we could unify the grep_source
1499 * and diff_filespec structs, this mess could just go away.
1501 df = alloc_filespec(gs->path);
1502 switch (gs->type) {
1503 case GREP_SOURCE_OID:
1504 fill_filespec(df, gs->identifier, 1, 0100644);
1505 break;
1506 case GREP_SOURCE_FILE:
1507 fill_filespec(df, null_oid(), 0, 0100644);
1508 break;
1509 default:
1510 BUG("attempt to textconv something without a path?");
1514 * fill_textconv is not remotely thread-safe; it modifies the global
1515 * diff tempfile structure, writes to the_repo's odb and might
1516 * internally call thread-unsafe functions such as the
1517 * prepare_packed_git() lazy-initializator. Because of the last two, we
1518 * must ensure mutual exclusion between this call and the object reading
1519 * API, thus we use obj_read_lock() here.
1521 * TODO: allowing text conversion to run in parallel with object
1522 * reading operations might increase performance in the multithreaded
1523 * non-worktreee git-grep with --textconv.
1525 obj_read_lock();
1526 size = fill_textconv(r, driver, df, &buf);
1527 obj_read_unlock();
1528 free_filespec(df);
1531 * The normal fill_textconv usage by the diff machinery would just keep
1532 * the textconv'd buf separate from the diff_filespec. But much of the
1533 * grep code passes around a grep_source and assumes that its "buf"
1534 * pointer is the beginning of the thing we are searching. So let's
1535 * install our textconv'd version into the grep_source, taking care not
1536 * to leak any existing buffer.
1538 grep_source_clear_data(gs);
1539 gs->buf = buf;
1540 gs->size = size;
1542 return 0;
1545 static int is_empty_line(const char *bol, const char *eol)
1547 while (bol < eol && isspace(*bol))
1548 bol++;
1549 return bol == eol;
1552 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1554 const char *bol;
1555 const char *peek_bol = NULL;
1556 unsigned long left;
1557 unsigned lno = 1;
1558 unsigned last_hit = 0;
1559 int binary_match_only = 0;
1560 unsigned count = 0;
1561 int try_lookahead = 0;
1562 int show_function = 0;
1563 struct userdiff_driver *textconv = NULL;
1564 enum grep_context ctx = GREP_CONTEXT_HEAD;
1565 xdemitconf_t xecfg;
1567 if (!opt->status_only && gs->name == NULL)
1568 BUG("grep call which could print a name requires "
1569 "grep_source.name be non-NULL");
1571 if (!opt->output)
1572 opt->output = std_output;
1574 if (opt->pre_context || opt->post_context || opt->file_break ||
1575 opt->funcbody) {
1576 /* Show hunk marks, except for the first file. */
1577 if (opt->last_shown)
1578 opt->show_hunk_mark = 1;
1580 * If we're using threads then we can't easily identify
1581 * the first file. Always put hunk marks in that case
1582 * and skip the very first one later in work_done().
1584 if (opt->output != std_output)
1585 opt->show_hunk_mark = 1;
1587 opt->last_shown = 0;
1589 if (opt->allow_textconv) {
1590 grep_source_load_driver(gs, opt->repo->index);
1592 * We might set up the shared textconv cache data here, which
1593 * is not thread-safe. Also, get_oid_with_context() and
1594 * parse_object() might be internally called. As they are not
1595 * currently thread-safe and might be racy with object reading,
1596 * obj_read_lock() must be called.
1598 grep_attr_lock();
1599 obj_read_lock();
1600 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1601 obj_read_unlock();
1602 grep_attr_unlock();
1606 * We know the result of a textconv is text, so we only have to care
1607 * about binary handling if we are not using it.
1609 if (!textconv) {
1610 switch (opt->binary) {
1611 case GREP_BINARY_DEFAULT:
1612 if (grep_source_is_binary(gs, opt->repo->index))
1613 binary_match_only = 1;
1614 break;
1615 case GREP_BINARY_NOMATCH:
1616 if (grep_source_is_binary(gs, opt->repo->index))
1617 return 0; /* Assume unmatch */
1618 break;
1619 case GREP_BINARY_TEXT:
1620 break;
1621 default:
1622 BUG("unknown binary handling mode");
1626 memset(&xecfg, 0, sizeof(xecfg));
1627 opt->priv = &xecfg;
1629 try_lookahead = should_lookahead(opt);
1631 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1632 return 0;
1634 bol = gs->buf;
1635 left = gs->size;
1636 while (left) {
1637 const char *eol;
1638 int hit;
1639 ssize_t cno;
1640 ssize_t col = -1, icol = -1;
1643 * look_ahead() skips quickly to the line that possibly
1644 * has the next hit; don't call it if we need to do
1645 * something more than just skipping the current line
1646 * in response to an unmatch for the current line. E.g.
1647 * inside a post-context window, we will show the current
1648 * line as a context around the previous hit when it
1649 * doesn't hit.
1651 if (try_lookahead
1652 && !(last_hit
1653 && (show_function ||
1654 lno <= last_hit + opt->post_context))
1655 && look_ahead(opt, &left, &lno, &bol))
1656 break;
1657 eol = end_of_line(bol, &left);
1659 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1660 ctx = GREP_CONTEXT_BODY;
1662 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1664 if (collect_hits)
1665 goto next_line;
1667 /* "grep -v -e foo -e bla" should list lines
1668 * that do not have either, so inversion should
1669 * be done outside.
1671 if (opt->invert)
1672 hit = !hit;
1673 if (opt->unmatch_name_only) {
1674 if (hit)
1675 return 0;
1676 goto next_line;
1678 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1679 count++;
1680 if (opt->status_only)
1681 return 1;
1682 if (opt->name_only) {
1683 show_name(opt, gs->name);
1684 return 1;
1686 if (opt->count)
1687 goto next_line;
1688 if (binary_match_only) {
1689 opt->output(opt, "Binary file ", 12);
1690 output_color(opt, gs->name, strlen(gs->name),
1691 opt->colors[GREP_COLOR_FILENAME]);
1692 opt->output(opt, " matches\n", 9);
1693 return 1;
1695 /* Hit at this line. If we haven't shown the
1696 * pre-context lines, we would need to show them.
1698 if (opt->pre_context || opt->funcbody)
1699 show_pre_context(opt, gs, bol, eol, lno);
1700 else if (opt->funcname)
1701 show_funcname_line(opt, gs, bol, lno);
1702 cno = opt->invert ? icol : col;
1703 if (cno < 0) {
1705 * A negative cno indicates that there was no
1706 * match on the line. We are thus inverted and
1707 * being asked to show all lines that _don't_
1708 * match a given expression. Therefore, set cno
1709 * to 0 to suggest the whole line matches.
1711 cno = 0;
1713 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1714 last_hit = lno;
1715 if (opt->funcbody)
1716 show_function = 1;
1717 goto next_line;
1719 if (show_function && (!peek_bol || peek_bol < bol)) {
1720 unsigned long peek_left = left;
1721 const char *peek_eol = eol;
1724 * Trailing empty lines are not interesting.
1725 * Peek past them to see if they belong to the
1726 * body of the current function.
1728 peek_bol = bol;
1729 while (is_empty_line(peek_bol, peek_eol)) {
1730 peek_bol = peek_eol + 1;
1731 peek_eol = end_of_line(peek_bol, &peek_left);
1734 if (match_funcname(opt, gs, peek_bol, peek_eol))
1735 show_function = 0;
1737 if (show_function ||
1738 (last_hit && lno <= last_hit + opt->post_context)) {
1739 /* If the last hit is within the post context,
1740 * we need to show this line.
1742 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1745 next_line:
1746 bol = eol + 1;
1747 if (!left)
1748 break;
1749 left--;
1750 lno++;
1753 if (collect_hits)
1754 return 0;
1756 if (opt->status_only)
1757 return opt->unmatch_name_only;
1758 if (opt->unmatch_name_only) {
1759 /* We did not see any hit, so we want to show this */
1760 show_name(opt, gs->name);
1761 return 1;
1764 xdiff_clear_find_func(&xecfg);
1765 opt->priv = NULL;
1767 /* NEEDSWORK:
1768 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1769 * which feels mostly useless but sometimes useful. Maybe
1770 * make it another option? For now suppress them.
1772 if (opt->count && count) {
1773 char buf[32];
1774 if (opt->pathname) {
1775 output_color(opt, gs->name, strlen(gs->name),
1776 opt->colors[GREP_COLOR_FILENAME]);
1777 output_sep(opt, ':');
1779 xsnprintf(buf, sizeof(buf), "%u\n", count);
1780 opt->output(opt, buf, strlen(buf));
1781 return 1;
1783 return !!last_hit;
1786 static void clr_hit_marker(struct grep_expr *x)
1788 /* All-hit markers are meaningful only at the very top level
1789 * OR node.
1791 while (1) {
1792 x->hit = 0;
1793 if (x->node != GREP_NODE_OR)
1794 return;
1795 x->u.binary.left->hit = 0;
1796 x = x->u.binary.right;
1800 static int chk_hit_marker(struct grep_expr *x)
1802 /* Top level nodes have hit markers. See if they all are hits */
1803 while (1) {
1804 if (x->node != GREP_NODE_OR)
1805 return x->hit;
1806 if (!x->u.binary.left->hit)
1807 return 0;
1808 x = x->u.binary.right;
1812 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1815 * we do not have to do the two-pass grep when we do not check
1816 * buffer-wide "all-match".
1818 if (!opt->all_match && !opt->no_body_match)
1819 return grep_source_1(opt, gs, 0);
1821 /* Otherwise the toplevel "or" terms hit a bit differently.
1822 * We first clear hit markers from them.
1824 clr_hit_marker(opt->pattern_expression);
1825 opt->body_hit = 0;
1826 grep_source_1(opt, gs, 1);
1828 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1829 return 0;
1830 if (opt->no_body_match && opt->body_hit)
1831 return 0;
1833 return grep_source_1(opt, gs, 0);
1836 static void grep_source_init_buf(struct grep_source *gs,
1837 const char *buf,
1838 unsigned long size)
1840 gs->type = GREP_SOURCE_BUF;
1841 gs->name = NULL;
1842 gs->path = NULL;
1843 gs->buf = buf;
1844 gs->size = size;
1845 gs->driver = NULL;
1846 gs->identifier = NULL;
1849 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1851 struct grep_source gs;
1852 int r;
1854 grep_source_init_buf(&gs, buf, size);
1856 r = grep_source(opt, &gs);
1858 grep_source_clear(&gs);
1859 return r;
1862 void grep_source_init_file(struct grep_source *gs, const char *name,
1863 const char *path)
1865 gs->type = GREP_SOURCE_FILE;
1866 gs->name = xstrdup_or_null(name);
1867 gs->path = xstrdup_or_null(path);
1868 gs->buf = NULL;
1869 gs->size = 0;
1870 gs->driver = NULL;
1871 gs->identifier = xstrdup(path);
1874 void grep_source_init_oid(struct grep_source *gs, const char *name,
1875 const char *path, const struct object_id *oid,
1876 struct repository *repo)
1878 gs->type = GREP_SOURCE_OID;
1879 gs->name = xstrdup_or_null(name);
1880 gs->path = xstrdup_or_null(path);
1881 gs->buf = NULL;
1882 gs->size = 0;
1883 gs->driver = NULL;
1884 gs->identifier = oiddup(oid);
1885 gs->repo = repo;
1888 void grep_source_clear(struct grep_source *gs)
1890 FREE_AND_NULL(gs->name);
1891 FREE_AND_NULL(gs->path);
1892 FREE_AND_NULL(gs->identifier);
1893 grep_source_clear_data(gs);
1896 void grep_source_clear_data(struct grep_source *gs)
1898 switch (gs->type) {
1899 case GREP_SOURCE_FILE:
1900 case GREP_SOURCE_OID:
1901 /* these types own the buffer */
1902 free((char *)gs->buf);
1903 gs->buf = NULL;
1904 gs->size = 0;
1905 break;
1906 case GREP_SOURCE_BUF:
1907 /* leave user-provided buf intact */
1908 break;
1912 static int grep_source_load_oid(struct grep_source *gs)
1914 enum object_type type;
1916 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1917 &gs->size);
1918 if (!gs->buf)
1919 return error(_("'%s': unable to read %s"),
1920 gs->name,
1921 oid_to_hex(gs->identifier));
1922 return 0;
1925 static int grep_source_load_file(struct grep_source *gs)
1927 const char *filename = gs->identifier;
1928 struct stat st;
1929 char *data;
1930 size_t size;
1931 int i;
1933 if (lstat(filename, &st) < 0) {
1934 err_ret:
1935 if (errno != ENOENT)
1936 error_errno(_("failed to stat '%s'"), filename);
1937 return -1;
1939 if (!S_ISREG(st.st_mode))
1940 return -1;
1941 size = xsize_t(st.st_size);
1942 i = open(filename, O_RDONLY);
1943 if (i < 0)
1944 goto err_ret;
1945 data = xmallocz(size);
1946 if (st.st_size != read_in_full(i, data, size)) {
1947 error_errno(_("'%s': short read"), filename);
1948 close(i);
1949 free(data);
1950 return -1;
1952 close(i);
1954 gs->buf = data;
1955 gs->size = size;
1956 return 0;
1959 static int grep_source_load(struct grep_source *gs)
1961 if (gs->buf)
1962 return 0;
1964 switch (gs->type) {
1965 case GREP_SOURCE_FILE:
1966 return grep_source_load_file(gs);
1967 case GREP_SOURCE_OID:
1968 return grep_source_load_oid(gs);
1969 case GREP_SOURCE_BUF:
1970 return gs->buf ? 0 : -1;
1972 BUG("invalid grep_source type to load");
1975 void grep_source_load_driver(struct grep_source *gs,
1976 struct index_state *istate)
1978 if (gs->driver)
1979 return;
1981 grep_attr_lock();
1982 if (gs->path)
1983 gs->driver = userdiff_find_by_path(istate, gs->path);
1984 if (!gs->driver)
1985 gs->driver = userdiff_find_by_name("default");
1986 grep_attr_unlock();
1989 static int grep_source_is_binary(struct grep_source *gs,
1990 struct index_state *istate)
1992 grep_source_load_driver(gs, istate);
1993 if (gs->driver->binary != -1)
1994 return gs->driver->binary;
1996 if (!grep_source_load(gs))
1997 return buffer_is_binary(gs->buf, gs->size);
1999 return 0;