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