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