4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
18 * git grep pathspecs are somewhat different from diff-tree pathspecs;
19 * pathname wildcards are allowed.
21 static int pathspec_matches(const char **paths, const char *name)
24 if (!paths || !*paths)
26 namelen = strlen(name);
27 for (i = 0; paths[i]; i++) {
28 const char *match = paths[i];
29 int matchlen = strlen(match);
30 const char *cp, *meta;
33 ((matchlen <= namelen) &&
34 !strncmp(name, match, matchlen) &&
35 (match[matchlen-1] == '/' ||
36 name[matchlen] == '\0' || name[matchlen] == '/')))
38 if (!fnmatch(match, name, 0))
40 if (name[namelen-1] != '/')
43 /* We are being asked if the directory ("name") is worth
46 * Find the longest leading directory name that does
47 * not have metacharacter in the pathspec; the name
48 * we are looking at must overlap with that directory.
50 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
52 if (ch == '*' || ch == '[' || ch == '?') {
58 meta = cp; /* fully literal */
60 if (namelen <= meta - match) {
61 /* Looking at "Documentation/" and
62 * the pattern says "Documentation/howto/", or
63 * "Documentation/diff*.txt". The name we
64 * have should match prefix.
66 if (!memcmp(match, name, namelen))
71 if (meta - match < namelen) {
72 /* Looking at "Documentation/howto/" and
73 * the pattern says "Documentation/h*";
74 * match up to "Do.../h"; this avoids descending
75 * into "Documentation/technical/".
77 if (!memcmp(match, name, meta - match))
95 struct grep_pat *next;
98 enum grep_pat_token token;
103 enum grep_expr_node {
111 enum grep_expr_node node;
113 struct grep_pat *atom;
114 struct grep_expr *unary;
116 struct grep_expr *left;
117 struct grep_expr *right;
123 struct grep_pat *pattern_list;
124 struct grep_pat **pattern_tail;
125 struct grep_expr *pattern_expression;
130 unsigned name_only:1;
131 unsigned unmatch_name_only:1;
133 unsigned word_regexp:1;
135 #define GREP_BINARY_DEFAULT 0
136 #define GREP_BINARY_NOMATCH 1
137 #define GREP_BINARY_TEXT 2
143 unsigned pre_context;
144 unsigned post_context;
147 static void add_pattern(struct grep_opt *opt, const char *pat,
148 const char *origin, int no, enum grep_pat_token t)
150 struct grep_pat *p = xcalloc(1, sizeof(*p));
155 *opt->pattern_tail = p;
156 opt->pattern_tail = &p->next;
160 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
162 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
167 sprintf(where, "In '%s' at %d, ",
170 sprintf(where, "%s, ", p->origin);
173 regerror(err, &p->regexp, errbuf, 1024);
175 die("%s'%s': %s", where, p->pattern, errbuf);
179 static struct grep_expr *compile_pattern_expr(struct grep_pat **);
180 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
187 case GREP_PATTERN: /* atom */
188 x = xcalloc(1, sizeof (struct grep_expr));
189 x->node = GREP_NODE_ATOM;
193 case GREP_OPEN_PAREN:
195 x = compile_pattern_expr(list);
198 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
199 die("unmatched parenthesis");
200 *list = (*list)->next;
207 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
216 die("--not not followed by pattern expression");
218 x = xcalloc(1, sizeof (struct grep_expr));
219 x->node = GREP_NODE_NOT;
220 x->u.unary = compile_pattern_not(list);
222 die("--not followed by non pattern expression");
225 return compile_pattern_atom(list);
229 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
232 struct grep_expr *x, *y, *z;
234 x = compile_pattern_not(list);
236 if (p && p->token == GREP_AND) {
238 die("--and not followed by pattern expression");
240 y = compile_pattern_and(list);
242 die("--and not followed by pattern expression");
243 z = xcalloc(1, sizeof (struct grep_expr));
244 z->node = GREP_NODE_AND;
245 z->u.binary.left = x;
246 z->u.binary.right = y;
252 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
255 struct grep_expr *x, *y, *z;
257 x = compile_pattern_and(list);
259 if (x && p && p->token != GREP_CLOSE_PAREN) {
260 y = compile_pattern_or(list);
262 die("not a pattern expression %s", p->pattern);
263 z = xcalloc(1, sizeof (struct grep_expr));
264 z->node = GREP_NODE_OR;
265 z->u.binary.left = x;
266 z->u.binary.right = y;
272 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
274 return compile_pattern_or(list);
277 static void compile_patterns(struct grep_opt *opt)
281 /* First compile regexps */
282 for (p = opt->pattern_list; p; p = p->next) {
283 if (p->token == GREP_PATTERN)
284 compile_regexp(p, opt);
292 /* Then bundle them up in an expression.
293 * A classic recursive descent parser would do.
295 p = opt->pattern_list;
296 opt->pattern_expression = compile_pattern_expr(&p);
298 die("incomplete pattern expression: %s", p->pattern);
301 static char *end_of_line(char *cp, unsigned long *left)
303 unsigned long l = *left;
304 while (l && *cp != '\n') {
312 static int word_char(char ch)
314 return isalnum(ch) || ch == '_';
317 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
318 const char *name, unsigned lno, char sign)
321 printf("%s%c", name, sign);
323 printf("%d%c", lno, sign);
324 printf("%.*s\n", (int)(eol-bol), bol);
328 * NEEDSWORK: share code with diff.c
330 #define FIRST_FEW_BYTES 8000
331 static int buffer_is_binary(const char *ptr, unsigned long size)
333 if (FIRST_FEW_BYTES < size)
334 size = FIRST_FEW_BYTES;
335 return !!memchr(ptr, 0, size);
338 static int fixmatch(const char *pattern, char *line, regmatch_t *match)
340 char *hit = strstr(line, pattern);
342 match->rm_so = match->rm_eo = -1;
346 match->rm_so = hit - line;
347 match->rm_eo = match->rm_so + strlen(pattern);
352 static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol)
356 regmatch_t pmatch[10];
360 regex_t *exp = &p->regexp;
361 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
365 hit = !fixmatch(p->pattern, bol, pmatch);
368 if (hit && opt->word_regexp) {
369 if ((pmatch[0].rm_so < 0) ||
370 (eol - bol) <= pmatch[0].rm_so ||
371 (pmatch[0].rm_eo < 0) ||
372 (eol - bol) < pmatch[0].rm_eo)
373 die("regexp returned nonsense");
375 /* Match beginning must be either beginning of the
376 * line, or at word boundary (i.e. the last char must
377 * not be a word char). Similarly, match end must be
378 * either end of the line, or at word boundary
379 * (i.e. the next char must not be a word char).
381 if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
382 !word_char(bol[pmatch[0].rm_so-1])) &&
383 ((pmatch[0].rm_eo == (eol-bol)) ||
384 !word_char(bol[pmatch[0].rm_eo])) )
389 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
390 /* There could be more than one match on the
391 * line, and the first match might not be
392 * strict word match. But later ones could be!
394 bol = pmatch[0].rm_so + bol + 1;
402 static int match_expr_eval(struct grep_opt *opt,
404 char *bol, char *eol)
408 return match_one_pattern(opt, x->u.atom, bol, eol);
411 return !match_expr_eval(opt, x->u.unary, bol, eol);
413 return (match_expr_eval(opt, x->u.binary.left, bol, eol) &&
414 match_expr_eval(opt, x->u.binary.right, bol, eol));
416 return (match_expr_eval(opt, x->u.binary.left, bol, eol) ||
417 match_expr_eval(opt, x->u.binary.right, bol, eol));
419 die("Unexpected node type (internal error) %d\n", x->node);
422 static int match_expr(struct grep_opt *opt, char *bol, char *eol)
424 struct grep_expr *x = opt->pattern_expression;
425 return match_expr_eval(opt, x, bol, eol);
428 static int match_line(struct grep_opt *opt, char *bol, char *eol)
432 return match_expr(opt, bol, eol);
433 for (p = opt->pattern_list; p; p = p->next) {
434 if (match_one_pattern(opt, p, bol, eol))
440 static int grep_buffer(struct grep_opt *opt, const char *name,
441 char *buf, unsigned long size)
444 unsigned long left = size;
446 struct pre_context_line {
449 } *prev = NULL, *pcl;
450 unsigned last_hit = 0;
451 unsigned last_shown = 0;
452 int binary_match_only = 0;
453 const char *hunk_mark = "";
456 if (buffer_is_binary(buf, size)) {
457 switch (opt->binary) {
458 case GREP_BINARY_DEFAULT:
459 binary_match_only = 1;
461 case GREP_BINARY_NOMATCH:
462 return 0; /* Assume unmatch */
469 if (opt->pre_context)
470 prev = xcalloc(opt->pre_context, sizeof(*prev));
471 if (opt->pre_context || opt->post_context)
478 eol = end_of_line(bol, &left);
482 hit = match_line(opt, bol, eol);
484 /* "grep -v -e foo -e bla" should list lines
485 * that do not have either, so inversion should
490 if (opt->unmatch_name_only) {
497 if (binary_match_only) {
498 printf("Binary file %s matches\n", name);
501 if (opt->name_only) {
502 printf("%s\n", name);
505 /* Hit at this line. If we haven't shown the
506 * pre-context lines, we would need to show them.
507 * When asked to do "count", this still show
508 * the context which is nonsense, but the user
509 * deserves to get that ;-).
511 if (opt->pre_context) {
513 if (opt->pre_context < lno)
514 from = lno - opt->pre_context;
517 if (from <= last_shown)
518 from = last_shown + 1;
519 if (last_shown && from != last_shown + 1)
522 pcl = &prev[lno-from-1];
523 show_line(opt, pcl->bol, pcl->eol,
529 if (last_shown && lno != last_shown + 1)
532 show_line(opt, bol, eol, name, lno, ':');
533 last_shown = last_hit = lno;
536 lno <= last_hit + opt->post_context) {
537 /* If the last hit is within the post context,
538 * we need to show this line.
540 if (last_shown && lno != last_shown + 1)
542 show_line(opt, bol, eol, name, lno, '-');
545 if (opt->pre_context) {
546 memmove(prev+1, prev,
547 (opt->pre_context-1) * sizeof(*prev));
561 if (opt->unmatch_name_only) {
562 /* We did not see any hit, so we want to show this */
563 printf("%s\n", name);
568 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
569 * which feels mostly useless but sometimes useful. Maybe
570 * make it another option? For now suppress them.
572 if (opt->count && count)
573 printf("%s:%u\n", name, count);
577 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
582 char *to_free = NULL;
585 data = read_sha1_file(sha1, type, &size);
587 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
590 if (opt->relative && opt->prefix_length) {
591 static char name_buf[PATH_MAX];
593 int name_len = strlen(name) - opt->prefix_length + 1;
596 name += opt->prefix_length;
598 if (ARRAY_SIZE(name_buf) <= name_len)
599 cp = to_free = xmalloc(name_len);
602 memcpy(cp, name, tree_name_len);
603 strcpy(cp + tree_name_len,
604 name + tree_name_len + opt->prefix_length);
608 hit = grep_buffer(opt, name, data, size);
614 static int grep_file(struct grep_opt *opt, const char *filename)
619 if (lstat(filename, &st) < 0) {
622 error("'%s': %s", filename, strerror(errno));
626 return 0; /* empty file -- no grep hit */
627 if (!S_ISREG(st.st_mode))
629 i = open(filename, O_RDONLY);
632 data = xmalloc(st.st_size + 1);
633 if (st.st_size != xread(i, data, st.st_size)) {
634 error("'%s': short read %s", filename, strerror(errno));
640 if (opt->relative && opt->prefix_length)
641 filename += opt->prefix_length;
642 i = grep_buffer(opt, filename, data, st.st_size);
647 static int exec_grep(int argc, const char **argv)
657 execvp("grep", (char **) argv);
660 while (waitpid(pid, &status, 0) < 0) {
665 if (WIFEXITED(status)) {
666 if (!WEXITSTATUS(status))
675 #define push_arg(a) do { \
676 if (nr < MAXARGS) argv[nr++] = (a); \
677 else die("maximum number of args exceeded"); \
680 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
682 int i, nr, argc, hit, len, status;
683 const char *argv[MAXARGS+1];
684 char randarg[ARGBUF];
685 char *argptr = randarg;
688 if (opt->extended || (opt->relative && opt->prefix_length))
698 if (opt->regflags & REG_EXTENDED)
700 if (opt->regflags & REG_ICASE)
702 if (opt->word_regexp)
706 if (opt->unmatch_name_only)
710 if (opt->post_context || opt->pre_context) {
711 if (opt->post_context != opt->pre_context) {
712 if (opt->pre_context) {
714 len += snprintf(argptr, sizeof(randarg)-len,
715 "%u", opt->pre_context);
716 if (sizeof(randarg) <= len)
717 die("maximum length of args exceeded");
721 if (opt->post_context) {
723 len += snprintf(argptr, sizeof(randarg)-len,
724 "%u", opt->post_context);
725 if (sizeof(randarg) <= len)
726 die("maximum length of args exceeded");
733 len += snprintf(argptr, sizeof(randarg)-len,
734 "%u", opt->post_context);
735 if (sizeof(randarg) <= len)
736 die("maximum length of args exceeded");
741 for (p = opt->pattern_list; p; p = p->next) {
743 push_arg(p->pattern);
747 * To make sure we get the header printed out when we want it,
748 * add /dev/null to the paths to grep. This is unnecessary
749 * (and wrong) with "-l" or "-L", which always print out the
752 * GNU grep has "-H", but this is portable.
754 if (!opt->name_only && !opt->unmatch_name_only)
755 push_arg("/dev/null");
759 for (i = 0; i < active_nr; i++) {
760 struct cache_entry *ce = active_cache[i];
762 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
764 if (!pathspec_matches(paths, ce->name))
767 if (name[0] == '-') {
768 int len = ce_namelen(ce);
769 name = xmalloc(len + 3);
770 memcpy(name, "./", 2);
771 memcpy(name + 2, ce->name, len + 1);
776 status = exec_grep(argc, argv);
782 status = exec_grep(argc, argv);
789 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
797 * Use the external "grep" command for the case where
798 * we grep through the checked-out files. It tends to
799 * be a lot more optimized
802 hit = external_grep(opt, paths, cached);
808 for (nr = 0; nr < active_nr; nr++) {
809 struct cache_entry *ce = active_cache[nr];
810 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
812 if (!pathspec_matches(paths, ce->name))
815 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
817 hit |= grep_file(opt, ce->name);
822 static int grep_tree(struct grep_opt *opt, const char **paths,
823 struct tree_desc *tree,
824 const char *tree_name, const char *base)
828 struct name_entry entry;
830 int tn_len = strlen(tree_name);
831 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
834 tn_len = sprintf(path_buf, "%s:", tree_name);
835 down = path_buf + tn_len;
842 len = strlen(path_buf);
844 while (tree_entry(tree, &entry)) {
845 strcpy(path_buf + len, entry.path);
847 if (S_ISDIR(entry.mode))
848 /* Match "abc/" against pathspec to
849 * decide if we want to descend into "abc"
852 strcpy(path_buf + len + entry.pathlen, "/");
854 if (!pathspec_matches(paths, down))
856 else if (S_ISREG(entry.mode))
857 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
858 else if (S_ISDIR(entry.mode)) {
860 struct tree_desc sub;
862 data = read_sha1_file(entry.sha1, type, &sub.size);
864 die("unable to read tree (%s)",
865 sha1_to_hex(entry.sha1));
867 hit |= grep_tree(opt, paths, &sub, tree_name, down);
874 static int grep_object(struct grep_opt *opt, const char **paths,
875 struct object *obj, const char *name)
877 if (obj->type == OBJ_BLOB)
878 return grep_sha1(opt, obj->sha1, name, 0);
879 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
880 struct tree_desc tree;
883 data = read_object_with_reference(obj->sha1, tree_type,
886 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
888 hit = grep_tree(opt, paths, &tree, name, "");
892 die("unable to grep from object of type %s", typename(obj->type));
895 static const char builtin_grep_usage[] =
896 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
898 static const char emsg_invalid_context_len[] =
899 "%s: invalid context length argument";
900 static const char emsg_missing_context_len[] =
901 "missing context length argument";
902 static const char emsg_missing_argument[] =
903 "option requires an argument -%s";
905 int cmd_grep(int argc, const char **argv, const char *prefix)
909 int seen_dashdash = 0;
911 struct object_array list = { 0, 0, NULL };
912 const char **paths = NULL;
915 memset(&opt, 0, sizeof(opt));
916 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
919 opt.pattern_tail = &opt.pattern_list;
920 opt.regflags = REG_NEWLINE;
923 * If there is no -- then the paths must exist in the working
924 * tree. If there is no explicit pattern specified with -e or
925 * -f, we take the first unrecognized non option to be the
926 * pattern, but then what follows it must be zero or more
927 * valid refs up to the -- (if exists), and then existing
928 * paths. If there is an explicit pattern, then the first
929 * unrecognized non option is the beginning of the refs list
930 * that continues up to the -- (if exists), and then paths.
934 const char *arg = argv[1];
936 if (!strcmp("--cached", arg)) {
940 if (!strcmp("-a", arg) ||
941 !strcmp("--text", arg)) {
942 opt.binary = GREP_BINARY_TEXT;
945 if (!strcmp("-i", arg) ||
946 !strcmp("--ignore-case", arg)) {
947 opt.regflags |= REG_ICASE;
950 if (!strcmp("-I", arg)) {
951 opt.binary = GREP_BINARY_NOMATCH;
954 if (!strcmp("-v", arg) ||
955 !strcmp("--invert-match", arg)) {
959 if (!strcmp("-E", arg) ||
960 !strcmp("--extended-regexp", arg)) {
961 opt.regflags |= REG_EXTENDED;
964 if (!strcmp("-F", arg) ||
965 !strcmp("--fixed-strings", arg)) {
969 if (!strcmp("-G", arg) ||
970 !strcmp("--basic-regexp", arg)) {
971 opt.regflags &= ~REG_EXTENDED;
974 if (!strcmp("-n", arg)) {
978 if (!strcmp("-h", arg)) {
982 if (!strcmp("-H", arg)) {
986 if (!strcmp("-l", arg) ||
987 !strcmp("--files-with-matches", arg)) {
991 if (!strcmp("-L", arg) ||
992 !strcmp("--files-without-match", arg)) {
993 opt.unmatch_name_only = 1;
996 if (!strcmp("-c", arg) ||
997 !strcmp("--count", arg)) {
1001 if (!strcmp("-w", arg) ||
1002 !strcmp("--word-regexp", arg)) {
1003 opt.word_regexp = 1;
1006 if (!strncmp("-A", arg, 2) ||
1007 !strncmp("-B", arg, 2) ||
1008 !strncmp("-C", arg, 2) ||
1009 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1013 case 'A': case 'B': case 'C':
1016 die(emsg_missing_context_len);
1027 if (sscanf(scan, "%u", &num) != 1)
1028 die(emsg_invalid_context_len, scan);
1031 opt.post_context = num;
1035 opt.post_context = num;
1037 opt.pre_context = num;
1042 if (!strcmp("-f", arg)) {
1047 die(emsg_missing_argument, arg);
1048 patterns = fopen(argv[1], "r");
1050 die("'%s': %s", argv[1], strerror(errno));
1051 while (fgets(buf, sizeof(buf), patterns)) {
1052 int len = strlen(buf);
1053 if (buf[len-1] == '\n')
1055 /* ignore empty line like grep does */
1058 add_pattern(&opt, xstrdup(buf), argv[1], ++lno,
1066 if (!strcmp("--not", arg)) {
1067 add_pattern(&opt, arg, "command line", 0, GREP_NOT);
1070 if (!strcmp("--and", arg)) {
1071 add_pattern(&opt, arg, "command line", 0, GREP_AND);
1074 if (!strcmp("--or", arg))
1075 continue; /* no-op */
1076 if (!strcmp("(", arg)) {
1077 add_pattern(&opt, arg, "command line", 0, GREP_OPEN_PAREN);
1080 if (!strcmp(")", arg)) {
1081 add_pattern(&opt, arg, "command line", 0, GREP_CLOSE_PAREN);
1084 if (!strcmp("-e", arg)) {
1086 add_pattern(&opt, argv[1], "-e option", 0,
1092 die(emsg_missing_argument, arg);
1094 if (!strcmp("--full-name", arg)) {
1098 if (!strcmp("--", arg)) {
1099 /* later processing wants to have this at argv[1] */
1105 usage(builtin_grep_usage);
1107 /* First unrecognized non-option token */
1108 if (!opt.pattern_list) {
1109 add_pattern(&opt, arg, "command line", 0,
1114 /* We are looking at the first path or rev;
1115 * it is found at argv[1] after leaving the
1123 if (!opt.pattern_list)
1124 die("no pattern given.");
1125 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1126 die("cannot mix --fixed-strings and regexp");
1128 compile_patterns(&opt);
1130 /* Check revs and then paths */
1131 for (i = 1; i < argc; i++) {
1132 const char *arg = argv[i];
1133 unsigned char sha1[20];
1135 if (!get_sha1(arg, sha1)) {
1136 struct object *object = parse_object(sha1);
1138 die("bad object %s", arg);
1139 add_object_array(object, arg, &list);
1142 if (!strcmp(arg, "--")) {
1149 /* The rest are paths */
1150 if (!seen_dashdash) {
1152 for (j = i; j < argc; j++)
1153 verify_filename(prefix, argv[j]);
1157 paths = get_pathspec(prefix, argv + i);
1158 if (opt.prefix_length && opt.relative) {
1159 /* Make sure we do not get outside of paths */
1160 for (i = 0; paths[i]; i++)
1161 if (strncmp(prefix, paths[i], opt.prefix_length))
1162 die("git-grep: cannot generate relative filenames containing '..'");
1166 paths = xcalloc(2, sizeof(const char *));
1172 return !grep_cache(&opt, paths, cached);
1175 die("both --cached and trees are given.");
1177 for (i = 0; i < list.nr; i++) {
1178 struct object *real_obj;
1179 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1180 if (grep_object(&opt, paths, real_obj, list.objects[i].name))