4 #include "xdiff-interface.h"
8 static int grep_source_load(struct grep_source *gs);
9 static int grep_source_is_binary(struct grep_source *gs);
11 static struct grep_opt grep_defaults;
14 * Initialize the grep_defaults template with hardcoded defaults.
15 * We could let the compiler do this, but without C99 initializers
16 * the code gets unwieldy and unreadable, so...
18 void init_grep_defaults(void)
20 struct grep_opt *opt = &grep_defaults;
27 memset(opt, 0, sizeof(*opt));
30 opt->regflags = REG_NEWLINE;
32 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
33 opt->extended_regexp_option = 0;
34 strcpy(opt->color_context, "");
35 strcpy(opt->color_filename, "");
36 strcpy(opt->color_function, "");
37 strcpy(opt->color_lineno, "");
38 strcpy(opt->color_match, GIT_COLOR_BOLD_RED);
39 strcpy(opt->color_selected, "");
40 strcpy(opt->color_sep, GIT_COLOR_CYAN);
44 static int parse_pattern_type_arg(const char *opt, const char *arg)
46 if (!strcmp(arg, "default"))
47 return GREP_PATTERN_TYPE_UNSPECIFIED;
48 else if (!strcmp(arg, "basic"))
49 return GREP_PATTERN_TYPE_BRE;
50 else if (!strcmp(arg, "extended"))
51 return GREP_PATTERN_TYPE_ERE;
52 else if (!strcmp(arg, "fixed"))
53 return GREP_PATTERN_TYPE_FIXED;
54 else if (!strcmp(arg, "perl"))
55 return GREP_PATTERN_TYPE_PCRE;
56 die("bad %s argument: %s", opt, arg);
60 * Read the configuration file once and store it in
61 * the grep_defaults template.
63 int grep_config(const char *var, const char *value, void *cb)
65 struct grep_opt *opt = &grep_defaults;
68 if (userdiff_config(var, value) < 0)
71 if (!strcmp(var, "grep.extendedregexp")) {
72 if (git_config_bool(var, value))
73 opt->extended_regexp_option = 1;
75 opt->extended_regexp_option = 0;
79 if (!strcmp(var, "grep.patterntype")) {
80 opt->pattern_type_option = parse_pattern_type_arg(var, value);
84 if (!strcmp(var, "grep.linenumber")) {
85 opt->linenum = git_config_bool(var, value);
89 if (!strcmp(var, "color.grep"))
90 opt->color = git_config_colorbool(var, value);
91 else if (!strcmp(var, "color.grep.context"))
92 color = opt->color_context;
93 else if (!strcmp(var, "color.grep.filename"))
94 color = opt->color_filename;
95 else if (!strcmp(var, "color.grep.function"))
96 color = opt->color_function;
97 else if (!strcmp(var, "color.grep.linenumber"))
98 color = opt->color_lineno;
99 else if (!strcmp(var, "color.grep.match"))
100 color = opt->color_match;
101 else if (!strcmp(var, "color.grep.selected"))
102 color = opt->color_selected;
103 else if (!strcmp(var, "color.grep.separator"))
104 color = opt->color_sep;
108 return config_error_nonbool(var);
109 color_parse(value, var, color);
115 * Initialize one instance of grep_opt and copy the
116 * default values from the template we read the configuration
117 * information in an earlier call to git_config(grep_config).
119 void grep_init(struct grep_opt *opt, const char *prefix)
121 struct grep_opt *def = &grep_defaults;
123 memset(opt, 0, sizeof(*opt));
124 opt->prefix = prefix;
125 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
126 opt->pattern_tail = &opt->pattern_list;
127 opt->header_tail = &opt->header_list;
129 opt->color = def->color;
130 opt->extended_regexp_option = def->extended_regexp_option;
131 opt->pattern_type_option = def->pattern_type_option;
132 opt->linenum = def->linenum;
133 opt->max_depth = def->max_depth;
134 opt->pathname = def->pathname;
135 opt->regflags = def->regflags;
136 opt->relative = def->relative;
138 strcpy(opt->color_context, def->color_context);
139 strcpy(opt->color_filename, def->color_filename);
140 strcpy(opt->color_function, def->color_function);
141 strcpy(opt->color_lineno, def->color_lineno);
142 strcpy(opt->color_match, def->color_match);
143 strcpy(opt->color_selected, def->color_selected);
144 strcpy(opt->color_sep, def->color_sep);
147 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
149 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
150 grep_set_pattern_type_option(pattern_type, opt);
151 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
152 grep_set_pattern_type_option(opt->pattern_type_option, opt);
153 else if (opt->extended_regexp_option)
154 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
157 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
159 switch (pattern_type) {
160 case GREP_PATTERN_TYPE_UNSPECIFIED:
163 case GREP_PATTERN_TYPE_BRE:
166 opt->regflags &= ~REG_EXTENDED;
169 case GREP_PATTERN_TYPE_ERE:
172 opt->regflags |= REG_EXTENDED;
175 case GREP_PATTERN_TYPE_FIXED:
178 opt->regflags &= ~REG_EXTENDED;
181 case GREP_PATTERN_TYPE_PCRE:
184 opt->regflags &= ~REG_EXTENDED;
189 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
190 const char *origin, int no,
191 enum grep_pat_token t,
192 enum grep_header_field field)
194 struct grep_pat *p = xcalloc(1, sizeof(*p));
195 p->pattern = xmemdupz(pat, patlen);
196 p->patternlen = patlen;
204 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
211 case GREP_PATTERN: /* atom */
212 case GREP_PATTERN_HEAD:
213 case GREP_PATTERN_BODY:
215 struct grep_pat *new_pat;
217 char *cp = p->pattern + p->patternlen, *nl = NULL;
218 while (++len <= p->patternlen) {
219 if (*(--cp) == '\n') {
226 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
227 p->no, p->token, p->field);
228 new_pat->next = p->next;
230 *tail = &new_pat->next;
233 p->patternlen -= len;
241 void append_header_grep_pattern(struct grep_opt *opt,
242 enum grep_header_field field, const char *pat)
244 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
245 GREP_PATTERN_HEAD, field);
246 if (field == GREP_HEADER_REFLOG)
247 opt->use_reflog_filter = 1;
248 do_append_grep_pat(&opt->header_tail, p);
251 void append_grep_pattern(struct grep_opt *opt, const char *pat,
252 const char *origin, int no, enum grep_pat_token t)
254 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
257 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
258 const char *origin, int no, enum grep_pat_token t)
260 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
261 do_append_grep_pat(&opt->pattern_tail, p);
264 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
266 struct grep_pat *pat;
267 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
270 ret->pattern_list = NULL;
271 ret->pattern_tail = &ret->pattern_list;
273 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
275 if(pat->token == GREP_PATTERN_HEAD)
276 append_header_grep_pattern(ret, pat->field,
279 append_grep_pat(ret, pat->pattern, pat->patternlen,
280 pat->origin, pat->no, pat->token);
286 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
292 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
294 sprintf(where, "%s, ", p->origin);
298 die("%s'%s': %s", where, p->pattern, error);
302 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
306 int options = PCRE_MULTILINE;
308 if (opt->ignore_case)
309 options |= PCRE_CASELESS;
311 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
314 compile_regexp_failed(p, error);
316 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
317 if (!p->pcre_extra_info && error)
321 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
322 regmatch_t *match, int eflags)
324 int ovector[30], ret, flags = 0;
326 if (eflags & REG_NOTBOL)
327 flags |= PCRE_NOTBOL;
329 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
330 0, flags, ovector, ARRAY_SIZE(ovector));
331 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
332 die("pcre_exec failed with error code %d", ret);
335 match->rm_so = ovector[0];
336 match->rm_eo = ovector[1];
342 static void free_pcre_regexp(struct grep_pat *p)
344 pcre_free(p->pcre_regexp);
345 pcre_free(p->pcre_extra_info);
347 #else /* !USE_LIBPCRE */
348 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
350 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
353 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
354 regmatch_t *match, int eflags)
359 static void free_pcre_regexp(struct grep_pat *p)
362 #endif /* !USE_LIBPCRE */
364 static int is_fixed(const char *s, size_t len)
368 /* regcomp cannot accept patterns with NULs so we
369 * consider any pattern containing a NUL fixed.
371 if (memchr(s, 0, len))
374 for (i = 0; i < len; i++) {
375 if (is_regex_special(s[i]))
382 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
386 p->word_regexp = opt->word_regexp;
387 p->ignore_case = opt->ignore_case;
389 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
395 if (opt->regflags & REG_ICASE || p->ignore_case)
396 p->kws = kwsalloc(tolower_trans_tbl);
398 p->kws = kwsalloc(NULL);
399 kwsincr(p->kws, p->pattern, p->patternlen);
405 compile_pcre_regexp(p, opt);
409 err = regcomp(&p->regexp, p->pattern, opt->regflags);
412 regerror(err, &p->regexp, errbuf, 1024);
414 compile_regexp_failed(p, errbuf);
418 static struct grep_expr *compile_pattern_or(struct grep_pat **);
419 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
428 case GREP_PATTERN: /* atom */
429 case GREP_PATTERN_HEAD:
430 case GREP_PATTERN_BODY:
431 x = xcalloc(1, sizeof (struct grep_expr));
432 x->node = GREP_NODE_ATOM;
436 case GREP_OPEN_PAREN:
438 x = compile_pattern_or(list);
439 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
440 die("unmatched parenthesis");
441 *list = (*list)->next;
448 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
459 die("--not not followed by pattern expression");
461 x = xcalloc(1, sizeof (struct grep_expr));
462 x->node = GREP_NODE_NOT;
463 x->u.unary = compile_pattern_not(list);
465 die("--not followed by non pattern expression");
468 return compile_pattern_atom(list);
472 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
475 struct grep_expr *x, *y, *z;
477 x = compile_pattern_not(list);
479 if (p && p->token == GREP_AND) {
481 die("--and not followed by pattern expression");
483 y = compile_pattern_and(list);
485 die("--and not followed by pattern expression");
486 z = xcalloc(1, sizeof (struct grep_expr));
487 z->node = GREP_NODE_AND;
488 z->u.binary.left = x;
489 z->u.binary.right = y;
495 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
498 struct grep_expr *x, *y, *z;
500 x = compile_pattern_and(list);
502 if (x && p && p->token != GREP_CLOSE_PAREN) {
503 y = compile_pattern_or(list);
505 die("not a pattern expression %s", p->pattern);
506 z = xcalloc(1, sizeof (struct grep_expr));
507 z->node = GREP_NODE_OR;
508 z->u.binary.left = x;
509 z->u.binary.right = y;
515 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
517 return compile_pattern_or(list);
520 static void indent(int in)
526 static void dump_grep_pat(struct grep_pat *p)
529 case GREP_AND: fprintf(stderr, "*and*"); break;
530 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
531 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
532 case GREP_NOT: fprintf(stderr, "*not*"); break;
533 case GREP_OR: fprintf(stderr, "*or*"); break;
535 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
536 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
537 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
542 case GREP_PATTERN_HEAD:
543 fprintf(stderr, "<head %d>", p->field); break;
544 case GREP_PATTERN_BODY:
545 fprintf(stderr, "<body>"); break;
549 case GREP_PATTERN_HEAD:
550 case GREP_PATTERN_BODY:
552 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
558 static void dump_grep_expression_1(struct grep_expr *x, int in)
563 fprintf(stderr, "true\n");
566 dump_grep_pat(x->u.atom);
569 fprintf(stderr, "(not\n");
570 dump_grep_expression_1(x->u.unary, in+1);
572 fprintf(stderr, ")\n");
575 fprintf(stderr, "(and\n");
576 dump_grep_expression_1(x->u.binary.left, in+1);
577 dump_grep_expression_1(x->u.binary.right, in+1);
579 fprintf(stderr, ")\n");
582 fprintf(stderr, "(or\n");
583 dump_grep_expression_1(x->u.binary.left, in+1);
584 dump_grep_expression_1(x->u.binary.right, in+1);
586 fprintf(stderr, ")\n");
591 static void dump_grep_expression(struct grep_opt *opt)
593 struct grep_expr *x = opt->pattern_expression;
596 fprintf(stderr, "[all-match]\n");
597 dump_grep_expression_1(x, 0);
601 static struct grep_expr *grep_true_expr(void)
603 struct grep_expr *z = xcalloc(1, sizeof(*z));
604 z->node = GREP_NODE_TRUE;
608 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
610 struct grep_expr *z = xcalloc(1, sizeof(*z));
611 z->node = GREP_NODE_OR;
612 z->u.binary.left = left;
613 z->u.binary.right = right;
617 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
620 struct grep_expr *header_expr;
621 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
622 enum grep_header_field fld;
624 if (!opt->header_list)
627 for (p = opt->header_list; p; p = p->next) {
628 if (p->token != GREP_PATTERN_HEAD)
629 die("bug: a non-header pattern in grep header list.");
630 if (p->field < GREP_HEADER_FIELD_MIN ||
631 GREP_HEADER_FIELD_MAX <= p->field)
632 die("bug: unknown header field %d", p->field);
633 compile_regexp(p, opt);
636 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
637 header_group[fld] = NULL;
639 for (p = opt->header_list; p; p = p->next) {
641 struct grep_pat *pp = p;
643 h = compile_pattern_atom(&pp);
644 if (!h || pp != p->next)
645 die("bug: malformed header expr");
646 if (!header_group[p->field]) {
647 header_group[p->field] = h;
650 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
655 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
656 if (!header_group[fld])
659 header_expr = grep_true_expr();
660 header_expr = grep_or_expr(header_group[fld], header_expr);
665 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
667 struct grep_expr *z = x;
670 assert(x->node == GREP_NODE_OR);
671 if (x->u.binary.right &&
672 x->u.binary.right->node == GREP_NODE_TRUE) {
673 x->u.binary.right = y;
676 x = x->u.binary.right;
681 static void compile_grep_patterns_real(struct grep_opt *opt)
684 struct grep_expr *header_expr = prep_header_patterns(opt);
686 for (p = opt->pattern_list; p; p = p->next) {
688 case GREP_PATTERN: /* atom */
689 case GREP_PATTERN_HEAD:
690 case GREP_PATTERN_BODY:
691 compile_regexp(p, opt);
699 if (opt->all_match || header_expr)
701 else if (!opt->extended && !opt->debug)
704 p = opt->pattern_list;
706 opt->pattern_expression = compile_pattern_expr(&p);
708 die("incomplete pattern expression: %s", p->pattern);
713 if (!opt->pattern_expression)
714 opt->pattern_expression = header_expr;
715 else if (opt->all_match)
716 opt->pattern_expression = grep_splice_or(header_expr,
717 opt->pattern_expression);
719 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
724 void compile_grep_patterns(struct grep_opt *opt)
726 compile_grep_patterns_real(opt);
728 dump_grep_expression(opt);
731 static void free_pattern_expr(struct grep_expr *x)
738 free_pattern_expr(x->u.unary);
742 free_pattern_expr(x->u.binary.left);
743 free_pattern_expr(x->u.binary.right);
749 void free_grep_patterns(struct grep_opt *opt)
751 struct grep_pat *p, *n;
753 for (p = opt->pattern_list; p; p = n) {
756 case GREP_PATTERN: /* atom */
757 case GREP_PATTERN_HEAD:
758 case GREP_PATTERN_BODY:
761 else if (p->pcre_regexp)
775 free_pattern_expr(opt->pattern_expression);
778 static char *end_of_line(char *cp, unsigned long *left)
780 unsigned long l = *left;
781 while (l && *cp != '\n') {
789 static int word_char(char ch)
791 return isalnum(ch) || ch == '_';
794 static void output_color(struct grep_opt *opt, const void *data, size_t size,
797 if (want_color(opt->color) && color && color[0]) {
798 opt->output(opt, color, strlen(color));
799 opt->output(opt, data, size);
800 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
802 opt->output(opt, data, size);
805 static void output_sep(struct grep_opt *opt, char sign)
807 if (opt->null_following_name)
808 opt->output(opt, "\0", 1);
810 output_color(opt, &sign, 1, opt->color_sep);
813 static void show_name(struct grep_opt *opt, const char *name)
815 output_color(opt, name, strlen(name), opt->color_filename);
816 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
819 static int fixmatch(struct grep_pat *p, char *line, char *eol,
822 struct kwsmatch kwsm;
823 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
825 match->rm_so = match->rm_eo = -1;
828 match->rm_so = offset;
829 match->rm_eo = match->rm_so + kwsm.size[0];
834 static int regmatch(const regex_t *preg, char *line, char *eol,
835 regmatch_t *match, int eflags)
839 match->rm_eo = eol - line;
840 eflags |= REG_STARTEND;
842 return regexec(preg, line, 1, match, eflags);
845 static int patmatch(struct grep_pat *p, char *line, char *eol,
846 regmatch_t *match, int eflags)
851 hit = !fixmatch(p, line, eol, match);
852 else if (p->pcre_regexp)
853 hit = !pcrematch(p, line, eol, match, eflags);
855 hit = !regmatch(&p->regexp, line, eol, match, eflags);
860 static int strip_timestamp(char *bol, char **eol_p)
865 while (bol < --eol) {
881 { "committer ", 10 },
885 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
886 enum grep_context ctx,
887 regmatch_t *pmatch, int eflags)
891 const char *start = bol;
893 if ((p->token != GREP_PATTERN) &&
894 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
897 if (p->token == GREP_PATTERN_HEAD) {
900 assert(p->field < ARRAY_SIZE(header_field));
901 field = header_field[p->field].field;
902 len = header_field[p->field].len;
903 if (strncmp(bol, field, len))
907 case GREP_HEADER_AUTHOR:
908 case GREP_HEADER_COMMITTER:
909 saved_ch = strip_timestamp(bol, &eol);
917 hit = patmatch(p, bol, eol, pmatch, eflags);
919 if (hit && p->word_regexp) {
920 if ((pmatch[0].rm_so < 0) ||
921 (eol - bol) < pmatch[0].rm_so ||
922 (pmatch[0].rm_eo < 0) ||
923 (eol - bol) < pmatch[0].rm_eo)
924 die("regexp returned nonsense");
926 /* Match beginning must be either beginning of the
927 * line, or at word boundary (i.e. the last char must
928 * not be a word char). Similarly, match end must be
929 * either end of the line, or at word boundary
930 * (i.e. the next char must not be a word char).
932 if ( ((pmatch[0].rm_so == 0) ||
933 !word_char(bol[pmatch[0].rm_so-1])) &&
934 ((pmatch[0].rm_eo == (eol-bol)) ||
935 !word_char(bol[pmatch[0].rm_eo])) )
940 /* Words consist of at least one character. */
941 if (pmatch->rm_so == pmatch->rm_eo)
944 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
945 /* There could be more than one match on the
946 * line, and the first match might not be
947 * strict word match. But later ones could be!
948 * Forward to the next possible start, i.e. the
949 * next position following a non-word char.
951 bol = pmatch[0].rm_so + bol + 1;
952 while (word_char(bol[-1]) && bol < eol)
954 eflags |= REG_NOTBOL;
959 if (p->token == GREP_PATTERN_HEAD && saved_ch)
962 pmatch[0].rm_so += bol - start;
963 pmatch[0].rm_eo += bol - start;
968 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
969 enum grep_context ctx, int collect_hits)
975 die("Not a valid grep expression");
981 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
984 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
987 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
989 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
993 return (match_expr_eval(x->u.binary.left,
995 match_expr_eval(x->u.binary.right,
997 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
998 x->u.binary.left->hit |= h;
999 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1002 die("Unexpected node type (internal error) %d", x->node);
1009 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1010 enum grep_context ctx, int collect_hits)
1012 struct grep_expr *x = opt->pattern_expression;
1013 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1016 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1017 enum grep_context ctx, int collect_hits)
1023 return match_expr(opt, bol, eol, ctx, collect_hits);
1025 /* we do not call with collect_hits without being extended */
1026 for (p = opt->pattern_list; p; p = p->next) {
1027 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1033 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1034 enum grep_context ctx,
1035 regmatch_t *pmatch, int eflags)
1039 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1041 if (match.rm_so < 0 || match.rm_eo < 0)
1043 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1044 if (match.rm_so > pmatch->rm_so)
1046 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1049 pmatch->rm_so = match.rm_so;
1050 pmatch->rm_eo = match.rm_eo;
1054 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1055 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1060 pmatch->rm_so = pmatch->rm_eo = -1;
1062 for (p = opt->pattern_list; p; p = p->next) {
1064 case GREP_PATTERN: /* atom */
1065 case GREP_PATTERN_HEAD:
1066 case GREP_PATTERN_BODY:
1067 hit |= match_next_pattern(p, bol, eol, ctx,
1078 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1079 const char *name, unsigned lno, char sign)
1081 int rest = eol - bol;
1082 char *line_color = NULL;
1084 if (opt->file_break && opt->last_shown == 0) {
1085 if (opt->show_hunk_mark)
1086 opt->output(opt, "\n", 1);
1087 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1088 if (opt->last_shown == 0) {
1089 if (opt->show_hunk_mark) {
1090 output_color(opt, "--", 2, opt->color_sep);
1091 opt->output(opt, "\n", 1);
1093 } else if (lno > opt->last_shown + 1) {
1094 output_color(opt, "--", 2, opt->color_sep);
1095 opt->output(opt, "\n", 1);
1098 if (opt->heading && opt->last_shown == 0) {
1099 output_color(opt, name, strlen(name), opt->color_filename);
1100 opt->output(opt, "\n", 1);
1102 opt->last_shown = lno;
1104 if (!opt->heading && opt->pathname) {
1105 output_color(opt, name, strlen(name), opt->color_filename);
1106 output_sep(opt, sign);
1110 snprintf(buf, sizeof(buf), "%d", lno);
1111 output_color(opt, buf, strlen(buf), opt->color_lineno);
1112 output_sep(opt, sign);
1116 enum grep_context ctx = GREP_CONTEXT_BODY;
1121 line_color = opt->color_selected;
1122 else if (sign == '-')
1123 line_color = opt->color_context;
1124 else if (sign == '=')
1125 line_color = opt->color_function;
1127 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1128 if (match.rm_so == match.rm_eo)
1131 output_color(opt, bol, match.rm_so, line_color);
1132 output_color(opt, bol + match.rm_so,
1133 match.rm_eo - match.rm_so,
1136 rest -= match.rm_eo;
1137 eflags = REG_NOTBOL;
1141 output_color(opt, bol, rest, line_color);
1142 opt->output(opt, "\n", 1);
1149 * This lock protects access to the gitattributes machinery, which is
1152 pthread_mutex_t grep_attr_mutex;
1154 static inline void grep_attr_lock(void)
1157 pthread_mutex_lock(&grep_attr_mutex);
1160 static inline void grep_attr_unlock(void)
1163 pthread_mutex_unlock(&grep_attr_mutex);
1167 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1169 pthread_mutex_t grep_read_mutex;
1172 #define grep_attr_lock()
1173 #define grep_attr_unlock()
1176 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1178 xdemitconf_t *xecfg = opt->priv;
1179 if (xecfg && !xecfg->find_func) {
1180 grep_source_load_driver(gs);
1181 if (gs->driver->funcname.pattern) {
1182 const struct userdiff_funcname *pe = &gs->driver->funcname;
1183 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1185 xecfg = opt->priv = NULL;
1191 return xecfg->find_func(bol, eol - bol, buf, 1,
1192 xecfg->find_func_priv) >= 0;
1197 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1202 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1203 char *bol, unsigned lno)
1205 while (bol > gs->buf) {
1208 while (bol > gs->buf && bol[-1] != '\n')
1212 if (lno <= opt->last_shown)
1215 if (match_funcname(opt, gs, bol, eol)) {
1216 show_line(opt, bol, eol, gs->name, lno, '=');
1222 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1223 char *bol, char *end, unsigned lno)
1225 unsigned cur = lno, from = 1, funcname_lno = 0;
1226 int funcname_needed = !!opt->funcname;
1228 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1229 funcname_needed = 2;
1231 if (opt->pre_context < lno)
1232 from = lno - opt->pre_context;
1233 if (from <= opt->last_shown)
1234 from = opt->last_shown + 1;
1237 while (bol > gs->buf &&
1238 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1241 while (bol > gs->buf && bol[-1] != '\n')
1244 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1246 funcname_needed = 0;
1250 /* We need to look even further back to find a function signature. */
1251 if (opt->funcname && funcname_needed)
1252 show_funcname_line(opt, gs, bol, cur);
1256 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1258 while (*eol != '\n')
1260 show_line(opt, bol, eol, gs->name, cur, sign);
1266 static int should_lookahead(struct grep_opt *opt)
1271 return 0; /* punt for too complex stuff */
1274 for (p = opt->pattern_list; p; p = p->next) {
1275 if (p->token != GREP_PATTERN)
1276 return 0; /* punt for "header only" and stuff */
1281 static int look_ahead(struct grep_opt *opt,
1282 unsigned long *left_p,
1286 unsigned lno = *lno_p;
1289 char *sp, *last_bol;
1290 regoff_t earliest = -1;
1292 for (p = opt->pattern_list; p; p = p->next) {
1296 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1297 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1299 if (earliest < 0 || m.rm_so < earliest)
1304 *bol_p = bol + *left_p;
1308 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1309 ; /* find the beginning of the line */
1312 for (sp = bol; sp < last_bol; sp++) {
1316 *left_p -= last_bol - bol;
1322 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1324 fwrite(buf, size, 1, stdout);
1327 static int fill_textconv_grep(struct userdiff_driver *driver,
1328 struct grep_source *gs)
1330 struct diff_filespec *df;
1334 if (!driver || !driver->textconv)
1335 return grep_source_load(gs);
1338 * The textconv interface is intimately tied to diff_filespecs, so we
1339 * have to pretend to be one. If we could unify the grep_source
1340 * and diff_filespec structs, this mess could just go away.
1342 df = alloc_filespec(gs->path);
1344 case GREP_SOURCE_SHA1:
1345 fill_filespec(df, gs->identifier, 1, 0100644);
1347 case GREP_SOURCE_FILE:
1348 fill_filespec(df, null_sha1, 0, 0100644);
1351 die("BUG: attempt to textconv something without a path?");
1355 * fill_textconv is not remotely thread-safe; it may load objects
1356 * behind the scenes, and it modifies the global diff tempfile
1360 size = fill_textconv(driver, df, &buf);
1365 * The normal fill_textconv usage by the diff machinery would just keep
1366 * the textconv'd buf separate from the diff_filespec. But much of the
1367 * grep code passes around a grep_source and assumes that its "buf"
1368 * pointer is the beginning of the thing we are searching. So let's
1369 * install our textconv'd version into the grep_source, taking care not
1370 * to leak any existing buffer.
1372 grep_source_clear_data(gs);
1379 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1384 unsigned last_hit = 0;
1385 int binary_match_only = 0;
1387 int try_lookahead = 0;
1388 int show_function = 0;
1389 struct userdiff_driver *textconv = NULL;
1390 enum grep_context ctx = GREP_CONTEXT_HEAD;
1394 opt->output = std_output;
1396 if (opt->pre_context || opt->post_context || opt->file_break ||
1398 /* Show hunk marks, except for the first file. */
1399 if (opt->last_shown)
1400 opt->show_hunk_mark = 1;
1402 * If we're using threads then we can't easily identify
1403 * the first file. Always put hunk marks in that case
1404 * and skip the very first one later in work_done().
1406 if (opt->output != std_output)
1407 opt->show_hunk_mark = 1;
1409 opt->last_shown = 0;
1411 if (opt->allow_textconv) {
1412 grep_source_load_driver(gs);
1414 * We might set up the shared textconv cache data here, which
1415 * is not thread-safe.
1418 textconv = userdiff_get_textconv(gs->driver);
1423 * We know the result of a textconv is text, so we only have to care
1424 * about binary handling if we are not using it.
1427 switch (opt->binary) {
1428 case GREP_BINARY_DEFAULT:
1429 if (grep_source_is_binary(gs))
1430 binary_match_only = 1;
1432 case GREP_BINARY_NOMATCH:
1433 if (grep_source_is_binary(gs))
1434 return 0; /* Assume unmatch */
1436 case GREP_BINARY_TEXT:
1439 die("bug: unknown binary handling mode");
1443 memset(&xecfg, 0, sizeof(xecfg));
1446 try_lookahead = should_lookahead(opt);
1448 if (fill_textconv_grep(textconv, gs) < 0)
1458 * look_ahead() skips quickly to the line that possibly
1459 * has the next hit; don't call it if we need to do
1460 * something more than just skipping the current line
1461 * in response to an unmatch for the current line. E.g.
1462 * inside a post-context window, we will show the current
1463 * line as a context around the previous hit when it
1468 && (show_function ||
1469 lno <= last_hit + opt->post_context))
1470 && look_ahead(opt, &left, &lno, &bol))
1472 eol = end_of_line(bol, &left);
1476 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1477 ctx = GREP_CONTEXT_BODY;
1479 hit = match_line(opt, bol, eol, ctx, collect_hits);
1485 /* "grep -v -e foo -e bla" should list lines
1486 * that do not have either, so inversion should
1491 if (opt->unmatch_name_only) {
1498 if (opt->status_only)
1500 if (opt->name_only) {
1501 show_name(opt, gs->name);
1506 if (binary_match_only) {
1507 opt->output(opt, "Binary file ", 12);
1508 output_color(opt, gs->name, strlen(gs->name),
1509 opt->color_filename);
1510 opt->output(opt, " matches\n", 9);
1513 /* Hit at this line. If we haven't shown the
1514 * pre-context lines, we would need to show them.
1516 if (opt->pre_context || opt->funcbody)
1517 show_pre_context(opt, gs, bol, eol, lno);
1518 else if (opt->funcname)
1519 show_funcname_line(opt, gs, bol, lno);
1520 show_line(opt, bol, eol, gs->name, lno, ':');
1526 if (show_function && match_funcname(opt, gs, bol, eol))
1528 if (show_function ||
1529 (last_hit && lno <= last_hit + opt->post_context)) {
1530 /* If the last hit is within the post context,
1531 * we need to show this line.
1533 show_line(opt, bol, eol, gs->name, lno, '-');
1547 if (opt->status_only)
1549 if (opt->unmatch_name_only) {
1550 /* We did not see any hit, so we want to show this */
1551 show_name(opt, gs->name);
1555 xdiff_clear_find_func(&xecfg);
1559 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1560 * which feels mostly useless but sometimes useful. Maybe
1561 * make it another option? For now suppress them.
1563 if (opt->count && count) {
1565 if (opt->pathname) {
1566 output_color(opt, gs->name, strlen(gs->name),
1567 opt->color_filename);
1568 output_sep(opt, ':');
1570 snprintf(buf, sizeof(buf), "%u\n", count);
1571 opt->output(opt, buf, strlen(buf));
1577 static void clr_hit_marker(struct grep_expr *x)
1579 /* All-hit markers are meaningful only at the very top level
1584 if (x->node != GREP_NODE_OR)
1586 x->u.binary.left->hit = 0;
1587 x = x->u.binary.right;
1591 static int chk_hit_marker(struct grep_expr *x)
1593 /* Top level nodes have hit markers. See if they all are hits */
1595 if (x->node != GREP_NODE_OR)
1597 if (!x->u.binary.left->hit)
1599 x = x->u.binary.right;
1603 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1606 * we do not have to do the two-pass grep when we do not check
1607 * buffer-wide "all-match".
1609 if (!opt->all_match)
1610 return grep_source_1(opt, gs, 0);
1612 /* Otherwise the toplevel "or" terms hit a bit differently.
1613 * We first clear hit markers from them.
1615 clr_hit_marker(opt->pattern_expression);
1616 grep_source_1(opt, gs, 1);
1618 if (!chk_hit_marker(opt->pattern_expression))
1621 return grep_source_1(opt, gs, 0);
1624 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1626 struct grep_source gs;
1629 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1633 r = grep_source(opt, &gs);
1635 grep_source_clear(&gs);
1639 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1640 const char *name, const char *path,
1641 const void *identifier)
1644 gs->name = name ? xstrdup(name) : NULL;
1645 gs->path = path ? xstrdup(path) : NULL;
1651 case GREP_SOURCE_FILE:
1652 gs->identifier = xstrdup(identifier);
1654 case GREP_SOURCE_SHA1:
1655 gs->identifier = xmalloc(20);
1656 hashcpy(gs->identifier, identifier);
1658 case GREP_SOURCE_BUF:
1659 gs->identifier = NULL;
1663 void grep_source_clear(struct grep_source *gs)
1669 free(gs->identifier);
1670 gs->identifier = NULL;
1671 grep_source_clear_data(gs);
1674 void grep_source_clear_data(struct grep_source *gs)
1677 case GREP_SOURCE_FILE:
1678 case GREP_SOURCE_SHA1:
1683 case GREP_SOURCE_BUF:
1684 /* leave user-provided buf intact */
1689 static int grep_source_load_sha1(struct grep_source *gs)
1691 enum object_type type;
1694 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1698 return error(_("'%s': unable to read %s"),
1700 sha1_to_hex(gs->identifier));
1704 static int grep_source_load_file(struct grep_source *gs)
1706 const char *filename = gs->identifier;
1712 if (lstat(filename, &st) < 0) {
1714 if (errno != ENOENT)
1715 error(_("'%s': %s"), filename, strerror(errno));
1718 if (!S_ISREG(st.st_mode))
1720 size = xsize_t(st.st_size);
1721 i = open(filename, O_RDONLY);
1724 data = xmalloc(size + 1);
1725 if (st.st_size != read_in_full(i, data, size)) {
1726 error(_("'%s': short read %s"), filename, strerror(errno));
1739 static int grep_source_load(struct grep_source *gs)
1745 case GREP_SOURCE_FILE:
1746 return grep_source_load_file(gs);
1747 case GREP_SOURCE_SHA1:
1748 return grep_source_load_sha1(gs);
1749 case GREP_SOURCE_BUF:
1750 return gs->buf ? 0 : -1;
1752 die("BUG: invalid grep_source type");
1755 void grep_source_load_driver(struct grep_source *gs)
1762 gs->driver = userdiff_find_by_path(gs->path);
1764 gs->driver = userdiff_find_by_name("default");
1768 static int grep_source_is_binary(struct grep_source *gs)
1770 grep_source_load_driver(gs);
1771 if (gs->driver->binary != -1)
1772 return gs->driver->binary;
1774 if (!grep_source_load(gs))
1775 return buffer_is_binary(gs->buf, gs->size);