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