]> git.ipfire.org Git - thirdparty/git.git/blame - grep.c
diff: convert diff_change to struct object_id
[thirdparty/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"
5c1ebcca 7#include "commit.h"
793dc676 8#include "quote.h"
83b5d2f5 9
07a7d656
JH
10static int grep_source_load(struct grep_source *gs);
11static int grep_source_is_binary(struct grep_source *gs);
12
7687a054
JH
13static struct grep_opt grep_defaults;
14
379642bc
BW
15static void std_output(struct grep_opt *opt, const void *buf, size_t size)
16{
17 fwrite(buf, size, 1, stdout);
18}
19
7687a054
JH
20/*
21 * Initialize the grep_defaults template with hardcoded defaults.
22 * We could let the compiler do this, but without C99 initializers
23 * the code gets unwieldy and unreadable, so...
24 */
25void init_grep_defaults(void)
26{
27 struct grep_opt *opt = &grep_defaults;
918d4e1c
JH
28 static int run_once;
29
30 if (run_once)
31 return;
32 run_once++;
7687a054
JH
33
34 memset(opt, 0, sizeof(*opt));
35 opt->relative = 1;
36 opt->pathname = 1;
37 opt->regflags = REG_NEWLINE;
38 opt->max_depth = -1;
39 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
40 opt->extended_regexp_option = 0;
7ce4fb94
JK
41 color_set(opt->color_context, "");
42 color_set(opt->color_filename, "");
43 color_set(opt->color_function, "");
44 color_set(opt->color_lineno, "");
45 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
46 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_selected, "");
48 color_set(opt->color_sep, GIT_COLOR_CYAN);
7687a054 49 opt->color = -1;
379642bc 50 opt->output = std_output;
7687a054
JH
51}
52
53static int parse_pattern_type_arg(const char *opt, const char *arg)
54{
55 if (!strcmp(arg, "default"))
56 return GREP_PATTERN_TYPE_UNSPECIFIED;
57 else if (!strcmp(arg, "basic"))
58 return GREP_PATTERN_TYPE_BRE;
59 else if (!strcmp(arg, "extended"))
60 return GREP_PATTERN_TYPE_ERE;
61 else if (!strcmp(arg, "fixed"))
62 return GREP_PATTERN_TYPE_FIXED;
63 else if (!strcmp(arg, "perl"))
64 return GREP_PATTERN_TYPE_PCRE;
65 die("bad %s argument: %s", opt, arg);
66}
67
68/*
69 * Read the configuration file once and store it in
70 * the grep_defaults template.
71 */
72int grep_config(const char *var, const char *value, void *cb)
73{
74 struct grep_opt *opt = &grep_defaults;
75 char *color = NULL;
76
77 if (userdiff_config(var, value) < 0)
78 return -1;
79
80 if (!strcmp(var, "grep.extendedregexp")) {
81 if (git_config_bool(var, value))
82 opt->extended_regexp_option = 1;
83 else
84 opt->extended_regexp_option = 0;
85 return 0;
86 }
87
88 if (!strcmp(var, "grep.patterntype")) {
89 opt->pattern_type_option = parse_pattern_type_arg(var, value);
90 return 0;
91 }
92
93 if (!strcmp(var, "grep.linenumber")) {
94 opt->linenum = git_config_bool(var, value);
95 return 0;
96 }
97
6453f7b3
AS
98 if (!strcmp(var, "grep.fullname")) {
99 opt->relative = !git_config_bool(var, value);
100 return 0;
101 }
102
7687a054
JH
103 if (!strcmp(var, "color.grep"))
104 opt->color = git_config_colorbool(var, value);
105 else if (!strcmp(var, "color.grep.context"))
106 color = opt->color_context;
107 else if (!strcmp(var, "color.grep.filename"))
108 color = opt->color_filename;
109 else if (!strcmp(var, "color.grep.function"))
110 color = opt->color_function;
111 else if (!strcmp(var, "color.grep.linenumber"))
112 color = opt->color_lineno;
79a77109
RS
113 else if (!strcmp(var, "color.grep.matchcontext"))
114 color = opt->color_match_context;
115 else if (!strcmp(var, "color.grep.matchselected"))
116 color = opt->color_match_selected;
7687a054
JH
117 else if (!strcmp(var, "color.grep.selected"))
118 color = opt->color_selected;
119 else if (!strcmp(var, "color.grep.separator"))
120 color = opt->color_sep;
79a77109
RS
121 else if (!strcmp(var, "color.grep.match")) {
122 int rc = 0;
123 if (!value)
124 return config_error_nonbool(var);
bf1f639e
JH
125 rc |= color_parse(value, opt->color_match_context);
126 rc |= color_parse(value, opt->color_match_selected);
79a77109
RS
127 return rc;
128 }
7687a054
JH
129
130 if (color) {
131 if (!value)
132 return config_error_nonbool(var);
f6c5a296 133 return color_parse(value, color);
7687a054
JH
134 }
135 return 0;
136}
137
138/*
139 * Initialize one instance of grep_opt and copy the
140 * default values from the template we read the configuration
141 * information in an earlier call to git_config(grep_config).
142 */
143void grep_init(struct grep_opt *opt, const char *prefix)
144{
145 struct grep_opt *def = &grep_defaults;
146
147 memset(opt, 0, sizeof(*opt));
148 opt->prefix = prefix;
149 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
150 opt->pattern_tail = &opt->pattern_list;
151 opt->header_tail = &opt->header_list;
152
153 opt->color = def->color;
154 opt->extended_regexp_option = def->extended_regexp_option;
155 opt->pattern_type_option = def->pattern_type_option;
156 opt->linenum = def->linenum;
157 opt->max_depth = def->max_depth;
158 opt->pathname = def->pathname;
159 opt->regflags = def->regflags;
160 opt->relative = def->relative;
379642bc 161 opt->output = def->output;
7687a054 162
7ce4fb94
JK
163 color_set(opt->color_context, def->color_context);
164 color_set(opt->color_filename, def->color_filename);
165 color_set(opt->color_function, def->color_function);
166 color_set(opt->color_lineno, def->color_lineno);
167 color_set(opt->color_match_context, def->color_match_context);
168 color_set(opt->color_match_selected, def->color_match_selected);
169 color_set(opt->color_selected, def->color_selected);
170 color_set(opt->color_sep, def->color_sep);
7687a054 171}
07a7d656 172
8465541e 173static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
c5c31d33
JH
174{
175 switch (pattern_type) {
176 case GREP_PATTERN_TYPE_UNSPECIFIED:
177 /* fall through */
178
179 case GREP_PATTERN_TYPE_BRE:
180 opt->fixed = 0;
181 opt->pcre = 0;
182 opt->regflags &= ~REG_EXTENDED;
183 break;
184
185 case GREP_PATTERN_TYPE_ERE:
186 opt->fixed = 0;
187 opt->pcre = 0;
188 opt->regflags |= REG_EXTENDED;
189 break;
190
191 case GREP_PATTERN_TYPE_FIXED:
192 opt->fixed = 1;
193 opt->pcre = 0;
194 opt->regflags &= ~REG_EXTENDED;
195 break;
196
197 case GREP_PATTERN_TYPE_PCRE:
198 opt->fixed = 0;
199 opt->pcre = 1;
200 opt->regflags &= ~REG_EXTENDED;
201 break;
202 }
203}
204
8465541e
JH
205void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
206{
207 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
208 grep_set_pattern_type_option(pattern_type, opt);
209 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
210 grep_set_pattern_type_option(opt->pattern_type_option, opt);
211 else if (opt->extended_regexp_option)
212 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
213}
214
fc456751
RS
215static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
216 const char *origin, int no,
217 enum grep_pat_token t,
218 enum grep_header_field field)
a4d7d2c6
JH
219{
220 struct grep_pat *p = xcalloc(1, sizeof(*p));
526a858a 221 p->pattern = xmemdupz(pat, patlen);
fc456751
RS
222 p->patternlen = patlen;
223 p->origin = origin;
224 p->no = no;
225 p->token = t;
a4d7d2c6 226 p->field = field;
fc456751
RS
227 return p;
228}
229
2b3873ff
RS
230static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
231{
232 **tail = p;
233 *tail = &p->next;
a4d7d2c6 234 p->next = NULL;
526a858a
RS
235
236 switch (p->token) {
237 case GREP_PATTERN: /* atom */
238 case GREP_PATTERN_HEAD:
239 case GREP_PATTERN_BODY:
240 for (;;) {
241 struct grep_pat *new_pat;
242 size_t len = 0;
243 char *cp = p->pattern + p->patternlen, *nl = NULL;
244 while (++len <= p->patternlen) {
245 if (*(--cp) == '\n') {
246 nl = cp;
247 break;
248 }
249 }
250 if (!nl)
251 break;
252 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
253 p->no, p->token, p->field);
254 new_pat->next = p->next;
255 if (!p->next)
256 *tail = &new_pat->next;
257 p->next = new_pat;
258 *nl = '\0';
259 p->patternlen -= len;
260 }
261 break;
262 default:
263 break;
264 }
2b3873ff
RS
265}
266
fc456751
RS
267void append_header_grep_pattern(struct grep_opt *opt,
268 enum grep_header_field field, const char *pat)
269{
270 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
271 GREP_PATTERN_HEAD, field);
baa6378f
JH
272 if (field == GREP_HEADER_REFLOG)
273 opt->use_reflog_filter = 1;
2b3873ff 274 do_append_grep_pat(&opt->header_tail, p);
a4d7d2c6
JH
275}
276
83b5d2f5
JH
277void append_grep_pattern(struct grep_opt *opt, const char *pat,
278 const char *origin, int no, enum grep_pat_token t)
ed40a095
RS
279{
280 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
281}
282
283void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
284 const char *origin, int no, enum grep_pat_token t)
83b5d2f5 285{
fc456751 286 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
2b3873ff 287 do_append_grep_pat(&opt->pattern_tail, p);
83b5d2f5
JH
288}
289
5b594f45
FK
290struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
291{
292 struct grep_pat *pat;
293 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
294 *ret = *opt;
295
296 ret->pattern_list = NULL;
297 ret->pattern_tail = &ret->pattern_list;
298
299 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
300 {
301 if(pat->token == GREP_PATTERN_HEAD)
302 append_header_grep_pattern(ret, pat->field,
303 pat->pattern);
304 else
ed40a095
RS
305 append_grep_pat(ret, pat->pattern, pat->patternlen,
306 pat->origin, pat->no, pat->token);
5b594f45
FK
307 }
308
309 return ret;
310}
311
a30c148a
MK
312static NORETURN void compile_regexp_failed(const struct grep_pat *p,
313 const char *error)
314{
315 char where[1024];
316
317 if (p->no)
19bdd3e7 318 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
a30c148a 319 else if (p->origin)
19bdd3e7 320 xsnprintf(where, sizeof(where), "%s, ", p->origin);
a30c148a
MK
321 else
322 where[0] = 0;
323
324 die("%s'%s': %s", where, p->pattern, error);
325}
326
63e7e9d8
MK
327#ifdef USE_LIBPCRE
328static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
329{
330 const char *error;
331 int erroffset;
fba4f125 332 int options = PCRE_MULTILINE;
63e7e9d8 333
9d9babb8
NTND
334 if (opt->ignore_case) {
335 if (has_non_ascii(p->pattern))
336 p->pcre_tables = pcre_maketables();
63e7e9d8 337 options |= PCRE_CASELESS;
9d9babb8 338 }
18547aac
NTND
339 if (is_utf8_locale() && has_non_ascii(p->pattern))
340 options |= PCRE_UTF8;
63e7e9d8
MK
341
342 p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
9d9babb8 343 p->pcre_tables);
63e7e9d8
MK
344 if (!p->pcre_regexp)
345 compile_regexp_failed(p, error);
346
347 p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
348 if (!p->pcre_extra_info && error)
349 die("%s", error);
350}
351
352static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
353 regmatch_t *match, int eflags)
354{
355 int ovector[30], ret, flags = 0;
356
357 if (eflags & REG_NOTBOL)
358 flags |= PCRE_NOTBOL;
359
360 ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
361 0, flags, ovector, ARRAY_SIZE(ovector));
362 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
363 die("pcre_exec failed with error code %d", ret);
364 if (ret > 0) {
365 ret = 0;
366 match->rm_so = ovector[0];
367 match->rm_eo = ovector[1];
368 }
369
370 return ret;
371}
372
373static void free_pcre_regexp(struct grep_pat *p)
374{
375 pcre_free(p->pcre_regexp);
376 pcre_free(p->pcre_extra_info);
9d9babb8 377 pcre_free((void *)p->pcre_tables);
63e7e9d8
MK
378}
379#else /* !USE_LIBPCRE */
380static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
381{
382 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
383}
384
385static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
386 regmatch_t *match, int eflags)
387{
388 return 1;
389}
390
391static void free_pcre_regexp(struct grep_pat *p)
392{
393}
394#endif /* !USE_LIBPCRE */
395
9eceddee
FK
396static int is_fixed(const char *s, size_t len)
397{
398 size_t i;
399
400 /* regcomp cannot accept patterns with NULs so we
401 * consider any pattern containing a NUL fixed.
402 */
403 if (memchr(s, 0, len))
404 return 1;
405
406 for (i = 0; i < len; i++) {
407 if (is_regex_special(s[i]))
408 return 0;
409 }
410
411 return 1;
412}
413
793dc676
NTND
414static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
415{
416 struct strbuf sb = STRBUF_INIT;
417 int err;
418 int regflags;
419
420 basic_regex_quote_buf(&sb, p->pattern);
421 regflags = opt->regflags & ~REG_EXTENDED;
422 if (opt->ignore_case)
423 regflags |= REG_ICASE;
424 err = regcomp(&p->regexp, sb.buf, regflags);
425 if (opt->debug)
426 fprintf(stderr, "fixed %s\n", sb.buf);
427 strbuf_release(&sb);
428 if (err) {
429 char errbuf[1024];
430 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
431 regfree(&p->regexp);
432 compile_regexp_failed(p, errbuf);
433 }
434}
435
83b5d2f5
JH
436static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
437{
5c1ebcca 438 int icase, ascii_only;
c822255c
RS
439 int err;
440
d7eb527d 441 p->word_regexp = opt->word_regexp;
5183bf67 442 p->ignore_case = opt->ignore_case;
5c1ebcca
NTND
443 icase = opt->regflags & REG_ICASE || p->ignore_case;
444 ascii_only = !has_non_ascii(p->pattern);
d7eb527d 445
793dc676
NTND
446 /*
447 * Even when -F (fixed) asks us to do a non-regexp search, we
448 * may not be able to correctly case-fold when -i
449 * (ignore-case) is asked (in which case, we'll synthesize a
450 * regexp to match the pattern that matches regexp special
451 * characters literally, while ignoring case differences). On
452 * the other hand, even without -F, if the pattern does not
453 * have any regexp special characters and there is no need for
454 * case-folding search, we can internally turn it into a
455 * simple string match using kws. p->fixed tells us if we
456 * want to use kws.
457 */
9eceddee 458 if (opt->fixed || is_fixed(p->pattern, p->patternlen))
793dc676 459 p->fixed = !icase || ascii_only;
9eceddee
FK
460 else
461 p->fixed = 0;
462
463 if (p->fixed) {
695f95ba 464 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
9eceddee
FK
465 kwsincr(p->kws, p->pattern, p->patternlen);
466 kwsprep(p->kws);
c822255c 467 return;
793dc676
NTND
468 } else if (opt->fixed) {
469 /*
470 * We come here when the pattern has the non-ascii
471 * characters we cannot case-fold, and asked to
472 * ignore-case.
473 */
474 compile_fixed_regexp(p, opt);
475 return;
9eceddee 476 }
c822255c 477
63e7e9d8
MK
478 if (opt->pcre) {
479 compile_pcre_regexp(p, opt);
480 return;
481 }
482
c822255c 483 err = regcomp(&p->regexp, p->pattern, opt->regflags);
83b5d2f5
JH
484 if (err) {
485 char errbuf[1024];
83b5d2f5
JH
486 regerror(err, &p->regexp, errbuf, 1024);
487 regfree(&p->regexp);
a30c148a 488 compile_regexp_failed(p, errbuf);
83b5d2f5
JH
489 }
490}
491
0ab7befa 492static struct grep_expr *compile_pattern_or(struct grep_pat **);
83b5d2f5
JH
493static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
494{
495 struct grep_pat *p;
496 struct grep_expr *x;
497
498 p = *list;
c922b01f
LT
499 if (!p)
500 return NULL;
83b5d2f5
JH
501 switch (p->token) {
502 case GREP_PATTERN: /* atom */
480c1ca6
JH
503 case GREP_PATTERN_HEAD:
504 case GREP_PATTERN_BODY:
83b5d2f5
JH
505 x = xcalloc(1, sizeof (struct grep_expr));
506 x->node = GREP_NODE_ATOM;
507 x->u.atom = p;
508 *list = p->next;
509 return x;
510 case GREP_OPEN_PAREN:
511 *list = p->next;
0ab7befa 512 x = compile_pattern_or(list);
83b5d2f5
JH
513 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
514 die("unmatched parenthesis");
515 *list = (*list)->next;
516 return x;
517 default:
518 return NULL;
519 }
520}
521
522static struct grep_expr *compile_pattern_not(struct grep_pat **list)
523{
524 struct grep_pat *p;
525 struct grep_expr *x;
526
527 p = *list;
c922b01f
LT
528 if (!p)
529 return NULL;
83b5d2f5
JH
530 switch (p->token) {
531 case GREP_NOT:
532 if (!p->next)
533 die("--not not followed by pattern expression");
534 *list = p->next;
535 x = xcalloc(1, sizeof (struct grep_expr));
536 x->node = GREP_NODE_NOT;
537 x->u.unary = compile_pattern_not(list);
538 if (!x->u.unary)
539 die("--not followed by non pattern expression");
540 return x;
541 default:
542 return compile_pattern_atom(list);
543 }
544}
545
546static struct grep_expr *compile_pattern_and(struct grep_pat **list)
547{
548 struct grep_pat *p;
549 struct grep_expr *x, *y, *z;
550
551 x = compile_pattern_not(list);
552 p = *list;
553 if (p && p->token == GREP_AND) {
554 if (!p->next)
555 die("--and not followed by pattern expression");
556 *list = p->next;
557 y = compile_pattern_and(list);
558 if (!y)
559 die("--and not followed by pattern expression");
560 z = xcalloc(1, sizeof (struct grep_expr));
561 z->node = GREP_NODE_AND;
562 z->u.binary.left = x;
563 z->u.binary.right = y;
564 return z;
565 }
566 return x;
567}
568
569static struct grep_expr *compile_pattern_or(struct grep_pat **list)
570{
571 struct grep_pat *p;
572 struct grep_expr *x, *y, *z;
573
574 x = compile_pattern_and(list);
575 p = *list;
576 if (x && p && p->token != GREP_CLOSE_PAREN) {
577 y = compile_pattern_or(list);
578 if (!y)
579 die("not a pattern expression %s", p->pattern);
580 z = xcalloc(1, sizeof (struct grep_expr));
581 z->node = GREP_NODE_OR;
582 z->u.binary.left = x;
583 z->u.binary.right = y;
584 return z;
585 }
586 return x;
587}
588
589static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
590{
591 return compile_pattern_or(list);
592}
593
17bf35a3
JH
594static void indent(int in)
595{
596 while (in-- > 0)
597 fputc(' ', stderr);
598}
599
600static void dump_grep_pat(struct grep_pat *p)
601{
602 switch (p->token) {
603 case GREP_AND: fprintf(stderr, "*and*"); break;
604 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
605 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
606 case GREP_NOT: fprintf(stderr, "*not*"); break;
607 case GREP_OR: fprintf(stderr, "*or*"); break;
608
609 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
610 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
611 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
612 }
613
614 switch (p->token) {
615 default: break;
616 case GREP_PATTERN_HEAD:
617 fprintf(stderr, "<head %d>", p->field); break;
618 case GREP_PATTERN_BODY:
619 fprintf(stderr, "<body>"); break;
620 }
621 switch (p->token) {
622 default: break;
623 case GREP_PATTERN_HEAD:
624 case GREP_PATTERN_BODY:
625 case GREP_PATTERN:
626 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
627 break;
628 }
629 fputc('\n', stderr);
630}
631
632static void dump_grep_expression_1(struct grep_expr *x, int in)
633{
634 indent(in);
635 switch (x->node) {
636 case GREP_NODE_TRUE:
637 fprintf(stderr, "true\n");
638 break;
639 case GREP_NODE_ATOM:
640 dump_grep_pat(x->u.atom);
641 break;
642 case GREP_NODE_NOT:
643 fprintf(stderr, "(not\n");
644 dump_grep_expression_1(x->u.unary, in+1);
645 indent(in);
646 fprintf(stderr, ")\n");
647 break;
648 case GREP_NODE_AND:
649 fprintf(stderr, "(and\n");
650 dump_grep_expression_1(x->u.binary.left, in+1);
651 dump_grep_expression_1(x->u.binary.right, in+1);
652 indent(in);
653 fprintf(stderr, ")\n");
654 break;
655 case GREP_NODE_OR:
656 fprintf(stderr, "(or\n");
657 dump_grep_expression_1(x->u.binary.left, in+1);
658 dump_grep_expression_1(x->u.binary.right, in+1);
659 indent(in);
660 fprintf(stderr, ")\n");
661 break;
662 }
663}
664
07a7d656 665static void dump_grep_expression(struct grep_opt *opt)
17bf35a3
JH
666{
667 struct grep_expr *x = opt->pattern_expression;
668
669 if (opt->all_match)
670 fprintf(stderr, "[all-match]\n");
671 dump_grep_expression_1(x, 0);
672 fflush(NULL);
673}
674
5aaeb733
JH
675static struct grep_expr *grep_true_expr(void)
676{
677 struct grep_expr *z = xcalloc(1, sizeof(*z));
678 z->node = GREP_NODE_TRUE;
679 return z;
680}
681
682static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
683{
684 struct grep_expr *z = xcalloc(1, sizeof(*z));
685 z->node = GREP_NODE_OR;
686 z->u.binary.left = left;
687 z->u.binary.right = right;
688 return z;
689}
690
95ce9ce2 691static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
83b5d2f5
JH
692{
693 struct grep_pat *p;
95ce9ce2 694 struct grep_expr *header_expr;
5aaeb733
JH
695 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
696 enum grep_header_field fld;
83b5d2f5 697
95ce9ce2
JH
698 if (!opt->header_list)
699 return NULL;
2385f246 700
95ce9ce2
JH
701 for (p = opt->header_list; p; p = p->next) {
702 if (p->token != GREP_PATTERN_HEAD)
ef1177d1 703 die("BUG: a non-header pattern in grep header list.");
3ce3ffb8
AP
704 if (p->field < GREP_HEADER_FIELD_MIN ||
705 GREP_HEADER_FIELD_MAX <= p->field)
ef1177d1 706 die("BUG: unknown header field %d", p->field);
95ce9ce2 707 compile_regexp(p, opt);
80235ba7 708 }
5aaeb733
JH
709
710 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
711 header_group[fld] = NULL;
712
713 for (p = opt->header_list; p; p = p->next) {
714 struct grep_expr *h;
715 struct grep_pat *pp = p;
716
717 h = compile_pattern_atom(&pp);
718 if (!h || pp != p->next)
ef1177d1 719 die("BUG: malformed header expr");
5aaeb733
JH
720 if (!header_group[p->field]) {
721 header_group[p->field] = h;
722 continue;
723 }
724 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
725 }
726
727 header_expr = NULL;
728
729 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
730 if (!header_group[fld])
731 continue;
732 if (!header_expr)
733 header_expr = grep_true_expr();
734 header_expr = grep_or_expr(header_group[fld], header_expr);
735 }
95ce9ce2
JH
736 return header_expr;
737}
738
13e4fc7e
JH
739static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
740{
741 struct grep_expr *z = x;
742
743 while (x) {
744 assert(x->node == GREP_NODE_OR);
745 if (x->u.binary.right &&
746 x->u.binary.right->node == GREP_NODE_TRUE) {
747 x->u.binary.right = y;
748 break;
749 }
750 x = x->u.binary.right;
751 }
752 return z;
753}
754
17bf35a3 755static void compile_grep_patterns_real(struct grep_opt *opt)
95ce9ce2
JH
756{
757 struct grep_pat *p;
758 struct grep_expr *header_expr = prep_header_patterns(opt);
0ab7befa 759
83b5d2f5 760 for (p = opt->pattern_list; p; p = p->next) {
480c1ca6
JH
761 switch (p->token) {
762 case GREP_PATTERN: /* atom */
763 case GREP_PATTERN_HEAD:
764 case GREP_PATTERN_BODY:
c822255c 765 compile_regexp(p, opt);
480c1ca6
JH
766 break;
767 default:
83b5d2f5 768 opt->extended = 1;
480c1ca6
JH
769 break;
770 }
83b5d2f5
JH
771 }
772
80235ba7
JH
773 if (opt->all_match || header_expr)
774 opt->extended = 1;
17bf35a3 775 else if (!opt->extended && !opt->debug)
83b5d2f5
JH
776 return;
777
83b5d2f5 778 p = opt->pattern_list;
ba150a3f
MB
779 if (p)
780 opt->pattern_expression = compile_pattern_expr(&p);
83b5d2f5
JH
781 if (p)
782 die("incomplete pattern expression: %s", p->pattern);
80235ba7
JH
783
784 if (!header_expr)
785 return;
786
5aaeb733 787 if (!opt->pattern_expression)
80235ba7 788 opt->pattern_expression = header_expr;
13e4fc7e
JH
789 else if (opt->all_match)
790 opt->pattern_expression = grep_splice_or(header_expr,
791 opt->pattern_expression);
5aaeb733
JH
792 else
793 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
794 header_expr);
80235ba7 795 opt->all_match = 1;
83b5d2f5
JH
796}
797
17bf35a3
JH
798void compile_grep_patterns(struct grep_opt *opt)
799{
800 compile_grep_patterns_real(opt);
801 if (opt->debug)
802 dump_grep_expression(opt);
803}
804
b48fb5b6
JH
805static void free_pattern_expr(struct grep_expr *x)
806{
807 switch (x->node) {
5aaeb733 808 case GREP_NODE_TRUE:
b48fb5b6
JH
809 case GREP_NODE_ATOM:
810 break;
811 case GREP_NODE_NOT:
812 free_pattern_expr(x->u.unary);
813 break;
814 case GREP_NODE_AND:
815 case GREP_NODE_OR:
816 free_pattern_expr(x->u.binary.left);
817 free_pattern_expr(x->u.binary.right);
818 break;
819 }
820 free(x);
821}
822
823void free_grep_patterns(struct grep_opt *opt)
824{
825 struct grep_pat *p, *n;
826
827 for (p = opt->pattern_list; p; p = n) {
828 n = p->next;
829 switch (p->token) {
830 case GREP_PATTERN: /* atom */
831 case GREP_PATTERN_HEAD:
832 case GREP_PATTERN_BODY:
9eceddee
FK
833 if (p->kws)
834 kwsfree(p->kws);
835 else if (p->pcre_regexp)
63e7e9d8
MK
836 free_pcre_regexp(p);
837 else
838 regfree(&p->regexp);
526a858a 839 free(p->pattern);
b48fb5b6
JH
840 break;
841 default:
842 break;
843 }
844 free(p);
845 }
846
847 if (!opt->extended)
848 return;
849 free_pattern_expr(opt->pattern_expression);
850}
851
83b5d2f5
JH
852static char *end_of_line(char *cp, unsigned long *left)
853{
854 unsigned long l = *left;
855 while (l && *cp != '\n') {
856 l--;
857 cp++;
858 }
859 *left = l;
860 return cp;
861}
862
863static int word_char(char ch)
864{
865 return isalnum(ch) || ch == '_';
866}
867
55f638bd
ML
868static void output_color(struct grep_opt *opt, const void *data, size_t size,
869 const char *color)
870{
daa0c3d9 871 if (want_color(opt->color) && color && color[0]) {
55f638bd
ML
872 opt->output(opt, color, strlen(color));
873 opt->output(opt, data, size);
874 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
875 } else
876 opt->output(opt, data, size);
877}
878
879static void output_sep(struct grep_opt *opt, char sign)
880{
881 if (opt->null_following_name)
882 opt->output(opt, "\0", 1);
883 else
884 output_color(opt, &sign, 1, opt->color_sep);
885}
886
83caecca
RZ
887static void show_name(struct grep_opt *opt, const char *name)
888{
55f638bd 889 output_color(opt, name, strlen(name), opt->color_filename);
5b594f45 890 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
83caecca
RZ
891}
892
ed40a095
RS
893static int fixmatch(struct grep_pat *p, char *line, char *eol,
894 regmatch_t *match)
83b5d2f5 895{
9eceddee
FK
896 struct kwsmatch kwsm;
897 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
898 if (offset == -1) {
83b5d2f5
JH
899 match->rm_so = match->rm_eo = -1;
900 return REG_NOMATCH;
9eceddee
FK
901 } else {
902 match->rm_so = offset;
903 match->rm_eo = match->rm_so + kwsm.size[0];
83b5d2f5
JH
904 return 0;
905 }
906}
907
97e77784
MK
908static int patmatch(struct grep_pat *p, char *line, char *eol,
909 regmatch_t *match, int eflags)
910{
911 int hit;
912
913 if (p->fixed)
914 hit = !fixmatch(p, line, eol, match);
63e7e9d8
MK
915 else if (p->pcre_regexp)
916 hit = !pcrematch(p, line, eol, match, eflags);
97e77784 917 else
b7d36ffc
JS
918 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
919 eflags);
97e77784
MK
920
921 return hit;
922}
923
a4d7d2c6
JH
924static int strip_timestamp(char *bol, char **eol_p)
925{
926 char *eol = *eol_p;
927 int ch;
928
929 while (bol < --eol) {
930 if (*eol != '>')
931 continue;
932 *eol_p = ++eol;
933 ch = *eol;
934 *eol = '\0';
935 return ch;
936 }
937 return 0;
938}
939
940static struct {
941 const char *field;
942 size_t len;
943} header_field[] = {
944 { "author ", 7 },
945 { "committer ", 10 },
72fd13f7 946 { "reflog ", 7 },
a4d7d2c6
JH
947};
948
d7eb527d 949static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
79212772
RS
950 enum grep_context ctx,
951 regmatch_t *pmatch, int eflags)
83b5d2f5
JH
952{
953 int hit = 0;
a4d7d2c6 954 int saved_ch = 0;
e701fadb 955 const char *start = bol;
83b5d2f5 956
480c1ca6
JH
957 if ((p->token != GREP_PATTERN) &&
958 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
959 return 0;
960
a4d7d2c6
JH
961 if (p->token == GREP_PATTERN_HEAD) {
962 const char *field;
963 size_t len;
964 assert(p->field < ARRAY_SIZE(header_field));
965 field = header_field[p->field].field;
966 len = header_field[p->field].len;
967 if (strncmp(bol, field, len))
968 return 0;
969 bol += len;
ad4813b3
NTND
970 switch (p->field) {
971 case GREP_HEADER_AUTHOR:
972 case GREP_HEADER_COMMITTER:
973 saved_ch = strip_timestamp(bol, &eol);
974 break;
975 default:
976 break;
977 }
a4d7d2c6
JH
978 }
979
83b5d2f5 980 again:
97e77784 981 hit = patmatch(p, bol, eol, pmatch, eflags);
83b5d2f5 982
d7eb527d 983 if (hit && p->word_regexp) {
83b5d2f5 984 if ((pmatch[0].rm_so < 0) ||
84201eae 985 (eol - bol) < pmatch[0].rm_so ||
83b5d2f5
JH
986 (pmatch[0].rm_eo < 0) ||
987 (eol - bol) < pmatch[0].rm_eo)
988 die("regexp returned nonsense");
989
990 /* Match beginning must be either beginning of the
991 * line, or at word boundary (i.e. the last char must
992 * not be a word char). Similarly, match end must be
993 * either end of the line, or at word boundary
994 * (i.e. the next char must not be a word char).
995 */
fb62eb7f 996 if ( ((pmatch[0].rm_so == 0) ||
83b5d2f5
JH
997 !word_char(bol[pmatch[0].rm_so-1])) &&
998 ((pmatch[0].rm_eo == (eol-bol)) ||
999 !word_char(bol[pmatch[0].rm_eo])) )
1000 ;
1001 else
1002 hit = 0;
1003
84201eae
RS
1004 /* Words consist of at least one character. */
1005 if (pmatch->rm_so == pmatch->rm_eo)
1006 hit = 0;
1007
83b5d2f5
JH
1008 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1009 /* There could be more than one match on the
1010 * line, and the first match might not be
1011 * strict word match. But later ones could be!
fb62eb7f
RS
1012 * Forward to the next possible start, i.e. the
1013 * next position following a non-word char.
83b5d2f5
JH
1014 */
1015 bol = pmatch[0].rm_so + bol + 1;
fb62eb7f
RS
1016 while (word_char(bol[-1]) && bol < eol)
1017 bol++;
dbb6a4ad 1018 eflags |= REG_NOTBOL;
fb62eb7f
RS
1019 if (bol < eol)
1020 goto again;
83b5d2f5
JH
1021 }
1022 }
a4d7d2c6
JH
1023 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1024 *eol = saved_ch;
e701fadb
RS
1025 if (hit) {
1026 pmatch[0].rm_so += bol - start;
1027 pmatch[0].rm_eo += bol - start;
1028 }
83b5d2f5
JH
1029 return hit;
1030}
1031
d7eb527d
RS
1032static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1033 enum grep_context ctx, int collect_hits)
83b5d2f5 1034{
0ab7befa 1035 int h = 0;
79212772 1036 regmatch_t match;
0ab7befa 1037
c922b01f
LT
1038 if (!x)
1039 die("Not a valid grep expression");
83b5d2f5 1040 switch (x->node) {
5aaeb733
JH
1041 case GREP_NODE_TRUE:
1042 h = 1;
1043 break;
83b5d2f5 1044 case GREP_NODE_ATOM:
79212772 1045 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
83b5d2f5
JH
1046 break;
1047 case GREP_NODE_NOT:
d7eb527d 1048 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
0ab7befa 1049 break;
83b5d2f5 1050 case GREP_NODE_AND:
d7eb527d 1051 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
252d560d 1052 return 0;
d7eb527d 1053 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
0ab7befa 1054 break;
83b5d2f5 1055 case GREP_NODE_OR:
0ab7befa 1056 if (!collect_hits)
d7eb527d 1057 return (match_expr_eval(x->u.binary.left,
0ab7befa 1058 bol, eol, ctx, 0) ||
d7eb527d 1059 match_expr_eval(x->u.binary.right,
0ab7befa 1060 bol, eol, ctx, 0));
d7eb527d 1061 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
0ab7befa 1062 x->u.binary.left->hit |= h;
d7eb527d 1063 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
0ab7befa
JH
1064 break;
1065 default:
d7530708 1066 die("Unexpected node type (internal error) %d", x->node);
83b5d2f5 1067 }
0ab7befa
JH
1068 if (collect_hits)
1069 x->hit |= h;
1070 return h;
83b5d2f5
JH
1071}
1072
480c1ca6 1073static int match_expr(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1074 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1075{
1076 struct grep_expr *x = opt->pattern_expression;
d7eb527d 1077 return match_expr_eval(x, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1078}
1079
480c1ca6 1080static int match_line(struct grep_opt *opt, char *bol, char *eol,
0ab7befa 1081 enum grep_context ctx, int collect_hits)
83b5d2f5
JH
1082{
1083 struct grep_pat *p;
79212772
RS
1084 regmatch_t match;
1085
83b5d2f5 1086 if (opt->extended)
0ab7befa
JH
1087 return match_expr(opt, bol, eol, ctx, collect_hits);
1088
1089 /* we do not call with collect_hits without being extended */
83b5d2f5 1090 for (p = opt->pattern_list; p; p = p->next) {
79212772 1091 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
83b5d2f5
JH
1092 return 1;
1093 }
1094 return 0;
1095}
1096
7e8f59d5
RS
1097static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1098 enum grep_context ctx,
1099 regmatch_t *pmatch, int eflags)
1100{
1101 regmatch_t match;
1102
1103 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1104 return 0;
1105 if (match.rm_so < 0 || match.rm_eo < 0)
1106 return 0;
1107 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1108 if (match.rm_so > pmatch->rm_so)
1109 return 1;
1110 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1111 return 1;
1112 }
1113 pmatch->rm_so = match.rm_so;
1114 pmatch->rm_eo = match.rm_eo;
1115 return 1;
1116}
1117
1118static int next_match(struct grep_opt *opt, char *bol, char *eol,
1119 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1120{
1121 struct grep_pat *p;
1122 int hit = 0;
1123
1124 pmatch->rm_so = pmatch->rm_eo = -1;
1125 if (bol < eol) {
1126 for (p = opt->pattern_list; p; p = p->next) {
1127 switch (p->token) {
1128 case GREP_PATTERN: /* atom */
1129 case GREP_PATTERN_HEAD:
1130 case GREP_PATTERN_BODY:
1131 hit |= match_next_pattern(p, bol, eol, ctx,
1132 pmatch, eflags);
1133 break;
1134 default:
1135 break;
1136 }
1137 }
1138 }
1139 return hit;
1140}
1141
1142static void show_line(struct grep_opt *opt, char *bol, char *eol,
1143 const char *name, unsigned lno, char sign)
1144{
1145 int rest = eol - bol;
79a77109 1146 const char *match_color, *line_color = NULL;
7e8f59d5 1147
a8f0e764
RS
1148 if (opt->file_break && opt->last_shown == 0) {
1149 if (opt->show_hunk_mark)
1150 opt->output(opt, "\n", 1);
ba8ea749 1151 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
046802d0 1152 if (opt->last_shown == 0) {
55f638bd
ML
1153 if (opt->show_hunk_mark) {
1154 output_color(opt, "--", 2, opt->color_sep);
1155 opt->output(opt, "\n", 1);
07b838f0 1156 }
55f638bd
ML
1157 } else if (lno > opt->last_shown + 1) {
1158 output_color(opt, "--", 2, opt->color_sep);
1159 opt->output(opt, "\n", 1);
1160 }
5dd06d38 1161 }
1d84f72e
RS
1162 if (opt->heading && opt->last_shown == 0) {
1163 output_color(opt, name, strlen(name), opt->color_filename);
1164 opt->output(opt, "\n", 1);
1165 }
5dd06d38
RS
1166 opt->last_shown = lno;
1167
1d84f72e 1168 if (!opt->heading && opt->pathname) {
55f638bd
ML
1169 output_color(opt, name, strlen(name), opt->color_filename);
1170 output_sep(opt, sign);
5b594f45
FK
1171 }
1172 if (opt->linenum) {
1173 char buf[32];
1a168e5c 1174 xsnprintf(buf, sizeof(buf), "%d", lno);
55f638bd
ML
1175 output_color(opt, buf, strlen(buf), opt->color_lineno);
1176 output_sep(opt, sign);
5b594f45 1177 }
7e8f59d5
RS
1178 if (opt->color) {
1179 regmatch_t match;
1180 enum grep_context ctx = GREP_CONTEXT_BODY;
1181 int ch = *eol;
1182 int eflags = 0;
1183
79a77109
RS
1184 if (sign == ':')
1185 match_color = opt->color_match_selected;
1186 else
1187 match_color = opt->color_match_context;
00588bb5
ML
1188 if (sign == ':')
1189 line_color = opt->color_selected;
1190 else if (sign == '-')
1191 line_color = opt->color_context;
1192 else if (sign == '=')
1193 line_color = opt->color_function;
7e8f59d5
RS
1194 *eol = '\0';
1195 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1f5b9cc4
RS
1196 if (match.rm_so == match.rm_eo)
1197 break;
5b594f45 1198
00588bb5 1199 output_color(opt, bol, match.rm_so, line_color);
55f638bd 1200 output_color(opt, bol + match.rm_so,
79a77109 1201 match.rm_eo - match.rm_so, match_color);
7e8f59d5
RS
1202 bol += match.rm_eo;
1203 rest -= match.rm_eo;
1204 eflags = REG_NOTBOL;
1205 }
1206 *eol = ch;
1207 }
00588bb5 1208 output_color(opt, bol, rest, line_color);
5b594f45 1209 opt->output(opt, "\n", 1);
7e8f59d5
RS
1210}
1211
0579f91d 1212#ifndef NO_PTHREADS
78db6ea9
JK
1213int grep_use_locks;
1214
0579f91d
TR
1215/*
1216 * This lock protects access to the gitattributes machinery, which is
1217 * not thread-safe.
1218 */
1219pthread_mutex_t grep_attr_mutex;
1220
78db6ea9 1221static inline void grep_attr_lock(void)
0579f91d 1222{
78db6ea9 1223 if (grep_use_locks)
0579f91d
TR
1224 pthread_mutex_lock(&grep_attr_mutex);
1225}
1226
78db6ea9 1227static inline void grep_attr_unlock(void)
0579f91d 1228{
78db6ea9 1229 if (grep_use_locks)
0579f91d
TR
1230 pthread_mutex_unlock(&grep_attr_mutex);
1231}
b3aeb285
JK
1232
1233/*
1234 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1235 */
1236pthread_mutex_t grep_read_mutex;
1237
0579f91d 1238#else
78db6ea9
JK
1239#define grep_attr_lock()
1240#define grep_attr_unlock()
0579f91d
TR
1241#endif
1242
e1327023 1243static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
2944e4e6 1244{
60ecac98 1245 xdemitconf_t *xecfg = opt->priv;
0579f91d 1246 if (xecfg && !xecfg->find_func) {
94ad9d9e
JK
1247 grep_source_load_driver(gs);
1248 if (gs->driver->funcname.pattern) {
1249 const struct userdiff_funcname *pe = &gs->driver->funcname;
0579f91d
TR
1250 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1251 } else {
1252 xecfg = opt->priv = NULL;
1253 }
1254 }
1255
1256 if (xecfg) {
60ecac98
RS
1257 char buf[1];
1258 return xecfg->find_func(bol, eol - bol, buf, 1,
1259 xecfg->find_func_priv) >= 0;
1260 }
1261
2944e4e6
RS
1262 if (bol == eol)
1263 return 0;
1264 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1265 return 1;
1266 return 0;
1267}
1268
e1327023
JK
1269static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1270 char *bol, unsigned lno)
2944e4e6 1271{
e1327023 1272 while (bol > gs->buf) {
2944e4e6
RS
1273 char *eol = --bol;
1274
e1327023 1275 while (bol > gs->buf && bol[-1] != '\n')
2944e4e6
RS
1276 bol--;
1277 lno--;
1278
1279 if (lno <= opt->last_shown)
1280 break;
1281
e1327023
JK
1282 if (match_funcname(opt, gs, bol, eol)) {
1283 show_line(opt, bol, eol, gs->name, lno, '=');
2944e4e6
RS
1284 break;
1285 }
1286 }
1287}
1288
e1327023 1289static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
ba8ea749 1290 char *bol, char *end, unsigned lno)
49de3216 1291{
2944e4e6 1292 unsigned cur = lno, from = 1, funcname_lno = 0;
ba8ea749
RS
1293 int funcname_needed = !!opt->funcname;
1294
e1327023 1295 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
ba8ea749 1296 funcname_needed = 2;
49de3216
RS
1297
1298 if (opt->pre_context < lno)
1299 from = lno - opt->pre_context;
1300 if (from <= opt->last_shown)
1301 from = opt->last_shown + 1;
1302
1303 /* Rewind. */
e1327023 1304 while (bol > gs->buf &&
ba8ea749 1305 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
2944e4e6
RS
1306 char *eol = --bol;
1307
e1327023 1308 while (bol > gs->buf && bol[-1] != '\n')
49de3216
RS
1309 bol--;
1310 cur--;
e1327023 1311 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
2944e4e6
RS
1312 funcname_lno = cur;
1313 funcname_needed = 0;
1314 }
49de3216
RS
1315 }
1316
2944e4e6
RS
1317 /* We need to look even further back to find a function signature. */
1318 if (opt->funcname && funcname_needed)
e1327023 1319 show_funcname_line(opt, gs, bol, cur);
2944e4e6 1320
49de3216
RS
1321 /* Back forward. */
1322 while (cur < lno) {
2944e4e6 1323 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
49de3216
RS
1324
1325 while (*eol != '\n')
1326 eol++;
e1327023 1327 show_line(opt, bol, eol, gs->name, cur, sign);
49de3216
RS
1328 bol = eol + 1;
1329 cur++;
1330 }
1331}
1332
a26345b6
JH
1333static int should_lookahead(struct grep_opt *opt)
1334{
1335 struct grep_pat *p;
1336
1337 if (opt->extended)
1338 return 0; /* punt for too complex stuff */
1339 if (opt->invert)
1340 return 0;
1341 for (p = opt->pattern_list; p; p = p->next) {
1342 if (p->token != GREP_PATTERN)
1343 return 0; /* punt for "header only" and stuff */
1344 }
1345 return 1;
1346}
1347
1348static int look_ahead(struct grep_opt *opt,
1349 unsigned long *left_p,
1350 unsigned *lno_p,
1351 char **bol_p)
1352{
1353 unsigned lno = *lno_p;
1354 char *bol = *bol_p;
1355 struct grep_pat *p;
1356 char *sp, *last_bol;
1357 regoff_t earliest = -1;
1358
1359 for (p = opt->pattern_list; p; p = p->next) {
1360 int hit;
1361 regmatch_t m;
1362
97e77784 1363 hit = patmatch(p, bol, bol + *left_p, &m, 0);
a26345b6
JH
1364 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1365 continue;
1366 if (earliest < 0 || m.rm_so < earliest)
1367 earliest = m.rm_so;
1368 }
1369
1370 if (earliest < 0) {
1371 *bol_p = bol + *left_p;
1372 *left_p = 0;
1373 return 1;
1374 }
1375 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1376 ; /* find the beginning of the line */
1377 last_bol = sp;
1378
1379 for (sp = bol; sp < last_bol; sp++) {
1380 if (*sp == '\n')
1381 lno++;
1382 }
1383 *left_p -= last_bol - bol;
1384 *bol_p = last_bol;
1385 *lno_p = lno;
1386 return 0;
1387}
1388
335ec3bf
JK
1389static int fill_textconv_grep(struct userdiff_driver *driver,
1390 struct grep_source *gs)
1391{
1392 struct diff_filespec *df;
1393 char *buf;
1394 size_t size;
1395
1396 if (!driver || !driver->textconv)
1397 return grep_source_load(gs);
1398
1399 /*
1400 * The textconv interface is intimately tied to diff_filespecs, so we
1401 * have to pretend to be one. If we could unify the grep_source
1402 * and diff_filespec structs, this mess could just go away.
1403 */
1404 df = alloc_filespec(gs->path);
1405 switch (gs->type) {
1c41c82b 1406 case GREP_SOURCE_OID:
335ec3bf
JK
1407 fill_filespec(df, gs->identifier, 1, 0100644);
1408 break;
1409 case GREP_SOURCE_FILE:
1410 fill_filespec(df, null_sha1, 0, 0100644);
1411 break;
1412 default:
1413 die("BUG: attempt to textconv something without a path?");
1414 }
1415
1416 /*
1417 * fill_textconv is not remotely thread-safe; it may load objects
1418 * behind the scenes, and it modifies the global diff tempfile
1419 * structure.
1420 */
1421 grep_read_lock();
1422 size = fill_textconv(driver, df, &buf);
1423 grep_read_unlock();
1424 free_filespec(df);
1425
1426 /*
1427 * The normal fill_textconv usage by the diff machinery would just keep
1428 * the textconv'd buf separate from the diff_filespec. But much of the
1429 * grep code passes around a grep_source and assumes that its "buf"
1430 * pointer is the beginning of the thing we are searching. So let's
1431 * install our textconv'd version into the grep_source, taking care not
1432 * to leak any existing buffer.
1433 */
1434 grep_source_clear_data(gs);
1435 gs->buf = buf;
1436 gs->size = size;
1437
1438 return 0;
1439}
1440
4aa2c475
RS
1441static int is_empty_line(const char *bol, const char *eol)
1442{
1443 while (bol < eol && isspace(*bol))
1444 bol++;
1445 return bol == eol;
1446}
1447
e1327023 1448static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
83b5d2f5 1449{
e1327023 1450 char *bol;
4aa2c475 1451 char *peek_bol = NULL;
e1327023 1452 unsigned long left;
83b5d2f5 1453 unsigned lno = 1;
83b5d2f5 1454 unsigned last_hit = 0;
83b5d2f5 1455 int binary_match_only = 0;
83b5d2f5 1456 unsigned count = 0;
a26345b6 1457 int try_lookahead = 0;
ba8ea749 1458 int show_function = 0;
335ec3bf 1459 struct userdiff_driver *textconv = NULL;
480c1ca6 1460 enum grep_context ctx = GREP_CONTEXT_HEAD;
60ecac98 1461 xdemitconf_t xecfg;
83b5d2f5 1462
5b594f45
FK
1463 if (!opt->output)
1464 opt->output = std_output;
1465
ba8ea749
RS
1466 if (opt->pre_context || opt->post_context || opt->file_break ||
1467 opt->funcbody) {
08303c36
RS
1468 /* Show hunk marks, except for the first file. */
1469 if (opt->last_shown)
1470 opt->show_hunk_mark = 1;
1471 /*
1472 * If we're using threads then we can't easily identify
1473 * the first file. Always put hunk marks in that case
1474 * and skip the very first one later in work_done().
1475 */
1476 if (opt->output != std_output)
1477 opt->show_hunk_mark = 1;
1478 }
431d6e7b
RS
1479 opt->last_shown = 0;
1480
335ec3bf
JK
1481 if (opt->allow_textconv) {
1482 grep_source_load_driver(gs);
1483 /*
1484 * We might set up the shared textconv cache data here, which
1485 * is not thread-safe.
1486 */
1487 grep_attr_lock();
1488 textconv = userdiff_get_textconv(gs->driver);
1489 grep_attr_unlock();
1490 }
1491
1492 /*
1493 * We know the result of a textconv is text, so we only have to care
1494 * about binary handling if we are not using it.
1495 */
1496 if (!textconv) {
1497 switch (opt->binary) {
1498 case GREP_BINARY_DEFAULT:
1499 if (grep_source_is_binary(gs))
1500 binary_match_only = 1;
1501 break;
1502 case GREP_BINARY_NOMATCH:
1503 if (grep_source_is_binary(gs))
1504 return 0; /* Assume unmatch */
1505 break;
1506 case GREP_BINARY_TEXT:
1507 break;
1508 default:
ef1177d1 1509 die("BUG: unknown binary handling mode");
335ec3bf 1510 }
83b5d2f5
JH
1511 }
1512
60ecac98 1513 memset(&xecfg, 0, sizeof(xecfg));
0579f91d
TR
1514 opt->priv = &xecfg;
1515
a26345b6 1516 try_lookahead = should_lookahead(opt);
60ecac98 1517
335ec3bf 1518 if (fill_textconv_grep(textconv, gs) < 0)
08265798
JK
1519 return 0;
1520
e1327023
JK
1521 bol = gs->buf;
1522 left = gs->size;
83b5d2f5
JH
1523 while (left) {
1524 char *eol, ch;
0ab7befa 1525 int hit;
83b5d2f5 1526
a26345b6 1527 /*
8997da38 1528 * look_ahead() skips quickly to the line that possibly
a26345b6
JH
1529 * has the next hit; don't call it if we need to do
1530 * something more than just skipping the current line
1531 * in response to an unmatch for the current line. E.g.
1532 * inside a post-context window, we will show the current
1533 * line as a context around the previous hit when it
1534 * doesn't hit.
1535 */
1536 if (try_lookahead
1537 && !(last_hit
ba8ea749
RS
1538 && (show_function ||
1539 lno <= last_hit + opt->post_context))
a26345b6
JH
1540 && look_ahead(opt, &left, &lno, &bol))
1541 break;
83b5d2f5
JH
1542 eol = end_of_line(bol, &left);
1543 ch = *eol;
1544 *eol = 0;
1545
480c1ca6
JH
1546 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1547 ctx = GREP_CONTEXT_BODY;
1548
0ab7befa 1549 hit = match_line(opt, bol, eol, ctx, collect_hits);
83b5d2f5
JH
1550 *eol = ch;
1551
0ab7befa
JH
1552 if (collect_hits)
1553 goto next_line;
1554
83b5d2f5
JH
1555 /* "grep -v -e foo -e bla" should list lines
1556 * that do not have either, so inversion should
1557 * be done outside.
1558 */
1559 if (opt->invert)
1560 hit = !hit;
1561 if (opt->unmatch_name_only) {
1562 if (hit)
1563 return 0;
1564 goto next_line;
1565 }
1566 if (hit) {
1567 count++;
1568 if (opt->status_only)
1569 return 1;
321ffcc0 1570 if (opt->name_only) {
e1327023 1571 show_name(opt, gs->name);
321ffcc0
RS
1572 return 1;
1573 }
c30c10cf
RS
1574 if (opt->count)
1575 goto next_line;
83b5d2f5 1576 if (binary_match_only) {
5b594f45 1577 opt->output(opt, "Binary file ", 12);
e1327023 1578 output_color(opt, gs->name, strlen(gs->name),
55f638bd 1579 opt->color_filename);
5b594f45 1580 opt->output(opt, " matches\n", 9);
83b5d2f5
JH
1581 return 1;
1582 }
83b5d2f5
JH
1583 /* Hit at this line. If we haven't shown the
1584 * pre-context lines, we would need to show them.
83b5d2f5 1585 */
ba8ea749 1586 if (opt->pre_context || opt->funcbody)
e1327023 1587 show_pre_context(opt, gs, bol, eol, lno);
2944e4e6 1588 else if (opt->funcname)
e1327023
JK
1589 show_funcname_line(opt, gs, bol, lno);
1590 show_line(opt, bol, eol, gs->name, lno, ':');
5dd06d38 1591 last_hit = lno;
ba8ea749
RS
1592 if (opt->funcbody)
1593 show_function = 1;
1594 goto next_line;
83b5d2f5 1595 }
4aa2c475
RS
1596 if (show_function && (!peek_bol || peek_bol < bol)) {
1597 unsigned long peek_left = left;
1598 char *peek_eol = eol;
1599
1600 /*
1601 * Trailing empty lines are not interesting.
1602 * Peek past them to see if they belong to the
1603 * body of the current function.
1604 */
1605 peek_bol = bol;
1606 while (is_empty_line(peek_bol, peek_eol)) {
1607 peek_bol = peek_eol + 1;
1608 peek_eol = end_of_line(peek_bol, &peek_left);
1609 }
1610
1611 if (match_funcname(opt, gs, peek_bol, peek_eol))
1612 show_function = 0;
1613 }
ba8ea749
RS
1614 if (show_function ||
1615 (last_hit && lno <= last_hit + opt->post_context)) {
83b5d2f5
JH
1616 /* If the last hit is within the post context,
1617 * we need to show this line.
1618 */
e1327023 1619 show_line(opt, bol, eol, gs->name, lno, '-');
83b5d2f5 1620 }
83b5d2f5
JH
1621
1622 next_line:
1623 bol = eol + 1;
1624 if (!left)
1625 break;
1626 left--;
1627 lno++;
1628 }
1629
0ab7befa
JH
1630 if (collect_hits)
1631 return 0;
b48fb5b6 1632
83b5d2f5
JH
1633 if (opt->status_only)
1634 return 0;
1635 if (opt->unmatch_name_only) {
1636 /* We did not see any hit, so we want to show this */
e1327023 1637 show_name(opt, gs->name);
83b5d2f5
JH
1638 return 1;
1639 }
1640
60ecac98
RS
1641 xdiff_clear_find_func(&xecfg);
1642 opt->priv = NULL;
1643
83b5d2f5
JH
1644 /* NEEDSWORK:
1645 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1646 * which feels mostly useless but sometimes useful. Maybe
1647 * make it another option? For now suppress them.
1648 */
5b594f45
FK
1649 if (opt->count && count) {
1650 char buf[32];
f76d947a
RS
1651 if (opt->pathname) {
1652 output_color(opt, gs->name, strlen(gs->name),
1653 opt->color_filename);
1654 output_sep(opt, ':');
1655 }
1a168e5c 1656 xsnprintf(buf, sizeof(buf), "%u\n", count);
5b594f45 1657 opt->output(opt, buf, strlen(buf));
c30c10cf 1658 return 1;
5b594f45 1659 }
83b5d2f5
JH
1660 return !!last_hit;
1661}
1662
0ab7befa
JH
1663static void clr_hit_marker(struct grep_expr *x)
1664{
1665 /* All-hit markers are meaningful only at the very top level
1666 * OR node.
1667 */
1668 while (1) {
1669 x->hit = 0;
1670 if (x->node != GREP_NODE_OR)
1671 return;
1672 x->u.binary.left->hit = 0;
1673 x = x->u.binary.right;
1674 }
1675}
1676
1677static int chk_hit_marker(struct grep_expr *x)
1678{
1679 /* Top level nodes have hit markers. See if they all are hits */
1680 while (1) {
1681 if (x->node != GREP_NODE_OR)
1682 return x->hit;
1683 if (!x->u.binary.left->hit)
1684 return 0;
1685 x = x->u.binary.right;
1686 }
1687}
1688
e1327023 1689int grep_source(struct grep_opt *opt, struct grep_source *gs)
0ab7befa
JH
1690{
1691 /*
1692 * we do not have to do the two-pass grep when we do not check
1693 * buffer-wide "all-match".
1694 */
1695 if (!opt->all_match)
e1327023 1696 return grep_source_1(opt, gs, 0);
0ab7befa
JH
1697
1698 /* Otherwise the toplevel "or" terms hit a bit differently.
1699 * We first clear hit markers from them.
1700 */
1701 clr_hit_marker(opt->pattern_expression);
e1327023 1702 grep_source_1(opt, gs, 1);
0ab7befa
JH
1703
1704 if (!chk_hit_marker(opt->pattern_expression))
1705 return 0;
1706
e1327023
JK
1707 return grep_source_1(opt, gs, 0);
1708}
1709
c876d6da 1710int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
e1327023
JK
1711{
1712 struct grep_source gs;
1713 int r;
1714
55c61688 1715 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
e1327023
JK
1716 gs.buf = buf;
1717 gs.size = size;
1718
1719 r = grep_source(opt, &gs);
1720
1721 grep_source_clear(&gs);
1722 return r;
1723}
1724
1725void grep_source_init(struct grep_source *gs, enum grep_source_type type,
55c61688
NTND
1726 const char *name, const char *path,
1727 const void *identifier)
e1327023
JK
1728{
1729 gs->type = type;
8c53f071
JK
1730 gs->name = xstrdup_or_null(name);
1731 gs->path = xstrdup_or_null(path);
e1327023
JK
1732 gs->buf = NULL;
1733 gs->size = 0;
94ad9d9e 1734 gs->driver = NULL;
e1327023
JK
1735
1736 switch (type) {
1737 case GREP_SOURCE_FILE:
1738 gs->identifier = xstrdup(identifier);
1739 break;
4538eef5
BW
1740 case GREP_SOURCE_SUBMODULE:
1741 if (!identifier) {
1742 gs->identifier = NULL;
1743 break;
1744 }
1745 /*
1746 * FALL THROUGH
1747 * If the identifier is non-NULL (in the submodule case) it
1748 * will be a SHA1 that needs to be copied.
1749 */
1c41c82b
BW
1750 case GREP_SOURCE_OID:
1751 gs->identifier = oiddup(identifier);
e1327023
JK
1752 break;
1753 case GREP_SOURCE_BUF:
1754 gs->identifier = NULL;
4538eef5 1755 break;
e1327023
JK
1756 }
1757}
1758
1759void grep_source_clear(struct grep_source *gs)
1760{
1761 free(gs->name);
1762 gs->name = NULL;
55c61688
NTND
1763 free(gs->path);
1764 gs->path = NULL;
e1327023
JK
1765 free(gs->identifier);
1766 gs->identifier = NULL;
1767 grep_source_clear_data(gs);
1768}
1769
1770void grep_source_clear_data(struct grep_source *gs)
1771{
1772 switch (gs->type) {
1773 case GREP_SOURCE_FILE:
1c41c82b 1774 case GREP_SOURCE_OID:
4538eef5 1775 case GREP_SOURCE_SUBMODULE:
e1327023
JK
1776 free(gs->buf);
1777 gs->buf = NULL;
1778 gs->size = 0;
1779 break;
1780 case GREP_SOURCE_BUF:
1781 /* leave user-provided buf intact */
1782 break;
1783 }
1784}
1785
1c41c82b 1786static int grep_source_load_oid(struct grep_source *gs)
e1327023
JK
1787{
1788 enum object_type type;
1789
1790 grep_read_lock();
1791 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1792 grep_read_unlock();
1793
1794 if (!gs->buf)
1795 return error(_("'%s': unable to read %s"),
1796 gs->name,
1c41c82b 1797 oid_to_hex(gs->identifier));
e1327023
JK
1798 return 0;
1799}
1800
1801static int grep_source_load_file(struct grep_source *gs)
1802{
1803 const char *filename = gs->identifier;
1804 struct stat st;
1805 char *data;
1806 size_t size;
1807 int i;
1808
1809 if (lstat(filename, &st) < 0) {
1810 err_ret:
1811 if (errno != ENOENT)
7645d8f1 1812 error_errno(_("failed to stat '%s'"), filename);
e1327023
JK
1813 return -1;
1814 }
1815 if (!S_ISREG(st.st_mode))
1816 return -1;
1817 size = xsize_t(st.st_size);
1818 i = open(filename, O_RDONLY);
1819 if (i < 0)
1820 goto err_ret;
3733e694 1821 data = xmallocz(size);
e1327023 1822 if (st.st_size != read_in_full(i, data, size)) {
7645d8f1 1823 error_errno(_("'%s': short read"), filename);
e1327023
JK
1824 close(i);
1825 free(data);
1826 return -1;
1827 }
1828 close(i);
e1327023
JK
1829
1830 gs->buf = data;
1831 gs->size = size;
1832 return 0;
1833}
1834
3083301e 1835static int grep_source_load(struct grep_source *gs)
e1327023
JK
1836{
1837 if (gs->buf)
1838 return 0;
1839
1840 switch (gs->type) {
1841 case GREP_SOURCE_FILE:
1842 return grep_source_load_file(gs);
1c41c82b
BW
1843 case GREP_SOURCE_OID:
1844 return grep_source_load_oid(gs);
e1327023
JK
1845 case GREP_SOURCE_BUF:
1846 return gs->buf ? 0 : -1;
4538eef5
BW
1847 case GREP_SOURCE_SUBMODULE:
1848 break;
e1327023 1849 }
4538eef5 1850 die("BUG: invalid grep_source type to load");
0ab7befa 1851}
94ad9d9e
JK
1852
1853void grep_source_load_driver(struct grep_source *gs)
1854{
1855 if (gs->driver)
1856 return;
1857
1858 grep_attr_lock();
55c61688
NTND
1859 if (gs->path)
1860 gs->driver = userdiff_find_by_path(gs->path);
94ad9d9e
JK
1861 if (!gs->driver)
1862 gs->driver = userdiff_find_by_name("default");
1863 grep_attr_unlock();
1864}
41b59bfc 1865
3083301e 1866static int grep_source_is_binary(struct grep_source *gs)
41b59bfc
JK
1867{
1868 grep_source_load_driver(gs);
1869 if (gs->driver->binary != -1)
1870 return gs->driver->binary;
1871
1872 if (!grep_source_load(gs))
1873 return buffer_is_binary(gs->buf, gs->size);
1874
1875 return 0;
1876}