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, 0, &error);
369 if (!p->pcre1_extra_info && error)
373 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
374 regmatch_t *match, int eflags)
376 int ovector[30], ret, flags = 0;
378 if (eflags & REG_NOTBOL)
379 flags |= PCRE_NOTBOL;
381 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line, eol - line,
382 0, flags, ovector, ARRAY_SIZE(ovector));
383 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
384 die("pcre_exec failed with error code %d", ret);
387 match->rm_so = ovector[0];
388 match->rm_eo = ovector[1];
394 static void free_pcre1_regexp(struct grep_pat *p)
396 pcre_free(p->pcre1_regexp);
397 pcre_free(p->pcre1_extra_info);
398 pcre_free((void *)p->pcre1_tables);
400 #else /* !USE_LIBPCRE1 */
401 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
403 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
406 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
407 regmatch_t *match, int eflags)
412 static void free_pcre1_regexp(struct grep_pat *p)
415 #endif /* !USE_LIBPCRE1 */
417 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
419 struct strbuf sb = STRBUF_INIT;
421 int regflags = opt->regflags;
423 basic_regex_quote_buf(&sb, p->pattern);
424 if (opt->ignore_case)
425 regflags |= REG_ICASE;
426 err = regcomp(&p->regexp, sb.buf, regflags);
428 fprintf(stderr, "fixed %s\n", sb.buf);
432 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
434 compile_regexp_failed(p, errbuf);
438 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
440 int icase, ascii_only;
443 p->word_regexp = opt->word_regexp;
444 p->ignore_case = opt->ignore_case;
445 icase = opt->regflags & REG_ICASE || p->ignore_case;
446 ascii_only = !has_non_ascii(p->pattern);
449 * Even when -F (fixed) asks us to do a non-regexp search, we
450 * may not be able to correctly case-fold when -i
451 * (ignore-case) is asked (in which case, we'll synthesize a
452 * regexp to match the pattern that matches regexp special
453 * characters literally, while ignoring case differences). On
454 * the other hand, even without -F, if the pattern does not
455 * have any regexp special characters and there is no need for
456 * case-folding search, we can internally turn it into a
457 * simple string match using kws. p->fixed tells us if we
461 has_null(p->pattern, p->patternlen) ||
462 is_fixed(p->pattern, p->patternlen))
463 p->fixed = !icase || ascii_only;
468 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
469 kwsincr(p->kws, p->pattern, p->patternlen);
472 } else if (opt->fixed) {
474 * We come here when the pattern has the non-ascii
475 * characters we cannot case-fold, and asked to
478 compile_fixed_regexp(p, opt);
483 compile_pcre1_regexp(p, opt);
487 err = regcomp(&p->regexp, p->pattern, opt->regflags);
490 regerror(err, &p->regexp, errbuf, 1024);
492 compile_regexp_failed(p, errbuf);
496 static struct grep_expr *compile_pattern_or(struct grep_pat **);
497 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
506 case GREP_PATTERN: /* atom */
507 case GREP_PATTERN_HEAD:
508 case GREP_PATTERN_BODY:
509 x = xcalloc(1, sizeof (struct grep_expr));
510 x->node = GREP_NODE_ATOM;
514 case GREP_OPEN_PAREN:
516 x = compile_pattern_or(list);
517 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
518 die("unmatched parenthesis");
519 *list = (*list)->next;
526 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
537 die("--not not followed by pattern expression");
539 x = xcalloc(1, sizeof (struct grep_expr));
540 x->node = GREP_NODE_NOT;
541 x->u.unary = compile_pattern_not(list);
543 die("--not followed by non pattern expression");
546 return compile_pattern_atom(list);
550 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
553 struct grep_expr *x, *y, *z;
555 x = compile_pattern_not(list);
557 if (p && p->token == GREP_AND) {
559 die("--and not followed by pattern expression");
561 y = compile_pattern_and(list);
563 die("--and not followed by pattern expression");
564 z = xcalloc(1, sizeof (struct grep_expr));
565 z->node = GREP_NODE_AND;
566 z->u.binary.left = x;
567 z->u.binary.right = y;
573 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
576 struct grep_expr *x, *y, *z;
578 x = compile_pattern_and(list);
580 if (x && p && p->token != GREP_CLOSE_PAREN) {
581 y = compile_pattern_or(list);
583 die("not a pattern expression %s", p->pattern);
584 z = xcalloc(1, sizeof (struct grep_expr));
585 z->node = GREP_NODE_OR;
586 z->u.binary.left = x;
587 z->u.binary.right = y;
593 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
595 return compile_pattern_or(list);
598 static void indent(int in)
604 static void dump_grep_pat(struct grep_pat *p)
607 case GREP_AND: fprintf(stderr, "*and*"); break;
608 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
609 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
610 case GREP_NOT: fprintf(stderr, "*not*"); break;
611 case GREP_OR: fprintf(stderr, "*or*"); break;
613 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
614 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
615 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
620 case GREP_PATTERN_HEAD:
621 fprintf(stderr, "<head %d>", p->field); break;
622 case GREP_PATTERN_BODY:
623 fprintf(stderr, "<body>"); break;
627 case GREP_PATTERN_HEAD:
628 case GREP_PATTERN_BODY:
630 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
636 static void dump_grep_expression_1(struct grep_expr *x, int in)
641 fprintf(stderr, "true\n");
644 dump_grep_pat(x->u.atom);
647 fprintf(stderr, "(not\n");
648 dump_grep_expression_1(x->u.unary, in+1);
650 fprintf(stderr, ")\n");
653 fprintf(stderr, "(and\n");
654 dump_grep_expression_1(x->u.binary.left, in+1);
655 dump_grep_expression_1(x->u.binary.right, in+1);
657 fprintf(stderr, ")\n");
660 fprintf(stderr, "(or\n");
661 dump_grep_expression_1(x->u.binary.left, in+1);
662 dump_grep_expression_1(x->u.binary.right, in+1);
664 fprintf(stderr, ")\n");
669 static void dump_grep_expression(struct grep_opt *opt)
671 struct grep_expr *x = opt->pattern_expression;
674 fprintf(stderr, "[all-match]\n");
675 dump_grep_expression_1(x, 0);
679 static struct grep_expr *grep_true_expr(void)
681 struct grep_expr *z = xcalloc(1, sizeof(*z));
682 z->node = GREP_NODE_TRUE;
686 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
688 struct grep_expr *z = xcalloc(1, sizeof(*z));
689 z->node = GREP_NODE_OR;
690 z->u.binary.left = left;
691 z->u.binary.right = right;
695 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
698 struct grep_expr *header_expr;
699 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
700 enum grep_header_field fld;
702 if (!opt->header_list)
705 for (p = opt->header_list; p; p = p->next) {
706 if (p->token != GREP_PATTERN_HEAD)
707 die("BUG: a non-header pattern in grep header list.");
708 if (p->field < GREP_HEADER_FIELD_MIN ||
709 GREP_HEADER_FIELD_MAX <= p->field)
710 die("BUG: unknown header field %d", p->field);
711 compile_regexp(p, opt);
714 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
715 header_group[fld] = NULL;
717 for (p = opt->header_list; p; p = p->next) {
719 struct grep_pat *pp = p;
721 h = compile_pattern_atom(&pp);
722 if (!h || pp != p->next)
723 die("BUG: malformed header expr");
724 if (!header_group[p->field]) {
725 header_group[p->field] = h;
728 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
733 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
734 if (!header_group[fld])
737 header_expr = grep_true_expr();
738 header_expr = grep_or_expr(header_group[fld], header_expr);
743 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
745 struct grep_expr *z = x;
748 assert(x->node == GREP_NODE_OR);
749 if (x->u.binary.right &&
750 x->u.binary.right->node == GREP_NODE_TRUE) {
751 x->u.binary.right = y;
754 x = x->u.binary.right;
759 static void compile_grep_patterns_real(struct grep_opt *opt)
762 struct grep_expr *header_expr = prep_header_patterns(opt);
764 for (p = opt->pattern_list; p; p = p->next) {
766 case GREP_PATTERN: /* atom */
767 case GREP_PATTERN_HEAD:
768 case GREP_PATTERN_BODY:
769 compile_regexp(p, opt);
777 if (opt->all_match || header_expr)
779 else if (!opt->extended && !opt->debug)
782 p = opt->pattern_list;
784 opt->pattern_expression = compile_pattern_expr(&p);
786 die("incomplete pattern expression: %s", p->pattern);
791 if (!opt->pattern_expression)
792 opt->pattern_expression = header_expr;
793 else if (opt->all_match)
794 opt->pattern_expression = grep_splice_or(header_expr,
795 opt->pattern_expression);
797 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
802 void compile_grep_patterns(struct grep_opt *opt)
804 compile_grep_patterns_real(opt);
806 dump_grep_expression(opt);
809 static void free_pattern_expr(struct grep_expr *x)
816 free_pattern_expr(x->u.unary);
820 free_pattern_expr(x->u.binary.left);
821 free_pattern_expr(x->u.binary.right);
827 void free_grep_patterns(struct grep_opt *opt)
829 struct grep_pat *p, *n;
831 for (p = opt->pattern_list; p; p = n) {
834 case GREP_PATTERN: /* atom */
835 case GREP_PATTERN_HEAD:
836 case GREP_PATTERN_BODY:
839 else if (p->pcre1_regexp)
840 free_pcre1_regexp(p);
853 free_pattern_expr(opt->pattern_expression);
856 static char *end_of_line(char *cp, unsigned long *left)
858 unsigned long l = *left;
859 while (l && *cp != '\n') {
867 static int word_char(char ch)
869 return isalnum(ch) || ch == '_';
872 static void output_color(struct grep_opt *opt, const void *data, size_t size,
875 if (want_color(opt->color) && color && color[0]) {
876 opt->output(opt, color, strlen(color));
877 opt->output(opt, data, size);
878 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
880 opt->output(opt, data, size);
883 static void output_sep(struct grep_opt *opt, char sign)
885 if (opt->null_following_name)
886 opt->output(opt, "\0", 1);
888 output_color(opt, &sign, 1, opt->color_sep);
891 static void show_name(struct grep_opt *opt, const char *name)
893 output_color(opt, name, strlen(name), opt->color_filename);
894 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
897 static int fixmatch(struct grep_pat *p, char *line, char *eol,
900 struct kwsmatch kwsm;
901 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
903 match->rm_so = match->rm_eo = -1;
906 match->rm_so = offset;
907 match->rm_eo = match->rm_so + kwsm.size[0];
912 static int patmatch(struct grep_pat *p, char *line, char *eol,
913 regmatch_t *match, int eflags)
918 hit = !fixmatch(p, line, eol, match);
919 else if (p->pcre1_regexp)
920 hit = !pcre1match(p, line, eol, match, eflags);
922 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
928 static int strip_timestamp(char *bol, char **eol_p)
933 while (bol < --eol) {
949 { "committer ", 10 },
953 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
954 enum grep_context ctx,
955 regmatch_t *pmatch, int eflags)
959 const char *start = bol;
961 if ((p->token != GREP_PATTERN) &&
962 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
965 if (p->token == GREP_PATTERN_HEAD) {
968 assert(p->field < ARRAY_SIZE(header_field));
969 field = header_field[p->field].field;
970 len = header_field[p->field].len;
971 if (strncmp(bol, field, len))
975 case GREP_HEADER_AUTHOR:
976 case GREP_HEADER_COMMITTER:
977 saved_ch = strip_timestamp(bol, &eol);
985 hit = patmatch(p, bol, eol, pmatch, eflags);
987 if (hit && p->word_regexp) {
988 if ((pmatch[0].rm_so < 0) ||
989 (eol - bol) < pmatch[0].rm_so ||
990 (pmatch[0].rm_eo < 0) ||
991 (eol - bol) < pmatch[0].rm_eo)
992 die("regexp returned nonsense");
994 /* Match beginning must be either beginning of the
995 * line, or at word boundary (i.e. the last char must
996 * not be a word char). Similarly, match end must be
997 * either end of the line, or at word boundary
998 * (i.e. the next char must not be a word char).
1000 if ( ((pmatch[0].rm_so == 0) ||
1001 !word_char(bol[pmatch[0].rm_so-1])) &&
1002 ((pmatch[0].rm_eo == (eol-bol)) ||
1003 !word_char(bol[pmatch[0].rm_eo])) )
1008 /* Words consist of at least one character. */
1009 if (pmatch->rm_so == pmatch->rm_eo)
1012 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1013 /* There could be more than one match on the
1014 * line, and the first match might not be
1015 * strict word match. But later ones could be!
1016 * Forward to the next possible start, i.e. the
1017 * next position following a non-word char.
1019 bol = pmatch[0].rm_so + bol + 1;
1020 while (word_char(bol[-1]) && bol < eol)
1022 eflags |= REG_NOTBOL;
1027 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1030 pmatch[0].rm_so += bol - start;
1031 pmatch[0].rm_eo += bol - start;
1036 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1037 enum grep_context ctx, int collect_hits)
1043 die("Not a valid grep expression");
1045 case GREP_NODE_TRUE:
1048 case GREP_NODE_ATOM:
1049 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1052 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1055 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1057 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1061 return (match_expr_eval(x->u.binary.left,
1062 bol, eol, ctx, 0) ||
1063 match_expr_eval(x->u.binary.right,
1065 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1066 x->u.binary.left->hit |= h;
1067 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1070 die("Unexpected node type (internal error) %d", x->node);
1077 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1078 enum grep_context ctx, int collect_hits)
1080 struct grep_expr *x = opt->pattern_expression;
1081 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1084 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1085 enum grep_context ctx, int collect_hits)
1091 return match_expr(opt, bol, eol, ctx, collect_hits);
1093 /* we do not call with collect_hits without being extended */
1094 for (p = opt->pattern_list; p; p = p->next) {
1095 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1101 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1102 enum grep_context ctx,
1103 regmatch_t *pmatch, int eflags)
1107 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1109 if (match.rm_so < 0 || match.rm_eo < 0)
1111 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1112 if (match.rm_so > pmatch->rm_so)
1114 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1117 pmatch->rm_so = match.rm_so;
1118 pmatch->rm_eo = match.rm_eo;
1122 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1123 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1128 pmatch->rm_so = pmatch->rm_eo = -1;
1130 for (p = opt->pattern_list; p; p = p->next) {
1132 case GREP_PATTERN: /* atom */
1133 case GREP_PATTERN_HEAD:
1134 case GREP_PATTERN_BODY:
1135 hit |= match_next_pattern(p, bol, eol, ctx,
1146 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1147 const char *name, unsigned lno, char sign)
1149 int rest = eol - bol;
1150 const char *match_color, *line_color = NULL;
1152 if (opt->file_break && opt->last_shown == 0) {
1153 if (opt->show_hunk_mark)
1154 opt->output(opt, "\n", 1);
1155 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1156 if (opt->last_shown == 0) {
1157 if (opt->show_hunk_mark) {
1158 output_color(opt, "--", 2, opt->color_sep);
1159 opt->output(opt, "\n", 1);
1161 } else if (lno > opt->last_shown + 1) {
1162 output_color(opt, "--", 2, opt->color_sep);
1163 opt->output(opt, "\n", 1);
1166 if (opt->heading && opt->last_shown == 0) {
1167 output_color(opt, name, strlen(name), opt->color_filename);
1168 opt->output(opt, "\n", 1);
1170 opt->last_shown = lno;
1172 if (!opt->heading && opt->pathname) {
1173 output_color(opt, name, strlen(name), opt->color_filename);
1174 output_sep(opt, sign);
1178 xsnprintf(buf, sizeof(buf), "%d", lno);
1179 output_color(opt, buf, strlen(buf), opt->color_lineno);
1180 output_sep(opt, sign);
1184 enum grep_context ctx = GREP_CONTEXT_BODY;
1189 match_color = opt->color_match_selected;
1191 match_color = opt->color_match_context;
1193 line_color = opt->color_selected;
1194 else if (sign == '-')
1195 line_color = opt->color_context;
1196 else if (sign == '=')
1197 line_color = opt->color_function;
1199 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1200 if (match.rm_so == match.rm_eo)
1203 output_color(opt, bol, match.rm_so, line_color);
1204 output_color(opt, bol + match.rm_so,
1205 match.rm_eo - match.rm_so, match_color);
1207 rest -= match.rm_eo;
1208 eflags = REG_NOTBOL;
1212 output_color(opt, bol, rest, line_color);
1213 opt->output(opt, "\n", 1);
1220 * This lock protects access to the gitattributes machinery, which is
1223 pthread_mutex_t grep_attr_mutex;
1225 static inline void grep_attr_lock(void)
1228 pthread_mutex_lock(&grep_attr_mutex);
1231 static inline void grep_attr_unlock(void)
1234 pthread_mutex_unlock(&grep_attr_mutex);
1238 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1240 pthread_mutex_t grep_read_mutex;
1243 #define grep_attr_lock()
1244 #define grep_attr_unlock()
1247 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1249 xdemitconf_t *xecfg = opt->priv;
1250 if (xecfg && !xecfg->find_func) {
1251 grep_source_load_driver(gs);
1252 if (gs->driver->funcname.pattern) {
1253 const struct userdiff_funcname *pe = &gs->driver->funcname;
1254 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1256 xecfg = opt->priv = NULL;
1262 return xecfg->find_func(bol, eol - bol, buf, 1,
1263 xecfg->find_func_priv) >= 0;
1268 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1273 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1274 char *bol, unsigned lno)
1276 while (bol > gs->buf) {
1279 while (bol > gs->buf && bol[-1] != '\n')
1283 if (lno <= opt->last_shown)
1286 if (match_funcname(opt, gs, bol, eol)) {
1287 show_line(opt, bol, eol, gs->name, lno, '=');
1293 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1294 char *bol, char *end, unsigned lno)
1296 unsigned cur = lno, from = 1, funcname_lno = 0;
1297 int funcname_needed = !!opt->funcname;
1299 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1300 funcname_needed = 2;
1302 if (opt->pre_context < lno)
1303 from = lno - opt->pre_context;
1304 if (from <= opt->last_shown)
1305 from = opt->last_shown + 1;
1308 while (bol > gs->buf &&
1309 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1312 while (bol > gs->buf && bol[-1] != '\n')
1315 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1317 funcname_needed = 0;
1321 /* We need to look even further back to find a function signature. */
1322 if (opt->funcname && funcname_needed)
1323 show_funcname_line(opt, gs, bol, cur);
1327 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1329 while (*eol != '\n')
1331 show_line(opt, bol, eol, gs->name, cur, sign);
1337 static int should_lookahead(struct grep_opt *opt)
1342 return 0; /* punt for too complex stuff */
1345 for (p = opt->pattern_list; p; p = p->next) {
1346 if (p->token != GREP_PATTERN)
1347 return 0; /* punt for "header only" and stuff */
1352 static int look_ahead(struct grep_opt *opt,
1353 unsigned long *left_p,
1357 unsigned lno = *lno_p;
1360 char *sp, *last_bol;
1361 regoff_t earliest = -1;
1363 for (p = opt->pattern_list; p; p = p->next) {
1367 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1368 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1370 if (earliest < 0 || m.rm_so < earliest)
1375 *bol_p = bol + *left_p;
1379 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1380 ; /* find the beginning of the line */
1383 for (sp = bol; sp < last_bol; sp++) {
1387 *left_p -= last_bol - bol;
1393 static int fill_textconv_grep(struct userdiff_driver *driver,
1394 struct grep_source *gs)
1396 struct diff_filespec *df;
1400 if (!driver || !driver->textconv)
1401 return grep_source_load(gs);
1404 * The textconv interface is intimately tied to diff_filespecs, so we
1405 * have to pretend to be one. If we could unify the grep_source
1406 * and diff_filespec structs, this mess could just go away.
1408 df = alloc_filespec(gs->path);
1410 case GREP_SOURCE_SHA1:
1411 fill_filespec(df, gs->identifier, 1, 0100644);
1413 case GREP_SOURCE_FILE:
1414 fill_filespec(df, null_sha1, 0, 0100644);
1417 die("BUG: attempt to textconv something without a path?");
1421 * fill_textconv is not remotely thread-safe; it may load objects
1422 * behind the scenes, and it modifies the global diff tempfile
1426 size = fill_textconv(driver, df, &buf);
1431 * The normal fill_textconv usage by the diff machinery would just keep
1432 * the textconv'd buf separate from the diff_filespec. But much of the
1433 * grep code passes around a grep_source and assumes that its "buf"
1434 * pointer is the beginning of the thing we are searching. So let's
1435 * install our textconv'd version into the grep_source, taking care not
1436 * to leak any existing buffer.
1438 grep_source_clear_data(gs);
1445 static int is_empty_line(const char *bol, const char *eol)
1447 while (bol < eol && isspace(*bol))
1452 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1455 char *peek_bol = NULL;
1458 unsigned last_hit = 0;
1459 int binary_match_only = 0;
1461 int try_lookahead = 0;
1462 int show_function = 0;
1463 struct userdiff_driver *textconv = NULL;
1464 enum grep_context ctx = GREP_CONTEXT_HEAD;
1468 opt->output = std_output;
1470 if (opt->pre_context || opt->post_context || opt->file_break ||
1472 /* Show hunk marks, except for the first file. */
1473 if (opt->last_shown)
1474 opt->show_hunk_mark = 1;
1476 * If we're using threads then we can't easily identify
1477 * the first file. Always put hunk marks in that case
1478 * and skip the very first one later in work_done().
1480 if (opt->output != std_output)
1481 opt->show_hunk_mark = 1;
1483 opt->last_shown = 0;
1485 if (opt->allow_textconv) {
1486 grep_source_load_driver(gs);
1488 * We might set up the shared textconv cache data here, which
1489 * is not thread-safe.
1492 textconv = userdiff_get_textconv(gs->driver);
1497 * We know the result of a textconv is text, so we only have to care
1498 * about binary handling if we are not using it.
1501 switch (opt->binary) {
1502 case GREP_BINARY_DEFAULT:
1503 if (grep_source_is_binary(gs))
1504 binary_match_only = 1;
1506 case GREP_BINARY_NOMATCH:
1507 if (grep_source_is_binary(gs))
1508 return 0; /* Assume unmatch */
1510 case GREP_BINARY_TEXT:
1513 die("BUG: unknown binary handling mode");
1517 memset(&xecfg, 0, sizeof(xecfg));
1520 try_lookahead = should_lookahead(opt);
1522 if (fill_textconv_grep(textconv, gs) < 0)
1532 * look_ahead() skips quickly to the line that possibly
1533 * has the next hit; don't call it if we need to do
1534 * something more than just skipping the current line
1535 * in response to an unmatch for the current line. E.g.
1536 * inside a post-context window, we will show the current
1537 * line as a context around the previous hit when it
1542 && (show_function ||
1543 lno <= last_hit + opt->post_context))
1544 && look_ahead(opt, &left, &lno, &bol))
1546 eol = end_of_line(bol, &left);
1550 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1551 ctx = GREP_CONTEXT_BODY;
1553 hit = match_line(opt, bol, eol, ctx, collect_hits);
1559 /* "grep -v -e foo -e bla" should list lines
1560 * that do not have either, so inversion should
1565 if (opt->unmatch_name_only) {
1572 if (opt->status_only)
1574 if (opt->name_only) {
1575 show_name(opt, gs->name);
1580 if (binary_match_only) {
1581 opt->output(opt, "Binary file ", 12);
1582 output_color(opt, gs->name, strlen(gs->name),
1583 opt->color_filename);
1584 opt->output(opt, " matches\n", 9);
1587 /* Hit at this line. If we haven't shown the
1588 * pre-context lines, we would need to show them.
1590 if (opt->pre_context || opt->funcbody)
1591 show_pre_context(opt, gs, bol, eol, lno);
1592 else if (opt->funcname)
1593 show_funcname_line(opt, gs, bol, lno);
1594 show_line(opt, bol, eol, gs->name, lno, ':');
1600 if (show_function && (!peek_bol || peek_bol < bol)) {
1601 unsigned long peek_left = left;
1602 char *peek_eol = eol;
1605 * Trailing empty lines are not interesting.
1606 * Peek past them to see if they belong to the
1607 * body of the current function.
1610 while (is_empty_line(peek_bol, peek_eol)) {
1611 peek_bol = peek_eol + 1;
1612 peek_eol = end_of_line(peek_bol, &peek_left);
1615 if (match_funcname(opt, gs, peek_bol, peek_eol))
1618 if (show_function ||
1619 (last_hit && lno <= last_hit + opt->post_context)) {
1620 /* If the last hit is within the post context,
1621 * we need to show this line.
1623 show_line(opt, bol, eol, gs->name, lno, '-');
1637 if (opt->status_only)
1639 if (opt->unmatch_name_only) {
1640 /* We did not see any hit, so we want to show this */
1641 show_name(opt, gs->name);
1645 xdiff_clear_find_func(&xecfg);
1649 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1650 * which feels mostly useless but sometimes useful. Maybe
1651 * make it another option? For now suppress them.
1653 if (opt->count && count) {
1655 if (opt->pathname) {
1656 output_color(opt, gs->name, strlen(gs->name),
1657 opt->color_filename);
1658 output_sep(opt, ':');
1660 xsnprintf(buf, sizeof(buf), "%u\n", count);
1661 opt->output(opt, buf, strlen(buf));
1667 static void clr_hit_marker(struct grep_expr *x)
1669 /* All-hit markers are meaningful only at the very top level
1674 if (x->node != GREP_NODE_OR)
1676 x->u.binary.left->hit = 0;
1677 x = x->u.binary.right;
1681 static int chk_hit_marker(struct grep_expr *x)
1683 /* Top level nodes have hit markers. See if they all are hits */
1685 if (x->node != GREP_NODE_OR)
1687 if (!x->u.binary.left->hit)
1689 x = x->u.binary.right;
1693 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1696 * we do not have to do the two-pass grep when we do not check
1697 * buffer-wide "all-match".
1699 if (!opt->all_match)
1700 return grep_source_1(opt, gs, 0);
1702 /* Otherwise the toplevel "or" terms hit a bit differently.
1703 * We first clear hit markers from them.
1705 clr_hit_marker(opt->pattern_expression);
1706 grep_source_1(opt, gs, 1);
1708 if (!chk_hit_marker(opt->pattern_expression))
1711 return grep_source_1(opt, gs, 0);
1714 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1716 struct grep_source gs;
1719 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1723 r = grep_source(opt, &gs);
1725 grep_source_clear(&gs);
1729 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1730 const char *name, const char *path,
1731 const void *identifier)
1734 gs->name = xstrdup_or_null(name);
1735 gs->path = xstrdup_or_null(path);
1741 case GREP_SOURCE_FILE:
1742 gs->identifier = xstrdup(identifier);
1744 case GREP_SOURCE_SUBMODULE:
1746 gs->identifier = NULL;
1751 * If the identifier is non-NULL (in the submodule case) it
1752 * will be a SHA1 that needs to be copied.
1754 case GREP_SOURCE_SHA1:
1755 gs->identifier = xmalloc(20);
1756 hashcpy(gs->identifier, identifier);
1758 case GREP_SOURCE_BUF:
1759 gs->identifier = NULL;
1764 void grep_source_clear(struct grep_source *gs)
1770 free(gs->identifier);
1771 gs->identifier = NULL;
1772 grep_source_clear_data(gs);
1775 void grep_source_clear_data(struct grep_source *gs)
1778 case GREP_SOURCE_FILE:
1779 case GREP_SOURCE_SHA1:
1780 case GREP_SOURCE_SUBMODULE:
1785 case GREP_SOURCE_BUF:
1786 /* leave user-provided buf intact */
1791 static int grep_source_load_sha1(struct grep_source *gs)
1793 enum object_type type;
1796 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1800 return error(_("'%s': unable to read %s"),
1802 sha1_to_hex(gs->identifier));
1806 static int grep_source_load_file(struct grep_source *gs)
1808 const char *filename = gs->identifier;
1814 if (lstat(filename, &st) < 0) {
1816 if (errno != ENOENT)
1817 error_errno(_("failed to stat '%s'"), filename);
1820 if (!S_ISREG(st.st_mode))
1822 size = xsize_t(st.st_size);
1823 i = open(filename, O_RDONLY);
1826 data = xmallocz(size);
1827 if (st.st_size != read_in_full(i, data, size)) {
1828 error_errno(_("'%s': short read"), filename);
1840 static int grep_source_load(struct grep_source *gs)
1846 case GREP_SOURCE_FILE:
1847 return grep_source_load_file(gs);
1848 case GREP_SOURCE_SHA1:
1849 return grep_source_load_sha1(gs);
1850 case GREP_SOURCE_BUF:
1851 return gs->buf ? 0 : -1;
1852 case GREP_SOURCE_SUBMODULE:
1855 die("BUG: invalid grep_source type to load");
1858 void grep_source_load_driver(struct grep_source *gs)
1865 gs->driver = userdiff_find_by_path(gs->path);
1867 gs->driver = userdiff_find_by_name("default");
1871 static int grep_source_is_binary(struct grep_source *gs)
1873 grep_source_load_driver(gs);
1874 if (gs->driver->binary != -1)
1875 return gs->driver->binary;
1877 if (!grep_source_load(gs))
1878 return buffer_is_binary(gs->buf, gs->size);