git maintenance: avoid console window in scheduled tasks on Windows
[git.git] / builtin / grep.c
blobb86c754defbc59654a6e455b2115487ba01f084f
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-file.h"
30 #include "object-name.h"
31 #include "object-store.h"
32 #include "packfile.h"
33 #include "pager.h"
34 #include "write-or-die.h"
36 static const char *grep_prefix;
38 static char const * const grep_usage[] = {
39 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
40 NULL
43 static int recurse_submodules;
45 static int num_threads;
47 static pthread_t *threads;
49 /* We use one producer thread and THREADS consumer
50 * threads. The producer adds struct work_items to 'todo' and the
51 * consumers pick work items from the same array.
53 struct work_item {
54 struct grep_source source;
55 char done;
56 struct strbuf out;
59 /* In the range [todo_done, todo_start) in 'todo' we have work_items
60 * that have been or are processed by a consumer thread. We haven't
61 * written the result for these to stdout yet.
63 * The work_items in [todo_start, todo_end) are waiting to be picked
64 * up by a consumer thread.
66 * The ranges are modulo TODO_SIZE.
68 #define TODO_SIZE 128
69 static struct work_item todo[TODO_SIZE];
70 static int todo_start;
71 static int todo_end;
72 static int todo_done;
74 /* Has all work items been added? */
75 static int all_work_added;
77 static struct repository **repos_to_free;
78 static size_t repos_to_free_nr, repos_to_free_alloc;
80 /* This lock protects all the variables above. */
81 static pthread_mutex_t grep_mutex;
83 static inline void grep_lock(void)
85 pthread_mutex_lock(&grep_mutex);
88 static inline void grep_unlock(void)
90 pthread_mutex_unlock(&grep_mutex);
93 /* Signalled when a new work_item is added to todo. */
94 static pthread_cond_t cond_add;
96 /* Signalled when the result from one work_item is written to
97 * stdout.
99 static pthread_cond_t cond_write;
101 /* Signalled when we are finished with everything. */
102 static pthread_cond_t cond_result;
104 static int skip_first_line;
106 static void add_work(struct grep_opt *opt, struct grep_source *gs)
108 if (opt->binary != GREP_BINARY_TEXT)
109 grep_source_load_driver(gs, opt->repo->index);
111 grep_lock();
113 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
114 pthread_cond_wait(&cond_write, &grep_mutex);
117 todo[todo_end].source = *gs;
118 todo[todo_end].done = 0;
119 strbuf_reset(&todo[todo_end].out);
120 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
122 pthread_cond_signal(&cond_add);
123 grep_unlock();
126 static struct work_item *get_work(void)
128 struct work_item *ret;
130 grep_lock();
131 while (todo_start == todo_end && !all_work_added) {
132 pthread_cond_wait(&cond_add, &grep_mutex);
135 if (todo_start == todo_end && all_work_added) {
136 ret = NULL;
137 } else {
138 ret = &todo[todo_start];
139 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
141 grep_unlock();
142 return ret;
145 static void work_done(struct work_item *w)
147 int old_done;
149 grep_lock();
150 w->done = 1;
151 old_done = todo_done;
152 for(; todo[todo_done].done && todo_done != todo_start;
153 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
154 w = &todo[todo_done];
155 if (w->out.len) {
156 const char *p = w->out.buf;
157 size_t len = w->out.len;
159 /* Skip the leading hunk mark of the first file. */
160 if (skip_first_line) {
161 while (len) {
162 len--;
163 if (*p++ == '\n')
164 break;
166 skip_first_line = 0;
169 write_or_die(1, p, len);
171 grep_source_clear(&w->source);
174 if (old_done != todo_done)
175 pthread_cond_signal(&cond_write);
177 if (all_work_added && todo_done == todo_end)
178 pthread_cond_signal(&cond_result);
180 grep_unlock();
183 static void free_repos(void)
185 int i;
187 for (i = 0; i < repos_to_free_nr; i++) {
188 repo_clear(repos_to_free[i]);
189 free(repos_to_free[i]);
191 FREE_AND_NULL(repos_to_free);
192 repos_to_free_nr = 0;
193 repos_to_free_alloc = 0;
196 static void *run(void *arg)
198 int hit = 0;
199 struct grep_opt *opt = arg;
201 while (1) {
202 struct work_item *w = get_work();
203 if (!w)
204 break;
206 opt->output_priv = w;
207 hit |= grep_source(opt, &w->source);
208 grep_source_clear_data(&w->source);
209 work_done(w);
211 free_grep_patterns(opt);
212 free(opt);
214 return (void*) (intptr_t) hit;
217 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
219 struct work_item *w = opt->output_priv;
220 strbuf_add(&w->out, buf, size);
223 static void start_threads(struct grep_opt *opt)
225 int i;
227 pthread_mutex_init(&grep_mutex, NULL);
228 pthread_mutex_init(&grep_attr_mutex, NULL);
229 pthread_cond_init(&cond_add, NULL);
230 pthread_cond_init(&cond_write, NULL);
231 pthread_cond_init(&cond_result, NULL);
232 grep_use_locks = 1;
233 enable_obj_read_lock();
235 for (i = 0; i < ARRAY_SIZE(todo); i++) {
236 strbuf_init(&todo[i].out, 0);
239 CALLOC_ARRAY(threads, num_threads);
240 for (i = 0; i < num_threads; i++) {
241 int err;
242 struct grep_opt *o = grep_opt_dup(opt);
243 o->output = strbuf_out;
244 compile_grep_patterns(o);
245 err = pthread_create(&threads[i], NULL, run, o);
247 if (err)
248 die(_("grep: failed to create thread: %s"),
249 strerror(err));
253 static int wait_all(void)
255 int hit = 0;
256 int i;
258 if (!HAVE_THREADS)
259 BUG("Never call this function unless you have started threads");
261 grep_lock();
262 all_work_added = 1;
264 /* Wait until all work is done. */
265 while (todo_done != todo_end)
266 pthread_cond_wait(&cond_result, &grep_mutex);
268 /* Wake up all the consumer threads so they can see that there
269 * is no more work to do.
271 pthread_cond_broadcast(&cond_add);
272 grep_unlock();
274 for (i = 0; i < num_threads; i++) {
275 void *h;
276 pthread_join(threads[i], &h);
277 hit |= (int) (intptr_t) h;
280 free(threads);
282 pthread_mutex_destroy(&grep_mutex);
283 pthread_mutex_destroy(&grep_attr_mutex);
284 pthread_cond_destroy(&cond_add);
285 pthread_cond_destroy(&cond_write);
286 pthread_cond_destroy(&cond_result);
287 grep_use_locks = 0;
288 disable_obj_read_lock();
290 return hit;
293 static int grep_cmd_config(const char *var, const char *value, void *cb)
295 int st = grep_config(var, value, cb);
296 if (git_color_default_config(var, value, NULL) < 0)
297 st = -1;
299 if (!strcmp(var, "grep.threads")) {
300 num_threads = git_config_int(var, value);
301 if (num_threads < 0)
302 die(_("invalid number of threads specified (%d) for %s"),
303 num_threads, var);
304 else if (!HAVE_THREADS && num_threads > 1) {
306 * TRANSLATORS: %s is the configuration
307 * variable for tweaking threads, currently
308 * grep.threads
310 warning(_("no threads support, ignoring %s"), var);
311 num_threads = 1;
315 if (!strcmp(var, "submodule.recurse"))
316 recurse_submodules = git_config_bool(var, value);
318 return st;
321 static void grep_source_name(struct grep_opt *opt, const char *filename,
322 int tree_name_len, struct strbuf *out)
324 strbuf_reset(out);
326 if (opt->null_following_name) {
327 if (opt->relative && grep_prefix) {
328 struct strbuf rel_buf = STRBUF_INIT;
329 const char *rel_name =
330 relative_path(filename + tree_name_len,
331 grep_prefix, &rel_buf);
333 if (tree_name_len)
334 strbuf_add(out, filename, tree_name_len);
336 strbuf_addstr(out, rel_name);
337 strbuf_release(&rel_buf);
338 } else {
339 strbuf_addstr(out, filename);
341 return;
344 if (opt->relative && grep_prefix)
345 quote_path(filename + tree_name_len, grep_prefix, out, 0);
346 else
347 quote_c_style(filename + tree_name_len, out, NULL, 0);
349 if (tree_name_len)
350 strbuf_insert(out, 0, filename, tree_name_len);
353 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
354 const char *filename, int tree_name_len,
355 const char *path)
357 struct strbuf pathbuf = STRBUF_INIT;
358 struct grep_source gs;
360 grep_source_name(opt, filename, tree_name_len, &pathbuf);
361 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
362 strbuf_release(&pathbuf);
364 if (num_threads > 1) {
366 * add_work() copies gs and thus assumes ownership of
367 * its fields, so do not call grep_source_clear()
369 add_work(opt, &gs);
370 return 0;
371 } else {
372 int hit;
374 hit = grep_source(opt, &gs);
376 grep_source_clear(&gs);
377 return hit;
381 static int grep_file(struct grep_opt *opt, const char *filename)
383 struct strbuf buf = STRBUF_INIT;
384 struct grep_source gs;
386 grep_source_name(opt, filename, 0, &buf);
387 grep_source_init_file(&gs, buf.buf, filename);
388 strbuf_release(&buf);
390 if (num_threads > 1) {
392 * add_work() copies gs and thus assumes ownership of
393 * its fields, so do not call grep_source_clear()
395 add_work(opt, &gs);
396 return 0;
397 } else {
398 int hit;
400 hit = grep_source(opt, &gs);
402 grep_source_clear(&gs);
403 return hit;
407 static void append_path(struct grep_opt *opt, const void *data, size_t len)
409 struct string_list *path_list = opt->output_priv;
411 if (len == 1 && *(const char *)data == '\0')
412 return;
413 string_list_append_nodup(path_list, xstrndup(data, len));
416 static void run_pager(struct grep_opt *opt, const char *prefix)
418 struct string_list *path_list = opt->output_priv;
419 struct child_process child = CHILD_PROCESS_INIT;
420 int i, status;
422 for (i = 0; i < path_list->nr; i++)
423 strvec_push(&child.args, path_list->items[i].string);
424 child.dir = prefix;
425 child.use_shell = 1;
427 status = run_command(&child);
428 if (status)
429 exit(status);
432 static int grep_cache(struct grep_opt *opt,
433 const struct pathspec *pathspec, int cached);
434 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
435 struct tree_desc *tree, struct strbuf *base, int tn_len,
436 int check_attr);
438 static int grep_submodule(struct grep_opt *opt,
439 const struct pathspec *pathspec,
440 const struct object_id *oid,
441 const char *filename, const char *path, int cached)
443 struct repository *subrepo;
444 struct repository *superproject = opt->repo;
445 struct grep_opt subopt;
446 int hit = 0;
448 if (!is_submodule_active(superproject, path))
449 return 0;
451 subrepo = xmalloc(sizeof(*subrepo));
452 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
453 free(subrepo);
454 return 0;
456 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
457 repos_to_free[repos_to_free_nr++] = subrepo;
460 * NEEDSWORK: repo_read_gitmodules() might call
461 * add_to_alternates_memory() via config_from_gitmodules(). This
462 * operation causes a race condition with concurrent object readings
463 * performed by the worker threads. That's why we need obj_read_lock()
464 * here. It should be removed once it's no longer necessary to add the
465 * subrepo's odbs to the in-memory alternates list.
467 obj_read_lock();
470 * NEEDSWORK: when reading a submodule, the sparsity settings in the
471 * superproject are incorrectly forgotten or misused. For example:
473 * 1. "command_requires_full_index"
474 * When this setting is turned on for `grep`, only the superproject
475 * knows it. All the submodules are read with their own configs
476 * and get prepare_repo_settings()'d. Therefore, these submodules
477 * "forget" the sparse-index feature switch. As a result, the index
478 * of these submodules are expanded unexpectedly.
480 * 2. "core_apply_sparse_checkout"
481 * When running `grep` in the superproject, this setting is
482 * populated using the superproject's configs. However, once
483 * initialized, this config is globally accessible and is read by
484 * prepare_repo_settings() for the submodules. For instance, if a
485 * submodule is using a sparse-checkout, however, the superproject
486 * is not, the result is that the config from the superproject will
487 * dictate the behavior for the submodule, making it "forget" its
488 * sparse-checkout state.
490 * 3. "core_sparse_checkout_cone"
491 * ditto.
493 * Note that this list is not exhaustive.
495 repo_read_gitmodules(subrepo, 0);
498 * All code paths tested by test code no longer need submodule ODBs to
499 * be added as alternates, but add it to the list just in case.
500 * Submodule ODBs added through add_submodule_odb_by_path() will be
501 * lazily registered as alternates when needed (and except in an
502 * unexpected code interaction, it won't be needed).
504 add_submodule_odb_by_path(subrepo->objects->odb->path);
505 obj_read_unlock();
507 memcpy(&subopt, opt, sizeof(subopt));
508 subopt.repo = subrepo;
510 if (oid) {
511 enum object_type object_type;
512 struct tree_desc tree;
513 void *data;
514 unsigned long size;
515 struct strbuf base = STRBUF_INIT;
517 obj_read_lock();
518 object_type = oid_object_info(subrepo, oid, NULL);
519 obj_read_unlock();
520 data = read_object_with_reference(subrepo,
521 oid, OBJ_TREE,
522 &size, NULL);
523 if (!data)
524 die(_("unable to read tree (%s)"), oid_to_hex(oid));
526 strbuf_addstr(&base, filename);
527 strbuf_addch(&base, '/');
529 init_tree_desc(&tree, data, size);
530 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
531 object_type == OBJ_COMMIT);
532 strbuf_release(&base);
533 free(data);
534 } else {
535 hit = grep_cache(&subopt, pathspec, cached);
538 return hit;
541 static int grep_cache(struct grep_opt *opt,
542 const struct pathspec *pathspec, int cached)
544 struct repository *repo = opt->repo;
545 int hit = 0;
546 int nr;
547 struct strbuf name = STRBUF_INIT;
548 int name_base_len = 0;
549 if (repo->submodule_prefix) {
550 name_base_len = strlen(repo->submodule_prefix);
551 strbuf_addstr(&name, repo->submodule_prefix);
554 if (repo_read_index(repo) < 0)
555 die(_("index file corrupt"));
557 for (nr = 0; nr < repo->index->cache_nr; nr++) {
558 const struct cache_entry *ce = repo->index->cache[nr];
560 if (!cached && ce_skip_worktree(ce))
561 continue;
563 strbuf_setlen(&name, name_base_len);
564 strbuf_addstr(&name, ce->name);
565 if (S_ISSPARSEDIR(ce->ce_mode)) {
566 enum object_type type;
567 struct tree_desc tree;
568 void *data;
569 unsigned long size;
571 data = repo_read_object_file(the_repository, &ce->oid,
572 &type, &size);
573 init_tree_desc(&tree, data, size);
575 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
576 strbuf_setlen(&name, name_base_len);
577 strbuf_addstr(&name, ce->name);
578 free(data);
579 } else if (S_ISREG(ce->ce_mode) &&
580 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
581 S_ISDIR(ce->ce_mode) ||
582 S_ISGITLINK(ce->ce_mode))) {
584 * If CE_VALID is on, we assume worktree file and its
585 * cache entry are identical, even if worktree file has
586 * been modified, so use cache version instead
588 if (cached || (ce->ce_flags & CE_VALID)) {
589 if (ce_stage(ce) || ce_intent_to_add(ce))
590 continue;
591 hit |= grep_oid(opt, &ce->oid, name.buf,
592 0, name.buf);
593 } else {
594 hit |= grep_file(opt, name.buf);
596 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
597 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
598 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
599 ce->name, cached);
600 } else {
601 continue;
604 if (ce_stage(ce)) {
605 do {
606 nr++;
607 } while (nr < repo->index->cache_nr &&
608 !strcmp(ce->name, repo->index->cache[nr]->name));
609 nr--; /* compensate for loop control */
611 if (hit && opt->status_only)
612 break;
615 strbuf_release(&name);
616 return hit;
619 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
620 struct tree_desc *tree, struct strbuf *base, int tn_len,
621 int check_attr)
623 struct repository *repo = opt->repo;
624 int hit = 0;
625 enum interesting match = entry_not_interesting;
626 struct name_entry entry;
627 int old_baselen = base->len;
628 struct strbuf name = STRBUF_INIT;
629 int name_base_len = 0;
630 if (repo->submodule_prefix) {
631 strbuf_addstr(&name, repo->submodule_prefix);
632 name_base_len = name.len;
635 while (tree_entry(tree, &entry)) {
636 int te_len = tree_entry_len(&entry);
638 if (match != all_entries_interesting) {
639 strbuf_addstr(&name, base->buf + tn_len);
640 match = tree_entry_interesting(repo->index,
641 &entry, &name,
642 0, pathspec);
643 strbuf_setlen(&name, name_base_len);
645 if (match == all_entries_not_interesting)
646 break;
647 if (match == entry_not_interesting)
648 continue;
651 strbuf_add(base, entry.path, te_len);
653 if (S_ISREG(entry.mode)) {
654 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
655 check_attr ? base->buf + tn_len : NULL);
656 } else if (S_ISDIR(entry.mode)) {
657 enum object_type type;
658 struct tree_desc sub;
659 void *data;
660 unsigned long size;
662 data = repo_read_object_file(the_repository,
663 &entry.oid, &type, &size);
664 if (!data)
665 die(_("unable to read tree (%s)"),
666 oid_to_hex(&entry.oid));
668 strbuf_addch(base, '/');
669 init_tree_desc(&sub, data, size);
670 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
671 check_attr);
672 free(data);
673 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
674 hit |= grep_submodule(opt, pathspec, &entry.oid,
675 base->buf, base->buf + tn_len,
676 1); /* ignored */
679 strbuf_setlen(base, old_baselen);
681 if (hit && opt->status_only)
682 break;
685 strbuf_release(&name);
686 return hit;
689 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
690 struct object *obj, const char *name, const char *path)
692 if (obj->type == OBJ_BLOB)
693 return grep_oid(opt, &obj->oid, name, 0, path);
694 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
695 struct tree_desc tree;
696 void *data;
697 unsigned long size;
698 struct strbuf base;
699 int hit, len;
701 data = read_object_with_reference(opt->repo,
702 &obj->oid, OBJ_TREE,
703 &size, NULL);
704 if (!data)
705 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
707 len = name ? strlen(name) : 0;
708 strbuf_init(&base, PATH_MAX + len + 1);
709 if (len) {
710 strbuf_add(&base, name, len);
711 strbuf_addch(&base, ':');
713 init_tree_desc(&tree, data, size);
714 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
715 obj->type == OBJ_COMMIT);
716 strbuf_release(&base);
717 free(data);
718 return hit;
720 die(_("unable to grep from object of type %s"), type_name(obj->type));
723 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
724 const struct object_array *list)
726 unsigned int i;
727 int hit = 0;
728 const unsigned int nr = list->nr;
730 for (i = 0; i < nr; i++) {
731 struct object *real_obj;
733 obj_read_lock();
734 real_obj = deref_tag(opt->repo, list->objects[i].item,
735 NULL, 0);
736 obj_read_unlock();
738 if (!real_obj) {
739 char hex[GIT_MAX_HEXSZ + 1];
740 const char *name = list->objects[i].name;
742 if (!name) {
743 oid_to_hex_r(hex, &list->objects[i].item->oid);
744 name = hex;
746 die(_("invalid object '%s' given."), name);
749 /* load the gitmodules file for this rev */
750 if (recurse_submodules) {
751 submodule_free(opt->repo);
752 obj_read_lock();
753 gitmodules_config_oid(&real_obj->oid);
754 obj_read_unlock();
756 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
757 list->objects[i].path)) {
758 hit = 1;
759 if (opt->status_only)
760 break;
763 return hit;
766 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
767 int exc_std, int use_index)
769 struct dir_struct dir = DIR_INIT;
770 int i, hit = 0;
772 if (!use_index)
773 dir.flags |= DIR_NO_GITLINKS;
774 if (exc_std)
775 setup_standard_excludes(&dir);
777 fill_directory(&dir, opt->repo->index, pathspec);
778 for (i = 0; i < dir.nr; i++) {
779 hit |= grep_file(opt, dir.entries[i]->name);
780 if (hit && opt->status_only)
781 break;
783 dir_clear(&dir);
784 return hit;
787 static int context_callback(const struct option *opt, const char *arg,
788 int unset)
790 struct grep_opt *grep_opt = opt->value;
791 int value;
792 const char *endp;
794 if (unset) {
795 grep_opt->pre_context = grep_opt->post_context = 0;
796 return 0;
798 value = strtol(arg, (char **)&endp, 10);
799 if (*endp) {
800 return error(_("switch `%c' expects a numerical value"),
801 opt->short_name);
803 grep_opt->pre_context = grep_opt->post_context = value;
804 return 0;
807 static int file_callback(const struct option *opt, const char *arg, int unset)
809 struct grep_opt *grep_opt = opt->value;
810 int from_stdin;
811 FILE *patterns;
812 int lno = 0;
813 struct strbuf sb = STRBUF_INIT;
815 BUG_ON_OPT_NEG(unset);
817 from_stdin = !strcmp(arg, "-");
818 patterns = from_stdin ? stdin : fopen(arg, "r");
819 if (!patterns)
820 die_errno(_("cannot open '%s'"), arg);
821 while (strbuf_getline(&sb, patterns) == 0) {
822 /* ignore empty line like grep does */
823 if (sb.len == 0)
824 continue;
826 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
827 GREP_PATTERN);
829 if (!from_stdin)
830 fclose(patterns);
831 strbuf_release(&sb);
832 return 0;
835 static int not_callback(const struct option *opt, const char *arg, int unset)
837 struct grep_opt *grep_opt = opt->value;
838 BUG_ON_OPT_NEG(unset);
839 BUG_ON_OPT_ARG(arg);
840 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
841 return 0;
844 static int and_callback(const struct option *opt, const char *arg, int unset)
846 struct grep_opt *grep_opt = opt->value;
847 BUG_ON_OPT_NEG(unset);
848 BUG_ON_OPT_ARG(arg);
849 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
850 return 0;
853 static int open_callback(const struct option *opt, const char *arg, int unset)
855 struct grep_opt *grep_opt = opt->value;
856 BUG_ON_OPT_NEG(unset);
857 BUG_ON_OPT_ARG(arg);
858 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
859 return 0;
862 static int close_callback(const struct option *opt, const char *arg, int unset)
864 struct grep_opt *grep_opt = opt->value;
865 BUG_ON_OPT_NEG(unset);
866 BUG_ON_OPT_ARG(arg);
867 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
868 return 0;
871 static int pattern_callback(const struct option *opt, const char *arg,
872 int unset)
874 struct grep_opt *grep_opt = opt->value;
875 BUG_ON_OPT_NEG(unset);
876 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
877 return 0;
880 int cmd_grep(int argc, const char **argv, const char *prefix)
882 int hit = 0;
883 int cached = 0, untracked = 0, opt_exclude = -1;
884 int seen_dashdash = 0;
885 int external_grep_allowed__ignored;
886 const char *show_in_pager = NULL, *default_pager = "dummy";
887 struct grep_opt opt;
888 struct object_array list = OBJECT_ARRAY_INIT;
889 struct pathspec pathspec;
890 struct string_list path_list = STRING_LIST_INIT_DUP;
891 int i;
892 int dummy;
893 int use_index = 1;
894 int allow_revs;
896 struct option options[] = {
897 OPT_BOOL(0, "cached", &cached,
898 N_("search in index instead of in the work tree")),
899 OPT_NEGBIT(0, "no-index", &use_index,
900 N_("find in contents not managed by git"), 1),
901 OPT_BOOL(0, "untracked", &untracked,
902 N_("search in both tracked and untracked files")),
903 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
904 N_("ignore files specified via '.gitignore'"), 1),
905 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
906 N_("recursively search in each submodule")),
907 OPT_GROUP(""),
908 OPT_BOOL('v', "invert-match", &opt.invert,
909 N_("show non-matching lines")),
910 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
911 N_("case insensitive matching")),
912 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
913 N_("match patterns only at word boundaries")),
914 OPT_SET_INT('a', "text", &opt.binary,
915 N_("process binary files as text"), GREP_BINARY_TEXT),
916 OPT_SET_INT('I', NULL, &opt.binary,
917 N_("don't match patterns in binary files"),
918 GREP_BINARY_NOMATCH),
919 OPT_BOOL(0, "textconv", &opt.allow_textconv,
920 N_("process binary files with textconv filters")),
921 OPT_SET_INT('r', "recursive", &opt.max_depth,
922 N_("search in subdirectories (default)"), -1),
923 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
924 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
925 NULL, 1 },
926 OPT_GROUP(""),
927 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
928 N_("use extended POSIX regular expressions"),
929 GREP_PATTERN_TYPE_ERE),
930 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
931 N_("use basic POSIX regular expressions (default)"),
932 GREP_PATTERN_TYPE_BRE),
933 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
934 N_("interpret patterns as fixed strings"),
935 GREP_PATTERN_TYPE_FIXED),
936 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
937 N_("use Perl-compatible regular expressions"),
938 GREP_PATTERN_TYPE_PCRE),
939 OPT_GROUP(""),
940 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
941 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
942 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
943 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
944 OPT_NEGBIT(0, "full-name", &opt.relative,
945 N_("show filenames relative to top directory"), 1),
946 OPT_BOOL('l', "files-with-matches", &opt.name_only,
947 N_("show only filenames instead of matching lines")),
948 OPT_BOOL(0, "name-only", &opt.name_only,
949 N_("synonym for --files-with-matches")),
950 OPT_BOOL('L', "files-without-match",
951 &opt.unmatch_name_only,
952 N_("show only the names of files without match")),
953 OPT_BOOL_F('z', "null", &opt.null_following_name,
954 N_("print NUL after filenames"),
955 PARSE_OPT_NOCOMPLETE),
956 OPT_BOOL('o', "only-matching", &opt.only_matching,
957 N_("show only matching parts of a line")),
958 OPT_BOOL('c', "count", &opt.count,
959 N_("show the number of matches instead of matching lines")),
960 OPT__COLOR(&opt.color, N_("highlight matches")),
961 OPT_BOOL(0, "break", &opt.file_break,
962 N_("print empty line between matches from different files")),
963 OPT_BOOL(0, "heading", &opt.heading,
964 N_("show filename only once above matches from same file")),
965 OPT_GROUP(""),
966 OPT_CALLBACK('C', "context", &opt, N_("n"),
967 N_("show <n> context lines before and after matches"),
968 context_callback),
969 OPT_INTEGER('B', "before-context", &opt.pre_context,
970 N_("show <n> context lines before matches")),
971 OPT_INTEGER('A', "after-context", &opt.post_context,
972 N_("show <n> context lines after matches")),
973 OPT_INTEGER(0, "threads", &num_threads,
974 N_("use <n> worker threads")),
975 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
976 context_callback),
977 OPT_BOOL('p', "show-function", &opt.funcname,
978 N_("show a line with the function name before matches")),
979 OPT_BOOL('W', "function-context", &opt.funcbody,
980 N_("show the surrounding function")),
981 OPT_GROUP(""),
982 OPT_CALLBACK('f', NULL, &opt, N_("file"),
983 N_("read patterns from file"), file_callback),
984 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
985 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
986 OPT_CALLBACK_F(0, "and", &opt, NULL,
987 N_("combine patterns specified with -e"),
988 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
989 OPT_BOOL(0, "or", &dummy, ""),
990 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
991 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
992 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
993 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
994 open_callback),
995 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
996 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
997 close_callback),
998 OPT__QUIET(&opt.status_only,
999 N_("indicate hit with exit status without output")),
1000 OPT_BOOL(0, "all-match", &opt.all_match,
1001 N_("show only matches from files that match all patterns")),
1002 OPT_GROUP(""),
1003 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1004 N_("pager"), N_("show matching files in the pager"),
1005 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
1006 NULL, (intptr_t)default_pager },
1007 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
1008 N_("allow calling of grep(1) (ignored by this build)"),
1009 PARSE_OPT_NOCOMPLETE),
1010 OPT_INTEGER('m', "max-count", &opt.max_count,
1011 N_("maximum number of results per file")),
1012 OPT_END()
1014 grep_prefix = prefix;
1016 grep_init(&opt, the_repository);
1017 git_config(grep_cmd_config, &opt);
1020 * If there is no -- then the paths must exist in the working
1021 * tree. If there is no explicit pattern specified with -e or
1022 * -f, we take the first unrecognized non option to be the
1023 * pattern, but then what follows it must be zero or more
1024 * valid refs up to the -- (if exists), and then existing
1025 * paths. If there is an explicit pattern, then the first
1026 * unrecognized non option is the beginning of the refs list
1027 * that continues up to the -- (if exists), and then paths.
1029 argc = parse_options(argc, argv, prefix, options, grep_usage,
1030 PARSE_OPT_KEEP_DASHDASH |
1031 PARSE_OPT_STOP_AT_NON_OPTION);
1033 if (the_repository->gitdir) {
1034 prepare_repo_settings(the_repository);
1035 the_repository->settings.command_requires_full_index = 0;
1038 if (use_index && !startup_info->have_repository) {
1039 int fallback = 0;
1040 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1041 if (fallback)
1042 use_index = 0;
1043 else
1044 /* die the same way as if we did it at the beginning */
1045 setup_git_directory();
1047 /* Ignore --recurse-submodules if --no-index is given or implied */
1048 if (!use_index)
1049 recurse_submodules = 0;
1052 * skip a -- separator; we know it cannot be
1053 * separating revisions from pathnames if
1054 * we haven't even had any patterns yet
1056 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1057 argv++;
1058 argc--;
1061 /* First unrecognized non-option token */
1062 if (argc > 0 && !opt.pattern_list) {
1063 append_grep_pattern(&opt, argv[0], "command line", 0,
1064 GREP_PATTERN);
1065 argv++;
1066 argc--;
1069 if (show_in_pager == default_pager)
1070 show_in_pager = git_pager(1);
1071 if (show_in_pager) {
1072 opt.color = 0;
1073 opt.name_only = 1;
1074 opt.null_following_name = 1;
1075 opt.output_priv = &path_list;
1076 opt.output = append_path;
1077 string_list_append(&path_list, show_in_pager);
1080 if (!opt.pattern_list)
1081 die(_("no pattern given"));
1083 /* --only-matching has no effect with --invert. */
1084 if (opt.invert)
1085 opt.only_matching = 0;
1088 * We have to find "--" in a separate pass, because its presence
1089 * influences how we will parse arguments that come before it.
1091 for (i = 0; i < argc; i++) {
1092 if (!strcmp(argv[i], "--")) {
1093 seen_dashdash = 1;
1094 break;
1099 * Resolve any rev arguments. If we have a dashdash, then everything up
1100 * to it must resolve as a rev. If not, then we stop at the first
1101 * non-rev and assume everything else is a path.
1103 allow_revs = use_index && !untracked;
1104 for (i = 0; i < argc; i++) {
1105 const char *arg = argv[i];
1106 struct object_id oid;
1107 struct object_context oc;
1108 struct object *object;
1110 if (!strcmp(arg, "--")) {
1111 i++;
1112 break;
1115 if (!allow_revs) {
1116 if (seen_dashdash)
1117 die(_("--no-index or --untracked cannot be used with revs"));
1118 break;
1121 if (get_oid_with_context(the_repository, arg,
1122 GET_OID_RECORD_PATH,
1123 &oid, &oc)) {
1124 if (seen_dashdash)
1125 die(_("unable to resolve revision: %s"), arg);
1126 break;
1129 object = parse_object_or_die(&oid, arg);
1130 if (!seen_dashdash)
1131 verify_non_filename(prefix, arg);
1132 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1133 free(oc.path);
1137 * Anything left over is presumed to be a path. But in the non-dashdash
1138 * "do what I mean" case, we verify and complain when that isn't true.
1140 if (!seen_dashdash) {
1141 int j;
1142 for (j = i; j < argc; j++)
1143 verify_filename(prefix, argv[j], j == i && allow_revs);
1146 parse_pathspec(&pathspec, 0,
1147 PATHSPEC_PREFER_CWD |
1148 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1149 prefix, argv + i);
1150 pathspec.max_depth = opt.max_depth;
1151 pathspec.recursive = 1;
1152 pathspec.recurse_submodules = !!recurse_submodules;
1154 if (recurse_submodules && untracked)
1155 die(_("--untracked not supported with --recurse-submodules"));
1158 * Optimize out the case where the amount of matches is limited to zero.
1159 * We do this to keep results consistent with GNU grep(1).
1161 if (opt.max_count == 0)
1162 return 1;
1164 if (show_in_pager) {
1165 if (num_threads > 1)
1166 warning(_("invalid option combination, ignoring --threads"));
1167 num_threads = 1;
1168 } else if (!HAVE_THREADS && num_threads > 1) {
1169 warning(_("no threads support, ignoring --threads"));
1170 num_threads = 1;
1171 } else if (num_threads < 0)
1172 die(_("invalid number of threads specified (%d)"), num_threads);
1173 else if (num_threads == 0)
1174 num_threads = HAVE_THREADS ? online_cpus() : 1;
1176 if (num_threads > 1) {
1177 if (!HAVE_THREADS)
1178 BUG("Somebody got num_threads calculation wrong!");
1179 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1180 && (opt.pre_context || opt.post_context ||
1181 opt.file_break || opt.funcbody))
1182 skip_first_line = 1;
1185 * Pre-read gitmodules (if not read already) and force eager
1186 * initialization of packed_git to prevent racy lazy
1187 * reading/initialization once worker threads are started.
1189 if (recurse_submodules)
1190 repo_read_gitmodules(the_repository, 1);
1191 if (startup_info->have_repository)
1192 (void)get_packed_git(the_repository);
1194 start_threads(&opt);
1195 } else {
1197 * The compiled patterns on the main path are only
1198 * used when not using threading. Otherwise
1199 * start_threads() above calls compile_grep_patterns()
1200 * for each thread.
1202 compile_grep_patterns(&opt);
1205 if (show_in_pager && (cached || list.nr))
1206 die(_("--open-files-in-pager only works on the worktree"));
1208 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1209 const char *pager = path_list.items[0].string;
1210 int len = strlen(pager);
1212 if (len > 4 && is_dir_sep(pager[len - 5]))
1213 pager += len - 4;
1215 if (opt.ignore_case && !strcmp("less", pager))
1216 string_list_append(&path_list, "-I");
1218 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1219 struct strbuf buf = STRBUF_INIT;
1220 strbuf_addf(&buf, "+/%s%s",
1221 strcmp("less", pager) ? "" : "*",
1222 opt.pattern_list->pattern);
1223 string_list_append_nodup(&path_list,
1224 strbuf_detach(&buf, NULL));
1228 if (!show_in_pager && !opt.status_only)
1229 setup_pager();
1231 die_for_incompatible_opt3(!use_index, "--no-index",
1232 untracked, "--untracked",
1233 cached, "--cached");
1235 if (!use_index || untracked) {
1236 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1237 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1238 } else if (0 <= opt_exclude) {
1239 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1240 } else if (!list.nr) {
1241 if (!cached)
1242 setup_work_tree();
1244 hit = grep_cache(&opt, &pathspec, cached);
1245 } else {
1246 if (cached)
1247 die(_("both --cached and trees are given"));
1249 hit = grep_objects(&opt, &pathspec, &list);
1252 if (num_threads > 1)
1253 hit |= wait_all();
1254 if (hit && show_in_pager)
1255 run_pager(&opt, prefix);
1256 clear_pathspec(&pathspec);
1257 string_list_clear(&path_list, 0);
1258 free_grep_patterns(&opt);
1259 object_array_clear(&list);
1260 free_repos();
1261 return !hit;