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(struct repository
*repo
)
47 struct grep_opt
*opt
= &grep_defaults
;
54 memset(opt
, 0, sizeof(*opt
));
59 opt
->pattern_type_option
= GREP_PATTERN_TYPE_UNSPECIFIED
;
60 color_set(opt
->colors
[GREP_COLOR_CONTEXT
], "");
61 color_set(opt
->colors
[GREP_COLOR_FILENAME
], "");
62 color_set(opt
->colors
[GREP_COLOR_FUNCTION
], "");
63 color_set(opt
->colors
[GREP_COLOR_LINENO
], "");
64 color_set(opt
->colors
[GREP_COLOR_COLUMNNO
], "");
65 color_set(opt
->colors
[GREP_COLOR_MATCH_CONTEXT
], GIT_COLOR_BOLD_RED
);
66 color_set(opt
->colors
[GREP_COLOR_MATCH_SELECTED
], GIT_COLOR_BOLD_RED
);
67 color_set(opt
->colors
[GREP_COLOR_SELECTED
], "");
68 color_set(opt
->colors
[GREP_COLOR_SEP
], GIT_COLOR_CYAN
);
69 opt
->only_matching
= 0;
71 opt
->output
= std_output
;
74 static int parse_pattern_type_arg(const char *opt
, const char *arg
)
76 if (!strcmp(arg
, "default"))
77 return GREP_PATTERN_TYPE_UNSPECIFIED
;
78 else if (!strcmp(arg
, "basic"))
79 return GREP_PATTERN_TYPE_BRE
;
80 else if (!strcmp(arg
, "extended"))
81 return GREP_PATTERN_TYPE_ERE
;
82 else if (!strcmp(arg
, "fixed"))
83 return GREP_PATTERN_TYPE_FIXED
;
84 else if (!strcmp(arg
, "perl"))
85 return GREP_PATTERN_TYPE_PCRE
;
86 die("bad %s argument: %s", opt
, arg
);
89 define_list_config_array_extra(color_grep_slots
, {"match"});
92 * Read the configuration file once and store it in
93 * the grep_defaults template.
95 int grep_config(const char *var
, const char *value
, void *cb
)
97 struct grep_opt
*opt
= &grep_defaults
;
100 if (userdiff_config(var
, value
) < 0)
103 if (!strcmp(var
, "grep.extendedregexp")) {
104 opt
->extended_regexp_option
= git_config_bool(var
, value
);
108 if (!strcmp(var
, "grep.patterntype")) {
109 opt
->pattern_type_option
= parse_pattern_type_arg(var
, value
);
113 if (!strcmp(var
, "grep.linenumber")) {
114 opt
->linenum
= git_config_bool(var
, value
);
117 if (!strcmp(var
, "grep.column")) {
118 opt
->columnnum
= git_config_bool(var
, value
);
122 if (!strcmp(var
, "grep.fullname")) {
123 opt
->relative
= !git_config_bool(var
, value
);
127 if (!strcmp(var
, "color.grep"))
128 opt
->color
= git_config_colorbool(var
, value
);
129 if (!strcmp(var
, "color.grep.match")) {
130 if (grep_config("color.grep.matchcontext", value
, cb
) < 0)
132 if (grep_config("color.grep.matchselected", value
, cb
) < 0)
134 } else if (skip_prefix(var
, "color.grep.", &slot
)) {
135 int i
= LOOKUP_CONFIG(color_grep_slots
, slot
);
140 color
= opt
->colors
[i
];
142 return config_error_nonbool(var
);
143 return color_parse(value
, color
);
149 * Initialize one instance of grep_opt and copy the
150 * default values from the template we read the configuration
151 * information in an earlier call to git_config(grep_config).
153 void grep_init(struct grep_opt
*opt
, struct repository
*repo
, const char *prefix
)
155 struct grep_opt
*def
= &grep_defaults
;
158 memset(opt
, 0, sizeof(*opt
));
160 opt
->prefix
= prefix
;
161 opt
->prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
162 opt
->pattern_tail
= &opt
->pattern_list
;
163 opt
->header_tail
= &opt
->header_list
;
165 opt
->only_matching
= def
->only_matching
;
166 opt
->color
= def
->color
;
167 opt
->extended_regexp_option
= def
->extended_regexp_option
;
168 opt
->pattern_type_option
= def
->pattern_type_option
;
169 opt
->linenum
= def
->linenum
;
170 opt
->columnnum
= def
->columnnum
;
171 opt
->max_depth
= def
->max_depth
;
172 opt
->pathname
= def
->pathname
;
173 opt
->relative
= def
->relative
;
174 opt
->output
= def
->output
;
176 for (i
= 0; i
< NR_GREP_COLORS
; i
++)
177 color_set(opt
->colors
[i
], def
->colors
[i
]);
180 static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type
, struct grep_opt
*opt
)
183 * When committing to the pattern type by setting the relevant
184 * fields in grep_opt it's generally not necessary to zero out
185 * the fields we're not choosing, since they won't have been
186 * set by anything. The extended_regexp_option field is the
187 * only exception to this.
189 * This is because in the process of parsing grep.patternType
190 * & grep.extendedRegexp we set opt->pattern_type_option and
191 * opt->extended_regexp_option, respectively. We then
192 * internally use opt->extended_regexp_option to see if we're
193 * compiling an ERE. It must be unset if that's not actually
196 if (pattern_type
!= GREP_PATTERN_TYPE_ERE
&&
197 opt
->extended_regexp_option
)
198 opt
->extended_regexp_option
= 0;
200 switch (pattern_type
) {
201 case GREP_PATTERN_TYPE_UNSPECIFIED
:
204 case GREP_PATTERN_TYPE_BRE
:
207 case GREP_PATTERN_TYPE_ERE
:
208 opt
->extended_regexp_option
= 1;
211 case GREP_PATTERN_TYPE_FIXED
:
215 case GREP_PATTERN_TYPE_PCRE
:
220 * It's important that pcre1 always be assigned to
221 * even when there's no USE_LIBPCRE* defined. We still
222 * call the PCRE stub function, it just dies with
223 * "cannot use Perl-compatible regexes[...]".
231 void grep_commit_pattern_type(enum grep_pattern_type pattern_type
, struct grep_opt
*opt
)
233 if (pattern_type
!= GREP_PATTERN_TYPE_UNSPECIFIED
)
234 grep_set_pattern_type_option(pattern_type
, opt
);
235 else if (opt
->pattern_type_option
!= GREP_PATTERN_TYPE_UNSPECIFIED
)
236 grep_set_pattern_type_option(opt
->pattern_type_option
, opt
);
237 else if (opt
->extended_regexp_option
)
239 * This branch *must* happen after setting from the
240 * opt->pattern_type_option above, we don't want
241 * grep.extendedRegexp to override grep.patternType!
243 grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE
, opt
);
246 static struct grep_pat
*create_grep_pat(const char *pat
, size_t patlen
,
247 const char *origin
, int no
,
248 enum grep_pat_token t
,
249 enum grep_header_field field
)
251 struct grep_pat
*p
= xcalloc(1, sizeof(*p
));
252 p
->pattern
= xmemdupz(pat
, patlen
);
253 p
->patternlen
= patlen
;
261 static void do_append_grep_pat(struct grep_pat
***tail
, struct grep_pat
*p
)
268 case GREP_PATTERN
: /* atom */
269 case GREP_PATTERN_HEAD
:
270 case GREP_PATTERN_BODY
:
272 struct grep_pat
*new_pat
;
274 char *cp
= p
->pattern
+ p
->patternlen
, *nl
= NULL
;
275 while (++len
<= p
->patternlen
) {
276 if (*(--cp
) == '\n') {
283 new_pat
= create_grep_pat(nl
+ 1, len
- 1, p
->origin
,
284 p
->no
, p
->token
, p
->field
);
285 new_pat
->next
= p
->next
;
287 *tail
= &new_pat
->next
;
290 p
->patternlen
-= len
;
298 void append_header_grep_pattern(struct grep_opt
*opt
,
299 enum grep_header_field field
, const char *pat
)
301 struct grep_pat
*p
= create_grep_pat(pat
, strlen(pat
), "header", 0,
302 GREP_PATTERN_HEAD
, field
);
303 if (field
== GREP_HEADER_REFLOG
)
304 opt
->use_reflog_filter
= 1;
305 do_append_grep_pat(&opt
->header_tail
, p
);
308 void append_grep_pattern(struct grep_opt
*opt
, const char *pat
,
309 const char *origin
, int no
, enum grep_pat_token t
)
311 append_grep_pat(opt
, pat
, strlen(pat
), origin
, no
, t
);
314 void append_grep_pat(struct grep_opt
*opt
, const char *pat
, size_t patlen
,
315 const char *origin
, int no
, enum grep_pat_token t
)
317 struct grep_pat
*p
= create_grep_pat(pat
, patlen
, origin
, no
, t
, 0);
318 do_append_grep_pat(&opt
->pattern_tail
, p
);
321 struct grep_opt
*grep_opt_dup(const struct grep_opt
*opt
)
323 struct grep_pat
*pat
;
324 struct grep_opt
*ret
= xmalloc(sizeof(struct grep_opt
));
327 ret
->pattern_list
= NULL
;
328 ret
->pattern_tail
= &ret
->pattern_list
;
330 for(pat
= opt
->pattern_list
; pat
!= NULL
; pat
= pat
->next
)
332 if(pat
->token
== GREP_PATTERN_HEAD
)
333 append_header_grep_pattern(ret
, pat
->field
,
336 append_grep_pat(ret
, pat
->pattern
, pat
->patternlen
,
337 pat
->origin
, pat
->no
, pat
->token
);
343 static NORETURN
void compile_regexp_failed(const struct grep_pat
*p
,
349 xsnprintf(where
, sizeof(where
), "In '%s' at %d, ", p
->origin
, p
->no
);
351 xsnprintf(where
, sizeof(where
), "%s, ", p
->origin
);
355 die("%s'%s': %s", where
, p
->pattern
, error
);
358 static int is_fixed(const char *s
, size_t len
)
362 for (i
= 0; i
< len
; i
++) {
363 if (is_regex_special(s
[i
]))
370 static int has_null(const char *s
, size_t len
)
373 * regcomp cannot accept patterns with NULs so when using it
374 * we consider any pattern containing a NUL fixed.
376 if (memchr(s
, 0, len
))
383 static void compile_pcre1_regexp(struct grep_pat
*p
, const struct grep_opt
*opt
)
387 int options
= PCRE_MULTILINE
;
389 if (opt
->ignore_case
) {
390 if (has_non_ascii(p
->pattern
))
391 p
->pcre1_tables
= pcre_maketables();
392 options
|= PCRE_CASELESS
;
394 if (is_utf8_locale() && has_non_ascii(p
->pattern
))
395 options
|= PCRE_UTF8
;
397 p
->pcre1_regexp
= pcre_compile(p
->pattern
, options
, &error
, &erroffset
,
399 if (!p
->pcre1_regexp
)
400 compile_regexp_failed(p
, error
);
402 p
->pcre1_extra_info
= pcre_study(p
->pcre1_regexp
, GIT_PCRE_STUDY_JIT_COMPILE
, &error
);
403 if (!p
->pcre1_extra_info
&& error
)
406 #ifdef GIT_PCRE1_USE_JIT
407 pcre_config(PCRE_CONFIG_JIT
, &p
->pcre1_jit_on
);
408 if (p
->pcre1_jit_on
== 1) {
409 p
->pcre1_jit_stack
= pcre_jit_stack_alloc(1, 1024 * 1024);
410 if (!p
->pcre1_jit_stack
)
411 die("Couldn't allocate PCRE JIT stack");
412 pcre_assign_jit_stack(p
->pcre1_extra_info
, NULL
, p
->pcre1_jit_stack
);
413 } else if (p
->pcre1_jit_on
!= 0) {
414 BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
420 static int pcre1match(struct grep_pat
*p
, const char *line
, const char *eol
,
421 regmatch_t
*match
, int eflags
)
423 int ovector
[30], ret
, flags
= 0;
425 if (eflags
& REG_NOTBOL
)
426 flags
|= PCRE_NOTBOL
;
428 #ifdef GIT_PCRE1_USE_JIT
429 if (p
->pcre1_jit_on
) {
430 ret
= pcre_jit_exec(p
->pcre1_regexp
, p
->pcre1_extra_info
, line
,
431 eol
- line
, 0, flags
, ovector
,
432 ARRAY_SIZE(ovector
), p
->pcre1_jit_stack
);
436 ret
= pcre_exec(p
->pcre1_regexp
, p
->pcre1_extra_info
, line
,
437 eol
- line
, 0, flags
, ovector
,
438 ARRAY_SIZE(ovector
));
441 if (ret
< 0 && ret
!= PCRE_ERROR_NOMATCH
)
442 die("pcre_exec failed with error code %d", ret
);
445 match
->rm_so
= ovector
[0];
446 match
->rm_eo
= ovector
[1];
452 static void free_pcre1_regexp(struct grep_pat
*p
)
454 pcre_free(p
->pcre1_regexp
);
455 #ifdef GIT_PCRE1_USE_JIT
456 if (p
->pcre1_jit_on
) {
457 pcre_free_study(p
->pcre1_extra_info
);
458 pcre_jit_stack_free(p
->pcre1_jit_stack
);
462 pcre_free(p
->pcre1_extra_info
);
464 pcre_free((void *)p
->pcre1_tables
);
466 #else /* !USE_LIBPCRE1 */
467 static void compile_pcre1_regexp(struct grep_pat
*p
, const struct grep_opt
*opt
)
469 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
472 static int pcre1match(struct grep_pat
*p
, const char *line
, const char *eol
,
473 regmatch_t
*match
, int eflags
)
478 static void free_pcre1_regexp(struct grep_pat
*p
)
481 #endif /* !USE_LIBPCRE1 */
484 static void compile_pcre2_pattern(struct grep_pat
*p
, const struct grep_opt
*opt
)
487 PCRE2_UCHAR errbuf
[256];
488 PCRE2_SIZE erroffset
;
489 int options
= PCRE2_MULTILINE
;
490 const uint8_t *character_tables
= NULL
;
497 p
->pcre2_compile_context
= NULL
;
499 if (opt
->ignore_case
) {
500 if (has_non_ascii(p
->pattern
)) {
501 character_tables
= pcre2_maketables(NULL
);
502 p
->pcre2_compile_context
= pcre2_compile_context_create(NULL
);
503 pcre2_set_character_tables(p
->pcre2_compile_context
, character_tables
);
505 options
|= PCRE2_CASELESS
;
507 if (is_utf8_locale() && has_non_ascii(p
->pattern
))
508 options
|= PCRE2_UTF
;
510 p
->pcre2_pattern
= pcre2_compile((PCRE2_SPTR
)p
->pattern
,
511 p
->patternlen
, options
, &error
, &erroffset
,
512 p
->pcre2_compile_context
);
514 if (p
->pcre2_pattern
) {
515 p
->pcre2_match_data
= pcre2_match_data_create_from_pattern(p
->pcre2_pattern
, NULL
);
516 if (!p
->pcre2_match_data
)
517 die("Couldn't allocate PCRE2 match data");
519 pcre2_get_error_message(error
, errbuf
, sizeof(errbuf
));
520 compile_regexp_failed(p
, (const char *)&errbuf
);
523 pcre2_config(PCRE2_CONFIG_JIT
, &p
->pcre2_jit_on
);
524 if (p
->pcre2_jit_on
== 1) {
525 jitret
= pcre2_jit_compile(p
->pcre2_pattern
, PCRE2_JIT_COMPLETE
);
527 die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p
->pattern
, jitret
);
530 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
531 * tells us whether the library itself supports JIT,
532 * but to see whether we're going to be actually using
533 * JIT we need to extract PCRE2_INFO_JITSIZE from the
534 * pattern *after* we do pcre2_jit_compile() above.
536 * This is because if the pattern contains the
537 * (*NO_JIT) verb (see pcre2syntax(3))
538 * pcre2_jit_compile() will exit early with 0. If we
539 * then proceed to call pcre2_jit_match() further down
540 * the line instead of pcre2_match() we'll either
541 * segfault (pre PCRE 10.31) or run into a fatal error
544 patinforet
= pcre2_pattern_info(p
->pcre2_pattern
, PCRE2_INFO_JITSIZE
, &jitsizearg
);
546 BUG("pcre2_pattern_info() failed: %d", patinforet
);
547 if (jitsizearg
== 0) {
552 p
->pcre2_jit_stack
= pcre2_jit_stack_create(1, 1024 * 1024, NULL
);
553 if (!p
->pcre2_jit_stack
)
554 die("Couldn't allocate PCRE2 JIT stack");
555 p
->pcre2_match_context
= pcre2_match_context_create(NULL
);
556 if (!p
->pcre2_match_context
)
557 die("Couldn't allocate PCRE2 match context");
558 pcre2_jit_stack_assign(p
->pcre2_match_context
, NULL
, p
->pcre2_jit_stack
);
559 } else if (p
->pcre2_jit_on
!= 0) {
560 BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
565 static int pcre2match(struct grep_pat
*p
, const char *line
, const char *eol
,
566 regmatch_t
*match
, int eflags
)
570 PCRE2_UCHAR errbuf
[256];
572 if (eflags
& REG_NOTBOL
)
573 flags
|= PCRE2_NOTBOL
;
576 ret
= pcre2_jit_match(p
->pcre2_pattern
, (unsigned char *)line
,
577 eol
- line
, 0, flags
, p
->pcre2_match_data
,
580 ret
= pcre2_match(p
->pcre2_pattern
, (unsigned char *)line
,
581 eol
- line
, 0, flags
, p
->pcre2_match_data
,
584 if (ret
< 0 && ret
!= PCRE2_ERROR_NOMATCH
) {
585 pcre2_get_error_message(ret
, errbuf
, sizeof(errbuf
));
586 die("%s failed with error code %d: %s",
587 (p
->pcre2_jit_on
? "pcre2_jit_match" : "pcre2_match"), ret
,
591 ovector
= pcre2_get_ovector_pointer(p
->pcre2_match_data
);
593 match
->rm_so
= (int)ovector
[0];
594 match
->rm_eo
= (int)ovector
[1];
600 static void free_pcre2_pattern(struct grep_pat
*p
)
602 pcre2_compile_context_free(p
->pcre2_compile_context
);
603 pcre2_code_free(p
->pcre2_pattern
);
604 pcre2_match_data_free(p
->pcre2_match_data
);
605 pcre2_jit_stack_free(p
->pcre2_jit_stack
);
606 pcre2_match_context_free(p
->pcre2_match_context
);
608 #else /* !USE_LIBPCRE2 */
609 static void compile_pcre2_pattern(struct grep_pat
*p
, const struct grep_opt
*opt
)
612 * Unreachable until USE_LIBPCRE2 becomes synonymous with
613 * USE_LIBPCRE. See the sibling comment in
614 * grep_set_pattern_type_option().
616 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
619 static int pcre2match(struct grep_pat
*p
, const char *line
, const char *eol
,
620 regmatch_t
*match
, int eflags
)
625 static void free_pcre2_pattern(struct grep_pat
*p
)
628 #endif /* !USE_LIBPCRE2 */
630 static void compile_fixed_regexp(struct grep_pat
*p
, struct grep_opt
*opt
)
632 struct strbuf sb
= STRBUF_INIT
;
636 basic_regex_quote_buf(&sb
, p
->pattern
);
637 if (opt
->ignore_case
)
638 regflags
|= REG_ICASE
;
639 err
= regcomp(&p
->regexp
, sb
.buf
, regflags
);
641 fprintf(stderr
, "fixed %s\n", sb
.buf
);
645 regerror(err
, &p
->regexp
, errbuf
, sizeof(errbuf
));
646 compile_regexp_failed(p
, errbuf
);
650 static void compile_regexp(struct grep_pat
*p
, struct grep_opt
*opt
)
654 int regflags
= REG_NEWLINE
;
656 p
->word_regexp
= opt
->word_regexp
;
657 p
->ignore_case
= opt
->ignore_case
;
658 ascii_only
= !has_non_ascii(p
->pattern
);
661 * Even when -F (fixed) asks us to do a non-regexp search, we
662 * may not be able to correctly case-fold when -i
663 * (ignore-case) is asked (in which case, we'll synthesize a
664 * regexp to match the pattern that matches regexp special
665 * characters literally, while ignoring case differences). On
666 * the other hand, even without -F, if the pattern does not
667 * have any regexp special characters and there is no need for
668 * case-folding search, we can internally turn it into a
669 * simple string match using kws. p->fixed tells us if we
673 has_null(p
->pattern
, p
->patternlen
) ||
674 is_fixed(p
->pattern
, p
->patternlen
))
675 p
->fixed
= !p
->ignore_case
|| ascii_only
;
678 p
->kws
= kwsalloc(p
->ignore_case
? tolower_trans_tbl
: NULL
);
679 kwsincr(p
->kws
, p
->pattern
, p
->patternlen
);
682 } else if (opt
->fixed
) {
684 * We come here when the pattern has the non-ascii
685 * characters we cannot case-fold, and asked to
688 compile_fixed_regexp(p
, opt
);
693 compile_pcre2_pattern(p
, opt
);
698 compile_pcre1_regexp(p
, opt
);
703 regflags
|= REG_ICASE
;
704 if (opt
->extended_regexp_option
)
705 regflags
|= REG_EXTENDED
;
706 err
= regcomp(&p
->regexp
, p
->pattern
, regflags
);
709 regerror(err
, &p
->regexp
, errbuf
, 1024);
710 compile_regexp_failed(p
, errbuf
);
714 static struct grep_expr
*compile_pattern_or(struct grep_pat
**);
715 static struct grep_expr
*compile_pattern_atom(struct grep_pat
**list
)
724 case GREP_PATTERN
: /* atom */
725 case GREP_PATTERN_HEAD
:
726 case GREP_PATTERN_BODY
:
727 x
= xcalloc(1, sizeof (struct grep_expr
));
728 x
->node
= GREP_NODE_ATOM
;
732 case GREP_OPEN_PAREN
:
734 x
= compile_pattern_or(list
);
735 if (!*list
|| (*list
)->token
!= GREP_CLOSE_PAREN
)
736 die("unmatched parenthesis");
737 *list
= (*list
)->next
;
744 static struct grep_expr
*compile_pattern_not(struct grep_pat
**list
)
755 die("--not not followed by pattern expression");
757 x
= xcalloc(1, sizeof (struct grep_expr
));
758 x
->node
= GREP_NODE_NOT
;
759 x
->u
.unary
= compile_pattern_not(list
);
761 die("--not followed by non pattern expression");
764 return compile_pattern_atom(list
);
768 static struct grep_expr
*compile_pattern_and(struct grep_pat
**list
)
771 struct grep_expr
*x
, *y
, *z
;
773 x
= compile_pattern_not(list
);
775 if (p
&& p
->token
== GREP_AND
) {
777 die("--and not followed by pattern expression");
779 y
= compile_pattern_and(list
);
781 die("--and not followed by pattern expression");
782 z
= xcalloc(1, sizeof (struct grep_expr
));
783 z
->node
= GREP_NODE_AND
;
784 z
->u
.binary
.left
= x
;
785 z
->u
.binary
.right
= y
;
791 static struct grep_expr
*compile_pattern_or(struct grep_pat
**list
)
794 struct grep_expr
*x
, *y
, *z
;
796 x
= compile_pattern_and(list
);
798 if (x
&& p
&& p
->token
!= GREP_CLOSE_PAREN
) {
799 y
= compile_pattern_or(list
);
801 die("not a pattern expression %s", p
->pattern
);
802 z
= xcalloc(1, sizeof (struct grep_expr
));
803 z
->node
= GREP_NODE_OR
;
804 z
->u
.binary
.left
= x
;
805 z
->u
.binary
.right
= y
;
811 static struct grep_expr
*compile_pattern_expr(struct grep_pat
**list
)
813 return compile_pattern_or(list
);
816 static void indent(int in
)
822 static void dump_grep_pat(struct grep_pat
*p
)
825 case GREP_AND
: fprintf(stderr
, "*and*"); break;
826 case GREP_OPEN_PAREN
: fprintf(stderr
, "*(*"); break;
827 case GREP_CLOSE_PAREN
: fprintf(stderr
, "*)*"); break;
828 case GREP_NOT
: fprintf(stderr
, "*not*"); break;
829 case GREP_OR
: fprintf(stderr
, "*or*"); break;
831 case GREP_PATTERN
: fprintf(stderr
, "pattern"); break;
832 case GREP_PATTERN_HEAD
: fprintf(stderr
, "pattern_head"); break;
833 case GREP_PATTERN_BODY
: fprintf(stderr
, "pattern_body"); break;
838 case GREP_PATTERN_HEAD
:
839 fprintf(stderr
, "<head %d>", p
->field
); break;
840 case GREP_PATTERN_BODY
:
841 fprintf(stderr
, "<body>"); break;
845 case GREP_PATTERN_HEAD
:
846 case GREP_PATTERN_BODY
:
848 fprintf(stderr
, "%.*s", (int)p
->patternlen
, p
->pattern
);
854 static void dump_grep_expression_1(struct grep_expr
*x
, int in
)
859 fprintf(stderr
, "true\n");
862 dump_grep_pat(x
->u
.atom
);
865 fprintf(stderr
, "(not\n");
866 dump_grep_expression_1(x
->u
.unary
, in
+1);
868 fprintf(stderr
, ")\n");
871 fprintf(stderr
, "(and\n");
872 dump_grep_expression_1(x
->u
.binary
.left
, in
+1);
873 dump_grep_expression_1(x
->u
.binary
.right
, in
+1);
875 fprintf(stderr
, ")\n");
878 fprintf(stderr
, "(or\n");
879 dump_grep_expression_1(x
->u
.binary
.left
, in
+1);
880 dump_grep_expression_1(x
->u
.binary
.right
, in
+1);
882 fprintf(stderr
, ")\n");
887 static void dump_grep_expression(struct grep_opt
*opt
)
889 struct grep_expr
*x
= opt
->pattern_expression
;
892 fprintf(stderr
, "[all-match]\n");
893 dump_grep_expression_1(x
, 0);
897 static struct grep_expr
*grep_true_expr(void)
899 struct grep_expr
*z
= xcalloc(1, sizeof(*z
));
900 z
->node
= GREP_NODE_TRUE
;
904 static struct grep_expr
*grep_or_expr(struct grep_expr
*left
, struct grep_expr
*right
)
906 struct grep_expr
*z
= xcalloc(1, sizeof(*z
));
907 z
->node
= GREP_NODE_OR
;
908 z
->u
.binary
.left
= left
;
909 z
->u
.binary
.right
= right
;
913 static struct grep_expr
*prep_header_patterns(struct grep_opt
*opt
)
916 struct grep_expr
*header_expr
;
917 struct grep_expr
*(header_group
[GREP_HEADER_FIELD_MAX
]);
918 enum grep_header_field fld
;
920 if (!opt
->header_list
)
923 for (p
= opt
->header_list
; p
; p
= p
->next
) {
924 if (p
->token
!= GREP_PATTERN_HEAD
)
925 BUG("a non-header pattern in grep header list.");
926 if (p
->field
< GREP_HEADER_FIELD_MIN
||
927 GREP_HEADER_FIELD_MAX
<= p
->field
)
928 BUG("unknown header field %d", p
->field
);
929 compile_regexp(p
, opt
);
932 for (fld
= 0; fld
< GREP_HEADER_FIELD_MAX
; fld
++)
933 header_group
[fld
] = NULL
;
935 for (p
= opt
->header_list
; p
; p
= p
->next
) {
937 struct grep_pat
*pp
= p
;
939 h
= compile_pattern_atom(&pp
);
940 if (!h
|| pp
!= p
->next
)
941 BUG("malformed header expr");
942 if (!header_group
[p
->field
]) {
943 header_group
[p
->field
] = h
;
946 header_group
[p
->field
] = grep_or_expr(h
, header_group
[p
->field
]);
951 for (fld
= 0; fld
< GREP_HEADER_FIELD_MAX
; fld
++) {
952 if (!header_group
[fld
])
955 header_expr
= grep_true_expr();
956 header_expr
= grep_or_expr(header_group
[fld
], header_expr
);
961 static struct grep_expr
*grep_splice_or(struct grep_expr
*x
, struct grep_expr
*y
)
963 struct grep_expr
*z
= x
;
966 assert(x
->node
== GREP_NODE_OR
);
967 if (x
->u
.binary
.right
&&
968 x
->u
.binary
.right
->node
== GREP_NODE_TRUE
) {
969 x
->u
.binary
.right
= y
;
972 x
= x
->u
.binary
.right
;
977 static void compile_grep_patterns_real(struct grep_opt
*opt
)
980 struct grep_expr
*header_expr
= prep_header_patterns(opt
);
982 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
984 case GREP_PATTERN
: /* atom */
985 case GREP_PATTERN_HEAD
:
986 case GREP_PATTERN_BODY
:
987 compile_regexp(p
, opt
);
995 if (opt
->all_match
|| header_expr
)
997 else if (!opt
->extended
&& !opt
->debug
)
1000 p
= opt
->pattern_list
;
1002 opt
->pattern_expression
= compile_pattern_expr(&p
);
1004 die("incomplete pattern expression: %s", p
->pattern
);
1009 if (!opt
->pattern_expression
)
1010 opt
->pattern_expression
= header_expr
;
1011 else if (opt
->all_match
)
1012 opt
->pattern_expression
= grep_splice_or(header_expr
,
1013 opt
->pattern_expression
);
1015 opt
->pattern_expression
= grep_or_expr(opt
->pattern_expression
,
1020 void compile_grep_patterns(struct grep_opt
*opt
)
1022 compile_grep_patterns_real(opt
);
1024 dump_grep_expression(opt
);
1027 static void free_pattern_expr(struct grep_expr
*x
)
1030 case GREP_NODE_TRUE
:
1031 case GREP_NODE_ATOM
:
1034 free_pattern_expr(x
->u
.unary
);
1038 free_pattern_expr(x
->u
.binary
.left
);
1039 free_pattern_expr(x
->u
.binary
.right
);
1045 void free_grep_patterns(struct grep_opt
*opt
)
1047 struct grep_pat
*p
, *n
;
1049 for (p
= opt
->pattern_list
; p
; p
= n
) {
1052 case GREP_PATTERN
: /* atom */
1053 case GREP_PATTERN_HEAD
:
1054 case GREP_PATTERN_BODY
:
1057 else if (p
->pcre1_regexp
)
1058 free_pcre1_regexp(p
);
1059 else if (p
->pcre2_pattern
)
1060 free_pcre2_pattern(p
);
1062 regfree(&p
->regexp
);
1073 free_pattern_expr(opt
->pattern_expression
);
1076 static char *end_of_line(char *cp
, unsigned long *left
)
1078 unsigned long l
= *left
;
1079 while (l
&& *cp
!= '\n') {
1087 static int word_char(char ch
)
1089 return isalnum(ch
) || ch
== '_';
1092 static void output_color(struct grep_opt
*opt
, const void *data
, size_t size
,
1095 if (want_color(opt
->color
) && color
&& color
[0]) {
1096 opt
->output(opt
, color
, strlen(color
));
1097 opt
->output(opt
, data
, size
);
1098 opt
->output(opt
, GIT_COLOR_RESET
, strlen(GIT_COLOR_RESET
));
1100 opt
->output(opt
, data
, size
);
1103 static void output_sep(struct grep_opt
*opt
, char sign
)
1105 if (opt
->null_following_name
)
1106 opt
->output(opt
, "\0", 1);
1108 output_color(opt
, &sign
, 1, opt
->colors
[GREP_COLOR_SEP
]);
1111 static void show_name(struct grep_opt
*opt
, const char *name
)
1113 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1114 opt
->output(opt
, opt
->null_following_name
? "\0" : "\n", 1);
1117 static int fixmatch(struct grep_pat
*p
, char *line
, char *eol
,
1120 struct kwsmatch kwsm
;
1121 size_t offset
= kwsexec(p
->kws
, line
, eol
- line
, &kwsm
);
1123 match
->rm_so
= match
->rm_eo
= -1;
1126 match
->rm_so
= offset
;
1127 match
->rm_eo
= match
->rm_so
+ kwsm
.size
[0];
1132 static int patmatch(struct grep_pat
*p
, char *line
, char *eol
,
1133 regmatch_t
*match
, int eflags
)
1138 hit
= !fixmatch(p
, line
, eol
, match
);
1139 else if (p
->pcre1_regexp
)
1140 hit
= !pcre1match(p
, line
, eol
, match
, eflags
);
1141 else if (p
->pcre2_pattern
)
1142 hit
= !pcre2match(p
, line
, eol
, match
, eflags
);
1144 hit
= !regexec_buf(&p
->regexp
, line
, eol
- line
, 1, match
,
1150 static int strip_timestamp(char *bol
, char **eol_p
)
1155 while (bol
< --eol
) {
1169 } header_field
[] = {
1171 { "committer ", 10 },
1175 static int match_one_pattern(struct grep_pat
*p
, char *bol
, char *eol
,
1176 enum grep_context ctx
,
1177 regmatch_t
*pmatch
, int eflags
)
1181 const char *start
= bol
;
1183 if ((p
->token
!= GREP_PATTERN
) &&
1184 ((p
->token
== GREP_PATTERN_HEAD
) != (ctx
== GREP_CONTEXT_HEAD
)))
1187 if (p
->token
== GREP_PATTERN_HEAD
) {
1190 assert(p
->field
< ARRAY_SIZE(header_field
));
1191 field
= header_field
[p
->field
].field
;
1192 len
= header_field
[p
->field
].len
;
1193 if (strncmp(bol
, field
, len
))
1197 case GREP_HEADER_AUTHOR
:
1198 case GREP_HEADER_COMMITTER
:
1199 saved_ch
= strip_timestamp(bol
, &eol
);
1207 hit
= patmatch(p
, bol
, eol
, pmatch
, eflags
);
1209 if (hit
&& p
->word_regexp
) {
1210 if ((pmatch
[0].rm_so
< 0) ||
1211 (eol
- bol
) < pmatch
[0].rm_so
||
1212 (pmatch
[0].rm_eo
< 0) ||
1213 (eol
- bol
) < pmatch
[0].rm_eo
)
1214 die("regexp returned nonsense");
1216 /* Match beginning must be either beginning of the
1217 * line, or at word boundary (i.e. the last char must
1218 * not be a word char). Similarly, match end must be
1219 * either end of the line, or at word boundary
1220 * (i.e. the next char must not be a word char).
1222 if ( ((pmatch
[0].rm_so
== 0) ||
1223 !word_char(bol
[pmatch
[0].rm_so
-1])) &&
1224 ((pmatch
[0].rm_eo
== (eol
-bol
)) ||
1225 !word_char(bol
[pmatch
[0].rm_eo
])) )
1230 /* Words consist of at least one character. */
1231 if (pmatch
->rm_so
== pmatch
->rm_eo
)
1234 if (!hit
&& pmatch
[0].rm_so
+ bol
+ 1 < eol
) {
1235 /* There could be more than one match on the
1236 * line, and the first match might not be
1237 * strict word match. But later ones could be!
1238 * Forward to the next possible start, i.e. the
1239 * next position following a non-word char.
1241 bol
= pmatch
[0].rm_so
+ bol
+ 1;
1242 while (word_char(bol
[-1]) && bol
< eol
)
1244 eflags
|= REG_NOTBOL
;
1249 if (p
->token
== GREP_PATTERN_HEAD
&& saved_ch
)
1252 pmatch
[0].rm_so
+= bol
- start
;
1253 pmatch
[0].rm_eo
+= bol
- start
;
1258 static int match_expr_eval(struct grep_opt
*opt
, struct grep_expr
*x
, char *bol
,
1259 char *eol
, enum grep_context ctx
, ssize_t
*col
,
1260 ssize_t
*icol
, int collect_hits
)
1265 die("Not a valid grep expression");
1267 case GREP_NODE_TRUE
:
1270 case GREP_NODE_ATOM
:
1273 h
= match_one_pattern(x
->u
.atom
, bol
, eol
, ctx
,
1275 if (h
&& (*col
< 0 || tmp
.rm_so
< *col
))
1281 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1283 h
= !match_expr_eval(opt
, x
->u
.unary
, bol
, eol
, ctx
, icol
, col
,
1287 h
= match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
, ctx
, col
,
1289 if (h
|| opt
->columnnum
) {
1291 * Don't short-circuit AND when given --column, since a
1292 * NOT earlier in the tree may turn this into an OR. In
1293 * this case, see the below comment.
1295 h
&= match_expr_eval(opt
, x
->u
.binary
.right
, bol
, eol
,
1300 if (!(collect_hits
|| opt
->columnnum
)) {
1302 * Don't short-circuit OR when given --column (or
1303 * collecting hits) to ensure we don't skip a later
1304 * child that would produce an earlier match.
1306 return (match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
,
1307 ctx
, col
, icol
, 0) ||
1308 match_expr_eval(opt
, x
->u
.binary
.right
, bol
,
1309 eol
, ctx
, col
, icol
, 0));
1311 h
= match_expr_eval(opt
, x
->u
.binary
.left
, bol
, eol
, ctx
, col
,
1314 x
->u
.binary
.left
->hit
|= h
;
1315 h
|= match_expr_eval(opt
, x
->u
.binary
.right
, bol
, eol
, ctx
, col
,
1316 icol
, collect_hits
);
1319 die("Unexpected node type (internal error) %d", x
->node
);
1326 static int match_expr(struct grep_opt
*opt
, char *bol
, char *eol
,
1327 enum grep_context ctx
, ssize_t
*col
,
1328 ssize_t
*icol
, int collect_hits
)
1330 struct grep_expr
*x
= opt
->pattern_expression
;
1331 return match_expr_eval(opt
, x
, bol
, eol
, ctx
, col
, icol
, collect_hits
);
1334 static int match_line(struct grep_opt
*opt
, char *bol
, char *eol
,
1335 ssize_t
*col
, ssize_t
*icol
,
1336 enum grep_context ctx
, int collect_hits
)
1342 return match_expr(opt
, bol
, eol
, ctx
, col
, icol
,
1345 /* we do not call with collect_hits without being extended */
1346 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1348 if (match_one_pattern(p
, bol
, eol
, ctx
, &tmp
, 0)) {
1350 if (!opt
->columnnum
) {
1352 * Without --column, any single match on a line
1353 * is enough to know that it needs to be
1354 * printed. With --column, scan _all_ patterns
1355 * to find the earliest.
1359 if (*col
< 0 || tmp
.rm_so
< *col
)
1366 static int match_next_pattern(struct grep_pat
*p
, char *bol
, char *eol
,
1367 enum grep_context ctx
,
1368 regmatch_t
*pmatch
, int eflags
)
1372 if (!match_one_pattern(p
, bol
, eol
, ctx
, &match
, eflags
))
1374 if (match
.rm_so
< 0 || match
.rm_eo
< 0)
1376 if (pmatch
->rm_so
>= 0 && pmatch
->rm_eo
>= 0) {
1377 if (match
.rm_so
> pmatch
->rm_so
)
1379 if (match
.rm_so
== pmatch
->rm_so
&& match
.rm_eo
< pmatch
->rm_eo
)
1382 pmatch
->rm_so
= match
.rm_so
;
1383 pmatch
->rm_eo
= match
.rm_eo
;
1387 static int next_match(struct grep_opt
*opt
, char *bol
, char *eol
,
1388 enum grep_context ctx
, regmatch_t
*pmatch
, int eflags
)
1393 pmatch
->rm_so
= pmatch
->rm_eo
= -1;
1395 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1397 case GREP_PATTERN
: /* atom */
1398 case GREP_PATTERN_HEAD
:
1399 case GREP_PATTERN_BODY
:
1400 hit
|= match_next_pattern(p
, bol
, eol
, ctx
,
1411 static void show_line_header(struct grep_opt
*opt
, const char *name
,
1412 unsigned lno
, ssize_t cno
, char sign
)
1414 if (opt
->heading
&& opt
->last_shown
== 0) {
1415 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1416 opt
->output(opt
, "\n", 1);
1418 opt
->last_shown
= lno
;
1420 if (!opt
->heading
&& opt
->pathname
) {
1421 output_color(opt
, name
, strlen(name
), opt
->colors
[GREP_COLOR_FILENAME
]);
1422 output_sep(opt
, sign
);
1426 xsnprintf(buf
, sizeof(buf
), "%d", lno
);
1427 output_color(opt
, buf
, strlen(buf
), opt
->colors
[GREP_COLOR_LINENO
]);
1428 output_sep(opt
, sign
);
1431 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1432 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1433 * being called with a context line.
1435 if (opt
->columnnum
&& cno
) {
1437 xsnprintf(buf
, sizeof(buf
), "%"PRIuMAX
, (uintmax_t)cno
);
1438 output_color(opt
, buf
, strlen(buf
), opt
->colors
[GREP_COLOR_COLUMNNO
]);
1439 output_sep(opt
, sign
);
1443 static void show_line(struct grep_opt
*opt
, char *bol
, char *eol
,
1444 const char *name
, unsigned lno
, ssize_t cno
, char sign
)
1446 int rest
= eol
- bol
;
1447 const char *match_color
= NULL
;
1448 const char *line_color
= NULL
;
1450 if (opt
->file_break
&& opt
->last_shown
== 0) {
1451 if (opt
->show_hunk_mark
)
1452 opt
->output(opt
, "\n", 1);
1453 } else if (opt
->pre_context
|| opt
->post_context
|| opt
->funcbody
) {
1454 if (opt
->last_shown
== 0) {
1455 if (opt
->show_hunk_mark
) {
1456 output_color(opt
, "--", 2, opt
->colors
[GREP_COLOR_SEP
]);
1457 opt
->output(opt
, "\n", 1);
1459 } else if (lno
> opt
->last_shown
+ 1) {
1460 output_color(opt
, "--", 2, opt
->colors
[GREP_COLOR_SEP
]);
1461 opt
->output(opt
, "\n", 1);
1464 if (!opt
->only_matching
) {
1466 * In case the line we're being called with contains more than
1467 * one match, leave printing each header to the loop below.
1469 show_line_header(opt
, name
, lno
, cno
, sign
);
1471 if (opt
->color
|| opt
->only_matching
) {
1473 enum grep_context ctx
= GREP_CONTEXT_BODY
;
1479 match_color
= opt
->colors
[GREP_COLOR_MATCH_SELECTED
];
1481 match_color
= opt
->colors
[GREP_COLOR_MATCH_CONTEXT
];
1483 line_color
= opt
->colors
[GREP_COLOR_SELECTED
];
1484 else if (sign
== '-')
1485 line_color
= opt
->colors
[GREP_COLOR_CONTEXT
];
1486 else if (sign
== '=')
1487 line_color
= opt
->colors
[GREP_COLOR_FUNCTION
];
1490 while (next_match(opt
, bol
, eol
, ctx
, &match
, eflags
)) {
1491 if (match
.rm_so
== match
.rm_eo
)
1494 if (opt
->only_matching
)
1495 show_line_header(opt
, name
, lno
, cno
, sign
);
1497 output_color(opt
, bol
, match
.rm_so
, line_color
);
1498 output_color(opt
, bol
+ match
.rm_so
,
1499 match
.rm_eo
- match
.rm_so
, match_color
);
1500 if (opt
->only_matching
)
1501 opt
->output(opt
, "\n", 1);
1504 rest
-= match
.rm_eo
;
1505 eflags
= REG_NOTBOL
;
1509 if (!opt
->only_matching
) {
1510 output_color(opt
, bol
, rest
, line_color
);
1511 opt
->output(opt
, "\n", 1);
1519 * This lock protects access to the gitattributes machinery, which is
1522 pthread_mutex_t grep_attr_mutex
;
1524 static inline void grep_attr_lock(void)
1527 pthread_mutex_lock(&grep_attr_mutex
);
1530 static inline void grep_attr_unlock(void)
1533 pthread_mutex_unlock(&grep_attr_mutex
);
1537 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
1539 pthread_mutex_t grep_read_mutex
;
1542 #define grep_attr_lock()
1543 #define grep_attr_unlock()
1546 static int match_funcname(struct grep_opt
*opt
, struct grep_source
*gs
, char *bol
, char *eol
)
1548 xdemitconf_t
*xecfg
= opt
->priv
;
1549 if (xecfg
&& !xecfg
->find_func
) {
1550 grep_source_load_driver(gs
);
1551 if (gs
->driver
->funcname
.pattern
) {
1552 const struct userdiff_funcname
*pe
= &gs
->driver
->funcname
;
1553 xdiff_set_find_func(xecfg
, pe
->pattern
, pe
->cflags
);
1555 xecfg
= opt
->priv
= NULL
;
1561 return xecfg
->find_func(bol
, eol
- bol
, buf
, 1,
1562 xecfg
->find_func_priv
) >= 0;
1567 if (isalpha(*bol
) || *bol
== '_' || *bol
== '$')
1572 static void show_funcname_line(struct grep_opt
*opt
, struct grep_source
*gs
,
1573 char *bol
, unsigned lno
)
1575 while (bol
> gs
->buf
) {
1578 while (bol
> gs
->buf
&& bol
[-1] != '\n')
1582 if (lno
<= opt
->last_shown
)
1585 if (match_funcname(opt
, gs
, bol
, eol
)) {
1586 show_line(opt
, bol
, eol
, gs
->name
, lno
, 0, '=');
1592 static int is_empty_line(const char *bol
, const char *eol
);
1594 static void show_pre_context(struct grep_opt
*opt
, struct grep_source
*gs
,
1595 char *bol
, char *end
, unsigned lno
)
1597 unsigned cur
= lno
, from
= 1, funcname_lno
= 0, orig_from
;
1598 int funcname_needed
= !!opt
->funcname
, comment_needed
= 0;
1600 if (opt
->pre_context
< lno
)
1601 from
= lno
- opt
->pre_context
;
1602 if (from
<= opt
->last_shown
)
1603 from
= opt
->last_shown
+ 1;
1605 if (opt
->funcbody
) {
1606 if (match_funcname(opt
, gs
, bol
, end
))
1609 funcname_needed
= 1;
1610 from
= opt
->last_shown
+ 1;
1614 while (bol
> gs
->buf
&& cur
> from
) {
1615 char *next_bol
= bol
;
1618 while (bol
> gs
->buf
&& bol
[-1] != '\n')
1621 if (comment_needed
&& (is_empty_line(bol
, eol
) ||
1622 match_funcname(opt
, gs
, bol
, eol
))) {
1631 if (funcname_needed
&& match_funcname(opt
, gs
, bol
, eol
)) {
1633 funcname_needed
= 0;
1641 /* We need to look even further back to find a function signature. */
1642 if (opt
->funcname
&& funcname_needed
)
1643 show_funcname_line(opt
, gs
, bol
, cur
);
1647 char *eol
= bol
, sign
= (cur
== funcname_lno
) ? '=' : '-';
1649 while (*eol
!= '\n')
1651 show_line(opt
, bol
, eol
, gs
->name
, cur
, 0, sign
);
1657 static int should_lookahead(struct grep_opt
*opt
)
1662 return 0; /* punt for too complex stuff */
1665 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1666 if (p
->token
!= GREP_PATTERN
)
1667 return 0; /* punt for "header only" and stuff */
1672 static int look_ahead(struct grep_opt
*opt
,
1673 unsigned long *left_p
,
1677 unsigned lno
= *lno_p
;
1680 char *sp
, *last_bol
;
1681 regoff_t earliest
= -1;
1683 for (p
= opt
->pattern_list
; p
; p
= p
->next
) {
1687 hit
= patmatch(p
, bol
, bol
+ *left_p
, &m
, 0);
1688 if (!hit
|| m
.rm_so
< 0 || m
.rm_eo
< 0)
1690 if (earliest
< 0 || m
.rm_so
< earliest
)
1695 *bol_p
= bol
+ *left_p
;
1699 for (sp
= bol
+ earliest
; bol
< sp
&& sp
[-1] != '\n'; sp
--)
1700 ; /* find the beginning of the line */
1703 for (sp
= bol
; sp
< last_bol
; sp
++) {
1707 *left_p
-= last_bol
- bol
;
1713 static int fill_textconv_grep(struct repository
*r
,
1714 struct userdiff_driver
*driver
,
1715 struct grep_source
*gs
)
1717 struct diff_filespec
*df
;
1721 if (!driver
|| !driver
->textconv
)
1722 return grep_source_load(gs
);
1725 * The textconv interface is intimately tied to diff_filespecs, so we
1726 * have to pretend to be one. If we could unify the grep_source
1727 * and diff_filespec structs, this mess could just go away.
1729 df
= alloc_filespec(gs
->path
);
1731 case GREP_SOURCE_OID
:
1732 fill_filespec(df
, gs
->identifier
, 1, 0100644);
1734 case GREP_SOURCE_FILE
:
1735 fill_filespec(df
, &null_oid
, 0, 0100644);
1738 BUG("attempt to textconv something without a path?");
1742 * fill_textconv is not remotely thread-safe; it may load objects
1743 * behind the scenes, and it modifies the global diff tempfile
1747 size
= fill_textconv(r
, driver
, df
, &buf
);
1752 * The normal fill_textconv usage by the diff machinery would just keep
1753 * the textconv'd buf separate from the diff_filespec. But much of the
1754 * grep code passes around a grep_source and assumes that its "buf"
1755 * pointer is the beginning of the thing we are searching. So let's
1756 * install our textconv'd version into the grep_source, taking care not
1757 * to leak any existing buffer.
1759 grep_source_clear_data(gs
);
1766 static int is_empty_line(const char *bol
, const char *eol
)
1768 while (bol
< eol
&& isspace(*bol
))
1773 static int grep_source_1(struct grep_opt
*opt
, struct grep_source
*gs
, int collect_hits
)
1776 char *peek_bol
= NULL
;
1779 unsigned last_hit
= 0;
1780 int binary_match_only
= 0;
1782 int try_lookahead
= 0;
1783 int show_function
= 0;
1784 struct userdiff_driver
*textconv
= NULL
;
1785 enum grep_context ctx
= GREP_CONTEXT_HEAD
;
1789 opt
->output
= std_output
;
1791 if (opt
->pre_context
|| opt
->post_context
|| opt
->file_break
||
1793 /* Show hunk marks, except for the first file. */
1794 if (opt
->last_shown
)
1795 opt
->show_hunk_mark
= 1;
1797 * If we're using threads then we can't easily identify
1798 * the first file. Always put hunk marks in that case
1799 * and skip the very first one later in work_done().
1801 if (opt
->output
!= std_output
)
1802 opt
->show_hunk_mark
= 1;
1804 opt
->last_shown
= 0;
1806 if (opt
->allow_textconv
) {
1807 grep_source_load_driver(gs
);
1809 * We might set up the shared textconv cache data here, which
1810 * is not thread-safe.
1813 textconv
= userdiff_get_textconv(gs
->driver
);
1818 * We know the result of a textconv is text, so we only have to care
1819 * about binary handling if we are not using it.
1822 switch (opt
->binary
) {
1823 case GREP_BINARY_DEFAULT
:
1824 if (grep_source_is_binary(gs
))
1825 binary_match_only
= 1;
1827 case GREP_BINARY_NOMATCH
:
1828 if (grep_source_is_binary(gs
))
1829 return 0; /* Assume unmatch */
1831 case GREP_BINARY_TEXT
:
1834 BUG("unknown binary handling mode");
1838 memset(&xecfg
, 0, sizeof(xecfg
));
1841 try_lookahead
= should_lookahead(opt
);
1843 if (fill_textconv_grep(opt
->repo
, textconv
, gs
) < 0)
1852 ssize_t col
= -1, icol
= -1;
1855 * look_ahead() skips quickly to the line that possibly
1856 * has the next hit; don't call it if we need to do
1857 * something more than just skipping the current line
1858 * in response to an unmatch for the current line. E.g.
1859 * inside a post-context window, we will show the current
1860 * line as a context around the previous hit when it
1865 && (show_function
||
1866 lno
<= last_hit
+ opt
->post_context
))
1867 && look_ahead(opt
, &left
, &lno
, &bol
))
1869 eol
= end_of_line(bol
, &left
);
1873 if ((ctx
== GREP_CONTEXT_HEAD
) && (eol
== bol
))
1874 ctx
= GREP_CONTEXT_BODY
;
1876 hit
= match_line(opt
, bol
, eol
, &col
, &icol
, ctx
, collect_hits
);
1882 /* "grep -v -e foo -e bla" should list lines
1883 * that do not have either, so inversion should
1888 if (opt
->unmatch_name_only
) {
1895 if (opt
->status_only
)
1897 if (opt
->name_only
) {
1898 show_name(opt
, gs
->name
);
1903 if (binary_match_only
) {
1904 opt
->output(opt
, "Binary file ", 12);
1905 output_color(opt
, gs
->name
, strlen(gs
->name
),
1906 opt
->colors
[GREP_COLOR_FILENAME
]);
1907 opt
->output(opt
, " matches\n", 9);
1910 /* Hit at this line. If we haven't shown the
1911 * pre-context lines, we would need to show them.
1913 if (opt
->pre_context
|| opt
->funcbody
)
1914 show_pre_context(opt
, gs
, bol
, eol
, lno
);
1915 else if (opt
->funcname
)
1916 show_funcname_line(opt
, gs
, bol
, lno
);
1917 cno
= opt
->invert
? icol
: col
;
1920 * A negative cno indicates that there was no
1921 * match on the line. We are thus inverted and
1922 * being asked to show all lines that _don't_
1923 * match a given expression. Therefore, set cno
1924 * to 0 to suggest the whole line matches.
1928 show_line(opt
, bol
, eol
, gs
->name
, lno
, cno
+ 1, ':');
1934 if (show_function
&& (!peek_bol
|| peek_bol
< bol
)) {
1935 unsigned long peek_left
= left
;
1936 char *peek_eol
= eol
;
1939 * Trailing empty lines are not interesting.
1940 * Peek past them to see if they belong to the
1941 * body of the current function.
1944 while (is_empty_line(peek_bol
, peek_eol
)) {
1945 peek_bol
= peek_eol
+ 1;
1946 peek_eol
= end_of_line(peek_bol
, &peek_left
);
1949 if (match_funcname(opt
, gs
, peek_bol
, peek_eol
))
1952 if (show_function
||
1953 (last_hit
&& lno
<= last_hit
+ opt
->post_context
)) {
1954 /* If the last hit is within the post context,
1955 * we need to show this line.
1957 show_line(opt
, bol
, eol
, gs
->name
, lno
, col
+ 1, '-');
1971 if (opt
->status_only
)
1972 return opt
->unmatch_name_only
;
1973 if (opt
->unmatch_name_only
) {
1974 /* We did not see any hit, so we want to show this */
1975 show_name(opt
, gs
->name
);
1979 xdiff_clear_find_func(&xecfg
);
1983 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1984 * which feels mostly useless but sometimes useful. Maybe
1985 * make it another option? For now suppress them.
1987 if (opt
->count
&& count
) {
1989 if (opt
->pathname
) {
1990 output_color(opt
, gs
->name
, strlen(gs
->name
),
1991 opt
->colors
[GREP_COLOR_FILENAME
]);
1992 output_sep(opt
, ':');
1994 xsnprintf(buf
, sizeof(buf
), "%u\n", count
);
1995 opt
->output(opt
, buf
, strlen(buf
));
2001 static void clr_hit_marker(struct grep_expr
*x
)
2003 /* All-hit markers are meaningful only at the very top level
2008 if (x
->node
!= GREP_NODE_OR
)
2010 x
->u
.binary
.left
->hit
= 0;
2011 x
= x
->u
.binary
.right
;
2015 static int chk_hit_marker(struct grep_expr
*x
)
2017 /* Top level nodes have hit markers. See if they all are hits */
2019 if (x
->node
!= GREP_NODE_OR
)
2021 if (!x
->u
.binary
.left
->hit
)
2023 x
= x
->u
.binary
.right
;
2027 int grep_source(struct grep_opt
*opt
, struct grep_source
*gs
)
2030 * we do not have to do the two-pass grep when we do not check
2031 * buffer-wide "all-match".
2033 if (!opt
->all_match
)
2034 return grep_source_1(opt
, gs
, 0);
2036 /* Otherwise the toplevel "or" terms hit a bit differently.
2037 * We first clear hit markers from them.
2039 clr_hit_marker(opt
->pattern_expression
);
2040 grep_source_1(opt
, gs
, 1);
2042 if (!chk_hit_marker(opt
->pattern_expression
))
2045 return grep_source_1(opt
, gs
, 0);
2048 int grep_buffer(struct grep_opt
*opt
, char *buf
, unsigned long size
)
2050 struct grep_source gs
;
2053 grep_source_init(&gs
, GREP_SOURCE_BUF
, NULL
, NULL
, NULL
);
2057 r
= grep_source(opt
, &gs
);
2059 grep_source_clear(&gs
);
2063 void grep_source_init(struct grep_source
*gs
, enum grep_source_type type
,
2064 const char *name
, const char *path
,
2065 const void *identifier
)
2068 gs
->name
= xstrdup_or_null(name
);
2069 gs
->path
= xstrdup_or_null(path
);
2075 case GREP_SOURCE_FILE
:
2076 gs
->identifier
= xstrdup(identifier
);
2078 case GREP_SOURCE_OID
:
2079 gs
->identifier
= oiddup(identifier
);
2081 case GREP_SOURCE_BUF
:
2082 gs
->identifier
= NULL
;
2087 void grep_source_clear(struct grep_source
*gs
)
2089 FREE_AND_NULL(gs
->name
);
2090 FREE_AND_NULL(gs
->path
);
2091 FREE_AND_NULL(gs
->identifier
);
2092 grep_source_clear_data(gs
);
2095 void grep_source_clear_data(struct grep_source
*gs
)
2098 case GREP_SOURCE_FILE
:
2099 case GREP_SOURCE_OID
:
2100 FREE_AND_NULL(gs
->buf
);
2103 case GREP_SOURCE_BUF
:
2104 /* leave user-provided buf intact */
2109 static int grep_source_load_oid(struct grep_source
*gs
)
2111 enum object_type type
;
2114 gs
->buf
= read_object_file(gs
->identifier
, &type
, &gs
->size
);
2118 return error(_("'%s': unable to read %s"),
2120 oid_to_hex(gs
->identifier
));
2124 static int grep_source_load_file(struct grep_source
*gs
)
2126 const char *filename
= gs
->identifier
;
2132 if (lstat(filename
, &st
) < 0) {
2134 if (errno
!= ENOENT
)
2135 error_errno(_("failed to stat '%s'"), filename
);
2138 if (!S_ISREG(st
.st_mode
))
2140 size
= xsize_t(st
.st_size
);
2141 i
= open(filename
, O_RDONLY
);
2144 data
= xmallocz(size
);
2145 if (st
.st_size
!= read_in_full(i
, data
, size
)) {
2146 error_errno(_("'%s': short read"), filename
);
2158 static int grep_source_load(struct grep_source
*gs
)
2164 case GREP_SOURCE_FILE
:
2165 return grep_source_load_file(gs
);
2166 case GREP_SOURCE_OID
:
2167 return grep_source_load_oid(gs
);
2168 case GREP_SOURCE_BUF
:
2169 return gs
->buf
? 0 : -1;
2171 BUG("invalid grep_source type to load");
2174 void grep_source_load_driver(struct grep_source
*gs
)
2181 gs
->driver
= userdiff_find_by_path(gs
->path
);
2183 gs
->driver
= userdiff_find_by_name("default");
2187 static int grep_source_is_binary(struct grep_source
*gs
)
2189 grep_source_load_driver(gs
);
2190 if (gs
->driver
->binary
!= -1)
2191 return gs
->driver
->binary
;
2193 if (!grep_source_load(gs
))
2194 return buffer_is_binary(gs
->buf
, gs
->size
);