4 #include "xdiff-interface.h"
6 static int grep_source_load(struct grep_source *gs);
7 static int grep_source_is_binary(struct grep_source *gs);
9 static struct grep_opt grep_defaults;
12 * Initialize the grep_defaults template with hardcoded defaults.
13 * We could let the compiler do this, but without C99 initializers
14 * the code gets unwieldy and unreadable, so...
16 void init_grep_defaults(void)
18 struct grep_opt *opt = &grep_defaults;
20 memset(opt, 0, sizeof(*opt));
23 opt->regflags = REG_NEWLINE;
25 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
26 opt->extended_regexp_option = 0;
27 strcpy(opt->color_context, "");
28 strcpy(opt->color_filename, "");
29 strcpy(opt->color_function, "");
30 strcpy(opt->color_lineno, "");
31 strcpy(opt->color_match, GIT_COLOR_BOLD_RED);
32 strcpy(opt->color_selected, "");
33 strcpy(opt->color_sep, GIT_COLOR_CYAN);
37 static int parse_pattern_type_arg(const char *opt, const char *arg)
39 if (!strcmp(arg, "default"))
40 return GREP_PATTERN_TYPE_UNSPECIFIED;
41 else if (!strcmp(arg, "basic"))
42 return GREP_PATTERN_TYPE_BRE;
43 else if (!strcmp(arg, "extended"))
44 return GREP_PATTERN_TYPE_ERE;
45 else if (!strcmp(arg, "fixed"))
46 return GREP_PATTERN_TYPE_FIXED;
47 else if (!strcmp(arg, "perl"))
48 return GREP_PATTERN_TYPE_PCRE;
49 die("bad %s argument: %s", opt, arg);
53 * Read the configuration file once and store it in
54 * the grep_defaults template.
56 int grep_config(const char *var, const char *value, void *cb)
58 struct grep_opt *opt = &grep_defaults;
61 if (userdiff_config(var, value) < 0)
64 if (!strcmp(var, "grep.extendedregexp")) {
65 if (git_config_bool(var, value))
66 opt->extended_regexp_option = 1;
68 opt->extended_regexp_option = 0;
72 if (!strcmp(var, "grep.patterntype")) {
73 opt->pattern_type_option = parse_pattern_type_arg(var, value);
77 if (!strcmp(var, "grep.linenumber")) {
78 opt->linenum = git_config_bool(var, value);
82 if (!strcmp(var, "color.grep"))
83 opt->color = git_config_colorbool(var, value);
84 else if (!strcmp(var, "color.grep.context"))
85 color = opt->color_context;
86 else if (!strcmp(var, "color.grep.filename"))
87 color = opt->color_filename;
88 else if (!strcmp(var, "color.grep.function"))
89 color = opt->color_function;
90 else if (!strcmp(var, "color.grep.linenumber"))
91 color = opt->color_lineno;
92 else if (!strcmp(var, "color.grep.match"))
93 color = opt->color_match;
94 else if (!strcmp(var, "color.grep.selected"))
95 color = opt->color_selected;
96 else if (!strcmp(var, "color.grep.separator"))
97 color = opt->color_sep;
101 return config_error_nonbool(var);
102 color_parse(value, var, color);
108 * Initialize one instance of grep_opt and copy the
109 * default values from the template we read the configuration
110 * information in an earlier call to git_config(grep_config).
112 void grep_init(struct grep_opt *opt, const char *prefix)
114 struct grep_opt *def = &grep_defaults;
116 memset(opt, 0, sizeof(*opt));
117 opt->prefix = prefix;
118 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
119 opt->pattern_tail = &opt->pattern_list;
120 opt->header_tail = &opt->header_list;
122 opt->color = def->color;
123 opt->extended_regexp_option = def->extended_regexp_option;
124 opt->pattern_type_option = def->pattern_type_option;
125 opt->linenum = def->linenum;
126 opt->max_depth = def->max_depth;
127 opt->pathname = def->pathname;
128 opt->regflags = def->regflags;
129 opt->relative = def->relative;
131 strcpy(opt->color_context, def->color_context);
132 strcpy(opt->color_filename, def->color_filename);
133 strcpy(opt->color_function, def->color_function);
134 strcpy(opt->color_lineno, def->color_lineno);
135 strcpy(opt->color_match, def->color_match);
136 strcpy(opt->color_selected, def->color_selected);
137 strcpy(opt->color_sep, def->color_sep);
140 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
141 const char *origin, int no,
142 enum grep_pat_token t,
143 enum grep_header_field field)
145 struct grep_pat *p = xcalloc(1, sizeof(*p));
146 p->pattern = xmemdupz(pat, patlen);
147 p->patternlen = patlen;
155 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
162 case GREP_PATTERN: /* atom */
163 case GREP_PATTERN_HEAD:
164 case GREP_PATTERN_BODY:
166 struct grep_pat *new_pat;
168 char *cp = p->pattern + p->patternlen, *nl = NULL;
169 while (++len <= p->patternlen) {
170 if (*(--cp) == '\n') {
177 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
178 p->no, p->token, p->field);
179 new_pat->next = p->next;
181 *tail = &new_pat->next;
184 p->patternlen -= len;
192 void append_header_grep_pattern(struct grep_opt *opt,
193 enum grep_header_field field, const char *pat)
195 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
196 GREP_PATTERN_HEAD, field);
197 if (field == GREP_HEADER_REFLOG)
198 opt->use_reflog_filter = 1;
199 do_append_grep_pat(&opt->header_tail, p);
202 void append_grep_pattern(struct grep_opt *opt, const char *pat,
203 const char *origin, int no, enum grep_pat_token t)
205 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
208 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
209 const char *origin, int no, enum grep_pat_token t)
211 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
212 do_append_grep_pat(&opt->pattern_tail, p);
215 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
217 struct grep_pat *pat;
218 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
221 ret->pattern_list = NULL;
222 ret->pattern_tail = &ret->pattern_list;
224 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
226 if(pat->token == GREP_PATTERN_HEAD)
227 append_header_grep_pattern(ret, pat->field,
230 append_grep_pat(ret, pat->pattern, pat->patternlen,
231 pat->origin, pat->no, pat->token);
237 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
243 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
245 sprintf(where, "%s, ", p->origin);
249 die("%s'%s': %s", where, p->pattern, error);
253 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
257 int options = PCRE_MULTILINE;
259 if (opt->ignore_case)
260 options |= PCRE_CASELESS;
262 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
265 compile_regexp_failed(p, error);
267 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
268 if (!p->pcre_extra_info && error)
272 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
273 regmatch_t *match, int eflags)
275 int ovector[30], ret, flags = 0;
277 if (eflags & REG_NOTBOL)
278 flags |= PCRE_NOTBOL;
280 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
281 0, flags, ovector, ARRAY_SIZE(ovector));
282 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
283 die("pcre_exec failed with error code %d", ret);
286 match->rm_so = ovector[0];
287 match->rm_eo = ovector[1];
293 static void free_pcre_regexp(struct grep_pat *p)
295 pcre_free(p->pcre_regexp);
296 pcre_free(p->pcre_extra_info);
298 #else /* !USE_LIBPCRE */
299 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
301 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
304 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
305 regmatch_t *match, int eflags)
310 static void free_pcre_regexp(struct grep_pat *p)
313 #endif /* !USE_LIBPCRE */
315 static int is_fixed(const char *s, size_t len)
319 /* regcomp cannot accept patterns with NULs so we
320 * consider any pattern containing a NUL fixed.
322 if (memchr(s, 0, len))
325 for (i = 0; i < len; i++) {
326 if (is_regex_special(s[i]))
333 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
337 p->word_regexp = opt->word_regexp;
338 p->ignore_case = opt->ignore_case;
340 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
346 if (opt->regflags & REG_ICASE || p->ignore_case)
347 p->kws = kwsalloc(tolower_trans_tbl);
349 p->kws = kwsalloc(NULL);
350 kwsincr(p->kws, p->pattern, p->patternlen);
356 compile_pcre_regexp(p, opt);
360 err = regcomp(&p->regexp, p->pattern, opt->regflags);
363 regerror(err, &p->regexp, errbuf, 1024);
365 compile_regexp_failed(p, errbuf);
369 static struct grep_expr *compile_pattern_or(struct grep_pat **);
370 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
379 case GREP_PATTERN: /* atom */
380 case GREP_PATTERN_HEAD:
381 case GREP_PATTERN_BODY:
382 x = xcalloc(1, sizeof (struct grep_expr));
383 x->node = GREP_NODE_ATOM;
387 case GREP_OPEN_PAREN:
389 x = compile_pattern_or(list);
390 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
391 die("unmatched parenthesis");
392 *list = (*list)->next;
399 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
410 die("--not not followed by pattern expression");
412 x = xcalloc(1, sizeof (struct grep_expr));
413 x->node = GREP_NODE_NOT;
414 x->u.unary = compile_pattern_not(list);
416 die("--not followed by non pattern expression");
419 return compile_pattern_atom(list);
423 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
426 struct grep_expr *x, *y, *z;
428 x = compile_pattern_not(list);
430 if (p && p->token == GREP_AND) {
432 die("--and not followed by pattern expression");
434 y = compile_pattern_and(list);
436 die("--and not followed by pattern expression");
437 z = xcalloc(1, sizeof (struct grep_expr));
438 z->node = GREP_NODE_AND;
439 z->u.binary.left = x;
440 z->u.binary.right = y;
446 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
449 struct grep_expr *x, *y, *z;
451 x = compile_pattern_and(list);
453 if (x && p && p->token != GREP_CLOSE_PAREN) {
454 y = compile_pattern_or(list);
456 die("not a pattern expression %s", p->pattern);
457 z = xcalloc(1, sizeof (struct grep_expr));
458 z->node = GREP_NODE_OR;
459 z->u.binary.left = x;
460 z->u.binary.right = y;
466 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
468 return compile_pattern_or(list);
471 static void indent(int in)
477 static void dump_grep_pat(struct grep_pat *p)
480 case GREP_AND: fprintf(stderr, "*and*"); break;
481 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
482 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
483 case GREP_NOT: fprintf(stderr, "*not*"); break;
484 case GREP_OR: fprintf(stderr, "*or*"); break;
486 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
487 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
488 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
493 case GREP_PATTERN_HEAD:
494 fprintf(stderr, "<head %d>", p->field); break;
495 case GREP_PATTERN_BODY:
496 fprintf(stderr, "<body>"); break;
500 case GREP_PATTERN_HEAD:
501 case GREP_PATTERN_BODY:
503 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
509 static void dump_grep_expression_1(struct grep_expr *x, int in)
514 fprintf(stderr, "true\n");
517 dump_grep_pat(x->u.atom);
520 fprintf(stderr, "(not\n");
521 dump_grep_expression_1(x->u.unary, in+1);
523 fprintf(stderr, ")\n");
526 fprintf(stderr, "(and\n");
527 dump_grep_expression_1(x->u.binary.left, in+1);
528 dump_grep_expression_1(x->u.binary.right, in+1);
530 fprintf(stderr, ")\n");
533 fprintf(stderr, "(or\n");
534 dump_grep_expression_1(x->u.binary.left, in+1);
535 dump_grep_expression_1(x->u.binary.right, in+1);
537 fprintf(stderr, ")\n");
542 static void dump_grep_expression(struct grep_opt *opt)
544 struct grep_expr *x = opt->pattern_expression;
547 fprintf(stderr, "[all-match]\n");
548 dump_grep_expression_1(x, 0);
552 static struct grep_expr *grep_true_expr(void)
554 struct grep_expr *z = xcalloc(1, sizeof(*z));
555 z->node = GREP_NODE_TRUE;
559 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
561 struct grep_expr *z = xcalloc(1, sizeof(*z));
562 z->node = GREP_NODE_OR;
563 z->u.binary.left = left;
564 z->u.binary.right = right;
568 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
571 struct grep_expr *header_expr;
572 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
573 enum grep_header_field fld;
575 if (!opt->header_list)
578 for (p = opt->header_list; p; p = p->next) {
579 if (p->token != GREP_PATTERN_HEAD)
580 die("bug: a non-header pattern in grep header list.");
581 if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
582 die("bug: unknown header field %d", p->field);
583 compile_regexp(p, opt);
586 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
587 header_group[fld] = NULL;
589 for (p = opt->header_list; p; p = p->next) {
591 struct grep_pat *pp = p;
593 h = compile_pattern_atom(&pp);
594 if (!h || pp != p->next)
595 die("bug: malformed header expr");
596 if (!header_group[p->field]) {
597 header_group[p->field] = h;
600 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
605 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
606 if (!header_group[fld])
609 header_expr = grep_true_expr();
610 header_expr = grep_or_expr(header_group[fld], header_expr);
615 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
617 struct grep_expr *z = x;
620 assert(x->node == GREP_NODE_OR);
621 if (x->u.binary.right &&
622 x->u.binary.right->node == GREP_NODE_TRUE) {
623 x->u.binary.right = y;
626 x = x->u.binary.right;
631 static void compile_grep_patterns_real(struct grep_opt *opt)
634 struct grep_expr *header_expr = prep_header_patterns(opt);
636 for (p = opt->pattern_list; p; p = p->next) {
638 case GREP_PATTERN: /* atom */
639 case GREP_PATTERN_HEAD:
640 case GREP_PATTERN_BODY:
641 compile_regexp(p, opt);
649 if (opt->all_match || header_expr)
651 else if (!opt->extended && !opt->debug)
654 p = opt->pattern_list;
656 opt->pattern_expression = compile_pattern_expr(&p);
658 die("incomplete pattern expression: %s", p->pattern);
663 if (!opt->pattern_expression)
664 opt->pattern_expression = header_expr;
665 else if (opt->all_match)
666 opt->pattern_expression = grep_splice_or(header_expr,
667 opt->pattern_expression);
669 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
674 void compile_grep_patterns(struct grep_opt *opt)
676 compile_grep_patterns_real(opt);
678 dump_grep_expression(opt);
681 static void free_pattern_expr(struct grep_expr *x)
688 free_pattern_expr(x->u.unary);
692 free_pattern_expr(x->u.binary.left);
693 free_pattern_expr(x->u.binary.right);
699 void free_grep_patterns(struct grep_opt *opt)
701 struct grep_pat *p, *n;
703 for (p = opt->pattern_list; p; p = n) {
706 case GREP_PATTERN: /* atom */
707 case GREP_PATTERN_HEAD:
708 case GREP_PATTERN_BODY:
711 else if (p->pcre_regexp)
725 free_pattern_expr(opt->pattern_expression);
728 static char *end_of_line(char *cp, unsigned long *left)
730 unsigned long l = *left;
731 while (l && *cp != '\n') {
739 static int word_char(char ch)
741 return isalnum(ch) || ch == '_';
744 static void output_color(struct grep_opt *opt, const void *data, size_t size,
747 if (want_color(opt->color) && color && color[0]) {
748 opt->output(opt, color, strlen(color));
749 opt->output(opt, data, size);
750 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
752 opt->output(opt, data, size);
755 static void output_sep(struct grep_opt *opt, char sign)
757 if (opt->null_following_name)
758 opt->output(opt, "\0", 1);
760 output_color(opt, &sign, 1, opt->color_sep);
763 static void show_name(struct grep_opt *opt, const char *name)
765 output_color(opt, name, strlen(name), opt->color_filename);
766 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
769 static int fixmatch(struct grep_pat *p, char *line, char *eol,
772 struct kwsmatch kwsm;
773 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
775 match->rm_so = match->rm_eo = -1;
778 match->rm_so = offset;
779 match->rm_eo = match->rm_so + kwsm.size[0];
784 static int regmatch(const regex_t *preg, char *line, char *eol,
785 regmatch_t *match, int eflags)
789 match->rm_eo = eol - line;
790 eflags |= REG_STARTEND;
792 return regexec(preg, line, 1, match, eflags);
795 static int patmatch(struct grep_pat *p, char *line, char *eol,
796 regmatch_t *match, int eflags)
801 hit = !fixmatch(p, line, eol, match);
802 else if (p->pcre_regexp)
803 hit = !pcrematch(p, line, eol, match, eflags);
805 hit = !regmatch(&p->regexp, line, eol, match, eflags);
810 static int strip_timestamp(char *bol, char **eol_p)
815 while (bol < --eol) {
831 { "committer ", 10 },
835 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
836 enum grep_context ctx,
837 regmatch_t *pmatch, int eflags)
841 const char *start = bol;
843 if ((p->token != GREP_PATTERN) &&
844 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
847 if (p->token == GREP_PATTERN_HEAD) {
850 assert(p->field < ARRAY_SIZE(header_field));
851 field = header_field[p->field].field;
852 len = header_field[p->field].len;
853 if (strncmp(bol, field, len))
857 case GREP_HEADER_AUTHOR:
858 case GREP_HEADER_COMMITTER:
859 saved_ch = strip_timestamp(bol, &eol);
867 hit = patmatch(p, bol, eol, pmatch, eflags);
869 if (hit && p->word_regexp) {
870 if ((pmatch[0].rm_so < 0) ||
871 (eol - bol) < pmatch[0].rm_so ||
872 (pmatch[0].rm_eo < 0) ||
873 (eol - bol) < pmatch[0].rm_eo)
874 die("regexp returned nonsense");
876 /* Match beginning must be either beginning of the
877 * line, or at word boundary (i.e. the last char must
878 * not be a word char). Similarly, match end must be
879 * either end of the line, or at word boundary
880 * (i.e. the next char must not be a word char).
882 if ( ((pmatch[0].rm_so == 0) ||
883 !word_char(bol[pmatch[0].rm_so-1])) &&
884 ((pmatch[0].rm_eo == (eol-bol)) ||
885 !word_char(bol[pmatch[0].rm_eo])) )
890 /* Words consist of at least one character. */
891 if (pmatch->rm_so == pmatch->rm_eo)
894 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
895 /* There could be more than one match on the
896 * line, and the first match might not be
897 * strict word match. But later ones could be!
898 * Forward to the next possible start, i.e. the
899 * next position following a non-word char.
901 bol = pmatch[0].rm_so + bol + 1;
902 while (word_char(bol[-1]) && bol < eol)
904 eflags |= REG_NOTBOL;
909 if (p->token == GREP_PATTERN_HEAD && saved_ch)
912 pmatch[0].rm_so += bol - start;
913 pmatch[0].rm_eo += bol - start;
918 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
919 enum grep_context ctx, int collect_hits)
925 die("Not a valid grep expression");
931 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
934 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
937 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
939 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
943 return (match_expr_eval(x->u.binary.left,
945 match_expr_eval(x->u.binary.right,
947 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
948 x->u.binary.left->hit |= h;
949 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
952 die("Unexpected node type (internal error) %d", x->node);
959 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
960 enum grep_context ctx, int collect_hits)
962 struct grep_expr *x = opt->pattern_expression;
963 return match_expr_eval(x, bol, eol, ctx, collect_hits);
966 static int match_line(struct grep_opt *opt, char *bol, char *eol,
967 enum grep_context ctx, int collect_hits)
973 return match_expr(opt, bol, eol, ctx, collect_hits);
975 /* we do not call with collect_hits without being extended */
976 for (p = opt->pattern_list; p; p = p->next) {
977 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
983 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
984 enum grep_context ctx,
985 regmatch_t *pmatch, int eflags)
989 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
991 if (match.rm_so < 0 || match.rm_eo < 0)
993 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
994 if (match.rm_so > pmatch->rm_so)
996 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
999 pmatch->rm_so = match.rm_so;
1000 pmatch->rm_eo = match.rm_eo;
1004 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1005 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1010 pmatch->rm_so = pmatch->rm_eo = -1;
1012 for (p = opt->pattern_list; p; p = p->next) {
1014 case GREP_PATTERN: /* atom */
1015 case GREP_PATTERN_HEAD:
1016 case GREP_PATTERN_BODY:
1017 hit |= match_next_pattern(p, bol, eol, ctx,
1028 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1029 const char *name, unsigned lno, char sign)
1031 int rest = eol - bol;
1032 char *line_color = NULL;
1034 if (opt->file_break && opt->last_shown == 0) {
1035 if (opt->show_hunk_mark)
1036 opt->output(opt, "\n", 1);
1037 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1038 if (opt->last_shown == 0) {
1039 if (opt->show_hunk_mark) {
1040 output_color(opt, "--", 2, opt->color_sep);
1041 opt->output(opt, "\n", 1);
1043 } else if (lno > opt->last_shown + 1) {
1044 output_color(opt, "--", 2, opt->color_sep);
1045 opt->output(opt, "\n", 1);
1048 if (opt->heading && opt->last_shown == 0) {
1049 output_color(opt, name, strlen(name), opt->color_filename);
1050 opt->output(opt, "\n", 1);
1052 opt->last_shown = lno;
1054 if (!opt->heading && opt->pathname) {
1055 output_color(opt, name, strlen(name), opt->color_filename);
1056 output_sep(opt, sign);
1060 snprintf(buf, sizeof(buf), "%d", lno);
1061 output_color(opt, buf, strlen(buf), opt->color_lineno);
1062 output_sep(opt, sign);
1066 enum grep_context ctx = GREP_CONTEXT_BODY;
1071 line_color = opt->color_selected;
1072 else if (sign == '-')
1073 line_color = opt->color_context;
1074 else if (sign == '=')
1075 line_color = opt->color_function;
1077 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1078 if (match.rm_so == match.rm_eo)
1081 output_color(opt, bol, match.rm_so, line_color);
1082 output_color(opt, bol + match.rm_so,
1083 match.rm_eo - match.rm_so,
1086 rest -= match.rm_eo;
1087 eflags = REG_NOTBOL;
1091 output_color(opt, bol, rest, line_color);
1092 opt->output(opt, "\n", 1);
1099 * This lock protects access to the gitattributes machinery, which is
1102 pthread_mutex_t grep_attr_mutex;
1104 static inline void grep_attr_lock(void)
1107 pthread_mutex_lock(&grep_attr_mutex);
1110 static inline void grep_attr_unlock(void)
1113 pthread_mutex_unlock(&grep_attr_mutex);
1117 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1119 pthread_mutex_t grep_read_mutex;
1122 #define grep_attr_lock()
1123 #define grep_attr_unlock()
1126 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1128 xdemitconf_t *xecfg = opt->priv;
1129 if (xecfg && !xecfg->find_func) {
1130 grep_source_load_driver(gs);
1131 if (gs->driver->funcname.pattern) {
1132 const struct userdiff_funcname *pe = &gs->driver->funcname;
1133 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1135 xecfg = opt->priv = NULL;
1141 return xecfg->find_func(bol, eol - bol, buf, 1,
1142 xecfg->find_func_priv) >= 0;
1147 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1152 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1153 char *bol, unsigned lno)
1155 while (bol > gs->buf) {
1158 while (bol > gs->buf && bol[-1] != '\n')
1162 if (lno <= opt->last_shown)
1165 if (match_funcname(opt, gs, bol, eol)) {
1166 show_line(opt, bol, eol, gs->name, lno, '=');
1172 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1173 char *bol, char *end, unsigned lno)
1175 unsigned cur = lno, from = 1, funcname_lno = 0;
1176 int funcname_needed = !!opt->funcname;
1178 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1179 funcname_needed = 2;
1181 if (opt->pre_context < lno)
1182 from = lno - opt->pre_context;
1183 if (from <= opt->last_shown)
1184 from = opt->last_shown + 1;
1187 while (bol > gs->buf &&
1188 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1191 while (bol > gs->buf && bol[-1] != '\n')
1194 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1196 funcname_needed = 0;
1200 /* We need to look even further back to find a function signature. */
1201 if (opt->funcname && funcname_needed)
1202 show_funcname_line(opt, gs, bol, cur);
1206 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1208 while (*eol != '\n')
1210 show_line(opt, bol, eol, gs->name, cur, sign);
1216 static int should_lookahead(struct grep_opt *opt)
1221 return 0; /* punt for too complex stuff */
1224 for (p = opt->pattern_list; p; p = p->next) {
1225 if (p->token != GREP_PATTERN)
1226 return 0; /* punt for "header only" and stuff */
1231 static int look_ahead(struct grep_opt *opt,
1232 unsigned long *left_p,
1236 unsigned lno = *lno_p;
1239 char *sp, *last_bol;
1240 regoff_t earliest = -1;
1242 for (p = opt->pattern_list; p; p = p->next) {
1246 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1247 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1249 if (earliest < 0 || m.rm_so < earliest)
1254 *bol_p = bol + *left_p;
1258 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1259 ; /* find the beginning of the line */
1262 for (sp = bol; sp < last_bol; sp++) {
1266 *left_p -= last_bol - bol;
1272 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1274 fwrite(buf, size, 1, stdout);
1277 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1282 unsigned last_hit = 0;
1283 int binary_match_only = 0;
1285 int try_lookahead = 0;
1286 int show_function = 0;
1287 enum grep_context ctx = GREP_CONTEXT_HEAD;
1291 opt->output = std_output;
1293 if (opt->pre_context || opt->post_context || opt->file_break ||
1295 /* Show hunk marks, except for the first file. */
1296 if (opt->last_shown)
1297 opt->show_hunk_mark = 1;
1299 * If we're using threads then we can't easily identify
1300 * the first file. Always put hunk marks in that case
1301 * and skip the very first one later in work_done().
1303 if (opt->output != std_output)
1304 opt->show_hunk_mark = 1;
1306 opt->last_shown = 0;
1308 switch (opt->binary) {
1309 case GREP_BINARY_DEFAULT:
1310 if (grep_source_is_binary(gs))
1311 binary_match_only = 1;
1313 case GREP_BINARY_NOMATCH:
1314 if (grep_source_is_binary(gs))
1315 return 0; /* Assume unmatch */
1317 case GREP_BINARY_TEXT:
1320 die("bug: unknown binary handling mode");
1323 memset(&xecfg, 0, sizeof(xecfg));
1326 try_lookahead = should_lookahead(opt);
1328 if (grep_source_load(gs) < 0)
1338 * look_ahead() skips quickly to the line that possibly
1339 * has the next hit; don't call it if we need to do
1340 * something more than just skipping the current line
1341 * in response to an unmatch for the current line. E.g.
1342 * inside a post-context window, we will show the current
1343 * line as a context around the previous hit when it
1348 && (show_function ||
1349 lno <= last_hit + opt->post_context))
1350 && look_ahead(opt, &left, &lno, &bol))
1352 eol = end_of_line(bol, &left);
1356 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1357 ctx = GREP_CONTEXT_BODY;
1359 hit = match_line(opt, bol, eol, ctx, collect_hits);
1365 /* "grep -v -e foo -e bla" should list lines
1366 * that do not have either, so inversion should
1371 if (opt->unmatch_name_only) {
1378 if (opt->status_only)
1380 if (opt->name_only) {
1381 show_name(opt, gs->name);
1386 if (binary_match_only) {
1387 opt->output(opt, "Binary file ", 12);
1388 output_color(opt, gs->name, strlen(gs->name),
1389 opt->color_filename);
1390 opt->output(opt, " matches\n", 9);
1393 /* Hit at this line. If we haven't shown the
1394 * pre-context lines, we would need to show them.
1396 if (opt->pre_context || opt->funcbody)
1397 show_pre_context(opt, gs, bol, eol, lno);
1398 else if (opt->funcname)
1399 show_funcname_line(opt, gs, bol, lno);
1400 show_line(opt, bol, eol, gs->name, lno, ':');
1406 if (show_function && match_funcname(opt, gs, bol, eol))
1408 if (show_function ||
1409 (last_hit && lno <= last_hit + opt->post_context)) {
1410 /* If the last hit is within the post context,
1411 * we need to show this line.
1413 show_line(opt, bol, eol, gs->name, lno, '-');
1427 if (opt->status_only)
1429 if (opt->unmatch_name_only) {
1430 /* We did not see any hit, so we want to show this */
1431 show_name(opt, gs->name);
1435 xdiff_clear_find_func(&xecfg);
1439 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1440 * which feels mostly useless but sometimes useful. Maybe
1441 * make it another option? For now suppress them.
1443 if (opt->count && count) {
1445 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1446 output_sep(opt, ':');
1447 snprintf(buf, sizeof(buf), "%u\n", count);
1448 opt->output(opt, buf, strlen(buf));
1454 static void clr_hit_marker(struct grep_expr *x)
1456 /* All-hit markers are meaningful only at the very top level
1461 if (x->node != GREP_NODE_OR)
1463 x->u.binary.left->hit = 0;
1464 x = x->u.binary.right;
1468 static int chk_hit_marker(struct grep_expr *x)
1470 /* Top level nodes have hit markers. See if they all are hits */
1472 if (x->node != GREP_NODE_OR)
1474 if (!x->u.binary.left->hit)
1476 x = x->u.binary.right;
1480 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1483 * we do not have to do the two-pass grep when we do not check
1484 * buffer-wide "all-match".
1486 if (!opt->all_match)
1487 return grep_source_1(opt, gs, 0);
1489 /* Otherwise the toplevel "or" terms hit a bit differently.
1490 * We first clear hit markers from them.
1492 clr_hit_marker(opt->pattern_expression);
1493 grep_source_1(opt, gs, 1);
1495 if (!chk_hit_marker(opt->pattern_expression))
1498 return grep_source_1(opt, gs, 0);
1501 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1503 struct grep_source gs;
1506 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL);
1510 r = grep_source(opt, &gs);
1512 grep_source_clear(&gs);
1516 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1517 const char *name, const void *identifier)
1520 gs->name = name ? xstrdup(name) : NULL;
1526 case GREP_SOURCE_FILE:
1527 gs->identifier = xstrdup(identifier);
1529 case GREP_SOURCE_SHA1:
1530 gs->identifier = xmalloc(20);
1531 memcpy(gs->identifier, identifier, 20);
1533 case GREP_SOURCE_BUF:
1534 gs->identifier = NULL;
1538 void grep_source_clear(struct grep_source *gs)
1542 free(gs->identifier);
1543 gs->identifier = NULL;
1544 grep_source_clear_data(gs);
1547 void grep_source_clear_data(struct grep_source *gs)
1550 case GREP_SOURCE_FILE:
1551 case GREP_SOURCE_SHA1:
1556 case GREP_SOURCE_BUF:
1557 /* leave user-provided buf intact */
1562 static int grep_source_load_sha1(struct grep_source *gs)
1564 enum object_type type;
1567 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1571 return error(_("'%s': unable to read %s"),
1573 sha1_to_hex(gs->identifier));
1577 static int grep_source_load_file(struct grep_source *gs)
1579 const char *filename = gs->identifier;
1585 if (lstat(filename, &st) < 0) {
1587 if (errno != ENOENT)
1588 error(_("'%s': %s"), filename, strerror(errno));
1591 if (!S_ISREG(st.st_mode))
1593 size = xsize_t(st.st_size);
1594 i = open(filename, O_RDONLY);
1597 data = xmalloc(size + 1);
1598 if (st.st_size != read_in_full(i, data, size)) {
1599 error(_("'%s': short read %s"), filename, strerror(errno));
1612 static int grep_source_load(struct grep_source *gs)
1618 case GREP_SOURCE_FILE:
1619 return grep_source_load_file(gs);
1620 case GREP_SOURCE_SHA1:
1621 return grep_source_load_sha1(gs);
1622 case GREP_SOURCE_BUF:
1623 return gs->buf ? 0 : -1;
1625 die("BUG: invalid grep_source type");
1628 void grep_source_load_driver(struct grep_source *gs)
1634 gs->driver = userdiff_find_by_path(gs->name);
1636 gs->driver = userdiff_find_by_name("default");
1640 static int grep_source_is_binary(struct grep_source *gs)
1642 grep_source_load_driver(gs);
1643 if (gs->driver->binary != -1)
1644 return gs->driver->binary;
1646 if (!grep_source_load(gs))
1647 return buffer_is_binary(gs->buf, gs->size);