regex: use regexec_buf()
[alt-git.git] / grep.c
blob8ed56236f049a47490f2c14d999a13e21b98fd2c
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"
8 static int grep_source_load(struct grep_source *gs);
9 static int grep_source_is_binary(struct grep_source *gs);
11 static struct grep_opt grep_defaults;
14 * Initialize the grep_defaults template with hardcoded defaults.
15 * We could let the compiler do this, but without C99 initializers
16 * the code gets unwieldy and unreadable, so...
18 void init_grep_defaults(void)
20 struct grep_opt *opt = &grep_defaults;
21 static int run_once;
23 if (run_once)
24 return;
25 run_once++;
27 memset(opt, 0, sizeof(*opt));
28 opt->relative = 1;
29 opt->pathname = 1;
30 opt->regflags = REG_NEWLINE;
31 opt->max_depth = -1;
32 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
33 opt->extended_regexp_option = 0;
34 color_set(opt->color_context, "");
35 color_set(opt->color_filename, "");
36 color_set(opt->color_function, "");
37 color_set(opt->color_lineno, "");
38 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
39 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
40 color_set(opt->color_selected, "");
41 color_set(opt->color_sep, GIT_COLOR_CYAN);
42 opt->color = -1;
45 static int parse_pattern_type_arg(const char *opt, const char *arg)
47 if (!strcmp(arg, "default"))
48 return GREP_PATTERN_TYPE_UNSPECIFIED;
49 else if (!strcmp(arg, "basic"))
50 return GREP_PATTERN_TYPE_BRE;
51 else if (!strcmp(arg, "extended"))
52 return GREP_PATTERN_TYPE_ERE;
53 else if (!strcmp(arg, "fixed"))
54 return GREP_PATTERN_TYPE_FIXED;
55 else if (!strcmp(arg, "perl"))
56 return GREP_PATTERN_TYPE_PCRE;
57 die("bad %s argument: %s", opt, arg);
61 * Read the configuration file once and store it in
62 * the grep_defaults template.
64 int grep_config(const char *var, const char *value, void *cb)
66 struct grep_opt *opt = &grep_defaults;
67 char *color = NULL;
69 if (userdiff_config(var, value) < 0)
70 return -1;
72 if (!strcmp(var, "grep.extendedregexp")) {
73 if (git_config_bool(var, value))
74 opt->extended_regexp_option = 1;
75 else
76 opt->extended_regexp_option = 0;
77 return 0;
80 if (!strcmp(var, "grep.patterntype")) {
81 opt->pattern_type_option = parse_pattern_type_arg(var, value);
82 return 0;
85 if (!strcmp(var, "grep.linenumber")) {
86 opt->linenum = git_config_bool(var, value);
87 return 0;
90 if (!strcmp(var, "grep.fullname")) {
91 opt->relative = !git_config_bool(var, value);
92 return 0;
95 if (!strcmp(var, "color.grep"))
96 opt->color = git_config_colorbool(var, value);
97 else if (!strcmp(var, "color.grep.context"))
98 color = opt->color_context;
99 else if (!strcmp(var, "color.grep.filename"))
100 color = opt->color_filename;
101 else if (!strcmp(var, "color.grep.function"))
102 color = opt->color_function;
103 else if (!strcmp(var, "color.grep.linenumber"))
104 color = opt->color_lineno;
105 else if (!strcmp(var, "color.grep.matchcontext"))
106 color = opt->color_match_context;
107 else if (!strcmp(var, "color.grep.matchselected"))
108 color = opt->color_match_selected;
109 else if (!strcmp(var, "color.grep.selected"))
110 color = opt->color_selected;
111 else if (!strcmp(var, "color.grep.separator"))
112 color = opt->color_sep;
113 else if (!strcmp(var, "color.grep.match")) {
114 int rc = 0;
115 if (!value)
116 return config_error_nonbool(var);
117 rc |= color_parse(value, opt->color_match_context);
118 rc |= color_parse(value, opt->color_match_selected);
119 return rc;
122 if (color) {
123 if (!value)
124 return config_error_nonbool(var);
125 return color_parse(value, color);
127 return 0;
131 * Initialize one instance of grep_opt and copy the
132 * default values from the template we read the configuration
133 * information in an earlier call to git_config(grep_config).
135 void grep_init(struct grep_opt *opt, const char *prefix)
137 struct grep_opt *def = &grep_defaults;
139 memset(opt, 0, sizeof(*opt));
140 opt->prefix = prefix;
141 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
142 opt->pattern_tail = &opt->pattern_list;
143 opt->header_tail = &opt->header_list;
145 opt->color = def->color;
146 opt->extended_regexp_option = def->extended_regexp_option;
147 opt->pattern_type_option = def->pattern_type_option;
148 opt->linenum = def->linenum;
149 opt->max_depth = def->max_depth;
150 opt->pathname = def->pathname;
151 opt->regflags = def->regflags;
152 opt->relative = def->relative;
154 color_set(opt->color_context, def->color_context);
155 color_set(opt->color_filename, def->color_filename);
156 color_set(opt->color_function, def->color_function);
157 color_set(opt->color_lineno, def->color_lineno);
158 color_set(opt->color_match_context, def->color_match_context);
159 color_set(opt->color_match_selected, def->color_match_selected);
160 color_set(opt->color_selected, def->color_selected);
161 color_set(opt->color_sep, def->color_sep);
164 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
166 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
167 grep_set_pattern_type_option(pattern_type, opt);
168 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
169 grep_set_pattern_type_option(opt->pattern_type_option, opt);
170 else if (opt->extended_regexp_option)
171 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
174 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
176 switch (pattern_type) {
177 case GREP_PATTERN_TYPE_UNSPECIFIED:
178 /* fall through */
180 case GREP_PATTERN_TYPE_BRE:
181 opt->fixed = 0;
182 opt->pcre = 0;
183 opt->regflags &= ~REG_EXTENDED;
184 break;
186 case GREP_PATTERN_TYPE_ERE:
187 opt->fixed = 0;
188 opt->pcre = 0;
189 opt->regflags |= REG_EXTENDED;
190 break;
192 case GREP_PATTERN_TYPE_FIXED:
193 opt->fixed = 1;
194 opt->pcre = 0;
195 opt->regflags &= ~REG_EXTENDED;
196 break;
198 case GREP_PATTERN_TYPE_PCRE:
199 opt->fixed = 0;
200 opt->pcre = 1;
201 opt->regflags &= ~REG_EXTENDED;
202 break;
206 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
207 const char *origin, int no,
208 enum grep_pat_token t,
209 enum grep_header_field field)
211 struct grep_pat *p = xcalloc(1, sizeof(*p));
212 p->pattern = xmemdupz(pat, patlen);
213 p->patternlen = patlen;
214 p->origin = origin;
215 p->no = no;
216 p->token = t;
217 p->field = field;
218 return p;
221 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
223 **tail = p;
224 *tail = &p->next;
225 p->next = NULL;
227 switch (p->token) {
228 case GREP_PATTERN: /* atom */
229 case GREP_PATTERN_HEAD:
230 case GREP_PATTERN_BODY:
231 for (;;) {
232 struct grep_pat *new_pat;
233 size_t len = 0;
234 char *cp = p->pattern + p->patternlen, *nl = NULL;
235 while (++len <= p->patternlen) {
236 if (*(--cp) == '\n') {
237 nl = cp;
238 break;
241 if (!nl)
242 break;
243 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
244 p->no, p->token, p->field);
245 new_pat->next = p->next;
246 if (!p->next)
247 *tail = &new_pat->next;
248 p->next = new_pat;
249 *nl = '\0';
250 p->patternlen -= len;
252 break;
253 default:
254 break;
258 void append_header_grep_pattern(struct grep_opt *opt,
259 enum grep_header_field field, const char *pat)
261 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
262 GREP_PATTERN_HEAD, field);
263 if (field == GREP_HEADER_REFLOG)
264 opt->use_reflog_filter = 1;
265 do_append_grep_pat(&opt->header_tail, p);
268 void append_grep_pattern(struct grep_opt *opt, const char *pat,
269 const char *origin, int no, enum grep_pat_token t)
271 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
274 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
275 const char *origin, int no, enum grep_pat_token t)
277 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
278 do_append_grep_pat(&opt->pattern_tail, p);
281 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
283 struct grep_pat *pat;
284 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
285 *ret = *opt;
287 ret->pattern_list = NULL;
288 ret->pattern_tail = &ret->pattern_list;
290 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
292 if(pat->token == GREP_PATTERN_HEAD)
293 append_header_grep_pattern(ret, pat->field,
294 pat->pattern);
295 else
296 append_grep_pat(ret, pat->pattern, pat->patternlen,
297 pat->origin, pat->no, pat->token);
300 return ret;
303 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
304 const char *error)
306 char where[1024];
308 if (p->no)
309 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
310 else if (p->origin)
311 xsnprintf(where, sizeof(where), "%s, ", p->origin);
312 else
313 where[0] = 0;
315 die("%s'%s': %s", where, p->pattern, error);
318 #ifdef USE_LIBPCRE
319 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
321 const char *error;
322 int erroffset;
323 int options = PCRE_MULTILINE;
325 if (opt->ignore_case)
326 options |= PCRE_CASELESS;
328 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
329 NULL);
330 if (!p->pcre_regexp)
331 compile_regexp_failed(p, error);
333 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
334 if (!p->pcre_extra_info && error)
335 die("%s", error);
338 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
339 regmatch_t *match, int eflags)
341 int ovector[30], ret, flags = 0;
343 if (eflags & REG_NOTBOL)
344 flags |= PCRE_NOTBOL;
346 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
347 0, flags, ovector, ARRAY_SIZE(ovector));
348 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
349 die("pcre_exec failed with error code %d", ret);
350 if (ret > 0) {
351 ret = 0;
352 match->rm_so = ovector[0];
353 match->rm_eo = ovector[1];
356 return ret;
359 static void free_pcre_regexp(struct grep_pat *p)
361 pcre_free(p->pcre_regexp);
362 pcre_free(p->pcre_extra_info);
364 #else /* !USE_LIBPCRE */
365 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
367 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
370 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
371 regmatch_t *match, int eflags)
373 return 1;
376 static void free_pcre_regexp(struct grep_pat *p)
379 #endif /* !USE_LIBPCRE */
381 static int is_fixed(const char *s, size_t len)
383 size_t i;
385 /* regcomp cannot accept patterns with NULs so we
386 * consider any pattern containing a NUL fixed.
388 if (memchr(s, 0, len))
389 return 1;
391 for (i = 0; i < len; i++) {
392 if (is_regex_special(s[i]))
393 return 0;
396 return 1;
399 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
401 int err;
403 p->word_regexp = opt->word_regexp;
404 p->ignore_case = opt->ignore_case;
406 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
407 p->fixed = 1;
408 else
409 p->fixed = 0;
411 if (p->fixed) {
412 if (opt->regflags & REG_ICASE || p->ignore_case)
413 p->kws = kwsalloc(tolower_trans_tbl);
414 else
415 p->kws = kwsalloc(NULL);
416 kwsincr(p->kws, p->pattern, p->patternlen);
417 kwsprep(p->kws);
418 return;
421 if (opt->pcre) {
422 compile_pcre_regexp(p, opt);
423 return;
426 err = regcomp(&p->regexp, p->pattern, opt->regflags);
427 if (err) {
428 char errbuf[1024];
429 regerror(err, &p->regexp, errbuf, 1024);
430 regfree(&p->regexp);
431 compile_regexp_failed(p, errbuf);
435 static struct grep_expr *compile_pattern_or(struct grep_pat **);
436 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
438 struct grep_pat *p;
439 struct grep_expr *x;
441 p = *list;
442 if (!p)
443 return NULL;
444 switch (p->token) {
445 case GREP_PATTERN: /* atom */
446 case GREP_PATTERN_HEAD:
447 case GREP_PATTERN_BODY:
448 x = xcalloc(1, sizeof (struct grep_expr));
449 x->node = GREP_NODE_ATOM;
450 x->u.atom = p;
451 *list = p->next;
452 return x;
453 case GREP_OPEN_PAREN:
454 *list = p->next;
455 x = compile_pattern_or(list);
456 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
457 die("unmatched parenthesis");
458 *list = (*list)->next;
459 return x;
460 default:
461 return NULL;
465 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
467 struct grep_pat *p;
468 struct grep_expr *x;
470 p = *list;
471 if (!p)
472 return NULL;
473 switch (p->token) {
474 case GREP_NOT:
475 if (!p->next)
476 die("--not not followed by pattern expression");
477 *list = p->next;
478 x = xcalloc(1, sizeof (struct grep_expr));
479 x->node = GREP_NODE_NOT;
480 x->u.unary = compile_pattern_not(list);
481 if (!x->u.unary)
482 die("--not followed by non pattern expression");
483 return x;
484 default:
485 return compile_pattern_atom(list);
489 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
491 struct grep_pat *p;
492 struct grep_expr *x, *y, *z;
494 x = compile_pattern_not(list);
495 p = *list;
496 if (p && p->token == GREP_AND) {
497 if (!p->next)
498 die("--and not followed by pattern expression");
499 *list = p->next;
500 y = compile_pattern_and(list);
501 if (!y)
502 die("--and not followed by pattern expression");
503 z = xcalloc(1, sizeof (struct grep_expr));
504 z->node = GREP_NODE_AND;
505 z->u.binary.left = x;
506 z->u.binary.right = y;
507 return z;
509 return x;
512 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
514 struct grep_pat *p;
515 struct grep_expr *x, *y, *z;
517 x = compile_pattern_and(list);
518 p = *list;
519 if (x && p && p->token != GREP_CLOSE_PAREN) {
520 y = compile_pattern_or(list);
521 if (!y)
522 die("not a pattern expression %s", p->pattern);
523 z = xcalloc(1, sizeof (struct grep_expr));
524 z->node = GREP_NODE_OR;
525 z->u.binary.left = x;
526 z->u.binary.right = y;
527 return z;
529 return x;
532 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
534 return compile_pattern_or(list);
537 static void indent(int in)
539 while (in-- > 0)
540 fputc(' ', stderr);
543 static void dump_grep_pat(struct grep_pat *p)
545 switch (p->token) {
546 case GREP_AND: fprintf(stderr, "*and*"); break;
547 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
548 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
549 case GREP_NOT: fprintf(stderr, "*not*"); break;
550 case GREP_OR: fprintf(stderr, "*or*"); break;
552 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
553 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
554 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
557 switch (p->token) {
558 default: break;
559 case GREP_PATTERN_HEAD:
560 fprintf(stderr, "<head %d>", p->field); break;
561 case GREP_PATTERN_BODY:
562 fprintf(stderr, "<body>"); break;
564 switch (p->token) {
565 default: break;
566 case GREP_PATTERN_HEAD:
567 case GREP_PATTERN_BODY:
568 case GREP_PATTERN:
569 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
570 break;
572 fputc('\n', stderr);
575 static void dump_grep_expression_1(struct grep_expr *x, int in)
577 indent(in);
578 switch (x->node) {
579 case GREP_NODE_TRUE:
580 fprintf(stderr, "true\n");
581 break;
582 case GREP_NODE_ATOM:
583 dump_grep_pat(x->u.atom);
584 break;
585 case GREP_NODE_NOT:
586 fprintf(stderr, "(not\n");
587 dump_grep_expression_1(x->u.unary, in+1);
588 indent(in);
589 fprintf(stderr, ")\n");
590 break;
591 case GREP_NODE_AND:
592 fprintf(stderr, "(and\n");
593 dump_grep_expression_1(x->u.binary.left, in+1);
594 dump_grep_expression_1(x->u.binary.right, in+1);
595 indent(in);
596 fprintf(stderr, ")\n");
597 break;
598 case GREP_NODE_OR:
599 fprintf(stderr, "(or\n");
600 dump_grep_expression_1(x->u.binary.left, in+1);
601 dump_grep_expression_1(x->u.binary.right, in+1);
602 indent(in);
603 fprintf(stderr, ")\n");
604 break;
608 static void dump_grep_expression(struct grep_opt *opt)
610 struct grep_expr *x = opt->pattern_expression;
612 if (opt->all_match)
613 fprintf(stderr, "[all-match]\n");
614 dump_grep_expression_1(x, 0);
615 fflush(NULL);
618 static struct grep_expr *grep_true_expr(void)
620 struct grep_expr *z = xcalloc(1, sizeof(*z));
621 z->node = GREP_NODE_TRUE;
622 return z;
625 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
627 struct grep_expr *z = xcalloc(1, sizeof(*z));
628 z->node = GREP_NODE_OR;
629 z->u.binary.left = left;
630 z->u.binary.right = right;
631 return z;
634 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
636 struct grep_pat *p;
637 struct grep_expr *header_expr;
638 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
639 enum grep_header_field fld;
641 if (!opt->header_list)
642 return NULL;
644 for (p = opt->header_list; p; p = p->next) {
645 if (p->token != GREP_PATTERN_HEAD)
646 die("bug: a non-header pattern in grep header list.");
647 if (p->field < GREP_HEADER_FIELD_MIN ||
648 GREP_HEADER_FIELD_MAX <= p->field)
649 die("bug: unknown header field %d", p->field);
650 compile_regexp(p, opt);
653 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
654 header_group[fld] = NULL;
656 for (p = opt->header_list; p; p = p->next) {
657 struct grep_expr *h;
658 struct grep_pat *pp = p;
660 h = compile_pattern_atom(&pp);
661 if (!h || pp != p->next)
662 die("bug: malformed header expr");
663 if (!header_group[p->field]) {
664 header_group[p->field] = h;
665 continue;
667 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
670 header_expr = NULL;
672 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
673 if (!header_group[fld])
674 continue;
675 if (!header_expr)
676 header_expr = grep_true_expr();
677 header_expr = grep_or_expr(header_group[fld], header_expr);
679 return header_expr;
682 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
684 struct grep_expr *z = x;
686 while (x) {
687 assert(x->node == GREP_NODE_OR);
688 if (x->u.binary.right &&
689 x->u.binary.right->node == GREP_NODE_TRUE) {
690 x->u.binary.right = y;
691 break;
693 x = x->u.binary.right;
695 return z;
698 static void compile_grep_patterns_real(struct grep_opt *opt)
700 struct grep_pat *p;
701 struct grep_expr *header_expr = prep_header_patterns(opt);
703 for (p = opt->pattern_list; p; p = p->next) {
704 switch (p->token) {
705 case GREP_PATTERN: /* atom */
706 case GREP_PATTERN_HEAD:
707 case GREP_PATTERN_BODY:
708 compile_regexp(p, opt);
709 break;
710 default:
711 opt->extended = 1;
712 break;
716 if (opt->all_match || header_expr)
717 opt->extended = 1;
718 else if (!opt->extended && !opt->debug)
719 return;
721 p = opt->pattern_list;
722 if (p)
723 opt->pattern_expression = compile_pattern_expr(&p);
724 if (p)
725 die("incomplete pattern expression: %s", p->pattern);
727 if (!header_expr)
728 return;
730 if (!opt->pattern_expression)
731 opt->pattern_expression = header_expr;
732 else if (opt->all_match)
733 opt->pattern_expression = grep_splice_or(header_expr,
734 opt->pattern_expression);
735 else
736 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
737 header_expr);
738 opt->all_match = 1;
741 void compile_grep_patterns(struct grep_opt *opt)
743 compile_grep_patterns_real(opt);
744 if (opt->debug)
745 dump_grep_expression(opt);
748 static void free_pattern_expr(struct grep_expr *x)
750 switch (x->node) {
751 case GREP_NODE_TRUE:
752 case GREP_NODE_ATOM:
753 break;
754 case GREP_NODE_NOT:
755 free_pattern_expr(x->u.unary);
756 break;
757 case GREP_NODE_AND:
758 case GREP_NODE_OR:
759 free_pattern_expr(x->u.binary.left);
760 free_pattern_expr(x->u.binary.right);
761 break;
763 free(x);
766 void free_grep_patterns(struct grep_opt *opt)
768 struct grep_pat *p, *n;
770 for (p = opt->pattern_list; p; p = n) {
771 n = p->next;
772 switch (p->token) {
773 case GREP_PATTERN: /* atom */
774 case GREP_PATTERN_HEAD:
775 case GREP_PATTERN_BODY:
776 if (p->kws)
777 kwsfree(p->kws);
778 else if (p->pcre_regexp)
779 free_pcre_regexp(p);
780 else
781 regfree(&p->regexp);
782 free(p->pattern);
783 break;
784 default:
785 break;
787 free(p);
790 if (!opt->extended)
791 return;
792 free_pattern_expr(opt->pattern_expression);
795 static char *end_of_line(char *cp, unsigned long *left)
797 unsigned long l = *left;
798 while (l && *cp != '\n') {
799 l--;
800 cp++;
802 *left = l;
803 return cp;
806 static int word_char(char ch)
808 return isalnum(ch) || ch == '_';
811 static void output_color(struct grep_opt *opt, const void *data, size_t size,
812 const char *color)
814 if (want_color(opt->color) && color && color[0]) {
815 opt->output(opt, color, strlen(color));
816 opt->output(opt, data, size);
817 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
818 } else
819 opt->output(opt, data, size);
822 static void output_sep(struct grep_opt *opt, char sign)
824 if (opt->null_following_name)
825 opt->output(opt, "\0", 1);
826 else
827 output_color(opt, &sign, 1, opt->color_sep);
830 static void show_name(struct grep_opt *opt, const char *name)
832 output_color(opt, name, strlen(name), opt->color_filename);
833 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
836 static int fixmatch(struct grep_pat *p, char *line, char *eol,
837 regmatch_t *match)
839 struct kwsmatch kwsm;
840 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
841 if (offset == -1) {
842 match->rm_so = match->rm_eo = -1;
843 return REG_NOMATCH;
844 } else {
845 match->rm_so = offset;
846 match->rm_eo = match->rm_so + kwsm.size[0];
847 return 0;
851 static int patmatch(struct grep_pat *p, char *line, char *eol,
852 regmatch_t *match, int eflags)
854 int hit;
856 if (p->fixed)
857 hit = !fixmatch(p, line, eol, match);
858 else if (p->pcre_regexp)
859 hit = !pcrematch(p, line, eol, match, eflags);
860 else
861 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
862 eflags);
864 return hit;
867 static int strip_timestamp(char *bol, char **eol_p)
869 char *eol = *eol_p;
870 int ch;
872 while (bol < --eol) {
873 if (*eol != '>')
874 continue;
875 *eol_p = ++eol;
876 ch = *eol;
877 *eol = '\0';
878 return ch;
880 return 0;
883 static struct {
884 const char *field;
885 size_t len;
886 } header_field[] = {
887 { "author ", 7 },
888 { "committer ", 10 },
889 { "reflog ", 7 },
892 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
893 enum grep_context ctx,
894 regmatch_t *pmatch, int eflags)
896 int hit = 0;
897 int saved_ch = 0;
898 const char *start = bol;
900 if ((p->token != GREP_PATTERN) &&
901 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
902 return 0;
904 if (p->token == GREP_PATTERN_HEAD) {
905 const char *field;
906 size_t len;
907 assert(p->field < ARRAY_SIZE(header_field));
908 field = header_field[p->field].field;
909 len = header_field[p->field].len;
910 if (strncmp(bol, field, len))
911 return 0;
912 bol += len;
913 switch (p->field) {
914 case GREP_HEADER_AUTHOR:
915 case GREP_HEADER_COMMITTER:
916 saved_ch = strip_timestamp(bol, &eol);
917 break;
918 default:
919 break;
923 again:
924 hit = patmatch(p, bol, eol, pmatch, eflags);
926 if (hit && p->word_regexp) {
927 if ((pmatch[0].rm_so < 0) ||
928 (eol - bol) < pmatch[0].rm_so ||
929 (pmatch[0].rm_eo < 0) ||
930 (eol - bol) < pmatch[0].rm_eo)
931 die("regexp returned nonsense");
933 /* Match beginning must be either beginning of the
934 * line, or at word boundary (i.e. the last char must
935 * not be a word char). Similarly, match end must be
936 * either end of the line, or at word boundary
937 * (i.e. the next char must not be a word char).
939 if ( ((pmatch[0].rm_so == 0) ||
940 !word_char(bol[pmatch[0].rm_so-1])) &&
941 ((pmatch[0].rm_eo == (eol-bol)) ||
942 !word_char(bol[pmatch[0].rm_eo])) )
944 else
945 hit = 0;
947 /* Words consist of at least one character. */
948 if (pmatch->rm_so == pmatch->rm_eo)
949 hit = 0;
951 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
952 /* There could be more than one match on the
953 * line, and the first match might not be
954 * strict word match. But later ones could be!
955 * Forward to the next possible start, i.e. the
956 * next position following a non-word char.
958 bol = pmatch[0].rm_so + bol + 1;
959 while (word_char(bol[-1]) && bol < eol)
960 bol++;
961 eflags |= REG_NOTBOL;
962 if (bol < eol)
963 goto again;
966 if (p->token == GREP_PATTERN_HEAD && saved_ch)
967 *eol = saved_ch;
968 if (hit) {
969 pmatch[0].rm_so += bol - start;
970 pmatch[0].rm_eo += bol - start;
972 return hit;
975 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
976 enum grep_context ctx, int collect_hits)
978 int h = 0;
979 regmatch_t match;
981 if (!x)
982 die("Not a valid grep expression");
983 switch (x->node) {
984 case GREP_NODE_TRUE:
985 h = 1;
986 break;
987 case GREP_NODE_ATOM:
988 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
989 break;
990 case GREP_NODE_NOT:
991 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
992 break;
993 case GREP_NODE_AND:
994 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
995 return 0;
996 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
997 break;
998 case GREP_NODE_OR:
999 if (!collect_hits)
1000 return (match_expr_eval(x->u.binary.left,
1001 bol, eol, ctx, 0) ||
1002 match_expr_eval(x->u.binary.right,
1003 bol, eol, ctx, 0));
1004 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1005 x->u.binary.left->hit |= h;
1006 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1007 break;
1008 default:
1009 die("Unexpected node type (internal error) %d", x->node);
1011 if (collect_hits)
1012 x->hit |= h;
1013 return h;
1016 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1017 enum grep_context ctx, int collect_hits)
1019 struct grep_expr *x = opt->pattern_expression;
1020 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1023 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1024 enum grep_context ctx, int collect_hits)
1026 struct grep_pat *p;
1027 regmatch_t match;
1029 if (opt->extended)
1030 return match_expr(opt, bol, eol, ctx, collect_hits);
1032 /* we do not call with collect_hits without being extended */
1033 for (p = opt->pattern_list; p; p = p->next) {
1034 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1035 return 1;
1037 return 0;
1040 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1041 enum grep_context ctx,
1042 regmatch_t *pmatch, int eflags)
1044 regmatch_t match;
1046 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1047 return 0;
1048 if (match.rm_so < 0 || match.rm_eo < 0)
1049 return 0;
1050 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1051 if (match.rm_so > pmatch->rm_so)
1052 return 1;
1053 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1054 return 1;
1056 pmatch->rm_so = match.rm_so;
1057 pmatch->rm_eo = match.rm_eo;
1058 return 1;
1061 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1062 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1064 struct grep_pat *p;
1065 int hit = 0;
1067 pmatch->rm_so = pmatch->rm_eo = -1;
1068 if (bol < eol) {
1069 for (p = opt->pattern_list; p; p = p->next) {
1070 switch (p->token) {
1071 case GREP_PATTERN: /* atom */
1072 case GREP_PATTERN_HEAD:
1073 case GREP_PATTERN_BODY:
1074 hit |= match_next_pattern(p, bol, eol, ctx,
1075 pmatch, eflags);
1076 break;
1077 default:
1078 break;
1082 return hit;
1085 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1086 const char *name, unsigned lno, char sign)
1088 int rest = eol - bol;
1089 const char *match_color, *line_color = NULL;
1091 if (opt->file_break && opt->last_shown == 0) {
1092 if (opt->show_hunk_mark)
1093 opt->output(opt, "\n", 1);
1094 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1095 if (opt->last_shown == 0) {
1096 if (opt->show_hunk_mark) {
1097 output_color(opt, "--", 2, opt->color_sep);
1098 opt->output(opt, "\n", 1);
1100 } else if (lno > opt->last_shown + 1) {
1101 output_color(opt, "--", 2, opt->color_sep);
1102 opt->output(opt, "\n", 1);
1105 if (opt->heading && opt->last_shown == 0) {
1106 output_color(opt, name, strlen(name), opt->color_filename);
1107 opt->output(opt, "\n", 1);
1109 opt->last_shown = lno;
1111 if (!opt->heading && opt->pathname) {
1112 output_color(opt, name, strlen(name), opt->color_filename);
1113 output_sep(opt, sign);
1115 if (opt->linenum) {
1116 char buf[32];
1117 snprintf(buf, sizeof(buf), "%d", lno);
1118 output_color(opt, buf, strlen(buf), opt->color_lineno);
1119 output_sep(opt, sign);
1121 if (opt->color) {
1122 regmatch_t match;
1123 enum grep_context ctx = GREP_CONTEXT_BODY;
1124 int ch = *eol;
1125 int eflags = 0;
1127 if (sign == ':')
1128 match_color = opt->color_match_selected;
1129 else
1130 match_color = opt->color_match_context;
1131 if (sign == ':')
1132 line_color = opt->color_selected;
1133 else if (sign == '-')
1134 line_color = opt->color_context;
1135 else if (sign == '=')
1136 line_color = opt->color_function;
1137 *eol = '\0';
1138 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1139 if (match.rm_so == match.rm_eo)
1140 break;
1142 output_color(opt, bol, match.rm_so, line_color);
1143 output_color(opt, bol + match.rm_so,
1144 match.rm_eo - match.rm_so, match_color);
1145 bol += match.rm_eo;
1146 rest -= match.rm_eo;
1147 eflags = REG_NOTBOL;
1149 *eol = ch;
1151 output_color(opt, bol, rest, line_color);
1152 opt->output(opt, "\n", 1);
1155 #ifndef NO_PTHREADS
1156 int grep_use_locks;
1159 * This lock protects access to the gitattributes machinery, which is
1160 * not thread-safe.
1162 pthread_mutex_t grep_attr_mutex;
1164 static inline void grep_attr_lock(void)
1166 if (grep_use_locks)
1167 pthread_mutex_lock(&grep_attr_mutex);
1170 static inline void grep_attr_unlock(void)
1172 if (grep_use_locks)
1173 pthread_mutex_unlock(&grep_attr_mutex);
1177 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1179 pthread_mutex_t grep_read_mutex;
1181 #else
1182 #define grep_attr_lock()
1183 #define grep_attr_unlock()
1184 #endif
1186 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1188 xdemitconf_t *xecfg = opt->priv;
1189 if (xecfg && !xecfg->find_func) {
1190 grep_source_load_driver(gs);
1191 if (gs->driver->funcname.pattern) {
1192 const struct userdiff_funcname *pe = &gs->driver->funcname;
1193 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1194 } else {
1195 xecfg = opt->priv = NULL;
1199 if (xecfg) {
1200 char buf[1];
1201 return xecfg->find_func(bol, eol - bol, buf, 1,
1202 xecfg->find_func_priv) >= 0;
1205 if (bol == eol)
1206 return 0;
1207 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1208 return 1;
1209 return 0;
1212 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1213 char *bol, unsigned lno)
1215 while (bol > gs->buf) {
1216 char *eol = --bol;
1218 while (bol > gs->buf && bol[-1] != '\n')
1219 bol--;
1220 lno--;
1222 if (lno <= opt->last_shown)
1223 break;
1225 if (match_funcname(opt, gs, bol, eol)) {
1226 show_line(opt, bol, eol, gs->name, lno, '=');
1227 break;
1232 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1233 char *bol, char *end, unsigned lno)
1235 unsigned cur = lno, from = 1, funcname_lno = 0;
1236 int funcname_needed = !!opt->funcname;
1238 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1239 funcname_needed = 2;
1241 if (opt->pre_context < lno)
1242 from = lno - opt->pre_context;
1243 if (from <= opt->last_shown)
1244 from = opt->last_shown + 1;
1246 /* Rewind. */
1247 while (bol > gs->buf &&
1248 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1249 char *eol = --bol;
1251 while (bol > gs->buf && bol[-1] != '\n')
1252 bol--;
1253 cur--;
1254 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1255 funcname_lno = cur;
1256 funcname_needed = 0;
1260 /* We need to look even further back to find a function signature. */
1261 if (opt->funcname && funcname_needed)
1262 show_funcname_line(opt, gs, bol, cur);
1264 /* Back forward. */
1265 while (cur < lno) {
1266 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1268 while (*eol != '\n')
1269 eol++;
1270 show_line(opt, bol, eol, gs->name, cur, sign);
1271 bol = eol + 1;
1272 cur++;
1276 static int should_lookahead(struct grep_opt *opt)
1278 struct grep_pat *p;
1280 if (opt->extended)
1281 return 0; /* punt for too complex stuff */
1282 if (opt->invert)
1283 return 0;
1284 for (p = opt->pattern_list; p; p = p->next) {
1285 if (p->token != GREP_PATTERN)
1286 return 0; /* punt for "header only" and stuff */
1288 return 1;
1291 static int look_ahead(struct grep_opt *opt,
1292 unsigned long *left_p,
1293 unsigned *lno_p,
1294 char **bol_p)
1296 unsigned lno = *lno_p;
1297 char *bol = *bol_p;
1298 struct grep_pat *p;
1299 char *sp, *last_bol;
1300 regoff_t earliest = -1;
1302 for (p = opt->pattern_list; p; p = p->next) {
1303 int hit;
1304 regmatch_t m;
1306 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1307 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1308 continue;
1309 if (earliest < 0 || m.rm_so < earliest)
1310 earliest = m.rm_so;
1313 if (earliest < 0) {
1314 *bol_p = bol + *left_p;
1315 *left_p = 0;
1316 return 1;
1318 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1319 ; /* find the beginning of the line */
1320 last_bol = sp;
1322 for (sp = bol; sp < last_bol; sp++) {
1323 if (*sp == '\n')
1324 lno++;
1326 *left_p -= last_bol - bol;
1327 *bol_p = last_bol;
1328 *lno_p = lno;
1329 return 0;
1332 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1334 fwrite(buf, size, 1, stdout);
1337 static int fill_textconv_grep(struct userdiff_driver *driver,
1338 struct grep_source *gs)
1340 struct diff_filespec *df;
1341 char *buf;
1342 size_t size;
1344 if (!driver || !driver->textconv)
1345 return grep_source_load(gs);
1348 * The textconv interface is intimately tied to diff_filespecs, so we
1349 * have to pretend to be one. If we could unify the grep_source
1350 * and diff_filespec structs, this mess could just go away.
1352 df = alloc_filespec(gs->path);
1353 switch (gs->type) {
1354 case GREP_SOURCE_SHA1:
1355 fill_filespec(df, gs->identifier, 1, 0100644);
1356 break;
1357 case GREP_SOURCE_FILE:
1358 fill_filespec(df, null_sha1, 0, 0100644);
1359 break;
1360 default:
1361 die("BUG: attempt to textconv something without a path?");
1365 * fill_textconv is not remotely thread-safe; it may load objects
1366 * behind the scenes, and it modifies the global diff tempfile
1367 * structure.
1369 grep_read_lock();
1370 size = fill_textconv(driver, df, &buf);
1371 grep_read_unlock();
1372 free_filespec(df);
1375 * The normal fill_textconv usage by the diff machinery would just keep
1376 * the textconv'd buf separate from the diff_filespec. But much of the
1377 * grep code passes around a grep_source and assumes that its "buf"
1378 * pointer is the beginning of the thing we are searching. So let's
1379 * install our textconv'd version into the grep_source, taking care not
1380 * to leak any existing buffer.
1382 grep_source_clear_data(gs);
1383 gs->buf = buf;
1384 gs->size = size;
1386 return 0;
1389 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1391 char *bol;
1392 unsigned long left;
1393 unsigned lno = 1;
1394 unsigned last_hit = 0;
1395 int binary_match_only = 0;
1396 unsigned count = 0;
1397 int try_lookahead = 0;
1398 int show_function = 0;
1399 struct userdiff_driver *textconv = NULL;
1400 enum grep_context ctx = GREP_CONTEXT_HEAD;
1401 xdemitconf_t xecfg;
1403 if (!opt->output)
1404 opt->output = std_output;
1406 if (opt->pre_context || opt->post_context || opt->file_break ||
1407 opt->funcbody) {
1408 /* Show hunk marks, except for the first file. */
1409 if (opt->last_shown)
1410 opt->show_hunk_mark = 1;
1412 * If we're using threads then we can't easily identify
1413 * the first file. Always put hunk marks in that case
1414 * and skip the very first one later in work_done().
1416 if (opt->output != std_output)
1417 opt->show_hunk_mark = 1;
1419 opt->last_shown = 0;
1421 if (opt->allow_textconv) {
1422 grep_source_load_driver(gs);
1424 * We might set up the shared textconv cache data here, which
1425 * is not thread-safe.
1427 grep_attr_lock();
1428 textconv = userdiff_get_textconv(gs->driver);
1429 grep_attr_unlock();
1433 * We know the result of a textconv is text, so we only have to care
1434 * about binary handling if we are not using it.
1436 if (!textconv) {
1437 switch (opt->binary) {
1438 case GREP_BINARY_DEFAULT:
1439 if (grep_source_is_binary(gs))
1440 binary_match_only = 1;
1441 break;
1442 case GREP_BINARY_NOMATCH:
1443 if (grep_source_is_binary(gs))
1444 return 0; /* Assume unmatch */
1445 break;
1446 case GREP_BINARY_TEXT:
1447 break;
1448 default:
1449 die("bug: unknown binary handling mode");
1453 memset(&xecfg, 0, sizeof(xecfg));
1454 opt->priv = &xecfg;
1456 try_lookahead = should_lookahead(opt);
1458 if (fill_textconv_grep(textconv, gs) < 0)
1459 return 0;
1461 bol = gs->buf;
1462 left = gs->size;
1463 while (left) {
1464 char *eol, ch;
1465 int hit;
1468 * look_ahead() skips quickly to the line that possibly
1469 * has the next hit; don't call it if we need to do
1470 * something more than just skipping the current line
1471 * in response to an unmatch for the current line. E.g.
1472 * inside a post-context window, we will show the current
1473 * line as a context around the previous hit when it
1474 * doesn't hit.
1476 if (try_lookahead
1477 && !(last_hit
1478 && (show_function ||
1479 lno <= last_hit + opt->post_context))
1480 && look_ahead(opt, &left, &lno, &bol))
1481 break;
1482 eol = end_of_line(bol, &left);
1483 ch = *eol;
1484 *eol = 0;
1486 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1487 ctx = GREP_CONTEXT_BODY;
1489 hit = match_line(opt, bol, eol, ctx, collect_hits);
1490 *eol = ch;
1492 if (collect_hits)
1493 goto next_line;
1495 /* "grep -v -e foo -e bla" should list lines
1496 * that do not have either, so inversion should
1497 * be done outside.
1499 if (opt->invert)
1500 hit = !hit;
1501 if (opt->unmatch_name_only) {
1502 if (hit)
1503 return 0;
1504 goto next_line;
1506 if (hit) {
1507 count++;
1508 if (opt->status_only)
1509 return 1;
1510 if (opt->name_only) {
1511 show_name(opt, gs->name);
1512 return 1;
1514 if (opt->count)
1515 goto next_line;
1516 if (binary_match_only) {
1517 opt->output(opt, "Binary file ", 12);
1518 output_color(opt, gs->name, strlen(gs->name),
1519 opt->color_filename);
1520 opt->output(opt, " matches\n", 9);
1521 return 1;
1523 /* Hit at this line. If we haven't shown the
1524 * pre-context lines, we would need to show them.
1526 if (opt->pre_context || opt->funcbody)
1527 show_pre_context(opt, gs, bol, eol, lno);
1528 else if (opt->funcname)
1529 show_funcname_line(opt, gs, bol, lno);
1530 show_line(opt, bol, eol, gs->name, lno, ':');
1531 last_hit = lno;
1532 if (opt->funcbody)
1533 show_function = 1;
1534 goto next_line;
1536 if (show_function && match_funcname(opt, gs, bol, eol))
1537 show_function = 0;
1538 if (show_function ||
1539 (last_hit && lno <= last_hit + opt->post_context)) {
1540 /* If the last hit is within the post context,
1541 * we need to show this line.
1543 show_line(opt, bol, eol, gs->name, lno, '-');
1546 next_line:
1547 bol = eol + 1;
1548 if (!left)
1549 break;
1550 left--;
1551 lno++;
1554 if (collect_hits)
1555 return 0;
1557 if (opt->status_only)
1558 return 0;
1559 if (opt->unmatch_name_only) {
1560 /* We did not see any hit, so we want to show this */
1561 show_name(opt, gs->name);
1562 return 1;
1565 xdiff_clear_find_func(&xecfg);
1566 opt->priv = NULL;
1568 /* NEEDSWORK:
1569 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1570 * which feels mostly useless but sometimes useful. Maybe
1571 * make it another option? For now suppress them.
1573 if (opt->count && count) {
1574 char buf[32];
1575 if (opt->pathname) {
1576 output_color(opt, gs->name, strlen(gs->name),
1577 opt->color_filename);
1578 output_sep(opt, ':');
1580 snprintf(buf, sizeof(buf), "%u\n", count);
1581 opt->output(opt, buf, strlen(buf));
1582 return 1;
1584 return !!last_hit;
1587 static void clr_hit_marker(struct grep_expr *x)
1589 /* All-hit markers are meaningful only at the very top level
1590 * OR node.
1592 while (1) {
1593 x->hit = 0;
1594 if (x->node != GREP_NODE_OR)
1595 return;
1596 x->u.binary.left->hit = 0;
1597 x = x->u.binary.right;
1601 static int chk_hit_marker(struct grep_expr *x)
1603 /* Top level nodes have hit markers. See if they all are hits */
1604 while (1) {
1605 if (x->node != GREP_NODE_OR)
1606 return x->hit;
1607 if (!x->u.binary.left->hit)
1608 return 0;
1609 x = x->u.binary.right;
1613 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1616 * we do not have to do the two-pass grep when we do not check
1617 * buffer-wide "all-match".
1619 if (!opt->all_match)
1620 return grep_source_1(opt, gs, 0);
1622 /* Otherwise the toplevel "or" terms hit a bit differently.
1623 * We first clear hit markers from them.
1625 clr_hit_marker(opt->pattern_expression);
1626 grep_source_1(opt, gs, 1);
1628 if (!chk_hit_marker(opt->pattern_expression))
1629 return 0;
1631 return grep_source_1(opt, gs, 0);
1634 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1636 struct grep_source gs;
1637 int r;
1639 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1640 gs.buf = buf;
1641 gs.size = size;
1643 r = grep_source(opt, &gs);
1645 grep_source_clear(&gs);
1646 return r;
1649 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1650 const char *name, const char *path,
1651 const void *identifier)
1653 gs->type = type;
1654 gs->name = xstrdup_or_null(name);
1655 gs->path = xstrdup_or_null(path);
1656 gs->buf = NULL;
1657 gs->size = 0;
1658 gs->driver = NULL;
1660 switch (type) {
1661 case GREP_SOURCE_FILE:
1662 gs->identifier = xstrdup(identifier);
1663 break;
1664 case GREP_SOURCE_SHA1:
1665 gs->identifier = xmalloc(20);
1666 hashcpy(gs->identifier, identifier);
1667 break;
1668 case GREP_SOURCE_BUF:
1669 gs->identifier = NULL;
1673 void grep_source_clear(struct grep_source *gs)
1675 free(gs->name);
1676 gs->name = NULL;
1677 free(gs->path);
1678 gs->path = NULL;
1679 free(gs->identifier);
1680 gs->identifier = NULL;
1681 grep_source_clear_data(gs);
1684 void grep_source_clear_data(struct grep_source *gs)
1686 switch (gs->type) {
1687 case GREP_SOURCE_FILE:
1688 case GREP_SOURCE_SHA1:
1689 free(gs->buf);
1690 gs->buf = NULL;
1691 gs->size = 0;
1692 break;
1693 case GREP_SOURCE_BUF:
1694 /* leave user-provided buf intact */
1695 break;
1699 static int grep_source_load_sha1(struct grep_source *gs)
1701 enum object_type type;
1703 grep_read_lock();
1704 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1705 grep_read_unlock();
1707 if (!gs->buf)
1708 return error(_("'%s': unable to read %s"),
1709 gs->name,
1710 sha1_to_hex(gs->identifier));
1711 return 0;
1714 static int grep_source_load_file(struct grep_source *gs)
1716 const char *filename = gs->identifier;
1717 struct stat st;
1718 char *data;
1719 size_t size;
1720 int i;
1722 if (lstat(filename, &st) < 0) {
1723 err_ret:
1724 if (errno != ENOENT)
1725 error(_("'%s': %s"), filename, strerror(errno));
1726 return -1;
1728 if (!S_ISREG(st.st_mode))
1729 return -1;
1730 size = xsize_t(st.st_size);
1731 i = open(filename, O_RDONLY);
1732 if (i < 0)
1733 goto err_ret;
1734 data = xmallocz(size);
1735 if (st.st_size != read_in_full(i, data, size)) {
1736 error(_("'%s': short read %s"), filename, strerror(errno));
1737 close(i);
1738 free(data);
1739 return -1;
1741 close(i);
1743 gs->buf = data;
1744 gs->size = size;
1745 return 0;
1748 static int grep_source_load(struct grep_source *gs)
1750 if (gs->buf)
1751 return 0;
1753 switch (gs->type) {
1754 case GREP_SOURCE_FILE:
1755 return grep_source_load_file(gs);
1756 case GREP_SOURCE_SHA1:
1757 return grep_source_load_sha1(gs);
1758 case GREP_SOURCE_BUF:
1759 return gs->buf ? 0 : -1;
1761 die("BUG: invalid grep_source type");
1764 void grep_source_load_driver(struct grep_source *gs)
1766 if (gs->driver)
1767 return;
1769 grep_attr_lock();
1770 if (gs->path)
1771 gs->driver = userdiff_find_by_path(gs->path);
1772 if (!gs->driver)
1773 gs->driver = userdiff_find_by_name("default");
1774 grep_attr_unlock();
1777 static int grep_source_is_binary(struct grep_source *gs)
1779 grep_source_load_driver(gs);
1780 if (gs->driver->binary != -1)
1781 return gs->driver->binary;
1783 if (!grep_source_load(gs))
1784 return buffer_is_binary(gs->buf, gs->size);
1786 return 0;