4 #include "object-store.h"
6 #include "xdiff-interface.h"
13 static int grep_source_load(struct grep_source
*gs
);
14 static int grep_source_is_binary(struct grep_source
*gs
);
16 static struct grep_opt grep_defaults
;
18 static const char *color_grep_slots
[] = {
19 [GREP_COLOR_CONTEXT
] = "context",
20 [GREP_COLOR_FILENAME
] = "filename",
21 [GREP_COLOR_FUNCTION
] = "function",
22 [GREP_COLOR_LINENO
] = "lineNumber",
23 [GREP_COLOR_COLUMNNO
] = "column",
24 [GREP_COLOR_MATCH_CONTEXT
] = "matchContext",
25 [GREP_COLOR_MATCH_SELECTED
] = "matchSelected",
26 [GREP_COLOR_SELECTED
] = "selected",
27 [GREP_COLOR_SEP
] = "separator",
30 static void std_output(struct grep_opt
*opt
, const void *buf
, size_t size
)
32 fwrite(buf
, size
, 1, stdout
);
35 static void color_set(char *dst
, const char *color_bytes
)
37 xsnprintf(dst
, COLOR_MAXLEN
, "%s", color_bytes
);
41 * Initialize the grep_defaults template with hardcoded defaults.
42 * We could let the compiler do this, but without C99 initializers
43 * the code gets unwieldy and unreadable, so...
45 void init_grep_defaults(void)
47 struct grep_opt
*opt
= &grep_defaults
;
54 memset(opt
, 0, sizeof(*opt
));
58 opt
->pattern_type_option
= GREP_PATTERN_TYPE_UNSPECIFIED
;
59 color_set(opt
->colors
[GREP_COLOR_CONTEXT
], "");
60 color_set(opt
->colors
[GREP_COLOR_FILENAME
], "");
61 color_set(opt
->colors
[GREP_COLOR_FUNCTION
], "");
62 color_set(opt
->colors
[GREP_COLOR_LINENO
], "");
63 color_set(opt
->colors
[GREP_COLOR_COLUMNNO
], "");
64 color_set(opt
->colors
[GREP_COLOR_MATCH_CONTEXT
], GIT_COLOR_BOLD_RED
);
65 color_set(opt
->colors
[GREP_COLOR_MATCH_SELECTED
], GIT_COLOR_BOLD_RED
);
66 color_set(opt
->colors
[GREP_COLOR_SELECTED
], "");
67 color_set(opt
->colors
[GREP_COLOR_SEP
], GIT_COLOR_CYAN
);
68 opt
->only_matching
= 0;
70 opt
->output
= std_output
;
73 static int parse_pattern_type_arg(const char *opt
, const char *arg
)
75 if (!strcmp(arg
, "default"))
76 return GREP_PATTERN_TYPE_UNSPECIFIED
;
77 else if (!strcmp(arg
, "basic"))
78 return GREP_PATTERN_TYPE_BRE
;
79 else if (!strcmp(arg
, "extended"))
80 return GREP_PATTERN_TYPE_ERE
;
81 else if (!strcmp(arg
, "fixed"))
82 return GREP_PATTERN_TYPE_FIXED
;
83 else if (!strcmp(arg
, "perl"))
84 return GREP_PATTERN_TYPE_PCRE
;
85 die("bad %s argument: %s", opt
, arg
);
88 define_list_config_array_extra(color_grep_slots
, {"match"});
91 * Read the configuration file once and store it in
92 * the grep_defaults template.
94 int grep_config(const char *var
, const char *value
, void *cb
)
96 struct grep_opt
*opt
= &grep_defaults
;
99 if (userdiff_config(var
, value
) < 0)
102 if (!strcmp(var
, "grep.extendedregexp")) {
103 opt
->extended_regexp_option
= git_config_bool(var
, value
);
107 if (!strcmp(var
, "grep.patterntype")) {
108 opt
->pattern_type_option
= parse_pattern_type_arg(var
, value
);
112 if (!strcmp(var
, "grep.linenumber")) {
113 opt
->linenum
= git_config_bool(var
, value
);
116 if (!strcmp(var
, "grep.column")) {
117 opt
->columnnum
= git_config_bool(var
, value
);
121 if (!strcmp(var
, "grep.fullname")) {
122 opt
->relative
= !git_config_bool(var
, value
);
126 if (!strcmp(var
, "color.grep"))
127 opt
->color
= git_config_colorbool(var
, value
);
128 if (!strcmp(var
, "color.grep.match")) {
129 if (grep_config("color.grep.matchcontext", value
, cb
) < 0)
131 if (grep_config("color.grep.matchselected", value
, cb
) < 0)
133 } else if (skip_prefix(var
, "color.grep.", &slot
)) {
134 int i
= LOOKUP_CONFIG(color_grep_slots
, slot
);
139 color
= opt
->colors
[i
];
141 return config_error_nonbool(var
);
142 return color_parse(value
, color
);
148 * Initialize one instance of grep_opt and copy the
149 * default values from the template we read the configuration
150 * information in an earlier call to git_config(grep_config).
152 void grep_init(struct grep_opt
*opt
, const char *prefix
)
154 struct grep_opt
*def
= &grep_defaults
;
157 memset(opt
, 0, sizeof(*opt
));
158 opt
->prefix
= prefix
;
159 opt
->prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
160 opt
->pattern_tail
= &opt
->pattern_list
;
161 opt
->header_tail
= &opt
->header_list
;
163 opt
->only_matching
= def
->only_matching
;
164 opt
->color
= def
->color
;
165 opt
->extended_regexp_option
= def
->extended_regexp_option
;
166 opt
->pattern_type_option
= def
->pattern_type_option
;
167 opt
->linenum
= def
->linenum
;
168 opt
->columnnum
= def
->columnnum
;
169 opt
->max_depth
= def
->max_depth
;
170 opt
->pathname
= def
->pathname
;
171 opt
->relative
= def
->relative
;
172 opt
->output
= def
->output
;
174 for (i
= 0; i
< NR_GREP_COLORS
; i
++)
175 color_set(opt
->colors
[i
], def
->colors
[i
]);
178 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type
, struct grep_opt
*opt
)
181 * When committing to the pattern type by setting the relevant
182 * fields in grep_opt it's generally not necessary to zero out
183 * the fields we're not choosing, since they won't have been
184 * set by anything. The extended_regexp_option field is the
185 * only exception to this.
187 * This is because in the process of parsing grep.patternType
188 * & grep.extendedRegexp we set opt->pattern_type_option and
189 * opt->extended_regexp_option, respectively. We then
190 * internally use opt->extended_regexp_option to see if we're
191 * compiling an ERE. It must be unset if that's not actually
194 if (pattern_type
!= GREP_PATTERN_TYPE_ERE
&&
195 opt
->extended_regexp_option
)
196 opt
->extended_regexp_option
= 0;
198 switch (pattern_type
) {
199 case GREP_PATTERN_TYPE_UNSPECIFIED
:
202 case GREP_PATTERN_TYPE_BRE
:
205 case GREP_PATTERN_TYPE_ERE
:
206 opt
->extended_regexp_option
= 1;
209 case GREP_PATTERN_TYPE_FIXED
:
213 case GREP_PATTERN_TYPE_PCRE
:
218 * It's important that pcre1 always be assigned to
219 * even when there's no USE_LIBPCRE* defined. We still
220 * call the PCRE stub function, it just dies with
221 * "cannot use Perl-compatible regexes[...]".
229 void grep_commit_pattern_type(enum grep_pattern_type pattern_type
, struct grep_opt
*opt
)
231 if (pattern_type
!= GREP_PATTERN_TYPE_UNSPECIFIED
)
232 grep_set_pattern_type_option(pattern_type
, opt
);
233 else if (opt
->pattern_type_option
!= GREP_PATTERN_TYPE_UNSPECIFIED
)
234 grep_set_pattern_type_option(opt
->pattern_type_option
, opt
);
235 else if (opt
->extended_regexp_option
)
237 * This branch *must* happen after setting from the
238 * opt->pattern_type_option above, we don't want
239 * grep.extendedRegexp to override grep.patternType!
241 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE
, opt
);
244 static struct grep_pat
*create_grep_pat(const char *pat
, size_t patlen
,
245 const char *origin
, int no
,
246 enum grep_pat_token t
,
247 enum grep_header_field field
)
249 struct grep_pat
*p
= xcalloc(1, sizeof(*p
));
250 p
->pattern
= xmemdupz(pat
, patlen
);
251 p
->patternlen
= patlen
;
259 static void do_append_grep_pat(struct grep_pat
***tail
, struct grep_pat
*p
)
266 case GREP_PATTERN
: /* atom */
267 case GREP_PATTERN_HEAD
:
268 case GREP_PATTERN_BODY
:
270 struct grep_pat
*new_pat
;
272 char *cp
= p
->pattern
+ p
->patternlen
, *nl
= NULL
;
273 while (++len
<= p
->patternlen
) {
274 if (*(--cp
) == '\n') {
281 new_pat
= create_grep_pat(nl
+ 1, len
- 1, p
->origin
,
282 p
->no
, p
->token
, p
->field
);
283 new_pat
->next
= p
->next
;
285 *tail
= &new_pat
->next
;
288 p
->patternlen
-= len
;
296 void append_header_grep_pattern(struct grep_opt
*opt
,
297 enum grep_header_field field
, const char *pat
)
299 struct grep_pat
*p
= create_grep_pat(pat
, strlen(pat
), "header", 0,
300 GREP_PATTERN_HEAD
, field
);
301 if (field
== GREP_HEADER_REFLOG
)
302 opt
->use_reflog_filter
= 1;
303 do_append_grep_pat(&opt
->header_tail
, p
);
306 void append_grep_pattern(struct grep_opt
*opt
, const char *pat
,
307 const char *origin
, int no
, enum grep_pat_token t
)
309 append_grep_pat(opt
, pat
, strlen(pat
), origin
, no
, t
);
312 void append_grep_pat(struct grep_opt
*opt
, const char *pat
, size_t patlen
,
313 const char *origin
, int no
, enum grep_pat_token t
)
315 struct grep_pat
*p
= create_grep_pat(pat
, patlen
, origin
, no
, t
, 0);
316 do_append_grep_pat(&opt
->pattern_tail
, p
);
319 struct grep_opt
*grep_opt_dup(const struct grep_opt
*opt
)
321 struct grep_pat
*pat
;
322 struct grep_opt
*ret
= xmalloc(sizeof(struct grep_opt
));
325 ret
->pattern_list
= NULL
;
326 ret
->pattern_tail
= &ret
->pattern_list
;
328 for(pat
= opt
->pattern_list
; pat
!= NULL
; pat
= pat
->next
)
330 if(pat
->token
== GREP_PATTERN_HEAD
)
331 append_header_grep_pattern(ret
, pat
->field
,
334 append_grep_pat(ret
, pat
->pattern
, pat
->patternlen
,
335 pat
->origin
, pat
->no
, pat
->token
);
341 static NORETURN
void compile_regexp_failed(const struct grep_pat
*p
,
347 xsnprintf(where
, sizeof(where
), "In '%s' at %d, ", p
->origin
, p
->no
);
349 xsnprintf(where
, sizeof(where
), "%s, ", p
->origin
);
353 die("%s'%s': %s", where
, p
->pattern
, error
);
356 static int is_fixed(const char *s
, size_t len
)
360 for (i
= 0; i
< len
; i
++) {
361 if (is_regex_special(s
[i
]))
368 static int has_null(const char *s
, size_t len
)
371 * regcomp cannot accept patterns with NULs so when using it
372 * we consider any pattern containing a NUL fixed.
374 if (memchr(s
, 0, len
))
381 static void compile_pcre1_regexp(struct grep_pat
*p
, const struct grep_opt
*opt
)
385 int options
= PCRE_MULTILINE
;
387 if (opt
->ignore_case
) {
388 if (has_non_ascii(p
->pattern
))
389 p
->pcre1_tables
= pcre_maketables();
390 options
|= PCRE_CASELESS
;
392 if (is_utf8_locale() && has_non_ascii(p
->pattern
))
393 options
|= PCRE_UTF8
;
395 p
->pcre1_regexp
= pcre_compile(p
->pattern
, options
, &error
, &erroffset
,
397 if (!p
->pcre1_regexp
)
398 compile_regexp_failed(p
, error
);
400 p
->pcre1_extra_info
= pcre_study(p
->pcre1_regexp
, GIT_PCRE_STUDY_JIT_COMPILE
, &error
);
401 if (!p
->pcre1_extra_info
&& error
)
404 #ifdef GIT_PCRE1_USE_JIT
405 pcre_config(PCRE_CONFIG_JIT
, &p
->pcre1_jit_on
);
406 if (p
->pcre1_jit_on
== 1) {
407 p
->pcre1_jit_stack
= pcre_jit_stack_alloc(1, 1024 * 1024);
408 if (!p
->pcre1_jit_stack
)
409 die("Couldn't allocate PCRE JIT stack");
410 pcre_assign_jit_stack(p
->pcre1_extra_info
, NULL
, p
->pcre1_jit_stack
);
411 } else if (p
->pcre1_jit_on
!= 0) {
412 BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
418 static int pcre1match(struct grep_pat
*p
, const char *line
, const char *eol
,
419 regmatch_t
*match
, int eflags
)
421 int ovector
[30], ret
, flags
= 0;
423 if (eflags
& REG_NOTBOL
)
424 flags
|= PCRE_NOTBOL
;
426 #ifdef GIT_PCRE1_USE_JIT
427 if (p
->pcre1_jit_on
) {
428 ret
= pcre_jit_exec(p
->pcre1_regexp
, p
->pcre1_extra_info
, line
,
429 eol
- line
, 0, flags
, ovector
,
430 ARRAY_SIZE(ovector
), p
->pcre1_jit_stack
);
434 ret
= pcre_exec(p
->pcre1_regexp
, p
->pcre1_extra_info
, line
,
435 eol
- line
, 0, flags
, ovector
,
436 ARRAY_SIZE(ovector
));
439 if (ret
< 0 && ret
!= PCRE_ERROR_NOMATCH
)
440 die("pcre_exec failed with error code %d", ret
);
443 match
->rm_so
= ovector
[0];
444 match
->rm_eo
= ovector
[1];
450 static void free_pcre1_regexp(struct grep_pat
*p
)
452 pcre_free(p
->pcre1_regexp
);
453 #ifdef GIT_PCRE1_USE_JIT
454 if (p
->pcre1_jit_on
) {
455 pcre_free_study(p
->pcre1_extra_info
);
456 pcre_jit_stack_free(p
->pcre1_jit_stack
);
460 pcre_free(p
->pcre1_extra_info
);
462 pcre_free((void *)p
->pcre1_tables
);
464 #else /* !USE_LIBPCRE1 */
465 static void compile_pcre1_regexp(struct grep_pat
*p
, const struct grep_opt
*opt
)
467 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
470 static int pcre1match(struct grep_pat
*p
, const char *line
, const char *eol
,
471 regmatch_t
*match
, int eflags
)
476 static void free_pcre1_regexp(struct grep_pat
*p
)
479 #endif /* !USE_LIBPCRE1 */
482 static void compile_pcre2_pattern(struct grep_pat
*p
, const struct grep_opt
*opt
)
485 PCRE2_UCHAR errbuf
[256];
486 PCRE2_SIZE erroffset
;
487 int options
= PCRE2_MULTILINE
;
488 const uint8_t *character_tables
= NULL
;
495 p
->pcre2_compile_context
= NULL
;
497 if (opt
->ignore_case
) {
498 if (has_non_ascii(p
->pattern
)) {
499 character_tables
= pcre2_maketables(NULL
);
500 p
->pcre2_compile_context
= pcre2_compile_context_create(NULL
);
501 pcre2_set_character_tables(p
->pcre2_compile_context
, character_tables
);
503 options
|= PCRE2_CASELESS
;
505 if (is_utf8_locale() && has_non_ascii(p
->pattern
))
506 options
|= PCRE2_UTF
;
508 p
->pcre2_pattern
= pcre2_compile((PCRE2_SPTR
)p
->pattern
,
509 p
->patternlen
, options
, &error
, &erroffset
,
510 p
->pcre2_compile_context
);
512 if (p
->pcre2_pattern
) {
513 p
->pcre2_match_data
= pcre2_match_data_create_from_pattern(p
->pcre2_pattern
, NULL
);
514 if (!p
->pcre2_match_data
)
515 die("Couldn't allocate PCRE2 match data");
517 pcre2_get_error_message(error
, errbuf
, sizeof(errbuf
));
518 compile_regexp_failed(p
, (const char *)&errbuf
);
521 pcre2_config(PCRE2_CONFIG_JIT
, &p
->pcre2_jit_on
);
522 if (p
->pcre2_jit_on
== 1) {
523 jitret
= pcre2_jit_compile(p
->pcre2_pattern
, PCRE2_JIT_COMPLETE
);
525 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p
->pattern
, jitret
);
528 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
529 * tells us whether the library itself supports JIT,
530 * but to see whether we're going to be actually using
531 * JIT we need to extract PCRE2_INFO_JITSIZE from the
532 * pattern *after* we do pcre2_jit_compile() above.
534 * This is because if the pattern contains the
535 * (*NO_JIT) verb (see pcre2syntax(3))
536 * pcre2_jit_compile() will exit early with 0. If we
537 * then proceed to call pcre2_jit_match() further down
538 * the line instead of pcre2_match() we'll either
539 * segfault (pre PCRE 10.31) or run into a fatal error
542 patinforet
= pcre2_pattern_info(p
->pcre2_pattern
, PCRE2_INFO_JITSIZE
, &jitsizearg
);
544 BUG("pcre2_pattern_info() failed: %d", patinforet
);
545 if (jitsizearg
== 0) {
550 p
->pcre2_jit_stack
= pcre2_jit_stack_create(1, 1024 * 1024, NULL
);
551 if (!p
->pcre2_jit_stack
)
552 die("Couldn't allocate PCRE2 JIT stack");
553 p
->pcre2_match_context
= pcre2_match_context_create(NULL
);
554 if (!p
->pcre2_match_context
)
555 die("Couldn't allocate PCRE2 match context");
556 pcre2_jit_stack_assign(p
->pcre2_match_context
, NULL
, p
->pcre2_jit_stack
);
557 } else if (p
->pcre2_jit_on
!= 0) {
558 BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
563 static int pcre2match(struct grep_pat
*p
, const char *line
, const char *eol
,
564 regmatch_t
*match
, int eflags
)
568 PCRE2_UCHAR errbuf
[256];
570 if (eflags
& REG_NOTBOL
)
571 flags
|= PCRE2_NOTBOL
;
574 ret
= pcre2_jit_match(p
->pcre2_pattern
, (unsigned char *)line
,
575 eol
- line
, 0, flags
, p
->pcre2_match_data
,
578 ret
= pcre2_match(p
->pcre2_pattern
, (unsigned char *)line
,
579 eol
- line
, 0, flags
, p
->pcre2_match_data
,
582 if (ret
< 0 && ret
!= PCRE2_ERROR_NOMATCH
) {
583 pcre2_get_error_message(ret
, errbuf
, sizeof(errbuf
));
584 die("%s failed with error code %d: %s",
585 (p
->pcre2_jit_on
? "pcre2_jit_match" : "pcre2_match"), ret
,
589 ovector
= pcre2_get_ovector_pointer(p
->pcre2_match_data
);
591 match
->rm_so
= (int)ovector
[0];
592 match
->rm_eo
= (int)ovector
[1];
598 static void free_pcre2_pattern(struct grep_pat
*p
)
600 pcre2_compile_context_free(p
->pcre2_compile_context
);
601 pcre2_code_free(p
->pcre2_pattern
);
602 pcre2_match_data_free(p
->pcre2_match_data
);
603 pcre2_jit_stack_free(p
->pcre2_jit_stack
);
604 pcre2_match_context_free(p
->pcre2_match_context
);
606 #else /* !USE_LIBPCRE2 */
607 static void compile_pcre2_pattern(struct grep_pat
*p
, const struct grep_opt
*opt
)
610 * Unreachable until USE_LIBPCRE2 becomes synonymous with
611 * USE_LIBPCRE. See the sibling comment in
612 * grep_set_pattern_type_option().
614 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
617 static int pcre2match(struct grep_pat
*p
, const char *line
, const char *eol
,
618 regmatch_t
*match
, int eflags
)
623 static void free_pcre2_pattern(struct grep_pat
*p
)
626 #endif /* !USE_LIBPCRE2 */
628 static void compile_fixed_regexp(struct grep_pat
*p
, struct grep_opt
*opt
)
630 struct strbuf sb
= STRBUF_INIT
;
634 basic_regex_quote_buf(&sb
, p
->pattern
);
635 if (opt
->ignore_case
)
636 regflags
|= REG_ICASE
;
637 err
= regcomp(&p
->regexp
, sb
.buf
, regflags
);
639 fprintf(stderr
, "fixed %s\n", sb
.buf
);
643 regerror(err
, &p
->regexp
, errbuf
, sizeof(errbuf
));
644 compile_regexp_failed(p
, errbuf
);
648 static void compile_regexp(struct grep_pat
*p
, struct grep_opt
*opt
)
652 int regflags
= REG_NEWLINE
;
654 p
->word_regexp
= opt
->word_regexp
;
655 p
->ignore_case
= opt
->ignore_case
;
656 ascii_only
= !has_non_ascii(p
->pattern
);
659 * Even when -F (fixed) asks us to do a non-regexp search, we
660 * may not be able to correctly case-fold when -i
661 * (ignore-case) is asked (in which case, we'll synthesize a
662 * regexp to match the pattern that matches regexp special
663 * characters literally, while ignoring case differences). On
664 * the other hand, even without -F, if the pattern does not
665 * have any regexp special characters and there is no need for
666 * case-folding search, we can internally turn it into a
667 * simple string match using kws. p->fixed tells us if we
671 has_null(p
->pattern
, p
->patternlen
) ||
672 is_fixed(p
->pattern
, p
->patternlen
))
673 p
->fixed
= !p
->ignore_case
|| ascii_only
;
676 p
->kws
= kwsalloc(p
->ignore_case
? tolower_trans_tbl
: NULL
);
677 kwsincr(p
->kws
, p
->pattern
, p
->patternlen
);
680 } else if (opt
->fixed
) {
682 * We come here when the pattern has the non-ascii
683 * characters we cannot case-fold, and asked to
686 compile_fixed_regexp(p
, opt
);
691 compile_pcre2_pattern(p
, opt
);
696 compile_pcre1_regexp(p
, opt
);
701 regflags
|= REG_ICASE
;
702 if (opt
->extended_regexp_option
)
703 regflags
|= REG_EXTENDED
;
704 err
= regcomp(&p
->regexp
, p
->pattern
, regflags
);
707 regerror(err
, &p
->regexp
, errbuf
, 1024);
708 compile_regexp_failed(p
, errbuf
);
712 static struct grep_expr
*compile_pattern_or(struct grep_pat
**);
713 static struct grep_expr
*compile_pattern_atom(struct grep_pat
**list
)
722 case GREP_PATTERN
: /* atom */
723 case GREP_PATTERN_HEAD
:
724 case GREP_PATTERN_BODY
:
725 x
= xcalloc(1, sizeof (struct grep_expr
));
726 x
->node
= GREP_NODE_ATOM
;
730 case GREP_OPEN_PAREN
:
732 x
= compile_pattern_or(list
);
733 if (!*list
|| (*list
)->token
!= GREP_CLOSE_PAREN
)
734 die("unmatched parenthesis");
735 *list
= (*list
)->next
;
742 static struct grep_expr
*compile_pattern_not(struct grep_pat
**list
)
753 die("--not not followed by pattern expression");
755 x
= xcalloc(1, sizeof (struct grep_expr
));
756 x
->node
= GREP_NODE_NOT
;
757 x
->u
.unary
= compile_pattern_not(list
);
759 die("--not followed by non pattern expression");
762 return compile_pattern_atom(list
);
766 static struct grep_expr
*compile_pattern_and(struct grep_pat
**list
)
769 struct grep_expr
*x
, *y
, *z
;
771 x
= compile_pattern_not(list
);
773 if (p
&& p
->token
== GREP_AND
) {
775 die("--and not followed by pattern expression");
777 y
= compile_pattern_and(list
);
779 die("--and not followed by pattern expression");
780 z
= xcalloc(1, sizeof (struct grep_expr
));
781 z
->node
= GREP_NODE_AND
;
782 z
->u
.binary
.left
= x
;
783 z
->u
.binary
.right
= y
;
789 static struct grep_expr
*compile_pattern_or(struct grep_pat
**list
)
792 struct grep_expr
*x
, *y
, *z
;
794 x
= compile_pattern_and(list
);
796 if (x
&& p
&& p
->token
!= GREP_CLOSE_PAREN
) {
797 y
= compile_pattern_or(list
);
799 die("not a pattern expression %s", p
->pattern
);
800 z
= xcalloc(1, sizeof (struct grep_expr
));
801 z
->node
= GREP_NODE_OR
;
802 z
->u
.binary
.left
= x
;
803 z
->u
.binary
.right
= y
;
809 static struct grep_expr
*compile_pattern_expr(struct grep_pat
**list
)
811 return compile_pattern_or(list
);
814 static void indent(int in
)
820 static void dump_grep_pat(struct grep_pat
*p
)
823 case GREP_AND
: fprintf(stderr
, "*and*"); break;
824 case GREP_OPEN_PAREN
: fprintf(stderr
, "*(*"); break;
825 case GREP_CLOSE_PAREN
: fprintf(stderr
, "*)*"); break;
826 case GREP_NOT
: fprintf(stderr
, "*not*"); break;
827 case GREP_OR
: fprintf(stderr
, "*or*"); break;
829 case GREP_PATTERN
: fprintf(stderr
, "pattern"); break;
830 case GREP_PATTERN_HEAD
: fprintf(stderr
, "pattern_head"); break;
831 case GREP_PATTERN_BODY
: fprintf(stderr
, "pattern_body"); break;
836 case GREP_PATTERN_HEAD
:
837 fprintf(stderr
, "<head %d>", p
->field
); break;
838 case GREP_PATTERN_BODY
:
839 fprintf(stderr
, "<body>"); break;
843 case GREP_PATTERN_HEAD
:
844 case GREP_PATTERN_BODY
:
846 fprintf(stderr
, "%.*s", (int)p
->patternlen
, p
->pattern
);
852 static void dump_grep_expression_1(struct grep_expr
*x
, int in
)
857 fprintf(stderr
, "true\n");
860 dump_grep_pat(x
->u
.atom
);
863 fprintf(stderr
, "(not\n");
864 dump_grep_expression_1(x
->u
.unary
, in
+1);
866 fprintf(stderr
, ")\n");
869 fprintf(stderr
, "(and\n");
870 dump_grep_expression_1(x
->u
.binary
.left
, in
+1);
871 dump_grep_expression_1(x
->u
.binary
.right
, in
+1);
873 fprintf(stderr
, ")\n");
876 fprintf(stderr
, "(or\n");
877 dump_grep_expression_1(x
->u
.binary
.left
, in
+1);
878 dump_grep_expression_1(x
->u
.binary
.right
, in
+1);
880 fprintf(stderr
, ")\n");
885 static void dump_grep_expression(struct grep_opt
*opt
)
887 struct grep_expr
*x
= opt
->pattern_expression
;
890 fprintf(stderr
, "[all-match]\n");
891 dump_grep_expression_1(x
, 0);
895 static struct grep_expr
*grep_true_expr(void)
897 struct grep_expr
*z
= xcalloc(1, sizeof(*z
));
898 z
->node
= GREP_NODE_TRUE
;
902 static struct grep_expr
*grep_or_expr(struct grep_expr
*left
, struct grep_expr
*right
)
904 struct grep_expr
*z
= xcalloc(1, sizeof(*z
));
905 z
->node
= GREP_NODE_OR
;
906 z
->u
.binary
.left
= left
;
907 z
->u
.binary
.right
= right
;
911 static struct grep_expr
*prep_header_patterns(struct grep_opt
*opt
)
914 struct grep_expr
*header_expr
;
915 struct grep_expr
*(header_group
[GREP_HEADER_FIELD_MAX
]);
916 enum grep_header_field fld
;
918 if (!opt
->header_list
)
921 for (p
= opt
->header_list
; p
; p
= p
->next
) {
922 if (p
->token
!= GREP_PATTERN_HEAD
)
923 BUG("a non-header pattern in grep header list.");
924 if (p
->field
< GREP_HEADER_FIELD_MIN
||
925 GREP_HEADER_FIELD_MAX
<= p
->field
)
926 BUG("unknown header field %d", p
->field
);
927 compile_regexp(p
, opt
);
930 for (fld
= 0; fld
< GREP_HEADER_FIELD_MAX
; fld
++)
931 header_group
[fld
] = NULL
;
933 for (p
= opt
->header_list
; p
; p
= p
->next
) {
935 struct grep_pat
*pp
= p
;
937 h
= compile_pattern_atom(&pp
);
938 if (!h
|| pp
!= p
->next
)
939 BUG("malformed header expr");
940 if (!header_group
[p
->field
]) {
941 header_group
[p
->field
] = h
;
944 header_group
[p
->field
] = grep_or_expr(h
, header_group
[p
->field
]);
949 for (fld
= 0; fld
< GREP_HEADER_FIELD_MAX
; fld
++) {
950 if (!header_group
[fld
])
953 header_expr
= grep_true_expr();
954 header_expr
= grep_or_expr(header_group
[fld
], header_expr
);
959 static struct grep_expr
*grep_splice_or(struct grep_expr
*x
, struct grep_expr
*y
)
961 struct grep_expr
*z
= x
;
964 assert(x
->node
== GREP_NODE_OR
);
965 if (x
->u
.binary
.right
&&
966 x
->u
.binary
.right
->node
== GREP_NODE_TRUE
) {
967 x
->u
.binary
.right
= y
;
970 x
= x
->u
.binary
.right
;
975 static void compile_grep_patterns_real(struct grep_opt
*opt
)
978 struct grep_expr
*header_expr
= prep_header_patterns(opt
);
980 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
982 case GREP_PATTERN
: /* atom */
983 case GREP_PATTERN_HEAD
:
984 case GREP_PATTERN_BODY
:
985 compile_regexp(p
, opt
);
993 if (opt
->all_match
|| header_expr
)
995 else if (!opt
->extended
&& !opt
->debug
)
998 p
= opt
->pattern_list
;
1000 opt
->pattern_expression
= compile_pattern_expr(&p
);
1002 die("incomplete pattern expression: %s", p
->pattern
);
1007 if (!opt
->pattern_expression
)
1008 opt
->pattern_expression
= header_expr
;
1009 else if (opt
->all_match
)
1010 opt
->pattern_expression
= grep_splice_or(header_expr
,
1011 opt
->pattern_expression
);
1013 opt
->pattern_expression
= grep_or_expr(opt
->pattern_expression
,
1018 void compile_grep_patterns(struct grep_opt
*opt
)
1020 compile_grep_patterns_real(opt
);
1022 dump_grep_expression(opt
);
1025 static void free_pattern_expr(struct grep_expr
*x
)
1028 case GREP_NODE_TRUE
:
1029 case GREP_NODE_ATOM
:
1032 free_pattern_expr(x
->u
.unary
);
1036 free_pattern_expr(x
->u
.binary
.left
);
1037 free_pattern_expr(x
->u
.binary
.right
);
1043 void free_grep_patterns(struct grep_opt
*opt
)
1045 struct grep_pat
*p
, *n
;
1047 for (p
= opt
->pattern_list
; p
; p
= n
) {
1050 case GREP_PATTERN
: /* atom */
1051 case GREP_PATTERN_HEAD
:
1052 case GREP_PATTERN_BODY
:
1055 else if (p
->pcre1_regexp
)
1056 free_pcre1_regexp(p
);
1057 else if (p
->pcre2_pattern
)
1058 free_pcre2_pattern(p
);
1060 regfree(&p
->regexp
);
1071 free_pattern_expr(opt
->pattern_expression
);
1074 static char *end_of_line(char *cp
, unsigned long *left
)
1076 unsigned long l
= *left
;
1077 while (l
&& *cp
!= '\n') {
1085 static int word_char(char ch
)
1087 return isalnum(ch
) || ch
== '_';
1090 static void output_color(struct grep_opt
*opt
, const void *data
, size_t size
,
1093 if (want_color(opt
->color
) && color
&& color
[0]) {
1094 opt
->output(opt
, color
, strlen(color
));
1095 opt
->output(opt
, data
, size
);
1096 opt
->output(opt
, GIT_COLOR_RESET
, strlen(GIT_COLOR_RESET
));
1098 opt
->output(opt
, data
, size
);
1101 static void output_sep(struct grep_opt
*opt
, char sign
)
1103 if (opt
->null_following_name
)
1104 opt
->output(opt
, "\0", 1);
1106 output_color(opt
, &sign
, 1, opt
->colors
[GREP_COLOR_SEP
]);
1109 static void show_name(struct grep_opt
*opt
, const char *name
)
1111 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1112 opt
->output(opt
, opt
->null_following_name
? "\0" : "\n", 1);
1115 static int fixmatch(struct grep_pat
*p
, char *line
, char *eol
,
1118 struct kwsmatch kwsm
;
1119 size_t offset
= kwsexec(p
->kws
, line
, eol
- line
, &kwsm
);
1121 match
->rm_so
= match
->rm_eo
= -1;
1124 match
->rm_so
= offset
;
1125 match
->rm_eo
= match
->rm_so
+ kwsm
.size
[0];
1130 static int patmatch(struct grep_pat
*p
, char *line
, char *eol
,
1131 regmatch_t
*match
, int eflags
)
1136 hit
= !fixmatch(p
, line
, eol
, match
);
1137 else if (p
->pcre1_regexp
)
1138 hit
= !pcre1match(p
, line
, eol
, match
, eflags
);
1139 else if (p
->pcre2_pattern
)
1140 hit
= !pcre2match(p
, line
, eol
, match
, eflags
);
1142 hit
= !regexec_buf(&p
->regexp
, line
, eol
- line
, 1, match
,
1148 static int strip_timestamp(char *bol
, char **eol_p
)
1153 while (bol
< --eol
) {
1167 } header_field
[] = {
1169 { "committer ", 10 },
1173 static int match_one_pattern(struct grep_pat
*p
, char *bol
, char *eol
,
1174 enum grep_context ctx
,
1175 regmatch_t
*pmatch
, int eflags
)
1179 const char *start
= bol
;
1181 if ((p
->token
!= GREP_PATTERN
) &&
1182 ((p
->token
== GREP_PATTERN_HEAD
) != (ctx
== GREP_CONTEXT_HEAD
)))
1185 if (p
->token
== GREP_PATTERN_HEAD
) {
1188 assert(p
->field
< ARRAY_SIZE(header_field
));
1189 field
= header_field
[p
->field
].field
;
1190 len
= header_field
[p
->field
].len
;
1191 if (strncmp(bol
, field
, len
))
1195 case GREP_HEADER_AUTHOR
:
1196 case GREP_HEADER_COMMITTER
:
1197 saved_ch
= strip_timestamp(bol
, &eol
);
1205 hit
= patmatch(p
, bol
, eol
, pmatch
, eflags
);
1207 if (hit
&& p
->word_regexp
) {
1208 if ((pmatch
[0].rm_so
< 0) ||
1209 (eol
- bol
) < pmatch
[0].rm_so
||
1210 (pmatch
[0].rm_eo
< 0) ||
1211 (eol
- bol
) < pmatch
[0].rm_eo
)
1212 die("regexp returned nonsense");
1214 /* Match beginning must be either beginning of the
1215 * line, or at word boundary (i.e. the last char must
1216 * not be a word char). Similarly, match end must be
1217 * either end of the line, or at word boundary
1218 * (i.e. the next char must not be a word char).
1220 if ( ((pmatch
[0].rm_so
== 0) ||
1221 !word_char(bol
[pmatch
[0].rm_so
-1])) &&
1222 ((pmatch
[0].rm_eo
== (eol
-bol
)) ||
1223 !word_char(bol
[pmatch
[0].rm_eo
])) )
1228 /* Words consist of at least one character. */
1229 if (pmatch
->rm_so
== pmatch
->rm_eo
)
1232 if (!hit
&& pmatch
[0].rm_so
+ bol
+ 1 < eol
) {
1233 /* There could be more than one match on the
1234 * line, and the first match might not be
1235 * strict word match. But later ones could be!
1236 * Forward to the next possible start, i.e. the
1237 * next position following a non-word char.
1239 bol
= pmatch
[0].rm_so
+ bol
+ 1;
1240 while (word_char(bol
[-1]) && bol
< eol
)
1242 eflags
|= REG_NOTBOL
;
1247 if (p
->token
== GREP_PATTERN_HEAD
&& saved_ch
)
1250 pmatch
[0].rm_so
+= bol
- start
;
1251 pmatch
[0].rm_eo
+= bol
- start
;
1256 static int match_expr_eval(struct grep_opt
*opt
, struct grep_expr
*x
, char *bol
,
1257 char *eol
, enum grep_context ctx
, ssize_t
*col
,
1258 ssize_t
*icol
, int collect_hits
)
1263 die("Not a valid grep expression");
1265 case GREP_NODE_TRUE
:
1268 case GREP_NODE_ATOM
:
1271 h
= match_one_pattern(x
->u
.atom
, bol
, eol
, ctx
,
1273 if (h
&& (*col
< 0 || tmp
.rm_so
< *col
))
1279 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1281 h
= !match_expr_eval(opt
, x
->u
.unary
, bol
, eol
, ctx
, icol
, col
,
1285 h
= match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
, ctx
, col
,
1287 if (h
|| opt
->columnnum
) {
1289 * Don't short-circuit AND when given --column, since a
1290 * NOT earlier in the tree may turn this into an OR. In
1291 * this case, see the below comment.
1293 h
&= match_expr_eval(opt
, x
->u
.binary
.right
, bol
, eol
,
1298 if (!(collect_hits
|| opt
->columnnum
)) {
1300 * Don't short-circuit OR when given --column (or
1301 * collecting hits) to ensure we don't skip a later
1302 * child that would produce an earlier match.
1304 return (match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
,
1305 ctx
, col
, icol
, 0) ||
1306 match_expr_eval(opt
, x
->u
.binary
.right
, bol
,
1307 eol
, ctx
, col
, icol
, 0));
1309 h
= match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
, ctx
, col
,
1312 x
->u
.binary
.left
->hit
|= h
;
1313 h
|= match_expr_eval(opt
, x
->u
.binary
.right
, bol
, eol
, ctx
, col
,
1314 icol
, collect_hits
);
1317 die("Unexpected node type (internal error) %d", x
->node
);
1324 static int match_expr(struct grep_opt
*opt
, char *bol
, char *eol
,
1325 enum grep_context ctx
, ssize_t
*col
,
1326 ssize_t
*icol
, int collect_hits
)
1328 struct grep_expr
*x
= opt
->pattern_expression
;
1329 return match_expr_eval(opt
, x
, bol
, eol
, ctx
, col
, icol
, collect_hits
);
1332 static int match_line(struct grep_opt
*opt
, char *bol
, char *eol
,
1333 ssize_t
*col
, ssize_t
*icol
,
1334 enum grep_context ctx
, int collect_hits
)
1340 return match_expr(opt
, bol
, eol
, ctx
, col
, icol
,
1343 /* we do not call with collect_hits without being extended */
1344 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1346 if (match_one_pattern(p
, bol
, eol
, ctx
, &tmp
, 0)) {
1348 if (!opt
->columnnum
) {
1350 * Without --column, any single match on a line
1351 * is enough to know that it needs to be
1352 * printed. With --column, scan _all_ patterns
1353 * to find the earliest.
1357 if (*col
< 0 || tmp
.rm_so
< *col
)
1364 static int match_next_pattern(struct grep_pat
*p
, char *bol
, char *eol
,
1365 enum grep_context ctx
,
1366 regmatch_t
*pmatch
, int eflags
)
1370 if (!match_one_pattern(p
, bol
, eol
, ctx
, &match
, eflags
))
1372 if (match
.rm_so
< 0 || match
.rm_eo
< 0)
1374 if (pmatch
->rm_so
>= 0 && pmatch
->rm_eo
>= 0) {
1375 if (match
.rm_so
> pmatch
->rm_so
)
1377 if (match
.rm_so
== pmatch
->rm_so
&& match
.rm_eo
< pmatch
->rm_eo
)
1380 pmatch
->rm_so
= match
.rm_so
;
1381 pmatch
->rm_eo
= match
.rm_eo
;
1385 static int next_match(struct grep_opt
*opt
, char *bol
, char *eol
,
1386 enum grep_context ctx
, regmatch_t
*pmatch
, int eflags
)
1391 pmatch
->rm_so
= pmatch
->rm_eo
= -1;
1393 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1395 case GREP_PATTERN
: /* atom */
1396 case GREP_PATTERN_HEAD
:
1397 case GREP_PATTERN_BODY
:
1398 hit
|= match_next_pattern(p
, bol
, eol
, ctx
,
1409 static void show_line_header(struct grep_opt
*opt
, const char *name
,
1410 unsigned lno
, ssize_t cno
, char sign
)
1412 if (opt
->heading
&& opt
->last_shown
== 0) {
1413 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1414 opt
->output(opt
, "\n", 1);
1416 opt
->last_shown
= lno
;
1418 if (!opt
->heading
&& opt
->pathname
) {
1419 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1420 output_sep(opt
, sign
);
1424 xsnprintf(buf
, sizeof(buf
), "%d", lno
);
1425 output_color(opt
, buf
, strlen(buf
), opt
->colors
[GREP_COLOR_LINENO
]);
1426 output_sep(opt
, sign
);
1429 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1430 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1431 * being called with a context line.
1433 if (opt
->columnnum
&& cno
) {
1435 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
, (uintmax_t)cno
);
1436 output_color(opt
, buf
, strlen(buf
), opt
->colors
[GREP_COLOR_COLUMNNO
]);
1437 output_sep(opt
, sign
);
1441 static void show_line(struct grep_opt
*opt
, char *bol
, char *eol
,
1442 const char *name
, unsigned lno
, ssize_t cno
, char sign
)
1444 int rest
= eol
- bol
;
1445 const char *match_color
= NULL
;
1446 const char *line_color
= NULL
;
1448 if (opt
->file_break
&& opt
->last_shown
== 0) {
1449 if (opt
->show_hunk_mark
)
1450 opt
->output(opt
, "\n", 1);
1451 } else if (opt
->pre_context
|| opt
->post_context
|| opt
->funcbody
) {
1452 if (opt
->last_shown
== 0) {
1453 if (opt
->show_hunk_mark
) {
1454 output_color(opt
, "--", 2, opt
->colors
[GREP_COLOR_SEP
]);
1455 opt
->output(opt
, "\n", 1);
1457 } else if (lno
> opt
->last_shown
+ 1) {
1458 output_color(opt
, "--", 2, opt
->colors
[GREP_COLOR_SEP
]);
1459 opt
->output(opt
, "\n", 1);
1462 if (!opt
->only_matching
) {
1464 * In case the line we're being called with contains more than
1465 * one match, leave printing each header to the loop below.
1467 show_line_header(opt
, name
, lno
, cno
, sign
);
1469 if (opt
->color
|| opt
->only_matching
) {
1471 enum grep_context ctx
= GREP_CONTEXT_BODY
;
1477 match_color
= opt
->colors
[GREP_COLOR_MATCH_SELECTED
];
1479 match_color
= opt
->colors
[GREP_COLOR_MATCH_CONTEXT
];
1481 line_color
= opt
->colors
[GREP_COLOR_SELECTED
];
1482 else if (sign
== '-')
1483 line_color
= opt
->colors
[GREP_COLOR_CONTEXT
];
1484 else if (sign
== '=')
1485 line_color
= opt
->colors
[GREP_COLOR_FUNCTION
];
1488 while (next_match(opt
, bol
, eol
, ctx
, &match
, eflags
)) {
1489 if (match
.rm_so
== match
.rm_eo
)
1492 if (opt
->only_matching
)
1493 show_line_header(opt
, name
, lno
, cno
, sign
);
1495 output_color(opt
, bol
, match
.rm_so
, line_color
);
1496 output_color(opt
, bol
+ match
.rm_so
,
1497 match
.rm_eo
- match
.rm_so
, match_color
);
1498 if (opt
->only_matching
)
1499 opt
->output(opt
, "\n", 1);
1502 rest
-= match
.rm_eo
;
1503 eflags
= REG_NOTBOL
;
1507 if (!opt
->only_matching
) {
1508 output_color(opt
, bol
, rest
, line_color
);
1509 opt
->output(opt
, "\n", 1);
1517 * This lock protects access to the gitattributes machinery, which is
1520 pthread_mutex_t grep_attr_mutex
;
1522 static inline void grep_attr_lock(void)
1525 pthread_mutex_lock(&grep_attr_mutex
);
1528 static inline void grep_attr_unlock(void)
1531 pthread_mutex_unlock(&grep_attr_mutex
);
1535 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1537 pthread_mutex_t grep_read_mutex
;
1540 #define grep_attr_lock()
1541 #define grep_attr_unlock()
1544 static int match_funcname(struct grep_opt
*opt
, struct grep_source
*gs
, char *bol
, char *eol
)
1546 xdemitconf_t
*xecfg
= opt
->priv
;
1547 if (xecfg
&& !xecfg
->find_func
) {
1548 grep_source_load_driver(gs
);
1549 if (gs
->driver
->funcname
.pattern
) {
1550 const struct userdiff_funcname
*pe
= &gs
->driver
->funcname
;
1551 xdiff_set_find_func(xecfg
, pe
->pattern
, pe
->cflags
);
1553 xecfg
= opt
->priv
= NULL
;
1559 return xecfg
->find_func(bol
, eol
- bol
, buf
, 1,
1560 xecfg
->find_func_priv
) >= 0;
1565 if (isalpha(*bol
) || *bol
== '_' || *bol
== '$')
1570 static void show_funcname_line(struct grep_opt
*opt
, struct grep_source
*gs
,
1571 char *bol
, unsigned lno
)
1573 while (bol
> gs
->buf
) {
1576 while (bol
> gs
->buf
&& bol
[-1] != '\n')
1580 if (lno
<= opt
->last_shown
)
1583 if (match_funcname(opt
, gs
, bol
, eol
)) {
1584 show_line(opt
, bol
, eol
, gs
->name
, lno
, 0, '=');
1590 static int is_empty_line(const char *bol
, const char *eol
);
1592 static void show_pre_context(struct grep_opt
*opt
, struct grep_source
*gs
,
1593 char *bol
, char *end
, unsigned lno
)
1595 unsigned cur
= lno
, from
= 1, funcname_lno
= 0, orig_from
;
1596 int funcname_needed
= !!opt
->funcname
, comment_needed
= 0;
1598 if (opt
->pre_context
< lno
)
1599 from
= lno
- opt
->pre_context
;
1600 if (from
<= opt
->last_shown
)
1601 from
= opt
->last_shown
+ 1;
1603 if (opt
->funcbody
) {
1604 if (match_funcname(opt
, gs
, bol
, end
))
1607 funcname_needed
= 1;
1608 from
= opt
->last_shown
+ 1;
1612 while (bol
> gs
->buf
&& cur
> from
) {
1613 char *next_bol
= bol
;
1616 while (bol
> gs
->buf
&& bol
[-1] != '\n')
1619 if (comment_needed
&& (is_empty_line(bol
, eol
) ||
1620 match_funcname(opt
, gs
, bol
, eol
))) {
1629 if (funcname_needed
&& match_funcname(opt
, gs
, bol
, eol
)) {
1631 funcname_needed
= 0;
1639 /* We need to look even further back to find a function signature. */
1640 if (opt
->funcname
&& funcname_needed
)
1641 show_funcname_line(opt
, gs
, bol
, cur
);
1645 char *eol
= bol
, sign
= (cur
== funcname_lno
) ? '=' : '-';
1647 while (*eol
!= '\n')
1649 show_line(opt
, bol
, eol
, gs
->name
, cur
, 0, sign
);
1655 static int should_lookahead(struct grep_opt
*opt
)
1660 return 0; /* punt for too complex stuff */
1663 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1664 if (p
->token
!= GREP_PATTERN
)
1665 return 0; /* punt for "header only" and stuff */
1670 static int look_ahead(struct grep_opt
*opt
,
1671 unsigned long *left_p
,
1675 unsigned lno
= *lno_p
;
1678 char *sp
, *last_bol
;
1679 regoff_t earliest
= -1;
1681 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1685 hit
= patmatch(p
, bol
, bol
+ *left_p
, &m
, 0);
1686 if (!hit
|| m
.rm_so
< 0 || m
.rm_eo
< 0)
1688 if (earliest
< 0 || m
.rm_so
< earliest
)
1693 *bol_p
= bol
+ *left_p
;
1697 for (sp
= bol
+ earliest
; bol
< sp
&& sp
[-1] != '\n'; sp
--)
1698 ; /* find the beginning of the line */
1701 for (sp
= bol
; sp
< last_bol
; sp
++) {
1705 *left_p
-= last_bol
- bol
;
1711 static int fill_textconv_grep(struct userdiff_driver
*driver
,
1712 struct grep_source
*gs
)
1714 struct diff_filespec
*df
;
1718 if (!driver
|| !driver
->textconv
)
1719 return grep_source_load(gs
);
1722 * The textconv interface is intimately tied to diff_filespecs, so we
1723 * have to pretend to be one. If we could unify the grep_source
1724 * and diff_filespec structs, this mess could just go away.
1726 df
= alloc_filespec(gs
->path
);
1728 case GREP_SOURCE_OID
:
1729 fill_filespec(df
, gs
->identifier
, 1, 0100644);
1731 case GREP_SOURCE_FILE
:
1732 fill_filespec(df
, &null_oid
, 0, 0100644);
1735 BUG("attempt to textconv something without a path?");
1739 * fill_textconv is not remotely thread-safe; it may load objects
1740 * behind the scenes, and it modifies the global diff tempfile
1744 size
= fill_textconv(driver
, df
, &buf
);
1749 * The normal fill_textconv usage by the diff machinery would just keep
1750 * the textconv'd buf separate from the diff_filespec. But much of the
1751 * grep code passes around a grep_source and assumes that its "buf"
1752 * pointer is the beginning of the thing we are searching. So let's
1753 * install our textconv'd version into the grep_source, taking care not
1754 * to leak any existing buffer.
1756 grep_source_clear_data(gs
);
1763 static int is_empty_line(const char *bol
, const char *eol
)
1765 while (bol
< eol
&& isspace(*bol
))
1770 static int grep_source_1(struct grep_opt
*opt
, struct grep_source
*gs
, int collect_hits
)
1773 char *peek_bol
= NULL
;
1776 unsigned last_hit
= 0;
1777 int binary_match_only
= 0;
1779 int try_lookahead
= 0;
1780 int show_function
= 0;
1781 struct userdiff_driver
*textconv
= NULL
;
1782 enum grep_context ctx
= GREP_CONTEXT_HEAD
;
1786 opt
->output
= std_output
;
1788 if (opt
->pre_context
|| opt
->post_context
|| opt
->file_break
||
1790 /* Show hunk marks, except for the first file. */
1791 if (opt
->last_shown
)
1792 opt
->show_hunk_mark
= 1;
1794 * If we're using threads then we can't easily identify
1795 * the first file. Always put hunk marks in that case
1796 * and skip the very first one later in work_done().
1798 if (opt
->output
!= std_output
)
1799 opt
->show_hunk_mark
= 1;
1801 opt
->last_shown
= 0;
1803 if (opt
->allow_textconv
) {
1804 grep_source_load_driver(gs
);
1806 * We might set up the shared textconv cache data here, which
1807 * is not thread-safe.
1810 textconv
= userdiff_get_textconv(gs
->driver
);
1815 * We know the result of a textconv is text, so we only have to care
1816 * about binary handling if we are not using it.
1819 switch (opt
->binary
) {
1820 case GREP_BINARY_DEFAULT
:
1821 if (grep_source_is_binary(gs
))
1822 binary_match_only
= 1;
1824 case GREP_BINARY_NOMATCH
:
1825 if (grep_source_is_binary(gs
))
1826 return 0; /* Assume unmatch */
1828 case GREP_BINARY_TEXT
:
1831 BUG("unknown binary handling mode");
1835 memset(&xecfg
, 0, sizeof(xecfg
));
1838 try_lookahead
= should_lookahead(opt
);
1840 if (fill_textconv_grep(textconv
, gs
) < 0)
1849 ssize_t col
= -1, icol
= -1;
1852 * look_ahead() skips quickly to the line that possibly
1853 * has the next hit; don't call it if we need to do
1854 * something more than just skipping the current line
1855 * in response to an unmatch for the current line. E.g.
1856 * inside a post-context window, we will show the current
1857 * line as a context around the previous hit when it
1862 && (show_function
||
1863 lno
<= last_hit
+ opt
->post_context
))
1864 && look_ahead(opt
, &left
, &lno
, &bol
))
1866 eol
= end_of_line(bol
, &left
);
1870 if ((ctx
== GREP_CONTEXT_HEAD
) && (eol
== bol
))
1871 ctx
= GREP_CONTEXT_BODY
;
1873 hit
= match_line(opt
, bol
, eol
, &col
, &icol
, ctx
, collect_hits
);
1879 /* "grep -v -e foo -e bla" should list lines
1880 * that do not have either, so inversion should
1885 if (opt
->unmatch_name_only
) {
1892 if (opt
->status_only
)
1894 if (opt
->name_only
) {
1895 show_name(opt
, gs
->name
);
1900 if (binary_match_only
) {
1901 opt
->output(opt
, "Binary file ", 12);
1902 output_color(opt
, gs
->name
, strlen(gs
->name
),
1903 opt
->colors
[GREP_COLOR_FILENAME
]);
1904 opt
->output(opt
, " matches\n", 9);
1907 /* Hit at this line. If we haven't shown the
1908 * pre-context lines, we would need to show them.
1910 if (opt
->pre_context
|| opt
->funcbody
)
1911 show_pre_context(opt
, gs
, bol
, eol
, lno
);
1912 else if (opt
->funcname
)
1913 show_funcname_line(opt
, gs
, bol
, lno
);
1914 cno
= opt
->invert
? icol
: col
;
1917 * A negative cno indicates that there was no
1918 * match on the line. We are thus inverted and
1919 * being asked to show all lines that _don't_
1920 * match a given expression. Therefore, set cno
1921 * to 0 to suggest the whole line matches.
1925 show_line(opt
, bol
, eol
, gs
->name
, lno
, cno
+ 1, ':');
1931 if (show_function
&& (!peek_bol
|| peek_bol
< bol
)) {
1932 unsigned long peek_left
= left
;
1933 char *peek_eol
= eol
;
1936 * Trailing empty lines are not interesting.
1937 * Peek past them to see if they belong to the
1938 * body of the current function.
1941 while (is_empty_line(peek_bol
, peek_eol
)) {
1942 peek_bol
= peek_eol
+ 1;
1943 peek_eol
= end_of_line(peek_bol
, &peek_left
);
1946 if (match_funcname(opt
, gs
, peek_bol
, peek_eol
))
1949 if (show_function
||
1950 (last_hit
&& lno
<= last_hit
+ opt
->post_context
)) {
1951 /* If the last hit is within the post context,
1952 * we need to show this line.
1954 show_line(opt
, bol
, eol
, gs
->name
, lno
, col
+ 1, '-');
1968 if (opt
->status_only
)
1969 return opt
->unmatch_name_only
;
1970 if (opt
->unmatch_name_only
) {
1971 /* We did not see any hit, so we want to show this */
1972 show_name(opt
, gs
->name
);
1976 xdiff_clear_find_func(&xecfg
);
1980 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1981 * which feels mostly useless but sometimes useful. Maybe
1982 * make it another option? For now suppress them.
1984 if (opt
->count
&& count
) {
1986 if (opt
->pathname
) {
1987 output_color(opt
, gs
->name
, strlen(gs
->name
),
1988 opt
->colors
[GREP_COLOR_FILENAME
]);
1989 output_sep(opt
, ':');
1991 xsnprintf(buf
, sizeof(buf
), "%u\n", count
);
1992 opt
->output(opt
, buf
, strlen(buf
));
1998 static void clr_hit_marker(struct grep_expr
*x
)
2000 /* All-hit markers are meaningful only at the very top level
2005 if (x
->node
!= GREP_NODE_OR
)
2007 x
->u
.binary
.left
->hit
= 0;
2008 x
= x
->u
.binary
.right
;
2012 static int chk_hit_marker(struct grep_expr
*x
)
2014 /* Top level nodes have hit markers. See if they all are hits */
2016 if (x
->node
!= GREP_NODE_OR
)
2018 if (!x
->u
.binary
.left
->hit
)
2020 x
= x
->u
.binary
.right
;
2024 int grep_source(struct grep_opt
*opt
, struct grep_source
*gs
)
2027 * we do not have to do the two-pass grep when we do not check
2028 * buffer-wide "all-match".
2030 if (!opt
->all_match
)
2031 return grep_source_1(opt
, gs
, 0);
2033 /* Otherwise the toplevel "or" terms hit a bit differently.
2034 * We first clear hit markers from them.
2036 clr_hit_marker(opt
->pattern_expression
);
2037 grep_source_1(opt
, gs
, 1);
2039 if (!chk_hit_marker(opt
->pattern_expression
))
2042 return grep_source_1(opt
, gs
, 0);
2045 int grep_buffer(struct grep_opt
*opt
, char *buf
, unsigned long size
)
2047 struct grep_source gs
;
2050 grep_source_init(&gs
, GREP_SOURCE_BUF
, NULL
, NULL
, NULL
);
2054 r
= grep_source(opt
, &gs
);
2056 grep_source_clear(&gs
);
2060 void grep_source_init(struct grep_source
*gs
, enum grep_source_type type
,
2061 const char *name
, const char *path
,
2062 const void *identifier
)
2065 gs
->name
= xstrdup_or_null(name
);
2066 gs
->path
= xstrdup_or_null(path
);
2072 case GREP_SOURCE_FILE
:
2073 gs
->identifier
= xstrdup(identifier
);
2075 case GREP_SOURCE_OID
:
2076 gs
->identifier
= oiddup(identifier
);
2078 case GREP_SOURCE_BUF
:
2079 gs
->identifier
= NULL
;
2084 void grep_source_clear(struct grep_source
*gs
)
2086 FREE_AND_NULL(gs
->name
);
2087 FREE_AND_NULL(gs
->path
);
2088 FREE_AND_NULL(gs
->identifier
);
2089 grep_source_clear_data(gs
);
2092 void grep_source_clear_data(struct grep_source
*gs
)
2095 case GREP_SOURCE_FILE
:
2096 case GREP_SOURCE_OID
:
2097 FREE_AND_NULL(gs
->buf
);
2100 case GREP_SOURCE_BUF
:
2101 /* leave user-provided buf intact */
2106 static int grep_source_load_oid(struct grep_source
*gs
)
2108 enum object_type type
;
2111 gs
->buf
= read_object_file(gs
->identifier
, &type
, &gs
->size
);
2115 return error(_("'%s': unable to read %s"),
2117 oid_to_hex(gs
->identifier
));
2121 static int grep_source_load_file(struct grep_source
*gs
)
2123 const char *filename
= gs
->identifier
;
2129 if (lstat(filename
, &st
) < 0) {
2131 if (errno
!= ENOENT
)
2132 error_errno(_("failed to stat '%s'"), filename
);
2135 if (!S_ISREG(st
.st_mode
))
2137 size
= xsize_t(st
.st_size
);
2138 i
= open(filename
, O_RDONLY
);
2141 data
= xmallocz(size
);
2142 if (st
.st_size
!= read_in_full(i
, data
, size
)) {
2143 error_errno(_("'%s': short read"), filename
);
2155 static int grep_source_load(struct grep_source
*gs
)
2161 case GREP_SOURCE_FILE
:
2162 return grep_source_load_file(gs
);
2163 case GREP_SOURCE_OID
:
2164 return grep_source_load_oid(gs
);
2165 case GREP_SOURCE_BUF
:
2166 return gs
->buf
? 0 : -1;
2168 BUG("invalid grep_source type to load");
2171 void grep_source_load_driver(struct grep_source
*gs
)
2178 gs
->driver
= userdiff_find_by_path(gs
->path
);
2180 gs
->driver
= userdiff_find_by_name("default");
2184 static int grep_source_is_binary(struct grep_source
*gs
)
2186 grep_source_load_driver(gs
);
2187 if (gs
->driver
->binary
!= -1)
2188 return gs
->driver
->binary
;
2190 if (!grep_source_load(gs
))
2191 return buffer_is_binary(gs
->buf
, gs
->size
);