commit.h: reduce unnecessary includes
[alt-git.git] / grep.c
blobe620e375b1dc8a2d73089e30bb043d28d7c7ee19
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.h"
7 #include "pretty.h"
8 #include "userdiff.h"
9 #include "xdiff-interface.h"
10 #include "diff.h"
11 #include "diffcore.h"
12 #include "commit.h"
13 #include "quote.h"
14 #include "help.h"
15 #include "wrapper.h"
17 static int grep_source_load(struct grep_source *gs);
18 static int grep_source_is_binary(struct grep_source *gs,
19 struct index_state *istate);
21 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
23 fwrite(buf, size, 1, stdout);
26 static const char *color_grep_slots[] = {
27 [GREP_COLOR_CONTEXT] = "context",
28 [GREP_COLOR_FILENAME] = "filename",
29 [GREP_COLOR_FUNCTION] = "function",
30 [GREP_COLOR_LINENO] = "lineNumber",
31 [GREP_COLOR_COLUMNNO] = "column",
32 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
33 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
34 [GREP_COLOR_SELECTED] = "selected",
35 [GREP_COLOR_SEP] = "separator",
38 static int parse_pattern_type_arg(const char *opt, const char *arg)
40 if (!strcmp(arg, "default"))
41 return GREP_PATTERN_TYPE_UNSPECIFIED;
42 else if (!strcmp(arg, "basic"))
43 return GREP_PATTERN_TYPE_BRE;
44 else if (!strcmp(arg, "extended"))
45 return GREP_PATTERN_TYPE_ERE;
46 else if (!strcmp(arg, "fixed"))
47 return GREP_PATTERN_TYPE_FIXED;
48 else if (!strcmp(arg, "perl"))
49 return GREP_PATTERN_TYPE_PCRE;
50 die("bad %s argument: %s", opt, arg);
53 define_list_config_array_extra(color_grep_slots, {"match"});
56 * Read the configuration file once and store it in
57 * the grep_defaults template.
59 int grep_config(const char *var, const char *value, void *cb)
61 struct grep_opt *opt = cb;
62 const char *slot;
64 if (userdiff_config(var, value) < 0)
65 return -1;
67 if (!strcmp(var, "grep.extendedregexp")) {
68 opt->extended_regexp_option = git_config_bool(var, value);
69 return 0;
72 if (!strcmp(var, "grep.patterntype")) {
73 opt->pattern_type_option = parse_pattern_type_arg(var, value);
74 return 0;
77 if (!strcmp(var, "grep.linenumber")) {
78 opt->linenum = git_config_bool(var, value);
79 return 0;
81 if (!strcmp(var, "grep.column")) {
82 opt->columnnum = git_config_bool(var, value);
83 return 0;
86 if (!strcmp(var, "grep.fullname")) {
87 opt->relative = !git_config_bool(var, value);
88 return 0;
91 if (!strcmp(var, "color.grep"))
92 opt->color = git_config_colorbool(var, value);
93 if (!strcmp(var, "color.grep.match")) {
94 if (grep_config("color.grep.matchcontext", value, cb) < 0)
95 return -1;
96 if (grep_config("color.grep.matchselected", value, cb) < 0)
97 return -1;
98 } else if (skip_prefix(var, "color.grep.", &slot)) {
99 int i = LOOKUP_CONFIG(color_grep_slots, slot);
100 char *color;
102 if (i < 0)
103 return -1;
104 color = opt->colors[i];
105 if (!value)
106 return config_error_nonbool(var);
107 return color_parse(value, color);
109 return 0;
112 void grep_init(struct grep_opt *opt, struct repository *repo)
114 struct grep_opt blank = GREP_OPT_INIT;
115 memcpy(opt, &blank, sizeof(*opt));
117 opt->repo = repo;
118 opt->pattern_tail = &opt->pattern_list;
119 opt->header_tail = &opt->header_list;
122 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
123 const char *origin, int no,
124 enum grep_pat_token t,
125 enum grep_header_field field)
127 struct grep_pat *p = xcalloc(1, sizeof(*p));
128 p->pattern = xmemdupz(pat, patlen);
129 p->patternlen = patlen;
130 p->origin = origin;
131 p->no = no;
132 p->token = t;
133 p->field = field;
134 return p;
137 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
139 **tail = p;
140 *tail = &p->next;
141 p->next = NULL;
143 switch (p->token) {
144 case GREP_PATTERN: /* atom */
145 case GREP_PATTERN_HEAD:
146 case GREP_PATTERN_BODY:
147 for (;;) {
148 struct grep_pat *new_pat;
149 size_t len = 0;
150 char *cp = p->pattern + p->patternlen, *nl = NULL;
151 while (++len <= p->patternlen) {
152 if (*(--cp) == '\n') {
153 nl = cp;
154 break;
157 if (!nl)
158 break;
159 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
160 p->no, p->token, p->field);
161 new_pat->next = p->next;
162 if (!p->next)
163 *tail = &new_pat->next;
164 p->next = new_pat;
165 *nl = '\0';
166 p->patternlen -= len;
168 break;
169 default:
170 break;
174 void append_header_grep_pattern(struct grep_opt *opt,
175 enum grep_header_field field, const char *pat)
177 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
178 GREP_PATTERN_HEAD, field);
179 if (field == GREP_HEADER_REFLOG)
180 opt->use_reflog_filter = 1;
181 do_append_grep_pat(&opt->header_tail, p);
184 void append_grep_pattern(struct grep_opt *opt, const char *pat,
185 const char *origin, int no, enum grep_pat_token t)
187 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
190 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
191 const char *origin, int no, enum grep_pat_token t)
193 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
194 do_append_grep_pat(&opt->pattern_tail, p);
197 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
199 struct grep_pat *pat;
200 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
201 *ret = *opt;
203 ret->pattern_list = NULL;
204 ret->pattern_tail = &ret->pattern_list;
206 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
208 if(pat->token == GREP_PATTERN_HEAD)
209 append_header_grep_pattern(ret, pat->field,
210 pat->pattern);
211 else
212 append_grep_pat(ret, pat->pattern, pat->patternlen,
213 pat->origin, pat->no, pat->token);
216 return ret;
219 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
220 const char *error)
222 char where[1024];
224 if (p->no)
225 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
226 else if (p->origin)
227 xsnprintf(where, sizeof(where), "%s, ", p->origin);
228 else
229 where[0] = 0;
231 die("%s'%s': %s", where, p->pattern, error);
234 static int is_fixed(const char *s, size_t len)
236 size_t i;
238 for (i = 0; i < len; i++) {
239 if (is_regex_special(s[i]))
240 return 0;
243 return 1;
246 #ifdef USE_LIBPCRE2
247 #define GREP_PCRE2_DEBUG_MALLOC 0
249 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
251 void *pointer = malloc(size);
252 #if GREP_PCRE2_DEBUG_MALLOC
253 static int count = 1;
254 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
255 #endif
256 return pointer;
259 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
261 #if GREP_PCRE2_DEBUG_MALLOC
262 static int count = 1;
263 if (pointer)
264 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
265 #endif
266 free(pointer);
269 static int pcre2_jit_functional(void)
271 static int jit_working = -1;
272 pcre2_code *code;
273 size_t off;
274 int err;
276 if (jit_working != -1)
277 return jit_working;
280 * Try to JIT compile a simple pattern to probe if the JIT is
281 * working in general. It might fail for systems where creating
282 * memory mappings for runtime code generation is restricted.
284 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
285 if (!code)
286 return 0;
288 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
289 pcre2_code_free(code);
291 return jit_working;
294 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
296 int error;
297 PCRE2_UCHAR errbuf[256];
298 PCRE2_SIZE erroffset;
299 int options = PCRE2_MULTILINE;
300 int jitret;
301 int patinforet;
302 size_t jitsizearg;
303 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
306 * Call pcre2_general_context_create() before calling any
307 * other pcre2_*(). It sets up our malloc()/free() functions
308 * with which everything else is allocated.
310 p->pcre2_general_context = pcre2_general_context_create(
311 pcre2_malloc, pcre2_free, NULL);
312 if (!p->pcre2_general_context)
313 die("Couldn't allocate PCRE2 general context");
315 if (opt->ignore_case) {
316 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
317 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
318 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
319 pcre2_set_character_tables(p->pcre2_compile_context,
320 p->pcre2_tables);
322 options |= PCRE2_CASELESS;
324 if (!opt->ignore_locale && is_utf8_locale() && !literal)
325 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
327 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
328 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
329 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
330 options |= PCRE2_NO_START_OPTIMIZE;
331 #endif
333 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
334 p->patternlen, options, &error, &erroffset,
335 p->pcre2_compile_context);
337 if (p->pcre2_pattern) {
338 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
339 if (!p->pcre2_match_data)
340 die("Couldn't allocate PCRE2 match data");
341 } else {
342 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
343 compile_regexp_failed(p, (const char *)&errbuf);
346 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
347 if (p->pcre2_jit_on) {
348 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
349 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
351 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
352 * indicated JIT support, the library might still
353 * fail to generate JIT code for various reasons,
354 * e.g. when SELinux's 'deny_execmem' or PaX's
355 * MPROTECT prevent creating W|X memory mappings.
357 * Instead of faling hard, fall back to interpreter
358 * mode, just as if the pattern was prefixed with
359 * '(*NO_JIT)'.
361 p->pcre2_jit_on = 0;
362 return;
363 } else if (jitret) {
364 int need_clip = p->patternlen > 64;
365 int clip_len = need_clip ? 64 : p->patternlen;
366 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
367 clip_len, p->pattern, need_clip ? "..." : "", jitret,
368 pcre2_jit_functional()
369 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
370 : "");
374 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
375 * tells us whether the library itself supports JIT,
376 * but to see whether we're going to be actually using
377 * JIT we need to extract PCRE2_INFO_JITSIZE from the
378 * pattern *after* we do pcre2_jit_compile() above.
380 * This is because if the pattern contains the
381 * (*NO_JIT) verb (see pcre2syntax(3))
382 * pcre2_jit_compile() will exit early with 0. If we
383 * then proceed to call pcre2_jit_match() further down
384 * the line instead of pcre2_match() we'll either
385 * segfault (pre PCRE 10.31) or run into a fatal error
386 * (post PCRE2 10.31)
388 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
389 if (patinforet)
390 BUG("pcre2_pattern_info() failed: %d", patinforet);
391 if (jitsizearg == 0) {
392 p->pcre2_jit_on = 0;
393 return;
398 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
399 regmatch_t *match, int eflags)
401 int ret, flags = 0;
402 PCRE2_SIZE *ovector;
403 PCRE2_UCHAR errbuf[256];
405 if (eflags & REG_NOTBOL)
406 flags |= PCRE2_NOTBOL;
408 if (p->pcre2_jit_on)
409 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
410 eol - line, 0, flags, p->pcre2_match_data,
411 NULL);
412 else
413 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
414 eol - line, 0, flags, p->pcre2_match_data,
415 NULL);
417 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
418 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
419 die("%s failed with error code %d: %s",
420 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
421 errbuf);
423 if (ret > 0) {
424 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
425 ret = 0;
426 match->rm_so = (int)ovector[0];
427 match->rm_eo = (int)ovector[1];
430 return ret;
433 static void free_pcre2_pattern(struct grep_pat *p)
435 pcre2_compile_context_free(p->pcre2_compile_context);
436 pcre2_code_free(p->pcre2_pattern);
437 pcre2_match_data_free(p->pcre2_match_data);
438 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
439 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
440 #else
441 free((void *)p->pcre2_tables);
442 #endif
443 pcre2_general_context_free(p->pcre2_general_context);
445 #else /* !USE_LIBPCRE2 */
446 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
448 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
451 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
452 regmatch_t *match, int eflags)
454 return 1;
457 static void free_pcre2_pattern(struct grep_pat *p)
461 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
463 struct strbuf sb = STRBUF_INIT;
464 int err;
465 int regflags = 0;
467 basic_regex_quote_buf(&sb, p->pattern);
468 if (opt->ignore_case)
469 regflags |= REG_ICASE;
470 err = regcomp(&p->regexp, sb.buf, regflags);
471 strbuf_release(&sb);
472 if (err) {
473 char errbuf[1024];
474 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
475 compile_regexp_failed(p, errbuf);
478 #endif /* !USE_LIBPCRE2 */
480 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
482 int err;
483 int regflags = REG_NEWLINE;
485 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
486 opt->pattern_type_option = (opt->extended_regexp_option
487 ? GREP_PATTERN_TYPE_ERE
488 : GREP_PATTERN_TYPE_BRE);
490 p->word_regexp = opt->word_regexp;
491 p->ignore_case = opt->ignore_case;
492 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
494 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
495 memchr(p->pattern, 0, p->patternlen))
496 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
498 p->is_fixed = is_fixed(p->pattern, p->patternlen);
499 #ifdef USE_LIBPCRE2
500 if (!p->fixed && !p->is_fixed) {
501 const char *no_jit = "(*NO_JIT)";
502 const int no_jit_len = strlen(no_jit);
503 if (starts_with(p->pattern, no_jit) &&
504 is_fixed(p->pattern + no_jit_len,
505 p->patternlen - no_jit_len))
506 p->is_fixed = 1;
508 #endif
509 if (p->fixed || p->is_fixed) {
510 #ifdef USE_LIBPCRE2
511 if (p->is_fixed) {
512 compile_pcre2_pattern(p, opt);
513 } else {
515 * E.g. t7811-grep-open.sh relies on the
516 * pattern being restored.
518 char *old_pattern = p->pattern;
519 size_t old_patternlen = p->patternlen;
520 struct strbuf sb = STRBUF_INIT;
523 * There is the PCRE2_LITERAL flag, but it's
524 * only in PCRE v2 10.30 and later. Needing to
525 * ifdef our way around that and dealing with
526 * it + PCRE2_MULTILINE being an error is more
527 * complex than just quoting this ourselves.
529 strbuf_add(&sb, "\\Q", 2);
530 strbuf_add(&sb, p->pattern, p->patternlen);
531 strbuf_add(&sb, "\\E", 2);
533 p->pattern = sb.buf;
534 p->patternlen = sb.len;
535 compile_pcre2_pattern(p, opt);
536 p->pattern = old_pattern;
537 p->patternlen = old_patternlen;
538 strbuf_release(&sb);
540 #else /* !USE_LIBPCRE2 */
541 compile_fixed_regexp(p, opt);
542 #endif /* !USE_LIBPCRE2 */
543 return;
546 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
547 compile_pcre2_pattern(p, opt);
548 return;
551 if (p->ignore_case)
552 regflags |= REG_ICASE;
553 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
554 regflags |= REG_EXTENDED;
555 err = regcomp(&p->regexp, p->pattern, regflags);
556 if (err) {
557 char errbuf[1024];
558 regerror(err, &p->regexp, errbuf, 1024);
559 compile_regexp_failed(p, errbuf);
563 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
565 struct grep_expr *z = xcalloc(1, sizeof(*z));
566 z->node = GREP_NODE_NOT;
567 z->u.unary = expr;
568 return z;
571 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
572 struct grep_expr *left,
573 struct grep_expr *right)
575 struct grep_expr *z = xcalloc(1, sizeof(*z));
576 z->node = kind;
577 z->u.binary.left = left;
578 z->u.binary.right = right;
579 return z;
582 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
584 return grep_binexp(GREP_NODE_OR, left, right);
587 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
589 return grep_binexp(GREP_NODE_AND, left, right);
592 static struct grep_expr *compile_pattern_or(struct grep_pat **);
593 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
595 struct grep_pat *p;
596 struct grep_expr *x;
598 p = *list;
599 if (!p)
600 return NULL;
601 switch (p->token) {
602 case GREP_PATTERN: /* atom */
603 case GREP_PATTERN_HEAD:
604 case GREP_PATTERN_BODY:
605 CALLOC_ARRAY(x, 1);
606 x->node = GREP_NODE_ATOM;
607 x->u.atom = p;
608 *list = p->next;
609 return x;
610 case GREP_OPEN_PAREN:
611 *list = p->next;
612 x = compile_pattern_or(list);
613 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
614 die("unmatched parenthesis");
615 *list = (*list)->next;
616 return x;
617 default:
618 return NULL;
622 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
624 struct grep_pat *p;
625 struct grep_expr *x;
627 p = *list;
628 if (!p)
629 return NULL;
630 switch (p->token) {
631 case GREP_NOT:
632 if (!p->next)
633 die("--not not followed by pattern expression");
634 *list = p->next;
635 x = compile_pattern_not(list);
636 if (!x)
637 die("--not followed by non pattern expression");
638 return grep_not_expr(x);
639 default:
640 return compile_pattern_atom(list);
644 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
646 struct grep_pat *p;
647 struct grep_expr *x, *y;
649 x = compile_pattern_not(list);
650 p = *list;
651 if (p && p->token == GREP_AND) {
652 if (!x)
653 die("--and not preceded by pattern expression");
654 if (!p->next)
655 die("--and not followed by pattern expression");
656 *list = p->next;
657 y = compile_pattern_and(list);
658 if (!y)
659 die("--and not followed by pattern expression");
660 return grep_and_expr(x, y);
662 return x;
665 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
667 struct grep_pat *p;
668 struct grep_expr *x, *y;
670 x = compile_pattern_and(list);
671 p = *list;
672 if (x && p && p->token != GREP_CLOSE_PAREN) {
673 y = compile_pattern_or(list);
674 if (!y)
675 die("not a pattern expression %s", p->pattern);
676 return grep_or_expr(x, y);
678 return x;
681 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
683 return compile_pattern_or(list);
686 static struct grep_expr *grep_true_expr(void)
688 struct grep_expr *z = xcalloc(1, sizeof(*z));
689 z->node = GREP_NODE_TRUE;
690 return z;
693 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
695 struct grep_pat *p;
696 struct grep_expr *header_expr;
697 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
698 enum grep_header_field fld;
700 if (!opt->header_list)
701 return NULL;
703 for (p = opt->header_list; p; p = p->next) {
704 if (p->token != GREP_PATTERN_HEAD)
705 BUG("a non-header pattern in grep header list.");
706 if (p->field < GREP_HEADER_FIELD_MIN ||
707 GREP_HEADER_FIELD_MAX <= p->field)
708 BUG("unknown header field %d", p->field);
709 compile_regexp(p, opt);
712 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
713 header_group[fld] = NULL;
715 for (p = opt->header_list; p; p = p->next) {
716 struct grep_expr *h;
717 struct grep_pat *pp = p;
719 h = compile_pattern_atom(&pp);
720 if (!h || pp != p->next)
721 BUG("malformed header expr");
722 if (!header_group[p->field]) {
723 header_group[p->field] = h;
724 continue;
726 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
729 header_expr = NULL;
731 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
732 if (!header_group[fld])
733 continue;
734 if (!header_expr)
735 header_expr = grep_true_expr();
736 header_expr = grep_or_expr(header_group[fld], header_expr);
738 return header_expr;
741 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
743 struct grep_expr *z = x;
745 while (x) {
746 assert(x->node == GREP_NODE_OR);
747 if (x->u.binary.right &&
748 x->u.binary.right->node == GREP_NODE_TRUE) {
749 x->u.binary.right = y;
750 break;
752 x = x->u.binary.right;
754 return z;
757 void compile_grep_patterns(struct grep_opt *opt)
759 struct grep_pat *p;
760 struct grep_expr *header_expr = prep_header_patterns(opt);
761 int extended = 0;
763 for (p = opt->pattern_list; p; p = p->next) {
764 switch (p->token) {
765 case GREP_PATTERN: /* atom */
766 case GREP_PATTERN_HEAD:
767 case GREP_PATTERN_BODY:
768 compile_regexp(p, opt);
769 break;
770 default:
771 extended = 1;
772 break;
776 if (opt->all_match || opt->no_body_match || header_expr)
777 extended = 1;
778 else if (!extended)
779 return;
781 p = opt->pattern_list;
782 if (p)
783 opt->pattern_expression = compile_pattern_expr(&p);
784 if (p)
785 die("incomplete pattern expression: %s", p->pattern);
787 if (opt->no_body_match && opt->pattern_expression)
788 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
790 if (!header_expr)
791 return;
793 if (!opt->pattern_expression)
794 opt->pattern_expression = header_expr;
795 else if (opt->all_match)
796 opt->pattern_expression = grep_splice_or(header_expr,
797 opt->pattern_expression);
798 else
799 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
800 header_expr);
801 opt->all_match = 1;
804 static void free_pattern_expr(struct grep_expr *x)
806 switch (x->node) {
807 case GREP_NODE_TRUE:
808 case GREP_NODE_ATOM:
809 break;
810 case GREP_NODE_NOT:
811 free_pattern_expr(x->u.unary);
812 break;
813 case GREP_NODE_AND:
814 case GREP_NODE_OR:
815 free_pattern_expr(x->u.binary.left);
816 free_pattern_expr(x->u.binary.right);
817 break;
819 free(x);
822 static void free_grep_pat(struct grep_pat *pattern)
824 struct grep_pat *p, *n;
826 for (p = pattern; p; p = n) {
827 n = p->next;
828 switch (p->token) {
829 case GREP_PATTERN: /* atom */
830 case GREP_PATTERN_HEAD:
831 case GREP_PATTERN_BODY:
832 if (p->pcre2_pattern)
833 free_pcre2_pattern(p);
834 else
835 regfree(&p->regexp);
836 free(p->pattern);
837 break;
838 default:
839 break;
841 free(p);
845 void free_grep_patterns(struct grep_opt *opt)
847 free_grep_pat(opt->pattern_list);
848 free_grep_pat(opt->header_list);
850 if (opt->pattern_expression)
851 free_pattern_expr(opt->pattern_expression);
854 static const char *end_of_line(const char *cp, unsigned long *left)
856 unsigned long l = *left;
857 while (l && *cp != '\n') {
858 l--;
859 cp++;
861 *left = l;
862 return cp;
865 static int word_char(char ch)
867 return isalnum(ch) || ch == '_';
870 static void output_color(struct grep_opt *opt, const void *data, size_t size,
871 const char *color)
873 if (want_color(opt->color) && color && color[0]) {
874 opt->output(opt, color, strlen(color));
875 opt->output(opt, data, size);
876 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
877 } else
878 opt->output(opt, data, size);
881 static void output_sep(struct grep_opt *opt, char sign)
883 if (opt->null_following_name)
884 opt->output(opt, "\0", 1);
885 else
886 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
889 static void show_name(struct grep_opt *opt, const char *name)
891 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
892 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
895 static int patmatch(struct grep_pat *p,
896 const char *line, const char *eol,
897 regmatch_t *match, int eflags)
899 int hit;
901 if (p->pcre2_pattern)
902 hit = !pcre2match(p, line, eol, match, eflags);
903 else
904 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
905 eflags);
907 return hit;
910 static void strip_timestamp(const char *bol, const char **eol_p)
912 const char *eol = *eol_p;
914 while (bol < --eol) {
915 if (*eol != '>')
916 continue;
917 *eol_p = ++eol;
918 break;
922 static struct {
923 const char *field;
924 size_t len;
925 } header_field[] = {
926 { "author ", 7 },
927 { "committer ", 10 },
928 { "reflog ", 7 },
931 static int headerless_match_one_pattern(struct grep_pat *p,
932 const char *bol, const char *eol,
933 enum grep_context ctx,
934 regmatch_t *pmatch, int eflags)
936 int hit = 0;
937 const char *start = bol;
939 if ((p->token != GREP_PATTERN) &&
940 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
941 return 0;
943 again:
944 hit = patmatch(p, bol, eol, pmatch, eflags);
946 if (hit && p->word_regexp) {
947 if ((pmatch[0].rm_so < 0) ||
948 (eol - bol) < pmatch[0].rm_so ||
949 (pmatch[0].rm_eo < 0) ||
950 (eol - bol) < pmatch[0].rm_eo)
951 die("regexp returned nonsense");
953 /* Match beginning must be either beginning of the
954 * line, or at word boundary (i.e. the last char must
955 * not be a word char). Similarly, match end must be
956 * either end of the line, or at word boundary
957 * (i.e. the next char must not be a word char).
959 if ( ((pmatch[0].rm_so == 0) ||
960 !word_char(bol[pmatch[0].rm_so-1])) &&
961 ((pmatch[0].rm_eo == (eol-bol)) ||
962 !word_char(bol[pmatch[0].rm_eo])) )
964 else
965 hit = 0;
967 /* Words consist of at least one character. */
968 if (pmatch->rm_so == pmatch->rm_eo)
969 hit = 0;
971 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
972 /* There could be more than one match on the
973 * line, and the first match might not be
974 * strict word match. But later ones could be!
975 * Forward to the next possible start, i.e. the
976 * next position following a non-word char.
978 bol = pmatch[0].rm_so + bol + 1;
979 while (word_char(bol[-1]) && bol < eol)
980 bol++;
981 eflags |= REG_NOTBOL;
982 if (bol < eol)
983 goto again;
986 if (hit) {
987 pmatch[0].rm_so += bol - start;
988 pmatch[0].rm_eo += bol - start;
990 return hit;
993 static int match_one_pattern(struct grep_pat *p,
994 const char *bol, const char *eol,
995 enum grep_context ctx, regmatch_t *pmatch,
996 int eflags)
998 const char *field;
999 size_t len;
1001 if (p->token == GREP_PATTERN_HEAD) {
1002 assert(p->field < ARRAY_SIZE(header_field));
1003 field = header_field[p->field].field;
1004 len = header_field[p->field].len;
1005 if (strncmp(bol, field, len))
1006 return 0;
1007 bol += len;
1009 switch (p->field) {
1010 case GREP_HEADER_AUTHOR:
1011 case GREP_HEADER_COMMITTER:
1012 strip_timestamp(bol, &eol);
1013 break;
1014 default:
1015 break;
1019 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1023 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1024 const char *bol, const char *eol,
1025 enum grep_context ctx, ssize_t *col,
1026 ssize_t *icol, int collect_hits)
1028 int h = 0;
1030 switch (x->node) {
1031 case GREP_NODE_TRUE:
1032 h = 1;
1033 break;
1034 case GREP_NODE_ATOM:
1036 regmatch_t tmp;
1037 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1038 &tmp, 0);
1039 if (h && (*col < 0 || tmp.rm_so < *col))
1040 *col = tmp.rm_so;
1042 if (x->u.atom->token == GREP_PATTERN_BODY)
1043 opt->body_hit |= h;
1044 break;
1045 case GREP_NODE_NOT:
1047 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1049 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1051 break;
1052 case GREP_NODE_AND:
1053 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1054 icol, 0);
1055 if (h || opt->columnnum) {
1057 * Don't short-circuit AND when given --column, since a
1058 * NOT earlier in the tree may turn this into an OR. In
1059 * this case, see the below comment.
1061 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1062 ctx, col, icol, 0);
1064 break;
1065 case GREP_NODE_OR:
1066 if (!(collect_hits || opt->columnnum)) {
1068 * Don't short-circuit OR when given --column (or
1069 * collecting hits) to ensure we don't skip a later
1070 * child that would produce an earlier match.
1072 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1073 ctx, col, icol, 0) ||
1074 match_expr_eval(opt, x->u.binary.right, bol,
1075 eol, ctx, col, icol, 0));
1077 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1078 icol, 0);
1079 if (collect_hits)
1080 x->u.binary.left->hit |= h;
1081 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1082 icol, collect_hits);
1083 break;
1084 default:
1085 die("Unexpected node type (internal error) %d", x->node);
1087 if (collect_hits)
1088 x->hit |= h;
1089 return h;
1092 static int match_expr(struct grep_opt *opt,
1093 const char *bol, const char *eol,
1094 enum grep_context ctx, ssize_t *col,
1095 ssize_t *icol, int collect_hits)
1097 struct grep_expr *x = opt->pattern_expression;
1098 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1101 static int match_line(struct grep_opt *opt,
1102 const char *bol, const char *eol,
1103 ssize_t *col, ssize_t *icol,
1104 enum grep_context ctx, int collect_hits)
1106 struct grep_pat *p;
1107 int hit = 0;
1109 if (opt->pattern_expression)
1110 return match_expr(opt, bol, eol, ctx, col, icol,
1111 collect_hits);
1113 /* we do not call with collect_hits without being extended */
1114 for (p = opt->pattern_list; p; p = p->next) {
1115 regmatch_t tmp;
1116 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1117 hit |= 1;
1118 if (!opt->columnnum) {
1120 * Without --column, any single match on a line
1121 * is enough to know that it needs to be
1122 * printed. With --column, scan _all_ patterns
1123 * to find the earliest.
1125 break;
1127 if (*col < 0 || tmp.rm_so < *col)
1128 *col = tmp.rm_so;
1131 return hit;
1134 static int match_next_pattern(struct grep_pat *p,
1135 const char *bol, const char *eol,
1136 enum grep_context ctx,
1137 regmatch_t *pmatch, int eflags)
1139 regmatch_t match;
1141 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1142 return 0;
1143 if (match.rm_so < 0 || match.rm_eo < 0)
1144 return 0;
1145 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1146 if (match.rm_so > pmatch->rm_so)
1147 return 1;
1148 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1149 return 1;
1151 pmatch->rm_so = match.rm_so;
1152 pmatch->rm_eo = match.rm_eo;
1153 return 1;
1156 int grep_next_match(struct grep_opt *opt,
1157 const char *bol, const char *eol,
1158 enum grep_context ctx, regmatch_t *pmatch,
1159 enum grep_header_field field, int eflags)
1161 struct grep_pat *p;
1162 int hit = 0;
1164 pmatch->rm_so = pmatch->rm_eo = -1;
1165 if (bol < eol) {
1166 for (p = ((ctx == GREP_CONTEXT_HEAD)
1167 ? opt->header_list : opt->pattern_list);
1168 p; p = p->next) {
1169 switch (p->token) {
1170 case GREP_PATTERN_HEAD:
1171 if ((field != GREP_HEADER_FIELD_MAX) &&
1172 (p->field != field))
1173 continue;
1174 /* fall thru */
1175 case GREP_PATTERN: /* atom */
1176 case GREP_PATTERN_BODY:
1177 hit |= match_next_pattern(p, bol, eol, ctx,
1178 pmatch, eflags);
1179 break;
1180 default:
1181 break;
1185 return hit;
1188 static void show_line_header(struct grep_opt *opt, const char *name,
1189 unsigned lno, ssize_t cno, char sign)
1191 if (opt->heading && opt->last_shown == 0) {
1192 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1193 opt->output(opt, "\n", 1);
1195 opt->last_shown = lno;
1197 if (!opt->heading && opt->pathname) {
1198 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1199 output_sep(opt, sign);
1201 if (opt->linenum) {
1202 char buf[32];
1203 xsnprintf(buf, sizeof(buf), "%d", lno);
1204 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1205 output_sep(opt, sign);
1208 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1209 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1210 * being called with a context line.
1212 if (opt->columnnum && cno) {
1213 char buf[32];
1214 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1215 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1216 output_sep(opt, sign);
1220 static void show_line(struct grep_opt *opt,
1221 const char *bol, const char *eol,
1222 const char *name, unsigned lno, ssize_t cno, char sign)
1224 int rest = eol - bol;
1225 const char *match_color = NULL;
1226 const char *line_color = NULL;
1228 if (opt->file_break && opt->last_shown == 0) {
1229 if (opt->show_hunk_mark)
1230 opt->output(opt, "\n", 1);
1231 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1232 if (opt->last_shown == 0) {
1233 if (opt->show_hunk_mark) {
1234 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1235 opt->output(opt, "\n", 1);
1237 } else if (lno > opt->last_shown + 1) {
1238 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1239 opt->output(opt, "\n", 1);
1242 if (!opt->only_matching) {
1244 * In case the line we're being called with contains more than
1245 * one match, leave printing each header to the loop below.
1247 show_line_header(opt, name, lno, cno, sign);
1249 if (opt->color || opt->only_matching) {
1250 regmatch_t match;
1251 enum grep_context ctx = GREP_CONTEXT_BODY;
1252 int eflags = 0;
1254 if (opt->color) {
1255 if (sign == ':')
1256 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1257 else
1258 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1259 if (sign == ':')
1260 line_color = opt->colors[GREP_COLOR_SELECTED];
1261 else if (sign == '-')
1262 line_color = opt->colors[GREP_COLOR_CONTEXT];
1263 else if (sign == '=')
1264 line_color = opt->colors[GREP_COLOR_FUNCTION];
1266 while (grep_next_match(opt, bol, eol, ctx, &match,
1267 GREP_HEADER_FIELD_MAX, eflags)) {
1268 if (match.rm_so == match.rm_eo)
1269 break;
1271 if (opt->only_matching)
1272 show_line_header(opt, name, lno, cno, sign);
1273 else
1274 output_color(opt, bol, match.rm_so, line_color);
1275 output_color(opt, bol + match.rm_so,
1276 match.rm_eo - match.rm_so, match_color);
1277 if (opt->only_matching)
1278 opt->output(opt, "\n", 1);
1279 bol += match.rm_eo;
1280 cno += match.rm_eo;
1281 rest -= match.rm_eo;
1282 eflags = REG_NOTBOL;
1285 if (!opt->only_matching) {
1286 output_color(opt, bol, rest, line_color);
1287 opt->output(opt, "\n", 1);
1291 int grep_use_locks;
1294 * This lock protects access to the gitattributes machinery, which is
1295 * not thread-safe.
1297 pthread_mutex_t grep_attr_mutex;
1299 static inline void grep_attr_lock(void)
1301 if (grep_use_locks)
1302 pthread_mutex_lock(&grep_attr_mutex);
1305 static inline void grep_attr_unlock(void)
1307 if (grep_use_locks)
1308 pthread_mutex_unlock(&grep_attr_mutex);
1311 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1312 const char *bol, const char *eol)
1314 xdemitconf_t *xecfg = opt->priv;
1315 if (xecfg && !xecfg->find_func) {
1316 grep_source_load_driver(gs, opt->repo->index);
1317 if (gs->driver->funcname.pattern) {
1318 const struct userdiff_funcname *pe = &gs->driver->funcname;
1319 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1320 } else {
1321 xecfg = opt->priv = NULL;
1325 if (xecfg) {
1326 char buf[1];
1327 return xecfg->find_func(bol, eol - bol, buf, 1,
1328 xecfg->find_func_priv) >= 0;
1331 if (bol == eol)
1332 return 0;
1333 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1334 return 1;
1335 return 0;
1338 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1339 const char *bol, unsigned lno)
1341 while (bol > gs->buf) {
1342 const char *eol = --bol;
1344 while (bol > gs->buf && bol[-1] != '\n')
1345 bol--;
1346 lno--;
1348 if (lno <= opt->last_shown)
1349 break;
1351 if (match_funcname(opt, gs, bol, eol)) {
1352 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1353 break;
1358 static int is_empty_line(const char *bol, const char *eol);
1360 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1361 const char *bol, const char *end, unsigned lno)
1363 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1364 int funcname_needed = !!opt->funcname, comment_needed = 0;
1366 if (opt->pre_context < lno)
1367 from = lno - opt->pre_context;
1368 if (from <= opt->last_shown)
1369 from = opt->last_shown + 1;
1370 orig_from = from;
1371 if (opt->funcbody) {
1372 if (match_funcname(opt, gs, bol, end))
1373 comment_needed = 1;
1374 else
1375 funcname_needed = 1;
1376 from = opt->last_shown + 1;
1379 /* Rewind. */
1380 while (bol > gs->buf && cur > from) {
1381 const char *next_bol = bol;
1382 const char *eol = --bol;
1384 while (bol > gs->buf && bol[-1] != '\n')
1385 bol--;
1386 cur--;
1387 if (comment_needed && (is_empty_line(bol, eol) ||
1388 match_funcname(opt, gs, bol, eol))) {
1389 comment_needed = 0;
1390 from = orig_from;
1391 if (cur < from) {
1392 cur++;
1393 bol = next_bol;
1394 break;
1397 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1398 funcname_lno = cur;
1399 funcname_needed = 0;
1400 if (opt->funcbody)
1401 comment_needed = 1;
1402 else
1403 from = orig_from;
1407 /* We need to look even further back to find a function signature. */
1408 if (opt->funcname && funcname_needed)
1409 show_funcname_line(opt, gs, bol, cur);
1411 /* Back forward. */
1412 while (cur < lno) {
1413 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1415 while (*eol != '\n')
1416 eol++;
1417 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1418 bol = eol + 1;
1419 cur++;
1423 static int should_lookahead(struct grep_opt *opt)
1425 struct grep_pat *p;
1427 if (opt->pattern_expression)
1428 return 0; /* punt for too complex stuff */
1429 if (opt->invert)
1430 return 0;
1431 for (p = opt->pattern_list; p; p = p->next) {
1432 if (p->token != GREP_PATTERN)
1433 return 0; /* punt for "header only" and stuff */
1435 return 1;
1438 static int look_ahead(struct grep_opt *opt,
1439 unsigned long *left_p,
1440 unsigned *lno_p,
1441 const char **bol_p)
1443 unsigned lno = *lno_p;
1444 const char *bol = *bol_p;
1445 struct grep_pat *p;
1446 const char *sp, *last_bol;
1447 regoff_t earliest = -1;
1449 for (p = opt->pattern_list; p; p = p->next) {
1450 int hit;
1451 regmatch_t m;
1453 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1454 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1455 continue;
1456 if (earliest < 0 || m.rm_so < earliest)
1457 earliest = m.rm_so;
1460 if (earliest < 0) {
1461 *bol_p = bol + *left_p;
1462 *left_p = 0;
1463 return 1;
1465 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1466 ; /* find the beginning of the line */
1467 last_bol = sp;
1469 for (sp = bol; sp < last_bol; sp++) {
1470 if (*sp == '\n')
1471 lno++;
1473 *left_p -= last_bol - bol;
1474 *bol_p = last_bol;
1475 *lno_p = lno;
1476 return 0;
1479 static int fill_textconv_grep(struct repository *r,
1480 struct userdiff_driver *driver,
1481 struct grep_source *gs)
1483 struct diff_filespec *df;
1484 char *buf;
1485 size_t size;
1487 if (!driver || !driver->textconv)
1488 return grep_source_load(gs);
1491 * The textconv interface is intimately tied to diff_filespecs, so we
1492 * have to pretend to be one. If we could unify the grep_source
1493 * and diff_filespec structs, this mess could just go away.
1495 df = alloc_filespec(gs->path);
1496 switch (gs->type) {
1497 case GREP_SOURCE_OID:
1498 fill_filespec(df, gs->identifier, 1, 0100644);
1499 break;
1500 case GREP_SOURCE_FILE:
1501 fill_filespec(df, null_oid(), 0, 0100644);
1502 break;
1503 default:
1504 BUG("attempt to textconv something without a path?");
1508 * fill_textconv is not remotely thread-safe; it modifies the global
1509 * diff tempfile structure, writes to the_repo's odb and might
1510 * internally call thread-unsafe functions such as the
1511 * prepare_packed_git() lazy-initializator. Because of the last two, we
1512 * must ensure mutual exclusion between this call and the object reading
1513 * API, thus we use obj_read_lock() here.
1515 * TODO: allowing text conversion to run in parallel with object
1516 * reading operations might increase performance in the multithreaded
1517 * non-worktreee git-grep with --textconv.
1519 obj_read_lock();
1520 size = fill_textconv(r, driver, df, &buf);
1521 obj_read_unlock();
1522 free_filespec(df);
1525 * The normal fill_textconv usage by the diff machinery would just keep
1526 * the textconv'd buf separate from the diff_filespec. But much of the
1527 * grep code passes around a grep_source and assumes that its "buf"
1528 * pointer is the beginning of the thing we are searching. So let's
1529 * install our textconv'd version into the grep_source, taking care not
1530 * to leak any existing buffer.
1532 grep_source_clear_data(gs);
1533 gs->buf = buf;
1534 gs->size = size;
1536 return 0;
1539 static int is_empty_line(const char *bol, const char *eol)
1541 while (bol < eol && isspace(*bol))
1542 bol++;
1543 return bol == eol;
1546 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1548 const char *bol;
1549 const char *peek_bol = NULL;
1550 unsigned long left;
1551 unsigned lno = 1;
1552 unsigned last_hit = 0;
1553 int binary_match_only = 0;
1554 unsigned count = 0;
1555 int try_lookahead = 0;
1556 int show_function = 0;
1557 struct userdiff_driver *textconv = NULL;
1558 enum grep_context ctx = GREP_CONTEXT_HEAD;
1559 xdemitconf_t xecfg;
1561 if (!opt->status_only && gs->name == NULL)
1562 BUG("grep call which could print a name requires "
1563 "grep_source.name be non-NULL");
1565 if (!opt->output)
1566 opt->output = std_output;
1568 if (opt->pre_context || opt->post_context || opt->file_break ||
1569 opt->funcbody) {
1570 /* Show hunk marks, except for the first file. */
1571 if (opt->last_shown)
1572 opt->show_hunk_mark = 1;
1574 * If we're using threads then we can't easily identify
1575 * the first file. Always put hunk marks in that case
1576 * and skip the very first one later in work_done().
1578 if (opt->output != std_output)
1579 opt->show_hunk_mark = 1;
1581 opt->last_shown = 0;
1583 if (opt->allow_textconv) {
1584 grep_source_load_driver(gs, opt->repo->index);
1586 * We might set up the shared textconv cache data here, which
1587 * is not thread-safe. Also, get_oid_with_context() and
1588 * parse_object() might be internally called. As they are not
1589 * currently thread-safe and might be racy with object reading,
1590 * obj_read_lock() must be called.
1592 grep_attr_lock();
1593 obj_read_lock();
1594 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1595 obj_read_unlock();
1596 grep_attr_unlock();
1600 * We know the result of a textconv is text, so we only have to care
1601 * about binary handling if we are not using it.
1603 if (!textconv) {
1604 switch (opt->binary) {
1605 case GREP_BINARY_DEFAULT:
1606 if (grep_source_is_binary(gs, opt->repo->index))
1607 binary_match_only = 1;
1608 break;
1609 case GREP_BINARY_NOMATCH:
1610 if (grep_source_is_binary(gs, opt->repo->index))
1611 return 0; /* Assume unmatch */
1612 break;
1613 case GREP_BINARY_TEXT:
1614 break;
1615 default:
1616 BUG("unknown binary handling mode");
1620 memset(&xecfg, 0, sizeof(xecfg));
1621 opt->priv = &xecfg;
1623 try_lookahead = should_lookahead(opt);
1625 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1626 return 0;
1628 bol = gs->buf;
1629 left = gs->size;
1630 while (left) {
1631 const char *eol;
1632 int hit;
1633 ssize_t cno;
1634 ssize_t col = -1, icol = -1;
1637 * look_ahead() skips quickly to the line that possibly
1638 * has the next hit; don't call it if we need to do
1639 * something more than just skipping the current line
1640 * in response to an unmatch for the current line. E.g.
1641 * inside a post-context window, we will show the current
1642 * line as a context around the previous hit when it
1643 * doesn't hit.
1645 if (try_lookahead
1646 && !(last_hit
1647 && (show_function ||
1648 lno <= last_hit + opt->post_context))
1649 && look_ahead(opt, &left, &lno, &bol))
1650 break;
1651 eol = end_of_line(bol, &left);
1653 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1654 ctx = GREP_CONTEXT_BODY;
1656 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1658 if (collect_hits)
1659 goto next_line;
1661 /* "grep -v -e foo -e bla" should list lines
1662 * that do not have either, so inversion should
1663 * be done outside.
1665 if (opt->invert)
1666 hit = !hit;
1667 if (opt->unmatch_name_only) {
1668 if (hit)
1669 return 0;
1670 goto next_line;
1672 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1673 count++;
1674 if (opt->status_only)
1675 return 1;
1676 if (opt->name_only) {
1677 show_name(opt, gs->name);
1678 return 1;
1680 if (opt->count)
1681 goto next_line;
1682 if (binary_match_only) {
1683 opt->output(opt, "Binary file ", 12);
1684 output_color(opt, gs->name, strlen(gs->name),
1685 opt->colors[GREP_COLOR_FILENAME]);
1686 opt->output(opt, " matches\n", 9);
1687 return 1;
1689 /* Hit at this line. If we haven't shown the
1690 * pre-context lines, we would need to show them.
1692 if (opt->pre_context || opt->funcbody)
1693 show_pre_context(opt, gs, bol, eol, lno);
1694 else if (opt->funcname)
1695 show_funcname_line(opt, gs, bol, lno);
1696 cno = opt->invert ? icol : col;
1697 if (cno < 0) {
1699 * A negative cno indicates that there was no
1700 * match on the line. We are thus inverted and
1701 * being asked to show all lines that _don't_
1702 * match a given expression. Therefore, set cno
1703 * to 0 to suggest the whole line matches.
1705 cno = 0;
1707 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1708 last_hit = lno;
1709 if (opt->funcbody)
1710 show_function = 1;
1711 goto next_line;
1713 if (show_function && (!peek_bol || peek_bol < bol)) {
1714 unsigned long peek_left = left;
1715 const char *peek_eol = eol;
1718 * Trailing empty lines are not interesting.
1719 * Peek past them to see if they belong to the
1720 * body of the current function.
1722 peek_bol = bol;
1723 while (is_empty_line(peek_bol, peek_eol)) {
1724 peek_bol = peek_eol + 1;
1725 peek_eol = end_of_line(peek_bol, &peek_left);
1728 if (match_funcname(opt, gs, peek_bol, peek_eol))
1729 show_function = 0;
1731 if (show_function ||
1732 (last_hit && lno <= last_hit + opt->post_context)) {
1733 /* If the last hit is within the post context,
1734 * we need to show this line.
1736 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1739 next_line:
1740 bol = eol + 1;
1741 if (!left)
1742 break;
1743 left--;
1744 lno++;
1747 if (collect_hits)
1748 return 0;
1750 if (opt->status_only)
1751 return opt->unmatch_name_only;
1752 if (opt->unmatch_name_only) {
1753 /* We did not see any hit, so we want to show this */
1754 show_name(opt, gs->name);
1755 return 1;
1758 xdiff_clear_find_func(&xecfg);
1759 opt->priv = NULL;
1761 /* NEEDSWORK:
1762 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1763 * which feels mostly useless but sometimes useful. Maybe
1764 * make it another option? For now suppress them.
1766 if (opt->count && count) {
1767 char buf[32];
1768 if (opt->pathname) {
1769 output_color(opt, gs->name, strlen(gs->name),
1770 opt->colors[GREP_COLOR_FILENAME]);
1771 output_sep(opt, ':');
1773 xsnprintf(buf, sizeof(buf), "%u\n", count);
1774 opt->output(opt, buf, strlen(buf));
1775 return 1;
1777 return !!last_hit;
1780 static void clr_hit_marker(struct grep_expr *x)
1782 /* All-hit markers are meaningful only at the very top level
1783 * OR node.
1785 while (1) {
1786 x->hit = 0;
1787 if (x->node != GREP_NODE_OR)
1788 return;
1789 x->u.binary.left->hit = 0;
1790 x = x->u.binary.right;
1794 static int chk_hit_marker(struct grep_expr *x)
1796 /* Top level nodes have hit markers. See if they all are hits */
1797 while (1) {
1798 if (x->node != GREP_NODE_OR)
1799 return x->hit;
1800 if (!x->u.binary.left->hit)
1801 return 0;
1802 x = x->u.binary.right;
1806 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1809 * we do not have to do the two-pass grep when we do not check
1810 * buffer-wide "all-match".
1812 if (!opt->all_match && !opt->no_body_match)
1813 return grep_source_1(opt, gs, 0);
1815 /* Otherwise the toplevel "or" terms hit a bit differently.
1816 * We first clear hit markers from them.
1818 clr_hit_marker(opt->pattern_expression);
1819 opt->body_hit = 0;
1820 grep_source_1(opt, gs, 1);
1822 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1823 return 0;
1824 if (opt->no_body_match && opt->body_hit)
1825 return 0;
1827 return grep_source_1(opt, gs, 0);
1830 static void grep_source_init_buf(struct grep_source *gs,
1831 const char *buf,
1832 unsigned long size)
1834 gs->type = GREP_SOURCE_BUF;
1835 gs->name = NULL;
1836 gs->path = NULL;
1837 gs->buf = buf;
1838 gs->size = size;
1839 gs->driver = NULL;
1840 gs->identifier = NULL;
1843 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1845 struct grep_source gs;
1846 int r;
1848 grep_source_init_buf(&gs, buf, size);
1850 r = grep_source(opt, &gs);
1852 grep_source_clear(&gs);
1853 return r;
1856 void grep_source_init_file(struct grep_source *gs, const char *name,
1857 const char *path)
1859 gs->type = GREP_SOURCE_FILE;
1860 gs->name = xstrdup_or_null(name);
1861 gs->path = xstrdup_or_null(path);
1862 gs->buf = NULL;
1863 gs->size = 0;
1864 gs->driver = NULL;
1865 gs->identifier = xstrdup(path);
1868 void grep_source_init_oid(struct grep_source *gs, const char *name,
1869 const char *path, const struct object_id *oid,
1870 struct repository *repo)
1872 gs->type = GREP_SOURCE_OID;
1873 gs->name = xstrdup_or_null(name);
1874 gs->path = xstrdup_or_null(path);
1875 gs->buf = NULL;
1876 gs->size = 0;
1877 gs->driver = NULL;
1878 gs->identifier = oiddup(oid);
1879 gs->repo = repo;
1882 void grep_source_clear(struct grep_source *gs)
1884 FREE_AND_NULL(gs->name);
1885 FREE_AND_NULL(gs->path);
1886 FREE_AND_NULL(gs->identifier);
1887 grep_source_clear_data(gs);
1890 void grep_source_clear_data(struct grep_source *gs)
1892 switch (gs->type) {
1893 case GREP_SOURCE_FILE:
1894 case GREP_SOURCE_OID:
1895 /* these types own the buffer */
1896 free((char *)gs->buf);
1897 gs->buf = NULL;
1898 gs->size = 0;
1899 break;
1900 case GREP_SOURCE_BUF:
1901 /* leave user-provided buf intact */
1902 break;
1906 static int grep_source_load_oid(struct grep_source *gs)
1908 enum object_type type;
1910 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1911 &gs->size);
1912 if (!gs->buf)
1913 return error(_("'%s': unable to read %s"),
1914 gs->name,
1915 oid_to_hex(gs->identifier));
1916 return 0;
1919 static int grep_source_load_file(struct grep_source *gs)
1921 const char *filename = gs->identifier;
1922 struct stat st;
1923 char *data;
1924 size_t size;
1925 int i;
1927 if (lstat(filename, &st) < 0) {
1928 err_ret:
1929 if (errno != ENOENT)
1930 error_errno(_("failed to stat '%s'"), filename);
1931 return -1;
1933 if (!S_ISREG(st.st_mode))
1934 return -1;
1935 size = xsize_t(st.st_size);
1936 i = open(filename, O_RDONLY);
1937 if (i < 0)
1938 goto err_ret;
1939 data = xmallocz(size);
1940 if (st.st_size != read_in_full(i, data, size)) {
1941 error_errno(_("'%s': short read"), filename);
1942 close(i);
1943 free(data);
1944 return -1;
1946 close(i);
1948 gs->buf = data;
1949 gs->size = size;
1950 return 0;
1953 static int grep_source_load(struct grep_source *gs)
1955 if (gs->buf)
1956 return 0;
1958 switch (gs->type) {
1959 case GREP_SOURCE_FILE:
1960 return grep_source_load_file(gs);
1961 case GREP_SOURCE_OID:
1962 return grep_source_load_oid(gs);
1963 case GREP_SOURCE_BUF:
1964 return gs->buf ? 0 : -1;
1966 BUG("invalid grep_source type to load");
1969 void grep_source_load_driver(struct grep_source *gs,
1970 struct index_state *istate)
1972 if (gs->driver)
1973 return;
1975 grep_attr_lock();
1976 if (gs->path)
1977 gs->driver = userdiff_find_by_path(istate, gs->path);
1978 if (!gs->driver)
1979 gs->driver = userdiff_find_by_name("default");
1980 grep_attr_unlock();
1983 static int grep_source_is_binary(struct grep_source *gs,
1984 struct index_state *istate)
1986 grep_source_load_driver(gs, istate);
1987 if (gs->driver->binary != -1)
1988 return gs->driver->binary;
1990 if (!grep_source_load(gs))
1991 return buffer_is_binary(gs->buf, gs->size);
1993 return 0;