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