setup: extract function to create the refdb
[git/gitster.git] / builtin / grep.c
blobfe78d4c98b13b578a09de344d6a56d2316a8cb00
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "builtin.h"
7 #include "abspath.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 "parse-options.h"
18 #include "string-list.h"
19 #include "run-command.h"
20 #include "userdiff.h"
21 #include "grep.h"
22 #include "quote.h"
23 #include "dir.h"
24 #include "pathspec.h"
25 #include "setup.h"
26 #include "submodule.h"
27 #include "submodule-config.h"
28 #include "object-file.h"
29 #include "object-name.h"
30 #include "object-store-ll.h"
31 #include "packfile.h"
32 #include "pager.h"
33 #include "path.h"
34 #include "read-cache-ll.h"
35 #include "write-or-die.h"
37 static const char *grep_prefix;
39 static char const * const grep_usage[] = {
40 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
41 NULL
44 static int recurse_submodules;
46 static int num_threads;
48 static pthread_t *threads;
50 /* We use one producer thread and THREADS consumer
51 * threads. The producer adds struct work_items to 'todo' and the
52 * consumers pick work items from the same array.
54 struct work_item {
55 struct grep_source source;
56 char done;
57 struct strbuf out;
60 /* In the range [todo_done, todo_start) in 'todo' we have work_items
61 * that have been or are processed by a consumer thread. We haven't
62 * written the result for these to stdout yet.
64 * The work_items in [todo_start, todo_end) are waiting to be picked
65 * up by a consumer thread.
67 * The ranges are modulo TODO_SIZE.
69 #define TODO_SIZE 128
70 static struct work_item todo[TODO_SIZE];
71 static int todo_start;
72 static int todo_end;
73 static int todo_done;
75 /* Has all work items been added? */
76 static int all_work_added;
78 static struct repository **repos_to_free;
79 static size_t repos_to_free_nr, repos_to_free_alloc;
81 /* This lock protects all the variables above. */
82 static pthread_mutex_t grep_mutex;
84 static inline void grep_lock(void)
86 pthread_mutex_lock(&grep_mutex);
89 static inline void grep_unlock(void)
91 pthread_mutex_unlock(&grep_mutex);
94 /* Signalled when a new work_item is added to todo. */
95 static pthread_cond_t cond_add;
97 /* Signalled when the result from one work_item is written to
98 * stdout.
100 static pthread_cond_t cond_write;
102 /* Signalled when we are finished with everything. */
103 static pthread_cond_t cond_result;
105 static int skip_first_line;
107 static void add_work(struct grep_opt *opt, struct grep_source *gs)
109 if (opt->binary != GREP_BINARY_TEXT)
110 grep_source_load_driver(gs, opt->repo->index);
112 grep_lock();
114 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
115 pthread_cond_wait(&cond_write, &grep_mutex);
118 todo[todo_end].source = *gs;
119 todo[todo_end].done = 0;
120 strbuf_reset(&todo[todo_end].out);
121 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
123 pthread_cond_signal(&cond_add);
124 grep_unlock();
127 static struct work_item *get_work(void)
129 struct work_item *ret;
131 grep_lock();
132 while (todo_start == todo_end && !all_work_added) {
133 pthread_cond_wait(&cond_add, &grep_mutex);
136 if (todo_start == todo_end && all_work_added) {
137 ret = NULL;
138 } else {
139 ret = &todo[todo_start];
140 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
142 grep_unlock();
143 return ret;
146 static void work_done(struct work_item *w)
148 int old_done;
150 grep_lock();
151 w->done = 1;
152 old_done = todo_done;
153 for(; todo[todo_done].done && todo_done != todo_start;
154 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
155 w = &todo[todo_done];
156 if (w->out.len) {
157 const char *p = w->out.buf;
158 size_t len = w->out.len;
160 /* Skip the leading hunk mark of the first file. */
161 if (skip_first_line) {
162 while (len) {
163 len--;
164 if (*p++ == '\n')
165 break;
167 skip_first_line = 0;
170 write_or_die(1, p, len);
172 grep_source_clear(&w->source);
175 if (old_done != todo_done)
176 pthread_cond_signal(&cond_write);
178 if (all_work_added && todo_done == todo_end)
179 pthread_cond_signal(&cond_result);
181 grep_unlock();
184 static void free_repos(void)
186 int i;
188 for (i = 0; i < repos_to_free_nr; i++) {
189 repo_clear(repos_to_free[i]);
190 free(repos_to_free[i]);
192 FREE_AND_NULL(repos_to_free);
193 repos_to_free_nr = 0;
194 repos_to_free_alloc = 0;
197 static void *run(void *arg)
199 int hit = 0;
200 struct grep_opt *opt = arg;
202 while (1) {
203 struct work_item *w = get_work();
204 if (!w)
205 break;
207 opt->output_priv = w;
208 hit |= grep_source(opt, &w->source);
209 grep_source_clear_data(&w->source);
210 work_done(w);
212 free_grep_patterns(opt);
213 free(opt);
215 return (void*) (intptr_t) hit;
218 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
220 struct work_item *w = opt->output_priv;
221 strbuf_add(&w->out, buf, size);
224 static void start_threads(struct grep_opt *opt)
226 int i;
228 pthread_mutex_init(&grep_mutex, NULL);
229 pthread_mutex_init(&grep_attr_mutex, NULL);
230 pthread_cond_init(&cond_add, NULL);
231 pthread_cond_init(&cond_write, NULL);
232 pthread_cond_init(&cond_result, NULL);
233 grep_use_locks = 1;
234 enable_obj_read_lock();
236 for (i = 0; i < ARRAY_SIZE(todo); i++) {
237 strbuf_init(&todo[i].out, 0);
240 CALLOC_ARRAY(threads, num_threads);
241 for (i = 0; i < num_threads; i++) {
242 int err;
243 struct grep_opt *o = grep_opt_dup(opt);
244 o->output = strbuf_out;
245 compile_grep_patterns(o);
246 err = pthread_create(&threads[i], NULL, run, o);
248 if (err)
249 die(_("grep: failed to create thread: %s"),
250 strerror(err));
254 static int wait_all(void)
256 int hit = 0;
257 int i;
259 if (!HAVE_THREADS)
260 BUG("Never call this function unless you have started threads");
262 grep_lock();
263 all_work_added = 1;
265 /* Wait until all work is done. */
266 while (todo_done != todo_end)
267 pthread_cond_wait(&cond_result, &grep_mutex);
269 /* Wake up all the consumer threads so they can see that there
270 * is no more work to do.
272 pthread_cond_broadcast(&cond_add);
273 grep_unlock();
275 for (i = 0; i < num_threads; i++) {
276 void *h;
277 pthread_join(threads[i], &h);
278 hit |= (int) (intptr_t) h;
281 free(threads);
283 pthread_mutex_destroy(&grep_mutex);
284 pthread_mutex_destroy(&grep_attr_mutex);
285 pthread_cond_destroy(&cond_add);
286 pthread_cond_destroy(&cond_write);
287 pthread_cond_destroy(&cond_result);
288 grep_use_locks = 0;
289 disable_obj_read_lock();
291 return hit;
294 static int grep_cmd_config(const char *var, const char *value,
295 const struct config_context *ctx, void *cb)
297 int st = grep_config(var, value, ctx, cb);
299 if (git_color_config(var, value, cb) < 0)
300 st = -1;
301 else if (git_default_config(var, value, ctx, cb) < 0)
302 st = -1;
304 if (!strcmp(var, "grep.threads")) {
305 num_threads = git_config_int(var, value, ctx->kvi);
306 if (num_threads < 0)
307 die(_("invalid number of threads specified (%d) for %s"),
308 num_threads, var);
309 else if (!HAVE_THREADS && num_threads > 1) {
311 * TRANSLATORS: %s is the configuration
312 * variable for tweaking threads, currently
313 * grep.threads
315 warning(_("no threads support, ignoring %s"), var);
316 num_threads = 1;
320 if (!strcmp(var, "submodule.recurse"))
321 recurse_submodules = git_config_bool(var, value);
323 return st;
326 static void grep_source_name(struct grep_opt *opt, const char *filename,
327 int tree_name_len, struct strbuf *out)
329 strbuf_reset(out);
331 if (opt->null_following_name) {
332 if (opt->relative && grep_prefix) {
333 struct strbuf rel_buf = STRBUF_INIT;
334 const char *rel_name =
335 relative_path(filename + tree_name_len,
336 grep_prefix, &rel_buf);
338 if (tree_name_len)
339 strbuf_add(out, filename, tree_name_len);
341 strbuf_addstr(out, rel_name);
342 strbuf_release(&rel_buf);
343 } else {
344 strbuf_addstr(out, filename);
346 return;
349 if (opt->relative && grep_prefix)
350 quote_path(filename + tree_name_len, grep_prefix, out, 0);
351 else
352 quote_c_style(filename + tree_name_len, out, NULL, 0);
354 if (tree_name_len)
355 strbuf_insert(out, 0, filename, tree_name_len);
358 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
359 const char *filename, int tree_name_len,
360 const char *path)
362 struct strbuf pathbuf = STRBUF_INIT;
363 struct grep_source gs;
365 grep_source_name(opt, filename, tree_name_len, &pathbuf);
366 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
367 strbuf_release(&pathbuf);
369 if (num_threads > 1) {
371 * add_work() copies gs and thus assumes ownership of
372 * its fields, so do not call grep_source_clear()
374 add_work(opt, &gs);
375 return 0;
376 } else {
377 int hit;
379 hit = grep_source(opt, &gs);
381 grep_source_clear(&gs);
382 return hit;
386 static int grep_file(struct grep_opt *opt, const char *filename)
388 struct strbuf buf = STRBUF_INIT;
389 struct grep_source gs;
391 grep_source_name(opt, filename, 0, &buf);
392 grep_source_init_file(&gs, buf.buf, filename);
393 strbuf_release(&buf);
395 if (num_threads > 1) {
397 * add_work() copies gs and thus assumes ownership of
398 * its fields, so do not call grep_source_clear()
400 add_work(opt, &gs);
401 return 0;
402 } else {
403 int hit;
405 hit = grep_source(opt, &gs);
407 grep_source_clear(&gs);
408 return hit;
412 static void append_path(struct grep_opt *opt, const void *data, size_t len)
414 struct string_list *path_list = opt->output_priv;
416 if (len == 1 && *(const char *)data == '\0')
417 return;
418 string_list_append_nodup(path_list, xstrndup(data, len));
421 static void run_pager(struct grep_opt *opt, const char *prefix)
423 struct string_list *path_list = opt->output_priv;
424 struct child_process child = CHILD_PROCESS_INIT;
425 int i, status;
427 for (i = 0; i < path_list->nr; i++)
428 strvec_push(&child.args, path_list->items[i].string);
429 child.dir = prefix;
430 child.use_shell = 1;
432 status = run_command(&child);
433 if (status)
434 exit(status);
437 static int grep_cache(struct grep_opt *opt,
438 const struct pathspec *pathspec, int cached);
439 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
440 struct tree_desc *tree, struct strbuf *base, int tn_len,
441 int check_attr);
443 static int grep_submodule(struct grep_opt *opt,
444 const struct pathspec *pathspec,
445 const struct object_id *oid,
446 const char *filename, const char *path, int cached)
448 struct repository *subrepo;
449 struct repository *superproject = opt->repo;
450 struct grep_opt subopt;
451 int hit = 0;
453 if (!is_submodule_active(superproject, path))
454 return 0;
456 subrepo = xmalloc(sizeof(*subrepo));
457 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
458 free(subrepo);
459 return 0;
461 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
462 repos_to_free[repos_to_free_nr++] = subrepo;
465 * NEEDSWORK: repo_read_gitmodules() might call
466 * add_to_alternates_memory() via config_from_gitmodules(). This
467 * operation causes a race condition with concurrent object readings
468 * performed by the worker threads. That's why we need obj_read_lock()
469 * here. It should be removed once it's no longer necessary to add the
470 * subrepo's odbs to the in-memory alternates list.
472 obj_read_lock();
475 * NEEDSWORK: when reading a submodule, the sparsity settings in the
476 * superproject are incorrectly forgotten or misused. For example:
478 * 1. "command_requires_full_index"
479 * When this setting is turned on for `grep`, only the superproject
480 * knows it. All the submodules are read with their own configs
481 * and get prepare_repo_settings()'d. Therefore, these submodules
482 * "forget" the sparse-index feature switch. As a result, the index
483 * of these submodules are expanded unexpectedly.
485 * 2. "core_apply_sparse_checkout"
486 * When running `grep` in the superproject, this setting is
487 * populated using the superproject's configs. However, once
488 * initialized, this config is globally accessible and is read by
489 * prepare_repo_settings() for the submodules. For instance, if a
490 * submodule is using a sparse-checkout, however, the superproject
491 * is not, the result is that the config from the superproject will
492 * dictate the behavior for the submodule, making it "forget" its
493 * sparse-checkout state.
495 * 3. "core_sparse_checkout_cone"
496 * ditto.
498 * Note that this list is not exhaustive.
500 repo_read_gitmodules(subrepo, 0);
503 * All code paths tested by test code no longer need submodule ODBs to
504 * be added as alternates, but add it to the list just in case.
505 * Submodule ODBs added through add_submodule_odb_by_path() will be
506 * lazily registered as alternates when needed (and except in an
507 * unexpected code interaction, it won't be needed).
509 add_submodule_odb_by_path(subrepo->objects->odb->path);
510 obj_read_unlock();
512 memcpy(&subopt, opt, sizeof(subopt));
513 subopt.repo = subrepo;
515 if (oid) {
516 enum object_type object_type;
517 struct tree_desc tree;
518 void *data;
519 unsigned long size;
520 struct strbuf base = STRBUF_INIT;
522 obj_read_lock();
523 object_type = oid_object_info(subrepo, oid, NULL);
524 obj_read_unlock();
525 data = read_object_with_reference(subrepo,
526 oid, OBJ_TREE,
527 &size, NULL);
528 if (!data)
529 die(_("unable to read tree (%s)"), oid_to_hex(oid));
531 strbuf_addstr(&base, filename);
532 strbuf_addch(&base, '/');
534 init_tree_desc(&tree, data, size);
535 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
536 object_type == OBJ_COMMIT);
537 strbuf_release(&base);
538 free(data);
539 } else {
540 hit = grep_cache(&subopt, pathspec, cached);
543 return hit;
546 static int grep_cache(struct grep_opt *opt,
547 const struct pathspec *pathspec, int cached)
549 struct repository *repo = opt->repo;
550 int hit = 0;
551 int nr;
552 struct strbuf name = STRBUF_INIT;
553 int name_base_len = 0;
554 if (repo->submodule_prefix) {
555 name_base_len = strlen(repo->submodule_prefix);
556 strbuf_addstr(&name, repo->submodule_prefix);
559 if (repo_read_index(repo) < 0)
560 die(_("index file corrupt"));
562 for (nr = 0; nr < repo->index->cache_nr; nr++) {
563 const struct cache_entry *ce = repo->index->cache[nr];
565 if (!cached && ce_skip_worktree(ce))
566 continue;
568 strbuf_setlen(&name, name_base_len);
569 strbuf_addstr(&name, ce->name);
570 if (S_ISSPARSEDIR(ce->ce_mode)) {
571 enum object_type type;
572 struct tree_desc tree;
573 void *data;
574 unsigned long size;
576 data = repo_read_object_file(the_repository, &ce->oid,
577 &type, &size);
578 init_tree_desc(&tree, data, size);
580 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
581 strbuf_setlen(&name, name_base_len);
582 strbuf_addstr(&name, ce->name);
583 free(data);
584 } else if (S_ISREG(ce->ce_mode) &&
585 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
586 S_ISDIR(ce->ce_mode) ||
587 S_ISGITLINK(ce->ce_mode))) {
589 * If CE_VALID is on, we assume worktree file and its
590 * cache entry are identical, even if worktree file has
591 * been modified, so use cache version instead
593 if (cached || (ce->ce_flags & CE_VALID)) {
594 if (ce_stage(ce) || ce_intent_to_add(ce))
595 continue;
596 hit |= grep_oid(opt, &ce->oid, name.buf,
597 0, name.buf);
598 } else {
599 hit |= grep_file(opt, name.buf);
601 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
602 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
603 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
604 ce->name, cached);
605 } else {
606 continue;
609 if (ce_stage(ce)) {
610 do {
611 nr++;
612 } while (nr < repo->index->cache_nr &&
613 !strcmp(ce->name, repo->index->cache[nr]->name));
614 nr--; /* compensate for loop control */
616 if (hit && opt->status_only)
617 break;
620 strbuf_release(&name);
621 return hit;
624 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
625 struct tree_desc *tree, struct strbuf *base, int tn_len,
626 int check_attr)
628 struct repository *repo = opt->repo;
629 int hit = 0;
630 enum interesting match = entry_not_interesting;
631 struct name_entry entry;
632 int old_baselen = base->len;
633 struct strbuf name = STRBUF_INIT;
634 int name_base_len = 0;
635 if (repo->submodule_prefix) {
636 strbuf_addstr(&name, repo->submodule_prefix);
637 name_base_len = name.len;
640 while (tree_entry(tree, &entry)) {
641 int te_len = tree_entry_len(&entry);
643 if (match != all_entries_interesting) {
644 strbuf_addstr(&name, base->buf + tn_len);
645 match = tree_entry_interesting(repo->index,
646 &entry, &name,
647 pathspec);
648 strbuf_setlen(&name, name_base_len);
650 if (match == all_entries_not_interesting)
651 break;
652 if (match == entry_not_interesting)
653 continue;
656 strbuf_add(base, entry.path, te_len);
658 if (S_ISREG(entry.mode)) {
659 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
660 check_attr ? base->buf + tn_len : NULL);
661 } else if (S_ISDIR(entry.mode)) {
662 enum object_type type;
663 struct tree_desc sub;
664 void *data;
665 unsigned long size;
667 data = repo_read_object_file(the_repository,
668 &entry.oid, &type, &size);
669 if (!data)
670 die(_("unable to read tree (%s)"),
671 oid_to_hex(&entry.oid));
673 strbuf_addch(base, '/');
674 init_tree_desc(&sub, data, size);
675 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
676 check_attr);
677 free(data);
678 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
679 hit |= grep_submodule(opt, pathspec, &entry.oid,
680 base->buf, base->buf + tn_len,
681 1); /* ignored */
684 strbuf_setlen(base, old_baselen);
686 if (hit && opt->status_only)
687 break;
690 strbuf_release(&name);
691 return hit;
694 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
695 struct object *obj, const char *name, const char *path)
697 if (obj->type == OBJ_BLOB)
698 return grep_oid(opt, &obj->oid, name, 0, path);
699 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
700 struct tree_desc tree;
701 void *data;
702 unsigned long size;
703 struct strbuf base;
704 int hit, len;
706 data = read_object_with_reference(opt->repo,
707 &obj->oid, OBJ_TREE,
708 &size, NULL);
709 if (!data)
710 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
712 len = name ? strlen(name) : 0;
713 strbuf_init(&base, PATH_MAX + len + 1);
714 if (len) {
715 strbuf_add(&base, name, len);
716 strbuf_addch(&base, ':');
718 init_tree_desc(&tree, data, size);
719 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
720 obj->type == OBJ_COMMIT);
721 strbuf_release(&base);
722 free(data);
723 return hit;
725 die(_("unable to grep from object of type %s"), type_name(obj->type));
728 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
729 const struct object_array *list)
731 unsigned int i;
732 int hit = 0;
733 const unsigned int nr = list->nr;
735 for (i = 0; i < nr; i++) {
736 struct object *real_obj;
738 obj_read_lock();
739 real_obj = deref_tag(opt->repo, list->objects[i].item,
740 NULL, 0);
741 obj_read_unlock();
743 if (!real_obj) {
744 char hex[GIT_MAX_HEXSZ + 1];
745 const char *name = list->objects[i].name;
747 if (!name) {
748 oid_to_hex_r(hex, &list->objects[i].item->oid);
749 name = hex;
751 die(_("invalid object '%s' given."), name);
754 /* load the gitmodules file for this rev */
755 if (recurse_submodules) {
756 submodule_free(opt->repo);
757 obj_read_lock();
758 gitmodules_config_oid(&real_obj->oid);
759 obj_read_unlock();
761 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
762 list->objects[i].path)) {
763 hit = 1;
764 if (opt->status_only)
765 break;
768 return hit;
771 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
772 int exc_std, int use_index)
774 struct dir_struct dir = DIR_INIT;
775 int i, hit = 0;
777 if (!use_index)
778 dir.flags |= DIR_NO_GITLINKS;
779 if (exc_std)
780 setup_standard_excludes(&dir);
782 fill_directory(&dir, opt->repo->index, pathspec);
783 for (i = 0; i < dir.nr; i++) {
784 hit |= grep_file(opt, dir.entries[i]->name);
785 if (hit && opt->status_only)
786 break;
788 dir_clear(&dir);
789 return hit;
792 static int context_callback(const struct option *opt, const char *arg,
793 int unset)
795 struct grep_opt *grep_opt = opt->value;
796 int value;
797 const char *endp;
799 if (unset) {
800 grep_opt->pre_context = grep_opt->post_context = 0;
801 return 0;
803 value = strtol(arg, (char **)&endp, 10);
804 if (*endp) {
805 return error(_("switch `%c' expects a numerical value"),
806 opt->short_name);
808 grep_opt->pre_context = grep_opt->post_context = value;
809 return 0;
812 static int file_callback(const struct option *opt, const char *arg, int unset)
814 struct grep_opt *grep_opt = opt->value;
815 int from_stdin;
816 const char *filename = arg;
817 FILE *patterns;
818 int lno = 0;
819 struct strbuf sb = STRBUF_INIT;
821 BUG_ON_OPT_NEG(unset);
823 if (!*filename)
824 ; /* leave it as-is */
825 else
826 filename = prefix_filename_except_for_dash(grep_prefix, filename);
828 from_stdin = !strcmp(filename, "-");
829 patterns = from_stdin ? stdin : fopen(filename, "r");
830 if (!patterns)
831 die_errno(_("cannot open '%s'"), arg);
832 while (strbuf_getline(&sb, patterns) == 0) {
833 /* ignore empty line like grep does */
834 if (sb.len == 0)
835 continue;
837 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
838 GREP_PATTERN);
840 if (!from_stdin)
841 fclose(patterns);
842 strbuf_release(&sb);
843 if (filename != arg)
844 free((void *)filename);
845 return 0;
848 static int not_callback(const struct option *opt, const char *arg, int unset)
850 struct grep_opt *grep_opt = opt->value;
851 BUG_ON_OPT_NEG(unset);
852 BUG_ON_OPT_ARG(arg);
853 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
854 return 0;
857 static int and_callback(const struct option *opt, const char *arg, int unset)
859 struct grep_opt *grep_opt = opt->value;
860 BUG_ON_OPT_NEG(unset);
861 BUG_ON_OPT_ARG(arg);
862 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
863 return 0;
866 static int open_callback(const struct option *opt, const char *arg, int unset)
868 struct grep_opt *grep_opt = opt->value;
869 BUG_ON_OPT_NEG(unset);
870 BUG_ON_OPT_ARG(arg);
871 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
872 return 0;
875 static int close_callback(const struct option *opt, const char *arg, int unset)
877 struct grep_opt *grep_opt = opt->value;
878 BUG_ON_OPT_NEG(unset);
879 BUG_ON_OPT_ARG(arg);
880 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
881 return 0;
884 static int pattern_callback(const struct option *opt, const char *arg,
885 int unset)
887 struct grep_opt *grep_opt = opt->value;
888 BUG_ON_OPT_NEG(unset);
889 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
890 return 0;
893 int cmd_grep(int argc, const char **argv, const char *prefix)
895 int hit = 0;
896 int cached = 0, untracked = 0, opt_exclude = -1;
897 int seen_dashdash = 0;
898 int external_grep_allowed__ignored;
899 const char *show_in_pager = NULL, *default_pager = "dummy";
900 struct grep_opt opt;
901 struct object_array list = OBJECT_ARRAY_INIT;
902 struct pathspec pathspec;
903 struct string_list path_list = STRING_LIST_INIT_DUP;
904 int i;
905 int dummy;
906 int use_index = 1;
907 int allow_revs;
909 struct option options[] = {
910 OPT_BOOL(0, "cached", &cached,
911 N_("search in index instead of in the work tree")),
912 OPT_NEGBIT(0, "no-index", &use_index,
913 N_("find in contents not managed by git"), 1),
914 OPT_BOOL(0, "untracked", &untracked,
915 N_("search in both tracked and untracked files")),
916 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
917 N_("ignore files specified via '.gitignore'"), 1),
918 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
919 N_("recursively search in each submodule")),
920 OPT_GROUP(""),
921 OPT_BOOL('v', "invert-match", &opt.invert,
922 N_("show non-matching lines")),
923 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
924 N_("case insensitive matching")),
925 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
926 N_("match patterns only at word boundaries")),
927 OPT_SET_INT('a', "text", &opt.binary,
928 N_("process binary files as text"), GREP_BINARY_TEXT),
929 OPT_SET_INT('I', NULL, &opt.binary,
930 N_("don't match patterns in binary files"),
931 GREP_BINARY_NOMATCH),
932 OPT_BOOL(0, "textconv", &opt.allow_textconv,
933 N_("process binary files with textconv filters")),
934 OPT_SET_INT('r', "recursive", &opt.max_depth,
935 N_("search in subdirectories (default)"), -1),
936 OPT_INTEGER_F(0, "max-depth", &opt.max_depth,
937 N_("descend at most <n> levels"), PARSE_OPT_NONEG),
938 OPT_GROUP(""),
939 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
940 N_("use extended POSIX regular expressions"),
941 GREP_PATTERN_TYPE_ERE),
942 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
943 N_("use basic POSIX regular expressions (default)"),
944 GREP_PATTERN_TYPE_BRE),
945 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
946 N_("interpret patterns as fixed strings"),
947 GREP_PATTERN_TYPE_FIXED),
948 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
949 N_("use Perl-compatible regular expressions"),
950 GREP_PATTERN_TYPE_PCRE),
951 OPT_GROUP(""),
952 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
953 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
954 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
955 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
956 OPT_NEGBIT(0, "full-name", &opt.relative,
957 N_("show filenames relative to top directory"), 1),
958 OPT_BOOL('l', "files-with-matches", &opt.name_only,
959 N_("show only filenames instead of matching lines")),
960 OPT_BOOL(0, "name-only", &opt.name_only,
961 N_("synonym for --files-with-matches")),
962 OPT_BOOL('L', "files-without-match",
963 &opt.unmatch_name_only,
964 N_("show only the names of files without match")),
965 OPT_BOOL_F('z', "null", &opt.null_following_name,
966 N_("print NUL after filenames"),
967 PARSE_OPT_NOCOMPLETE),
968 OPT_BOOL('o', "only-matching", &opt.only_matching,
969 N_("show only matching parts of a line")),
970 OPT_BOOL('c', "count", &opt.count,
971 N_("show the number of matches instead of matching lines")),
972 OPT__COLOR(&opt.color, N_("highlight matches")),
973 OPT_BOOL(0, "break", &opt.file_break,
974 N_("print empty line between matches from different files")),
975 OPT_BOOL(0, "heading", &opt.heading,
976 N_("show filename only once above matches from same file")),
977 OPT_GROUP(""),
978 OPT_CALLBACK('C', "context", &opt, N_("n"),
979 N_("show <n> context lines before and after matches"),
980 context_callback),
981 OPT_INTEGER('B', "before-context", &opt.pre_context,
982 N_("show <n> context lines before matches")),
983 OPT_INTEGER('A', "after-context", &opt.post_context,
984 N_("show <n> context lines after matches")),
985 OPT_INTEGER(0, "threads", &num_threads,
986 N_("use <n> worker threads")),
987 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
988 context_callback),
989 OPT_BOOL('p', "show-function", &opt.funcname,
990 N_("show a line with the function name before matches")),
991 OPT_BOOL('W', "function-context", &opt.funcbody,
992 N_("show the surrounding function")),
993 OPT_GROUP(""),
994 OPT_CALLBACK('f', NULL, &opt, N_("file"),
995 N_("read patterns from file"), file_callback),
996 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
997 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
998 OPT_CALLBACK_F(0, "and", &opt, NULL,
999 N_("combine patterns specified with -e"),
1000 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
1001 OPT_BOOL_F(0, "or", &dummy, "", PARSE_OPT_NONEG),
1002 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
1003 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
1004 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
1005 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1006 open_callback),
1007 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
1008 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1009 close_callback),
1010 OPT__QUIET(&opt.status_only,
1011 N_("indicate hit with exit status without output")),
1012 OPT_BOOL(0, "all-match", &opt.all_match,
1013 N_("show only matches from files that match all patterns")),
1014 OPT_GROUP(""),
1015 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1016 N_("pager"), N_("show matching files in the pager"),
1017 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
1018 NULL, (intptr_t)default_pager },
1019 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
1020 N_("allow calling of grep(1) (ignored by this build)"),
1021 PARSE_OPT_NOCOMPLETE),
1022 OPT_INTEGER('m', "max-count", &opt.max_count,
1023 N_("maximum number of results per file")),
1024 OPT_END()
1026 grep_prefix = prefix;
1028 grep_init(&opt, the_repository);
1029 git_config(grep_cmd_config, &opt);
1032 * If there is no -- then the paths must exist in the working
1033 * tree. If there is no explicit pattern specified with -e or
1034 * -f, we take the first unrecognized non option to be the
1035 * pattern, but then what follows it must be zero or more
1036 * valid refs up to the -- (if exists), and then existing
1037 * paths. If there is an explicit pattern, then the first
1038 * unrecognized non option is the beginning of the refs list
1039 * that continues up to the -- (if exists), and then paths.
1041 argc = parse_options(argc, argv, prefix, options, grep_usage,
1042 PARSE_OPT_KEEP_DASHDASH |
1043 PARSE_OPT_STOP_AT_NON_OPTION);
1045 if (the_repository->gitdir) {
1046 prepare_repo_settings(the_repository);
1047 the_repository->settings.command_requires_full_index = 0;
1050 if (use_index && !startup_info->have_repository) {
1051 int fallback = 0;
1052 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1053 if (fallback)
1054 use_index = 0;
1055 else
1056 /* die the same way as if we did it at the beginning */
1057 setup_git_directory();
1059 /* Ignore --recurse-submodules if --no-index is given or implied */
1060 if (!use_index)
1061 recurse_submodules = 0;
1064 * skip a -- separator; we know it cannot be
1065 * separating revisions from pathnames if
1066 * we haven't even had any patterns yet
1068 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1069 argv++;
1070 argc--;
1073 /* First unrecognized non-option token */
1074 if (argc > 0 && !opt.pattern_list) {
1075 append_grep_pattern(&opt, argv[0], "command line", 0,
1076 GREP_PATTERN);
1077 argv++;
1078 argc--;
1081 if (show_in_pager == default_pager)
1082 show_in_pager = git_pager(1);
1083 if (show_in_pager) {
1084 opt.color = 0;
1085 opt.name_only = 1;
1086 opt.null_following_name = 1;
1087 opt.output_priv = &path_list;
1088 opt.output = append_path;
1089 string_list_append(&path_list, show_in_pager);
1092 if (!opt.pattern_list)
1093 die(_("no pattern given"));
1095 /* --only-matching has no effect with --invert. */
1096 if (opt.invert)
1097 opt.only_matching = 0;
1100 * We have to find "--" in a separate pass, because its presence
1101 * influences how we will parse arguments that come before it.
1103 for (i = 0; i < argc; i++) {
1104 if (!strcmp(argv[i], "--")) {
1105 seen_dashdash = 1;
1106 break;
1111 * Resolve any rev arguments. If we have a dashdash, then everything up
1112 * to it must resolve as a rev. If not, then we stop at the first
1113 * non-rev and assume everything else is a path.
1115 allow_revs = use_index && !untracked;
1116 for (i = 0; i < argc; i++) {
1117 const char *arg = argv[i];
1118 struct object_id oid;
1119 struct object_context oc;
1120 struct object *object;
1122 if (!strcmp(arg, "--")) {
1123 i++;
1124 break;
1127 if (!allow_revs) {
1128 if (seen_dashdash)
1129 die(_("--no-index or --untracked cannot be used with revs"));
1130 break;
1133 if (get_oid_with_context(the_repository, arg,
1134 GET_OID_RECORD_PATH,
1135 &oid, &oc)) {
1136 if (seen_dashdash)
1137 die(_("unable to resolve revision: %s"), arg);
1138 break;
1141 object = parse_object_or_die(&oid, arg);
1142 if (!seen_dashdash)
1143 verify_non_filename(prefix, arg);
1144 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1145 free(oc.path);
1149 * Anything left over is presumed to be a path. But in the non-dashdash
1150 * "do what I mean" case, we verify and complain when that isn't true.
1152 if (!seen_dashdash) {
1153 int j;
1154 for (j = i; j < argc; j++)
1155 verify_filename(prefix, argv[j], j == i && allow_revs);
1158 parse_pathspec(&pathspec, 0,
1159 PATHSPEC_PREFER_CWD |
1160 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1161 prefix, argv + i);
1162 pathspec.max_depth = opt.max_depth;
1163 pathspec.recursive = 1;
1164 pathspec.recurse_submodules = !!recurse_submodules;
1166 if (recurse_submodules && untracked)
1167 die(_("--untracked not supported with --recurse-submodules"));
1170 * Optimize out the case where the amount of matches is limited to zero.
1171 * We do this to keep results consistent with GNU grep(1).
1173 if (opt.max_count == 0)
1174 return 1;
1176 if (show_in_pager) {
1177 if (num_threads > 1)
1178 warning(_("invalid option combination, ignoring --threads"));
1179 num_threads = 1;
1180 } else if (!HAVE_THREADS && num_threads > 1) {
1181 warning(_("no threads support, ignoring --threads"));
1182 num_threads = 1;
1183 } else if (num_threads < 0)
1184 die(_("invalid number of threads specified (%d)"), num_threads);
1185 else if (num_threads == 0)
1186 num_threads = HAVE_THREADS ? online_cpus() : 1;
1188 if (num_threads > 1) {
1189 if (!HAVE_THREADS)
1190 BUG("Somebody got num_threads calculation wrong!");
1191 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1192 && (opt.pre_context || opt.post_context ||
1193 opt.file_break || opt.funcbody))
1194 skip_first_line = 1;
1197 * Pre-read gitmodules (if not read already) and force eager
1198 * initialization of packed_git to prevent racy lazy
1199 * reading/initialization once worker threads are started.
1201 if (recurse_submodules)
1202 repo_read_gitmodules(the_repository, 1);
1203 if (startup_info->have_repository)
1204 (void)get_packed_git(the_repository);
1206 start_threads(&opt);
1207 } else {
1209 * The compiled patterns on the main path are only
1210 * used when not using threading. Otherwise
1211 * start_threads() above calls compile_grep_patterns()
1212 * for each thread.
1214 compile_grep_patterns(&opt);
1217 if (show_in_pager && (cached || list.nr))
1218 die(_("--open-files-in-pager only works on the worktree"));
1220 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1221 const char *pager = path_list.items[0].string;
1222 int len = strlen(pager);
1224 if (len > 4 && is_dir_sep(pager[len - 5]))
1225 pager += len - 4;
1227 if (opt.ignore_case && !strcmp("less", pager))
1228 string_list_append(&path_list, "-I");
1230 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1231 struct strbuf buf = STRBUF_INIT;
1232 strbuf_addf(&buf, "+/%s%s",
1233 strcmp("less", pager) ? "" : "*",
1234 opt.pattern_list->pattern);
1235 string_list_append_nodup(&path_list,
1236 strbuf_detach(&buf, NULL));
1240 if (!show_in_pager && !opt.status_only)
1241 setup_pager();
1243 die_for_incompatible_opt3(!use_index, "--no-index",
1244 untracked, "--untracked",
1245 cached, "--cached");
1247 if (!use_index || untracked) {
1248 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1249 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1250 } else if (0 <= opt_exclude) {
1251 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1252 } else if (!list.nr) {
1253 if (!cached)
1254 setup_work_tree();
1256 hit = grep_cache(&opt, &pathspec, cached);
1257 } else {
1258 if (cached)
1259 die(_("both --cached and trees are given"));
1261 hit = grep_objects(&opt, &pathspec, &list);
1264 if (num_threads > 1)
1265 hit |= wait_all();
1266 if (hit && show_in_pager)
1267 run_pager(&opt, prefix);
1268 clear_pathspec(&pathspec);
1269 string_list_clear(&path_list, 0);
1270 free_grep_patterns(&opt);
1271 object_array_clear(&list);
1272 free_repos();
1273 return !hit;