t9200: Re-code non-ascii path test in UTF-8
[git/jnareb-git.git] / builtin-grep.c
blob2bfbdb71407dcd0ddfe970f6a614158d954cd4c0
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"
16 * git grep pathspecs are somewhat different from diff-tree pathspecs;
17 * pathname wildcards are allowed.
19 static int pathspec_matches(const char **paths, const char *name)
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;
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;
41 /* We are being asked if the directory ("name") is worth
42 * descending into.
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.
48 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
49 char ch = *cp;
50 if (ch == '*' || ch == '[' || ch == '?') {
51 meta = cp;
52 break;
55 if (!meta)
56 meta = cp; /* fully literal */
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.
64 if (!memcmp(match, name, namelen))
65 return 1;
66 continue;
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/".
75 if (!memcmp(match, name, meta - match))
76 return 1;
77 continue;
80 return 0;
83 static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
85 unsigned long size;
86 char *data;
87 char type[20];
88 char *to_free = NULL;
89 int hit;
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;
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;
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;
114 hit = grep_buffer(opt, name, data, size);
115 free(data);
116 free(to_free);
117 return hit;
120 static int grep_file(struct grep_opt *opt, const char *filename)
122 struct stat st;
123 int i;
124 char *data;
125 if (lstat(filename, &st) < 0) {
126 err_ret:
127 if (errno != ENOENT)
128 error("'%s': %s", filename, strerror(errno));
129 return 0;
131 if (!st.st_size)
132 return 0; /* empty file -- no grep hit */
133 if (!S_ISREG(st.st_mode))
134 return 0;
135 i = open(filename, O_RDONLY);
136 if (i < 0)
137 goto err_ret;
138 data = xmalloc(st.st_size + 1);
139 if (st.st_size != read_in_full(i, data, st.st_size)) {
140 error("'%s': short read %s", filename, strerror(errno));
141 close(i);
142 free(data);
143 return 0;
145 close(i);
146 if (opt->relative && opt->prefix_length)
147 filename += opt->prefix_length;
148 i = grep_buffer(opt, filename, data, st.st_size);
149 free(data);
150 return i;
153 static int exec_grep(int argc, const char **argv)
155 pid_t pid;
156 int status;
158 argv[argc] = NULL;
159 pid = fork();
160 if (pid < 0)
161 return pid;
162 if (!pid) {
163 execvp("grep", (char **) argv);
164 exit(255);
166 while (waitpid(pid, &status, 0) < 0) {
167 if (errno == EINTR)
168 continue;
169 return -1;
171 if (WIFEXITED(status)) {
172 if (!WEXITSTATUS(status))
173 return 1;
174 return 0;
176 return -1;
179 #define MAXARGS 1000
180 #define ARGBUF 4096
181 #define push_arg(a) do { \
182 if (nr < MAXARGS) argv[nr++] = (a); \
183 else die("maximum number of args exceeded"); \
184 } while (0)
186 static int external_grep(struct grep_opt *opt, const char **paths, int cached)
188 int i, nr, argc, hit, len, status;
189 const char *argv[MAXARGS+1];
190 char randarg[ARGBUF];
191 char *argptr = randarg;
192 struct grep_pat *p;
194 if (opt->extended || (opt->relative && opt->prefix_length))
195 return -1;
196 len = nr = 0;
197 push_arg("grep");
198 if (opt->fixed)
199 push_arg("-F");
200 if (opt->linenum)
201 push_arg("-n");
202 if (!opt->pathname)
203 push_arg("-h");
204 if (opt->regflags & REG_EXTENDED)
205 push_arg("-E");
206 if (opt->regflags & REG_ICASE)
207 push_arg("-i");
208 if (opt->word_regexp)
209 push_arg("-w");
210 if (opt->name_only)
211 push_arg("-l");
212 if (opt->unmatch_name_only)
213 push_arg("-L");
214 if (opt->count)
215 push_arg("-c");
216 if (opt->post_context || opt->pre_context) {
217 if (opt->post_context != opt->pre_context) {
218 if (opt->pre_context) {
219 push_arg("-B");
220 len += snprintf(argptr, sizeof(randarg)-len,
221 "%u", opt->pre_context);
222 if (sizeof(randarg) <= len)
223 die("maximum length of args exceeded");
224 push_arg(argptr);
225 argptr += len;
227 if (opt->post_context) {
228 push_arg("-A");
229 len += snprintf(argptr, sizeof(randarg)-len,
230 "%u", opt->post_context);
231 if (sizeof(randarg) <= len)
232 die("maximum length of args exceeded");
233 push_arg(argptr);
234 argptr += len;
237 else {
238 push_arg("-C");
239 len += snprintf(argptr, sizeof(randarg)-len,
240 "%u", opt->post_context);
241 if (sizeof(randarg) <= len)
242 die("maximum length of args exceeded");
243 push_arg(argptr);
244 argptr += len;
247 for (p = opt->pattern_list; p; p = p->next) {
248 push_arg("-e");
249 push_arg(p->pattern);
253 * To make sure we get the header printed out when we want it,
254 * add /dev/null to the paths to grep. This is unnecessary
255 * (and wrong) with "-l" or "-L", which always print out the
256 * name anyway.
258 * GNU grep has "-H", but this is portable.
260 if (!opt->name_only && !opt->unmatch_name_only)
261 push_arg("/dev/null");
263 hit = 0;
264 argc = nr;
265 for (i = 0; i < active_nr; i++) {
266 struct cache_entry *ce = active_cache[i];
267 char *name;
268 if (!S_ISREG(ntohl(ce->ce_mode)))
269 continue;
270 if (!pathspec_matches(paths, ce->name))
271 continue;
272 name = ce->name;
273 if (name[0] == '-') {
274 int len = ce_namelen(ce);
275 name = xmalloc(len + 3);
276 memcpy(name, "./", 2);
277 memcpy(name + 2, ce->name, len + 1);
279 argv[argc++] = name;
280 if (argc < MAXARGS && !ce_stage(ce))
281 continue;
282 status = exec_grep(argc, argv);
283 if (0 < status)
284 hit = 1;
285 argc = nr;
286 if (ce_stage(ce)) {
287 do {
288 i++;
289 } while (i < active_nr &&
290 !strcmp(ce->name, active_cache[i]->name));
291 i--; /* compensate for loop control */
294 if (argc > nr) {
295 status = exec_grep(argc, argv);
296 if (0 < status)
297 hit = 1;
299 return hit;
302 static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
304 int hit = 0;
305 int nr;
306 read_cache();
308 #ifdef __unix__
310 * Use the external "grep" command for the case where
311 * we grep through the checked-out files. It tends to
312 * be a lot more optimized
314 if (!cached) {
315 hit = external_grep(opt, paths, cached);
316 if (hit >= 0)
317 return hit;
319 #endif
321 for (nr = 0; nr < active_nr; nr++) {
322 struct cache_entry *ce = active_cache[nr];
323 if (!S_ISREG(ntohl(ce->ce_mode)))
324 continue;
325 if (!pathspec_matches(paths, ce->name))
326 continue;
327 if (cached) {
328 if (ce_stage(ce))
329 continue;
330 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
332 else
333 hit |= grep_file(opt, ce->name);
334 if (ce_stage(ce)) {
335 do {
336 nr++;
337 } while (nr < active_nr &&
338 !strcmp(ce->name, active_cache[nr]->name));
339 nr--; /* compensate for loop control */
342 free_grep_patterns(opt);
343 return hit;
346 static int grep_tree(struct grep_opt *opt, const char **paths,
347 struct tree_desc *tree,
348 const char *tree_name, const char *base)
350 int len;
351 int hit = 0;
352 struct name_entry entry;
353 char *down;
354 int tn_len = strlen(tree_name);
355 char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
357 if (tn_len) {
358 tn_len = sprintf(path_buf, "%s:", tree_name);
359 down = path_buf + tn_len;
360 strcat(down, base);
362 else {
363 down = path_buf;
364 strcpy(down, base);
366 len = strlen(path_buf);
368 while (tree_entry(tree, &entry)) {
369 strcpy(path_buf + len, entry.path);
371 if (S_ISDIR(entry.mode))
372 /* Match "abc/" against pathspec to
373 * decide if we want to descend into "abc"
374 * directory.
376 strcpy(path_buf + len + entry.pathlen, "/");
378 if (!pathspec_matches(paths, down))
380 else if (S_ISREG(entry.mode))
381 hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
382 else if (S_ISDIR(entry.mode)) {
383 char type[20];
384 struct tree_desc sub;
385 void *data;
386 data = read_sha1_file(entry.sha1, type, &sub.size);
387 if (!data)
388 die("unable to read tree (%s)",
389 sha1_to_hex(entry.sha1));
390 sub.buf = data;
391 hit |= grep_tree(opt, paths, &sub, tree_name, down);
392 free(data);
395 return hit;
398 static int grep_object(struct grep_opt *opt, const char **paths,
399 struct object *obj, const char *name)
401 if (obj->type == OBJ_BLOB)
402 return grep_sha1(opt, obj->sha1, name, 0);
403 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
404 struct tree_desc tree;
405 void *data;
406 int hit;
407 data = read_object_with_reference(obj->sha1, tree_type,
408 &tree.size, NULL);
409 if (!data)
410 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
411 tree.buf = data;
412 hit = grep_tree(opt, paths, &tree, name, "");
413 free(data);
414 return hit;
416 die("unable to grep from object of type %s", typename(obj->type));
419 static const char builtin_grep_usage[] =
420 "git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
422 static const char emsg_invalid_context_len[] =
423 "%s: invalid context length argument";
424 static const char emsg_missing_context_len[] =
425 "missing context length argument";
426 static const char emsg_missing_argument[] =
427 "option requires an argument -%s";
429 int cmd_grep(int argc, const char **argv, const char *prefix)
431 int hit = 0;
432 int cached = 0;
433 int seen_dashdash = 0;
434 struct grep_opt opt;
435 struct object_array list = { 0, 0, NULL };
436 const char **paths = NULL;
437 int i;
439 memset(&opt, 0, sizeof(opt));
440 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
441 opt.relative = 1;
442 opt.pathname = 1;
443 opt.pattern_tail = &opt.pattern_list;
444 opt.regflags = REG_NEWLINE;
447 * If there is no -- then the paths must exist in the working
448 * tree. If there is no explicit pattern specified with -e or
449 * -f, we take the first unrecognized non option to be the
450 * pattern, but then what follows it must be zero or more
451 * valid refs up to the -- (if exists), and then existing
452 * paths. If there is an explicit pattern, then the first
453 * unrecognized non option is the beginning of the refs list
454 * that continues up to the -- (if exists), and then paths.
457 while (1 < argc) {
458 const char *arg = argv[1];
459 argc--; argv++;
460 if (!strcmp("--cached", arg)) {
461 cached = 1;
462 continue;
464 if (!strcmp("-a", arg) ||
465 !strcmp("--text", arg)) {
466 opt.binary = GREP_BINARY_TEXT;
467 continue;
469 if (!strcmp("-i", arg) ||
470 !strcmp("--ignore-case", arg)) {
471 opt.regflags |= REG_ICASE;
472 continue;
474 if (!strcmp("-I", arg)) {
475 opt.binary = GREP_BINARY_NOMATCH;
476 continue;
478 if (!strcmp("-v", arg) ||
479 !strcmp("--invert-match", arg)) {
480 opt.invert = 1;
481 continue;
483 if (!strcmp("-E", arg) ||
484 !strcmp("--extended-regexp", arg)) {
485 opt.regflags |= REG_EXTENDED;
486 continue;
488 if (!strcmp("-F", arg) ||
489 !strcmp("--fixed-strings", arg)) {
490 opt.fixed = 1;
491 continue;
493 if (!strcmp("-G", arg) ||
494 !strcmp("--basic-regexp", arg)) {
495 opt.regflags &= ~REG_EXTENDED;
496 continue;
498 if (!strcmp("-n", arg)) {
499 opt.linenum = 1;
500 continue;
502 if (!strcmp("-h", arg)) {
503 opt.pathname = 0;
504 continue;
506 if (!strcmp("-H", arg)) {
507 opt.pathname = 1;
508 continue;
510 if (!strcmp("-l", arg) ||
511 !strcmp("--files-with-matches", arg)) {
512 opt.name_only = 1;
513 continue;
515 if (!strcmp("-L", arg) ||
516 !strcmp("--files-without-match", arg)) {
517 opt.unmatch_name_only = 1;
518 continue;
520 if (!strcmp("-c", arg) ||
521 !strcmp("--count", arg)) {
522 opt.count = 1;
523 continue;
525 if (!strcmp("-w", arg) ||
526 !strcmp("--word-regexp", arg)) {
527 opt.word_regexp = 1;
528 continue;
530 if (!strncmp("-A", arg, 2) ||
531 !strncmp("-B", arg, 2) ||
532 !strncmp("-C", arg, 2) ||
533 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
534 unsigned num;
535 const char *scan;
536 switch (arg[1]) {
537 case 'A': case 'B': case 'C':
538 if (!arg[2]) {
539 if (argc <= 1)
540 die(emsg_missing_context_len);
541 scan = *++argv;
542 argc--;
544 else
545 scan = arg + 2;
546 break;
547 default:
548 scan = arg + 1;
549 break;
551 if (sscanf(scan, "%u", &num) != 1)
552 die(emsg_invalid_context_len, scan);
553 switch (arg[1]) {
554 case 'A':
555 opt.post_context = num;
556 break;
557 default:
558 case 'C':
559 opt.post_context = num;
560 case 'B':
561 opt.pre_context = num;
562 break;
564 continue;
566 if (!strcmp("-f", arg)) {
567 FILE *patterns;
568 int lno = 0;
569 char buf[1024];
570 if (argc <= 1)
571 die(emsg_missing_argument, arg);
572 patterns = fopen(argv[1], "r");
573 if (!patterns)
574 die("'%s': %s", argv[1], strerror(errno));
575 while (fgets(buf, sizeof(buf), patterns)) {
576 int len = strlen(buf);
577 if (buf[len-1] == '\n')
578 buf[len-1] = 0;
579 /* ignore empty line like grep does */
580 if (!buf[0])
581 continue;
582 append_grep_pattern(&opt, xstrdup(buf),
583 argv[1], ++lno,
584 GREP_PATTERN);
586 fclose(patterns);
587 argv++;
588 argc--;
589 continue;
591 if (!strcmp("--not", arg)) {
592 append_grep_pattern(&opt, arg, "command line", 0,
593 GREP_NOT);
594 continue;
596 if (!strcmp("--and", arg)) {
597 append_grep_pattern(&opt, arg, "command line", 0,
598 GREP_AND);
599 continue;
601 if (!strcmp("--or", arg))
602 continue; /* no-op */
603 if (!strcmp("(", arg)) {
604 append_grep_pattern(&opt, arg, "command line", 0,
605 GREP_OPEN_PAREN);
606 continue;
608 if (!strcmp(")", arg)) {
609 append_grep_pattern(&opt, arg, "command line", 0,
610 GREP_CLOSE_PAREN);
611 continue;
613 if (!strcmp("--all-match", arg)) {
614 opt.all_match = 1;
615 continue;
617 if (!strcmp("-e", arg)) {
618 if (1 < argc) {
619 append_grep_pattern(&opt, argv[1],
620 "-e option", 0,
621 GREP_PATTERN);
622 argv++;
623 argc--;
624 continue;
626 die(emsg_missing_argument, arg);
628 if (!strcmp("--full-name", arg)) {
629 opt.relative = 0;
630 continue;
632 if (!strcmp("--", arg)) {
633 /* later processing wants to have this at argv[1] */
634 argv--;
635 argc++;
636 break;
638 if (*arg == '-')
639 usage(builtin_grep_usage);
641 /* First unrecognized non-option token */
642 if (!opt.pattern_list) {
643 append_grep_pattern(&opt, arg, "command line", 0,
644 GREP_PATTERN);
645 break;
647 else {
648 /* We are looking at the first path or rev;
649 * it is found at argv[1] after leaving the
650 * loop.
652 argc++; argv--;
653 break;
657 if (!opt.pattern_list)
658 die("no pattern given.");
659 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
660 die("cannot mix --fixed-strings and regexp");
661 compile_grep_patterns(&opt);
663 /* Check revs and then paths */
664 for (i = 1; i < argc; i++) {
665 const char *arg = argv[i];
666 unsigned char sha1[20];
667 /* Is it a rev? */
668 if (!get_sha1(arg, sha1)) {
669 struct object *object = parse_object(sha1);
670 if (!object)
671 die("bad object %s", arg);
672 add_object_array(object, arg, &list);
673 continue;
675 if (!strcmp(arg, "--")) {
676 i++;
677 seen_dashdash = 1;
679 break;
682 /* The rest are paths */
683 if (!seen_dashdash) {
684 int j;
685 for (j = i; j < argc; j++)
686 verify_filename(prefix, argv[j]);
689 if (i < argc) {
690 paths = get_pathspec(prefix, argv + i);
691 if (opt.prefix_length && opt.relative) {
692 /* Make sure we do not get outside of paths */
693 for (i = 0; paths[i]; i++)
694 if (strncmp(prefix, paths[i], opt.prefix_length))
695 die("git-grep: cannot generate relative filenames containing '..'");
698 else if (prefix) {
699 paths = xcalloc(2, sizeof(const char *));
700 paths[0] = prefix;
701 paths[1] = NULL;
704 if (!list.nr)
705 return !grep_cache(&opt, paths, cached);
707 if (cached)
708 die("both --cached and trees are given.");
710 for (i = 0; i < list.nr; i++) {
711 struct object *real_obj;
712 real_obj = deref_tag(list.objects[i].item, NULL, 0);
713 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
714 hit = 1;
716 free_grep_patterns(&opt);
717 return !hit;