Add GIT_COLOR_BOLD_* and GIT_COLOR_BG_*
[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"
59332d13 17#include "dir.h"
5f7c643a 18
5b594f45
FK
19#ifndef NO_PTHREADS
20#include "thread-utils.h"
21#include <pthread.h>
22#endif
23
3e230fa1
RS
24static char const * const grep_usage[] = {
25 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
26 NULL
27};
28
5b594f45
FK
29static int use_threads = 1;
30
31#ifndef NO_PTHREADS
32#define THREADS 8
33static pthread_t threads[THREADS];
34
35static void *load_sha1(const unsigned char *sha1, unsigned long *size,
36 const char *name);
37static void *load_file(const char *filename, size_t *sz);
38
39enum work_type {WORK_SHA1, WORK_FILE};
40
41/* We use one producer thread and THREADS consumer
42 * threads. The producer adds struct work_items to 'todo' and the
43 * consumers pick work items from the same array.
44 */
45struct work_item
46{
47 enum work_type type;
48 char *name;
49
50 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
51 * otherwise type == WORK_FILE, and 'identifier' is a NUL
52 * terminated filename.
53 */
54 void *identifier;
55 char done;
56 struct strbuf out;
57};
58
59/* In the range [todo_done, todo_start) in 'todo' we have work_items
60 * that have been or are processed by a consumer thread. We haven't
61 * written the result for these to stdout yet.
62 *
63 * The work_items in [todo_start, todo_end) are waiting to be picked
64 * up by a consumer thread.
65 *
66 * The ranges are modulo TODO_SIZE.
67 */
68#define TODO_SIZE 128
69static struct work_item todo[TODO_SIZE];
70static int todo_start;
71static int todo_end;
72static int todo_done;
73
74/* Has all work items been added? */
75static int all_work_added;
76
77/* This lock protects all the variables above. */
78static pthread_mutex_t grep_mutex;
79
80/* Used to serialize calls to read_sha1_file. */
81static pthread_mutex_t read_sha1_mutex;
82
83#define grep_lock() pthread_mutex_lock(&grep_mutex)
84#define grep_unlock() pthread_mutex_unlock(&grep_mutex)
85#define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
86#define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
87
88/* Signalled when a new work_item is added to todo. */
89static pthread_cond_t cond_add;
90
91/* Signalled when the result from one work_item is written to
92 * stdout.
93 */
94static pthread_cond_t cond_write;
95
96/* Signalled when we are finished with everything. */
97static pthread_cond_t cond_result;
98
99static void add_work(enum work_type type, char *name, void *id)
100{
101 grep_lock();
102
103 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
104 pthread_cond_wait(&cond_write, &grep_mutex);
105 }
106
107 todo[todo_end].type = type;
108 todo[todo_end].name = name;
109 todo[todo_end].identifier = id;
110 todo[todo_end].done = 0;
111 strbuf_reset(&todo[todo_end].out);
112 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
113
114 pthread_cond_signal(&cond_add);
115 grep_unlock();
116}
117
118static struct work_item *get_work(void)
119{
120 struct work_item *ret;
121
122 grep_lock();
123 while (todo_start == todo_end && !all_work_added) {
124 pthread_cond_wait(&cond_add, &grep_mutex);
125 }
126
127 if (todo_start == todo_end && all_work_added) {
128 ret = NULL;
129 } else {
130 ret = &todo[todo_start];
131 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
132 }
133 grep_unlock();
134 return ret;
135}
136
137static void grep_sha1_async(struct grep_opt *opt, char *name,
138 const unsigned char *sha1)
139{
140 unsigned char *s;
141 s = xmalloc(20);
142 memcpy(s, sha1, 20);
143 add_work(WORK_SHA1, name, s);
144}
145
146static void grep_file_async(struct grep_opt *opt, char *name,
147 const char *filename)
148{
149 add_work(WORK_FILE, name, xstrdup(filename));
150}
151
152static void work_done(struct work_item *w)
153{
154 int old_done;
155
156 grep_lock();
157 w->done = 1;
158 old_done = todo_done;
159 for(; todo[todo_done].done && todo_done != todo_start;
160 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
161 w = &todo[todo_done];
162 write_or_die(1, w->out.buf, w->out.len);
163 free(w->name);
164 free(w->identifier);
165 }
166
167 if (old_done != todo_done)
168 pthread_cond_signal(&cond_write);
169
170 if (all_work_added && todo_done == todo_end)
171 pthread_cond_signal(&cond_result);
172
173 grep_unlock();
174}
175
176static void *run(void *arg)
177{
178 int hit = 0;
179 struct grep_opt *opt = arg;
180
181 while (1) {
182 struct work_item *w = get_work();
183 if (!w)
184 break;
185
186 opt->output_priv = w;
187 if (w->type == WORK_SHA1) {
188 unsigned long sz;
189 void* data = load_sha1(w->identifier, &sz, w->name);
190
191 if (data) {
192 hit |= grep_buffer(opt, w->name, data, sz);
193 free(data);
194 }
195 } else if (w->type == WORK_FILE) {
196 size_t sz;
197 void* data = load_file(w->identifier, &sz);
198 if (data) {
199 hit |= grep_buffer(opt, w->name, data, sz);
200 free(data);
201 }
202 } else {
203 assert(0);
204 }
205
206 work_done(w);
207 }
bfac23d9
DM
208 free_grep_patterns(arg);
209 free(arg);
5b594f45
FK
210
211 return (void*) (intptr_t) hit;
212}
213
214static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
215{
216 struct work_item *w = opt->output_priv;
217 strbuf_add(&w->out, buf, size);
218}
219
220static void start_threads(struct grep_opt *opt)
221{
222 int i;
223
224 pthread_mutex_init(&grep_mutex, NULL);
225 pthread_mutex_init(&read_sha1_mutex, NULL);
226 pthread_cond_init(&cond_add, NULL);
227 pthread_cond_init(&cond_write, NULL);
228 pthread_cond_init(&cond_result, NULL);
229
230 for (i = 0; i < ARRAY_SIZE(todo); i++) {
231 strbuf_init(&todo[i].out, 0);
232 }
233
234 for (i = 0; i < ARRAY_SIZE(threads); i++) {
235 int err;
236 struct grep_opt *o = grep_opt_dup(opt);
237 o->output = strbuf_out;
238 compile_grep_patterns(o);
239 err = pthread_create(&threads[i], NULL, run, o);
240
241 if (err)
242 die("grep: failed to create thread: %s",
243 strerror(err));
244 }
245}
246
247static int wait_all(void)
248{
249 int hit = 0;
250 int i;
251
252 grep_lock();
253 all_work_added = 1;
254
255 /* Wait until all work is done. */
256 while (todo_done != todo_end)
257 pthread_cond_wait(&cond_result, &grep_mutex);
258
259 /* Wake up all the consumer threads so they can see that there
260 * is no more work to do.
261 */
262 pthread_cond_broadcast(&cond_add);
263 grep_unlock();
264
265 for (i = 0; i < ARRAY_SIZE(threads); i++) {
266 void *h;
267 pthread_join(threads[i], &h);
268 hit |= (int) (intptr_t) h;
269 }
270
271 pthread_mutex_destroy(&grep_mutex);
272 pthread_mutex_destroy(&read_sha1_mutex);
273 pthread_cond_destroy(&cond_add);
274 pthread_cond_destroy(&cond_write);
275 pthread_cond_destroy(&cond_result);
276
277 return hit;
278}
279#else /* !NO_PTHREADS */
280#define read_sha1_lock()
281#define read_sha1_unlock()
282
283static int wait_all(void)
284{
285 return 0;
286}
287#endif
288
7e8f59d5
RS
289static int grep_config(const char *var, const char *value, void *cb)
290{
291 struct grep_opt *opt = cb;
292
60ecac98
RS
293 switch (userdiff_config(var, value)) {
294 case 0: break;
295 case -1: return -1;
296 default: return 0;
297 }
298
fe3420b6 299 if (!strcmp(var, "color.grep")) {
7e8f59d5
RS
300 opt->color = git_config_colorbool(var, value, -1);
301 return 0;
302 }
fe3420b6 303 if (!strcmp(var, "color.grep.match")) {
7e8f59d5
RS
304 if (!value)
305 return config_error_nonbool(var);
306 color_parse(value, var, opt->color_match);
307 return 0;
308 }
309 return git_color_default_config(var, value, cb);
310}
311
a91f453f
MK
312/*
313 * Return non-zero if max_depth is negative or path has no more then max_depth
314 * slashes.
315 */
316static int accept_subdir(const char *path, int max_depth)
317{
318 if (max_depth < 0)
319 return 1;
320
321 while ((path = strchr(path, '/')) != NULL) {
322 max_depth--;
323 if (max_depth < 0)
324 return 0;
325 path++;
326 }
327 return 1;
328}
329
330/*
331 * Return non-zero if name is a subdirectory of match and is not too deep.
332 */
333static int is_subdir(const char *name, int namelen,
334 const char *match, int matchlen, int max_depth)
335{
336 if (matchlen > namelen || strncmp(name, match, matchlen))
337 return 0;
338
339 if (name[matchlen] == '\0') /* exact match */
340 return 1;
341
342 if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
343 return accept_subdir(name + matchlen + 1, max_depth);
344
345 return 0;
346}
347
e0eb889f
JH
348/*
349 * git grep pathspecs are somewhat different from diff-tree pathspecs;
350 * pathname wildcards are allowed.
351 */
a91f453f 352static int pathspec_matches(const char **paths, const char *name, int max_depth)
5010cb5f 353{
e0eb889f 354 int namelen, i;
1362671f 355 if (!paths || !*paths)
a91f453f 356 return accept_subdir(name, max_depth);
5010cb5f 357 namelen = strlen(name);
1362671f
JH
358 for (i = 0; paths[i]; i++) {
359 const char *match = paths[i];
360 int matchlen = strlen(match);
1e3d90e0 361 const char *cp, *meta;
e0eb889f 362
a91f453f 363 if (is_subdir(name, namelen, match, matchlen, max_depth))
e0eb889f
JH
364 return 1;
365 if (!fnmatch(match, name, 0))
366 return 1;
367 if (name[namelen-1] != '/')
5010cb5f 368 continue;
e0eb889f 369
1e3d90e0 370 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
371 * descending into.
372 *
373 * Find the longest leading directory name that does
374 * not have metacharacter in the pathspec; the name
375 * we are looking at must overlap with that directory.
5010cb5f 376 */
1e3d90e0 377 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 378 char ch = *cp;
1e3d90e0
JH
379 if (ch == '*' || ch == '[' || ch == '?') {
380 meta = cp;
5010cb5f 381 break;
1e3d90e0 382 }
e0eb889f 383 }
1e3d90e0
JH
384 if (!meta)
385 meta = cp; /* fully literal */
386
387 if (namelen <= meta - match) {
e0eb889f
JH
388 /* Looking at "Documentation/" and
389 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
390 * "Documentation/diff*.txt". The name we
391 * have should match prefix.
e0eb889f
JH
392 */
393 if (!memcmp(match, name, namelen))
394 return 1;
1e3d90e0 395 continue;
e0eb889f 396 }
1e3d90e0
JH
397
398 if (meta - match < namelen) {
e0eb889f 399 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
400 * the pattern says "Documentation/h*";
401 * match up to "Do.../h"; this avoids descending
402 * into "Documentation/technical/".
e0eb889f 403 */
1e3d90e0 404 if (!memcmp(match, name, meta - match))
e0eb889f 405 return 1;
1e3d90e0 406 continue;
e0eb889f 407 }
5010cb5f
JH
408 }
409 return 0;
410}
411
5f02d315
JH
412static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
413{
414 void *data;
415
416 if (use_threads) {
417 read_sha1_lock();
418 data = read_sha1_file(sha1, type, size);
419 read_sha1_unlock();
420 } else {
421 data = read_sha1_file(sha1, type, size);
422 }
423 return data;
424}
425
5b594f45
FK
426static void *load_sha1(const unsigned char *sha1, unsigned long *size,
427 const char *name)
5010cb5f 428{
21666f1a 429 enum object_type type;
5f02d315 430 void *data = lock_and_read_sha1_file(sha1, &type, size);
5b594f45
FK
431
432 if (!data)
5010cb5f 433 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
5b594f45
FK
434
435 return data;
436}
437
438static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
439 const char *filename, int tree_name_len)
440{
441 struct strbuf pathbuf = STRBUF_INIT;
442 char *name;
443
0d042fec 444 if (opt->relative && opt->prefix_length) {
5b594f45
FK
445 quote_path_relative(filename + tree_name_len, -1, &pathbuf,
446 opt->prefix);
447 strbuf_insert(&pathbuf, 0, filename, tree_name_len);
448 } else {
449 strbuf_addstr(&pathbuf, filename);
450 }
451
452 name = strbuf_detach(&pathbuf, NULL);
453
454#ifndef NO_PTHREADS
455 if (use_threads) {
456 grep_sha1_async(opt, name, sha1);
457 return 0;
458 } else
459#endif
460 {
461 int hit;
462 unsigned long sz;
463 void *data = load_sha1(sha1, &sz, name);
464 if (!data)
465 hit = 0;
466 else
467 hit = grep_buffer(opt, name, data, sz);
468
469 free(data);
470 free(name);
471 return hit;
0d042fec 472 }
5010cb5f
JH
473}
474
5b594f45 475static void *load_file(const char *filename, size_t *sz)
5010cb5f
JH
476{
477 struct stat st;
5010cb5f 478 char *data;
5b594f45 479 int i;
dc49cd76 480
5010cb5f
JH
481 if (lstat(filename, &st) < 0) {
482 err_ret:
483 if (errno != ENOENT)
484 error("'%s': %s", filename, strerror(errno));
485 return 0;
486 }
5010cb5f
JH
487 if (!S_ISREG(st.st_mode))
488 return 0;
5b594f45 489 *sz = xsize_t(st.st_size);
5010cb5f
JH
490 i = open(filename, O_RDONLY);
491 if (i < 0)
492 goto err_ret;
5b594f45
FK
493 data = xmalloc(*sz + 1);
494 if (st.st_size != read_in_full(i, data, *sz)) {
5010cb5f
JH
495 error("'%s': short read %s", filename, strerror(errno));
496 close(i);
497 free(data);
498 return 0;
499 }
500 close(i);
5b594f45
FK
501 data[*sz] = 0;
502 return data;
503}
504
505static int grep_file(struct grep_opt *opt, const char *filename)
506{
507 struct strbuf buf = STRBUF_INIT;
508 char *name;
509
0d042fec 510 if (opt->relative && opt->prefix_length)
5b594f45
FK
511 quote_path_relative(filename, -1, &buf, opt->prefix);
512 else
513 strbuf_addstr(&buf, filename);
514 name = strbuf_detach(&buf, NULL);
515
516#ifndef NO_PTHREADS
517 if (use_threads) {
518 grep_file_async(opt, name, filename);
519 return 0;
520 } else
521#endif
522 {
523 int hit;
524 size_t sz;
525 void *data = load_file(filename, &sz);
526 if (!data)
527 hit = 0;
528 else
529 hit = grep_buffer(opt, name, data, sz);
530
531 free(data);
532 free(name);
533 return hit;
534 }
5010cb5f
JH
535}
536
bbc09c22 537static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
5010cb5f
JH
538{
539 int hit = 0;
540 int nr;
541 read_cache();
542
543 for (nr = 0; nr < active_nr; nr++) {
544 struct cache_entry *ce = active_cache[nr];
7a51ed66 545 if (!S_ISREG(ce->ce_mode))
5010cb5f 546 continue;
a91f453f 547 if (!pathspec_matches(paths, ce->name, opt->max_depth))
5010cb5f 548 continue;
57d43466
NTND
549 /*
550 * If CE_VALID is on, we assume worktree file and its cache entry
551 * are identical, even if worktree file has been modified, so use
552 * cache version instead
553 */
b4d1690d 554 if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
36f2587f
JH
555 if (ce_stage(ce))
556 continue;
0d042fec 557 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
36f2587f 558 }
5010cb5f
JH
559 else
560 hit |= grep_file(opt, ce->name);
36f2587f
JH
561 if (ce_stage(ce)) {
562 do {
563 nr++;
564 } while (nr < active_nr &&
565 !strcmp(ce->name, active_cache[nr]->name));
566 nr--; /* compensate for loop control */
567 }
c8610a2e
JH
568 if (hit && opt->status_only)
569 break;
5010cb5f 570 }
b48fb5b6 571 free_grep_patterns(opt);
5010cb5f
JH
572 return hit;
573}
574
1362671f 575static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
576 struct tree_desc *tree,
577 const char *tree_name, const char *base)
578{
5010cb5f
JH
579 int len;
580 int hit = 0;
4c068a98 581 struct name_entry entry;
e0eb889f 582 char *down;
0d042fec 583 int tn_len = strlen(tree_name);
620e2bb9
DP
584 struct strbuf pathbuf;
585
586 strbuf_init(&pathbuf, PATH_MAX + tn_len);
5010cb5f 587
0d042fec 588 if (tn_len) {
620e2bb9
DP
589 strbuf_add(&pathbuf, tree_name, tn_len);
590 strbuf_addch(&pathbuf, ':');
591 tn_len = pathbuf.len;
5010cb5f 592 }
620e2bb9
DP
593 strbuf_addstr(&pathbuf, base);
594 len = pathbuf.len;
5010cb5f 595
4c068a98 596 while (tree_entry(tree, &entry)) {
620e2bb9
DP
597 int te_len = tree_entry_len(entry.path, entry.sha1);
598 pathbuf.len = len;
599 strbuf_add(&pathbuf, entry.path, te_len);
5010cb5f 600
4c068a98 601 if (S_ISDIR(entry.mode))
e0eb889f
JH
602 /* Match "abc/" against pathspec to
603 * decide if we want to descend into "abc"
604 * directory.
605 */
620e2bb9 606 strbuf_addch(&pathbuf, '/');
e0eb889f 607
620e2bb9 608 down = pathbuf.buf + tn_len;
a91f453f 609 if (!pathspec_matches(paths, down, opt->max_depth))
5010cb5f 610 ;
4c068a98 611 else if (S_ISREG(entry.mode))
620e2bb9 612 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
4c068a98 613 else if (S_ISDIR(entry.mode)) {
21666f1a 614 enum object_type type;
5010cb5f
JH
615 struct tree_desc sub;
616 void *data;
6fda5e51
LT
617 unsigned long size;
618
5f02d315 619 data = lock_and_read_sha1_file(entry.sha1, &type, &size);
5010cb5f
JH
620 if (!data)
621 die("unable to read tree (%s)",
4c068a98 622 sha1_to_hex(entry.sha1));
6fda5e51 623 init_tree_desc(&sub, data, size);
1362671f 624 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
625 free(data);
626 }
c8610a2e
JH
627 if (hit && opt->status_only)
628 break;
5010cb5f 629 }
620e2bb9 630 strbuf_release(&pathbuf);
5010cb5f
JH
631 return hit;
632}
633
1362671f 634static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
635 struct object *obj, const char *name)
636{
1974632c 637 if (obj->type == OBJ_BLOB)
0d042fec 638 return grep_sha1(opt, obj->sha1, name, 0);
1974632c 639 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
640 struct tree_desc tree;
641 void *data;
6fda5e51 642 unsigned long size;
5010cb5f
JH
643 int hit;
644 data = read_object_with_reference(obj->sha1, tree_type,
6fda5e51 645 &size, NULL);
5010cb5f
JH
646 if (!data)
647 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
6fda5e51 648 init_tree_desc(&tree, data, size);
1362671f 649 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
650 free(data);
651 return hit;
652 }
885a86ab 653 die("unable to grep from object of type %s", typename(obj->type));
5010cb5f
JH
654}
655
59332d13
JH
656static int grep_directory(struct grep_opt *opt, const char **paths)
657{
658 struct dir_struct dir;
659 int i, hit = 0;
660
661 memset(&dir, 0, sizeof(dir));
662 setup_standard_excludes(&dir);
663
664 fill_directory(&dir, paths);
665 for (i = 0; i < dir.nr; i++) {
666 hit |= grep_file(opt, dir.entries[i]->name);
667 if (hit && opt->status_only)
668 break;
669 }
670 free_grep_patterns(opt);
671 return hit;
672}
673
ff3c7f9a
RS
674static int context_callback(const struct option *opt, const char *arg,
675 int unset)
3e230fa1
RS
676{
677 struct grep_opt *grep_opt = opt->value;
678 int value;
679 const char *endp;
680
681 if (unset) {
682 grep_opt->pre_context = grep_opt->post_context = 0;
683 return 0;
684 }
685 value = strtol(arg, (char **)&endp, 10);
686 if (*endp) {
687 return error("switch `%c' expects a numerical value",
688 opt->short_name);
689 }
690 grep_opt->pre_context = grep_opt->post_context = value;
691 return 0;
692}
693
ff3c7f9a 694static int file_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
695{
696 struct grep_opt *grep_opt = opt->value;
697 FILE *patterns;
698 int lno = 0;
cfe370c6 699 struct strbuf sb = STRBUF_INIT;
3e230fa1
RS
700
701 patterns = fopen(arg, "r");
702 if (!patterns)
d824cbba 703 die_errno("cannot open '%s'", arg);
3e230fa1
RS
704 while (strbuf_getline(&sb, patterns, '\n') == 0) {
705 /* ignore empty line like grep does */
706 if (sb.len == 0)
707 continue;
708 append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
709 ++lno, GREP_PATTERN);
710 }
711 fclose(patterns);
712 strbuf_release(&sb);
713 return 0;
714}
715
ff3c7f9a 716static int not_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
717{
718 struct grep_opt *grep_opt = opt->value;
719 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
720 return 0;
721}
722
ff3c7f9a 723static int and_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
724{
725 struct grep_opt *grep_opt = opt->value;
726 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
727 return 0;
728}
729
ff3c7f9a 730static int open_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
731{
732 struct grep_opt *grep_opt = opt->value;
733 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
734 return 0;
735}
736
ff3c7f9a 737static int close_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
738{
739 struct grep_opt *grep_opt = opt->value;
740 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
741 return 0;
742}
743
ff3c7f9a
RS
744static int pattern_callback(const struct option *opt, const char *arg,
745 int unset)
3e230fa1
RS
746{
747 struct grep_opt *grep_opt = opt->value;
748 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
749 return 0;
750}
5010cb5f 751
ff3c7f9a 752static int help_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
753{
754 return -1;
755}
088b084b 756
a633fca0 757int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 758{
5010cb5f 759 int hit = 0;
5010cb5f 760 int cached = 0;
5acd64ed 761 int seen_dashdash = 0;
bbc09c22 762 int external_grep_allowed__ignored;
5010cb5f 763 struct grep_opt opt;
1f1e895f 764 struct object_array list = { 0, 0, NULL };
1362671f 765 const char **paths = NULL;
5acd64ed 766 int i;
3e230fa1 767 int dummy;
59332d13 768 int nongit = 0, use_index = 1;
3e230fa1
RS
769 struct option options[] = {
770 OPT_BOOLEAN(0, "cached", &cached,
771 "search in index instead of in the work tree"),
59332d13
JH
772 OPT_BOOLEAN(0, "index", &use_index,
773 "--no-index finds in contents not managed by git"),
3e230fa1
RS
774 OPT_GROUP(""),
775 OPT_BOOLEAN('v', "invert-match", &opt.invert,
776 "show non-matching lines"),
5183bf67
BC
777 OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
778 "case insensitive matching"),
3e230fa1
RS
779 OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
780 "match patterns only at word boundaries"),
781 OPT_SET_INT('a', "text", &opt.binary,
782 "process binary files as text", GREP_BINARY_TEXT),
783 OPT_SET_INT('I', NULL, &opt.binary,
784 "don't match patterns in binary files",
785 GREP_BINARY_NOMATCH),
a91f453f
MK
786 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
787 "descend at most <depth> levels", PARSE_OPT_NONEG,
788 NULL, 1 },
3e230fa1
RS
789 OPT_GROUP(""),
790 OPT_BIT('E', "extended-regexp", &opt.regflags,
791 "use extended POSIX regular expressions", REG_EXTENDED),
792 OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
793 "use basic POSIX regular expressions (default)",
794 REG_EXTENDED),
795 OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
796 "interpret patterns as fixed strings"),
797 OPT_GROUP(""),
798 OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
799 OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
800 OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
801 OPT_NEGBIT(0, "full-name", &opt.relative,
802 "show filenames relative to top directory", 1),
803 OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
804 "show only filenames instead of matching lines"),
805 OPT_BOOLEAN(0, "name-only", &opt.name_only,
806 "synonym for --files-with-matches"),
807 OPT_BOOLEAN('L', "files-without-match",
808 &opt.unmatch_name_only,
809 "show only the names of files without match"),
810 OPT_BOOLEAN('z', "null", &opt.null_following_name,
811 "print NUL after filenames"),
812 OPT_BOOLEAN('c', "count", &opt.count,
813 "show the number of matches instead of matching lines"),
814 OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
815 OPT_GROUP(""),
816 OPT_CALLBACK('C', NULL, &opt, "n",
817 "show <n> context lines before and after matches",
818 context_callback),
819 OPT_INTEGER('B', NULL, &opt.pre_context,
820 "show <n> context lines before matches"),
821 OPT_INTEGER('A', NULL, &opt.post_context,
822 "show <n> context lines after matches"),
823 OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
824 context_callback),
2944e4e6
RS
825 OPT_BOOLEAN('p', "show-function", &opt.funcname,
826 "show a line with the function name before matches"),
3e230fa1
RS
827 OPT_GROUP(""),
828 OPT_CALLBACK('f', NULL, &opt, "file",
829 "read patterns from file", file_callback),
830 { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
831 "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
832 { OPTION_CALLBACK, 0, "and", &opt, NULL,
833 "combine patterns specified with -e",
834 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
835 OPT_BOOLEAN(0, "or", &dummy, ""),
836 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
837 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
838 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
839 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
840 open_callback },
841 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
842 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
843 close_callback },
4ff61c21 844 OPT_BOOLEAN('q', "quiet", &opt.status_only,
c8610a2e 845 "indicate hit with exit status without output"),
3e230fa1
RS
846 OPT_BOOLEAN(0, "all-match", &opt.all_match,
847 "show only matches from files that match all patterns"),
848 OPT_GROUP(""),
bbc09c22
JH
849 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
850 "allow calling of grep(1) (ignored by this build)"),
3e230fa1
RS
851 { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
852 PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
853 OPT_END()
854 };
5010cb5f 855
59332d13
JH
856 prefix = setup_git_directory_gently(&nongit);
857
9c855c31
JN
858 /*
859 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
860 * to show usage information and exit.
861 */
862 if (argc == 2 && !strcmp(argv[1], "-h"))
863 usage_with_options(grep_usage, options);
864
5010cb5f 865 memset(&opt, 0, sizeof(opt));
493b7a08 866 opt.prefix = prefix;
0d042fec
JH
867 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
868 opt.relative = 1;
7977f0ea 869 opt.pathname = 1;
f9b9faf6 870 opt.pattern_tail = &opt.pattern_list;
5010cb5f 871 opt.regflags = REG_NEWLINE;
a91f453f 872 opt.max_depth = -1;
5010cb5f 873
758df17a 874 strcpy(opt.color_match, GIT_COLOR_BOLD_RED);
7e8f59d5
RS
875 opt.color = -1;
876 git_config(grep_config, &opt);
877 if (opt.color == -1)
878 opt.color = git_use_color_default;
879
5010cb5f 880 /*
5acd64ed
JH
881 * If there is no -- then the paths must exist in the working
882 * tree. If there is no explicit pattern specified with -e or
883 * -f, we take the first unrecognized non option to be the
884 * pattern, but then what follows it must be zero or more
885 * valid refs up to the -- (if exists), and then existing
886 * paths. If there is an explicit pattern, then the first
82e5a82f 887 * unrecognized non option is the beginning of the refs list
5acd64ed 888 * that continues up to the -- (if exists), and then paths.
5010cb5f 889 */
37782920 890 argc = parse_options(argc, argv, prefix, options, grep_usage,
3e230fa1
RS
891 PARSE_OPT_KEEP_DASHDASH |
892 PARSE_OPT_STOP_AT_NON_OPTION |
893 PARSE_OPT_NO_INTERNAL_HELP);
894
59332d13
JH
895 if (use_index && nongit)
896 /* die the same way as if we did it at the beginning */
897 setup_git_directory();
898
1123c67c
JK
899 /*
900 * skip a -- separator; we know it cannot be
901 * separating revisions from pathnames if
902 * we haven't even had any patterns yet
903 */
904 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
905 argv++;
906 argc--;
907 }
908
3e230fa1
RS
909 /* First unrecognized non-option token */
910 if (argc > 0 && !opt.pattern_list) {
911 append_grep_pattern(&opt, argv[0], "command line", 0,
912 GREP_PATTERN);
913 argv++;
914 argc--;
5010cb5f 915 }
5acd64ed 916
f9b9faf6 917 if (!opt.pattern_list)
5010cb5f 918 die("no pattern given.");
5183bf67
BC
919 if (!opt.fixed && opt.ignore_case)
920 opt.regflags |= REG_ICASE;
07ea91d8
JH
921 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
922 die("cannot mix --fixed-strings and regexp");
5b594f45
FK
923
924#ifndef NO_PTHREADS
925 if (online_cpus() == 1 || !grep_threads_ok(&opt))
926 use_threads = 0;
927
928 if (use_threads)
929 start_threads(&opt);
930#else
931 use_threads = 0;
932#endif
933
83b5d2f5 934 compile_grep_patterns(&opt);
5acd64ed
JH
935
936 /* Check revs and then paths */
3e230fa1 937 for (i = 0; i < argc; i++) {
5acd64ed 938 const char *arg = argv[i];
1362671f 939 unsigned char sha1[20];
5acd64ed
JH
940 /* Is it a rev? */
941 if (!get_sha1(arg, sha1)) {
942 struct object *object = parse_object(sha1);
5acd64ed
JH
943 if (!object)
944 die("bad object %s", arg);
1f1e895f 945 add_object_array(object, arg, &list);
5acd64ed
JH
946 continue;
947 }
948 if (!strcmp(arg, "--")) {
949 i++;
950 seen_dashdash = 1;
951 }
952 break;
1362671f 953 }
5acd64ed
JH
954
955 /* The rest are paths */
956 if (!seen_dashdash) {
957 int j;
c39c4f47 958 for (j = i; j < argc; j++)
5acd64ed
JH
959 verify_filename(prefix, argv[j]);
960 }
961
493b7a08 962 if (i < argc)
5acd64ed 963 paths = get_pathspec(prefix, argv + i);
1362671f
JH
964 else if (prefix) {
965 paths = xcalloc(2, sizeof(const char *));
966 paths[0] = prefix;
967 paths[1] = NULL;
968 }
5010cb5f 969
59332d13
JH
970 if (!use_index) {
971 int hit;
972 if (cached)
973 die("--cached cannot be used with --no-index.");
974 if (list.nr)
975 die("--no-index cannot be used with revs.");
976 hit = grep_directory(&opt, paths);
977 if (use_threads)
978 hit |= wait_all();
979 return !hit;
980 }
981
6577f542 982 if (!list.nr) {
5b594f45 983 int hit;
6577f542
NTND
984 if (!cached)
985 setup_work_tree();
5b594f45
FK
986
987 hit = grep_cache(&opt, paths, cached);
988 if (use_threads)
989 hit |= wait_all();
990 return !hit;
6577f542 991 }
aa8c79ad 992
5010cb5f 993 if (cached)
aa8c79ad 994 die("both --cached and trees are given.");
5010cb5f 995
1f1e895f 996 for (i = 0; i < list.nr; i++) {
5010cb5f 997 struct object *real_obj;
1f1e895f 998 real_obj = deref_tag(list.objects[i].item, NULL, 0);
c8610a2e 999 if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
5010cb5f 1000 hit = 1;
c8610a2e
JH
1001 if (opt.status_only)
1002 break;
1003 }
5010cb5f 1004 }
5b594f45
FK
1005
1006 if (use_threads)
1007 hit |= wait_all();
b48fb5b6 1008 free_grep_patterns(&opt);
5010cb5f
JH
1009 return !hit;
1010}