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