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;
129 unsigned name_only:1;
130 unsigned unmatch_name_only:1;
132 unsigned word_regexp:1;
134 #define GREP_BINARY_DEFAULT 0
135 #define GREP_BINARY_NOMATCH 1
136 #define GREP_BINARY_TEXT 2
140 unsigned pre_context;
141 unsigned post_context;
144 static void add_pattern(struct grep_opt *opt, const char *pat,
145 const char *origin, int no, enum grep_pat_token t)
147 struct grep_pat *p = xcalloc(1, sizeof(*p));
152 *opt->pattern_tail = p;
153 opt->pattern_tail = &p->next;
157 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
159 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
164 sprintf(where, "In '%s' at %d, ",
167 sprintf(where, "%s, ", p->origin);
170 regerror(err, &p->regexp, errbuf, 1024);
172 die("%s'%s': %s", where, p->pattern, errbuf);
177 static inline void indent(int in)
180 for (i = 0; i < in; i++) putchar(' ');
183 static void dump_pattern_exp(struct grep_expr *x, int in)
188 puts(x->u.atom->pattern);
193 dump_pattern_exp(x->u.unary, in+1);
196 dump_pattern_exp(x->u.binary.left, in+1);
199 dump_pattern_exp(x->u.binary.right, in+1);
202 dump_pattern_exp(x->u.binary.left, in+1);
205 dump_pattern_exp(x->u.binary.right, in+1);
210 static void looking_at(const char *msg, struct grep_pat **list)
212 struct grep_pat *p = *list;
213 fprintf(stderr, "%s: looking at ", msg);
215 fprintf(stderr, "empty\n");
217 fprintf(stderr, "<%s>\n", p->pattern);
220 #define looking_at(a,b) do {} while(0)
223 static struct grep_expr *compile_pattern_expr(struct grep_pat **);
224 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
229 looking_at("atom", list);
233 case GREP_PATTERN: /* atom */
234 x = xcalloc(1, sizeof (struct grep_expr));
235 x->node = GREP_NODE_ATOM;
239 case GREP_OPEN_PAREN:
241 x = compile_pattern_expr(list);
244 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
245 die("unmatched parenthesis");
246 *list = (*list)->next;
253 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
258 looking_at("not", list);
264 die("--not not followed by pattern expression");
266 x = xcalloc(1, sizeof (struct grep_expr));
267 x->node = GREP_NODE_NOT;
268 x->u.unary = compile_pattern_not(list);
270 die("--not followed by non pattern expression");
273 return compile_pattern_atom(list);
277 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
280 struct grep_expr *x, *y, *z;
282 looking_at("and", list);
284 x = compile_pattern_not(list);
286 if (p && p->token == GREP_AND) {
288 die("--and not followed by pattern expression");
290 y = compile_pattern_and(list);
292 die("--and not followed by pattern expression");
293 z = xcalloc(1, sizeof (struct grep_expr));
294 z->node = GREP_NODE_AND;
295 z->u.binary.left = x;
296 z->u.binary.right = y;
302 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
305 struct grep_expr *x, *y, *z;
307 looking_at("or", list);
309 x = compile_pattern_and(list);
311 if (x && p && p->token != GREP_CLOSE_PAREN) {
312 y = compile_pattern_or(list);
314 die("not a pattern expression %s", p->pattern);
315 z = xcalloc(1, sizeof (struct grep_expr));
316 z->node = GREP_NODE_OR;
317 z->u.binary.left = x;
318 z->u.binary.right = y;
324 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
326 looking_at("expr", list);
328 return compile_pattern_or(list);
331 static void compile_patterns(struct grep_opt *opt)
335 /* First compile regexps */
336 for (p = opt->pattern_list; p; p = p->next) {
337 if (p->token == GREP_PATTERN)
338 compile_regexp(p, opt);
346 /* Then bundle them up in an expression.
347 * A classic recursive descent parser would do.
349 p = opt->pattern_list;
350 opt->pattern_expression = compile_pattern_expr(&p);
352 dump_pattern_exp(opt->pattern_expression, 0);
355 die("incomplete pattern expression: %s", p->pattern);
358 static char *end_of_line(char *cp, unsigned long *left)
360 unsigned long l = *left;
361 while (l && *cp != '\n') {
369 static int word_char(char ch)
371 return isalnum(ch) || ch == '_';
374 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
375 const char *name, unsigned lno, char sign)
377 printf("%s%c", name, sign);
379 printf("%d%c", lno, sign);
380 printf("%.*s\n", (int)(eol-bol), bol);
384 * NEEDSWORK: share code with diff.c
386 #define FIRST_FEW_BYTES 8000
387 static int buffer_is_binary(const char *ptr, unsigned long size)
389 if (FIRST_FEW_BYTES < size)
390 size = FIRST_FEW_BYTES;
391 if (memchr(ptr, 0, size))
396 static int fixmatch(const char *pattern, char *line, regmatch_t *match)
398 char *hit = strstr(line, pattern);
400 match->rm_so = match->rm_eo = -1;
404 match->rm_so = hit - line;
405 match->rm_eo = match->rm_so + strlen(pattern);
410 static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol)
414 regmatch_t pmatch[10];
418 regex_t *exp = &p->regexp;
419 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
423 hit = !fixmatch(p->pattern, bol, pmatch);
426 if (hit && opt->word_regexp) {
427 if ((pmatch[0].rm_so < 0) ||
428 (eol - bol) <= pmatch[0].rm_so ||
429 (pmatch[0].rm_eo < 0) ||
430 (eol - bol) < pmatch[0].rm_eo)
431 die("regexp returned nonsense");
433 /* Match beginning must be either beginning of the
434 * line, or at word boundary (i.e. the last char must
435 * not be a word char). Similarly, match end must be
436 * either end of the line, or at word boundary
437 * (i.e. the next char must not be a word char).
439 if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
440 !word_char(bol[pmatch[0].rm_so-1])) &&
441 ((pmatch[0].rm_eo == (eol-bol)) ||
442 !word_char(bol[pmatch[0].rm_eo])) )
447 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
448 /* There could be more than one match on the
449 * line, and the first match might not be
450 * strict word match. But later ones could be!
452 bol = pmatch[0].rm_so + bol + 1;
460 static int match_expr_eval(struct grep_opt *opt,
462 char *bol, char *eol)
466 return match_one_pattern(opt, x->u.atom, bol, eol);
469 return !match_expr_eval(opt, x->u.unary, bol, eol);
471 return (match_expr_eval(opt, x->u.binary.left, bol, eol) &&
472 match_expr_eval(opt, x->u.binary.right, bol, eol));
474 return (match_expr_eval(opt, x->u.binary.left, bol, eol) ||
475 match_expr_eval(opt, x->u.binary.right, bol, eol));
477 die("Unexpected node type (internal error) %d\n", x->node);
480 static int match_expr(struct grep_opt *opt, char *bol, char *eol)
482 struct grep_expr *x = opt->pattern_expression;
483 return match_expr_eval(opt, x, bol, eol);
486 static int match_line(struct grep_opt *opt, char *bol, char *eol)
490 return match_expr(opt, bol, eol);
491 for (p = opt->pattern_list; p; p = p->next) {
492 if (match_one_pattern(opt, p, bol, eol))
498 static int grep_buffer(struct grep_opt *opt, const char *name,
499 char *buf, unsigned long size)
502 unsigned long left = size;
504 struct pre_context_line {
507 } *prev = NULL, *pcl;
508 unsigned last_hit = 0;
509 unsigned last_shown = 0;
510 int binary_match_only = 0;
511 const char *hunk_mark = "";
514 if (buffer_is_binary(buf, size)) {
515 switch (opt->binary) {
516 case GREP_BINARY_DEFAULT:
517 binary_match_only = 1;
519 case GREP_BINARY_NOMATCH:
520 return 0; /* Assume unmatch */
527 if (opt->pre_context)
528 prev = xcalloc(opt->pre_context, sizeof(*prev));
529 if (opt->pre_context || opt->post_context)
536 eol = end_of_line(bol, &left);
540 hit = match_line(opt, bol, eol);
542 /* "grep -v -e foo -e bla" should list lines
543 * that do not have either, so inversion should
548 if (opt->unmatch_name_only) {
555 if (binary_match_only) {
556 printf("Binary file %s matches\n", name);
559 if (opt->name_only) {
560 printf("%s\n", name);
563 /* Hit at this line. If we haven't shown the
564 * pre-context lines, we would need to show them.
565 * When asked to do "count", this still show
566 * the context which is nonsense, but the user
567 * deserves to get that ;-).
569 if (opt->pre_context) {
571 if (opt->pre_context < lno)
572 from = lno - opt->pre_context;
575 if (from <= last_shown)
576 from = last_shown + 1;
577 if (last_shown && from != last_shown + 1)
580 pcl = &prev[lno-from-1];
581 show_line(opt, pcl->bol, pcl->eol,
587 if (last_shown && lno != last_shown + 1)
590 show_line(opt, bol, eol, name, lno, ':');
591 last_shown = last_hit = lno;
594 lno <= last_hit + opt->post_context) {
595 /* If the last hit is within the post context,
596 * we need to show this line.
598 if (last_shown && lno != last_shown + 1)
600 show_line(opt, bol, eol, name, lno, '-');
603 if (opt->pre_context) {
604 memmove(prev+1, prev,
605 (opt->pre_context-1) * sizeof(*prev));
619 if (opt->unmatch_name_only) {
620 /* We did not see any hit, so we want to show this */
621 printf("%s\n", name);
626 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
627 * which feels mostly useless but sometimes useful. Maybe
628 * make it another option? For now suppress them.
630 if (opt->count && count)
631 printf("%s:%u\n", name, count);
635 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
641 data = read_sha1_file(sha1, type, &size);
643 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
646 hit = grep_buffer(opt, name, data, size);
651 static int grep_file(struct grep_opt *opt, const char *filename)
656 if (lstat(filename, &st) < 0) {
659 error("'%s': %s", filename, strerror(errno));
663 return 0; /* empty file -- no grep hit */
664 if (!S_ISREG(st.st_mode))
666 i = open(filename, O_RDONLY);
669 data = xmalloc(st.st_size + 1);
670 if (st.st_size != xread(i, data, st.st_size)) {
671 error("'%s': short read %s", filename, strerror(errno));
677 i = grep_buffer(opt, filename, data, st.st_size);
682 static int exec_grep(int argc, const char **argv)
692 execvp("grep", (char **) argv);
695 while (waitpid(pid, &status, 0) < 0) {
700 if (WIFEXITED(status)) {
701 if (!WEXITSTATUS(status))
710 #define push_arg(a) do { \
711 if (nr < MAXARGS) argv[nr++] = (a); \
712 else die("maximum number of args exceeded"); \
715 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
717 int i, nr, argc, hit, len, status;
718 const char *argv[MAXARGS+1];
719 char randarg[ARGBUF];
720 char *argptr = randarg;
731 if (opt->regflags & REG_EXTENDED)
733 if (opt->regflags & REG_ICASE)
735 if (opt->word_regexp)
739 if (opt->unmatch_name_only)
743 if (opt->post_context || opt->pre_context) {
744 if (opt->post_context != opt->pre_context) {
745 if (opt->pre_context) {
747 len += snprintf(argptr, sizeof(randarg)-len,
748 "%u", opt->pre_context);
749 if (sizeof(randarg) <= len)
750 die("maximum length of args exceeded");
754 if (opt->post_context) {
756 len += snprintf(argptr, sizeof(randarg)-len,
757 "%u", opt->post_context);
758 if (sizeof(randarg) <= len)
759 die("maximum length of args exceeded");
766 len += snprintf(argptr, sizeof(randarg)-len,
767 "%u", opt->post_context);
768 if (sizeof(randarg) <= len)
769 die("maximum length of args exceeded");
774 for (p = opt->pattern_list; p; p = p->next) {
776 push_arg(p->pattern);
780 * To make sure we get the header printed out when we want it,
781 * add /dev/null to the paths to grep. This is unnecessary
782 * (and wrong) with "-l" or "-L", which always print out the
785 * GNU grep has "-H", but this is portable.
787 if (!opt->name_only && !opt->unmatch_name_only)
788 push_arg("/dev/null");
792 for (i = 0; i < active_nr; i++) {
793 struct cache_entry *ce = active_cache[i];
795 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
797 if (!pathspec_matches(paths, ce->name))
800 if (name[0] == '-') {
801 int len = ce_namelen(ce);
802 name = xmalloc(len + 3);
803 memcpy(name, "./", 2);
804 memcpy(name + 2, ce->name, len + 1);
809 status = exec_grep(argc, argv);
815 status = exec_grep(argc, argv);
822 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
830 * Use the external "grep" command for the case where
831 * we grep through the checked-out files. It tends to
832 * be a lot more optimized
835 hit = external_grep(opt, paths, cached);
841 for (nr = 0; nr < active_nr; nr++) {
842 struct cache_entry *ce = active_cache[nr];
843 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
845 if (!pathspec_matches(paths, ce->name))
848 hit |= grep_sha1(opt, ce->sha1, ce->name);
850 hit |= grep_file(opt, ce->name);
855 static int grep_tree(struct grep_opt *opt, const char **paths,
856 struct tree_desc *tree,
857 const char *tree_name, const char *base)
861 struct name_entry entry;
863 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
866 int offset = sprintf(path_buf, "%s:", tree_name);
867 down = path_buf + offset;
874 len = strlen(path_buf);
876 while (tree_entry(tree, &entry)) {
877 strcpy(path_buf + len, entry.path);
879 if (S_ISDIR(entry.mode))
880 /* Match "abc/" against pathspec to
881 * decide if we want to descend into "abc"
884 strcpy(path_buf + len + entry.pathlen, "/");
886 if (!pathspec_matches(paths, down))
888 else if (S_ISREG(entry.mode))
889 hit |= grep_sha1(opt, entry.sha1, path_buf);
890 else if (S_ISDIR(entry.mode)) {
892 struct tree_desc sub;
894 data = read_sha1_file(entry.sha1, type, &sub.size);
896 die("unable to read tree (%s)",
897 sha1_to_hex(entry.sha1));
899 hit |= grep_tree(opt, paths, &sub, tree_name, down);
906 static int grep_object(struct grep_opt *opt, const char **paths,
907 struct object *obj, const char *name)
909 if (obj->type == OBJ_BLOB)
910 return grep_sha1(opt, obj->sha1, name);
911 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
912 struct tree_desc tree;
915 data = read_object_with_reference(obj->sha1, tree_type,
918 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
920 hit = grep_tree(opt, paths, &tree, name, "");
924 die("unable to grep from object of type %s", typename(obj->type));
927 static const char builtin_grep_usage[] =
928 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
930 static const char emsg_invalid_context_len[] =
931 "%s: invalid context length argument";
932 static const char emsg_missing_context_len[] =
933 "missing context length argument";
934 static const char emsg_missing_argument[] =
935 "option requires an argument -%s";
937 int cmd_grep(int argc, const char **argv, const char *prefix)
941 int seen_dashdash = 0;
943 struct object_array list = { 0, 0, NULL };
944 const char **paths = NULL;
947 memset(&opt, 0, sizeof(opt));
948 opt.pattern_tail = &opt.pattern_list;
949 opt.regflags = REG_NEWLINE;
952 * If there is no -- then the paths must exist in the working
953 * tree. If there is no explicit pattern specified with -e or
954 * -f, we take the first unrecognized non option to be the
955 * pattern, but then what follows it must be zero or more
956 * valid refs up to the -- (if exists), and then existing
957 * paths. If there is an explicit pattern, then the first
958 * unrecognized non option is the beginning of the refs list
959 * that continues up to the -- (if exists), and then paths.
963 const char *arg = argv[1];
965 if (!strcmp("--cached", arg)) {
969 if (!strcmp("-a", arg) ||
970 !strcmp("--text", arg)) {
971 opt.binary = GREP_BINARY_TEXT;
974 if (!strcmp("-i", arg) ||
975 !strcmp("--ignore-case", arg)) {
976 opt.regflags |= REG_ICASE;
979 if (!strcmp("-I", arg)) {
980 opt.binary = GREP_BINARY_NOMATCH;
983 if (!strcmp("-v", arg) ||
984 !strcmp("--invert-match", arg)) {
988 if (!strcmp("-E", arg) ||
989 !strcmp("--extended-regexp", arg)) {
990 opt.regflags |= REG_EXTENDED;
993 if (!strcmp("-F", arg) ||
994 !strcmp("--fixed-strings", arg)) {
998 if (!strcmp("-G", arg) ||
999 !strcmp("--basic-regexp", arg)) {
1000 opt.regflags &= ~REG_EXTENDED;
1003 if (!strcmp("-n", arg)) {
1007 if (!strcmp("-H", arg)) {
1008 /* We always show the pathname, so this
1013 if (!strcmp("-l", arg) ||
1014 !strcmp("--files-with-matches", arg)) {
1018 if (!strcmp("-L", arg) ||
1019 !strcmp("--files-without-match", arg)) {
1020 opt.unmatch_name_only = 1;
1023 if (!strcmp("-c", arg) ||
1024 !strcmp("--count", arg)) {
1028 if (!strcmp("-w", arg) ||
1029 !strcmp("--word-regexp", arg)) {
1030 opt.word_regexp = 1;
1033 if (!strncmp("-A", arg, 2) ||
1034 !strncmp("-B", arg, 2) ||
1035 !strncmp("-C", arg, 2) ||
1036 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1040 case 'A': case 'B': case 'C':
1043 die(emsg_missing_context_len);
1054 if (sscanf(scan, "%u", &num) != 1)
1055 die(emsg_invalid_context_len, scan);
1058 opt.post_context = num;
1062 opt.post_context = num;
1064 opt.pre_context = num;
1069 if (!strcmp("-f", arg)) {
1074 die(emsg_missing_argument, arg);
1075 patterns = fopen(argv[1], "r");
1077 die("'%s': %s", argv[1], strerror(errno));
1078 while (fgets(buf, sizeof(buf), patterns)) {
1079 int len = strlen(buf);
1080 if (buf[len-1] == '\n')
1082 /* ignore empty line like grep does */
1085 add_pattern(&opt, strdup(buf), argv[1], ++lno,
1093 if (!strcmp("--not", arg)) {
1094 add_pattern(&opt, arg, "command line", 0, GREP_NOT);
1097 if (!strcmp("--and", arg)) {
1098 add_pattern(&opt, arg, "command line", 0, GREP_AND);
1101 if (!strcmp("--or", arg))
1102 continue; /* no-op */
1103 if (!strcmp("(", arg)) {
1104 add_pattern(&opt, arg, "command line", 0, GREP_OPEN_PAREN);
1107 if (!strcmp(")", arg)) {
1108 add_pattern(&opt, arg, "command line", 0, GREP_CLOSE_PAREN);
1111 if (!strcmp("-e", arg)) {
1113 add_pattern(&opt, argv[1], "-e option", 0,
1119 die(emsg_missing_argument, arg);
1121 if (!strcmp("--", arg)) {
1122 /* later processing wants to have this at argv[1] */
1128 usage(builtin_grep_usage);
1130 /* First unrecognized non-option token */
1131 if (!opt.pattern_list) {
1132 add_pattern(&opt, arg, "command line", 0,
1137 /* We are looking at the first path or rev;
1138 * it is found at argv[1] after leaving the
1146 if (!opt.pattern_list)
1147 die("no pattern given.");
1148 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1149 die("cannot mix --fixed-strings and regexp");
1151 compile_patterns(&opt);
1153 /* Check revs and then paths */
1154 for (i = 1; i < argc; i++) {
1155 const char *arg = argv[i];
1156 unsigned char sha1[20];
1158 if (!get_sha1(arg, sha1)) {
1159 struct object *object = parse_object(sha1);
1161 die("bad object %s", arg);
1162 add_object_array(object, arg, &list);
1165 if (!strcmp(arg, "--")) {
1172 /* The rest are paths */
1173 if (!seen_dashdash) {
1175 for (j = i; j < argc; j++)
1176 verify_filename(prefix, argv[j]);
1180 paths = get_pathspec(prefix, argv + i);
1182 paths = xcalloc(2, sizeof(const char *));
1188 return !grep_cache(&opt, paths, cached);
1191 die("both --cached and trees are given.");
1193 for (i = 0; i < list.nr; i++) {
1194 struct object *real_obj;
1195 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1196 if (grep_object(&opt, paths, real_obj, list.objects[i].name))