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