git p4 doc: use two-line style for options with multiple spellings
[git/mingw/j6t.git] / grep.c
blobc668034739258d0cd1e7108357da80d44891221f
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 strcpy(opt->color_context, "");
35 strcpy(opt->color_filename, "");
36 strcpy(opt->color_function, "");
37 strcpy(opt->color_lineno, "");
38 strcpy(opt->color_match, GIT_COLOR_BOLD_RED);
39 strcpy(opt->color_selected, "");
40 strcpy(opt->color_sep, GIT_COLOR_CYAN);
41 opt->color = -1;
44 static int parse_pattern_type_arg(const char *opt, const char *arg)
46 if (!strcmp(arg, "default"))
47 return GREP_PATTERN_TYPE_UNSPECIFIED;
48 else if (!strcmp(arg, "basic"))
49 return GREP_PATTERN_TYPE_BRE;
50 else if (!strcmp(arg, "extended"))
51 return GREP_PATTERN_TYPE_ERE;
52 else if (!strcmp(arg, "fixed"))
53 return GREP_PATTERN_TYPE_FIXED;
54 else if (!strcmp(arg, "perl"))
55 return GREP_PATTERN_TYPE_PCRE;
56 die("bad %s argument: %s", opt, arg);
60 * Read the configuration file once and store it in
61 * the grep_defaults template.
63 int grep_config(const char *var, const char *value, void *cb)
65 struct grep_opt *opt = &grep_defaults;
66 char *color = NULL;
68 if (userdiff_config(var, value) < 0)
69 return -1;
71 if (!strcmp(var, "grep.extendedregexp")) {
72 if (git_config_bool(var, value))
73 opt->extended_regexp_option = 1;
74 else
75 opt->extended_regexp_option = 0;
76 return 0;
79 if (!strcmp(var, "grep.patterntype")) {
80 opt->pattern_type_option = parse_pattern_type_arg(var, value);
81 return 0;
84 if (!strcmp(var, "grep.linenumber")) {
85 opt->linenum = git_config_bool(var, value);
86 return 0;
89 if (!strcmp(var, "color.grep"))
90 opt->color = git_config_colorbool(var, value);
91 else if (!strcmp(var, "color.grep.context"))
92 color = opt->color_context;
93 else if (!strcmp(var, "color.grep.filename"))
94 color = opt->color_filename;
95 else if (!strcmp(var, "color.grep.function"))
96 color = opt->color_function;
97 else if (!strcmp(var, "color.grep.linenumber"))
98 color = opt->color_lineno;
99 else if (!strcmp(var, "color.grep.match"))
100 color = opt->color_match;
101 else if (!strcmp(var, "color.grep.selected"))
102 color = opt->color_selected;
103 else if (!strcmp(var, "color.grep.separator"))
104 color = opt->color_sep;
106 if (color) {
107 if (!value)
108 return config_error_nonbool(var);
109 color_parse(value, var, color);
111 return 0;
115 * Initialize one instance of grep_opt and copy the
116 * default values from the template we read the configuration
117 * information in an earlier call to git_config(grep_config).
119 void grep_init(struct grep_opt *opt, const char *prefix)
121 struct grep_opt *def = &grep_defaults;
123 memset(opt, 0, sizeof(*opt));
124 opt->prefix = prefix;
125 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
126 opt->pattern_tail = &opt->pattern_list;
127 opt->header_tail = &opt->header_list;
129 opt->color = def->color;
130 opt->extended_regexp_option = def->extended_regexp_option;
131 opt->pattern_type_option = def->pattern_type_option;
132 opt->linenum = def->linenum;
133 opt->max_depth = def->max_depth;
134 opt->pathname = def->pathname;
135 opt->regflags = def->regflags;
136 opt->relative = def->relative;
138 strcpy(opt->color_context, def->color_context);
139 strcpy(opt->color_filename, def->color_filename);
140 strcpy(opt->color_function, def->color_function);
141 strcpy(opt->color_lineno, def->color_lineno);
142 strcpy(opt->color_match, def->color_match);
143 strcpy(opt->color_selected, def->color_selected);
144 strcpy(opt->color_sep, def->color_sep);
147 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
149 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
150 grep_set_pattern_type_option(pattern_type, opt);
151 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
152 grep_set_pattern_type_option(opt->pattern_type_option, opt);
153 else if (opt->extended_regexp_option)
154 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
157 void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
159 switch (pattern_type) {
160 case GREP_PATTERN_TYPE_UNSPECIFIED:
161 /* fall through */
163 case GREP_PATTERN_TYPE_BRE:
164 opt->fixed = 0;
165 opt->pcre = 0;
166 opt->regflags &= ~REG_EXTENDED;
167 break;
169 case GREP_PATTERN_TYPE_ERE:
170 opt->fixed = 0;
171 opt->pcre = 0;
172 opt->regflags |= REG_EXTENDED;
173 break;
175 case GREP_PATTERN_TYPE_FIXED:
176 opt->fixed = 1;
177 opt->pcre = 0;
178 opt->regflags &= ~REG_EXTENDED;
179 break;
181 case GREP_PATTERN_TYPE_PCRE:
182 opt->fixed = 0;
183 opt->pcre = 1;
184 opt->regflags &= ~REG_EXTENDED;
185 break;
189 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
190 const char *origin, int no,
191 enum grep_pat_token t,
192 enum grep_header_field field)
194 struct grep_pat *p = xcalloc(1, sizeof(*p));
195 p->pattern = xmemdupz(pat, patlen);
196 p->patternlen = patlen;
197 p->origin = origin;
198 p->no = no;
199 p->token = t;
200 p->field = field;
201 return p;
204 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
206 **tail = p;
207 *tail = &p->next;
208 p->next = NULL;
210 switch (p->token) {
211 case GREP_PATTERN: /* atom */
212 case GREP_PATTERN_HEAD:
213 case GREP_PATTERN_BODY:
214 for (;;) {
215 struct grep_pat *new_pat;
216 size_t len = 0;
217 char *cp = p->pattern + p->patternlen, *nl = NULL;
218 while (++len <= p->patternlen) {
219 if (*(--cp) == '\n') {
220 nl = cp;
221 break;
224 if (!nl)
225 break;
226 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
227 p->no, p->token, p->field);
228 new_pat->next = p->next;
229 if (!p->next)
230 *tail = &new_pat->next;
231 p->next = new_pat;
232 *nl = '\0';
233 p->patternlen -= len;
235 break;
236 default:
237 break;
241 void append_header_grep_pattern(struct grep_opt *opt,
242 enum grep_header_field field, const char *pat)
244 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
245 GREP_PATTERN_HEAD, field);
246 if (field == GREP_HEADER_REFLOG)
247 opt->use_reflog_filter = 1;
248 do_append_grep_pat(&opt->header_tail, p);
251 void append_grep_pattern(struct grep_opt *opt, const char *pat,
252 const char *origin, int no, enum grep_pat_token t)
254 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
257 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
258 const char *origin, int no, enum grep_pat_token t)
260 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
261 do_append_grep_pat(&opt->pattern_tail, p);
264 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
266 struct grep_pat *pat;
267 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
268 *ret = *opt;
270 ret->pattern_list = NULL;
271 ret->pattern_tail = &ret->pattern_list;
273 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
275 if(pat->token == GREP_PATTERN_HEAD)
276 append_header_grep_pattern(ret, pat->field,
277 pat->pattern);
278 else
279 append_grep_pat(ret, pat->pattern, pat->patternlen,
280 pat->origin, pat->no, pat->token);
283 return ret;
286 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
287 const char *error)
289 char where[1024];
291 if (p->no)
292 sprintf(where, "In '%s' at %d, ", p->origin, p->no);
293 else if (p->origin)
294 sprintf(where, "%s, ", p->origin);
295 else
296 where[0] = 0;
298 die("%s'%s': %s", where, p->pattern, error);
301 #ifdef USE_LIBPCRE
302 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
304 const char *error;
305 int erroffset;
306 int options = PCRE_MULTILINE;
308 if (opt->ignore_case)
309 options |= PCRE_CASELESS;
311 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
312 NULL);
313 if (!p->pcre_regexp)
314 compile_regexp_failed(p, error);
316 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
317 if (!p->pcre_extra_info && error)
318 die("%s", error);
321 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
322 regmatch_t *match, int eflags)
324 int ovector[30], ret, flags = 0;
326 if (eflags & REG_NOTBOL)
327 flags |= PCRE_NOTBOL;
329 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
330 0, flags, ovector, ARRAY_SIZE(ovector));
331 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
332 die("pcre_exec failed with error code %d", ret);
333 if (ret > 0) {
334 ret = 0;
335 match->rm_so = ovector[0];
336 match->rm_eo = ovector[1];
339 return ret;
342 static void free_pcre_regexp(struct grep_pat *p)
344 pcre_free(p->pcre_regexp);
345 pcre_free(p->pcre_extra_info);
347 #else /* !USE_LIBPCRE */
348 static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
350 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
353 static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
354 regmatch_t *match, int eflags)
356 return 1;
359 static void free_pcre_regexp(struct grep_pat *p)
362 #endif /* !USE_LIBPCRE */
364 static int is_fixed(const char *s, size_t len)
366 size_t i;
368 /* regcomp cannot accept patterns with NULs so we
369 * consider any pattern containing a NUL fixed.
371 if (memchr(s, 0, len))
372 return 1;
374 for (i = 0; i < len; i++) {
375 if (is_regex_special(s[i]))
376 return 0;
379 return 1;
382 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
384 int err;
386 p->word_regexp = opt->word_regexp;
387 p->ignore_case = opt->ignore_case;
389 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
390 p->fixed = 1;
391 else
392 p->fixed = 0;
394 if (p->fixed) {
395 if (opt->regflags & REG_ICASE || p->ignore_case)
396 p->kws = kwsalloc(tolower_trans_tbl);
397 else
398 p->kws = kwsalloc(NULL);
399 kwsincr(p->kws, p->pattern, p->patternlen);
400 kwsprep(p->kws);
401 return;
404 if (opt->pcre) {
405 compile_pcre_regexp(p, opt);
406 return;
409 err = regcomp(&p->regexp, p->pattern, opt->regflags);
410 if (err) {
411 char errbuf[1024];
412 regerror(err, &p->regexp, errbuf, 1024);
413 regfree(&p->regexp);
414 compile_regexp_failed(p, errbuf);
418 static struct grep_expr *compile_pattern_or(struct grep_pat **);
419 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
421 struct grep_pat *p;
422 struct grep_expr *x;
424 p = *list;
425 if (!p)
426 return NULL;
427 switch (p->token) {
428 case GREP_PATTERN: /* atom */
429 case GREP_PATTERN_HEAD:
430 case GREP_PATTERN_BODY:
431 x = xcalloc(1, sizeof (struct grep_expr));
432 x->node = GREP_NODE_ATOM;
433 x->u.atom = p;
434 *list = p->next;
435 return x;
436 case GREP_OPEN_PAREN:
437 *list = p->next;
438 x = compile_pattern_or(list);
439 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
440 die("unmatched parenthesis");
441 *list = (*list)->next;
442 return x;
443 default:
444 return NULL;
448 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
450 struct grep_pat *p;
451 struct grep_expr *x;
453 p = *list;
454 if (!p)
455 return NULL;
456 switch (p->token) {
457 case GREP_NOT:
458 if (!p->next)
459 die("--not not followed by pattern expression");
460 *list = p->next;
461 x = xcalloc(1, sizeof (struct grep_expr));
462 x->node = GREP_NODE_NOT;
463 x->u.unary = compile_pattern_not(list);
464 if (!x->u.unary)
465 die("--not followed by non pattern expression");
466 return x;
467 default:
468 return compile_pattern_atom(list);
472 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
474 struct grep_pat *p;
475 struct grep_expr *x, *y, *z;
477 x = compile_pattern_not(list);
478 p = *list;
479 if (p && p->token == GREP_AND) {
480 if (!p->next)
481 die("--and not followed by pattern expression");
482 *list = p->next;
483 y = compile_pattern_and(list);
484 if (!y)
485 die("--and not followed by pattern expression");
486 z = xcalloc(1, sizeof (struct grep_expr));
487 z->node = GREP_NODE_AND;
488 z->u.binary.left = x;
489 z->u.binary.right = y;
490 return z;
492 return x;
495 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
497 struct grep_pat *p;
498 struct grep_expr *x, *y, *z;
500 x = compile_pattern_and(list);
501 p = *list;
502 if (x && p && p->token != GREP_CLOSE_PAREN) {
503 y = compile_pattern_or(list);
504 if (!y)
505 die("not a pattern expression %s", p->pattern);
506 z = xcalloc(1, sizeof (struct grep_expr));
507 z->node = GREP_NODE_OR;
508 z->u.binary.left = x;
509 z->u.binary.right = y;
510 return z;
512 return x;
515 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
517 return compile_pattern_or(list);
520 static void indent(int in)
522 while (in-- > 0)
523 fputc(' ', stderr);
526 static void dump_grep_pat(struct grep_pat *p)
528 switch (p->token) {
529 case GREP_AND: fprintf(stderr, "*and*"); break;
530 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
531 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
532 case GREP_NOT: fprintf(stderr, "*not*"); break;
533 case GREP_OR: fprintf(stderr, "*or*"); break;
535 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
536 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
537 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
540 switch (p->token) {
541 default: break;
542 case GREP_PATTERN_HEAD:
543 fprintf(stderr, "<head %d>", p->field); break;
544 case GREP_PATTERN_BODY:
545 fprintf(stderr, "<body>"); break;
547 switch (p->token) {
548 default: break;
549 case GREP_PATTERN_HEAD:
550 case GREP_PATTERN_BODY:
551 case GREP_PATTERN:
552 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
553 break;
555 fputc('\n', stderr);
558 static void dump_grep_expression_1(struct grep_expr *x, int in)
560 indent(in);
561 switch (x->node) {
562 case GREP_NODE_TRUE:
563 fprintf(stderr, "true\n");
564 break;
565 case GREP_NODE_ATOM:
566 dump_grep_pat(x->u.atom);
567 break;
568 case GREP_NODE_NOT:
569 fprintf(stderr, "(not\n");
570 dump_grep_expression_1(x->u.unary, in+1);
571 indent(in);
572 fprintf(stderr, ")\n");
573 break;
574 case GREP_NODE_AND:
575 fprintf(stderr, "(and\n");
576 dump_grep_expression_1(x->u.binary.left, in+1);
577 dump_grep_expression_1(x->u.binary.right, in+1);
578 indent(in);
579 fprintf(stderr, ")\n");
580 break;
581 case GREP_NODE_OR:
582 fprintf(stderr, "(or\n");
583 dump_grep_expression_1(x->u.binary.left, in+1);
584 dump_grep_expression_1(x->u.binary.right, in+1);
585 indent(in);
586 fprintf(stderr, ")\n");
587 break;
591 static void dump_grep_expression(struct grep_opt *opt)
593 struct grep_expr *x = opt->pattern_expression;
595 if (opt->all_match)
596 fprintf(stderr, "[all-match]\n");
597 dump_grep_expression_1(x, 0);
598 fflush(NULL);
601 static struct grep_expr *grep_true_expr(void)
603 struct grep_expr *z = xcalloc(1, sizeof(*z));
604 z->node = GREP_NODE_TRUE;
605 return z;
608 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
610 struct grep_expr *z = xcalloc(1, sizeof(*z));
611 z->node = GREP_NODE_OR;
612 z->u.binary.left = left;
613 z->u.binary.right = right;
614 return z;
617 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
619 struct grep_pat *p;
620 struct grep_expr *header_expr;
621 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
622 enum grep_header_field fld;
624 if (!opt->header_list)
625 return NULL;
627 for (p = opt->header_list; p; p = p->next) {
628 if (p->token != GREP_PATTERN_HEAD)
629 die("bug: a non-header pattern in grep header list.");
630 if (p->field < GREP_HEADER_FIELD_MIN ||
631 GREP_HEADER_FIELD_MAX <= p->field)
632 die("bug: unknown header field %d", p->field);
633 compile_regexp(p, opt);
636 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
637 header_group[fld] = NULL;
639 for (p = opt->header_list; p; p = p->next) {
640 struct grep_expr *h;
641 struct grep_pat *pp = p;
643 h = compile_pattern_atom(&pp);
644 if (!h || pp != p->next)
645 die("bug: malformed header expr");
646 if (!header_group[p->field]) {
647 header_group[p->field] = h;
648 continue;
650 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
653 header_expr = NULL;
655 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
656 if (!header_group[fld])
657 continue;
658 if (!header_expr)
659 header_expr = grep_true_expr();
660 header_expr = grep_or_expr(header_group[fld], header_expr);
662 return header_expr;
665 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
667 struct grep_expr *z = x;
669 while (x) {
670 assert(x->node == GREP_NODE_OR);
671 if (x->u.binary.right &&
672 x->u.binary.right->node == GREP_NODE_TRUE) {
673 x->u.binary.right = y;
674 break;
676 x = x->u.binary.right;
678 return z;
681 static void compile_grep_patterns_real(struct grep_opt *opt)
683 struct grep_pat *p;
684 struct grep_expr *header_expr = prep_header_patterns(opt);
686 for (p = opt->pattern_list; p; p = p->next) {
687 switch (p->token) {
688 case GREP_PATTERN: /* atom */
689 case GREP_PATTERN_HEAD:
690 case GREP_PATTERN_BODY:
691 compile_regexp(p, opt);
692 break;
693 default:
694 opt->extended = 1;
695 break;
699 if (opt->all_match || header_expr)
700 opt->extended = 1;
701 else if (!opt->extended && !opt->debug)
702 return;
704 p = opt->pattern_list;
705 if (p)
706 opt->pattern_expression = compile_pattern_expr(&p);
707 if (p)
708 die("incomplete pattern expression: %s", p->pattern);
710 if (!header_expr)
711 return;
713 if (!opt->pattern_expression)
714 opt->pattern_expression = header_expr;
715 else if (opt->all_match)
716 opt->pattern_expression = grep_splice_or(header_expr,
717 opt->pattern_expression);
718 else
719 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
720 header_expr);
721 opt->all_match = 1;
724 void compile_grep_patterns(struct grep_opt *opt)
726 compile_grep_patterns_real(opt);
727 if (opt->debug)
728 dump_grep_expression(opt);
731 static void free_pattern_expr(struct grep_expr *x)
733 switch (x->node) {
734 case GREP_NODE_TRUE:
735 case GREP_NODE_ATOM:
736 break;
737 case GREP_NODE_NOT:
738 free_pattern_expr(x->u.unary);
739 break;
740 case GREP_NODE_AND:
741 case GREP_NODE_OR:
742 free_pattern_expr(x->u.binary.left);
743 free_pattern_expr(x->u.binary.right);
744 break;
746 free(x);
749 void free_grep_patterns(struct grep_opt *opt)
751 struct grep_pat *p, *n;
753 for (p = opt->pattern_list; p; p = n) {
754 n = p->next;
755 switch (p->token) {
756 case GREP_PATTERN: /* atom */
757 case GREP_PATTERN_HEAD:
758 case GREP_PATTERN_BODY:
759 if (p->kws)
760 kwsfree(p->kws);
761 else if (p->pcre_regexp)
762 free_pcre_regexp(p);
763 else
764 regfree(&p->regexp);
765 free(p->pattern);
766 break;
767 default:
768 break;
770 free(p);
773 if (!opt->extended)
774 return;
775 free_pattern_expr(opt->pattern_expression);
778 static char *end_of_line(char *cp, unsigned long *left)
780 unsigned long l = *left;
781 while (l && *cp != '\n') {
782 l--;
783 cp++;
785 *left = l;
786 return cp;
789 static int word_char(char ch)
791 return isalnum(ch) || ch == '_';
794 static void output_color(struct grep_opt *opt, const void *data, size_t size,
795 const char *color)
797 if (want_color(opt->color) && color && color[0]) {
798 opt->output(opt, color, strlen(color));
799 opt->output(opt, data, size);
800 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
801 } else
802 opt->output(opt, data, size);
805 static void output_sep(struct grep_opt *opt, char sign)
807 if (opt->null_following_name)
808 opt->output(opt, "\0", 1);
809 else
810 output_color(opt, &sign, 1, opt->color_sep);
813 static void show_name(struct grep_opt *opt, const char *name)
815 output_color(opt, name, strlen(name), opt->color_filename);
816 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
819 static int fixmatch(struct grep_pat *p, char *line, char *eol,
820 regmatch_t *match)
822 struct kwsmatch kwsm;
823 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
824 if (offset == -1) {
825 match->rm_so = match->rm_eo = -1;
826 return REG_NOMATCH;
827 } else {
828 match->rm_so = offset;
829 match->rm_eo = match->rm_so + kwsm.size[0];
830 return 0;
834 static int regmatch(const regex_t *preg, char *line, char *eol,
835 regmatch_t *match, int eflags)
837 #ifdef REG_STARTEND
838 match->rm_so = 0;
839 match->rm_eo = eol - line;
840 eflags |= REG_STARTEND;
841 #endif
842 return regexec(preg, line, 1, match, eflags);
845 static int patmatch(struct grep_pat *p, char *line, char *eol,
846 regmatch_t *match, int eflags)
848 int hit;
850 if (p->fixed)
851 hit = !fixmatch(p, line, eol, match);
852 else if (p->pcre_regexp)
853 hit = !pcrematch(p, line, eol, match, eflags);
854 else
855 hit = !regmatch(&p->regexp, line, eol, match, eflags);
857 return hit;
860 static int strip_timestamp(char *bol, char **eol_p)
862 char *eol = *eol_p;
863 int ch;
865 while (bol < --eol) {
866 if (*eol != '>')
867 continue;
868 *eol_p = ++eol;
869 ch = *eol;
870 *eol = '\0';
871 return ch;
873 return 0;
876 static struct {
877 const char *field;
878 size_t len;
879 } header_field[] = {
880 { "author ", 7 },
881 { "committer ", 10 },
882 { "reflog ", 7 },
885 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
886 enum grep_context ctx,
887 regmatch_t *pmatch, int eflags)
889 int hit = 0;
890 int saved_ch = 0;
891 const char *start = bol;
893 if ((p->token != GREP_PATTERN) &&
894 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
895 return 0;
897 if (p->token == GREP_PATTERN_HEAD) {
898 const char *field;
899 size_t len;
900 assert(p->field < ARRAY_SIZE(header_field));
901 field = header_field[p->field].field;
902 len = header_field[p->field].len;
903 if (strncmp(bol, field, len))
904 return 0;
905 bol += len;
906 switch (p->field) {
907 case GREP_HEADER_AUTHOR:
908 case GREP_HEADER_COMMITTER:
909 saved_ch = strip_timestamp(bol, &eol);
910 break;
911 default:
912 break;
916 again:
917 hit = patmatch(p, bol, eol, pmatch, eflags);
919 if (hit && p->word_regexp) {
920 if ((pmatch[0].rm_so < 0) ||
921 (eol - bol) < pmatch[0].rm_so ||
922 (pmatch[0].rm_eo < 0) ||
923 (eol - bol) < pmatch[0].rm_eo)
924 die("regexp returned nonsense");
926 /* Match beginning must be either beginning of the
927 * line, or at word boundary (i.e. the last char must
928 * not be a word char). Similarly, match end must be
929 * either end of the line, or at word boundary
930 * (i.e. the next char must not be a word char).
932 if ( ((pmatch[0].rm_so == 0) ||
933 !word_char(bol[pmatch[0].rm_so-1])) &&
934 ((pmatch[0].rm_eo == (eol-bol)) ||
935 !word_char(bol[pmatch[0].rm_eo])) )
937 else
938 hit = 0;
940 /* Words consist of at least one character. */
941 if (pmatch->rm_so == pmatch->rm_eo)
942 hit = 0;
944 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
945 /* There could be more than one match on the
946 * line, and the first match might not be
947 * strict word match. But later ones could be!
948 * Forward to the next possible start, i.e. the
949 * next position following a non-word char.
951 bol = pmatch[0].rm_so + bol + 1;
952 while (word_char(bol[-1]) && bol < eol)
953 bol++;
954 eflags |= REG_NOTBOL;
955 if (bol < eol)
956 goto again;
959 if (p->token == GREP_PATTERN_HEAD && saved_ch)
960 *eol = saved_ch;
961 if (hit) {
962 pmatch[0].rm_so += bol - start;
963 pmatch[0].rm_eo += bol - start;
965 return hit;
968 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
969 enum grep_context ctx, int collect_hits)
971 int h = 0;
972 regmatch_t match;
974 if (!x)
975 die("Not a valid grep expression");
976 switch (x->node) {
977 case GREP_NODE_TRUE:
978 h = 1;
979 break;
980 case GREP_NODE_ATOM:
981 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
982 break;
983 case GREP_NODE_NOT:
984 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
985 break;
986 case GREP_NODE_AND:
987 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
988 return 0;
989 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
990 break;
991 case GREP_NODE_OR:
992 if (!collect_hits)
993 return (match_expr_eval(x->u.binary.left,
994 bol, eol, ctx, 0) ||
995 match_expr_eval(x->u.binary.right,
996 bol, eol, ctx, 0));
997 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
998 x->u.binary.left->hit |= h;
999 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1000 break;
1001 default:
1002 die("Unexpected node type (internal error) %d", x->node);
1004 if (collect_hits)
1005 x->hit |= h;
1006 return h;
1009 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1010 enum grep_context ctx, int collect_hits)
1012 struct grep_expr *x = opt->pattern_expression;
1013 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1016 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1017 enum grep_context ctx, int collect_hits)
1019 struct grep_pat *p;
1020 regmatch_t match;
1022 if (opt->extended)
1023 return match_expr(opt, bol, eol, ctx, collect_hits);
1025 /* we do not call with collect_hits without being extended */
1026 for (p = opt->pattern_list; p; p = p->next) {
1027 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1028 return 1;
1030 return 0;
1033 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1034 enum grep_context ctx,
1035 regmatch_t *pmatch, int eflags)
1037 regmatch_t match;
1039 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1040 return 0;
1041 if (match.rm_so < 0 || match.rm_eo < 0)
1042 return 0;
1043 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1044 if (match.rm_so > pmatch->rm_so)
1045 return 1;
1046 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1047 return 1;
1049 pmatch->rm_so = match.rm_so;
1050 pmatch->rm_eo = match.rm_eo;
1051 return 1;
1054 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1055 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1057 struct grep_pat *p;
1058 int hit = 0;
1060 pmatch->rm_so = pmatch->rm_eo = -1;
1061 if (bol < eol) {
1062 for (p = opt->pattern_list; p; p = p->next) {
1063 switch (p->token) {
1064 case GREP_PATTERN: /* atom */
1065 case GREP_PATTERN_HEAD:
1066 case GREP_PATTERN_BODY:
1067 hit |= match_next_pattern(p, bol, eol, ctx,
1068 pmatch, eflags);
1069 break;
1070 default:
1071 break;
1075 return hit;
1078 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1079 const char *name, unsigned lno, char sign)
1081 int rest = eol - bol;
1082 char *line_color = NULL;
1084 if (opt->file_break && opt->last_shown == 0) {
1085 if (opt->show_hunk_mark)
1086 opt->output(opt, "\n", 1);
1087 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1088 if (opt->last_shown == 0) {
1089 if (opt->show_hunk_mark) {
1090 output_color(opt, "--", 2, opt->color_sep);
1091 opt->output(opt, "\n", 1);
1093 } else if (lno > opt->last_shown + 1) {
1094 output_color(opt, "--", 2, opt->color_sep);
1095 opt->output(opt, "\n", 1);
1098 if (opt->heading && opt->last_shown == 0) {
1099 output_color(opt, name, strlen(name), opt->color_filename);
1100 opt->output(opt, "\n", 1);
1102 opt->last_shown = lno;
1104 if (!opt->heading && opt->pathname) {
1105 output_color(opt, name, strlen(name), opt->color_filename);
1106 output_sep(opt, sign);
1108 if (opt->linenum) {
1109 char buf[32];
1110 snprintf(buf, sizeof(buf), "%d", lno);
1111 output_color(opt, buf, strlen(buf), opt->color_lineno);
1112 output_sep(opt, sign);
1114 if (opt->color) {
1115 regmatch_t match;
1116 enum grep_context ctx = GREP_CONTEXT_BODY;
1117 int ch = *eol;
1118 int eflags = 0;
1120 if (sign == ':')
1121 line_color = opt->color_selected;
1122 else if (sign == '-')
1123 line_color = opt->color_context;
1124 else if (sign == '=')
1125 line_color = opt->color_function;
1126 *eol = '\0';
1127 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1128 if (match.rm_so == match.rm_eo)
1129 break;
1131 output_color(opt, bol, match.rm_so, line_color);
1132 output_color(opt, bol + match.rm_so,
1133 match.rm_eo - match.rm_so,
1134 opt->color_match);
1135 bol += match.rm_eo;
1136 rest -= match.rm_eo;
1137 eflags = REG_NOTBOL;
1139 *eol = ch;
1141 output_color(opt, bol, rest, line_color);
1142 opt->output(opt, "\n", 1);
1145 #ifndef NO_PTHREADS
1146 int grep_use_locks;
1149 * This lock protects access to the gitattributes machinery, which is
1150 * not thread-safe.
1152 pthread_mutex_t grep_attr_mutex;
1154 static inline void grep_attr_lock(void)
1156 if (grep_use_locks)
1157 pthread_mutex_lock(&grep_attr_mutex);
1160 static inline void grep_attr_unlock(void)
1162 if (grep_use_locks)
1163 pthread_mutex_unlock(&grep_attr_mutex);
1167 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1169 pthread_mutex_t grep_read_mutex;
1171 #else
1172 #define grep_attr_lock()
1173 #define grep_attr_unlock()
1174 #endif
1176 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1178 xdemitconf_t *xecfg = opt->priv;
1179 if (xecfg && !xecfg->find_func) {
1180 grep_source_load_driver(gs);
1181 if (gs->driver->funcname.pattern) {
1182 const struct userdiff_funcname *pe = &gs->driver->funcname;
1183 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1184 } else {
1185 xecfg = opt->priv = NULL;
1189 if (xecfg) {
1190 char buf[1];
1191 return xecfg->find_func(bol, eol - bol, buf, 1,
1192 xecfg->find_func_priv) >= 0;
1195 if (bol == eol)
1196 return 0;
1197 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1198 return 1;
1199 return 0;
1202 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1203 char *bol, unsigned lno)
1205 while (bol > gs->buf) {
1206 char *eol = --bol;
1208 while (bol > gs->buf && bol[-1] != '\n')
1209 bol--;
1210 lno--;
1212 if (lno <= opt->last_shown)
1213 break;
1215 if (match_funcname(opt, gs, bol, eol)) {
1216 show_line(opt, bol, eol, gs->name, lno, '=');
1217 break;
1222 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1223 char *bol, char *end, unsigned lno)
1225 unsigned cur = lno, from = 1, funcname_lno = 0;
1226 int funcname_needed = !!opt->funcname;
1228 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1229 funcname_needed = 2;
1231 if (opt->pre_context < lno)
1232 from = lno - opt->pre_context;
1233 if (from <= opt->last_shown)
1234 from = opt->last_shown + 1;
1236 /* Rewind. */
1237 while (bol > gs->buf &&
1238 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1239 char *eol = --bol;
1241 while (bol > gs->buf && bol[-1] != '\n')
1242 bol--;
1243 cur--;
1244 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1245 funcname_lno = cur;
1246 funcname_needed = 0;
1250 /* We need to look even further back to find a function signature. */
1251 if (opt->funcname && funcname_needed)
1252 show_funcname_line(opt, gs, bol, cur);
1254 /* Back forward. */
1255 while (cur < lno) {
1256 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1258 while (*eol != '\n')
1259 eol++;
1260 show_line(opt, bol, eol, gs->name, cur, sign);
1261 bol = eol + 1;
1262 cur++;
1266 static int should_lookahead(struct grep_opt *opt)
1268 struct grep_pat *p;
1270 if (opt->extended)
1271 return 0; /* punt for too complex stuff */
1272 if (opt->invert)
1273 return 0;
1274 for (p = opt->pattern_list; p; p = p->next) {
1275 if (p->token != GREP_PATTERN)
1276 return 0; /* punt for "header only" and stuff */
1278 return 1;
1281 static int look_ahead(struct grep_opt *opt,
1282 unsigned long *left_p,
1283 unsigned *lno_p,
1284 char **bol_p)
1286 unsigned lno = *lno_p;
1287 char *bol = *bol_p;
1288 struct grep_pat *p;
1289 char *sp, *last_bol;
1290 regoff_t earliest = -1;
1292 for (p = opt->pattern_list; p; p = p->next) {
1293 int hit;
1294 regmatch_t m;
1296 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1297 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1298 continue;
1299 if (earliest < 0 || m.rm_so < earliest)
1300 earliest = m.rm_so;
1303 if (earliest < 0) {
1304 *bol_p = bol + *left_p;
1305 *left_p = 0;
1306 return 1;
1308 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1309 ; /* find the beginning of the line */
1310 last_bol = sp;
1312 for (sp = bol; sp < last_bol; sp++) {
1313 if (*sp == '\n')
1314 lno++;
1316 *left_p -= last_bol - bol;
1317 *bol_p = last_bol;
1318 *lno_p = lno;
1319 return 0;
1322 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1324 fwrite(buf, size, 1, stdout);
1327 static int fill_textconv_grep(struct userdiff_driver *driver,
1328 struct grep_source *gs)
1330 struct diff_filespec *df;
1331 char *buf;
1332 size_t size;
1334 if (!driver || !driver->textconv)
1335 return grep_source_load(gs);
1338 * The textconv interface is intimately tied to diff_filespecs, so we
1339 * have to pretend to be one. If we could unify the grep_source
1340 * and diff_filespec structs, this mess could just go away.
1342 df = alloc_filespec(gs->path);
1343 switch (gs->type) {
1344 case GREP_SOURCE_SHA1:
1345 fill_filespec(df, gs->identifier, 1, 0100644);
1346 break;
1347 case GREP_SOURCE_FILE:
1348 fill_filespec(df, null_sha1, 0, 0100644);
1349 break;
1350 default:
1351 die("BUG: attempt to textconv something without a path?");
1355 * fill_textconv is not remotely thread-safe; it may load objects
1356 * behind the scenes, and it modifies the global diff tempfile
1357 * structure.
1359 grep_read_lock();
1360 size = fill_textconv(driver, df, &buf);
1361 grep_read_unlock();
1362 free_filespec(df);
1365 * The normal fill_textconv usage by the diff machinery would just keep
1366 * the textconv'd buf separate from the diff_filespec. But much of the
1367 * grep code passes around a grep_source and assumes that its "buf"
1368 * pointer is the beginning of the thing we are searching. So let's
1369 * install our textconv'd version into the grep_source, taking care not
1370 * to leak any existing buffer.
1372 grep_source_clear_data(gs);
1373 gs->buf = buf;
1374 gs->size = size;
1376 return 0;
1379 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1381 char *bol;
1382 unsigned long left;
1383 unsigned lno = 1;
1384 unsigned last_hit = 0;
1385 int binary_match_only = 0;
1386 unsigned count = 0;
1387 int try_lookahead = 0;
1388 int show_function = 0;
1389 struct userdiff_driver *textconv = NULL;
1390 enum grep_context ctx = GREP_CONTEXT_HEAD;
1391 xdemitconf_t xecfg;
1393 if (!opt->output)
1394 opt->output = std_output;
1396 if (opt->pre_context || opt->post_context || opt->file_break ||
1397 opt->funcbody) {
1398 /* Show hunk marks, except for the first file. */
1399 if (opt->last_shown)
1400 opt->show_hunk_mark = 1;
1402 * If we're using threads then we can't easily identify
1403 * the first file. Always put hunk marks in that case
1404 * and skip the very first one later in work_done().
1406 if (opt->output != std_output)
1407 opt->show_hunk_mark = 1;
1409 opt->last_shown = 0;
1411 if (opt->allow_textconv) {
1412 grep_source_load_driver(gs);
1414 * We might set up the shared textconv cache data here, which
1415 * is not thread-safe.
1417 grep_attr_lock();
1418 textconv = userdiff_get_textconv(gs->driver);
1419 grep_attr_unlock();
1423 * We know the result of a textconv is text, so we only have to care
1424 * about binary handling if we are not using it.
1426 if (!textconv) {
1427 switch (opt->binary) {
1428 case GREP_BINARY_DEFAULT:
1429 if (grep_source_is_binary(gs))
1430 binary_match_only = 1;
1431 break;
1432 case GREP_BINARY_NOMATCH:
1433 if (grep_source_is_binary(gs))
1434 return 0; /* Assume unmatch */
1435 break;
1436 case GREP_BINARY_TEXT:
1437 break;
1438 default:
1439 die("bug: unknown binary handling mode");
1443 memset(&xecfg, 0, sizeof(xecfg));
1444 opt->priv = &xecfg;
1446 try_lookahead = should_lookahead(opt);
1448 if (fill_textconv_grep(textconv, gs) < 0)
1449 return 0;
1451 bol = gs->buf;
1452 left = gs->size;
1453 while (left) {
1454 char *eol, ch;
1455 int hit;
1458 * look_ahead() skips quickly to the line that possibly
1459 * has the next hit; don't call it if we need to do
1460 * something more than just skipping the current line
1461 * in response to an unmatch for the current line. E.g.
1462 * inside a post-context window, we will show the current
1463 * line as a context around the previous hit when it
1464 * doesn't hit.
1466 if (try_lookahead
1467 && !(last_hit
1468 && (show_function ||
1469 lno <= last_hit + opt->post_context))
1470 && look_ahead(opt, &left, &lno, &bol))
1471 break;
1472 eol = end_of_line(bol, &left);
1473 ch = *eol;
1474 *eol = 0;
1476 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1477 ctx = GREP_CONTEXT_BODY;
1479 hit = match_line(opt, bol, eol, ctx, collect_hits);
1480 *eol = ch;
1482 if (collect_hits)
1483 goto next_line;
1485 /* "grep -v -e foo -e bla" should list lines
1486 * that do not have either, so inversion should
1487 * be done outside.
1489 if (opt->invert)
1490 hit = !hit;
1491 if (opt->unmatch_name_only) {
1492 if (hit)
1493 return 0;
1494 goto next_line;
1496 if (hit) {
1497 count++;
1498 if (opt->status_only)
1499 return 1;
1500 if (opt->name_only) {
1501 show_name(opt, gs->name);
1502 return 1;
1504 if (opt->count)
1505 goto next_line;
1506 if (binary_match_only) {
1507 opt->output(opt, "Binary file ", 12);
1508 output_color(opt, gs->name, strlen(gs->name),
1509 opt->color_filename);
1510 opt->output(opt, " matches\n", 9);
1511 return 1;
1513 /* Hit at this line. If we haven't shown the
1514 * pre-context lines, we would need to show them.
1516 if (opt->pre_context || opt->funcbody)
1517 show_pre_context(opt, gs, bol, eol, lno);
1518 else if (opt->funcname)
1519 show_funcname_line(opt, gs, bol, lno);
1520 show_line(opt, bol, eol, gs->name, lno, ':');
1521 last_hit = lno;
1522 if (opt->funcbody)
1523 show_function = 1;
1524 goto next_line;
1526 if (show_function && match_funcname(opt, gs, bol, eol))
1527 show_function = 0;
1528 if (show_function ||
1529 (last_hit && lno <= last_hit + opt->post_context)) {
1530 /* If the last hit is within the post context,
1531 * we need to show this line.
1533 show_line(opt, bol, eol, gs->name, lno, '-');
1536 next_line:
1537 bol = eol + 1;
1538 if (!left)
1539 break;
1540 left--;
1541 lno++;
1544 if (collect_hits)
1545 return 0;
1547 if (opt->status_only)
1548 return 0;
1549 if (opt->unmatch_name_only) {
1550 /* We did not see any hit, so we want to show this */
1551 show_name(opt, gs->name);
1552 return 1;
1555 xdiff_clear_find_func(&xecfg);
1556 opt->priv = NULL;
1558 /* NEEDSWORK:
1559 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1560 * which feels mostly useless but sometimes useful. Maybe
1561 * make it another option? For now suppress them.
1563 if (opt->count && count) {
1564 char buf[32];
1565 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1566 output_sep(opt, ':');
1567 snprintf(buf, sizeof(buf), "%u\n", count);
1568 opt->output(opt, buf, strlen(buf));
1569 return 1;
1571 return !!last_hit;
1574 static void clr_hit_marker(struct grep_expr *x)
1576 /* All-hit markers are meaningful only at the very top level
1577 * OR node.
1579 while (1) {
1580 x->hit = 0;
1581 if (x->node != GREP_NODE_OR)
1582 return;
1583 x->u.binary.left->hit = 0;
1584 x = x->u.binary.right;
1588 static int chk_hit_marker(struct grep_expr *x)
1590 /* Top level nodes have hit markers. See if they all are hits */
1591 while (1) {
1592 if (x->node != GREP_NODE_OR)
1593 return x->hit;
1594 if (!x->u.binary.left->hit)
1595 return 0;
1596 x = x->u.binary.right;
1600 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1603 * we do not have to do the two-pass grep when we do not check
1604 * buffer-wide "all-match".
1606 if (!opt->all_match)
1607 return grep_source_1(opt, gs, 0);
1609 /* Otherwise the toplevel "or" terms hit a bit differently.
1610 * We first clear hit markers from them.
1612 clr_hit_marker(opt->pattern_expression);
1613 grep_source_1(opt, gs, 1);
1615 if (!chk_hit_marker(opt->pattern_expression))
1616 return 0;
1618 return grep_source_1(opt, gs, 0);
1621 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1623 struct grep_source gs;
1624 int r;
1626 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1627 gs.buf = buf;
1628 gs.size = size;
1630 r = grep_source(opt, &gs);
1632 grep_source_clear(&gs);
1633 return r;
1636 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1637 const char *name, const char *path,
1638 const void *identifier)
1640 gs->type = type;
1641 gs->name = name ? xstrdup(name) : NULL;
1642 gs->path = path ? xstrdup(path) : NULL;
1643 gs->buf = NULL;
1644 gs->size = 0;
1645 gs->driver = NULL;
1647 switch (type) {
1648 case GREP_SOURCE_FILE:
1649 gs->identifier = xstrdup(identifier);
1650 break;
1651 case GREP_SOURCE_SHA1:
1652 gs->identifier = xmalloc(20);
1653 memcpy(gs->identifier, identifier, 20);
1654 break;
1655 case GREP_SOURCE_BUF:
1656 gs->identifier = NULL;
1660 void grep_source_clear(struct grep_source *gs)
1662 free(gs->name);
1663 gs->name = NULL;
1664 free(gs->path);
1665 gs->path = NULL;
1666 free(gs->identifier);
1667 gs->identifier = NULL;
1668 grep_source_clear_data(gs);
1671 void grep_source_clear_data(struct grep_source *gs)
1673 switch (gs->type) {
1674 case GREP_SOURCE_FILE:
1675 case GREP_SOURCE_SHA1:
1676 free(gs->buf);
1677 gs->buf = NULL;
1678 gs->size = 0;
1679 break;
1680 case GREP_SOURCE_BUF:
1681 /* leave user-provided buf intact */
1682 break;
1686 static int grep_source_load_sha1(struct grep_source *gs)
1688 enum object_type type;
1690 grep_read_lock();
1691 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1692 grep_read_unlock();
1694 if (!gs->buf)
1695 return error(_("'%s': unable to read %s"),
1696 gs->name,
1697 sha1_to_hex(gs->identifier));
1698 return 0;
1701 static int grep_source_load_file(struct grep_source *gs)
1703 const char *filename = gs->identifier;
1704 struct stat st;
1705 char *data;
1706 size_t size;
1707 int i;
1709 if (lstat(filename, &st) < 0) {
1710 err_ret:
1711 if (errno != ENOENT)
1712 error(_("'%s': %s"), filename, strerror(errno));
1713 return -1;
1715 if (!S_ISREG(st.st_mode))
1716 return -1;
1717 size = xsize_t(st.st_size);
1718 i = open(filename, O_RDONLY);
1719 if (i < 0)
1720 goto err_ret;
1721 data = xmalloc(size + 1);
1722 if (st.st_size != read_in_full(i, data, size)) {
1723 error(_("'%s': short read %s"), filename, strerror(errno));
1724 close(i);
1725 free(data);
1726 return -1;
1728 close(i);
1729 data[size] = 0;
1731 gs->buf = data;
1732 gs->size = size;
1733 return 0;
1736 static int grep_source_load(struct grep_source *gs)
1738 if (gs->buf)
1739 return 0;
1741 switch (gs->type) {
1742 case GREP_SOURCE_FILE:
1743 return grep_source_load_file(gs);
1744 case GREP_SOURCE_SHA1:
1745 return grep_source_load_sha1(gs);
1746 case GREP_SOURCE_BUF:
1747 return gs->buf ? 0 : -1;
1749 die("BUG: invalid grep_source type");
1752 void grep_source_load_driver(struct grep_source *gs)
1754 if (gs->driver)
1755 return;
1757 grep_attr_lock();
1758 if (gs->path)
1759 gs->driver = userdiff_find_by_path(gs->path);
1760 if (!gs->driver)
1761 gs->driver = userdiff_find_by_name("default");
1762 grep_attr_unlock();
1765 static int grep_source_is_binary(struct grep_source *gs)
1767 grep_source_load_driver(gs);
1768 if (gs->driver->binary != -1)
1769 return gs->driver->binary;
1771 if (!grep_source_load(gs))
1772 return buffer_is_binary(gs->buf, gs->size);
1774 return 0;