5 #include "xdiff-interface.h"
11 static int grep_source_load(struct grep_source *gs);
12 static int grep_source_is_binary(struct grep_source *gs);
14 static struct grep_opt grep_defaults;
16 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
18 fwrite(buf, size, 1, stdout);
22 * Initialize the grep_defaults template with hardcoded defaults.
23 * We could let the compiler do this, but without C99 initializers
24 * the code gets unwieldy and unreadable, so...
26 void init_grep_defaults(void)
28 struct grep_opt *opt = &grep_defaults;
35 memset(opt, 0, sizeof(*opt));
38 opt->regflags = REG_NEWLINE;
40 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
41 opt->extended_regexp_option = 0;
42 color_set(opt->color_context, "");
43 color_set(opt->color_filename, "");
44 color_set(opt->color_function, "");
45 color_set(opt->color_lineno, "");
46 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
48 color_set(opt->color_selected, "");
49 color_set(opt->color_sep, GIT_COLOR_CYAN);
51 opt->output = std_output;
54 static int parse_pattern_type_arg(const char *opt, const char *arg)
56 if (!strcmp(arg, "default"))
57 return GREP_PATTERN_TYPE_UNSPECIFIED;
58 else if (!strcmp(arg, "basic"))
59 return GREP_PATTERN_TYPE_BRE;
60 else if (!strcmp(arg, "extended"))
61 return GREP_PATTERN_TYPE_ERE;
62 else if (!strcmp(arg, "fixed"))
63 return GREP_PATTERN_TYPE_FIXED;
64 else if (!strcmp(arg, "perl"))
65 return GREP_PATTERN_TYPE_PCRE;
66 die("bad %s argument: %s", opt, arg);
70 * Read the configuration file once and store it in
71 * the grep_defaults template.
73 int grep_config(const char *var, const char *value, void *cb)
75 struct grep_opt *opt = &grep_defaults;
78 if (userdiff_config(var, value) < 0)
81 if (!strcmp(var, "grep.extendedregexp")) {
82 if (git_config_bool(var, value))
83 opt->extended_regexp_option = 1;
85 opt->extended_regexp_option = 0;
89 if (!strcmp(var, "grep.patterntype")) {
90 opt->pattern_type_option = parse_pattern_type_arg(var, value);
94 if (!strcmp(var, "grep.linenumber")) {
95 opt->linenum = git_config_bool(var, value);
99 if (!strcmp(var, "grep.fullname")) {
100 opt->relative = !git_config_bool(var, value);
104 if (!strcmp(var, "color.grep"))
105 opt->color = git_config_colorbool(var, value);
106 else if (!strcmp(var, "color.grep.context"))
107 color = opt->color_context;
108 else if (!strcmp(var, "color.grep.filename"))
109 color = opt->color_filename;
110 else if (!strcmp(var, "color.grep.function"))
111 color = opt->color_function;
112 else if (!strcmp(var, "color.grep.linenumber"))
113 color = opt->color_lineno;
114 else if (!strcmp(var, "color.grep.matchcontext"))
115 color = opt->color_match_context;
116 else if (!strcmp(var, "color.grep.matchselected"))
117 color = opt->color_match_selected;
118 else if (!strcmp(var, "color.grep.selected"))
119 color = opt->color_selected;
120 else if (!strcmp(var, "color.grep.separator"))
121 color = opt->color_sep;
122 else if (!strcmp(var, "color.grep.match")) {
125 return config_error_nonbool(var);
126 rc |= color_parse(value, opt->color_match_context);
127 rc |= color_parse(value, opt->color_match_selected);
133 return config_error_nonbool(var);
134 return color_parse(value, color);
140 * Initialize one instance of grep_opt and copy the
141 * default values from the template we read the configuration
142 * information in an earlier call to git_config(grep_config).
144 void grep_init(struct grep_opt *opt, const char *prefix)
146 struct grep_opt *def = &grep_defaults;
148 memset(opt, 0, sizeof(*opt));
149 opt->prefix = prefix;
150 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
151 opt->pattern_tail = &opt->pattern_list;
152 opt->header_tail = &opt->header_list;
154 opt->color = def->color;
155 opt->extended_regexp_option = def->extended_regexp_option;
156 opt->pattern_type_option = def->pattern_type_option;
157 opt->linenum = def->linenum;
158 opt->max_depth = def->max_depth;
159 opt->pathname = def->pathname;
160 opt->regflags = def->regflags;
161 opt->relative = def->relative;
162 opt->output = def->output;
164 color_set(opt->color_context, def->color_context);
165 color_set(opt->color_filename, def->color_filename);
166 color_set(opt->color_function, def->color_function);
167 color_set(opt->color_lineno, def->color_lineno);
168 color_set(opt->color_match_context, def->color_match_context);
169 color_set(opt->color_match_selected, def->color_match_selected);
170 color_set(opt->color_selected, def->color_selected);
171 color_set(opt->color_sep, def->color_sep);
174 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
176 switch (pattern_type) {
177 case GREP_PATTERN_TYPE_UNSPECIFIED:
180 case GREP_PATTERN_TYPE_BRE:
183 opt->regflags &= ~REG_EXTENDED;
186 case GREP_PATTERN_TYPE_ERE:
189 opt->regflags |= REG_EXTENDED;
192 case GREP_PATTERN_TYPE_FIXED:
195 opt->regflags &= ~REG_EXTENDED;
198 case GREP_PATTERN_TYPE_PCRE:
201 opt->regflags &= ~REG_EXTENDED;
206 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
208 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
209 grep_set_pattern_type_option(pattern_type, opt);
210 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
211 grep_set_pattern_type_option(opt->pattern_type_option, opt);
212 else if (opt->extended_regexp_option)
213 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
216 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
217 const char *origin, int no,
218 enum grep_pat_token t,
219 enum grep_header_field field)
221 struct grep_pat *p = xcalloc(1, sizeof(*p));
222 p->pattern = xmemdupz(pat, patlen);
223 p->patternlen = patlen;
231 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
238 case GREP_PATTERN: /* atom */
239 case GREP_PATTERN_HEAD:
240 case GREP_PATTERN_BODY:
242 struct grep_pat *new_pat;
244 char *cp = p->pattern + p->patternlen, *nl = NULL;
245 while (++len <= p->patternlen) {
246 if (*(--cp) == '\n') {
253 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
254 p->no, p->token, p->field);
255 new_pat->next = p->next;
257 *tail = &new_pat->next;
260 p->patternlen -= len;
268 void append_header_grep_pattern(struct grep_opt *opt,
269 enum grep_header_field field, const char *pat)
271 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
272 GREP_PATTERN_HEAD, field);
273 if (field == GREP_HEADER_REFLOG)
274 opt->use_reflog_filter = 1;
275 do_append_grep_pat(&opt->header_tail, p);
278 void append_grep_pattern(struct grep_opt *opt, const char *pat,
279 const char *origin, int no, enum grep_pat_token t)
281 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
284 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
285 const char *origin, int no, enum grep_pat_token t)
287 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
288 do_append_grep_pat(&opt->pattern_tail, p);
291 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
293 struct grep_pat *pat;
294 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
297 ret->pattern_list = NULL;
298 ret->pattern_tail = &ret->pattern_list;
300 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
302 if(pat->token == GREP_PATTERN_HEAD)
303 append_header_grep_pattern(ret, pat->field,
306 append_grep_pat(ret, pat->pattern, pat->patternlen,
307 pat->origin, pat->no, pat->token);
313 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
319 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
321 xsnprintf(where, sizeof(where), "%s, ", p->origin);
325 die("%s'%s': %s", where, p->pattern, error);
329 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
333 int options = PCRE_MULTILINE;
335 if (opt->ignore_case) {
336 if (has_non_ascii(p->pattern))
337 p->pcre_tables = pcre_maketables();
338 options |= PCRE_CASELESS;
340 if (is_utf8_locale() && has_non_ascii(p->pattern))
341 options |= PCRE_UTF8;
343 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
346 compile_regexp_failed(p, error);
348 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
349 if (!p->pcre_extra_info && error)
353 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
354 regmatch_t *match, int eflags)
356 int ovector[30], ret, flags = 0;
358 if (eflags & REG_NOTBOL)
359 flags |= PCRE_NOTBOL;
361 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
362 0, flags, ovector, ARRAY_SIZE(ovector));
363 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
364 die("pcre_exec failed with error code %d", ret);
367 match->rm_so = ovector[0];
368 match->rm_eo = ovector[1];
374 static void free_pcre_regexp(struct grep_pat *p)
376 pcre_free(p->pcre_regexp);
377 pcre_free(p->pcre_extra_info);
378 pcre_free((void *)p->pcre_tables);
380 #else /* !USE_LIBPCRE */
381 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
383 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
386 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
387 regmatch_t *match, int eflags)
392 static void free_pcre_regexp(struct grep_pat *p)
395 #endif /* !USE_LIBPCRE */
397 static int is_fixed(const char *s, size_t len)
401 /* regcomp cannot accept patterns with NULs so we
402 * consider any pattern containing a NUL fixed.
404 if (memchr(s, 0, len))
407 for (i = 0; i < len; i++) {
408 if (is_regex_special(s[i]))
415 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
417 struct strbuf sb = STRBUF_INIT;
421 basic_regex_quote_buf(&sb, p->pattern);
422 regflags = opt->regflags & ~REG_EXTENDED;
423 if (opt->ignore_case)
424 regflags |= REG_ICASE;
425 err = regcomp(&p->regexp, sb.buf, regflags);
427 fprintf(stderr, "fixed %s\n", sb.buf);
431 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
433 compile_regexp_failed(p, errbuf);
437 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
439 int icase, ascii_only;
442 p->word_regexp = opt->word_regexp;
443 p->ignore_case = opt->ignore_case;
444 icase = opt->regflags & REG_ICASE || p->ignore_case;
445 ascii_only = !has_non_ascii(p->pattern);
448 * Even when -F (fixed) asks us to do a non-regexp search, we
449 * may not be able to correctly case-fold when -i
450 * (ignore-case) is asked (in which case, we'll synthesize a
451 * regexp to match the pattern that matches regexp special
452 * characters literally, while ignoring case differences). On
453 * the other hand, even without -F, if the pattern does not
454 * have any regexp special characters and there is no need for
455 * case-folding search, we can internally turn it into a
456 * simple string match using kws. p->fixed tells us if we
459 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
460 p->fixed = !icase || ascii_only;
465 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
466 kwsincr(p->kws, p->pattern, p->patternlen);
469 } else if (opt->fixed) {
471 * We come here when the pattern has the non-ascii
472 * characters we cannot case-fold, and asked to
475 compile_fixed_regexp(p, opt);
480 compile_pcre_regexp(p, opt);
484 err = regcomp(&p->regexp, p->pattern, opt->regflags);
487 regerror(err, &p->regexp, errbuf, 1024);
489 compile_regexp_failed(p, errbuf);
493 static struct grep_expr *compile_pattern_or(struct grep_pat **);
494 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
503 case GREP_PATTERN: /* atom */
504 case GREP_PATTERN_HEAD:
505 case GREP_PATTERN_BODY:
506 x = xcalloc(1, sizeof (struct grep_expr));
507 x->node = GREP_NODE_ATOM;
511 case GREP_OPEN_PAREN:
513 x = compile_pattern_or(list);
514 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
515 die("unmatched parenthesis");
516 *list = (*list)->next;
523 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
534 die("--not not followed by pattern expression");
536 x = xcalloc(1, sizeof (struct grep_expr));
537 x->node = GREP_NODE_NOT;
538 x->u.unary = compile_pattern_not(list);
540 die("--not followed by non pattern expression");
543 return compile_pattern_atom(list);
547 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
550 struct grep_expr *x, *y, *z;
552 x = compile_pattern_not(list);
554 if (p && p->token == GREP_AND) {
556 die("--and not followed by pattern expression");
558 y = compile_pattern_and(list);
560 die("--and not followed by pattern expression");
561 z = xcalloc(1, sizeof (struct grep_expr));
562 z->node = GREP_NODE_AND;
563 z->u.binary.left = x;
564 z->u.binary.right = y;
570 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
573 struct grep_expr *x, *y, *z;
575 x = compile_pattern_and(list);
577 if (x && p && p->token != GREP_CLOSE_PAREN) {
578 y = compile_pattern_or(list);
580 die("not a pattern expression %s", p->pattern);
581 z = xcalloc(1, sizeof (struct grep_expr));
582 z->node = GREP_NODE_OR;
583 z->u.binary.left = x;
584 z->u.binary.right = y;
590 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
592 return compile_pattern_or(list);
595 static void indent(int in)
601 static void dump_grep_pat(struct grep_pat *p)
604 case GREP_AND: fprintf(stderr, "*and*"); break;
605 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
606 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
607 case GREP_NOT: fprintf(stderr, "*not*"); break;
608 case GREP_OR: fprintf(stderr, "*or*"); break;
610 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
611 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
612 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
617 case GREP_PATTERN_HEAD:
618 fprintf(stderr, "<head %d>", p->field); break;
619 case GREP_PATTERN_BODY:
620 fprintf(stderr, "<body>"); break;
624 case GREP_PATTERN_HEAD:
625 case GREP_PATTERN_BODY:
627 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
633 static void dump_grep_expression_1(struct grep_expr *x, int in)
638 fprintf(stderr, "true\n");
641 dump_grep_pat(x->u.atom);
644 fprintf(stderr, "(not\n");
645 dump_grep_expression_1(x->u.unary, in+1);
647 fprintf(stderr, ")\n");
650 fprintf(stderr, "(and\n");
651 dump_grep_expression_1(x->u.binary.left, in+1);
652 dump_grep_expression_1(x->u.binary.right, in+1);
654 fprintf(stderr, ")\n");
657 fprintf(stderr, "(or\n");
658 dump_grep_expression_1(x->u.binary.left, in+1);
659 dump_grep_expression_1(x->u.binary.right, in+1);
661 fprintf(stderr, ")\n");
666 static void dump_grep_expression(struct grep_opt *opt)
668 struct grep_expr *x = opt->pattern_expression;
671 fprintf(stderr, "[all-match]\n");
672 dump_grep_expression_1(x, 0);
676 static struct grep_expr *grep_true_expr(void)
678 struct grep_expr *z = xcalloc(1, sizeof(*z));
679 z->node = GREP_NODE_TRUE;
683 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
685 struct grep_expr *z = xcalloc(1, sizeof(*z));
686 z->node = GREP_NODE_OR;
687 z->u.binary.left = left;
688 z->u.binary.right = right;
692 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
695 struct grep_expr *header_expr;
696 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
697 enum grep_header_field fld;
699 if (!opt->header_list)
702 for (p = opt->header_list; p; p = p->next) {
703 if (p->token != GREP_PATTERN_HEAD)
704 die("BUG: a non-header pattern in grep header list.");
705 if (p->field < GREP_HEADER_FIELD_MIN ||
706 GREP_HEADER_FIELD_MAX <= p->field)
707 die("BUG: unknown header field %d", p->field);
708 compile_regexp(p, opt);
711 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
712 header_group[fld] = NULL;
714 for (p = opt->header_list; p; p = p->next) {
716 struct grep_pat *pp = p;
718 h = compile_pattern_atom(&pp);
719 if (!h || pp != p->next)
720 die("BUG: malformed header expr");
721 if (!header_group[p->field]) {
722 header_group[p->field] = h;
725 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
730 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
731 if (!header_group[fld])
734 header_expr = grep_true_expr();
735 header_expr = grep_or_expr(header_group[fld], header_expr);
740 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
742 struct grep_expr *z = x;
745 assert(x->node == GREP_NODE_OR);
746 if (x->u.binary.right &&
747 x->u.binary.right->node == GREP_NODE_TRUE) {
748 x->u.binary.right = y;
751 x = x->u.binary.right;
756 static void compile_grep_patterns_real(struct grep_opt *opt)
759 struct grep_expr *header_expr = prep_header_patterns(opt);
761 for (p = opt->pattern_list; p; p = p->next) {
763 case GREP_PATTERN: /* atom */
764 case GREP_PATTERN_HEAD:
765 case GREP_PATTERN_BODY:
766 compile_regexp(p, opt);
774 if (opt->all_match || header_expr)
776 else if (!opt->extended && !opt->debug)
779 p = opt->pattern_list;
781 opt->pattern_expression = compile_pattern_expr(&p);
783 die("incomplete pattern expression: %s", p->pattern);
788 if (!opt->pattern_expression)
789 opt->pattern_expression = header_expr;
790 else if (opt->all_match)
791 opt->pattern_expression = grep_splice_or(header_expr,
792 opt->pattern_expression);
794 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
799 void compile_grep_patterns(struct grep_opt *opt)
801 compile_grep_patterns_real(opt);
803 dump_grep_expression(opt);
806 static void free_pattern_expr(struct grep_expr *x)
813 free_pattern_expr(x->u.unary);
817 free_pattern_expr(x->u.binary.left);
818 free_pattern_expr(x->u.binary.right);
824 void free_grep_patterns(struct grep_opt *opt)
826 struct grep_pat *p, *n;
828 for (p = opt->pattern_list; p; p = n) {
831 case GREP_PATTERN: /* atom */
832 case GREP_PATTERN_HEAD:
833 case GREP_PATTERN_BODY:
836 else if (p->pcre_regexp)
850 free_pattern_expr(opt->pattern_expression);
853 static char *end_of_line(char *cp, unsigned long *left)
855 unsigned long l = *left;
856 while (l && *cp != '\n') {
864 static int word_char(char ch)
866 return isalnum(ch) || ch == '_';
869 static void output_color(struct grep_opt *opt, const void *data, size_t size,
872 if (want_color(opt->color) && color && color[0]) {
873 opt->output(opt, color, strlen(color));
874 opt->output(opt, data, size);
875 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
877 opt->output(opt, data, size);
880 static void output_sep(struct grep_opt *opt, char sign)
882 if (opt->null_following_name)
883 opt->output(opt, "\0", 1);
885 output_color(opt, &sign, 1, opt->color_sep);
888 static void show_name(struct grep_opt *opt, const char *name)
890 output_color(opt, name, strlen(name), opt->color_filename);
891 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
894 static int fixmatch(struct grep_pat *p, char *line, char *eol,
897 struct kwsmatch kwsm;
898 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
900 match->rm_so = match->rm_eo = -1;
903 match->rm_so = offset;
904 match->rm_eo = match->rm_so + kwsm.size[0];
909 static int patmatch(struct grep_pat *p, char *line, char *eol,
910 regmatch_t *match, int eflags)
915 hit = !fixmatch(p, line, eol, match);
916 else if (p->pcre_regexp)
917 hit = !pcrematch(p, line, eol, match, eflags);
919 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
925 static int strip_timestamp(char *bol, char **eol_p)
930 while (bol < --eol) {
946 { "committer ", 10 },
950 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
951 enum grep_context ctx,
952 regmatch_t *pmatch, int eflags)
956 const char *start = bol;
958 if ((p->token != GREP_PATTERN) &&
959 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
962 if (p->token == GREP_PATTERN_HEAD) {
965 assert(p->field < ARRAY_SIZE(header_field));
966 field = header_field[p->field].field;
967 len = header_field[p->field].len;
968 if (strncmp(bol, field, len))
972 case GREP_HEADER_AUTHOR:
973 case GREP_HEADER_COMMITTER:
974 saved_ch = strip_timestamp(bol, &eol);
982 hit = patmatch(p, bol, eol, pmatch, eflags);
984 if (hit && p->word_regexp) {
985 if ((pmatch[0].rm_so < 0) ||
986 (eol - bol) < pmatch[0].rm_so ||
987 (pmatch[0].rm_eo < 0) ||
988 (eol - bol) < pmatch[0].rm_eo)
989 die("regexp returned nonsense");
991 /* Match beginning must be either beginning of the
992 * line, or at word boundary (i.e. the last char must
993 * not be a word char). Similarly, match end must be
994 * either end of the line, or at word boundary
995 * (i.e. the next char must not be a word char).
997 if ( ((pmatch[0].rm_so == 0) ||
998 !word_char(bol[pmatch[0].rm_so-1])) &&
999 ((pmatch[0].rm_eo == (eol-bol)) ||
1000 !word_char(bol[pmatch[0].rm_eo])) )
1005 /* Words consist of at least one character. */
1006 if (pmatch->rm_so == pmatch->rm_eo)
1009 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1010 /* There could be more than one match on the
1011 * line, and the first match might not be
1012 * strict word match. But later ones could be!
1013 * Forward to the next possible start, i.e. the
1014 * next position following a non-word char.
1016 bol = pmatch[0].rm_so + bol + 1;
1017 while (word_char(bol[-1]) && bol < eol)
1019 eflags |= REG_NOTBOL;
1024 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1027 pmatch[0].rm_so += bol - start;
1028 pmatch[0].rm_eo += bol - start;
1033 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1034 enum grep_context ctx, int collect_hits)
1040 die("Not a valid grep expression");
1042 case GREP_NODE_TRUE:
1045 case GREP_NODE_ATOM:
1046 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1049 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1052 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1054 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1058 return (match_expr_eval(x->u.binary.left,
1059 bol, eol, ctx, 0) ||
1060 match_expr_eval(x->u.binary.right,
1062 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1063 x->u.binary.left->hit |= h;
1064 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1067 die("Unexpected node type (internal error) %d", x->node);
1074 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1075 enum grep_context ctx, int collect_hits)
1077 struct grep_expr *x = opt->pattern_expression;
1078 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1081 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1082 enum grep_context ctx, int collect_hits)
1088 return match_expr(opt, bol, eol, ctx, collect_hits);
1090 /* we do not call with collect_hits without being extended */
1091 for (p = opt->pattern_list; p; p = p->next) {
1092 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1098 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1099 enum grep_context ctx,
1100 regmatch_t *pmatch, int eflags)
1104 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1106 if (match.rm_so < 0 || match.rm_eo < 0)
1108 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1109 if (match.rm_so > pmatch->rm_so)
1111 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1114 pmatch->rm_so = match.rm_so;
1115 pmatch->rm_eo = match.rm_eo;
1119 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1120 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1125 pmatch->rm_so = pmatch->rm_eo = -1;
1127 for (p = opt->pattern_list; p; p = p->next) {
1129 case GREP_PATTERN: /* atom */
1130 case GREP_PATTERN_HEAD:
1131 case GREP_PATTERN_BODY:
1132 hit |= match_next_pattern(p, bol, eol, ctx,
1143 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1144 const char *name, unsigned lno, char sign)
1146 int rest = eol - bol;
1147 const char *match_color, *line_color = NULL;
1149 if (opt->file_break && opt->last_shown == 0) {
1150 if (opt->show_hunk_mark)
1151 opt->output(opt, "\n", 1);
1152 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1153 if (opt->last_shown == 0) {
1154 if (opt->show_hunk_mark) {
1155 output_color(opt, "--", 2, opt->color_sep);
1156 opt->output(opt, "\n", 1);
1158 } else if (lno > opt->last_shown + 1) {
1159 output_color(opt, "--", 2, opt->color_sep);
1160 opt->output(opt, "\n", 1);
1163 if (opt->heading && opt->last_shown == 0) {
1164 output_color(opt, name, strlen(name), opt->color_filename);
1165 opt->output(opt, "\n", 1);
1167 opt->last_shown = lno;
1169 if (!opt->heading && opt->pathname) {
1170 output_color(opt, name, strlen(name), opt->color_filename);
1171 output_sep(opt, sign);
1175 xsnprintf(buf, sizeof(buf), "%d", lno);
1176 output_color(opt, buf, strlen(buf), opt->color_lineno);
1177 output_sep(opt, sign);
1181 enum grep_context ctx = GREP_CONTEXT_BODY;
1186 match_color = opt->color_match_selected;
1188 match_color = opt->color_match_context;
1190 line_color = opt->color_selected;
1191 else if (sign == '-')
1192 line_color = opt->color_context;
1193 else if (sign == '=')
1194 line_color = opt->color_function;
1196 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1197 if (match.rm_so == match.rm_eo)
1200 output_color(opt, bol, match.rm_so, line_color);
1201 output_color(opt, bol + match.rm_so,
1202 match.rm_eo - match.rm_so, match_color);
1204 rest -= match.rm_eo;
1205 eflags = REG_NOTBOL;
1209 output_color(opt, bol, rest, line_color);
1210 opt->output(opt, "\n", 1);
1217 * This lock protects access to the gitattributes machinery, which is
1220 pthread_mutex_t grep_attr_mutex;
1222 static inline void grep_attr_lock(void)
1225 pthread_mutex_lock(&grep_attr_mutex);
1228 static inline void grep_attr_unlock(void)
1231 pthread_mutex_unlock(&grep_attr_mutex);
1235 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1237 pthread_mutex_t grep_read_mutex;
1240 #define grep_attr_lock()
1241 #define grep_attr_unlock()
1244 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1246 xdemitconf_t *xecfg = opt->priv;
1247 if (xecfg && !xecfg->find_func) {
1248 grep_source_load_driver(gs);
1249 if (gs->driver->funcname.pattern) {
1250 const struct userdiff_funcname *pe = &gs->driver->funcname;
1251 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1253 xecfg = opt->priv = NULL;
1259 return xecfg->find_func(bol, eol - bol, buf, 1,
1260 xecfg->find_func_priv) >= 0;
1265 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1270 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1271 char *bol, unsigned lno)
1273 while (bol > gs->buf) {
1276 while (bol > gs->buf && bol[-1] != '\n')
1280 if (lno <= opt->last_shown)
1283 if (match_funcname(opt, gs, bol, eol)) {
1284 show_line(opt, bol, eol, gs->name, lno, '=');
1290 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1291 char *bol, char *end, unsigned lno)
1293 unsigned cur = lno, from = 1, funcname_lno = 0;
1294 int funcname_needed = !!opt->funcname;
1296 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1297 funcname_needed = 2;
1299 if (opt->pre_context < lno)
1300 from = lno - opt->pre_context;
1301 if (from <= opt->last_shown)
1302 from = opt->last_shown + 1;
1305 while (bol > gs->buf &&
1306 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1309 while (bol > gs->buf && bol[-1] != '\n')
1312 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1314 funcname_needed = 0;
1318 /* We need to look even further back to find a function signature. */
1319 if (opt->funcname && funcname_needed)
1320 show_funcname_line(opt, gs, bol, cur);
1324 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1326 while (*eol != '\n')
1328 show_line(opt, bol, eol, gs->name, cur, sign);
1334 static int should_lookahead(struct grep_opt *opt)
1339 return 0; /* punt for too complex stuff */
1342 for (p = opt->pattern_list; p; p = p->next) {
1343 if (p->token != GREP_PATTERN)
1344 return 0; /* punt for "header only" and stuff */
1349 static int look_ahead(struct grep_opt *opt,
1350 unsigned long *left_p,
1354 unsigned lno = *lno_p;
1357 char *sp, *last_bol;
1358 regoff_t earliest = -1;
1360 for (p = opt->pattern_list; p; p = p->next) {
1364 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1365 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1367 if (earliest < 0 || m.rm_so < earliest)
1372 *bol_p = bol + *left_p;
1376 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1377 ; /* find the beginning of the line */
1380 for (sp = bol; sp < last_bol; sp++) {
1384 *left_p -= last_bol - bol;
1390 static int fill_textconv_grep(struct userdiff_driver *driver,
1391 struct grep_source *gs)
1393 struct diff_filespec *df;
1397 if (!driver || !driver->textconv)
1398 return grep_source_load(gs);
1401 * The textconv interface is intimately tied to diff_filespecs, so we
1402 * have to pretend to be one. If we could unify the grep_source
1403 * and diff_filespec structs, this mess could just go away.
1405 df = alloc_filespec(gs->path);
1407 case GREP_SOURCE_SHA1:
1408 fill_filespec(df, gs->identifier, 1, 0100644);
1410 case GREP_SOURCE_FILE:
1411 fill_filespec(df, null_sha1, 0, 0100644);
1414 die("BUG: attempt to textconv something without a path?");
1418 * fill_textconv is not remotely thread-safe; it may load objects
1419 * behind the scenes, and it modifies the global diff tempfile
1423 size = fill_textconv(driver, df, &buf);
1428 * The normal fill_textconv usage by the diff machinery would just keep
1429 * the textconv'd buf separate from the diff_filespec. But much of the
1430 * grep code passes around a grep_source and assumes that its "buf"
1431 * pointer is the beginning of the thing we are searching. So let's
1432 * install our textconv'd version into the grep_source, taking care not
1433 * to leak any existing buffer.
1435 grep_source_clear_data(gs);
1442 static int is_empty_line(const char *bol, const char *eol)
1444 while (bol < eol && isspace(*bol))
1449 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1452 char *peek_bol = NULL;
1455 unsigned last_hit = 0;
1456 int binary_match_only = 0;
1458 int try_lookahead = 0;
1459 int show_function = 0;
1460 struct userdiff_driver *textconv = NULL;
1461 enum grep_context ctx = GREP_CONTEXT_HEAD;
1465 opt->output = std_output;
1467 if (opt->pre_context || opt->post_context || opt->file_break ||
1469 /* Show hunk marks, except for the first file. */
1470 if (opt->last_shown)
1471 opt->show_hunk_mark = 1;
1473 * If we're using threads then we can't easily identify
1474 * the first file. Always put hunk marks in that case
1475 * and skip the very first one later in work_done().
1477 if (opt->output != std_output)
1478 opt->show_hunk_mark = 1;
1480 opt->last_shown = 0;
1482 if (opt->allow_textconv) {
1483 grep_source_load_driver(gs);
1485 * We might set up the shared textconv cache data here, which
1486 * is not thread-safe.
1489 textconv = userdiff_get_textconv(gs->driver);
1494 * We know the result of a textconv is text, so we only have to care
1495 * about binary handling if we are not using it.
1498 switch (opt->binary) {
1499 case GREP_BINARY_DEFAULT:
1500 if (grep_source_is_binary(gs))
1501 binary_match_only = 1;
1503 case GREP_BINARY_NOMATCH:
1504 if (grep_source_is_binary(gs))
1505 return 0; /* Assume unmatch */
1507 case GREP_BINARY_TEXT:
1510 die("BUG: unknown binary handling mode");
1514 memset(&xecfg, 0, sizeof(xecfg));
1517 try_lookahead = should_lookahead(opt);
1519 if (fill_textconv_grep(textconv, gs) < 0)
1529 * look_ahead() skips quickly to the line that possibly
1530 * has the next hit; don't call it if we need to do
1531 * something more than just skipping the current line
1532 * in response to an unmatch for the current line. E.g.
1533 * inside a post-context window, we will show the current
1534 * line as a context around the previous hit when it
1539 && (show_function ||
1540 lno <= last_hit + opt->post_context))
1541 && look_ahead(opt, &left, &lno, &bol))
1543 eol = end_of_line(bol, &left);
1547 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1548 ctx = GREP_CONTEXT_BODY;
1550 hit = match_line(opt, bol, eol, ctx, collect_hits);
1556 /* "grep -v -e foo -e bla" should list lines
1557 * that do not have either, so inversion should
1562 if (opt->unmatch_name_only) {
1569 if (opt->status_only)
1571 if (opt->name_only) {
1572 show_name(opt, gs->name);
1577 if (binary_match_only) {
1578 opt->output(opt, "Binary file ", 12);
1579 output_color(opt, gs->name, strlen(gs->name),
1580 opt->color_filename);
1581 opt->output(opt, " matches\n", 9);
1584 /* Hit at this line. If we haven't shown the
1585 * pre-context lines, we would need to show them.
1587 if (opt->pre_context || opt->funcbody)
1588 show_pre_context(opt, gs, bol, eol, lno);
1589 else if (opt->funcname)
1590 show_funcname_line(opt, gs, bol, lno);
1591 show_line(opt, bol, eol, gs->name, lno, ':');
1597 if (show_function && (!peek_bol || peek_bol < bol)) {
1598 unsigned long peek_left = left;
1599 char *peek_eol = eol;
1602 * Trailing empty lines are not interesting.
1603 * Peek past them to see if they belong to the
1604 * body of the current function.
1607 while (is_empty_line(peek_bol, peek_eol)) {
1608 peek_bol = peek_eol + 1;
1609 peek_eol = end_of_line(peek_bol, &peek_left);
1612 if (match_funcname(opt, gs, peek_bol, peek_eol))
1615 if (show_function ||
1616 (last_hit && lno <= last_hit + opt->post_context)) {
1617 /* If the last hit is within the post context,
1618 * we need to show this line.
1620 show_line(opt, bol, eol, gs->name, lno, '-');
1634 if (opt->status_only)
1636 if (opt->unmatch_name_only) {
1637 /* We did not see any hit, so we want to show this */
1638 show_name(opt, gs->name);
1642 xdiff_clear_find_func(&xecfg);
1646 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1647 * which feels mostly useless but sometimes useful. Maybe
1648 * make it another option? For now suppress them.
1650 if (opt->count && count) {
1652 if (opt->pathname) {
1653 output_color(opt, gs->name, strlen(gs->name),
1654 opt->color_filename);
1655 output_sep(opt, ':');
1657 xsnprintf(buf, sizeof(buf), "%u\n", count);
1658 opt->output(opt, buf, strlen(buf));
1664 static void clr_hit_marker(struct grep_expr *x)
1666 /* All-hit markers are meaningful only at the very top level
1671 if (x->node != GREP_NODE_OR)
1673 x->u.binary.left->hit = 0;
1674 x = x->u.binary.right;
1678 static int chk_hit_marker(struct grep_expr *x)
1680 /* Top level nodes have hit markers. See if they all are hits */
1682 if (x->node != GREP_NODE_OR)
1684 if (!x->u.binary.left->hit)
1686 x = x->u.binary.right;
1690 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1693 * we do not have to do the two-pass grep when we do not check
1694 * buffer-wide "all-match".
1696 if (!opt->all_match)
1697 return grep_source_1(opt, gs, 0);
1699 /* Otherwise the toplevel "or" terms hit a bit differently.
1700 * We first clear hit markers from them.
1702 clr_hit_marker(opt->pattern_expression);
1703 grep_source_1(opt, gs, 1);
1705 if (!chk_hit_marker(opt->pattern_expression))
1708 return grep_source_1(opt, gs, 0);
1711 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1713 struct grep_source gs;
1716 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1720 r = grep_source(opt, &gs);
1722 grep_source_clear(&gs);
1726 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1727 const char *name, const char *path,
1728 const void *identifier)
1731 gs->name = xstrdup_or_null(name);
1732 gs->path = xstrdup_or_null(path);
1738 case GREP_SOURCE_FILE:
1739 gs->identifier = xstrdup(identifier);
1741 case GREP_SOURCE_SUBMODULE:
1743 gs->identifier = NULL;
1748 * If the identifier is non-NULL (in the submodule case) it
1749 * will be a SHA1 that needs to be copied.
1751 case GREP_SOURCE_SHA1:
1752 gs->identifier = xmalloc(20);
1753 hashcpy(gs->identifier, identifier);
1755 case GREP_SOURCE_BUF:
1756 gs->identifier = NULL;
1761 void grep_source_clear(struct grep_source *gs)
1767 free(gs->identifier);
1768 gs->identifier = NULL;
1769 grep_source_clear_data(gs);
1772 void grep_source_clear_data(struct grep_source *gs)
1775 case GREP_SOURCE_FILE:
1776 case GREP_SOURCE_SHA1:
1777 case GREP_SOURCE_SUBMODULE:
1782 case GREP_SOURCE_BUF:
1783 /* leave user-provided buf intact */
1788 static int grep_source_load_sha1(struct grep_source *gs)
1790 enum object_type type;
1793 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1797 return error(_("'%s': unable to read %s"),
1799 sha1_to_hex(gs->identifier));
1803 static int grep_source_load_file(struct grep_source *gs)
1805 const char *filename = gs->identifier;
1811 if (lstat(filename, &st) < 0) {
1813 if (errno != ENOENT)
1814 error_errno(_("failed to stat '%s'"), filename);
1817 if (!S_ISREG(st.st_mode))
1819 size = xsize_t(st.st_size);
1820 i = open(filename, O_RDONLY);
1823 data = xmallocz(size);
1824 if (st.st_size != read_in_full(i, data, size)) {
1825 error_errno(_("'%s': short read"), filename);
1837 static int grep_source_load(struct grep_source *gs)
1843 case GREP_SOURCE_FILE:
1844 return grep_source_load_file(gs);
1845 case GREP_SOURCE_SHA1:
1846 return grep_source_load_sha1(gs);
1847 case GREP_SOURCE_BUF:
1848 return gs->buf ? 0 : -1;
1849 case GREP_SOURCE_SUBMODULE:
1852 die("BUG: invalid grep_source type to load");
1855 void grep_source_load_driver(struct grep_source *gs)
1862 gs->driver = userdiff_find_by_path(gs->path);
1864 gs->driver = userdiff_find_by_name("default");
1868 static int grep_source_is_binary(struct grep_source *gs)
1870 grep_source_load_driver(gs);
1871 if (gs->driver->binary != -1)
1872 return gs->driver->binary;
1874 if (!grep_source_load(gs))
1875 return buffer_is_binary(gs->buf, gs->size);