builtin/fsck: convert remaining caller of get_sha1 to object_id
[git/debian.git] / grep.c
blob98733db623ae2a0c4b3c11b71e3560429ec975ff
1 #include "cache.h"
2 #include "config.h"
3 #include "grep.h"
4 #include "userdiff.h"
5 #include "xdiff-interface.h"
6 #include "diff.h"
7 #include "diffcore.h"
8 #include "commit.h"
9 #include "quote.h"
11 static int grep_source_load(struct grep_source *gs);
12 static int grep_source_is_binary(struct grep_source *gs);
14 static struct grep_opt grep_defaults;
16 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
18 fwrite(buf, size, 1, stdout);
22 * Initialize the grep_defaults template with hardcoded defaults.
23 * We could let the compiler do this, but without C99 initializers
24 * the code gets unwieldy and unreadable, so...
26 void init_grep_defaults(void)
28 struct grep_opt *opt = &grep_defaults;
29 static int run_once;
31 if (run_once)
32 return;
33 run_once++;
35 memset(opt, 0, sizeof(*opt));
36 opt->relative = 1;
37 opt->pathname = 1;
38 opt->regflags = REG_NEWLINE;
39 opt->max_depth = -1;
40 opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
41 opt->extended_regexp_option = 0;
42 color_set(opt->color_context, "");
43 color_set(opt->color_filename, "");
44 color_set(opt->color_function, "");
45 color_set(opt->color_lineno, "");
46 color_set(opt->color_match_context, GIT_COLOR_BOLD_RED);
47 color_set(opt->color_match_selected, GIT_COLOR_BOLD_RED);
48 color_set(opt->color_selected, "");
49 color_set(opt->color_sep, GIT_COLOR_CYAN);
50 opt->color = -1;
51 opt->output = std_output;
54 static int parse_pattern_type_arg(const char *opt, const char *arg)
56 if (!strcmp(arg, "default"))
57 return GREP_PATTERN_TYPE_UNSPECIFIED;
58 else if (!strcmp(arg, "basic"))
59 return GREP_PATTERN_TYPE_BRE;
60 else if (!strcmp(arg, "extended"))
61 return GREP_PATTERN_TYPE_ERE;
62 else if (!strcmp(arg, "fixed"))
63 return GREP_PATTERN_TYPE_FIXED;
64 else if (!strcmp(arg, "perl"))
65 return GREP_PATTERN_TYPE_PCRE;
66 die("bad %s argument: %s", opt, arg);
70 * Read the configuration file once and store it in
71 * the grep_defaults template.
73 int grep_config(const char *var, const char *value, void *cb)
75 struct grep_opt *opt = &grep_defaults;
76 char *color = NULL;
78 if (userdiff_config(var, value) < 0)
79 return -1;
81 if (!strcmp(var, "grep.extendedregexp")) {
82 if (git_config_bool(var, value))
83 opt->extended_regexp_option = 1;
84 else
85 opt->extended_regexp_option = 0;
86 return 0;
89 if (!strcmp(var, "grep.patterntype")) {
90 opt->pattern_type_option = parse_pattern_type_arg(var, value);
91 return 0;
94 if (!strcmp(var, "grep.linenumber")) {
95 opt->linenum = git_config_bool(var, value);
96 return 0;
99 if (!strcmp(var, "grep.fullname")) {
100 opt->relative = !git_config_bool(var, value);
101 return 0;
104 if (!strcmp(var, "color.grep"))
105 opt->color = git_config_colorbool(var, value);
106 else if (!strcmp(var, "color.grep.context"))
107 color = opt->color_context;
108 else if (!strcmp(var, "color.grep.filename"))
109 color = opt->color_filename;
110 else if (!strcmp(var, "color.grep.function"))
111 color = opt->color_function;
112 else if (!strcmp(var, "color.grep.linenumber"))
113 color = opt->color_lineno;
114 else if (!strcmp(var, "color.grep.matchcontext"))
115 color = opt->color_match_context;
116 else if (!strcmp(var, "color.grep.matchselected"))
117 color = opt->color_match_selected;
118 else if (!strcmp(var, "color.grep.selected"))
119 color = opt->color_selected;
120 else if (!strcmp(var, "color.grep.separator"))
121 color = opt->color_sep;
122 else if (!strcmp(var, "color.grep.match")) {
123 int rc = 0;
124 if (!value)
125 return config_error_nonbool(var);
126 rc |= color_parse(value, opt->color_match_context);
127 rc |= color_parse(value, opt->color_match_selected);
128 return rc;
131 if (color) {
132 if (!value)
133 return config_error_nonbool(var);
134 return color_parse(value, color);
136 return 0;
140 * Initialize one instance of grep_opt and copy the
141 * default values from the template we read the configuration
142 * information in an earlier call to git_config(grep_config).
144 void grep_init(struct grep_opt *opt, const char *prefix)
146 struct grep_opt *def = &grep_defaults;
148 memset(opt, 0, sizeof(*opt));
149 opt->prefix = prefix;
150 opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
151 opt->pattern_tail = &opt->pattern_list;
152 opt->header_tail = &opt->header_list;
154 opt->color = def->color;
155 opt->extended_regexp_option = def->extended_regexp_option;
156 opt->pattern_type_option = def->pattern_type_option;
157 opt->linenum = def->linenum;
158 opt->max_depth = def->max_depth;
159 opt->pathname = def->pathname;
160 opt->regflags = def->regflags;
161 opt->relative = def->relative;
162 opt->output = def->output;
164 color_set(opt->color_context, def->color_context);
165 color_set(opt->color_filename, def->color_filename);
166 color_set(opt->color_function, def->color_function);
167 color_set(opt->color_lineno, def->color_lineno);
168 color_set(opt->color_match_context, def->color_match_context);
169 color_set(opt->color_match_selected, def->color_match_selected);
170 color_set(opt->color_selected, def->color_selected);
171 color_set(opt->color_sep, def->color_sep);
174 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
176 switch (pattern_type) {
177 case GREP_PATTERN_TYPE_UNSPECIFIED:
178 /* fall through */
180 case GREP_PATTERN_TYPE_BRE:
181 opt->fixed = 0;
182 opt->pcre1 = 0;
183 opt->pcre2 = 0;
184 break;
186 case GREP_PATTERN_TYPE_ERE:
187 opt->fixed = 0;
188 opt->pcre1 = 0;
189 opt->pcre2 = 0;
190 opt->regflags |= REG_EXTENDED;
191 break;
193 case GREP_PATTERN_TYPE_FIXED:
194 opt->fixed = 1;
195 opt->pcre1 = 0;
196 opt->pcre2 = 0;
197 break;
199 case GREP_PATTERN_TYPE_PCRE:
200 opt->fixed = 0;
201 #ifdef USE_LIBPCRE2
202 opt->pcre1 = 0;
203 opt->pcre2 = 1;
204 #else
206 * It's important that pcre1 always be assigned to
207 * even when there's no USE_LIBPCRE* defined. We still
208 * call the PCRE stub function, it just dies with
209 * "cannot use Perl-compatible regexes[...]".
211 opt->pcre1 = 1;
212 opt->pcre2 = 0;
213 #endif
214 break;
218 void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
220 if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
221 grep_set_pattern_type_option(pattern_type, opt);
222 else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
223 grep_set_pattern_type_option(opt->pattern_type_option, opt);
224 else if (opt->extended_regexp_option)
225 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
228 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
229 const char *origin, int no,
230 enum grep_pat_token t,
231 enum grep_header_field field)
233 struct grep_pat *p = xcalloc(1, sizeof(*p));
234 p->pattern = xmemdupz(pat, patlen);
235 p->patternlen = patlen;
236 p->origin = origin;
237 p->no = no;
238 p->token = t;
239 p->field = field;
240 return p;
243 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
245 **tail = p;
246 *tail = &p->next;
247 p->next = NULL;
249 switch (p->token) {
250 case GREP_PATTERN: /* atom */
251 case GREP_PATTERN_HEAD:
252 case GREP_PATTERN_BODY:
253 for (;;) {
254 struct grep_pat *new_pat;
255 size_t len = 0;
256 char *cp = p->pattern + p->patternlen, *nl = NULL;
257 while (++len <= p->patternlen) {
258 if (*(--cp) == '\n') {
259 nl = cp;
260 break;
263 if (!nl)
264 break;
265 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
266 p->no, p->token, p->field);
267 new_pat->next = p->next;
268 if (!p->next)
269 *tail = &new_pat->next;
270 p->next = new_pat;
271 *nl = '\0';
272 p->patternlen -= len;
274 break;
275 default:
276 break;
280 void append_header_grep_pattern(struct grep_opt *opt,
281 enum grep_header_field field, const char *pat)
283 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
284 GREP_PATTERN_HEAD, field);
285 if (field == GREP_HEADER_REFLOG)
286 opt->use_reflog_filter = 1;
287 do_append_grep_pat(&opt->header_tail, p);
290 void append_grep_pattern(struct grep_opt *opt, const char *pat,
291 const char *origin, int no, enum grep_pat_token t)
293 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
296 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
297 const char *origin, int no, enum grep_pat_token t)
299 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
300 do_append_grep_pat(&opt->pattern_tail, p);
303 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
305 struct grep_pat *pat;
306 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
307 *ret = *opt;
309 ret->pattern_list = NULL;
310 ret->pattern_tail = &ret->pattern_list;
312 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
314 if(pat->token == GREP_PATTERN_HEAD)
315 append_header_grep_pattern(ret, pat->field,
316 pat->pattern);
317 else
318 append_grep_pat(ret, pat->pattern, pat->patternlen,
319 pat->origin, pat->no, pat->token);
322 return ret;
325 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
326 const char *error)
328 char where[1024];
330 if (p->no)
331 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
332 else if (p->origin)
333 xsnprintf(where, sizeof(where), "%s, ", p->origin);
334 else
335 where[0] = 0;
337 die("%s'%s': %s", where, p->pattern, error);
340 static int is_fixed(const char *s, size_t len)
342 size_t i;
344 for (i = 0; i < len; i++) {
345 if (is_regex_special(s[i]))
346 return 0;
349 return 1;
352 static int has_null(const char *s, size_t len)
355 * regcomp cannot accept patterns with NULs so when using it
356 * we consider any pattern containing a NUL fixed.
358 if (memchr(s, 0, len))
359 return 1;
361 return 0;
364 #ifdef USE_LIBPCRE1
365 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
367 const char *error;
368 int erroffset;
369 int options = PCRE_MULTILINE;
371 if (opt->ignore_case) {
372 if (has_non_ascii(p->pattern))
373 p->pcre1_tables = pcre_maketables();
374 options |= PCRE_CASELESS;
376 if (is_utf8_locale() && has_non_ascii(p->pattern))
377 options |= PCRE_UTF8;
379 p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
380 p->pcre1_tables);
381 if (!p->pcre1_regexp)
382 compile_regexp_failed(p, error);
384 p->pcre1_extra_info = pcre_study(p->pcre1_regexp, PCRE_STUDY_JIT_COMPILE, &error);
385 if (!p->pcre1_extra_info && error)
386 die("%s", error);
388 #ifdef GIT_PCRE1_USE_JIT
389 pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
390 if (p->pcre1_jit_on == 1) {
391 p->pcre1_jit_stack = pcre_jit_stack_alloc(1, 1024 * 1024);
392 if (!p->pcre1_jit_stack)
393 die("Couldn't allocate PCRE JIT stack");
394 pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
395 } else if (p->pcre1_jit_on != 0) {
396 die("BUG: The pcre1_jit_on variable should be 0 or 1, not %d",
397 p->pcre1_jit_on);
399 #endif
402 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
403 regmatch_t *match, int eflags)
405 int ovector[30], ret, flags = 0;
407 if (eflags & REG_NOTBOL)
408 flags |= PCRE_NOTBOL;
410 #ifdef GIT_PCRE1_USE_JIT
411 if (p->pcre1_jit_on) {
412 ret = pcre_jit_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
413 eol - line, 0, flags, ovector,
414 ARRAY_SIZE(ovector), p->pcre1_jit_stack);
415 } else
416 #endif
418 ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
419 eol - line, 0, flags, ovector,
420 ARRAY_SIZE(ovector));
423 if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
424 die("pcre_exec failed with error code %d", ret);
425 if (ret > 0) {
426 ret = 0;
427 match->rm_so = ovector[0];
428 match->rm_eo = ovector[1];
431 return ret;
434 static void free_pcre1_regexp(struct grep_pat *p)
436 pcre_free(p->pcre1_regexp);
437 #ifdef GIT_PCRE1_USE_JIT
438 if (p->pcre1_jit_on) {
439 pcre_free_study(p->pcre1_extra_info);
440 pcre_jit_stack_free(p->pcre1_jit_stack);
441 } else
442 #endif
444 pcre_free(p->pcre1_extra_info);
446 pcre_free((void *)p->pcre1_tables);
448 #else /* !USE_LIBPCRE1 */
449 static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
451 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
454 static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
455 regmatch_t *match, int eflags)
457 return 1;
460 static void free_pcre1_regexp(struct grep_pat *p)
463 #endif /* !USE_LIBPCRE1 */
465 #ifdef USE_LIBPCRE2
466 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
468 int error;
469 PCRE2_UCHAR errbuf[256];
470 PCRE2_SIZE erroffset;
471 int options = PCRE2_MULTILINE;
472 const uint8_t *character_tables = NULL;
473 int jitret;
475 assert(opt->pcre2);
477 p->pcre2_compile_context = NULL;
479 if (opt->ignore_case) {
480 if (has_non_ascii(p->pattern)) {
481 character_tables = pcre2_maketables(NULL);
482 p->pcre2_compile_context = pcre2_compile_context_create(NULL);
483 pcre2_set_character_tables(p->pcre2_compile_context, character_tables);
485 options |= PCRE2_CASELESS;
487 if (is_utf8_locale() && has_non_ascii(p->pattern))
488 options |= PCRE2_UTF;
490 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
491 p->patternlen, options, &error, &erroffset,
492 p->pcre2_compile_context);
494 if (p->pcre2_pattern) {
495 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
496 if (!p->pcre2_match_data)
497 die("Couldn't allocate PCRE2 match data");
498 } else {
499 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
500 compile_regexp_failed(p, (const char *)&errbuf);
503 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
504 if (p->pcre2_jit_on == 1) {
505 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
506 if (jitret)
507 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
508 p->pcre2_jit_stack = pcre2_jit_stack_create(1, 1024 * 1024, NULL);
509 if (!p->pcre2_jit_stack)
510 die("Couldn't allocate PCRE2 JIT stack");
511 p->pcre2_match_context = pcre2_match_context_create(NULL);
512 if (!p->pcre2_match_context)
513 die("Couldn't allocate PCRE2 match context");
514 pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
515 } else if (p->pcre2_jit_on != 0) {
516 die("BUG: The pcre2_jit_on variable should be 0 or 1, not %d",
517 p->pcre1_jit_on);
521 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
522 regmatch_t *match, int eflags)
524 int ret, flags = 0;
525 PCRE2_SIZE *ovector;
526 PCRE2_UCHAR errbuf[256];
528 if (eflags & REG_NOTBOL)
529 flags |= PCRE2_NOTBOL;
531 if (p->pcre2_jit_on)
532 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
533 eol - line, 0, flags, p->pcre2_match_data,
534 NULL);
535 else
536 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
537 eol - line, 0, flags, p->pcre2_match_data,
538 NULL);
540 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
541 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
542 die("%s failed with error code %d: %s",
543 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
544 errbuf);
546 if (ret > 0) {
547 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
548 ret = 0;
549 match->rm_so = (int)ovector[0];
550 match->rm_eo = (int)ovector[1];
553 return ret;
556 static void free_pcre2_pattern(struct grep_pat *p)
558 pcre2_compile_context_free(p->pcre2_compile_context);
559 pcre2_code_free(p->pcre2_pattern);
560 pcre2_match_data_free(p->pcre2_match_data);
561 pcre2_jit_stack_free(p->pcre2_jit_stack);
562 pcre2_match_context_free(p->pcre2_match_context);
564 #else /* !USE_LIBPCRE2 */
565 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
568 * Unreachable until USE_LIBPCRE2 becomes synonymous with
569 * USE_LIBPCRE. See the sibling comment in
570 * grep_set_pattern_type_option().
572 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
575 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
576 regmatch_t *match, int eflags)
578 return 1;
581 static void free_pcre2_pattern(struct grep_pat *p)
584 #endif /* !USE_LIBPCRE2 */
586 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
588 struct strbuf sb = STRBUF_INIT;
589 int err;
590 int regflags = opt->regflags;
592 basic_regex_quote_buf(&sb, p->pattern);
593 if (opt->ignore_case)
594 regflags |= REG_ICASE;
595 err = regcomp(&p->regexp, sb.buf, regflags);
596 if (opt->debug)
597 fprintf(stderr, "fixed %s\n", sb.buf);
598 strbuf_release(&sb);
599 if (err) {
600 char errbuf[1024];
601 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
602 regfree(&p->regexp);
603 compile_regexp_failed(p, errbuf);
607 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
609 int icase, ascii_only;
610 int err;
612 p->word_regexp = opt->word_regexp;
613 p->ignore_case = opt->ignore_case;
614 icase = opt->regflags & REG_ICASE || p->ignore_case;
615 ascii_only = !has_non_ascii(p->pattern);
618 * Even when -F (fixed) asks us to do a non-regexp search, we
619 * may not be able to correctly case-fold when -i
620 * (ignore-case) is asked (in which case, we'll synthesize a
621 * regexp to match the pattern that matches regexp special
622 * characters literally, while ignoring case differences). On
623 * the other hand, even without -F, if the pattern does not
624 * have any regexp special characters and there is no need for
625 * case-folding search, we can internally turn it into a
626 * simple string match using kws. p->fixed tells us if we
627 * want to use kws.
629 if (opt->fixed ||
630 has_null(p->pattern, p->patternlen) ||
631 is_fixed(p->pattern, p->patternlen))
632 p->fixed = !icase || ascii_only;
633 else
634 p->fixed = 0;
636 if (p->fixed) {
637 p->kws = kwsalloc(icase ? tolower_trans_tbl : NULL);
638 kwsincr(p->kws, p->pattern, p->patternlen);
639 kwsprep(p->kws);
640 return;
641 } else if (opt->fixed) {
643 * We come here when the pattern has the non-ascii
644 * characters we cannot case-fold, and asked to
645 * ignore-case.
647 compile_fixed_regexp(p, opt);
648 return;
651 if (opt->pcre2) {
652 compile_pcre2_pattern(p, opt);
653 return;
656 if (opt->pcre1) {
657 compile_pcre1_regexp(p, opt);
658 return;
661 err = regcomp(&p->regexp, p->pattern, opt->regflags);
662 if (err) {
663 char errbuf[1024];
664 regerror(err, &p->regexp, errbuf, 1024);
665 regfree(&p->regexp);
666 compile_regexp_failed(p, errbuf);
670 static struct grep_expr *compile_pattern_or(struct grep_pat **);
671 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
673 struct grep_pat *p;
674 struct grep_expr *x;
676 p = *list;
677 if (!p)
678 return NULL;
679 switch (p->token) {
680 case GREP_PATTERN: /* atom */
681 case GREP_PATTERN_HEAD:
682 case GREP_PATTERN_BODY:
683 x = xcalloc(1, sizeof (struct grep_expr));
684 x->node = GREP_NODE_ATOM;
685 x->u.atom = p;
686 *list = p->next;
687 return x;
688 case GREP_OPEN_PAREN:
689 *list = p->next;
690 x = compile_pattern_or(list);
691 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
692 die("unmatched parenthesis");
693 *list = (*list)->next;
694 return x;
695 default:
696 return NULL;
700 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
702 struct grep_pat *p;
703 struct grep_expr *x;
705 p = *list;
706 if (!p)
707 return NULL;
708 switch (p->token) {
709 case GREP_NOT:
710 if (!p->next)
711 die("--not not followed by pattern expression");
712 *list = p->next;
713 x = xcalloc(1, sizeof (struct grep_expr));
714 x->node = GREP_NODE_NOT;
715 x->u.unary = compile_pattern_not(list);
716 if (!x->u.unary)
717 die("--not followed by non pattern expression");
718 return x;
719 default:
720 return compile_pattern_atom(list);
724 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
726 struct grep_pat *p;
727 struct grep_expr *x, *y, *z;
729 x = compile_pattern_not(list);
730 p = *list;
731 if (p && p->token == GREP_AND) {
732 if (!p->next)
733 die("--and not followed by pattern expression");
734 *list = p->next;
735 y = compile_pattern_and(list);
736 if (!y)
737 die("--and not followed by pattern expression");
738 z = xcalloc(1, sizeof (struct grep_expr));
739 z->node = GREP_NODE_AND;
740 z->u.binary.left = x;
741 z->u.binary.right = y;
742 return z;
744 return x;
747 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
749 struct grep_pat *p;
750 struct grep_expr *x, *y, *z;
752 x = compile_pattern_and(list);
753 p = *list;
754 if (x && p && p->token != GREP_CLOSE_PAREN) {
755 y = compile_pattern_or(list);
756 if (!y)
757 die("not a pattern expression %s", p->pattern);
758 z = xcalloc(1, sizeof (struct grep_expr));
759 z->node = GREP_NODE_OR;
760 z->u.binary.left = x;
761 z->u.binary.right = y;
762 return z;
764 return x;
767 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
769 return compile_pattern_or(list);
772 static void indent(int in)
774 while (in-- > 0)
775 fputc(' ', stderr);
778 static void dump_grep_pat(struct grep_pat *p)
780 switch (p->token) {
781 case GREP_AND: fprintf(stderr, "*and*"); break;
782 case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
783 case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
784 case GREP_NOT: fprintf(stderr, "*not*"); break;
785 case GREP_OR: fprintf(stderr, "*or*"); break;
787 case GREP_PATTERN: fprintf(stderr, "pattern"); break;
788 case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
789 case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
792 switch (p->token) {
793 default: break;
794 case GREP_PATTERN_HEAD:
795 fprintf(stderr, "<head %d>", p->field); break;
796 case GREP_PATTERN_BODY:
797 fprintf(stderr, "<body>"); break;
799 switch (p->token) {
800 default: break;
801 case GREP_PATTERN_HEAD:
802 case GREP_PATTERN_BODY:
803 case GREP_PATTERN:
804 fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
805 break;
807 fputc('\n', stderr);
810 static void dump_grep_expression_1(struct grep_expr *x, int in)
812 indent(in);
813 switch (x->node) {
814 case GREP_NODE_TRUE:
815 fprintf(stderr, "true\n");
816 break;
817 case GREP_NODE_ATOM:
818 dump_grep_pat(x->u.atom);
819 break;
820 case GREP_NODE_NOT:
821 fprintf(stderr, "(not\n");
822 dump_grep_expression_1(x->u.unary, in+1);
823 indent(in);
824 fprintf(stderr, ")\n");
825 break;
826 case GREP_NODE_AND:
827 fprintf(stderr, "(and\n");
828 dump_grep_expression_1(x->u.binary.left, in+1);
829 dump_grep_expression_1(x->u.binary.right, in+1);
830 indent(in);
831 fprintf(stderr, ")\n");
832 break;
833 case GREP_NODE_OR:
834 fprintf(stderr, "(or\n");
835 dump_grep_expression_1(x->u.binary.left, in+1);
836 dump_grep_expression_1(x->u.binary.right, in+1);
837 indent(in);
838 fprintf(stderr, ")\n");
839 break;
843 static void dump_grep_expression(struct grep_opt *opt)
845 struct grep_expr *x = opt->pattern_expression;
847 if (opt->all_match)
848 fprintf(stderr, "[all-match]\n");
849 dump_grep_expression_1(x, 0);
850 fflush(NULL);
853 static struct grep_expr *grep_true_expr(void)
855 struct grep_expr *z = xcalloc(1, sizeof(*z));
856 z->node = GREP_NODE_TRUE;
857 return z;
860 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
862 struct grep_expr *z = xcalloc(1, sizeof(*z));
863 z->node = GREP_NODE_OR;
864 z->u.binary.left = left;
865 z->u.binary.right = right;
866 return z;
869 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
871 struct grep_pat *p;
872 struct grep_expr *header_expr;
873 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
874 enum grep_header_field fld;
876 if (!opt->header_list)
877 return NULL;
879 for (p = opt->header_list; p; p = p->next) {
880 if (p->token != GREP_PATTERN_HEAD)
881 die("BUG: a non-header pattern in grep header list.");
882 if (p->field < GREP_HEADER_FIELD_MIN ||
883 GREP_HEADER_FIELD_MAX <= p->field)
884 die("BUG: unknown header field %d", p->field);
885 compile_regexp(p, opt);
888 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
889 header_group[fld] = NULL;
891 for (p = opt->header_list; p; p = p->next) {
892 struct grep_expr *h;
893 struct grep_pat *pp = p;
895 h = compile_pattern_atom(&pp);
896 if (!h || pp != p->next)
897 die("BUG: malformed header expr");
898 if (!header_group[p->field]) {
899 header_group[p->field] = h;
900 continue;
902 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
905 header_expr = NULL;
907 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
908 if (!header_group[fld])
909 continue;
910 if (!header_expr)
911 header_expr = grep_true_expr();
912 header_expr = grep_or_expr(header_group[fld], header_expr);
914 return header_expr;
917 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
919 struct grep_expr *z = x;
921 while (x) {
922 assert(x->node == GREP_NODE_OR);
923 if (x->u.binary.right &&
924 x->u.binary.right->node == GREP_NODE_TRUE) {
925 x->u.binary.right = y;
926 break;
928 x = x->u.binary.right;
930 return z;
933 static void compile_grep_patterns_real(struct grep_opt *opt)
935 struct grep_pat *p;
936 struct grep_expr *header_expr = prep_header_patterns(opt);
938 for (p = opt->pattern_list; p; p = p->next) {
939 switch (p->token) {
940 case GREP_PATTERN: /* atom */
941 case GREP_PATTERN_HEAD:
942 case GREP_PATTERN_BODY:
943 compile_regexp(p, opt);
944 break;
945 default:
946 opt->extended = 1;
947 break;
951 if (opt->all_match || header_expr)
952 opt->extended = 1;
953 else if (!opt->extended && !opt->debug)
954 return;
956 p = opt->pattern_list;
957 if (p)
958 opt->pattern_expression = compile_pattern_expr(&p);
959 if (p)
960 die("incomplete pattern expression: %s", p->pattern);
962 if (!header_expr)
963 return;
965 if (!opt->pattern_expression)
966 opt->pattern_expression = header_expr;
967 else if (opt->all_match)
968 opt->pattern_expression = grep_splice_or(header_expr,
969 opt->pattern_expression);
970 else
971 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
972 header_expr);
973 opt->all_match = 1;
976 void compile_grep_patterns(struct grep_opt *opt)
978 compile_grep_patterns_real(opt);
979 if (opt->debug)
980 dump_grep_expression(opt);
983 static void free_pattern_expr(struct grep_expr *x)
985 switch (x->node) {
986 case GREP_NODE_TRUE:
987 case GREP_NODE_ATOM:
988 break;
989 case GREP_NODE_NOT:
990 free_pattern_expr(x->u.unary);
991 break;
992 case GREP_NODE_AND:
993 case GREP_NODE_OR:
994 free_pattern_expr(x->u.binary.left);
995 free_pattern_expr(x->u.binary.right);
996 break;
998 free(x);
1001 void free_grep_patterns(struct grep_opt *opt)
1003 struct grep_pat *p, *n;
1005 for (p = opt->pattern_list; p; p = n) {
1006 n = p->next;
1007 switch (p->token) {
1008 case GREP_PATTERN: /* atom */
1009 case GREP_PATTERN_HEAD:
1010 case GREP_PATTERN_BODY:
1011 if (p->kws)
1012 kwsfree(p->kws);
1013 else if (p->pcre1_regexp)
1014 free_pcre1_regexp(p);
1015 else if (p->pcre2_pattern)
1016 free_pcre2_pattern(p);
1017 else
1018 regfree(&p->regexp);
1019 free(p->pattern);
1020 break;
1021 default:
1022 break;
1024 free(p);
1027 if (!opt->extended)
1028 return;
1029 free_pattern_expr(opt->pattern_expression);
1032 static char *end_of_line(char *cp, unsigned long *left)
1034 unsigned long l = *left;
1035 while (l && *cp != '\n') {
1036 l--;
1037 cp++;
1039 *left = l;
1040 return cp;
1043 static int word_char(char ch)
1045 return isalnum(ch) || ch == '_';
1048 static void output_color(struct grep_opt *opt, const void *data, size_t size,
1049 const char *color)
1051 if (want_color(opt->color) && color && color[0]) {
1052 opt->output(opt, color, strlen(color));
1053 opt->output(opt, data, size);
1054 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
1055 } else
1056 opt->output(opt, data, size);
1059 static void output_sep(struct grep_opt *opt, char sign)
1061 if (opt->null_following_name)
1062 opt->output(opt, "\0", 1);
1063 else
1064 output_color(opt, &sign, 1, opt->color_sep);
1067 static void show_name(struct grep_opt *opt, const char *name)
1069 output_color(opt, name, strlen(name), opt->color_filename);
1070 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
1073 static int fixmatch(struct grep_pat *p, char *line, char *eol,
1074 regmatch_t *match)
1076 struct kwsmatch kwsm;
1077 size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
1078 if (offset == -1) {
1079 match->rm_so = match->rm_eo = -1;
1080 return REG_NOMATCH;
1081 } else {
1082 match->rm_so = offset;
1083 match->rm_eo = match->rm_so + kwsm.size[0];
1084 return 0;
1088 static int patmatch(struct grep_pat *p, char *line, char *eol,
1089 regmatch_t *match, int eflags)
1091 int hit;
1093 if (p->fixed)
1094 hit = !fixmatch(p, line, eol, match);
1095 else if (p->pcre1_regexp)
1096 hit = !pcre1match(p, line, eol, match, eflags);
1097 else if (p->pcre2_pattern)
1098 hit = !pcre2match(p, line, eol, match, eflags);
1099 else
1100 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
1101 eflags);
1103 return hit;
1106 static int strip_timestamp(char *bol, char **eol_p)
1108 char *eol = *eol_p;
1109 int ch;
1111 while (bol < --eol) {
1112 if (*eol != '>')
1113 continue;
1114 *eol_p = ++eol;
1115 ch = *eol;
1116 *eol = '\0';
1117 return ch;
1119 return 0;
1122 static struct {
1123 const char *field;
1124 size_t len;
1125 } header_field[] = {
1126 { "author ", 7 },
1127 { "committer ", 10 },
1128 { "reflog ", 7 },
1131 static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
1132 enum grep_context ctx,
1133 regmatch_t *pmatch, int eflags)
1135 int hit = 0;
1136 int saved_ch = 0;
1137 const char *start = bol;
1139 if ((p->token != GREP_PATTERN) &&
1140 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
1141 return 0;
1143 if (p->token == GREP_PATTERN_HEAD) {
1144 const char *field;
1145 size_t len;
1146 assert(p->field < ARRAY_SIZE(header_field));
1147 field = header_field[p->field].field;
1148 len = header_field[p->field].len;
1149 if (strncmp(bol, field, len))
1150 return 0;
1151 bol += len;
1152 switch (p->field) {
1153 case GREP_HEADER_AUTHOR:
1154 case GREP_HEADER_COMMITTER:
1155 saved_ch = strip_timestamp(bol, &eol);
1156 break;
1157 default:
1158 break;
1162 again:
1163 hit = patmatch(p, bol, eol, pmatch, eflags);
1165 if (hit && p->word_regexp) {
1166 if ((pmatch[0].rm_so < 0) ||
1167 (eol - bol) < pmatch[0].rm_so ||
1168 (pmatch[0].rm_eo < 0) ||
1169 (eol - bol) < pmatch[0].rm_eo)
1170 die("regexp returned nonsense");
1172 /* Match beginning must be either beginning of the
1173 * line, or at word boundary (i.e. the last char must
1174 * not be a word char). Similarly, match end must be
1175 * either end of the line, or at word boundary
1176 * (i.e. the next char must not be a word char).
1178 if ( ((pmatch[0].rm_so == 0) ||
1179 !word_char(bol[pmatch[0].rm_so-1])) &&
1180 ((pmatch[0].rm_eo == (eol-bol)) ||
1181 !word_char(bol[pmatch[0].rm_eo])) )
1183 else
1184 hit = 0;
1186 /* Words consist of at least one character. */
1187 if (pmatch->rm_so == pmatch->rm_eo)
1188 hit = 0;
1190 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
1191 /* There could be more than one match on the
1192 * line, and the first match might not be
1193 * strict word match. But later ones could be!
1194 * Forward to the next possible start, i.e. the
1195 * next position following a non-word char.
1197 bol = pmatch[0].rm_so + bol + 1;
1198 while (word_char(bol[-1]) && bol < eol)
1199 bol++;
1200 eflags |= REG_NOTBOL;
1201 if (bol < eol)
1202 goto again;
1205 if (p->token == GREP_PATTERN_HEAD && saved_ch)
1206 *eol = saved_ch;
1207 if (hit) {
1208 pmatch[0].rm_so += bol - start;
1209 pmatch[0].rm_eo += bol - start;
1211 return hit;
1214 static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
1215 enum grep_context ctx, int collect_hits)
1217 int h = 0;
1218 regmatch_t match;
1220 if (!x)
1221 die("Not a valid grep expression");
1222 switch (x->node) {
1223 case GREP_NODE_TRUE:
1224 h = 1;
1225 break;
1226 case GREP_NODE_ATOM:
1227 h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
1228 break;
1229 case GREP_NODE_NOT:
1230 h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
1231 break;
1232 case GREP_NODE_AND:
1233 if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
1234 return 0;
1235 h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
1236 break;
1237 case GREP_NODE_OR:
1238 if (!collect_hits)
1239 return (match_expr_eval(x->u.binary.left,
1240 bol, eol, ctx, 0) ||
1241 match_expr_eval(x->u.binary.right,
1242 bol, eol, ctx, 0));
1243 h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
1244 x->u.binary.left->hit |= h;
1245 h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
1246 break;
1247 default:
1248 die("Unexpected node type (internal error) %d", x->node);
1250 if (collect_hits)
1251 x->hit |= h;
1252 return h;
1255 static int match_expr(struct grep_opt *opt, char *bol, char *eol,
1256 enum grep_context ctx, int collect_hits)
1258 struct grep_expr *x = opt->pattern_expression;
1259 return match_expr_eval(x, bol, eol, ctx, collect_hits);
1262 static int match_line(struct grep_opt *opt, char *bol, char *eol,
1263 enum grep_context ctx, int collect_hits)
1265 struct grep_pat *p;
1266 regmatch_t match;
1268 if (opt->extended)
1269 return match_expr(opt, bol, eol, ctx, collect_hits);
1271 /* we do not call with collect_hits without being extended */
1272 for (p = opt->pattern_list; p; p = p->next) {
1273 if (match_one_pattern(p, bol, eol, ctx, &match, 0))
1274 return 1;
1276 return 0;
1279 static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
1280 enum grep_context ctx,
1281 regmatch_t *pmatch, int eflags)
1283 regmatch_t match;
1285 if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
1286 return 0;
1287 if (match.rm_so < 0 || match.rm_eo < 0)
1288 return 0;
1289 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1290 if (match.rm_so > pmatch->rm_so)
1291 return 1;
1292 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1293 return 1;
1295 pmatch->rm_so = match.rm_so;
1296 pmatch->rm_eo = match.rm_eo;
1297 return 1;
1300 static int next_match(struct grep_opt *opt, char *bol, char *eol,
1301 enum grep_context ctx, regmatch_t *pmatch, int eflags)
1303 struct grep_pat *p;
1304 int hit = 0;
1306 pmatch->rm_so = pmatch->rm_eo = -1;
1307 if (bol < eol) {
1308 for (p = opt->pattern_list; p; p = p->next) {
1309 switch (p->token) {
1310 case GREP_PATTERN: /* atom */
1311 case GREP_PATTERN_HEAD:
1312 case GREP_PATTERN_BODY:
1313 hit |= match_next_pattern(p, bol, eol, ctx,
1314 pmatch, eflags);
1315 break;
1316 default:
1317 break;
1321 return hit;
1324 static void show_line(struct grep_opt *opt, char *bol, char *eol,
1325 const char *name, unsigned lno, char sign)
1327 int rest = eol - bol;
1328 const char *match_color, *line_color = NULL;
1330 if (opt->file_break && opt->last_shown == 0) {
1331 if (opt->show_hunk_mark)
1332 opt->output(opt, "\n", 1);
1333 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1334 if (opt->last_shown == 0) {
1335 if (opt->show_hunk_mark) {
1336 output_color(opt, "--", 2, opt->color_sep);
1337 opt->output(opt, "\n", 1);
1339 } else if (lno > opt->last_shown + 1) {
1340 output_color(opt, "--", 2, opt->color_sep);
1341 opt->output(opt, "\n", 1);
1344 if (opt->heading && opt->last_shown == 0) {
1345 output_color(opt, name, strlen(name), opt->color_filename);
1346 opt->output(opt, "\n", 1);
1348 opt->last_shown = lno;
1350 if (!opt->heading && opt->pathname) {
1351 output_color(opt, name, strlen(name), opt->color_filename);
1352 output_sep(opt, sign);
1354 if (opt->linenum) {
1355 char buf[32];
1356 xsnprintf(buf, sizeof(buf), "%d", lno);
1357 output_color(opt, buf, strlen(buf), opt->color_lineno);
1358 output_sep(opt, sign);
1360 if (opt->color) {
1361 regmatch_t match;
1362 enum grep_context ctx = GREP_CONTEXT_BODY;
1363 int ch = *eol;
1364 int eflags = 0;
1366 if (sign == ':')
1367 match_color = opt->color_match_selected;
1368 else
1369 match_color = opt->color_match_context;
1370 if (sign == ':')
1371 line_color = opt->color_selected;
1372 else if (sign == '-')
1373 line_color = opt->color_context;
1374 else if (sign == '=')
1375 line_color = opt->color_function;
1376 *eol = '\0';
1377 while (next_match(opt, bol, eol, ctx, &match, eflags)) {
1378 if (match.rm_so == match.rm_eo)
1379 break;
1381 output_color(opt, bol, match.rm_so, line_color);
1382 output_color(opt, bol + match.rm_so,
1383 match.rm_eo - match.rm_so, match_color);
1384 bol += match.rm_eo;
1385 rest -= match.rm_eo;
1386 eflags = REG_NOTBOL;
1388 *eol = ch;
1390 output_color(opt, bol, rest, line_color);
1391 opt->output(opt, "\n", 1);
1394 #ifndef NO_PTHREADS
1395 int grep_use_locks;
1398 * This lock protects access to the gitattributes machinery, which is
1399 * not thread-safe.
1401 pthread_mutex_t grep_attr_mutex;
1403 static inline void grep_attr_lock(void)
1405 if (grep_use_locks)
1406 pthread_mutex_lock(&grep_attr_mutex);
1409 static inline void grep_attr_unlock(void)
1411 if (grep_use_locks)
1412 pthread_mutex_unlock(&grep_attr_mutex);
1416 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1418 pthread_mutex_t grep_read_mutex;
1420 #else
1421 #define grep_attr_lock()
1422 #define grep_attr_unlock()
1423 #endif
1425 static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
1427 xdemitconf_t *xecfg = opt->priv;
1428 if (xecfg && !xecfg->find_func) {
1429 grep_source_load_driver(gs);
1430 if (gs->driver->funcname.pattern) {
1431 const struct userdiff_funcname *pe = &gs->driver->funcname;
1432 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1433 } else {
1434 xecfg = opt->priv = NULL;
1438 if (xecfg) {
1439 char buf[1];
1440 return xecfg->find_func(bol, eol - bol, buf, 1,
1441 xecfg->find_func_priv) >= 0;
1444 if (bol == eol)
1445 return 0;
1446 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1447 return 1;
1448 return 0;
1451 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1452 char *bol, unsigned lno)
1454 while (bol > gs->buf) {
1455 char *eol = --bol;
1457 while (bol > gs->buf && bol[-1] != '\n')
1458 bol--;
1459 lno--;
1461 if (lno <= opt->last_shown)
1462 break;
1464 if (match_funcname(opt, gs, bol, eol)) {
1465 show_line(opt, bol, eol, gs->name, lno, '=');
1466 break;
1471 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1472 char *bol, char *end, unsigned lno)
1474 unsigned cur = lno, from = 1, funcname_lno = 0;
1475 int funcname_needed = !!opt->funcname;
1477 if (opt->funcbody && !match_funcname(opt, gs, bol, end))
1478 funcname_needed = 2;
1480 if (opt->pre_context < lno)
1481 from = lno - opt->pre_context;
1482 if (from <= opt->last_shown)
1483 from = opt->last_shown + 1;
1485 /* Rewind. */
1486 while (bol > gs->buf &&
1487 cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
1488 char *eol = --bol;
1490 while (bol > gs->buf && bol[-1] != '\n')
1491 bol--;
1492 cur--;
1493 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1494 funcname_lno = cur;
1495 funcname_needed = 0;
1499 /* We need to look even further back to find a function signature. */
1500 if (opt->funcname && funcname_needed)
1501 show_funcname_line(opt, gs, bol, cur);
1503 /* Back forward. */
1504 while (cur < lno) {
1505 char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1507 while (*eol != '\n')
1508 eol++;
1509 show_line(opt, bol, eol, gs->name, cur, sign);
1510 bol = eol + 1;
1511 cur++;
1515 static int should_lookahead(struct grep_opt *opt)
1517 struct grep_pat *p;
1519 if (opt->extended)
1520 return 0; /* punt for too complex stuff */
1521 if (opt->invert)
1522 return 0;
1523 for (p = opt->pattern_list; p; p = p->next) {
1524 if (p->token != GREP_PATTERN)
1525 return 0; /* punt for "header only" and stuff */
1527 return 1;
1530 static int look_ahead(struct grep_opt *opt,
1531 unsigned long *left_p,
1532 unsigned *lno_p,
1533 char **bol_p)
1535 unsigned lno = *lno_p;
1536 char *bol = *bol_p;
1537 struct grep_pat *p;
1538 char *sp, *last_bol;
1539 regoff_t earliest = -1;
1541 for (p = opt->pattern_list; p; p = p->next) {
1542 int hit;
1543 regmatch_t m;
1545 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1546 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1547 continue;
1548 if (earliest < 0 || m.rm_so < earliest)
1549 earliest = m.rm_so;
1552 if (earliest < 0) {
1553 *bol_p = bol + *left_p;
1554 *left_p = 0;
1555 return 1;
1557 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1558 ; /* find the beginning of the line */
1559 last_bol = sp;
1561 for (sp = bol; sp < last_bol; sp++) {
1562 if (*sp == '\n')
1563 lno++;
1565 *left_p -= last_bol - bol;
1566 *bol_p = last_bol;
1567 *lno_p = lno;
1568 return 0;
1571 static int fill_textconv_grep(struct userdiff_driver *driver,
1572 struct grep_source *gs)
1574 struct diff_filespec *df;
1575 char *buf;
1576 size_t size;
1578 if (!driver || !driver->textconv)
1579 return grep_source_load(gs);
1582 * The textconv interface is intimately tied to diff_filespecs, so we
1583 * have to pretend to be one. If we could unify the grep_source
1584 * and diff_filespec structs, this mess could just go away.
1586 df = alloc_filespec(gs->path);
1587 switch (gs->type) {
1588 case GREP_SOURCE_OID:
1589 fill_filespec(df, gs->identifier, 1, 0100644);
1590 break;
1591 case GREP_SOURCE_FILE:
1592 fill_filespec(df, &null_oid, 0, 0100644);
1593 break;
1594 default:
1595 die("BUG: attempt to textconv something without a path?");
1599 * fill_textconv is not remotely thread-safe; it may load objects
1600 * behind the scenes, and it modifies the global diff tempfile
1601 * structure.
1603 grep_read_lock();
1604 size = fill_textconv(driver, df, &buf);
1605 grep_read_unlock();
1606 free_filespec(df);
1609 * The normal fill_textconv usage by the diff machinery would just keep
1610 * the textconv'd buf separate from the diff_filespec. But much of the
1611 * grep code passes around a grep_source and assumes that its "buf"
1612 * pointer is the beginning of the thing we are searching. So let's
1613 * install our textconv'd version into the grep_source, taking care not
1614 * to leak any existing buffer.
1616 grep_source_clear_data(gs);
1617 gs->buf = buf;
1618 gs->size = size;
1620 return 0;
1623 static int is_empty_line(const char *bol, const char *eol)
1625 while (bol < eol && isspace(*bol))
1626 bol++;
1627 return bol == eol;
1630 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1632 char *bol;
1633 char *peek_bol = NULL;
1634 unsigned long left;
1635 unsigned lno = 1;
1636 unsigned last_hit = 0;
1637 int binary_match_only = 0;
1638 unsigned count = 0;
1639 int try_lookahead = 0;
1640 int show_function = 0;
1641 struct userdiff_driver *textconv = NULL;
1642 enum grep_context ctx = GREP_CONTEXT_HEAD;
1643 xdemitconf_t xecfg;
1645 if (!opt->output)
1646 opt->output = std_output;
1648 if (opt->pre_context || opt->post_context || opt->file_break ||
1649 opt->funcbody) {
1650 /* Show hunk marks, except for the first file. */
1651 if (opt->last_shown)
1652 opt->show_hunk_mark = 1;
1654 * If we're using threads then we can't easily identify
1655 * the first file. Always put hunk marks in that case
1656 * and skip the very first one later in work_done().
1658 if (opt->output != std_output)
1659 opt->show_hunk_mark = 1;
1661 opt->last_shown = 0;
1663 if (opt->allow_textconv) {
1664 grep_source_load_driver(gs);
1666 * We might set up the shared textconv cache data here, which
1667 * is not thread-safe.
1669 grep_attr_lock();
1670 textconv = userdiff_get_textconv(gs->driver);
1671 grep_attr_unlock();
1675 * We know the result of a textconv is text, so we only have to care
1676 * about binary handling if we are not using it.
1678 if (!textconv) {
1679 switch (opt->binary) {
1680 case GREP_BINARY_DEFAULT:
1681 if (grep_source_is_binary(gs))
1682 binary_match_only = 1;
1683 break;
1684 case GREP_BINARY_NOMATCH:
1685 if (grep_source_is_binary(gs))
1686 return 0; /* Assume unmatch */
1687 break;
1688 case GREP_BINARY_TEXT:
1689 break;
1690 default:
1691 die("BUG: unknown binary handling mode");
1695 memset(&xecfg, 0, sizeof(xecfg));
1696 opt->priv = &xecfg;
1698 try_lookahead = should_lookahead(opt);
1700 if (fill_textconv_grep(textconv, gs) < 0)
1701 return 0;
1703 bol = gs->buf;
1704 left = gs->size;
1705 while (left) {
1706 char *eol, ch;
1707 int hit;
1710 * look_ahead() skips quickly to the line that possibly
1711 * has the next hit; don't call it if we need to do
1712 * something more than just skipping the current line
1713 * in response to an unmatch for the current line. E.g.
1714 * inside a post-context window, we will show the current
1715 * line as a context around the previous hit when it
1716 * doesn't hit.
1718 if (try_lookahead
1719 && !(last_hit
1720 && (show_function ||
1721 lno <= last_hit + opt->post_context))
1722 && look_ahead(opt, &left, &lno, &bol))
1723 break;
1724 eol = end_of_line(bol, &left);
1725 ch = *eol;
1726 *eol = 0;
1728 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1729 ctx = GREP_CONTEXT_BODY;
1731 hit = match_line(opt, bol, eol, ctx, collect_hits);
1732 *eol = ch;
1734 if (collect_hits)
1735 goto next_line;
1737 /* "grep -v -e foo -e bla" should list lines
1738 * that do not have either, so inversion should
1739 * be done outside.
1741 if (opt->invert)
1742 hit = !hit;
1743 if (opt->unmatch_name_only) {
1744 if (hit)
1745 return 0;
1746 goto next_line;
1748 if (hit) {
1749 count++;
1750 if (opt->status_only)
1751 return 1;
1752 if (opt->name_only) {
1753 show_name(opt, gs->name);
1754 return 1;
1756 if (opt->count)
1757 goto next_line;
1758 if (binary_match_only) {
1759 opt->output(opt, "Binary file ", 12);
1760 output_color(opt, gs->name, strlen(gs->name),
1761 opt->color_filename);
1762 opt->output(opt, " matches\n", 9);
1763 return 1;
1765 /* Hit at this line. If we haven't shown the
1766 * pre-context lines, we would need to show them.
1768 if (opt->pre_context || opt->funcbody)
1769 show_pre_context(opt, gs, bol, eol, lno);
1770 else if (opt->funcname)
1771 show_funcname_line(opt, gs, bol, lno);
1772 show_line(opt, bol, eol, gs->name, lno, ':');
1773 last_hit = lno;
1774 if (opt->funcbody)
1775 show_function = 1;
1776 goto next_line;
1778 if (show_function && (!peek_bol || peek_bol < bol)) {
1779 unsigned long peek_left = left;
1780 char *peek_eol = eol;
1783 * Trailing empty lines are not interesting.
1784 * Peek past them to see if they belong to the
1785 * body of the current function.
1787 peek_bol = bol;
1788 while (is_empty_line(peek_bol, peek_eol)) {
1789 peek_bol = peek_eol + 1;
1790 peek_eol = end_of_line(peek_bol, &peek_left);
1793 if (match_funcname(opt, gs, peek_bol, peek_eol))
1794 show_function = 0;
1796 if (show_function ||
1797 (last_hit && lno <= last_hit + opt->post_context)) {
1798 /* If the last hit is within the post context,
1799 * we need to show this line.
1801 show_line(opt, bol, eol, gs->name, lno, '-');
1804 next_line:
1805 bol = eol + 1;
1806 if (!left)
1807 break;
1808 left--;
1809 lno++;
1812 if (collect_hits)
1813 return 0;
1815 if (opt->status_only)
1816 return 0;
1817 if (opt->unmatch_name_only) {
1818 /* We did not see any hit, so we want to show this */
1819 show_name(opt, gs->name);
1820 return 1;
1823 xdiff_clear_find_func(&xecfg);
1824 opt->priv = NULL;
1826 /* NEEDSWORK:
1827 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1828 * which feels mostly useless but sometimes useful. Maybe
1829 * make it another option? For now suppress them.
1831 if (opt->count && count) {
1832 char buf[32];
1833 if (opt->pathname) {
1834 output_color(opt, gs->name, strlen(gs->name),
1835 opt->color_filename);
1836 output_sep(opt, ':');
1838 xsnprintf(buf, sizeof(buf), "%u\n", count);
1839 opt->output(opt, buf, strlen(buf));
1840 return 1;
1842 return !!last_hit;
1845 static void clr_hit_marker(struct grep_expr *x)
1847 /* All-hit markers are meaningful only at the very top level
1848 * OR node.
1850 while (1) {
1851 x->hit = 0;
1852 if (x->node != GREP_NODE_OR)
1853 return;
1854 x->u.binary.left->hit = 0;
1855 x = x->u.binary.right;
1859 static int chk_hit_marker(struct grep_expr *x)
1861 /* Top level nodes have hit markers. See if they all are hits */
1862 while (1) {
1863 if (x->node != GREP_NODE_OR)
1864 return x->hit;
1865 if (!x->u.binary.left->hit)
1866 return 0;
1867 x = x->u.binary.right;
1871 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1874 * we do not have to do the two-pass grep when we do not check
1875 * buffer-wide "all-match".
1877 if (!opt->all_match)
1878 return grep_source_1(opt, gs, 0);
1880 /* Otherwise the toplevel "or" terms hit a bit differently.
1881 * We first clear hit markers from them.
1883 clr_hit_marker(opt->pattern_expression);
1884 grep_source_1(opt, gs, 1);
1886 if (!chk_hit_marker(opt->pattern_expression))
1887 return 0;
1889 return grep_source_1(opt, gs, 0);
1892 int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1894 struct grep_source gs;
1895 int r;
1897 grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
1898 gs.buf = buf;
1899 gs.size = size;
1901 r = grep_source(opt, &gs);
1903 grep_source_clear(&gs);
1904 return r;
1907 void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1908 const char *name, const char *path,
1909 const void *identifier)
1911 gs->type = type;
1912 gs->name = xstrdup_or_null(name);
1913 gs->path = xstrdup_or_null(path);
1914 gs->buf = NULL;
1915 gs->size = 0;
1916 gs->driver = NULL;
1918 switch (type) {
1919 case GREP_SOURCE_FILE:
1920 gs->identifier = xstrdup(identifier);
1921 break;
1922 case GREP_SOURCE_SUBMODULE:
1923 if (!identifier) {
1924 gs->identifier = NULL;
1925 break;
1928 * FALL THROUGH
1929 * If the identifier is non-NULL (in the submodule case) it
1930 * will be a SHA1 that needs to be copied.
1932 case GREP_SOURCE_OID:
1933 gs->identifier = oiddup(identifier);
1934 break;
1935 case GREP_SOURCE_BUF:
1936 gs->identifier = NULL;
1937 break;
1941 void grep_source_clear(struct grep_source *gs)
1943 FREE_AND_NULL(gs->name);
1944 FREE_AND_NULL(gs->path);
1945 FREE_AND_NULL(gs->identifier);
1946 grep_source_clear_data(gs);
1949 void grep_source_clear_data(struct grep_source *gs)
1951 switch (gs->type) {
1952 case GREP_SOURCE_FILE:
1953 case GREP_SOURCE_OID:
1954 case GREP_SOURCE_SUBMODULE:
1955 FREE_AND_NULL(gs->buf);
1956 gs->size = 0;
1957 break;
1958 case GREP_SOURCE_BUF:
1959 /* leave user-provided buf intact */
1960 break;
1964 static int grep_source_load_oid(struct grep_source *gs)
1966 enum object_type type;
1968 grep_read_lock();
1969 gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1970 grep_read_unlock();
1972 if (!gs->buf)
1973 return error(_("'%s': unable to read %s"),
1974 gs->name,
1975 oid_to_hex(gs->identifier));
1976 return 0;
1979 static int grep_source_load_file(struct grep_source *gs)
1981 const char *filename = gs->identifier;
1982 struct stat st;
1983 char *data;
1984 size_t size;
1985 int i;
1987 if (lstat(filename, &st) < 0) {
1988 err_ret:
1989 if (errno != ENOENT)
1990 error_errno(_("failed to stat '%s'"), filename);
1991 return -1;
1993 if (!S_ISREG(st.st_mode))
1994 return -1;
1995 size = xsize_t(st.st_size);
1996 i = open(filename, O_RDONLY);
1997 if (i < 0)
1998 goto err_ret;
1999 data = xmallocz(size);
2000 if (st.st_size != read_in_full(i, data, size)) {
2001 error_errno(_("'%s': short read"), filename);
2002 close(i);
2003 free(data);
2004 return -1;
2006 close(i);
2008 gs->buf = data;
2009 gs->size = size;
2010 return 0;
2013 static int grep_source_load(struct grep_source *gs)
2015 if (gs->buf)
2016 return 0;
2018 switch (gs->type) {
2019 case GREP_SOURCE_FILE:
2020 return grep_source_load_file(gs);
2021 case GREP_SOURCE_OID:
2022 return grep_source_load_oid(gs);
2023 case GREP_SOURCE_BUF:
2024 return gs->buf ? 0 : -1;
2025 case GREP_SOURCE_SUBMODULE:
2026 break;
2028 die("BUG: invalid grep_source type to load");
2031 void grep_source_load_driver(struct grep_source *gs)
2033 if (gs->driver)
2034 return;
2036 grep_attr_lock();
2037 if (gs->path)
2038 gs->driver = userdiff_find_by_path(gs->path);
2039 if (!gs->driver)
2040 gs->driver = userdiff_find_by_name("default");
2041 grep_attr_unlock();
2044 static int grep_source_is_binary(struct grep_source *gs)
2046 grep_source_load_driver(gs);
2047 if (gs->driver->binary != -1)
2048 return gs->driver->binary;
2050 if (!grep_source_load(gs))
2051 return buffer_is_binary(gs->buf, gs->size);
2053 return 0;