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