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