]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/grep.c
grep: prefer "struct grep_opt" over its "void *" equivalent
[thirdparty/git.git] / builtin / grep.c
CommitLineData
5010cb5f
JH
1/*
2 * Builtin "git grep"
3 *
4 * Copyright (c) 2006 Junio C Hamano
5 */
f8adbec9 6#define USE_THE_INDEX_COMPATIBILITY_MACROS
5010cb5f 7#include "cache.h"
627d9342 8#include "repository.h"
b2141fc1 9#include "config.h"
5010cb5f
JH
10#include "blob.h"
11#include "tree.h"
12#include "commit.h"
13#include "tag.h"
1362671f 14#include "tree-walk.h"
5010cb5f 15#include "builtin.h"
3e230fa1 16#include "parse-options.h"
678e484b
JS
17#include "string-list.h"
18#include "run-command.h"
60ecac98 19#include "userdiff.h"
83b5d2f5 20#include "grep.h"
493b7a08 21#include "quote.h"
59332d13 22#include "dir.h"
64acde94 23#include "pathspec.h"
0281e487 24#include "submodule.h"
74ed4371 25#include "submodule-config.h"
90c62155 26#include "object-store.h"
6c307626 27#include "packfile.h"
5b594f45 28
3e230fa1 29static char const * const grep_usage[] = {
9c9b4f2f 30 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
3e230fa1
RS
31 NULL
32};
33
0281e487 34static int recurse_submodules;
0281e487 35
89f09dd3 36static int num_threads;
5b594f45 37
89f09dd3 38static pthread_t *threads;
5b594f45 39
5b594f45
FK
40/* We use one producer thread and THREADS consumer
41 * threads. The producer adds struct work_items to 'todo' and the
42 * consumers pick work items from the same array.
43 */
9cba13ca 44struct work_item {
8f24a632 45 struct grep_source source;
5b594f45
FK
46 char done;
47 struct strbuf out;
48};
49
50/* In the range [todo_done, todo_start) in 'todo' we have work_items
51 * that have been or are processed by a consumer thread. We haven't
52 * written the result for these to stdout yet.
53 *
54 * The work_items in [todo_start, todo_end) are waiting to be picked
55 * up by a consumer thread.
56 *
57 * The ranges are modulo TODO_SIZE.
58 */
59#define TODO_SIZE 128
60static struct work_item todo[TODO_SIZE];
61static int todo_start;
62static int todo_end;
63static int todo_done;
64
65/* Has all work items been added? */
66static int all_work_added;
67
dd45471a
JT
68static struct repository **repos_to_free;
69static size_t repos_to_free_nr, repos_to_free_alloc;
70
5b594f45
FK
71/* This lock protects all the variables above. */
72static pthread_mutex_t grep_mutex;
73
1487a12b
JH
74static inline void grep_lock(void)
75{
8df4c295 76 pthread_mutex_lock(&grep_mutex);
1487a12b
JH
77}
78
79static inline void grep_unlock(void)
80{
8df4c295 81 pthread_mutex_unlock(&grep_mutex);
1487a12b
JH
82}
83
5b594f45
FK
84/* Signalled when a new work_item is added to todo. */
85static pthread_cond_t cond_add;
86
87/* Signalled when the result from one work_item is written to
88 * stdout.
89 */
90static pthread_cond_t cond_write;
91
92/* Signalled when we are finished with everything. */
93static pthread_cond_t cond_result;
94
08303c36 95static int skip_first_line;
431d6e7b 96
70a9fef2 97static void add_work(struct grep_opt *opt, struct grep_source *gs)
5b594f45 98{
70a9fef2
MT
99 if (opt->binary != GREP_BINARY_TEXT)
100 grep_source_load_driver(gs, opt->repo->index);
101
5b594f45
FK
102 grep_lock();
103
104 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105 pthread_cond_wait(&cond_write, &grep_mutex);
106 }
107
e2e05d61 108 todo[todo_end].source = *gs;
5b594f45
FK
109 todo[todo_end].done = 0;
110 strbuf_reset(&todo[todo_end].out);
111 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
112
113 pthread_cond_signal(&cond_add);
114 grep_unlock();
115}
116
117static struct work_item *get_work(void)
118{
119 struct work_item *ret;
120
121 grep_lock();
122 while (todo_start == todo_end && !all_work_added) {
123 pthread_cond_wait(&cond_add, &grep_mutex);
124 }
125
126 if (todo_start == todo_end && all_work_added) {
127 ret = NULL;
128 } else {
129 ret = &todo[todo_start];
130 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
131 }
132 grep_unlock();
133 return ret;
134}
135
5b594f45
FK
136static void work_done(struct work_item *w)
137{
138 int old_done;
139
140 grep_lock();
141 w->done = 1;
142 old_done = todo_done;
143 for(; todo[todo_done].done && todo_done != todo_start;
144 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
145 w = &todo[todo_done];
431d6e7b 146 if (w->out.len) {
08303c36
RS
147 const char *p = w->out.buf;
148 size_t len = w->out.len;
149
150 /* Skip the leading hunk mark of the first file. */
151 if (skip_first_line) {
152 while (len) {
153 len--;
154 if (*p++ == '\n')
155 break;
156 }
157 skip_first_line = 0;
158 }
159
160 write_or_die(1, p, len);
431d6e7b 161 }
8f24a632 162 grep_source_clear(&w->source);
5b594f45
FK
163 }
164
165 if (old_done != todo_done)
166 pthread_cond_signal(&cond_write);
167
168 if (all_work_added && todo_done == todo_end)
169 pthread_cond_signal(&cond_result);
170
171 grep_unlock();
172}
173
dd45471a
JT
174static void free_repos(void)
175{
176 int i;
177
178 for (i = 0; i < repos_to_free_nr; i++) {
179 repo_clear(repos_to_free[i]);
180 free(repos_to_free[i]);
181 }
182 FREE_AND_NULL(repos_to_free);
183 repos_to_free_nr = 0;
184 repos_to_free_alloc = 0;
185}
186
5b594f45
FK
187static void *run(void *arg)
188{
189 int hit = 0;
190 struct grep_opt *opt = arg;
191
192 while (1) {
193 struct work_item *w = get_work();
194 if (!w)
195 break;
196
197 opt->output_priv = w;
f9ee2fcd 198 hit |= grep_source(opt, &w->source);
8f24a632 199 grep_source_clear_data(&w->source);
5b594f45
FK
200 work_done(w);
201 }
a2fb7672
ÆAB
202 free_grep_patterns(opt);
203 free(opt);
5b594f45
FK
204
205 return (void*) (intptr_t) hit;
206}
207
208static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
209{
210 struct work_item *w = opt->output_priv;
211 strbuf_add(&w->out, buf, size);
212}
213
214static void start_threads(struct grep_opt *opt)
215{
216 int i;
217
218 pthread_mutex_init(&grep_mutex, NULL);
0579f91d 219 pthread_mutex_init(&grep_attr_mutex, NULL);
5b594f45
FK
220 pthread_cond_init(&cond_add, NULL);
221 pthread_cond_init(&cond_write, NULL);
222 pthread_cond_init(&cond_result, NULL);
78db6ea9 223 grep_use_locks = 1;
1d1729ca 224 enable_obj_read_lock();
5b594f45
FK
225
226 for (i = 0; i < ARRAY_SIZE(todo); i++) {
227 strbuf_init(&todo[i].out, 0);
228 }
229
ca56dadb 230 CALLOC_ARRAY(threads, num_threads);
89f09dd3 231 for (i = 0; i < num_threads; i++) {
5b594f45
FK
232 int err;
233 struct grep_opt *o = grep_opt_dup(opt);
234 o->output = strbuf_out;
235 compile_grep_patterns(o);
236 err = pthread_create(&threads[i], NULL, run, o);
237
238 if (err)
2fc5f9f1 239 die(_("grep: failed to create thread: %s"),
5b594f45
FK
240 strerror(err));
241 }
242}
243
244static int wait_all(void)
245{
246 int hit = 0;
247 int i;
248
4002e87c 249 if (!HAVE_THREADS)
fd6263fb 250 BUG("Never call this function unless you have started threads");
4002e87c 251
5b594f45
FK
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
89f09dd3 265 for (i = 0; i < num_threads; i++) {
5b594f45
FK
266 void *h;
267 pthread_join(threads[i], &h);
268 hit |= (int) (intptr_t) h;
269 }
270
89f09dd3
VL
271 free(threads);
272
5b594f45 273 pthread_mutex_destroy(&grep_mutex);
0579f91d 274 pthread_mutex_destroy(&grep_attr_mutex);
5b594f45
FK
275 pthread_cond_destroy(&cond_add);
276 pthread_cond_destroy(&cond_write);
277 pthread_cond_destroy(&cond_result);
78db6ea9 278 grep_use_locks = 0;
1d1729ca 279 disable_obj_read_lock();
5b594f45
FK
280
281 return hit;
282}
5b594f45 283
15fabd1b
JH
284static int grep_cmd_config(const char *var, const char *value, void *cb)
285{
286 int st = grep_config(var, value, cb);
33c643bb 287 if (git_color_default_config(var, value, cb) < 0)
15fabd1b 288 st = -1;
89f09dd3
VL
289
290 if (!strcmp(var, "grep.threads")) {
291 num_threads = git_config_int(var, value);
292 if (num_threads < 0)
293 die(_("invalid number of threads specified (%d) for %s"),
294 num_threads, var);
fd6263fb 295 else if (!HAVE_THREADS && num_threads > 1) {
d1edee4a
ÆAB
296 /*
297 * TRANSLATORS: %s is the configuration
298 * variable for tweaking threads, currently
299 * grep.threads
300 */
301 warning(_("no threads support, ignoring %s"), var);
fd6263fb 302 num_threads = 1;
d1edee4a 303 }
89f09dd3
VL
304 }
305
9071c078
SB
306 if (!strcmp(var, "submodule.recurse"))
307 recurse_submodules = git_config_bool(var, value);
308
15fabd1b
JH
309 return st;
310}
311
45115d84
MT
312static void grep_source_name(struct grep_opt *opt, const char *filename,
313 int tree_name_len, struct strbuf *out)
314{
315 strbuf_reset(out);
316
317 if (opt->null_following_name) {
318 if (opt->relative && opt->prefix_length) {
319 struct strbuf rel_buf = STRBUF_INIT;
320 const char *rel_name =
321 relative_path(filename + tree_name_len,
322 opt->prefix, &rel_buf);
323
324 if (tree_name_len)
325 strbuf_add(out, filename, tree_name_len);
326
327 strbuf_addstr(out, rel_name);
328 strbuf_release(&rel_buf);
329 } else {
330 strbuf_addstr(out, filename);
331 }
332 return;
333 }
334
335 if (opt->relative && opt->prefix_length)
88910c99 336 quote_path(filename + tree_name_len, opt->prefix, out, 0);
45115d84
MT
337 else
338 quote_c_style(filename + tree_name_len, out, NULL, 0);
339
340 if (tree_name_len)
341 strbuf_insert(out, 0, filename, tree_name_len);
342}
343
1db11086 344static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
55c61688
NTND
345 const char *filename, int tree_name_len,
346 const char *path)
5b594f45
FK
347{
348 struct strbuf pathbuf = STRBUF_INIT;
e2e05d61 349 struct grep_source gs;
5b594f45 350
45115d84 351 grep_source_name(opt, filename, tree_name_len, &pathbuf);
0693806b 352 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
38ef24dc 353 strbuf_release(&pathbuf);
e2e05d61 354
fd6263fb 355 if (num_threads > 1) {
e2e05d61
RV
356 /*
357 * add_work() copies gs and thus assumes ownership of
358 * its fields, so do not call grep_source_clear()
359 */
360 add_work(opt, &gs);
5b594f45 361 return 0;
4002e87c 362 } else {
5b594f45 363 int hit;
5010cb5f 364
8f24a632 365 hit = grep_source(opt, &gs);
dc49cd76 366
8f24a632
JK
367 grep_source_clear(&gs);
368 return hit;
5010cb5f 369 }
5b594f45
FK
370}
371
372static int grep_file(struct grep_opt *opt, const char *filename)
373{
374 struct strbuf buf = STRBUF_INIT;
e2e05d61 375 struct grep_source gs;
5b594f45 376
45115d84 377 grep_source_name(opt, filename, 0, &buf);
50d92b5f 378 grep_source_init_file(&gs, buf.buf, filename);
38ef24dc 379 strbuf_release(&buf);
e2e05d61 380
fd6263fb 381 if (num_threads > 1) {
e2e05d61
RV
382 /*
383 * add_work() copies gs and thus assumes ownership of
384 * its fields, so do not call grep_source_clear()
385 */
386 add_work(opt, &gs);
5b594f45 387 return 0;
4002e87c 388 } else {
5b594f45 389 int hit;
5b594f45 390
8f24a632
JK
391 hit = grep_source(opt, &gs);
392
393 grep_source_clear(&gs);
5b594f45
FK
394 return hit;
395 }
5010cb5f
JH
396}
397
678e484b
JS
398static void append_path(struct grep_opt *opt, const void *data, size_t len)
399{
400 struct string_list *path_list = opt->output_priv;
401
402 if (len == 1 && *(const char *)data == '\0')
403 return;
0c72cead 404 string_list_append(path_list, xstrndup(data, len));
678e484b
JS
405}
406
407static void run_pager(struct grep_opt *opt, const char *prefix)
408{
409 struct string_list *path_list = opt->output_priv;
850d2fec 410 struct child_process child = CHILD_PROCESS_INIT;
678e484b
JS
411 int i, status;
412
413 for (i = 0; i < path_list->nr; i++)
22f9b7f3 414 strvec_push(&child.args, path_list->items[i].string);
850d2fec
JK
415 child.dir = prefix;
416 child.use_shell = 1;
678e484b 417
850d2fec 418 status = run_command(&child);
678e484b
JS
419 if (status)
420 exit(status);
678e484b
JS
421}
422
dba093dd 423static int grep_cache(struct grep_opt *opt,
f9ee2fcd
BW
424 const struct pathspec *pathspec, int cached);
425static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
426 struct tree_desc *tree, struct strbuf *base, int tn_len,
dba093dd 427 int check_attr);
0281e487 428
dba093dd 429static int grep_submodule(struct grep_opt *opt,
f9ee2fcd
BW
430 const struct pathspec *pathspec,
431 const struct object_id *oid,
6a289d45 432 const char *filename, const char *path, int cached)
0281e487 433{
dd45471a 434 struct repository *subrepo;
dba093dd 435 struct repository *superproject = opt->repo;
dba093dd 436 struct grep_opt subopt;
dd45471a 437 int hit = 0;
74ed4371 438
c441ea4e 439 if (!is_submodule_active(superproject, path))
f9ee2fcd 440 return 0;
0281e487 441
dd45471a 442 subrepo = xmalloc(sizeof(*subrepo));
8eb8dcf9 443 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
dd45471a 444 free(subrepo);
f9ee2fcd 445 return 0;
dd45471a
JT
446 }
447 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
448 repos_to_free[repos_to_free_nr++] = subrepo;
be80a239 449
c441ea4e
MT
450 /*
451 * NEEDSWORK: repo_read_gitmodules() might call
452 * add_to_alternates_memory() via config_from_gitmodules(). This
453 * operation causes a race condition with concurrent object readings
454 * performed by the worker threads. That's why we need obj_read_lock()
455 * here. It should be removed once it's no longer necessary to add the
456 * subrepo's odbs to the in-memory alternates list.
457 */
458 obj_read_lock();
dd45471a 459 repo_read_gitmodules(subrepo, 0);
0281e487 460
74ed4371 461 /*
0693806b
JT
462 * All code paths tested by test code no longer need submodule ODBs to
463 * be added as alternates, but add it to the list just in case.
464 * Submodule ODBs added through add_submodule_odb_by_path() will be
465 * lazily registered as alternates when needed (and except in an
466 * unexpected code interaction, it won't be needed).
74ed4371 467 */
dd45471a 468 add_submodule_odb_by_path(subrepo->objects->odb->path);
1d1729ca 469 obj_read_unlock();
74ed4371 470
dba093dd 471 memcpy(&subopt, opt, sizeof(subopt));
dd45471a 472 subopt.repo = subrepo;
dba093dd 473
f9ee2fcd 474 if (oid) {
78ca584f 475 enum object_type object_type;
f9ee2fcd
BW
476 struct tree_desc tree;
477 void *data;
478 unsigned long size;
479 struct strbuf base = STRBUF_INIT;
74ed4371 480
1d1729ca 481 obj_read_lock();
dd45471a 482 object_type = oid_object_info(subrepo, oid, NULL);
1d1729ca 483 obj_read_unlock();
dd45471a 484 data = read_object_with_reference(subrepo,
78ca584f 485 oid, tree_type,
f9ee2fcd 486 &size, NULL);
f9ee2fcd 487 if (!data)
78ca584f 488 die(_("unable to read tree (%s)"), oid_to_hex(oid));
0281e487 489
f9ee2fcd
BW
490 strbuf_addstr(&base, filename);
491 strbuf_addch(&base, '/');
0281e487 492
f9ee2fcd 493 init_tree_desc(&tree, data, size);
dba093dd 494 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
78ca584f 495 object_type == OBJ_COMMIT);
f9ee2fcd
BW
496 strbuf_release(&base);
497 free(data);
498 } else {
6a289d45 499 hit = grep_cache(&subopt, pathspec, cached);
e6fac7f3 500 }
0281e487 501
f9ee2fcd 502 return hit;
0281e487
BW
503}
504
dba093dd 505static int grep_cache(struct grep_opt *opt,
f9ee2fcd 506 const struct pathspec *pathspec, int cached)
5010cb5f 507{
dba093dd 508 struct repository *repo = opt->repo;
5010cb5f
JH
509 int hit = 0;
510 int nr;
0281e487
BW
511 struct strbuf name = STRBUF_INIT;
512 int name_base_len = 0;
f9ee2fcd
BW
513 if (repo->submodule_prefix) {
514 name_base_len = strlen(repo->submodule_prefix);
515 strbuf_addstr(&name, repo->submodule_prefix);
0281e487
BW
516 }
517
b2aa84c7 518 if (repo_read_index(repo) < 0)
5507067d 519 die(_("index file corrupt"));
5010cb5f 520
46eb6e31
DS
521 /* TODO: audit for interaction with sparse-index. */
522 ensure_full_index(repo->index);
f9ee2fcd
BW
523 for (nr = 0; nr < repo->index->cache_nr; nr++) {
524 const struct cache_entry *ce = repo->index->cache[nr];
42d906be
MT
525
526 if (!cached && ce_skip_worktree(ce))
527 continue;
528
0281e487
BW
529 strbuf_setlen(&name, name_base_len);
530 strbuf_addstr(&name, ce->name);
531
532 if (S_ISREG(ce->ce_mode) &&
a4009b0b 533 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
0281e487
BW
534 S_ISDIR(ce->ce_mode) ||
535 S_ISGITLINK(ce->ce_mode))) {
536 /*
537 * If CE_VALID is on, we assume worktree file and its
538 * cache entry are identical, even if worktree file has
539 * been modified, so use cache version instead
540 */
42d906be 541 if (cached || (ce->ce_flags & CE_VALID)) {
0281e487
BW
542 if (ce_stage(ce) || ce_intent_to_add(ce))
543 continue;
f9ee2fcd
BW
544 hit |= grep_oid(opt, &ce->oid, name.buf,
545 0, name.buf);
0281e487 546 } else {
f9ee2fcd 547 hit |= grep_file(opt, name.buf);
0281e487
BW
548 }
549 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
a4009b0b 550 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
6a289d45
MT
551 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
552 ce->name, cached);
0281e487 553 } else {
5010cb5f 554 continue;
36f2587f 555 }
0281e487 556
36f2587f
JH
557 if (ce_stage(ce)) {
558 do {
559 nr++;
f9ee2fcd
BW
560 } while (nr < repo->index->cache_nr &&
561 !strcmp(ce->name, repo->index->cache[nr]->name));
36f2587f
JH
562 nr--; /* compensate for loop control */
563 }
c8610a2e
JH
564 if (hit && opt->status_only)
565 break;
5010cb5f 566 }
0281e487
BW
567
568 strbuf_release(&name);
5010cb5f
JH
569 return hit;
570}
571
f34bbc15 572static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
55c61688 573 struct tree_desc *tree, struct strbuf *base, int tn_len,
dba093dd 574 int check_attr)
5010cb5f 575{
dba093dd 576 struct repository *repo = opt->repo;
d688cf07
NTND
577 int hit = 0;
578 enum interesting match = entry_not_interesting;
4c068a98 579 struct name_entry entry;
e5e062b6 580 int old_baselen = base->len;
74ed4371
BW
581 struct strbuf name = STRBUF_INIT;
582 int name_base_len = 0;
f9ee2fcd
BW
583 if (repo->submodule_prefix) {
584 strbuf_addstr(&name, repo->submodule_prefix);
74ed4371
BW
585 name_base_len = name.len;
586 }
5010cb5f 587
4c068a98 588 while (tree_entry(tree, &entry)) {
0de16337 589 int te_len = tree_entry_len(&entry);
e5e062b6 590
d688cf07 591 if (match != all_entries_interesting) {
74ed4371 592 strbuf_addstr(&name, base->buf + tn_len);
67022e02
NTND
593 match = tree_entry_interesting(repo->index,
594 &entry, &name,
74ed4371
BW
595 0, pathspec);
596 strbuf_setlen(&name, name_base_len);
597
d688cf07 598 if (match == all_entries_not_interesting)
97d0b74a 599 break;
d688cf07 600 if (match == entry_not_interesting)
1376e507
NTND
601 continue;
602 }
5010cb5f 603
1376e507 604 strbuf_add(base, entry.path, te_len);
e0eb889f 605
1376e507 606 if (S_ISREG(entry.mode)) {
ea82b2a0 607 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
55c61688 608 check_attr ? base->buf + tn_len : NULL);
74ed4371 609 } else if (S_ISDIR(entry.mode)) {
21666f1a 610 enum object_type type;
5010cb5f
JH
611 struct tree_desc sub;
612 void *data;
6fda5e51
LT
613 unsigned long size;
614
1d1729ca 615 data = read_object_file(&entry.oid, &type, &size);
5010cb5f 616 if (!data)
2fc5f9f1 617 die(_("unable to read tree (%s)"),
ea82b2a0 618 oid_to_hex(&entry.oid));
1376e507
NTND
619
620 strbuf_addch(base, '/');
6fda5e51 621 init_tree_desc(&sub, data, size);
55c61688 622 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
dba093dd 623 check_attr);
5010cb5f 624 free(data);
74ed4371 625 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
7589e636 626 hit |= grep_submodule(opt, pathspec, &entry.oid,
6a289d45
MT
627 base->buf, base->buf + tn_len,
628 1); /* ignored */
5010cb5f 629 }
74ed4371 630
e5e062b6
NTND
631 strbuf_setlen(base, old_baselen);
632
c8610a2e
JH
633 if (hit && opt->status_only)
634 break;
5010cb5f 635 }
74ed4371
BW
636
637 strbuf_release(&name);
5010cb5f
JH
638 return hit;
639}
640
f34bbc15 641static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
6856077a 642 struct object *obj, const char *name, const char *path)
5010cb5f 643{
1974632c 644 if (obj->type == OBJ_BLOB)
1db11086 645 return grep_oid(opt, &obj->oid, name, 0, path);
1974632c 646 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
647 struct tree_desc tree;
648 void *data;
6fda5e51 649 unsigned long size;
e5e062b6
NTND
650 struct strbuf base;
651 int hit, len;
652
d3b4705a
NTND
653 data = read_object_with_reference(opt->repo,
654 &obj->oid, tree_type,
6fda5e51 655 &size, NULL);
5010cb5f 656 if (!data)
f2fd0760 657 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
e5e062b6
NTND
658
659 len = name ? strlen(name) : 0;
660 strbuf_init(&base, PATH_MAX + len + 1);
661 if (len) {
662 strbuf_add(&base, name, len);
663 strbuf_addch(&base, ':');
664 }
6fda5e51 665 init_tree_desc(&tree, data, size);
55c61688 666 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
dba093dd 667 obj->type == OBJ_COMMIT);
e5e062b6 668 strbuf_release(&base);
5010cb5f
JH
669 free(data);
670 return hit;
671 }
debca9d2 672 die(_("unable to grep from object of type %s"), type_name(obj->type));
5010cb5f
JH
673}
674
f34bbc15 675static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
30d00c39
JN
676 const struct object_array *list)
677{
678 unsigned int i;
679 int hit = 0;
680 const unsigned int nr = list->nr;
681
682 for (i = 0; i < nr; i++) {
683 struct object *real_obj;
d5b0bac5 684
1d1729ca 685 obj_read_lock();
dba093dd 686 real_obj = deref_tag(opt->repo, list->objects[i].item,
a74093da 687 NULL, 0);
1d1729ca 688 obj_read_unlock();
74ed4371 689
e30b1525
RS
690 if (!real_obj) {
691 char hex[GIT_MAX_HEXSZ + 1];
692 const char *name = list->objects[i].name;
693
694 if (!name) {
695 oid_to_hex_r(hex, &list->objects[i].item->oid);
696 name = hex;
697 }
698 die(_("invalid object '%s' given."), name);
699 }
700
74ed4371
BW
701 /* load the gitmodules file for this rev */
702 if (recurse_submodules) {
dba093dd 703 submodule_free(opt->repo);
1d1729ca 704 obj_read_lock();
cd73de47 705 gitmodules_config_oid(&real_obj->oid);
1d1729ca 706 obj_read_unlock();
74ed4371 707 }
6856077a
JT
708 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
709 list->objects[i].path)) {
30d00c39
JN
710 hit = 1;
711 if (opt->status_only)
712 break;
713 }
714 }
715 return hit;
716}
717
dbfae86a 718static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
85975c0c 719 int exc_std, int use_index)
59332d13 720{
ce93a4c6 721 struct dir_struct dir = DIR_INIT;
59332d13
JH
722 int i, hit = 0;
723
85975c0c
JK
724 if (!use_index)
725 dir.flags |= DIR_NO_GITLINKS;
0a93fb8a
JH
726 if (exc_std)
727 setup_standard_excludes(&dir);
59332d13 728
dba093dd 729 fill_directory(&dir, opt->repo->index, pathspec);
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 }
eceba532 735 dir_clear(&dir);
59332d13
JH
736 return hit;
737}
738
ff3c7f9a
RS
739static int context_callback(const struct option *opt, const char *arg,
740 int unset)
3e230fa1
RS
741{
742 struct grep_opt *grep_opt = opt->value;
743 int value;
744 const char *endp;
745
746 if (unset) {
747 grep_opt->pre_context = grep_opt->post_context = 0;
748 return 0;
749 }
750 value = strtol(arg, (char **)&endp, 10);
751 if (*endp) {
2fc5f9f1 752 return error(_("switch `%c' expects a numerical value"),
3e230fa1
RS
753 opt->short_name);
754 }
755 grep_opt->pre_context = grep_opt->post_context = value;
756 return 0;
757}
758
ff3c7f9a 759static int file_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
760{
761 struct grep_opt *grep_opt = opt->value;
517fe807 762 int from_stdin;
3e230fa1
RS
763 FILE *patterns;
764 int lno = 0;
cfe370c6 765 struct strbuf sb = STRBUF_INIT;
3e230fa1 766
517fe807
JK
767 BUG_ON_OPT_NEG(unset);
768
769 from_stdin = !strcmp(arg, "-");
c41dd2fd 770 patterns = from_stdin ? stdin : fopen(arg, "r");
3e230fa1 771 if (!patterns)
2fc5f9f1 772 die_errno(_("cannot open '%s'"), arg);
a5518431 773 while (strbuf_getline(&sb, patterns) == 0) {
3e230fa1
RS
774 /* ignore empty line like grep does */
775 if (sb.len == 0)
776 continue;
ed40a095 777
ec830611
RS
778 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
779 GREP_PATTERN);
3e230fa1 780 }
c41dd2fd
RS
781 if (!from_stdin)
782 fclose(patterns);
3e230fa1
RS
783 strbuf_release(&sb);
784 return 0;
785}
786
ff3c7f9a 787static int not_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
788{
789 struct grep_opt *grep_opt = opt->value;
517fe807
JK
790 BUG_ON_OPT_NEG(unset);
791 BUG_ON_OPT_ARG(arg);
3e230fa1
RS
792 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
793 return 0;
794}
795
ff3c7f9a 796static int and_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
797{
798 struct grep_opt *grep_opt = opt->value;
517fe807
JK
799 BUG_ON_OPT_NEG(unset);
800 BUG_ON_OPT_ARG(arg);
3e230fa1
RS
801 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
802 return 0;
803}
804
ff3c7f9a 805static int open_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
806{
807 struct grep_opt *grep_opt = opt->value;
517fe807
JK
808 BUG_ON_OPT_NEG(unset);
809 BUG_ON_OPT_ARG(arg);
3e230fa1
RS
810 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
811 return 0;
812}
813
ff3c7f9a 814static int close_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
815{
816 struct grep_opt *grep_opt = opt->value;
517fe807
JK
817 BUG_ON_OPT_NEG(unset);
818 BUG_ON_OPT_ARG(arg);
3e230fa1
RS
819 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
820 return 0;
821}
822
ff3c7f9a
RS
823static int pattern_callback(const struct option *opt, const char *arg,
824 int unset)
3e230fa1
RS
825{
826 struct grep_opt *grep_opt = opt->value;
517fe807 827 BUG_ON_OPT_NEG(unset);
3e230fa1
RS
828 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
829 return 0;
830}
5010cb5f 831
a633fca0 832int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 833{
5010cb5f 834 int hit = 0;
0a93fb8a 835 int cached = 0, untracked = 0, opt_exclude = -1;
5acd64ed 836 int seen_dashdash = 0;
bbc09c22 837 int external_grep_allowed__ignored;
0af88c15 838 const char *show_in_pager = NULL, *default_pager = "dummy";
5010cb5f 839 struct grep_opt opt;
3cd47459 840 struct object_array list = OBJECT_ARRAY_INIT;
f34bbc15 841 struct pathspec pathspec;
183113a5 842 struct string_list path_list = STRING_LIST_INIT_NODUP;
5acd64ed 843 int i;
3e230fa1 844 int dummy;
ff38d1a9 845 int use_index = 1;
84befcd0 846 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
131f3c96 847 int allow_revs;
cca2c172 848
3e230fa1 849 struct option options[] = {
d5d09d47 850 OPT_BOOL(0, "cached", &cached,
4b407bc5 851 N_("search in index instead of in the work tree")),
cbb08c2e 852 OPT_NEGBIT(0, "no-index", &use_index,
f63cf8c9 853 N_("find in contents not managed by git"), 1),
d5d09d47 854 OPT_BOOL(0, "untracked", &untracked,
4b407bc5 855 N_("search in both tracked and untracked files")),
0a93fb8a 856 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
77fdb8a8 857 N_("ignore files specified via '.gitignore'"), 1),
0281e487 858 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
4fb1c6aa 859 N_("recursively search in each submodule")),
3e230fa1 860 OPT_GROUP(""),
d5d09d47 861 OPT_BOOL('v', "invert-match", &opt.invert,
4b407bc5 862 N_("show non-matching lines")),
d5d09d47 863 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
4b407bc5 864 N_("case insensitive matching")),
d5d09d47 865 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
4b407bc5 866 N_("match patterns only at word boundaries")),
3e230fa1 867 OPT_SET_INT('a', "text", &opt.binary,
4b407bc5 868 N_("process binary files as text"), GREP_BINARY_TEXT),
3e230fa1 869 OPT_SET_INT('I', NULL, &opt.binary,
4b407bc5 870 N_("don't match patterns in binary files"),
3e230fa1 871 GREP_BINARY_NOMATCH),
335ec3bf
JK
872 OPT_BOOL(0, "textconv", &opt.allow_textconv,
873 N_("process binary files with textconv filters")),
0a09e5ed
RS
874 OPT_SET_INT('r', "recursive", &opt.max_depth,
875 N_("search in subdirectories (default)"), -1),
4b407bc5
NTND
876 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
877 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
a91f453f 878 NULL, 1 },
3e230fa1 879 OPT_GROUP(""),
84befcd0 880 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
4b407bc5 881 N_("use extended POSIX regular expressions"),
84befcd0
S
882 GREP_PATTERN_TYPE_ERE),
883 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
4b407bc5 884 N_("use basic POSIX regular expressions (default)"),
84befcd0
S
885 GREP_PATTERN_TYPE_BRE),
886 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
4b407bc5 887 N_("interpret patterns as fixed strings"),
84befcd0
S
888 GREP_PATTERN_TYPE_FIXED),
889 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
4b407bc5 890 N_("use Perl-compatible regular expressions"),
84befcd0 891 GREP_PATTERN_TYPE_PCRE),
3e230fa1 892 OPT_GROUP(""),
d5d09d47 893 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
a449f27f 894 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
4b407bc5
NTND
895 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
896 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
3e230fa1 897 OPT_NEGBIT(0, "full-name", &opt.relative,
4b407bc5 898 N_("show filenames relative to top directory"), 1),
d5d09d47 899 OPT_BOOL('l', "files-with-matches", &opt.name_only,
4b407bc5 900 N_("show only filenames instead of matching lines")),
d5d09d47 901 OPT_BOOL(0, "name-only", &opt.name_only,
4b407bc5 902 N_("synonym for --files-with-matches")),
d5d09d47 903 OPT_BOOL('L', "files-without-match",
3e230fa1 904 &opt.unmatch_name_only,
4b407bc5 905 N_("show only the names of files without match")),
caf2de33
NTND
906 OPT_BOOL_F('z', "null", &opt.null_following_name,
907 N_("print NUL after filenames"),
908 PARSE_OPT_NOCOMPLETE),
9d8db06e
TB
909 OPT_BOOL('o', "only-matching", &opt.only_matching,
910 N_("show only matching parts of a line")),
d5d09d47 911 OPT_BOOL('c', "count", &opt.count,
4b407bc5
NTND
912 N_("show the number of matches instead of matching lines")),
913 OPT__COLOR(&opt.color, N_("highlight matches")),
d5d09d47 914 OPT_BOOL(0, "break", &opt.file_break,
4b407bc5 915 N_("print empty line between matches from different files")),
d5d09d47 916 OPT_BOOL(0, "heading", &opt.heading,
4b407bc5 917 N_("show filename only once above matches from same file")),
3e230fa1 918 OPT_GROUP(""),
4b407bc5
NTND
919 OPT_CALLBACK('C', "context", &opt, N_("n"),
920 N_("show <n> context lines before and after matches"),
3e230fa1 921 context_callback),
317f63c2 922 OPT_INTEGER('B', "before-context", &opt.pre_context,
4b407bc5 923 N_("show <n> context lines before matches")),
317f63c2 924 OPT_INTEGER('A', "after-context", &opt.post_context,
4b407bc5 925 N_("show <n> context lines after matches")),
89f09dd3
VL
926 OPT_INTEGER(0, "threads", &num_threads,
927 N_("use <n> worker threads")),
4b407bc5 928 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
3e230fa1 929 context_callback),
d5d09d47 930 OPT_BOOL('p', "show-function", &opt.funcname,
4b407bc5 931 N_("show a line with the function name before matches")),
d5d09d47 932 OPT_BOOL('W', "function-context", &opt.funcbody,
4b407bc5 933 N_("show the surrounding function")),
3e230fa1 934 OPT_GROUP(""),
4b407bc5
NTND
935 OPT_CALLBACK('f', NULL, &opt, N_("file"),
936 N_("read patterns from file"), file_callback),
203c8533
DL
937 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
938 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
939 OPT_CALLBACK_F(0, "and", &opt, NULL,
940 N_("combine patterns specified with -e"),
941 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
d5d09d47 942 OPT_BOOL(0, "or", &dummy, ""),
203c8533
DL
943 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
944 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
945 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
946 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
947 open_callback),
948 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
949 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
950 close_callback),
d52ee6e6 951 OPT__QUIET(&opt.status_only,
4b407bc5 952 N_("indicate hit with exit status without output")),
d5d09d47 953 OPT_BOOL(0, "all-match", &opt.all_match,
4b407bc5 954 N_("show only matches from files that match all patterns")),
3e230fa1 955 OPT_GROUP(""),
0af88c15 956 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
4b407bc5 957 N_("pager"), N_("show matching files in the pager"),
caf2de33
NTND
958 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
959 NULL, (intptr_t)default_pager },
960 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
961 N_("allow calling of grep(1) (ignored by this build)"),
962 PARSE_OPT_NOCOMPLETE),
3e230fa1
RS
963 OPT_END()
964 };
5010cb5f 965
15fabd1b 966 git_config(grep_cmd_config, NULL);
38bbc2ea 967 grep_init(&opt, the_repository, prefix);
7e8f59d5 968
5010cb5f 969 /*
5acd64ed
JH
970 * If there is no -- then the paths must exist in the working
971 * tree. If there is no explicit pattern specified with -e or
972 * -f, we take the first unrecognized non option to be the
973 * pattern, but then what follows it must be zero or more
974 * valid refs up to the -- (if exists), and then existing
975 * paths. If there is an explicit pattern, then the first
82e5a82f 976 * unrecognized non option is the beginning of the refs list
5acd64ed 977 * that continues up to the -- (if exists), and then paths.
5010cb5f 978 */
37782920 979 argc = parse_options(argc, argv, prefix, options, grep_usage,
3e230fa1 980 PARSE_OPT_KEEP_DASHDASH |
44415499 981 PARSE_OPT_STOP_AT_NON_OPTION);
c5c31d33 982 grep_commit_pattern_type(pattern_type_arg, &opt);
3e230fa1 983
ecd9ba61
TG
984 if (use_index && !startup_info->have_repository) {
985 int fallback = 0;
986 git_config_get_bool("grep.fallbacktonoindex", &fallback);
987 if (fallback)
988 use_index = 0;
989 else
990 /* die the same way as if we did it at the beginning */
991 setup_git_directory();
992 }
c56c48dd
PB
993 /* Ignore --recurse-submodules if --no-index is given or implied */
994 if (!use_index)
995 recurse_submodules = 0;
59332d13 996
1123c67c
JK
997 /*
998 * skip a -- separator; we know it cannot be
999 * separating revisions from pathnames if
1000 * we haven't even had any patterns yet
1001 */
1002 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1003 argv++;
1004 argc--;
1005 }
1006
3e230fa1
RS
1007 /* First unrecognized non-option token */
1008 if (argc > 0 && !opt.pattern_list) {
1009 append_grep_pattern(&opt, argv[0], "command line", 0,
1010 GREP_PATTERN);
1011 argv++;
1012 argc--;
5010cb5f 1013 }
5acd64ed 1014
0af88c15
JS
1015 if (show_in_pager == default_pager)
1016 show_in_pager = git_pager(1);
678e484b 1017 if (show_in_pager) {
e7b082a4 1018 opt.color = 0;
0af88c15
JS
1019 opt.name_only = 1;
1020 opt.null_following_name = 1;
1021 opt.output_priv = &path_list;
1022 opt.output = append_path;
0c72cead 1023 string_list_append(&path_list, show_in_pager);
678e484b
JS
1024 }
1025
f9b9faf6 1026 if (!opt.pattern_list)
1a07e59c 1027 die(_("no pattern given"));
5b594f45 1028
9d8db06e
TB
1029 /* --only-matching has no effect with --invert. */
1030 if (opt.invert)
1031 opt.only_matching = 0;
1032
b5b81136
JK
1033 /*
1034 * We have to find "--" in a separate pass, because its presence
1035 * influences how we will parse arguments that come before it.
1036 */
1037 for (i = 0; i < argc; i++) {
1038 if (!strcmp(argv[i], "--")) {
1039 seen_dashdash = 1;
1040 break;
1041 }
1042 }
1043
1044 /*
1045 * Resolve any rev arguments. If we have a dashdash, then everything up
1046 * to it must resolve as a rev. If not, then we stop at the first
1047 * non-rev and assume everything else is a path.
1048 */
131f3c96 1049 allow_revs = use_index && !untracked;
3e230fa1 1050 for (i = 0; i < argc; i++) {
5acd64ed 1051 const char *arg = argv[i];
1db11086 1052 struct object_id oid;
afa15f3c 1053 struct object_context oc;
20d6421c
JK
1054 struct object *object;
1055
dca3b5f5
JT
1056 if (!strcmp(arg, "--")) {
1057 i++;
dca3b5f5
JT
1058 break;
1059 }
20d6421c 1060
131f3c96 1061 if (!allow_revs) {
d0ffc069 1062 if (seen_dashdash)
131f3c96 1063 die(_("--no-index or --untracked cannot be used with revs"));
d0ffc069
JK
1064 break;
1065 }
1066
3a7a698e
NTND
1067 if (get_oid_with_context(the_repository, arg,
1068 GET_OID_RECORD_PATH,
e82caf38 1069 &oid, &oc)) {
b5b81136
JK
1070 if (seen_dashdash)
1071 die(_("unable to resolve revision: %s"), arg);
20d6421c 1072 break;
b5b81136 1073 }
20d6421c 1074
c251c83d 1075 object = parse_object_or_die(&oid, arg);
20d6421c
JK
1076 if (!seen_dashdash)
1077 verify_non_filename(prefix, arg);
1078 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
dc944b65 1079 free(oc.path);
1362671f 1080 }
5acd64ed 1081
b5b81136
JK
1082 /*
1083 * Anything left over is presumed to be a path. But in the non-dashdash
1084 * "do what I mean" case, we verify and complain when that isn't true.
1085 */
a0fe2b0d
JK
1086 if (!seen_dashdash) {
1087 int j;
1088 for (j = i; j < argc; j++)
131f3c96 1089 verify_filename(prefix, argv[j], j == i && allow_revs);
a0fe2b0d
JK
1090 }
1091
1092 parse_pathspec(&pathspec, 0,
1093 PATHSPEC_PREFER_CWD |
1094 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1095 prefix, argv + i);
1096 pathspec.max_depth = opt.max_depth;
1097 pathspec.recursive = 1;
eef3df5a 1098 pathspec.recurse_submodules = !!recurse_submodules;
a0fe2b0d 1099
56ceb64e
JH
1100 if (recurse_submodules && untracked)
1101 die(_("--untracked not supported with --recurse-submodules"));
c441ea4e 1102
1184a95e 1103 if (show_in_pager) {
fd6263fb
NTND
1104 if (num_threads > 1)
1105 warning(_("invalid option combination, ignoring --threads"));
1106 num_threads = 1;
1107 } else if (!HAVE_THREADS && num_threads > 1) {
d1edee4a 1108 warning(_("no threads support, ignoring --threads"));
fd6263fb
NTND
1109 num_threads = 1;
1110 } else if (num_threads < 0)
1111 die(_("invalid number of threads specified (%d)"), num_threads);
1112 else if (num_threads == 0)
f1928f04 1113 num_threads = HAVE_THREADS ? online_cpus() : 1;
53b8d931 1114
fd6263fb
NTND
1115 if (num_threads > 1) {
1116 if (!HAVE_THREADS)
1117 BUG("Somebody got num_threads calculation wrong!");
1118 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1119 && (opt.pre_context || opt.post_context ||
1120 opt.file_break || opt.funcbody))
1121 skip_first_line = 1;
c441ea4e
MT
1122
1123 /*
6c307626
MT
1124 * Pre-read gitmodules (if not read already) and force eager
1125 * initialization of packed_git to prevent racy lazy
1126 * reading/initialization once worker threads are started.
c441ea4e
MT
1127 */
1128 if (recurse_submodules)
1129 repo_read_gitmodules(the_repository, 1);
6c307626
MT
1130 if (startup_info->have_repository)
1131 (void)get_packed_git(the_repository);
c441ea4e 1132
fd6263fb 1133 start_threads(&opt);
4002e87c 1134 } else {
6d423dd5
ÆAB
1135 /*
1136 * The compiled patterns on the main path are only
1137 * used when not using threading. Otherwise
fd6263fb 1138 * start_threads() above calls compile_grep_patterns()
6d423dd5
ÆAB
1139 * for each thread.
1140 */
1141 compile_grep_patterns(&opt);
53b8d931 1142 }
53b8d931 1143
678e484b 1144 if (show_in_pager && (cached || list.nr))
e4fe4ba5 1145 die(_("--open-files-in-pager only works on the worktree"));
678e484b
JS
1146
1147 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1148 const char *pager = path_list.items[0].string;
1149 int len = strlen(pager);
1150
1151 if (len > 4 && is_dir_sep(pager[len - 5]))
1152 pager += len - 4;
1153
f7febbea
JS
1154 if (opt.ignore_case && !strcmp("less", pager))
1155 string_list_append(&path_list, "-I");
1156
678e484b
JS
1157 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1158 struct strbuf buf = STRBUF_INIT;
1159 strbuf_addf(&buf, "+/%s%s",
1160 strcmp("less", pager) ? "" : "*",
1161 opt.pattern_list->pattern);
fd99c2dd
RS
1162 string_list_append(&path_list,
1163 strbuf_detach(&buf, NULL));
678e484b
JS
1164 }
1165 }
1166
c2048f0b 1167 if (!show_in_pager && !opt.status_only)
678e484b
JS
1168 setup_pager();
1169
0a93fb8a 1170 if (!use_index && (untracked || cached))
1a07e59c 1171 die(_("--cached or --untracked cannot be used with --no-index"));
678e484b 1172
0c5d83b2
MT
1173 if (untracked && cached)
1174 die(_("--untracked cannot be used with --cached"));
1175
0a93fb8a 1176 if (!use_index || untracked) {
0a93fb8a 1177 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
85975c0c 1178 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
dbfae86a 1179 } else if (0 <= opt_exclude) {
1a07e59c 1180 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
685359cf 1181 } else if (!list.nr) {
6577f542
NTND
1182 if (!cached)
1183 setup_work_tree();
5b594f45 1184
dba093dd 1185 hit = grep_cache(&opt, &pathspec, cached);
685359cf
JS
1186 } else {
1187 if (cached)
1a07e59c 1188 die(_("both --cached and trees are given"));
f9ee2fcd 1189
6856077a 1190 hit = grep_objects(&opt, &pathspec, &list);
5010cb5f 1191 }
5b594f45 1192
fd6263fb 1193 if (num_threads > 1)
5b594f45 1194 hit |= wait_all();
678e484b
JS
1195 if (hit && show_in_pager)
1196 run_pager(&opt, prefix);
7861fa07 1197 clear_pathspec(&pathspec);
b48fb5b6 1198 free_grep_patterns(&opt);
dd45471a 1199 free_repos();
5010cb5f
JH
1200 return !hit;
1201}