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 void std_output(struct grep_opt *opt, const void *buf, size_t size)
19 fwrite(buf, size, 1, stdout);
22 static struct grep_opt grep_defaults = {
26 .pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED,
28 [GREP_COLOR_CONTEXT] = "",
29 [GREP_COLOR_FILENAME] = "",
30 [GREP_COLOR_FUNCTION] = "",
31 [GREP_COLOR_LINENO] = "",
32 [GREP_COLOR_COLUMNNO] = "",
33 [GREP_COLOR_MATCH_CONTEXT] = GIT_COLOR_BOLD_RED,
34 [GREP_COLOR_MATCH_SELECTED] = GIT_COLOR_BOLD_RED,
35 [GREP_COLOR_SELECTED] = "",
36 [GREP_COLOR_SEP] = GIT_COLOR_CYAN,
44 static pcre2_general_context *pcre2_global_context;
46 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
51 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
57 static const char *color_grep_slots[] = {
58 [GREP_COLOR_CONTEXT] = "context",
59 [GREP_COLOR_FILENAME] = "filename",
60 [GREP_COLOR_FUNCTION] = "function",
61 [GREP_COLOR_LINENO] = "lineNumber",
62 [GREP_COLOR_COLUMNNO] = "column",
63 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
64 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
65 [GREP_COLOR_SELECTED] = "selected",
66 [GREP_COLOR_SEP] = "separator",
69 static void color_set(char *dst, const char *color_bytes)
71 xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
74 static int parse_pattern_type_arg(const char *opt, const char *arg)
76 if (!strcmp(arg, "default"))
77 return GREP_PATTERN_TYPE_UNSPECIFIED;
78 else if (!strcmp(arg, "basic"))
79 return GREP_PATTERN_TYPE_BRE;
80 else if (!strcmp(arg, "extended"))
81 return GREP_PATTERN_TYPE_ERE;
82 else if (!strcmp(arg, "fixed"))
83 return GREP_PATTERN_TYPE_FIXED;
84 else if (!strcmp(arg, "perl"))
85 return GREP_PATTERN_TYPE_PCRE;
86 die("bad %s argument: %s", opt, arg);
89 define_list_config_array_extra(color_grep_slots, {"match"});
92 * Read the configuration file once and store it in
93 * the grep_defaults template.
95 int grep_config(const char *var, const char *value, void *cb)
97 struct grep_opt *opt = &grep_defaults;
100 if (userdiff_config(var, value) < 0)
103 if (!strcmp(var, "grep.extendedregexp")) {
104 opt->extended_regexp_option = git_config_bool(var, value);
108 if (!strcmp(var, "grep.patterntype")) {
109 opt->pattern_type_option = parse_pattern_type_arg(var, value);
113 if (!strcmp(var, "grep.linenumber")) {
114 opt->linenum = git_config_bool(var, value);
117 if (!strcmp(var, "grep.column")) {
118 opt->columnnum = git_config_bool(var, value);
122 if (!strcmp(var, "grep.fullname")) {
123 opt->relative = !git_config_bool(var, value);
127 if (!strcmp(var, "color.grep"))
128 opt->color = git_config_colorbool(var, value);
129 if (!strcmp(var, "color.grep.match")) {
130 if (grep_config("color.grep.matchcontext", value, cb) < 0)
132 if (grep_config("color.grep.matchselected", value, cb) < 0)
134 } else if (skip_prefix(var, "color.grep.", &slot)) {
135 int i = LOOKUP_CONFIG(color_grep_slots, slot);
140 color = opt->colors[i];
142 return config_error_nonbool(var);
143 return color_parse(value, color);
149 * Initialize one instance of grep_opt and copy the
150 * default values from the template we read the configuration
151 * information in an earlier call to git_config(grep_config).
153 * If using PCRE, make sure that the library is configured
154 * to use the same allocator as Git (e.g. nedmalloc on Windows).
156 * Any allocated memory needs to be released in grep_destroy().
158 void grep_init(struct grep_opt *opt, struct repository *repo, const char *prefix)
160 struct grep_opt *def = &grep_defaults;
163 #if defined(USE_LIBPCRE2)
164 if (!pcre2_global_context)
165 pcre2_global_context = pcre2_general_context_create(
166 pcre2_malloc, pcre2_free, NULL);
170 pcre_malloc = malloc;
174 memset(opt, 0, sizeof(*opt));
176 opt->prefix = prefix;
177 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
178 opt->pattern_tail = &opt->pattern_list;
179 opt->header_tail = &opt->header_list;
181 opt->only_matching = def->only_matching;
182 opt->color = def->color;
183 opt->extended_regexp_option = def->extended_regexp_option;
184 opt->pattern_type_option = def->pattern_type_option;
185 opt->linenum = def->linenum;
186 opt->columnnum = def->columnnum;
187 opt->max_depth = def->max_depth;
188 opt->pathname = def->pathname;
189 opt->relative = def->relative;
190 opt->output = def->output;
192 for (i = 0; i < NR_GREP_COLORS; i++)
193 color_set(opt->colors[i], def->colors[i]);
196 void grep_destroy(void)
199 pcre2_general_context_free(pcre2_global_context);
203 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
206 * When committing to the pattern type by setting the relevant
207 * fields in grep_opt it's generally not necessary to zero out
208 * the fields we're not choosing, since they won't have been
209 * set by anything. The extended_regexp_option field is the
210 * only exception to this.
212 * This is because in the process of parsing grep.patternType
213 * & grep.extendedRegexp we set opt->pattern_type_option and
214 * opt->extended_regexp_option, respectively. We then
215 * internally use opt->extended_regexp_option to see if we're
216 * compiling an ERE. It must be unset if that's not actually
219 if (pattern_type != GREP_PATTERN_TYPE_ERE &&
220 opt->extended_regexp_option)
221 opt->extended_regexp_option = 0;
223 switch (pattern_type) {
224 case GREP_PATTERN_TYPE_UNSPECIFIED:
227 case GREP_PATTERN_TYPE_BRE:
230 case GREP_PATTERN_TYPE_ERE:
231 opt->extended_regexp_option = 1;
234 case GREP_PATTERN_TYPE_FIXED:
238 case GREP_PATTERN_TYPE_PCRE:
243 * It's important that pcre1 always be assigned to
244 * even when there's no USE_LIBPCRE* defined. We still
245 * call the PCRE stub function, it just dies with
246 * "cannot use Perl-compatible regexes[...]".
254 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
256 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
257 grep_set_pattern_type_option(pattern_type, opt);
258 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
259 grep_set_pattern_type_option(opt->pattern_type_option, opt);
260 else if (opt->extended_regexp_option)
262 * This branch *must* happen after setting from the
263 * opt->pattern_type_option above, we don't want
264 * grep.extendedRegexp to override grep.patternType!
266 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
269 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
270 const char *origin, int no,
271 enum grep_pat_token t,
272 enum grep_header_field field)
274 struct grep_pat *p = xcalloc(1, sizeof(*p));
275 p->pattern = xmemdupz(pat, patlen);
276 p->patternlen = patlen;
284 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
291 case GREP_PATTERN: /* atom */
292 case GREP_PATTERN_HEAD:
293 case GREP_PATTERN_BODY:
295 struct grep_pat *new_pat;
297 char *cp = p->pattern + p->patternlen, *nl = NULL;
298 while (++len <= p->patternlen) {
299 if (*(--cp) == '\n') {
306 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
307 p->no, p->token, p->field);
308 new_pat->next = p->next;
310 *tail = &new_pat->next;
313 p->patternlen -= len;
321 void append_header_grep_pattern(struct grep_opt *opt,
322 enum grep_header_field field, const char *pat)
324 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
325 GREP_PATTERN_HEAD, field);
326 if (field == GREP_HEADER_REFLOG)
327 opt->use_reflog_filter = 1;
328 do_append_grep_pat(&opt->header_tail, p);
331 void append_grep_pattern(struct grep_opt *opt, const char *pat,
332 const char *origin, int no, enum grep_pat_token t)
334 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
337 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
338 const char *origin, int no, enum grep_pat_token t)
340 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
341 do_append_grep_pat(&opt->pattern_tail, p);
344 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
346 struct grep_pat *pat;
347 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
350 ret->pattern_list = NULL;
351 ret->pattern_tail = &ret->pattern_list;
353 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
355 if(pat->token == GREP_PATTERN_HEAD)
356 append_header_grep_pattern(ret, pat->field,
359 append_grep_pat(ret, pat->pattern, pat->patternlen,
360 pat->origin, pat->no, pat->token);
366 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
372 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
374 xsnprintf(where, sizeof(where), "%s, ", p->origin);
378 die("%s'%s': %s", where, p->pattern, error);
381 static int is_fixed(const char *s, size_t len)
385 for (i = 0; i < len; i++) {
386 if (is_regex_special(s[i]))
394 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
398 int options = PCRE_MULTILINE;
399 int study_options = 0;
401 if (opt->ignore_case) {
402 if (!opt->ignore_locale && has_non_ascii(p->pattern))
403 p->pcre1_tables = pcre_maketables();
404 options |= PCRE_CASELESS;
406 if (!opt->ignore_locale && is_utf8_locale() && has_non_ascii(p->pattern))
407 options |= PCRE_UTF8;
409 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
411 if (!p->pcre1_regexp)
412 compile_regexp_failed(p, error);
414 #if defined(PCRE_CONFIG_JIT) && !defined(NO_LIBPCRE1_JIT)
415 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
417 fprintf(stderr, "pcre1_jit_on=%d\n", p->pcre1_jit_on);
420 study_options = PCRE_STUDY_JIT_COMPILE;
423 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, study_options, &error);
424 if (!p->pcre1_extra_info && error)
428 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
429 regmatch_t *match, int eflags)
431 int ovector[30], ret, flags = PCRE_NO_UTF8_CHECK;
433 if (eflags & REG_NOTBOL)
434 flags |= PCRE_NOTBOL;
436 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
437 eol - line, 0, flags, ovector,
438 ARRAY_SIZE(ovector));
440 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
441 die("pcre_exec failed with error code %d", ret);
444 match->rm_so = ovector[0];
445 match->rm_eo = ovector[1];
451 static void free_pcre1_regexp(struct grep_pat *p)
453 pcre_free(p->pcre1_regexp);
454 #ifdef PCRE_CONFIG_JIT
456 pcre_free_study(p->pcre1_extra_info);
459 pcre_free(p->pcre1_extra_info);
460 pcre_free((void *)p->pcre1_tables);
462 #else /* !USE_LIBPCRE1 */
463 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
465 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
468 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
469 regmatch_t *match, int eflags)
474 static void free_pcre1_regexp(struct grep_pat *p)
477 #endif /* !USE_LIBPCRE1 */
480 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
483 PCRE2_UCHAR errbuf[256];
484 PCRE2_SIZE erroffset;
485 int options = PCRE2_MULTILINE;
492 p->pcre2_compile_context = NULL;
494 /* pcre2_global_context is initialized in append_grep_pattern */
495 if (opt->ignore_case) {
496 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
497 if (!pcre2_global_context)
498 BUG("pcre2_global_context uninitialized");
499 p->pcre2_tables = pcre2_maketables(pcre2_global_context);
500 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
501 pcre2_set_character_tables(p->pcre2_compile_context,
504 options |= PCRE2_CASELESS;
506 if (!opt->ignore_locale && is_utf8_locale() && has_non_ascii(p->pattern) &&
507 !(!opt->ignore_case && (p->fixed || p->is_fixed)))
508 options |= PCRE2_UTF;
510 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
511 p->patternlen, options, &error, &erroffset,
512 p->pcre2_compile_context);
514 if (p->pcre2_pattern) {
515 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
516 if (!p->pcre2_match_data)
517 die("Couldn't allocate PCRE2 match data");
519 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
520 compile_regexp_failed(p, (const char *)&errbuf);
523 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
525 fprintf(stderr, "pcre2_jit_on=%d\n", p->pcre2_jit_on);
526 if (p->pcre2_jit_on) {
527 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
529 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
532 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
533 * tells us whether the library itself supports JIT,
534 * but to see whether we're going to be actually using
535 * JIT we need to extract PCRE2_INFO_JITSIZE from the
536 * pattern *after* we do pcre2_jit_compile() above.
538 * This is because if the pattern contains the
539 * (*NO_JIT) verb (see pcre2syntax(3))
540 * pcre2_jit_compile() will exit early with 0. If we
541 * then proceed to call pcre2_jit_match() further down
542 * the line instead of pcre2_match() we'll either
543 * segfault (pre PCRE 10.31) or run into a fatal error
546 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
548 BUG("pcre2_pattern_info() failed: %d", patinforet);
549 if (jitsizearg == 0) {
552 fprintf(stderr, "pcre2_jit_on=%d: (*NO_JIT) in regex\n",
559 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
560 regmatch_t *match, int eflags)
564 PCRE2_UCHAR errbuf[256];
566 if (eflags & REG_NOTBOL)
567 flags |= PCRE2_NOTBOL;
570 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
571 eol - line, 0, flags, p->pcre2_match_data,
574 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
575 eol - line, 0, flags, p->pcre2_match_data,
578 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
579 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
580 die("%s failed with error code %d: %s",
581 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
585 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
587 match->rm_so = (int)ovector[0];
588 match->rm_eo = (int)ovector[1];
594 static void free_pcre2_pattern(struct grep_pat *p)
596 pcre2_compile_context_free(p->pcre2_compile_context);
597 pcre2_code_free(p->pcre2_pattern);
598 pcre2_match_data_free(p->pcre2_match_data);
599 free((void *)p->pcre2_tables);
601 #else /* !USE_LIBPCRE2 */
602 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
605 * Unreachable until USE_LIBPCRE2 becomes synonymous with
606 * USE_LIBPCRE. See the sibling comment in
607 * grep_set_pattern_type_option().
609 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
612 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
613 regmatch_t *match, int eflags)
618 static void free_pcre2_pattern(struct grep_pat *p)
622 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
624 struct strbuf sb = STRBUF_INIT;
628 basic_regex_quote_buf(&sb, p->pattern);
629 if (opt->ignore_case)
630 regflags |= REG_ICASE;
631 err = regcomp(&p->regexp, sb.buf, regflags);
633 fprintf(stderr, "fixed %s\n", sb.buf);
637 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
638 compile_regexp_failed(p, errbuf);
641 #endif /* !USE_LIBPCRE2 */
643 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
646 int regflags = REG_NEWLINE;
648 p->word_regexp = opt->word_regexp;
649 p->ignore_case = opt->ignore_case;
650 p->fixed = opt->fixed;
652 if (memchr(p->pattern, 0, p->patternlen) && !opt->pcre2)
653 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
655 p->is_fixed = is_fixed(p->pattern, p->patternlen);
657 if (!p->fixed && !p->is_fixed) {
658 const char *no_jit = "(*NO_JIT)";
659 const int no_jit_len = strlen(no_jit);
660 if (starts_with(p->pattern, no_jit) &&
661 is_fixed(p->pattern + no_jit_len,
662 p->patternlen - no_jit_len))
666 if (p->fixed || p->is_fixed) {
670 compile_pcre2_pattern(p, opt);
673 * E.g. t7811-grep-open.sh relies on the
674 * pattern being restored.
676 char *old_pattern = p->pattern;
677 size_t old_patternlen = p->patternlen;
678 struct strbuf sb = STRBUF_INIT;
681 * There is the PCRE2_LITERAL flag, but it's
682 * only in PCRE v2 10.30 and later. Needing to
683 * ifdef our way around that and dealing with
684 * it + PCRE2_MULTILINE being an error is more
685 * complex than just quoting this ourselves.
687 strbuf_add(&sb, "\\Q", 2);
688 strbuf_add(&sb, p->pattern, p->patternlen);
689 strbuf_add(&sb, "\\E", 2);
692 p->patternlen = sb.len;
693 compile_pcre2_pattern(p, opt);
694 p->pattern = old_pattern;
695 p->patternlen = old_patternlen;
698 #else /* !USE_LIBPCRE2 */
699 compile_fixed_regexp(p, opt);
700 #endif /* !USE_LIBPCRE2 */
705 compile_pcre2_pattern(p, opt);
710 compile_pcre1_regexp(p, opt);
715 regflags |= REG_ICASE;
716 if (opt->extended_regexp_option)
717 regflags |= REG_EXTENDED;
718 err = regcomp(&p->regexp, p->pattern, regflags);
721 regerror(err, &p->regexp, errbuf, 1024);
722 compile_regexp_failed(p, errbuf);
726 static struct grep_expr *compile_pattern_or(struct grep_pat **);
727 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
736 case GREP_PATTERN: /* atom */
737 case GREP_PATTERN_HEAD:
738 case GREP_PATTERN_BODY:
739 x = xcalloc(1, sizeof (struct grep_expr));
740 x->node = GREP_NODE_ATOM;
744 case GREP_OPEN_PAREN:
746 x = compile_pattern_or(list);
747 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
748 die("unmatched parenthesis");
749 *list = (*list)->next;
756 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
767 die("--not not followed by pattern expression");
769 x = xcalloc(1, sizeof (struct grep_expr));
770 x->node = GREP_NODE_NOT;
771 x->u.unary = compile_pattern_not(list);
773 die("--not followed by non pattern expression");
776 return compile_pattern_atom(list);
780 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
783 struct grep_expr *x, *y, *z;
785 x = compile_pattern_not(list);
787 if (p && p->token == GREP_AND) {
789 die("--and not followed by pattern expression");
791 y = compile_pattern_and(list);
793 die("--and not followed by pattern expression");
794 z = xcalloc(1, sizeof (struct grep_expr));
795 z->node = GREP_NODE_AND;
796 z->u.binary.left = x;
797 z->u.binary.right = y;
803 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
806 struct grep_expr *x, *y, *z;
808 x = compile_pattern_and(list);
810 if (x && p && p->token != GREP_CLOSE_PAREN) {
811 y = compile_pattern_or(list);
813 die("not a pattern expression %s", p->pattern);
814 z = xcalloc(1, sizeof (struct grep_expr));
815 z->node = GREP_NODE_OR;
816 z->u.binary.left = x;
817 z->u.binary.right = y;
823 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
825 return compile_pattern_or(list);
828 static void indent(int in)
834 static void dump_grep_pat(struct grep_pat *p)
837 case GREP_AND: fprintf(stderr, "*and*"); break;
838 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
839 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
840 case GREP_NOT: fprintf(stderr, "*not*"); break;
841 case GREP_OR: fprintf(stderr, "*or*"); break;
843 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
844 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
845 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
850 case GREP_PATTERN_HEAD:
851 fprintf(stderr, "<head %d>", p->field); break;
852 case GREP_PATTERN_BODY:
853 fprintf(stderr, "<body>"); break;
857 case GREP_PATTERN_HEAD:
858 case GREP_PATTERN_BODY:
860 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
866 static void dump_grep_expression_1(struct grep_expr *x, int in)
871 fprintf(stderr, "true\n");
874 dump_grep_pat(x->u.atom);
877 fprintf(stderr, "(not\n");
878 dump_grep_expression_1(x->u.unary, in+1);
880 fprintf(stderr, ")\n");
883 fprintf(stderr, "(and\n");
884 dump_grep_expression_1(x->u.binary.left, in+1);
885 dump_grep_expression_1(x->u.binary.right, in+1);
887 fprintf(stderr, ")\n");
890 fprintf(stderr, "(or\n");
891 dump_grep_expression_1(x->u.binary.left, in+1);
892 dump_grep_expression_1(x->u.binary.right, in+1);
894 fprintf(stderr, ")\n");
899 static void dump_grep_expression(struct grep_opt *opt)
901 struct grep_expr *x = opt->pattern_expression;
904 fprintf(stderr, "[all-match]\n");
905 dump_grep_expression_1(x, 0);
909 static struct grep_expr *grep_true_expr(void)
911 struct grep_expr *z = xcalloc(1, sizeof(*z));
912 z->node = GREP_NODE_TRUE;
916 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
918 struct grep_expr *z = xcalloc(1, sizeof(*z));
919 z->node = GREP_NODE_OR;
920 z->u.binary.left = left;
921 z->u.binary.right = right;
925 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
928 struct grep_expr *header_expr;
929 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
930 enum grep_header_field fld;
932 if (!opt->header_list)
935 for (p = opt->header_list; p; p = p->next) {
936 if (p->token != GREP_PATTERN_HEAD)
937 BUG("a non-header pattern in grep header list.");
938 if (p->field < GREP_HEADER_FIELD_MIN ||
939 GREP_HEADER_FIELD_MAX <= p->field)
940 BUG("unknown header field %d", p->field);
941 compile_regexp(p, opt);
944 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
945 header_group[fld] = NULL;
947 for (p = opt->header_list; p; p = p->next) {
949 struct grep_pat *pp = p;
951 h = compile_pattern_atom(&pp);
952 if (!h || pp != p->next)
953 BUG("malformed header expr");
954 if (!header_group[p->field]) {
955 header_group[p->field] = h;
958 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
963 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
964 if (!header_group[fld])
967 header_expr = grep_true_expr();
968 header_expr = grep_or_expr(header_group[fld], header_expr);
973 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
975 struct grep_expr *z = x;
978 assert(x->node == GREP_NODE_OR);
979 if (x->u.binary.right &&
980 x->u.binary.right->node == GREP_NODE_TRUE) {
981 x->u.binary.right = y;
984 x = x->u.binary.right;
989 static void compile_grep_patterns_real(struct grep_opt *opt)
992 struct grep_expr *header_expr = prep_header_patterns(opt);
994 for (p = opt->pattern_list; p; p = p->next) {
996 case GREP_PATTERN: /* atom */
997 case GREP_PATTERN_HEAD:
998 case GREP_PATTERN_BODY:
999 compile_regexp(p, opt);
1007 if (opt->all_match || header_expr)
1009 else if (!opt->extended && !opt->debug)
1012 p = opt->pattern_list;
1014 opt->pattern_expression = compile_pattern_expr(&p);
1016 die("incomplete pattern expression: %s", p->pattern);
1021 if (!opt->pattern_expression)
1022 opt->pattern_expression = header_expr;
1023 else if (opt->all_match)
1024 opt->pattern_expression = grep_splice_or(header_expr,
1025 opt->pattern_expression);
1027 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
1032 void compile_grep_patterns(struct grep_opt *opt)
1034 compile_grep_patterns_real(opt);
1036 dump_grep_expression(opt);
1039 static void free_pattern_expr(struct grep_expr *x)
1042 case GREP_NODE_TRUE:
1043 case GREP_NODE_ATOM:
1046 free_pattern_expr(x->u.unary);
1050 free_pattern_expr(x->u.binary.left);
1051 free_pattern_expr(x->u.binary.right);
1057 void free_grep_patterns(struct grep_opt *opt)
1059 struct grep_pat *p, *n;
1061 for (p = opt->pattern_list; p; p = n) {
1064 case GREP_PATTERN: /* atom */
1065 case GREP_PATTERN_HEAD:
1066 case GREP_PATTERN_BODY:
1067 if (p->pcre1_regexp)
1068 free_pcre1_regexp(p);
1069 else if (p->pcre2_pattern)
1070 free_pcre2_pattern(p);
1072 regfree(&p->regexp);
1083 free_pattern_expr(opt->pattern_expression);
1086 static char *end_of_line(char *cp, unsigned long *left)
1088 unsigned long l = *left;
1089 while (l && *cp != '\n') {
1097 static int word_char(char ch)
1099 return isalnum(ch) || ch == '_';
1102 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1105 if (want_color(opt->color) && color && color[0]) {
1106 opt->output(opt, color, strlen(color));
1107 opt->output(opt, data, size);
1108 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1110 opt->output(opt, data, size);
1113 static void output_sep(struct grep_opt *opt, char sign)
1115 if (opt->null_following_name)
1116 opt->output(opt, "\0", 1);
1118 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
1121 static void show_name(struct grep_opt *opt, const char *name)
1123 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1124 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1127 static int patmatch(struct grep_pat *p, char *line, char *eol,
1128 regmatch_t *match, int eflags)
1132 if (p->pcre1_regexp)
1133 hit = !pcre1match(p, line, eol, match, eflags);
1134 else if (p->pcre2_pattern)
1135 hit = !pcre2match(p, line, eol, match, eflags);
1137 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1143 static int strip_timestamp(char *bol, char **eol_p)
1148 while (bol < --eol) {
1162 } header_field[] = {
1164 { "committer ", 10 },
1168 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1169 enum grep_context ctx,
1170 regmatch_t *pmatch, int eflags)
1174 const char *start = bol;
1176 if ((p->token != GREP_PATTERN) &&
1177 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1180 if (p->token == GREP_PATTERN_HEAD) {
1183 assert(p->field < ARRAY_SIZE(header_field));
1184 field = header_field[p->field].field;
1185 len = header_field[p->field].len;
1186 if (strncmp(bol, field, len))
1190 case GREP_HEADER_AUTHOR:
1191 case GREP_HEADER_COMMITTER:
1192 saved_ch = strip_timestamp(bol, &eol);
1200 hit = patmatch(p, bol, eol, pmatch, eflags);
1202 if (hit && p->word_regexp) {
1203 if ((pmatch[0].rm_so < 0) ||
1204 (eol - bol) < pmatch[0].rm_so ||
1205 (pmatch[0].rm_eo < 0) ||
1206 (eol - bol) < pmatch[0].rm_eo)
1207 die("regexp returned nonsense");
1209 /* Match beginning must be either beginning of the
1210 * line, or at word boundary (i.e. the last char must
1211 * not be a word char). Similarly, match end must be
1212 * either end of the line, or at word boundary
1213 * (i.e. the next char must not be a word char).
1215 if ( ((pmatch[0].rm_so == 0) ||
1216 !word_char(bol[pmatch[0].rm_so-1])) &&
1217 ((pmatch[0].rm_eo == (eol-bol)) ||
1218 !word_char(bol[pmatch[0].rm_eo])) )
1223 /* Words consist of at least one character. */
1224 if (pmatch->rm_so == pmatch->rm_eo)
1227 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1228 /* There could be more than one match on the
1229 * line, and the first match might not be
1230 * strict word match. But later ones could be!
1231 * Forward to the next possible start, i.e. the
1232 * next position following a non-word char.
1234 bol = pmatch[0].rm_so + bol + 1;
1235 while (word_char(bol[-1]) && bol < eol)
1237 eflags |= REG_NOTBOL;
1242 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1245 pmatch[0].rm_so += bol - start;
1246 pmatch[0].rm_eo += bol - start;
1251 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
1252 char *eol, enum grep_context ctx, ssize_t *col,
1253 ssize_t *icol, int collect_hits)
1258 die("Not a valid grep expression");
1260 case GREP_NODE_TRUE:
1263 case GREP_NODE_ATOM:
1266 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1268 if (h && (*col < 0 || tmp.rm_so < *col))
1274 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1276 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1280 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1282 if (h || opt->columnnum) {
1284 * Don't short-circuit AND when given --column, since a
1285 * NOT earlier in the tree may turn this into an OR. In
1286 * this case, see the below comment.
1288 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1293 if (!(collect_hits || opt->columnnum)) {
1295 * Don't short-circuit OR when given --column (or
1296 * collecting hits) to ensure we don't skip a later
1297 * child that would produce an earlier match.
1299 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1300 ctx, col, icol, 0) ||
1301 match_expr_eval(opt, x->u.binary.right, bol,
1302 eol, ctx, col, icol, 0));
1304 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1307 x->u.binary.left->hit |= h;
1308 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1309 icol, collect_hits);
1312 die("Unexpected node type (internal error) %d", x->node);
1319 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1320 enum grep_context ctx, ssize_t *col,
1321 ssize_t *icol, int collect_hits)
1323 struct grep_expr *x = opt->pattern_expression;
1324 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1327 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1328 ssize_t *col, ssize_t *icol,
1329 enum grep_context ctx, int collect_hits)
1335 return match_expr(opt, bol, eol, ctx, col, icol,
1338 /* we do not call with collect_hits without being extended */
1339 for (p = opt->pattern_list; p; p = p->next) {
1341 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1343 if (!opt->columnnum) {
1345 * Without --column, any single match on a line
1346 * is enough to know that it needs to be
1347 * printed. With --column, scan _all_ patterns
1348 * to find the earliest.
1352 if (*col < 0 || tmp.rm_so < *col)
1359 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1360 enum grep_context ctx,
1361 regmatch_t *pmatch, int eflags)
1365 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1367 if (match.rm_so < 0 || match.rm_eo < 0)
1369 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1370 if (match.rm_so > pmatch->rm_so)
1372 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1375 pmatch->rm_so = match.rm_so;
1376 pmatch->rm_eo = match.rm_eo;
1380 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1381 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1386 pmatch->rm_so = pmatch->rm_eo = -1;
1388 for (p = opt->pattern_list; p; p = p->next) {
1390 case GREP_PATTERN: /* atom */
1391 case GREP_PATTERN_HEAD:
1392 case GREP_PATTERN_BODY:
1393 hit |= match_next_pattern(p, bol, eol, ctx,
1404 static void show_line_header(struct grep_opt *opt, const char *name,
1405 unsigned lno, ssize_t cno, char sign)
1407 if (opt->heading && opt->last_shown == 0) {
1408 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1409 opt->output(opt, "\n", 1);
1411 opt->last_shown = lno;
1413 if (!opt->heading && opt->pathname) {
1414 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1415 output_sep(opt, sign);
1419 xsnprintf(buf, sizeof(buf), "%d", lno);
1420 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1421 output_sep(opt, sign);
1424 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1425 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1426 * being called with a context line.
1428 if (opt->columnnum && cno) {
1430 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1431 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1432 output_sep(opt, sign);
1436 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1437 const char *name, unsigned lno, ssize_t cno, char sign)
1439 int rest = eol - bol;
1440 const char *match_color = NULL;
1441 const char *line_color = NULL;
1443 if (opt->file_break && opt->last_shown == 0) {
1444 if (opt->show_hunk_mark)
1445 opt->output(opt, "\n", 1);
1446 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1447 if (opt->last_shown == 0) {
1448 if (opt->show_hunk_mark) {
1449 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1450 opt->output(opt, "\n", 1);
1452 } else if (lno > opt->last_shown + 1) {
1453 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1454 opt->output(opt, "\n", 1);
1457 if (!opt->only_matching) {
1459 * In case the line we're being called with contains more than
1460 * one match, leave printing each header to the loop below.
1462 show_line_header(opt, name, lno, cno, sign);
1464 if (opt->color || opt->only_matching) {
1466 enum grep_context ctx = GREP_CONTEXT_BODY;
1472 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1474 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1476 line_color = opt->colors[GREP_COLOR_SELECTED];
1477 else if (sign == '-')
1478 line_color = opt->colors[GREP_COLOR_CONTEXT];
1479 else if (sign == '=')
1480 line_color = opt->colors[GREP_COLOR_FUNCTION];
1483 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1484 if (match.rm_so == match.rm_eo)
1487 if (opt->only_matching)
1488 show_line_header(opt, name, lno, cno, sign);
1490 output_color(opt, bol, match.rm_so, line_color);
1491 output_color(opt, bol + match.rm_so,
1492 match.rm_eo - match.rm_so, match_color);
1493 if (opt->only_matching)
1494 opt->output(opt, "\n", 1);
1497 rest -= match.rm_eo;
1498 eflags = REG_NOTBOL;
1502 if (!opt->only_matching) {
1503 output_color(opt, bol, rest, line_color);
1504 opt->output(opt, "\n", 1);
1511 * This lock protects access to the gitattributes machinery, which is
1514 pthread_mutex_t grep_attr_mutex;
1516 static inline void grep_attr_lock(void)
1519 pthread_mutex_lock(&grep_attr_mutex);
1522 static inline void grep_attr_unlock(void)
1525 pthread_mutex_unlock(&grep_attr_mutex);
1528 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1530 xdemitconf_t *xecfg = opt->priv;
1531 if (xecfg && !xecfg->find_func) {
1532 grep_source_load_driver(gs, opt->repo->index);
1533 if (gs->driver->funcname.pattern) {
1534 const struct userdiff_funcname *pe = &gs->driver->funcname;
1535 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1537 xecfg = opt->priv = NULL;
1543 return xecfg->find_func(bol, eol - bol, buf, 1,
1544 xecfg->find_func_priv) >= 0;
1549 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1554 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1555 char *bol, unsigned lno)
1557 while (bol > gs->buf) {
1560 while (bol > gs->buf && bol[-1] != '\n')
1564 if (lno <= opt->last_shown)
1567 if (match_funcname(opt, gs, bol, eol)) {
1568 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1574 static int is_empty_line(const char *bol, const char *eol);
1576 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1577 char *bol, char *end, unsigned lno)
1579 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1580 int funcname_needed = !!opt->funcname, comment_needed = 0;
1582 if (opt->pre_context < lno)
1583 from = lno - opt->pre_context;
1584 if (from <= opt->last_shown)
1585 from = opt->last_shown + 1;
1587 if (opt->funcbody) {
1588 if (match_funcname(opt, gs, bol, end))
1591 funcname_needed = 1;
1592 from = opt->last_shown + 1;
1596 while (bol > gs->buf && cur > from) {
1597 char *next_bol = bol;
1600 while (bol > gs->buf && bol[-1] != '\n')
1603 if (comment_needed && (is_empty_line(bol, eol) ||
1604 match_funcname(opt, gs, bol, eol))) {
1613 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1615 funcname_needed = 0;
1623 /* We need to look even further back to find a function signature. */
1624 if (opt->funcname && funcname_needed)
1625 show_funcname_line(opt, gs, bol, cur);
1629 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1631 while (*eol != '\n')
1633 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1639 static int should_lookahead(struct grep_opt *opt)
1644 return 0; /* punt for too complex stuff */
1647 for (p = opt->pattern_list; p; p = p->next) {
1648 if (p->token != GREP_PATTERN)
1649 return 0; /* punt for "header only" and stuff */
1654 static int look_ahead(struct grep_opt *opt,
1655 unsigned long *left_p,
1659 unsigned lno = *lno_p;
1662 char *sp, *last_bol;
1663 regoff_t earliest = -1;
1665 for (p = opt->pattern_list; p; p = p->next) {
1669 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1670 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1672 if (earliest < 0 || m.rm_so < earliest)
1677 *bol_p = bol + *left_p;
1681 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1682 ; /* find the beginning of the line */
1685 for (sp = bol; sp < last_bol; sp++) {
1689 *left_p -= last_bol - bol;
1695 static int fill_textconv_grep(struct repository *r,
1696 struct userdiff_driver *driver,
1697 struct grep_source *gs)
1699 struct diff_filespec *df;
1703 if (!driver || !driver->textconv)
1704 return grep_source_load(gs);
1707 * The textconv interface is intimately tied to diff_filespecs, so we
1708 * have to pretend to be one. If we could unify the grep_source
1709 * and diff_filespec structs, this mess could just go away.
1711 df = alloc_filespec(gs->path);
1713 case GREP_SOURCE_OID:
1714 fill_filespec(df, gs->identifier, 1, 0100644);
1716 case GREP_SOURCE_FILE:
1717 fill_filespec(df, &null_oid, 0, 0100644);
1720 BUG("attempt to textconv something without a path?");
1724 * fill_textconv is not remotely thread-safe; it modifies the global
1725 * diff tempfile structure, writes to the_repo's odb and might
1726 * internally call thread-unsafe functions such as the
1727 * prepare_packed_git() lazy-initializator. Because of the last two, we
1728 * must ensure mutual exclusion between this call and the object reading
1729 * API, thus we use obj_read_lock() here.
1731 * TODO: allowing text conversion to run in parallel with object
1732 * reading operations might increase performance in the multithreaded
1733 * non-worktreee git-grep with --textconv.
1736 size = fill_textconv(r, driver, df, &buf);
1741 * The normal fill_textconv usage by the diff machinery would just keep
1742 * the textconv'd buf separate from the diff_filespec. But much of the
1743 * grep code passes around a grep_source and assumes that its "buf"
1744 * pointer is the beginning of the thing we are searching. So let's
1745 * install our textconv'd version into the grep_source, taking care not
1746 * to leak any existing buffer.
1748 grep_source_clear_data(gs);
1755 static int is_empty_line(const char *bol, const char *eol)
1757 while (bol < eol && isspace(*bol))
1762 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1765 char *peek_bol = NULL;
1768 unsigned last_hit = 0;
1769 int binary_match_only = 0;
1771 int try_lookahead = 0;
1772 int show_function = 0;
1773 struct userdiff_driver *textconv = NULL;
1774 enum grep_context ctx = GREP_CONTEXT_HEAD;
1777 if (!opt->status_only && gs->name == NULL)
1778 BUG("grep call which could print a name requires "
1779 "grep_source.name be non-NULL");
1782 opt->output = std_output;
1784 if (opt->pre_context || opt->post_context || opt->file_break ||
1786 /* Show hunk marks, except for the first file. */
1787 if (opt->last_shown)
1788 opt->show_hunk_mark = 1;
1790 * If we're using threads then we can't easily identify
1791 * the first file. Always put hunk marks in that case
1792 * and skip the very first one later in work_done().
1794 if (opt->output != std_output)
1795 opt->show_hunk_mark = 1;
1797 opt->last_shown = 0;
1799 if (opt->allow_textconv) {
1800 grep_source_load_driver(gs, opt->repo->index);
1802 * We might set up the shared textconv cache data here, which
1803 * is not thread-safe. Also, get_oid_with_context() and
1804 * parse_object() might be internally called. As they are not
1805 * currently thread-safe and might be racy with object reading,
1806 * obj_read_lock() must be called.
1810 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1816 * We know the result of a textconv is text, so we only have to care
1817 * about binary handling if we are not using it.
1820 switch (opt->binary) {
1821 case GREP_BINARY_DEFAULT:
1822 if (grep_source_is_binary(gs, opt->repo->index))
1823 binary_match_only = 1;
1825 case GREP_BINARY_NOMATCH:
1826 if (grep_source_is_binary(gs, opt->repo->index))
1827 return 0; /* Assume unmatch */
1829 case GREP_BINARY_TEXT:
1832 BUG("unknown binary handling mode");
1836 memset(&xecfg, 0, sizeof(xecfg));
1839 try_lookahead = should_lookahead(opt);
1841 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1850 ssize_t col = -1, icol = -1;
1853 * look_ahead() skips quickly to the line that possibly
1854 * has the next hit; don't call it if we need to do
1855 * something more than just skipping the current line
1856 * in response to an unmatch for the current line. E.g.
1857 * inside a post-context window, we will show the current
1858 * line as a context around the previous hit when it
1863 && (show_function ||
1864 lno <= last_hit + opt->post_context))
1865 && look_ahead(opt, &left, &lno, &bol))
1867 eol = end_of_line(bol, &left);
1871 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1872 ctx = GREP_CONTEXT_BODY;
1874 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1880 /* "grep -v -e foo -e bla" should list lines
1881 * that do not have either, so inversion should
1886 if (opt->unmatch_name_only) {
1893 if (opt->status_only)
1895 if (opt->name_only) {
1896 show_name(opt, gs->name);
1901 if (binary_match_only) {
1902 opt->output(opt, "Binary file ", 12);
1903 output_color(opt, gs->name, strlen(gs->name),
1904 opt->colors[GREP_COLOR_FILENAME]);
1905 opt->output(opt, " matches\n", 9);
1908 /* Hit at this line. If we haven't shown the
1909 * pre-context lines, we would need to show them.
1911 if (opt->pre_context || opt->funcbody)
1912 show_pre_context(opt, gs, bol, eol, lno);
1913 else if (opt->funcname)
1914 show_funcname_line(opt, gs, bol, lno);
1915 cno = opt->invert ? icol : col;
1918 * A negative cno indicates that there was no
1919 * match on the line. We are thus inverted and
1920 * being asked to show all lines that _don't_
1921 * match a given expression. Therefore, set cno
1922 * to 0 to suggest the whole line matches.
1926 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1932 if (show_function && (!peek_bol || peek_bol < bol)) {
1933 unsigned long peek_left = left;
1934 char *peek_eol = eol;
1937 * Trailing empty lines are not interesting.
1938 * Peek past them to see if they belong to the
1939 * body of the current function.
1942 while (is_empty_line(peek_bol, peek_eol)) {
1943 peek_bol = peek_eol + 1;
1944 peek_eol = end_of_line(peek_bol, &peek_left);
1947 if (match_funcname(opt, gs, peek_bol, peek_eol))
1950 if (show_function ||
1951 (last_hit && lno <= last_hit + opt->post_context)) {
1952 /* If the last hit is within the post context,
1953 * we need to show this line.
1955 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1969 if (opt->status_only)
1970 return opt->unmatch_name_only;
1971 if (opt->unmatch_name_only) {
1972 /* We did not see any hit, so we want to show this */
1973 show_name(opt, gs->name);
1977 xdiff_clear_find_func(&xecfg);
1981 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1982 * which feels mostly useless but sometimes useful. Maybe
1983 * make it another option? For now suppress them.
1985 if (opt->count && count) {
1987 if (opt->pathname) {
1988 output_color(opt, gs->name, strlen(gs->name),
1989 opt->colors[GREP_COLOR_FILENAME]);
1990 output_sep(opt, ':');
1992 xsnprintf(buf, sizeof(buf), "%u\n", count);
1993 opt->output(opt, buf, strlen(buf));
1999 static void clr_hit_marker(struct grep_expr *x)
2001 /* All-hit markers are meaningful only at the very top level
2006 if (x->node != GREP_NODE_OR)
2008 x->u.binary.left->hit = 0;
2009 x = x->u.binary.right;
2013 static int chk_hit_marker(struct grep_expr *x)
2015 /* Top level nodes have hit markers. See if they all are hits */
2017 if (x->node != GREP_NODE_OR)
2019 if (!x->u.binary.left->hit)
2021 x = x->u.binary.right;
2025 int grep_source(struct grep_opt *opt, struct grep_source *gs)
2028 * we do not have to do the two-pass grep when we do not check
2029 * buffer-wide "all-match".
2031 if (!opt->all_match)
2032 return grep_source_1(opt, gs, 0);
2034 /* Otherwise the toplevel "or" terms hit a bit differently.
2035 * We first clear hit markers from them.
2037 clr_hit_marker(opt->pattern_expression);
2038 grep_source_1(opt, gs, 1);
2040 if (!chk_hit_marker(opt->pattern_expression))
2043 return grep_source_1(opt, gs, 0);
2046 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
2048 struct grep_source gs;
2051 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
2055 r = grep_source(opt, &gs);
2057 grep_source_clear(&gs);
2061 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
2062 const char *name, const char *path,
2063 const void *identifier)
2066 gs->name = xstrdup_or_null(name);
2067 gs->path = xstrdup_or_null(path);
2073 case GREP_SOURCE_FILE:
2074 gs->identifier = xstrdup(identifier);
2076 case GREP_SOURCE_OID:
2077 gs->identifier = oiddup(identifier);
2079 case GREP_SOURCE_BUF:
2080 gs->identifier = NULL;
2085 void grep_source_clear(struct grep_source *gs)
2087 FREE_AND_NULL(gs->name);
2088 FREE_AND_NULL(gs->path);
2089 FREE_AND_NULL(gs->identifier);
2090 grep_source_clear_data(gs);
2093 void grep_source_clear_data(struct grep_source *gs)
2096 case GREP_SOURCE_FILE:
2097 case GREP_SOURCE_OID:
2098 FREE_AND_NULL(gs->buf);
2101 case GREP_SOURCE_BUF:
2102 /* leave user-provided buf intact */
2107 static int grep_source_load_oid(struct grep_source *gs)
2109 enum object_type type;
2111 gs->buf = read_object_file(gs->identifier, &type, &gs->size);
2113 return error(_("'%s': unable to read %s"),
2115 oid_to_hex(gs->identifier));
2119 static int grep_source_load_file(struct grep_source *gs)
2121 const char *filename = gs->identifier;
2127 if (lstat(filename, &st) < 0) {
2129 if (errno != ENOENT)
2130 error_errno(_("failed to stat '%s'"), filename);
2133 if (!S_ISREG(st.st_mode))
2135 size = xsize_t(st.st_size);
2136 i = open(filename, O_RDONLY);
2139 data = xmallocz(size);
2140 if (st.st_size != read_in_full(i, data, size)) {
2141 error_errno(_("'%s': short read"), filename);
2153 static int grep_source_load(struct grep_source *gs)
2159 case GREP_SOURCE_FILE:
2160 return grep_source_load_file(gs);
2161 case GREP_SOURCE_OID:
2162 return grep_source_load_oid(gs);
2163 case GREP_SOURCE_BUF:
2164 return gs->buf ? 0 : -1;
2166 BUG("invalid grep_source type to load");
2169 void grep_source_load_driver(struct grep_source *gs,
2170 struct index_state *istate)
2177 gs->driver = userdiff_find_by_path(istate, gs->path);
2179 gs->driver = userdiff_find_by_name("default");
2183 static int grep_source_is_binary(struct grep_source *gs,
2184 struct index_state *istate)
2186 grep_source_load_driver(gs, istate);
2187 if (gs->driver->binary != -1)
2188 return gs->driver->binary;
2190 if (!grep_source_load(gs))
2191 return buffer_is_binary(gs->buf, gs->size);