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