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;
16 * Initialize the grep_defaults template with hardcoded defaults.
17 * We could let the compiler do this, but without C99 initializers
18 * the code gets unwieldy and unreadable, so...
20 void init_grep_defaults(void)
22 struct grep_opt *opt = &grep_defaults;
29 memset(opt, 0, sizeof(*opt));
32 opt->regflags = REG_NEWLINE;
34 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
35 opt->extended_regexp_option = 0;
36 color_set(opt->color_context, "");
37 color_set(opt->color_filename, "");
38 color_set(opt->color_function, "");
39 color_set(opt->color_lineno, "");
40 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
41 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
42 color_set(opt->color_selected, "");
43 color_set(opt->color_sep, GIT_COLOR_CYAN);
47 static int parse_pattern_type_arg(const char *opt, const char *arg)
49 if (!strcmp(arg, "default"))
50 return GREP_PATTERN_TYPE_UNSPECIFIED;
51 else if (!strcmp(arg, "basic"))
52 return GREP_PATTERN_TYPE_BRE;
53 else if (!strcmp(arg, "extended"))
54 return GREP_PATTERN_TYPE_ERE;
55 else if (!strcmp(arg, "fixed"))
56 return GREP_PATTERN_TYPE_FIXED;
57 else if (!strcmp(arg, "perl"))
58 return GREP_PATTERN_TYPE_PCRE;
59 die("bad %s argument: %s", opt, arg);
63 * Read the configuration file once and store it in
64 * the grep_defaults template.
66 int grep_config(const char *var, const char *value, void *cb)
68 struct grep_opt *opt = &grep_defaults;
71 if (userdiff_config(var, value) < 0)
74 if (!strcmp(var, "grep.extendedregexp")) {
75 if (git_config_bool(var, value))
76 opt->extended_regexp_option = 1;
78 opt->extended_regexp_option = 0;
82 if (!strcmp(var, "grep.patterntype")) {
83 opt->pattern_type_option = parse_pattern_type_arg(var, value);
87 if (!strcmp(var, "grep.linenumber")) {
88 opt->linenum = git_config_bool(var, value);
92 if (!strcmp(var, "grep.fullname")) {
93 opt->relative = !git_config_bool(var, value);
97 if (!strcmp(var, "color.grep"))
98 opt->color = git_config_colorbool(var, value);
99 else if (!strcmp(var, "color.grep.context"))
100 color = opt->color_context;
101 else if (!strcmp(var, "color.grep.filename"))
102 color = opt->color_filename;
103 else if (!strcmp(var, "color.grep.function"))
104 color = opt->color_function;
105 else if (!strcmp(var, "color.grep.linenumber"))
106 color = opt->color_lineno;
107 else if (!strcmp(var, "color.grep.matchcontext"))
108 color = opt->color_match_context;
109 else if (!strcmp(var, "color.grep.matchselected"))
110 color = opt->color_match_selected;
111 else if (!strcmp(var, "color.grep.selected"))
112 color = opt->color_selected;
113 else if (!strcmp(var, "color.grep.separator"))
114 color = opt->color_sep;
115 else if (!strcmp(var, "color.grep.match")) {
118 return config_error_nonbool(var);
119 rc |= color_parse(value, opt->color_match_context);
120 rc |= color_parse(value, opt->color_match_selected);
126 return config_error_nonbool(var);
127 return color_parse(value, color);
133 * Initialize one instance of grep_opt and copy the
134 * default values from the template we read the configuration
135 * information in an earlier call to git_config(grep_config).
137 void grep_init(struct grep_opt *opt, const char *prefix)
139 struct grep_opt *def = &grep_defaults;
141 memset(opt, 0, sizeof(*opt));
142 opt->prefix = prefix;
143 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
144 opt->pattern_tail = &opt->pattern_list;
145 opt->header_tail = &opt->header_list;
147 opt->color = def->color;
148 opt->extended_regexp_option = def->extended_regexp_option;
149 opt->pattern_type_option = def->pattern_type_option;
150 opt->linenum = def->linenum;
151 opt->max_depth = def->max_depth;
152 opt->pathname = def->pathname;
153 opt->regflags = def->regflags;
154 opt->relative = def->relative;
156 color_set(opt->color_context, def->color_context);
157 color_set(opt->color_filename, def->color_filename);
158 color_set(opt->color_function, def->color_function);
159 color_set(opt->color_lineno, def->color_lineno);
160 color_set(opt->color_match_context, def->color_match_context);
161 color_set(opt->color_match_selected, def->color_match_selected);
162 color_set(opt->color_selected, def->color_selected);
163 color_set(opt->color_sep, def->color_sep);
166 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
168 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
169 grep_set_pattern_type_option(pattern_type, opt);
170 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
171 grep_set_pattern_type_option(opt->pattern_type_option, opt);
172 else if (opt->extended_regexp_option)
173 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
176 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
178 switch (pattern_type) {
179 case GREP_PATTERN_TYPE_UNSPECIFIED:
182 case GREP_PATTERN_TYPE_BRE:
185 opt->regflags &= ~REG_EXTENDED;
188 case GREP_PATTERN_TYPE_ERE:
191 opt->regflags |= REG_EXTENDED;
194 case GREP_PATTERN_TYPE_FIXED:
197 opt->regflags &= ~REG_EXTENDED;
200 case GREP_PATTERN_TYPE_PCRE:
203 opt->regflags &= ~REG_EXTENDED;
208 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
209 const char *origin, int no,
210 enum grep_pat_token t,
211 enum grep_header_field field)
213 struct grep_pat *p = xcalloc(1, sizeof(*p));
214 p->pattern = xmemdupz(pat, patlen);
215 p->patternlen = patlen;
223 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
230 case GREP_PATTERN: /* atom */
231 case GREP_PATTERN_HEAD:
232 case GREP_PATTERN_BODY:
234 struct grep_pat *new_pat;
236 char *cp = p->pattern + p->patternlen, *nl = NULL;
237 while (++len <= p->patternlen) {
238 if (*(--cp) == '\n') {
245 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
246 p->no, p->token, p->field);
247 new_pat->next = p->next;
249 *tail = &new_pat->next;
252 p->patternlen -= len;
260 void append_header_grep_pattern(struct grep_opt *opt,
261 enum grep_header_field field, const char *pat)
263 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
264 GREP_PATTERN_HEAD, field);
265 if (field == GREP_HEADER_REFLOG)
266 opt->use_reflog_filter = 1;
267 do_append_grep_pat(&opt->header_tail, p);
270 void append_grep_pattern(struct grep_opt *opt, const char *pat,
271 const char *origin, int no, enum grep_pat_token t)
273 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
276 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
277 const char *origin, int no, enum grep_pat_token t)
279 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
280 do_append_grep_pat(&opt->pattern_tail, p);
283 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
285 struct grep_pat *pat;
286 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
289 ret->pattern_list = NULL;
290 ret->pattern_tail = &ret->pattern_list;
292 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
294 if(pat->token == GREP_PATTERN_HEAD)
295 append_header_grep_pattern(ret, pat->field,
298 append_grep_pat(ret, pat->pattern, pat->patternlen,
299 pat->origin, pat->no, pat->token);
305 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
311 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
313 xsnprintf(where, sizeof(where), "%s, ", p->origin);
317 die("%s'%s': %s", where, p->pattern, error);
321 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
325 int options = PCRE_MULTILINE;
327 if (opt->ignore_case) {
328 if (has_non_ascii(p->pattern))
329 p->pcre_tables = pcre_maketables();
330 options |= PCRE_CASELESS;
333 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
336 compile_regexp_failed(p, error);
338 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
339 if (!p->pcre_extra_info && error)
343 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
344 regmatch_t *match, int eflags)
346 int ovector[30], ret, flags = 0;
348 if (eflags & REG_NOTBOL)
349 flags |= PCRE_NOTBOL;
351 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
352 0, flags, ovector, ARRAY_SIZE(ovector));
353 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
354 die("pcre_exec failed with error code %d", ret);
357 match->rm_so = ovector[0];
358 match->rm_eo = ovector[1];
364 static void free_pcre_regexp(struct grep_pat *p)
366 pcre_free(p->pcre_regexp);
367 pcre_free(p->pcre_extra_info);
368 pcre_free((void *)p->pcre_tables);
370 #else /* !USE_LIBPCRE */
371 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
373 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
376 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
377 regmatch_t *match, int eflags)
382 static void free_pcre_regexp(struct grep_pat *p)
385 #endif /* !USE_LIBPCRE */
387 static int is_fixed(const char *s, size_t len)
391 /* regcomp cannot accept patterns with NULs so we
392 * consider any pattern containing a NUL fixed.
394 if (memchr(s, 0, len))
397 for (i = 0; i < len; i++) {
398 if (is_regex_special(s[i]))
405 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
407 struct strbuf sb = STRBUF_INIT;
411 basic_regex_quote_buf(&sb, p->pattern);
412 regflags = opt->regflags & ~REG_EXTENDED;
413 if (opt->ignore_case)
414 regflags |= REG_ICASE;
415 err = regcomp(&p->regexp, sb.buf, regflags);
417 fprintf(stderr, "fixed %s\n", sb.buf);
421 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
423 compile_regexp_failed(p, errbuf);
427 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
429 int icase, ascii_only;
432 p->word_regexp = opt->word_regexp;
433 p->ignore_case = opt->ignore_case;
434 icase = opt->regflags & REG_ICASE || p->ignore_case;
435 ascii_only = !has_non_ascii(p->pattern);
438 * Even when -F (fixed) asks us to do a non-regexp search, we
439 * may not be able to correctly case-fold when -i
440 * (ignore-case) is asked (in which case, we'll synthesize a
441 * regexp to match the pattern that matches regexp special
442 * characters literally, while ignoring case differences). On
443 * the other hand, even without -F, if the pattern does not
444 * have any regexp special characters and there is no need for
445 * case-folding search, we can internally turn it into a
446 * simple string match using kws. p->fixed tells us if we
449 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
450 p->fixed = !icase || ascii_only;
455 if (opt->regflags & REG_ICASE || p->ignore_case)
456 p->kws = kwsalloc(tolower_trans_tbl);
458 p->kws = kwsalloc(NULL);
459 kwsincr(p->kws, p->pattern, p->patternlen);
462 } else if (opt->fixed) {
464 * We come here when the pattern has the non-ascii
465 * characters we cannot case-fold, and asked to
468 compile_fixed_regexp(p, opt);
473 compile_pcre_regexp(p, opt);
477 err = regcomp(&p->regexp, p->pattern, opt->regflags);
480 regerror(err, &p->regexp, errbuf, 1024);
482 compile_regexp_failed(p, errbuf);
486 static struct grep_expr *compile_pattern_or(struct grep_pat **);
487 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
496 case GREP_PATTERN: /* atom */
497 case GREP_PATTERN_HEAD:
498 case GREP_PATTERN_BODY:
499 x = xcalloc(1, sizeof (struct grep_expr));
500 x->node = GREP_NODE_ATOM;
504 case GREP_OPEN_PAREN:
506 x = compile_pattern_or(list);
507 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
508 die("unmatched parenthesis");
509 *list = (*list)->next;
516 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
527 die("--not not followed by pattern expression");
529 x = xcalloc(1, sizeof (struct grep_expr));
530 x->node = GREP_NODE_NOT;
531 x->u.unary = compile_pattern_not(list);
533 die("--not followed by non pattern expression");
536 return compile_pattern_atom(list);
540 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
543 struct grep_expr *x, *y, *z;
545 x = compile_pattern_not(list);
547 if (p && p->token == GREP_AND) {
549 die("--and not followed by pattern expression");
551 y = compile_pattern_and(list);
553 die("--and not followed by pattern expression");
554 z = xcalloc(1, sizeof (struct grep_expr));
555 z->node = GREP_NODE_AND;
556 z->u.binary.left = x;
557 z->u.binary.right = y;
563 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
566 struct grep_expr *x, *y, *z;
568 x = compile_pattern_and(list);
570 if (x && p && p->token != GREP_CLOSE_PAREN) {
571 y = compile_pattern_or(list);
573 die("not a pattern expression %s", p->pattern);
574 z = xcalloc(1, sizeof (struct grep_expr));
575 z->node = GREP_NODE_OR;
576 z->u.binary.left = x;
577 z->u.binary.right = y;
583 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
585 return compile_pattern_or(list);
588 static void indent(int in)
594 static void dump_grep_pat(struct grep_pat *p)
597 case GREP_AND: fprintf(stderr, "*and*"); break;
598 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
599 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
600 case GREP_NOT: fprintf(stderr, "*not*"); break;
601 case GREP_OR: fprintf(stderr, "*or*"); break;
603 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
604 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
605 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
610 case GREP_PATTERN_HEAD:
611 fprintf(stderr, "<head %d>", p->field); break;
612 case GREP_PATTERN_BODY:
613 fprintf(stderr, "<body>"); break;
617 case GREP_PATTERN_HEAD:
618 case GREP_PATTERN_BODY:
620 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
626 static void dump_grep_expression_1(struct grep_expr *x, int in)
631 fprintf(stderr, "true\n");
634 dump_grep_pat(x->u.atom);
637 fprintf(stderr, "(not\n");
638 dump_grep_expression_1(x->u.unary, in+1);
640 fprintf(stderr, ")\n");
643 fprintf(stderr, "(and\n");
644 dump_grep_expression_1(x->u.binary.left, in+1);
645 dump_grep_expression_1(x->u.binary.right, in+1);
647 fprintf(stderr, ")\n");
650 fprintf(stderr, "(or\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");
659 static void dump_grep_expression(struct grep_opt *opt)
661 struct grep_expr *x = opt->pattern_expression;
664 fprintf(stderr, "[all-match]\n");
665 dump_grep_expression_1(x, 0);
669 static struct grep_expr *grep_true_expr(void)
671 struct grep_expr *z = xcalloc(1, sizeof(*z));
672 z->node = GREP_NODE_TRUE;
676 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
678 struct grep_expr *z = xcalloc(1, sizeof(*z));
679 z->node = GREP_NODE_OR;
680 z->u.binary.left = left;
681 z->u.binary.right = right;
685 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
688 struct grep_expr *header_expr;
689 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
690 enum grep_header_field fld;
692 if (!opt->header_list)
695 for (p = opt->header_list; p; p = p->next) {
696 if (p->token != GREP_PATTERN_HEAD)
697 die("bug: a non-header pattern in grep header list.");
698 if (p->field < GREP_HEADER_FIELD_MIN ||
699 GREP_HEADER_FIELD_MAX <= p->field)
700 die("bug: unknown header field %d", p->field);
701 compile_regexp(p, opt);
704 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
705 header_group[fld] = NULL;
707 for (p = opt->header_list; p; p = p->next) {
709 struct grep_pat *pp = p;
711 h = compile_pattern_atom(&pp);
712 if (!h || pp != p->next)
713 die("bug: malformed header expr");
714 if (!header_group[p->field]) {
715 header_group[p->field] = h;
718 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
723 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
724 if (!header_group[fld])
727 header_expr = grep_true_expr();
728 header_expr = grep_or_expr(header_group[fld], header_expr);
733 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
735 struct grep_expr *z = x;
738 assert(x->node == GREP_NODE_OR);
739 if (x->u.binary.right &&
740 x->u.binary.right->node == GREP_NODE_TRUE) {
741 x->u.binary.right = y;
744 x = x->u.binary.right;
749 static void compile_grep_patterns_real(struct grep_opt *opt)
752 struct grep_expr *header_expr = prep_header_patterns(opt);
754 for (p = opt->pattern_list; p; p = p->next) {
756 case GREP_PATTERN: /* atom */
757 case GREP_PATTERN_HEAD:
758 case GREP_PATTERN_BODY:
759 compile_regexp(p, opt);
767 if (opt->all_match || header_expr)
769 else if (!opt->extended && !opt->debug)
772 p = opt->pattern_list;
774 opt->pattern_expression = compile_pattern_expr(&p);
776 die("incomplete pattern expression: %s", p->pattern);
781 if (!opt->pattern_expression)
782 opt->pattern_expression = header_expr;
783 else if (opt->all_match)
784 opt->pattern_expression = grep_splice_or(header_expr,
785 opt->pattern_expression);
787 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
792 void compile_grep_patterns(struct grep_opt *opt)
794 compile_grep_patterns_real(opt);
796 dump_grep_expression(opt);
799 static void free_pattern_expr(struct grep_expr *x)
806 free_pattern_expr(x->u.unary);
810 free_pattern_expr(x->u.binary.left);
811 free_pattern_expr(x->u.binary.right);
817 void free_grep_patterns(struct grep_opt *opt)
819 struct grep_pat *p, *n;
821 for (p = opt->pattern_list; p; p = n) {
824 case GREP_PATTERN: /* atom */
825 case GREP_PATTERN_HEAD:
826 case GREP_PATTERN_BODY:
829 else if (p->pcre_regexp)
843 free_pattern_expr(opt->pattern_expression);
846 static char *end_of_line(char *cp, unsigned long *left)
848 unsigned long l = *left;
849 while (l && *cp != '\n') {
857 static int word_char(char ch)
859 return isalnum(ch) || ch == '_';
862 static void output_color(struct grep_opt *opt, const void *data, size_t size,
865 if (want_color(opt->color) && color && color[0]) {
866 opt->output(opt, color, strlen(color));
867 opt->output(opt, data, size);
868 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
870 opt->output(opt, data, size);
873 static void output_sep(struct grep_opt *opt, char sign)
875 if (opt->null_following_name)
876 opt->output(opt, "\0", 1);
878 output_color(opt, &sign, 1, opt->color_sep);
881 static void show_name(struct grep_opt *opt, const char *name)
883 output_color(opt, name, strlen(name), opt->color_filename);
884 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
887 static int fixmatch(struct grep_pat *p, char *line, char *eol,
890 struct kwsmatch kwsm;
891 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
893 match->rm_so = match->rm_eo = -1;
896 match->rm_so = offset;
897 match->rm_eo = match->rm_so + kwsm.size[0];
902 static int regmatch(const regex_t *preg, char *line, char *eol,
903 regmatch_t *match, int eflags)
907 match->rm_eo = eol - line;
908 eflags |= REG_STARTEND;
910 return regexec(preg, line, 1, match, eflags);
913 static int patmatch(struct grep_pat *p, char *line, char *eol,
914 regmatch_t *match, int eflags)
919 hit = !fixmatch(p, line, eol, match);
920 else if (p->pcre_regexp)
921 hit = !pcrematch(p, line, eol, match, eflags);
923 hit = !regmatch(&p->regexp, line, eol, match, eflags);
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 snprintf(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 void std_output(struct grep_opt *opt, const void *buf, size_t size)
1395 fwrite(buf, size, 1, stdout);
1398 static int fill_textconv_grep(struct userdiff_driver *driver,
1399 struct grep_source *gs)
1401 struct diff_filespec *df;
1405 if (!driver || !driver->textconv)
1406 return grep_source_load(gs);
1409 * The textconv interface is intimately tied to diff_filespecs, so we
1410 * have to pretend to be one. If we could unify the grep_source
1411 * and diff_filespec structs, this mess could just go away.
1413 df = alloc_filespec(gs->path);
1415 case GREP_SOURCE_SHA1:
1416 fill_filespec(df, gs->identifier, 1, 0100644);
1418 case GREP_SOURCE_FILE:
1419 fill_filespec(df, null_sha1, 0, 0100644);
1422 die("BUG: attempt to textconv something without a path?");
1426 * fill_textconv is not remotely thread-safe; it may load objects
1427 * behind the scenes, and it modifies the global diff tempfile
1431 size = fill_textconv(driver, df, &buf);
1436 * The normal fill_textconv usage by the diff machinery would just keep
1437 * the textconv'd buf separate from the diff_filespec. But much of the
1438 * grep code passes around a grep_source and assumes that its "buf"
1439 * pointer is the beginning of the thing we are searching. So let's
1440 * install our textconv'd version into the grep_source, taking care not
1441 * to leak any existing buffer.
1443 grep_source_clear_data(gs);
1450 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
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 && match_funcname(opt, gs, bol, eol))
1599 if (show_function ||
1600 (last_hit && lno <= last_hit + opt->post_context)) {
1601 /* If the last hit is within the post context,
1602 * we need to show this line.
1604 show_line(opt, bol, eol, gs->name, lno, '-');
1618 if (opt->status_only)
1620 if (opt->unmatch_name_only) {
1621 /* We did not see any hit, so we want to show this */
1622 show_name(opt, gs->name);
1626 xdiff_clear_find_func(&xecfg);
1630 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1631 * which feels mostly useless but sometimes useful. Maybe
1632 * make it another option? For now suppress them.
1634 if (opt->count && count) {
1636 if (opt->pathname) {
1637 output_color(opt, gs->name, strlen(gs->name),
1638 opt->color_filename);
1639 output_sep(opt, ':');
1641 snprintf(buf, sizeof(buf), "%u\n", count);
1642 opt->output(opt, buf, strlen(buf));
1648 static void clr_hit_marker(struct grep_expr *x)
1650 /* All-hit markers are meaningful only at the very top level
1655 if (x->node != GREP_NODE_OR)
1657 x->u.binary.left->hit = 0;
1658 x = x->u.binary.right;
1662 static int chk_hit_marker(struct grep_expr *x)
1664 /* Top level nodes have hit markers. See if they all are hits */
1666 if (x->node != GREP_NODE_OR)
1668 if (!x->u.binary.left->hit)
1670 x = x->u.binary.right;
1674 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1677 * we do not have to do the two-pass grep when we do not check
1678 * buffer-wide "all-match".
1680 if (!opt->all_match)
1681 return grep_source_1(opt, gs, 0);
1683 /* Otherwise the toplevel "or" terms hit a bit differently.
1684 * We first clear hit markers from them.
1686 clr_hit_marker(opt->pattern_expression);
1687 grep_source_1(opt, gs, 1);
1689 if (!chk_hit_marker(opt->pattern_expression))
1692 return grep_source_1(opt, gs, 0);
1695 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1697 struct grep_source gs;
1700 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1704 r = grep_source(opt, &gs);
1706 grep_source_clear(&gs);
1710 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1711 const char *name, const char *path,
1712 const void *identifier)
1715 gs->name = xstrdup_or_null(name);
1716 gs->path = xstrdup_or_null(path);
1722 case GREP_SOURCE_FILE:
1723 gs->identifier = xstrdup(identifier);
1725 case GREP_SOURCE_SHA1:
1726 gs->identifier = xmalloc(20);
1727 hashcpy(gs->identifier, identifier);
1729 case GREP_SOURCE_BUF:
1730 gs->identifier = NULL;
1734 void grep_source_clear(struct grep_source *gs)
1740 free(gs->identifier);
1741 gs->identifier = NULL;
1742 grep_source_clear_data(gs);
1745 void grep_source_clear_data(struct grep_source *gs)
1748 case GREP_SOURCE_FILE:
1749 case GREP_SOURCE_SHA1:
1754 case GREP_SOURCE_BUF:
1755 /* leave user-provided buf intact */
1760 static int grep_source_load_sha1(struct grep_source *gs)
1762 enum object_type type;
1765 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1769 return error(_("'%s': unable to read %s"),
1771 sha1_to_hex(gs->identifier));
1775 static int grep_source_load_file(struct grep_source *gs)
1777 const char *filename = gs->identifier;
1783 if (lstat(filename, &st) < 0) {
1785 if (errno != ENOENT)
1786 error(_("'%s': %s"), filename, strerror(errno));
1789 if (!S_ISREG(st.st_mode))
1791 size = xsize_t(st.st_size);
1792 i = open(filename, O_RDONLY);
1795 data = xmalloc(size + 1);
1796 if (st.st_size != read_in_full(i, data, size)) {
1797 error(_("'%s': short read %s"), filename, strerror(errno));
1810 static int grep_source_load(struct grep_source *gs)
1816 case GREP_SOURCE_FILE:
1817 return grep_source_load_file(gs);
1818 case GREP_SOURCE_SHA1:
1819 return grep_source_load_sha1(gs);
1820 case GREP_SOURCE_BUF:
1821 return gs->buf ? 0 : -1;
1823 die("BUG: invalid grep_source type");
1826 void grep_source_load_driver(struct grep_source *gs)
1833 gs->driver = userdiff_find_by_path(gs->path);
1835 gs->driver = userdiff_find_by_name("default");
1839 static int grep_source_is_binary(struct grep_source *gs)
1841 grep_source_load_driver(gs);
1842 if (gs->driver->binary != -1)
1843 return gs->driver->binary;
1845 if (!grep_source_load(gs))
1846 return buffer_is_binary(gs->buf, gs->size);