grep: print context hunk marks between files
[git/git.git] / builtin-grep.c
CommitLineData
5010cb5f
JH
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"
1362671f 11#include "tree-walk.h"
5010cb5f 12#include "builtin.h"
3e230fa1 13#include "parse-options.h"
83b5d2f5 14#include "grep.h"
5010cb5f 15
5f7c643a
JK
16#ifndef NO_EXTERNAL_GREP
17#ifdef __unix__
18#define NO_EXTERNAL_GREP 0
19#else
20#define NO_EXTERNAL_GREP 1
21#endif
22#endif
23
3e230fa1
RS
24static char const * const grep_usage[] = {
25 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
26 NULL
27};
28
7e8f59d5
RS
29static int grep_config(const char *var, const char *value, void *cb)
30{
31 struct grep_opt *opt = cb;
32
fe3420b6 33 if (!strcmp(var, "color.grep")) {
7e8f59d5
RS
34 opt->color = git_config_colorbool(var, value, -1);
35 return 0;
36 }
fe3420b6 37 if (!strcmp(var, "color.grep.external"))
a94982ef 38 return git_config_string(&(opt->color_external), var, value);
fe3420b6 39 if (!strcmp(var, "color.grep.match")) {
7e8f59d5
RS
40 if (!value)
41 return config_error_nonbool(var);
42 color_parse(value, var, opt->color_match);
43 return 0;
44 }
45 return git_color_default_config(var, value, cb);
46}
47
e0eb889f
JH
48/*
49 * git grep pathspecs are somewhat different from diff-tree pathspecs;
50 * pathname wildcards are allowed.
51 */
1362671f 52static int pathspec_matches(const char **paths, const char *name)
5010cb5f 53{
e0eb889f 54 int namelen, i;
1362671f 55 if (!paths || !*paths)
5010cb5f
JH
56 return 1;
57 namelen = strlen(name);
1362671f
JH
58 for (i = 0; paths[i]; i++) {
59 const char *match = paths[i];
60 int matchlen = strlen(match);
1e3d90e0 61 const char *cp, *meta;
e0eb889f 62
bb9e15a8
UKK
63 if (!matchlen ||
64 ((matchlen <= namelen) &&
65 !strncmp(name, match, matchlen) &&
66 (match[matchlen-1] == '/' ||
67 name[matchlen] == '\0' || name[matchlen] == '/')))
e0eb889f
JH
68 return 1;
69 if (!fnmatch(match, name, 0))
70 return 1;
71 if (name[namelen-1] != '/')
5010cb5f 72 continue;
e0eb889f 73
1e3d90e0 74 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
75 * descending into.
76 *
77 * Find the longest leading directory name that does
78 * not have metacharacter in the pathspec; the name
79 * we are looking at must overlap with that directory.
5010cb5f 80 */
1e3d90e0 81 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 82 char ch = *cp;
1e3d90e0
JH
83 if (ch == '*' || ch == '[' || ch == '?') {
84 meta = cp;
5010cb5f 85 break;
1e3d90e0 86 }
e0eb889f 87 }
1e3d90e0
JH
88 if (!meta)
89 meta = cp; /* fully literal */
90
91 if (namelen <= meta - match) {
e0eb889f
JH
92 /* Looking at "Documentation/" and
93 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
94 * "Documentation/diff*.txt". The name we
95 * have should match prefix.
e0eb889f
JH
96 */
97 if (!memcmp(match, name, namelen))
98 return 1;
1e3d90e0 99 continue;
e0eb889f 100 }
1e3d90e0
JH
101
102 if (meta - match < namelen) {
e0eb889f 103 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
104 * the pattern says "Documentation/h*";
105 * match up to "Do.../h"; this avoids descending
106 * into "Documentation/technical/".
e0eb889f 107 */
1e3d90e0 108 if (!memcmp(match, name, meta - match))
e0eb889f 109 return 1;
1e3d90e0 110 continue;
e0eb889f 111 }
5010cb5f
JH
112 }
113 return 0;
114}
115
0d042fec 116static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
5010cb5f
JH
117{
118 unsigned long size;
119 char *data;
21666f1a 120 enum object_type type;
0d042fec 121 char *to_free = NULL;
5010cb5f 122 int hit;
0d042fec 123
21666f1a 124 data = read_sha1_file(sha1, &type, &size);
5010cb5f
JH
125 if (!data) {
126 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
127 return 0;
128 }
0d042fec
JH
129 if (opt->relative && opt->prefix_length) {
130 static char name_buf[PATH_MAX];
131 char *cp;
132 int name_len = strlen(name) - opt->prefix_length + 1;
133
134 if (!tree_name_len)
135 name += opt->prefix_length;
136 else {
137 if (ARRAY_SIZE(name_buf) <= name_len)
138 cp = to_free = xmalloc(name_len);
139 else
140 cp = name_buf;
141 memcpy(cp, name, tree_name_len);
142 strcpy(cp + tree_name_len,
143 name + tree_name_len + opt->prefix_length);
144 name = cp;
145 }
146 }
5010cb5f
JH
147 hit = grep_buffer(opt, name, data, size);
148 free(data);
0d042fec 149 free(to_free);
5010cb5f
JH
150 return hit;
151}
152
153static int grep_file(struct grep_opt *opt, const char *filename)
154{
155 struct stat st;
156 int i;
157 char *data;
dc49cd76
SP
158 size_t sz;
159
5010cb5f
JH
160 if (lstat(filename, &st) < 0) {
161 err_ret:
162 if (errno != ENOENT)
163 error("'%s': %s", filename, strerror(errno));
164 return 0;
165 }
166 if (!st.st_size)
167 return 0; /* empty file -- no grep hit */
168 if (!S_ISREG(st.st_mode))
169 return 0;
dc49cd76 170 sz = xsize_t(st.st_size);
5010cb5f
JH
171 i = open(filename, O_RDONLY);
172 if (i < 0)
173 goto err_ret;
dc49cd76
SP
174 data = xmalloc(sz + 1);
175 if (st.st_size != read_in_full(i, data, sz)) {
5010cb5f
JH
176 error("'%s': short read %s", filename, strerror(errno));
177 close(i);
178 free(data);
179 return 0;
180 }
181 close(i);
0d042fec
JH
182 if (opt->relative && opt->prefix_length)
183 filename += opt->prefix_length;
dc49cd76 184 i = grep_buffer(opt, filename, data, sz);
5010cb5f
JH
185 free(data);
186 return i;
187}
188
5f7c643a 189#if !NO_EXTERNAL_GREP
1e2398d7
LT
190static int exec_grep(int argc, const char **argv)
191{
192 pid_t pid;
193 int status;
194
195 argv[argc] = NULL;
196 pid = fork();
197 if (pid < 0)
198 return pid;
199 if (!pid) {
200 execvp("grep", (char **) argv);
201 exit(255);
202 }
203 while (waitpid(pid, &status, 0) < 0) {
204 if (errno == EINTR)
205 continue;
206 return -1;
207 }
208 if (WIFEXITED(status)) {
209 if (!WEXITSTATUS(status))
210 return 1;
211 return 0;
212 }
213 return -1;
214}
215
216#define MAXARGS 1000
ffa0a7ab
JH
217#define ARGBUF 4096
218#define push_arg(a) do { \
219 if (nr < MAXARGS) argv[nr++] = (a); \
220 else die("maximum number of args exceeded"); \
221 } while (0)
1e2398d7 222
d99ebf08
JH
223/*
224 * If you send a singleton filename to grep, it does not give
225 * the name of the file. GNU grep has "-H" but we would want
226 * that behaviour in a portable way.
227 *
228 * So we keep two pathnames in argv buffer unsent to grep in
229 * the main loop if we need to do more than one grep.
230 */
231static int flush_grep(struct grep_opt *opt,
232 int argc, int arg0, const char **argv, int *kept)
233{
234 int status;
235 int count = argc - arg0;
236 const char *kept_0 = NULL;
237
238 if (count <= 2) {
239 /*
240 * Because we keep at least 2 paths in the call from
241 * the main loop (i.e. kept != NULL), and MAXARGS is
242 * far greater than 2, this usually is a call to
243 * conclude the grep. However, the user could attempt
244 * to overflow the argv buffer by giving too many
245 * options to leave very small number of real
246 * arguments even for the call in the main loop.
247 */
248 if (kept)
249 die("insanely many options to grep");
250
251 /*
252 * If we have two or more paths, we do not have to do
253 * anything special, but we need to push /dev/null to
254 * get "-H" behaviour of GNU grep portably but when we
255 * are not doing "-l" nor "-L" nor "-c".
256 */
257 if (count == 1 &&
258 !opt->name_only &&
259 !opt->unmatch_name_only &&
260 !opt->count) {
261 argv[argc++] = "/dev/null";
262 argv[argc] = NULL;
263 }
264 }
265
266 else if (kept) {
267 /*
268 * Called because we found many paths and haven't finished
269 * iterating over the cache yet. We keep two paths
270 * for the concluding call. argv[argc-2] and argv[argc-1]
271 * has the last two paths, so save the first one away,
272 * replace it with NULL while sending the list to grep,
273 * and recover them after we are done.
274 */
275 *kept = 2;
276 kept_0 = argv[argc-2];
277 argv[argc-2] = NULL;
278 argc -= 2;
279 }
280
046802d0
RS
281 if (opt->pre_context || opt->post_context) {
282 /*
283 * grep handles hunk marks between files, but we need to
284 * do that ourselves between multiple calls.
285 */
286 if (opt->show_hunk_mark)
287 write_or_die(1, "--\n", 3);
288 else
289 opt->show_hunk_mark = 1;
290 }
291
d99ebf08
JH
292 status = exec_grep(argc, argv);
293
294 if (kept_0) {
295 /*
296 * Then recover them. Now the last arg is beyond the
297 * terminating NULL which is at argc, and the second
298 * from the last is what we saved away in kept_0
299 */
300 argv[arg0++] = kept_0;
301 argv[arg0] = argv[argc+1];
302 }
303 return status;
304}
305
a94982ef
RS
306static void grep_add_color(struct strbuf *sb, const char *escape_seq)
307{
308 size_t orig_len = sb->len;
309
310 while (*escape_seq) {
311 if (*escape_seq == 'm')
312 strbuf_addch(sb, ';');
313 else if (*escape_seq != '\033' && *escape_seq != '[')
314 strbuf_addch(sb, *escape_seq);
315 escape_seq++;
316 }
317 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
318 strbuf_setlen(sb, sb->len - 1);
319}
320
1e2398d7
LT
321static int external_grep(struct grep_opt *opt, const char **paths, int cached)
322{
fcfe34b5 323 int i, nr, argc, hit, len, status;
1e2398d7 324 const char *argv[MAXARGS+1];
ffa0a7ab
JH
325 char randarg[ARGBUF];
326 char *argptr = randarg;
1e2398d7
LT
327 struct grep_pat *p;
328
0d042fec 329 if (opt->extended || (opt->relative && opt->prefix_length))
79d3696c 330 return -1;
ffa0a7ab
JH
331 len = nr = 0;
332 push_arg("grep");
ffa0a7ab 333 if (opt->fixed)
f6647519 334 push_arg("-F");
ffa0a7ab
JH
335 if (opt->linenum)
336 push_arg("-n");
7977f0ea
LT
337 if (!opt->pathname)
338 push_arg("-h");
ffa0a7ab
JH
339 if (opt->regflags & REG_EXTENDED)
340 push_arg("-E");
3026402c
RF
341 if (opt->regflags & REG_ICASE)
342 push_arg("-i");
bc395643
JH
343 if (opt->binary == GREP_BINARY_NOMATCH)
344 push_arg("-I");
1e2398d7 345 if (opt->word_regexp)
ffa0a7ab 346 push_arg("-w");
1e2398d7 347 if (opt->name_only)
ffa0a7ab
JH
348 push_arg("-l");
349 if (opt->unmatch_name_only)
350 push_arg("-L");
83caecca
RZ
351 if (opt->null_following_name)
352 /* in GNU grep git's "-z" translates to "-Z" */
353 push_arg("-Z");
ffa0a7ab
JH
354 if (opt->count)
355 push_arg("-c");
356 if (opt->post_context || opt->pre_context) {
357 if (opt->post_context != opt->pre_context) {
358 if (opt->pre_context) {
359 push_arg("-B");
360 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 361 "%u", opt->pre_context) + 1;
ffa0a7ab
JH
362 if (sizeof(randarg) <= len)
363 die("maximum length of args exceeded");
364 push_arg(argptr);
365 argptr += len;
366 }
367 if (opt->post_context) {
368 push_arg("-A");
369 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 370 "%u", opt->post_context) + 1;
ffa0a7ab
JH
371 if (sizeof(randarg) <= len)
372 die("maximum length of args exceeded");
373 push_arg(argptr);
374 argptr += len;
375 }
376 }
377 else {
378 push_arg("-C");
379 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 380 "%u", opt->post_context) + 1;
ffa0a7ab
JH
381 if (sizeof(randarg) <= len)
382 die("maximum length of args exceeded");
383 push_arg(argptr);
384 argptr += len;
385 }
386 }
1e2398d7 387 for (p = opt->pattern_list; p; p = p->next) {
ffa0a7ab
JH
388 push_arg("-e");
389 push_arg(p->pattern);
1e2398d7 390 }
a94982ef
RS
391 if (opt->color) {
392 struct strbuf sb = STRBUF_INIT;
393
394 grep_add_color(&sb, opt->color_match);
395 setenv("GREP_COLOR", sb.buf, 1);
396
397 strbuf_reset(&sb);
398 strbuf_addstr(&sb, "mt=");
399 grep_add_color(&sb, opt->color_match);
400 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
401 setenv("GREP_COLORS", sb.buf, 1);
402
403 strbuf_release(&sb);
404
405 if (opt->color_external && strlen(opt->color_external) > 0)
406 push_arg(opt->color_external);
407 }
bbb66c60 408
1e2398d7
LT
409 hit = 0;
410 argc = nr;
411 for (i = 0; i < active_nr; i++) {
412 struct cache_entry *ce = active_cache[i];
fbd01abf 413 char *name;
d99ebf08 414 int kept;
7a51ed66 415 if (!S_ISREG(ce->ce_mode))
1e2398d7
LT
416 continue;
417 if (!pathspec_matches(paths, ce->name))
418 continue;
bbb66c60
LT
419 name = ce->name;
420 if (name[0] == '-') {
421 int len = ce_namelen(ce);
422 name = xmalloc(len + 3);
423 memcpy(name, "./", 2);
424 memcpy(name + 2, ce->name, len + 1);
425 }
426 argv[argc++] = name;
6326cee5
JH
427 if (MAXARGS <= argc) {
428 status = flush_grep(opt, argc, nr, argv, &kept);
429 if (0 < status)
430 hit = 1;
431 argc = nr + kept;
432 }
36f2587f
JH
433 if (ce_stage(ce)) {
434 do {
435 i++;
436 } while (i < active_nr &&
437 !strcmp(ce->name, active_cache[i]->name));
438 i--; /* compensate for loop control */
439 }
1e2398d7 440 }
fcfe34b5 441 if (argc > nr) {
d99ebf08 442 status = flush_grep(opt, argc, nr, argv, NULL);
fcfe34b5
JH
443 if (0 < status)
444 hit = 1;
445 }
446 return hit;
1e2398d7 447}
ff1f9945 448#endif
1e2398d7 449
1b5fb44a
RS
450static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
451 int external_grep_allowed)
5010cb5f
JH
452{
453 int hit = 0;
454 int nr;
455 read_cache();
456
5f7c643a 457#if !NO_EXTERNAL_GREP
1e2398d7
LT
458 /*
459 * Use the external "grep" command for the case where
460 * we grep through the checked-out files. It tends to
461 * be a lot more optimized
462 */
1b5fb44a 463 if (!cached && external_grep_allowed) {
1e2398d7
LT
464 hit = external_grep(opt, paths, cached);
465 if (hit >= 0)
466 return hit;
467 }
468#endif
469
5010cb5f
JH
470 for (nr = 0; nr < active_nr; nr++) {
471 struct cache_entry *ce = active_cache[nr];
7a51ed66 472 if (!S_ISREG(ce->ce_mode))
5010cb5f 473 continue;
1362671f 474 if (!pathspec_matches(paths, ce->name))
5010cb5f 475 continue;
57d43466
NTND
476 /*
477 * If CE_VALID is on, we assume worktree file and its cache entry
478 * are identical, even if worktree file has been modified, so use
479 * cache version instead
480 */
481 if (cached || (ce->ce_flags & CE_VALID)) {
36f2587f
JH
482 if (ce_stage(ce))
483 continue;
0d042fec 484 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
36f2587f 485 }
5010cb5f
JH
486 else
487 hit |= grep_file(opt, ce->name);
36f2587f
JH
488 if (ce_stage(ce)) {
489 do {
490 nr++;
491 } while (nr < active_nr &&
492 !strcmp(ce->name, active_cache[nr]->name));
493 nr--; /* compensate for loop control */
494 }
5010cb5f 495 }
b48fb5b6 496 free_grep_patterns(opt);
5010cb5f
JH
497 return hit;
498}
499
1362671f 500static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
501 struct tree_desc *tree,
502 const char *tree_name, const char *base)
503{
5010cb5f
JH
504 int len;
505 int hit = 0;
4c068a98 506 struct name_entry entry;
e0eb889f 507 char *down;
0d042fec 508 int tn_len = strlen(tree_name);
620e2bb9
DP
509 struct strbuf pathbuf;
510
511 strbuf_init(&pathbuf, PATH_MAX + tn_len);
5010cb5f 512
0d042fec 513 if (tn_len) {
620e2bb9
DP
514 strbuf_add(&pathbuf, tree_name, tn_len);
515 strbuf_addch(&pathbuf, ':');
516 tn_len = pathbuf.len;
5010cb5f 517 }
620e2bb9
DP
518 strbuf_addstr(&pathbuf, base);
519 len = pathbuf.len;
5010cb5f 520
4c068a98 521 while (tree_entry(tree, &entry)) {
620e2bb9
DP
522 int te_len = tree_entry_len(entry.path, entry.sha1);
523 pathbuf.len = len;
524 strbuf_add(&pathbuf, entry.path, te_len);
5010cb5f 525
4c068a98 526 if (S_ISDIR(entry.mode))
e0eb889f
JH
527 /* Match "abc/" against pathspec to
528 * decide if we want to descend into "abc"
529 * directory.
530 */
620e2bb9 531 strbuf_addch(&pathbuf, '/');
e0eb889f 532
620e2bb9 533 down = pathbuf.buf + tn_len;
1362671f 534 if (!pathspec_matches(paths, down))
5010cb5f 535 ;
4c068a98 536 else if (S_ISREG(entry.mode))
620e2bb9 537 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
4c068a98 538 else if (S_ISDIR(entry.mode)) {
21666f1a 539 enum object_type type;
5010cb5f
JH
540 struct tree_desc sub;
541 void *data;
6fda5e51
LT
542 unsigned long size;
543
544 data = read_sha1_file(entry.sha1, &type, &size);
5010cb5f
JH
545 if (!data)
546 die("unable to read tree (%s)",
4c068a98 547 sha1_to_hex(entry.sha1));
6fda5e51 548 init_tree_desc(&sub, data, size);
1362671f 549 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
550 free(data);
551 }
5010cb5f 552 }
620e2bb9 553 strbuf_release(&pathbuf);
5010cb5f
JH
554 return hit;
555}
556
1362671f 557static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
558 struct object *obj, const char *name)
559{
1974632c 560 if (obj->type == OBJ_BLOB)
0d042fec 561 return grep_sha1(opt, obj->sha1, name, 0);
1974632c 562 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
563 struct tree_desc tree;
564 void *data;
6fda5e51 565 unsigned long size;
5010cb5f
JH
566 int hit;
567 data = read_object_with_reference(obj->sha1, tree_type,
6fda5e51 568 &size, NULL);
5010cb5f
JH
569 if (!data)
570 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
6fda5e51 571 init_tree_desc(&tree, data, size);
1362671f 572 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
573 free(data);
574 return hit;
575 }
885a86ab 576 die("unable to grep from object of type %s", typename(obj->type));
5010cb5f
JH
577}
578
ff3c7f9a
RS
579static int context_callback(const struct option *opt, const char *arg,
580 int unset)
3e230fa1
RS
581{
582 struct grep_opt *grep_opt = opt->value;
583 int value;
584 const char *endp;
585
586 if (unset) {
587 grep_opt->pre_context = grep_opt->post_context = 0;
588 return 0;
589 }
590 value = strtol(arg, (char **)&endp, 10);
591 if (*endp) {
592 return error("switch `%c' expects a numerical value",
593 opt->short_name);
594 }
595 grep_opt->pre_context = grep_opt->post_context = value;
596 return 0;
597}
598
ff3c7f9a 599static int file_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
600{
601 struct grep_opt *grep_opt = opt->value;
602 FILE *patterns;
603 int lno = 0;
604 struct strbuf sb;
605
606 patterns = fopen(arg, "r");
607 if (!patterns)
608 die("'%s': %s", arg, strerror(errno));
609 while (strbuf_getline(&sb, patterns, '\n') == 0) {
610 /* ignore empty line like grep does */
611 if (sb.len == 0)
612 continue;
613 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
614 ++lno, GREP_PATTERN);
615 }
616 fclose(patterns);
617 strbuf_release(&sb);
618 return 0;
619}
620
ff3c7f9a 621static int not_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
622{
623 struct grep_opt *grep_opt = opt->value;
624 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
625 return 0;
626}
627
ff3c7f9a 628static int and_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
629{
630 struct grep_opt *grep_opt = opt->value;
631 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
632 return 0;
633}
634
ff3c7f9a 635static int open_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
636{
637 struct grep_opt *grep_opt = opt->value;
638 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
639 return 0;
640}
641
ff3c7f9a 642static int close_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
643{
644 struct grep_opt *grep_opt = opt->value;
645 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
646 return 0;
647}
648
ff3c7f9a
RS
649static int pattern_callback(const struct option *opt, const char *arg,
650 int unset)
3e230fa1
RS
651{
652 struct grep_opt *grep_opt = opt->value;
653 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
654 return 0;
655}
5010cb5f 656
ff3c7f9a 657static int help_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
658{
659 return -1;
660}
088b084b 661
a633fca0 662int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 663{
5010cb5f 664 int hit = 0;
5010cb5f 665 int cached = 0;
1b5fb44a 666 int external_grep_allowed = 1;
5acd64ed 667 int seen_dashdash = 0;
5010cb5f 668 struct grep_opt opt;
1f1e895f 669 struct object_array list = { 0, 0, NULL };
1362671f 670 const char **paths = NULL;
5acd64ed 671 int i;
3e230fa1
RS
672 int dummy;
673 struct option options[] = {
674 OPT_BOOLEAN(0, "cached", &cached,
675 "search in index instead of in the work tree"),
676 OPT_GROUP(""),
677 OPT_BOOLEAN('v', "invert-match", &opt.invert,
678 "show non-matching lines"),
679 OPT_BIT('i', "ignore-case", &opt.regflags,
680 "case insensitive matching", REG_ICASE),
681 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
682 "match patterns only at word boundaries"),
683 OPT_SET_INT('a', "text", &opt.binary,
684 "process binary files as text", GREP_BINARY_TEXT),
685 OPT_SET_INT('I', NULL, &opt.binary,
686 "don't match patterns in binary files",
687 GREP_BINARY_NOMATCH),
688 OPT_GROUP(""),
689 OPT_BIT('E', "extended-regexp", &opt.regflags,
690 "use extended POSIX regular expressions", REG_EXTENDED),
691 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
692 "use basic POSIX regular expressions (default)",
693 REG_EXTENDED),
694 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
695 "interpret patterns as fixed strings"),
696 OPT_GROUP(""),
697 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
698 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
699 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
700 OPT_NEGBIT(0, "full-name", &opt.relative,
701 "show filenames relative to top directory", 1),
702 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
703 "show only filenames instead of matching lines"),
704 OPT_BOOLEAN(0, "name-only", &opt.name_only,
705 "synonym for --files-with-matches"),
706 OPT_BOOLEAN('L', "files-without-match",
707 &opt.unmatch_name_only,
708 "show only the names of files without match"),
709 OPT_BOOLEAN('z', "null", &opt.null_following_name,
710 "print NUL after filenames"),
711 OPT_BOOLEAN('c', "count", &opt.count,
712 "show the number of matches instead of matching lines"),
713 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
714 OPT_GROUP(""),
715 OPT_CALLBACK('C', NULL, &opt, "n",
716 "show <n> context lines before and after matches",
717 context_callback),
718 OPT_INTEGER('B', NULL, &opt.pre_context,
719 "show <n> context lines before matches"),
720 OPT_INTEGER('A', NULL, &opt.post_context,
721 "show <n> context lines after matches"),
722 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
723 context_callback),
724 OPT_GROUP(""),
725 OPT_CALLBACK('f', NULL, &opt, "file",
726 "read patterns from file", file_callback),
727 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
728 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
729 { OPTION_CALLBACK, 0, "and", &opt, NULL,
730 "combine patterns specified with -e",
731 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
732 OPT_BOOLEAN(0, "or", &dummy, ""),
733 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
734 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
735 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
736 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
737 open_callback },
738 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
739 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
740 close_callback },
741 OPT_BOOLEAN(0, "all-match", &opt.all_match,
742 "show only matches from files that match all patterns"),
743 OPT_GROUP(""),
744#if NO_EXTERNAL_GREP
745 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
746 "allow calling of grep(1) (ignored by this build)"),
747#else
748 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
749 "allow calling of grep(1) (default)"),
750#endif
751 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
752 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
753 OPT_END()
754 };
5010cb5f
JH
755
756 memset(&opt, 0, sizeof(opt));
0d042fec
JH
757 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
758 opt.relative = 1;
7977f0ea 759 opt.pathname = 1;
f9b9faf6 760 opt.pattern_tail = &opt.pattern_list;
5010cb5f
JH
761 opt.regflags = REG_NEWLINE;
762
7e8f59d5
RS
763 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
764 opt.color = -1;
765 git_config(grep_config, &opt);
766 if (opt.color == -1)
767 opt.color = git_use_color_default;
768
5010cb5f 769 /*
5acd64ed
JH
770 * If there is no -- then the paths must exist in the working
771 * tree. If there is no explicit pattern specified with -e or
772 * -f, we take the first unrecognized non option to be the
773 * pattern, but then what follows it must be zero or more
774 * valid refs up to the -- (if exists), and then existing
775 * paths. If there is an explicit pattern, then the first
82e5a82f 776 * unrecognized non option is the beginning of the refs list
5acd64ed 777 * that continues up to the -- (if exists), and then paths.
5010cb5f 778 */
37782920 779 argc = parse_options(argc, argv, prefix, options, grep_usage,
3e230fa1
RS
780 PARSE_OPT_KEEP_DASHDASH |
781 PARSE_OPT_STOP_AT_NON_OPTION |
782 PARSE_OPT_NO_INTERNAL_HELP);
783
784 /* First unrecognized non-option token */
785 if (argc > 0 && !opt.pattern_list) {
786 append_grep_pattern(&opt, argv[0], "command line", 0,
787 GREP_PATTERN);
788 argv++;
789 argc--;
5010cb5f 790 }
5acd64ed 791
6e89ec0f 792 if (opt.color && !opt.color_external)
1b5fb44a 793 external_grep_allowed = 0;
f9b9faf6 794 if (!opt.pattern_list)
5010cb5f 795 die("no pattern given.");
07ea91d8
JH
796 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
797 die("cannot mix --fixed-strings and regexp");
83b5d2f5 798 compile_grep_patterns(&opt);
5acd64ed
JH
799
800 /* Check revs and then paths */
3e230fa1 801 for (i = 0; i < argc; i++) {
5acd64ed 802 const char *arg = argv[i];
1362671f 803 unsigned char sha1[20];
5acd64ed
JH
804 /* Is it a rev? */
805 if (!get_sha1(arg, sha1)) {
806 struct object *object = parse_object(sha1);
5acd64ed
JH
807 if (!object)
808 die("bad object %s", arg);
1f1e895f 809 add_object_array(object, arg, &list);
5acd64ed
JH
810 continue;
811 }
812 if (!strcmp(arg, "--")) {
813 i++;
814 seen_dashdash = 1;
815 }
816 break;
1362671f 817 }
5acd64ed
JH
818
819 /* The rest are paths */
820 if (!seen_dashdash) {
821 int j;
c39c4f47 822 for (j = i; j < argc; j++)
5acd64ed
JH
823 verify_filename(prefix, argv[j]);
824 }
825
0d042fec 826 if (i < argc) {
5acd64ed 827 paths = get_pathspec(prefix, argv + i);
0d042fec
JH
828 if (opt.prefix_length && opt.relative) {
829 /* Make sure we do not get outside of paths */
830 for (i = 0; paths[i]; i++)
831 if (strncmp(prefix, paths[i], opt.prefix_length))
7e44c935 832 die("git grep: cannot generate relative filenames containing '..'");
0d042fec
JH
833 }
834 }
1362671f
JH
835 else if (prefix) {
836 paths = xcalloc(2, sizeof(const char *));
837 paths[0] = prefix;
838 paths[1] = NULL;
839 }
5010cb5f 840
6577f542
NTND
841 if (!list.nr) {
842 if (!cached)
843 setup_work_tree();
1b5fb44a 844 return !grep_cache(&opt, paths, cached, external_grep_allowed);
6577f542 845 }
aa8c79ad 846
5010cb5f 847 if (cached)
aa8c79ad 848 die("both --cached and trees are given.");
5010cb5f 849
1f1e895f 850 for (i = 0; i < list.nr; i++) {
5010cb5f 851 struct object *real_obj;
1f1e895f
LT
852 real_obj = deref_tag(list.objects[i].item, NULL, 0);
853 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
5010cb5f
JH
854 hit = 1;
855 }
b48fb5b6 856 free_grep_patterns(&opt);
5010cb5f
JH
857 return !hit;
858}