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