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
142 unsigned pre_context;
143 unsigned post_context;
146 static void add_pattern(struct grep_opt *opt, const char *pat,
147 const char *origin, int no, enum grep_pat_token t)
149 struct grep_pat *p = xcalloc(1, sizeof(*p));
154 *opt->pattern_tail = p;
155 opt->pattern_tail = &p->next;
159 static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
161 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
166 sprintf(where, "In '%s' at %d, ",
169 sprintf(where, "%s, ", p->origin);
172 regerror(err, &p->regexp, errbuf, 1024);
174 die("%s'%s': %s", where, p->pattern, errbuf);
178 static struct grep_expr *compile_pattern_expr(struct grep_pat **);
179 static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
186 case GREP_PATTERN: /* atom */
187 x = xcalloc(1, sizeof (struct grep_expr));
188 x->node = GREP_NODE_ATOM;
192 case GREP_OPEN_PAREN:
194 x = compile_pattern_expr(list);
197 if (!*list || (*list)->token != GREP_CLOSE_PAREN)
198 die("unmatched parenthesis");
199 *list = (*list)->next;
206 static struct grep_expr *compile_pattern_not(struct grep_pat **list)
215 die("--not not followed by pattern expression");
217 x = xcalloc(1, sizeof (struct grep_expr));
218 x->node = GREP_NODE_NOT;
219 x->u.unary = compile_pattern_not(list);
221 die("--not followed by non pattern expression");
224 return compile_pattern_atom(list);
228 static struct grep_expr *compile_pattern_and(struct grep_pat **list)
231 struct grep_expr *x, *y, *z;
233 x = compile_pattern_not(list);
235 if (p && p->token == GREP_AND) {
237 die("--and not followed by pattern expression");
239 y = compile_pattern_and(list);
241 die("--and not followed by pattern expression");
242 z = xcalloc(1, sizeof (struct grep_expr));
243 z->node = GREP_NODE_AND;
244 z->u.binary.left = x;
245 z->u.binary.right = y;
251 static struct grep_expr *compile_pattern_or(struct grep_pat **list)
254 struct grep_expr *x, *y, *z;
256 x = compile_pattern_and(list);
258 if (x && p && p->token != GREP_CLOSE_PAREN) {
259 y = compile_pattern_or(list);
261 die("not a pattern expression %s", p->pattern);
262 z = xcalloc(1, sizeof (struct grep_expr));
263 z->node = GREP_NODE_OR;
264 z->u.binary.left = x;
265 z->u.binary.right = y;
271 static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
273 return compile_pattern_or(list);
276 static void compile_patterns(struct grep_opt *opt)
280 /* First compile regexps */
281 for (p = opt->pattern_list; p; p = p->next) {
282 if (p->token == GREP_PATTERN)
283 compile_regexp(p, opt);
291 /* Then bundle them up in an expression.
292 * A classic recursive descent parser would do.
294 p = opt->pattern_list;
295 opt->pattern_expression = compile_pattern_expr(&p);
297 die("incomplete pattern expression: %s", p->pattern);
300 static char *end_of_line(char *cp, unsigned long *left)
302 unsigned long l = *left;
303 while (l && *cp != '\n') {
311 static int word_char(char ch)
313 return isalnum(ch) || ch == '_';
316 static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
317 const char *name, unsigned lno, char sign)
319 printf("%s%c", name, sign);
321 printf("%d%c", lno, sign);
322 printf("%.*s\n", (int)(eol-bol), bol);
326 * NEEDSWORK: share code with diff.c
328 #define FIRST_FEW_BYTES 8000
329 static int buffer_is_binary(const char *ptr, unsigned long size)
331 if (FIRST_FEW_BYTES < size)
332 size = FIRST_FEW_BYTES;
333 return !!memchr(ptr, 0, size);
336 static int fixmatch(const char *pattern, char *line, regmatch_t *match)
338 char *hit = strstr(line, pattern);
340 match->rm_so = match->rm_eo = -1;
344 match->rm_so = hit - line;
345 match->rm_eo = match->rm_so + strlen(pattern);
350 static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol)
354 regmatch_t pmatch[10];
358 regex_t *exp = &p->regexp;
359 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
363 hit = !fixmatch(p->pattern, bol, pmatch);
366 if (hit && opt->word_regexp) {
367 if ((pmatch[0].rm_so < 0) ||
368 (eol - bol) <= pmatch[0].rm_so ||
369 (pmatch[0].rm_eo < 0) ||
370 (eol - bol) < pmatch[0].rm_eo)
371 die("regexp returned nonsense");
373 /* Match beginning must be either beginning of the
374 * line, or at word boundary (i.e. the last char must
375 * not be a word char). Similarly, match end must be
376 * either end of the line, or at word boundary
377 * (i.e. the next char must not be a word char).
379 if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
380 !word_char(bol[pmatch[0].rm_so-1])) &&
381 ((pmatch[0].rm_eo == (eol-bol)) ||
382 !word_char(bol[pmatch[0].rm_eo])) )
387 if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
388 /* There could be more than one match on the
389 * line, and the first match might not be
390 * strict word match. But later ones could be!
392 bol = pmatch[0].rm_so + bol + 1;
400 static int match_expr_eval(struct grep_opt *opt,
402 char *bol, char *eol)
406 return match_one_pattern(opt, x->u.atom, bol, eol);
409 return !match_expr_eval(opt, x->u.unary, bol, eol);
411 return (match_expr_eval(opt, x->u.binary.left, bol, eol) &&
412 match_expr_eval(opt, x->u.binary.right, bol, eol));
414 return (match_expr_eval(opt, x->u.binary.left, bol, eol) ||
415 match_expr_eval(opt, x->u.binary.right, bol, eol));
417 die("Unexpected node type (internal error) %d\n", x->node);
420 static int match_expr(struct grep_opt *opt, char *bol, char *eol)
422 struct grep_expr *x = opt->pattern_expression;
423 return match_expr_eval(opt, x, bol, eol);
426 static int match_line(struct grep_opt *opt, char *bol, char *eol)
430 return match_expr(opt, bol, eol);
431 for (p = opt->pattern_list; p; p = p->next) {
432 if (match_one_pattern(opt, p, bol, eol))
438 static int grep_buffer(struct grep_opt *opt, const char *name,
439 char *buf, unsigned long size)
442 unsigned long left = size;
444 struct pre_context_line {
447 } *prev = NULL, *pcl;
448 unsigned last_hit = 0;
449 unsigned last_shown = 0;
450 int binary_match_only = 0;
451 const char *hunk_mark = "";
454 if (buffer_is_binary(buf, size)) {
455 switch (opt->binary) {
456 case GREP_BINARY_DEFAULT:
457 binary_match_only = 1;
459 case GREP_BINARY_NOMATCH:
460 return 0; /* Assume unmatch */
467 if (opt->pre_context)
468 prev = xcalloc(opt->pre_context, sizeof(*prev));
469 if (opt->pre_context || opt->post_context)
476 eol = end_of_line(bol, &left);
480 hit = match_line(opt, bol, eol);
482 /* "grep -v -e foo -e bla" should list lines
483 * that do not have either, so inversion should
488 if (opt->unmatch_name_only) {
495 if (binary_match_only) {
496 printf("Binary file %s matches\n", name);
499 if (opt->name_only) {
500 printf("%s\n", name);
503 /* Hit at this line. If we haven't shown the
504 * pre-context lines, we would need to show them.
505 * When asked to do "count", this still show
506 * the context which is nonsense, but the user
507 * deserves to get that ;-).
509 if (opt->pre_context) {
511 if (opt->pre_context < lno)
512 from = lno - opt->pre_context;
515 if (from <= last_shown)
516 from = last_shown + 1;
517 if (last_shown && from != last_shown + 1)
520 pcl = &prev[lno-from-1];
521 show_line(opt, pcl->bol, pcl->eol,
527 if (last_shown && lno != last_shown + 1)
530 show_line(opt, bol, eol, name, lno, ':');
531 last_shown = last_hit = lno;
534 lno <= last_hit + opt->post_context) {
535 /* If the last hit is within the post context,
536 * we need to show this line.
538 if (last_shown && lno != last_shown + 1)
540 show_line(opt, bol, eol, name, lno, '-');
543 if (opt->pre_context) {
544 memmove(prev+1, prev,
545 (opt->pre_context-1) * sizeof(*prev));
559 if (opt->unmatch_name_only) {
560 /* We did not see any hit, so we want to show this */
561 printf("%s\n", name);
566 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
567 * which feels mostly useless but sometimes useful. Maybe
568 * make it another option? For now suppress them.
570 if (opt->count && count)
571 printf("%s:%u\n", name, count);
575 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
580 char *to_free = NULL;
583 data = read_sha1_file(sha1, type, &size);
585 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
588 if (opt->relative && opt->prefix_length) {
589 static char name_buf[PATH_MAX];
591 int name_len = strlen(name) - opt->prefix_length + 1;
594 name += opt->prefix_length;
596 if (ARRAY_SIZE(name_buf) <= name_len)
597 cp = to_free = xmalloc(name_len);
600 memcpy(cp, name, tree_name_len);
601 strcpy(cp + tree_name_len,
602 name + tree_name_len + opt->prefix_length);
606 hit = grep_buffer(opt, name, data, size);
612 static int grep_file(struct grep_opt *opt, const char *filename)
617 if (lstat(filename, &st) < 0) {
620 error("'%s': %s", filename, strerror(errno));
624 return 0; /* empty file -- no grep hit */
625 if (!S_ISREG(st.st_mode))
627 i = open(filename, O_RDONLY);
630 data = xmalloc(st.st_size + 1);
631 if (st.st_size != xread(i, data, st.st_size)) {
632 error("'%s': short read %s", filename, strerror(errno));
638 if (opt->relative && opt->prefix_length)
639 filename += opt->prefix_length;
640 i = grep_buffer(opt, filename, data, st.st_size);
645 static int exec_grep(int argc, const char **argv)
655 execvp("grep", (char **) argv);
658 while (waitpid(pid, &status, 0) < 0) {
663 if (WIFEXITED(status)) {
664 if (!WEXITSTATUS(status))
673 #define push_arg(a) do { \
674 if (nr < MAXARGS) argv[nr++] = (a); \
675 else die("maximum number of args exceeded"); \
678 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
680 int i, nr, argc, hit, len, status;
681 const char *argv[MAXARGS+1];
682 char randarg[ARGBUF];
683 char *argptr = randarg;
686 if (opt->extended || (opt->relative && opt->prefix_length))
694 if (opt->regflags & REG_EXTENDED)
696 if (opt->regflags & REG_ICASE)
698 if (opt->word_regexp)
702 if (opt->unmatch_name_only)
706 if (opt->post_context || opt->pre_context) {
707 if (opt->post_context != opt->pre_context) {
708 if (opt->pre_context) {
710 len += snprintf(argptr, sizeof(randarg)-len,
711 "%u", opt->pre_context);
712 if (sizeof(randarg) <= len)
713 die("maximum length of args exceeded");
717 if (opt->post_context) {
719 len += snprintf(argptr, sizeof(randarg)-len,
720 "%u", opt->post_context);
721 if (sizeof(randarg) <= len)
722 die("maximum length of args exceeded");
729 len += snprintf(argptr, sizeof(randarg)-len,
730 "%u", opt->post_context);
731 if (sizeof(randarg) <= len)
732 die("maximum length of args exceeded");
737 for (p = opt->pattern_list; p; p = p->next) {
739 push_arg(p->pattern);
743 * To make sure we get the header printed out when we want it,
744 * add /dev/null to the paths to grep. This is unnecessary
745 * (and wrong) with "-l" or "-L", which always print out the
748 * GNU grep has "-H", but this is portable.
750 if (!opt->name_only && !opt->unmatch_name_only)
751 push_arg("/dev/null");
755 for (i = 0; i < active_nr; i++) {
756 struct cache_entry *ce = active_cache[i];
758 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
760 if (!pathspec_matches(paths, ce->name))
763 if (name[0] == '-') {
764 int len = ce_namelen(ce);
765 name = xmalloc(len + 3);
766 memcpy(name, "./", 2);
767 memcpy(name + 2, ce->name, len + 1);
772 status = exec_grep(argc, argv);
778 status = exec_grep(argc, argv);
785 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
793 * Use the external "grep" command for the case where
794 * we grep through the checked-out files. It tends to
795 * be a lot more optimized
798 hit = external_grep(opt, paths, cached);
804 for (nr = 0; nr < active_nr; nr++) {
805 struct cache_entry *ce = active_cache[nr];
806 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
808 if (!pathspec_matches(paths, ce->name))
811 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
813 hit |= grep_file(opt, ce->name);
818 static int grep_tree(struct grep_opt *opt, const char **paths,
819 struct tree_desc *tree,
820 const char *tree_name, const char *base)
824 struct name_entry entry;
826 int tn_len = strlen(tree_name);
827 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
830 tn_len = sprintf(path_buf, "%s:", tree_name);
831 down = path_buf + tn_len;
838 len = strlen(path_buf);
840 while (tree_entry(tree, &entry)) {
841 strcpy(path_buf + len, entry.path);
843 if (S_ISDIR(entry.mode))
844 /* Match "abc/" against pathspec to
845 * decide if we want to descend into "abc"
848 strcpy(path_buf + len + entry.pathlen, "/");
850 if (!pathspec_matches(paths, down))
852 else if (S_ISREG(entry.mode))
853 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
854 else if (S_ISDIR(entry.mode)) {
856 struct tree_desc sub;
858 data = read_sha1_file(entry.sha1, type, &sub.size);
860 die("unable to read tree (%s)",
861 sha1_to_hex(entry.sha1));
863 hit |= grep_tree(opt, paths, &sub, tree_name, down);
870 static int grep_object(struct grep_opt *opt, const char **paths,
871 struct object *obj, const char *name)
873 if (obj->type == OBJ_BLOB)
874 return grep_sha1(opt, obj->sha1, name, 0);
875 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
876 struct tree_desc tree;
879 data = read_object_with_reference(obj->sha1, tree_type,
882 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
884 hit = grep_tree(opt, paths, &tree, name, "");
888 die("unable to grep from object of type %s", typename(obj->type));
891 static const char builtin_grep_usage[] =
892 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
894 static const char emsg_invalid_context_len[] =
895 "%s: invalid context length argument";
896 static const char emsg_missing_context_len[] =
897 "missing context length argument";
898 static const char emsg_missing_argument[] =
899 "option requires an argument -%s";
901 int cmd_grep(int argc, const char **argv, const char *prefix)
905 int seen_dashdash = 0;
907 struct object_array list = { 0, 0, NULL };
908 const char **paths = NULL;
911 memset(&opt, 0, sizeof(opt));
912 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
914 opt.pattern_tail = &opt.pattern_list;
915 opt.regflags = REG_NEWLINE;
918 * If there is no -- then the paths must exist in the working
919 * tree. If there is no explicit pattern specified with -e or
920 * -f, we take the first unrecognized non option to be the
921 * pattern, but then what follows it must be zero or more
922 * valid refs up to the -- (if exists), and then existing
923 * paths. If there is an explicit pattern, then the first
924 * unrecognized non option is the beginning of the refs list
925 * that continues up to the -- (if exists), and then paths.
929 const char *arg = argv[1];
931 if (!strcmp("--cached", arg)) {
935 if (!strcmp("-a", arg) ||
936 !strcmp("--text", arg)) {
937 opt.binary = GREP_BINARY_TEXT;
940 if (!strcmp("-i", arg) ||
941 !strcmp("--ignore-case", arg)) {
942 opt.regflags |= REG_ICASE;
945 if (!strcmp("-I", arg)) {
946 opt.binary = GREP_BINARY_NOMATCH;
949 if (!strcmp("-v", arg) ||
950 !strcmp("--invert-match", arg)) {
954 if (!strcmp("-E", arg) ||
955 !strcmp("--extended-regexp", arg)) {
956 opt.regflags |= REG_EXTENDED;
959 if (!strcmp("-F", arg) ||
960 !strcmp("--fixed-strings", arg)) {
964 if (!strcmp("-G", arg) ||
965 !strcmp("--basic-regexp", arg)) {
966 opt.regflags &= ~REG_EXTENDED;
969 if (!strcmp("-n", arg)) {
973 if (!strcmp("-H", arg)) {
974 /* We always show the pathname, so this
979 if (!strcmp("-l", arg) ||
980 !strcmp("--files-with-matches", arg)) {
984 if (!strcmp("-L", arg) ||
985 !strcmp("--files-without-match", arg)) {
986 opt.unmatch_name_only = 1;
989 if (!strcmp("-c", arg) ||
990 !strcmp("--count", arg)) {
994 if (!strcmp("-w", arg) ||
995 !strcmp("--word-regexp", arg)) {
999 if (!strncmp("-A", arg, 2) ||
1000 !strncmp("-B", arg, 2) ||
1001 !strncmp("-C", arg, 2) ||
1002 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1006 case 'A': case 'B': case 'C':
1009 die(emsg_missing_context_len);
1020 if (sscanf(scan, "%u", &num) != 1)
1021 die(emsg_invalid_context_len, scan);
1024 opt.post_context = num;
1028 opt.post_context = num;
1030 opt.pre_context = num;
1035 if (!strcmp("-f", arg)) {
1040 die(emsg_missing_argument, arg);
1041 patterns = fopen(argv[1], "r");
1043 die("'%s': %s", argv[1], strerror(errno));
1044 while (fgets(buf, sizeof(buf), patterns)) {
1045 int len = strlen(buf);
1046 if (buf[len-1] == '\n')
1048 /* ignore empty line like grep does */
1051 add_pattern(&opt, xstrdup(buf), argv[1], ++lno,
1059 if (!strcmp("--not", arg)) {
1060 add_pattern(&opt, arg, "command line", 0, GREP_NOT);
1063 if (!strcmp("--and", arg)) {
1064 add_pattern(&opt, arg, "command line", 0, GREP_AND);
1067 if (!strcmp("--or", arg))
1068 continue; /* no-op */
1069 if (!strcmp("(", arg)) {
1070 add_pattern(&opt, arg, "command line", 0, GREP_OPEN_PAREN);
1073 if (!strcmp(")", arg)) {
1074 add_pattern(&opt, arg, "command line", 0, GREP_CLOSE_PAREN);
1077 if (!strcmp("-e", arg)) {
1079 add_pattern(&opt, argv[1], "-e option", 0,
1085 die(emsg_missing_argument, arg);
1087 if (!strcmp("--full-name", arg)) {
1091 if (!strcmp("--", arg)) {
1092 /* later processing wants to have this at argv[1] */
1098 usage(builtin_grep_usage);
1100 /* First unrecognized non-option token */
1101 if (!opt.pattern_list) {
1102 add_pattern(&opt, arg, "command line", 0,
1107 /* We are looking at the first path or rev;
1108 * it is found at argv[1] after leaving the
1116 if (!opt.pattern_list)
1117 die("no pattern given.");
1118 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1119 die("cannot mix --fixed-strings and regexp");
1121 compile_patterns(&opt);
1123 /* Check revs and then paths */
1124 for (i = 1; i < argc; i++) {
1125 const char *arg = argv[i];
1126 unsigned char sha1[20];
1128 if (!get_sha1(arg, sha1)) {
1129 struct object *object = parse_object(sha1);
1131 die("bad object %s", arg);
1132 add_object_array(object, arg, &list);
1135 if (!strcmp(arg, "--")) {
1142 /* The rest are paths */
1143 if (!seen_dashdash) {
1145 for (j = i; j < argc; j++)
1146 verify_filename(prefix, argv[j]);
1150 paths = get_pathspec(prefix, argv + i);
1151 if (opt.prefix_length && opt.relative) {
1152 /* Make sure we do not get outside of paths */
1153 for (i = 0; paths[i]; i++)
1154 if (strncmp(prefix, paths[i], opt.prefix_length))
1155 die("git-grep: cannot generate relative filenames containing '..'");
1159 paths = xcalloc(2, sizeof(const char *));
1165 return !grep_cache(&opt, paths, cached);
1168 die("both --cached and trees are given.");
1170 for (i = 0; i < list.nr; i++) {
1171 struct object *real_obj;
1172 real_obj = deref_tag(list.objects[i].item, NULL, 0);
1173 if (grep_object(&opt, paths, real_obj, list.objects[i].name))