4 #include "xdiff-interface.h"
9 static int grep_source_load(struct grep_source *gs);
10 static int grep_source_is_binary(struct grep_source *gs);
12 static struct grep_opt grep_defaults;
15 * Initialize the grep_defaults template with hardcoded defaults.
16 * We could let the compiler do this, but without C99 initializers
17 * the code gets unwieldy and unreadable, so...
19 void init_grep_defaults(void)
21 struct grep_opt *opt = &grep_defaults;
28 memset(opt, 0, sizeof(*opt));
31 opt->regflags = REG_NEWLINE;
33 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
34 opt->extended_regexp_option = 0;
35 color_set(opt->color_context, "");
36 color_set(opt->color_filename, "");
37 color_set(opt->color_function, "");
38 color_set(opt->color_lineno, "");
39 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
40 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
41 color_set(opt->color_selected, "");
42 color_set(opt->color_sep, GIT_COLOR_CYAN);
46 static int parse_pattern_type_arg(const char *opt, const char *arg)
48 if (!strcmp(arg, "default"))
49 return GREP_PATTERN_TYPE_UNSPECIFIED;
50 else if (!strcmp(arg, "basic"))
51 return GREP_PATTERN_TYPE_BRE;
52 else if (!strcmp(arg, "extended"))
53 return GREP_PATTERN_TYPE_ERE;
54 else if (!strcmp(arg, "fixed"))
55 return GREP_PATTERN_TYPE_FIXED;
56 else if (!strcmp(arg, "perl"))
57 return GREP_PATTERN_TYPE_PCRE;
58 die("bad %s argument: %s", opt, arg);
62 * Read the configuration file once and store it in
63 * the grep_defaults template.
65 int grep_config(const char *var, const char *value, void *cb)
67 struct grep_opt *opt = &grep_defaults;
70 if (userdiff_config(var, value) < 0)
73 if (!strcmp(var, "grep.extendedregexp")) {
74 if (git_config_bool(var, value))
75 opt->extended_regexp_option = 1;
77 opt->extended_regexp_option = 0;
81 if (!strcmp(var, "grep.patterntype")) {
82 opt->pattern_type_option = parse_pattern_type_arg(var, value);
86 if (!strcmp(var, "grep.linenumber")) {
87 opt->linenum = git_config_bool(var, value);
91 if (!strcmp(var, "grep.fullname")) {
92 opt->relative = !git_config_bool(var, value);
96 if (!strcmp(var, "color.grep"))
97 opt->color = git_config_colorbool(var, value);
98 else if (!strcmp(var, "color.grep.context"))
99 color = opt->color_context;
100 else if (!strcmp(var, "color.grep.filename"))
101 color = opt->color_filename;
102 else if (!strcmp(var, "color.grep.function"))
103 color = opt->color_function;
104 else if (!strcmp(var, "color.grep.linenumber"))
105 color = opt->color_lineno;
106 else if (!strcmp(var, "color.grep.matchcontext"))
107 color = opt->color_match_context;
108 else if (!strcmp(var, "color.grep.matchselected"))
109 color = opt->color_match_selected;
110 else if (!strcmp(var, "color.grep.selected"))
111 color = opt->color_selected;
112 else if (!strcmp(var, "color.grep.separator"))
113 color = opt->color_sep;
114 else if (!strcmp(var, "color.grep.match")) {
117 return config_error_nonbool(var);
118 rc |= color_parse(value, opt->color_match_context);
119 rc |= color_parse(value, opt->color_match_selected);
125 return config_error_nonbool(var);
126 return color_parse(value, color);
132 * Initialize one instance of grep_opt and copy the
133 * default values from the template we read the configuration
134 * information in an earlier call to git_config(grep_config).
136 void grep_init(struct grep_opt *opt, const char *prefix)
138 struct grep_opt *def = &grep_defaults;
140 memset(opt, 0, sizeof(*opt));
141 opt->prefix = prefix;
142 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
143 opt->pattern_tail = &opt->pattern_list;
144 opt->header_tail = &opt->header_list;
146 opt->color = def->color;
147 opt->extended_regexp_option = def->extended_regexp_option;
148 opt->pattern_type_option = def->pattern_type_option;
149 opt->linenum = def->linenum;
150 opt->max_depth = def->max_depth;
151 opt->pathname = def->pathname;
152 opt->regflags = def->regflags;
153 opt->relative = def->relative;
155 color_set(opt->color_context, def->color_context);
156 color_set(opt->color_filename, def->color_filename);
157 color_set(opt->color_function, def->color_function);
158 color_set(opt->color_lineno, def->color_lineno);
159 color_set(opt->color_match_context, def->color_match_context);
160 color_set(opt->color_match_selected, def->color_match_selected);
161 color_set(opt->color_selected, def->color_selected);
162 color_set(opt->color_sep, def->color_sep);
165 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
167 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
168 grep_set_pattern_type_option(pattern_type, opt);
169 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
170 grep_set_pattern_type_option(opt->pattern_type_option, opt);
171 else if (opt->extended_regexp_option)
172 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
175 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
177 switch (pattern_type) {
178 case GREP_PATTERN_TYPE_UNSPECIFIED:
181 case GREP_PATTERN_TYPE_BRE:
184 opt->regflags &= ~REG_EXTENDED;
187 case GREP_PATTERN_TYPE_ERE:
190 opt->regflags |= REG_EXTENDED;
193 case GREP_PATTERN_TYPE_FIXED:
196 opt->regflags &= ~REG_EXTENDED;
199 case GREP_PATTERN_TYPE_PCRE:
202 opt->regflags &= ~REG_EXTENDED;
207 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
208 const char *origin, int no,
209 enum grep_pat_token t,
210 enum grep_header_field field)
212 struct grep_pat *p = xcalloc(1, sizeof(*p));
213 p->pattern = xmemdupz(pat, patlen);
214 p->patternlen = patlen;
222 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
229 case GREP_PATTERN: /* atom */
230 case GREP_PATTERN_HEAD:
231 case GREP_PATTERN_BODY:
233 struct grep_pat *new_pat;
235 char *cp = p->pattern + p->patternlen, *nl = NULL;
236 while (++len <= p->patternlen) {
237 if (*(--cp) == '\n') {
244 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
245 p->no, p->token, p->field);
246 new_pat->next = p->next;
248 *tail = &new_pat->next;
251 p->patternlen -= len;
259 void append_header_grep_pattern(struct grep_opt *opt,
260 enum grep_header_field field, const char *pat)
262 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
263 GREP_PATTERN_HEAD, field);
264 if (field == GREP_HEADER_REFLOG)
265 opt->use_reflog_filter = 1;
266 do_append_grep_pat(&opt->header_tail, p);
269 void append_grep_pattern(struct grep_opt *opt, const char *pat,
270 const char *origin, int no, enum grep_pat_token t)
272 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
275 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
276 const char *origin, int no, enum grep_pat_token t)
278 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
279 do_append_grep_pat(&opt->pattern_tail, p);
282 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
284 struct grep_pat *pat;
285 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
288 ret->pattern_list = NULL;
289 ret->pattern_tail = &ret->pattern_list;
291 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
293 if(pat->token == GREP_PATTERN_HEAD)
294 append_header_grep_pattern(ret, pat->field,
297 append_grep_pat(ret, pat->pattern, pat->patternlen,
298 pat->origin, pat->no, pat->token);
304 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
310 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
312 xsnprintf(where, sizeof(where), "%s, ", p->origin);
316 die("%s'%s': %s", where, p->pattern, error);
320 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
324 int options = PCRE_MULTILINE;
326 if (opt->ignore_case)
327 options |= PCRE_CASELESS;
329 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
332 compile_regexp_failed(p, error);
334 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
335 if (!p->pcre_extra_info && error)
339 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
340 regmatch_t *match, int eflags)
342 int ovector[30], ret, flags = 0;
344 if (eflags & REG_NOTBOL)
345 flags |= PCRE_NOTBOL;
347 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
348 0, flags, ovector, ARRAY_SIZE(ovector));
349 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
350 die("pcre_exec failed with error code %d", ret);
353 match->rm_so = ovector[0];
354 match->rm_eo = ovector[1];
360 static void free_pcre_regexp(struct grep_pat *p)
362 pcre_free(p->pcre_regexp);
363 pcre_free(p->pcre_extra_info);
365 #else /* !USE_LIBPCRE */
366 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
368 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
371 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
372 regmatch_t *match, int eflags)
377 static void free_pcre_regexp(struct grep_pat *p)
380 #endif /* !USE_LIBPCRE */
382 static int is_fixed(const char *s, size_t len)
386 /* regcomp cannot accept patterns with NULs so we
387 * consider any pattern containing a NUL fixed.
389 if (memchr(s, 0, len))
392 for (i = 0; i < len; i++) {
393 if (is_regex_special(s[i]))
400 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
402 int icase, ascii_only;
405 p->word_regexp = opt->word_regexp;
406 p->ignore_case = opt->ignore_case;
407 icase = opt->regflags & REG_ICASE || p->ignore_case;
408 ascii_only = !has_non_ascii(p->pattern);
412 else if ((!icase || ascii_only) &&
413 is_fixed(p->pattern, p->patternlen))
419 if (opt->regflags & REG_ICASE || p->ignore_case)
420 p->kws = kwsalloc(tolower_trans_tbl);
422 p->kws = kwsalloc(NULL);
423 kwsincr(p->kws, p->pattern, p->patternlen);
429 compile_pcre_regexp(p, opt);
433 err = regcomp(&p->regexp, p->pattern, opt->regflags);
436 regerror(err, &p->regexp, errbuf, 1024);
438 compile_regexp_failed(p, errbuf);
442 static struct grep_expr *compile_pattern_or(struct grep_pat **);
443 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
452 case GREP_PATTERN: /* atom */
453 case GREP_PATTERN_HEAD:
454 case GREP_PATTERN_BODY:
455 x = xcalloc(1, sizeof (struct grep_expr));
456 x->node = GREP_NODE_ATOM;
460 case GREP_OPEN_PAREN:
462 x = compile_pattern_or(list);
463 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
464 die("unmatched parenthesis");
465 *list = (*list)->next;
472 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
483 die("--not not followed by pattern expression");
485 x = xcalloc(1, sizeof (struct grep_expr));
486 x->node = GREP_NODE_NOT;
487 x->u.unary = compile_pattern_not(list);
489 die("--not followed by non pattern expression");
492 return compile_pattern_atom(list);
496 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
499 struct grep_expr *x, *y, *z;
501 x = compile_pattern_not(list);
503 if (p && p->token == GREP_AND) {
505 die("--and not followed by pattern expression");
507 y = compile_pattern_and(list);
509 die("--and not followed by pattern expression");
510 z = xcalloc(1, sizeof (struct grep_expr));
511 z->node = GREP_NODE_AND;
512 z->u.binary.left = x;
513 z->u.binary.right = y;
519 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
522 struct grep_expr *x, *y, *z;
524 x = compile_pattern_and(list);
526 if (x && p && p->token != GREP_CLOSE_PAREN) {
527 y = compile_pattern_or(list);
529 die("not a pattern expression %s", p->pattern);
530 z = xcalloc(1, sizeof (struct grep_expr));
531 z->node = GREP_NODE_OR;
532 z->u.binary.left = x;
533 z->u.binary.right = y;
539 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
541 return compile_pattern_or(list);
544 static void indent(int in)
550 static void dump_grep_pat(struct grep_pat *p)
553 case GREP_AND: fprintf(stderr, "*and*"); break;
554 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
555 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
556 case GREP_NOT: fprintf(stderr, "*not*"); break;
557 case GREP_OR: fprintf(stderr, "*or*"); break;
559 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
560 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
561 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
566 case GREP_PATTERN_HEAD:
567 fprintf(stderr, "<head %d>", p->field); break;
568 case GREP_PATTERN_BODY:
569 fprintf(stderr, "<body>"); break;
573 case GREP_PATTERN_HEAD:
574 case GREP_PATTERN_BODY:
576 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
582 static void dump_grep_expression_1(struct grep_expr *x, int in)
587 fprintf(stderr, "true\n");
590 dump_grep_pat(x->u.atom);
593 fprintf(stderr, "(not\n");
594 dump_grep_expression_1(x->u.unary, in+1);
596 fprintf(stderr, ")\n");
599 fprintf(stderr, "(and\n");
600 dump_grep_expression_1(x->u.binary.left, in+1);
601 dump_grep_expression_1(x->u.binary.right, in+1);
603 fprintf(stderr, ")\n");
606 fprintf(stderr, "(or\n");
607 dump_grep_expression_1(x->u.binary.left, in+1);
608 dump_grep_expression_1(x->u.binary.right, in+1);
610 fprintf(stderr, ")\n");
615 static void dump_grep_expression(struct grep_opt *opt)
617 struct grep_expr *x = opt->pattern_expression;
620 fprintf(stderr, "[all-match]\n");
621 dump_grep_expression_1(x, 0);
625 static struct grep_expr *grep_true_expr(void)
627 struct grep_expr *z = xcalloc(1, sizeof(*z));
628 z->node = GREP_NODE_TRUE;
632 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
634 struct grep_expr *z = xcalloc(1, sizeof(*z));
635 z->node = GREP_NODE_OR;
636 z->u.binary.left = left;
637 z->u.binary.right = right;
641 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
644 struct grep_expr *header_expr;
645 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
646 enum grep_header_field fld;
648 if (!opt->header_list)
651 for (p = opt->header_list; p; p = p->next) {
652 if (p->token != GREP_PATTERN_HEAD)
653 die("bug: a non-header pattern in grep header list.");
654 if (p->field < GREP_HEADER_FIELD_MIN ||
655 GREP_HEADER_FIELD_MAX <= p->field)
656 die("bug: unknown header field %d", p->field);
657 compile_regexp(p, opt);
660 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
661 header_group[fld] = NULL;
663 for (p = opt->header_list; p; p = p->next) {
665 struct grep_pat *pp = p;
667 h = compile_pattern_atom(&pp);
668 if (!h || pp != p->next)
669 die("bug: malformed header expr");
670 if (!header_group[p->field]) {
671 header_group[p->field] = h;
674 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
679 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
680 if (!header_group[fld])
683 header_expr = grep_true_expr();
684 header_expr = grep_or_expr(header_group[fld], header_expr);
689 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
691 struct grep_expr *z = x;
694 assert(x->node == GREP_NODE_OR);
695 if (x->u.binary.right &&
696 x->u.binary.right->node == GREP_NODE_TRUE) {
697 x->u.binary.right = y;
700 x = x->u.binary.right;
705 static void compile_grep_patterns_real(struct grep_opt *opt)
708 struct grep_expr *header_expr = prep_header_patterns(opt);
710 for (p = opt->pattern_list; p; p = p->next) {
712 case GREP_PATTERN: /* atom */
713 case GREP_PATTERN_HEAD:
714 case GREP_PATTERN_BODY:
715 compile_regexp(p, opt);
723 if (opt->all_match || header_expr)
725 else if (!opt->extended && !opt->debug)
728 p = opt->pattern_list;
730 opt->pattern_expression = compile_pattern_expr(&p);
732 die("incomplete pattern expression: %s", p->pattern);
737 if (!opt->pattern_expression)
738 opt->pattern_expression = header_expr;
739 else if (opt->all_match)
740 opt->pattern_expression = grep_splice_or(header_expr,
741 opt->pattern_expression);
743 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
748 void compile_grep_patterns(struct grep_opt *opt)
750 compile_grep_patterns_real(opt);
752 dump_grep_expression(opt);
755 static void free_pattern_expr(struct grep_expr *x)
762 free_pattern_expr(x->u.unary);
766 free_pattern_expr(x->u.binary.left);
767 free_pattern_expr(x->u.binary.right);
773 void free_grep_patterns(struct grep_opt *opt)
775 struct grep_pat *p, *n;
777 for (p = opt->pattern_list; p; p = n) {
780 case GREP_PATTERN: /* atom */
781 case GREP_PATTERN_HEAD:
782 case GREP_PATTERN_BODY:
785 else if (p->pcre_regexp)
799 free_pattern_expr(opt->pattern_expression);
802 static char *end_of_line(char *cp, unsigned long *left)
804 unsigned long l = *left;
805 while (l && *cp != '\n') {
813 static int word_char(char ch)
815 return isalnum(ch) || ch == '_';
818 static void output_color(struct grep_opt *opt, const void *data, size_t size,
821 if (want_color(opt->color) && color && color[0]) {
822 opt->output(opt, color, strlen(color));
823 opt->output(opt, data, size);
824 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
826 opt->output(opt, data, size);
829 static void output_sep(struct grep_opt *opt, char sign)
831 if (opt->null_following_name)
832 opt->output(opt, "\0", 1);
834 output_color(opt, &sign, 1, opt->color_sep);
837 static void show_name(struct grep_opt *opt, const char *name)
839 output_color(opt, name, strlen(name), opt->color_filename);
840 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
843 static int fixmatch(struct grep_pat *p, char *line, char *eol,
846 struct kwsmatch kwsm;
847 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
849 match->rm_so = match->rm_eo = -1;
852 match->rm_so = offset;
853 match->rm_eo = match->rm_so + kwsm.size[0];
858 static int regmatch(const regex_t *preg, char *line, char *eol,
859 regmatch_t *match, int eflags)
863 match->rm_eo = eol - line;
864 eflags |= REG_STARTEND;
866 return regexec(preg, line, 1, match, eflags);
869 static int patmatch(struct grep_pat *p, char *line, char *eol,
870 regmatch_t *match, int eflags)
875 hit = !fixmatch(p, line, eol, match);
876 else if (p->pcre_regexp)
877 hit = !pcrematch(p, line, eol, match, eflags);
879 hit = !regmatch(&p->regexp, line, eol, match, eflags);
884 static int strip_timestamp(char *bol, char **eol_p)
889 while (bol < --eol) {
905 { "committer ", 10 },
909 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
910 enum grep_context ctx,
911 regmatch_t *pmatch, int eflags)
915 const char *start = bol;
917 if ((p->token != GREP_PATTERN) &&
918 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
921 if (p->token == GREP_PATTERN_HEAD) {
924 assert(p->field < ARRAY_SIZE(header_field));
925 field = header_field[p->field].field;
926 len = header_field[p->field].len;
927 if (strncmp(bol, field, len))
931 case GREP_HEADER_AUTHOR:
932 case GREP_HEADER_COMMITTER:
933 saved_ch = strip_timestamp(bol, &eol);
941 hit = patmatch(p, bol, eol, pmatch, eflags);
943 if (hit && p->word_regexp) {
944 if ((pmatch[0].rm_so < 0) ||
945 (eol - bol) < pmatch[0].rm_so ||
946 (pmatch[0].rm_eo < 0) ||
947 (eol - bol) < pmatch[0].rm_eo)
948 die("regexp returned nonsense");
950 /* Match beginning must be either beginning of the
951 * line, or at word boundary (i.e. the last char must
952 * not be a word char). Similarly, match end must be
953 * either end of the line, or at word boundary
954 * (i.e. the next char must not be a word char).
956 if ( ((pmatch[0].rm_so == 0) ||
957 !word_char(bol[pmatch[0].rm_so-1])) &&
958 ((pmatch[0].rm_eo == (eol-bol)) ||
959 !word_char(bol[pmatch[0].rm_eo])) )
964 /* Words consist of at least one character. */
965 if (pmatch->rm_so == pmatch->rm_eo)
968 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
969 /* There could be more than one match on the
970 * line, and the first match might not be
971 * strict word match. But later ones could be!
972 * Forward to the next possible start, i.e. the
973 * next position following a non-word char.
975 bol = pmatch[0].rm_so + bol + 1;
976 while (word_char(bol[-1]) && bol < eol)
978 eflags |= REG_NOTBOL;
983 if (p->token == GREP_PATTERN_HEAD && saved_ch)
986 pmatch[0].rm_so += bol - start;
987 pmatch[0].rm_eo += bol - start;
992 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
993 enum grep_context ctx, int collect_hits)
999 die("Not a valid grep expression");
1001 case GREP_NODE_TRUE:
1004 case GREP_NODE_ATOM:
1005 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1008 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1011 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1013 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1017 return (match_expr_eval(x->u.binary.left,
1018 bol, eol, ctx, 0) ||
1019 match_expr_eval(x->u.binary.right,
1021 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1022 x->u.binary.left->hit |= h;
1023 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1026 die("Unexpected node type (internal error) %d", x->node);
1033 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1034 enum grep_context ctx, int collect_hits)
1036 struct grep_expr *x = opt->pattern_expression;
1037 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1040 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1041 enum grep_context ctx, int collect_hits)
1047 return match_expr(opt, bol, eol, ctx, collect_hits);
1049 /* we do not call with collect_hits without being extended */
1050 for (p = opt->pattern_list; p; p = p->next) {
1051 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1057 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1058 enum grep_context ctx,
1059 regmatch_t *pmatch, int eflags)
1063 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1065 if (match.rm_so < 0 || match.rm_eo < 0)
1067 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1068 if (match.rm_so > pmatch->rm_so)
1070 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1073 pmatch->rm_so = match.rm_so;
1074 pmatch->rm_eo = match.rm_eo;
1078 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1079 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1084 pmatch->rm_so = pmatch->rm_eo = -1;
1086 for (p = opt->pattern_list; p; p = p->next) {
1088 case GREP_PATTERN: /* atom */
1089 case GREP_PATTERN_HEAD:
1090 case GREP_PATTERN_BODY:
1091 hit |= match_next_pattern(p, bol, eol, ctx,
1102 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1103 const char *name, unsigned lno, char sign)
1105 int rest = eol - bol;
1106 const char *match_color, *line_color = NULL;
1108 if (opt->file_break && opt->last_shown == 0) {
1109 if (opt->show_hunk_mark)
1110 opt->output(opt, "\n", 1);
1111 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1112 if (opt->last_shown == 0) {
1113 if (opt->show_hunk_mark) {
1114 output_color(opt, "--", 2, opt->color_sep);
1115 opt->output(opt, "\n", 1);
1117 } else if (lno > opt->last_shown + 1) {
1118 output_color(opt, "--", 2, opt->color_sep);
1119 opt->output(opt, "\n", 1);
1122 if (opt->heading && opt->last_shown == 0) {
1123 output_color(opt, name, strlen(name), opt->color_filename);
1124 opt->output(opt, "\n", 1);
1126 opt->last_shown = lno;
1128 if (!opt->heading && opt->pathname) {
1129 output_color(opt, name, strlen(name), opt->color_filename);
1130 output_sep(opt, sign);
1134 snprintf(buf, sizeof(buf), "%d", lno);
1135 output_color(opt, buf, strlen(buf), opt->color_lineno);
1136 output_sep(opt, sign);
1140 enum grep_context ctx = GREP_CONTEXT_BODY;
1145 match_color = opt->color_match_selected;
1147 match_color = opt->color_match_context;
1149 line_color = opt->color_selected;
1150 else if (sign == '-')
1151 line_color = opt->color_context;
1152 else if (sign == '=')
1153 line_color = opt->color_function;
1155 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1156 if (match.rm_so == match.rm_eo)
1159 output_color(opt, bol, match.rm_so, line_color);
1160 output_color(opt, bol + match.rm_so,
1161 match.rm_eo - match.rm_so, match_color);
1163 rest -= match.rm_eo;
1164 eflags = REG_NOTBOL;
1168 output_color(opt, bol, rest, line_color);
1169 opt->output(opt, "\n", 1);
1176 * This lock protects access to the gitattributes machinery, which is
1179 pthread_mutex_t grep_attr_mutex;
1181 static inline void grep_attr_lock(void)
1184 pthread_mutex_lock(&grep_attr_mutex);
1187 static inline void grep_attr_unlock(void)
1190 pthread_mutex_unlock(&grep_attr_mutex);
1194 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1196 pthread_mutex_t grep_read_mutex;
1199 #define grep_attr_lock()
1200 #define grep_attr_unlock()
1203 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1205 xdemitconf_t *xecfg = opt->priv;
1206 if (xecfg && !xecfg->find_func) {
1207 grep_source_load_driver(gs);
1208 if (gs->driver->funcname.pattern) {
1209 const struct userdiff_funcname *pe = &gs->driver->funcname;
1210 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1212 xecfg = opt->priv = NULL;
1218 return xecfg->find_func(bol, eol - bol, buf, 1,
1219 xecfg->find_func_priv) >= 0;
1224 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1229 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1230 char *bol, unsigned lno)
1232 while (bol > gs->buf) {
1235 while (bol > gs->buf && bol[-1] != '\n')
1239 if (lno <= opt->last_shown)
1242 if (match_funcname(opt, gs, bol, eol)) {
1243 show_line(opt, bol, eol, gs->name, lno, '=');
1249 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1250 char *bol, char *end, unsigned lno)
1252 unsigned cur = lno, from = 1, funcname_lno = 0;
1253 int funcname_needed = !!opt->funcname;
1255 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1256 funcname_needed = 2;
1258 if (opt->pre_context < lno)
1259 from = lno - opt->pre_context;
1260 if (from <= opt->last_shown)
1261 from = opt->last_shown + 1;
1264 while (bol > gs->buf &&
1265 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1268 while (bol > gs->buf && bol[-1] != '\n')
1271 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1273 funcname_needed = 0;
1277 /* We need to look even further back to find a function signature. */
1278 if (opt->funcname && funcname_needed)
1279 show_funcname_line(opt, gs, bol, cur);
1283 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1285 while (*eol != '\n')
1287 show_line(opt, bol, eol, gs->name, cur, sign);
1293 static int should_lookahead(struct grep_opt *opt)
1298 return 0; /* punt for too complex stuff */
1301 for (p = opt->pattern_list; p; p = p->next) {
1302 if (p->token != GREP_PATTERN)
1303 return 0; /* punt for "header only" and stuff */
1308 static int look_ahead(struct grep_opt *opt,
1309 unsigned long *left_p,
1313 unsigned lno = *lno_p;
1316 char *sp, *last_bol;
1317 regoff_t earliest = -1;
1319 for (p = opt->pattern_list; p; p = p->next) {
1323 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1324 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1326 if (earliest < 0 || m.rm_so < earliest)
1331 *bol_p = bol + *left_p;
1335 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1336 ; /* find the beginning of the line */
1339 for (sp = bol; sp < last_bol; sp++) {
1343 *left_p -= last_bol - bol;
1349 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1351 fwrite(buf, size, 1, stdout);
1354 static int fill_textconv_grep(struct userdiff_driver *driver,
1355 struct grep_source *gs)
1357 struct diff_filespec *df;
1361 if (!driver || !driver->textconv)
1362 return grep_source_load(gs);
1365 * The textconv interface is intimately tied to diff_filespecs, so we
1366 * have to pretend to be one. If we could unify the grep_source
1367 * and diff_filespec structs, this mess could just go away.
1369 df = alloc_filespec(gs->path);
1371 case GREP_SOURCE_SHA1:
1372 fill_filespec(df, gs->identifier, 1, 0100644);
1374 case GREP_SOURCE_FILE:
1375 fill_filespec(df, null_sha1, 0, 0100644);
1378 die("BUG: attempt to textconv something without a path?");
1382 * fill_textconv is not remotely thread-safe; it may load objects
1383 * behind the scenes, and it modifies the global diff tempfile
1387 size = fill_textconv(driver, df, &buf);
1392 * The normal fill_textconv usage by the diff machinery would just keep
1393 * the textconv'd buf separate from the diff_filespec. But much of the
1394 * grep code passes around a grep_source and assumes that its "buf"
1395 * pointer is the beginning of the thing we are searching. So let's
1396 * install our textconv'd version into the grep_source, taking care not
1397 * to leak any existing buffer.
1399 grep_source_clear_data(gs);
1406 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1411 unsigned last_hit = 0;
1412 int binary_match_only = 0;
1414 int try_lookahead = 0;
1415 int show_function = 0;
1416 struct userdiff_driver *textconv = NULL;
1417 enum grep_context ctx = GREP_CONTEXT_HEAD;
1421 opt->output = std_output;
1423 if (opt->pre_context || opt->post_context || opt->file_break ||
1425 /* Show hunk marks, except for the first file. */
1426 if (opt->last_shown)
1427 opt->show_hunk_mark = 1;
1429 * If we're using threads then we can't easily identify
1430 * the first file. Always put hunk marks in that case
1431 * and skip the very first one later in work_done().
1433 if (opt->output != std_output)
1434 opt->show_hunk_mark = 1;
1436 opt->last_shown = 0;
1438 if (opt->allow_textconv) {
1439 grep_source_load_driver(gs);
1441 * We might set up the shared textconv cache data here, which
1442 * is not thread-safe.
1445 textconv = userdiff_get_textconv(gs->driver);
1450 * We know the result of a textconv is text, so we only have to care
1451 * about binary handling if we are not using it.
1454 switch (opt->binary) {
1455 case GREP_BINARY_DEFAULT:
1456 if (grep_source_is_binary(gs))
1457 binary_match_only = 1;
1459 case GREP_BINARY_NOMATCH:
1460 if (grep_source_is_binary(gs))
1461 return 0; /* Assume unmatch */
1463 case GREP_BINARY_TEXT:
1466 die("bug: unknown binary handling mode");
1470 memset(&xecfg, 0, sizeof(xecfg));
1473 try_lookahead = should_lookahead(opt);
1475 if (fill_textconv_grep(textconv, gs) < 0)
1485 * look_ahead() skips quickly to the line that possibly
1486 * has the next hit; don't call it if we need to do
1487 * something more than just skipping the current line
1488 * in response to an unmatch for the current line. E.g.
1489 * inside a post-context window, we will show the current
1490 * line as a context around the previous hit when it
1495 && (show_function ||
1496 lno <= last_hit + opt->post_context))
1497 && look_ahead(opt, &left, &lno, &bol))
1499 eol = end_of_line(bol, &left);
1503 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1504 ctx = GREP_CONTEXT_BODY;
1506 hit = match_line(opt, bol, eol, ctx, collect_hits);
1512 /* "grep -v -e foo -e bla" should list lines
1513 * that do not have either, so inversion should
1518 if (opt->unmatch_name_only) {
1525 if (opt->status_only)
1527 if (opt->name_only) {
1528 show_name(opt, gs->name);
1533 if (binary_match_only) {
1534 opt->output(opt, "Binary file ", 12);
1535 output_color(opt, gs->name, strlen(gs->name),
1536 opt->color_filename);
1537 opt->output(opt, " matches\n", 9);
1540 /* Hit at this line. If we haven't shown the
1541 * pre-context lines, we would need to show them.
1543 if (opt->pre_context || opt->funcbody)
1544 show_pre_context(opt, gs, bol, eol, lno);
1545 else if (opt->funcname)
1546 show_funcname_line(opt, gs, bol, lno);
1547 show_line(opt, bol, eol, gs->name, lno, ':');
1553 if (show_function && match_funcname(opt, gs, bol, eol))
1555 if (show_function ||
1556 (last_hit && lno <= last_hit + opt->post_context)) {
1557 /* If the last hit is within the post context,
1558 * we need to show this line.
1560 show_line(opt, bol, eol, gs->name, lno, '-');
1574 if (opt->status_only)
1576 if (opt->unmatch_name_only) {
1577 /* We did not see any hit, so we want to show this */
1578 show_name(opt, gs->name);
1582 xdiff_clear_find_func(&xecfg);
1586 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1587 * which feels mostly useless but sometimes useful. Maybe
1588 * make it another option? For now suppress them.
1590 if (opt->count && count) {
1592 if (opt->pathname) {
1593 output_color(opt, gs->name, strlen(gs->name),
1594 opt->color_filename);
1595 output_sep(opt, ':');
1597 snprintf(buf, sizeof(buf), "%u\n", count);
1598 opt->output(opt, buf, strlen(buf));
1604 static void clr_hit_marker(struct grep_expr *x)
1606 /* All-hit markers are meaningful only at the very top level
1611 if (x->node != GREP_NODE_OR)
1613 x->u.binary.left->hit = 0;
1614 x = x->u.binary.right;
1618 static int chk_hit_marker(struct grep_expr *x)
1620 /* Top level nodes have hit markers. See if they all are hits */
1622 if (x->node != GREP_NODE_OR)
1624 if (!x->u.binary.left->hit)
1626 x = x->u.binary.right;
1630 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1633 * we do not have to do the two-pass grep when we do not check
1634 * buffer-wide "all-match".
1636 if (!opt->all_match)
1637 return grep_source_1(opt, gs, 0);
1639 /* Otherwise the toplevel "or" terms hit a bit differently.
1640 * We first clear hit markers from them.
1642 clr_hit_marker(opt->pattern_expression);
1643 grep_source_1(opt, gs, 1);
1645 if (!chk_hit_marker(opt->pattern_expression))
1648 return grep_source_1(opt, gs, 0);
1651 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1653 struct grep_source gs;
1656 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1660 r = grep_source(opt, &gs);
1662 grep_source_clear(&gs);
1666 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1667 const char *name, const char *path,
1668 const void *identifier)
1671 gs->name = xstrdup_or_null(name);
1672 gs->path = xstrdup_or_null(path);
1678 case GREP_SOURCE_FILE:
1679 gs->identifier = xstrdup(identifier);
1681 case GREP_SOURCE_SHA1:
1682 gs->identifier = xmalloc(20);
1683 hashcpy(gs->identifier, identifier);
1685 case GREP_SOURCE_BUF:
1686 gs->identifier = NULL;
1690 void grep_source_clear(struct grep_source *gs)
1696 free(gs->identifier);
1697 gs->identifier = NULL;
1698 grep_source_clear_data(gs);
1701 void grep_source_clear_data(struct grep_source *gs)
1704 case GREP_SOURCE_FILE:
1705 case GREP_SOURCE_SHA1:
1710 case GREP_SOURCE_BUF:
1711 /* leave user-provided buf intact */
1716 static int grep_source_load_sha1(struct grep_source *gs)
1718 enum object_type type;
1721 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1725 return error(_("'%s': unable to read %s"),
1727 sha1_to_hex(gs->identifier));
1731 static int grep_source_load_file(struct grep_source *gs)
1733 const char *filename = gs->identifier;
1739 if (lstat(filename, &st) < 0) {
1741 if (errno != ENOENT)
1742 error(_("'%s': %s"), filename, strerror(errno));
1745 if (!S_ISREG(st.st_mode))
1747 size = xsize_t(st.st_size);
1748 i = open(filename, O_RDONLY);
1751 data = xmalloc(size + 1);
1752 if (st.st_size != read_in_full(i, data, size)) {
1753 error(_("'%s': short read %s"), filename, strerror(errno));
1766 static int grep_source_load(struct grep_source *gs)
1772 case GREP_SOURCE_FILE:
1773 return grep_source_load_file(gs);
1774 case GREP_SOURCE_SHA1:
1775 return grep_source_load_sha1(gs);
1776 case GREP_SOURCE_BUF:
1777 return gs->buf ? 0 : -1;
1779 die("BUG: invalid grep_source type");
1782 void grep_source_load_driver(struct grep_source *gs)
1789 gs->driver = userdiff_find_by_path(gs->path);
1791 gs->driver = userdiff_find_by_name("default");
1795 static int grep_source_is_binary(struct grep_source *gs)
1797 grep_source_load_driver(gs);
1798 if (gs->driver->binary != -1)
1799 return gs->driver->binary;
1801 if (!grep_source_load(gs))
1802 return buffer_is_binary(gs->buf, gs->size);