4 #include "object-store.h"
6 #include "xdiff-interface.h"
13 static int grep_source_load(struct grep_source *gs);
14 static int grep_source_is_binary(struct grep_source *gs,
15 struct index_state *istate);
17 static struct grep_opt grep_defaults;
20 static pcre2_general_context *pcre2_global_context;
22 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
27 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
33 static const char *color_grep_slots[] = {
34 [GREP_COLOR_CONTEXT] = "context",
35 [GREP_COLOR_FILENAME] = "filename",
36 [GREP_COLOR_FUNCTION] = "function",
37 [GREP_COLOR_LINENO] = "lineNumber",
38 [GREP_COLOR_COLUMNNO] = "column",
39 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
40 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
41 [GREP_COLOR_SELECTED] = "selected",
42 [GREP_COLOR_SEP] = "separator",
45 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
47 fwrite(buf, size, 1, stdout);
50 static void color_set(char *dst, const char *color_bytes)
52 xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
56 * Initialize the grep_defaults template with hardcoded defaults.
57 * We could let the compiler do this, but without C99 initializers
58 * the code gets unwieldy and unreadable, so...
60 void init_grep_defaults(struct repository *repo)
62 struct grep_opt *opt = &grep_defaults;
69 memset(opt, 0, sizeof(*opt));
74 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
75 color_set(opt->colors[GREP_COLOR_CONTEXT], "");
76 color_set(opt->colors[GREP_COLOR_FILENAME], "");
77 color_set(opt->colors[GREP_COLOR_FUNCTION], "");
78 color_set(opt->colors[GREP_COLOR_LINENO], "");
79 color_set(opt->colors[GREP_COLOR_COLUMNNO], "");
80 color_set(opt->colors[GREP_COLOR_MATCH_CONTEXT], GIT_COLOR_BOLD_RED);
81 color_set(opt->colors[GREP_COLOR_MATCH_SELECTED], GIT_COLOR_BOLD_RED);
82 color_set(opt->colors[GREP_COLOR_SELECTED], "");
83 color_set(opt->colors[GREP_COLOR_SEP], GIT_COLOR_CYAN);
84 opt->only_matching = 0;
86 opt->output = std_output;
89 static int parse_pattern_type_arg(const char *opt, const char *arg)
91 if (!strcmp(arg, "default"))
92 return GREP_PATTERN_TYPE_UNSPECIFIED;
93 else if (!strcmp(arg, "basic"))
94 return GREP_PATTERN_TYPE_BRE;
95 else if (!strcmp(arg, "extended"))
96 return GREP_PATTERN_TYPE_ERE;
97 else if (!strcmp(arg, "fixed"))
98 return GREP_PATTERN_TYPE_FIXED;
99 else if (!strcmp(arg, "perl"))
100 return GREP_PATTERN_TYPE_PCRE;
101 die("bad %s argument: %s", opt, arg);
104 define_list_config_array_extra(color_grep_slots, {"match"});
107 * Read the configuration file once and store it in
108 * the grep_defaults template.
110 int grep_config(const char *var, const char *value, void *cb)
112 struct grep_opt *opt = &grep_defaults;
115 if (userdiff_config(var, value) < 0)
118 if (!strcmp(var, "grep.extendedregexp")) {
119 opt->extended_regexp_option = git_config_bool(var, value);
123 if (!strcmp(var, "grep.patterntype")) {
124 opt->pattern_type_option = parse_pattern_type_arg(var, value);
128 if (!strcmp(var, "grep.linenumber")) {
129 opt->linenum = git_config_bool(var, value);
132 if (!strcmp(var, "grep.column")) {
133 opt->columnnum = git_config_bool(var, value);
137 if (!strcmp(var, "grep.fullname")) {
138 opt->relative = !git_config_bool(var, value);
142 if (!strcmp(var, "color.grep"))
143 opt->color = git_config_colorbool(var, value);
144 if (!strcmp(var, "color.grep.match")) {
145 if (grep_config("color.grep.matchcontext", value, cb) < 0)
147 if (grep_config("color.grep.matchselected", value, cb) < 0)
149 } else if (skip_prefix(var, "color.grep.", &slot)) {
150 int i = LOOKUP_CONFIG(color_grep_slots, slot);
155 color = opt->colors[i];
157 return config_error_nonbool(var);
158 return color_parse(value, color);
164 * Initialize one instance of grep_opt and copy the
165 * default values from the template we read the configuration
166 * information in an earlier call to git_config(grep_config).
168 * If using PCRE, make sure that the library is configured
169 * to use the same allocator as Git (e.g. nedmalloc on Windows).
171 * Any allocated memory needs to be released in grep_destroy().
173 void grep_init(struct grep_opt *opt, struct repository *repo, const char *prefix)
175 struct grep_opt *def = &grep_defaults;
178 #if defined(USE_LIBPCRE2)
179 if (!pcre2_global_context)
180 pcre2_global_context = pcre2_general_context_create(
181 pcre2_malloc, pcre2_free, NULL);
185 pcre_malloc = malloc;
189 memset(opt, 0, sizeof(*opt));
191 opt->prefix = prefix;
192 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
193 opt->pattern_tail = &opt->pattern_list;
194 opt->header_tail = &opt->header_list;
196 opt->only_matching = def->only_matching;
197 opt->color = def->color;
198 opt->extended_regexp_option = def->extended_regexp_option;
199 opt->pattern_type_option = def->pattern_type_option;
200 opt->linenum = def->linenum;
201 opt->columnnum = def->columnnum;
202 opt->max_depth = def->max_depth;
203 opt->pathname = def->pathname;
204 opt->relative = def->relative;
205 opt->output = def->output;
207 for (i = 0; i < NR_GREP_COLORS; i++)
208 color_set(opt->colors[i], def->colors[i]);
211 void grep_destroy(void)
214 pcre2_general_context_free(pcre2_global_context);
218 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
221 * When committing to the pattern type by setting the relevant
222 * fields in grep_opt it's generally not necessary to zero out
223 * the fields we're not choosing, since they won't have been
224 * set by anything. The extended_regexp_option field is the
225 * only exception to this.
227 * This is because in the process of parsing grep.patternType
228 * & grep.extendedRegexp we set opt->pattern_type_option and
229 * opt->extended_regexp_option, respectively. We then
230 * internally use opt->extended_regexp_option to see if we're
231 * compiling an ERE. It must be unset if that's not actually
234 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
235 opt->extended_regexp_option)
236 opt->extended_regexp_option = 0;
238 switch (pattern_type) {
239 case GREP_PATTERN_TYPE_UNSPECIFIED:
242 case GREP_PATTERN_TYPE_BRE:
245 case GREP_PATTERN_TYPE_ERE:
246 opt->extended_regexp_option = 1;
249 case GREP_PATTERN_TYPE_FIXED:
253 case GREP_PATTERN_TYPE_PCRE:
258 * It's important that pcre1 always be assigned to
259 * even when there's no USE_LIBPCRE* defined. We still
260 * call the PCRE stub function, it just dies with
261 * "cannot use Perl-compatible regexes[...]".
269 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
271 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
272 grep_set_pattern_type_option(pattern_type, opt);
273 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
274 grep_set_pattern_type_option(opt->pattern_type_option, opt);
275 else if (opt->extended_regexp_option)
277 * This branch *must* happen after setting from the
278 * opt->pattern_type_option above, we don't want
279 * grep.extendedRegexp to override grep.patternType!
281 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
284 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
285 const char *origin, int no,
286 enum grep_pat_token t,
287 enum grep_header_field field)
289 struct grep_pat *p = xcalloc(1, sizeof(*p));
290 p->pattern = xmemdupz(pat, patlen);
291 p->patternlen = patlen;
299 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
306 case GREP_PATTERN: /* atom */
307 case GREP_PATTERN_HEAD:
308 case GREP_PATTERN_BODY:
310 struct grep_pat *new_pat;
312 char *cp = p->pattern + p->patternlen, *nl = NULL;
313 while (++len <= p->patternlen) {
314 if (*(--cp) == '\n') {
321 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
322 p->no, p->token, p->field);
323 new_pat->next = p->next;
325 *tail = &new_pat->next;
328 p->patternlen -= len;
336 void append_header_grep_pattern(struct grep_opt *opt,
337 enum grep_header_field field, const char *pat)
339 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
340 GREP_PATTERN_HEAD, field);
341 if (field == GREP_HEADER_REFLOG)
342 opt->use_reflog_filter = 1;
343 do_append_grep_pat(&opt->header_tail, p);
346 void append_grep_pattern(struct grep_opt *opt, const char *pat,
347 const char *origin, int no, enum grep_pat_token t)
349 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
352 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
353 const char *origin, int no, enum grep_pat_token t)
355 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
356 do_append_grep_pat(&opt->pattern_tail, p);
359 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
361 struct grep_pat *pat;
362 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
365 ret->pattern_list = NULL;
366 ret->pattern_tail = &ret->pattern_list;
368 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
370 if(pat->token == GREP_PATTERN_HEAD)
371 append_header_grep_pattern(ret, pat->field,
374 append_grep_pat(ret, pat->pattern, pat->patternlen,
375 pat->origin, pat->no, pat->token);
381 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
387 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
389 xsnprintf(where, sizeof(where), "%s, ", p->origin);
393 die("%s'%s': %s", where, p->pattern, error);
396 static int is_fixed(const char *s, size_t len)
400 for (i = 0; i < len; i++) {
401 if (is_regex_special(s[i]))
408 static int has_null(const char *s, size_t len)
411 * regcomp cannot accept patterns with NULs so when using it
412 * we consider any pattern containing a NUL fixed.
414 if (memchr(s, 0, len))
421 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
425 int options = PCRE_MULTILINE;
427 if (opt->ignore_case) {
428 if (has_non_ascii(p->pattern))
429 p->pcre1_tables = pcre_maketables();
430 options |= PCRE_CASELESS;
432 if (is_utf8_locale() && has_non_ascii(p->pattern))
433 options |= PCRE_UTF8;
435 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
437 if (!p->pcre1_regexp)
438 compile_regexp_failed(p, error);
440 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, GIT_PCRE_STUDY_JIT_COMPILE, &error);
441 if (!p->pcre1_extra_info && error)
444 #ifdef GIT_PCRE1_USE_JIT
445 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
446 if (p->pcre1_jit_on == 1) {
447 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
448 if (!p->pcre1_jit_stack)
449 die("Couldn't allocate PCRE JIT stack");
450 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
451 } else if (p->pcre1_jit_on != 0) {
452 BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
458 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
459 regmatch_t *match, int eflags)
461 int ovector[30], ret, flags = 0;
463 if (eflags & REG_NOTBOL)
464 flags |= PCRE_NOTBOL;
466 #ifdef GIT_PCRE1_USE_JIT
467 if (p->pcre1_jit_on) {
468 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
469 eol - line, 0, flags, ovector,
470 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
474 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
475 eol - line, 0, flags, ovector,
476 ARRAY_SIZE(ovector));
479 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
480 die("pcre_exec failed with error code %d", ret);
483 match->rm_so = ovector[0];
484 match->rm_eo = ovector[1];
490 static void free_pcre1_regexp(struct grep_pat *p)
492 pcre_free(p->pcre1_regexp);
493 #ifdef GIT_PCRE1_USE_JIT
494 if (p->pcre1_jit_on) {
495 pcre_free_study(p->pcre1_extra_info);
496 pcre_jit_stack_free(p->pcre1_jit_stack);
500 pcre_free(p->pcre1_extra_info);
502 pcre_free((void *)p->pcre1_tables);
504 #else /* !USE_LIBPCRE1 */
505 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
507 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
510 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
511 regmatch_t *match, int eflags)
516 static void free_pcre1_regexp(struct grep_pat *p)
519 #endif /* !USE_LIBPCRE1 */
522 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
525 PCRE2_UCHAR errbuf[256];
526 PCRE2_SIZE erroffset;
527 int options = PCRE2_MULTILINE;
534 p->pcre2_compile_context = NULL;
536 /* pcre2_global_context is initialized in append_grep_pattern */
537 if (opt->ignore_case) {
538 if (has_non_ascii(p->pattern)) {
539 if (!pcre2_global_context)
540 BUG("pcre2_global_context uninitialized");
541 p->pcre2_tables = pcre2_maketables(pcre2_global_context);
542 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
543 pcre2_set_character_tables(p->pcre2_compile_context,
546 options |= PCRE2_CASELESS;
548 if (is_utf8_locale() && has_non_ascii(p->pattern))
549 options |= PCRE2_UTF;
551 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
552 p->patternlen, options, &error, &erroffset,
553 p->pcre2_compile_context);
555 if (p->pcre2_pattern) {
556 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
557 if (!p->pcre2_match_data)
558 die("Couldn't allocate PCRE2 match data");
560 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
561 compile_regexp_failed(p, (const char *)&errbuf);
564 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
565 if (p->pcre2_jit_on == 1) {
566 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
568 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
571 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
572 * tells us whether the library itself supports JIT,
573 * but to see whether we're going to be actually using
574 * JIT we need to extract PCRE2_INFO_JITSIZE from the
575 * pattern *after* we do pcre2_jit_compile() above.
577 * This is because if the pattern contains the
578 * (*NO_JIT) verb (see pcre2syntax(3))
579 * pcre2_jit_compile() will exit early with 0. If we
580 * then proceed to call pcre2_jit_match() further down
581 * the line instead of pcre2_match() we'll either
582 * segfault (pre PCRE 10.31) or run into a fatal error
585 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
587 BUG("pcre2_pattern_info() failed: %d", patinforet);
588 if (jitsizearg == 0) {
593 p->pcre2_jit_stack = pcre2_jit_stack_create(1, 1024 * 1024, NULL);
594 if (!p->pcre2_jit_stack)
595 die("Couldn't allocate PCRE2 JIT stack");
596 p->pcre2_match_context = pcre2_match_context_create(NULL);
597 if (!p->pcre2_match_context)
598 die("Couldn't allocate PCRE2 match context");
599 pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
600 } else if (p->pcre2_jit_on != 0) {
601 BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
606 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
607 regmatch_t *match, int eflags)
611 PCRE2_UCHAR errbuf[256];
613 if (eflags & REG_NOTBOL)
614 flags |= PCRE2_NOTBOL;
617 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
618 eol - line, 0, flags, p->pcre2_match_data,
621 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
622 eol - line, 0, flags, p->pcre2_match_data,
625 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
626 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
627 die("%s failed with error code %d: %s",
628 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
632 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
634 match->rm_so = (int)ovector[0];
635 match->rm_eo = (int)ovector[1];
641 static void free_pcre2_pattern(struct grep_pat *p)
643 pcre2_compile_context_free(p->pcre2_compile_context);
644 pcre2_code_free(p->pcre2_pattern);
645 pcre2_match_data_free(p->pcre2_match_data);
646 pcre2_jit_stack_free(p->pcre2_jit_stack);
647 pcre2_match_context_free(p->pcre2_match_context);
648 free((void *)p->pcre2_tables);
650 #else /* !USE_LIBPCRE2 */
651 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
654 * Unreachable until USE_LIBPCRE2 becomes synonymous with
655 * USE_LIBPCRE. See the sibling comment in
656 * grep_set_pattern_type_option().
658 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
661 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
662 regmatch_t *match, int eflags)
667 static void free_pcre2_pattern(struct grep_pat *p)
670 #endif /* !USE_LIBPCRE2 */
672 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
674 struct strbuf sb = STRBUF_INIT;
678 basic_regex_quote_buf(&sb, p->pattern);
679 if (opt->ignore_case)
680 regflags |= REG_ICASE;
681 err = regcomp(&p->regexp, sb.buf, regflags);
683 fprintf(stderr, "fixed %s\n", sb.buf);
687 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
688 compile_regexp_failed(p, errbuf);
692 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
696 int regflags = REG_NEWLINE;
698 p->word_regexp = opt->word_regexp;
699 p->ignore_case = opt->ignore_case;
700 ascii_only = !has_non_ascii(p->pattern);
703 * Even when -F (fixed) asks us to do a non-regexp search, we
704 * may not be able to correctly case-fold when -i
705 * (ignore-case) is asked (in which case, we'll synthesize a
706 * regexp to match the pattern that matches regexp special
707 * characters literally, while ignoring case differences). On
708 * the other hand, even without -F, if the pattern does not
709 * have any regexp special characters and there is no need for
710 * case-folding search, we can internally turn it into a
711 * simple string match using kws. p->fixed tells us if we
715 has_null(p->pattern, p->patternlen) ||
716 is_fixed(p->pattern, p->patternlen))
717 p->fixed = !p->ignore_case || ascii_only;
720 p->kws = kwsalloc(p->ignore_case ? tolower_trans_tbl : NULL);
721 kwsincr(p->kws, p->pattern, p->patternlen);
724 } else if (opt->fixed) {
726 * We come here when the pattern has the non-ascii
727 * characters we cannot case-fold, and asked to
730 compile_fixed_regexp(p, opt);
735 compile_pcre2_pattern(p, opt);
740 compile_pcre1_regexp(p, opt);
745 regflags |= REG_ICASE;
746 if (opt->extended_regexp_option)
747 regflags |= REG_EXTENDED;
748 err = regcomp(&p->regexp, p->pattern, regflags);
751 regerror(err, &p->regexp, errbuf, 1024);
752 compile_regexp_failed(p, errbuf);
756 static struct grep_expr *compile_pattern_or(struct grep_pat **);
757 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
766 case GREP_PATTERN: /* atom */
767 case GREP_PATTERN_HEAD:
768 case GREP_PATTERN_BODY:
769 x = xcalloc(1, sizeof (struct grep_expr));
770 x->node = GREP_NODE_ATOM;
774 case GREP_OPEN_PAREN:
776 x = compile_pattern_or(list);
777 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
778 die("unmatched parenthesis");
779 *list = (*list)->next;
786 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
797 die("--not not followed by pattern expression");
799 x = xcalloc(1, sizeof (struct grep_expr));
800 x->node = GREP_NODE_NOT;
801 x->u.unary = compile_pattern_not(list);
803 die("--not followed by non pattern expression");
806 return compile_pattern_atom(list);
810 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
813 struct grep_expr *x, *y, *z;
815 x = compile_pattern_not(list);
817 if (p && p->token == GREP_AND) {
819 die("--and not followed by pattern expression");
821 y = compile_pattern_and(list);
823 die("--and not followed by pattern expression");
824 z = xcalloc(1, sizeof (struct grep_expr));
825 z->node = GREP_NODE_AND;
826 z->u.binary.left = x;
827 z->u.binary.right = y;
833 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
836 struct grep_expr *x, *y, *z;
838 x = compile_pattern_and(list);
840 if (x && p && p->token != GREP_CLOSE_PAREN) {
841 y = compile_pattern_or(list);
843 die("not a pattern expression %s", p->pattern);
844 z = xcalloc(1, sizeof (struct grep_expr));
845 z->node = GREP_NODE_OR;
846 z->u.binary.left = x;
847 z->u.binary.right = y;
853 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
855 return compile_pattern_or(list);
858 static void indent(int in)
864 static void dump_grep_pat(struct grep_pat *p)
867 case GREP_AND: fprintf(stderr, "*and*"); break;
868 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
869 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
870 case GREP_NOT: fprintf(stderr, "*not*"); break;
871 case GREP_OR: fprintf(stderr, "*or*"); break;
873 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
874 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
875 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
880 case GREP_PATTERN_HEAD:
881 fprintf(stderr, "<head %d>", p->field); break;
882 case GREP_PATTERN_BODY:
883 fprintf(stderr, "<body>"); break;
887 case GREP_PATTERN_HEAD:
888 case GREP_PATTERN_BODY:
890 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
896 static void dump_grep_expression_1(struct grep_expr *x, int in)
901 fprintf(stderr, "true\n");
904 dump_grep_pat(x->u.atom);
907 fprintf(stderr, "(not\n");
908 dump_grep_expression_1(x->u.unary, in+1);
910 fprintf(stderr, ")\n");
913 fprintf(stderr, "(and\n");
914 dump_grep_expression_1(x->u.binary.left, in+1);
915 dump_grep_expression_1(x->u.binary.right, in+1);
917 fprintf(stderr, ")\n");
920 fprintf(stderr, "(or\n");
921 dump_grep_expression_1(x->u.binary.left, in+1);
922 dump_grep_expression_1(x->u.binary.right, in+1);
924 fprintf(stderr, ")\n");
929 static void dump_grep_expression(struct grep_opt *opt)
931 struct grep_expr *x = opt->pattern_expression;
934 fprintf(stderr, "[all-match]\n");
935 dump_grep_expression_1(x, 0);
939 static struct grep_expr *grep_true_expr(void)
941 struct grep_expr *z = xcalloc(1, sizeof(*z));
942 z->node = GREP_NODE_TRUE;
946 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
948 struct grep_expr *z = xcalloc(1, sizeof(*z));
949 z->node = GREP_NODE_OR;
950 z->u.binary.left = left;
951 z->u.binary.right = right;
955 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
958 struct grep_expr *header_expr;
959 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
960 enum grep_header_field fld;
962 if (!opt->header_list)
965 for (p = opt->header_list; p; p = p->next) {
966 if (p->token != GREP_PATTERN_HEAD)
967 BUG("a non-header pattern in grep header list.");
968 if (p->field < GREP_HEADER_FIELD_MIN ||
969 GREP_HEADER_FIELD_MAX <= p->field)
970 BUG("unknown header field %d", p->field);
971 compile_regexp(p, opt);
974 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
975 header_group[fld] = NULL;
977 for (p = opt->header_list; p; p = p->next) {
979 struct grep_pat *pp = p;
981 h = compile_pattern_atom(&pp);
982 if (!h || pp != p->next)
983 BUG("malformed header expr");
984 if (!header_group[p->field]) {
985 header_group[p->field] = h;
988 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
993 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
994 if (!header_group[fld])
997 header_expr = grep_true_expr();
998 header_expr = grep_or_expr(header_group[fld], header_expr);
1003 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
1005 struct grep_expr *z = x;
1008 assert(x->node == GREP_NODE_OR);
1009 if (x->u.binary.right &&
1010 x->u.binary.right->node == GREP_NODE_TRUE) {
1011 x->u.binary.right = y;
1014 x = x->u.binary.right;
1019 static void compile_grep_patterns_real(struct grep_opt *opt)
1022 struct grep_expr *header_expr = prep_header_patterns(opt);
1024 for (p = opt->pattern_list; p; p = p->next) {
1026 case GREP_PATTERN: /* atom */
1027 case GREP_PATTERN_HEAD:
1028 case GREP_PATTERN_BODY:
1029 compile_regexp(p, opt);
1037 if (opt->all_match || header_expr)
1039 else if (!opt->extended && !opt->debug)
1042 p = opt->pattern_list;
1044 opt->pattern_expression = compile_pattern_expr(&p);
1046 die("incomplete pattern expression: %s", p->pattern);
1051 if (!opt->pattern_expression)
1052 opt->pattern_expression = header_expr;
1053 else if (opt->all_match)
1054 opt->pattern_expression = grep_splice_or(header_expr,
1055 opt->pattern_expression);
1057 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
1062 void compile_grep_patterns(struct grep_opt *opt)
1064 compile_grep_patterns_real(opt);
1066 dump_grep_expression(opt);
1069 static void free_pattern_expr(struct grep_expr *x)
1072 case GREP_NODE_TRUE:
1073 case GREP_NODE_ATOM:
1076 free_pattern_expr(x->u.unary);
1080 free_pattern_expr(x->u.binary.left);
1081 free_pattern_expr(x->u.binary.right);
1087 void free_grep_patterns(struct grep_opt *opt)
1089 struct grep_pat *p, *n;
1091 for (p = opt->pattern_list; p; p = n) {
1094 case GREP_PATTERN: /* atom */
1095 case GREP_PATTERN_HEAD:
1096 case GREP_PATTERN_BODY:
1099 else if (p->pcre1_regexp)
1100 free_pcre1_regexp(p);
1101 else if (p->pcre2_pattern)
1102 free_pcre2_pattern(p);
1104 regfree(&p->regexp);
1115 free_pattern_expr(opt->pattern_expression);
1118 static char *end_of_line(char *cp, unsigned long *left)
1120 unsigned long l = *left;
1121 while (l && *cp != '\n') {
1129 static int word_char(char ch)
1131 return isalnum(ch) || ch == '_';
1134 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1137 if (want_color(opt->color) && color && color[0]) {
1138 opt->output(opt, color, strlen(color));
1139 opt->output(opt, data, size);
1140 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1142 opt->output(opt, data, size);
1145 static void output_sep(struct grep_opt *opt, char sign)
1147 if (opt->null_following_name)
1148 opt->output(opt, "\0", 1);
1150 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
1153 static void show_name(struct grep_opt *opt, const char *name)
1155 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1156 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1159 static int fixmatch(struct grep_pat *p, char *line, char *eol,
1162 struct kwsmatch kwsm;
1163 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
1165 match->rm_so = match->rm_eo = -1;
1168 match->rm_so = offset;
1169 match->rm_eo = match->rm_so + kwsm.size[0];
1174 static int patmatch(struct grep_pat *p, char *line, char *eol,
1175 regmatch_t *match, int eflags)
1180 hit = !fixmatch(p, line, eol, match);
1181 else if (p->pcre1_regexp)
1182 hit = !pcre1match(p, line, eol, match, eflags);
1183 else if (p->pcre2_pattern)
1184 hit = !pcre2match(p, line, eol, match, eflags);
1186 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1192 static int strip_timestamp(char *bol, char **eol_p)
1197 while (bol < --eol) {
1211 } header_field[] = {
1213 { "committer ", 10 },
1217 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1218 enum grep_context ctx,
1219 regmatch_t *pmatch, int eflags)
1223 const char *start = bol;
1225 if ((p->token != GREP_PATTERN) &&
1226 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1229 if (p->token == GREP_PATTERN_HEAD) {
1232 assert(p->field < ARRAY_SIZE(header_field));
1233 field = header_field[p->field].field;
1234 len = header_field[p->field].len;
1235 if (strncmp(bol, field, len))
1239 case GREP_HEADER_AUTHOR:
1240 case GREP_HEADER_COMMITTER:
1241 saved_ch = strip_timestamp(bol, &eol);
1249 hit = patmatch(p, bol, eol, pmatch, eflags);
1251 if (hit && p->word_regexp) {
1252 if ((pmatch[0].rm_so < 0) ||
1253 (eol - bol) < pmatch[0].rm_so ||
1254 (pmatch[0].rm_eo < 0) ||
1255 (eol - bol) < pmatch[0].rm_eo)
1256 die("regexp returned nonsense");
1258 /* Match beginning must be either beginning of the
1259 * line, or at word boundary (i.e. the last char must
1260 * not be a word char). Similarly, match end must be
1261 * either end of the line, or at word boundary
1262 * (i.e. the next char must not be a word char).
1264 if ( ((pmatch[0].rm_so == 0) ||
1265 !word_char(bol[pmatch[0].rm_so-1])) &&
1266 ((pmatch[0].rm_eo == (eol-bol)) ||
1267 !word_char(bol[pmatch[0].rm_eo])) )
1272 /* Words consist of at least one character. */
1273 if (pmatch->rm_so == pmatch->rm_eo)
1276 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1277 /* There could be more than one match on the
1278 * line, and the first match might not be
1279 * strict word match. But later ones could be!
1280 * Forward to the next possible start, i.e. the
1281 * next position following a non-word char.
1283 bol = pmatch[0].rm_so + bol + 1;
1284 while (word_char(bol[-1]) && bol < eol)
1286 eflags |= REG_NOTBOL;
1291 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1294 pmatch[0].rm_so += bol - start;
1295 pmatch[0].rm_eo += bol - start;
1300 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
1301 char *eol, enum grep_context ctx, ssize_t *col,
1302 ssize_t *icol, int collect_hits)
1307 die("Not a valid grep expression");
1309 case GREP_NODE_TRUE:
1312 case GREP_NODE_ATOM:
1315 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1317 if (h && (*col < 0 || tmp.rm_so < *col))
1323 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1325 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1329 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1331 if (h || opt->columnnum) {
1333 * Don't short-circuit AND when given --column, since a
1334 * NOT earlier in the tree may turn this into an OR. In
1335 * this case, see the below comment.
1337 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1342 if (!(collect_hits || opt->columnnum)) {
1344 * Don't short-circuit OR when given --column (or
1345 * collecting hits) to ensure we don't skip a later
1346 * child that would produce an earlier match.
1348 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1349 ctx, col, icol, 0) ||
1350 match_expr_eval(opt, x->u.binary.right, bol,
1351 eol, ctx, col, icol, 0));
1353 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1356 x->u.binary.left->hit |= h;
1357 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1358 icol, collect_hits);
1361 die("Unexpected node type (internal error) %d", x->node);
1368 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1369 enum grep_context ctx, ssize_t *col,
1370 ssize_t *icol, int collect_hits)
1372 struct grep_expr *x = opt->pattern_expression;
1373 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1376 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1377 ssize_t *col, ssize_t *icol,
1378 enum grep_context ctx, int collect_hits)
1384 return match_expr(opt, bol, eol, ctx, col, icol,
1387 /* we do not call with collect_hits without being extended */
1388 for (p = opt->pattern_list; p; p = p->next) {
1390 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1392 if (!opt->columnnum) {
1394 * Without --column, any single match on a line
1395 * is enough to know that it needs to be
1396 * printed. With --column, scan _all_ patterns
1397 * to find the earliest.
1401 if (*col < 0 || tmp.rm_so < *col)
1408 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1409 enum grep_context ctx,
1410 regmatch_t *pmatch, int eflags)
1414 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1416 if (match.rm_so < 0 || match.rm_eo < 0)
1418 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1419 if (match.rm_so > pmatch->rm_so)
1421 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1424 pmatch->rm_so = match.rm_so;
1425 pmatch->rm_eo = match.rm_eo;
1429 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1430 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1435 pmatch->rm_so = pmatch->rm_eo = -1;
1437 for (p = opt->pattern_list; p; p = p->next) {
1439 case GREP_PATTERN: /* atom */
1440 case GREP_PATTERN_HEAD:
1441 case GREP_PATTERN_BODY:
1442 hit |= match_next_pattern(p, bol, eol, ctx,
1453 static void show_line_header(struct grep_opt *opt, const char *name,
1454 unsigned lno, ssize_t cno, char sign)
1456 if (opt->heading && opt->last_shown == 0) {
1457 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1458 opt->output(opt, "\n", 1);
1460 opt->last_shown = lno;
1462 if (!opt->heading && opt->pathname) {
1463 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1464 output_sep(opt, sign);
1468 xsnprintf(buf, sizeof(buf), "%d", lno);
1469 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1470 output_sep(opt, sign);
1473 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1474 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1475 * being called with a context line.
1477 if (opt->columnnum && cno) {
1479 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1480 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1481 output_sep(opt, sign);
1485 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1486 const char *name, unsigned lno, ssize_t cno, char sign)
1488 int rest = eol - bol;
1489 const char *match_color = NULL;
1490 const char *line_color = NULL;
1492 if (opt->file_break && opt->last_shown == 0) {
1493 if (opt->show_hunk_mark)
1494 opt->output(opt, "\n", 1);
1495 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1496 if (opt->last_shown == 0) {
1497 if (opt->show_hunk_mark) {
1498 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1499 opt->output(opt, "\n", 1);
1501 } else if (lno > opt->last_shown + 1) {
1502 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1503 opt->output(opt, "\n", 1);
1506 if (!opt->only_matching) {
1508 * In case the line we're being called with contains more than
1509 * one match, leave printing each header to the loop below.
1511 show_line_header(opt, name, lno, cno, sign);
1513 if (opt->color || opt->only_matching) {
1515 enum grep_context ctx = GREP_CONTEXT_BODY;
1521 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1523 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1525 line_color = opt->colors[GREP_COLOR_SELECTED];
1526 else if (sign == '-')
1527 line_color = opt->colors[GREP_COLOR_CONTEXT];
1528 else if (sign == '=')
1529 line_color = opt->colors[GREP_COLOR_FUNCTION];
1532 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1533 if (match.rm_so == match.rm_eo)
1536 if (opt->only_matching)
1537 show_line_header(opt, name, lno, cno, sign);
1539 output_color(opt, bol, match.rm_so, line_color);
1540 output_color(opt, bol + match.rm_so,
1541 match.rm_eo - match.rm_so, match_color);
1542 if (opt->only_matching)
1543 opt->output(opt, "\n", 1);
1546 rest -= match.rm_eo;
1547 eflags = REG_NOTBOL;
1551 if (!opt->only_matching) {
1552 output_color(opt, bol, rest, line_color);
1553 opt->output(opt, "\n", 1);
1560 * This lock protects access to the gitattributes machinery, which is
1563 pthread_mutex_t grep_attr_mutex;
1565 static inline void grep_attr_lock(void)
1568 pthread_mutex_lock(&grep_attr_mutex);
1571 static inline void grep_attr_unlock(void)
1574 pthread_mutex_unlock(&grep_attr_mutex);
1578 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1580 pthread_mutex_t grep_read_mutex;
1582 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1584 xdemitconf_t *xecfg = opt->priv;
1585 if (xecfg && !xecfg->find_func) {
1586 grep_source_load_driver(gs, opt->repo->index);
1587 if (gs->driver->funcname.pattern) {
1588 const struct userdiff_funcname *pe = &gs->driver->funcname;
1589 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1591 xecfg = opt->priv = NULL;
1597 return xecfg->find_func(bol, eol - bol, buf, 1,
1598 xecfg->find_func_priv) >= 0;
1603 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1608 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1609 char *bol, unsigned lno)
1611 while (bol > gs->buf) {
1614 while (bol > gs->buf && bol[-1] != '\n')
1618 if (lno <= opt->last_shown)
1621 if (match_funcname(opt, gs, bol, eol)) {
1622 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1628 static int is_empty_line(const char *bol, const char *eol);
1630 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1631 char *bol, char *end, unsigned lno)
1633 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1634 int funcname_needed = !!opt->funcname, comment_needed = 0;
1636 if (opt->pre_context < lno)
1637 from = lno - opt->pre_context;
1638 if (from <= opt->last_shown)
1639 from = opt->last_shown + 1;
1641 if (opt->funcbody) {
1642 if (match_funcname(opt, gs, bol, end))
1645 funcname_needed = 1;
1646 from = opt->last_shown + 1;
1650 while (bol > gs->buf && cur > from) {
1651 char *next_bol = bol;
1654 while (bol > gs->buf && bol[-1] != '\n')
1657 if (comment_needed && (is_empty_line(bol, eol) ||
1658 match_funcname(opt, gs, bol, eol))) {
1667 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1669 funcname_needed = 0;
1677 /* We need to look even further back to find a function signature. */
1678 if (opt->funcname && funcname_needed)
1679 show_funcname_line(opt, gs, bol, cur);
1683 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1685 while (*eol != '\n')
1687 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1693 static int should_lookahead(struct grep_opt *opt)
1698 return 0; /* punt for too complex stuff */
1701 for (p = opt->pattern_list; p; p = p->next) {
1702 if (p->token != GREP_PATTERN)
1703 return 0; /* punt for "header only" and stuff */
1708 static int look_ahead(struct grep_opt *opt,
1709 unsigned long *left_p,
1713 unsigned lno = *lno_p;
1716 char *sp, *last_bol;
1717 regoff_t earliest = -1;
1719 for (p = opt->pattern_list; p; p = p->next) {
1723 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1724 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1726 if (earliest < 0 || m.rm_so < earliest)
1731 *bol_p = bol + *left_p;
1735 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1736 ; /* find the beginning of the line */
1739 for (sp = bol; sp < last_bol; sp++) {
1743 *left_p -= last_bol - bol;
1749 static int fill_textconv_grep(struct repository *r,
1750 struct userdiff_driver *driver,
1751 struct grep_source *gs)
1753 struct diff_filespec *df;
1757 if (!driver || !driver->textconv)
1758 return grep_source_load(gs);
1761 * The textconv interface is intimately tied to diff_filespecs, so we
1762 * have to pretend to be one. If we could unify the grep_source
1763 * and diff_filespec structs, this mess could just go away.
1765 df = alloc_filespec(gs->path);
1767 case GREP_SOURCE_OID:
1768 fill_filespec(df, gs->identifier, 1, 0100644);
1770 case GREP_SOURCE_FILE:
1771 fill_filespec(df, &null_oid, 0, 0100644);
1774 BUG("attempt to textconv something without a path?");
1778 * fill_textconv is not remotely thread-safe; it may load objects
1779 * behind the scenes, and it modifies the global diff tempfile
1783 size = fill_textconv(r, driver, df, &buf);
1788 * The normal fill_textconv usage by the diff machinery would just keep
1789 * the textconv'd buf separate from the diff_filespec. But much of the
1790 * grep code passes around a grep_source and assumes that its "buf"
1791 * pointer is the beginning of the thing we are searching. So let's
1792 * install our textconv'd version into the grep_source, taking care not
1793 * to leak any existing buffer.
1795 grep_source_clear_data(gs);
1802 static int is_empty_line(const char *bol, const char *eol)
1804 while (bol < eol && isspace(*bol))
1809 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1812 char *peek_bol = NULL;
1815 unsigned last_hit = 0;
1816 int binary_match_only = 0;
1818 int try_lookahead = 0;
1819 int show_function = 0;
1820 struct userdiff_driver *textconv = NULL;
1821 enum grep_context ctx = GREP_CONTEXT_HEAD;
1824 if (!opt->status_only && gs->name == NULL)
1825 BUG("grep call which could print a name requires "
1826 "grep_source.name be non-NULL");
1829 opt->output = std_output;
1831 if (opt->pre_context || opt->post_context || opt->file_break ||
1833 /* Show hunk marks, except for the first file. */
1834 if (opt->last_shown)
1835 opt->show_hunk_mark = 1;
1837 * If we're using threads then we can't easily identify
1838 * the first file. Always put hunk marks in that case
1839 * and skip the very first one later in work_done().
1841 if (opt->output != std_output)
1842 opt->show_hunk_mark = 1;
1844 opt->last_shown = 0;
1846 if (opt->allow_textconv) {
1847 grep_source_load_driver(gs, opt->repo->index);
1849 * We might set up the shared textconv cache data here, which
1850 * is not thread-safe.
1853 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1858 * We know the result of a textconv is text, so we only have to care
1859 * about binary handling if we are not using it.
1862 switch (opt->binary) {
1863 case GREP_BINARY_DEFAULT:
1864 if (grep_source_is_binary(gs, opt->repo->index))
1865 binary_match_only = 1;
1867 case GREP_BINARY_NOMATCH:
1868 if (grep_source_is_binary(gs, opt->repo->index))
1869 return 0; /* Assume unmatch */
1871 case GREP_BINARY_TEXT:
1874 BUG("unknown binary handling mode");
1878 memset(&xecfg, 0, sizeof(xecfg));
1881 try_lookahead = should_lookahead(opt);
1883 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1892 ssize_t col = -1, icol = -1;
1895 * look_ahead() skips quickly to the line that possibly
1896 * has the next hit; don't call it if we need to do
1897 * something more than just skipping the current line
1898 * in response to an unmatch for the current line. E.g.
1899 * inside a post-context window, we will show the current
1900 * line as a context around the previous hit when it
1905 && (show_function ||
1906 lno <= last_hit + opt->post_context))
1907 && look_ahead(opt, &left, &lno, &bol))
1909 eol = end_of_line(bol, &left);
1913 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1914 ctx = GREP_CONTEXT_BODY;
1916 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1922 /* "grep -v -e foo -e bla" should list lines
1923 * that do not have either, so inversion should
1928 if (opt->unmatch_name_only) {
1935 if (opt->status_only)
1937 if (opt->name_only) {
1938 show_name(opt, gs->name);
1943 if (binary_match_only) {
1944 opt->output(opt, "Binary file ", 12);
1945 output_color(opt, gs->name, strlen(gs->name),
1946 opt->colors[GREP_COLOR_FILENAME]);
1947 opt->output(opt, " matches\n", 9);
1950 /* Hit at this line. If we haven't shown the
1951 * pre-context lines, we would need to show them.
1953 if (opt->pre_context || opt->funcbody)
1954 show_pre_context(opt, gs, bol, eol, lno);
1955 else if (opt->funcname)
1956 show_funcname_line(opt, gs, bol, lno);
1957 cno = opt->invert ? icol : col;
1960 * A negative cno indicates that there was no
1961 * match on the line. We are thus inverted and
1962 * being asked to show all lines that _don't_
1963 * match a given expression. Therefore, set cno
1964 * to 0 to suggest the whole line matches.
1968 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1974 if (show_function && (!peek_bol || peek_bol < bol)) {
1975 unsigned long peek_left = left;
1976 char *peek_eol = eol;
1979 * Trailing empty lines are not interesting.
1980 * Peek past them to see if they belong to the
1981 * body of the current function.
1984 while (is_empty_line(peek_bol, peek_eol)) {
1985 peek_bol = peek_eol + 1;
1986 peek_eol = end_of_line(peek_bol, &peek_left);
1989 if (match_funcname(opt, gs, peek_bol, peek_eol))
1992 if (show_function ||
1993 (last_hit && lno <= last_hit + opt->post_context)) {
1994 /* If the last hit is within the post context,
1995 * we need to show this line.
1997 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
2011 if (opt->status_only)
2012 return opt->unmatch_name_only;
2013 if (opt->unmatch_name_only) {
2014 /* We did not see any hit, so we want to show this */
2015 show_name(opt, gs->name);
2019 xdiff_clear_find_func(&xecfg);
2023 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
2024 * which feels mostly useless but sometimes useful. Maybe
2025 * make it another option? For now suppress them.
2027 if (opt->count && count) {
2029 if (opt->pathname) {
2030 output_color(opt, gs->name, strlen(gs->name),
2031 opt->colors[GREP_COLOR_FILENAME]);
2032 output_sep(opt, ':');
2034 xsnprintf(buf, sizeof(buf), "%u\n", count);
2035 opt->output(opt, buf, strlen(buf));
2041 static void clr_hit_marker(struct grep_expr *x)
2043 /* All-hit markers are meaningful only at the very top level
2048 if (x->node != GREP_NODE_OR)
2050 x->u.binary.left->hit = 0;
2051 x = x->u.binary.right;
2055 static int chk_hit_marker(struct grep_expr *x)
2057 /* Top level nodes have hit markers. See if they all are hits */
2059 if (x->node != GREP_NODE_OR)
2061 if (!x->u.binary.left->hit)
2063 x = x->u.binary.right;
2067 int grep_source(struct grep_opt *opt, struct grep_source *gs)
2070 * we do not have to do the two-pass grep when we do not check
2071 * buffer-wide "all-match".
2073 if (!opt->all_match)
2074 return grep_source_1(opt, gs, 0);
2076 /* Otherwise the toplevel "or" terms hit a bit differently.
2077 * We first clear hit markers from them.
2079 clr_hit_marker(opt->pattern_expression);
2080 grep_source_1(opt, gs, 1);
2082 if (!chk_hit_marker(opt->pattern_expression))
2085 return grep_source_1(opt, gs, 0);
2088 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
2090 struct grep_source gs;
2093 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
2097 r = grep_source(opt, &gs);
2099 grep_source_clear(&gs);
2103 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
2104 const char *name, const char *path,
2105 const void *identifier)
2108 gs->name = xstrdup_or_null(name);
2109 gs->path = xstrdup_or_null(path);
2115 case GREP_SOURCE_FILE:
2116 gs->identifier = xstrdup(identifier);
2118 case GREP_SOURCE_OID:
2119 gs->identifier = oiddup(identifier);
2121 case GREP_SOURCE_BUF:
2122 gs->identifier = NULL;
2127 void grep_source_clear(struct grep_source *gs)
2129 FREE_AND_NULL(gs->name);
2130 FREE_AND_NULL(gs->path);
2131 FREE_AND_NULL(gs->identifier);
2132 grep_source_clear_data(gs);
2135 void grep_source_clear_data(struct grep_source *gs)
2138 case GREP_SOURCE_FILE:
2139 case GREP_SOURCE_OID:
2140 FREE_AND_NULL(gs->buf);
2143 case GREP_SOURCE_BUF:
2144 /* leave user-provided buf intact */
2149 static int grep_source_load_oid(struct grep_source *gs)
2151 enum object_type type;
2154 gs->buf = read_object_file(gs->identifier, &type, &gs->size);
2158 return error(_("'%s': unable to read %s"),
2160 oid_to_hex(gs->identifier));
2164 static int grep_source_load_file(struct grep_source *gs)
2166 const char *filename = gs->identifier;
2172 if (lstat(filename, &st) < 0) {
2174 if (errno != ENOENT)
2175 error_errno(_("failed to stat '%s'"), filename);
2178 if (!S_ISREG(st.st_mode))
2180 size = xsize_t(st.st_size);
2181 i = open(filename, O_RDONLY);
2184 data = xmallocz(size);
2185 if (st.st_size != read_in_full(i, data, size)) {
2186 error_errno(_("'%s': short read"), filename);
2198 static int grep_source_load(struct grep_source *gs)
2204 case GREP_SOURCE_FILE:
2205 return grep_source_load_file(gs);
2206 case GREP_SOURCE_OID:
2207 return grep_source_load_oid(gs);
2208 case GREP_SOURCE_BUF:
2209 return gs->buf ? 0 : -1;
2211 BUG("invalid grep_source type to load");
2214 void grep_source_load_driver(struct grep_source *gs,
2215 struct index_state *istate)
2222 gs->driver = userdiff_find_by_path(istate, gs->path);
2224 gs->driver = userdiff_find_by_name("default");
2228 static int grep_source_is_binary(struct grep_source *gs,
2229 struct index_state *istate)
2231 grep_source_load_driver(gs, istate);
2232 if (gs->driver->binary != -1)
2233 return gs->driver->binary;
2235 if (!grep_source_load(gs))
2236 return buffer_is_binary(gs->buf, gs->size);