rebase -i: remove patch file after conflict resolution
[git.git] / builtin / grep.c
bloba1b68d90bdb630327f08273b4f3658db86e2eb6a
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "cache.h"
7 #include "alloc.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "repository.h"
11 #include "config.h"
12 #include "blob.h"
13 #include "tree.h"
14 #include "commit.h"
15 #include "tag.h"
16 #include "tree-walk.h"
17 #include "builtin.h"
18 #include "parse-options.h"
19 #include "string-list.h"
20 #include "run-command.h"
21 #include "userdiff.h"
22 #include "grep.h"
23 #include "quote.h"
24 #include "dir.h"
25 #include "pathspec.h"
26 #include "setup.h"
27 #include "submodule.h"
28 #include "submodule-config.h"
29 #include "object-store.h"
30 #include "packfile.h"
31 #include "write-or-die.h"
33 static const char *grep_prefix;
35 static char const * const grep_usage[] = {
36 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
37 NULL
40 static int recurse_submodules;
42 static int num_threads;
44 static pthread_t *threads;
46 /* We use one producer thread and THREADS consumer
47 * threads. The producer adds struct work_items to 'todo' and the
48 * consumers pick work items from the same array.
50 struct work_item {
51 struct grep_source source;
52 char done;
53 struct strbuf out;
56 /* In the range [todo_done, todo_start) in 'todo' we have work_items
57 * that have been or are processed by a consumer thread. We haven't
58 * written the result for these to stdout yet.
60 * The work_items in [todo_start, todo_end) are waiting to be picked
61 * up by a consumer thread.
63 * The ranges are modulo TODO_SIZE.
65 #define TODO_SIZE 128
66 static struct work_item todo[TODO_SIZE];
67 static int todo_start;
68 static int todo_end;
69 static int todo_done;
71 /* Has all work items been added? */
72 static int all_work_added;
74 static struct repository **repos_to_free;
75 static size_t repos_to_free_nr, repos_to_free_alloc;
77 /* This lock protects all the variables above. */
78 static pthread_mutex_t grep_mutex;
80 static inline void grep_lock(void)
82 pthread_mutex_lock(&grep_mutex);
85 static inline void grep_unlock(void)
87 pthread_mutex_unlock(&grep_mutex);
90 /* Signalled when a new work_item is added to todo. */
91 static pthread_cond_t cond_add;
93 /* Signalled when the result from one work_item is written to
94 * stdout.
96 static pthread_cond_t cond_write;
98 /* Signalled when we are finished with everything. */
99 static pthread_cond_t cond_result;
101 static int skip_first_line;
103 static void add_work(struct grep_opt *opt, struct grep_source *gs)
105 if (opt->binary != GREP_BINARY_TEXT)
106 grep_source_load_driver(gs, opt->repo->index);
108 grep_lock();
110 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
111 pthread_cond_wait(&cond_write, &grep_mutex);
114 todo[todo_end].source = *gs;
115 todo[todo_end].done = 0;
116 strbuf_reset(&todo[todo_end].out);
117 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
119 pthread_cond_signal(&cond_add);
120 grep_unlock();
123 static struct work_item *get_work(void)
125 struct work_item *ret;
127 grep_lock();
128 while (todo_start == todo_end && !all_work_added) {
129 pthread_cond_wait(&cond_add, &grep_mutex);
132 if (todo_start == todo_end && all_work_added) {
133 ret = NULL;
134 } else {
135 ret = &todo[todo_start];
136 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
138 grep_unlock();
139 return ret;
142 static void work_done(struct work_item *w)
144 int old_done;
146 grep_lock();
147 w->done = 1;
148 old_done = todo_done;
149 for(; todo[todo_done].done && todo_done != todo_start;
150 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
151 w = &todo[todo_done];
152 if (w->out.len) {
153 const char *p = w->out.buf;
154 size_t len = w->out.len;
156 /* Skip the leading hunk mark of the first file. */
157 if (skip_first_line) {
158 while (len) {
159 len--;
160 if (*p++ == '\n')
161 break;
163 skip_first_line = 0;
166 write_or_die(1, p, len);
168 grep_source_clear(&w->source);
171 if (old_done != todo_done)
172 pthread_cond_signal(&cond_write);
174 if (all_work_added && todo_done == todo_end)
175 pthread_cond_signal(&cond_result);
177 grep_unlock();
180 static void free_repos(void)
182 int i;
184 for (i = 0; i < repos_to_free_nr; i++) {
185 repo_clear(repos_to_free[i]);
186 free(repos_to_free[i]);
188 FREE_AND_NULL(repos_to_free);
189 repos_to_free_nr = 0;
190 repos_to_free_alloc = 0;
193 static void *run(void *arg)
195 int hit = 0;
196 struct grep_opt *opt = arg;
198 while (1) {
199 struct work_item *w = get_work();
200 if (!w)
201 break;
203 opt->output_priv = w;
204 hit |= grep_source(opt, &w->source);
205 grep_source_clear_data(&w->source);
206 work_done(w);
208 free_grep_patterns(opt);
209 free(opt);
211 return (void*) (intptr_t) hit;
214 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
216 struct work_item *w = opt->output_priv;
217 strbuf_add(&w->out, buf, size);
220 static void start_threads(struct grep_opt *opt)
222 int i;
224 pthread_mutex_init(&grep_mutex, NULL);
225 pthread_mutex_init(&grep_attr_mutex, NULL);
226 pthread_cond_init(&cond_add, NULL);
227 pthread_cond_init(&cond_write, NULL);
228 pthread_cond_init(&cond_result, NULL);
229 grep_use_locks = 1;
230 enable_obj_read_lock();
232 for (i = 0; i < ARRAY_SIZE(todo); i++) {
233 strbuf_init(&todo[i].out, 0);
236 CALLOC_ARRAY(threads, num_threads);
237 for (i = 0; i < num_threads; i++) {
238 int err;
239 struct grep_opt *o = grep_opt_dup(opt);
240 o->output = strbuf_out;
241 compile_grep_patterns(o);
242 err = pthread_create(&threads[i], NULL, run, o);
244 if (err)
245 die(_("grep: failed to create thread: %s"),
246 strerror(err));
250 static int wait_all(void)
252 int hit = 0;
253 int i;
255 if (!HAVE_THREADS)
256 BUG("Never call this function unless you have started threads");
258 grep_lock();
259 all_work_added = 1;
261 /* Wait until all work is done. */
262 while (todo_done != todo_end)
263 pthread_cond_wait(&cond_result, &grep_mutex);
265 /* Wake up all the consumer threads so they can see that there
266 * is no more work to do.
268 pthread_cond_broadcast(&cond_add);
269 grep_unlock();
271 for (i = 0; i < num_threads; i++) {
272 void *h;
273 pthread_join(threads[i], &h);
274 hit |= (int) (intptr_t) h;
277 free(threads);
279 pthread_mutex_destroy(&grep_mutex);
280 pthread_mutex_destroy(&grep_attr_mutex);
281 pthread_cond_destroy(&cond_add);
282 pthread_cond_destroy(&cond_write);
283 pthread_cond_destroy(&cond_result);
284 grep_use_locks = 0;
285 disable_obj_read_lock();
287 return hit;
290 static int grep_cmd_config(const char *var, const char *value, void *cb)
292 int st = grep_config(var, value, cb);
293 if (git_color_default_config(var, value, NULL) < 0)
294 st = -1;
296 if (!strcmp(var, "grep.threads")) {
297 num_threads = git_config_int(var, value);
298 if (num_threads < 0)
299 die(_("invalid number of threads specified (%d) for %s"),
300 num_threads, var);
301 else if (!HAVE_THREADS && num_threads > 1) {
303 * TRANSLATORS: %s is the configuration
304 * variable for tweaking threads, currently
305 * grep.threads
307 warning(_("no threads support, ignoring %s"), var);
308 num_threads = 1;
312 if (!strcmp(var, "submodule.recurse"))
313 recurse_submodules = git_config_bool(var, value);
315 return st;
318 static void grep_source_name(struct grep_opt *opt, const char *filename,
319 int tree_name_len, struct strbuf *out)
321 strbuf_reset(out);
323 if (opt->null_following_name) {
324 if (opt->relative && grep_prefix) {
325 struct strbuf rel_buf = STRBUF_INIT;
326 const char *rel_name =
327 relative_path(filename + tree_name_len,
328 grep_prefix, &rel_buf);
330 if (tree_name_len)
331 strbuf_add(out, filename, tree_name_len);
333 strbuf_addstr(out, rel_name);
334 strbuf_release(&rel_buf);
335 } else {
336 strbuf_addstr(out, filename);
338 return;
341 if (opt->relative && grep_prefix)
342 quote_path(filename + tree_name_len, grep_prefix, out, 0);
343 else
344 quote_c_style(filename + tree_name_len, out, NULL, 0);
346 if (tree_name_len)
347 strbuf_insert(out, 0, filename, tree_name_len);
350 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
351 const char *filename, int tree_name_len,
352 const char *path)
354 struct strbuf pathbuf = STRBUF_INIT;
355 struct grep_source gs;
357 grep_source_name(opt, filename, tree_name_len, &pathbuf);
358 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
359 strbuf_release(&pathbuf);
361 if (num_threads > 1) {
363 * add_work() copies gs and thus assumes ownership of
364 * its fields, so do not call grep_source_clear()
366 add_work(opt, &gs);
367 return 0;
368 } else {
369 int hit;
371 hit = grep_source(opt, &gs);
373 grep_source_clear(&gs);
374 return hit;
378 static int grep_file(struct grep_opt *opt, const char *filename)
380 struct strbuf buf = STRBUF_INIT;
381 struct grep_source gs;
383 grep_source_name(opt, filename, 0, &buf);
384 grep_source_init_file(&gs, buf.buf, filename);
385 strbuf_release(&buf);
387 if (num_threads > 1) {
389 * add_work() copies gs and thus assumes ownership of
390 * its fields, so do not call grep_source_clear()
392 add_work(opt, &gs);
393 return 0;
394 } else {
395 int hit;
397 hit = grep_source(opt, &gs);
399 grep_source_clear(&gs);
400 return hit;
404 static void append_path(struct grep_opt *opt, const void *data, size_t len)
406 struct string_list *path_list = opt->output_priv;
408 if (len == 1 && *(const char *)data == '\0')
409 return;
410 string_list_append_nodup(path_list, xstrndup(data, len));
413 static void run_pager(struct grep_opt *opt, const char *prefix)
415 struct string_list *path_list = opt->output_priv;
416 struct child_process child = CHILD_PROCESS_INIT;
417 int i, status;
419 for (i = 0; i < path_list->nr; i++)
420 strvec_push(&child.args, path_list->items[i].string);
421 child.dir = prefix;
422 child.use_shell = 1;
424 status = run_command(&child);
425 if (status)
426 exit(status);
429 static int grep_cache(struct grep_opt *opt,
430 const struct pathspec *pathspec, int cached);
431 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
432 struct tree_desc *tree, struct strbuf *base, int tn_len,
433 int check_attr);
435 static int grep_submodule(struct grep_opt *opt,
436 const struct pathspec *pathspec,
437 const struct object_id *oid,
438 const char *filename, const char *path, int cached)
440 struct repository *subrepo;
441 struct repository *superproject = opt->repo;
442 struct grep_opt subopt;
443 int hit = 0;
445 if (!is_submodule_active(superproject, path))
446 return 0;
448 subrepo = xmalloc(sizeof(*subrepo));
449 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
450 free(subrepo);
451 return 0;
453 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
454 repos_to_free[repos_to_free_nr++] = subrepo;
457 * NEEDSWORK: repo_read_gitmodules() might call
458 * add_to_alternates_memory() via config_from_gitmodules(). This
459 * operation causes a race condition with concurrent object readings
460 * performed by the worker threads. That's why we need obj_read_lock()
461 * here. It should be removed once it's no longer necessary to add the
462 * subrepo's odbs to the in-memory alternates list.
464 obj_read_lock();
467 * NEEDSWORK: when reading a submodule, the sparsity settings in the
468 * superproject are incorrectly forgotten or misused. For example:
470 * 1. "command_requires_full_index"
471 * When this setting is turned on for `grep`, only the superproject
472 * knows it. All the submodules are read with their own configs
473 * and get prepare_repo_settings()'d. Therefore, these submodules
474 * "forget" the sparse-index feature switch. As a result, the index
475 * of these submodules are expanded unexpectedly.
477 * 2. "core_apply_sparse_checkout"
478 * When running `grep` in the superproject, this setting is
479 * populated using the superproject's configs. However, once
480 * initialized, this config is globally accessible and is read by
481 * prepare_repo_settings() for the submodules. For instance, if a
482 * submodule is using a sparse-checkout, however, the superproject
483 * is not, the result is that the config from the superproject will
484 * dictate the behavior for the submodule, making it "forget" its
485 * sparse-checkout state.
487 * 3. "core_sparse_checkout_cone"
488 * ditto.
490 * Note that this list is not exhaustive.
492 repo_read_gitmodules(subrepo, 0);
495 * All code paths tested by test code no longer need submodule ODBs to
496 * be added as alternates, but add it to the list just in case.
497 * Submodule ODBs added through add_submodule_odb_by_path() will be
498 * lazily registered as alternates when needed (and except in an
499 * unexpected code interaction, it won't be needed).
501 add_submodule_odb_by_path(subrepo->objects->odb->path);
502 obj_read_unlock();
504 memcpy(&subopt, opt, sizeof(subopt));
505 subopt.repo = subrepo;
507 if (oid) {
508 enum object_type object_type;
509 struct tree_desc tree;
510 void *data;
511 unsigned long size;
512 struct strbuf base = STRBUF_INIT;
514 obj_read_lock();
515 object_type = oid_object_info(subrepo, oid, NULL);
516 obj_read_unlock();
517 data = read_object_with_reference(subrepo,
518 oid, OBJ_TREE,
519 &size, NULL);
520 if (!data)
521 die(_("unable to read tree (%s)"), oid_to_hex(oid));
523 strbuf_addstr(&base, filename);
524 strbuf_addch(&base, '/');
526 init_tree_desc(&tree, data, size);
527 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
528 object_type == OBJ_COMMIT);
529 strbuf_release(&base);
530 free(data);
531 } else {
532 hit = grep_cache(&subopt, pathspec, cached);
535 return hit;
538 static int grep_cache(struct grep_opt *opt,
539 const struct pathspec *pathspec, int cached)
541 struct repository *repo = opt->repo;
542 int hit = 0;
543 int nr;
544 struct strbuf name = STRBUF_INIT;
545 int name_base_len = 0;
546 if (repo->submodule_prefix) {
547 name_base_len = strlen(repo->submodule_prefix);
548 strbuf_addstr(&name, repo->submodule_prefix);
551 if (repo_read_index(repo) < 0)
552 die(_("index file corrupt"));
554 for (nr = 0; nr < repo->index->cache_nr; nr++) {
555 const struct cache_entry *ce = repo->index->cache[nr];
557 if (!cached && ce_skip_worktree(ce))
558 continue;
560 strbuf_setlen(&name, name_base_len);
561 strbuf_addstr(&name, ce->name);
562 if (S_ISSPARSEDIR(ce->ce_mode)) {
563 enum object_type type;
564 struct tree_desc tree;
565 void *data;
566 unsigned long size;
568 data = repo_read_object_file(the_repository, &ce->oid,
569 &type, &size);
570 init_tree_desc(&tree, data, size);
572 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
573 strbuf_setlen(&name, name_base_len);
574 strbuf_addstr(&name, ce->name);
575 free(data);
576 } else if (S_ISREG(ce->ce_mode) &&
577 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
578 S_ISDIR(ce->ce_mode) ||
579 S_ISGITLINK(ce->ce_mode))) {
581 * If CE_VALID is on, we assume worktree file and its
582 * cache entry are identical, even if worktree file has
583 * been modified, so use cache version instead
585 if (cached || (ce->ce_flags & CE_VALID)) {
586 if (ce_stage(ce) || ce_intent_to_add(ce))
587 continue;
588 hit |= grep_oid(opt, &ce->oid, name.buf,
589 0, name.buf);
590 } else {
591 hit |= grep_file(opt, name.buf);
593 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
594 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
595 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
596 ce->name, cached);
597 } else {
598 continue;
601 if (ce_stage(ce)) {
602 do {
603 nr++;
604 } while (nr < repo->index->cache_nr &&
605 !strcmp(ce->name, repo->index->cache[nr]->name));
606 nr--; /* compensate for loop control */
608 if (hit && opt->status_only)
609 break;
612 strbuf_release(&name);
613 return hit;
616 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
617 struct tree_desc *tree, struct strbuf *base, int tn_len,
618 int check_attr)
620 struct repository *repo = opt->repo;
621 int hit = 0;
622 enum interesting match = entry_not_interesting;
623 struct name_entry entry;
624 int old_baselen = base->len;
625 struct strbuf name = STRBUF_INIT;
626 int name_base_len = 0;
627 if (repo->submodule_prefix) {
628 strbuf_addstr(&name, repo->submodule_prefix);
629 name_base_len = name.len;
632 while (tree_entry(tree, &entry)) {
633 int te_len = tree_entry_len(&entry);
635 if (match != all_entries_interesting) {
636 strbuf_addstr(&name, base->buf + tn_len);
637 match = tree_entry_interesting(repo->index,
638 &entry, &name,
639 0, pathspec);
640 strbuf_setlen(&name, name_base_len);
642 if (match == all_entries_not_interesting)
643 break;
644 if (match == entry_not_interesting)
645 continue;
648 strbuf_add(base, entry.path, te_len);
650 if (S_ISREG(entry.mode)) {
651 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
652 check_attr ? base->buf + tn_len : NULL);
653 } else if (S_ISDIR(entry.mode)) {
654 enum object_type type;
655 struct tree_desc sub;
656 void *data;
657 unsigned long size;
659 data = repo_read_object_file(the_repository,
660 &entry.oid, &type, &size);
661 if (!data)
662 die(_("unable to read tree (%s)"),
663 oid_to_hex(&entry.oid));
665 strbuf_addch(base, '/');
666 init_tree_desc(&sub, data, size);
667 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
668 check_attr);
669 free(data);
670 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
671 hit |= grep_submodule(opt, pathspec, &entry.oid,
672 base->buf, base->buf + tn_len,
673 1); /* ignored */
676 strbuf_setlen(base, old_baselen);
678 if (hit && opt->status_only)
679 break;
682 strbuf_release(&name);
683 return hit;
686 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
687 struct object *obj, const char *name, const char *path)
689 if (obj->type == OBJ_BLOB)
690 return grep_oid(opt, &obj->oid, name, 0, path);
691 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
692 struct tree_desc tree;
693 void *data;
694 unsigned long size;
695 struct strbuf base;
696 int hit, len;
698 data = read_object_with_reference(opt->repo,
699 &obj->oid, OBJ_TREE,
700 &size, NULL);
701 if (!data)
702 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
704 len = name ? strlen(name) : 0;
705 strbuf_init(&base, PATH_MAX + len + 1);
706 if (len) {
707 strbuf_add(&base, name, len);
708 strbuf_addch(&base, ':');
710 init_tree_desc(&tree, data, size);
711 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
712 obj->type == OBJ_COMMIT);
713 strbuf_release(&base);
714 free(data);
715 return hit;
717 die(_("unable to grep from object of type %s"), type_name(obj->type));
720 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
721 const struct object_array *list)
723 unsigned int i;
724 int hit = 0;
725 const unsigned int nr = list->nr;
727 for (i = 0; i < nr; i++) {
728 struct object *real_obj;
730 obj_read_lock();
731 real_obj = deref_tag(opt->repo, list->objects[i].item,
732 NULL, 0);
733 obj_read_unlock();
735 if (!real_obj) {
736 char hex[GIT_MAX_HEXSZ + 1];
737 const char *name = list->objects[i].name;
739 if (!name) {
740 oid_to_hex_r(hex, &list->objects[i].item->oid);
741 name = hex;
743 die(_("invalid object '%s' given."), name);
746 /* load the gitmodules file for this rev */
747 if (recurse_submodules) {
748 submodule_free(opt->repo);
749 obj_read_lock();
750 gitmodules_config_oid(&real_obj->oid);
751 obj_read_unlock();
753 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
754 list->objects[i].path)) {
755 hit = 1;
756 if (opt->status_only)
757 break;
760 return hit;
763 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
764 int exc_std, int use_index)
766 struct dir_struct dir = DIR_INIT;
767 int i, hit = 0;
769 if (!use_index)
770 dir.flags |= DIR_NO_GITLINKS;
771 if (exc_std)
772 setup_standard_excludes(&dir);
774 fill_directory(&dir, opt->repo->index, pathspec);
775 for (i = 0; i < dir.nr; i++) {
776 hit |= grep_file(opt, dir.entries[i]->name);
777 if (hit && opt->status_only)
778 break;
780 dir_clear(&dir);
781 return hit;
784 static int context_callback(const struct option *opt, const char *arg,
785 int unset)
787 struct grep_opt *grep_opt = opt->value;
788 int value;
789 const char *endp;
791 if (unset) {
792 grep_opt->pre_context = grep_opt->post_context = 0;
793 return 0;
795 value = strtol(arg, (char **)&endp, 10);
796 if (*endp) {
797 return error(_("switch `%c' expects a numerical value"),
798 opt->short_name);
800 grep_opt->pre_context = grep_opt->post_context = value;
801 return 0;
804 static int file_callback(const struct option *opt, const char *arg, int unset)
806 struct grep_opt *grep_opt = opt->value;
807 int from_stdin;
808 FILE *patterns;
809 int lno = 0;
810 struct strbuf sb = STRBUF_INIT;
812 BUG_ON_OPT_NEG(unset);
814 from_stdin = !strcmp(arg, "-");
815 patterns = from_stdin ? stdin : fopen(arg, "r");
816 if (!patterns)
817 die_errno(_("cannot open '%s'"), arg);
818 while (strbuf_getline(&sb, patterns) == 0) {
819 /* ignore empty line like grep does */
820 if (sb.len == 0)
821 continue;
823 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
824 GREP_PATTERN);
826 if (!from_stdin)
827 fclose(patterns);
828 strbuf_release(&sb);
829 return 0;
832 static int not_callback(const struct option *opt, const char *arg, int unset)
834 struct grep_opt *grep_opt = opt->value;
835 BUG_ON_OPT_NEG(unset);
836 BUG_ON_OPT_ARG(arg);
837 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
838 return 0;
841 static int and_callback(const struct option *opt, const char *arg, int unset)
843 struct grep_opt *grep_opt = opt->value;
844 BUG_ON_OPT_NEG(unset);
845 BUG_ON_OPT_ARG(arg);
846 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
847 return 0;
850 static int open_callback(const struct option *opt, const char *arg, int unset)
852 struct grep_opt *grep_opt = opt->value;
853 BUG_ON_OPT_NEG(unset);
854 BUG_ON_OPT_ARG(arg);
855 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
856 return 0;
859 static int close_callback(const struct option *opt, const char *arg, int unset)
861 struct grep_opt *grep_opt = opt->value;
862 BUG_ON_OPT_NEG(unset);
863 BUG_ON_OPT_ARG(arg);
864 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
865 return 0;
868 static int pattern_callback(const struct option *opt, const char *arg,
869 int unset)
871 struct grep_opt *grep_opt = opt->value;
872 BUG_ON_OPT_NEG(unset);
873 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
874 return 0;
877 int cmd_grep(int argc, const char **argv, const char *prefix)
879 int hit = 0;
880 int cached = 0, untracked = 0, opt_exclude = -1;
881 int seen_dashdash = 0;
882 int external_grep_allowed__ignored;
883 const char *show_in_pager = NULL, *default_pager = "dummy";
884 struct grep_opt opt;
885 struct object_array list = OBJECT_ARRAY_INIT;
886 struct pathspec pathspec;
887 struct string_list path_list = STRING_LIST_INIT_DUP;
888 int i;
889 int dummy;
890 int use_index = 1;
891 int allow_revs;
893 struct option options[] = {
894 OPT_BOOL(0, "cached", &cached,
895 N_("search in index instead of in the work tree")),
896 OPT_NEGBIT(0, "no-index", &use_index,
897 N_("find in contents not managed by git"), 1),
898 OPT_BOOL(0, "untracked", &untracked,
899 N_("search in both tracked and untracked files")),
900 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
901 N_("ignore files specified via '.gitignore'"), 1),
902 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
903 N_("recursively search in each submodule")),
904 OPT_GROUP(""),
905 OPT_BOOL('v', "invert-match", &opt.invert,
906 N_("show non-matching lines")),
907 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
908 N_("case insensitive matching")),
909 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
910 N_("match patterns only at word boundaries")),
911 OPT_SET_INT('a', "text", &opt.binary,
912 N_("process binary files as text"), GREP_BINARY_TEXT),
913 OPT_SET_INT('I', NULL, &opt.binary,
914 N_("don't match patterns in binary files"),
915 GREP_BINARY_NOMATCH),
916 OPT_BOOL(0, "textconv", &opt.allow_textconv,
917 N_("process binary files with textconv filters")),
918 OPT_SET_INT('r', "recursive", &opt.max_depth,
919 N_("search in subdirectories (default)"), -1),
920 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
921 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
922 NULL, 1 },
923 OPT_GROUP(""),
924 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
925 N_("use extended POSIX regular expressions"),
926 GREP_PATTERN_TYPE_ERE),
927 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
928 N_("use basic POSIX regular expressions (default)"),
929 GREP_PATTERN_TYPE_BRE),
930 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
931 N_("interpret patterns as fixed strings"),
932 GREP_PATTERN_TYPE_FIXED),
933 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
934 N_("use Perl-compatible regular expressions"),
935 GREP_PATTERN_TYPE_PCRE),
936 OPT_GROUP(""),
937 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
938 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
939 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
940 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
941 OPT_NEGBIT(0, "full-name", &opt.relative,
942 N_("show filenames relative to top directory"), 1),
943 OPT_BOOL('l', "files-with-matches", &opt.name_only,
944 N_("show only filenames instead of matching lines")),
945 OPT_BOOL(0, "name-only", &opt.name_only,
946 N_("synonym for --files-with-matches")),
947 OPT_BOOL('L', "files-without-match",
948 &opt.unmatch_name_only,
949 N_("show only the names of files without match")),
950 OPT_BOOL_F('z', "null", &opt.null_following_name,
951 N_("print NUL after filenames"),
952 PARSE_OPT_NOCOMPLETE),
953 OPT_BOOL('o', "only-matching", &opt.only_matching,
954 N_("show only matching parts of a line")),
955 OPT_BOOL('c', "count", &opt.count,
956 N_("show the number of matches instead of matching lines")),
957 OPT__COLOR(&opt.color, N_("highlight matches")),
958 OPT_BOOL(0, "break", &opt.file_break,
959 N_("print empty line between matches from different files")),
960 OPT_BOOL(0, "heading", &opt.heading,
961 N_("show filename only once above matches from same file")),
962 OPT_GROUP(""),
963 OPT_CALLBACK('C', "context", &opt, N_("n"),
964 N_("show <n> context lines before and after matches"),
965 context_callback),
966 OPT_INTEGER('B', "before-context", &opt.pre_context,
967 N_("show <n> context lines before matches")),
968 OPT_INTEGER('A', "after-context", &opt.post_context,
969 N_("show <n> context lines after matches")),
970 OPT_INTEGER(0, "threads", &num_threads,
971 N_("use <n> worker threads")),
972 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
973 context_callback),
974 OPT_BOOL('p', "show-function", &opt.funcname,
975 N_("show a line with the function name before matches")),
976 OPT_BOOL('W', "function-context", &opt.funcbody,
977 N_("show the surrounding function")),
978 OPT_GROUP(""),
979 OPT_CALLBACK('f', NULL, &opt, N_("file"),
980 N_("read patterns from file"), file_callback),
981 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
982 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
983 OPT_CALLBACK_F(0, "and", &opt, NULL,
984 N_("combine patterns specified with -e"),
985 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
986 OPT_BOOL(0, "or", &dummy, ""),
987 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
988 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
989 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
990 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
991 open_callback),
992 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
993 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
994 close_callback),
995 OPT__QUIET(&opt.status_only,
996 N_("indicate hit with exit status without output")),
997 OPT_BOOL(0, "all-match", &opt.all_match,
998 N_("show only matches from files that match all patterns")),
999 OPT_GROUP(""),
1000 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1001 N_("pager"), N_("show matching files in the pager"),
1002 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
1003 NULL, (intptr_t)default_pager },
1004 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
1005 N_("allow calling of grep(1) (ignored by this build)"),
1006 PARSE_OPT_NOCOMPLETE),
1007 OPT_INTEGER('m', "max-count", &opt.max_count,
1008 N_("maximum number of results per file")),
1009 OPT_END()
1011 grep_prefix = prefix;
1013 grep_init(&opt, the_repository);
1014 git_config(grep_cmd_config, &opt);
1017 * If there is no -- then the paths must exist in the working
1018 * tree. If there is no explicit pattern specified with -e or
1019 * -f, we take the first unrecognized non option to be the
1020 * pattern, but then what follows it must be zero or more
1021 * valid refs up to the -- (if exists), and then existing
1022 * paths. If there is an explicit pattern, then the first
1023 * unrecognized non option is the beginning of the refs list
1024 * that continues up to the -- (if exists), and then paths.
1026 argc = parse_options(argc, argv, prefix, options, grep_usage,
1027 PARSE_OPT_KEEP_DASHDASH |
1028 PARSE_OPT_STOP_AT_NON_OPTION);
1030 if (the_repository->gitdir) {
1031 prepare_repo_settings(the_repository);
1032 the_repository->settings.command_requires_full_index = 0;
1035 if (use_index && !startup_info->have_repository) {
1036 int fallback = 0;
1037 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1038 if (fallback)
1039 use_index = 0;
1040 else
1041 /* die the same way as if we did it at the beginning */
1042 setup_git_directory();
1044 /* Ignore --recurse-submodules if --no-index is given or implied */
1045 if (!use_index)
1046 recurse_submodules = 0;
1049 * skip a -- separator; we know it cannot be
1050 * separating revisions from pathnames if
1051 * we haven't even had any patterns yet
1053 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1054 argv++;
1055 argc--;
1058 /* First unrecognized non-option token */
1059 if (argc > 0 && !opt.pattern_list) {
1060 append_grep_pattern(&opt, argv[0], "command line", 0,
1061 GREP_PATTERN);
1062 argv++;
1063 argc--;
1066 if (show_in_pager == default_pager)
1067 show_in_pager = git_pager(1);
1068 if (show_in_pager) {
1069 opt.color = 0;
1070 opt.name_only = 1;
1071 opt.null_following_name = 1;
1072 opt.output_priv = &path_list;
1073 opt.output = append_path;
1074 string_list_append(&path_list, show_in_pager);
1077 if (!opt.pattern_list)
1078 die(_("no pattern given"));
1080 /* --only-matching has no effect with --invert. */
1081 if (opt.invert)
1082 opt.only_matching = 0;
1085 * We have to find "--" in a separate pass, because its presence
1086 * influences how we will parse arguments that come before it.
1088 for (i = 0; i < argc; i++) {
1089 if (!strcmp(argv[i], "--")) {
1090 seen_dashdash = 1;
1091 break;
1096 * Resolve any rev arguments. If we have a dashdash, then everything up
1097 * to it must resolve as a rev. If not, then we stop at the first
1098 * non-rev and assume everything else is a path.
1100 allow_revs = use_index && !untracked;
1101 for (i = 0; i < argc; i++) {
1102 const char *arg = argv[i];
1103 struct object_id oid;
1104 struct object_context oc;
1105 struct object *object;
1107 if (!strcmp(arg, "--")) {
1108 i++;
1109 break;
1112 if (!allow_revs) {
1113 if (seen_dashdash)
1114 die(_("--no-index or --untracked cannot be used with revs"));
1115 break;
1118 if (get_oid_with_context(the_repository, arg,
1119 GET_OID_RECORD_PATH,
1120 &oid, &oc)) {
1121 if (seen_dashdash)
1122 die(_("unable to resolve revision: %s"), arg);
1123 break;
1126 object = parse_object_or_die(&oid, arg);
1127 if (!seen_dashdash)
1128 verify_non_filename(prefix, arg);
1129 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1130 free(oc.path);
1134 * Anything left over is presumed to be a path. But in the non-dashdash
1135 * "do what I mean" case, we verify and complain when that isn't true.
1137 if (!seen_dashdash) {
1138 int j;
1139 for (j = i; j < argc; j++)
1140 verify_filename(prefix, argv[j], j == i && allow_revs);
1143 parse_pathspec(&pathspec, 0,
1144 PATHSPEC_PREFER_CWD |
1145 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1146 prefix, argv + i);
1147 pathspec.max_depth = opt.max_depth;
1148 pathspec.recursive = 1;
1149 pathspec.recurse_submodules = !!recurse_submodules;
1151 if (recurse_submodules && untracked)
1152 die(_("--untracked not supported with --recurse-submodules"));
1155 * Optimize out the case where the amount of matches is limited to zero.
1156 * We do this to keep results consistent with GNU grep(1).
1158 if (opt.max_count == 0)
1159 return 1;
1161 if (show_in_pager) {
1162 if (num_threads > 1)
1163 warning(_("invalid option combination, ignoring --threads"));
1164 num_threads = 1;
1165 } else if (!HAVE_THREADS && num_threads > 1) {
1166 warning(_("no threads support, ignoring --threads"));
1167 num_threads = 1;
1168 } else if (num_threads < 0)
1169 die(_("invalid number of threads specified (%d)"), num_threads);
1170 else if (num_threads == 0)
1171 num_threads = HAVE_THREADS ? online_cpus() : 1;
1173 if (num_threads > 1) {
1174 if (!HAVE_THREADS)
1175 BUG("Somebody got num_threads calculation wrong!");
1176 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1177 && (opt.pre_context || opt.post_context ||
1178 opt.file_break || opt.funcbody))
1179 skip_first_line = 1;
1182 * Pre-read gitmodules (if not read already) and force eager
1183 * initialization of packed_git to prevent racy lazy
1184 * reading/initialization once worker threads are started.
1186 if (recurse_submodules)
1187 repo_read_gitmodules(the_repository, 1);
1188 if (startup_info->have_repository)
1189 (void)get_packed_git(the_repository);
1191 start_threads(&opt);
1192 } else {
1194 * The compiled patterns on the main path are only
1195 * used when not using threading. Otherwise
1196 * start_threads() above calls compile_grep_patterns()
1197 * for each thread.
1199 compile_grep_patterns(&opt);
1202 if (show_in_pager && (cached || list.nr))
1203 die(_("--open-files-in-pager only works on the worktree"));
1205 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1206 const char *pager = path_list.items[0].string;
1207 int len = strlen(pager);
1209 if (len > 4 && is_dir_sep(pager[len - 5]))
1210 pager += len - 4;
1212 if (opt.ignore_case && !strcmp("less", pager))
1213 string_list_append(&path_list, "-I");
1215 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1216 struct strbuf buf = STRBUF_INIT;
1217 strbuf_addf(&buf, "+/%s%s",
1218 strcmp("less", pager) ? "" : "*",
1219 opt.pattern_list->pattern);
1220 string_list_append_nodup(&path_list,
1221 strbuf_detach(&buf, NULL));
1225 if (!show_in_pager && !opt.status_only)
1226 setup_pager();
1228 die_for_incompatible_opt3(!use_index, "--no-index",
1229 untracked, "--untracked",
1230 cached, "--cached");
1232 if (!use_index || untracked) {
1233 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
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();
1241 hit = grep_cache(&opt, &pathspec, cached);
1242 } else {
1243 if (cached)
1244 die(_("both --cached and trees are given"));
1246 hit = grep_objects(&opt, &pathspec, &list);
1249 if (num_threads > 1)
1250 hit |= wait_all();
1251 if (hit && show_in_pager)
1252 run_pager(&opt, prefix);
1253 clear_pathspec(&pathspec);
1254 string_list_clear(&path_list, 0);
1255 free_grep_patterns(&opt);
1256 object_array_clear(&list);
1257 free_repos();
1258 return !hit;