Update draft release notes to Git 2.0
[git/git.git] / grep.c
CommitLineData
83b5d2f5 1#include "cache.h"
83b5d2f5 2#include "grep.h"
60ecac98 3#include "userdiff.h"
6bfce93e 4#include "xdiff-interface.h"
335ec3bf
JK
5#include "diff.h"
6#include "diffcore.h"
83b5d2f5 7
07a7d656
JH
8static int grep_source_load(struct grep_source *gs);
9static int grep_source_is_binary(struct grep_source *gs);
10
7687a054
JH
11static struct grep_opt grep_defaults;
12
13/*
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...
17 */
18void init_grep_defaults(void)
19{
20 struct grep_opt *opt = &grep_defaults;
918d4e1c
JH
21 static int run_once;
22
23 if (run_once)
24 return;
25 run_once++;
7687a054
JH
26
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;
42}
43
44static int parse_pattern_type_arg(const char *opt, const char *arg)
45{
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);
57}
58
59/*
60 * Read the configuration file once and store it in
61 * the grep_defaults template.
62 */
63int grep_config(const char *var, const char *value, void *cb)
64{
65 struct grep_opt *opt = &grep_defaults;
66 char *color = NULL;
67
68 if (userdiff_config(var, value) < 0)
69 return -1;
70
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;
77 }
78
79 if (!strcmp(var, "grep.patterntype")) {
80 opt->pattern_type_option = parse_pattern_type_arg(var, value);
81 return 0;
82 }
83
84 if (!strcmp(var, "grep.linenumber")) {
85 opt->linenum = git_config_bool(var, value);
86 return 0;
87 }
88
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;
105
106 if (color) {
107 if (!value)
108 return config_error_nonbool(var);
109 color_parse(value, var, color);
110 }
111 return 0;
112}
113
114/*
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).
118 */
119void grep_init(struct grep_opt *opt, const char *prefix)
120{
121 struct grep_opt *def = &grep_defaults;
122
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;
128
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;
137
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);
145}
07a7d656 146
c5c31d33
JH
147void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
148{
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);
155}
156
157void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
158{
159 switch (pattern_type) {
160 case GREP_PATTERN_TYPE_UNSPECIFIED:
161 /* fall through */
162
163 case GREP_PATTERN_TYPE_BRE:
164 opt->fixed = 0;
165 opt->pcre = 0;
166 opt->regflags &= ~REG_EXTENDED;
167 break;
168
169 case GREP_PATTERN_TYPE_ERE:
170 opt->fixed = 0;
171 opt->pcre = 0;
172 opt->regflags |= REG_EXTENDED;
173 break;
174
175 case GREP_PATTERN_TYPE_FIXED:
176 opt->fixed = 1;
177 opt->pcre = 0;
178 opt->regflags &= ~REG_EXTENDED;
179 break;
180
181 case GREP_PATTERN_TYPE_PCRE:
182 opt->fixed = 0;
183 opt->pcre = 1;
184 opt->regflags &= ~REG_EXTENDED;
185 break;
186 }
187}
188
fc456751
RS
189static 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)
a4d7d2c6
JH
193{
194 struct grep_pat *p = xcalloc(1, sizeof(*p));
526a858a 195 p->pattern = xmemdupz(pat, patlen);
fc456751
RS
196 p->patternlen = patlen;
197 p->origin = origin;
198 p->no = no;
199 p->token = t;
a4d7d2c6 200 p->field = field;
fc456751
RS
201 return p;
202}
203
2b3873ff
RS
204static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
205{
206 **tail = p;
207 *tail = &p->next;
a4d7d2c6 208 p->next = NULL;
526a858a
RS
209
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;
222 }
223 }
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;
234 }
235 break;
236 default:
237 break;
238 }
2b3873ff
RS
239}
240
fc456751
RS
241void append_header_grep_pattern(struct grep_opt *opt,
242 enum grep_header_field field, const char *pat)
243{
244 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
245 GREP_PATTERN_HEAD, field);
baa6378f
JH
246 if (field == GREP_HEADER_REFLOG)
247 opt->use_reflog_filter = 1;
2b3873ff 248 do_append_grep_pat(&opt->header_tail, p);
a4d7d2c6
JH
249}
250
83b5d2f5
JH
251void append_grep_pattern(struct grep_opt *opt, const char *pat,
252 const char *origin, int no, enum grep_pat_token t)
ed40a095
RS
253{
254 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
255}
256
257void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
258 const char *origin, int no, enum grep_pat_token t)
83b5d2f5 259{
fc456751 260 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
2b3873ff 261 do_append_grep_pat(&opt->pattern_tail, p);
83b5d2f5
JH
262}
263
5b594f45
FK
264struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
265{
266 struct grep_pat *pat;
267 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
268 *ret = *opt;
269
270 ret->pattern_list = NULL;
271 ret->pattern_tail = &ret->pattern_list;
272
273 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
274 {
275 if(pat->token == GREP_PATTERN_HEAD)
276 append_header_grep_pattern(ret, pat->field,
277 pat->pattern);
278 else
ed40a095
RS
279 append_grep_pat(ret, pat->pattern, pat->patternlen,
280 pat->origin, pat->no, pat->token);
5b594f45
FK
281 }
282
283 return ret;
284}
285
a30c148a
MK
286static NORETURN void compile_regexp_failed(const struct grep_pat *p,
287 const char *error)
288{
289 char where[1024];
290
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;
297
298 die("%s'%s': %s", where, p->pattern, error);
299}
300
63e7e9d8
MK
301#ifdef USE_LIBPCRE
302static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
303{
304 const char *error;
305 int erroffset;
fba4f125 306 int options = PCRE_MULTILINE;
63e7e9d8
MK
307
308 if (opt->ignore_case)
309 options |= PCRE_CASELESS;
310
311 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
312 NULL);
313 if (!p->pcre_regexp)
314 compile_regexp_failed(p, error);
315
316 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
317 if (!p->pcre_extra_info && error)
318 die("%s", error);
319}
320
321static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
322 regmatch_t *match, int eflags)
323{
324 int ovector[30], ret, flags = 0;
325
326 if (eflags & REG_NOTBOL)
327 flags |= PCRE_NOTBOL;
328
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];
337 }
338
339 return ret;
340}
341
342static void free_pcre_regexp(struct grep_pat *p)
343{
344 pcre_free(p->pcre_regexp);
345 pcre_free(p->pcre_extra_info);
346}
347#else /* !USE_LIBPCRE */
348static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
349{
350 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
351}
352
353static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
354 regmatch_t *match, int eflags)
355{
356 return 1;
357}
358
359static void free_pcre_regexp(struct grep_pat *p)
360{
361}
362#endif /* !USE_LIBPCRE */
363
9eceddee
FK
364static int is_fixed(const char *s, size_t len)
365{
366 size_t i;
367
368 /* regcomp cannot accept patterns with NULs so we
369 * consider any pattern containing a NUL fixed.
370 */
371 if (memchr(s, 0, len))
372 return 1;
373
374 for (i = 0; i < len; i++) {
375 if (is_regex_special(s[i]))
376 return 0;
377 }
378
379 return 1;
380}
381
83b5d2f5
JH
382static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
383{
c822255c
RS
384 int err;
385
d7eb527d 386 p->word_regexp = opt->word_regexp;
5183bf67 387 p->ignore_case = opt->ignore_case;
d7eb527d 388
9eceddee
FK
389 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
390 p->fixed = 1;
391 else
392 p->fixed = 0;
393
394 if (p->fixed) {
0f871cf5
JH
395 if (opt->regflags & REG_ICASE || p->ignore_case)
396 p->kws = kwsalloc(tolower_trans_tbl);
397 else
9eceddee 398 p->kws = kwsalloc(NULL);
9eceddee
FK
399 kwsincr(p->kws, p->pattern, p->patternlen);
400 kwsprep(p->kws);
c822255c 401 return;
9eceddee 402 }
c822255c 403
63e7e9d8
MK
404 if (opt->pcre) {
405 compile_pcre_regexp(p, opt);
406 return;
407 }
408
c822255c 409 err = regcomp(&p->regexp, p->pattern, opt->regflags);
83b5d2f5
JH
410 if (err) {
411 char errbuf[1024];
83b5d2f5
JH
412 regerror(err, &p->regexp, errbuf, 1024);
413 regfree(&p->regexp);
a30c148a 414 compile_regexp_failed(p, errbuf);
83b5d2f5
JH
415 }
416}
417
0ab7befa 418static struct grep_expr *compile_pattern_or(struct grep_pat **);
83b5d2f5
JH
419static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
420{
421 struct grep_pat *p;
422 struct grep_expr *x;
423
424 p = *list;
c922b01f
LT
425 if (!p)
426 return NULL;
83b5d2f5
JH
427 switch (p->token) {
428 case GREP_PATTERN: /* atom */
480c1ca6
JH
429 case GREP_PATTERN_HEAD:
430 case GREP_PATTERN_BODY:
83b5d2f5
JH
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;
0ab7befa 438 x = compile_pattern_or(list);
83b5d2f5
JH
439 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
440 die("unmatched parenthesis");
441 *list = (*list)->next;
442 return x;
443 default:
444 return NULL;
445 }
446}
447
448static struct grep_expr *compile_pattern_not(struct grep_pat **list)
449{
450 struct grep_pat *p;
451 struct grep_expr *x;
452
453 p = *list;
c922b01f
LT
454 if (!p)
455 return NULL;
83b5d2f5
JH
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);
469 }
470}
471
472static struct grep_expr *compile_pattern_and(struct grep_pat **list)
473{
474 struct grep_pat *p;
475 struct grep_expr *x, *y, *z;
476
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;
491 }
492 return x;
493}
494
495static struct grep_expr *compile_pattern_or(struct grep_pat **list)
496{
497 struct grep_pat *p;
498 struct grep_expr *x, *y, *z;
499
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;
511 }
512 return x;
513}
514
515static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
516{
517 return compile_pattern_or(list);
518}
519
17bf35a3
JH
520static void indent(int in)
521{
522 while (in-- > 0)
523 fputc(' ', stderr);
524}
525
526static void dump_grep_pat(struct grep_pat *p)
527{
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;
534
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;
538 }
539
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;
546 }
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;
554 }
555 fputc('\n', stderr);
556}
557
558static void dump_grep_expression_1(struct grep_expr *x, int in)
559{
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;
588 }
589}
590
07a7d656 591static void dump_grep_expression(struct grep_opt *opt)
17bf35a3
JH
592{
593 struct grep_expr *x = opt->pattern_expression;
594
595 if (opt->all_match)
596 fprintf(stderr, "[all-match]\n");
597 dump_grep_expression_1(x, 0);
598 fflush(NULL);
599}
600
5aaeb733
JH
601static struct grep_expr *grep_true_expr(void)
602{
603 struct grep_expr *z = xcalloc(1, sizeof(*z));
604 z->node = GREP_NODE_TRUE;
605 return z;
606}
607
608static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
609{
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;
615}
616
95ce9ce2 617static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
83b5d2f5
JH
618{
619 struct grep_pat *p;
95ce9ce2 620 struct grep_expr *header_expr;
5aaeb733
JH
621 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
622 enum grep_header_field fld;
83b5d2f5 623
95ce9ce2
JH
624 if (!opt->header_list)
625 return NULL;
2385f246 626
95ce9ce2
JH
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.");
3ce3ffb8
AP
630 if (p->field < GREP_HEADER_FIELD_MIN ||
631 GREP_HEADER_FIELD_MAX <= p->field)
95ce9ce2
JH
632 die("bug: unknown header field %d", p->field);
633 compile_regexp(p, opt);
80235ba7 634 }
5aaeb733
JH
635
636 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
637 header_group[fld] = NULL;
638
639 for (p = opt->header_list; p; p = p->next) {
640 struct grep_expr *h;
641 struct grep_pat *pp = p;
642
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;
649 }
650 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
651 }
652
653 header_expr = NULL;
654
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);
661 }
95ce9ce2
JH
662 return header_expr;
663}
664
13e4fc7e
JH
665static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
666{
667 struct grep_expr *z = x;
668
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;
675 }
676 x = x->u.binary.right;
677 }
678 return z;
679}
680
17bf35a3 681static void compile_grep_patterns_real(struct grep_opt *opt)
95ce9ce2
JH
682{
683 struct grep_pat *p;
684 struct grep_expr *header_expr = prep_header_patterns(opt);
0ab7befa 685
83b5d2f5 686 for (p = opt->pattern_list; p; p = p->next) {
480c1ca6
JH
687 switch (p->token) {
688 case GREP_PATTERN: /* atom */
689 case GREP_PATTERN_HEAD:
690 case GREP_PATTERN_BODY:
c822255c 691 compile_regexp(p, opt);
480c1ca6
JH
692 break;
693 default:
83b5d2f5 694 opt->extended = 1;
480c1ca6
JH
695 break;
696 }
83b5d2f5
JH
697 }
698
80235ba7
JH
699 if (opt->all_match || header_expr)
700 opt->extended = 1;
17bf35a3 701 else if (!opt->extended && !opt->debug)
83b5d2f5
JH
702 return;
703
83b5d2f5 704 p = opt->pattern_list;
ba150a3f
MB
705 if (p)
706 opt->pattern_expression = compile_pattern_expr(&p);
83b5d2f5
JH
707 if (p)
708 die("incomplete pattern expression: %s", p->pattern);
80235ba7
JH
709
710 if (!header_expr)
711 return;
712
5aaeb733 713 if (!opt->pattern_expression)
80235ba7 714 opt->pattern_expression = header_expr;
13e4fc7e
JH
715 else if (opt->all_match)
716 opt->pattern_expression = grep_splice_or(header_expr,
717 opt->pattern_expression);
5aaeb733
JH
718 else
719 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
720 header_expr);
80235ba7 721 opt->all_match = 1;
83b5d2f5
JH
722}
723
17bf35a3
JH
724void compile_grep_patterns(struct grep_opt *opt)
725{
726 compile_grep_patterns_real(opt);
727 if (opt->debug)
728 dump_grep_expression(opt);
729}
730
b48fb5b6
JH
731static void free_pattern_expr(struct grep_expr *x)
732{
733 switch (x->node) {
5aaeb733 734 case GREP_NODE_TRUE:
b48fb5b6
JH
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;
745 }
746 free(x);
747}
748
749void free_grep_patterns(struct grep_opt *opt)
750{
751 struct grep_pat *p, *n;
752
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:
9eceddee
FK
759 if (p->kws)
760 kwsfree(p->kws);
761 else if (p->pcre_regexp)
63e7e9d8
MK
762 free_pcre_regexp(p);
763 else
764 regfree(&p->regexp);
526a858a 765 free(p->pattern);
b48fb5b6
JH
766 break;
767 default:
768 break;
769 }
770 free(p);
771 }
772
773 if (!opt->extended)
774 return;
775 free_pattern_expr(opt->pattern_expression);
776}
777
83b5d2f5
JH
778static char *end_of_line(char *cp, unsigned long *left)
779{
780 unsigned long l = *left;
781 while (l && *cp != '\n') {
782 l--;
783 cp++;
784 }
785 *left = l;
786 return cp;
787}
788
789static int word_char(char ch)
790{
791 return isalnum(ch) || ch == '_';
792}
793
55f638bd
ML
794static void output_color(struct grep_opt *opt, const void *data, size_t size,
795 const char *color)
796{
daa0c3d9 797 if (want_color(opt->color) && color && color[0]) {
55f638bd
ML
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);
803}
804
805static void output_sep(struct grep_opt *opt, char sign)
806{
807 if (opt->null_following_name)
808 opt->output(opt, "\0", 1);
809 else
810 output_color(opt, &sign, 1, opt->color_sep);
811}
812
83caecca
RZ
813static void show_name(struct grep_opt *opt, const char *name)
814{
55f638bd 815 output_color(opt, name, strlen(name), opt->color_filename);
5b594f45 816 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
83caecca
RZ
817}
818
ed40a095
RS
819static int fixmatch(struct grep_pat *p, char *line, char *eol,
820 regmatch_t *match)
83b5d2f5 821{
9eceddee
FK
822 struct kwsmatch kwsm;
823 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
824 if (offset == -1) {
83b5d2f5
JH
825 match->rm_so = match->rm_eo = -1;
826 return REG_NOMATCH;
9eceddee
FK
827 } else {
828 match->rm_so = offset;
829 match->rm_eo = match->rm_so + kwsm.size[0];
83b5d2f5
JH
830 return 0;
831 }
832}
833
f96e5673
RS
834static int regmatch(const regex_t *preg, char *line, char *eol,
835 regmatch_t *match, int eflags)
836{
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);
843}
844
97e77784
MK
845static int patmatch(struct grep_pat *p, char *line, char *eol,
846 regmatch_t *match, int eflags)
847{
848 int hit;
849
850 if (p->fixed)
851 hit = !fixmatch(p, line, eol, match);
63e7e9d8
MK
852 else if (p->pcre_regexp)
853 hit = !pcrematch(p, line, eol, match, eflags);
97e77784
MK
854 else
855 hit = !regmatch(&p->regexp, line, eol, match, eflags);
856
857 return hit;
858}
859
a4d7d2c6
JH
860static int strip_timestamp(char *bol, char **eol_p)
861{
862 char *eol = *eol_p;
863 int ch;
864
865 while (bol < --eol) {
866 if (*eol != '>')
867 continue;
868 *eol_p = ++eol;
869 ch = *eol;
870 *eol = '\0';
871 return ch;
872 }
873 return 0;
874}
875
876static struct {
877 const char *field;
878 size_t len;
879} header_field[] = {
880 { "author ", 7 },
881 { "committer ", 10 },
72fd13f7 882 { "reflog ", 7 },
a4d7d2c6
JH
883};
884
d7eb527d 885static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
79212772
RS
886 enum grep_context ctx,
887 regmatch_t *pmatch, int eflags)
83b5d2f5
JH
888{
889 int hit = 0;
a4d7d2c6 890 int saved_ch = 0;
e701fadb 891 const char *start = bol;
83b5d2f5 892
480c1ca6
JH
893 if ((p->token != GREP_PATTERN) &&
894 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
895 return 0;
896
a4d7d2c6
JH
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;
ad4813b3
NTND
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;
913 }
a4d7d2c6
JH
914 }
915
83b5d2f5 916 again:
97e77784 917 hit = patmatch(p, bol, eol, pmatch, eflags);
83b5d2f5 918
d7eb527d 919 if (hit && p->word_regexp) {
83b5d2f5 920 if ((pmatch[0].rm_so < 0) ||
84201eae 921 (eol - bol) < pmatch[0].rm_so ||
83b5d2f5
JH
922 (pmatch[0].rm_eo < 0) ||
923 (eol - bol) < pmatch[0].rm_eo)
924 die("regexp returned nonsense");
925
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).
931 */
fb62eb7f 932 if ( ((pmatch[0].rm_so == 0) ||
83b5d2f5
JH
933 !word_char(bol[pmatch[0].rm_so-1])) &&
934 ((pmatch[0].rm_eo == (eol-bol)) ||
935 !word_char(bol[pmatch[0].rm_eo])) )
936 ;
937 else
938 hit = 0;
939
84201eae
RS
940 /* Words consist of at least one character. */
941 if (pmatch->rm_so == pmatch->rm_eo)
942 hit = 0;
943
83b5d2f5
JH
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!
fb62eb7f
RS
948 * Forward to the next possible start, i.e. the
949 * next position following a non-word char.
83b5d2f5
JH
950 */
951 bol = pmatch[0].rm_so + bol + 1;
fb62eb7f
RS
952 while (word_char(bol[-1]) && bol < eol)
953 bol++;
dbb6a4ad 954 eflags |= REG_NOTBOL;
fb62eb7f
RS
955 if (bol < eol)
956 goto again;
83b5d2f5
JH
957 }
958 }
a4d7d2c6
JH
959 if (p->token == GREP_PATTERN_HEAD && saved_ch)
960 *eol = saved_ch;
e701fadb
RS
961 if (hit) {
962 pmatch[0].rm_so += bol - start;
963 pmatch[0].rm_eo += bol - start;
964 }
83b5d2f5
JH
965 return hit;
966}
967
d7eb527d
RS
968static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
969 enum grep_context ctx, int collect_hits)
83b5d2f5 970{
0ab7befa 971 int h = 0;
79212772 972 regmatch_t match;
0ab7befa 973
c922b01f
LT
974 if (!x)
975 die("Not a valid grep expression");
83b5d2f5 976 switch (x->node) {
5aaeb733
JH
977 case GREP_NODE_TRUE:
978 h = 1;
979 break;
83b5d2f5 980 case GREP_NODE_ATOM:
79212772 981 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
83b5d2f5
JH
982 break;
983 case GREP_NODE_NOT:
d7eb527d 984 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
0ab7befa 985 break;
83b5d2f5 986 case GREP_NODE_AND:
d7eb527d 987 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
252d560d 988 return 0;
d7eb527d 989 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
0ab7befa 990 break;
83b5d2f5 991 case GREP_NODE_OR:
0ab7befa 992 if (!collect_hits)
d7eb527d 993 return (match_expr_eval(x->u.binary.left,
0ab7befa 994 bol, eol, ctx, 0) ||
d7eb527d 995 match_expr_eval(x->u.binary.right,
0ab7befa 996 bol, eol, ctx, 0));
d7eb527d 997 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
0ab7befa 998 x->u.binary.left->hit |= h;
d7eb527d 999 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
0ab7befa
JH
1000 break;
1001 default:
d7530708 1002 die("Unexpected node type (internal error) %d", x->node);
83b5d2f5 1003 }
0ab7befa
JH
1004 if (collect_hits)
1005 x->hit |= h;
1006 return h;
83b5d2f5
JH
1007}
1008
480c1ca6 1009static int match_expr(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1010 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1011{
1012 struct grep_expr *x = opt->pattern_expression;
d7eb527d 1013 return match_expr_eval(x, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1014}
1015
480c1ca6 1016static int match_line(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1017 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1018{
1019 struct grep_pat *p;
79212772
RS
1020 regmatch_t match;
1021
83b5d2f5 1022 if (opt->extended)
0ab7befa
JH
1023 return match_expr(opt, bol, eol, ctx, collect_hits);
1024
1025 /* we do not call with collect_hits without being extended */
83b5d2f5 1026 for (p = opt->pattern_list; p; p = p->next) {
79212772 1027 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
83b5d2f5
JH
1028 return 1;
1029 }
1030 return 0;
1031}
1032
7e8f59d5
RS
1033static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1034 enum grep_context ctx,
1035 regmatch_t *pmatch, int eflags)
1036{
1037 regmatch_t match;
1038
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;
1048 }
1049 pmatch->rm_so = match.rm_so;
1050 pmatch->rm_eo = match.rm_eo;
1051 return 1;
1052}
1053
1054static int next_match(struct grep_opt *opt, char *bol, char *eol,
1055 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1056{
1057 struct grep_pat *p;
1058 int hit = 0;
1059
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;
1072 }
1073 }
1074 }
1075 return hit;
1076}
1077
1078static void show_line(struct grep_opt *opt, char *bol, char *eol,
1079 const char *name, unsigned lno, char sign)
1080{
1081 int rest = eol - bol;
00588bb5 1082 char *line_color = NULL;
7e8f59d5 1083
a8f0e764
RS
1084 if (opt->file_break && opt->last_shown == 0) {
1085 if (opt->show_hunk_mark)
1086 opt->output(opt, "\n", 1);
ba8ea749 1087 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
046802d0 1088 if (opt->last_shown == 0) {
55f638bd
ML
1089 if (opt->show_hunk_mark) {
1090 output_color(opt, "--", 2, opt->color_sep);
1091 opt->output(opt, "\n", 1);
07b838f0 1092 }
55f638bd
ML
1093 } else if (lno > opt->last_shown + 1) {
1094 output_color(opt, "--", 2, opt->color_sep);
1095 opt->output(opt, "\n", 1);
1096 }
5dd06d38 1097 }
1d84f72e
RS
1098 if (opt->heading && opt->last_shown == 0) {
1099 output_color(opt, name, strlen(name), opt->color_filename);
1100 opt->output(opt, "\n", 1);
1101 }
5dd06d38
RS
1102 opt->last_shown = lno;
1103
1d84f72e 1104 if (!opt->heading && opt->pathname) {
55f638bd
ML
1105 output_color(opt, name, strlen(name), opt->color_filename);
1106 output_sep(opt, sign);
5b594f45
FK
1107 }
1108 if (opt->linenum) {
1109 char buf[32];
1110 snprintf(buf, sizeof(buf), "%d", lno);
55f638bd
ML
1111 output_color(opt, buf, strlen(buf), opt->color_lineno);
1112 output_sep(opt, sign);
5b594f45 1113 }
7e8f59d5
RS
1114 if (opt->color) {
1115 regmatch_t match;
1116 enum grep_context ctx = GREP_CONTEXT_BODY;
1117 int ch = *eol;
1118 int eflags = 0;
1119
00588bb5
ML
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;
7e8f59d5
RS
1126 *eol = '\0';
1127 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1f5b9cc4
RS
1128 if (match.rm_so == match.rm_eo)
1129 break;
5b594f45 1130
00588bb5 1131 output_color(opt, bol, match.rm_so, line_color);
55f638bd
ML
1132 output_color(opt, bol + match.rm_so,
1133 match.rm_eo - match.rm_so,
1134 opt->color_match);
7e8f59d5
RS
1135 bol += match.rm_eo;
1136 rest -= match.rm_eo;
1137 eflags = REG_NOTBOL;
1138 }
1139 *eol = ch;
1140 }
00588bb5 1141 output_color(opt, bol, rest, line_color);
5b594f45 1142 opt->output(opt, "\n", 1);
7e8f59d5
RS
1143}
1144
0579f91d 1145#ifndef NO_PTHREADS
78db6ea9
JK
1146int grep_use_locks;
1147
0579f91d
TR
1148/*
1149 * This lock protects access to the gitattributes machinery, which is
1150 * not thread-safe.
1151 */
1152pthread_mutex_t grep_attr_mutex;
1153
78db6ea9 1154static inline void grep_attr_lock(void)
0579f91d 1155{
78db6ea9 1156 if (grep_use_locks)
0579f91d
TR
1157 pthread_mutex_lock(&grep_attr_mutex);
1158}
1159
78db6ea9 1160static inline void grep_attr_unlock(void)
0579f91d 1161{
78db6ea9 1162 if (grep_use_locks)
0579f91d
TR
1163 pthread_mutex_unlock(&grep_attr_mutex);
1164}
b3aeb285
JK
1165
1166/*
1167 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1168 */
1169pthread_mutex_t grep_read_mutex;
1170
0579f91d 1171#else
78db6ea9
JK
1172#define grep_attr_lock()
1173#define grep_attr_unlock()
0579f91d
TR
1174#endif
1175
e1327023 1176static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
2944e4e6 1177{
60ecac98 1178 xdemitconf_t *xecfg = opt->priv;
0579f91d 1179 if (xecfg && !xecfg->find_func) {
94ad9d9e
JK
1180 grep_source_load_driver(gs);
1181 if (gs->driver->funcname.pattern) {
1182 const struct userdiff_funcname *pe = &gs->driver->funcname;
0579f91d
TR
1183 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1184 } else {
1185 xecfg = opt->priv = NULL;
1186 }
1187 }
1188
1189 if (xecfg) {
60ecac98
RS
1190 char buf[1];
1191 return xecfg->find_func(bol, eol - bol, buf, 1,
1192 xecfg->find_func_priv) >= 0;
1193 }
1194
2944e4e6
RS
1195 if (bol == eol)
1196 return 0;
1197 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1198 return 1;
1199 return 0;
1200}
1201
e1327023
JK
1202static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1203 char *bol, unsigned lno)
2944e4e6 1204{
e1327023 1205 while (bol > gs->buf) {
2944e4e6
RS
1206 char *eol = --bol;
1207
e1327023 1208 while (bol > gs->buf && bol[-1] != '\n')
2944e4e6
RS
1209 bol--;
1210 lno--;
1211
1212 if (lno <= opt->last_shown)
1213 break;
1214
e1327023
JK
1215 if (match_funcname(opt, gs, bol, eol)) {
1216 show_line(opt, bol, eol, gs->name, lno, '=');
2944e4e6
RS
1217 break;
1218 }
1219 }
1220}
1221
e1327023 1222static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
ba8ea749 1223 char *bol, char *end, unsigned lno)
49de3216 1224{
2944e4e6 1225 unsigned cur = lno, from = 1, funcname_lno = 0;
ba8ea749
RS
1226 int funcname_needed = !!opt->funcname;
1227
e1327023 1228 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
ba8ea749 1229 funcname_needed = 2;
49de3216
RS
1230
1231 if (opt->pre_context < lno)
1232 from = lno - opt->pre_context;
1233 if (from <= opt->last_shown)
1234 from = opt->last_shown + 1;
1235
1236 /* Rewind. */
e1327023 1237 while (bol > gs->buf &&
ba8ea749 1238 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
2944e4e6
RS
1239 char *eol = --bol;
1240
e1327023 1241 while (bol > gs->buf && bol[-1] != '\n')
49de3216
RS
1242 bol--;
1243 cur--;
e1327023 1244 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
2944e4e6
RS
1245 funcname_lno = cur;
1246 funcname_needed = 0;
1247 }
49de3216
RS
1248 }
1249
2944e4e6
RS
1250 /* We need to look even further back to find a function signature. */
1251 if (opt->funcname && funcname_needed)
e1327023 1252 show_funcname_line(opt, gs, bol, cur);
2944e4e6 1253
49de3216
RS
1254 /* Back forward. */
1255 while (cur < lno) {
2944e4e6 1256 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
49de3216
RS
1257
1258 while (*eol != '\n')
1259 eol++;
e1327023 1260 show_line(opt, bol, eol, gs->name, cur, sign);
49de3216
RS
1261 bol = eol + 1;
1262 cur++;
1263 }
1264}
1265
a26345b6
JH
1266static int should_lookahead(struct grep_opt *opt)
1267{
1268 struct grep_pat *p;
1269
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 */
1277 }
1278 return 1;
1279}
1280
1281static int look_ahead(struct grep_opt *opt,
1282 unsigned long *left_p,
1283 unsigned *lno_p,
1284 char **bol_p)
1285{
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;
1291
1292 for (p = opt->pattern_list; p; p = p->next) {
1293 int hit;
1294 regmatch_t m;
1295
97e77784 1296 hit = patmatch(p, bol, bol + *left_p, &m, 0);
a26345b6
JH
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;
1301 }
1302
1303 if (earliest < 0) {
1304 *bol_p = bol + *left_p;
1305 *left_p = 0;
1306 return 1;
1307 }
1308 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1309 ; /* find the beginning of the line */
1310 last_bol = sp;
1311
1312 for (sp = bol; sp < last_bol; sp++) {
1313 if (*sp == '\n')
1314 lno++;
1315 }
1316 *left_p -= last_bol - bol;
1317 *bol_p = last_bol;
1318 *lno_p = lno;
1319 return 0;
1320}
1321
5b594f45
FK
1322static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1323{
1324 fwrite(buf, size, 1, stdout);
1325}
1326
335ec3bf
JK
1327static int fill_textconv_grep(struct userdiff_driver *driver,
1328 struct grep_source *gs)
1329{
1330 struct diff_filespec *df;
1331 char *buf;
1332 size_t size;
1333
1334 if (!driver || !driver->textconv)
1335 return grep_source_load(gs);
1336
1337 /*
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.
1341 */
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?");
1352 }
1353
1354 /*
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.
1358 */
1359 grep_read_lock();
1360 size = fill_textconv(driver, df, &buf);
1361 grep_read_unlock();
1362 free_filespec(df);
1363
1364 /*
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.
1371 */
1372 grep_source_clear_data(gs);
1373 gs->buf = buf;
1374 gs->size = size;
1375
1376 return 0;
1377}
1378
e1327023 1379static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
83b5d2f5 1380{
e1327023
JK
1381 char *bol;
1382 unsigned long left;
83b5d2f5 1383 unsigned lno = 1;
83b5d2f5 1384 unsigned last_hit = 0;
83b5d2f5 1385 int binary_match_only = 0;
83b5d2f5 1386 unsigned count = 0;
a26345b6 1387 int try_lookahead = 0;
ba8ea749 1388 int show_function = 0;
335ec3bf 1389 struct userdiff_driver *textconv = NULL;
480c1ca6 1390 enum grep_context ctx = GREP_CONTEXT_HEAD;
60ecac98 1391 xdemitconf_t xecfg;
83b5d2f5 1392
5b594f45
FK
1393 if (!opt->output)
1394 opt->output = std_output;
1395
ba8ea749
RS
1396 if (opt->pre_context || opt->post_context || opt->file_break ||
1397 opt->funcbody) {
08303c36
RS
1398 /* Show hunk marks, except for the first file. */
1399 if (opt->last_shown)
1400 opt->show_hunk_mark = 1;
1401 /*
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().
1405 */
1406 if (opt->output != std_output)
1407 opt->show_hunk_mark = 1;
1408 }
431d6e7b
RS
1409 opt->last_shown = 0;
1410
335ec3bf
JK
1411 if (opt->allow_textconv) {
1412 grep_source_load_driver(gs);
1413 /*
1414 * We might set up the shared textconv cache data here, which
1415 * is not thread-safe.
1416 */
1417 grep_attr_lock();
1418 textconv = userdiff_get_textconv(gs->driver);
1419 grep_attr_unlock();
1420 }
1421
1422 /*
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.
1425 */
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");
1440 }
83b5d2f5
JH
1441 }
1442
60ecac98 1443 memset(&xecfg, 0, sizeof(xecfg));
0579f91d
TR
1444 opt->priv = &xecfg;
1445
a26345b6 1446 try_lookahead = should_lookahead(opt);
60ecac98 1447
335ec3bf 1448 if (fill_textconv_grep(textconv, gs) < 0)
08265798
JK
1449 return 0;
1450
e1327023
JK
1451 bol = gs->buf;
1452 left = gs->size;
83b5d2f5
JH
1453 while (left) {
1454 char *eol, ch;
0ab7befa 1455 int hit;
83b5d2f5 1456
a26345b6 1457 /*
8997da38 1458 * look_ahead() skips quickly to the line that possibly
a26345b6
JH
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.
1465 */
1466 if (try_lookahead
1467 && !(last_hit
ba8ea749
RS
1468 && (show_function ||
1469 lno <= last_hit + opt->post_context))
a26345b6
JH
1470 && look_ahead(opt, &left, &lno, &bol))
1471 break;
83b5d2f5
JH
1472 eol = end_of_line(bol, &left);
1473 ch = *eol;
1474 *eol = 0;
1475
480c1ca6
JH
1476 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1477 ctx = GREP_CONTEXT_BODY;
1478
0ab7befa 1479 hit = match_line(opt, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1480 *eol = ch;
1481
0ab7befa
JH
1482 if (collect_hits)
1483 goto next_line;
1484
83b5d2f5
JH
1485 /* "grep -v -e foo -e bla" should list lines
1486 * that do not have either, so inversion should
1487 * be done outside.
1488 */
1489 if (opt->invert)
1490 hit = !hit;
1491 if (opt->unmatch_name_only) {
1492 if (hit)
1493 return 0;
1494 goto next_line;
1495 }
1496 if (hit) {
1497 count++;
1498 if (opt->status_only)
1499 return 1;
321ffcc0 1500 if (opt->name_only) {
e1327023 1501 show_name(opt, gs->name);
321ffcc0
RS
1502 return 1;
1503 }
c30c10cf
RS
1504 if (opt->count)
1505 goto next_line;
83b5d2f5 1506 if (binary_match_only) {
5b594f45 1507 opt->output(opt, "Binary file ", 12);
e1327023 1508 output_color(opt, gs->name, strlen(gs->name),
55f638bd 1509 opt->color_filename);
5b594f45 1510 opt->output(opt, " matches\n", 9);
83b5d2f5
JH
1511 return 1;
1512 }
83b5d2f5
JH
1513 /* Hit at this line. If we haven't shown the
1514 * pre-context lines, we would need to show them.
83b5d2f5 1515 */
ba8ea749 1516 if (opt->pre_context || opt->funcbody)
e1327023 1517 show_pre_context(opt, gs, bol, eol, lno);
2944e4e6 1518 else if (opt->funcname)
e1327023
JK
1519 show_funcname_line(opt, gs, bol, lno);
1520 show_line(opt, bol, eol, gs->name, lno, ':');
5dd06d38 1521 last_hit = lno;
ba8ea749
RS
1522 if (opt->funcbody)
1523 show_function = 1;
1524 goto next_line;
83b5d2f5 1525 }
e1327023 1526 if (show_function && match_funcname(opt, gs, bol, eol))
ba8ea749
RS
1527 show_function = 0;
1528 if (show_function ||
1529 (last_hit && lno <= last_hit + opt->post_context)) {
83b5d2f5
JH
1530 /* If the last hit is within the post context,
1531 * we need to show this line.
1532 */
e1327023 1533 show_line(opt, bol, eol, gs->name, lno, '-');
83b5d2f5 1534 }
83b5d2f5
JH
1535
1536 next_line:
1537 bol = eol + 1;
1538 if (!left)
1539 break;
1540 left--;
1541 lno++;
1542 }
1543
0ab7befa
JH
1544 if (collect_hits)
1545 return 0;
b48fb5b6 1546
83b5d2f5
JH
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 */
e1327023 1551 show_name(opt, gs->name);
83b5d2f5
JH
1552 return 1;
1553 }
1554
60ecac98
RS
1555 xdiff_clear_find_func(&xecfg);
1556 opt->priv = NULL;
1557
83b5d2f5
JH
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.
1562 */
5b594f45
FK
1563 if (opt->count && count) {
1564 char buf[32];
e1327023 1565 output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
55f638bd
ML
1566 output_sep(opt, ':');
1567 snprintf(buf, sizeof(buf), "%u\n", count);
5b594f45 1568 opt->output(opt, buf, strlen(buf));
c30c10cf 1569 return 1;
5b594f45 1570 }
83b5d2f5
JH
1571 return !!last_hit;
1572}
1573
0ab7befa
JH
1574static void clr_hit_marker(struct grep_expr *x)
1575{
1576 /* All-hit markers are meaningful only at the very top level
1577 * OR node.
1578 */
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;
1585 }
1586}
1587
1588static int chk_hit_marker(struct grep_expr *x)
1589{
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;
1597 }
1598}
1599
e1327023 1600int grep_source(struct grep_opt *opt, struct grep_source *gs)
0ab7befa
JH
1601{
1602 /*
1603 * we do not have to do the two-pass grep when we do not check
1604 * buffer-wide "all-match".
1605 */
1606 if (!opt->all_match)
e1327023 1607 return grep_source_1(opt, gs, 0);
0ab7befa
JH
1608
1609 /* Otherwise the toplevel "or" terms hit a bit differently.
1610 * We first clear hit markers from them.
1611 */
1612 clr_hit_marker(opt->pattern_expression);
e1327023 1613 grep_source_1(opt, gs, 1);
0ab7befa
JH
1614
1615 if (!chk_hit_marker(opt->pattern_expression))
1616 return 0;
1617
e1327023
JK
1618 return grep_source_1(opt, gs, 0);
1619}
1620
c876d6da 1621int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
e1327023
JK
1622{
1623 struct grep_source gs;
1624 int r;
1625
55c61688 1626 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
e1327023
JK
1627 gs.buf = buf;
1628 gs.size = size;
1629
1630 r = grep_source(opt, &gs);
1631
1632 grep_source_clear(&gs);
1633 return r;
1634}
1635
1636void grep_source_init(struct grep_source *gs, enum grep_source_type type,
55c61688
NTND
1637 const char *name, const char *path,
1638 const void *identifier)
e1327023
JK
1639{
1640 gs->type = type;
1641 gs->name = name ? xstrdup(name) : NULL;
55c61688 1642 gs->path = path ? xstrdup(path) : NULL;
e1327023
JK
1643 gs->buf = NULL;
1644 gs->size = 0;
94ad9d9e 1645 gs->driver = NULL;
e1327023
JK
1646
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;
1657 }
1658}
1659
1660void grep_source_clear(struct grep_source *gs)
1661{
1662 free(gs->name);
1663 gs->name = NULL;
55c61688
NTND
1664 free(gs->path);
1665 gs->path = NULL;
e1327023
JK
1666 free(gs->identifier);
1667 gs->identifier = NULL;
1668 grep_source_clear_data(gs);
1669}
1670
1671void grep_source_clear_data(struct grep_source *gs)
1672{
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;
1683 }
1684}
1685
1686static int grep_source_load_sha1(struct grep_source *gs)
1687{
1688 enum object_type type;
1689
1690 grep_read_lock();
1691 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1692 grep_read_unlock();
1693
1694 if (!gs->buf)
1695 return error(_("'%s': unable to read %s"),
1696 gs->name,
1697 sha1_to_hex(gs->identifier));
1698 return 0;
1699}
1700
1701static int grep_source_load_file(struct grep_source *gs)
1702{
1703 const char *filename = gs->identifier;
1704 struct stat st;
1705 char *data;
1706 size_t size;
1707 int i;
1708
1709 if (lstat(filename, &st) < 0) {
1710 err_ret:
1711 if (errno != ENOENT)
1712 error(_("'%s': %s"), filename, strerror(errno));
1713 return -1;
1714 }
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;
1727 }
1728 close(i);
1729 data[size] = 0;
1730
1731 gs->buf = data;
1732 gs->size = size;
1733 return 0;
1734}
1735
3083301e 1736static int grep_source_load(struct grep_source *gs)
e1327023
JK
1737{
1738 if (gs->buf)
1739 return 0;
1740
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;
1748 }
1749 die("BUG: invalid grep_source type");
0ab7befa 1750}
94ad9d9e
JK
1751
1752void grep_source_load_driver(struct grep_source *gs)
1753{
1754 if (gs->driver)
1755 return;
1756
1757 grep_attr_lock();
55c61688
NTND
1758 if (gs->path)
1759 gs->driver = userdiff_find_by_path(gs->path);
94ad9d9e
JK
1760 if (!gs->driver)
1761 gs->driver = userdiff_find_by_name("default");
1762 grep_attr_unlock();
1763}
41b59bfc 1764
3083301e 1765static int grep_source_is_binary(struct grep_source *gs)
41b59bfc
JK
1766{
1767 grep_source_load_driver(gs);
1768 if (gs->driver->binary != -1)
1769 return gs->driver->binary;
1770
1771 if (!grep_source_load(gs))
1772 return buffer_is_binary(gs->buf, gs->size);
1773
1774 return 0;
1775}