grep/pcre: prepare locale-dependent tables for icase matching
[git/raj.git] / grep.c
blobaf920c45425cddc2778cdf627c28adf6e7138fb7
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 if (has_non_ascii(p->pattern))
329 p->pcre_tables = pcre_maketables();
330 options |= PCRE_CASELESS;
333 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
334 p->pcre_tables);
335 if (!p->pcre_regexp)
336 compile_regexp_failed(p, error);
338 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
339 if (!p->pcre_extra_info && error)
340 die("%s", error);
343 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
344 regmatch_t *match, int eflags)
346 int ovector[30], ret, flags = 0;
348 if (eflags & REG_NOTBOL)
349 flags |= PCRE_NOTBOL;
351 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
352 0, flags, ovector, ARRAY_SIZE(ovector));
353 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
354 die("pcre_exec failed with error code %d", ret);
355 if (ret > 0) {
356 ret = 0;
357 match->rm_so = ovector[0];
358 match->rm_eo = ovector[1];
361 return ret;
364 static void free_pcre_regexp(struct grep_pat *p)
366 pcre_free(p->pcre_regexp);
367 pcre_free(p->pcre_extra_info);
368 pcre_free((void *)p->pcre_tables);
370 #else /* !USE_LIBPCRE */
371 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
373 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
376 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
377 regmatch_t *match, int eflags)
379 return 1;
382 static void free_pcre_regexp(struct grep_pat *p)
385 #endif /* !USE_LIBPCRE */
387 static int is_fixed(const char *s, size_t len)
389 size_t i;
391 /* regcomp cannot accept patterns with NULs so we
392 * consider any pattern containing a NUL fixed.
394 if (memchr(s, 0, len))
395 return 1;
397 for (i = 0; i < len; i++) {
398 if (is_regex_special(s[i]))
399 return 0;
402 return 1;
405 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
407 struct strbuf sb = STRBUF_INIT;
408 int err;
409 int regflags;
411 basic_regex_quote_buf(&sb, p->pattern);
412 regflags = opt->regflags & ~REG_EXTENDED;
413 if (opt->ignore_case)
414 regflags |= REG_ICASE;
415 err = regcomp(&p->regexp, sb.buf, regflags);
416 if (opt->debug)
417 fprintf(stderr, "fixed %s\n", sb.buf);
418 strbuf_release(&sb);
419 if (err) {
420 char errbuf[1024];
421 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
422 regfree(&p->regexp);
423 compile_regexp_failed(p, errbuf);
427 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
429 int icase, ascii_only;
430 int err;
432 p->word_regexp = opt->word_regexp;
433 p->ignore_case = opt->ignore_case;
434 icase = opt->regflags & REG_ICASE || p->ignore_case;
435 ascii_only = !has_non_ascii(p->pattern);
438 * Even when -F (fixed) asks us to do a non-regexp search, we
439 * may not be able to correctly case-fold when -i
440 * (ignore-case) is asked (in which case, we'll synthesize a
441 * regexp to match the pattern that matches regexp special
442 * characters literally, while ignoring case differences). On
443 * the other hand, even without -F, if the pattern does not
444 * have any regexp special characters and there is no need for
445 * case-folding search, we can internally turn it into a
446 * simple string match using kws. p->fixed tells us if we
447 * want to use kws.
449 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
450 p->fixed = !icase || ascii_only;
451 else
452 p->fixed = 0;
454 if (p->fixed) {
455 if (opt->regflags & REG_ICASE || p->ignore_case)
456 p->kws = kwsalloc(tolower_trans_tbl);
457 else
458 p->kws = kwsalloc(NULL);
459 kwsincr(p->kws, p->pattern, p->patternlen);
460 kwsprep(p->kws);
461 return;
462 } else if (opt->fixed) {
464 * We come here when the pattern has the non-ascii
465 * characters we cannot case-fold, and asked to
466 * ignore-case.
468 compile_fixed_regexp(p, opt);
469 return;
472 if (opt->pcre) {
473 compile_pcre_regexp(p, opt);
474 return;
477 err = regcomp(&p->regexp, p->pattern, opt->regflags);
478 if (err) {
479 char errbuf[1024];
480 regerror(err, &p->regexp, errbuf, 1024);
481 regfree(&p->regexp);
482 compile_regexp_failed(p, errbuf);
486 static struct grep_expr *compile_pattern_or(struct grep_pat **);
487 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
489 struct grep_pat *p;
490 struct grep_expr *x;
492 p = *list;
493 if (!p)
494 return NULL;
495 switch (p->token) {
496 case GREP_PATTERN: /* atom */
497 case GREP_PATTERN_HEAD:
498 case GREP_PATTERN_BODY:
499 x = xcalloc(1, sizeof (struct grep_expr));
500 x->node = GREP_NODE_ATOM;
501 x->u.atom = p;
502 *list = p->next;
503 return x;
504 case GREP_OPEN_PAREN:
505 *list = p->next;
506 x = compile_pattern_or(list);
507 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
508 die("unmatched parenthesis");
509 *list = (*list)->next;
510 return x;
511 default:
512 return NULL;
516 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
518 struct grep_pat *p;
519 struct grep_expr *x;
521 p = *list;
522 if (!p)
523 return NULL;
524 switch (p->token) {
525 case GREP_NOT:
526 if (!p->next)
527 die("--not not followed by pattern expression");
528 *list = p->next;
529 x = xcalloc(1, sizeof (struct grep_expr));
530 x->node = GREP_NODE_NOT;
531 x->u.unary = compile_pattern_not(list);
532 if (!x->u.unary)
533 die("--not followed by non pattern expression");
534 return x;
535 default:
536 return compile_pattern_atom(list);
540 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
542 struct grep_pat *p;
543 struct grep_expr *x, *y, *z;
545 x = compile_pattern_not(list);
546 p = *list;
547 if (p && p->token == GREP_AND) {
548 if (!p->next)
549 die("--and not followed by pattern expression");
550 *list = p->next;
551 y = compile_pattern_and(list);
552 if (!y)
553 die("--and not followed by pattern expression");
554 z = xcalloc(1, sizeof (struct grep_expr));
555 z->node = GREP_NODE_AND;
556 z->u.binary.left = x;
557 z->u.binary.right = y;
558 return z;
560 return x;
563 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
565 struct grep_pat *p;
566 struct grep_expr *x, *y, *z;
568 x = compile_pattern_and(list);
569 p = *list;
570 if (x && p && p->token != GREP_CLOSE_PAREN) {
571 y = compile_pattern_or(list);
572 if (!y)
573 die("not a pattern expression %s", p->pattern);
574 z = xcalloc(1, sizeof (struct grep_expr));
575 z->node = GREP_NODE_OR;
576 z->u.binary.left = x;
577 z->u.binary.right = y;
578 return z;
580 return x;
583 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
585 return compile_pattern_or(list);
588 static void indent(int in)
590 while (in-- > 0)
591 fputc(' ', stderr);
594 static void dump_grep_pat(struct grep_pat *p)
596 switch (p->token) {
597 case GREP_AND: fprintf(stderr, "*and*"); break;
598 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
599 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
600 case GREP_NOT: fprintf(stderr, "*not*"); break;
601 case GREP_OR: fprintf(stderr, "*or*"); break;
603 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
604 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
605 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
608 switch (p->token) {
609 default: break;
610 case GREP_PATTERN_HEAD:
611 fprintf(stderr, "<head %d>", p->field); break;
612 case GREP_PATTERN_BODY:
613 fprintf(stderr, "<body>"); break;
615 switch (p->token) {
616 default: break;
617 case GREP_PATTERN_HEAD:
618 case GREP_PATTERN_BODY:
619 case GREP_PATTERN:
620 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
621 break;
623 fputc('\n', stderr);
626 static void dump_grep_expression_1(struct grep_expr *x, int in)
628 indent(in);
629 switch (x->node) {
630 case GREP_NODE_TRUE:
631 fprintf(stderr, "true\n");
632 break;
633 case GREP_NODE_ATOM:
634 dump_grep_pat(x->u.atom);
635 break;
636 case GREP_NODE_NOT:
637 fprintf(stderr, "(not\n");
638 dump_grep_expression_1(x->u.unary, in+1);
639 indent(in);
640 fprintf(stderr, ")\n");
641 break;
642 case GREP_NODE_AND:
643 fprintf(stderr, "(and\n");
644 dump_grep_expression_1(x->u.binary.left, in+1);
645 dump_grep_expression_1(x->u.binary.right, in+1);
646 indent(in);
647 fprintf(stderr, ")\n");
648 break;
649 case GREP_NODE_OR:
650 fprintf(stderr, "(or\n");
651 dump_grep_expression_1(x->u.binary.left, in+1);
652 dump_grep_expression_1(x->u.binary.right, in+1);
653 indent(in);
654 fprintf(stderr, ")\n");
655 break;
659 static void dump_grep_expression(struct grep_opt *opt)
661 struct grep_expr *x = opt->pattern_expression;
663 if (opt->all_match)
664 fprintf(stderr, "[all-match]\n");
665 dump_grep_expression_1(x, 0);
666 fflush(NULL);
669 static struct grep_expr *grep_true_expr(void)
671 struct grep_expr *z = xcalloc(1, sizeof(*z));
672 z->node = GREP_NODE_TRUE;
673 return z;
676 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
678 struct grep_expr *z = xcalloc(1, sizeof(*z));
679 z->node = GREP_NODE_OR;
680 z->u.binary.left = left;
681 z->u.binary.right = right;
682 return z;
685 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
687 struct grep_pat *p;
688 struct grep_expr *header_expr;
689 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
690 enum grep_header_field fld;
692 if (!opt->header_list)
693 return NULL;
695 for (p = opt->header_list; p; p = p->next) {
696 if (p->token != GREP_PATTERN_HEAD)
697 die("bug: a non-header pattern in grep header list.");
698 if (p->field < GREP_HEADER_FIELD_MIN ||
699 GREP_HEADER_FIELD_MAX <= p->field)
700 die("bug: unknown header field %d", p->field);
701 compile_regexp(p, opt);
704 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
705 header_group[fld] = NULL;
707 for (p = opt->header_list; p; p = p->next) {
708 struct grep_expr *h;
709 struct grep_pat *pp = p;
711 h = compile_pattern_atom(&pp);
712 if (!h || pp != p->next)
713 die("bug: malformed header expr");
714 if (!header_group[p->field]) {
715 header_group[p->field] = h;
716 continue;
718 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
721 header_expr = NULL;
723 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
724 if (!header_group[fld])
725 continue;
726 if (!header_expr)
727 header_expr = grep_true_expr();
728 header_expr = grep_or_expr(header_group[fld], header_expr);
730 return header_expr;
733 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
735 struct grep_expr *z = x;
737 while (x) {
738 assert(x->node == GREP_NODE_OR);
739 if (x->u.binary.right &&
740 x->u.binary.right->node == GREP_NODE_TRUE) {
741 x->u.binary.right = y;
742 break;
744 x = x->u.binary.right;
746 return z;
749 static void compile_grep_patterns_real(struct grep_opt *opt)
751 struct grep_pat *p;
752 struct grep_expr *header_expr = prep_header_patterns(opt);
754 for (p = opt->pattern_list; p; p = p->next) {
755 switch (p->token) {
756 case GREP_PATTERN: /* atom */
757 case GREP_PATTERN_HEAD:
758 case GREP_PATTERN_BODY:
759 compile_regexp(p, opt);
760 break;
761 default:
762 opt->extended = 1;
763 break;
767 if (opt->all_match || header_expr)
768 opt->extended = 1;
769 else if (!opt->extended && !opt->debug)
770 return;
772 p = opt->pattern_list;
773 if (p)
774 opt->pattern_expression = compile_pattern_expr(&p);
775 if (p)
776 die("incomplete pattern expression: %s", p->pattern);
778 if (!header_expr)
779 return;
781 if (!opt->pattern_expression)
782 opt->pattern_expression = header_expr;
783 else if (opt->all_match)
784 opt->pattern_expression = grep_splice_or(header_expr,
785 opt->pattern_expression);
786 else
787 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
788 header_expr);
789 opt->all_match = 1;
792 void compile_grep_patterns(struct grep_opt *opt)
794 compile_grep_patterns_real(opt);
795 if (opt->debug)
796 dump_grep_expression(opt);
799 static void free_pattern_expr(struct grep_expr *x)
801 switch (x->node) {
802 case GREP_NODE_TRUE:
803 case GREP_NODE_ATOM:
804 break;
805 case GREP_NODE_NOT:
806 free_pattern_expr(x->u.unary);
807 break;
808 case GREP_NODE_AND:
809 case GREP_NODE_OR:
810 free_pattern_expr(x->u.binary.left);
811 free_pattern_expr(x->u.binary.right);
812 break;
814 free(x);
817 void free_grep_patterns(struct grep_opt *opt)
819 struct grep_pat *p, *n;
821 for (p = opt->pattern_list; p; p = n) {
822 n = p->next;
823 switch (p->token) {
824 case GREP_PATTERN: /* atom */
825 case GREP_PATTERN_HEAD:
826 case GREP_PATTERN_BODY:
827 if (p->kws)
828 kwsfree(p->kws);
829 else if (p->pcre_regexp)
830 free_pcre_regexp(p);
831 else
832 regfree(&p->regexp);
833 free(p->pattern);
834 break;
835 default:
836 break;
838 free(p);
841 if (!opt->extended)
842 return;
843 free_pattern_expr(opt->pattern_expression);
846 static char *end_of_line(char *cp, unsigned long *left)
848 unsigned long l = *left;
849 while (l && *cp != '\n') {
850 l--;
851 cp++;
853 *left = l;
854 return cp;
857 static int word_char(char ch)
859 return isalnum(ch) || ch == '_';
862 static void output_color(struct grep_opt *opt, const void *data, size_t size,
863 const char *color)
865 if (want_color(opt->color) && color && color[0]) {
866 opt->output(opt, color, strlen(color));
867 opt->output(opt, data, size);
868 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
869 } else
870 opt->output(opt, data, size);
873 static void output_sep(struct grep_opt *opt, char sign)
875 if (opt->null_following_name)
876 opt->output(opt, "\0", 1);
877 else
878 output_color(opt, &sign, 1, opt->color_sep);
881 static void show_name(struct grep_opt *opt, const char *name)
883 output_color(opt, name, strlen(name), opt->color_filename);
884 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
887 static int fixmatch(struct grep_pat *p, char *line, char *eol,
888 regmatch_t *match)
890 struct kwsmatch kwsm;
891 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
892 if (offset == -1) {
893 match->rm_so = match->rm_eo = -1;
894 return REG_NOMATCH;
895 } else {
896 match->rm_so = offset;
897 match->rm_eo = match->rm_so + kwsm.size[0];
898 return 0;
902 static int regmatch(const regex_t *preg, char *line, char *eol,
903 regmatch_t *match, int eflags)
905 #ifdef REG_STARTEND
906 match->rm_so = 0;
907 match->rm_eo = eol - line;
908 eflags |= REG_STARTEND;
909 #endif
910 return regexec(preg, line, 1, match, eflags);
913 static int patmatch(struct grep_pat *p, char *line, char *eol,
914 regmatch_t *match, int eflags)
916 int hit;
918 if (p->fixed)
919 hit = !fixmatch(p, line, eol, match);
920 else if (p->pcre_regexp)
921 hit = !pcrematch(p, line, eol, match, eflags);
922 else
923 hit = !regmatch(&p->regexp, line, eol, match, eflags);
925 return hit;
928 static int strip_timestamp(char *bol, char **eol_p)
930 char *eol = *eol_p;
931 int ch;
933 while (bol < --eol) {
934 if (*eol != '>')
935 continue;
936 *eol_p = ++eol;
937 ch = *eol;
938 *eol = '\0';
939 return ch;
941 return 0;
944 static struct {
945 const char *field;
946 size_t len;
947 } header_field[] = {
948 { "author ", 7 },
949 { "committer ", 10 },
950 { "reflog ", 7 },
953 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
954 enum grep_context ctx,
955 regmatch_t *pmatch, int eflags)
957 int hit = 0;
958 int saved_ch = 0;
959 const char *start = bol;
961 if ((p->token != GREP_PATTERN) &&
962 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
963 return 0;
965 if (p->token == GREP_PATTERN_HEAD) {
966 const char *field;
967 size_t len;
968 assert(p->field < ARRAY_SIZE(header_field));
969 field = header_field[p->field].field;
970 len = header_field[p->field].len;
971 if (strncmp(bol, field, len))
972 return 0;
973 bol += len;
974 switch (p->field) {
975 case GREP_HEADER_AUTHOR:
976 case GREP_HEADER_COMMITTER:
977 saved_ch = strip_timestamp(bol, &eol);
978 break;
979 default:
980 break;
984 again:
985 hit = patmatch(p, bol, eol, pmatch, eflags);
987 if (hit && p->word_regexp) {
988 if ((pmatch[0].rm_so < 0) ||
989 (eol - bol) < pmatch[0].rm_so ||
990 (pmatch[0].rm_eo < 0) ||
991 (eol - bol) < pmatch[0].rm_eo)
992 die("regexp returned nonsense");
994 /* Match beginning must be either beginning of the
995 * line, or at word boundary (i.e. the last char must
996 * not be a word char). Similarly, match end must be
997 * either end of the line, or at word boundary
998 * (i.e. the next char must not be a word char).
1000 if ( ((pmatch[0].rm_so == 0) ||
1001 !word_char(bol[pmatch[0].rm_so-1])) &&
1002 ((pmatch[0].rm_eo == (eol-bol)) ||
1003 !word_char(bol[pmatch[0].rm_eo])) )
1005 else
1006 hit = 0;
1008 /* Words consist of at least one character. */
1009 if (pmatch->rm_so == pmatch->rm_eo)
1010 hit = 0;
1012 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1013 /* There could be more than one match on the
1014 * line, and the first match might not be
1015 * strict word match. But later ones could be!
1016 * Forward to the next possible start, i.e. the
1017 * next position following a non-word char.
1019 bol = pmatch[0].rm_so + bol + 1;
1020 while (word_char(bol[-1]) && bol < eol)
1021 bol++;
1022 eflags |= REG_NOTBOL;
1023 if (bol < eol)
1024 goto again;
1027 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1028 *eol = saved_ch;
1029 if (hit) {
1030 pmatch[0].rm_so += bol - start;
1031 pmatch[0].rm_eo += bol - start;
1033 return hit;
1036 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1037 enum grep_context ctx, int collect_hits)
1039 int h = 0;
1040 regmatch_t match;
1042 if (!x)
1043 die("Not a valid grep expression");
1044 switch (x->node) {
1045 case GREP_NODE_TRUE:
1046 h = 1;
1047 break;
1048 case GREP_NODE_ATOM:
1049 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1050 break;
1051 case GREP_NODE_NOT:
1052 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1053 break;
1054 case GREP_NODE_AND:
1055 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1056 return 0;
1057 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1058 break;
1059 case GREP_NODE_OR:
1060 if (!collect_hits)
1061 return (match_expr_eval(x->u.binary.left,
1062 bol, eol, ctx, 0) ||
1063 match_expr_eval(x->u.binary.right,
1064 bol, eol, ctx, 0));
1065 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1066 x->u.binary.left->hit |= h;
1067 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1068 break;
1069 default:
1070 die("Unexpected node type (internal error) %d", x->node);
1072 if (collect_hits)
1073 x->hit |= h;
1074 return h;
1077 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1078 enum grep_context ctx, int collect_hits)
1080 struct grep_expr *x = opt->pattern_expression;
1081 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1084 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1085 enum grep_context ctx, int collect_hits)
1087 struct grep_pat *p;
1088 regmatch_t match;
1090 if (opt->extended)
1091 return match_expr(opt, bol, eol, ctx, collect_hits);
1093 /* we do not call with collect_hits without being extended */
1094 for (p = opt->pattern_list; p; p = p->next) {
1095 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1096 return 1;
1098 return 0;
1101 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1102 enum grep_context ctx,
1103 regmatch_t *pmatch, int eflags)
1105 regmatch_t match;
1107 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1108 return 0;
1109 if (match.rm_so < 0 || match.rm_eo < 0)
1110 return 0;
1111 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1112 if (match.rm_so > pmatch->rm_so)
1113 return 1;
1114 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1115 return 1;
1117 pmatch->rm_so = match.rm_so;
1118 pmatch->rm_eo = match.rm_eo;
1119 return 1;
1122 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1123 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1125 struct grep_pat *p;
1126 int hit = 0;
1128 pmatch->rm_so = pmatch->rm_eo = -1;
1129 if (bol < eol) {
1130 for (p = opt->pattern_list; p; p = p->next) {
1131 switch (p->token) {
1132 case GREP_PATTERN: /* atom */
1133 case GREP_PATTERN_HEAD:
1134 case GREP_PATTERN_BODY:
1135 hit |= match_next_pattern(p, bol, eol, ctx,
1136 pmatch, eflags);
1137 break;
1138 default:
1139 break;
1143 return hit;
1146 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1147 const char *name, unsigned lno, char sign)
1149 int rest = eol - bol;
1150 const char *match_color, *line_color = NULL;
1152 if (opt->file_break && opt->last_shown == 0) {
1153 if (opt->show_hunk_mark)
1154 opt->output(opt, "\n", 1);
1155 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1156 if (opt->last_shown == 0) {
1157 if (opt->show_hunk_mark) {
1158 output_color(opt, "--", 2, opt->color_sep);
1159 opt->output(opt, "\n", 1);
1161 } else if (lno > opt->last_shown + 1) {
1162 output_color(opt, "--", 2, opt->color_sep);
1163 opt->output(opt, "\n", 1);
1166 if (opt->heading && opt->last_shown == 0) {
1167 output_color(opt, name, strlen(name), opt->color_filename);
1168 opt->output(opt, "\n", 1);
1170 opt->last_shown = lno;
1172 if (!opt->heading && opt->pathname) {
1173 output_color(opt, name, strlen(name), opt->color_filename);
1174 output_sep(opt, sign);
1176 if (opt->linenum) {
1177 char buf[32];
1178 snprintf(buf, sizeof(buf), "%d", lno);
1179 output_color(opt, buf, strlen(buf), opt->color_lineno);
1180 output_sep(opt, sign);
1182 if (opt->color) {
1183 regmatch_t match;
1184 enum grep_context ctx = GREP_CONTEXT_BODY;
1185 int ch = *eol;
1186 int eflags = 0;
1188 if (sign == ':')
1189 match_color = opt->color_match_selected;
1190 else
1191 match_color = opt->color_match_context;
1192 if (sign == ':')
1193 line_color = opt->color_selected;
1194 else if (sign == '-')
1195 line_color = opt->color_context;
1196 else if (sign == '=')
1197 line_color = opt->color_function;
1198 *eol = '\0';
1199 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1200 if (match.rm_so == match.rm_eo)
1201 break;
1203 output_color(opt, bol, match.rm_so, line_color);
1204 output_color(opt, bol + match.rm_so,
1205 match.rm_eo - match.rm_so, match_color);
1206 bol += match.rm_eo;
1207 rest -= match.rm_eo;
1208 eflags = REG_NOTBOL;
1210 *eol = ch;
1212 output_color(opt, bol, rest, line_color);
1213 opt->output(opt, "\n", 1);
1216 #ifndef NO_PTHREADS
1217 int grep_use_locks;
1220 * This lock protects access to the gitattributes machinery, which is
1221 * not thread-safe.
1223 pthread_mutex_t grep_attr_mutex;
1225 static inline void grep_attr_lock(void)
1227 if (grep_use_locks)
1228 pthread_mutex_lock(&grep_attr_mutex);
1231 static inline void grep_attr_unlock(void)
1233 if (grep_use_locks)
1234 pthread_mutex_unlock(&grep_attr_mutex);
1238 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1240 pthread_mutex_t grep_read_mutex;
1242 #else
1243 #define grep_attr_lock()
1244 #define grep_attr_unlock()
1245 #endif
1247 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1249 xdemitconf_t *xecfg = opt->priv;
1250 if (xecfg && !xecfg->find_func) {
1251 grep_source_load_driver(gs);
1252 if (gs->driver->funcname.pattern) {
1253 const struct userdiff_funcname *pe = &gs->driver->funcname;
1254 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1255 } else {
1256 xecfg = opt->priv = NULL;
1260 if (xecfg) {
1261 char buf[1];
1262 return xecfg->find_func(bol, eol - bol, buf, 1,
1263 xecfg->find_func_priv) >= 0;
1266 if (bol == eol)
1267 return 0;
1268 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1269 return 1;
1270 return 0;
1273 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1274 char *bol, unsigned lno)
1276 while (bol > gs->buf) {
1277 char *eol = --bol;
1279 while (bol > gs->buf && bol[-1] != '\n')
1280 bol--;
1281 lno--;
1283 if (lno <= opt->last_shown)
1284 break;
1286 if (match_funcname(opt, gs, bol, eol)) {
1287 show_line(opt, bol, eol, gs->name, lno, '=');
1288 break;
1293 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1294 char *bol, char *end, unsigned lno)
1296 unsigned cur = lno, from = 1, funcname_lno = 0;
1297 int funcname_needed = !!opt->funcname;
1299 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1300 funcname_needed = 2;
1302 if (opt->pre_context < lno)
1303 from = lno - opt->pre_context;
1304 if (from <= opt->last_shown)
1305 from = opt->last_shown + 1;
1307 /* Rewind. */
1308 while (bol > gs->buf &&
1309 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1310 char *eol = --bol;
1312 while (bol > gs->buf && bol[-1] != '\n')
1313 bol--;
1314 cur--;
1315 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1316 funcname_lno = cur;
1317 funcname_needed = 0;
1321 /* We need to look even further back to find a function signature. */
1322 if (opt->funcname && funcname_needed)
1323 show_funcname_line(opt, gs, bol, cur);
1325 /* Back forward. */
1326 while (cur < lno) {
1327 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1329 while (*eol != '\n')
1330 eol++;
1331 show_line(opt, bol, eol, gs->name, cur, sign);
1332 bol = eol + 1;
1333 cur++;
1337 static int should_lookahead(struct grep_opt *opt)
1339 struct grep_pat *p;
1341 if (opt->extended)
1342 return 0; /* punt for too complex stuff */
1343 if (opt->invert)
1344 return 0;
1345 for (p = opt->pattern_list; p; p = p->next) {
1346 if (p->token != GREP_PATTERN)
1347 return 0; /* punt for "header only" and stuff */
1349 return 1;
1352 static int look_ahead(struct grep_opt *opt,
1353 unsigned long *left_p,
1354 unsigned *lno_p,
1355 char **bol_p)
1357 unsigned lno = *lno_p;
1358 char *bol = *bol_p;
1359 struct grep_pat *p;
1360 char *sp, *last_bol;
1361 regoff_t earliest = -1;
1363 for (p = opt->pattern_list; p; p = p->next) {
1364 int hit;
1365 regmatch_t m;
1367 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1368 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1369 continue;
1370 if (earliest < 0 || m.rm_so < earliest)
1371 earliest = m.rm_so;
1374 if (earliest < 0) {
1375 *bol_p = bol + *left_p;
1376 *left_p = 0;
1377 return 1;
1379 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1380 ; /* find the beginning of the line */
1381 last_bol = sp;
1383 for (sp = bol; sp < last_bol; sp++) {
1384 if (*sp == '\n')
1385 lno++;
1387 *left_p -= last_bol - bol;
1388 *bol_p = last_bol;
1389 *lno_p = lno;
1390 return 0;
1393 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1395 fwrite(buf, size, 1, stdout);
1398 static int fill_textconv_grep(struct userdiff_driver *driver,
1399 struct grep_source *gs)
1401 struct diff_filespec *df;
1402 char *buf;
1403 size_t size;
1405 if (!driver || !driver->textconv)
1406 return grep_source_load(gs);
1409 * The textconv interface is intimately tied to diff_filespecs, so we
1410 * have to pretend to be one. If we could unify the grep_source
1411 * and diff_filespec structs, this mess could just go away.
1413 df = alloc_filespec(gs->path);
1414 switch (gs->type) {
1415 case GREP_SOURCE_SHA1:
1416 fill_filespec(df, gs->identifier, 1, 0100644);
1417 break;
1418 case GREP_SOURCE_FILE:
1419 fill_filespec(df, null_sha1, 0, 0100644);
1420 break;
1421 default:
1422 die("BUG: attempt to textconv something without a path?");
1426 * fill_textconv is not remotely thread-safe; it may load objects
1427 * behind the scenes, and it modifies the global diff tempfile
1428 * structure.
1430 grep_read_lock();
1431 size = fill_textconv(driver, df, &buf);
1432 grep_read_unlock();
1433 free_filespec(df);
1436 * The normal fill_textconv usage by the diff machinery would just keep
1437 * the textconv'd buf separate from the diff_filespec. But much of the
1438 * grep code passes around a grep_source and assumes that its "buf"
1439 * pointer is the beginning of the thing we are searching. So let's
1440 * install our textconv'd version into the grep_source, taking care not
1441 * to leak any existing buffer.
1443 grep_source_clear_data(gs);
1444 gs->buf = buf;
1445 gs->size = size;
1447 return 0;
1450 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1452 char *bol;
1453 unsigned long left;
1454 unsigned lno = 1;
1455 unsigned last_hit = 0;
1456 int binary_match_only = 0;
1457 unsigned count = 0;
1458 int try_lookahead = 0;
1459 int show_function = 0;
1460 struct userdiff_driver *textconv = NULL;
1461 enum grep_context ctx = GREP_CONTEXT_HEAD;
1462 xdemitconf_t xecfg;
1464 if (!opt->output)
1465 opt->output = std_output;
1467 if (opt->pre_context || opt->post_context || opt->file_break ||
1468 opt->funcbody) {
1469 /* Show hunk marks, except for the first file. */
1470 if (opt->last_shown)
1471 opt->show_hunk_mark = 1;
1473 * If we're using threads then we can't easily identify
1474 * the first file. Always put hunk marks in that case
1475 * and skip the very first one later in work_done().
1477 if (opt->output != std_output)
1478 opt->show_hunk_mark = 1;
1480 opt->last_shown = 0;
1482 if (opt->allow_textconv) {
1483 grep_source_load_driver(gs);
1485 * We might set up the shared textconv cache data here, which
1486 * is not thread-safe.
1488 grep_attr_lock();
1489 textconv = userdiff_get_textconv(gs->driver);
1490 grep_attr_unlock();
1494 * We know the result of a textconv is text, so we only have to care
1495 * about binary handling if we are not using it.
1497 if (!textconv) {
1498 switch (opt->binary) {
1499 case GREP_BINARY_DEFAULT:
1500 if (grep_source_is_binary(gs))
1501 binary_match_only = 1;
1502 break;
1503 case GREP_BINARY_NOMATCH:
1504 if (grep_source_is_binary(gs))
1505 return 0; /* Assume unmatch */
1506 break;
1507 case GREP_BINARY_TEXT:
1508 break;
1509 default:
1510 die("bug: unknown binary handling mode");
1514 memset(&xecfg, 0, sizeof(xecfg));
1515 opt->priv = &xecfg;
1517 try_lookahead = should_lookahead(opt);
1519 if (fill_textconv_grep(textconv, gs) < 0)
1520 return 0;
1522 bol = gs->buf;
1523 left = gs->size;
1524 while (left) {
1525 char *eol, ch;
1526 int hit;
1529 * look_ahead() skips quickly to the line that possibly
1530 * has the next hit; don't call it if we need to do
1531 * something more than just skipping the current line
1532 * in response to an unmatch for the current line. E.g.
1533 * inside a post-context window, we will show the current
1534 * line as a context around the previous hit when it
1535 * doesn't hit.
1537 if (try_lookahead
1538 && !(last_hit
1539 && (show_function ||
1540 lno <= last_hit + opt->post_context))
1541 && look_ahead(opt, &left, &lno, &bol))
1542 break;
1543 eol = end_of_line(bol, &left);
1544 ch = *eol;
1545 *eol = 0;
1547 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1548 ctx = GREP_CONTEXT_BODY;
1550 hit = match_line(opt, bol, eol, ctx, collect_hits);
1551 *eol = ch;
1553 if (collect_hits)
1554 goto next_line;
1556 /* "grep -v -e foo -e bla" should list lines
1557 * that do not have either, so inversion should
1558 * be done outside.
1560 if (opt->invert)
1561 hit = !hit;
1562 if (opt->unmatch_name_only) {
1563 if (hit)
1564 return 0;
1565 goto next_line;
1567 if (hit) {
1568 count++;
1569 if (opt->status_only)
1570 return 1;
1571 if (opt->name_only) {
1572 show_name(opt, gs->name);
1573 return 1;
1575 if (opt->count)
1576 goto next_line;
1577 if (binary_match_only) {
1578 opt->output(opt, "Binary file ", 12);
1579 output_color(opt, gs->name, strlen(gs->name),
1580 opt->color_filename);
1581 opt->output(opt, " matches\n", 9);
1582 return 1;
1584 /* Hit at this line. If we haven't shown the
1585 * pre-context lines, we would need to show them.
1587 if (opt->pre_context || opt->funcbody)
1588 show_pre_context(opt, gs, bol, eol, lno);
1589 else if (opt->funcname)
1590 show_funcname_line(opt, gs, bol, lno);
1591 show_line(opt, bol, eol, gs->name, lno, ':');
1592 last_hit = lno;
1593 if (opt->funcbody)
1594 show_function = 1;
1595 goto next_line;
1597 if (show_function && match_funcname(opt, gs, bol, eol))
1598 show_function = 0;
1599 if (show_function ||
1600 (last_hit && lno <= last_hit + opt->post_context)) {
1601 /* If the last hit is within the post context,
1602 * we need to show this line.
1604 show_line(opt, bol, eol, gs->name, lno, '-');
1607 next_line:
1608 bol = eol + 1;
1609 if (!left)
1610 break;
1611 left--;
1612 lno++;
1615 if (collect_hits)
1616 return 0;
1618 if (opt->status_only)
1619 return 0;
1620 if (opt->unmatch_name_only) {
1621 /* We did not see any hit, so we want to show this */
1622 show_name(opt, gs->name);
1623 return 1;
1626 xdiff_clear_find_func(&xecfg);
1627 opt->priv = NULL;
1629 /* NEEDSWORK:
1630 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1631 * which feels mostly useless but sometimes useful. Maybe
1632 * make it another option? For now suppress them.
1634 if (opt->count && count) {
1635 char buf[32];
1636 if (opt->pathname) {
1637 output_color(opt, gs->name, strlen(gs->name),
1638 opt->color_filename);
1639 output_sep(opt, ':');
1641 snprintf(buf, sizeof(buf), "%u\n", count);
1642 opt->output(opt, buf, strlen(buf));
1643 return 1;
1645 return !!last_hit;
1648 static void clr_hit_marker(struct grep_expr *x)
1650 /* All-hit markers are meaningful only at the very top level
1651 * OR node.
1653 while (1) {
1654 x->hit = 0;
1655 if (x->node != GREP_NODE_OR)
1656 return;
1657 x->u.binary.left->hit = 0;
1658 x = x->u.binary.right;
1662 static int chk_hit_marker(struct grep_expr *x)
1664 /* Top level nodes have hit markers. See if they all are hits */
1665 while (1) {
1666 if (x->node != GREP_NODE_OR)
1667 return x->hit;
1668 if (!x->u.binary.left->hit)
1669 return 0;
1670 x = x->u.binary.right;
1674 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1677 * we do not have to do the two-pass grep when we do not check
1678 * buffer-wide "all-match".
1680 if (!opt->all_match)
1681 return grep_source_1(opt, gs, 0);
1683 /* Otherwise the toplevel "or" terms hit a bit differently.
1684 * We first clear hit markers from them.
1686 clr_hit_marker(opt->pattern_expression);
1687 grep_source_1(opt, gs, 1);
1689 if (!chk_hit_marker(opt->pattern_expression))
1690 return 0;
1692 return grep_source_1(opt, gs, 0);
1695 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1697 struct grep_source gs;
1698 int r;
1700 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1701 gs.buf = buf;
1702 gs.size = size;
1704 r = grep_source(opt, &gs);
1706 grep_source_clear(&gs);
1707 return r;
1710 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1711 const char *name, const char *path,
1712 const void *identifier)
1714 gs->type = type;
1715 gs->name = xstrdup_or_null(name);
1716 gs->path = xstrdup_or_null(path);
1717 gs->buf = NULL;
1718 gs->size = 0;
1719 gs->driver = NULL;
1721 switch (type) {
1722 case GREP_SOURCE_FILE:
1723 gs->identifier = xstrdup(identifier);
1724 break;
1725 case GREP_SOURCE_SHA1:
1726 gs->identifier = xmalloc(20);
1727 hashcpy(gs->identifier, identifier);
1728 break;
1729 case GREP_SOURCE_BUF:
1730 gs->identifier = NULL;
1734 void grep_source_clear(struct grep_source *gs)
1736 free(gs->name);
1737 gs->name = NULL;
1738 free(gs->path);
1739 gs->path = NULL;
1740 free(gs->identifier);
1741 gs->identifier = NULL;
1742 grep_source_clear_data(gs);
1745 void grep_source_clear_data(struct grep_source *gs)
1747 switch (gs->type) {
1748 case GREP_SOURCE_FILE:
1749 case GREP_SOURCE_SHA1:
1750 free(gs->buf);
1751 gs->buf = NULL;
1752 gs->size = 0;
1753 break;
1754 case GREP_SOURCE_BUF:
1755 /* leave user-provided buf intact */
1756 break;
1760 static int grep_source_load_sha1(struct grep_source *gs)
1762 enum object_type type;
1764 grep_read_lock();
1765 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1766 grep_read_unlock();
1768 if (!gs->buf)
1769 return error(_("'%s': unable to read %s"),
1770 gs->name,
1771 sha1_to_hex(gs->identifier));
1772 return 0;
1775 static int grep_source_load_file(struct grep_source *gs)
1777 const char *filename = gs->identifier;
1778 struct stat st;
1779 char *data;
1780 size_t size;
1781 int i;
1783 if (lstat(filename, &st) < 0) {
1784 err_ret:
1785 if (errno != ENOENT)
1786 error(_("'%s': %s"), filename, strerror(errno));
1787 return -1;
1789 if (!S_ISREG(st.st_mode))
1790 return -1;
1791 size = xsize_t(st.st_size);
1792 i = open(filename, O_RDONLY);
1793 if (i < 0)
1794 goto err_ret;
1795 data = xmalloc(size + 1);
1796 if (st.st_size != read_in_full(i, data, size)) {
1797 error(_("'%s': short read %s"), filename, strerror(errno));
1798 close(i);
1799 free(data);
1800 return -1;
1802 close(i);
1803 data[size] = 0;
1805 gs->buf = data;
1806 gs->size = size;
1807 return 0;
1810 static int grep_source_load(struct grep_source *gs)
1812 if (gs->buf)
1813 return 0;
1815 switch (gs->type) {
1816 case GREP_SOURCE_FILE:
1817 return grep_source_load_file(gs);
1818 case GREP_SOURCE_SHA1:
1819 return grep_source_load_sha1(gs);
1820 case GREP_SOURCE_BUF:
1821 return gs->buf ? 0 : -1;
1823 die("BUG: invalid grep_source type");
1826 void grep_source_load_driver(struct grep_source *gs)
1828 if (gs->driver)
1829 return;
1831 grep_attr_lock();
1832 if (gs->path)
1833 gs->driver = userdiff_find_by_path(gs->path);
1834 if (!gs->driver)
1835 gs->driver = userdiff_find_by_name("default");
1836 grep_attr_unlock();
1839 static int grep_source_is_binary(struct grep_source *gs)
1841 grep_source_load_driver(gs);
1842 if (gs->driver->binary != -1)
1843 return gs->driver->binary;
1845 if (!grep_source_load(gs))
1846 return buffer_is_binary(gs->buf, gs->size);
1848 return 0;