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