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