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