git-compat-util: add a FREE_AND_NULL() wrapper around free(ptr); ptr = NULL
[alt-git.git] / builtin / grep.c
blobd188871556d814b1532f7118f1d76741850a370d
1 /*
2 * Builtin "git grep"
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"
24 static char const * const grep_usage[] = {
25 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
26 NULL
29 static const char *super_prefix;
30 static int recurse_submodules;
31 static struct argv_array submodule_options = ARGV_ARRAY_INIT;
32 static const char *parent_basename;
34 static int grep_submodule_launch(struct grep_opt *opt,
35 const struct grep_source *gs);
37 #define GREP_NUM_THREADS_DEFAULT 8
38 static int num_threads;
40 #ifndef NO_PTHREADS
41 static pthread_t *threads;
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.
47 struct work_item {
48 struct grep_source source;
49 char done;
50 struct strbuf out;
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.
57 * The work_items in [todo_start, todo_end) are waiting to be picked
58 * up by a consumer thread.
60 * The ranges are modulo TODO_SIZE.
62 #define TODO_SIZE 128
63 static struct work_item todo[TODO_SIZE];
64 static int todo_start;
65 static int todo_end;
66 static int todo_done;
68 /* Has all work items been added? */
69 static int all_work_added;
71 /* This lock protects all the variables above. */
72 static pthread_mutex_t grep_mutex;
74 static inline void grep_lock(void)
76 assert(num_threads);
77 pthread_mutex_lock(&grep_mutex);
80 static inline void grep_unlock(void)
82 assert(num_threads);
83 pthread_mutex_unlock(&grep_mutex);
86 /* Signalled when a new work_item is added to todo. */
87 static pthread_cond_t cond_add;
89 /* Signalled when the result from one work_item is written to
90 * stdout.
92 static pthread_cond_t cond_write;
94 /* Signalled when we are finished with everything. */
95 static pthread_cond_t cond_result;
97 static int skip_first_line;
99 static void add_work(struct grep_opt *opt, enum grep_source_type type,
100 const char *name, const char *path, const void *id)
102 grep_lock();
104 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105 pthread_cond_wait(&cond_write, &grep_mutex);
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);
115 pthread_cond_signal(&cond_add);
116 grep_unlock();
119 static struct work_item *get_work(void)
121 struct work_item *ret;
123 grep_lock();
124 while (todo_start == todo_end && !all_work_added) {
125 pthread_cond_wait(&cond_add, &grep_mutex);
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);
134 grep_unlock();
135 return ret;
138 static void work_done(struct work_item *w)
140 int old_done;
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;
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;
159 skip_first_line = 0;
162 write_or_die(1, p, len);
164 grep_source_clear(&w->source);
167 if (old_done != todo_done)
168 pthread_cond_signal(&cond_write);
170 if (all_work_added && todo_done == todo_end)
171 pthread_cond_signal(&cond_result);
173 grep_unlock();
176 static void *run(void *arg)
178 int hit = 0;
179 struct grep_opt *opt = arg;
181 while (1) {
182 struct work_item *w = get_work();
183 if (!w)
184 break;
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);
194 free_grep_patterns(arg);
195 free(arg);
197 return (void*) (intptr_t) hit;
200 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
202 struct work_item *w = opt->output_priv;
203 strbuf_add(&w->out, buf, size);
206 static void start_threads(struct grep_opt *opt)
208 int i;
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;
218 for (i = 0; i < ARRAY_SIZE(todo); i++) {
219 strbuf_init(&todo[i].out, 0);
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);
231 if (err)
232 die(_("grep: failed to create thread: %s"),
233 strerror(err));
237 static int wait_all(void)
239 int hit = 0;
240 int i;
242 grep_lock();
243 all_work_added = 1;
245 /* Wait until all work is done. */
246 while (todo_done != todo_end)
247 pthread_cond_wait(&cond_result, &grep_mutex);
249 /* Wake up all the consumer threads so they can see that there
250 * is no more work to do.
252 pthread_cond_broadcast(&cond_add);
253 grep_unlock();
255 for (i = 0; i < num_threads; i++) {
256 void *h;
257 pthread_join(threads[i], &h);
258 hit |= (int) (intptr_t) h;
261 free(threads);
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;
271 return hit;
273 #else /* !NO_PTHREADS */
275 static int wait_all(void)
277 return 0;
279 #endif
281 static int grep_cmd_config(const char *var, const char *value, void *cb)
283 int st = grep_config(var, value, cb);
284 if (git_color_default_config(var, value, cb) < 0)
285 st = -1;
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 #ifdef NO_PTHREADS
293 else if (num_threads && num_threads != 1) {
295 * TRANSLATORS: %s is the configuration
296 * variable for tweaking threads, currently
297 * grep.threads
299 warning(_("no threads support, ignoring %s"), var);
300 num_threads = 0;
302 #endif
305 if (!strcmp(var, "submodule.recurse"))
306 recurse_submodules = git_config_bool(var, value);
308 return st;
311 static void *lock_and_read_oid_file(const struct object_id *oid, enum object_type *type, unsigned long *size)
313 void *data;
315 grep_read_lock();
316 data = read_sha1_file(oid->hash, type, size);
317 grep_read_unlock();
318 return data;
321 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
322 const char *filename, int tree_name_len,
323 const char *path)
325 struct strbuf pathbuf = STRBUF_INIT;
327 if (super_prefix) {
328 strbuf_add(&pathbuf, filename, tree_name_len);
329 strbuf_addstr(&pathbuf, super_prefix);
330 strbuf_addstr(&pathbuf, filename + tree_name_len);
331 } else {
332 strbuf_addstr(&pathbuf, filename);
335 if (opt->relative && opt->prefix_length) {
336 char *name = strbuf_detach(&pathbuf, NULL);
337 quote_path_relative(name + tree_name_len, opt->prefix, &pathbuf);
338 strbuf_insert(&pathbuf, 0, name, tree_name_len);
339 free(name);
342 #ifndef NO_PTHREADS
343 if (num_threads) {
344 add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, path, oid);
345 strbuf_release(&pathbuf);
346 return 0;
347 } else
348 #endif
350 struct grep_source gs;
351 int hit;
353 grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, path, oid);
354 strbuf_release(&pathbuf);
355 hit = grep_source(opt, &gs);
357 grep_source_clear(&gs);
358 return hit;
362 static int grep_file(struct grep_opt *opt, const char *filename)
364 struct strbuf buf = STRBUF_INIT;
366 if (super_prefix)
367 strbuf_addstr(&buf, super_prefix);
368 strbuf_addstr(&buf, filename);
370 if (opt->relative && opt->prefix_length) {
371 char *name = strbuf_detach(&buf, NULL);
372 quote_path_relative(name, opt->prefix, &buf);
373 free(name);
376 #ifndef NO_PTHREADS
377 if (num_threads) {
378 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
379 strbuf_release(&buf);
380 return 0;
381 } else
382 #endif
384 struct grep_source gs;
385 int hit;
387 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
388 strbuf_release(&buf);
389 hit = grep_source(opt, &gs);
391 grep_source_clear(&gs);
392 return hit;
396 static void append_path(struct grep_opt *opt, const void *data, size_t len)
398 struct string_list *path_list = opt->output_priv;
400 if (len == 1 && *(const char *)data == '\0')
401 return;
402 string_list_append(path_list, xstrndup(data, len));
405 static void run_pager(struct grep_opt *opt, const char *prefix)
407 struct string_list *path_list = opt->output_priv;
408 struct child_process child = CHILD_PROCESS_INIT;
409 int i, status;
411 for (i = 0; i < path_list->nr; i++)
412 argv_array_push(&child.args, path_list->items[i].string);
413 child.dir = prefix;
414 child.use_shell = 1;
416 status = run_command(&child);
417 if (status)
418 exit(status);
421 static void compile_submodule_options(const struct grep_opt *opt,
422 const char **argv,
423 int cached, int untracked,
424 int opt_exclude, int use_index,
425 int pattern_type_arg)
427 struct grep_pat *pattern;
429 if (recurse_submodules)
430 argv_array_push(&submodule_options, "--recurse-submodules");
432 if (cached)
433 argv_array_push(&submodule_options, "--cached");
434 if (!use_index)
435 argv_array_push(&submodule_options, "--no-index");
436 if (untracked)
437 argv_array_push(&submodule_options, "--untracked");
438 if (opt_exclude > 0)
439 argv_array_push(&submodule_options, "--exclude-standard");
441 if (opt->invert)
442 argv_array_push(&submodule_options, "-v");
443 if (opt->ignore_case)
444 argv_array_push(&submodule_options, "-i");
445 if (opt->word_regexp)
446 argv_array_push(&submodule_options, "-w");
447 switch (opt->binary) {
448 case GREP_BINARY_NOMATCH:
449 argv_array_push(&submodule_options, "-I");
450 break;
451 case GREP_BINARY_TEXT:
452 argv_array_push(&submodule_options, "-a");
453 break;
454 default:
455 break;
457 if (opt->allow_textconv)
458 argv_array_push(&submodule_options, "--textconv");
459 if (opt->max_depth != -1)
460 argv_array_pushf(&submodule_options, "--max-depth=%d",
461 opt->max_depth);
462 if (opt->linenum)
463 argv_array_push(&submodule_options, "-n");
464 if (!opt->pathname)
465 argv_array_push(&submodule_options, "-h");
466 if (!opt->relative)
467 argv_array_push(&submodule_options, "--full-name");
468 if (opt->name_only)
469 argv_array_push(&submodule_options, "-l");
470 if (opt->unmatch_name_only)
471 argv_array_push(&submodule_options, "-L");
472 if (opt->null_following_name)
473 argv_array_push(&submodule_options, "-z");
474 if (opt->count)
475 argv_array_push(&submodule_options, "-c");
476 if (opt->file_break)
477 argv_array_push(&submodule_options, "--break");
478 if (opt->heading)
479 argv_array_push(&submodule_options, "--heading");
480 if (opt->pre_context)
481 argv_array_pushf(&submodule_options, "--before-context=%d",
482 opt->pre_context);
483 if (opt->post_context)
484 argv_array_pushf(&submodule_options, "--after-context=%d",
485 opt->post_context);
486 if (opt->funcname)
487 argv_array_push(&submodule_options, "-p");
488 if (opt->funcbody)
489 argv_array_push(&submodule_options, "-W");
490 if (opt->all_match)
491 argv_array_push(&submodule_options, "--all-match");
492 if (opt->debug)
493 argv_array_push(&submodule_options, "--debug");
494 if (opt->status_only)
495 argv_array_push(&submodule_options, "-q");
497 switch (pattern_type_arg) {
498 case GREP_PATTERN_TYPE_BRE:
499 argv_array_push(&submodule_options, "-G");
500 break;
501 case GREP_PATTERN_TYPE_ERE:
502 argv_array_push(&submodule_options, "-E");
503 break;
504 case GREP_PATTERN_TYPE_FIXED:
505 argv_array_push(&submodule_options, "-F");
506 break;
507 case GREP_PATTERN_TYPE_PCRE:
508 argv_array_push(&submodule_options, "-P");
509 break;
510 case GREP_PATTERN_TYPE_UNSPECIFIED:
511 break;
512 default:
513 die("BUG: Added a new grep pattern type without updating switch statement");
516 for (pattern = opt->pattern_list; pattern != NULL;
517 pattern = pattern->next) {
518 switch (pattern->token) {
519 case GREP_PATTERN:
520 argv_array_pushf(&submodule_options, "-e%s",
521 pattern->pattern);
522 break;
523 case GREP_AND:
524 case GREP_OPEN_PAREN:
525 case GREP_CLOSE_PAREN:
526 case GREP_NOT:
527 case GREP_OR:
528 argv_array_push(&submodule_options, pattern->pattern);
529 break;
530 /* BODY and HEAD are not used by git-grep */
531 case GREP_PATTERN_BODY:
532 case GREP_PATTERN_HEAD:
533 break;
538 * Limit number of threads for child process to use.
539 * This is to prevent potential fork-bomb behavior of git-grep as each
540 * submodule process has its own thread pool.
542 argv_array_pushf(&submodule_options, "--threads=%d",
543 (num_threads + 1) / 2);
545 /* Add Pathspecs */
546 argv_array_push(&submodule_options, "--");
547 for (; *argv; argv++)
548 argv_array_push(&submodule_options, *argv);
552 * Launch child process to grep contents of a submodule
554 static int grep_submodule_launch(struct grep_opt *opt,
555 const struct grep_source *gs)
557 struct child_process cp = CHILD_PROCESS_INIT;
558 int status, i;
559 const char *end_of_base;
560 const char *name;
561 struct strbuf child_output = STRBUF_INIT;
563 end_of_base = strchr(gs->name, ':');
564 if (gs->identifier && end_of_base)
565 name = end_of_base + 1;
566 else
567 name = gs->name;
569 prepare_submodule_repo_env(&cp.env_array);
570 argv_array_push(&cp.env_array, GIT_DIR_ENVIRONMENT);
572 if (opt->relative && opt->prefix_length)
573 argv_array_pushf(&cp.env_array, "%s=%s",
574 GIT_TOPLEVEL_PREFIX_ENVIRONMENT,
575 opt->prefix);
577 /* Add super prefix */
578 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
579 super_prefix ? super_prefix : "",
580 name);
581 argv_array_push(&cp.args, "grep");
584 * Add basename of parent project
585 * When performing grep on a tree object the filename is prefixed
586 * with the object's name: 'tree-name:filename'. In order to
587 * provide uniformity of output we want to pass the name of the
588 * parent project's object name to the submodule so the submodule can
589 * prefix its output with the parent's name and not its own SHA1.
591 if (gs->identifier && end_of_base)
592 argv_array_pushf(&cp.args, "--parent-basename=%.*s",
593 (int) (end_of_base - gs->name),
594 gs->name);
596 /* Add options */
597 for (i = 0; i < submodule_options.argc; i++) {
599 * If there is a tree identifier for the submodule, add the
600 * rev after adding the submodule options but before the
601 * pathspecs. To do this we listen for the '--' and insert the
602 * sha1 before pushing the '--' onto the child process argv
603 * array.
605 if (gs->identifier &&
606 !strcmp("--", submodule_options.argv[i])) {
607 argv_array_push(&cp.args, sha1_to_hex(gs->identifier));
610 argv_array_push(&cp.args, submodule_options.argv[i]);
613 cp.git_cmd = 1;
614 cp.dir = gs->path;
617 * Capture output to output buffer and check the return code from the
618 * child process. A '0' indicates a hit, a '1' indicates no hit and
619 * anything else is an error.
621 status = capture_command(&cp, &child_output, 0);
622 if (status && (status != 1)) {
623 /* flush the buffer */
624 write_or_die(1, child_output.buf, child_output.len);
625 die("process for submodule '%s' failed with exit code: %d",
626 gs->name, status);
629 opt->output(opt, child_output.buf, child_output.len);
630 strbuf_release(&child_output);
631 /* invert the return code to make a hit equal to 1 */
632 return !status;
636 * Prep grep structures for a submodule grep
637 * sha1: the sha1 of the submodule or NULL if using the working tree
638 * filename: name of the submodule including tree name of parent
639 * path: location of the submodule
641 static int grep_submodule(struct grep_opt *opt, const unsigned char *sha1,
642 const char *filename, const char *path)
644 if (!is_submodule_initialized(path))
645 return 0;
646 if (!is_submodule_populated_gently(path, NULL)) {
648 * If searching history, check for the presense of the
649 * submodule's gitdir before skipping the submodule.
651 if (sha1) {
652 const struct submodule *sub =
653 submodule_from_path(null_sha1, path);
654 if (sub)
655 path = git_path("modules/%s", sub->name);
657 if (!(is_directory(path) && is_git_directory(path)))
658 return 0;
659 } else {
660 return 0;
664 #ifndef NO_PTHREADS
665 if (num_threads) {
666 add_work(opt, GREP_SOURCE_SUBMODULE, filename, path, sha1);
667 return 0;
668 } else
669 #endif
671 struct grep_source gs;
672 int hit;
674 grep_source_init(&gs, GREP_SOURCE_SUBMODULE,
675 filename, path, sha1);
676 hit = grep_submodule_launch(opt, &gs);
678 grep_source_clear(&gs);
679 return hit;
683 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec,
684 int cached)
686 int hit = 0;
687 int nr;
688 struct strbuf name = STRBUF_INIT;
689 int name_base_len = 0;
690 if (super_prefix) {
691 name_base_len = strlen(super_prefix);
692 strbuf_addstr(&name, super_prefix);
695 read_cache();
697 for (nr = 0; nr < active_nr; nr++) {
698 const struct cache_entry *ce = active_cache[nr];
699 strbuf_setlen(&name, name_base_len);
700 strbuf_addstr(&name, ce->name);
702 if (S_ISREG(ce->ce_mode) &&
703 match_pathspec(pathspec, name.buf, name.len, 0, NULL,
704 S_ISDIR(ce->ce_mode) ||
705 S_ISGITLINK(ce->ce_mode))) {
707 * If CE_VALID is on, we assume worktree file and its
708 * cache entry are identical, even if worktree file has
709 * been modified, so use cache version instead
711 if (cached || (ce->ce_flags & CE_VALID) ||
712 ce_skip_worktree(ce)) {
713 if (ce_stage(ce) || ce_intent_to_add(ce))
714 continue;
715 hit |= grep_oid(opt, &ce->oid, ce->name,
716 0, ce->name);
717 } else {
718 hit |= grep_file(opt, ce->name);
720 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
721 submodule_path_match(pathspec, name.buf, NULL)) {
722 hit |= grep_submodule(opt, NULL, ce->name, ce->name);
723 } else {
724 continue;
727 if (ce_stage(ce)) {
728 do {
729 nr++;
730 } while (nr < active_nr &&
731 !strcmp(ce->name, active_cache[nr]->name));
732 nr--; /* compensate for loop control */
734 if (hit && opt->status_only)
735 break;
738 strbuf_release(&name);
739 return hit;
742 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
743 struct tree_desc *tree, struct strbuf *base, int tn_len,
744 int check_attr)
746 int hit = 0;
747 enum interesting match = entry_not_interesting;
748 struct name_entry entry;
749 int old_baselen = base->len;
750 struct strbuf name = STRBUF_INIT;
751 int name_base_len = 0;
752 if (super_prefix) {
753 strbuf_addstr(&name, super_prefix);
754 name_base_len = name.len;
757 while (tree_entry(tree, &entry)) {
758 int te_len = tree_entry_len(&entry);
760 if (match != all_entries_interesting) {
761 strbuf_addstr(&name, base->buf + tn_len);
762 match = tree_entry_interesting(&entry, &name,
763 0, pathspec);
764 strbuf_setlen(&name, name_base_len);
766 if (match == all_entries_not_interesting)
767 break;
768 if (match == entry_not_interesting)
769 continue;
772 strbuf_add(base, entry.path, te_len);
774 if (S_ISREG(entry.mode)) {
775 hit |= grep_oid(opt, entry.oid, base->buf, tn_len,
776 check_attr ? base->buf + tn_len : NULL);
777 } else if (S_ISDIR(entry.mode)) {
778 enum object_type type;
779 struct tree_desc sub;
780 void *data;
781 unsigned long size;
783 data = lock_and_read_oid_file(entry.oid, &type, &size);
784 if (!data)
785 die(_("unable to read tree (%s)"),
786 oid_to_hex(entry.oid));
788 strbuf_addch(base, '/');
789 init_tree_desc(&sub, data, size);
790 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
791 check_attr);
792 free(data);
793 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
794 hit |= grep_submodule(opt, entry.oid->hash, base->buf,
795 base->buf + tn_len);
798 strbuf_setlen(base, old_baselen);
800 if (hit && opt->status_only)
801 break;
804 strbuf_release(&name);
805 return hit;
808 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
809 struct object *obj, const char *name, const char *path)
811 if (obj->type == OBJ_BLOB)
812 return grep_oid(opt, &obj->oid, name, 0, path);
813 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
814 struct tree_desc tree;
815 void *data;
816 unsigned long size;
817 struct strbuf base;
818 int hit, len;
820 grep_read_lock();
821 data = read_object_with_reference(obj->oid.hash, tree_type,
822 &size, NULL);
823 grep_read_unlock();
825 if (!data)
826 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
828 /* Use parent's name as base when recursing submodules */
829 if (recurse_submodules && parent_basename)
830 name = parent_basename;
832 len = name ? strlen(name) : 0;
833 strbuf_init(&base, PATH_MAX + len + 1);
834 if (len) {
835 strbuf_add(&base, name, len);
836 strbuf_addch(&base, ':');
838 init_tree_desc(&tree, data, size);
839 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
840 obj->type == OBJ_COMMIT);
841 strbuf_release(&base);
842 free(data);
843 return hit;
845 die(_("unable to grep from object of type %s"), typename(obj->type));
848 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
849 const struct object_array *list)
851 unsigned int i;
852 int hit = 0;
853 const unsigned int nr = list->nr;
855 for (i = 0; i < nr; i++) {
856 struct object *real_obj;
857 real_obj = deref_tag(list->objects[i].item, NULL, 0);
859 /* load the gitmodules file for this rev */
860 if (recurse_submodules) {
861 submodule_free();
862 gitmodules_config_sha1(real_obj->oid.hash);
864 if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
865 hit = 1;
866 if (opt->status_only)
867 break;
870 return hit;
873 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
874 int exc_std, int use_index)
876 struct dir_struct dir;
877 int i, hit = 0;
879 memset(&dir, 0, sizeof(dir));
880 if (!use_index)
881 dir.flags |= DIR_NO_GITLINKS;
882 if (exc_std)
883 setup_standard_excludes(&dir);
885 fill_directory(&dir, &the_index, pathspec);
886 for (i = 0; i < dir.nr; i++) {
887 if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
888 continue;
889 hit |= grep_file(opt, dir.entries[i]->name);
890 if (hit && opt->status_only)
891 break;
893 return hit;
896 static int context_callback(const struct option *opt, const char *arg,
897 int unset)
899 struct grep_opt *grep_opt = opt->value;
900 int value;
901 const char *endp;
903 if (unset) {
904 grep_opt->pre_context = grep_opt->post_context = 0;
905 return 0;
907 value = strtol(arg, (char **)&endp, 10);
908 if (*endp) {
909 return error(_("switch `%c' expects a numerical value"),
910 opt->short_name);
912 grep_opt->pre_context = grep_opt->post_context = value;
913 return 0;
916 static int file_callback(const struct option *opt, const char *arg, int unset)
918 struct grep_opt *grep_opt = opt->value;
919 int from_stdin = !strcmp(arg, "-");
920 FILE *patterns;
921 int lno = 0;
922 struct strbuf sb = STRBUF_INIT;
924 patterns = from_stdin ? stdin : fopen(arg, "r");
925 if (!patterns)
926 die_errno(_("cannot open '%s'"), arg);
927 while (strbuf_getline(&sb, patterns) == 0) {
928 /* ignore empty line like grep does */
929 if (sb.len == 0)
930 continue;
932 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
933 GREP_PATTERN);
935 if (!from_stdin)
936 fclose(patterns);
937 strbuf_release(&sb);
938 return 0;
941 static int not_callback(const struct option *opt, const char *arg, int unset)
943 struct grep_opt *grep_opt = opt->value;
944 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
945 return 0;
948 static int and_callback(const struct option *opt, const char *arg, int unset)
950 struct grep_opt *grep_opt = opt->value;
951 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
952 return 0;
955 static int open_callback(const struct option *opt, const char *arg, int unset)
957 struct grep_opt *grep_opt = opt->value;
958 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
959 return 0;
962 static int close_callback(const struct option *opt, const char *arg, int unset)
964 struct grep_opt *grep_opt = opt->value;
965 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
966 return 0;
969 static int pattern_callback(const struct option *opt, const char *arg,
970 int unset)
972 struct grep_opt *grep_opt = opt->value;
973 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
974 return 0;
977 int cmd_grep(int argc, const char **argv, const char *prefix)
979 int hit = 0;
980 int cached = 0, untracked = 0, opt_exclude = -1;
981 int seen_dashdash = 0;
982 int external_grep_allowed__ignored;
983 const char *show_in_pager = NULL, *default_pager = "dummy";
984 struct grep_opt opt;
985 struct object_array list = OBJECT_ARRAY_INIT;
986 struct pathspec pathspec;
987 struct string_list path_list = STRING_LIST_INIT_NODUP;
988 int i;
989 int dummy;
990 int use_index = 1;
991 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
992 int allow_revs;
994 struct option options[] = {
995 OPT_BOOL(0, "cached", &cached,
996 N_("search in index instead of in the work tree")),
997 OPT_NEGBIT(0, "no-index", &use_index,
998 N_("find in contents not managed by git"), 1),
999 OPT_BOOL(0, "untracked", &untracked,
1000 N_("search in both tracked and untracked files")),
1001 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
1002 N_("ignore files specified via '.gitignore'"), 1),
1003 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
1004 N_("recursively search in each submodule")),
1005 OPT_STRING(0, "parent-basename", &parent_basename,
1006 N_("basename"),
1007 N_("prepend parent project's basename to output")),
1008 OPT_GROUP(""),
1009 OPT_BOOL('v', "invert-match", &opt.invert,
1010 N_("show non-matching lines")),
1011 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
1012 N_("case insensitive matching")),
1013 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
1014 N_("match patterns only at word boundaries")),
1015 OPT_SET_INT('a', "text", &opt.binary,
1016 N_("process binary files as text"), GREP_BINARY_TEXT),
1017 OPT_SET_INT('I', NULL, &opt.binary,
1018 N_("don't match patterns in binary files"),
1019 GREP_BINARY_NOMATCH),
1020 OPT_BOOL(0, "textconv", &opt.allow_textconv,
1021 N_("process binary files with textconv filters")),
1022 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
1023 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
1024 NULL, 1 },
1025 OPT_GROUP(""),
1026 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
1027 N_("use extended POSIX regular expressions"),
1028 GREP_PATTERN_TYPE_ERE),
1029 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
1030 N_("use basic POSIX regular expressions (default)"),
1031 GREP_PATTERN_TYPE_BRE),
1032 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
1033 N_("interpret patterns as fixed strings"),
1034 GREP_PATTERN_TYPE_FIXED),
1035 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
1036 N_("use Perl-compatible regular expressions"),
1037 GREP_PATTERN_TYPE_PCRE),
1038 OPT_GROUP(""),
1039 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
1040 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
1041 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
1042 OPT_NEGBIT(0, "full-name", &opt.relative,
1043 N_("show filenames relative to top directory"), 1),
1044 OPT_BOOL('l', "files-with-matches", &opt.name_only,
1045 N_("show only filenames instead of matching lines")),
1046 OPT_BOOL(0, "name-only", &opt.name_only,
1047 N_("synonym for --files-with-matches")),
1048 OPT_BOOL('L', "files-without-match",
1049 &opt.unmatch_name_only,
1050 N_("show only the names of files without match")),
1051 OPT_BOOL('z', "null", &opt.null_following_name,
1052 N_("print NUL after filenames")),
1053 OPT_BOOL('c', "count", &opt.count,
1054 N_("show the number of matches instead of matching lines")),
1055 OPT__COLOR(&opt.color, N_("highlight matches")),
1056 OPT_BOOL(0, "break", &opt.file_break,
1057 N_("print empty line between matches from different files")),
1058 OPT_BOOL(0, "heading", &opt.heading,
1059 N_("show filename only once above matches from same file")),
1060 OPT_GROUP(""),
1061 OPT_CALLBACK('C', "context", &opt, N_("n"),
1062 N_("show <n> context lines before and after matches"),
1063 context_callback),
1064 OPT_INTEGER('B', "before-context", &opt.pre_context,
1065 N_("show <n> context lines before matches")),
1066 OPT_INTEGER('A', "after-context", &opt.post_context,
1067 N_("show <n> context lines after matches")),
1068 OPT_INTEGER(0, "threads", &num_threads,
1069 N_("use <n> worker threads")),
1070 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
1071 context_callback),
1072 OPT_BOOL('p', "show-function", &opt.funcname,
1073 N_("show a line with the function name before matches")),
1074 OPT_BOOL('W', "function-context", &opt.funcbody,
1075 N_("show the surrounding function")),
1076 OPT_GROUP(""),
1077 OPT_CALLBACK('f', NULL, &opt, N_("file"),
1078 N_("read patterns from file"), file_callback),
1079 { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
1080 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
1081 { OPTION_CALLBACK, 0, "and", &opt, NULL,
1082 N_("combine patterns specified with -e"),
1083 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
1084 OPT_BOOL(0, "or", &dummy, ""),
1085 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
1086 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
1087 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
1088 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1089 open_callback },
1090 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
1091 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1092 close_callback },
1093 OPT__QUIET(&opt.status_only,
1094 N_("indicate hit with exit status without output")),
1095 OPT_BOOL(0, "all-match", &opt.all_match,
1096 N_("show only matches from files that match all patterns")),
1097 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
1098 N_("show parse tree for grep expression"),
1099 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
1100 OPT_GROUP(""),
1101 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1102 N_("pager"), N_("show matching files in the pager"),
1103 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
1104 OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
1105 N_("allow calling of grep(1) (ignored by this build)")),
1106 OPT_END()
1109 init_grep_defaults();
1110 git_config(grep_cmd_config, NULL);
1111 grep_init(&opt, prefix);
1112 super_prefix = get_super_prefix();
1115 * If there is no -- then the paths must exist in the working
1116 * tree. If there is no explicit pattern specified with -e or
1117 * -f, we take the first unrecognized non option to be the
1118 * pattern, but then what follows it must be zero or more
1119 * valid refs up to the -- (if exists), and then existing
1120 * paths. If there is an explicit pattern, then the first
1121 * unrecognized non option is the beginning of the refs list
1122 * that continues up to the -- (if exists), and then paths.
1124 argc = parse_options(argc, argv, prefix, options, grep_usage,
1125 PARSE_OPT_KEEP_DASHDASH |
1126 PARSE_OPT_STOP_AT_NON_OPTION);
1127 grep_commit_pattern_type(pattern_type_arg, &opt);
1129 if (use_index && !startup_info->have_repository) {
1130 int fallback = 0;
1131 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1132 if (fallback)
1133 use_index = 0;
1134 else
1135 /* die the same way as if we did it at the beginning */
1136 setup_git_directory();
1140 * skip a -- separator; we know it cannot be
1141 * separating revisions from pathnames if
1142 * we haven't even had any patterns yet
1144 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1145 argv++;
1146 argc--;
1149 /* First unrecognized non-option token */
1150 if (argc > 0 && !opt.pattern_list) {
1151 append_grep_pattern(&opt, argv[0], "command line", 0,
1152 GREP_PATTERN);
1153 argv++;
1154 argc--;
1157 if (show_in_pager == default_pager)
1158 show_in_pager = git_pager(1);
1159 if (show_in_pager) {
1160 opt.color = 0;
1161 opt.name_only = 1;
1162 opt.null_following_name = 1;
1163 opt.output_priv = &path_list;
1164 opt.output = append_path;
1165 string_list_append(&path_list, show_in_pager);
1168 if (!opt.pattern_list)
1169 die(_("no pattern given."));
1170 if (!opt.fixed && opt.ignore_case)
1171 opt.regflags |= REG_ICASE;
1173 compile_grep_patterns(&opt);
1176 * We have to find "--" in a separate pass, because its presence
1177 * influences how we will parse arguments that come before it.
1179 for (i = 0; i < argc; i++) {
1180 if (!strcmp(argv[i], "--")) {
1181 seen_dashdash = 1;
1182 break;
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.
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;
1198 if (!strcmp(arg, "--")) {
1199 i++;
1200 break;
1203 if (!allow_revs) {
1204 if (seen_dashdash)
1205 die(_("--no-index or --untracked cannot be used with revs"));
1206 break;
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;
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);
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.
1227 if (!seen_dashdash) {
1228 int j;
1229 for (j = i; j < argc; j++)
1230 verify_filename(prefix, argv[j], j == i && allow_revs);
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;
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 #else
1248 if (num_threads)
1249 warning(_("no threads support, ignoring --threads"));
1250 num_threads = 0;
1251 #endif
1253 #ifndef NO_PTHREADS
1254 if (num_threads) {
1255 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1256 && (opt.pre_context || opt.post_context ||
1257 opt.file_break || opt.funcbody))
1258 skip_first_line = 1;
1259 start_threads(&opt);
1261 #endif
1263 if (recurse_submodules) {
1264 gitmodules_config();
1265 compile_submodule_options(&opt, argv + i, cached, untracked,
1266 opt_exclude, use_index,
1267 pattern_type_arg);
1270 if (show_in_pager && (cached || list.nr))
1271 die(_("--open-files-in-pager only works on the worktree"));
1273 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1274 const char *pager = path_list.items[0].string;
1275 int len = strlen(pager);
1277 if (len > 4 && is_dir_sep(pager[len - 5]))
1278 pager += len - 4;
1280 if (opt.ignore_case && !strcmp("less", pager))
1281 string_list_append(&path_list, "-I");
1283 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1284 struct strbuf buf = STRBUF_INIT;
1285 strbuf_addf(&buf, "+/%s%s",
1286 strcmp("less", pager) ? "" : "*",
1287 opt.pattern_list->pattern);
1288 string_list_append(&path_list, buf.buf);
1289 strbuf_detach(&buf, NULL);
1293 if (recurse_submodules && (!use_index || untracked))
1294 die(_("option not supported with --recurse-submodules."));
1296 if (!show_in_pager && !opt.status_only)
1297 setup_pager();
1299 if (!use_index && (untracked || cached))
1300 die(_("--cached or --untracked cannot be used with --no-index."));
1302 if (!use_index || untracked) {
1303 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1304 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1305 } else if (0 <= opt_exclude) {
1306 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1307 } else if (!list.nr) {
1308 if (!cached)
1309 setup_work_tree();
1311 hit = grep_cache(&opt, &pathspec, cached);
1312 } else {
1313 if (cached)
1314 die(_("both --cached and trees are given."));
1315 hit = grep_objects(&opt, &pathspec, &list);
1318 if (num_threads)
1319 hit |= wait_all();
1320 if (hit && show_in_pager)
1321 run_pager(&opt, prefix);
1322 clear_pathspec(&pathspec);
1323 free_grep_patterns(&opt);
1324 return !hit;