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