git grep: honor textconv by default
[git/mjg.git] / grep.c
blob161d3f099ac37f433d75306ccd8e3938ea3e3bf0
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 opt->allow_textconv = 1;
35 strcpy(opt->color_context, "");
36 strcpy(opt->color_filename, "");
37 strcpy(opt->color_function, "");
38 strcpy(opt->color_lineno, "");
39 strcpy(opt->color_match, GIT_COLOR_BOLD_RED);
40 strcpy(opt->color_selected, "");
41 strcpy(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, "color.grep"))
91 opt->color = git_config_colorbool(var, value);
92 else if (!strcmp(var, "color.grep.context"))
93 color = opt->color_context;
94 else if (!strcmp(var, "color.grep.filename"))
95 color = opt->color_filename;
96 else if (!strcmp(var, "color.grep.function"))
97 color = opt->color_function;
98 else if (!strcmp(var, "color.grep.linenumber"))
99 color = opt->color_lineno;
100 else if (!strcmp(var, "color.grep.match"))
101 color = opt->color_match;
102 else if (!strcmp(var, "color.grep.selected"))
103 color = opt->color_selected;
104 else if (!strcmp(var, "color.grep.separator"))
105 color = opt->color_sep;
107 if (color) {
108 if (!value)
109 return config_error_nonbool(var);
110 color_parse(value, var, color);
112 return 0;
116 * Initialize one instance of grep_opt and copy the
117 * default values from the template we read the configuration
118 * information in an earlier call to git_config(grep_config).
120 void grep_init(struct grep_opt *opt, const char *prefix)
122 struct grep_opt *def = &grep_defaults;
124 memset(opt, 0, sizeof(*opt));
125 opt->prefix = prefix;
126 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
127 opt->pattern_tail = &opt->pattern_list;
128 opt->header_tail = &opt->header_list;
130 opt->color = def->color;
131 opt->extended_regexp_option = def->extended_regexp_option;
132 opt->pattern_type_option = def->pattern_type_option;
133 opt->linenum = def->linenum;
134 opt->max_depth = def->max_depth;
135 opt->pathname = def->pathname;
136 opt->regflags = def->regflags;
137 opt->relative = def->relative;
138 opt->allow_textconv = def->allow_textconv;
140 strcpy(opt->color_context, def->color_context);
141 strcpy(opt->color_filename, def->color_filename);
142 strcpy(opt->color_function, def->color_function);
143 strcpy(opt->color_lineno, def->color_lineno);
144 strcpy(opt->color_match, def->color_match);
145 strcpy(opt->color_selected, def->color_selected);
146 strcpy(opt->color_sep, def->color_sep);
149 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
151 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
152 grep_set_pattern_type_option(pattern_type, opt);
153 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
154 grep_set_pattern_type_option(opt->pattern_type_option, opt);
155 else if (opt->extended_regexp_option)
156 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
159 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
161 switch (pattern_type) {
162 case GREP_PATTERN_TYPE_UNSPECIFIED:
163 /* fall through */
165 case GREP_PATTERN_TYPE_BRE:
166 opt->fixed = 0;
167 opt->pcre = 0;
168 opt->regflags &= ~REG_EXTENDED;
169 break;
171 case GREP_PATTERN_TYPE_ERE:
172 opt->fixed = 0;
173 opt->pcre = 0;
174 opt->regflags |= REG_EXTENDED;
175 break;
177 case GREP_PATTERN_TYPE_FIXED:
178 opt->fixed = 1;
179 opt->pcre = 0;
180 opt->regflags &= ~REG_EXTENDED;
181 break;
183 case GREP_PATTERN_TYPE_PCRE:
184 opt->fixed = 0;
185 opt->pcre = 1;
186 opt->regflags &= ~REG_EXTENDED;
187 break;
191 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
192 const char *origin, int no,
193 enum grep_pat_token t,
194 enum grep_header_field field)
196 struct grep_pat *p = xcalloc(1, sizeof(*p));
197 p->pattern = xmemdupz(pat, patlen);
198 p->patternlen = patlen;
199 p->origin = origin;
200 p->no = no;
201 p->token = t;
202 p->field = field;
203 return p;
206 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
208 **tail = p;
209 *tail = &p->next;
210 p->next = NULL;
212 switch (p->token) {
213 case GREP_PATTERN: /* atom */
214 case GREP_PATTERN_HEAD:
215 case GREP_PATTERN_BODY:
216 for (;;) {
217 struct grep_pat *new_pat;
218 size_t len = 0;
219 char *cp = p->pattern + p->patternlen, *nl = NULL;
220 while (++len <= p->patternlen) {
221 if (*(--cp) == '\n') {
222 nl = cp;
223 break;
226 if (!nl)
227 break;
228 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
229 p->no, p->token, p->field);
230 new_pat->next = p->next;
231 if (!p->next)
232 *tail = &new_pat->next;
233 p->next = new_pat;
234 *nl = '\0';
235 p->patternlen -= len;
237 break;
238 default:
239 break;
243 void append_header_grep_pattern(struct grep_opt *opt,
244 enum grep_header_field field, const char *pat)
246 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
247 GREP_PATTERN_HEAD, field);
248 if (field == GREP_HEADER_REFLOG)
249 opt->use_reflog_filter = 1;
250 do_append_grep_pat(&opt->header_tail, p);
253 void append_grep_pattern(struct grep_opt *opt, const char *pat,
254 const char *origin, int no, enum grep_pat_token t)
256 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
259 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
260 const char *origin, int no, enum grep_pat_token t)
262 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
263 do_append_grep_pat(&opt->pattern_tail, p);
266 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
268 struct grep_pat *pat;
269 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
270 *ret = *opt;
272 ret->pattern_list = NULL;
273 ret->pattern_tail = &ret->pattern_list;
275 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
277 if(pat->token == GREP_PATTERN_HEAD)
278 append_header_grep_pattern(ret, pat->field,
279 pat->pattern);
280 else
281 append_grep_pat(ret, pat->pattern, pat->patternlen,
282 pat->origin, pat->no, pat->token);
285 return ret;
288 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
289 const char *error)
291 char where[1024];
293 if (p->no)
294 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
295 else if (p->origin)
296 sprintf(where, "%s, ", p->origin);
297 else
298 where[0] = 0;
300 die("%s'%s': %s", where, p->pattern, error);
303 #ifdef USE_LIBPCRE
304 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
306 const char *error;
307 int erroffset;
308 int options = PCRE_MULTILINE;
310 if (opt->ignore_case)
311 options |= PCRE_CASELESS;
313 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
314 NULL);
315 if (!p->pcre_regexp)
316 compile_regexp_failed(p, error);
318 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
319 if (!p->pcre_extra_info && error)
320 die("%s", error);
323 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
324 regmatch_t *match, int eflags)
326 int ovector[30], ret, flags = 0;
328 if (eflags & REG_NOTBOL)
329 flags |= PCRE_NOTBOL;
331 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
332 0, flags, ovector, ARRAY_SIZE(ovector));
333 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
334 die("pcre_exec failed with error code %d", ret);
335 if (ret > 0) {
336 ret = 0;
337 match->rm_so = ovector[0];
338 match->rm_eo = ovector[1];
341 return ret;
344 static void free_pcre_regexp(struct grep_pat *p)
346 pcre_free(p->pcre_regexp);
347 pcre_free(p->pcre_extra_info);
349 #else /* !USE_LIBPCRE */
350 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
352 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
355 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
356 regmatch_t *match, int eflags)
358 return 1;
361 static void free_pcre_regexp(struct grep_pat *p)
364 #endif /* !USE_LIBPCRE */
366 static int is_fixed(const char *s, size_t len)
368 size_t i;
370 /* regcomp cannot accept patterns with NULs so we
371 * consider any pattern containing a NUL fixed.
373 if (memchr(s, 0, len))
374 return 1;
376 for (i = 0; i < len; i++) {
377 if (is_regex_special(s[i]))
378 return 0;
381 return 1;
384 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
386 int err;
388 p->word_regexp = opt->word_regexp;
389 p->ignore_case = opt->ignore_case;
391 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
392 p->fixed = 1;
393 else
394 p->fixed = 0;
396 if (p->fixed) {
397 if (opt->regflags & REG_ICASE || p->ignore_case)
398 p->kws = kwsalloc(tolower_trans_tbl);
399 else
400 p->kws = kwsalloc(NULL);
401 kwsincr(p->kws, p->pattern, p->patternlen);
402 kwsprep(p->kws);
403 return;
406 if (opt->pcre) {
407 compile_pcre_regexp(p, opt);
408 return;
411 err = regcomp(&p->regexp, p->pattern, opt->regflags);
412 if (err) {
413 char errbuf[1024];
414 regerror(err, &p->regexp, errbuf, 1024);
415 regfree(&p->regexp);
416 compile_regexp_failed(p, errbuf);
420 static struct grep_expr *compile_pattern_or(struct grep_pat **);
421 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
423 struct grep_pat *p;
424 struct grep_expr *x;
426 p = *list;
427 if (!p)
428 return NULL;
429 switch (p->token) {
430 case GREP_PATTERN: /* atom */
431 case GREP_PATTERN_HEAD:
432 case GREP_PATTERN_BODY:
433 x = xcalloc(1, sizeof (struct grep_expr));
434 x->node = GREP_NODE_ATOM;
435 x->u.atom = p;
436 *list = p->next;
437 return x;
438 case GREP_OPEN_PAREN:
439 *list = p->next;
440 x = compile_pattern_or(list);
441 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
442 die("unmatched parenthesis");
443 *list = (*list)->next;
444 return x;
445 default:
446 return NULL;
450 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
452 struct grep_pat *p;
453 struct grep_expr *x;
455 p = *list;
456 if (!p)
457 return NULL;
458 switch (p->token) {
459 case GREP_NOT:
460 if (!p->next)
461 die("--not not followed by pattern expression");
462 *list = p->next;
463 x = xcalloc(1, sizeof (struct grep_expr));
464 x->node = GREP_NODE_NOT;
465 x->u.unary = compile_pattern_not(list);
466 if (!x->u.unary)
467 die("--not followed by non pattern expression");
468 return x;
469 default:
470 return compile_pattern_atom(list);
474 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
476 struct grep_pat *p;
477 struct grep_expr *x, *y, *z;
479 x = compile_pattern_not(list);
480 p = *list;
481 if (p && p->token == GREP_AND) {
482 if (!p->next)
483 die("--and not followed by pattern expression");
484 *list = p->next;
485 y = compile_pattern_and(list);
486 if (!y)
487 die("--and not followed by pattern expression");
488 z = xcalloc(1, sizeof (struct grep_expr));
489 z->node = GREP_NODE_AND;
490 z->u.binary.left = x;
491 z->u.binary.right = y;
492 return z;
494 return x;
497 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
499 struct grep_pat *p;
500 struct grep_expr *x, *y, *z;
502 x = compile_pattern_and(list);
503 p = *list;
504 if (x && p && p->token != GREP_CLOSE_PAREN) {
505 y = compile_pattern_or(list);
506 if (!y)
507 die("not a pattern expression %s", p->pattern);
508 z = xcalloc(1, sizeof (struct grep_expr));
509 z->node = GREP_NODE_OR;
510 z->u.binary.left = x;
511 z->u.binary.right = y;
512 return z;
514 return x;
517 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
519 return compile_pattern_or(list);
522 static void indent(int in)
524 while (in-- > 0)
525 fputc(' ', stderr);
528 static void dump_grep_pat(struct grep_pat *p)
530 switch (p->token) {
531 case GREP_AND: fprintf(stderr, "*and*"); break;
532 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
533 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
534 case GREP_NOT: fprintf(stderr, "*not*"); break;
535 case GREP_OR: fprintf(stderr, "*or*"); break;
537 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
538 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
539 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
542 switch (p->token) {
543 default: break;
544 case GREP_PATTERN_HEAD:
545 fprintf(stderr, "<head %d>", p->field); break;
546 case GREP_PATTERN_BODY:
547 fprintf(stderr, "<body>"); break;
549 switch (p->token) {
550 default: break;
551 case GREP_PATTERN_HEAD:
552 case GREP_PATTERN_BODY:
553 case GREP_PATTERN:
554 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
555 break;
557 fputc('\n', stderr);
560 static void dump_grep_expression_1(struct grep_expr *x, int in)
562 indent(in);
563 switch (x->node) {
564 case GREP_NODE_TRUE:
565 fprintf(stderr, "true\n");
566 break;
567 case GREP_NODE_ATOM:
568 dump_grep_pat(x->u.atom);
569 break;
570 case GREP_NODE_NOT:
571 fprintf(stderr, "(not\n");
572 dump_grep_expression_1(x->u.unary, in+1);
573 indent(in);
574 fprintf(stderr, ")\n");
575 break;
576 case GREP_NODE_AND:
577 fprintf(stderr, "(and\n");
578 dump_grep_expression_1(x->u.binary.left, in+1);
579 dump_grep_expression_1(x->u.binary.right, in+1);
580 indent(in);
581 fprintf(stderr, ")\n");
582 break;
583 case GREP_NODE_OR:
584 fprintf(stderr, "(or\n");
585 dump_grep_expression_1(x->u.binary.left, in+1);
586 dump_grep_expression_1(x->u.binary.right, in+1);
587 indent(in);
588 fprintf(stderr, ")\n");
589 break;
593 static void dump_grep_expression(struct grep_opt *opt)
595 struct grep_expr *x = opt->pattern_expression;
597 if (opt->all_match)
598 fprintf(stderr, "[all-match]\n");
599 dump_grep_expression_1(x, 0);
600 fflush(NULL);
603 static struct grep_expr *grep_true_expr(void)
605 struct grep_expr *z = xcalloc(1, sizeof(*z));
606 z->node = GREP_NODE_TRUE;
607 return z;
610 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
612 struct grep_expr *z = xcalloc(1, sizeof(*z));
613 z->node = GREP_NODE_OR;
614 z->u.binary.left = left;
615 z->u.binary.right = right;
616 return z;
619 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
621 struct grep_pat *p;
622 struct grep_expr *header_expr;
623 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
624 enum grep_header_field fld;
626 if (!opt->header_list)
627 return NULL;
629 for (p = opt->header_list; p; p = p->next) {
630 if (p->token != GREP_PATTERN_HEAD)
631 die("bug: a non-header pattern in grep header list.");
632 if (p->field < GREP_HEADER_FIELD_MIN ||
633 GREP_HEADER_FIELD_MAX <= p->field)
634 die("bug: unknown header field %d", p->field);
635 compile_regexp(p, opt);
638 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
639 header_group[fld] = NULL;
641 for (p = opt->header_list; p; p = p->next) {
642 struct grep_expr *h;
643 struct grep_pat *pp = p;
645 h = compile_pattern_atom(&pp);
646 if (!h || pp != p->next)
647 die("bug: malformed header expr");
648 if (!header_group[p->field]) {
649 header_group[p->field] = h;
650 continue;
652 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
655 header_expr = NULL;
657 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
658 if (!header_group[fld])
659 continue;
660 if (!header_expr)
661 header_expr = grep_true_expr();
662 header_expr = grep_or_expr(header_group[fld], header_expr);
664 return header_expr;
667 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
669 struct grep_expr *z = x;
671 while (x) {
672 assert(x->node == GREP_NODE_OR);
673 if (x->u.binary.right &&
674 x->u.binary.right->node == GREP_NODE_TRUE) {
675 x->u.binary.right = y;
676 break;
678 x = x->u.binary.right;
680 return z;
683 static void compile_grep_patterns_real(struct grep_opt *opt)
685 struct grep_pat *p;
686 struct grep_expr *header_expr = prep_header_patterns(opt);
688 for (p = opt->pattern_list; p; p = p->next) {
689 switch (p->token) {
690 case GREP_PATTERN: /* atom */
691 case GREP_PATTERN_HEAD:
692 case GREP_PATTERN_BODY:
693 compile_regexp(p, opt);
694 break;
695 default:
696 opt->extended = 1;
697 break;
701 if (opt->all_match || header_expr)
702 opt->extended = 1;
703 else if (!opt->extended && !opt->debug)
704 return;
706 p = opt->pattern_list;
707 if (p)
708 opt->pattern_expression = compile_pattern_expr(&p);
709 if (p)
710 die("incomplete pattern expression: %s", p->pattern);
712 if (!header_expr)
713 return;
715 if (!opt->pattern_expression)
716 opt->pattern_expression = header_expr;
717 else if (opt->all_match)
718 opt->pattern_expression = grep_splice_or(header_expr,
719 opt->pattern_expression);
720 else
721 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
722 header_expr);
723 opt->all_match = 1;
726 void compile_grep_patterns(struct grep_opt *opt)
728 compile_grep_patterns_real(opt);
729 if (opt->debug)
730 dump_grep_expression(opt);
733 static void free_pattern_expr(struct grep_expr *x)
735 switch (x->node) {
736 case GREP_NODE_TRUE:
737 case GREP_NODE_ATOM:
738 break;
739 case GREP_NODE_NOT:
740 free_pattern_expr(x->u.unary);
741 break;
742 case GREP_NODE_AND:
743 case GREP_NODE_OR:
744 free_pattern_expr(x->u.binary.left);
745 free_pattern_expr(x->u.binary.right);
746 break;
748 free(x);
751 void free_grep_patterns(struct grep_opt *opt)
753 struct grep_pat *p, *n;
755 for (p = opt->pattern_list; p; p = n) {
756 n = p->next;
757 switch (p->token) {
758 case GREP_PATTERN: /* atom */
759 case GREP_PATTERN_HEAD:
760 case GREP_PATTERN_BODY:
761 if (p->kws)
762 kwsfree(p->kws);
763 else if (p->pcre_regexp)
764 free_pcre_regexp(p);
765 else
766 regfree(&p->regexp);
767 free(p->pattern);
768 break;
769 default:
770 break;
772 free(p);
775 if (!opt->extended)
776 return;
777 free_pattern_expr(opt->pattern_expression);
780 static char *end_of_line(char *cp, unsigned long *left)
782 unsigned long l = *left;
783 while (l && *cp != '\n') {
784 l--;
785 cp++;
787 *left = l;
788 return cp;
791 static int word_char(char ch)
793 return isalnum(ch) || ch == '_';
796 static void output_color(struct grep_opt *opt, const void *data, size_t size,
797 const char *color)
799 if (want_color(opt->color) && color && color[0]) {
800 opt->output(opt, color, strlen(color));
801 opt->output(opt, data, size);
802 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
803 } else
804 opt->output(opt, data, size);
807 static void output_sep(struct grep_opt *opt, char sign)
809 if (opt->null_following_name)
810 opt->output(opt, "\0", 1);
811 else
812 output_color(opt, &sign, 1, opt->color_sep);
815 static void show_name(struct grep_opt *opt, const char *name)
817 output_color(opt, name, strlen(name), opt->color_filename);
818 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
821 static int fixmatch(struct grep_pat *p, char *line, char *eol,
822 regmatch_t *match)
824 struct kwsmatch kwsm;
825 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
826 if (offset == -1) {
827 match->rm_so = match->rm_eo = -1;
828 return REG_NOMATCH;
829 } else {
830 match->rm_so = offset;
831 match->rm_eo = match->rm_so + kwsm.size[0];
832 return 0;
836 static int regmatch(const regex_t *preg, char *line, char *eol,
837 regmatch_t *match, int eflags)
839 #ifdef REG_STARTEND
840 match->rm_so = 0;
841 match->rm_eo = eol - line;
842 eflags |= REG_STARTEND;
843 #endif
844 return regexec(preg, line, 1, match, eflags);
847 static int patmatch(struct grep_pat *p, char *line, char *eol,
848 regmatch_t *match, int eflags)
850 int hit;
852 if (p->fixed)
853 hit = !fixmatch(p, line, eol, match);
854 else if (p->pcre_regexp)
855 hit = !pcrematch(p, line, eol, match, eflags);
856 else
857 hit = !regmatch(&p->regexp, line, eol, match, eflags);
859 return hit;
862 static int strip_timestamp(char *bol, char **eol_p)
864 char *eol = *eol_p;
865 int ch;
867 while (bol < --eol) {
868 if (*eol != '>')
869 continue;
870 *eol_p = ++eol;
871 ch = *eol;
872 *eol = '\0';
873 return ch;
875 return 0;
878 static struct {
879 const char *field;
880 size_t len;
881 } header_field[] = {
882 { "author ", 7 },
883 { "committer ", 10 },
884 { "reflog ", 7 },
887 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
888 enum grep_context ctx,
889 regmatch_t *pmatch, int eflags)
891 int hit = 0;
892 int saved_ch = 0;
893 const char *start = bol;
895 if ((p->token != GREP_PATTERN) &&
896 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
897 return 0;
899 if (p->token == GREP_PATTERN_HEAD) {
900 const char *field;
901 size_t len;
902 assert(p->field < ARRAY_SIZE(header_field));
903 field = header_field[p->field].field;
904 len = header_field[p->field].len;
905 if (strncmp(bol, field, len))
906 return 0;
907 bol += len;
908 switch (p->field) {
909 case GREP_HEADER_AUTHOR:
910 case GREP_HEADER_COMMITTER:
911 saved_ch = strip_timestamp(bol, &eol);
912 break;
913 default:
914 break;
918 again:
919 hit = patmatch(p, bol, eol, pmatch, eflags);
921 if (hit && p->word_regexp) {
922 if ((pmatch[0].rm_so < 0) ||
923 (eol - bol) < pmatch[0].rm_so ||
924 (pmatch[0].rm_eo < 0) ||
925 (eol - bol) < pmatch[0].rm_eo)
926 die("regexp returned nonsense");
928 /* Match beginning must be either beginning of the
929 * line, or at word boundary (i.e. the last char must
930 * not be a word char). Similarly, match end must be
931 * either end of the line, or at word boundary
932 * (i.e. the next char must not be a word char).
934 if ( ((pmatch[0].rm_so == 0) ||
935 !word_char(bol[pmatch[0].rm_so-1])) &&
936 ((pmatch[0].rm_eo == (eol-bol)) ||
937 !word_char(bol[pmatch[0].rm_eo])) )
939 else
940 hit = 0;
942 /* Words consist of at least one character. */
943 if (pmatch->rm_so == pmatch->rm_eo)
944 hit = 0;
946 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
947 /* There could be more than one match on the
948 * line, and the first match might not be
949 * strict word match. But later ones could be!
950 * Forward to the next possible start, i.e. the
951 * next position following a non-word char.
953 bol = pmatch[0].rm_so + bol + 1;
954 while (word_char(bol[-1]) && bol < eol)
955 bol++;
956 eflags |= REG_NOTBOL;
957 if (bol < eol)
958 goto again;
961 if (p->token == GREP_PATTERN_HEAD && saved_ch)
962 *eol = saved_ch;
963 if (hit) {
964 pmatch[0].rm_so += bol - start;
965 pmatch[0].rm_eo += bol - start;
967 return hit;
970 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
971 enum grep_context ctx, int collect_hits)
973 int h = 0;
974 regmatch_t match;
976 if (!x)
977 die("Not a valid grep expression");
978 switch (x->node) {
979 case GREP_NODE_TRUE:
980 h = 1;
981 break;
982 case GREP_NODE_ATOM:
983 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
984 break;
985 case GREP_NODE_NOT:
986 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
987 break;
988 case GREP_NODE_AND:
989 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
990 return 0;
991 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
992 break;
993 case GREP_NODE_OR:
994 if (!collect_hits)
995 return (match_expr_eval(x->u.binary.left,
996 bol, eol, ctx, 0) ||
997 match_expr_eval(x->u.binary.right,
998 bol, eol, ctx, 0));
999 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1000 x->u.binary.left->hit |= h;
1001 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1002 break;
1003 default:
1004 die("Unexpected node type (internal error) %d", x->node);
1006 if (collect_hits)
1007 x->hit |= h;
1008 return h;
1011 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1012 enum grep_context ctx, int collect_hits)
1014 struct grep_expr *x = opt->pattern_expression;
1015 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1018 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1019 enum grep_context ctx, int collect_hits)
1021 struct grep_pat *p;
1022 regmatch_t match;
1024 if (opt->extended)
1025 return match_expr(opt, bol, eol, ctx, collect_hits);
1027 /* we do not call with collect_hits without being extended */
1028 for (p = opt->pattern_list; p; p = p->next) {
1029 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1030 return 1;
1032 return 0;
1035 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1036 enum grep_context ctx,
1037 regmatch_t *pmatch, int eflags)
1039 regmatch_t match;
1041 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1042 return 0;
1043 if (match.rm_so < 0 || match.rm_eo < 0)
1044 return 0;
1045 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1046 if (match.rm_so > pmatch->rm_so)
1047 return 1;
1048 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1049 return 1;
1051 pmatch->rm_so = match.rm_so;
1052 pmatch->rm_eo = match.rm_eo;
1053 return 1;
1056 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1057 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1059 struct grep_pat *p;
1060 int hit = 0;
1062 pmatch->rm_so = pmatch->rm_eo = -1;
1063 if (bol < eol) {
1064 for (p = opt->pattern_list; p; p = p->next) {
1065 switch (p->token) {
1066 case GREP_PATTERN: /* atom */
1067 case GREP_PATTERN_HEAD:
1068 case GREP_PATTERN_BODY:
1069 hit |= match_next_pattern(p, bol, eol, ctx,
1070 pmatch, eflags);
1071 break;
1072 default:
1073 break;
1077 return hit;
1080 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1081 const char *name, unsigned lno, char sign)
1083 int rest = eol - bol;
1084 char *line_color = NULL;
1086 if (opt->file_break && opt->last_shown == 0) {
1087 if (opt->show_hunk_mark)
1088 opt->output(opt, "\n", 1);
1089 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1090 if (opt->last_shown == 0) {
1091 if (opt->show_hunk_mark) {
1092 output_color(opt, "--", 2, opt->color_sep);
1093 opt->output(opt, "\n", 1);
1095 } else if (lno > opt->last_shown + 1) {
1096 output_color(opt, "--", 2, opt->color_sep);
1097 opt->output(opt, "\n", 1);
1100 if (opt->heading && opt->last_shown == 0) {
1101 output_color(opt, name, strlen(name), opt->color_filename);
1102 opt->output(opt, "\n", 1);
1104 opt->last_shown = lno;
1106 if (!opt->heading && opt->pathname) {
1107 output_color(opt, name, strlen(name), opt->color_filename);
1108 output_sep(opt, sign);
1110 if (opt->linenum) {
1111 char buf[32];
1112 snprintf(buf, sizeof(buf), "%d", lno);
1113 output_color(opt, buf, strlen(buf), opt->color_lineno);
1114 output_sep(opt, sign);
1116 if (opt->color) {
1117 regmatch_t match;
1118 enum grep_context ctx = GREP_CONTEXT_BODY;
1119 int ch = *eol;
1120 int eflags = 0;
1122 if (sign == ':')
1123 line_color = opt->color_selected;
1124 else if (sign == '-')
1125 line_color = opt->color_context;
1126 else if (sign == '=')
1127 line_color = opt->color_function;
1128 *eol = '\0';
1129 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1130 if (match.rm_so == match.rm_eo)
1131 break;
1133 output_color(opt, bol, match.rm_so, line_color);
1134 output_color(opt, bol + match.rm_so,
1135 match.rm_eo - match.rm_so,
1136 opt->color_match);
1137 bol += match.rm_eo;
1138 rest -= match.rm_eo;
1139 eflags = REG_NOTBOL;
1141 *eol = ch;
1143 output_color(opt, bol, rest, line_color);
1144 opt->output(opt, "\n", 1);
1147 #ifndef NO_PTHREADS
1148 int grep_use_locks;
1151 * This lock protects access to the gitattributes machinery, which is
1152 * not thread-safe.
1154 pthread_mutex_t grep_attr_mutex;
1156 static inline void grep_attr_lock(void)
1158 if (grep_use_locks)
1159 pthread_mutex_lock(&grep_attr_mutex);
1162 static inline void grep_attr_unlock(void)
1164 if (grep_use_locks)
1165 pthread_mutex_unlock(&grep_attr_mutex);
1169 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1171 pthread_mutex_t grep_read_mutex;
1173 #else
1174 #define grep_attr_lock()
1175 #define grep_attr_unlock()
1176 #endif
1178 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1180 xdemitconf_t *xecfg = opt->priv;
1181 if (xecfg && !xecfg->find_func) {
1182 grep_source_load_driver(gs);
1183 if (gs->driver->funcname.pattern) {
1184 const struct userdiff_funcname *pe = &gs->driver->funcname;
1185 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1186 } else {
1187 xecfg = opt->priv = NULL;
1191 if (xecfg) {
1192 char buf[1];
1193 return xecfg->find_func(bol, eol - bol, buf, 1,
1194 xecfg->find_func_priv) >= 0;
1197 if (bol == eol)
1198 return 0;
1199 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1200 return 1;
1201 return 0;
1204 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1205 char *bol, unsigned lno)
1207 while (bol > gs->buf) {
1208 char *eol = --bol;
1210 while (bol > gs->buf && bol[-1] != '\n')
1211 bol--;
1212 lno--;
1214 if (lno <= opt->last_shown)
1215 break;
1217 if (match_funcname(opt, gs, bol, eol)) {
1218 show_line(opt, bol, eol, gs->name, lno, '=');
1219 break;
1224 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1225 char *bol, char *end, unsigned lno)
1227 unsigned cur = lno, from = 1, funcname_lno = 0;
1228 int funcname_needed = !!opt->funcname;
1230 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1231 funcname_needed = 2;
1233 if (opt->pre_context < lno)
1234 from = lno - opt->pre_context;
1235 if (from <= opt->last_shown)
1236 from = opt->last_shown + 1;
1238 /* Rewind. */
1239 while (bol > gs->buf &&
1240 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1241 char *eol = --bol;
1243 while (bol > gs->buf && bol[-1] != '\n')
1244 bol--;
1245 cur--;
1246 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1247 funcname_lno = cur;
1248 funcname_needed = 0;
1252 /* We need to look even further back to find a function signature. */
1253 if (opt->funcname && funcname_needed)
1254 show_funcname_line(opt, gs, bol, cur);
1256 /* Back forward. */
1257 while (cur < lno) {
1258 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1260 while (*eol != '\n')
1261 eol++;
1262 show_line(opt, bol, eol, gs->name, cur, sign);
1263 bol = eol + 1;
1264 cur++;
1268 static int should_lookahead(struct grep_opt *opt)
1270 struct grep_pat *p;
1272 if (opt->extended)
1273 return 0; /* punt for too complex stuff */
1274 if (opt->invert)
1275 return 0;
1276 for (p = opt->pattern_list; p; p = p->next) {
1277 if (p->token != GREP_PATTERN)
1278 return 0; /* punt for "header only" and stuff */
1280 return 1;
1283 static int look_ahead(struct grep_opt *opt,
1284 unsigned long *left_p,
1285 unsigned *lno_p,
1286 char **bol_p)
1288 unsigned lno = *lno_p;
1289 char *bol = *bol_p;
1290 struct grep_pat *p;
1291 char *sp, *last_bol;
1292 regoff_t earliest = -1;
1294 for (p = opt->pattern_list; p; p = p->next) {
1295 int hit;
1296 regmatch_t m;
1298 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1299 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1300 continue;
1301 if (earliest < 0 || m.rm_so < earliest)
1302 earliest = m.rm_so;
1305 if (earliest < 0) {
1306 *bol_p = bol + *left_p;
1307 *left_p = 0;
1308 return 1;
1310 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1311 ; /* find the beginning of the line */
1312 last_bol = sp;
1314 for (sp = bol; sp < last_bol; sp++) {
1315 if (*sp == '\n')
1316 lno++;
1318 *left_p -= last_bol - bol;
1319 *bol_p = last_bol;
1320 *lno_p = lno;
1321 return 0;
1324 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1326 fwrite(buf, size, 1, stdout);
1329 static int fill_textconv_grep(struct userdiff_driver *driver,
1330 struct grep_source *gs)
1332 struct diff_filespec *df;
1333 char *buf;
1334 size_t size;
1336 if (!driver || !driver->textconv)
1337 return grep_source_load(gs);
1340 * The textconv interface is intimately tied to diff_filespecs, so we
1341 * have to pretend to be one. If we could unify the grep_source
1342 * and diff_filespec structs, this mess could just go away.
1344 df = alloc_filespec(gs->path);
1345 switch (gs->type) {
1346 case GREP_SOURCE_SHA1:
1347 fill_filespec(df, gs->identifier, 1, 0100644);
1348 break;
1349 case GREP_SOURCE_FILE:
1350 fill_filespec(df, null_sha1, 0, 0100644);
1351 break;
1352 default:
1353 die("BUG: attempt to textconv something without a path?");
1357 * fill_textconv is not remotely thread-safe; it may load objects
1358 * behind the scenes, and it modifies the global diff tempfile
1359 * structure.
1361 grep_read_lock();
1362 size = fill_textconv(driver, df, &buf);
1363 grep_read_unlock();
1364 free_filespec(df);
1367 * The normal fill_textconv usage by the diff machinery would just keep
1368 * the textconv'd buf separate from the diff_filespec. But much of the
1369 * grep code passes around a grep_source and assumes that its "buf"
1370 * pointer is the beginning of the thing we are searching. So let's
1371 * install our textconv'd version into the grep_source, taking care not
1372 * to leak any existing buffer.
1374 grep_source_clear_data(gs);
1375 gs->buf = buf;
1376 gs->size = size;
1378 return 0;
1381 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1383 char *bol;
1384 unsigned long left;
1385 unsigned lno = 1;
1386 unsigned last_hit = 0;
1387 int binary_match_only = 0;
1388 unsigned count = 0;
1389 int try_lookahead = 0;
1390 int show_function = 0;
1391 struct userdiff_driver *textconv = NULL;
1392 enum grep_context ctx = GREP_CONTEXT_HEAD;
1393 xdemitconf_t xecfg;
1395 if (!opt->output)
1396 opt->output = std_output;
1398 if (opt->pre_context || opt->post_context || opt->file_break ||
1399 opt->funcbody) {
1400 /* Show hunk marks, except for the first file. */
1401 if (opt->last_shown)
1402 opt->show_hunk_mark = 1;
1404 * If we're using threads then we can't easily identify
1405 * the first file. Always put hunk marks in that case
1406 * and skip the very first one later in work_done().
1408 if (opt->output != std_output)
1409 opt->show_hunk_mark = 1;
1411 opt->last_shown = 0;
1413 if (opt->allow_textconv) {
1414 grep_source_load_driver(gs);
1416 * We might set up the shared textconv cache data here, which
1417 * is not thread-safe.
1419 grep_attr_lock();
1420 textconv = userdiff_get_textconv(gs->driver);
1421 grep_attr_unlock();
1425 * We know the result of a textconv is text, so we only have to care
1426 * about binary handling if we are not using it.
1428 if (!textconv) {
1429 switch (opt->binary) {
1430 case GREP_BINARY_DEFAULT:
1431 if (grep_source_is_binary(gs))
1432 binary_match_only = 1;
1433 break;
1434 case GREP_BINARY_NOMATCH:
1435 if (grep_source_is_binary(gs))
1436 return 0; /* Assume unmatch */
1437 break;
1438 case GREP_BINARY_TEXT:
1439 break;
1440 default:
1441 die("bug: unknown binary handling mode");
1445 memset(&xecfg, 0, sizeof(xecfg));
1446 opt->priv = &xecfg;
1448 try_lookahead = should_lookahead(opt);
1450 if (fill_textconv_grep(textconv, gs) < 0)
1451 return 0;
1453 bol = gs->buf;
1454 left = gs->size;
1455 while (left) {
1456 char *eol, ch;
1457 int hit;
1460 * look_ahead() skips quickly to the line that possibly
1461 * has the next hit; don't call it if we need to do
1462 * something more than just skipping the current line
1463 * in response to an unmatch for the current line. E.g.
1464 * inside a post-context window, we will show the current
1465 * line as a context around the previous hit when it
1466 * doesn't hit.
1468 if (try_lookahead
1469 && !(last_hit
1470 && (show_function ||
1471 lno <= last_hit + opt->post_context))
1472 && look_ahead(opt, &left, &lno, &bol))
1473 break;
1474 eol = end_of_line(bol, &left);
1475 ch = *eol;
1476 *eol = 0;
1478 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1479 ctx = GREP_CONTEXT_BODY;
1481 hit = match_line(opt, bol, eol, ctx, collect_hits);
1482 *eol = ch;
1484 if (collect_hits)
1485 goto next_line;
1487 /* "grep -v -e foo -e bla" should list lines
1488 * that do not have either, so inversion should
1489 * be done outside.
1491 if (opt->invert)
1492 hit = !hit;
1493 if (opt->unmatch_name_only) {
1494 if (hit)
1495 return 0;
1496 goto next_line;
1498 if (hit) {
1499 count++;
1500 if (opt->status_only)
1501 return 1;
1502 if (opt->name_only) {
1503 show_name(opt, gs->name);
1504 return 1;
1506 if (opt->count)
1507 goto next_line;
1508 if (binary_match_only) {
1509 opt->output(opt, "Binary file ", 12);
1510 output_color(opt, gs->name, strlen(gs->name),
1511 opt->color_filename);
1512 opt->output(opt, " matches\n", 9);
1513 return 1;
1515 /* Hit at this line. If we haven't shown the
1516 * pre-context lines, we would need to show them.
1518 if (opt->pre_context || opt->funcbody)
1519 show_pre_context(opt, gs, bol, eol, lno);
1520 else if (opt->funcname)
1521 show_funcname_line(opt, gs, bol, lno);
1522 show_line(opt, bol, eol, gs->name, lno, ':');
1523 last_hit = lno;
1524 if (opt->funcbody)
1525 show_function = 1;
1526 goto next_line;
1528 if (show_function && match_funcname(opt, gs, bol, eol))
1529 show_function = 0;
1530 if (show_function ||
1531 (last_hit && lno <= last_hit + opt->post_context)) {
1532 /* If the last hit is within the post context,
1533 * we need to show this line.
1535 show_line(opt, bol, eol, gs->name, lno, '-');
1538 next_line:
1539 bol = eol + 1;
1540 if (!left)
1541 break;
1542 left--;
1543 lno++;
1546 if (collect_hits)
1547 return 0;
1549 if (opt->status_only)
1550 return 0;
1551 if (opt->unmatch_name_only) {
1552 /* We did not see any hit, so we want to show this */
1553 show_name(opt, gs->name);
1554 return 1;
1557 xdiff_clear_find_func(&xecfg);
1558 opt->priv = NULL;
1560 /* NEEDSWORK:
1561 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1562 * which feels mostly useless but sometimes useful. Maybe
1563 * make it another option? For now suppress them.
1565 if (opt->count && count) {
1566 char buf[32];
1567 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1568 output_sep(opt, ':');
1569 snprintf(buf, sizeof(buf), "%u\n", count);
1570 opt->output(opt, buf, strlen(buf));
1571 return 1;
1573 return !!last_hit;
1576 static void clr_hit_marker(struct grep_expr *x)
1578 /* All-hit markers are meaningful only at the very top level
1579 * OR node.
1581 while (1) {
1582 x->hit = 0;
1583 if (x->node != GREP_NODE_OR)
1584 return;
1585 x->u.binary.left->hit = 0;
1586 x = x->u.binary.right;
1590 static int chk_hit_marker(struct grep_expr *x)
1592 /* Top level nodes have hit markers. See if they all are hits */
1593 while (1) {
1594 if (x->node != GREP_NODE_OR)
1595 return x->hit;
1596 if (!x->u.binary.left->hit)
1597 return 0;
1598 x = x->u.binary.right;
1602 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1605 * we do not have to do the two-pass grep when we do not check
1606 * buffer-wide "all-match".
1608 if (!opt->all_match)
1609 return grep_source_1(opt, gs, 0);
1611 /* Otherwise the toplevel "or" terms hit a bit differently.
1612 * We first clear hit markers from them.
1614 clr_hit_marker(opt->pattern_expression);
1615 grep_source_1(opt, gs, 1);
1617 if (!chk_hit_marker(opt->pattern_expression))
1618 return 0;
1620 return grep_source_1(opt, gs, 0);
1623 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1625 struct grep_source gs;
1626 int r;
1628 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1629 gs.buf = buf;
1630 gs.size = size;
1632 r = grep_source(opt, &gs);
1634 grep_source_clear(&gs);
1635 return r;
1638 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1639 const char *name, const char *path,
1640 const void *identifier)
1642 gs->type = type;
1643 gs->name = name ? xstrdup(name) : NULL;
1644 gs->path = path ? xstrdup(path) : NULL;
1645 gs->buf = NULL;
1646 gs->size = 0;
1647 gs->driver = NULL;
1649 switch (type) {
1650 case GREP_SOURCE_FILE:
1651 gs->identifier = xstrdup(identifier);
1652 break;
1653 case GREP_SOURCE_SHA1:
1654 gs->identifier = xmalloc(20);
1655 memcpy(gs->identifier, identifier, 20);
1656 break;
1657 case GREP_SOURCE_BUF:
1658 gs->identifier = NULL;
1662 void grep_source_clear(struct grep_source *gs)
1664 free(gs->name);
1665 gs->name = NULL;
1666 free(gs->path);
1667 gs->path = NULL;
1668 free(gs->identifier);
1669 gs->identifier = NULL;
1670 grep_source_clear_data(gs);
1673 void grep_source_clear_data(struct grep_source *gs)
1675 switch (gs->type) {
1676 case GREP_SOURCE_FILE:
1677 case GREP_SOURCE_SHA1:
1678 free(gs->buf);
1679 gs->buf = NULL;
1680 gs->size = 0;
1681 break;
1682 case GREP_SOURCE_BUF:
1683 /* leave user-provided buf intact */
1684 break;
1688 static int grep_source_load_sha1(struct grep_source *gs)
1690 enum object_type type;
1692 grep_read_lock();
1693 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1694 grep_read_unlock();
1696 if (!gs->buf)
1697 return error(_("'%s': unable to read %s"),
1698 gs->name,
1699 sha1_to_hex(gs->identifier));
1700 return 0;
1703 static int grep_source_load_file(struct grep_source *gs)
1705 const char *filename = gs->identifier;
1706 struct stat st;
1707 char *data;
1708 size_t size;
1709 int i;
1711 if (lstat(filename, &st) < 0) {
1712 err_ret:
1713 if (errno != ENOENT)
1714 error(_("'%s': %s"), filename, strerror(errno));
1715 return -1;
1717 if (!S_ISREG(st.st_mode))
1718 return -1;
1719 size = xsize_t(st.st_size);
1720 i = open(filename, O_RDONLY);
1721 if (i < 0)
1722 goto err_ret;
1723 data = xmalloc(size + 1);
1724 if (st.st_size != read_in_full(i, data, size)) {
1725 error(_("'%s': short read %s"), filename, strerror(errno));
1726 close(i);
1727 free(data);
1728 return -1;
1730 close(i);
1731 data[size] = 0;
1733 gs->buf = data;
1734 gs->size = size;
1735 return 0;
1738 static int grep_source_load(struct grep_source *gs)
1740 if (gs->buf)
1741 return 0;
1743 switch (gs->type) {
1744 case GREP_SOURCE_FILE:
1745 return grep_source_load_file(gs);
1746 case GREP_SOURCE_SHA1:
1747 return grep_source_load_sha1(gs);
1748 case GREP_SOURCE_BUF:
1749 return gs->buf ? 0 : -1;
1751 die("BUG: invalid grep_source type");
1754 void grep_source_load_driver(struct grep_source *gs)
1756 if (gs->driver)
1757 return;
1759 grep_attr_lock();
1760 if (gs->path)
1761 gs->driver = userdiff_find_by_path(gs->path);
1762 if (!gs->driver)
1763 gs->driver = userdiff_find_by_name("default");
1764 grep_attr_unlock();
1767 static int grep_source_is_binary(struct grep_source *gs)
1769 grep_source_load_driver(gs);
1770 if (gs->driver->binary != -1)
1771 return gs->driver->binary;
1773 if (!grep_source_load(gs))
1774 return buffer_is_binary(gs->buf, gs->size);
1776 return 0;