notes doc: split up run-on sentences
[alt-git.git] / grep.c
blobb86462a12a9e38bf6693da5a5dbe7e8f0fa798f3
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "gettext.h"
4 #include "grep.h"
5 #include "hex.h"
6 #include "object-store.h"
7 #include "userdiff.h"
8 #include "xdiff-interface.h"
9 #include "diff.h"
10 #include "diffcore.h"
11 #include "commit.h"
12 #include "quote.h"
13 #include "help.h"
15 static int grep_source_load(struct grep_source *gs);
16 static int grep_source_is_binary(struct grep_source *gs,
17 struct index_state *istate);
19 static void std_output(struct grep_opt *opt, const void *buf, size_t size)
21 fwrite(buf, size, 1, stdout);
24 static const char *color_grep_slots[] = {
25 [GREP_COLOR_CONTEXT] = "context",
26 [GREP_COLOR_FILENAME] = "filename",
27 [GREP_COLOR_FUNCTION] = "function",
28 [GREP_COLOR_LINENO] = "lineNumber",
29 [GREP_COLOR_COLUMNNO] = "column",
30 [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
31 [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
32 [GREP_COLOR_SELECTED] = "selected",
33 [GREP_COLOR_SEP] = "separator",
36 static int parse_pattern_type_arg(const char *opt, const char *arg)
38 if (!strcmp(arg, "default"))
39 return GREP_PATTERN_TYPE_UNSPECIFIED;
40 else if (!strcmp(arg, "basic"))
41 return GREP_PATTERN_TYPE_BRE;
42 else if (!strcmp(arg, "extended"))
43 return GREP_PATTERN_TYPE_ERE;
44 else if (!strcmp(arg, "fixed"))
45 return GREP_PATTERN_TYPE_FIXED;
46 else if (!strcmp(arg, "perl"))
47 return GREP_PATTERN_TYPE_PCRE;
48 die("bad %s argument: %s", opt, arg);
51 define_list_config_array_extra(color_grep_slots, {"match"});
54 * Read the configuration file once and store it in
55 * the grep_defaults template.
57 int grep_config(const char *var, const char *value, void *cb)
59 struct grep_opt *opt = cb;
60 const char *slot;
62 if (userdiff_config(var, value) < 0)
63 return -1;
65 if (!strcmp(var, "grep.extendedregexp")) {
66 opt->extended_regexp_option = git_config_bool(var, value);
67 return 0;
70 if (!strcmp(var, "grep.patterntype")) {
71 opt->pattern_type_option = parse_pattern_type_arg(var, value);
72 return 0;
75 if (!strcmp(var, "grep.linenumber")) {
76 opt->linenum = git_config_bool(var, value);
77 return 0;
79 if (!strcmp(var, "grep.column")) {
80 opt->columnnum = git_config_bool(var, value);
81 return 0;
84 if (!strcmp(var, "grep.fullname")) {
85 opt->relative = !git_config_bool(var, value);
86 return 0;
89 if (!strcmp(var, "color.grep"))
90 opt->color = git_config_colorbool(var, value);
91 if (!strcmp(var, "color.grep.match")) {
92 if (grep_config("color.grep.matchcontext", value, cb) < 0)
93 return -1;
94 if (grep_config("color.grep.matchselected", value, cb) < 0)
95 return -1;
96 } else if (skip_prefix(var, "color.grep.", &slot)) {
97 int i = LOOKUP_CONFIG(color_grep_slots, slot);
98 char *color;
100 if (i < 0)
101 return -1;
102 color = opt->colors[i];
103 if (!value)
104 return config_error_nonbool(var);
105 return color_parse(value, color);
107 return 0;
110 void grep_init(struct grep_opt *opt, struct repository *repo)
112 struct grep_opt blank = GREP_OPT_INIT;
113 memcpy(opt, &blank, sizeof(*opt));
115 opt->repo = repo;
116 opt->pattern_tail = &opt->pattern_list;
117 opt->header_tail = &opt->header_list;
120 static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
121 const char *origin, int no,
122 enum grep_pat_token t,
123 enum grep_header_field field)
125 struct grep_pat *p = xcalloc(1, sizeof(*p));
126 p->pattern = xmemdupz(pat, patlen);
127 p->patternlen = patlen;
128 p->origin = origin;
129 p->no = no;
130 p->token = t;
131 p->field = field;
132 return p;
135 static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
137 **tail = p;
138 *tail = &p->next;
139 p->next = NULL;
141 switch (p->token) {
142 case GREP_PATTERN: /* atom */
143 case GREP_PATTERN_HEAD:
144 case GREP_PATTERN_BODY:
145 for (;;) {
146 struct grep_pat *new_pat;
147 size_t len = 0;
148 char *cp = p->pattern + p->patternlen, *nl = NULL;
149 while (++len <= p->patternlen) {
150 if (*(--cp) == '\n') {
151 nl = cp;
152 break;
155 if (!nl)
156 break;
157 new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
158 p->no, p->token, p->field);
159 new_pat->next = p->next;
160 if (!p->next)
161 *tail = &new_pat->next;
162 p->next = new_pat;
163 *nl = '\0';
164 p->patternlen -= len;
166 break;
167 default:
168 break;
172 void append_header_grep_pattern(struct grep_opt *opt,
173 enum grep_header_field field, const char *pat)
175 struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
176 GREP_PATTERN_HEAD, field);
177 if (field == GREP_HEADER_REFLOG)
178 opt->use_reflog_filter = 1;
179 do_append_grep_pat(&opt->header_tail, p);
182 void append_grep_pattern(struct grep_opt *opt, const char *pat,
183 const char *origin, int no, enum grep_pat_token t)
185 append_grep_pat(opt, pat, strlen(pat), origin, no, t);
188 void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
189 const char *origin, int no, enum grep_pat_token t)
191 struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
192 do_append_grep_pat(&opt->pattern_tail, p);
195 struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
197 struct grep_pat *pat;
198 struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
199 *ret = *opt;
201 ret->pattern_list = NULL;
202 ret->pattern_tail = &ret->pattern_list;
204 for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
206 if(pat->token == GREP_PATTERN_HEAD)
207 append_header_grep_pattern(ret, pat->field,
208 pat->pattern);
209 else
210 append_grep_pat(ret, pat->pattern, pat->patternlen,
211 pat->origin, pat->no, pat->token);
214 return ret;
217 static NORETURN void compile_regexp_failed(const struct grep_pat *p,
218 const char *error)
220 char where[1024];
222 if (p->no)
223 xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
224 else if (p->origin)
225 xsnprintf(where, sizeof(where), "%s, ", p->origin);
226 else
227 where[0] = 0;
229 die("%s'%s': %s", where, p->pattern, error);
232 static int is_fixed(const char *s, size_t len)
234 size_t i;
236 for (i = 0; i < len; i++) {
237 if (is_regex_special(s[i]))
238 return 0;
241 return 1;
244 #ifdef USE_LIBPCRE2
245 #define GREP_PCRE2_DEBUG_MALLOC 0
247 static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
249 void *pointer = malloc(size);
250 #if GREP_PCRE2_DEBUG_MALLOC
251 static int count = 1;
252 fprintf(stderr, "PCRE2:%p -> #%02d: alloc(%lu)\n", pointer, count++, size);
253 #endif
254 return pointer;
257 static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
259 #if GREP_PCRE2_DEBUG_MALLOC
260 static int count = 1;
261 if (pointer)
262 fprintf(stderr, "PCRE2:%p -> #%02d: free()\n", pointer, count++);
263 #endif
264 free(pointer);
267 static int pcre2_jit_functional(void)
269 static int jit_working = -1;
270 pcre2_code *code;
271 size_t off;
272 int err;
274 if (jit_working != -1)
275 return jit_working;
278 * Try to JIT compile a simple pattern to probe if the JIT is
279 * working in general. It might fail for systems where creating
280 * memory mappings for runtime code generation is restricted.
282 code = pcre2_compile((PCRE2_SPTR)".", 1, 0, &err, &off, NULL);
283 if (!code)
284 return 0;
286 jit_working = pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) == 0;
287 pcre2_code_free(code);
289 return jit_working;
292 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
294 int error;
295 PCRE2_UCHAR errbuf[256];
296 PCRE2_SIZE erroffset;
297 int options = PCRE2_MULTILINE;
298 int jitret;
299 int patinforet;
300 size_t jitsizearg;
301 int literal = !opt->ignore_case && (p->fixed || p->is_fixed);
304 * Call pcre2_general_context_create() before calling any
305 * other pcre2_*(). It sets up our malloc()/free() functions
306 * with which everything else is allocated.
308 p->pcre2_general_context = pcre2_general_context_create(
309 pcre2_malloc, pcre2_free, NULL);
310 if (!p->pcre2_general_context)
311 die("Couldn't allocate PCRE2 general context");
313 if (opt->ignore_case) {
314 if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
315 p->pcre2_tables = pcre2_maketables(p->pcre2_general_context);
316 p->pcre2_compile_context = pcre2_compile_context_create(p->pcre2_general_context);
317 pcre2_set_character_tables(p->pcre2_compile_context,
318 p->pcre2_tables);
320 options |= PCRE2_CASELESS;
322 if (!opt->ignore_locale && is_utf8_locale() && !literal)
323 options |= (PCRE2_UTF | PCRE2_UCP | PCRE2_MATCH_INVALID_UTF);
325 #ifndef GIT_PCRE2_VERSION_10_35_OR_HIGHER
327 * Work around a JIT bug related to invalid Unicode character handling
328 * fixed in 10.35:
329 * https://github.com/PCRE2Project/pcre2/commit/c21bd977547d
331 options &= ~PCRE2_UCP;
332 #endif
334 #ifndef GIT_PCRE2_VERSION_10_36_OR_HIGHER
335 /* Work around https://bugs.exim.org/show_bug.cgi?id=2642 fixed in 10.36 */
336 if (PCRE2_MATCH_INVALID_UTF && options & (PCRE2_UTF | PCRE2_CASELESS))
337 options |= PCRE2_NO_START_OPTIMIZE;
338 #endif
340 p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
341 p->patternlen, options, &error, &erroffset,
342 p->pcre2_compile_context);
344 if (p->pcre2_pattern) {
345 p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, p->pcre2_general_context);
346 if (!p->pcre2_match_data)
347 die("Couldn't allocate PCRE2 match data");
348 } else {
349 pcre2_get_error_message(error, errbuf, sizeof(errbuf));
350 compile_regexp_failed(p, (const char *)&errbuf);
353 pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
354 if (p->pcre2_jit_on) {
355 jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
356 if (jitret == PCRE2_ERROR_NOMEMORY && !pcre2_jit_functional()) {
358 * Even though pcre2_config(PCRE2_CONFIG_JIT, ...)
359 * indicated JIT support, the library might still
360 * fail to generate JIT code for various reasons,
361 * e.g. when SELinux's 'deny_execmem' or PaX's
362 * MPROTECT prevent creating W|X memory mappings.
364 * Instead of faling hard, fall back to interpreter
365 * mode, just as if the pattern was prefixed with
366 * '(*NO_JIT)'.
368 p->pcre2_jit_on = 0;
369 return;
370 } else if (jitret) {
371 int need_clip = p->patternlen > 64;
372 int clip_len = need_clip ? 64 : p->patternlen;
373 die("Couldn't JIT the PCRE2 pattern '%.*s'%s, got '%d'%s",
374 clip_len, p->pattern, need_clip ? "..." : "", jitret,
375 pcre2_jit_functional()
376 ? "\nPerhaps prefix (*NO_JIT) to your pattern?"
377 : "");
381 * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
382 * tells us whether the library itself supports JIT,
383 * but to see whether we're going to be actually using
384 * JIT we need to extract PCRE2_INFO_JITSIZE from the
385 * pattern *after* we do pcre2_jit_compile() above.
387 * This is because if the pattern contains the
388 * (*NO_JIT) verb (see pcre2syntax(3))
389 * pcre2_jit_compile() will exit early with 0. If we
390 * then proceed to call pcre2_jit_match() further down
391 * the line instead of pcre2_match() we'll either
392 * segfault (pre PCRE 10.31) or run into a fatal error
393 * (post PCRE2 10.31)
395 patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
396 if (patinforet)
397 BUG("pcre2_pattern_info() failed: %d", patinforet);
398 if (jitsizearg == 0) {
399 p->pcre2_jit_on = 0;
400 return;
405 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
406 regmatch_t *match, int eflags)
408 int ret, flags = 0;
409 PCRE2_SIZE *ovector;
410 PCRE2_UCHAR errbuf[256];
412 if (eflags & REG_NOTBOL)
413 flags |= PCRE2_NOTBOL;
415 if (p->pcre2_jit_on)
416 ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
417 eol - line, 0, flags, p->pcre2_match_data,
418 NULL);
419 else
420 ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
421 eol - line, 0, flags, p->pcre2_match_data,
422 NULL);
424 if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
425 pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
426 die("%s failed with error code %d: %s",
427 (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
428 errbuf);
430 if (ret > 0) {
431 ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
432 ret = 0;
433 match->rm_so = (int)ovector[0];
434 match->rm_eo = (int)ovector[1];
437 return ret;
440 static void free_pcre2_pattern(struct grep_pat *p)
442 pcre2_compile_context_free(p->pcre2_compile_context);
443 pcre2_code_free(p->pcre2_pattern);
444 pcre2_match_data_free(p->pcre2_match_data);
445 #ifdef GIT_PCRE2_VERSION_10_34_OR_HIGHER
446 pcre2_maketables_free(p->pcre2_general_context, p->pcre2_tables);
447 #else
448 free((void *)p->pcre2_tables);
449 #endif
450 pcre2_general_context_free(p->pcre2_general_context);
452 #else /* !USE_LIBPCRE2 */
453 static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
455 die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
458 static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
459 regmatch_t *match, int eflags)
461 return 1;
464 static void free_pcre2_pattern(struct grep_pat *p)
468 static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
470 struct strbuf sb = STRBUF_INIT;
471 int err;
472 int regflags = 0;
474 basic_regex_quote_buf(&sb, p->pattern);
475 if (opt->ignore_case)
476 regflags |= REG_ICASE;
477 err = regcomp(&p->regexp, sb.buf, regflags);
478 strbuf_release(&sb);
479 if (err) {
480 char errbuf[1024];
481 regerror(err, &p->regexp, errbuf, sizeof(errbuf));
482 compile_regexp_failed(p, errbuf);
485 #endif /* !USE_LIBPCRE2 */
487 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
489 int err;
490 int regflags = REG_NEWLINE;
492 if (opt->pattern_type_option == GREP_PATTERN_TYPE_UNSPECIFIED)
493 opt->pattern_type_option = (opt->extended_regexp_option
494 ? GREP_PATTERN_TYPE_ERE
495 : GREP_PATTERN_TYPE_BRE);
497 p->word_regexp = opt->word_regexp;
498 p->ignore_case = opt->ignore_case;
499 p->fixed = opt->pattern_type_option == GREP_PATTERN_TYPE_FIXED;
501 if (opt->pattern_type_option != GREP_PATTERN_TYPE_PCRE &&
502 memchr(p->pattern, 0, p->patternlen))
503 die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
505 p->is_fixed = is_fixed(p->pattern, p->patternlen);
506 #ifdef USE_LIBPCRE2
507 if (!p->fixed && !p->is_fixed) {
508 const char *no_jit = "(*NO_JIT)";
509 const int no_jit_len = strlen(no_jit);
510 if (starts_with(p->pattern, no_jit) &&
511 is_fixed(p->pattern + no_jit_len,
512 p->patternlen - no_jit_len))
513 p->is_fixed = 1;
515 #endif
516 if (p->fixed || p->is_fixed) {
517 #ifdef USE_LIBPCRE2
518 if (p->is_fixed) {
519 compile_pcre2_pattern(p, opt);
520 } else {
522 * E.g. t7811-grep-open.sh relies on the
523 * pattern being restored.
525 char *old_pattern = p->pattern;
526 size_t old_patternlen = p->patternlen;
527 struct strbuf sb = STRBUF_INIT;
530 * There is the PCRE2_LITERAL flag, but it's
531 * only in PCRE v2 10.30 and later. Needing to
532 * ifdef our way around that and dealing with
533 * it + PCRE2_MULTILINE being an error is more
534 * complex than just quoting this ourselves.
536 strbuf_add(&sb, "\\Q", 2);
537 strbuf_add(&sb, p->pattern, p->patternlen);
538 strbuf_add(&sb, "\\E", 2);
540 p->pattern = sb.buf;
541 p->patternlen = sb.len;
542 compile_pcre2_pattern(p, opt);
543 p->pattern = old_pattern;
544 p->patternlen = old_patternlen;
545 strbuf_release(&sb);
547 #else /* !USE_LIBPCRE2 */
548 compile_fixed_regexp(p, opt);
549 #endif /* !USE_LIBPCRE2 */
550 return;
553 if (opt->pattern_type_option == GREP_PATTERN_TYPE_PCRE) {
554 compile_pcre2_pattern(p, opt);
555 return;
558 if (p->ignore_case)
559 regflags |= REG_ICASE;
560 if (opt->pattern_type_option == GREP_PATTERN_TYPE_ERE)
561 regflags |= REG_EXTENDED;
562 err = regcomp(&p->regexp, p->pattern, regflags);
563 if (err) {
564 char errbuf[1024];
565 regerror(err, &p->regexp, errbuf, 1024);
566 compile_regexp_failed(p, errbuf);
570 static struct grep_expr *grep_not_expr(struct grep_expr *expr)
572 struct grep_expr *z = xcalloc(1, sizeof(*z));
573 z->node = GREP_NODE_NOT;
574 z->u.unary = expr;
575 return z;
578 static struct grep_expr *grep_binexp(enum grep_expr_node kind,
579 struct grep_expr *left,
580 struct grep_expr *right)
582 struct grep_expr *z = xcalloc(1, sizeof(*z));
583 z->node = kind;
584 z->u.binary.left = left;
585 z->u.binary.right = right;
586 return z;
589 static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
591 return grep_binexp(GREP_NODE_OR, left, right);
594 static struct grep_expr *grep_and_expr(struct grep_expr *left, struct grep_expr *right)
596 return grep_binexp(GREP_NODE_AND, left, right);
599 static struct grep_expr *compile_pattern_or(struct grep_pat **);
600 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
602 struct grep_pat *p;
603 struct grep_expr *x;
605 p = *list;
606 if (!p)
607 return NULL;
608 switch (p->token) {
609 case GREP_PATTERN: /* atom */
610 case GREP_PATTERN_HEAD:
611 case GREP_PATTERN_BODY:
612 CALLOC_ARRAY(x, 1);
613 x->node = GREP_NODE_ATOM;
614 x->u.atom = p;
615 *list = p->next;
616 return x;
617 case GREP_OPEN_PAREN:
618 *list = p->next;
619 x = compile_pattern_or(list);
620 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
621 die("unmatched parenthesis");
622 *list = (*list)->next;
623 return x;
624 default:
625 return NULL;
629 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
631 struct grep_pat *p;
632 struct grep_expr *x;
634 p = *list;
635 if (!p)
636 return NULL;
637 switch (p->token) {
638 case GREP_NOT:
639 if (!p->next)
640 die("--not not followed by pattern expression");
641 *list = p->next;
642 x = compile_pattern_not(list);
643 if (!x)
644 die("--not followed by non pattern expression");
645 return grep_not_expr(x);
646 default:
647 return compile_pattern_atom(list);
651 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
653 struct grep_pat *p;
654 struct grep_expr *x, *y;
656 x = compile_pattern_not(list);
657 p = *list;
658 if (p && p->token == GREP_AND) {
659 if (!x)
660 die("--and not preceded by pattern expression");
661 if (!p->next)
662 die("--and not followed by pattern expression");
663 *list = p->next;
664 y = compile_pattern_and(list);
665 if (!y)
666 die("--and not followed by pattern expression");
667 return grep_and_expr(x, y);
669 return x;
672 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
674 struct grep_pat *p;
675 struct grep_expr *x, *y;
677 x = compile_pattern_and(list);
678 p = *list;
679 if (x && p && p->token != GREP_CLOSE_PAREN) {
680 y = compile_pattern_or(list);
681 if (!y)
682 die("not a pattern expression %s", p->pattern);
683 return grep_or_expr(x, y);
685 return x;
688 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
690 return compile_pattern_or(list);
693 static struct grep_expr *grep_true_expr(void)
695 struct grep_expr *z = xcalloc(1, sizeof(*z));
696 z->node = GREP_NODE_TRUE;
697 return z;
700 static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
702 struct grep_pat *p;
703 struct grep_expr *header_expr;
704 struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
705 enum grep_header_field fld;
707 if (!opt->header_list)
708 return NULL;
710 for (p = opt->header_list; p; p = p->next) {
711 if (p->token != GREP_PATTERN_HEAD)
712 BUG("a non-header pattern in grep header list.");
713 if (p->field < GREP_HEADER_FIELD_MIN ||
714 GREP_HEADER_FIELD_MAX <= p->field)
715 BUG("unknown header field %d", p->field);
716 compile_regexp(p, opt);
719 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
720 header_group[fld] = NULL;
722 for (p = opt->header_list; p; p = p->next) {
723 struct grep_expr *h;
724 struct grep_pat *pp = p;
726 h = compile_pattern_atom(&pp);
727 if (!h || pp != p->next)
728 BUG("malformed header expr");
729 if (!header_group[p->field]) {
730 header_group[p->field] = h;
731 continue;
733 header_group[p->field] = grep_or_expr(h, header_group[p->field]);
736 header_expr = NULL;
738 for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
739 if (!header_group[fld])
740 continue;
741 if (!header_expr)
742 header_expr = grep_true_expr();
743 header_expr = grep_or_expr(header_group[fld], header_expr);
745 return header_expr;
748 static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
750 struct grep_expr *z = x;
752 while (x) {
753 assert(x->node == GREP_NODE_OR);
754 if (x->u.binary.right &&
755 x->u.binary.right->node == GREP_NODE_TRUE) {
756 x->u.binary.right = y;
757 break;
759 x = x->u.binary.right;
761 return z;
764 void compile_grep_patterns(struct grep_opt *opt)
766 struct grep_pat *p;
767 struct grep_expr *header_expr = prep_header_patterns(opt);
768 int extended = 0;
770 for (p = opt->pattern_list; p; p = p->next) {
771 switch (p->token) {
772 case GREP_PATTERN: /* atom */
773 case GREP_PATTERN_HEAD:
774 case GREP_PATTERN_BODY:
775 compile_regexp(p, opt);
776 break;
777 default:
778 extended = 1;
779 break;
783 if (opt->all_match || opt->no_body_match || header_expr)
784 extended = 1;
785 else if (!extended)
786 return;
788 p = opt->pattern_list;
789 if (p)
790 opt->pattern_expression = compile_pattern_expr(&p);
791 if (p)
792 die("incomplete pattern expression: %s", p->pattern);
794 if (opt->no_body_match && opt->pattern_expression)
795 opt->pattern_expression = grep_not_expr(opt->pattern_expression);
797 if (!header_expr)
798 return;
800 if (!opt->pattern_expression)
801 opt->pattern_expression = header_expr;
802 else if (opt->all_match)
803 opt->pattern_expression = grep_splice_or(header_expr,
804 opt->pattern_expression);
805 else
806 opt->pattern_expression = grep_or_expr(opt->pattern_expression,
807 header_expr);
808 opt->all_match = 1;
811 static void free_pattern_expr(struct grep_expr *x)
813 switch (x->node) {
814 case GREP_NODE_TRUE:
815 case GREP_NODE_ATOM:
816 break;
817 case GREP_NODE_NOT:
818 free_pattern_expr(x->u.unary);
819 break;
820 case GREP_NODE_AND:
821 case GREP_NODE_OR:
822 free_pattern_expr(x->u.binary.left);
823 free_pattern_expr(x->u.binary.right);
824 break;
826 free(x);
829 static void free_grep_pat(struct grep_pat *pattern)
831 struct grep_pat *p, *n;
833 for (p = pattern; p; p = n) {
834 n = p->next;
835 switch (p->token) {
836 case GREP_PATTERN: /* atom */
837 case GREP_PATTERN_HEAD:
838 case GREP_PATTERN_BODY:
839 if (p->pcre2_pattern)
840 free_pcre2_pattern(p);
841 else
842 regfree(&p->regexp);
843 free(p->pattern);
844 break;
845 default:
846 break;
848 free(p);
852 void free_grep_patterns(struct grep_opt *opt)
854 free_grep_pat(opt->pattern_list);
855 free_grep_pat(opt->header_list);
857 if (opt->pattern_expression)
858 free_pattern_expr(opt->pattern_expression);
861 static const char *end_of_line(const char *cp, unsigned long *left)
863 unsigned long l = *left;
864 while (l && *cp != '\n') {
865 l--;
866 cp++;
868 *left = l;
869 return cp;
872 static int word_char(char ch)
874 return isalnum(ch) || ch == '_';
877 static void output_color(struct grep_opt *opt, const void *data, size_t size,
878 const char *color)
880 if (want_color(opt->color) && color && color[0]) {
881 opt->output(opt, color, strlen(color));
882 opt->output(opt, data, size);
883 opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
884 } else
885 opt->output(opt, data, size);
888 static void output_sep(struct grep_opt *opt, char sign)
890 if (opt->null_following_name)
891 opt->output(opt, "\0", 1);
892 else
893 output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
896 static void show_name(struct grep_opt *opt, const char *name)
898 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
899 opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
902 static int patmatch(struct grep_pat *p,
903 const char *line, const char *eol,
904 regmatch_t *match, int eflags)
906 int hit;
908 if (p->pcre2_pattern)
909 hit = !pcre2match(p, line, eol, match, eflags);
910 else
911 hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
912 eflags);
914 return hit;
917 static void strip_timestamp(const char *bol, const char **eol_p)
919 const char *eol = *eol_p;
921 while (bol < --eol) {
922 if (*eol != '>')
923 continue;
924 *eol_p = ++eol;
925 break;
929 static struct {
930 const char *field;
931 size_t len;
932 } header_field[] = {
933 { "author ", 7 },
934 { "committer ", 10 },
935 { "reflog ", 7 },
938 static int headerless_match_one_pattern(struct grep_pat *p,
939 const char *bol, const char *eol,
940 enum grep_context ctx,
941 regmatch_t *pmatch, int eflags)
943 int hit = 0;
944 const char *start = bol;
946 if ((p->token != GREP_PATTERN) &&
947 ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
948 return 0;
950 again:
951 hit = patmatch(p, bol, eol, pmatch, eflags);
953 if (hit && p->word_regexp) {
954 if ((pmatch[0].rm_so < 0) ||
955 (eol - bol) < pmatch[0].rm_so ||
956 (pmatch[0].rm_eo < 0) ||
957 (eol - bol) < pmatch[0].rm_eo)
958 die("regexp returned nonsense");
960 /* Match beginning must be either beginning of the
961 * line, or at word boundary (i.e. the last char must
962 * not be a word char). Similarly, match end must be
963 * either end of the line, or at word boundary
964 * (i.e. the next char must not be a word char).
966 if ( ((pmatch[0].rm_so == 0) ||
967 !word_char(bol[pmatch[0].rm_so-1])) &&
968 ((pmatch[0].rm_eo == (eol-bol)) ||
969 !word_char(bol[pmatch[0].rm_eo])) )
971 else
972 hit = 0;
974 /* Words consist of at least one character. */
975 if (pmatch->rm_so == pmatch->rm_eo)
976 hit = 0;
978 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
979 /* There could be more than one match on the
980 * line, and the first match might not be
981 * strict word match. But later ones could be!
982 * Forward to the next possible start, i.e. the
983 * next position following a non-word char.
985 bol = pmatch[0].rm_so + bol + 1;
986 while (word_char(bol[-1]) && bol < eol)
987 bol++;
988 eflags |= REG_NOTBOL;
989 if (bol < eol)
990 goto again;
993 if (hit) {
994 pmatch[0].rm_so += bol - start;
995 pmatch[0].rm_eo += bol - start;
997 return hit;
1000 static int match_one_pattern(struct grep_pat *p,
1001 const char *bol, const char *eol,
1002 enum grep_context ctx, regmatch_t *pmatch,
1003 int eflags)
1005 const char *field;
1006 size_t len;
1008 if (p->token == GREP_PATTERN_HEAD) {
1009 assert(p->field < ARRAY_SIZE(header_field));
1010 field = header_field[p->field].field;
1011 len = header_field[p->field].len;
1012 if (strncmp(bol, field, len))
1013 return 0;
1014 bol += len;
1016 switch (p->field) {
1017 case GREP_HEADER_AUTHOR:
1018 case GREP_HEADER_COMMITTER:
1019 strip_timestamp(bol, &eol);
1020 break;
1021 default:
1022 break;
1026 return headerless_match_one_pattern(p, bol, eol, ctx, pmatch, eflags);
1030 static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x,
1031 const char *bol, const char *eol,
1032 enum grep_context ctx, ssize_t *col,
1033 ssize_t *icol, int collect_hits)
1035 int h = 0;
1037 switch (x->node) {
1038 case GREP_NODE_TRUE:
1039 h = 1;
1040 break;
1041 case GREP_NODE_ATOM:
1043 regmatch_t tmp;
1044 h = match_one_pattern(x->u.atom, bol, eol, ctx,
1045 &tmp, 0);
1046 if (h && (*col < 0 || tmp.rm_so < *col))
1047 *col = tmp.rm_so;
1049 if (x->u.atom->token == GREP_PATTERN_BODY)
1050 opt->body_hit |= h;
1051 break;
1052 case GREP_NODE_NOT:
1054 * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
1056 h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
1058 break;
1059 case GREP_NODE_AND:
1060 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1061 icol, 0);
1062 if (h || opt->columnnum) {
1064 * Don't short-circuit AND when given --column, since a
1065 * NOT earlier in the tree may turn this into an OR. In
1066 * this case, see the below comment.
1068 h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
1069 ctx, col, icol, 0);
1071 break;
1072 case GREP_NODE_OR:
1073 if (!(collect_hits || opt->columnnum)) {
1075 * Don't short-circuit OR when given --column (or
1076 * collecting hits) to ensure we don't skip a later
1077 * child that would produce an earlier match.
1079 return (match_expr_eval(opt, x->u.binary.left, bol, eol,
1080 ctx, col, icol, 0) ||
1081 match_expr_eval(opt, x->u.binary.right, bol,
1082 eol, ctx, col, icol, 0));
1084 h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
1085 icol, 0);
1086 if (collect_hits)
1087 x->u.binary.left->hit |= h;
1088 h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
1089 icol, collect_hits);
1090 break;
1091 default:
1092 die("Unexpected node type (internal error) %d", x->node);
1094 if (collect_hits)
1095 x->hit |= h;
1096 return h;
1099 static int match_expr(struct grep_opt *opt,
1100 const char *bol, const char *eol,
1101 enum grep_context ctx, ssize_t *col,
1102 ssize_t *icol, int collect_hits)
1104 struct grep_expr *x = opt->pattern_expression;
1105 return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
1108 static int match_line(struct grep_opt *opt,
1109 const char *bol, const char *eol,
1110 ssize_t *col, ssize_t *icol,
1111 enum grep_context ctx, int collect_hits)
1113 struct grep_pat *p;
1114 int hit = 0;
1116 if (opt->pattern_expression)
1117 return match_expr(opt, bol, eol, ctx, col, icol,
1118 collect_hits);
1120 /* we do not call with collect_hits without being extended */
1121 for (p = opt->pattern_list; p; p = p->next) {
1122 regmatch_t tmp;
1123 if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
1124 hit |= 1;
1125 if (!opt->columnnum) {
1127 * Without --column, any single match on a line
1128 * is enough to know that it needs to be
1129 * printed. With --column, scan _all_ patterns
1130 * to find the earliest.
1132 break;
1134 if (*col < 0 || tmp.rm_so < *col)
1135 *col = tmp.rm_so;
1138 return hit;
1141 static int match_next_pattern(struct grep_pat *p,
1142 const char *bol, const char *eol,
1143 enum grep_context ctx,
1144 regmatch_t *pmatch, int eflags)
1146 regmatch_t match;
1148 if (!headerless_match_one_pattern(p, bol, eol, ctx, &match, eflags))
1149 return 0;
1150 if (match.rm_so < 0 || match.rm_eo < 0)
1151 return 0;
1152 if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
1153 if (match.rm_so > pmatch->rm_so)
1154 return 1;
1155 if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
1156 return 1;
1158 pmatch->rm_so = match.rm_so;
1159 pmatch->rm_eo = match.rm_eo;
1160 return 1;
1163 int grep_next_match(struct grep_opt *opt,
1164 const char *bol, const char *eol,
1165 enum grep_context ctx, regmatch_t *pmatch,
1166 enum grep_header_field field, int eflags)
1168 struct grep_pat *p;
1169 int hit = 0;
1171 pmatch->rm_so = pmatch->rm_eo = -1;
1172 if (bol < eol) {
1173 for (p = ((ctx == GREP_CONTEXT_HEAD)
1174 ? opt->header_list : opt->pattern_list);
1175 p; p = p->next) {
1176 switch (p->token) {
1177 case GREP_PATTERN_HEAD:
1178 if ((field != GREP_HEADER_FIELD_MAX) &&
1179 (p->field != field))
1180 continue;
1181 /* fall thru */
1182 case GREP_PATTERN: /* atom */
1183 case GREP_PATTERN_BODY:
1184 hit |= match_next_pattern(p, bol, eol, ctx,
1185 pmatch, eflags);
1186 break;
1187 default:
1188 break;
1192 return hit;
1195 static void show_line_header(struct grep_opt *opt, const char *name,
1196 unsigned lno, ssize_t cno, char sign)
1198 if (opt->heading && opt->last_shown == 0) {
1199 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1200 opt->output(opt, "\n", 1);
1202 opt->last_shown = lno;
1204 if (!opt->heading && opt->pathname) {
1205 output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
1206 output_sep(opt, sign);
1208 if (opt->linenum) {
1209 char buf[32];
1210 xsnprintf(buf, sizeof(buf), "%d", lno);
1211 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
1212 output_sep(opt, sign);
1215 * Treat 'cno' as the 1-indexed offset from the start of a non-context
1216 * line to its first match. Otherwise, 'cno' is 0 indicating that we are
1217 * being called with a context line.
1219 if (opt->columnnum && cno) {
1220 char buf[32];
1221 xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
1222 output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
1223 output_sep(opt, sign);
1227 static void show_line(struct grep_opt *opt,
1228 const char *bol, const char *eol,
1229 const char *name, unsigned lno, ssize_t cno, char sign)
1231 int rest = eol - bol;
1232 const char *match_color = NULL;
1233 const char *line_color = NULL;
1235 if (opt->file_break && opt->last_shown == 0) {
1236 if (opt->show_hunk_mark)
1237 opt->output(opt, "\n", 1);
1238 } else if (opt->pre_context || opt->post_context || opt->funcbody) {
1239 if (opt->last_shown == 0) {
1240 if (opt->show_hunk_mark) {
1241 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1242 opt->output(opt, "\n", 1);
1244 } else if (lno > opt->last_shown + 1) {
1245 output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
1246 opt->output(opt, "\n", 1);
1249 if (!opt->only_matching) {
1251 * In case the line we're being called with contains more than
1252 * one match, leave printing each header to the loop below.
1254 show_line_header(opt, name, lno, cno, sign);
1256 if (opt->color || opt->only_matching) {
1257 regmatch_t match;
1258 enum grep_context ctx = GREP_CONTEXT_BODY;
1259 int eflags = 0;
1261 if (opt->color) {
1262 if (sign == ':')
1263 match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
1264 else
1265 match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
1266 if (sign == ':')
1267 line_color = opt->colors[GREP_COLOR_SELECTED];
1268 else if (sign == '-')
1269 line_color = opt->colors[GREP_COLOR_CONTEXT];
1270 else if (sign == '=')
1271 line_color = opt->colors[GREP_COLOR_FUNCTION];
1273 while (grep_next_match(opt, bol, eol, ctx, &match,
1274 GREP_HEADER_FIELD_MAX, eflags)) {
1275 if (match.rm_so == match.rm_eo)
1276 break;
1278 if (opt->only_matching)
1279 show_line_header(opt, name, lno, cno, sign);
1280 else
1281 output_color(opt, bol, match.rm_so, line_color);
1282 output_color(opt, bol + match.rm_so,
1283 match.rm_eo - match.rm_so, match_color);
1284 if (opt->only_matching)
1285 opt->output(opt, "\n", 1);
1286 bol += match.rm_eo;
1287 cno += match.rm_eo;
1288 rest -= match.rm_eo;
1289 eflags = REG_NOTBOL;
1292 if (!opt->only_matching) {
1293 output_color(opt, bol, rest, line_color);
1294 opt->output(opt, "\n", 1);
1298 int grep_use_locks;
1301 * This lock protects access to the gitattributes machinery, which is
1302 * not thread-safe.
1304 pthread_mutex_t grep_attr_mutex;
1306 static inline void grep_attr_lock(void)
1308 if (grep_use_locks)
1309 pthread_mutex_lock(&grep_attr_mutex);
1312 static inline void grep_attr_unlock(void)
1314 if (grep_use_locks)
1315 pthread_mutex_unlock(&grep_attr_mutex);
1318 static int match_funcname(struct grep_opt *opt, struct grep_source *gs,
1319 const char *bol, const char *eol)
1321 xdemitconf_t *xecfg = opt->priv;
1322 if (xecfg && !xecfg->find_func) {
1323 grep_source_load_driver(gs, opt->repo->index);
1324 if (gs->driver->funcname.pattern) {
1325 const struct userdiff_funcname *pe = &gs->driver->funcname;
1326 xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
1327 } else {
1328 xecfg = opt->priv = NULL;
1332 if (xecfg) {
1333 char buf[1];
1334 return xecfg->find_func(bol, eol - bol, buf, 1,
1335 xecfg->find_func_priv) >= 0;
1338 if (bol == eol)
1339 return 0;
1340 if (isalpha(*bol) || *bol == '_' || *bol == '$')
1341 return 1;
1342 return 0;
1345 static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
1346 const char *bol, unsigned lno)
1348 while (bol > gs->buf) {
1349 const char *eol = --bol;
1351 while (bol > gs->buf && bol[-1] != '\n')
1352 bol--;
1353 lno--;
1355 if (lno <= opt->last_shown)
1356 break;
1358 if (match_funcname(opt, gs, bol, eol)) {
1359 show_line(opt, bol, eol, gs->name, lno, 0, '=');
1360 break;
1365 static int is_empty_line(const char *bol, const char *eol);
1367 static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
1368 const char *bol, const char *end, unsigned lno)
1370 unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
1371 int funcname_needed = !!opt->funcname, comment_needed = 0;
1373 if (opt->pre_context < lno)
1374 from = lno - opt->pre_context;
1375 if (from <= opt->last_shown)
1376 from = opt->last_shown + 1;
1377 orig_from = from;
1378 if (opt->funcbody) {
1379 if (match_funcname(opt, gs, bol, end))
1380 comment_needed = 1;
1381 else
1382 funcname_needed = 1;
1383 from = opt->last_shown + 1;
1386 /* Rewind. */
1387 while (bol > gs->buf && cur > from) {
1388 const char *next_bol = bol;
1389 const char *eol = --bol;
1391 while (bol > gs->buf && bol[-1] != '\n')
1392 bol--;
1393 cur--;
1394 if (comment_needed && (is_empty_line(bol, eol) ||
1395 match_funcname(opt, gs, bol, eol))) {
1396 comment_needed = 0;
1397 from = orig_from;
1398 if (cur < from) {
1399 cur++;
1400 bol = next_bol;
1401 break;
1404 if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
1405 funcname_lno = cur;
1406 funcname_needed = 0;
1407 if (opt->funcbody)
1408 comment_needed = 1;
1409 else
1410 from = orig_from;
1414 /* We need to look even further back to find a function signature. */
1415 if (opt->funcname && funcname_needed)
1416 show_funcname_line(opt, gs, bol, cur);
1418 /* Back forward. */
1419 while (cur < lno) {
1420 const char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
1422 while (*eol != '\n')
1423 eol++;
1424 show_line(opt, bol, eol, gs->name, cur, 0, sign);
1425 bol = eol + 1;
1426 cur++;
1430 static int should_lookahead(struct grep_opt *opt)
1432 struct grep_pat *p;
1434 if (opt->pattern_expression)
1435 return 0; /* punt for too complex stuff */
1436 if (opt->invert)
1437 return 0;
1438 for (p = opt->pattern_list; p; p = p->next) {
1439 if (p->token != GREP_PATTERN)
1440 return 0; /* punt for "header only" and stuff */
1442 return 1;
1445 static int look_ahead(struct grep_opt *opt,
1446 unsigned long *left_p,
1447 unsigned *lno_p,
1448 const char **bol_p)
1450 unsigned lno = *lno_p;
1451 const char *bol = *bol_p;
1452 struct grep_pat *p;
1453 const char *sp, *last_bol;
1454 regoff_t earliest = -1;
1456 for (p = opt->pattern_list; p; p = p->next) {
1457 int hit;
1458 regmatch_t m;
1460 hit = patmatch(p, bol, bol + *left_p, &m, 0);
1461 if (!hit || m.rm_so < 0 || m.rm_eo < 0)
1462 continue;
1463 if (earliest < 0 || m.rm_so < earliest)
1464 earliest = m.rm_so;
1467 if (earliest < 0) {
1468 *bol_p = bol + *left_p;
1469 *left_p = 0;
1470 return 1;
1472 for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1473 ; /* find the beginning of the line */
1474 last_bol = sp;
1476 for (sp = bol; sp < last_bol; sp++) {
1477 if (*sp == '\n')
1478 lno++;
1480 *left_p -= last_bol - bol;
1481 *bol_p = last_bol;
1482 *lno_p = lno;
1483 return 0;
1486 static int fill_textconv_grep(struct repository *r,
1487 struct userdiff_driver *driver,
1488 struct grep_source *gs)
1490 struct diff_filespec *df;
1491 char *buf;
1492 size_t size;
1494 if (!driver || !driver->textconv)
1495 return grep_source_load(gs);
1498 * The textconv interface is intimately tied to diff_filespecs, so we
1499 * have to pretend to be one. If we could unify the grep_source
1500 * and diff_filespec structs, this mess could just go away.
1502 df = alloc_filespec(gs->path);
1503 switch (gs->type) {
1504 case GREP_SOURCE_OID:
1505 fill_filespec(df, gs->identifier, 1, 0100644);
1506 break;
1507 case GREP_SOURCE_FILE:
1508 fill_filespec(df, null_oid(), 0, 0100644);
1509 break;
1510 default:
1511 BUG("attempt to textconv something without a path?");
1515 * fill_textconv is not remotely thread-safe; it modifies the global
1516 * diff tempfile structure, writes to the_repo's odb and might
1517 * internally call thread-unsafe functions such as the
1518 * prepare_packed_git() lazy-initializator. Because of the last two, we
1519 * must ensure mutual exclusion between this call and the object reading
1520 * API, thus we use obj_read_lock() here.
1522 * TODO: allowing text conversion to run in parallel with object
1523 * reading operations might increase performance in the multithreaded
1524 * non-worktreee git-grep with --textconv.
1526 obj_read_lock();
1527 size = fill_textconv(r, driver, df, &buf);
1528 obj_read_unlock();
1529 free_filespec(df);
1532 * The normal fill_textconv usage by the diff machinery would just keep
1533 * the textconv'd buf separate from the diff_filespec. But much of the
1534 * grep code passes around a grep_source and assumes that its "buf"
1535 * pointer is the beginning of the thing we are searching. So let's
1536 * install our textconv'd version into the grep_source, taking care not
1537 * to leak any existing buffer.
1539 grep_source_clear_data(gs);
1540 gs->buf = buf;
1541 gs->size = size;
1543 return 0;
1546 static int is_empty_line(const char *bol, const char *eol)
1548 while (bol < eol && isspace(*bol))
1549 bol++;
1550 return bol == eol;
1553 static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1555 const char *bol;
1556 const char *peek_bol = NULL;
1557 unsigned long left;
1558 unsigned lno = 1;
1559 unsigned last_hit = 0;
1560 int binary_match_only = 0;
1561 unsigned count = 0;
1562 int try_lookahead = 0;
1563 int show_function = 0;
1564 struct userdiff_driver *textconv = NULL;
1565 enum grep_context ctx = GREP_CONTEXT_HEAD;
1566 xdemitconf_t xecfg;
1568 if (!opt->status_only && gs->name == NULL)
1569 BUG("grep call which could print a name requires "
1570 "grep_source.name be non-NULL");
1572 if (!opt->output)
1573 opt->output = std_output;
1575 if (opt->pre_context || opt->post_context || opt->file_break ||
1576 opt->funcbody) {
1577 /* Show hunk marks, except for the first file. */
1578 if (opt->last_shown)
1579 opt->show_hunk_mark = 1;
1581 * If we're using threads then we can't easily identify
1582 * the first file. Always put hunk marks in that case
1583 * and skip the very first one later in work_done().
1585 if (opt->output != std_output)
1586 opt->show_hunk_mark = 1;
1588 opt->last_shown = 0;
1590 if (opt->allow_textconv) {
1591 grep_source_load_driver(gs, opt->repo->index);
1593 * We might set up the shared textconv cache data here, which
1594 * is not thread-safe. Also, get_oid_with_context() and
1595 * parse_object() might be internally called. As they are not
1596 * currently thread-safe and might be racy with object reading,
1597 * obj_read_lock() must be called.
1599 grep_attr_lock();
1600 obj_read_lock();
1601 textconv = userdiff_get_textconv(opt->repo, gs->driver);
1602 obj_read_unlock();
1603 grep_attr_unlock();
1607 * We know the result of a textconv is text, so we only have to care
1608 * about binary handling if we are not using it.
1610 if (!textconv) {
1611 switch (opt->binary) {
1612 case GREP_BINARY_DEFAULT:
1613 if (grep_source_is_binary(gs, opt->repo->index))
1614 binary_match_only = 1;
1615 break;
1616 case GREP_BINARY_NOMATCH:
1617 if (grep_source_is_binary(gs, opt->repo->index))
1618 return 0; /* Assume unmatch */
1619 break;
1620 case GREP_BINARY_TEXT:
1621 break;
1622 default:
1623 BUG("unknown binary handling mode");
1627 memset(&xecfg, 0, sizeof(xecfg));
1628 opt->priv = &xecfg;
1630 try_lookahead = should_lookahead(opt);
1632 if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
1633 return 0;
1635 bol = gs->buf;
1636 left = gs->size;
1637 while (left) {
1638 const char *eol;
1639 int hit;
1640 ssize_t cno;
1641 ssize_t col = -1, icol = -1;
1644 * look_ahead() skips quickly to the line that possibly
1645 * has the next hit; don't call it if we need to do
1646 * something more than just skipping the current line
1647 * in response to an unmatch for the current line. E.g.
1648 * inside a post-context window, we will show the current
1649 * line as a context around the previous hit when it
1650 * doesn't hit.
1652 if (try_lookahead
1653 && !(last_hit
1654 && (show_function ||
1655 lno <= last_hit + opt->post_context))
1656 && look_ahead(opt, &left, &lno, &bol))
1657 break;
1658 eol = end_of_line(bol, &left);
1660 if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1661 ctx = GREP_CONTEXT_BODY;
1663 hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
1665 if (collect_hits)
1666 goto next_line;
1668 /* "grep -v -e foo -e bla" should list lines
1669 * that do not have either, so inversion should
1670 * be done outside.
1672 if (opt->invert)
1673 hit = !hit;
1674 if (opt->unmatch_name_only) {
1675 if (hit)
1676 return 0;
1677 goto next_line;
1679 if (hit && (opt->max_count < 0 || count < opt->max_count)) {
1680 count++;
1681 if (opt->status_only)
1682 return 1;
1683 if (opt->name_only) {
1684 show_name(opt, gs->name);
1685 return 1;
1687 if (opt->count)
1688 goto next_line;
1689 if (binary_match_only) {
1690 opt->output(opt, "Binary file ", 12);
1691 output_color(opt, gs->name, strlen(gs->name),
1692 opt->colors[GREP_COLOR_FILENAME]);
1693 opt->output(opt, " matches\n", 9);
1694 return 1;
1696 /* Hit at this line. If we haven't shown the
1697 * pre-context lines, we would need to show them.
1699 if (opt->pre_context || opt->funcbody)
1700 show_pre_context(opt, gs, bol, eol, lno);
1701 else if (opt->funcname)
1702 show_funcname_line(opt, gs, bol, lno);
1703 cno = opt->invert ? icol : col;
1704 if (cno < 0) {
1706 * A negative cno indicates that there was no
1707 * match on the line. We are thus inverted and
1708 * being asked to show all lines that _don't_
1709 * match a given expression. Therefore, set cno
1710 * to 0 to suggest the whole line matches.
1712 cno = 0;
1714 show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
1715 last_hit = lno;
1716 if (opt->funcbody)
1717 show_function = 1;
1718 goto next_line;
1720 if (show_function && (!peek_bol || peek_bol < bol)) {
1721 unsigned long peek_left = left;
1722 const char *peek_eol = eol;
1725 * Trailing empty lines are not interesting.
1726 * Peek past them to see if they belong to the
1727 * body of the current function.
1729 peek_bol = bol;
1730 while (is_empty_line(peek_bol, peek_eol)) {
1731 peek_bol = peek_eol + 1;
1732 peek_eol = end_of_line(peek_bol, &peek_left);
1735 if (match_funcname(opt, gs, peek_bol, peek_eol))
1736 show_function = 0;
1738 if (show_function ||
1739 (last_hit && lno <= last_hit + opt->post_context)) {
1740 /* If the last hit is within the post context,
1741 * we need to show this line.
1743 show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
1746 next_line:
1747 bol = eol + 1;
1748 if (!left)
1749 break;
1750 left--;
1751 lno++;
1754 if (collect_hits)
1755 return 0;
1757 if (opt->status_only)
1758 return opt->unmatch_name_only;
1759 if (opt->unmatch_name_only) {
1760 /* We did not see any hit, so we want to show this */
1761 show_name(opt, gs->name);
1762 return 1;
1765 xdiff_clear_find_func(&xecfg);
1766 opt->priv = NULL;
1768 /* NEEDSWORK:
1769 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1770 * which feels mostly useless but sometimes useful. Maybe
1771 * make it another option? For now suppress them.
1773 if (opt->count && count) {
1774 char buf[32];
1775 if (opt->pathname) {
1776 output_color(opt, gs->name, strlen(gs->name),
1777 opt->colors[GREP_COLOR_FILENAME]);
1778 output_sep(opt, ':');
1780 xsnprintf(buf, sizeof(buf), "%u\n", count);
1781 opt->output(opt, buf, strlen(buf));
1782 return 1;
1784 return !!last_hit;
1787 static void clr_hit_marker(struct grep_expr *x)
1789 /* All-hit markers are meaningful only at the very top level
1790 * OR node.
1792 while (1) {
1793 x->hit = 0;
1794 if (x->node != GREP_NODE_OR)
1795 return;
1796 x->u.binary.left->hit = 0;
1797 x = x->u.binary.right;
1801 static int chk_hit_marker(struct grep_expr *x)
1803 /* Top level nodes have hit markers. See if they all are hits */
1804 while (1) {
1805 if (x->node != GREP_NODE_OR)
1806 return x->hit;
1807 if (!x->u.binary.left->hit)
1808 return 0;
1809 x = x->u.binary.right;
1813 int grep_source(struct grep_opt *opt, struct grep_source *gs)
1816 * we do not have to do the two-pass grep when we do not check
1817 * buffer-wide "all-match".
1819 if (!opt->all_match && !opt->no_body_match)
1820 return grep_source_1(opt, gs, 0);
1822 /* Otherwise the toplevel "or" terms hit a bit differently.
1823 * We first clear hit markers from them.
1825 clr_hit_marker(opt->pattern_expression);
1826 opt->body_hit = 0;
1827 grep_source_1(opt, gs, 1);
1829 if (opt->all_match && !chk_hit_marker(opt->pattern_expression))
1830 return 0;
1831 if (opt->no_body_match && opt->body_hit)
1832 return 0;
1834 return grep_source_1(opt, gs, 0);
1837 static void grep_source_init_buf(struct grep_source *gs,
1838 const char *buf,
1839 unsigned long size)
1841 gs->type = GREP_SOURCE_BUF;
1842 gs->name = NULL;
1843 gs->path = NULL;
1844 gs->buf = buf;
1845 gs->size = size;
1846 gs->driver = NULL;
1847 gs->identifier = NULL;
1850 int grep_buffer(struct grep_opt *opt, const char *buf, unsigned long size)
1852 struct grep_source gs;
1853 int r;
1855 grep_source_init_buf(&gs, buf, size);
1857 r = grep_source(opt, &gs);
1859 grep_source_clear(&gs);
1860 return r;
1863 void grep_source_init_file(struct grep_source *gs, const char *name,
1864 const char *path)
1866 gs->type = GREP_SOURCE_FILE;
1867 gs->name = xstrdup_or_null(name);
1868 gs->path = xstrdup_or_null(path);
1869 gs->buf = NULL;
1870 gs->size = 0;
1871 gs->driver = NULL;
1872 gs->identifier = xstrdup(path);
1875 void grep_source_init_oid(struct grep_source *gs, const char *name,
1876 const char *path, const struct object_id *oid,
1877 struct repository *repo)
1879 gs->type = GREP_SOURCE_OID;
1880 gs->name = xstrdup_or_null(name);
1881 gs->path = xstrdup_or_null(path);
1882 gs->buf = NULL;
1883 gs->size = 0;
1884 gs->driver = NULL;
1885 gs->identifier = oiddup(oid);
1886 gs->repo = repo;
1889 void grep_source_clear(struct grep_source *gs)
1891 FREE_AND_NULL(gs->name);
1892 FREE_AND_NULL(gs->path);
1893 FREE_AND_NULL(gs->identifier);
1894 grep_source_clear_data(gs);
1897 void grep_source_clear_data(struct grep_source *gs)
1899 switch (gs->type) {
1900 case GREP_SOURCE_FILE:
1901 case GREP_SOURCE_OID:
1902 /* these types own the buffer */
1903 free((char *)gs->buf);
1904 gs->buf = NULL;
1905 gs->size = 0;
1906 break;
1907 case GREP_SOURCE_BUF:
1908 /* leave user-provided buf intact */
1909 break;
1913 static int grep_source_load_oid(struct grep_source *gs)
1915 enum object_type type;
1917 gs->buf = repo_read_object_file(gs->repo, gs->identifier, &type,
1918 &gs->size);
1919 if (!gs->buf)
1920 return error(_("'%s': unable to read %s"),
1921 gs->name,
1922 oid_to_hex(gs->identifier));
1923 return 0;
1926 static int grep_source_load_file(struct grep_source *gs)
1928 const char *filename = gs->identifier;
1929 struct stat st;
1930 char *data;
1931 size_t size;
1932 int i;
1934 if (lstat(filename, &st) < 0) {
1935 err_ret:
1936 if (errno != ENOENT)
1937 error_errno(_("failed to stat '%s'"), filename);
1938 return -1;
1940 if (!S_ISREG(st.st_mode))
1941 return -1;
1942 size = xsize_t(st.st_size);
1943 i = open(filename, O_RDONLY);
1944 if (i < 0)
1945 goto err_ret;
1946 data = xmallocz(size);
1947 if (st.st_size != read_in_full(i, data, size)) {
1948 error_errno(_("'%s': short read"), filename);
1949 close(i);
1950 free(data);
1951 return -1;
1953 close(i);
1955 gs->buf = data;
1956 gs->size = size;
1957 return 0;
1960 static int grep_source_load(struct grep_source *gs)
1962 if (gs->buf)
1963 return 0;
1965 switch (gs->type) {
1966 case GREP_SOURCE_FILE:
1967 return grep_source_load_file(gs);
1968 case GREP_SOURCE_OID:
1969 return grep_source_load_oid(gs);
1970 case GREP_SOURCE_BUF:
1971 return gs->buf ? 0 : -1;
1973 BUG("invalid grep_source type to load");
1976 void grep_source_load_driver(struct grep_source *gs,
1977 struct index_state *istate)
1979 if (gs->driver)
1980 return;
1982 grep_attr_lock();
1983 if (gs->path)
1984 gs->driver = userdiff_find_by_path(istate, gs->path);
1985 if (!gs->driver)
1986 gs->driver = userdiff_find_by_name("default");
1987 grep_attr_unlock();
1990 static int grep_source_is_binary(struct grep_source *gs,
1991 struct index_state *istate)
1993 grep_source_load_driver(gs, istate);
1994 if (gs->driver->binary != -1)
1995 return gs->driver->binary;
1997 if (!grep_source_load(gs))
1998 return buffer_is_binary(gs->buf, gs->size);
2000 return 0;