5 #include "xdiff-interface.h"
11 static int grep_source_load(struct grep_source *gs);
12 static int grep_source_is_binary(struct grep_source *gs);
14 static struct grep_opt grep_defaults;
16 static const char *color_grep_slots[] = {
17 [GREP_COLOR_CONTEXT] = "context",
18 [GREP_COLOR_FILENAME] = "filename",
19 [GREP_COLOR_FUNCTION] = "function",
20 [GREP_COLOR_LINENO] = "lineNumber",
21 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
22 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
23 [GREP_COLOR_SELECTED] = "selected",
24 [GREP_COLOR_SEP] = "separator",
27 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
29 fwrite(buf, size, 1, stdout);
32 static void color_set(char *dst, const char *color_bytes)
34 xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
38 * Initialize the grep_defaults template with hardcoded defaults.
39 * We could let the compiler do this, but without C99 initializers
40 * the code gets unwieldy and unreadable, so...
42 void init_grep_defaults(void)
44 struct grep_opt *opt = &grep_defaults;
51 memset(opt, 0, sizeof(*opt));
55 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
56 color_set(opt->colors[GREP_COLOR_CONTEXT], "");
57 color_set(opt->colors[GREP_COLOR_FILENAME], "");
58 color_set(opt->colors[GREP_COLOR_FUNCTION], "");
59 color_set(opt->colors[GREP_COLOR_LINENO], "");
60 color_set(opt->colors[GREP_COLOR_MATCH_CONTEXT], GIT_COLOR_BOLD_RED);
61 color_set(opt->colors[GREP_COLOR_MATCH_SELECTED], GIT_COLOR_BOLD_RED);
62 color_set(opt->colors[GREP_COLOR_SELECTED], "");
63 color_set(opt->colors[GREP_COLOR_SEP], GIT_COLOR_CYAN);
65 opt->output = std_output;
68 static int parse_pattern_type_arg(const char *opt, const char *arg)
70 if (!strcmp(arg, "default"))
71 return GREP_PATTERN_TYPE_UNSPECIFIED;
72 else if (!strcmp(arg, "basic"))
73 return GREP_PATTERN_TYPE_BRE;
74 else if (!strcmp(arg, "extended"))
75 return GREP_PATTERN_TYPE_ERE;
76 else if (!strcmp(arg, "fixed"))
77 return GREP_PATTERN_TYPE_FIXED;
78 else if (!strcmp(arg, "perl"))
79 return GREP_PATTERN_TYPE_PCRE;
80 die("bad %s argument: %s", opt, arg);
84 * Read the configuration file once and store it in
85 * the grep_defaults template.
87 int grep_config(const char *var, const char *value, void *cb)
89 struct grep_opt *opt = &grep_defaults;
92 if (userdiff_config(var, value) < 0)
95 if (!strcmp(var, "grep.extendedregexp")) {
96 opt->extended_regexp_option = git_config_bool(var, value);
100 if (!strcmp(var, "grep.patterntype")) {
101 opt->pattern_type_option = parse_pattern_type_arg(var, value);
105 if (!strcmp(var, "grep.linenumber")) {
106 opt->linenum = git_config_bool(var, value);
110 if (!strcmp(var, "grep.fullname")) {
111 opt->relative = !git_config_bool(var, value);
115 if (!strcmp(var, "color.grep"))
116 opt->color = git_config_colorbool(var, value);
117 if (!strcmp(var, "color.grep.match")) {
118 if (grep_config("color.grep.matchcontext", value, cb) < 0)
120 if (grep_config("color.grep.matchselected", value, cb) < 0)
122 } else if (skip_prefix(var, "color.grep.", &slot)) {
123 int i = LOOKUP_CONFIG(color_grep_slots, slot);
128 color = opt->colors[i];
130 return config_error_nonbool(var);
131 return color_parse(value, color);
137 * Initialize one instance of grep_opt and copy the
138 * default values from the template we read the configuration
139 * information in an earlier call to git_config(grep_config).
141 void grep_init(struct grep_opt *opt, const char *prefix)
143 struct grep_opt *def = &grep_defaults;
146 memset(opt, 0, sizeof(*opt));
147 opt->prefix = prefix;
148 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
149 opt->pattern_tail = &opt->pattern_list;
150 opt->header_tail = &opt->header_list;
152 opt->color = def->color;
153 opt->extended_regexp_option = def->extended_regexp_option;
154 opt->pattern_type_option = def->pattern_type_option;
155 opt->linenum = def->linenum;
156 opt->max_depth = def->max_depth;
157 opt->pathname = def->pathname;
158 opt->relative = def->relative;
159 opt->output = def->output;
161 for (i = 0; i < NR_GREP_COLORS; i++)
162 color_set(opt->colors[i], def->colors[i]);
165 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
168 * When committing to the pattern type by setting the relevant
169 * fields in grep_opt it's generally not necessary to zero out
170 * the fields we're not choosing, since they won't have been
171 * set by anything. The extended_regexp_option field is the
172 * only exception to this.
174 * This is because in the process of parsing grep.patternType
175 * & grep.extendedRegexp we set opt->pattern_type_option and
176 * opt->extended_regexp_option, respectively. We then
177 * internally use opt->extended_regexp_option to see if we're
178 * compiling an ERE. It must be unset if that's not actually
181 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
182 opt->extended_regexp_option)
183 opt->extended_regexp_option = 0;
185 switch (pattern_type) {
186 case GREP_PATTERN_TYPE_UNSPECIFIED:
189 case GREP_PATTERN_TYPE_BRE:
192 case GREP_PATTERN_TYPE_ERE:
193 opt->extended_regexp_option = 1;
196 case GREP_PATTERN_TYPE_FIXED:
200 case GREP_PATTERN_TYPE_PCRE:
205 * It's important that pcre1 always be assigned to
206 * even when there's no USE_LIBPCRE* defined. We still
207 * call the PCRE stub function, it just dies with
208 * "cannot use Perl-compatible regexes[...]".
216 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
218 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
219 grep_set_pattern_type_option(pattern_type, opt);
220 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
221 grep_set_pattern_type_option(opt->pattern_type_option, opt);
222 else if (opt->extended_regexp_option)
224 * This branch *must* happen after setting from the
225 * opt->pattern_type_option above, we don't want
226 * grep.extendedRegexp to override grep.patternType!
228 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
231 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
232 const char *origin, int no,
233 enum grep_pat_token t,
234 enum grep_header_field field)
236 struct grep_pat *p = xcalloc(1, sizeof(*p));
237 p->pattern = xmemdupz(pat, patlen);
238 p->patternlen = patlen;
246 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
253 case GREP_PATTERN: /* atom */
254 case GREP_PATTERN_HEAD:
255 case GREP_PATTERN_BODY:
257 struct grep_pat *new_pat;
259 char *cp = p->pattern + p->patternlen, *nl = NULL;
260 while (++len <= p->patternlen) {
261 if (*(--cp) == '\n') {
268 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
269 p->no, p->token, p->field);
270 new_pat->next = p->next;
272 *tail = &new_pat->next;
275 p->patternlen -= len;
283 void append_header_grep_pattern(struct grep_opt *opt,
284 enum grep_header_field field, const char *pat)
286 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
287 GREP_PATTERN_HEAD, field);
288 if (field == GREP_HEADER_REFLOG)
289 opt->use_reflog_filter = 1;
290 do_append_grep_pat(&opt->header_tail, p);
293 void append_grep_pattern(struct grep_opt *opt, const char *pat,
294 const char *origin, int no, enum grep_pat_token t)
296 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
299 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
300 const char *origin, int no, enum grep_pat_token t)
302 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
303 do_append_grep_pat(&opt->pattern_tail, p);
306 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
308 struct grep_pat *pat;
309 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
312 ret->pattern_list = NULL;
313 ret->pattern_tail = &ret->pattern_list;
315 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
317 if(pat->token == GREP_PATTERN_HEAD)
318 append_header_grep_pattern(ret, pat->field,
321 append_grep_pat(ret, pat->pattern, pat->patternlen,
322 pat->origin, pat->no, pat->token);
328 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
334 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
336 xsnprintf(where, sizeof(where), "%s, ", p->origin);
340 die("%s'%s': %s", where, p->pattern, error);
343 static int is_fixed(const char *s, size_t len)
347 for (i = 0; i < len; i++) {
348 if (is_regex_special(s[i]))
355 static int has_null(const char *s, size_t len)
358 * regcomp cannot accept patterns with NULs so when using it
359 * we consider any pattern containing a NUL fixed.
361 if (memchr(s, 0, len))
368 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
372 int options = PCRE_MULTILINE;
374 if (opt->ignore_case) {
375 if (has_non_ascii(p->pattern))
376 p->pcre1_tables = pcre_maketables();
377 options |= PCRE_CASELESS;
379 if (is_utf8_locale() && has_non_ascii(p->pattern))
380 options |= PCRE_UTF8;
382 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
384 if (!p->pcre1_regexp)
385 compile_regexp_failed(p, error);
387 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, GIT_PCRE_STUDY_JIT_COMPILE, &error);
388 if (!p->pcre1_extra_info && error)
391 #ifdef GIT_PCRE1_USE_JIT
392 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
393 if (p->pcre1_jit_on == 1) {
394 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
395 if (!p->pcre1_jit_stack)
396 die("Couldn't allocate PCRE JIT stack");
397 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
398 } else if (p->pcre1_jit_on != 0) {
399 die("BUG: The pcre1_jit_on variable should be 0 or 1, not %d",
405 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
406 regmatch_t *match, int eflags)
408 int ovector[30], ret, flags = 0;
410 if (eflags & REG_NOTBOL)
411 flags |= PCRE_NOTBOL;
413 #ifdef GIT_PCRE1_USE_JIT
414 if (p->pcre1_jit_on) {
415 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
416 eol - line, 0, flags, ovector,
417 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
421 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
422 eol - line, 0, flags, ovector,
423 ARRAY_SIZE(ovector));
426 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
427 die("pcre_exec failed with error code %d", ret);
430 match->rm_so = ovector[0];
431 match->rm_eo = ovector[1];
437 static void free_pcre1_regexp(struct grep_pat *p)
439 pcre_free(p->pcre1_regexp);
440 #ifdef GIT_PCRE1_USE_JIT
441 if (p->pcre1_jit_on) {
442 pcre_free_study(p->pcre1_extra_info);
443 pcre_jit_stack_free(p->pcre1_jit_stack);
447 pcre_free(p->pcre1_extra_info);
449 pcre_free((void *)p->pcre1_tables);
451 #else /* !USE_LIBPCRE1 */
452 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
454 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
457 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
458 regmatch_t *match, int eflags)
463 static void free_pcre1_regexp(struct grep_pat *p)
466 #endif /* !USE_LIBPCRE1 */
469 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
472 PCRE2_UCHAR errbuf[256];
473 PCRE2_SIZE erroffset;
474 int options = PCRE2_MULTILINE;
475 const uint8_t *character_tables = NULL;
482 p->pcre2_compile_context = NULL;
484 if (opt->ignore_case) {
485 if (has_non_ascii(p->pattern)) {
486 character_tables = pcre2_maketables(NULL);
487 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
488 pcre2_set_character_tables(p->pcre2_compile_context, character_tables);
490 options |= PCRE2_CASELESS;
492 if (is_utf8_locale() && has_non_ascii(p->pattern))
493 options |= PCRE2_UTF;
495 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
496 p->patternlen, options, &error, &erroffset,
497 p->pcre2_compile_context);
499 if (p->pcre2_pattern) {
500 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
501 if (!p->pcre2_match_data)
502 die("Couldn't allocate PCRE2 match data");
504 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
505 compile_regexp_failed(p, (const char *)&errbuf);
508 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
509 if (p->pcre2_jit_on == 1) {
510 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
512 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
515 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
516 * tells us whether the library itself supports JIT,
517 * but to see whether we're going to be actually using
518 * JIT we need to extract PCRE2_INFO_JITSIZE from the
519 * pattern *after* we do pcre2_jit_compile() above.
521 * This is because if the pattern contains the
522 * (*NO_JIT) verb (see pcre2syntax(3))
523 * pcre2_jit_compile() will exit early with 0. If we
524 * then proceed to call pcre2_jit_match() further down
525 * the line instead of pcre2_match() we'll either
526 * segfault (pre PCRE 10.31) or run into a fatal error
529 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
531 BUG("pcre2_pattern_info() failed: %d", patinforet);
532 if (jitsizearg == 0) {
537 p->pcre2_jit_stack = pcre2_jit_stack_create(1, 1024 * 1024, NULL);
538 if (!p->pcre2_jit_stack)
539 die("Couldn't allocate PCRE2 JIT stack");
540 p->pcre2_match_context = pcre2_match_context_create(NULL);
541 if (!p->pcre2_match_context)
542 die("Couldn't allocate PCRE2 match context");
543 pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
544 } else if (p->pcre2_jit_on != 0) {
545 die("BUG: The pcre2_jit_on variable should be 0 or 1, not %d",
550 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
551 regmatch_t *match, int eflags)
555 PCRE2_UCHAR errbuf[256];
557 if (eflags & REG_NOTBOL)
558 flags |= PCRE2_NOTBOL;
561 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
562 eol - line, 0, flags, p->pcre2_match_data,
565 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
566 eol - line, 0, flags, p->pcre2_match_data,
569 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
570 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
571 die("%s failed with error code %d: %s",
572 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
576 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
578 match->rm_so = (int)ovector[0];
579 match->rm_eo = (int)ovector[1];
585 static void free_pcre2_pattern(struct grep_pat *p)
587 pcre2_compile_context_free(p->pcre2_compile_context);
588 pcre2_code_free(p->pcre2_pattern);
589 pcre2_match_data_free(p->pcre2_match_data);
590 pcre2_jit_stack_free(p->pcre2_jit_stack);
591 pcre2_match_context_free(p->pcre2_match_context);
593 #else /* !USE_LIBPCRE2 */
594 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
597 * Unreachable until USE_LIBPCRE2 becomes synonymous with
598 * USE_LIBPCRE. See the sibling comment in
599 * grep_set_pattern_type_option().
601 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
604 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
605 regmatch_t *match, int eflags)
610 static void free_pcre2_pattern(struct grep_pat *p)
613 #endif /* !USE_LIBPCRE2 */
615 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
617 struct strbuf sb = STRBUF_INIT;
621 basic_regex_quote_buf(&sb, p->pattern);
622 if (opt->ignore_case)
623 regflags |= REG_ICASE;
624 err = regcomp(&p->regexp, sb.buf, regflags);
626 fprintf(stderr, "fixed %s\n", sb.buf);
630 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
632 compile_regexp_failed(p, errbuf);
636 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
640 int regflags = REG_NEWLINE;
642 p->word_regexp = opt->word_regexp;
643 p->ignore_case = opt->ignore_case;
644 ascii_only = !has_non_ascii(p->pattern);
647 * Even when -F (fixed) asks us to do a non-regexp search, we
648 * may not be able to correctly case-fold when -i
649 * (ignore-case) is asked (in which case, we'll synthesize a
650 * regexp to match the pattern that matches regexp special
651 * characters literally, while ignoring case differences). On
652 * the other hand, even without -F, if the pattern does not
653 * have any regexp special characters and there is no need for
654 * case-folding search, we can internally turn it into a
655 * simple string match using kws. p->fixed tells us if we
659 has_null(p->pattern, p->patternlen) ||
660 is_fixed(p->pattern, p->patternlen))
661 p->fixed = !p->ignore_case || ascii_only;
664 p->kws = kwsalloc(p->ignore_case ? tolower_trans_tbl : NULL);
665 kwsincr(p->kws, p->pattern, p->patternlen);
668 } else if (opt->fixed) {
670 * We come here when the pattern has the non-ascii
671 * characters we cannot case-fold, and asked to
674 compile_fixed_regexp(p, opt);
679 compile_pcre2_pattern(p, opt);
684 compile_pcre1_regexp(p, opt);
689 regflags |= REG_ICASE;
690 if (opt->extended_regexp_option)
691 regflags |= REG_EXTENDED;
692 err = regcomp(&p->regexp, p->pattern, regflags);
695 regerror(err, &p->regexp, errbuf, 1024);
697 compile_regexp_failed(p, errbuf);
701 static struct grep_expr *compile_pattern_or(struct grep_pat **);
702 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
711 case GREP_PATTERN: /* atom */
712 case GREP_PATTERN_HEAD:
713 case GREP_PATTERN_BODY:
714 x = xcalloc(1, sizeof (struct grep_expr));
715 x->node = GREP_NODE_ATOM;
719 case GREP_OPEN_PAREN:
721 x = compile_pattern_or(list);
722 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
723 die("unmatched parenthesis");
724 *list = (*list)->next;
731 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
742 die("--not not followed by pattern expression");
744 x = xcalloc(1, sizeof (struct grep_expr));
745 x->node = GREP_NODE_NOT;
746 x->u.unary = compile_pattern_not(list);
748 die("--not followed by non pattern expression");
751 return compile_pattern_atom(list);
755 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
758 struct grep_expr *x, *y, *z;
760 x = compile_pattern_not(list);
762 if (p && p->token == GREP_AND) {
764 die("--and not followed by pattern expression");
766 y = compile_pattern_and(list);
768 die("--and not followed by pattern expression");
769 z = xcalloc(1, sizeof (struct grep_expr));
770 z->node = GREP_NODE_AND;
771 z->u.binary.left = x;
772 z->u.binary.right = y;
778 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
781 struct grep_expr *x, *y, *z;
783 x = compile_pattern_and(list);
785 if (x && p && p->token != GREP_CLOSE_PAREN) {
786 y = compile_pattern_or(list);
788 die("not a pattern expression %s", p->pattern);
789 z = xcalloc(1, sizeof (struct grep_expr));
790 z->node = GREP_NODE_OR;
791 z->u.binary.left = x;
792 z->u.binary.right = y;
798 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
800 return compile_pattern_or(list);
803 static void indent(int in)
809 static void dump_grep_pat(struct grep_pat *p)
812 case GREP_AND: fprintf(stderr, "*and*"); break;
813 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
814 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
815 case GREP_NOT: fprintf(stderr, "*not*"); break;
816 case GREP_OR: fprintf(stderr, "*or*"); break;
818 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
819 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
820 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
825 case GREP_PATTERN_HEAD:
826 fprintf(stderr, "<head %d>", p->field); break;
827 case GREP_PATTERN_BODY:
828 fprintf(stderr, "<body>"); break;
832 case GREP_PATTERN_HEAD:
833 case GREP_PATTERN_BODY:
835 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
841 static void dump_grep_expression_1(struct grep_expr *x, int in)
846 fprintf(stderr, "true\n");
849 dump_grep_pat(x->u.atom);
852 fprintf(stderr, "(not\n");
853 dump_grep_expression_1(x->u.unary, in+1);
855 fprintf(stderr, ")\n");
858 fprintf(stderr, "(and\n");
859 dump_grep_expression_1(x->u.binary.left, in+1);
860 dump_grep_expression_1(x->u.binary.right, in+1);
862 fprintf(stderr, ")\n");
865 fprintf(stderr, "(or\n");
866 dump_grep_expression_1(x->u.binary.left, in+1);
867 dump_grep_expression_1(x->u.binary.right, in+1);
869 fprintf(stderr, ")\n");
874 static void dump_grep_expression(struct grep_opt *opt)
876 struct grep_expr *x = opt->pattern_expression;
879 fprintf(stderr, "[all-match]\n");
880 dump_grep_expression_1(x, 0);
884 static struct grep_expr *grep_true_expr(void)
886 struct grep_expr *z = xcalloc(1, sizeof(*z));
887 z->node = GREP_NODE_TRUE;
891 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
893 struct grep_expr *z = xcalloc(1, sizeof(*z));
894 z->node = GREP_NODE_OR;
895 z->u.binary.left = left;
896 z->u.binary.right = right;
900 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
903 struct grep_expr *header_expr;
904 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
905 enum grep_header_field fld;
907 if (!opt->header_list)
910 for (p = opt->header_list; p; p = p->next) {
911 if (p->token != GREP_PATTERN_HEAD)
912 die("BUG: a non-header pattern in grep header list.");
913 if (p->field < GREP_HEADER_FIELD_MIN ||
914 GREP_HEADER_FIELD_MAX <= p->field)
915 die("BUG: unknown header field %d", p->field);
916 compile_regexp(p, opt);
919 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
920 header_group[fld] = NULL;
922 for (p = opt->header_list; p; p = p->next) {
924 struct grep_pat *pp = p;
926 h = compile_pattern_atom(&pp);
927 if (!h || pp != p->next)
928 die("BUG: malformed header expr");
929 if (!header_group[p->field]) {
930 header_group[p->field] = h;
933 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
938 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
939 if (!header_group[fld])
942 header_expr = grep_true_expr();
943 header_expr = grep_or_expr(header_group[fld], header_expr);
948 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
950 struct grep_expr *z = x;
953 assert(x->node == GREP_NODE_OR);
954 if (x->u.binary.right &&
955 x->u.binary.right->node == GREP_NODE_TRUE) {
956 x->u.binary.right = y;
959 x = x->u.binary.right;
964 static void compile_grep_patterns_real(struct grep_opt *opt)
967 struct grep_expr *header_expr = prep_header_patterns(opt);
969 for (p = opt->pattern_list; p; p = p->next) {
971 case GREP_PATTERN: /* atom */
972 case GREP_PATTERN_HEAD:
973 case GREP_PATTERN_BODY:
974 compile_regexp(p, opt);
982 if (opt->all_match || header_expr)
984 else if (!opt->extended && !opt->debug)
987 p = opt->pattern_list;
989 opt->pattern_expression = compile_pattern_expr(&p);
991 die("incomplete pattern expression: %s", p->pattern);
996 if (!opt->pattern_expression)
997 opt->pattern_expression = header_expr;
998 else if (opt->all_match)
999 opt->pattern_expression = grep_splice_or(header_expr,
1000 opt->pattern_expression);
1002 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
1007 void compile_grep_patterns(struct grep_opt *opt)
1009 compile_grep_patterns_real(opt);
1011 dump_grep_expression(opt);
1014 static void free_pattern_expr(struct grep_expr *x)
1017 case GREP_NODE_TRUE:
1018 case GREP_NODE_ATOM:
1021 free_pattern_expr(x->u.unary);
1025 free_pattern_expr(x->u.binary.left);
1026 free_pattern_expr(x->u.binary.right);
1032 void free_grep_patterns(struct grep_opt *opt)
1034 struct grep_pat *p, *n;
1036 for (p = opt->pattern_list; p; p = n) {
1039 case GREP_PATTERN: /* atom */
1040 case GREP_PATTERN_HEAD:
1041 case GREP_PATTERN_BODY:
1044 else if (p->pcre1_regexp)
1045 free_pcre1_regexp(p);
1046 else if (p->pcre2_pattern)
1047 free_pcre2_pattern(p);
1049 regfree(&p->regexp);
1060 free_pattern_expr(opt->pattern_expression);
1063 static char *end_of_line(char *cp, unsigned long *left)
1065 unsigned long l = *left;
1066 while (l && *cp != '\n') {
1074 static int word_char(char ch)
1076 return isalnum(ch) || ch == '_';
1079 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1082 if (want_color(opt->color) && color && color[0]) {
1083 opt->output(opt, color, strlen(color));
1084 opt->output(opt, data, size);
1085 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1087 opt->output(opt, data, size);
1090 static void output_sep(struct grep_opt *opt, char sign)
1092 if (opt->null_following_name)
1093 opt->output(opt, "\0", 1);
1095 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
1098 static void show_name(struct grep_opt *opt, const char *name)
1100 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1101 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1104 static int fixmatch(struct grep_pat *p, char *line, char *eol,
1107 struct kwsmatch kwsm;
1108 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
1110 match->rm_so = match->rm_eo = -1;
1113 match->rm_so = offset;
1114 match->rm_eo = match->rm_so + kwsm.size[0];
1119 static int patmatch(struct grep_pat *p, char *line, char *eol,
1120 regmatch_t *match, int eflags)
1125 hit = !fixmatch(p, line, eol, match);
1126 else if (p->pcre1_regexp)
1127 hit = !pcre1match(p, line, eol, match, eflags);
1128 else if (p->pcre2_pattern)
1129 hit = !pcre2match(p, line, eol, match, eflags);
1131 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1137 static int strip_timestamp(char *bol, char **eol_p)
1142 while (bol < --eol) {
1156 } header_field[] = {
1158 { "committer ", 10 },
1162 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1163 enum grep_context ctx,
1164 regmatch_t *pmatch, int eflags)
1168 const char *start = bol;
1170 if ((p->token != GREP_PATTERN) &&
1171 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1174 if (p->token == GREP_PATTERN_HEAD) {
1177 assert(p->field < ARRAY_SIZE(header_field));
1178 field = header_field[p->field].field;
1179 len = header_field[p->field].len;
1180 if (strncmp(bol, field, len))
1184 case GREP_HEADER_AUTHOR:
1185 case GREP_HEADER_COMMITTER:
1186 saved_ch = strip_timestamp(bol, &eol);
1194 hit = patmatch(p, bol, eol, pmatch, eflags);
1196 if (hit && p->word_regexp) {
1197 if ((pmatch[0].rm_so < 0) ||
1198 (eol - bol) < pmatch[0].rm_so ||
1199 (pmatch[0].rm_eo < 0) ||
1200 (eol - bol) < pmatch[0].rm_eo)
1201 die("regexp returned nonsense");
1203 /* Match beginning must be either beginning of the
1204 * line, or at word boundary (i.e. the last char must
1205 * not be a word char). Similarly, match end must be
1206 * either end of the line, or at word boundary
1207 * (i.e. the next char must not be a word char).
1209 if ( ((pmatch[0].rm_so == 0) ||
1210 !word_char(bol[pmatch[0].rm_so-1])) &&
1211 ((pmatch[0].rm_eo == (eol-bol)) ||
1212 !word_char(bol[pmatch[0].rm_eo])) )
1217 /* Words consist of at least one character. */
1218 if (pmatch->rm_so == pmatch->rm_eo)
1221 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1222 /* There could be more than one match on the
1223 * line, and the first match might not be
1224 * strict word match. But later ones could be!
1225 * Forward to the next possible start, i.e. the
1226 * next position following a non-word char.
1228 bol = pmatch[0].rm_so + bol + 1;
1229 while (word_char(bol[-1]) && bol < eol)
1231 eflags |= REG_NOTBOL;
1236 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1239 pmatch[0].rm_so += bol - start;
1240 pmatch[0].rm_eo += bol - start;
1245 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1246 enum grep_context ctx, int collect_hits)
1252 die("Not a valid grep expression");
1254 case GREP_NODE_TRUE:
1257 case GREP_NODE_ATOM:
1258 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1261 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1264 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1266 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1270 return (match_expr_eval(x->u.binary.left,
1271 bol, eol, ctx, 0) ||
1272 match_expr_eval(x->u.binary.right,
1274 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1275 x->u.binary.left->hit |= h;
1276 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1279 die("Unexpected node type (internal error) %d", x->node);
1286 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1287 enum grep_context ctx, int collect_hits)
1289 struct grep_expr *x = opt->pattern_expression;
1290 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1293 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1294 enum grep_context ctx, int collect_hits)
1300 return match_expr(opt, bol, eol, ctx, collect_hits);
1302 /* we do not call with collect_hits without being extended */
1303 for (p = opt->pattern_list; p; p = p->next) {
1304 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1310 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1311 enum grep_context ctx,
1312 regmatch_t *pmatch, int eflags)
1316 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1318 if (match.rm_so < 0 || match.rm_eo < 0)
1320 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1321 if (match.rm_so > pmatch->rm_so)
1323 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1326 pmatch->rm_so = match.rm_so;
1327 pmatch->rm_eo = match.rm_eo;
1331 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1332 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1337 pmatch->rm_so = pmatch->rm_eo = -1;
1339 for (p = opt->pattern_list; p; p = p->next) {
1341 case GREP_PATTERN: /* atom */
1342 case GREP_PATTERN_HEAD:
1343 case GREP_PATTERN_BODY:
1344 hit |= match_next_pattern(p, bol, eol, ctx,
1355 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1356 const char *name, unsigned lno, char sign)
1358 int rest = eol - bol;
1359 const char *match_color, *line_color = NULL;
1361 if (opt->file_break && opt->last_shown == 0) {
1362 if (opt->show_hunk_mark)
1363 opt->output(opt, "\n", 1);
1364 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1365 if (opt->last_shown == 0) {
1366 if (opt->show_hunk_mark) {
1367 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1368 opt->output(opt, "\n", 1);
1370 } else if (lno > opt->last_shown + 1) {
1371 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1372 opt->output(opt, "\n", 1);
1375 if (opt->heading && opt->last_shown == 0) {
1376 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1377 opt->output(opt, "\n", 1);
1379 opt->last_shown = lno;
1381 if (!opt->heading && opt->pathname) {
1382 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1383 output_sep(opt, sign);
1387 xsnprintf(buf, sizeof(buf), "%d", lno);
1388 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1389 output_sep(opt, sign);
1393 enum grep_context ctx = GREP_CONTEXT_BODY;
1398 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1400 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1402 line_color = opt->colors[GREP_COLOR_SELECTED];
1403 else if (sign == '-')
1404 line_color = opt->colors[GREP_COLOR_CONTEXT];
1405 else if (sign == '=')
1406 line_color = opt->colors[GREP_COLOR_FUNCTION];
1408 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1409 if (match.rm_so == match.rm_eo)
1412 output_color(opt, bol, match.rm_so, line_color);
1413 output_color(opt, bol + match.rm_so,
1414 match.rm_eo - match.rm_so, match_color);
1416 rest -= match.rm_eo;
1417 eflags = REG_NOTBOL;
1421 output_color(opt, bol, rest, line_color);
1422 opt->output(opt, "\n", 1);
1429 * This lock protects access to the gitattributes machinery, which is
1432 pthread_mutex_t grep_attr_mutex;
1434 static inline void grep_attr_lock(void)
1437 pthread_mutex_lock(&grep_attr_mutex);
1440 static inline void grep_attr_unlock(void)
1443 pthread_mutex_unlock(&grep_attr_mutex);
1447 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1449 pthread_mutex_t grep_read_mutex;
1452 #define grep_attr_lock()
1453 #define grep_attr_unlock()
1456 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1458 xdemitconf_t *xecfg = opt->priv;
1459 if (xecfg && !xecfg->find_func) {
1460 grep_source_load_driver(gs);
1461 if (gs->driver->funcname.pattern) {
1462 const struct userdiff_funcname *pe = &gs->driver->funcname;
1463 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1465 xecfg = opt->priv = NULL;
1471 return xecfg->find_func(bol, eol - bol, buf, 1,
1472 xecfg->find_func_priv) >= 0;
1477 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1482 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1483 char *bol, unsigned lno)
1485 while (bol > gs->buf) {
1488 while (bol > gs->buf && bol[-1] != '\n')
1492 if (lno <= opt->last_shown)
1495 if (match_funcname(opt, gs, bol, eol)) {
1496 show_line(opt, bol, eol, gs->name, lno, '=');
1502 static int is_empty_line(const char *bol, const char *eol);
1504 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1505 char *bol, char *end, unsigned lno)
1507 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1508 int funcname_needed = !!opt->funcname, comment_needed = 0;
1510 if (opt->pre_context < lno)
1511 from = lno - opt->pre_context;
1512 if (from <= opt->last_shown)
1513 from = opt->last_shown + 1;
1515 if (opt->funcbody) {
1516 if (match_funcname(opt, gs, bol, end))
1519 funcname_needed = 1;
1520 from = opt->last_shown + 1;
1524 while (bol > gs->buf && cur > from) {
1525 char *next_bol = bol;
1528 while (bol > gs->buf && bol[-1] != '\n')
1531 if (comment_needed && (is_empty_line(bol, eol) ||
1532 match_funcname(opt, gs, bol, eol))) {
1541 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1543 funcname_needed = 0;
1551 /* We need to look even further back to find a function signature. */
1552 if (opt->funcname && funcname_needed)
1553 show_funcname_line(opt, gs, bol, cur);
1557 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1559 while (*eol != '\n')
1561 show_line(opt, bol, eol, gs->name, cur, sign);
1567 static int should_lookahead(struct grep_opt *opt)
1572 return 0; /* punt for too complex stuff */
1575 for (p = opt->pattern_list; p; p = p->next) {
1576 if (p->token != GREP_PATTERN)
1577 return 0; /* punt for "header only" and stuff */
1582 static int look_ahead(struct grep_opt *opt,
1583 unsigned long *left_p,
1587 unsigned lno = *lno_p;
1590 char *sp, *last_bol;
1591 regoff_t earliest = -1;
1593 for (p = opt->pattern_list; p; p = p->next) {
1597 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1598 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1600 if (earliest < 0 || m.rm_so < earliest)
1605 *bol_p = bol + *left_p;
1609 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1610 ; /* find the beginning of the line */
1613 for (sp = bol; sp < last_bol; sp++) {
1617 *left_p -= last_bol - bol;
1623 static int fill_textconv_grep(struct userdiff_driver *driver,
1624 struct grep_source *gs)
1626 struct diff_filespec *df;
1630 if (!driver || !driver->textconv)
1631 return grep_source_load(gs);
1634 * The textconv interface is intimately tied to diff_filespecs, so we
1635 * have to pretend to be one. If we could unify the grep_source
1636 * and diff_filespec structs, this mess could just go away.
1638 df = alloc_filespec(gs->path);
1640 case GREP_SOURCE_OID:
1641 fill_filespec(df, gs->identifier, 1, 0100644);
1643 case GREP_SOURCE_FILE:
1644 fill_filespec(df, &null_oid, 0, 0100644);
1647 die("BUG: attempt to textconv something without a path?");
1651 * fill_textconv is not remotely thread-safe; it may load objects
1652 * behind the scenes, and it modifies the global diff tempfile
1656 size = fill_textconv(driver, df, &buf);
1661 * The normal fill_textconv usage by the diff machinery would just keep
1662 * the textconv'd buf separate from the diff_filespec. But much of the
1663 * grep code passes around a grep_source and assumes that its "buf"
1664 * pointer is the beginning of the thing we are searching. So let's
1665 * install our textconv'd version into the grep_source, taking care not
1666 * to leak any existing buffer.
1668 grep_source_clear_data(gs);
1675 static int is_empty_line(const char *bol, const char *eol)
1677 while (bol < eol && isspace(*bol))
1682 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1685 char *peek_bol = NULL;
1688 unsigned last_hit = 0;
1689 int binary_match_only = 0;
1691 int try_lookahead = 0;
1692 int show_function = 0;
1693 struct userdiff_driver *textconv = NULL;
1694 enum grep_context ctx = GREP_CONTEXT_HEAD;
1698 opt->output = std_output;
1700 if (opt->pre_context || opt->post_context || opt->file_break ||
1702 /* Show hunk marks, except for the first file. */
1703 if (opt->last_shown)
1704 opt->show_hunk_mark = 1;
1706 * If we're using threads then we can't easily identify
1707 * the first file. Always put hunk marks in that case
1708 * and skip the very first one later in work_done().
1710 if (opt->output != std_output)
1711 opt->show_hunk_mark = 1;
1713 opt->last_shown = 0;
1715 if (opt->allow_textconv) {
1716 grep_source_load_driver(gs);
1718 * We might set up the shared textconv cache data here, which
1719 * is not thread-safe.
1722 textconv = userdiff_get_textconv(gs->driver);
1727 * We know the result of a textconv is text, so we only have to care
1728 * about binary handling if we are not using it.
1731 switch (opt->binary) {
1732 case GREP_BINARY_DEFAULT:
1733 if (grep_source_is_binary(gs))
1734 binary_match_only = 1;
1736 case GREP_BINARY_NOMATCH:
1737 if (grep_source_is_binary(gs))
1738 return 0; /* Assume unmatch */
1740 case GREP_BINARY_TEXT:
1743 die("BUG: unknown binary handling mode");
1747 memset(&xecfg, 0, sizeof(xecfg));
1750 try_lookahead = should_lookahead(opt);
1752 if (fill_textconv_grep(textconv, gs) < 0)
1762 * look_ahead() skips quickly to the line that possibly
1763 * has the next hit; don't call it if we need to do
1764 * something more than just skipping the current line
1765 * in response to an unmatch for the current line. E.g.
1766 * inside a post-context window, we will show the current
1767 * line as a context around the previous hit when it
1772 && (show_function ||
1773 lno <= last_hit + opt->post_context))
1774 && look_ahead(opt, &left, &lno, &bol))
1776 eol = end_of_line(bol, &left);
1780 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1781 ctx = GREP_CONTEXT_BODY;
1783 hit = match_line(opt, bol, eol, ctx, collect_hits);
1789 /* "grep -v -e foo -e bla" should list lines
1790 * that do not have either, so inversion should
1795 if (opt->unmatch_name_only) {
1802 if (opt->status_only)
1804 if (opt->name_only) {
1805 show_name(opt, gs->name);
1810 if (binary_match_only) {
1811 opt->output(opt, "Binary file ", 12);
1812 output_color(opt, gs->name, strlen(gs->name),
1813 opt->colors[GREP_COLOR_FILENAME]);
1814 opt->output(opt, " matches\n", 9);
1817 /* Hit at this line. If we haven't shown the
1818 * pre-context lines, we would need to show them.
1820 if (opt->pre_context || opt->funcbody)
1821 show_pre_context(opt, gs, bol, eol, lno);
1822 else if (opt->funcname)
1823 show_funcname_line(opt, gs, bol, lno);
1824 show_line(opt, bol, eol, gs->name, lno, ':');
1830 if (show_function && (!peek_bol || peek_bol < bol)) {
1831 unsigned long peek_left = left;
1832 char *peek_eol = eol;
1835 * Trailing empty lines are not interesting.
1836 * Peek past them to see if they belong to the
1837 * body of the current function.
1840 while (is_empty_line(peek_bol, peek_eol)) {
1841 peek_bol = peek_eol + 1;
1842 peek_eol = end_of_line(peek_bol, &peek_left);
1845 if (match_funcname(opt, gs, peek_bol, peek_eol))
1848 if (show_function ||
1849 (last_hit && lno <= last_hit + opt->post_context)) {
1850 /* If the last hit is within the post context,
1851 * we need to show this line.
1853 show_line(opt, bol, eol, gs->name, lno, '-');
1867 if (opt->status_only)
1868 return opt->unmatch_name_only;
1869 if (opt->unmatch_name_only) {
1870 /* We did not see any hit, so we want to show this */
1871 show_name(opt, gs->name);
1875 xdiff_clear_find_func(&xecfg);
1879 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1880 * which feels mostly useless but sometimes useful. Maybe
1881 * make it another option? For now suppress them.
1883 if (opt->count && count) {
1885 if (opt->pathname) {
1886 output_color(opt, gs->name, strlen(gs->name),
1887 opt->colors[GREP_COLOR_FILENAME]);
1888 output_sep(opt, ':');
1890 xsnprintf(buf, sizeof(buf), "%u\n", count);
1891 opt->output(opt, buf, strlen(buf));
1897 static void clr_hit_marker(struct grep_expr *x)
1899 /* All-hit markers are meaningful only at the very top level
1904 if (x->node != GREP_NODE_OR)
1906 x->u.binary.left->hit = 0;
1907 x = x->u.binary.right;
1911 static int chk_hit_marker(struct grep_expr *x)
1913 /* Top level nodes have hit markers. See if they all are hits */
1915 if (x->node != GREP_NODE_OR)
1917 if (!x->u.binary.left->hit)
1919 x = x->u.binary.right;
1923 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1926 * we do not have to do the two-pass grep when we do not check
1927 * buffer-wide "all-match".
1929 if (!opt->all_match)
1930 return grep_source_1(opt, gs, 0);
1932 /* Otherwise the toplevel "or" terms hit a bit differently.
1933 * We first clear hit markers from them.
1935 clr_hit_marker(opt->pattern_expression);
1936 grep_source_1(opt, gs, 1);
1938 if (!chk_hit_marker(opt->pattern_expression))
1941 return grep_source_1(opt, gs, 0);
1944 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1946 struct grep_source gs;
1949 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1953 r = grep_source(opt, &gs);
1955 grep_source_clear(&gs);
1959 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1960 const char *name, const char *path,
1961 const void *identifier)
1964 gs->name = xstrdup_or_null(name);
1965 gs->path = xstrdup_or_null(path);
1971 case GREP_SOURCE_FILE:
1972 gs->identifier = xstrdup(identifier);
1974 case GREP_SOURCE_OID:
1975 gs->identifier = oiddup(identifier);
1977 case GREP_SOURCE_BUF:
1978 gs->identifier = NULL;
1983 void grep_source_clear(struct grep_source *gs)
1985 FREE_AND_NULL(gs->name);
1986 FREE_AND_NULL(gs->path);
1987 FREE_AND_NULL(gs->identifier);
1988 grep_source_clear_data(gs);
1991 void grep_source_clear_data(struct grep_source *gs)
1994 case GREP_SOURCE_FILE:
1995 case GREP_SOURCE_OID:
1996 FREE_AND_NULL(gs->buf);
1999 case GREP_SOURCE_BUF:
2000 /* leave user-provided buf intact */
2005 static int grep_source_load_oid(struct grep_source *gs)
2007 enum object_type type;
2010 gs->buf = read_object_file(gs->identifier, &type, &gs->size);
2014 return error(_("'%s': unable to read %s"),
2016 oid_to_hex(gs->identifier));
2020 static int grep_source_load_file(struct grep_source *gs)
2022 const char *filename = gs->identifier;
2028 if (lstat(filename, &st) < 0) {
2030 if (errno != ENOENT)
2031 error_errno(_("failed to stat '%s'"), filename);
2034 if (!S_ISREG(st.st_mode))
2036 size = xsize_t(st.st_size);
2037 i = open(filename, O_RDONLY);
2040 data = xmallocz(size);
2041 if (st.st_size != read_in_full(i, data, size)) {
2042 error_errno(_("'%s': short read"), filename);
2054 static int grep_source_load(struct grep_source *gs)
2060 case GREP_SOURCE_FILE:
2061 return grep_source_load_file(gs);
2062 case GREP_SOURCE_OID:
2063 return grep_source_load_oid(gs);
2064 case GREP_SOURCE_BUF:
2065 return gs->buf ? 0 : -1;
2067 die("BUG: invalid grep_source type to load");
2070 void grep_source_load_driver(struct grep_source *gs)
2077 gs->driver = userdiff_find_by_path(gs->path);
2079 gs->driver = userdiff_find_by_name("default");
2083 static int grep_source_is_binary(struct grep_source *gs)
2085 grep_source_load_driver(gs);
2086 if (gs->driver->binary != -1)
2087 return gs->driver->binary;
2089 if (!grep_source_load(gs))
2090 return buffer_is_binary(gs->buf, gs->size);