tests: change "cd ... && git fetch" to "cd &&\n\tgit fetch"
[alt-git.git] / grep.c
blob47cee4506703f5dd2b7db84e09dae93adf99fbaf
1 #include "cache.h"
2 #include "grep.h"
3 #include "userdiff.h"
4 #include "xdiff-interface.h"
5 #include "diff.h"
6 #include "diffcore.h"
7 #include "commit.h"
8 #include "quote.h"
10 static int grep_source_load(struct grep_source *gs);
11 static int grep_source_is_binary(struct grep_source *gs);
13 static struct grep_opt grep_defaults;
15 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
17 fwrite(buf, size, 1, stdout);
21 * Initialize the grep_defaults template with hardcoded defaults.
22 * We could let the compiler do this, but without C99 initializers
23 * the code gets unwieldy and unreadable, so...
25 void init_grep_defaults(void)
27 struct grep_opt *opt = &grep_defaults;
28 static int run_once;
30 if (run_once)
31 return;
32 run_once++;
34 memset(opt, 0, sizeof(*opt));
35 opt->relative = 1;
36 opt->pathname = 1;
37 opt->regflags = REG_NEWLINE;
38 opt->max_depth = -1;
39 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
40 opt->extended_regexp_option = 0;
41 color_set(opt->color_context, "");
42 color_set(opt->color_filename, "");
43 color_set(opt->color_function, "");
44 color_set(opt->color_lineno, "");
45 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
46 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_selected, "");
48 color_set(opt->color_sep, GIT_COLOR_CYAN);
49 opt->color = -1;
50 opt->output = std_output;
53 static int parse_pattern_type_arg(const char *opt, const char *arg)
55 if (!strcmp(arg, "default"))
56 return GREP_PATTERN_TYPE_UNSPECIFIED;
57 else if (!strcmp(arg, "basic"))
58 return GREP_PATTERN_TYPE_BRE;
59 else if (!strcmp(arg, "extended"))
60 return GREP_PATTERN_TYPE_ERE;
61 else if (!strcmp(arg, "fixed"))
62 return GREP_PATTERN_TYPE_FIXED;
63 else if (!strcmp(arg, "perl"))
64 return GREP_PATTERN_TYPE_PCRE;
65 die("bad %s argument: %s", opt, arg);
69 * Read the configuration file once and store it in
70 * the grep_defaults template.
72 int grep_config(const char *var, const char *value, void *cb)
74 struct grep_opt *opt = &grep_defaults;
75 char *color = NULL;
77 if (userdiff_config(var, value) < 0)
78 return -1;
80 if (!strcmp(var, "grep.extendedregexp")) {
81 if (git_config_bool(var, value))
82 opt->extended_regexp_option = 1;
83 else
84 opt->extended_regexp_option = 0;
85 return 0;
88 if (!strcmp(var, "grep.patterntype")) {
89 opt->pattern_type_option = parse_pattern_type_arg(var, value);
90 return 0;
93 if (!strcmp(var, "grep.linenumber")) {
94 opt->linenum = git_config_bool(var, value);
95 return 0;
98 if (!strcmp(var, "grep.fullname")) {
99 opt->relative = !git_config_bool(var, value);
100 return 0;
103 if (!strcmp(var, "color.grep"))
104 opt->color = git_config_colorbool(var, value);
105 else if (!strcmp(var, "color.grep.context"))
106 color = opt->color_context;
107 else if (!strcmp(var, "color.grep.filename"))
108 color = opt->color_filename;
109 else if (!strcmp(var, "color.grep.function"))
110 color = opt->color_function;
111 else if (!strcmp(var, "color.grep.linenumber"))
112 color = opt->color_lineno;
113 else if (!strcmp(var, "color.grep.matchcontext"))
114 color = opt->color_match_context;
115 else if (!strcmp(var, "color.grep.matchselected"))
116 color = opt->color_match_selected;
117 else if (!strcmp(var, "color.grep.selected"))
118 color = opt->color_selected;
119 else if (!strcmp(var, "color.grep.separator"))
120 color = opt->color_sep;
121 else if (!strcmp(var, "color.grep.match")) {
122 int rc = 0;
123 if (!value)
124 return config_error_nonbool(var);
125 rc |= color_parse(value, opt->color_match_context);
126 rc |= color_parse(value, opt->color_match_selected);
127 return rc;
130 if (color) {
131 if (!value)
132 return config_error_nonbool(var);
133 return color_parse(value, color);
135 return 0;
139 * Initialize one instance of grep_opt and copy the
140 * default values from the template we read the configuration
141 * information in an earlier call to git_config(grep_config).
143 void grep_init(struct grep_opt *opt, const char *prefix)
145 struct grep_opt *def = &grep_defaults;
147 memset(opt, 0, sizeof(*opt));
148 opt->prefix = prefix;
149 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
150 opt->pattern_tail = &opt->pattern_list;
151 opt->header_tail = &opt->header_list;
153 opt->color = def->color;
154 opt->extended_regexp_option = def->extended_regexp_option;
155 opt->pattern_type_option = def->pattern_type_option;
156 opt->linenum = def->linenum;
157 opt->max_depth = def->max_depth;
158 opt->pathname = def->pathname;
159 opt->regflags = def->regflags;
160 opt->relative = def->relative;
161 opt->output = def->output;
163 color_set(opt->color_context, def->color_context);
164 color_set(opt->color_filename, def->color_filename);
165 color_set(opt->color_function, def->color_function);
166 color_set(opt->color_lineno, def->color_lineno);
167 color_set(opt->color_match_context, def->color_match_context);
168 color_set(opt->color_match_selected, def->color_match_selected);
169 color_set(opt->color_selected, def->color_selected);
170 color_set(opt->color_sep, def->color_sep);
173 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
175 switch (pattern_type) {
176 case GREP_PATTERN_TYPE_UNSPECIFIED:
177 /* fall through */
179 case GREP_PATTERN_TYPE_BRE:
180 opt->fixed = 0;
181 opt->pcre = 0;
182 opt->regflags &= ~REG_EXTENDED;
183 break;
185 case GREP_PATTERN_TYPE_ERE:
186 opt->fixed = 0;
187 opt->pcre = 0;
188 opt->regflags |= REG_EXTENDED;
189 break;
191 case GREP_PATTERN_TYPE_FIXED:
192 opt->fixed = 1;
193 opt->pcre = 0;
194 opt->regflags &= ~REG_EXTENDED;
195 break;
197 case GREP_PATTERN_TYPE_PCRE:
198 opt->fixed = 0;
199 opt->pcre = 1;
200 opt->regflags &= ~REG_EXTENDED;
201 break;
205 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
207 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
208 grep_set_pattern_type_option(pattern_type, opt);
209 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
210 grep_set_pattern_type_option(opt->pattern_type_option, opt);
211 else if (opt->extended_regexp_option)
212 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
215 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
216 const char *origin, int no,
217 enum grep_pat_token t,
218 enum grep_header_field field)
220 struct grep_pat *p = xcalloc(1, sizeof(*p));
221 p->pattern = xmemdupz(pat, patlen);
222 p->patternlen = patlen;
223 p->origin = origin;
224 p->no = no;
225 p->token = t;
226 p->field = field;
227 return p;
230 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
232 **tail = p;
233 *tail = &p->next;
234 p->next = NULL;
236 switch (p->token) {
237 case GREP_PATTERN: /* atom */
238 case GREP_PATTERN_HEAD:
239 case GREP_PATTERN_BODY:
240 for (;;) {
241 struct grep_pat *new_pat;
242 size_t len = 0;
243 char *cp = p->pattern + p->patternlen, *nl = NULL;
244 while (++len <= p->patternlen) {
245 if (*(--cp) == '\n') {
246 nl = cp;
247 break;
250 if (!nl)
251 break;
252 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
253 p->no, p->token, p->field);
254 new_pat->next = p->next;
255 if (!p->next)
256 *tail = &new_pat->next;
257 p->next = new_pat;
258 *nl = '\0';
259 p->patternlen -= len;
261 break;
262 default:
263 break;
267 void append_header_grep_pattern(struct grep_opt *opt,
268 enum grep_header_field field, const char *pat)
270 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
271 GREP_PATTERN_HEAD, field);
272 if (field == GREP_HEADER_REFLOG)
273 opt->use_reflog_filter = 1;
274 do_append_grep_pat(&opt->header_tail, p);
277 void append_grep_pattern(struct grep_opt *opt, const char *pat,
278 const char *origin, int no, enum grep_pat_token t)
280 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
283 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
284 const char *origin, int no, enum grep_pat_token t)
286 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
287 do_append_grep_pat(&opt->pattern_tail, p);
290 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
292 struct grep_pat *pat;
293 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
294 *ret = *opt;
296 ret->pattern_list = NULL;
297 ret->pattern_tail = &ret->pattern_list;
299 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
301 if(pat->token == GREP_PATTERN_HEAD)
302 append_header_grep_pattern(ret, pat->field,
303 pat->pattern);
304 else
305 append_grep_pat(ret, pat->pattern, pat->patternlen,
306 pat->origin, pat->no, pat->token);
309 return ret;
312 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
313 const char *error)
315 char where[1024];
317 if (p->no)
318 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
319 else if (p->origin)
320 xsnprintf(where, sizeof(where), "%s, ", p->origin);
321 else
322 where[0] = 0;
324 die("%s'%s': %s", where, p->pattern, error);
327 #ifdef USE_LIBPCRE
328 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
330 const char *error;
331 int erroffset;
332 int options = PCRE_MULTILINE;
334 if (opt->ignore_case) {
335 if (has_non_ascii(p->pattern))
336 p->pcre_tables = pcre_maketables();
337 options |= PCRE_CASELESS;
339 if (is_utf8_locale() && has_non_ascii(p->pattern))
340 options |= PCRE_UTF8;
342 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
343 p->pcre_tables);
344 if (!p->pcre_regexp)
345 compile_regexp_failed(p, error);
347 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
348 if (!p->pcre_extra_info && error)
349 die("%s", error);
352 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
353 regmatch_t *match, int eflags)
355 int ovector[30], ret, flags = 0;
357 if (eflags & REG_NOTBOL)
358 flags |= PCRE_NOTBOL;
360 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
361 0, flags, ovector, ARRAY_SIZE(ovector));
362 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
363 die("pcre_exec failed with error code %d", ret);
364 if (ret > 0) {
365 ret = 0;
366 match->rm_so = ovector[0];
367 match->rm_eo = ovector[1];
370 return ret;
373 static void free_pcre_regexp(struct grep_pat *p)
375 pcre_free(p->pcre_regexp);
376 pcre_free(p->pcre_extra_info);
377 pcre_free((void *)p->pcre_tables);
379 #else /* !USE_LIBPCRE */
380 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
382 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
385 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
386 regmatch_t *match, int eflags)
388 return 1;
391 static void free_pcre_regexp(struct grep_pat *p)
394 #endif /* !USE_LIBPCRE */
396 static int is_fixed(const char *s, size_t len)
398 size_t i;
400 /* regcomp cannot accept patterns with NULs so we
401 * consider any pattern containing a NUL fixed.
403 if (memchr(s, 0, len))
404 return 1;
406 for (i = 0; i < len; i++) {
407 if (is_regex_special(s[i]))
408 return 0;
411 return 1;
414 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
416 struct strbuf sb = STRBUF_INIT;
417 int err;
418 int regflags;
420 basic_regex_quote_buf(&sb, p->pattern);
421 regflags = opt->regflags & ~REG_EXTENDED;
422 if (opt->ignore_case)
423 regflags |= REG_ICASE;
424 err = regcomp(&p->regexp, sb.buf, regflags);
425 if (opt->debug)
426 fprintf(stderr, "fixed %s\n", sb.buf);
427 strbuf_release(&sb);
428 if (err) {
429 char errbuf[1024];
430 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
431 regfree(&p->regexp);
432 compile_regexp_failed(p, errbuf);
436 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
438 int icase, ascii_only;
439 int err;
441 p->word_regexp = opt->word_regexp;
442 p->ignore_case = opt->ignore_case;
443 icase = opt->regflags & REG_ICASE || p->ignore_case;
444 ascii_only = !has_non_ascii(p->pattern);
447 * Even when -F (fixed) asks us to do a non-regexp search, we
448 * may not be able to correctly case-fold when -i
449 * (ignore-case) is asked (in which case, we'll synthesize a
450 * regexp to match the pattern that matches regexp special
451 * characters literally, while ignoring case differences). On
452 * the other hand, even without -F, if the pattern does not
453 * have any regexp special characters and there is no need for
454 * case-folding search, we can internally turn it into a
455 * simple string match using kws. p->fixed tells us if we
456 * want to use kws.
458 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
459 p->fixed = !icase || ascii_only;
460 else
461 p->fixed = 0;
463 if (p->fixed) {
464 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
465 kwsincr(p->kws, p->pattern, p->patternlen);
466 kwsprep(p->kws);
467 return;
468 } else if (opt->fixed) {
470 * We come here when the pattern has the non-ascii
471 * characters we cannot case-fold, and asked to
472 * ignore-case.
474 compile_fixed_regexp(p, opt);
475 return;
478 if (opt->pcre) {
479 compile_pcre_regexp(p, opt);
480 return;
483 err = regcomp(&p->regexp, p->pattern, opt->regflags);
484 if (err) {
485 char errbuf[1024];
486 regerror(err, &p->regexp, errbuf, 1024);
487 regfree(&p->regexp);
488 compile_regexp_failed(p, errbuf);
492 static struct grep_expr *compile_pattern_or(struct grep_pat **);
493 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
495 struct grep_pat *p;
496 struct grep_expr *x;
498 p = *list;
499 if (!p)
500 return NULL;
501 switch (p->token) {
502 case GREP_PATTERN: /* atom */
503 case GREP_PATTERN_HEAD:
504 case GREP_PATTERN_BODY:
505 x = xcalloc(1, sizeof (struct grep_expr));
506 x->node = GREP_NODE_ATOM;
507 x->u.atom = p;
508 *list = p->next;
509 return x;
510 case GREP_OPEN_PAREN:
511 *list = p->next;
512 x = compile_pattern_or(list);
513 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
514 die("unmatched parenthesis");
515 *list = (*list)->next;
516 return x;
517 default:
518 return NULL;
522 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
524 struct grep_pat *p;
525 struct grep_expr *x;
527 p = *list;
528 if (!p)
529 return NULL;
530 switch (p->token) {
531 case GREP_NOT:
532 if (!p->next)
533 die("--not not followed by pattern expression");
534 *list = p->next;
535 x = xcalloc(1, sizeof (struct grep_expr));
536 x->node = GREP_NODE_NOT;
537 x->u.unary = compile_pattern_not(list);
538 if (!x->u.unary)
539 die("--not followed by non pattern expression");
540 return x;
541 default:
542 return compile_pattern_atom(list);
546 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
548 struct grep_pat *p;
549 struct grep_expr *x, *y, *z;
551 x = compile_pattern_not(list);
552 p = *list;
553 if (p && p->token == GREP_AND) {
554 if (!p->next)
555 die("--and not followed by pattern expression");
556 *list = p->next;
557 y = compile_pattern_and(list);
558 if (!y)
559 die("--and not followed by pattern expression");
560 z = xcalloc(1, sizeof (struct grep_expr));
561 z->node = GREP_NODE_AND;
562 z->u.binary.left = x;
563 z->u.binary.right = y;
564 return z;
566 return x;
569 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
571 struct grep_pat *p;
572 struct grep_expr *x, *y, *z;
574 x = compile_pattern_and(list);
575 p = *list;
576 if (x && p && p->token != GREP_CLOSE_PAREN) {
577 y = compile_pattern_or(list);
578 if (!y)
579 die("not a pattern expression %s", p->pattern);
580 z = xcalloc(1, sizeof (struct grep_expr));
581 z->node = GREP_NODE_OR;
582 z->u.binary.left = x;
583 z->u.binary.right = y;
584 return z;
586 return x;
589 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
591 return compile_pattern_or(list);
594 static void indent(int in)
596 while (in-- > 0)
597 fputc(' ', stderr);
600 static void dump_grep_pat(struct grep_pat *p)
602 switch (p->token) {
603 case GREP_AND: fprintf(stderr, "*and*"); break;
604 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
605 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
606 case GREP_NOT: fprintf(stderr, "*not*"); break;
607 case GREP_OR: fprintf(stderr, "*or*"); break;
609 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
610 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
611 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
614 switch (p->token) {
615 default: break;
616 case GREP_PATTERN_HEAD:
617 fprintf(stderr, "<head %d>", p->field); break;
618 case GREP_PATTERN_BODY:
619 fprintf(stderr, "<body>"); break;
621 switch (p->token) {
622 default: break;
623 case GREP_PATTERN_HEAD:
624 case GREP_PATTERN_BODY:
625 case GREP_PATTERN:
626 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
627 break;
629 fputc('\n', stderr);
632 static void dump_grep_expression_1(struct grep_expr *x, int in)
634 indent(in);
635 switch (x->node) {
636 case GREP_NODE_TRUE:
637 fprintf(stderr, "true\n");
638 break;
639 case GREP_NODE_ATOM:
640 dump_grep_pat(x->u.atom);
641 break;
642 case GREP_NODE_NOT:
643 fprintf(stderr, "(not\n");
644 dump_grep_expression_1(x->u.unary, in+1);
645 indent(in);
646 fprintf(stderr, ")\n");
647 break;
648 case GREP_NODE_AND:
649 fprintf(stderr, "(and\n");
650 dump_grep_expression_1(x->u.binary.left, in+1);
651 dump_grep_expression_1(x->u.binary.right, in+1);
652 indent(in);
653 fprintf(stderr, ")\n");
654 break;
655 case GREP_NODE_OR:
656 fprintf(stderr, "(or\n");
657 dump_grep_expression_1(x->u.binary.left, in+1);
658 dump_grep_expression_1(x->u.binary.right, in+1);
659 indent(in);
660 fprintf(stderr, ")\n");
661 break;
665 static void dump_grep_expression(struct grep_opt *opt)
667 struct grep_expr *x = opt->pattern_expression;
669 if (opt->all_match)
670 fprintf(stderr, "[all-match]\n");
671 dump_grep_expression_1(x, 0);
672 fflush(NULL);
675 static struct grep_expr *grep_true_expr(void)
677 struct grep_expr *z = xcalloc(1, sizeof(*z));
678 z->node = GREP_NODE_TRUE;
679 return z;
682 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
684 struct grep_expr *z = xcalloc(1, sizeof(*z));
685 z->node = GREP_NODE_OR;
686 z->u.binary.left = left;
687 z->u.binary.right = right;
688 return z;
691 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
693 struct grep_pat *p;
694 struct grep_expr *header_expr;
695 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
696 enum grep_header_field fld;
698 if (!opt->header_list)
699 return NULL;
701 for (p = opt->header_list; p; p = p->next) {
702 if (p->token != GREP_PATTERN_HEAD)
703 die("BUG: a non-header pattern in grep header list.");
704 if (p->field < GREP_HEADER_FIELD_MIN ||
705 GREP_HEADER_FIELD_MAX <= p->field)
706 die("BUG: unknown header field %d", p->field);
707 compile_regexp(p, opt);
710 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
711 header_group[fld] = NULL;
713 for (p = opt->header_list; p; p = p->next) {
714 struct grep_expr *h;
715 struct grep_pat *pp = p;
717 h = compile_pattern_atom(&pp);
718 if (!h || pp != p->next)
719 die("BUG: malformed header expr");
720 if (!header_group[p->field]) {
721 header_group[p->field] = h;
722 continue;
724 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
727 header_expr = NULL;
729 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
730 if (!header_group[fld])
731 continue;
732 if (!header_expr)
733 header_expr = grep_true_expr();
734 header_expr = grep_or_expr(header_group[fld], header_expr);
736 return header_expr;
739 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
741 struct grep_expr *z = x;
743 while (x) {
744 assert(x->node == GREP_NODE_OR);
745 if (x->u.binary.right &&
746 x->u.binary.right->node == GREP_NODE_TRUE) {
747 x->u.binary.right = y;
748 break;
750 x = x->u.binary.right;
752 return z;
755 static void compile_grep_patterns_real(struct grep_opt *opt)
757 struct grep_pat *p;
758 struct grep_expr *header_expr = prep_header_patterns(opt);
760 for (p = opt->pattern_list; p; p = p->next) {
761 switch (p->token) {
762 case GREP_PATTERN: /* atom */
763 case GREP_PATTERN_HEAD:
764 case GREP_PATTERN_BODY:
765 compile_regexp(p, opt);
766 break;
767 default:
768 opt->extended = 1;
769 break;
773 if (opt->all_match || header_expr)
774 opt->extended = 1;
775 else if (!opt->extended && !opt->debug)
776 return;
778 p = opt->pattern_list;
779 if (p)
780 opt->pattern_expression = compile_pattern_expr(&p);
781 if (p)
782 die("incomplete pattern expression: %s", p->pattern);
784 if (!header_expr)
785 return;
787 if (!opt->pattern_expression)
788 opt->pattern_expression = header_expr;
789 else if (opt->all_match)
790 opt->pattern_expression = grep_splice_or(header_expr,
791 opt->pattern_expression);
792 else
793 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
794 header_expr);
795 opt->all_match = 1;
798 void compile_grep_patterns(struct grep_opt *opt)
800 compile_grep_patterns_real(opt);
801 if (opt->debug)
802 dump_grep_expression(opt);
805 static void free_pattern_expr(struct grep_expr *x)
807 switch (x->node) {
808 case GREP_NODE_TRUE:
809 case GREP_NODE_ATOM:
810 break;
811 case GREP_NODE_NOT:
812 free_pattern_expr(x->u.unary);
813 break;
814 case GREP_NODE_AND:
815 case GREP_NODE_OR:
816 free_pattern_expr(x->u.binary.left);
817 free_pattern_expr(x->u.binary.right);
818 break;
820 free(x);
823 void free_grep_patterns(struct grep_opt *opt)
825 struct grep_pat *p, *n;
827 for (p = opt->pattern_list; p; p = n) {
828 n = p->next;
829 switch (p->token) {
830 case GREP_PATTERN: /* atom */
831 case GREP_PATTERN_HEAD:
832 case GREP_PATTERN_BODY:
833 if (p->kws)
834 kwsfree(p->kws);
835 else if (p->pcre_regexp)
836 free_pcre_regexp(p);
837 else
838 regfree(&p->regexp);
839 free(p->pattern);
840 break;
841 default:
842 break;
844 free(p);
847 if (!opt->extended)
848 return;
849 free_pattern_expr(opt->pattern_expression);
852 static char *end_of_line(char *cp, unsigned long *left)
854 unsigned long l = *left;
855 while (l && *cp != '\n') {
856 l--;
857 cp++;
859 *left = l;
860 return cp;
863 static int word_char(char ch)
865 return isalnum(ch) || ch == '_';
868 static void output_color(struct grep_opt *opt, const void *data, size_t size,
869 const char *color)
871 if (want_color(opt->color) && color && color[0]) {
872 opt->output(opt, color, strlen(color));
873 opt->output(opt, data, size);
874 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
875 } else
876 opt->output(opt, data, size);
879 static void output_sep(struct grep_opt *opt, char sign)
881 if (opt->null_following_name)
882 opt->output(opt, "\0", 1);
883 else
884 output_color(opt, &sign, 1, opt->color_sep);
887 static void show_name(struct grep_opt *opt, const char *name)
889 output_color(opt, name, strlen(name), opt->color_filename);
890 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
893 static int fixmatch(struct grep_pat *p, char *line, char *eol,
894 regmatch_t *match)
896 struct kwsmatch kwsm;
897 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
898 if (offset == -1) {
899 match->rm_so = match->rm_eo = -1;
900 return REG_NOMATCH;
901 } else {
902 match->rm_so = offset;
903 match->rm_eo = match->rm_so + kwsm.size[0];
904 return 0;
908 static int patmatch(struct grep_pat *p, char *line, char *eol,
909 regmatch_t *match, int eflags)
911 int hit;
913 if (p->fixed)
914 hit = !fixmatch(p, line, eol, match);
915 else if (p->pcre_regexp)
916 hit = !pcrematch(p, line, eol, match, eflags);
917 else
918 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
919 eflags);
921 return hit;
924 static int strip_timestamp(char *bol, char **eol_p)
926 char *eol = *eol_p;
927 int ch;
929 while (bol < --eol) {
930 if (*eol != '>')
931 continue;
932 *eol_p = ++eol;
933 ch = *eol;
934 *eol = '\0';
935 return ch;
937 return 0;
940 static struct {
941 const char *field;
942 size_t len;
943 } header_field[] = {
944 { "author ", 7 },
945 { "committer ", 10 },
946 { "reflog ", 7 },
949 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
950 enum grep_context ctx,
951 regmatch_t *pmatch, int eflags)
953 int hit = 0;
954 int saved_ch = 0;
955 const char *start = bol;
957 if ((p->token != GREP_PATTERN) &&
958 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
959 return 0;
961 if (p->token == GREP_PATTERN_HEAD) {
962 const char *field;
963 size_t len;
964 assert(p->field < ARRAY_SIZE(header_field));
965 field = header_field[p->field].field;
966 len = header_field[p->field].len;
967 if (strncmp(bol, field, len))
968 return 0;
969 bol += len;
970 switch (p->field) {
971 case GREP_HEADER_AUTHOR:
972 case GREP_HEADER_COMMITTER:
973 saved_ch = strip_timestamp(bol, &eol);
974 break;
975 default:
976 break;
980 again:
981 hit = patmatch(p, bol, eol, pmatch, eflags);
983 if (hit && p->word_regexp) {
984 if ((pmatch[0].rm_so < 0) ||
985 (eol - bol) < pmatch[0].rm_so ||
986 (pmatch[0].rm_eo < 0) ||
987 (eol - bol) < pmatch[0].rm_eo)
988 die("regexp returned nonsense");
990 /* Match beginning must be either beginning of the
991 * line, or at word boundary (i.e. the last char must
992 * not be a word char). Similarly, match end must be
993 * either end of the line, or at word boundary
994 * (i.e. the next char must not be a word char).
996 if ( ((pmatch[0].rm_so == 0) ||
997 !word_char(bol[pmatch[0].rm_so-1])) &&
998 ((pmatch[0].rm_eo == (eol-bol)) ||
999 !word_char(bol[pmatch[0].rm_eo])) )
1001 else
1002 hit = 0;
1004 /* Words consist of at least one character. */
1005 if (pmatch->rm_so == pmatch->rm_eo)
1006 hit = 0;
1008 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1009 /* There could be more than one match on the
1010 * line, and the first match might not be
1011 * strict word match. But later ones could be!
1012 * Forward to the next possible start, i.e. the
1013 * next position following a non-word char.
1015 bol = pmatch[0].rm_so + bol + 1;
1016 while (word_char(bol[-1]) && bol < eol)
1017 bol++;
1018 eflags |= REG_NOTBOL;
1019 if (bol < eol)
1020 goto again;
1023 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1024 *eol = saved_ch;
1025 if (hit) {
1026 pmatch[0].rm_so += bol - start;
1027 pmatch[0].rm_eo += bol - start;
1029 return hit;
1032 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1033 enum grep_context ctx, int collect_hits)
1035 int h = 0;
1036 regmatch_t match;
1038 if (!x)
1039 die("Not a valid grep expression");
1040 switch (x->node) {
1041 case GREP_NODE_TRUE:
1042 h = 1;
1043 break;
1044 case GREP_NODE_ATOM:
1045 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1046 break;
1047 case GREP_NODE_NOT:
1048 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1049 break;
1050 case GREP_NODE_AND:
1051 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1052 return 0;
1053 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1054 break;
1055 case GREP_NODE_OR:
1056 if (!collect_hits)
1057 return (match_expr_eval(x->u.binary.left,
1058 bol, eol, ctx, 0) ||
1059 match_expr_eval(x->u.binary.right,
1060 bol, eol, ctx, 0));
1061 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1062 x->u.binary.left->hit |= h;
1063 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1064 break;
1065 default:
1066 die("Unexpected node type (internal error) %d", x->node);
1068 if (collect_hits)
1069 x->hit |= h;
1070 return h;
1073 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1074 enum grep_context ctx, int collect_hits)
1076 struct grep_expr *x = opt->pattern_expression;
1077 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1080 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1081 enum grep_context ctx, int collect_hits)
1083 struct grep_pat *p;
1084 regmatch_t match;
1086 if (opt->extended)
1087 return match_expr(opt, bol, eol, ctx, collect_hits);
1089 /* we do not call with collect_hits without being extended */
1090 for (p = opt->pattern_list; p; p = p->next) {
1091 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1092 return 1;
1094 return 0;
1097 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1098 enum grep_context ctx,
1099 regmatch_t *pmatch, int eflags)
1101 regmatch_t match;
1103 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1104 return 0;
1105 if (match.rm_so < 0 || match.rm_eo < 0)
1106 return 0;
1107 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1108 if (match.rm_so > pmatch->rm_so)
1109 return 1;
1110 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1111 return 1;
1113 pmatch->rm_so = match.rm_so;
1114 pmatch->rm_eo = match.rm_eo;
1115 return 1;
1118 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1119 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1121 struct grep_pat *p;
1122 int hit = 0;
1124 pmatch->rm_so = pmatch->rm_eo = -1;
1125 if (bol < eol) {
1126 for (p = opt->pattern_list; p; p = p->next) {
1127 switch (p->token) {
1128 case GREP_PATTERN: /* atom */
1129 case GREP_PATTERN_HEAD:
1130 case GREP_PATTERN_BODY:
1131 hit |= match_next_pattern(p, bol, eol, ctx,
1132 pmatch, eflags);
1133 break;
1134 default:
1135 break;
1139 return hit;
1142 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1143 const char *name, unsigned lno, char sign)
1145 int rest = eol - bol;
1146 const char *match_color, *line_color = NULL;
1148 if (opt->file_break && opt->last_shown == 0) {
1149 if (opt->show_hunk_mark)
1150 opt->output(opt, "\n", 1);
1151 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1152 if (opt->last_shown == 0) {
1153 if (opt->show_hunk_mark) {
1154 output_color(opt, "--", 2, opt->color_sep);
1155 opt->output(opt, "\n", 1);
1157 } else if (lno > opt->last_shown + 1) {
1158 output_color(opt, "--", 2, opt->color_sep);
1159 opt->output(opt, "\n", 1);
1162 if (opt->heading && opt->last_shown == 0) {
1163 output_color(opt, name, strlen(name), opt->color_filename);
1164 opt->output(opt, "\n", 1);
1166 opt->last_shown = lno;
1168 if (!opt->heading && opt->pathname) {
1169 output_color(opt, name, strlen(name), opt->color_filename);
1170 output_sep(opt, sign);
1172 if (opt->linenum) {
1173 char buf[32];
1174 xsnprintf(buf, sizeof(buf), "%d", lno);
1175 output_color(opt, buf, strlen(buf), opt->color_lineno);
1176 output_sep(opt, sign);
1178 if (opt->color) {
1179 regmatch_t match;
1180 enum grep_context ctx = GREP_CONTEXT_BODY;
1181 int ch = *eol;
1182 int eflags = 0;
1184 if (sign == ':')
1185 match_color = opt->color_match_selected;
1186 else
1187 match_color = opt->color_match_context;
1188 if (sign == ':')
1189 line_color = opt->color_selected;
1190 else if (sign == '-')
1191 line_color = opt->color_context;
1192 else if (sign == '=')
1193 line_color = opt->color_function;
1194 *eol = '\0';
1195 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1196 if (match.rm_so == match.rm_eo)
1197 break;
1199 output_color(opt, bol, match.rm_so, line_color);
1200 output_color(opt, bol + match.rm_so,
1201 match.rm_eo - match.rm_so, match_color);
1202 bol += match.rm_eo;
1203 rest -= match.rm_eo;
1204 eflags = REG_NOTBOL;
1206 *eol = ch;
1208 output_color(opt, bol, rest, line_color);
1209 opt->output(opt, "\n", 1);
1212 #ifndef NO_PTHREADS
1213 int grep_use_locks;
1216 * This lock protects access to the gitattributes machinery, which is
1217 * not thread-safe.
1219 pthread_mutex_t grep_attr_mutex;
1221 static inline void grep_attr_lock(void)
1223 if (grep_use_locks)
1224 pthread_mutex_lock(&grep_attr_mutex);
1227 static inline void grep_attr_unlock(void)
1229 if (grep_use_locks)
1230 pthread_mutex_unlock(&grep_attr_mutex);
1234 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1236 pthread_mutex_t grep_read_mutex;
1238 #else
1239 #define grep_attr_lock()
1240 #define grep_attr_unlock()
1241 #endif
1243 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1245 xdemitconf_t *xecfg = opt->priv;
1246 if (xecfg && !xecfg->find_func) {
1247 grep_source_load_driver(gs);
1248 if (gs->driver->funcname.pattern) {
1249 const struct userdiff_funcname *pe = &gs->driver->funcname;
1250 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1251 } else {
1252 xecfg = opt->priv = NULL;
1256 if (xecfg) {
1257 char buf[1];
1258 return xecfg->find_func(bol, eol - bol, buf, 1,
1259 xecfg->find_func_priv) >= 0;
1262 if (bol == eol)
1263 return 0;
1264 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1265 return 1;
1266 return 0;
1269 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1270 char *bol, unsigned lno)
1272 while (bol > gs->buf) {
1273 char *eol = --bol;
1275 while (bol > gs->buf && bol[-1] != '\n')
1276 bol--;
1277 lno--;
1279 if (lno <= opt->last_shown)
1280 break;
1282 if (match_funcname(opt, gs, bol, eol)) {
1283 show_line(opt, bol, eol, gs->name, lno, '=');
1284 break;
1289 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1290 char *bol, char *end, unsigned lno)
1292 unsigned cur = lno, from = 1, funcname_lno = 0;
1293 int funcname_needed = !!opt->funcname;
1295 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1296 funcname_needed = 2;
1298 if (opt->pre_context < lno)
1299 from = lno - opt->pre_context;
1300 if (from <= opt->last_shown)
1301 from = opt->last_shown + 1;
1303 /* Rewind. */
1304 while (bol > gs->buf &&
1305 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1306 char *eol = --bol;
1308 while (bol > gs->buf && bol[-1] != '\n')
1309 bol--;
1310 cur--;
1311 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1312 funcname_lno = cur;
1313 funcname_needed = 0;
1317 /* We need to look even further back to find a function signature. */
1318 if (opt->funcname && funcname_needed)
1319 show_funcname_line(opt, gs, bol, cur);
1321 /* Back forward. */
1322 while (cur < lno) {
1323 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1325 while (*eol != '\n')
1326 eol++;
1327 show_line(opt, bol, eol, gs->name, cur, sign);
1328 bol = eol + 1;
1329 cur++;
1333 static int should_lookahead(struct grep_opt *opt)
1335 struct grep_pat *p;
1337 if (opt->extended)
1338 return 0; /* punt for too complex stuff */
1339 if (opt->invert)
1340 return 0;
1341 for (p = opt->pattern_list; p; p = p->next) {
1342 if (p->token != GREP_PATTERN)
1343 return 0; /* punt for "header only" and stuff */
1345 return 1;
1348 static int look_ahead(struct grep_opt *opt,
1349 unsigned long *left_p,
1350 unsigned *lno_p,
1351 char **bol_p)
1353 unsigned lno = *lno_p;
1354 char *bol = *bol_p;
1355 struct grep_pat *p;
1356 char *sp, *last_bol;
1357 regoff_t earliest = -1;
1359 for (p = opt->pattern_list; p; p = p->next) {
1360 int hit;
1361 regmatch_t m;
1363 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1364 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1365 continue;
1366 if (earliest < 0 || m.rm_so < earliest)
1367 earliest = m.rm_so;
1370 if (earliest < 0) {
1371 *bol_p = bol + *left_p;
1372 *left_p = 0;
1373 return 1;
1375 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1376 ; /* find the beginning of the line */
1377 last_bol = sp;
1379 for (sp = bol; sp < last_bol; sp++) {
1380 if (*sp == '\n')
1381 lno++;
1383 *left_p -= last_bol - bol;
1384 *bol_p = last_bol;
1385 *lno_p = lno;
1386 return 0;
1389 static int fill_textconv_grep(struct userdiff_driver *driver,
1390 struct grep_source *gs)
1392 struct diff_filespec *df;
1393 char *buf;
1394 size_t size;
1396 if (!driver || !driver->textconv)
1397 return grep_source_load(gs);
1400 * The textconv interface is intimately tied to diff_filespecs, so we
1401 * have to pretend to be one. If we could unify the grep_source
1402 * and diff_filespec structs, this mess could just go away.
1404 df = alloc_filespec(gs->path);
1405 switch (gs->type) {
1406 case GREP_SOURCE_SHA1:
1407 fill_filespec(df, gs->identifier, 1, 0100644);
1408 break;
1409 case GREP_SOURCE_FILE:
1410 fill_filespec(df, null_sha1, 0, 0100644);
1411 break;
1412 default:
1413 die("BUG: attempt to textconv something without a path?");
1417 * fill_textconv is not remotely thread-safe; it may load objects
1418 * behind the scenes, and it modifies the global diff tempfile
1419 * structure.
1421 grep_read_lock();
1422 size = fill_textconv(driver, df, &buf);
1423 grep_read_unlock();
1424 free_filespec(df);
1427 * The normal fill_textconv usage by the diff machinery would just keep
1428 * the textconv'd buf separate from the diff_filespec. But much of the
1429 * grep code passes around a grep_source and assumes that its "buf"
1430 * pointer is the beginning of the thing we are searching. So let's
1431 * install our textconv'd version into the grep_source, taking care not
1432 * to leak any existing buffer.
1434 grep_source_clear_data(gs);
1435 gs->buf = buf;
1436 gs->size = size;
1438 return 0;
1441 static int is_empty_line(const char *bol, const char *eol)
1443 while (bol < eol && isspace(*bol))
1444 bol++;
1445 return bol == eol;
1448 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1450 char *bol;
1451 char *peek_bol = NULL;
1452 unsigned long left;
1453 unsigned lno = 1;
1454 unsigned last_hit = 0;
1455 int binary_match_only = 0;
1456 unsigned count = 0;
1457 int try_lookahead = 0;
1458 int show_function = 0;
1459 struct userdiff_driver *textconv = NULL;
1460 enum grep_context ctx = GREP_CONTEXT_HEAD;
1461 xdemitconf_t xecfg;
1463 if (!opt->output)
1464 opt->output = std_output;
1466 if (opt->pre_context || opt->post_context || opt->file_break ||
1467 opt->funcbody) {
1468 /* Show hunk marks, except for the first file. */
1469 if (opt->last_shown)
1470 opt->show_hunk_mark = 1;
1472 * If we're using threads then we can't easily identify
1473 * the first file. Always put hunk marks in that case
1474 * and skip the very first one later in work_done().
1476 if (opt->output != std_output)
1477 opt->show_hunk_mark = 1;
1479 opt->last_shown = 0;
1481 if (opt->allow_textconv) {
1482 grep_source_load_driver(gs);
1484 * We might set up the shared textconv cache data here, which
1485 * is not thread-safe.
1487 grep_attr_lock();
1488 textconv = userdiff_get_textconv(gs->driver);
1489 grep_attr_unlock();
1493 * We know the result of a textconv is text, so we only have to care
1494 * about binary handling if we are not using it.
1496 if (!textconv) {
1497 switch (opt->binary) {
1498 case GREP_BINARY_DEFAULT:
1499 if (grep_source_is_binary(gs))
1500 binary_match_only = 1;
1501 break;
1502 case GREP_BINARY_NOMATCH:
1503 if (grep_source_is_binary(gs))
1504 return 0; /* Assume unmatch */
1505 break;
1506 case GREP_BINARY_TEXT:
1507 break;
1508 default:
1509 die("BUG: unknown binary handling mode");
1513 memset(&xecfg, 0, sizeof(xecfg));
1514 opt->priv = &xecfg;
1516 try_lookahead = should_lookahead(opt);
1518 if (fill_textconv_grep(textconv, gs) < 0)
1519 return 0;
1521 bol = gs->buf;
1522 left = gs->size;
1523 while (left) {
1524 char *eol, ch;
1525 int hit;
1528 * look_ahead() skips quickly to the line that possibly
1529 * has the next hit; don't call it if we need to do
1530 * something more than just skipping the current line
1531 * in response to an unmatch for the current line. E.g.
1532 * inside a post-context window, we will show the current
1533 * line as a context around the previous hit when it
1534 * doesn't hit.
1536 if (try_lookahead
1537 && !(last_hit
1538 && (show_function ||
1539 lno <= last_hit + opt->post_context))
1540 && look_ahead(opt, &left, &lno, &bol))
1541 break;
1542 eol = end_of_line(bol, &left);
1543 ch = *eol;
1544 *eol = 0;
1546 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1547 ctx = GREP_CONTEXT_BODY;
1549 hit = match_line(opt, bol, eol, ctx, collect_hits);
1550 *eol = ch;
1552 if (collect_hits)
1553 goto next_line;
1555 /* "grep -v -e foo -e bla" should list lines
1556 * that do not have either, so inversion should
1557 * be done outside.
1559 if (opt->invert)
1560 hit = !hit;
1561 if (opt->unmatch_name_only) {
1562 if (hit)
1563 return 0;
1564 goto next_line;
1566 if (hit) {
1567 count++;
1568 if (opt->status_only)
1569 return 1;
1570 if (opt->name_only) {
1571 show_name(opt, gs->name);
1572 return 1;
1574 if (opt->count)
1575 goto next_line;
1576 if (binary_match_only) {
1577 opt->output(opt, "Binary file ", 12);
1578 output_color(opt, gs->name, strlen(gs->name),
1579 opt->color_filename);
1580 opt->output(opt, " matches\n", 9);
1581 return 1;
1583 /* Hit at this line. If we haven't shown the
1584 * pre-context lines, we would need to show them.
1586 if (opt->pre_context || opt->funcbody)
1587 show_pre_context(opt, gs, bol, eol, lno);
1588 else if (opt->funcname)
1589 show_funcname_line(opt, gs, bol, lno);
1590 show_line(opt, bol, eol, gs->name, lno, ':');
1591 last_hit = lno;
1592 if (opt->funcbody)
1593 show_function = 1;
1594 goto next_line;
1596 if (show_function && (!peek_bol || peek_bol < bol)) {
1597 unsigned long peek_left = left;
1598 char *peek_eol = eol;
1601 * Trailing empty lines are not interesting.
1602 * Peek past them to see if they belong to the
1603 * body of the current function.
1605 peek_bol = bol;
1606 while (is_empty_line(peek_bol, peek_eol)) {
1607 peek_bol = peek_eol + 1;
1608 peek_eol = end_of_line(peek_bol, &peek_left);
1611 if (match_funcname(opt, gs, peek_bol, peek_eol))
1612 show_function = 0;
1614 if (show_function ||
1615 (last_hit && lno <= last_hit + opt->post_context)) {
1616 /* If the last hit is within the post context,
1617 * we need to show this line.
1619 show_line(opt, bol, eol, gs->name, lno, '-');
1622 next_line:
1623 bol = eol + 1;
1624 if (!left)
1625 break;
1626 left--;
1627 lno++;
1630 if (collect_hits)
1631 return 0;
1633 if (opt->status_only)
1634 return 0;
1635 if (opt->unmatch_name_only) {
1636 /* We did not see any hit, so we want to show this */
1637 show_name(opt, gs->name);
1638 return 1;
1641 xdiff_clear_find_func(&xecfg);
1642 opt->priv = NULL;
1644 /* NEEDSWORK:
1645 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1646 * which feels mostly useless but sometimes useful. Maybe
1647 * make it another option? For now suppress them.
1649 if (opt->count && count) {
1650 char buf[32];
1651 if (opt->pathname) {
1652 output_color(opt, gs->name, strlen(gs->name),
1653 opt->color_filename);
1654 output_sep(opt, ':');
1656 xsnprintf(buf, sizeof(buf), "%u\n", count);
1657 opt->output(opt, buf, strlen(buf));
1658 return 1;
1660 return !!last_hit;
1663 static void clr_hit_marker(struct grep_expr *x)
1665 /* All-hit markers are meaningful only at the very top level
1666 * OR node.
1668 while (1) {
1669 x->hit = 0;
1670 if (x->node != GREP_NODE_OR)
1671 return;
1672 x->u.binary.left->hit = 0;
1673 x = x->u.binary.right;
1677 static int chk_hit_marker(struct grep_expr *x)
1679 /* Top level nodes have hit markers. See if they all are hits */
1680 while (1) {
1681 if (x->node != GREP_NODE_OR)
1682 return x->hit;
1683 if (!x->u.binary.left->hit)
1684 return 0;
1685 x = x->u.binary.right;
1689 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1692 * we do not have to do the two-pass grep when we do not check
1693 * buffer-wide "all-match".
1695 if (!opt->all_match)
1696 return grep_source_1(opt, gs, 0);
1698 /* Otherwise the toplevel "or" terms hit a bit differently.
1699 * We first clear hit markers from them.
1701 clr_hit_marker(opt->pattern_expression);
1702 grep_source_1(opt, gs, 1);
1704 if (!chk_hit_marker(opt->pattern_expression))
1705 return 0;
1707 return grep_source_1(opt, gs, 0);
1710 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1712 struct grep_source gs;
1713 int r;
1715 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1716 gs.buf = buf;
1717 gs.size = size;
1719 r = grep_source(opt, &gs);
1721 grep_source_clear(&gs);
1722 return r;
1725 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1726 const char *name, const char *path,
1727 const void *identifier)
1729 gs->type = type;
1730 gs->name = xstrdup_or_null(name);
1731 gs->path = xstrdup_or_null(path);
1732 gs->buf = NULL;
1733 gs->size = 0;
1734 gs->driver = NULL;
1736 switch (type) {
1737 case GREP_SOURCE_FILE:
1738 gs->identifier = xstrdup(identifier);
1739 break;
1740 case GREP_SOURCE_SUBMODULE:
1741 if (!identifier) {
1742 gs->identifier = NULL;
1743 break;
1746 * FALL THROUGH
1747 * If the identifier is non-NULL (in the submodule case) it
1748 * will be a SHA1 that needs to be copied.
1750 case GREP_SOURCE_SHA1:
1751 gs->identifier = xmalloc(20);
1752 hashcpy(gs->identifier, identifier);
1753 break;
1754 case GREP_SOURCE_BUF:
1755 gs->identifier = NULL;
1756 break;
1760 void grep_source_clear(struct grep_source *gs)
1762 free(gs->name);
1763 gs->name = NULL;
1764 free(gs->path);
1765 gs->path = NULL;
1766 free(gs->identifier);
1767 gs->identifier = NULL;
1768 grep_source_clear_data(gs);
1771 void grep_source_clear_data(struct grep_source *gs)
1773 switch (gs->type) {
1774 case GREP_SOURCE_FILE:
1775 case GREP_SOURCE_SHA1:
1776 case GREP_SOURCE_SUBMODULE:
1777 free(gs->buf);
1778 gs->buf = NULL;
1779 gs->size = 0;
1780 break;
1781 case GREP_SOURCE_BUF:
1782 /* leave user-provided buf intact */
1783 break;
1787 static int grep_source_load_sha1(struct grep_source *gs)
1789 enum object_type type;
1791 grep_read_lock();
1792 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1793 grep_read_unlock();
1795 if (!gs->buf)
1796 return error(_("'%s': unable to read %s"),
1797 gs->name,
1798 sha1_to_hex(gs->identifier));
1799 return 0;
1802 static int grep_source_load_file(struct grep_source *gs)
1804 const char *filename = gs->identifier;
1805 struct stat st;
1806 char *data;
1807 size_t size;
1808 int i;
1810 if (lstat(filename, &st) < 0) {
1811 err_ret:
1812 if (errno != ENOENT)
1813 error_errno(_("failed to stat '%s'"), filename);
1814 return -1;
1816 if (!S_ISREG(st.st_mode))
1817 return -1;
1818 size = xsize_t(st.st_size);
1819 i = open(filename, O_RDONLY);
1820 if (i < 0)
1821 goto err_ret;
1822 data = xmallocz(size);
1823 if (st.st_size != read_in_full(i, data, size)) {
1824 error_errno(_("'%s': short read"), filename);
1825 close(i);
1826 free(data);
1827 return -1;
1829 close(i);
1831 gs->buf = data;
1832 gs->size = size;
1833 return 0;
1836 static int grep_source_load(struct grep_source *gs)
1838 if (gs->buf)
1839 return 0;
1841 switch (gs->type) {
1842 case GREP_SOURCE_FILE:
1843 return grep_source_load_file(gs);
1844 case GREP_SOURCE_SHA1:
1845 return grep_source_load_sha1(gs);
1846 case GREP_SOURCE_BUF:
1847 return gs->buf ? 0 : -1;
1848 case GREP_SOURCE_SUBMODULE:
1849 break;
1851 die("BUG: invalid grep_source type to load");
1854 void grep_source_load_driver(struct grep_source *gs)
1856 if (gs->driver)
1857 return;
1859 grep_attr_lock();
1860 if (gs->path)
1861 gs->driver = userdiff_find_by_path(gs->path);
1862 if (!gs->driver)
1863 gs->driver = userdiff_find_by_name("default");
1864 grep_attr_unlock();
1867 static int grep_source_is_binary(struct grep_source *gs)
1869 grep_source_load_driver(gs);
1870 if (gs->driver->binary != -1)
1871 return gs->driver->binary;
1873 if (!grep_source_load(gs))
1874 return buffer_is_binary(gs->buf, gs->size);
1876 return 0;