]> git.ipfire.org Git - thirdparty/git.git/blame - builtin-grep.c
grep: fix exit status if external_grep() punts
[thirdparty/git.git] / builtin-grep.c
CommitLineData
5010cb5f
JH
1/*
2 * Builtin "git grep"
3 *
4 * Copyright (c) 2006 Junio C Hamano
5 */
6#include "cache.h"
7#include "blob.h"
8#include "tree.h"
9#include "commit.h"
10#include "tag.h"
1362671f 11#include "tree-walk.h"
5010cb5f 12#include "builtin.h"
83b5d2f5 13#include "grep.h"
5010cb5f 14
5f7c643a
JK
15#ifndef NO_EXTERNAL_GREP
16#ifdef __unix__
17#define NO_EXTERNAL_GREP 0
18#else
19#define NO_EXTERNAL_GREP 1
20#endif
21#endif
22
e70b9a8b
NTND
23static int builtin_grep;
24
7e8f59d5
RS
25static int grep_config(const char *var, const char *value, void *cb)
26{
27 struct grep_opt *opt = cb;
28
fe3420b6 29 if (!strcmp(var, "color.grep")) {
7e8f59d5
RS
30 opt->color = git_config_colorbool(var, value, -1);
31 return 0;
32 }
fe3420b6 33 if (!strcmp(var, "color.grep.external"))
a94982ef 34 return git_config_string(&(opt->color_external), var, value);
fe3420b6 35 if (!strcmp(var, "color.grep.match")) {
7e8f59d5
RS
36 if (!value)
37 return config_error_nonbool(var);
38 color_parse(value, var, opt->color_match);
39 return 0;
40 }
41 return git_color_default_config(var, value, cb);
42}
43
e0eb889f
JH
44/*
45 * git grep pathspecs are somewhat different from diff-tree pathspecs;
46 * pathname wildcards are allowed.
47 */
1362671f 48static int pathspec_matches(const char **paths, const char *name)
5010cb5f 49{
e0eb889f 50 int namelen, i;
1362671f 51 if (!paths || !*paths)
5010cb5f
JH
52 return 1;
53 namelen = strlen(name);
1362671f
JH
54 for (i = 0; paths[i]; i++) {
55 const char *match = paths[i];
56 int matchlen = strlen(match);
1e3d90e0 57 const char *cp, *meta;
e0eb889f 58
bb9e15a8
UKK
59 if (!matchlen ||
60 ((matchlen <= namelen) &&
61 !strncmp(name, match, matchlen) &&
62 (match[matchlen-1] == '/' ||
63 name[matchlen] == '\0' || name[matchlen] == '/')))
e0eb889f
JH
64 return 1;
65 if (!fnmatch(match, name, 0))
66 return 1;
67 if (name[namelen-1] != '/')
5010cb5f 68 continue;
e0eb889f 69
1e3d90e0 70 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
71 * descending into.
72 *
73 * Find the longest leading directory name that does
74 * not have metacharacter in the pathspec; the name
75 * we are looking at must overlap with that directory.
5010cb5f 76 */
1e3d90e0 77 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 78 char ch = *cp;
1e3d90e0
JH
79 if (ch == '*' || ch == '[' || ch == '?') {
80 meta = cp;
5010cb5f 81 break;
1e3d90e0 82 }
e0eb889f 83 }
1e3d90e0
JH
84 if (!meta)
85 meta = cp; /* fully literal */
86
87 if (namelen <= meta - match) {
e0eb889f
JH
88 /* Looking at "Documentation/" and
89 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
90 * "Documentation/diff*.txt". The name we
91 * have should match prefix.
e0eb889f
JH
92 */
93 if (!memcmp(match, name, namelen))
94 return 1;
1e3d90e0 95 continue;
e0eb889f 96 }
1e3d90e0
JH
97
98 if (meta - match < namelen) {
e0eb889f 99 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
100 * the pattern says "Documentation/h*";
101 * match up to "Do.../h"; this avoids descending
102 * into "Documentation/technical/".
e0eb889f 103 */
1e3d90e0 104 if (!memcmp(match, name, meta - match))
e0eb889f 105 return 1;
1e3d90e0 106 continue;
e0eb889f 107 }
5010cb5f
JH
108 }
109 return 0;
110}
111
0d042fec 112static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
5010cb5f
JH
113{
114 unsigned long size;
115 char *data;
21666f1a 116 enum object_type type;
0d042fec 117 char *to_free = NULL;
5010cb5f 118 int hit;
0d042fec 119
21666f1a 120 data = read_sha1_file(sha1, &type, &size);
5010cb5f
JH
121 if (!data) {
122 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
123 return 0;
124 }
0d042fec
JH
125 if (opt->relative && opt->prefix_length) {
126 static char name_buf[PATH_MAX];
127 char *cp;
128 int name_len = strlen(name) - opt->prefix_length + 1;
129
130 if (!tree_name_len)
131 name += opt->prefix_length;
132 else {
133 if (ARRAY_SIZE(name_buf) <= name_len)
134 cp = to_free = xmalloc(name_len);
135 else
136 cp = name_buf;
137 memcpy(cp, name, tree_name_len);
138 strcpy(cp + tree_name_len,
139 name + tree_name_len + opt->prefix_length);
140 name = cp;
141 }
142 }
5010cb5f
JH
143 hit = grep_buffer(opt, name, data, size);
144 free(data);
0d042fec 145 free(to_free);
5010cb5f
JH
146 return hit;
147}
148
149static int grep_file(struct grep_opt *opt, const char *filename)
150{
151 struct stat st;
152 int i;
153 char *data;
dc49cd76
SP
154 size_t sz;
155
5010cb5f
JH
156 if (lstat(filename, &st) < 0) {
157 err_ret:
158 if (errno != ENOENT)
159 error("'%s': %s", filename, strerror(errno));
160 return 0;
161 }
162 if (!st.st_size)
163 return 0; /* empty file -- no grep hit */
164 if (!S_ISREG(st.st_mode))
165 return 0;
dc49cd76 166 sz = xsize_t(st.st_size);
5010cb5f
JH
167 i = open(filename, O_RDONLY);
168 if (i < 0)
169 goto err_ret;
dc49cd76
SP
170 data = xmalloc(sz + 1);
171 if (st.st_size != read_in_full(i, data, sz)) {
5010cb5f
JH
172 error("'%s': short read %s", filename, strerror(errno));
173 close(i);
174 free(data);
175 return 0;
176 }
177 close(i);
0d042fec
JH
178 if (opt->relative && opt->prefix_length)
179 filename += opt->prefix_length;
dc49cd76 180 i = grep_buffer(opt, filename, data, sz);
5010cb5f
JH
181 free(data);
182 return i;
183}
184
5f7c643a 185#if !NO_EXTERNAL_GREP
1e2398d7
LT
186static int exec_grep(int argc, const char **argv)
187{
188 pid_t pid;
189 int status;
190
191 argv[argc] = NULL;
192 pid = fork();
193 if (pid < 0)
194 return pid;
195 if (!pid) {
196 execvp("grep", (char **) argv);
197 exit(255);
198 }
199 while (waitpid(pid, &status, 0) < 0) {
200 if (errno == EINTR)
201 continue;
202 return -1;
203 }
204 if (WIFEXITED(status)) {
205 if (!WEXITSTATUS(status))
206 return 1;
207 return 0;
208 }
209 return -1;
210}
211
212#define MAXARGS 1000
ffa0a7ab
JH
213#define ARGBUF 4096
214#define push_arg(a) do { \
215 if (nr < MAXARGS) argv[nr++] = (a); \
216 else die("maximum number of args exceeded"); \
217 } while (0)
1e2398d7 218
d99ebf08
JH
219/*
220 * If you send a singleton filename to grep, it does not give
221 * the name of the file. GNU grep has "-H" but we would want
222 * that behaviour in a portable way.
223 *
224 * So we keep two pathnames in argv buffer unsent to grep in
225 * the main loop if we need to do more than one grep.
226 */
227static int flush_grep(struct grep_opt *opt,
228 int argc, int arg0, const char **argv, int *kept)
229{
230 int status;
231 int count = argc - arg0;
232 const char *kept_0 = NULL;
233
234 if (count <= 2) {
235 /*
236 * Because we keep at least 2 paths in the call from
237 * the main loop (i.e. kept != NULL), and MAXARGS is
238 * far greater than 2, this usually is a call to
239 * conclude the grep. However, the user could attempt
240 * to overflow the argv buffer by giving too many
241 * options to leave very small number of real
242 * arguments even for the call in the main loop.
243 */
244 if (kept)
245 die("insanely many options to grep");
246
247 /*
248 * If we have two or more paths, we do not have to do
249 * anything special, but we need to push /dev/null to
250 * get "-H" behaviour of GNU grep portably but when we
251 * are not doing "-l" nor "-L" nor "-c".
252 */
253 if (count == 1 &&
254 !opt->name_only &&
255 !opt->unmatch_name_only &&
256 !opt->count) {
257 argv[argc++] = "/dev/null";
258 argv[argc] = NULL;
259 }
260 }
261
262 else if (kept) {
263 /*
264 * Called because we found many paths and haven't finished
265 * iterating over the cache yet. We keep two paths
266 * for the concluding call. argv[argc-2] and argv[argc-1]
267 * has the last two paths, so save the first one away,
268 * replace it with NULL while sending the list to grep,
269 * and recover them after we are done.
270 */
271 *kept = 2;
272 kept_0 = argv[argc-2];
273 argv[argc-2] = NULL;
274 argc -= 2;
275 }
276
277 status = exec_grep(argc, argv);
278
279 if (kept_0) {
280 /*
281 * Then recover them. Now the last arg is beyond the
282 * terminating NULL which is at argc, and the second
283 * from the last is what we saved away in kept_0
284 */
285 argv[arg0++] = kept_0;
286 argv[arg0] = argv[argc+1];
287 }
288 return status;
289}
290
a94982ef
RS
291static void grep_add_color(struct strbuf *sb, const char *escape_seq)
292{
293 size_t orig_len = sb->len;
294
295 while (*escape_seq) {
296 if (*escape_seq == 'm')
297 strbuf_addch(sb, ';');
298 else if (*escape_seq != '\033' && *escape_seq != '[')
299 strbuf_addch(sb, *escape_seq);
300 escape_seq++;
301 }
302 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
303 strbuf_setlen(sb, sb->len - 1);
304}
305
1e2398d7
LT
306static int external_grep(struct grep_opt *opt, const char **paths, int cached)
307{
fcfe34b5 308 int i, nr, argc, hit, len, status;
1e2398d7 309 const char *argv[MAXARGS+1];
ffa0a7ab
JH
310 char randarg[ARGBUF];
311 char *argptr = randarg;
1e2398d7
LT
312 struct grep_pat *p;
313
0d042fec 314 if (opt->extended || (opt->relative && opt->prefix_length))
79d3696c 315 return -1;
ffa0a7ab
JH
316 len = nr = 0;
317 push_arg("grep");
ffa0a7ab 318 if (opt->fixed)
f6647519 319 push_arg("-F");
ffa0a7ab
JH
320 if (opt->linenum)
321 push_arg("-n");
7977f0ea
LT
322 if (!opt->pathname)
323 push_arg("-h");
ffa0a7ab
JH
324 if (opt->regflags & REG_EXTENDED)
325 push_arg("-E");
3026402c
RF
326 if (opt->regflags & REG_ICASE)
327 push_arg("-i");
bc395643
JH
328 if (opt->binary == GREP_BINARY_NOMATCH)
329 push_arg("-I");
1e2398d7 330 if (opt->word_regexp)
ffa0a7ab 331 push_arg("-w");
1e2398d7 332 if (opt->name_only)
ffa0a7ab
JH
333 push_arg("-l");
334 if (opt->unmatch_name_only)
335 push_arg("-L");
83caecca
RZ
336 if (opt->null_following_name)
337 /* in GNU grep git's "-z" translates to "-Z" */
338 push_arg("-Z");
ffa0a7ab
JH
339 if (opt->count)
340 push_arg("-c");
341 if (opt->post_context || opt->pre_context) {
342 if (opt->post_context != opt->pre_context) {
343 if (opt->pre_context) {
344 push_arg("-B");
345 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 346 "%u", opt->pre_context) + 1;
ffa0a7ab
JH
347 if (sizeof(randarg) <= len)
348 die("maximum length of args exceeded");
349 push_arg(argptr);
350 argptr += len;
351 }
352 if (opt->post_context) {
353 push_arg("-A");
354 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 355 "%u", opt->post_context) + 1;
ffa0a7ab
JH
356 if (sizeof(randarg) <= len)
357 die("maximum length of args exceeded");
358 push_arg(argptr);
359 argptr += len;
360 }
361 }
362 else {
363 push_arg("-C");
364 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 365 "%u", opt->post_context) + 1;
ffa0a7ab
JH
366 if (sizeof(randarg) <= len)
367 die("maximum length of args exceeded");
368 push_arg(argptr);
369 argptr += len;
370 }
371 }
1e2398d7 372 for (p = opt->pattern_list; p; p = p->next) {
ffa0a7ab
JH
373 push_arg("-e");
374 push_arg(p->pattern);
1e2398d7 375 }
a94982ef
RS
376 if (opt->color) {
377 struct strbuf sb = STRBUF_INIT;
378
379 grep_add_color(&sb, opt->color_match);
380 setenv("GREP_COLOR", sb.buf, 1);
381
382 strbuf_reset(&sb);
383 strbuf_addstr(&sb, "mt=");
384 grep_add_color(&sb, opt->color_match);
385 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
386 setenv("GREP_COLORS", sb.buf, 1);
387
388 strbuf_release(&sb);
389
390 if (opt->color_external && strlen(opt->color_external) > 0)
391 push_arg(opt->color_external);
392 }
bbb66c60 393
1e2398d7
LT
394 hit = 0;
395 argc = nr;
396 for (i = 0; i < active_nr; i++) {
397 struct cache_entry *ce = active_cache[i];
fbd01abf 398 char *name;
d99ebf08 399 int kept;
7a51ed66 400 if (!S_ISREG(ce->ce_mode))
1e2398d7
LT
401 continue;
402 if (!pathspec_matches(paths, ce->name))
403 continue;
bbb66c60
LT
404 name = ce->name;
405 if (name[0] == '-') {
406 int len = ce_namelen(ce);
407 name = xmalloc(len + 3);
408 memcpy(name, "./", 2);
409 memcpy(name + 2, ce->name, len + 1);
410 }
411 argv[argc++] = name;
6326cee5
JH
412 if (MAXARGS <= argc) {
413 status = flush_grep(opt, argc, nr, argv, &kept);
414 if (0 < status)
415 hit = 1;
416 argc = nr + kept;
417 }
36f2587f
JH
418 if (ce_stage(ce)) {
419 do {
420 i++;
421 } while (i < active_nr &&
422 !strcmp(ce->name, active_cache[i]->name));
423 i--; /* compensate for loop control */
424 }
1e2398d7 425 }
fcfe34b5 426 if (argc > nr) {
d99ebf08 427 status = flush_grep(opt, argc, nr, argv, NULL);
fcfe34b5
JH
428 if (0 < status)
429 hit = 1;
430 }
431 return hit;
1e2398d7 432}
ff1f9945 433#endif
1e2398d7 434
1362671f 435static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
5010cb5f
JH
436{
437 int hit = 0;
438 int nr;
439 read_cache();
440
5f7c643a 441#if !NO_EXTERNAL_GREP
1e2398d7
LT
442 /*
443 * Use the external "grep" command for the case where
444 * we grep through the checked-out files. It tends to
445 * be a lot more optimized
446 */
e70b9a8b 447 if (!cached && !builtin_grep) {
1e2398d7
LT
448 hit = external_grep(opt, paths, cached);
449 if (hit >= 0)
450 return hit;
929e37d3 451 hit = 0;
1e2398d7
LT
452 }
453#endif
454
5010cb5f
JH
455 for (nr = 0; nr < active_nr; nr++) {
456 struct cache_entry *ce = active_cache[nr];
7a51ed66 457 if (!S_ISREG(ce->ce_mode))
5010cb5f 458 continue;
1362671f 459 if (!pathspec_matches(paths, ce->name))
5010cb5f 460 continue;
57d43466
NTND
461 /*
462 * If CE_VALID is on, we assume worktree file and its cache entry
463 * are identical, even if worktree file has been modified, so use
464 * cache version instead
465 */
466 if (cached || (ce->ce_flags & CE_VALID)) {
36f2587f
JH
467 if (ce_stage(ce))
468 continue;
0d042fec 469 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
36f2587f 470 }
5010cb5f
JH
471 else
472 hit |= grep_file(opt, ce->name);
36f2587f
JH
473 if (ce_stage(ce)) {
474 do {
475 nr++;
476 } while (nr < active_nr &&
477 !strcmp(ce->name, active_cache[nr]->name));
478 nr--; /* compensate for loop control */
479 }
5010cb5f 480 }
b48fb5b6 481 free_grep_patterns(opt);
5010cb5f
JH
482 return hit;
483}
484
1362671f 485static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
486 struct tree_desc *tree,
487 const char *tree_name, const char *base)
488{
5010cb5f
JH
489 int len;
490 int hit = 0;
4c068a98 491 struct name_entry entry;
e0eb889f 492 char *down;
0d042fec 493 int tn_len = strlen(tree_name);
620e2bb9
DP
494 struct strbuf pathbuf;
495
496 strbuf_init(&pathbuf, PATH_MAX + tn_len);
5010cb5f 497
0d042fec 498 if (tn_len) {
620e2bb9
DP
499 strbuf_add(&pathbuf, tree_name, tn_len);
500 strbuf_addch(&pathbuf, ':');
501 tn_len = pathbuf.len;
5010cb5f 502 }
620e2bb9
DP
503 strbuf_addstr(&pathbuf, base);
504 len = pathbuf.len;
5010cb5f 505
4c068a98 506 while (tree_entry(tree, &entry)) {
620e2bb9
DP
507 int te_len = tree_entry_len(entry.path, entry.sha1);
508 pathbuf.len = len;
509 strbuf_add(&pathbuf, entry.path, te_len);
5010cb5f 510
4c068a98 511 if (S_ISDIR(entry.mode))
e0eb889f
JH
512 /* Match "abc/" against pathspec to
513 * decide if we want to descend into "abc"
514 * directory.
515 */
620e2bb9 516 strbuf_addch(&pathbuf, '/');
e0eb889f 517
620e2bb9 518 down = pathbuf.buf + tn_len;
1362671f 519 if (!pathspec_matches(paths, down))
5010cb5f 520 ;
4c068a98 521 else if (S_ISREG(entry.mode))
620e2bb9 522 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
4c068a98 523 else if (S_ISDIR(entry.mode)) {
21666f1a 524 enum object_type type;
5010cb5f
JH
525 struct tree_desc sub;
526 void *data;
6fda5e51
LT
527 unsigned long size;
528
529 data = read_sha1_file(entry.sha1, &type, &size);
5010cb5f
JH
530 if (!data)
531 die("unable to read tree (%s)",
4c068a98 532 sha1_to_hex(entry.sha1));
6fda5e51 533 init_tree_desc(&sub, data, size);
1362671f 534 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
535 free(data);
536 }
5010cb5f 537 }
620e2bb9 538 strbuf_release(&pathbuf);
5010cb5f
JH
539 return hit;
540}
541
1362671f 542static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
543 struct object *obj, const char *name)
544{
1974632c 545 if (obj->type == OBJ_BLOB)
0d042fec 546 return grep_sha1(opt, obj->sha1, name, 0);
1974632c 547 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
548 struct tree_desc tree;
549 void *data;
6fda5e51 550 unsigned long size;
5010cb5f
JH
551 int hit;
552 data = read_object_with_reference(obj->sha1, tree_type,
6fda5e51 553 &size, NULL);
5010cb5f
JH
554 if (!data)
555 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
6fda5e51 556 init_tree_desc(&tree, data, size);
1362671f 557 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
558 free(data);
559 return hit;
560 }
885a86ab 561 die("unable to grep from object of type %s", typename(obj->type));
5010cb5f
JH
562}
563
564static const char builtin_grep_usage[] =
fa4946b5 565"git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
5010cb5f 566
088b084b
JH
567static const char emsg_invalid_context_len[] =
568"%s: invalid context length argument";
569static const char emsg_missing_context_len[] =
570"missing context length argument";
571static const char emsg_missing_argument[] =
572"option requires an argument -%s";
573
a633fca0 574int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 575{
5010cb5f 576 int hit = 0;
5010cb5f 577 int cached = 0;
5acd64ed 578 int seen_dashdash = 0;
5010cb5f 579 struct grep_opt opt;
1f1e895f 580 struct object_array list = { 0, 0, NULL };
1362671f 581 const char **paths = NULL;
5acd64ed 582 int i;
5010cb5f
JH
583
584 memset(&opt, 0, sizeof(opt));
0d042fec
JH
585 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
586 opt.relative = 1;
7977f0ea 587 opt.pathname = 1;
f9b9faf6 588 opt.pattern_tail = &opt.pattern_list;
5010cb5f
JH
589 opt.regflags = REG_NEWLINE;
590
7e8f59d5
RS
591 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
592 opt.color = -1;
593 git_config(grep_config, &opt);
594 if (opt.color == -1)
595 opt.color = git_use_color_default;
596
5010cb5f 597 /*
5acd64ed
JH
598 * If there is no -- then the paths must exist in the working
599 * tree. If there is no explicit pattern specified with -e or
600 * -f, we take the first unrecognized non option to be the
601 * pattern, but then what follows it must be zero or more
602 * valid refs up to the -- (if exists), and then existing
603 * paths. If there is an explicit pattern, then the first
82e5a82f 604 * unrecognized non option is the beginning of the refs list
5acd64ed 605 * that continues up to the -- (if exists), and then paths.
5010cb5f 606 */
5acd64ed 607
1362671f
JH
608 while (1 < argc) {
609 const char *arg = argv[1];
610 argc--; argv++;
611 if (!strcmp("--cached", arg)) {
612 cached = 1;
613 continue;
614 }
e70b9a8b
NTND
615 if (!strcmp("--no-ext-grep", arg)) {
616 builtin_grep = 1;
617 continue;
618 }
b8d0f5a0
JH
619 if (!strcmp("-a", arg) ||
620 !strcmp("--text", arg)) {
621 opt.binary = GREP_BINARY_TEXT;
622 continue;
623 }
1362671f
JH
624 if (!strcmp("-i", arg) ||
625 !strcmp("--ignore-case", arg)) {
626 opt.regflags |= REG_ICASE;
627 continue;
628 }
b8d0f5a0
JH
629 if (!strcmp("-I", arg)) {
630 opt.binary = GREP_BINARY_NOMATCH;
631 continue;
632 }
1362671f
JH
633 if (!strcmp("-v", arg) ||
634 !strcmp("--invert-match", arg)) {
635 opt.invert = 1;
636 continue;
637 }
638 if (!strcmp("-E", arg) ||
639 !strcmp("--extended-regexp", arg)) {
640 opt.regflags |= REG_EXTENDED;
641 continue;
642 }
07ea91d8
JH
643 if (!strcmp("-F", arg) ||
644 !strcmp("--fixed-strings", arg)) {
645 opt.fixed = 1;
646 continue;
647 }
1362671f
JH
648 if (!strcmp("-G", arg) ||
649 !strcmp("--basic-regexp", arg)) {
650 opt.regflags &= ~REG_EXTENDED;
651 continue;
652 }
653 if (!strcmp("-n", arg)) {
654 opt.linenum = 1;
655 continue;
656 }
7977f0ea
LT
657 if (!strcmp("-h", arg)) {
658 opt.pathname = 0;
659 continue;
660 }
1362671f 661 if (!strcmp("-H", arg)) {
7977f0ea 662 opt.pathname = 1;
1362671f
JH
663 continue;
664 }
665 if (!strcmp("-l", arg) ||
2cd5dfd2 666 !strcmp("--name-only", arg) ||
1362671f
JH
667 !strcmp("--files-with-matches", arg)) {
668 opt.name_only = 1;
669 continue;
670 }
e23d2d6b
JH
671 if (!strcmp("-L", arg) ||
672 !strcmp("--files-without-match", arg)) {
673 opt.unmatch_name_only = 1;
674 continue;
675 }
83caecca
RZ
676 if (!strcmp("-z", arg) ||
677 !strcmp("--null", arg)) {
678 opt.null_following_name = 1;
679 continue;
680 }
2c866cf1
JH
681 if (!strcmp("-c", arg) ||
682 !strcmp("--count", arg)) {
683 opt.count = 1;
684 continue;
685 }
7839a25e
JH
686 if (!strcmp("-w", arg) ||
687 !strcmp("--word-regexp", arg)) {
688 opt.word_regexp = 1;
689 continue;
690 }
599065a3
JH
691 if (!prefixcmp(arg, "-A") ||
692 !prefixcmp(arg, "-B") ||
693 !prefixcmp(arg, "-C") ||
f462ebb4 694 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1362671f 695 unsigned num;
f462ebb4
JH
696 const char *scan;
697 switch (arg[1]) {
698 case 'A': case 'B': case 'C':
699 if (!arg[2]) {
700 if (argc <= 1)
088b084b 701 die(emsg_missing_context_len);
f462ebb4
JH
702 scan = *++argv;
703 argc--;
704 }
705 else
706 scan = arg + 2;
707 break;
708 default:
709 scan = arg + 1;
710 break;
711 }
6aead43d 712 if (strtoul_ui(scan, 10, &num))
088b084b 713 die(emsg_invalid_context_len, scan);
1362671f
JH
714 switch (arg[1]) {
715 case 'A':
716 opt.post_context = num;
717 break;
f462ebb4 718 default:
1362671f
JH
719 case 'C':
720 opt.post_context = num;
721 case 'B':
722 opt.pre_context = num;
723 break;
5010cb5f 724 }
1362671f
JH
725 continue;
726 }
aa8c79ad
JH
727 if (!strcmp("-f", arg)) {
728 FILE *patterns;
729 int lno = 0;
730 char buf[1024];
731 if (argc <= 1)
088b084b 732 die(emsg_missing_argument, arg);
aa8c79ad
JH
733 patterns = fopen(argv[1], "r");
734 if (!patterns)
5acd64ed 735 die("'%s': %s", argv[1], strerror(errno));
aa8c79ad
JH
736 while (fgets(buf, sizeof(buf), patterns)) {
737 int len = strlen(buf);
872c930d 738 if (len && buf[len-1] == '\n')
aa8c79ad
JH
739 buf[len-1] = 0;
740 /* ignore empty line like grep does */
741 if (!buf[0])
742 continue;
83b5d2f5
JH
743 append_grep_pattern(&opt, xstrdup(buf),
744 argv[1], ++lno,
745 GREP_PATTERN);
aa8c79ad
JH
746 }
747 fclose(patterns);
748 argv++;
749 argc--;
750 continue;
751 }
79d3696c 752 if (!strcmp("--not", arg)) {
83b5d2f5
JH
753 append_grep_pattern(&opt, arg, "command line", 0,
754 GREP_NOT);
79d3696c
JH
755 continue;
756 }
757 if (!strcmp("--and", arg)) {
83b5d2f5
JH
758 append_grep_pattern(&opt, arg, "command line", 0,
759 GREP_AND);
79d3696c
JH
760 continue;
761 }
762 if (!strcmp("--or", arg))
763 continue; /* no-op */
764 if (!strcmp("(", arg)) {
83b5d2f5
JH
765 append_grep_pattern(&opt, arg, "command line", 0,
766 GREP_OPEN_PAREN);
79d3696c
JH
767 continue;
768 }
769 if (!strcmp(")", arg)) {
83b5d2f5
JH
770 append_grep_pattern(&opt, arg, "command line", 0,
771 GREP_CLOSE_PAREN);
79d3696c
JH
772 continue;
773 }
0ab7befa
JH
774 if (!strcmp("--all-match", arg)) {
775 opt.all_match = 1;
776 continue;
777 }
1362671f
JH
778 if (!strcmp("-e", arg)) {
779 if (1 < argc) {
83b5d2f5
JH
780 append_grep_pattern(&opt, argv[1],
781 "-e option", 0,
782 GREP_PATTERN);
f9b9faf6 783 argv++;
1362671f 784 argc--;
5010cb5f
JH
785 continue;
786 }
088b084b 787 die(emsg_missing_argument, arg);
1362671f 788 }
0d042fec
JH
789 if (!strcmp("--full-name", arg)) {
790 opt.relative = 0;
791 continue;
792 }
7e8f59d5
RS
793 if (!strcmp("--color", arg)) {
794 opt.color = 1;
795 continue;
796 }
797 if (!strcmp("--no-color", arg)) {
798 opt.color = 0;
799 continue;
800 }
5390590f
JH
801 if (!strcmp("--", arg)) {
802 /* later processing wants to have this at argv[1] */
803 argv--;
804 argc++;
5acd64ed 805 break;
5390590f 806 }
5acd64ed 807 if (*arg == '-')
1362671f 808 usage(builtin_grep_usage);
5acd64ed
JH
809
810 /* First unrecognized non-option token */
f9b9faf6 811 if (!opt.pattern_list) {
83b5d2f5
JH
812 append_grep_pattern(&opt, arg, "command line", 0,
813 GREP_PATTERN);
1362671f
JH
814 break;
815 }
816 else {
817 /* We are looking at the first path or rev;
5acd64ed 818 * it is found at argv[1] after leaving the
1362671f
JH
819 * loop.
820 */
821 argc++; argv--;
822 break;
5010cb5f 823 }
5010cb5f 824 }
5acd64ed 825
6e89ec0f
NTND
826 if (opt.color && !opt.color_external)
827 builtin_grep = 1;
f9b9faf6 828 if (!opt.pattern_list)
5010cb5f 829 die("no pattern given.");
07ea91d8
JH
830 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
831 die("cannot mix --fixed-strings and regexp");
83b5d2f5 832 compile_grep_patterns(&opt);
5acd64ed
JH
833
834 /* Check revs and then paths */
835 for (i = 1; i < argc; i++) {
836 const char *arg = argv[i];
1362671f 837 unsigned char sha1[20];
5acd64ed
JH
838 /* Is it a rev? */
839 if (!get_sha1(arg, sha1)) {
840 struct object *object = parse_object(sha1);
5acd64ed
JH
841 if (!object)
842 die("bad object %s", arg);
1f1e895f 843 add_object_array(object, arg, &list);
5acd64ed
JH
844 continue;
845 }
846 if (!strcmp(arg, "--")) {
847 i++;
848 seen_dashdash = 1;
849 }
850 break;
1362671f 851 }
5acd64ed
JH
852
853 /* The rest are paths */
854 if (!seen_dashdash) {
855 int j;
c39c4f47 856 for (j = i; j < argc; j++)
5acd64ed
JH
857 verify_filename(prefix, argv[j]);
858 }
859
0d042fec 860 if (i < argc) {
5acd64ed 861 paths = get_pathspec(prefix, argv + i);
0d042fec
JH
862 if (opt.prefix_length && opt.relative) {
863 /* Make sure we do not get outside of paths */
864 for (i = 0; paths[i]; i++)
865 if (strncmp(prefix, paths[i], opt.prefix_length))
7e44c935 866 die("git grep: cannot generate relative filenames containing '..'");
0d042fec
JH
867 }
868 }
1362671f
JH
869 else if (prefix) {
870 paths = xcalloc(2, sizeof(const char *));
871 paths[0] = prefix;
872 paths[1] = NULL;
873 }
5010cb5f 874
6577f542
NTND
875 if (!list.nr) {
876 if (!cached)
877 setup_work_tree();
1362671f 878 return !grep_cache(&opt, paths, cached);
6577f542 879 }
aa8c79ad 880
5010cb5f 881 if (cached)
aa8c79ad 882 die("both --cached and trees are given.");
5010cb5f 883
1f1e895f 884 for (i = 0; i < list.nr; i++) {
5010cb5f 885 struct object *real_obj;
1f1e895f
LT
886 real_obj = deref_tag(list.objects[i].item, NULL, 0);
887 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
5010cb5f
JH
888 hit = 1;
889 }
b48fb5b6 890 free_grep_patterns(&opt);
5010cb5f
JH
891 return !hit;
892}