1/*
2 * Builtin "git grep"
3 *
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 "parse-options.h"
14#include "userdiff.h"
15#include "grep.h"
16#include "quote.h"
17#include "dir.h"
18
19static char const * const grep_usage[] = {
20 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
21 NULL
22};
23
24static int grep_config(const char *var, const char *value, void *cb)
25{
26 struct grep_opt *opt = cb;
27
28 switch (userdiff_config(var, value)) {
29 case 0: break;
30 case -1: return -1;
31 default: return 0;
32 }
33
34 if (!strcmp(var, "color.grep")) {
35 opt->color = git_config_colorbool(var, value, -1);
36 return 0;
37 }
38 if (!strcmp(var, "color.grep.match")) {
39 if (!value)
40 return config_error_nonbool(var);
41 color_parse(value, var, opt->color_match);
42 return 0;
43 }
44 return git_color_default_config(var, value, cb);
45}
46
47/*
48 * Return non-zero if max_depth is negative or path has no more then max_depth
49 * slashes.
50 */
51static int accept_subdir(const char *path, int max_depth)
52{
53 if (max_depth < 0)
54 return 1;
55
56 while ((path = strchr(path, '/')) != NULL) {
57 max_depth--;
58 if (max_depth < 0)
59 return 0;
60 path++;
61 }
62 return 1;
63}
64
65/*
66 * Return non-zero if name is a subdirectory of match and is not too deep.
67 */
68static int is_subdir(const char *name, int namelen,
69 const char *match, int matchlen, int max_depth)
70{
71 if (matchlen > namelen || strncmp(name, match, matchlen))
72 return 0;
73
74 if (name[matchlen] == '\0') /* exact match */
75 return 1;
76
77 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
78 return accept_subdir(name + matchlen + 1, max_depth);
79
80 return 0;
81}
82
83/*
84 * git grep pathspecs are somewhat different from diff-tree pathspecs;
85 * pathname wildcards are allowed.
86 */
87static int pathspec_matches(const char **paths, const char *name, int max_depth)
88{
89 int namelen, i;
90 if (!paths || !*paths)
91 return accept_subdir(name, max_depth);
92 namelen = strlen(name);
93 for (i = 0; paths[i]; i++) {
94 const char *match = paths[i];
95 int matchlen = strlen(match);
96 const char *cp, *meta;
97
98 if (is_subdir(name, namelen, match, matchlen, max_depth))
99 return 1;
100 if (!fnmatch(match, name, 0))
101 return 1;
102 if (name[namelen-1] != '/')
103 continue;
104
105 /* We are being asked if the directory ("name") is worth
106 * descending into.
107 *
108 * Find the longest leading directory name that does
109 * not have metacharacter in the pathspec; the name
110 * we are looking at must overlap with that directory.
111 */
112 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
113 char ch = *cp;
114 if (ch == '*' || ch == '[' || ch == '?') {
115 meta = cp;
116 break;
117 }
118 }
119 if (!meta)
120 meta = cp; /* fully literal */
121
122 if (namelen <= meta - match) {
123 /* Looking at "Documentation/" and
124 * the pattern says "Documentation/howto/", or
125 * "Documentation/diff*.txt". The name we
126 * have should match prefix.
127 */
128 if (!memcmp(match, name, namelen))
129 return 1;
130 continue;
131 }
132
133 if (meta - match < namelen) {
134 /* Looking at "Documentation/howto/" and
135 * the pattern says "Documentation/h*";
136 * match up to "Do.../h"; this avoids descending
137 * into "Documentation/technical/".
138 */
139 if (!memcmp(match, name, meta - match))
140 return 1;
141 continue;
142 }
143 }
144 return 0;
145}
146
147static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
148{
149 unsigned long size;
150 char *data;
151 enum object_type type;
152 int hit;
153 struct strbuf pathbuf = STRBUF_INIT;
154
155 data = read_sha1_file(sha1, &type, &size);
156 if (!data) {
157 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
158 return 0;
159 }
160 if (opt->relative && opt->prefix_length) {
161 quote_path_relative(name + tree_name_len, -1, &pathbuf, opt->prefix);
162 strbuf_insert(&pathbuf, 0, name, tree_name_len);
163 name = pathbuf.buf;
164 }
165 hit = grep_buffer(opt, name, data, size);
166 strbuf_release(&pathbuf);
167 free(data);
168 return hit;
169}
170
171static int grep_file(struct grep_opt *opt, const char *filename)
172{
173 struct stat st;
174 int i;
175 char *data;
176 size_t sz;
177 struct strbuf buf = STRBUF_INIT;
178
179 if (lstat(filename, &st) < 0) {
180 err_ret:
181 if (errno != ENOENT)
182 error("'%s': %s", filename, strerror(errno));
183 return 0;
184 }
185 if (!st.st_size)
186 return 0; /* empty file -- no grep hit */
187 if (!S_ISREG(st.st_mode))
188 return 0;
189 sz = xsize_t(st.st_size);
190 i = open(filename, O_RDONLY);
191 if (i < 0)
192 goto err_ret;
193 data = xmalloc(sz + 1);
194 if (st.st_size != read_in_full(i, data, sz)) {
195 error("'%s': short read %s", filename, strerror(errno));
196 close(i);
197 free(data);
198 return 0;
199 }
200 close(i);
201 if (opt->relative && opt->prefix_length)
202 filename = quote_path_relative(filename, -1, &buf, opt->prefix);
203 i = grep_buffer(opt, filename, data, sz);
204 strbuf_release(&buf);
205 free(data);
206 return i;
207}
208
209static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
210{
211 int hit = 0;
212 int nr;
213 read_cache();
214
215 for (nr = 0; nr < active_nr; nr++) {
216 struct cache_entry *ce = active_cache[nr];
217 if (!S_ISREG(ce->ce_mode))
218 continue;
219 if (!pathspec_matches(paths, ce->name, opt->max_depth))
220 continue;
221 /*
222 * If CE_VALID is on, we assume worktree file and its cache entry
223 * are identical, even if worktree file has been modified, so use
224 * cache version instead
225 */
226 if (cached || (ce->ce_flags & CE_VALID)) {
227 if (ce_stage(ce))
228 continue;
229 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
230 }
231 else
232 hit |= grep_file(opt, ce->name);
233 if (ce_stage(ce)) {
234 do {
235 nr++;
236 } while (nr < active_nr &&
237 !strcmp(ce->name, active_cache[nr]->name));
238 nr--; /* compensate for loop control */
239 }
240 }
241 free_grep_patterns(opt);
242 return hit;
243}
244
245static int grep_tree(struct grep_opt *opt, const char **paths,
246 struct tree_desc *tree,
247 const char *tree_name, const char *base)
248{
249 int len;
250 int hit = 0;
251 struct name_entry entry;
252 char *down;
253 int tn_len = strlen(tree_name);
254 struct strbuf pathbuf;
255
256 strbuf_init(&pathbuf, PATH_MAX + tn_len);
257
258 if (tn_len) {
259 strbuf_add(&pathbuf, tree_name, tn_len);
260 strbuf_addch(&pathbuf, ':');
261 tn_len = pathbuf.len;
262 }
263 strbuf_addstr(&pathbuf, base);
264 len = pathbuf.len;
265
266 while (tree_entry(tree, &entry)) {
267 int te_len = tree_entry_len(entry.path, entry.sha1);
268 pathbuf.len = len;
269 strbuf_add(&pathbuf, entry.path, te_len);
270
271 if (S_ISDIR(entry.mode))
272 /* Match "abc/" against pathspec to
273 * decide if we want to descend into "abc"
274 * directory.
275 */
276 strbuf_addch(&pathbuf, '/');
277
278 down = pathbuf.buf + tn_len;
279 if (!pathspec_matches(paths, down, opt->max_depth))
280 ;
281 else if (S_ISREG(entry.mode))
282 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
283 else if (S_ISDIR(entry.mode)) {
284 enum object_type type;
285 struct tree_desc sub;
286 void *data;
287 unsigned long size;
288
289 data = read_sha1_file(entry.sha1, &type, &size);
290 if (!data)
291 die("unable to read tree (%s)",
292 sha1_to_hex(entry.sha1));
293 init_tree_desc(&sub, data, size);
294 hit |= grep_tree(opt, paths, &sub, tree_name, down);
295 free(data);
296 }
297 }
298 strbuf_release(&pathbuf);
299 return hit;
300}
301
302static int grep_object(struct grep_opt *opt, const char **paths,
303 struct object *obj, const char *name)
304{
305 if (obj->type == OBJ_BLOB)
306 return grep_sha1(opt, obj->sha1, name, 0);
307 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
308 struct tree_desc tree;
309 void *data;
310 unsigned long size;
311 int hit;
312 data = read_object_with_reference(obj->sha1, tree_type,
313 &size, NULL);
314 if (!data)
315 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
316 init_tree_desc(&tree, data, size);
317 hit = grep_tree(opt, paths, &tree, name, "");
318 free(data);
319 return hit;
320 }
321 die("unable to grep from object of type %s", typename(obj->type));
322}
323
324static int grep_directory(struct grep_opt *opt, const char **paths)
325{
326 struct dir_struct dir;
327 int i, hit = 0;
328
329 memset(&dir, 0, sizeof(dir));
330 setup_standard_excludes(&dir);
331
332 fill_directory(&dir, paths);
333 for (i = 0; i < dir.nr; i++)
334 hit |= grep_file(opt, dir.entries[i]->name);
335 free_grep_patterns(opt);
336 return hit;
337}
338
339static int context_callback(const struct option *opt, const char *arg,
340 int unset)
341{
342 struct grep_opt *grep_opt = opt->value;
343 int value;
344 const char *endp;
345
346 if (unset) {
347 grep_opt->pre_context = grep_opt->post_context = 0;
348 return 0;
349 }
350 value = strtol(arg, (char **)&endp, 10);
351 if (*endp) {
352 return error("switch `%c' expects a numerical value",
353 opt->short_name);
354 }
355 grep_opt->pre_context = grep_opt->post_context = value;
356 return 0;
357}
358
359static int file_callback(const struct option *opt, const char *arg, int unset)
360{
361 struct grep_opt *grep_opt = opt->value;
362 FILE *patterns;
363 int lno = 0;
364 struct strbuf sb = STRBUF_INIT;
365
366 patterns = fopen(arg, "r");
367 if (!patterns)
368 die_errno("cannot open '%s'", arg);
369 while (strbuf_getline(&sb, patterns, '\n') == 0) {
370 /* ignore empty line like grep does */
371 if (sb.len == 0)
372 continue;
373 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
374 ++lno, GREP_PATTERN);
375 }
376 fclose(patterns);
377 strbuf_release(&sb);
378 return 0;
379}
380
381static int not_callback(const struct option *opt, const char *arg, int unset)
382{
383 struct grep_opt *grep_opt = opt->value;
384 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
385 return 0;
386}
387
388static int and_callback(const struct option *opt, const char *arg, int unset)
389{
390 struct grep_opt *grep_opt = opt->value;
391 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
392 return 0;
393}
394
395static int open_callback(const struct option *opt, const char *arg, int unset)
396{
397 struct grep_opt *grep_opt = opt->value;
398 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
399 return 0;
400}
401
402static int close_callback(const struct option *opt, const char *arg, int unset)
403{
404 struct grep_opt *grep_opt = opt->value;
405 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
406 return 0;
407}
408
409static int pattern_callback(const struct option *opt, const char *arg,
410 int unset)
411{
412 struct grep_opt *grep_opt = opt->value;
413 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
414 return 0;
415}
416
417static int help_callback(const struct option *opt, const char *arg, int unset)
418{
419 return -1;
420}
421
422int cmd_grep(int argc, const char **argv, const char *prefix)
423{
424 int hit = 0;
425 int cached = 0;
426 int seen_dashdash = 0;
427 int external_grep_allowed__ignored;
428 struct grep_opt opt;
429 struct object_array list = { 0, 0, NULL };
430 const char **paths = NULL;
431 int i;
432 int dummy;
433 int nongit = 0, use_index = 1;
434 struct option options[] = {
435 OPT_BOOLEAN(0, "cached", &cached,
436 "search in index instead of in the work tree"),
437 OPT_BOOLEAN(0, "index", &use_index,
438 "--no-index finds in contents not managed by git"),
439 OPT_GROUP(""),
440 OPT_BOOLEAN('v', "invert-match", &opt.invert,
441 "show non-matching lines"),
442 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
443 "case insensitive matching"),
444 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
445 "match patterns only at word boundaries"),
446 OPT_SET_INT('a', "text", &opt.binary,
447 "process binary files as text", GREP_BINARY_TEXT),
448 OPT_SET_INT('I', NULL, &opt.binary,
449 "don't match patterns in binary files",
450 GREP_BINARY_NOMATCH),
451 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
452 "descend at most <depth> levels", PARSE_OPT_NONEG,
453 NULL, 1 },
454 OPT_GROUP(""),
455 OPT_BIT('E', "extended-regexp", &opt.regflags,
456 "use extended POSIX regular expressions", REG_EXTENDED),
457 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
458 "use basic POSIX regular expressions (default)",
459 REG_EXTENDED),
460 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
461 "interpret patterns as fixed strings"),
462 OPT_GROUP(""),
463 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
464 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
465 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
466 OPT_NEGBIT(0, "full-name", &opt.relative,
467 "show filenames relative to top directory", 1),
468 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
469 "show only filenames instead of matching lines"),
470 OPT_BOOLEAN(0, "name-only", &opt.name_only,
471 "synonym for --files-with-matches"),
472 OPT_BOOLEAN('L', "files-without-match",
473 &opt.unmatch_name_only,
474 "show only the names of files without match"),
475 OPT_BOOLEAN('z', "null", &opt.null_following_name,
476 "print NUL after filenames"),
477 OPT_BOOLEAN('c', "count", &opt.count,
478 "show the number of matches instead of matching lines"),
479 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
480 OPT_GROUP(""),
481 OPT_CALLBACK('C', NULL, &opt, "n",
482 "show <n> context lines before and after matches",
483 context_callback),
484 OPT_INTEGER('B', NULL, &opt.pre_context,
485 "show <n> context lines before matches"),
486 OPT_INTEGER('A', NULL, &opt.post_context,
487 "show <n> context lines after matches"),
488 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
489 context_callback),
490 OPT_BOOLEAN('p', "show-function", &opt.funcname,
491 "show a line with the function name before matches"),
492 OPT_GROUP(""),
493 OPT_CALLBACK('f', NULL, &opt, "file",
494 "read patterns from file", file_callback),
495 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
496 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
497 { OPTION_CALLBACK, 0, "and", &opt, NULL,
498 "combine patterns specified with -e",
499 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
500 OPT_BOOLEAN(0, "or", &dummy, ""),
501 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
502 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
503 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
504 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
505 open_callback },
506 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
507 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
508 close_callback },
509 OPT_BOOLEAN(0, "all-match", &opt.all_match,
510 "show only matches from files that match all patterns"),
511 OPT_GROUP(""),
512 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
513 "allow calling of grep(1) (ignored by this build)"),
514 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
515 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
516 OPT_END()
517 };
518
519 prefix = setup_git_directory_gently(&nongit);
520
521 /*
522 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
523 * to show usage information and exit.
524 */
525 if (argc == 2 && !strcmp(argv[1], "-h"))
526 usage_with_options(grep_usage, options);
527
528 memset(&opt, 0, sizeof(opt));
529 opt.prefix = prefix;
530 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
531 opt.relative = 1;
532 opt.pathname = 1;
533 opt.pattern_tail = &opt.pattern_list;
534 opt.regflags = REG_NEWLINE;
535 opt.max_depth = -1;
536
537 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
538 opt.color = -1;
539 git_config(grep_config, &opt);
540 if (opt.color == -1)
541 opt.color = git_use_color_default;
542
543 /*
544 * If there is no -- then the paths must exist in the working
545 * tree. If there is no explicit pattern specified with -e or
546 * -f, we take the first unrecognized non option to be the
547 * pattern, but then what follows it must be zero or more
548 * valid refs up to the -- (if exists), and then existing
549 * paths. If there is an explicit pattern, then the first
550 * unrecognized non option is the beginning of the refs list
551 * that continues up to the -- (if exists), and then paths.
552 */
553 argc = parse_options(argc, argv, prefix, options, grep_usage,
554 PARSE_OPT_KEEP_DASHDASH |
555 PARSE_OPT_STOP_AT_NON_OPTION |
556 PARSE_OPT_NO_INTERNAL_HELP);
557
558 if (use_index && nongit)
559 /* die the same way as if we did it at the beginning */
560 setup_git_directory();
561
562 /* First unrecognized non-option token */
563 if (argc > 0 && !opt.pattern_list) {
564 append_grep_pattern(&opt, argv[0], "command line", 0,
565 GREP_PATTERN);
566 argv++;
567 argc--;
568 }
569
570 if (!opt.pattern_list)
571 die("no pattern given.");
572 if (!opt.fixed && opt.ignore_case)
573 opt.regflags |= REG_ICASE;
574 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
575 die("cannot mix --fixed-strings and regexp");
576 compile_grep_patterns(&opt);
577
578 /* Check revs and then paths */
579 for (i = 0; i < argc; i++) {
580 const char *arg = argv[i];
581 unsigned char sha1[20];
582 /* Is it a rev? */
583 if (!get_sha1(arg, sha1)) {
584 struct object *object = parse_object(sha1);
585 if (!object)
586 die("bad object %s", arg);
587 add_object_array(object, arg, &list);
588 continue;
589 }
590 if (!strcmp(arg, "--")) {
591 i++;
592 seen_dashdash = 1;
593 }
594 break;
595 }
596
597 /* The rest are paths */
598 if (!seen_dashdash) {
599 int j;
600 for (j = i; j < argc; j++)
601 verify_filename(prefix, argv[j]);
602 }
603
604 if (i < argc)
605 paths = get_pathspec(prefix, argv + i);
606 else if (prefix) {
607 paths = xcalloc(2, sizeof(const char *));
608 paths[0] = prefix;
609 paths[1] = NULL;
610 }
611
612 if (!use_index) {
613 if (cached)
614 die("--cached cannot be used with --no-index.");
615 if (list.nr)
616 die("--no-index cannot be used with revs.");
617 return !grep_directory(&opt, paths);
618 }
619
620 if (!list.nr) {
621 if (!cached)
622 setup_work_tree();
623 return !grep_cache(&opt, paths, cached);
624 }
625
626 if (cached)
627 die("both --cached and trees are given.");
628
629 for (i = 0; i < list.nr; i++) {
630 struct object *real_obj;
631 real_obj = deref_tag(list.objects[i].item, NULL, 0);
632 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
633 hit = 1;
634 }
635 free_grep_patterns(&opt);
636 return !hit;
637}