4 #include "xdiff-interface.h"
10 static int grep_source_load(struct grep_source *gs);
11 static int grep_source_is_binary(struct grep_source *gs);
13 static struct grep_opt grep_defaults;
15 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
17 fwrite(buf, size, 1, stdout);
21 * Initialize the grep_defaults template with hardcoded defaults.
22 * We could let the compiler do this, but without C99 initializers
23 * the code gets unwieldy and unreadable, so...
25 void init_grep_defaults(void)
27 struct grep_opt *opt = &grep_defaults;
34 memset(opt, 0, sizeof(*opt));
37 opt->regflags = REG_NEWLINE;
39 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
40 opt->extended_regexp_option = 0;
41 color_set(opt->color_context, "");
42 color_set(opt->color_filename, "");
43 color_set(opt->color_function, "");
44 color_set(opt->color_lineno, "");
45 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
46 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_selected, "");
48 color_set(opt->color_sep, GIT_COLOR_CYAN);
50 opt->output = std_output;
53 static int parse_pattern_type_arg(const char *opt, const char *arg)
55 if (!strcmp(arg, "default"))
56 return GREP_PATTERN_TYPE_UNSPECIFIED;
57 else if (!strcmp(arg, "basic"))
58 return GREP_PATTERN_TYPE_BRE;
59 else if (!strcmp(arg, "extended"))
60 return GREP_PATTERN_TYPE_ERE;
61 else if (!strcmp(arg, "fixed"))
62 return GREP_PATTERN_TYPE_FIXED;
63 else if (!strcmp(arg, "perl"))
64 return GREP_PATTERN_TYPE_PCRE;
65 die("bad %s argument: %s", opt, arg);
69 * Read the configuration file once and store it in
70 * the grep_defaults template.
72 int grep_config(const char *var, const char *value, void *cb)
74 struct grep_opt *opt = &grep_defaults;
77 if (userdiff_config(var, value) < 0)
80 if (!strcmp(var, "grep.extendedregexp")) {
81 if (git_config_bool(var, value))
82 opt->extended_regexp_option = 1;
84 opt->extended_regexp_option = 0;
88 if (!strcmp(var, "grep.patterntype")) {
89 opt->pattern_type_option = parse_pattern_type_arg(var, value);
93 if (!strcmp(var, "grep.linenumber")) {
94 opt->linenum = git_config_bool(var, value);
98 if (!strcmp(var, "grep.fullname")) {
99 opt->relative = !git_config_bool(var, value);
103 if (!strcmp(var, "color.grep"))
104 opt->color = git_config_colorbool(var, value);
105 else if (!strcmp(var, "color.grep.context"))
106 color = opt->color_context;
107 else if (!strcmp(var, "color.grep.filename"))
108 color = opt->color_filename;
109 else if (!strcmp(var, "color.grep.function"))
110 color = opt->color_function;
111 else if (!strcmp(var, "color.grep.linenumber"))
112 color = opt->color_lineno;
113 else if (!strcmp(var, "color.grep.matchcontext"))
114 color = opt->color_match_context;
115 else if (!strcmp(var, "color.grep.matchselected"))
116 color = opt->color_match_selected;
117 else if (!strcmp(var, "color.grep.selected"))
118 color = opt->color_selected;
119 else if (!strcmp(var, "color.grep.separator"))
120 color = opt->color_sep;
121 else if (!strcmp(var, "color.grep.match")) {
124 return config_error_nonbool(var);
125 rc |= color_parse(value, opt->color_match_context);
126 rc |= color_parse(value, opt->color_match_selected);
132 return config_error_nonbool(var);
133 return color_parse(value, color);
139 * Initialize one instance of grep_opt and copy the
140 * default values from the template we read the configuration
141 * information in an earlier call to git_config(grep_config).
143 void grep_init(struct grep_opt *opt, const char *prefix)
145 struct grep_opt *def = &grep_defaults;
147 memset(opt, 0, sizeof(*opt));
148 opt->prefix = prefix;
149 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
150 opt->pattern_tail = &opt->pattern_list;
151 opt->header_tail = &opt->header_list;
153 opt->color = def->color;
154 opt->extended_regexp_option = def->extended_regexp_option;
155 opt->pattern_type_option = def->pattern_type_option;
156 opt->linenum = def->linenum;
157 opt->max_depth = def->max_depth;
158 opt->pathname = def->pathname;
159 opt->regflags = def->regflags;
160 opt->relative = def->relative;
161 opt->output = def->output;
163 color_set(opt->color_context, def->color_context);
164 color_set(opt->color_filename, def->color_filename);
165 color_set(opt->color_function, def->color_function);
166 color_set(opt->color_lineno, def->color_lineno);
167 color_set(opt->color_match_context, def->color_match_context);
168 color_set(opt->color_match_selected, def->color_match_selected);
169 color_set(opt->color_selected, def->color_selected);
170 color_set(opt->color_sep, def->color_sep);
173 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
175 switch (pattern_type) {
176 case GREP_PATTERN_TYPE_UNSPECIFIED:
179 case GREP_PATTERN_TYPE_BRE:
184 case GREP_PATTERN_TYPE_ERE:
187 opt->regflags |= REG_EXTENDED;
190 case GREP_PATTERN_TYPE_FIXED:
195 case GREP_PATTERN_TYPE_PCRE:
202 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
204 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
205 grep_set_pattern_type_option(pattern_type, opt);
206 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
207 grep_set_pattern_type_option(opt->pattern_type_option, opt);
208 else if (opt->extended_regexp_option)
209 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
212 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
213 const char *origin, int no,
214 enum grep_pat_token t,
215 enum grep_header_field field)
217 struct grep_pat *p = xcalloc(1, sizeof(*p));
218 p->pattern = xmemdupz(pat, patlen);
219 p->patternlen = patlen;
227 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
234 case GREP_PATTERN: /* atom */
235 case GREP_PATTERN_HEAD:
236 case GREP_PATTERN_BODY:
238 struct grep_pat *new_pat;
240 char *cp = p->pattern + p->patternlen, *nl = NULL;
241 while (++len <= p->patternlen) {
242 if (*(--cp) == '\n') {
249 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
250 p->no, p->token, p->field);
251 new_pat->next = p->next;
253 *tail = &new_pat->next;
256 p->patternlen -= len;
264 void append_header_grep_pattern(struct grep_opt *opt,
265 enum grep_header_field field, const char *pat)
267 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
268 GREP_PATTERN_HEAD, field);
269 if (field == GREP_HEADER_REFLOG)
270 opt->use_reflog_filter = 1;
271 do_append_grep_pat(&opt->header_tail, p);
274 void append_grep_pattern(struct grep_opt *opt, const char *pat,
275 const char *origin, int no, enum grep_pat_token t)
277 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
280 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
281 const char *origin, int no, enum grep_pat_token t)
283 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
284 do_append_grep_pat(&opt->pattern_tail, p);
287 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
289 struct grep_pat *pat;
290 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
293 ret->pattern_list = NULL;
294 ret->pattern_tail = &ret->pattern_list;
296 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
298 if(pat->token == GREP_PATTERN_HEAD)
299 append_header_grep_pattern(ret, pat->field,
302 append_grep_pat(ret, pat->pattern, pat->patternlen,
303 pat->origin, pat->no, pat->token);
309 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
315 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
317 xsnprintf(where, sizeof(where), "%s, ", p->origin);
321 die("%s'%s': %s", where, p->pattern, error);
324 static int is_fixed(const char *s, size_t len)
328 for (i = 0; i < len; i++) {
329 if (is_regex_special(s[i]))
336 static int has_null(const char *s, size_t len)
339 * regcomp cannot accept patterns with NULs so when using it
340 * we consider any pattern containing a NUL fixed.
342 if (memchr(s, 0, len))
349 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
353 int options = PCRE_MULTILINE;
355 if (opt->ignore_case) {
356 if (has_non_ascii(p->pattern))
357 p->pcre1_tables = pcre_maketables();
358 options |= PCRE_CASELESS;
360 if (is_utf8_locale() && has_non_ascii(p->pattern))
361 options |= PCRE_UTF8;
363 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
365 if (!p->pcre1_regexp)
366 compile_regexp_failed(p, error);
368 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, PCRE_STUDY_JIT_COMPILE, &error);
369 if (!p->pcre1_extra_info && error)
372 #ifdef PCRE_CONFIG_JIT
373 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
374 if (p->pcre1_jit_on == 1) {
375 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
376 if (!p->pcre1_jit_stack)
377 die("Couldn't allocate PCRE JIT stack");
378 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
379 } else if (p->pcre1_jit_on != 0) {
380 die("BUG: The pcre1_jit_on variable should be 0 or 1, not %d",
386 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
387 regmatch_t *match, int eflags)
389 int ovector[30], ret, flags = 0;
391 if (eflags & REG_NOTBOL)
392 flags |= PCRE_NOTBOL;
394 #ifdef PCRE_CONFIG_JIT
395 if (p->pcre1_jit_on) {
396 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
397 eol - line, 0, flags, ovector,
398 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
402 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
403 eol - line, 0, flags, ovector,
404 ARRAY_SIZE(ovector));
407 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
408 die("pcre_exec failed with error code %d", ret);
411 match->rm_so = ovector[0];
412 match->rm_eo = ovector[1];
418 static void free_pcre1_regexp(struct grep_pat *p)
420 pcre_free(p->pcre1_regexp);
421 #ifdef PCRE_CONFIG_JIT
422 if (p->pcre1_jit_on) {
423 pcre_free_study(p->pcre1_extra_info);
424 pcre_jit_stack_free(p->pcre1_jit_stack);
428 pcre_free(p->pcre1_extra_info);
430 pcre_free((void *)p->pcre1_tables);
432 #else /* !USE_LIBPCRE1 */
433 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
435 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
438 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
439 regmatch_t *match, int eflags)
444 static void free_pcre1_regexp(struct grep_pat *p)
447 #endif /* !USE_LIBPCRE1 */
449 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
451 struct strbuf sb = STRBUF_INIT;
453 int regflags = opt->regflags;
455 basic_regex_quote_buf(&sb, p->pattern);
456 if (opt->ignore_case)
457 regflags |= REG_ICASE;
458 err = regcomp(&p->regexp, sb.buf, regflags);
460 fprintf(stderr, "fixed %s\n", sb.buf);
464 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
466 compile_regexp_failed(p, errbuf);
470 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
472 int icase, ascii_only;
475 p->word_regexp = opt->word_regexp;
476 p->ignore_case = opt->ignore_case;
477 icase = opt->regflags & REG_ICASE || p->ignore_case;
478 ascii_only = !has_non_ascii(p->pattern);
481 * Even when -F (fixed) asks us to do a non-regexp search, we
482 * may not be able to correctly case-fold when -i
483 * (ignore-case) is asked (in which case, we'll synthesize a
484 * regexp to match the pattern that matches regexp special
485 * characters literally, while ignoring case differences). On
486 * the other hand, even without -F, if the pattern does not
487 * have any regexp special characters and there is no need for
488 * case-folding search, we can internally turn it into a
489 * simple string match using kws. p->fixed tells us if we
493 has_null(p->pattern, p->patternlen) ||
494 is_fixed(p->pattern, p->patternlen))
495 p->fixed = !icase || ascii_only;
500 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
501 kwsincr(p->kws, p->pattern, p->patternlen);
504 } else if (opt->fixed) {
506 * We come here when the pattern has the non-ascii
507 * characters we cannot case-fold, and asked to
510 compile_fixed_regexp(p, opt);
515 compile_pcre1_regexp(p, opt);
519 err = regcomp(&p->regexp, p->pattern, opt->regflags);
522 regerror(err, &p->regexp, errbuf, 1024);
524 compile_regexp_failed(p, errbuf);
528 static struct grep_expr *compile_pattern_or(struct grep_pat **);
529 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
538 case GREP_PATTERN: /* atom */
539 case GREP_PATTERN_HEAD:
540 case GREP_PATTERN_BODY:
541 x = xcalloc(1, sizeof (struct grep_expr));
542 x->node = GREP_NODE_ATOM;
546 case GREP_OPEN_PAREN:
548 x = compile_pattern_or(list);
549 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
550 die("unmatched parenthesis");
551 *list = (*list)->next;
558 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
569 die("--not not followed by pattern expression");
571 x = xcalloc(1, sizeof (struct grep_expr));
572 x->node = GREP_NODE_NOT;
573 x->u.unary = compile_pattern_not(list);
575 die("--not followed by non pattern expression");
578 return compile_pattern_atom(list);
582 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
585 struct grep_expr *x, *y, *z;
587 x = compile_pattern_not(list);
589 if (p && p->token == GREP_AND) {
591 die("--and not followed by pattern expression");
593 y = compile_pattern_and(list);
595 die("--and not followed by pattern expression");
596 z = xcalloc(1, sizeof (struct grep_expr));
597 z->node = GREP_NODE_AND;
598 z->u.binary.left = x;
599 z->u.binary.right = y;
605 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
608 struct grep_expr *x, *y, *z;
610 x = compile_pattern_and(list);
612 if (x && p && p->token != GREP_CLOSE_PAREN) {
613 y = compile_pattern_or(list);
615 die("not a pattern expression %s", p->pattern);
616 z = xcalloc(1, sizeof (struct grep_expr));
617 z->node = GREP_NODE_OR;
618 z->u.binary.left = x;
619 z->u.binary.right = y;
625 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
627 return compile_pattern_or(list);
630 static void indent(int in)
636 static void dump_grep_pat(struct grep_pat *p)
639 case GREP_AND: fprintf(stderr, "*and*"); break;
640 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
641 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
642 case GREP_NOT: fprintf(stderr, "*not*"); break;
643 case GREP_OR: fprintf(stderr, "*or*"); break;
645 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
646 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
647 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
652 case GREP_PATTERN_HEAD:
653 fprintf(stderr, "<head %d>", p->field); break;
654 case GREP_PATTERN_BODY:
655 fprintf(stderr, "<body>"); break;
659 case GREP_PATTERN_HEAD:
660 case GREP_PATTERN_BODY:
662 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
668 static void dump_grep_expression_1(struct grep_expr *x, int in)
673 fprintf(stderr, "true\n");
676 dump_grep_pat(x->u.atom);
679 fprintf(stderr, "(not\n");
680 dump_grep_expression_1(x->u.unary, in+1);
682 fprintf(stderr, ")\n");
685 fprintf(stderr, "(and\n");
686 dump_grep_expression_1(x->u.binary.left, in+1);
687 dump_grep_expression_1(x->u.binary.right, in+1);
689 fprintf(stderr, ")\n");
692 fprintf(stderr, "(or\n");
693 dump_grep_expression_1(x->u.binary.left, in+1);
694 dump_grep_expression_1(x->u.binary.right, in+1);
696 fprintf(stderr, ")\n");
701 static void dump_grep_expression(struct grep_opt *opt)
703 struct grep_expr *x = opt->pattern_expression;
706 fprintf(stderr, "[all-match]\n");
707 dump_grep_expression_1(x, 0);
711 static struct grep_expr *grep_true_expr(void)
713 struct grep_expr *z = xcalloc(1, sizeof(*z));
714 z->node = GREP_NODE_TRUE;
718 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
720 struct grep_expr *z = xcalloc(1, sizeof(*z));
721 z->node = GREP_NODE_OR;
722 z->u.binary.left = left;
723 z->u.binary.right = right;
727 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
730 struct grep_expr *header_expr;
731 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
732 enum grep_header_field fld;
734 if (!opt->header_list)
737 for (p = opt->header_list; p; p = p->next) {
738 if (p->token != GREP_PATTERN_HEAD)
739 die("BUG: a non-header pattern in grep header list.");
740 if (p->field < GREP_HEADER_FIELD_MIN ||
741 GREP_HEADER_FIELD_MAX <= p->field)
742 die("BUG: unknown header field %d", p->field);
743 compile_regexp(p, opt);
746 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
747 header_group[fld] = NULL;
749 for (p = opt->header_list; p; p = p->next) {
751 struct grep_pat *pp = p;
753 h = compile_pattern_atom(&pp);
754 if (!h || pp != p->next)
755 die("BUG: malformed header expr");
756 if (!header_group[p->field]) {
757 header_group[p->field] = h;
760 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
765 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
766 if (!header_group[fld])
769 header_expr = grep_true_expr();
770 header_expr = grep_or_expr(header_group[fld], header_expr);
775 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
777 struct grep_expr *z = x;
780 assert(x->node == GREP_NODE_OR);
781 if (x->u.binary.right &&
782 x->u.binary.right->node == GREP_NODE_TRUE) {
783 x->u.binary.right = y;
786 x = x->u.binary.right;
791 static void compile_grep_patterns_real(struct grep_opt *opt)
794 struct grep_expr *header_expr = prep_header_patterns(opt);
796 for (p = opt->pattern_list; p; p = p->next) {
798 case GREP_PATTERN: /* atom */
799 case GREP_PATTERN_HEAD:
800 case GREP_PATTERN_BODY:
801 compile_regexp(p, opt);
809 if (opt->all_match || header_expr)
811 else if (!opt->extended && !opt->debug)
814 p = opt->pattern_list;
816 opt->pattern_expression = compile_pattern_expr(&p);
818 die("incomplete pattern expression: %s", p->pattern);
823 if (!opt->pattern_expression)
824 opt->pattern_expression = header_expr;
825 else if (opt->all_match)
826 opt->pattern_expression = grep_splice_or(header_expr,
827 opt->pattern_expression);
829 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
834 void compile_grep_patterns(struct grep_opt *opt)
836 compile_grep_patterns_real(opt);
838 dump_grep_expression(opt);
841 static void free_pattern_expr(struct grep_expr *x)
848 free_pattern_expr(x->u.unary);
852 free_pattern_expr(x->u.binary.left);
853 free_pattern_expr(x->u.binary.right);
859 void free_grep_patterns(struct grep_opt *opt)
861 struct grep_pat *p, *n;
863 for (p = opt->pattern_list; p; p = n) {
866 case GREP_PATTERN: /* atom */
867 case GREP_PATTERN_HEAD:
868 case GREP_PATTERN_BODY:
871 else if (p->pcre1_regexp)
872 free_pcre1_regexp(p);
885 free_pattern_expr(opt->pattern_expression);
888 static char *end_of_line(char *cp, unsigned long *left)
890 unsigned long l = *left;
891 while (l && *cp != '\n') {
899 static int word_char(char ch)
901 return isalnum(ch) || ch == '_';
904 static void output_color(struct grep_opt *opt, const void *data, size_t size,
907 if (want_color(opt->color) && color && color[0]) {
908 opt->output(opt, color, strlen(color));
909 opt->output(opt, data, size);
910 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
912 opt->output(opt, data, size);
915 static void output_sep(struct grep_opt *opt, char sign)
917 if (opt->null_following_name)
918 opt->output(opt, "\0", 1);
920 output_color(opt, &sign, 1, opt->color_sep);
923 static void show_name(struct grep_opt *opt, const char *name)
925 output_color(opt, name, strlen(name), opt->color_filename);
926 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
929 static int fixmatch(struct grep_pat *p, char *line, char *eol,
932 struct kwsmatch kwsm;
933 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
935 match->rm_so = match->rm_eo = -1;
938 match->rm_so = offset;
939 match->rm_eo = match->rm_so + kwsm.size[0];
944 static int patmatch(struct grep_pat *p, char *line, char *eol,
945 regmatch_t *match, int eflags)
950 hit = !fixmatch(p, line, eol, match);
951 else if (p->pcre1_regexp)
952 hit = !pcre1match(p, line, eol, match, eflags);
954 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
960 static int strip_timestamp(char *bol, char **eol_p)
965 while (bol < --eol) {
981 { "committer ", 10 },
985 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
986 enum grep_context ctx,
987 regmatch_t *pmatch, int eflags)
991 const char *start = bol;
993 if ((p->token != GREP_PATTERN) &&
994 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
997 if (p->token == GREP_PATTERN_HEAD) {
1000 assert(p->field < ARRAY_SIZE(header_field));
1001 field = header_field[p->field].field;
1002 len = header_field[p->field].len;
1003 if (strncmp(bol, field, len))
1007 case GREP_HEADER_AUTHOR:
1008 case GREP_HEADER_COMMITTER:
1009 saved_ch = strip_timestamp(bol, &eol);
1017 hit = patmatch(p, bol, eol, pmatch, eflags);
1019 if (hit && p->word_regexp) {
1020 if ((pmatch[0].rm_so < 0) ||
1021 (eol - bol) < pmatch[0].rm_so ||
1022 (pmatch[0].rm_eo < 0) ||
1023 (eol - bol) < pmatch[0].rm_eo)
1024 die("regexp returned nonsense");
1026 /* Match beginning must be either beginning of the
1027 * line, or at word boundary (i.e. the last char must
1028 * not be a word char). Similarly, match end must be
1029 * either end of the line, or at word boundary
1030 * (i.e. the next char must not be a word char).
1032 if ( ((pmatch[0].rm_so == 0) ||
1033 !word_char(bol[pmatch[0].rm_so-1])) &&
1034 ((pmatch[0].rm_eo == (eol-bol)) ||
1035 !word_char(bol[pmatch[0].rm_eo])) )
1040 /* Words consist of at least one character. */
1041 if (pmatch->rm_so == pmatch->rm_eo)
1044 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1045 /* There could be more than one match on the
1046 * line, and the first match might not be
1047 * strict word match. But later ones could be!
1048 * Forward to the next possible start, i.e. the
1049 * next position following a non-word char.
1051 bol = pmatch[0].rm_so + bol + 1;
1052 while (word_char(bol[-1]) && bol < eol)
1054 eflags |= REG_NOTBOL;
1059 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1062 pmatch[0].rm_so += bol - start;
1063 pmatch[0].rm_eo += bol - start;
1068 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1069 enum grep_context ctx, int collect_hits)
1075 die("Not a valid grep expression");
1077 case GREP_NODE_TRUE:
1080 case GREP_NODE_ATOM:
1081 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1084 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1087 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1089 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1093 return (match_expr_eval(x->u.binary.left,
1094 bol, eol, ctx, 0) ||
1095 match_expr_eval(x->u.binary.right,
1097 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1098 x->u.binary.left->hit |= h;
1099 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1102 die("Unexpected node type (internal error) %d", x->node);
1109 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1110 enum grep_context ctx, int collect_hits)
1112 struct grep_expr *x = opt->pattern_expression;
1113 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1116 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1117 enum grep_context ctx, int collect_hits)
1123 return match_expr(opt, bol, eol, ctx, collect_hits);
1125 /* we do not call with collect_hits without being extended */
1126 for (p = opt->pattern_list; p; p = p->next) {
1127 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1133 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1134 enum grep_context ctx,
1135 regmatch_t *pmatch, int eflags)
1139 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1141 if (match.rm_so < 0 || match.rm_eo < 0)
1143 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1144 if (match.rm_so > pmatch->rm_so)
1146 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1149 pmatch->rm_so = match.rm_so;
1150 pmatch->rm_eo = match.rm_eo;
1154 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1155 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1160 pmatch->rm_so = pmatch->rm_eo = -1;
1162 for (p = opt->pattern_list; p; p = p->next) {
1164 case GREP_PATTERN: /* atom */
1165 case GREP_PATTERN_HEAD:
1166 case GREP_PATTERN_BODY:
1167 hit |= match_next_pattern(p, bol, eol, ctx,
1178 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1179 const char *name, unsigned lno, char sign)
1181 int rest = eol - bol;
1182 const char *match_color, *line_color = NULL;
1184 if (opt->file_break && opt->last_shown == 0) {
1185 if (opt->show_hunk_mark)
1186 opt->output(opt, "\n", 1);
1187 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1188 if (opt->last_shown == 0) {
1189 if (opt->show_hunk_mark) {
1190 output_color(opt, "--", 2, opt->color_sep);
1191 opt->output(opt, "\n", 1);
1193 } else if (lno > opt->last_shown + 1) {
1194 output_color(opt, "--", 2, opt->color_sep);
1195 opt->output(opt, "\n", 1);
1198 if (opt->heading && opt->last_shown == 0) {
1199 output_color(opt, name, strlen(name), opt->color_filename);
1200 opt->output(opt, "\n", 1);
1202 opt->last_shown = lno;
1204 if (!opt->heading && opt->pathname) {
1205 output_color(opt, name, strlen(name), opt->color_filename);
1206 output_sep(opt, sign);
1210 xsnprintf(buf, sizeof(buf), "%d", lno);
1211 output_color(opt, buf, strlen(buf), opt->color_lineno);
1212 output_sep(opt, sign);
1216 enum grep_context ctx = GREP_CONTEXT_BODY;
1221 match_color = opt->color_match_selected;
1223 match_color = opt->color_match_context;
1225 line_color = opt->color_selected;
1226 else if (sign == '-')
1227 line_color = opt->color_context;
1228 else if (sign == '=')
1229 line_color = opt->color_function;
1231 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1232 if (match.rm_so == match.rm_eo)
1235 output_color(opt, bol, match.rm_so, line_color);
1236 output_color(opt, bol + match.rm_so,
1237 match.rm_eo - match.rm_so, match_color);
1239 rest -= match.rm_eo;
1240 eflags = REG_NOTBOL;
1244 output_color(opt, bol, rest, line_color);
1245 opt->output(opt, "\n", 1);
1252 * This lock protects access to the gitattributes machinery, which is
1255 pthread_mutex_t grep_attr_mutex;
1257 static inline void grep_attr_lock(void)
1260 pthread_mutex_lock(&grep_attr_mutex);
1263 static inline void grep_attr_unlock(void)
1266 pthread_mutex_unlock(&grep_attr_mutex);
1270 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1272 pthread_mutex_t grep_read_mutex;
1275 #define grep_attr_lock()
1276 #define grep_attr_unlock()
1279 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1281 xdemitconf_t *xecfg = opt->priv;
1282 if (xecfg && !xecfg->find_func) {
1283 grep_source_load_driver(gs);
1284 if (gs->driver->funcname.pattern) {
1285 const struct userdiff_funcname *pe = &gs->driver->funcname;
1286 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1288 xecfg = opt->priv = NULL;
1294 return xecfg->find_func(bol, eol - bol, buf, 1,
1295 xecfg->find_func_priv) >= 0;
1300 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1305 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1306 char *bol, unsigned lno)
1308 while (bol > gs->buf) {
1311 while (bol > gs->buf && bol[-1] != '\n')
1315 if (lno <= opt->last_shown)
1318 if (match_funcname(opt, gs, bol, eol)) {
1319 show_line(opt, bol, eol, gs->name, lno, '=');
1325 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1326 char *bol, char *end, unsigned lno)
1328 unsigned cur = lno, from = 1, funcname_lno = 0;
1329 int funcname_needed = !!opt->funcname;
1331 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1332 funcname_needed = 2;
1334 if (opt->pre_context < lno)
1335 from = lno - opt->pre_context;
1336 if (from <= opt->last_shown)
1337 from = opt->last_shown + 1;
1340 while (bol > gs->buf &&
1341 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1344 while (bol > gs->buf && bol[-1] != '\n')
1347 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1349 funcname_needed = 0;
1353 /* We need to look even further back to find a function signature. */
1354 if (opt->funcname && funcname_needed)
1355 show_funcname_line(opt, gs, bol, cur);
1359 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1361 while (*eol != '\n')
1363 show_line(opt, bol, eol, gs->name, cur, sign);
1369 static int should_lookahead(struct grep_opt *opt)
1374 return 0; /* punt for too complex stuff */
1377 for (p = opt->pattern_list; p; p = p->next) {
1378 if (p->token != GREP_PATTERN)
1379 return 0; /* punt for "header only" and stuff */
1384 static int look_ahead(struct grep_opt *opt,
1385 unsigned long *left_p,
1389 unsigned lno = *lno_p;
1392 char *sp, *last_bol;
1393 regoff_t earliest = -1;
1395 for (p = opt->pattern_list; p; p = p->next) {
1399 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1400 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1402 if (earliest < 0 || m.rm_so < earliest)
1407 *bol_p = bol + *left_p;
1411 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1412 ; /* find the beginning of the line */
1415 for (sp = bol; sp < last_bol; sp++) {
1419 *left_p -= last_bol - bol;
1425 static int fill_textconv_grep(struct userdiff_driver *driver,
1426 struct grep_source *gs)
1428 struct diff_filespec *df;
1432 if (!driver || !driver->textconv)
1433 return grep_source_load(gs);
1436 * The textconv interface is intimately tied to diff_filespecs, so we
1437 * have to pretend to be one. If we could unify the grep_source
1438 * and diff_filespec structs, this mess could just go away.
1440 df = alloc_filespec(gs->path);
1442 case GREP_SOURCE_SHA1:
1443 fill_filespec(df, gs->identifier, 1, 0100644);
1445 case GREP_SOURCE_FILE:
1446 fill_filespec(df, null_sha1, 0, 0100644);
1449 die("BUG: attempt to textconv something without a path?");
1453 * fill_textconv is not remotely thread-safe; it may load objects
1454 * behind the scenes, and it modifies the global diff tempfile
1458 size = fill_textconv(driver, df, &buf);
1463 * The normal fill_textconv usage by the diff machinery would just keep
1464 * the textconv'd buf separate from the diff_filespec. But much of the
1465 * grep code passes around a grep_source and assumes that its "buf"
1466 * pointer is the beginning of the thing we are searching. So let's
1467 * install our textconv'd version into the grep_source, taking care not
1468 * to leak any existing buffer.
1470 grep_source_clear_data(gs);
1477 static int is_empty_line(const char *bol, const char *eol)
1479 while (bol < eol && isspace(*bol))
1484 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1487 char *peek_bol = NULL;
1490 unsigned last_hit = 0;
1491 int binary_match_only = 0;
1493 int try_lookahead = 0;
1494 int show_function = 0;
1495 struct userdiff_driver *textconv = NULL;
1496 enum grep_context ctx = GREP_CONTEXT_HEAD;
1500 opt->output = std_output;
1502 if (opt->pre_context || opt->post_context || opt->file_break ||
1504 /* Show hunk marks, except for the first file. */
1505 if (opt->last_shown)
1506 opt->show_hunk_mark = 1;
1508 * If we're using threads then we can't easily identify
1509 * the first file. Always put hunk marks in that case
1510 * and skip the very first one later in work_done().
1512 if (opt->output != std_output)
1513 opt->show_hunk_mark = 1;
1515 opt->last_shown = 0;
1517 if (opt->allow_textconv) {
1518 grep_source_load_driver(gs);
1520 * We might set up the shared textconv cache data here, which
1521 * is not thread-safe.
1524 textconv = userdiff_get_textconv(gs->driver);
1529 * We know the result of a textconv is text, so we only have to care
1530 * about binary handling if we are not using it.
1533 switch (opt->binary) {
1534 case GREP_BINARY_DEFAULT:
1535 if (grep_source_is_binary(gs))
1536 binary_match_only = 1;
1538 case GREP_BINARY_NOMATCH:
1539 if (grep_source_is_binary(gs))
1540 return 0; /* Assume unmatch */
1542 case GREP_BINARY_TEXT:
1545 die("BUG: unknown binary handling mode");
1549 memset(&xecfg, 0, sizeof(xecfg));
1552 try_lookahead = should_lookahead(opt);
1554 if (fill_textconv_grep(textconv, gs) < 0)
1564 * look_ahead() skips quickly to the line that possibly
1565 * has the next hit; don't call it if we need to do
1566 * something more than just skipping the current line
1567 * in response to an unmatch for the current line. E.g.
1568 * inside a post-context window, we will show the current
1569 * line as a context around the previous hit when it
1574 && (show_function ||
1575 lno <= last_hit + opt->post_context))
1576 && look_ahead(opt, &left, &lno, &bol))
1578 eol = end_of_line(bol, &left);
1582 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1583 ctx = GREP_CONTEXT_BODY;
1585 hit = match_line(opt, bol, eol, ctx, collect_hits);
1591 /* "grep -v -e foo -e bla" should list lines
1592 * that do not have either, so inversion should
1597 if (opt->unmatch_name_only) {
1604 if (opt->status_only)
1606 if (opt->name_only) {
1607 show_name(opt, gs->name);
1612 if (binary_match_only) {
1613 opt->output(opt, "Binary file ", 12);
1614 output_color(opt, gs->name, strlen(gs->name),
1615 opt->color_filename);
1616 opt->output(opt, " matches\n", 9);
1619 /* Hit at this line. If we haven't shown the
1620 * pre-context lines, we would need to show them.
1622 if (opt->pre_context || opt->funcbody)
1623 show_pre_context(opt, gs, bol, eol, lno);
1624 else if (opt->funcname)
1625 show_funcname_line(opt, gs, bol, lno);
1626 show_line(opt, bol, eol, gs->name, lno, ':');
1632 if (show_function && (!peek_bol || peek_bol < bol)) {
1633 unsigned long peek_left = left;
1634 char *peek_eol = eol;
1637 * Trailing empty lines are not interesting.
1638 * Peek past them to see if they belong to the
1639 * body of the current function.
1642 while (is_empty_line(peek_bol, peek_eol)) {
1643 peek_bol = peek_eol + 1;
1644 peek_eol = end_of_line(peek_bol, &peek_left);
1647 if (match_funcname(opt, gs, peek_bol, peek_eol))
1650 if (show_function ||
1651 (last_hit && lno <= last_hit + opt->post_context)) {
1652 /* If the last hit is within the post context,
1653 * we need to show this line.
1655 show_line(opt, bol, eol, gs->name, lno, '-');
1669 if (opt->status_only)
1671 if (opt->unmatch_name_only) {
1672 /* We did not see any hit, so we want to show this */
1673 show_name(opt, gs->name);
1677 xdiff_clear_find_func(&xecfg);
1681 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1682 * which feels mostly useless but sometimes useful. Maybe
1683 * make it another option? For now suppress them.
1685 if (opt->count && count) {
1687 if (opt->pathname) {
1688 output_color(opt, gs->name, strlen(gs->name),
1689 opt->color_filename);
1690 output_sep(opt, ':');
1692 xsnprintf(buf, sizeof(buf), "%u\n", count);
1693 opt->output(opt, buf, strlen(buf));
1699 static void clr_hit_marker(struct grep_expr *x)
1701 /* All-hit markers are meaningful only at the very top level
1706 if (x->node != GREP_NODE_OR)
1708 x->u.binary.left->hit = 0;
1709 x = x->u.binary.right;
1713 static int chk_hit_marker(struct grep_expr *x)
1715 /* Top level nodes have hit markers. See if they all are hits */
1717 if (x->node != GREP_NODE_OR)
1719 if (!x->u.binary.left->hit)
1721 x = x->u.binary.right;
1725 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1728 * we do not have to do the two-pass grep when we do not check
1729 * buffer-wide "all-match".
1731 if (!opt->all_match)
1732 return grep_source_1(opt, gs, 0);
1734 /* Otherwise the toplevel "or" terms hit a bit differently.
1735 * We first clear hit markers from them.
1737 clr_hit_marker(opt->pattern_expression);
1738 grep_source_1(opt, gs, 1);
1740 if (!chk_hit_marker(opt->pattern_expression))
1743 return grep_source_1(opt, gs, 0);
1746 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1748 struct grep_source gs;
1751 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1755 r = grep_source(opt, &gs);
1757 grep_source_clear(&gs);
1761 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1762 const char *name, const char *path,
1763 const void *identifier)
1766 gs->name = xstrdup_or_null(name);
1767 gs->path = xstrdup_or_null(path);
1773 case GREP_SOURCE_FILE:
1774 gs->identifier = xstrdup(identifier);
1776 case GREP_SOURCE_SUBMODULE:
1778 gs->identifier = NULL;
1783 * If the identifier is non-NULL (in the submodule case) it
1784 * will be a SHA1 that needs to be copied.
1786 case GREP_SOURCE_SHA1:
1787 gs->identifier = xmalloc(20);
1788 hashcpy(gs->identifier, identifier);
1790 case GREP_SOURCE_BUF:
1791 gs->identifier = NULL;
1796 void grep_source_clear(struct grep_source *gs)
1802 free(gs->identifier);
1803 gs->identifier = NULL;
1804 grep_source_clear_data(gs);
1807 void grep_source_clear_data(struct grep_source *gs)
1810 case GREP_SOURCE_FILE:
1811 case GREP_SOURCE_SHA1:
1812 case GREP_SOURCE_SUBMODULE:
1817 case GREP_SOURCE_BUF:
1818 /* leave user-provided buf intact */
1823 static int grep_source_load_sha1(struct grep_source *gs)
1825 enum object_type type;
1828 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1832 return error(_("'%s': unable to read %s"),
1834 sha1_to_hex(gs->identifier));
1838 static int grep_source_load_file(struct grep_source *gs)
1840 const char *filename = gs->identifier;
1846 if (lstat(filename, &st) < 0) {
1848 if (errno != ENOENT)
1849 error_errno(_("failed to stat '%s'"), filename);
1852 if (!S_ISREG(st.st_mode))
1854 size = xsize_t(st.st_size);
1855 i = open(filename, O_RDONLY);
1858 data = xmallocz(size);
1859 if (st.st_size != read_in_full(i, data, size)) {
1860 error_errno(_("'%s': short read"), filename);
1872 static int grep_source_load(struct grep_source *gs)
1878 case GREP_SOURCE_FILE:
1879 return grep_source_load_file(gs);
1880 case GREP_SOURCE_SHA1:
1881 return grep_source_load_sha1(gs);
1882 case GREP_SOURCE_BUF:
1883 return gs->buf ? 0 : -1;
1884 case GREP_SOURCE_SUBMODULE:
1887 die("BUG: invalid grep_source type to load");
1890 void grep_source_load_driver(struct grep_source *gs)
1897 gs->driver = userdiff_find_by_path(gs->path);
1899 gs->driver = userdiff_find_by_name("default");
1903 static int grep_source_is_binary(struct grep_source *gs)
1905 grep_source_load_driver(gs);
1906 if (gs->driver->binary != -1)
1907 return gs->driver->binary;
1909 if (!grep_source_load(gs))
1910 return buffer_is_binary(gs->buf, gs->size);