grep: reject --no-or
[git.git] / builtin / grep.c
blob3486cb924496eae45b8947eaf0e19d09b12a9148
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "cache.h"
7 #include "repository.h"
8 #include "config.h"
9 #include "blob.h"
10 #include "tree.h"
11 #include "commit.h"
12 #include "tag.h"
13 #include "tree-walk.h"
14 #include "builtin.h"
15 #include "parse-options.h"
16 #include "string-list.h"
17 #include "run-command.h"
18 #include "userdiff.h"
19 #include "grep.h"
20 #include "quote.h"
21 #include "dir.h"
22 #include "pathspec.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
25 #include "object-store.h"
26 #include "packfile.h"
28 static const char *grep_prefix;
30 static char const * const grep_usage[] = {
31 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
32 NULL
35 static int recurse_submodules;
37 static int num_threads;
39 static pthread_t *threads;
41 /* We use one producer thread and THREADS consumer
42 * threads. The producer adds struct work_items to 'todo' and the
43 * consumers pick work items from the same array.
45 struct work_item {
46 struct grep_source source;
47 char done;
48 struct strbuf out;
51 /* In the range [todo_done, todo_start) in 'todo' we have work_items
52 * that have been or are processed by a consumer thread. We haven't
53 * written the result for these to stdout yet.
55 * The work_items in [todo_start, todo_end) are waiting to be picked
56 * up by a consumer thread.
58 * The ranges are modulo TODO_SIZE.
60 #define TODO_SIZE 128
61 static struct work_item todo[TODO_SIZE];
62 static int todo_start;
63 static int todo_end;
64 static int todo_done;
66 /* Has all work items been added? */
67 static int all_work_added;
69 static struct repository **repos_to_free;
70 static size_t repos_to_free_nr, repos_to_free_alloc;
72 /* This lock protects all the variables above. */
73 static pthread_mutex_t grep_mutex;
75 static inline void grep_lock(void)
77 pthread_mutex_lock(&grep_mutex);
80 static inline void grep_unlock(void)
82 pthread_mutex_unlock(&grep_mutex);
85 /* Signalled when a new work_item is added to todo. */
86 static pthread_cond_t cond_add;
88 /* Signalled when the result from one work_item is written to
89 * stdout.
91 static pthread_cond_t cond_write;
93 /* Signalled when we are finished with everything. */
94 static pthread_cond_t cond_result;
96 static int skip_first_line;
98 static void add_work(struct grep_opt *opt, struct grep_source *gs)
100 if (opt->binary != GREP_BINARY_TEXT)
101 grep_source_load_driver(gs, opt->repo->index);
103 grep_lock();
105 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
106 pthread_cond_wait(&cond_write, &grep_mutex);
109 todo[todo_end].source = *gs;
110 todo[todo_end].done = 0;
111 strbuf_reset(&todo[todo_end].out);
112 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
114 pthread_cond_signal(&cond_add);
115 grep_unlock();
118 static struct work_item *get_work(void)
120 struct work_item *ret;
122 grep_lock();
123 while (todo_start == todo_end && !all_work_added) {
124 pthread_cond_wait(&cond_add, &grep_mutex);
127 if (todo_start == todo_end && all_work_added) {
128 ret = NULL;
129 } else {
130 ret = &todo[todo_start];
131 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
133 grep_unlock();
134 return ret;
137 static void work_done(struct work_item *w)
139 int old_done;
141 grep_lock();
142 w->done = 1;
143 old_done = todo_done;
144 for(; todo[todo_done].done && todo_done != todo_start;
145 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
146 w = &todo[todo_done];
147 if (w->out.len) {
148 const char *p = w->out.buf;
149 size_t len = w->out.len;
151 /* Skip the leading hunk mark of the first file. */
152 if (skip_first_line) {
153 while (len) {
154 len--;
155 if (*p++ == '\n')
156 break;
158 skip_first_line = 0;
161 write_or_die(1, p, len);
163 grep_source_clear(&w->source);
166 if (old_done != todo_done)
167 pthread_cond_signal(&cond_write);
169 if (all_work_added && todo_done == todo_end)
170 pthread_cond_signal(&cond_result);
172 grep_unlock();
175 static void free_repos(void)
177 int i;
179 for (i = 0; i < repos_to_free_nr; i++) {
180 repo_clear(repos_to_free[i]);
181 free(repos_to_free[i]);
183 FREE_AND_NULL(repos_to_free);
184 repos_to_free_nr = 0;
185 repos_to_free_alloc = 0;
188 static void *run(void *arg)
190 int hit = 0;
191 struct grep_opt *opt = arg;
193 while (1) {
194 struct work_item *w = get_work();
195 if (!w)
196 break;
198 opt->output_priv = w;
199 hit |= grep_source(opt, &w->source);
200 grep_source_clear_data(&w->source);
201 work_done(w);
203 free_grep_patterns(opt);
204 free(opt);
206 return (void*) (intptr_t) hit;
209 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
211 struct work_item *w = opt->output_priv;
212 strbuf_add(&w->out, buf, size);
215 static void start_threads(struct grep_opt *opt)
217 int i;
219 pthread_mutex_init(&grep_mutex, NULL);
220 pthread_mutex_init(&grep_attr_mutex, NULL);
221 pthread_cond_init(&cond_add, NULL);
222 pthread_cond_init(&cond_write, NULL);
223 pthread_cond_init(&cond_result, NULL);
224 grep_use_locks = 1;
225 enable_obj_read_lock();
227 for (i = 0; i < ARRAY_SIZE(todo); i++) {
228 strbuf_init(&todo[i].out, 0);
231 CALLOC_ARRAY(threads, num_threads);
232 for (i = 0; i < num_threads; i++) {
233 int err;
234 struct grep_opt *o = grep_opt_dup(opt);
235 o->output = strbuf_out;
236 compile_grep_patterns(o);
237 err = pthread_create(&threads[i], NULL, run, o);
239 if (err)
240 die(_("grep: failed to create thread: %s"),
241 strerror(err));
245 static int wait_all(void)
247 int hit = 0;
248 int i;
250 if (!HAVE_THREADS)
251 BUG("Never call this function unless you have started threads");
253 grep_lock();
254 all_work_added = 1;
256 /* Wait until all work is done. */
257 while (todo_done != todo_end)
258 pthread_cond_wait(&cond_result, &grep_mutex);
260 /* Wake up all the consumer threads so they can see that there
261 * is no more work to do.
263 pthread_cond_broadcast(&cond_add);
264 grep_unlock();
266 for (i = 0; i < num_threads; i++) {
267 void *h;
268 pthread_join(threads[i], &h);
269 hit |= (int) (intptr_t) h;
272 free(threads);
274 pthread_mutex_destroy(&grep_mutex);
275 pthread_mutex_destroy(&grep_attr_mutex);
276 pthread_cond_destroy(&cond_add);
277 pthread_cond_destroy(&cond_write);
278 pthread_cond_destroy(&cond_result);
279 grep_use_locks = 0;
280 disable_obj_read_lock();
282 return hit;
285 static int grep_cmd_config(const char *var, const char *value, void *cb)
287 int st = grep_config(var, value, cb);
288 if (git_color_default_config(var, value, NULL) < 0)
289 st = -1;
291 if (!strcmp(var, "grep.threads")) {
292 num_threads = git_config_int(var, value);
293 if (num_threads < 0)
294 die(_("invalid number of threads specified (%d) for %s"),
295 num_threads, var);
296 else if (!HAVE_THREADS && num_threads > 1) {
298 * TRANSLATORS: %s is the configuration
299 * variable for tweaking threads, currently
300 * grep.threads
302 warning(_("no threads support, ignoring %s"), var);
303 num_threads = 1;
307 if (!strcmp(var, "submodule.recurse"))
308 recurse_submodules = git_config_bool(var, value);
310 return st;
313 static void grep_source_name(struct grep_opt *opt, const char *filename,
314 int tree_name_len, struct strbuf *out)
316 strbuf_reset(out);
318 if (opt->null_following_name) {
319 if (opt->relative && grep_prefix) {
320 struct strbuf rel_buf = STRBUF_INIT;
321 const char *rel_name =
322 relative_path(filename + tree_name_len,
323 grep_prefix, &rel_buf);
325 if (tree_name_len)
326 strbuf_add(out, filename, tree_name_len);
328 strbuf_addstr(out, rel_name);
329 strbuf_release(&rel_buf);
330 } else {
331 strbuf_addstr(out, filename);
333 return;
336 if (opt->relative && grep_prefix)
337 quote_path(filename + tree_name_len, grep_prefix, out, 0);
338 else
339 quote_c_style(filename + tree_name_len, out, NULL, 0);
341 if (tree_name_len)
342 strbuf_insert(out, 0, filename, tree_name_len);
345 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
346 const char *filename, int tree_name_len,
347 const char *path)
349 struct strbuf pathbuf = STRBUF_INIT;
350 struct grep_source gs;
352 grep_source_name(opt, filename, tree_name_len, &pathbuf);
353 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
354 strbuf_release(&pathbuf);
356 if (num_threads > 1) {
358 * add_work() copies gs and thus assumes ownership of
359 * its fields, so do not call grep_source_clear()
361 add_work(opt, &gs);
362 return 0;
363 } else {
364 int hit;
366 hit = grep_source(opt, &gs);
368 grep_source_clear(&gs);
369 return hit;
373 static int grep_file(struct grep_opt *opt, const char *filename)
375 struct strbuf buf = STRBUF_INIT;
376 struct grep_source gs;
378 grep_source_name(opt, filename, 0, &buf);
379 grep_source_init_file(&gs, buf.buf, filename);
380 strbuf_release(&buf);
382 if (num_threads > 1) {
384 * add_work() copies gs and thus assumes ownership of
385 * its fields, so do not call grep_source_clear()
387 add_work(opt, &gs);
388 return 0;
389 } else {
390 int hit;
392 hit = grep_source(opt, &gs);
394 grep_source_clear(&gs);
395 return hit;
399 static void append_path(struct grep_opt *opt, const void *data, size_t len)
401 struct string_list *path_list = opt->output_priv;
403 if (len == 1 && *(const char *)data == '\0')
404 return;
405 string_list_append_nodup(path_list, xstrndup(data, len));
408 static void run_pager(struct grep_opt *opt, const char *prefix)
410 struct string_list *path_list = opt->output_priv;
411 struct child_process child = CHILD_PROCESS_INIT;
412 int i, status;
414 for (i = 0; i < path_list->nr; i++)
415 strvec_push(&child.args, path_list->items[i].string);
416 child.dir = prefix;
417 child.use_shell = 1;
419 status = run_command(&child);
420 if (status)
421 exit(status);
424 static int grep_cache(struct grep_opt *opt,
425 const struct pathspec *pathspec, int cached);
426 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
427 struct tree_desc *tree, struct strbuf *base, int tn_len,
428 int check_attr);
430 static int grep_submodule(struct grep_opt *opt,
431 const struct pathspec *pathspec,
432 const struct object_id *oid,
433 const char *filename, const char *path, int cached)
435 struct repository *subrepo;
436 struct repository *superproject = opt->repo;
437 struct grep_opt subopt;
438 int hit = 0;
440 if (!is_submodule_active(superproject, path))
441 return 0;
443 subrepo = xmalloc(sizeof(*subrepo));
444 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
445 free(subrepo);
446 return 0;
448 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
449 repos_to_free[repos_to_free_nr++] = subrepo;
452 * NEEDSWORK: repo_read_gitmodules() might call
453 * add_to_alternates_memory() via config_from_gitmodules(). This
454 * operation causes a race condition with concurrent object readings
455 * performed by the worker threads. That's why we need obj_read_lock()
456 * here. It should be removed once it's no longer necessary to add the
457 * subrepo's odbs to the in-memory alternates list.
459 obj_read_lock();
462 * NEEDSWORK: when reading a submodule, the sparsity settings in the
463 * superproject are incorrectly forgotten or misused. For example:
465 * 1. "command_requires_full_index"
466 * When this setting is turned on for `grep`, only the superproject
467 * knows it. All the submodules are read with their own configs
468 * and get prepare_repo_settings()'d. Therefore, these submodules
469 * "forget" the sparse-index feature switch. As a result, the index
470 * of these submodules are expanded unexpectedly.
472 * 2. "core_apply_sparse_checkout"
473 * When running `grep` in the superproject, this setting is
474 * populated using the superproject's configs. However, once
475 * initialized, this config is globally accessible and is read by
476 * prepare_repo_settings() for the submodules. For instance, if a
477 * submodule is using a sparse-checkout, however, the superproject
478 * is not, the result is that the config from the superproject will
479 * dictate the behavior for the submodule, making it "forget" its
480 * sparse-checkout state.
482 * 3. "core_sparse_checkout_cone"
483 * ditto.
485 * Note that this list is not exhaustive.
487 repo_read_gitmodules(subrepo, 0);
490 * All code paths tested by test code no longer need submodule ODBs to
491 * be added as alternates, but add it to the list just in case.
492 * Submodule ODBs added through add_submodule_odb_by_path() will be
493 * lazily registered as alternates when needed (and except in an
494 * unexpected code interaction, it won't be needed).
496 add_submodule_odb_by_path(subrepo->objects->odb->path);
497 obj_read_unlock();
499 memcpy(&subopt, opt, sizeof(subopt));
500 subopt.repo = subrepo;
502 if (oid) {
503 enum object_type object_type;
504 struct tree_desc tree;
505 void *data;
506 unsigned long size;
507 struct strbuf base = STRBUF_INIT;
509 obj_read_lock();
510 object_type = oid_object_info(subrepo, oid, NULL);
511 obj_read_unlock();
512 data = read_object_with_reference(subrepo,
513 oid, OBJ_TREE,
514 &size, NULL);
515 if (!data)
516 die(_("unable to read tree (%s)"), oid_to_hex(oid));
518 strbuf_addstr(&base, filename);
519 strbuf_addch(&base, '/');
521 init_tree_desc(&tree, data, size);
522 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
523 object_type == OBJ_COMMIT);
524 strbuf_release(&base);
525 free(data);
526 } else {
527 hit = grep_cache(&subopt, pathspec, cached);
530 return hit;
533 static int grep_cache(struct grep_opt *opt,
534 const struct pathspec *pathspec, int cached)
536 struct repository *repo = opt->repo;
537 int hit = 0;
538 int nr;
539 struct strbuf name = STRBUF_INIT;
540 int name_base_len = 0;
541 if (repo->submodule_prefix) {
542 name_base_len = strlen(repo->submodule_prefix);
543 strbuf_addstr(&name, repo->submodule_prefix);
546 if (repo_read_index(repo) < 0)
547 die(_("index file corrupt"));
549 for (nr = 0; nr < repo->index->cache_nr; nr++) {
550 const struct cache_entry *ce = repo->index->cache[nr];
552 if (!cached && ce_skip_worktree(ce))
553 continue;
555 strbuf_setlen(&name, name_base_len);
556 strbuf_addstr(&name, ce->name);
557 if (S_ISSPARSEDIR(ce->ce_mode)) {
558 enum object_type type;
559 struct tree_desc tree;
560 void *data;
561 unsigned long size;
563 data = read_object_file(&ce->oid, &type, &size);
564 init_tree_desc(&tree, data, size);
566 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
567 strbuf_setlen(&name, name_base_len);
568 strbuf_addstr(&name, ce->name);
569 free(data);
570 } else if (S_ISREG(ce->ce_mode) &&
571 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
572 S_ISDIR(ce->ce_mode) ||
573 S_ISGITLINK(ce->ce_mode))) {
575 * If CE_VALID is on, we assume worktree file and its
576 * cache entry are identical, even if worktree file has
577 * been modified, so use cache version instead
579 if (cached || (ce->ce_flags & CE_VALID)) {
580 if (ce_stage(ce) || ce_intent_to_add(ce))
581 continue;
582 hit |= grep_oid(opt, &ce->oid, name.buf,
583 0, name.buf);
584 } else {
585 hit |= grep_file(opt, name.buf);
587 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
588 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
589 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
590 ce->name, cached);
591 } else {
592 continue;
595 if (ce_stage(ce)) {
596 do {
597 nr++;
598 } while (nr < repo->index->cache_nr &&
599 !strcmp(ce->name, repo->index->cache[nr]->name));
600 nr--; /* compensate for loop control */
602 if (hit && opt->status_only)
603 break;
606 strbuf_release(&name);
607 return hit;
610 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
611 struct tree_desc *tree, struct strbuf *base, int tn_len,
612 int check_attr)
614 struct repository *repo = opt->repo;
615 int hit = 0;
616 enum interesting match = entry_not_interesting;
617 struct name_entry entry;
618 int old_baselen = base->len;
619 struct strbuf name = STRBUF_INIT;
620 int name_base_len = 0;
621 if (repo->submodule_prefix) {
622 strbuf_addstr(&name, repo->submodule_prefix);
623 name_base_len = name.len;
626 while (tree_entry(tree, &entry)) {
627 int te_len = tree_entry_len(&entry);
629 if (match != all_entries_interesting) {
630 strbuf_addstr(&name, base->buf + tn_len);
631 match = tree_entry_interesting(repo->index,
632 &entry, &name,
633 0, pathspec);
634 strbuf_setlen(&name, name_base_len);
636 if (match == all_entries_not_interesting)
637 break;
638 if (match == entry_not_interesting)
639 continue;
642 strbuf_add(base, entry.path, te_len);
644 if (S_ISREG(entry.mode)) {
645 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
646 check_attr ? base->buf + tn_len : NULL);
647 } else if (S_ISDIR(entry.mode)) {
648 enum object_type type;
649 struct tree_desc sub;
650 void *data;
651 unsigned long size;
653 data = read_object_file(&entry.oid, &type, &size);
654 if (!data)
655 die(_("unable to read tree (%s)"),
656 oid_to_hex(&entry.oid));
658 strbuf_addch(base, '/');
659 init_tree_desc(&sub, data, size);
660 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
661 check_attr);
662 free(data);
663 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
664 hit |= grep_submodule(opt, pathspec, &entry.oid,
665 base->buf, base->buf + tn_len,
666 1); /* ignored */
669 strbuf_setlen(base, old_baselen);
671 if (hit && opt->status_only)
672 break;
675 strbuf_release(&name);
676 return hit;
679 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
680 struct object *obj, const char *name, const char *path)
682 if (obj->type == OBJ_BLOB)
683 return grep_oid(opt, &obj->oid, name, 0, path);
684 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
685 struct tree_desc tree;
686 void *data;
687 unsigned long size;
688 struct strbuf base;
689 int hit, len;
691 data = read_object_with_reference(opt->repo,
692 &obj->oid, OBJ_TREE,
693 &size, NULL);
694 if (!data)
695 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
697 len = name ? strlen(name) : 0;
698 strbuf_init(&base, PATH_MAX + len + 1);
699 if (len) {
700 strbuf_add(&base, name, len);
701 strbuf_addch(&base, ':');
703 init_tree_desc(&tree, data, size);
704 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
705 obj->type == OBJ_COMMIT);
706 strbuf_release(&base);
707 free(data);
708 return hit;
710 die(_("unable to grep from object of type %s"), type_name(obj->type));
713 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
714 const struct object_array *list)
716 unsigned int i;
717 int hit = 0;
718 const unsigned int nr = list->nr;
720 for (i = 0; i < nr; i++) {
721 struct object *real_obj;
723 obj_read_lock();
724 real_obj = deref_tag(opt->repo, list->objects[i].item,
725 NULL, 0);
726 obj_read_unlock();
728 if (!real_obj) {
729 char hex[GIT_MAX_HEXSZ + 1];
730 const char *name = list->objects[i].name;
732 if (!name) {
733 oid_to_hex_r(hex, &list->objects[i].item->oid);
734 name = hex;
736 die(_("invalid object '%s' given."), name);
739 /* load the gitmodules file for this rev */
740 if (recurse_submodules) {
741 submodule_free(opt->repo);
742 obj_read_lock();
743 gitmodules_config_oid(&real_obj->oid);
744 obj_read_unlock();
746 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
747 list->objects[i].path)) {
748 hit = 1;
749 if (opt->status_only)
750 break;
753 return hit;
756 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
757 int exc_std, int use_index)
759 struct dir_struct dir = DIR_INIT;
760 int i, hit = 0;
762 if (!use_index)
763 dir.flags |= DIR_NO_GITLINKS;
764 if (exc_std)
765 setup_standard_excludes(&dir);
767 fill_directory(&dir, opt->repo->index, pathspec);
768 for (i = 0; i < dir.nr; i++) {
769 hit |= grep_file(opt, dir.entries[i]->name);
770 if (hit && opt->status_only)
771 break;
773 dir_clear(&dir);
774 return hit;
777 static int context_callback(const struct option *opt, const char *arg,
778 int unset)
780 struct grep_opt *grep_opt = opt->value;
781 int value;
782 const char *endp;
784 if (unset) {
785 grep_opt->pre_context = grep_opt->post_context = 0;
786 return 0;
788 value = strtol(arg, (char **)&endp, 10);
789 if (*endp) {
790 return error(_("switch `%c' expects a numerical value"),
791 opt->short_name);
793 grep_opt->pre_context = grep_opt->post_context = value;
794 return 0;
797 static int file_callback(const struct option *opt, const char *arg, int unset)
799 struct grep_opt *grep_opt = opt->value;
800 int from_stdin;
801 FILE *patterns;
802 int lno = 0;
803 struct strbuf sb = STRBUF_INIT;
805 BUG_ON_OPT_NEG(unset);
807 from_stdin = !strcmp(arg, "-");
808 patterns = from_stdin ? stdin : fopen(arg, "r");
809 if (!patterns)
810 die_errno(_("cannot open '%s'"), arg);
811 while (strbuf_getline(&sb, patterns) == 0) {
812 /* ignore empty line like grep does */
813 if (sb.len == 0)
814 continue;
816 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
817 GREP_PATTERN);
819 if (!from_stdin)
820 fclose(patterns);
821 strbuf_release(&sb);
822 return 0;
825 static int not_callback(const struct option *opt, const char *arg, int unset)
827 struct grep_opt *grep_opt = opt->value;
828 BUG_ON_OPT_NEG(unset);
829 BUG_ON_OPT_ARG(arg);
830 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
831 return 0;
834 static int and_callback(const struct option *opt, const char *arg, int unset)
836 struct grep_opt *grep_opt = opt->value;
837 BUG_ON_OPT_NEG(unset);
838 BUG_ON_OPT_ARG(arg);
839 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
840 return 0;
843 static int open_callback(const struct option *opt, const char *arg, int unset)
845 struct grep_opt *grep_opt = opt->value;
846 BUG_ON_OPT_NEG(unset);
847 BUG_ON_OPT_ARG(arg);
848 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
849 return 0;
852 static int close_callback(const struct option *opt, const char *arg, int unset)
854 struct grep_opt *grep_opt = opt->value;
855 BUG_ON_OPT_NEG(unset);
856 BUG_ON_OPT_ARG(arg);
857 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
858 return 0;
861 static int pattern_callback(const struct option *opt, const char *arg,
862 int unset)
864 struct grep_opt *grep_opt = opt->value;
865 BUG_ON_OPT_NEG(unset);
866 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
867 return 0;
870 int cmd_grep(int argc, const char **argv, const char *prefix)
872 int hit = 0;
873 int cached = 0, untracked = 0, opt_exclude = -1;
874 int seen_dashdash = 0;
875 int external_grep_allowed__ignored;
876 const char *show_in_pager = NULL, *default_pager = "dummy";
877 struct grep_opt opt;
878 struct object_array list = OBJECT_ARRAY_INIT;
879 struct pathspec pathspec;
880 struct string_list path_list = STRING_LIST_INIT_DUP;
881 int i;
882 int dummy;
883 int use_index = 1;
884 int allow_revs;
886 struct option options[] = {
887 OPT_BOOL(0, "cached", &cached,
888 N_("search in index instead of in the work tree")),
889 OPT_NEGBIT(0, "no-index", &use_index,
890 N_("find in contents not managed by git"), 1),
891 OPT_BOOL(0, "untracked", &untracked,
892 N_("search in both tracked and untracked files")),
893 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
894 N_("ignore files specified via '.gitignore'"), 1),
895 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
896 N_("recursively search in each submodule")),
897 OPT_GROUP(""),
898 OPT_BOOL('v', "invert-match", &opt.invert,
899 N_("show non-matching lines")),
900 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
901 N_("case insensitive matching")),
902 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
903 N_("match patterns only at word boundaries")),
904 OPT_SET_INT('a', "text", &opt.binary,
905 N_("process binary files as text"), GREP_BINARY_TEXT),
906 OPT_SET_INT('I', NULL, &opt.binary,
907 N_("don't match patterns in binary files"),
908 GREP_BINARY_NOMATCH),
909 OPT_BOOL(0, "textconv", &opt.allow_textconv,
910 N_("process binary files with textconv filters")),
911 OPT_SET_INT('r', "recursive", &opt.max_depth,
912 N_("search in subdirectories (default)"), -1),
913 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
914 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
915 NULL, 1 },
916 OPT_GROUP(""),
917 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
918 N_("use extended POSIX regular expressions"),
919 GREP_PATTERN_TYPE_ERE),
920 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
921 N_("use basic POSIX regular expressions (default)"),
922 GREP_PATTERN_TYPE_BRE),
923 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
924 N_("interpret patterns as fixed strings"),
925 GREP_PATTERN_TYPE_FIXED),
926 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
927 N_("use Perl-compatible regular expressions"),
928 GREP_PATTERN_TYPE_PCRE),
929 OPT_GROUP(""),
930 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
931 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
932 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
933 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
934 OPT_NEGBIT(0, "full-name", &opt.relative,
935 N_("show filenames relative to top directory"), 1),
936 OPT_BOOL('l', "files-with-matches", &opt.name_only,
937 N_("show only filenames instead of matching lines")),
938 OPT_BOOL(0, "name-only", &opt.name_only,
939 N_("synonym for --files-with-matches")),
940 OPT_BOOL('L', "files-without-match",
941 &opt.unmatch_name_only,
942 N_("show only the names of files without match")),
943 OPT_BOOL_F('z', "null", &opt.null_following_name,
944 N_("print NUL after filenames"),
945 PARSE_OPT_NOCOMPLETE),
946 OPT_BOOL('o', "only-matching", &opt.only_matching,
947 N_("show only matching parts of a line")),
948 OPT_BOOL('c', "count", &opt.count,
949 N_("show the number of matches instead of matching lines")),
950 OPT__COLOR(&opt.color, N_("highlight matches")),
951 OPT_BOOL(0, "break", &opt.file_break,
952 N_("print empty line between matches from different files")),
953 OPT_BOOL(0, "heading", &opt.heading,
954 N_("show filename only once above matches from same file")),
955 OPT_GROUP(""),
956 OPT_CALLBACK('C', "context", &opt, N_("n"),
957 N_("show <n> context lines before and after matches"),
958 context_callback),
959 OPT_INTEGER('B', "before-context", &opt.pre_context,
960 N_("show <n> context lines before matches")),
961 OPT_INTEGER('A', "after-context", &opt.post_context,
962 N_("show <n> context lines after matches")),
963 OPT_INTEGER(0, "threads", &num_threads,
964 N_("use <n> worker threads")),
965 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
966 context_callback),
967 OPT_BOOL('p', "show-function", &opt.funcname,
968 N_("show a line with the function name before matches")),
969 OPT_BOOL('W', "function-context", &opt.funcbody,
970 N_("show the surrounding function")),
971 OPT_GROUP(""),
972 OPT_CALLBACK('f', NULL, &opt, N_("file"),
973 N_("read patterns from file"), file_callback),
974 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
975 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
976 OPT_CALLBACK_F(0, "and", &opt, NULL,
977 N_("combine patterns specified with -e"),
978 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
979 OPT_BOOL_F(0, "or", &dummy, "", PARSE_OPT_NONEG),
980 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
981 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
982 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
983 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
984 open_callback),
985 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
986 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
987 close_callback),
988 OPT__QUIET(&opt.status_only,
989 N_("indicate hit with exit status without output")),
990 OPT_BOOL(0, "all-match", &opt.all_match,
991 N_("show only matches from files that match all patterns")),
992 OPT_GROUP(""),
993 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
994 N_("pager"), N_("show matching files in the pager"),
995 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
996 NULL, (intptr_t)default_pager },
997 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
998 N_("allow calling of grep(1) (ignored by this build)"),
999 PARSE_OPT_NOCOMPLETE),
1000 OPT_INTEGER('m', "max-count", &opt.max_count,
1001 N_("maximum number of results per file")),
1002 OPT_END()
1004 grep_prefix = prefix;
1006 grep_init(&opt, the_repository);
1007 git_config(grep_cmd_config, &opt);
1010 * If there is no -- then the paths must exist in the working
1011 * tree. If there is no explicit pattern specified with -e or
1012 * -f, we take the first unrecognized non option to be the
1013 * pattern, but then what follows it must be zero or more
1014 * valid refs up to the -- (if exists), and then existing
1015 * paths. If there is an explicit pattern, then the first
1016 * unrecognized non option is the beginning of the refs list
1017 * that continues up to the -- (if exists), and then paths.
1019 argc = parse_options(argc, argv, prefix, options, grep_usage,
1020 PARSE_OPT_KEEP_DASHDASH |
1021 PARSE_OPT_STOP_AT_NON_OPTION);
1023 if (the_repository->gitdir) {
1024 prepare_repo_settings(the_repository);
1025 the_repository->settings.command_requires_full_index = 0;
1028 if (use_index && !startup_info->have_repository) {
1029 int fallback = 0;
1030 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1031 if (fallback)
1032 use_index = 0;
1033 else
1034 /* die the same way as if we did it at the beginning */
1035 setup_git_directory();
1037 /* Ignore --recurse-submodules if --no-index is given or implied */
1038 if (!use_index)
1039 recurse_submodules = 0;
1042 * skip a -- separator; we know it cannot be
1043 * separating revisions from pathnames if
1044 * we haven't even had any patterns yet
1046 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1047 argv++;
1048 argc--;
1051 /* First unrecognized non-option token */
1052 if (argc > 0 && !opt.pattern_list) {
1053 append_grep_pattern(&opt, argv[0], "command line", 0,
1054 GREP_PATTERN);
1055 argv++;
1056 argc--;
1059 if (show_in_pager == default_pager)
1060 show_in_pager = git_pager(1);
1061 if (show_in_pager) {
1062 opt.color = 0;
1063 opt.name_only = 1;
1064 opt.null_following_name = 1;
1065 opt.output_priv = &path_list;
1066 opt.output = append_path;
1067 string_list_append(&path_list, show_in_pager);
1070 if (!opt.pattern_list)
1071 die(_("no pattern given"));
1073 /* --only-matching has no effect with --invert. */
1074 if (opt.invert)
1075 opt.only_matching = 0;
1078 * We have to find "--" in a separate pass, because its presence
1079 * influences how we will parse arguments that come before it.
1081 for (i = 0; i < argc; i++) {
1082 if (!strcmp(argv[i], "--")) {
1083 seen_dashdash = 1;
1084 break;
1089 * Resolve any rev arguments. If we have a dashdash, then everything up
1090 * to it must resolve as a rev. If not, then we stop at the first
1091 * non-rev and assume everything else is a path.
1093 allow_revs = use_index && !untracked;
1094 for (i = 0; i < argc; i++) {
1095 const char *arg = argv[i];
1096 struct object_id oid;
1097 struct object_context oc;
1098 struct object *object;
1100 if (!strcmp(arg, "--")) {
1101 i++;
1102 break;
1105 if (!allow_revs) {
1106 if (seen_dashdash)
1107 die(_("--no-index or --untracked cannot be used with revs"));
1108 break;
1111 if (get_oid_with_context(the_repository, arg,
1112 GET_OID_RECORD_PATH,
1113 &oid, &oc)) {
1114 if (seen_dashdash)
1115 die(_("unable to resolve revision: %s"), arg);
1116 break;
1119 object = parse_object_or_die(&oid, arg);
1120 if (!seen_dashdash)
1121 verify_non_filename(prefix, arg);
1122 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1123 free(oc.path);
1127 * Anything left over is presumed to be a path. But in the non-dashdash
1128 * "do what I mean" case, we verify and complain when that isn't true.
1130 if (!seen_dashdash) {
1131 int j;
1132 for (j = i; j < argc; j++)
1133 verify_filename(prefix, argv[j], j == i && allow_revs);
1136 parse_pathspec(&pathspec, 0,
1137 PATHSPEC_PREFER_CWD |
1138 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1139 prefix, argv + i);
1140 pathspec.max_depth = opt.max_depth;
1141 pathspec.recursive = 1;
1142 pathspec.recurse_submodules = !!recurse_submodules;
1144 if (recurse_submodules && untracked)
1145 die(_("--untracked not supported with --recurse-submodules"));
1148 * Optimize out the case where the amount of matches is limited to zero.
1149 * We do this to keep results consistent with GNU grep(1).
1151 if (opt.max_count == 0)
1152 return 1;
1154 if (show_in_pager) {
1155 if (num_threads > 1)
1156 warning(_("invalid option combination, ignoring --threads"));
1157 num_threads = 1;
1158 } else if (!HAVE_THREADS && num_threads > 1) {
1159 warning(_("no threads support, ignoring --threads"));
1160 num_threads = 1;
1161 } else if (num_threads < 0)
1162 die(_("invalid number of threads specified (%d)"), num_threads);
1163 else if (num_threads == 0)
1164 num_threads = HAVE_THREADS ? online_cpus() : 1;
1166 if (num_threads > 1) {
1167 if (!HAVE_THREADS)
1168 BUG("Somebody got num_threads calculation wrong!");
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;
1175 * Pre-read gitmodules (if not read already) and force eager
1176 * initialization of packed_git to prevent racy lazy
1177 * reading/initialization once worker threads are started.
1179 if (recurse_submodules)
1180 repo_read_gitmodules(the_repository, 1);
1181 if (startup_info->have_repository)
1182 (void)get_packed_git(the_repository);
1184 start_threads(&opt);
1185 } else {
1187 * The compiled patterns on the main path are only
1188 * used when not using threading. Otherwise
1189 * start_threads() above calls compile_grep_patterns()
1190 * for each thread.
1192 compile_grep_patterns(&opt);
1195 if (show_in_pager && (cached || list.nr))
1196 die(_("--open-files-in-pager only works on the worktree"));
1198 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1199 const char *pager = path_list.items[0].string;
1200 int len = strlen(pager);
1202 if (len > 4 && is_dir_sep(pager[len - 5]))
1203 pager += len - 4;
1205 if (opt.ignore_case && !strcmp("less", pager))
1206 string_list_append(&path_list, "-I");
1208 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1209 struct strbuf buf = STRBUF_INIT;
1210 strbuf_addf(&buf, "+/%s%s",
1211 strcmp("less", pager) ? "" : "*",
1212 opt.pattern_list->pattern);
1213 string_list_append_nodup(&path_list,
1214 strbuf_detach(&buf, NULL));
1218 if (!show_in_pager && !opt.status_only)
1219 setup_pager();
1221 die_for_incompatible_opt3(!use_index, "--no-index",
1222 untracked, "--untracked",
1223 cached, "--cached");
1225 if (!use_index || untracked) {
1226 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1227 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1228 } else if (0 <= opt_exclude) {
1229 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1230 } else if (!list.nr) {
1231 if (!cached)
1232 setup_work_tree();
1234 hit = grep_cache(&opt, &pathspec, cached);
1235 } else {
1236 if (cached)
1237 die(_("both --cached and trees are given"));
1239 hit = grep_objects(&opt, &pathspec, &list);
1242 if (num_threads > 1)
1243 hit |= wait_all();
1244 if (hit && show_in_pager)
1245 run_pager(&opt, prefix);
1246 clear_pathspec(&pathspec);
1247 string_list_clear(&path_list, 0);
1248 free_grep_patterns(&opt);
1249 object_array_clear(&list);
1250 free_repos();
1251 return !hit;