grep: rewrite an if/else condition to avoid duplicate expression
[git/debian.git] / grep.c
blob6325cafe73fe695d5bb04bc979d79917669255f4
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;
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;
23 static int run_once;
25 if (run_once)
26 return;
27 run_once++;
29 memset(opt, 0, sizeof(*opt));
30 opt->relative = 1;
31 opt->pathname = 1;
32 opt->regflags = REG_NEWLINE;
33 opt->max_depth = -1;
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);
44 opt->color = -1;
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;
69 char *color = NULL;
71 if (userdiff_config(var, value) < 0)
72 return -1;
74 if (!strcmp(var, "grep.extendedregexp")) {
75 if (git_config_bool(var, value))
76 opt->extended_regexp_option = 1;
77 else
78 opt->extended_regexp_option = 0;
79 return 0;
82 if (!strcmp(var, "grep.patterntype")) {
83 opt->pattern_type_option = parse_pattern_type_arg(var, value);
84 return 0;
87 if (!strcmp(var, "grep.linenumber")) {
88 opt->linenum = git_config_bool(var, value);
89 return 0;
92 if (!strcmp(var, "grep.fullname")) {
93 opt->relative = !git_config_bool(var, value);
94 return 0;
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")) {
116 int rc = 0;
117 if (!value)
118 return config_error_nonbool(var);
119 rc |= color_parse(value, opt->color_match_context);
120 rc |= color_parse(value, opt->color_match_selected);
121 return rc;
124 if (color) {
125 if (!value)
126 return config_error_nonbool(var);
127 return color_parse(value, color);
129 return 0;
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:
180 /* fall through */
182 case GREP_PATTERN_TYPE_BRE:
183 opt->fixed = 0;
184 opt->pcre = 0;
185 opt->regflags &= ~REG_EXTENDED;
186 break;
188 case GREP_PATTERN_TYPE_ERE:
189 opt->fixed = 0;
190 opt->pcre = 0;
191 opt->regflags |= REG_EXTENDED;
192 break;
194 case GREP_PATTERN_TYPE_FIXED:
195 opt->fixed = 1;
196 opt->pcre = 0;
197 opt->regflags &= ~REG_EXTENDED;
198 break;
200 case GREP_PATTERN_TYPE_PCRE:
201 opt->fixed = 0;
202 opt->pcre = 1;
203 opt->regflags &= ~REG_EXTENDED;
204 break;
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;
216 p->origin = origin;
217 p->no = no;
218 p->token = t;
219 p->field = field;
220 return p;
223 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
225 **tail = p;
226 *tail = &p->next;
227 p->next = NULL;
229 switch (p->token) {
230 case GREP_PATTERN: /* atom */
231 case GREP_PATTERN_HEAD:
232 case GREP_PATTERN_BODY:
233 for (;;) {
234 struct grep_pat *new_pat;
235 size_t len = 0;
236 char *cp = p->pattern + p->patternlen, *nl = NULL;
237 while (++len <= p->patternlen) {
238 if (*(--cp) == '\n') {
239 nl = cp;
240 break;
243 if (!nl)
244 break;
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;
248 if (!p->next)
249 *tail = &new_pat->next;
250 p->next = new_pat;
251 *nl = '\0';
252 p->patternlen -= len;
254 break;
255 default:
256 break;
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));
287 *ret = *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,
296 pat->pattern);
297 else
298 append_grep_pat(ret, pat->pattern, pat->patternlen,
299 pat->origin, pat->no, pat->token);
302 return ret;
305 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
306 const char *error)
308 char where[1024];
310 if (p->no)
311 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
312 else if (p->origin)
313 xsnprintf(where, sizeof(where), "%s, ", p->origin);
314 else
315 where[0] = 0;
317 die("%s'%s': %s", where, p->pattern, error);
320 #ifdef USE_LIBPCRE
321 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
323 const char *error;
324 int erroffset;
325 int options = PCRE_MULTILINE;
327 if (opt->ignore_case)
328 options |= PCRE_CASELESS;
330 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
331 NULL);
332 if (!p->pcre_regexp)
333 compile_regexp_failed(p, error);
335 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
336 if (!p->pcre_extra_info && error)
337 die("%s", error);
340 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
341 regmatch_t *match, int eflags)
343 int ovector[30], ret, flags = 0;
345 if (eflags & REG_NOTBOL)
346 flags |= PCRE_NOTBOL;
348 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
349 0, flags, ovector, ARRAY_SIZE(ovector));
350 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
351 die("pcre_exec failed with error code %d", ret);
352 if (ret > 0) {
353 ret = 0;
354 match->rm_so = ovector[0];
355 match->rm_eo = ovector[1];
358 return ret;
361 static void free_pcre_regexp(struct grep_pat *p)
363 pcre_free(p->pcre_regexp);
364 pcre_free(p->pcre_extra_info);
366 #else /* !USE_LIBPCRE */
367 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
369 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
372 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
373 regmatch_t *match, int eflags)
375 return 1;
378 static void free_pcre_regexp(struct grep_pat *p)
381 #endif /* !USE_LIBPCRE */
383 static int is_fixed(const char *s, size_t len)
385 size_t i;
387 /* regcomp cannot accept patterns with NULs so we
388 * consider any pattern containing a NUL fixed.
390 if (memchr(s, 0, len))
391 return 1;
393 for (i = 0; i < len; i++) {
394 if (is_regex_special(s[i]))
395 return 0;
398 return 1;
401 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
403 struct strbuf sb = STRBUF_INIT;
404 int err;
405 int regflags;
407 basic_regex_quote_buf(&sb, p->pattern);
408 regflags = opt->regflags & ~REG_EXTENDED;
409 if (opt->ignore_case)
410 regflags |= REG_ICASE;
411 err = regcomp(&p->regexp, sb.buf, regflags);
412 if (opt->debug)
413 fprintf(stderr, "fixed %s\n", sb.buf);
414 strbuf_release(&sb);
415 if (err) {
416 char errbuf[1024];
417 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
418 regfree(&p->regexp);
419 compile_regexp_failed(p, errbuf);
423 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
425 int icase, ascii_only;
426 int err;
428 p->word_regexp = opt->word_regexp;
429 p->ignore_case = opt->ignore_case;
430 icase = opt->regflags & REG_ICASE || p->ignore_case;
431 ascii_only = !has_non_ascii(p->pattern);
434 * Even when -F (fixed) asks us to do a non-regexp search, we
435 * may not be able to correctly case-fold when -i
436 * (ignore-case) is asked (in which case, we'll synthesize a
437 * regexp to match the pattern that matches regexp special
438 * characters literally, while ignoring case differences). On
439 * the other hand, even without -F, if the pattern does not
440 * have any regexp special characters and there is no need for
441 * case-folding search, we can internally turn it into a
442 * simple string match using kws. p->fixed tells us if we
443 * want to use kws.
445 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
446 p->fixed = !icase || ascii_only;
447 else
448 p->fixed = 0;
450 if (p->fixed) {
451 if (opt->regflags & REG_ICASE || p->ignore_case)
452 p->kws = kwsalloc(tolower_trans_tbl);
453 else
454 p->kws = kwsalloc(NULL);
455 kwsincr(p->kws, p->pattern, p->patternlen);
456 kwsprep(p->kws);
457 return;
458 } else if (opt->fixed) {
460 * We come here when the pattern has the non-ascii
461 * characters we cannot case-fold, and asked to
462 * ignore-case.
464 compile_fixed_regexp(p, opt);
465 return;
468 if (opt->pcre) {
469 compile_pcre_regexp(p, opt);
470 return;
473 err = regcomp(&p->regexp, p->pattern, opt->regflags);
474 if (err) {
475 char errbuf[1024];
476 regerror(err, &p->regexp, errbuf, 1024);
477 regfree(&p->regexp);
478 compile_regexp_failed(p, errbuf);
482 static struct grep_expr *compile_pattern_or(struct grep_pat **);
483 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
485 struct grep_pat *p;
486 struct grep_expr *x;
488 p = *list;
489 if (!p)
490 return NULL;
491 switch (p->token) {
492 case GREP_PATTERN: /* atom */
493 case GREP_PATTERN_HEAD:
494 case GREP_PATTERN_BODY:
495 x = xcalloc(1, sizeof (struct grep_expr));
496 x->node = GREP_NODE_ATOM;
497 x->u.atom = p;
498 *list = p->next;
499 return x;
500 case GREP_OPEN_PAREN:
501 *list = p->next;
502 x = compile_pattern_or(list);
503 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
504 die("unmatched parenthesis");
505 *list = (*list)->next;
506 return x;
507 default:
508 return NULL;
512 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
514 struct grep_pat *p;
515 struct grep_expr *x;
517 p = *list;
518 if (!p)
519 return NULL;
520 switch (p->token) {
521 case GREP_NOT:
522 if (!p->next)
523 die("--not not followed by pattern expression");
524 *list = p->next;
525 x = xcalloc(1, sizeof (struct grep_expr));
526 x->node = GREP_NODE_NOT;
527 x->u.unary = compile_pattern_not(list);
528 if (!x->u.unary)
529 die("--not followed by non pattern expression");
530 return x;
531 default:
532 return compile_pattern_atom(list);
536 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
538 struct grep_pat *p;
539 struct grep_expr *x, *y, *z;
541 x = compile_pattern_not(list);
542 p = *list;
543 if (p && p->token == GREP_AND) {
544 if (!p->next)
545 die("--and not followed by pattern expression");
546 *list = p->next;
547 y = compile_pattern_and(list);
548 if (!y)
549 die("--and not followed by pattern expression");
550 z = xcalloc(1, sizeof (struct grep_expr));
551 z->node = GREP_NODE_AND;
552 z->u.binary.left = x;
553 z->u.binary.right = y;
554 return z;
556 return x;
559 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
561 struct grep_pat *p;
562 struct grep_expr *x, *y, *z;
564 x = compile_pattern_and(list);
565 p = *list;
566 if (x && p && p->token != GREP_CLOSE_PAREN) {
567 y = compile_pattern_or(list);
568 if (!y)
569 die("not a pattern expression %s", p->pattern);
570 z = xcalloc(1, sizeof (struct grep_expr));
571 z->node = GREP_NODE_OR;
572 z->u.binary.left = x;
573 z->u.binary.right = y;
574 return z;
576 return x;
579 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
581 return compile_pattern_or(list);
584 static void indent(int in)
586 while (in-- > 0)
587 fputc(' ', stderr);
590 static void dump_grep_pat(struct grep_pat *p)
592 switch (p->token) {
593 case GREP_AND: fprintf(stderr, "*and*"); break;
594 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
595 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
596 case GREP_NOT: fprintf(stderr, "*not*"); break;
597 case GREP_OR: fprintf(stderr, "*or*"); break;
599 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
600 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
601 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
604 switch (p->token) {
605 default: break;
606 case GREP_PATTERN_HEAD:
607 fprintf(stderr, "<head %d>", p->field); break;
608 case GREP_PATTERN_BODY:
609 fprintf(stderr, "<body>"); break;
611 switch (p->token) {
612 default: break;
613 case GREP_PATTERN_HEAD:
614 case GREP_PATTERN_BODY:
615 case GREP_PATTERN:
616 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
617 break;
619 fputc('\n', stderr);
622 static void dump_grep_expression_1(struct grep_expr *x, int in)
624 indent(in);
625 switch (x->node) {
626 case GREP_NODE_TRUE:
627 fprintf(stderr, "true\n");
628 break;
629 case GREP_NODE_ATOM:
630 dump_grep_pat(x->u.atom);
631 break;
632 case GREP_NODE_NOT:
633 fprintf(stderr, "(not\n");
634 dump_grep_expression_1(x->u.unary, in+1);
635 indent(in);
636 fprintf(stderr, ")\n");
637 break;
638 case GREP_NODE_AND:
639 fprintf(stderr, "(and\n");
640 dump_grep_expression_1(x->u.binary.left, in+1);
641 dump_grep_expression_1(x->u.binary.right, in+1);
642 indent(in);
643 fprintf(stderr, ")\n");
644 break;
645 case GREP_NODE_OR:
646 fprintf(stderr, "(or\n");
647 dump_grep_expression_1(x->u.binary.left, in+1);
648 dump_grep_expression_1(x->u.binary.right, in+1);
649 indent(in);
650 fprintf(stderr, ")\n");
651 break;
655 static void dump_grep_expression(struct grep_opt *opt)
657 struct grep_expr *x = opt->pattern_expression;
659 if (opt->all_match)
660 fprintf(stderr, "[all-match]\n");
661 dump_grep_expression_1(x, 0);
662 fflush(NULL);
665 static struct grep_expr *grep_true_expr(void)
667 struct grep_expr *z = xcalloc(1, sizeof(*z));
668 z->node = GREP_NODE_TRUE;
669 return z;
672 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
674 struct grep_expr *z = xcalloc(1, sizeof(*z));
675 z->node = GREP_NODE_OR;
676 z->u.binary.left = left;
677 z->u.binary.right = right;
678 return z;
681 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
683 struct grep_pat *p;
684 struct grep_expr *header_expr;
685 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
686 enum grep_header_field fld;
688 if (!opt->header_list)
689 return NULL;
691 for (p = opt->header_list; p; p = p->next) {
692 if (p->token != GREP_PATTERN_HEAD)
693 die("bug: a non-header pattern in grep header list.");
694 if (p->field < GREP_HEADER_FIELD_MIN ||
695 GREP_HEADER_FIELD_MAX <= p->field)
696 die("bug: unknown header field %d", p->field);
697 compile_regexp(p, opt);
700 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
701 header_group[fld] = NULL;
703 for (p = opt->header_list; p; p = p->next) {
704 struct grep_expr *h;
705 struct grep_pat *pp = p;
707 h = compile_pattern_atom(&pp);
708 if (!h || pp != p->next)
709 die("bug: malformed header expr");
710 if (!header_group[p->field]) {
711 header_group[p->field] = h;
712 continue;
714 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
717 header_expr = NULL;
719 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
720 if (!header_group[fld])
721 continue;
722 if (!header_expr)
723 header_expr = grep_true_expr();
724 header_expr = grep_or_expr(header_group[fld], header_expr);
726 return header_expr;
729 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
731 struct grep_expr *z = x;
733 while (x) {
734 assert(x->node == GREP_NODE_OR);
735 if (x->u.binary.right &&
736 x->u.binary.right->node == GREP_NODE_TRUE) {
737 x->u.binary.right = y;
738 break;
740 x = x->u.binary.right;
742 return z;
745 static void compile_grep_patterns_real(struct grep_opt *opt)
747 struct grep_pat *p;
748 struct grep_expr *header_expr = prep_header_patterns(opt);
750 for (p = opt->pattern_list; p; p = p->next) {
751 switch (p->token) {
752 case GREP_PATTERN: /* atom */
753 case GREP_PATTERN_HEAD:
754 case GREP_PATTERN_BODY:
755 compile_regexp(p, opt);
756 break;
757 default:
758 opt->extended = 1;
759 break;
763 if (opt->all_match || header_expr)
764 opt->extended = 1;
765 else if (!opt->extended && !opt->debug)
766 return;
768 p = opt->pattern_list;
769 if (p)
770 opt->pattern_expression = compile_pattern_expr(&p);
771 if (p)
772 die("incomplete pattern expression: %s", p->pattern);
774 if (!header_expr)
775 return;
777 if (!opt->pattern_expression)
778 opt->pattern_expression = header_expr;
779 else if (opt->all_match)
780 opt->pattern_expression = grep_splice_or(header_expr,
781 opt->pattern_expression);
782 else
783 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
784 header_expr);
785 opt->all_match = 1;
788 void compile_grep_patterns(struct grep_opt *opt)
790 compile_grep_patterns_real(opt);
791 if (opt->debug)
792 dump_grep_expression(opt);
795 static void free_pattern_expr(struct grep_expr *x)
797 switch (x->node) {
798 case GREP_NODE_TRUE:
799 case GREP_NODE_ATOM:
800 break;
801 case GREP_NODE_NOT:
802 free_pattern_expr(x->u.unary);
803 break;
804 case GREP_NODE_AND:
805 case GREP_NODE_OR:
806 free_pattern_expr(x->u.binary.left);
807 free_pattern_expr(x->u.binary.right);
808 break;
810 free(x);
813 void free_grep_patterns(struct grep_opt *opt)
815 struct grep_pat *p, *n;
817 for (p = opt->pattern_list; p; p = n) {
818 n = p->next;
819 switch (p->token) {
820 case GREP_PATTERN: /* atom */
821 case GREP_PATTERN_HEAD:
822 case GREP_PATTERN_BODY:
823 if (p->kws)
824 kwsfree(p->kws);
825 else if (p->pcre_regexp)
826 free_pcre_regexp(p);
827 else
828 regfree(&p->regexp);
829 free(p->pattern);
830 break;
831 default:
832 break;
834 free(p);
837 if (!opt->extended)
838 return;
839 free_pattern_expr(opt->pattern_expression);
842 static char *end_of_line(char *cp, unsigned long *left)
844 unsigned long l = *left;
845 while (l && *cp != '\n') {
846 l--;
847 cp++;
849 *left = l;
850 return cp;
853 static int word_char(char ch)
855 return isalnum(ch) || ch == '_';
858 static void output_color(struct grep_opt *opt, const void *data, size_t size,
859 const char *color)
861 if (want_color(opt->color) && color && color[0]) {
862 opt->output(opt, color, strlen(color));
863 opt->output(opt, data, size);
864 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
865 } else
866 opt->output(opt, data, size);
869 static void output_sep(struct grep_opt *opt, char sign)
871 if (opt->null_following_name)
872 opt->output(opt, "\0", 1);
873 else
874 output_color(opt, &sign, 1, opt->color_sep);
877 static void show_name(struct grep_opt *opt, const char *name)
879 output_color(opt, name, strlen(name), opt->color_filename);
880 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
883 static int fixmatch(struct grep_pat *p, char *line, char *eol,
884 regmatch_t *match)
886 struct kwsmatch kwsm;
887 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
888 if (offset == -1) {
889 match->rm_so = match->rm_eo = -1;
890 return REG_NOMATCH;
891 } else {
892 match->rm_so = offset;
893 match->rm_eo = match->rm_so + kwsm.size[0];
894 return 0;
898 static int regmatch(const regex_t *preg, char *line, char *eol,
899 regmatch_t *match, int eflags)
901 #ifdef REG_STARTEND
902 match->rm_so = 0;
903 match->rm_eo = eol - line;
904 eflags |= REG_STARTEND;
905 #endif
906 return regexec(preg, line, 1, match, eflags);
909 static int patmatch(struct grep_pat *p, char *line, char *eol,
910 regmatch_t *match, int eflags)
912 int hit;
914 if (p->fixed)
915 hit = !fixmatch(p, line, eol, match);
916 else if (p->pcre_regexp)
917 hit = !pcrematch(p, line, eol, match, eflags);
918 else
919 hit = !regmatch(&p->regexp, line, eol, match, 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 snprintf(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 void std_output(struct grep_opt *opt, const void *buf, size_t size)
1391 fwrite(buf, size, 1, stdout);
1394 static int fill_textconv_grep(struct userdiff_driver *driver,
1395 struct grep_source *gs)
1397 struct diff_filespec *df;
1398 char *buf;
1399 size_t size;
1401 if (!driver || !driver->textconv)
1402 return grep_source_load(gs);
1405 * The textconv interface is intimately tied to diff_filespecs, so we
1406 * have to pretend to be one. If we could unify the grep_source
1407 * and diff_filespec structs, this mess could just go away.
1409 df = alloc_filespec(gs->path);
1410 switch (gs->type) {
1411 case GREP_SOURCE_SHA1:
1412 fill_filespec(df, gs->identifier, 1, 0100644);
1413 break;
1414 case GREP_SOURCE_FILE:
1415 fill_filespec(df, null_sha1, 0, 0100644);
1416 break;
1417 default:
1418 die("BUG: attempt to textconv something without a path?");
1422 * fill_textconv is not remotely thread-safe; it may load objects
1423 * behind the scenes, and it modifies the global diff tempfile
1424 * structure.
1426 grep_read_lock();
1427 size = fill_textconv(driver, df, &buf);
1428 grep_read_unlock();
1429 free_filespec(df);
1432 * The normal fill_textconv usage by the diff machinery would just keep
1433 * the textconv'd buf separate from the diff_filespec. But much of the
1434 * grep code passes around a grep_source and assumes that its "buf"
1435 * pointer is the beginning of the thing we are searching. So let's
1436 * install our textconv'd version into the grep_source, taking care not
1437 * to leak any existing buffer.
1439 grep_source_clear_data(gs);
1440 gs->buf = buf;
1441 gs->size = size;
1443 return 0;
1446 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1448 char *bol;
1449 unsigned long left;
1450 unsigned lno = 1;
1451 unsigned last_hit = 0;
1452 int binary_match_only = 0;
1453 unsigned count = 0;
1454 int try_lookahead = 0;
1455 int show_function = 0;
1456 struct userdiff_driver *textconv = NULL;
1457 enum grep_context ctx = GREP_CONTEXT_HEAD;
1458 xdemitconf_t xecfg;
1460 if (!opt->output)
1461 opt->output = std_output;
1463 if (opt->pre_context || opt->post_context || opt->file_break ||
1464 opt->funcbody) {
1465 /* Show hunk marks, except for the first file. */
1466 if (opt->last_shown)
1467 opt->show_hunk_mark = 1;
1469 * If we're using threads then we can't easily identify
1470 * the first file. Always put hunk marks in that case
1471 * and skip the very first one later in work_done().
1473 if (opt->output != std_output)
1474 opt->show_hunk_mark = 1;
1476 opt->last_shown = 0;
1478 if (opt->allow_textconv) {
1479 grep_source_load_driver(gs);
1481 * We might set up the shared textconv cache data here, which
1482 * is not thread-safe.
1484 grep_attr_lock();
1485 textconv = userdiff_get_textconv(gs->driver);
1486 grep_attr_unlock();
1490 * We know the result of a textconv is text, so we only have to care
1491 * about binary handling if we are not using it.
1493 if (!textconv) {
1494 switch (opt->binary) {
1495 case GREP_BINARY_DEFAULT:
1496 if (grep_source_is_binary(gs))
1497 binary_match_only = 1;
1498 break;
1499 case GREP_BINARY_NOMATCH:
1500 if (grep_source_is_binary(gs))
1501 return 0; /* Assume unmatch */
1502 break;
1503 case GREP_BINARY_TEXT:
1504 break;
1505 default:
1506 die("bug: unknown binary handling mode");
1510 memset(&xecfg, 0, sizeof(xecfg));
1511 opt->priv = &xecfg;
1513 try_lookahead = should_lookahead(opt);
1515 if (fill_textconv_grep(textconv, gs) < 0)
1516 return 0;
1518 bol = gs->buf;
1519 left = gs->size;
1520 while (left) {
1521 char *eol, ch;
1522 int hit;
1525 * look_ahead() skips quickly to the line that possibly
1526 * has the next hit; don't call it if we need to do
1527 * something more than just skipping the current line
1528 * in response to an unmatch for the current line. E.g.
1529 * inside a post-context window, we will show the current
1530 * line as a context around the previous hit when it
1531 * doesn't hit.
1533 if (try_lookahead
1534 && !(last_hit
1535 && (show_function ||
1536 lno <= last_hit + opt->post_context))
1537 && look_ahead(opt, &left, &lno, &bol))
1538 break;
1539 eol = end_of_line(bol, &left);
1540 ch = *eol;
1541 *eol = 0;
1543 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1544 ctx = GREP_CONTEXT_BODY;
1546 hit = match_line(opt, bol, eol, ctx, collect_hits);
1547 *eol = ch;
1549 if (collect_hits)
1550 goto next_line;
1552 /* "grep -v -e foo -e bla" should list lines
1553 * that do not have either, so inversion should
1554 * be done outside.
1556 if (opt->invert)
1557 hit = !hit;
1558 if (opt->unmatch_name_only) {
1559 if (hit)
1560 return 0;
1561 goto next_line;
1563 if (hit) {
1564 count++;
1565 if (opt->status_only)
1566 return 1;
1567 if (opt->name_only) {
1568 show_name(opt, gs->name);
1569 return 1;
1571 if (opt->count)
1572 goto next_line;
1573 if (binary_match_only) {
1574 opt->output(opt, "Binary file ", 12);
1575 output_color(opt, gs->name, strlen(gs->name),
1576 opt->color_filename);
1577 opt->output(opt, " matches\n", 9);
1578 return 1;
1580 /* Hit at this line. If we haven't shown the
1581 * pre-context lines, we would need to show them.
1583 if (opt->pre_context || opt->funcbody)
1584 show_pre_context(opt, gs, bol, eol, lno);
1585 else if (opt->funcname)
1586 show_funcname_line(opt, gs, bol, lno);
1587 show_line(opt, bol, eol, gs->name, lno, ':');
1588 last_hit = lno;
1589 if (opt->funcbody)
1590 show_function = 1;
1591 goto next_line;
1593 if (show_function && match_funcname(opt, gs, bol, eol))
1594 show_function = 0;
1595 if (show_function ||
1596 (last_hit && lno <= last_hit + opt->post_context)) {
1597 /* If the last hit is within the post context,
1598 * we need to show this line.
1600 show_line(opt, bol, eol, gs->name, lno, '-');
1603 next_line:
1604 bol = eol + 1;
1605 if (!left)
1606 break;
1607 left--;
1608 lno++;
1611 if (collect_hits)
1612 return 0;
1614 if (opt->status_only)
1615 return 0;
1616 if (opt->unmatch_name_only) {
1617 /* We did not see any hit, so we want to show this */
1618 show_name(opt, gs->name);
1619 return 1;
1622 xdiff_clear_find_func(&xecfg);
1623 opt->priv = NULL;
1625 /* NEEDSWORK:
1626 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1627 * which feels mostly useless but sometimes useful. Maybe
1628 * make it another option? For now suppress them.
1630 if (opt->count && count) {
1631 char buf[32];
1632 if (opt->pathname) {
1633 output_color(opt, gs->name, strlen(gs->name),
1634 opt->color_filename);
1635 output_sep(opt, ':');
1637 snprintf(buf, sizeof(buf), "%u\n", count);
1638 opt->output(opt, buf, strlen(buf));
1639 return 1;
1641 return !!last_hit;
1644 static void clr_hit_marker(struct grep_expr *x)
1646 /* All-hit markers are meaningful only at the very top level
1647 * OR node.
1649 while (1) {
1650 x->hit = 0;
1651 if (x->node != GREP_NODE_OR)
1652 return;
1653 x->u.binary.left->hit = 0;
1654 x = x->u.binary.right;
1658 static int chk_hit_marker(struct grep_expr *x)
1660 /* Top level nodes have hit markers. See if they all are hits */
1661 while (1) {
1662 if (x->node != GREP_NODE_OR)
1663 return x->hit;
1664 if (!x->u.binary.left->hit)
1665 return 0;
1666 x = x->u.binary.right;
1670 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1673 * we do not have to do the two-pass grep when we do not check
1674 * buffer-wide "all-match".
1676 if (!opt->all_match)
1677 return grep_source_1(opt, gs, 0);
1679 /* Otherwise the toplevel "or" terms hit a bit differently.
1680 * We first clear hit markers from them.
1682 clr_hit_marker(opt->pattern_expression);
1683 grep_source_1(opt, gs, 1);
1685 if (!chk_hit_marker(opt->pattern_expression))
1686 return 0;
1688 return grep_source_1(opt, gs, 0);
1691 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1693 struct grep_source gs;
1694 int r;
1696 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1697 gs.buf = buf;
1698 gs.size = size;
1700 r = grep_source(opt, &gs);
1702 grep_source_clear(&gs);
1703 return r;
1706 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1707 const char *name, const char *path,
1708 const void *identifier)
1710 gs->type = type;
1711 gs->name = xstrdup_or_null(name);
1712 gs->path = xstrdup_or_null(path);
1713 gs->buf = NULL;
1714 gs->size = 0;
1715 gs->driver = NULL;
1717 switch (type) {
1718 case GREP_SOURCE_FILE:
1719 gs->identifier = xstrdup(identifier);
1720 break;
1721 case GREP_SOURCE_SHA1:
1722 gs->identifier = xmalloc(20);
1723 hashcpy(gs->identifier, identifier);
1724 break;
1725 case GREP_SOURCE_BUF:
1726 gs->identifier = NULL;
1730 void grep_source_clear(struct grep_source *gs)
1732 free(gs->name);
1733 gs->name = NULL;
1734 free(gs->path);
1735 gs->path = NULL;
1736 free(gs->identifier);
1737 gs->identifier = NULL;
1738 grep_source_clear_data(gs);
1741 void grep_source_clear_data(struct grep_source *gs)
1743 switch (gs->type) {
1744 case GREP_SOURCE_FILE:
1745 case GREP_SOURCE_SHA1:
1746 free(gs->buf);
1747 gs->buf = NULL;
1748 gs->size = 0;
1749 break;
1750 case GREP_SOURCE_BUF:
1751 /* leave user-provided buf intact */
1752 break;
1756 static int grep_source_load_sha1(struct grep_source *gs)
1758 enum object_type type;
1760 grep_read_lock();
1761 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1762 grep_read_unlock();
1764 if (!gs->buf)
1765 return error(_("'%s': unable to read %s"),
1766 gs->name,
1767 sha1_to_hex(gs->identifier));
1768 return 0;
1771 static int grep_source_load_file(struct grep_source *gs)
1773 const char *filename = gs->identifier;
1774 struct stat st;
1775 char *data;
1776 size_t size;
1777 int i;
1779 if (lstat(filename, &st) < 0) {
1780 err_ret:
1781 if (errno != ENOENT)
1782 error(_("'%s': %s"), filename, strerror(errno));
1783 return -1;
1785 if (!S_ISREG(st.st_mode))
1786 return -1;
1787 size = xsize_t(st.st_size);
1788 i = open(filename, O_RDONLY);
1789 if (i < 0)
1790 goto err_ret;
1791 data = xmalloc(size + 1);
1792 if (st.st_size != read_in_full(i, data, size)) {
1793 error(_("'%s': short read %s"), filename, strerror(errno));
1794 close(i);
1795 free(data);
1796 return -1;
1798 close(i);
1799 data[size] = 0;
1801 gs->buf = data;
1802 gs->size = size;
1803 return 0;
1806 static int grep_source_load(struct grep_source *gs)
1808 if (gs->buf)
1809 return 0;
1811 switch (gs->type) {
1812 case GREP_SOURCE_FILE:
1813 return grep_source_load_file(gs);
1814 case GREP_SOURCE_SHA1:
1815 return grep_source_load_sha1(gs);
1816 case GREP_SOURCE_BUF:
1817 return gs->buf ? 0 : -1;
1819 die("BUG: invalid grep_source type");
1822 void grep_source_load_driver(struct grep_source *gs)
1824 if (gs->driver)
1825 return;
1827 grep_attr_lock();
1828 if (gs->path)
1829 gs->driver = userdiff_find_by_path(gs->path);
1830 if (!gs->driver)
1831 gs->driver = userdiff_find_by_name("default");
1832 grep_attr_unlock();
1835 static int grep_source_is_binary(struct grep_source *gs)
1837 grep_source_load_driver(gs);
1838 if (gs->driver->binary != -1)
1839 return gs->driver->binary;
1841 if (!grep_source_load(gs))
1842 return buffer_is_binary(gs->buf, gs->size);
1844 return 0;