]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/grep.c
submodule: merge repo_read_gitmodules and gitmodules_config
[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"
627d9342 7#include "repository.h"
b2141fc1 8#include "config.h"
5010cb5f
JH
9#include "blob.h"
10#include "tree.h"
11#include "commit.h"
12#include "tag.h"
1362671f 13#include "tree-walk.h"
5010cb5f 14#include "builtin.h"
3e230fa1 15#include "parse-options.h"
678e484b
JS
16#include "string-list.h"
17#include "run-command.h"
60ecac98 18#include "userdiff.h"
83b5d2f5 19#include "grep.h"
493b7a08 20#include "quote.h"
59332d13 21#include "dir.h"
64acde94 22#include "pathspec.h"
0281e487 23#include "submodule.h"
74ed4371 24#include "submodule-config.h"
5b594f45 25
3e230fa1 26static char const * const grep_usage[] = {
9c9b4f2f 27 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
3e230fa1
RS
28 NULL
29};
30
0281e487
BW
31static const char *super_prefix;
32static int recurse_submodules;
33static struct argv_array submodule_options = ARGV_ARRAY_INIT;
74ed4371 34static const char *parent_basename;
0281e487
BW
35
36static int grep_submodule_launch(struct grep_opt *opt,
37 const struct grep_source *gs);
38
89f09dd3
VL
39#define GREP_NUM_THREADS_DEFAULT 8
40static int num_threads;
5b594f45
FK
41
42#ifndef NO_PTHREADS
89f09dd3 43static pthread_t *threads;
5b594f45 44
5b594f45
FK
45/* We use one producer thread and THREADS consumer
46 * threads. The producer adds struct work_items to 'todo' and the
47 * consumers pick work items from the same array.
48 */
9cba13ca 49struct work_item {
8f24a632 50 struct grep_source source;
5b594f45
FK
51 char done;
52 struct strbuf out;
53};
54
55/* In the range [todo_done, todo_start) in 'todo' we have work_items
56 * that have been or are processed by a consumer thread. We haven't
57 * written the result for these to stdout yet.
58 *
59 * The work_items in [todo_start, todo_end) are waiting to be picked
60 * up by a consumer thread.
61 *
62 * The ranges are modulo TODO_SIZE.
63 */
64#define TODO_SIZE 128
65static struct work_item todo[TODO_SIZE];
66static int todo_start;
67static int todo_end;
68static int todo_done;
69
70/* Has all work items been added? */
71static int all_work_added;
72
73/* This lock protects all the variables above. */
74static pthread_mutex_t grep_mutex;
75
1487a12b
JH
76static inline void grep_lock(void)
77{
8df4c295
ÆAB
78 assert(num_threads);
79 pthread_mutex_lock(&grep_mutex);
1487a12b
JH
80}
81
82static inline void grep_unlock(void)
83{
8df4c295
ÆAB
84 assert(num_threads);
85 pthread_mutex_unlock(&grep_mutex);
1487a12b
JH
86}
87
5b594f45
FK
88/* Signalled when a new work_item is added to todo. */
89static pthread_cond_t cond_add;
90
91/* Signalled when the result from one work_item is written to
92 * stdout.
93 */
94static pthread_cond_t cond_write;
95
96/* Signalled when we are finished with everything. */
97static pthread_cond_t cond_result;
98
08303c36 99static int skip_first_line;
431d6e7b 100
9dd5245c 101static void add_work(struct grep_opt *opt, enum grep_source_type type,
55c61688 102 const char *name, const char *path, const void *id)
5b594f45
FK
103{
104 grep_lock();
105
106 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
107 pthread_cond_wait(&cond_write, &grep_mutex);
108 }
109
55c61688 110 grep_source_init(&todo[todo_end].source, type, name, path, id);
9dd5245c
JK
111 if (opt->binary != GREP_BINARY_TEXT)
112 grep_source_load_driver(&todo[todo_end].source);
5b594f45
FK
113 todo[todo_end].done = 0;
114 strbuf_reset(&todo[todo_end].out);
115 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
116
117 pthread_cond_signal(&cond_add);
118 grep_unlock();
119}
120
121static struct work_item *get_work(void)
122{
123 struct work_item *ret;
124
125 grep_lock();
126 while (todo_start == todo_end && !all_work_added) {
127 pthread_cond_wait(&cond_add, &grep_mutex);
128 }
129
130 if (todo_start == todo_end && all_work_added) {
131 ret = NULL;
132 } else {
133 ret = &todo[todo_start];
134 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
135 }
136 grep_unlock();
137 return ret;
138}
139
5b594f45
FK
140static void work_done(struct work_item *w)
141{
142 int old_done;
143
144 grep_lock();
145 w->done = 1;
146 old_done = todo_done;
147 for(; todo[todo_done].done && todo_done != todo_start;
148 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
149 w = &todo[todo_done];
431d6e7b 150 if (w->out.len) {
08303c36
RS
151 const char *p = w->out.buf;
152 size_t len = w->out.len;
153
154 /* Skip the leading hunk mark of the first file. */
155 if (skip_first_line) {
156 while (len) {
157 len--;
158 if (*p++ == '\n')
159 break;
160 }
161 skip_first_line = 0;
162 }
163
164 write_or_die(1, p, len);
431d6e7b 165 }
8f24a632 166 grep_source_clear(&w->source);
5b594f45
FK
167 }
168
169 if (old_done != todo_done)
170 pthread_cond_signal(&cond_write);
171
172 if (all_work_added && todo_done == todo_end)
173 pthread_cond_signal(&cond_result);
174
175 grep_unlock();
176}
177
178static void *run(void *arg)
179{
180 int hit = 0;
181 struct grep_opt *opt = arg;
182
183 while (1) {
184 struct work_item *w = get_work();
185 if (!w)
186 break;
187
188 opt->output_priv = w;
0281e487
BW
189 if (w->source.type == GREP_SOURCE_SUBMODULE)
190 hit |= grep_submodule_launch(opt, &w->source);
191 else
192 hit |= grep_source(opt, &w->source);
8f24a632 193 grep_source_clear_data(&w->source);
5b594f45
FK
194 work_done(w);
195 }
bfac23d9
DM
196 free_grep_patterns(arg);
197 free(arg);
5b594f45
FK
198
199 return (void*) (intptr_t) hit;
200}
201
202static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
203{
204 struct work_item *w = opt->output_priv;
205 strbuf_add(&w->out, buf, size);
206}
207
208static void start_threads(struct grep_opt *opt)
209{
210 int i;
211
212 pthread_mutex_init(&grep_mutex, NULL);
b3aeb285 213 pthread_mutex_init(&grep_read_mutex, NULL);
0579f91d 214 pthread_mutex_init(&grep_attr_mutex, NULL);
5b594f45
FK
215 pthread_cond_init(&cond_add, NULL);
216 pthread_cond_init(&cond_write, NULL);
217 pthread_cond_init(&cond_result, NULL);
78db6ea9 218 grep_use_locks = 1;
5b594f45
FK
219
220 for (i = 0; i < ARRAY_SIZE(todo); i++) {
221 strbuf_init(&todo[i].out, 0);
222 }
223
89f09dd3
VL
224 threads = xcalloc(num_threads, sizeof(*threads));
225 for (i = 0; i < num_threads; i++) {
5b594f45
FK
226 int err;
227 struct grep_opt *o = grep_opt_dup(opt);
228 o->output = strbuf_out;
6d423dd5
ÆAB
229 if (i)
230 o->debug = 0;
5b594f45
FK
231 compile_grep_patterns(o);
232 err = pthread_create(&threads[i], NULL, run, o);
233
234 if (err)
2fc5f9f1 235 die(_("grep: failed to create thread: %s"),
5b594f45
FK
236 strerror(err));
237 }
238}
239
240static int wait_all(void)
241{
242 int hit = 0;
243 int i;
244
245 grep_lock();
246 all_work_added = 1;
247
248 /* Wait until all work is done. */
249 while (todo_done != todo_end)
250 pthread_cond_wait(&cond_result, &grep_mutex);
251
252 /* Wake up all the consumer threads so they can see that there
253 * is no more work to do.
254 */
255 pthread_cond_broadcast(&cond_add);
256 grep_unlock();
257
89f09dd3 258 for (i = 0; i < num_threads; i++) {
5b594f45
FK
259 void *h;
260 pthread_join(threads[i], &h);
261 hit |= (int) (intptr_t) h;
262 }
263
89f09dd3
VL
264 free(threads);
265
5b594f45 266 pthread_mutex_destroy(&grep_mutex);
b3aeb285 267 pthread_mutex_destroy(&grep_read_mutex);
0579f91d 268 pthread_mutex_destroy(&grep_attr_mutex);
5b594f45
FK
269 pthread_cond_destroy(&cond_add);
270 pthread_cond_destroy(&cond_write);
271 pthread_cond_destroy(&cond_result);
78db6ea9 272 grep_use_locks = 0;
5b594f45
FK
273
274 return hit;
275}
276#else /* !NO_PTHREADS */
5b594f45
FK
277
278static int wait_all(void)
279{
280 return 0;
281}
282#endif
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);
287 if (git_color_default_config(var, value, cb) < 0)
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);
d1edee4a
ÆAB
295#ifdef NO_PTHREADS
296 else if (num_threads && num_threads != 1) {
297 /*
298 * TRANSLATORS: %s is the configuration
299 * variable for tweaking threads, currently
300 * grep.threads
301 */
302 warning(_("no threads support, ignoring %s"), var);
303 num_threads = 0;
304 }
305#endif
89f09dd3
VL
306 }
307
9071c078
SB
308 if (!strcmp(var, "submodule.recurse"))
309 recurse_submodules = git_config_bool(var, value);
310
15fabd1b
JH
311 return st;
312}
313
1db11086 314static void *lock_and_read_oid_file(const struct object_id *oid, enum object_type *type, unsigned long *size)
5f02d315
JH
315{
316 void *data;
317
b3aeb285 318 grep_read_lock();
1db11086 319 data = read_sha1_file(oid->hash, type, size);
b3aeb285 320 grep_read_unlock();
5b594f45
FK
321 return data;
322}
323
1db11086 324static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
55c61688
NTND
325 const char *filename, int tree_name_len,
326 const char *path)
5b594f45
FK
327{
328 struct strbuf pathbuf = STRBUF_INIT;
5b594f45 329
be80a239 330 if (super_prefix) {
0281e487
BW
331 strbuf_add(&pathbuf, filename, tree_name_len);
332 strbuf_addstr(&pathbuf, super_prefix);
333 strbuf_addstr(&pathbuf, filename + tree_name_len);
5b594f45
FK
334 } else {
335 strbuf_addstr(&pathbuf, filename);
336 }
337
be80a239
BW
338 if (opt->relative && opt->prefix_length) {
339 char *name = strbuf_detach(&pathbuf, NULL);
340 quote_path_relative(name + tree_name_len, opt->prefix, &pathbuf);
341 strbuf_insert(&pathbuf, 0, name, tree_name_len);
342 free(name);
343 }
344
5b594f45 345#ifndef NO_PTHREADS
89f09dd3 346 if (num_threads) {
1c41c82b 347 add_work(opt, GREP_SOURCE_OID, pathbuf.buf, path, oid);
8f24a632 348 strbuf_release(&pathbuf);
5b594f45
FK
349 return 0;
350 } else
351#endif
352 {
8f24a632 353 struct grep_source gs;
5b594f45 354 int hit;
5010cb5f 355
1c41c82b 356 grep_source_init(&gs, GREP_SOURCE_OID, pathbuf.buf, path, oid);
8f24a632
JK
357 strbuf_release(&pathbuf);
358 hit = grep_source(opt, &gs);
dc49cd76 359
8f24a632
JK
360 grep_source_clear(&gs);
361 return hit;
5010cb5f 362 }
5b594f45
FK
363}
364
365static int grep_file(struct grep_opt *opt, const char *filename)
366{
367 struct strbuf buf = STRBUF_INIT;
5b594f45 368
be80a239
BW
369 if (super_prefix)
370 strbuf_addstr(&buf, super_prefix);
371 strbuf_addstr(&buf, filename);
372
0281e487 373 if (opt->relative && opt->prefix_length) {
be80a239
BW
374 char *name = strbuf_detach(&buf, NULL);
375 quote_path_relative(name, opt->prefix, &buf);
376 free(name);
0281e487 377 }
5b594f45
FK
378
379#ifndef NO_PTHREADS
89f09dd3 380 if (num_threads) {
55c61688 381 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
8f24a632 382 strbuf_release(&buf);
5b594f45
FK
383 return 0;
384 } else
385#endif
386 {
8f24a632 387 struct grep_source gs;
5b594f45 388 int hit;
5b594f45 389
55c61688 390 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
8f24a632
JK
391 strbuf_release(&buf);
392 hit = grep_source(opt, &gs);
393
394 grep_source_clear(&gs);
5b594f45
FK
395 return hit;
396 }
5010cb5f
JH
397}
398
678e484b
JS
399static void append_path(struct grep_opt *opt, const void *data, size_t len)
400{
401 struct string_list *path_list = opt->output_priv;
402
403 if (len == 1 && *(const char *)data == '\0')
404 return;
0c72cead 405 string_list_append(path_list, xstrndup(data, len));
678e484b
JS
406}
407
408static void run_pager(struct grep_opt *opt, const char *prefix)
409{
410 struct string_list *path_list = opt->output_priv;
850d2fec 411 struct child_process child = CHILD_PROCESS_INIT;
678e484b
JS
412 int i, status;
413
414 for (i = 0; i < path_list->nr; i++)
850d2fec
JK
415 argv_array_push(&child.args, path_list->items[i].string);
416 child.dir = prefix;
417 child.use_shell = 1;
678e484b 418
850d2fec 419 status = run_command(&child);
678e484b
JS
420 if (status)
421 exit(status);
678e484b
JS
422}
423
0281e487 424static void compile_submodule_options(const struct grep_opt *opt,
be80a239 425 const char **argv,
0281e487
BW
426 int cached, int untracked,
427 int opt_exclude, int use_index,
428 int pattern_type_arg)
429{
430 struct grep_pat *pattern;
0281e487
BW
431
432 if (recurse_submodules)
433 argv_array_push(&submodule_options, "--recurse-submodules");
434
435 if (cached)
436 argv_array_push(&submodule_options, "--cached");
437 if (!use_index)
438 argv_array_push(&submodule_options, "--no-index");
439 if (untracked)
440 argv_array_push(&submodule_options, "--untracked");
441 if (opt_exclude > 0)
442 argv_array_push(&submodule_options, "--exclude-standard");
443
444 if (opt->invert)
445 argv_array_push(&submodule_options, "-v");
446 if (opt->ignore_case)
447 argv_array_push(&submodule_options, "-i");
448 if (opt->word_regexp)
449 argv_array_push(&submodule_options, "-w");
450 switch (opt->binary) {
451 case GREP_BINARY_NOMATCH:
452 argv_array_push(&submodule_options, "-I");
453 break;
454 case GREP_BINARY_TEXT:
455 argv_array_push(&submodule_options, "-a");
456 break;
457 default:
458 break;
459 }
460 if (opt->allow_textconv)
461 argv_array_push(&submodule_options, "--textconv");
462 if (opt->max_depth != -1)
463 argv_array_pushf(&submodule_options, "--max-depth=%d",
464 opt->max_depth);
465 if (opt->linenum)
466 argv_array_push(&submodule_options, "-n");
467 if (!opt->pathname)
468 argv_array_push(&submodule_options, "-h");
469 if (!opt->relative)
470 argv_array_push(&submodule_options, "--full-name");
471 if (opt->name_only)
472 argv_array_push(&submodule_options, "-l");
473 if (opt->unmatch_name_only)
474 argv_array_push(&submodule_options, "-L");
475 if (opt->null_following_name)
476 argv_array_push(&submodule_options, "-z");
477 if (opt->count)
478 argv_array_push(&submodule_options, "-c");
479 if (opt->file_break)
480 argv_array_push(&submodule_options, "--break");
481 if (opt->heading)
482 argv_array_push(&submodule_options, "--heading");
483 if (opt->pre_context)
484 argv_array_pushf(&submodule_options, "--before-context=%d",
485 opt->pre_context);
486 if (opt->post_context)
487 argv_array_pushf(&submodule_options, "--after-context=%d",
488 opt->post_context);
489 if (opt->funcname)
490 argv_array_push(&submodule_options, "-p");
491 if (opt->funcbody)
492 argv_array_push(&submodule_options, "-W");
493 if (opt->all_match)
494 argv_array_push(&submodule_options, "--all-match");
495 if (opt->debug)
496 argv_array_push(&submodule_options, "--debug");
497 if (opt->status_only)
498 argv_array_push(&submodule_options, "-q");
499
500 switch (pattern_type_arg) {
501 case GREP_PATTERN_TYPE_BRE:
502 argv_array_push(&submodule_options, "-G");
503 break;
504 case GREP_PATTERN_TYPE_ERE:
505 argv_array_push(&submodule_options, "-E");
506 break;
507 case GREP_PATTERN_TYPE_FIXED:
508 argv_array_push(&submodule_options, "-F");
509 break;
510 case GREP_PATTERN_TYPE_PCRE:
511 argv_array_push(&submodule_options, "-P");
512 break;
513 case GREP_PATTERN_TYPE_UNSPECIFIED:
514 break;
374166cb
ÆAB
515 default:
516 die("BUG: Added a new grep pattern type without updating switch statement");
0281e487
BW
517 }
518
519 for (pattern = opt->pattern_list; pattern != NULL;
520 pattern = pattern->next) {
521 switch (pattern->token) {
522 case GREP_PATTERN:
523 argv_array_pushf(&submodule_options, "-e%s",
524 pattern->pattern);
525 break;
526 case GREP_AND:
527 case GREP_OPEN_PAREN:
528 case GREP_CLOSE_PAREN:
529 case GREP_NOT:
530 case GREP_OR:
531 argv_array_push(&submodule_options, pattern->pattern);
532 break;
533 /* BODY and HEAD are not used by git-grep */
534 case GREP_PATTERN_BODY:
535 case GREP_PATTERN_HEAD:
536 break;
537 }
538 }
539
540 /*
541 * Limit number of threads for child process to use.
542 * This is to prevent potential fork-bomb behavior of git-grep as each
543 * submodule process has its own thread pool.
544 */
545 argv_array_pushf(&submodule_options, "--threads=%d",
42c78a21 546 DIV_ROUND_UP(num_threads, 2));
0281e487
BW
547
548 /* Add Pathspecs */
549 argv_array_push(&submodule_options, "--");
be80a239
BW
550 for (; *argv; argv++)
551 argv_array_push(&submodule_options, *argv);
0281e487
BW
552}
553
554/*
555 * Launch child process to grep contents of a submodule
556 */
557static int grep_submodule_launch(struct grep_opt *opt,
558 const struct grep_source *gs)
559{
560 struct child_process cp = CHILD_PROCESS_INIT;
561 int status, i;
74ed4371
BW
562 const char *end_of_base;
563 const char *name;
2225e1ea 564 struct strbuf child_output = STRBUF_INIT;
0281e487 565
74ed4371
BW
566 end_of_base = strchr(gs->name, ':');
567 if (gs->identifier && end_of_base)
568 name = end_of_base + 1;
569 else
570 name = gs->name;
571
0281e487 572 prepare_submodule_repo_env(&cp.env_array);
e6fac7f3 573 argv_array_push(&cp.env_array, GIT_DIR_ENVIRONMENT);
0281e487 574
be80a239
BW
575 if (opt->relative && opt->prefix_length)
576 argv_array_pushf(&cp.env_array, "%s=%s",
577 GIT_TOPLEVEL_PREFIX_ENVIRONMENT,
578 opt->prefix);
579
0281e487
BW
580 /* Add super prefix */
581 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
582 super_prefix ? super_prefix : "",
74ed4371 583 name);
0281e487
BW
584 argv_array_push(&cp.args, "grep");
585
74ed4371
BW
586 /*
587 * Add basename of parent project
588 * When performing grep on a tree object the filename is prefixed
589 * with the object's name: 'tree-name:filename'. In order to
590 * provide uniformity of output we want to pass the name of the
591 * parent project's object name to the submodule so the submodule can
1c41c82b 592 * prefix its output with the parent's name and not its own OID.
74ed4371
BW
593 */
594 if (gs->identifier && end_of_base)
595 argv_array_pushf(&cp.args, "--parent-basename=%.*s",
596 (int) (end_of_base - gs->name),
597 gs->name);
598
0281e487 599 /* Add options */
74ed4371
BW
600 for (i = 0; i < submodule_options.argc; i++) {
601 /*
602 * If there is a tree identifier for the submodule, add the
603 * rev after adding the submodule options but before the
604 * pathspecs. To do this we listen for the '--' and insert the
1c41c82b 605 * oid before pushing the '--' onto the child process argv
74ed4371
BW
606 * array.
607 */
608 if (gs->identifier &&
609 !strcmp("--", submodule_options.argv[i])) {
1c41c82b 610 argv_array_push(&cp.args, oid_to_hex(gs->identifier));
74ed4371
BW
611 }
612
0281e487 613 argv_array_push(&cp.args, submodule_options.argv[i]);
74ed4371 614 }
0281e487
BW
615
616 cp.git_cmd = 1;
617 cp.dir = gs->path;
618
619 /*
620 * Capture output to output buffer and check the return code from the
621 * child process. A '0' indicates a hit, a '1' indicates no hit and
622 * anything else is an error.
623 */
2225e1ea 624 status = capture_command(&cp, &child_output, 0);
0281e487
BW
625 if (status && (status != 1)) {
626 /* flush the buffer */
2225e1ea 627 write_or_die(1, child_output.buf, child_output.len);
0281e487
BW
628 die("process for submodule '%s' failed with exit code: %d",
629 gs->name, status);
630 }
631
2225e1ea
BW
632 opt->output(opt, child_output.buf, child_output.len);
633 strbuf_release(&child_output);
0281e487
BW
634 /* invert the return code to make a hit equal to 1 */
635 return !status;
636}
637
638/*
639 * Prep grep structures for a submodule grep
1c41c82b 640 * oid: the oid of the submodule or NULL if using the working tree
0281e487
BW
641 * filename: name of the submodule including tree name of parent
642 * path: location of the submodule
643 */
1c41c82b 644static int grep_submodule(struct grep_opt *opt, const struct object_id *oid,
0281e487
BW
645 const char *filename, const char *path)
646{
627d9342 647 if (!is_submodule_active(the_repository, path))
0281e487 648 return 0;
15cdc647 649 if (!is_submodule_populated_gently(path, NULL)) {
e6fac7f3 650 /*
64127575 651 * If searching history, check for the presence of the
e6fac7f3
BW
652 * submodule's gitdir before skipping the submodule.
653 */
1c41c82b 654 if (oid) {
e6fac7f3
BW
655 const struct submodule *sub =
656 submodule_from_path(null_sha1, path);
657 if (sub)
658 path = git_path("modules/%s", sub->name);
659
660 if (!(is_directory(path) && is_git_directory(path)))
661 return 0;
662 } else {
663 return 0;
664 }
665 }
0281e487
BW
666
667#ifndef NO_PTHREADS
668 if (num_threads) {
1c41c82b 669 add_work(opt, GREP_SOURCE_SUBMODULE, filename, path, oid);
0281e487
BW
670 return 0;
671 } else
672#endif
673 {
2225e1ea 674 struct grep_source gs;
0281e487
BW
675 int hit;
676
2225e1ea 677 grep_source_init(&gs, GREP_SOURCE_SUBMODULE,
1c41c82b 678 filename, path, oid);
2225e1ea 679 hit = grep_submodule_launch(opt, &gs);
0281e487 680
2225e1ea 681 grep_source_clear(&gs);
0281e487
BW
682 return hit;
683 }
684}
685
686static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec,
687 int cached)
5010cb5f
JH
688{
689 int hit = 0;
690 int nr;
0281e487
BW
691 struct strbuf name = STRBUF_INIT;
692 int name_base_len = 0;
693 if (super_prefix) {
694 name_base_len = strlen(super_prefix);
695 strbuf_addstr(&name, super_prefix);
696 }
697
5010cb5f
JH
698 read_cache();
699
700 for (nr = 0; nr < active_nr; nr++) {
9c5e6c80 701 const struct cache_entry *ce = active_cache[nr];
0281e487
BW
702 strbuf_setlen(&name, name_base_len);
703 strbuf_addstr(&name, ce->name);
704
705 if (S_ISREG(ce->ce_mode) &&
706 match_pathspec(pathspec, name.buf, name.len, 0, NULL,
707 S_ISDIR(ce->ce_mode) ||
708 S_ISGITLINK(ce->ce_mode))) {
709 /*
710 * If CE_VALID is on, we assume worktree file and its
711 * cache entry are identical, even if worktree file has
712 * been modified, so use cache version instead
713 */
714 if (cached || (ce->ce_flags & CE_VALID) ||
715 ce_skip_worktree(ce)) {
716 if (ce_stage(ce) || ce_intent_to_add(ce))
717 continue;
1db11086 718 hit |= grep_oid(opt, &ce->oid, ce->name,
0281e487
BW
719 0, ce->name);
720 } else {
721 hit |= grep_file(opt, ce->name);
722 }
723 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
724 submodule_path_match(pathspec, name.buf, NULL)) {
725 hit |= grep_submodule(opt, NULL, ce->name, ce->name);
726 } else {
5010cb5f 727 continue;
36f2587f 728 }
0281e487 729
36f2587f
JH
730 if (ce_stage(ce)) {
731 do {
732 nr++;
733 } while (nr < active_nr &&
734 !strcmp(ce->name, active_cache[nr]->name));
735 nr--; /* compensate for loop control */
736 }
c8610a2e
JH
737 if (hit && opt->status_only)
738 break;
5010cb5f 739 }
0281e487
BW
740
741 strbuf_release(&name);
5010cb5f
JH
742 return hit;
743}
744
f34bbc15 745static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
55c61688
NTND
746 struct tree_desc *tree, struct strbuf *base, int tn_len,
747 int check_attr)
5010cb5f 748{
d688cf07
NTND
749 int hit = 0;
750 enum interesting match = entry_not_interesting;
4c068a98 751 struct name_entry entry;
e5e062b6 752 int old_baselen = base->len;
74ed4371
BW
753 struct strbuf name = STRBUF_INIT;
754 int name_base_len = 0;
755 if (super_prefix) {
756 strbuf_addstr(&name, super_prefix);
757 name_base_len = name.len;
758 }
5010cb5f 759
4c068a98 760 while (tree_entry(tree, &entry)) {
0de16337 761 int te_len = tree_entry_len(&entry);
e5e062b6 762
d688cf07 763 if (match != all_entries_interesting) {
74ed4371
BW
764 strbuf_addstr(&name, base->buf + tn_len);
765 match = tree_entry_interesting(&entry, &name,
766 0, pathspec);
767 strbuf_setlen(&name, name_base_len);
768
d688cf07 769 if (match == all_entries_not_interesting)
97d0b74a 770 break;
d688cf07 771 if (match == entry_not_interesting)
1376e507
NTND
772 continue;
773 }
5010cb5f 774
1376e507 775 strbuf_add(base, entry.path, te_len);
e0eb889f 776
1376e507 777 if (S_ISREG(entry.mode)) {
1db11086 778 hit |= grep_oid(opt, entry.oid, base->buf, tn_len,
55c61688 779 check_attr ? base->buf + tn_len : NULL);
74ed4371 780 } else if (S_ISDIR(entry.mode)) {
21666f1a 781 enum object_type type;
5010cb5f
JH
782 struct tree_desc sub;
783 void *data;
6fda5e51
LT
784 unsigned long size;
785
1db11086 786 data = lock_and_read_oid_file(entry.oid, &type, &size);
5010cb5f 787 if (!data)
2fc5f9f1 788 die(_("unable to read tree (%s)"),
7d924c91 789 oid_to_hex(entry.oid));
1376e507
NTND
790
791 strbuf_addch(base, '/');
6fda5e51 792 init_tree_desc(&sub, data, size);
55c61688
NTND
793 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
794 check_attr);
5010cb5f 795 free(data);
74ed4371 796 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
1c41c82b 797 hit |= grep_submodule(opt, entry.oid, base->buf,
74ed4371 798 base->buf + tn_len);
5010cb5f 799 }
74ed4371 800
e5e062b6
NTND
801 strbuf_setlen(base, old_baselen);
802
c8610a2e
JH
803 if (hit && opt->status_only)
804 break;
5010cb5f 805 }
74ed4371
BW
806
807 strbuf_release(&name);
5010cb5f
JH
808 return hit;
809}
810
f34bbc15 811static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
9e0c3c4f 812 struct object *obj, const char *name, const char *path)
5010cb5f 813{
1974632c 814 if (obj->type == OBJ_BLOB)
1db11086 815 return grep_oid(opt, &obj->oid, name, 0, path);
1974632c 816 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
817 struct tree_desc tree;
818 void *data;
6fda5e51 819 unsigned long size;
e5e062b6
NTND
820 struct strbuf base;
821 int hit, len;
822
b3aeb285 823 grep_read_lock();
f2fd0760 824 data = read_object_with_reference(obj->oid.hash, tree_type,
6fda5e51 825 &size, NULL);
b3aeb285 826 grep_read_unlock();
8cb5775b 827
5010cb5f 828 if (!data)
f2fd0760 829 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
e5e062b6 830
74ed4371
BW
831 /* Use parent's name as base when recursing submodules */
832 if (recurse_submodules && parent_basename)
833 name = parent_basename;
834
e5e062b6
NTND
835 len = name ? strlen(name) : 0;
836 strbuf_init(&base, PATH_MAX + len + 1);
837 if (len) {
838 strbuf_add(&base, name, len);
839 strbuf_addch(&base, ':');
840 }
6fda5e51 841 init_tree_desc(&tree, data, size);
55c61688
NTND
842 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
843 obj->type == OBJ_COMMIT);
e5e062b6 844 strbuf_release(&base);
5010cb5f
JH
845 free(data);
846 return hit;
847 }
2fc5f9f1 848 die(_("unable to grep from object of type %s"), typename(obj->type));
5010cb5f
JH
849}
850
f34bbc15 851static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
30d00c39
JN
852 const struct object_array *list)
853{
854 unsigned int i;
855 int hit = 0;
856 const unsigned int nr = list->nr;
857
858 for (i = 0; i < nr; i++) {
859 struct object *real_obj;
860 real_obj = deref_tag(list->objects[i].item, NULL, 0);
74ed4371
BW
861
862 /* load the gitmodules file for this rev */
863 if (recurse_submodules) {
864 submodule_free();
865 gitmodules_config_sha1(real_obj->oid.hash);
866 }
9e0c3c4f 867 if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
30d00c39
JN
868 hit = 1;
869 if (opt->status_only)
870 break;
871 }
872 }
873 return hit;
874}
875
dbfae86a 876static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
85975c0c 877 int exc_std, int use_index)
59332d13
JH
878{
879 struct dir_struct dir;
880 int i, hit = 0;
881
882 memset(&dir, 0, sizeof(dir));
85975c0c
JK
883 if (!use_index)
884 dir.flags |= DIR_NO_GITLINKS;
0a93fb8a
JH
885 if (exc_std)
886 setup_standard_excludes(&dir);
59332d13 887
0d32c183 888 fill_directory(&dir, &the_index, pathspec);
59332d13 889 for (i = 0; i < dir.nr; i++) {
ebb32893 890 if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
9d8b831b 891 continue;
59332d13
JH
892 hit |= grep_file(opt, dir.entries[i]->name);
893 if (hit && opt->status_only)
894 break;
895 }
59332d13
JH
896 return hit;
897}
898
ff3c7f9a
RS
899static int context_callback(const struct option *opt, const char *arg,
900 int unset)
3e230fa1
RS
901{
902 struct grep_opt *grep_opt = opt->value;
903 int value;
904 const char *endp;
905
906 if (unset) {
907 grep_opt->pre_context = grep_opt->post_context = 0;
908 return 0;
909 }
910 value = strtol(arg, (char **)&endp, 10);
911 if (*endp) {
2fc5f9f1 912 return error(_("switch `%c' expects a numerical value"),
3e230fa1
RS
913 opt->short_name);
914 }
915 grep_opt->pre_context = grep_opt->post_context = value;
916 return 0;
917}
918
ff3c7f9a 919static int file_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
920{
921 struct grep_opt *grep_opt = opt->value;
c41dd2fd 922 int from_stdin = !strcmp(arg, "-");
3e230fa1
RS
923 FILE *patterns;
924 int lno = 0;
cfe370c6 925 struct strbuf sb = STRBUF_INIT;
3e230fa1 926
c41dd2fd 927 patterns = from_stdin ? stdin : fopen(arg, "r");
3e230fa1 928 if (!patterns)
2fc5f9f1 929 die_errno(_("cannot open '%s'"), arg);
a5518431 930 while (strbuf_getline(&sb, patterns) == 0) {
3e230fa1
RS
931 /* ignore empty line like grep does */
932 if (sb.len == 0)
933 continue;
ed40a095 934
ec830611
RS
935 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
936 GREP_PATTERN);
3e230fa1 937 }
c41dd2fd
RS
938 if (!from_stdin)
939 fclose(patterns);
3e230fa1
RS
940 strbuf_release(&sb);
941 return 0;
942}
943
ff3c7f9a 944static int not_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
945{
946 struct grep_opt *grep_opt = opt->value;
947 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
948 return 0;
949}
950
ff3c7f9a 951static int and_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
952{
953 struct grep_opt *grep_opt = opt->value;
954 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
955 return 0;
956}
957
ff3c7f9a 958static int open_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
959{
960 struct grep_opt *grep_opt = opt->value;
961 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
962 return 0;
963}
964
ff3c7f9a 965static int close_callback(const struct option *opt, const char *arg, int unset)
3e230fa1
RS
966{
967 struct grep_opt *grep_opt = opt->value;
968 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
969 return 0;
970}
971
ff3c7f9a
RS
972static int pattern_callback(const struct option *opt, const char *arg,
973 int unset)
3e230fa1
RS
974{
975 struct grep_opt *grep_opt = opt->value;
976 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
977 return 0;
978}
5010cb5f 979
a633fca0 980int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 981{
5010cb5f 982 int hit = 0;
0a93fb8a 983 int cached = 0, untracked = 0, opt_exclude = -1;
5acd64ed 984 int seen_dashdash = 0;
bbc09c22 985 int external_grep_allowed__ignored;
0af88c15 986 const char *show_in_pager = NULL, *default_pager = "dummy";
5010cb5f 987 struct grep_opt opt;
3cd47459 988 struct object_array list = OBJECT_ARRAY_INIT;
f34bbc15 989 struct pathspec pathspec;
183113a5 990 struct string_list path_list = STRING_LIST_INIT_NODUP;
5acd64ed 991 int i;
3e230fa1 992 int dummy;
ff38d1a9 993 int use_index = 1;
84befcd0 994 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
131f3c96 995 int allow_revs;
cca2c172 996
3e230fa1 997 struct option options[] = {
d5d09d47 998 OPT_BOOL(0, "cached", &cached,
4b407bc5 999 N_("search in index instead of in the work tree")),
cbb08c2e 1000 OPT_NEGBIT(0, "no-index", &use_index,
f63cf8c9 1001 N_("find in contents not managed by git"), 1),
d5d09d47 1002 OPT_BOOL(0, "untracked", &untracked,
4b407bc5 1003 N_("search in both tracked and untracked files")),
0a93fb8a 1004 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
77fdb8a8 1005 N_("ignore files specified via '.gitignore'"), 1),
0281e487 1006 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
4fb1c6aa 1007 N_("recursively search in each submodule")),
74ed4371
BW
1008 OPT_STRING(0, "parent-basename", &parent_basename,
1009 N_("basename"),
1010 N_("prepend parent project's basename to output")),
3e230fa1 1011 OPT_GROUP(""),
d5d09d47 1012 OPT_BOOL('v', "invert-match", &opt.invert,
4b407bc5 1013 N_("show non-matching lines")),
d5d09d47 1014 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
4b407bc5 1015 N_("case insensitive matching")),
d5d09d47 1016 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
4b407bc5 1017 N_("match patterns only at word boundaries")),
3e230fa1 1018 OPT_SET_INT('a', "text", &opt.binary,
4b407bc5 1019 N_("process binary files as text"), GREP_BINARY_TEXT),
3e230fa1 1020 OPT_SET_INT('I', NULL, &opt.binary,
4b407bc5 1021 N_("don't match patterns in binary files"),
3e230fa1 1022 GREP_BINARY_NOMATCH),
335ec3bf
JK
1023 OPT_BOOL(0, "textconv", &opt.allow_textconv,
1024 N_("process binary files with textconv filters")),
4b407bc5
NTND
1025 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
1026 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
a91f453f 1027 NULL, 1 },
3e230fa1 1028 OPT_GROUP(""),
84befcd0 1029 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
4b407bc5 1030 N_("use extended POSIX regular expressions"),
84befcd0
S
1031 GREP_PATTERN_TYPE_ERE),
1032 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
4b407bc5 1033 N_("use basic POSIX regular expressions (default)"),
84befcd0
S
1034 GREP_PATTERN_TYPE_BRE),
1035 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
4b407bc5 1036 N_("interpret patterns as fixed strings"),
84befcd0
S
1037 GREP_PATTERN_TYPE_FIXED),
1038 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
4b407bc5 1039 N_("use Perl-compatible regular expressions"),
84befcd0 1040 GREP_PATTERN_TYPE_PCRE),
3e230fa1 1041 OPT_GROUP(""),
d5d09d47 1042 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
4b407bc5
NTND
1043 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
1044 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
3e230fa1 1045 OPT_NEGBIT(0, "full-name", &opt.relative,
4b407bc5 1046 N_("show filenames relative to top directory"), 1),
d5d09d47 1047 OPT_BOOL('l', "files-with-matches", &opt.name_only,
4b407bc5 1048 N_("show only filenames instead of matching lines")),
d5d09d47 1049 OPT_BOOL(0, "name-only", &opt.name_only,
4b407bc5 1050 N_("synonym for --files-with-matches")),
d5d09d47 1051 OPT_BOOL('L', "files-without-match",
3e230fa1 1052 &opt.unmatch_name_only,
4b407bc5 1053 N_("show only the names of files without match")),
d5d09d47 1054 OPT_BOOL('z', "null", &opt.null_following_name,
4b407bc5 1055 N_("print NUL after filenames")),
d5d09d47 1056 OPT_BOOL('c', "count", &opt.count,
4b407bc5
NTND
1057 N_("show the number of matches instead of matching lines")),
1058 OPT__COLOR(&opt.color, N_("highlight matches")),
d5d09d47 1059 OPT_BOOL(0, "break", &opt.file_break,
4b407bc5 1060 N_("print empty line between matches from different files")),
d5d09d47 1061 OPT_BOOL(0, "heading", &opt.heading,
4b407bc5 1062 N_("show filename only once above matches from same file")),
3e230fa1 1063 OPT_GROUP(""),
4b407bc5
NTND
1064 OPT_CALLBACK('C', "context", &opt, N_("n"),
1065 N_("show <n> context lines before and after matches"),
3e230fa1 1066 context_callback),
317f63c2 1067 OPT_INTEGER('B', "before-context", &opt.pre_context,
4b407bc5 1068 N_("show <n> context lines before matches")),
317f63c2 1069 OPT_INTEGER('A', "after-context", &opt.post_context,
4b407bc5 1070 N_("show <n> context lines after matches")),
89f09dd3
VL
1071 OPT_INTEGER(0, "threads", &num_threads,
1072 N_("use <n> worker threads")),
4b407bc5 1073 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
3e230fa1 1074 context_callback),
d5d09d47 1075 OPT_BOOL('p', "show-function", &opt.funcname,
4b407bc5 1076 N_("show a line with the function name before matches")),
d5d09d47 1077 OPT_BOOL('W', "function-context", &opt.funcbody,
4b407bc5 1078 N_("show the surrounding function")),
3e230fa1 1079 OPT_GROUP(""),
4b407bc5
NTND
1080 OPT_CALLBACK('f', NULL, &opt, N_("file"),
1081 N_("read patterns from file"), file_callback),
1082 { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
1083 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
3e230fa1 1084 { OPTION_CALLBACK, 0, "and", &opt, NULL,
4b407bc5 1085 N_("combine patterns specified with -e"),
3e230fa1 1086 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
d5d09d47 1087 OPT_BOOL(0, "or", &dummy, ""),
3e230fa1
RS
1088 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
1089 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
1090 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
1091 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1092 open_callback },
1093 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
1094 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1095 close_callback },
d52ee6e6 1096 OPT__QUIET(&opt.status_only,
4b407bc5 1097 N_("indicate hit with exit status without output")),
d5d09d47 1098 OPT_BOOL(0, "all-match", &opt.all_match,
4b407bc5 1099 N_("show only matches from files that match all patterns")),
17bf35a3 1100 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
3d7535e4 1101 N_("show parse tree for grep expression"),
17bf35a3 1102 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
3e230fa1 1103 OPT_GROUP(""),
0af88c15 1104 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
4b407bc5 1105 N_("pager"), N_("show matching files in the pager"),
0af88c15 1106 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
d5d09d47
SB
1107 OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
1108 N_("allow calling of grep(1) (ignored by this build)")),
3e230fa1
RS
1109 OPT_END()
1110 };
5010cb5f 1111
15fabd1b
JH
1112 init_grep_defaults();
1113 git_config(grep_cmd_config, NULL);
1114 grep_init(&opt, prefix);
0281e487 1115 super_prefix = get_super_prefix();
7e8f59d5 1116
5010cb5f 1117 /*
5acd64ed
JH
1118 * If there is no -- then the paths must exist in the working
1119 * tree. If there is no explicit pattern specified with -e or
1120 * -f, we take the first unrecognized non option to be the
1121 * pattern, but then what follows it must be zero or more
1122 * valid refs up to the -- (if exists), and then existing
1123 * paths. If there is an explicit pattern, then the first
82e5a82f 1124 * unrecognized non option is the beginning of the refs list
5acd64ed 1125 * that continues up to the -- (if exists), and then paths.
5010cb5f 1126 */
37782920 1127 argc = parse_options(argc, argv, prefix, options, grep_usage,
3e230fa1 1128 PARSE_OPT_KEEP_DASHDASH |
44415499 1129 PARSE_OPT_STOP_AT_NON_OPTION);
c5c31d33 1130 grep_commit_pattern_type(pattern_type_arg, &opt);
3e230fa1 1131
ecd9ba61
TG
1132 if (use_index && !startup_info->have_repository) {
1133 int fallback = 0;
1134 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1135 if (fallback)
1136 use_index = 0;
1137 else
1138 /* die the same way as if we did it at the beginning */
1139 setup_git_directory();
1140 }
59332d13 1141
1123c67c
JK
1142 /*
1143 * skip a -- separator; we know it cannot be
1144 * separating revisions from pathnames if
1145 * we haven't even had any patterns yet
1146 */
1147 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1148 argv++;
1149 argc--;
1150 }
1151
3e230fa1
RS
1152 /* First unrecognized non-option token */
1153 if (argc > 0 && !opt.pattern_list) {
1154 append_grep_pattern(&opt, argv[0], "command line", 0,
1155 GREP_PATTERN);
1156 argv++;
1157 argc--;
5010cb5f 1158 }
5acd64ed 1159
0af88c15
JS
1160 if (show_in_pager == default_pager)
1161 show_in_pager = git_pager(1);
678e484b 1162 if (show_in_pager) {
e7b082a4 1163 opt.color = 0;
0af88c15
JS
1164 opt.name_only = 1;
1165 opt.null_following_name = 1;
1166 opt.output_priv = &path_list;
1167 opt.output = append_path;
0c72cead 1168 string_list_append(&path_list, show_in_pager);
678e484b
JS
1169 }
1170
f9b9faf6 1171 if (!opt.pattern_list)
2fc5f9f1 1172 die(_("no pattern given."));
5b594f45 1173
b5b81136
JK
1174 /*
1175 * We have to find "--" in a separate pass, because its presence
1176 * influences how we will parse arguments that come before it.
1177 */
1178 for (i = 0; i < argc; i++) {
1179 if (!strcmp(argv[i], "--")) {
1180 seen_dashdash = 1;
1181 break;
1182 }
1183 }
1184
1185 /*
1186 * Resolve any rev arguments. If we have a dashdash, then everything up
1187 * to it must resolve as a rev. If not, then we stop at the first
1188 * non-rev and assume everything else is a path.
1189 */
131f3c96 1190 allow_revs = use_index && !untracked;
3e230fa1 1191 for (i = 0; i < argc; i++) {
5acd64ed 1192 const char *arg = argv[i];
1db11086 1193 struct object_id oid;
afa15f3c 1194 struct object_context oc;
20d6421c
JK
1195 struct object *object;
1196
dca3b5f5
JT
1197 if (!strcmp(arg, "--")) {
1198 i++;
dca3b5f5
JT
1199 break;
1200 }
20d6421c 1201
131f3c96 1202 if (!allow_revs) {
d0ffc069 1203 if (seen_dashdash)
131f3c96 1204 die(_("--no-index or --untracked cannot be used with revs"));
d0ffc069
JK
1205 break;
1206 }
1207
dc944b65
JK
1208 if (get_sha1_with_context(arg, GET_SHA1_RECORD_PATH,
1209 oid.hash, &oc)) {
b5b81136
JK
1210 if (seen_dashdash)
1211 die(_("unable to resolve revision: %s"), arg);
20d6421c 1212 break;
b5b81136 1213 }
20d6421c 1214
c251c83d 1215 object = parse_object_or_die(&oid, arg);
20d6421c
JK
1216 if (!seen_dashdash)
1217 verify_non_filename(prefix, arg);
1218 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
dc944b65 1219 free(oc.path);
1362671f 1220 }
5acd64ed 1221
b5b81136
JK
1222 /*
1223 * Anything left over is presumed to be a path. But in the non-dashdash
1224 * "do what I mean" case, we verify and complain when that isn't true.
1225 */
a0fe2b0d
JK
1226 if (!seen_dashdash) {
1227 int j;
1228 for (j = i; j < argc; j++)
131f3c96 1229 verify_filename(prefix, argv[j], j == i && allow_revs);
a0fe2b0d
JK
1230 }
1231
1232 parse_pathspec(&pathspec, 0,
1233 PATHSPEC_PREFER_CWD |
1234 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1235 prefix, argv + i);
1236 pathspec.max_depth = opt.max_depth;
1237 pathspec.recursive = 1;
1238
53b8d931 1239#ifndef NO_PTHREADS
044b1f3c 1240 if (list.nr || cached || show_in_pager)
89f09dd3
VL
1241 num_threads = 0;
1242 else if (num_threads == 0)
1243 num_threads = GREP_NUM_THREADS_DEFAULT;
1244 else if (num_threads < 0)
1245 die(_("invalid number of threads specified (%d)"), num_threads);
9ec726a4
ÆAB
1246 if (num_threads == 1)
1247 num_threads = 0;
53b8d931 1248#else
d1edee4a
ÆAB
1249 if (num_threads)
1250 warning(_("no threads support, ignoring --threads"));
89f09dd3 1251 num_threads = 0;
53b8d931
TR
1252#endif
1253
6d423dd5
ÆAB
1254 if (!num_threads)
1255 /*
1256 * The compiled patterns on the main path are only
1257 * used when not using threading. Otherwise
1258 * start_threads() below calls compile_grep_patterns()
1259 * for each thread.
1260 */
1261 compile_grep_patterns(&opt);
1262
53b8d931 1263#ifndef NO_PTHREADS
89f09dd3 1264 if (num_threads) {
50dd0f2f
AY
1265 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1266 && (opt.pre_context || opt.post_context ||
1267 opt.file_break || opt.funcbody))
53b8d931
TR
1268 skip_first_line = 1;
1269 start_threads(&opt);
1270 }
1271#endif
1272
0281e487
BW
1273 if (recurse_submodules) {
1274 gitmodules_config();
be80a239 1275 compile_submodule_options(&opt, argv + i, cached, untracked,
0281e487
BW
1276 opt_exclude, use_index,
1277 pattern_type_arg);
1278 }
1279
678e484b 1280 if (show_in_pager && (cached || list.nr))
e4fe4ba5 1281 die(_("--open-files-in-pager only works on the worktree"));
678e484b
JS
1282
1283 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1284 const char *pager = path_list.items[0].string;
1285 int len = strlen(pager);
1286
1287 if (len > 4 && is_dir_sep(pager[len - 5]))
1288 pager += len - 4;
1289
f7febbea
JS
1290 if (opt.ignore_case && !strcmp("less", pager))
1291 string_list_append(&path_list, "-I");
1292
678e484b
JS
1293 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1294 struct strbuf buf = STRBUF_INIT;
1295 strbuf_addf(&buf, "+/%s%s",
1296 strcmp("less", pager) ? "" : "*",
1297 opt.pattern_list->pattern);
0c72cead 1298 string_list_append(&path_list, buf.buf);
678e484b
JS
1299 strbuf_detach(&buf, NULL);
1300 }
1301 }
1302
74ed4371 1303 if (recurse_submodules && (!use_index || untracked))
0281e487
BW
1304 die(_("option not supported with --recurse-submodules."));
1305
c2048f0b 1306 if (!show_in_pager && !opt.status_only)
678e484b
JS
1307 setup_pager();
1308
0a93fb8a 1309 if (!use_index && (untracked || cached))
dbfae86a 1310 die(_("--cached or --untracked cannot be used with --no-index."));
678e484b 1311
0a93fb8a 1312 if (!use_index || untracked) {
0a93fb8a 1313 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
85975c0c 1314 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
dbfae86a 1315 } else if (0 <= opt_exclude) {
9fddaf78 1316 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
685359cf 1317 } else if (!list.nr) {
6577f542
NTND
1318 if (!cached)
1319 setup_work_tree();
5b594f45 1320
f34bbc15 1321 hit = grep_cache(&opt, &pathspec, cached);
685359cf
JS
1322 } else {
1323 if (cached)
2fc5f9f1 1324 die(_("both --cached and trees are given."));
f34bbc15 1325 hit = grep_objects(&opt, &pathspec, &list);
5010cb5f 1326 }
5b594f45 1327
89f09dd3 1328 if (num_threads)
5b594f45 1329 hit |= wait_all();
678e484b
JS
1330 if (hit && show_in_pager)
1331 run_pager(&opt, prefix);
7861fa07 1332 clear_pathspec(&pathspec);
b48fb5b6 1333 free_grep_patterns(&opt);
5010cb5f
JH
1334 return !hit;
1335}