t5312: test non-destructive repack
[git/gitster.git] / builtin / grep.c
blob51278b01fa273fbad1d01430dbb26c9c66fda41c
1 /*
2 * Builtin "git grep"
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
7 #include "cache.h"
8 #include "repository.h"
9 #include "config.h"
10 #include "blob.h"
11 #include "tree.h"
12 #include "commit.h"
13 #include "tag.h"
14 #include "tree-walk.h"
15 #include "builtin.h"
16 #include "parse-options.h"
17 #include "string-list.h"
18 #include "run-command.h"
19 #include "userdiff.h"
20 #include "grep.h"
21 #include "quote.h"
22 #include "dir.h"
23 #include "pathspec.h"
24 #include "submodule.h"
25 #include "submodule-config.h"
26 #include "object-store.h"
27 #include "packfile.h"
29 static char const * const grep_usage[] = {
30 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
31 NULL
34 static int recurse_submodules;
36 static int num_threads;
38 static pthread_t *threads;
40 /* We use one producer thread and THREADS consumer
41 * threads. The producer adds struct work_items to 'todo' and the
42 * consumers pick work items from the same array.
44 struct work_item {
45 struct grep_source source;
46 char done;
47 struct strbuf out;
50 /* In the range [todo_done, todo_start) in 'todo' we have work_items
51 * that have been or are processed by a consumer thread. We haven't
52 * written the result for these to stdout yet.
54 * The work_items in [todo_start, todo_end) are waiting to be picked
55 * up by a consumer thread.
57 * The ranges are modulo TODO_SIZE.
59 #define TODO_SIZE 128
60 static struct work_item todo[TODO_SIZE];
61 static int todo_start;
62 static int todo_end;
63 static int todo_done;
65 /* Has all work items been added? */
66 static int all_work_added;
68 static struct repository **repos_to_free;
69 static size_t repos_to_free_nr, repos_to_free_alloc;
71 /* This lock protects all the variables above. */
72 static pthread_mutex_t grep_mutex;
74 static inline void grep_lock(void)
76 pthread_mutex_lock(&grep_mutex);
79 static inline void grep_unlock(void)
81 pthread_mutex_unlock(&grep_mutex);
84 /* Signalled when a new work_item is added to todo. */
85 static pthread_cond_t cond_add;
87 /* Signalled when the result from one work_item is written to
88 * stdout.
90 static pthread_cond_t cond_write;
92 /* Signalled when we are finished with everything. */
93 static pthread_cond_t cond_result;
95 static int skip_first_line;
97 static void add_work(struct grep_opt *opt, struct grep_source *gs)
99 if (opt->binary != GREP_BINARY_TEXT)
100 grep_source_load_driver(gs, opt->repo->index);
102 grep_lock();
104 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105 pthread_cond_wait(&cond_write, &grep_mutex);
108 todo[todo_end].source = *gs;
109 todo[todo_end].done = 0;
110 strbuf_reset(&todo[todo_end].out);
111 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
113 pthread_cond_signal(&cond_add);
114 grep_unlock();
117 static struct work_item *get_work(void)
119 struct work_item *ret;
121 grep_lock();
122 while (todo_start == todo_end && !all_work_added) {
123 pthread_cond_wait(&cond_add, &grep_mutex);
126 if (todo_start == todo_end && all_work_added) {
127 ret = NULL;
128 } else {
129 ret = &todo[todo_start];
130 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
132 grep_unlock();
133 return ret;
136 static void work_done(struct work_item *w)
138 int old_done;
140 grep_lock();
141 w->done = 1;
142 old_done = todo_done;
143 for(; todo[todo_done].done && todo_done != todo_start;
144 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
145 w = &todo[todo_done];
146 if (w->out.len) {
147 const char *p = w->out.buf;
148 size_t len = w->out.len;
150 /* Skip the leading hunk mark of the first file. */
151 if (skip_first_line) {
152 while (len) {
153 len--;
154 if (*p++ == '\n')
155 break;
157 skip_first_line = 0;
160 write_or_die(1, p, len);
162 grep_source_clear(&w->source);
165 if (old_done != todo_done)
166 pthread_cond_signal(&cond_write);
168 if (all_work_added && todo_done == todo_end)
169 pthread_cond_signal(&cond_result);
171 grep_unlock();
174 static void free_repos(void)
176 int i;
178 for (i = 0; i < repos_to_free_nr; i++) {
179 repo_clear(repos_to_free[i]);
180 free(repos_to_free[i]);
182 FREE_AND_NULL(repos_to_free);
183 repos_to_free_nr = 0;
184 repos_to_free_alloc = 0;
187 static void *run(void *arg)
189 int hit = 0;
190 struct grep_opt *opt = arg;
192 while (1) {
193 struct work_item *w = get_work();
194 if (!w)
195 break;
197 opt->output_priv = w;
198 hit |= grep_source(opt, &w->source);
199 grep_source_clear_data(&w->source);
200 work_done(w);
202 free_grep_patterns(arg);
203 free(arg);
205 return (void*) (intptr_t) hit;
208 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
210 struct work_item *w = opt->output_priv;
211 strbuf_add(&w->out, buf, size);
214 static void start_threads(struct grep_opt *opt)
216 int i;
218 pthread_mutex_init(&grep_mutex, NULL);
219 pthread_mutex_init(&grep_attr_mutex, NULL);
220 pthread_cond_init(&cond_add, NULL);
221 pthread_cond_init(&cond_write, NULL);
222 pthread_cond_init(&cond_result, NULL);
223 grep_use_locks = 1;
224 enable_obj_read_lock();
226 for (i = 0; i < ARRAY_SIZE(todo); i++) {
227 strbuf_init(&todo[i].out, 0);
230 CALLOC_ARRAY(threads, num_threads);
231 for (i = 0; i < num_threads; i++) {
232 int err;
233 struct grep_opt *o = grep_opt_dup(opt);
234 o->output = strbuf_out;
235 compile_grep_patterns(o);
236 err = pthread_create(&threads[i], NULL, run, o);
238 if (err)
239 die(_("grep: failed to create thread: %s"),
240 strerror(err));
244 static int wait_all(void)
246 int hit = 0;
247 int i;
249 if (!HAVE_THREADS)
250 BUG("Never call this function unless you have started threads");
252 grep_lock();
253 all_work_added = 1;
255 /* Wait until all work is done. */
256 while (todo_done != todo_end)
257 pthread_cond_wait(&cond_result, &grep_mutex);
259 /* Wake up all the consumer threads so they can see that there
260 * is no more work to do.
262 pthread_cond_broadcast(&cond_add);
263 grep_unlock();
265 for (i = 0; i < num_threads; i++) {
266 void *h;
267 pthread_join(threads[i], &h);
268 hit |= (int) (intptr_t) h;
271 free(threads);
273 pthread_mutex_destroy(&grep_mutex);
274 pthread_mutex_destroy(&grep_attr_mutex);
275 pthread_cond_destroy(&cond_add);
276 pthread_cond_destroy(&cond_write);
277 pthread_cond_destroy(&cond_result);
278 grep_use_locks = 0;
279 disable_obj_read_lock();
281 return hit;
284 static int grep_cmd_config(const char *var, const char *value, void *cb)
286 int st = grep_config(var, value, cb);
287 if (git_color_default_config(var, value, cb) < 0)
288 st = -1;
290 if (!strcmp(var, "grep.threads")) {
291 num_threads = git_config_int(var, value);
292 if (num_threads < 0)
293 die(_("invalid number of threads specified (%d) for %s"),
294 num_threads, var);
295 else if (!HAVE_THREADS && num_threads > 1) {
297 * TRANSLATORS: %s is the configuration
298 * variable for tweaking threads, currently
299 * grep.threads
301 warning(_("no threads support, ignoring %s"), var);
302 num_threads = 1;
306 if (!strcmp(var, "submodule.recurse"))
307 recurse_submodules = git_config_bool(var, value);
309 return st;
312 static void grep_source_name(struct grep_opt *opt, const char *filename,
313 int tree_name_len, struct strbuf *out)
315 strbuf_reset(out);
317 if (opt->null_following_name) {
318 if (opt->relative && opt->prefix_length) {
319 struct strbuf rel_buf = STRBUF_INIT;
320 const char *rel_name =
321 relative_path(filename + tree_name_len,
322 opt->prefix, &rel_buf);
324 if (tree_name_len)
325 strbuf_add(out, filename, tree_name_len);
327 strbuf_addstr(out, rel_name);
328 strbuf_release(&rel_buf);
329 } else {
330 strbuf_addstr(out, filename);
332 return;
335 if (opt->relative && opt->prefix_length)
336 quote_path(filename + tree_name_len, opt->prefix, out, 0);
337 else
338 quote_c_style(filename + tree_name_len, out, NULL, 0);
340 if (tree_name_len)
341 strbuf_insert(out, 0, filename, tree_name_len);
344 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
345 const char *filename, int tree_name_len,
346 const char *path)
348 struct strbuf pathbuf = STRBUF_INIT;
349 struct grep_source gs;
351 grep_source_name(opt, filename, tree_name_len, &pathbuf);
352 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
353 strbuf_release(&pathbuf);
355 if (num_threads > 1) {
357 * add_work() copies gs and thus assumes ownership of
358 * its fields, so do not call grep_source_clear()
360 add_work(opt, &gs);
361 return 0;
362 } else {
363 int hit;
365 hit = grep_source(opt, &gs);
367 grep_source_clear(&gs);
368 return hit;
372 static int grep_file(struct grep_opt *opt, const char *filename)
374 struct strbuf buf = STRBUF_INIT;
375 struct grep_source gs;
377 grep_source_name(opt, filename, 0, &buf);
378 grep_source_init_file(&gs, buf.buf, filename);
379 strbuf_release(&buf);
381 if (num_threads > 1) {
383 * add_work() copies gs and thus assumes ownership of
384 * its fields, so do not call grep_source_clear()
386 add_work(opt, &gs);
387 return 0;
388 } else {
389 int hit;
391 hit = grep_source(opt, &gs);
393 grep_source_clear(&gs);
394 return hit;
398 static void append_path(struct grep_opt *opt, const void *data, size_t len)
400 struct string_list *path_list = opt->output_priv;
402 if (len == 1 && *(const char *)data == '\0')
403 return;
404 string_list_append(path_list, xstrndup(data, len));
407 static void run_pager(struct grep_opt *opt, const char *prefix)
409 struct string_list *path_list = opt->output_priv;
410 struct child_process child = CHILD_PROCESS_INIT;
411 int i, status;
413 for (i = 0; i < path_list->nr; i++)
414 strvec_push(&child.args, path_list->items[i].string);
415 child.dir = prefix;
416 child.use_shell = 1;
418 status = run_command(&child);
419 if (status)
420 exit(status);
423 static int grep_cache(struct grep_opt *opt,
424 const struct pathspec *pathspec, int cached);
425 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
426 struct tree_desc *tree, struct strbuf *base, int tn_len,
427 int check_attr);
429 static int grep_submodule(struct grep_opt *opt,
430 const struct pathspec *pathspec,
431 const struct object_id *oid,
432 const char *filename, const char *path, int cached)
434 struct repository *subrepo;
435 struct repository *superproject = opt->repo;
436 const struct submodule *sub;
437 struct grep_opt subopt;
438 int hit = 0;
440 sub = submodule_from_path(superproject, null_oid(), path);
442 if (!is_submodule_active(superproject, path))
443 return 0;
445 subrepo = xmalloc(sizeof(*subrepo));
446 if (repo_submodule_init(subrepo, superproject, sub)) {
447 free(subrepo);
448 return 0;
450 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
451 repos_to_free[repos_to_free_nr++] = subrepo;
454 * NEEDSWORK: repo_read_gitmodules() might call
455 * add_to_alternates_memory() via config_from_gitmodules(). This
456 * operation causes a race condition with concurrent object readings
457 * performed by the worker threads. That's why we need obj_read_lock()
458 * here. It should be removed once it's no longer necessary to add the
459 * subrepo's odbs to the in-memory alternates list.
461 obj_read_lock();
462 repo_read_gitmodules(subrepo, 0);
465 * All code paths tested by test code no longer need submodule ODBs to
466 * be added as alternates, but add it to the list just in case.
467 * Submodule ODBs added through add_submodule_odb_by_path() will be
468 * lazily registered as alternates when needed (and except in an
469 * unexpected code interaction, it won't be needed).
471 add_submodule_odb_by_path(subrepo->objects->odb->path);
472 obj_read_unlock();
474 memcpy(&subopt, opt, sizeof(subopt));
475 subopt.repo = subrepo;
477 if (oid) {
478 enum object_type object_type;
479 struct tree_desc tree;
480 void *data;
481 unsigned long size;
482 struct strbuf base = STRBUF_INIT;
484 obj_read_lock();
485 object_type = oid_object_info(subrepo, oid, NULL);
486 obj_read_unlock();
487 data = read_object_with_reference(subrepo,
488 oid, tree_type,
489 &size, NULL);
490 if (!data)
491 die(_("unable to read tree (%s)"), oid_to_hex(oid));
493 strbuf_addstr(&base, filename);
494 strbuf_addch(&base, '/');
496 init_tree_desc(&tree, data, size);
497 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
498 object_type == OBJ_COMMIT);
499 strbuf_release(&base);
500 free(data);
501 } else {
502 hit = grep_cache(&subopt, pathspec, cached);
505 return hit;
508 static int grep_cache(struct grep_opt *opt,
509 const struct pathspec *pathspec, int cached)
511 struct repository *repo = opt->repo;
512 int hit = 0;
513 int nr;
514 struct strbuf name = STRBUF_INIT;
515 int name_base_len = 0;
516 if (repo->submodule_prefix) {
517 name_base_len = strlen(repo->submodule_prefix);
518 strbuf_addstr(&name, repo->submodule_prefix);
521 if (repo_read_index(repo) < 0)
522 die(_("index file corrupt"));
524 /* TODO: audit for interaction with sparse-index. */
525 ensure_full_index(repo->index);
526 for (nr = 0; nr < repo->index->cache_nr; nr++) {
527 const struct cache_entry *ce = repo->index->cache[nr];
529 if (!cached && ce_skip_worktree(ce))
530 continue;
532 strbuf_setlen(&name, name_base_len);
533 strbuf_addstr(&name, ce->name);
535 if (S_ISREG(ce->ce_mode) &&
536 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
537 S_ISDIR(ce->ce_mode) ||
538 S_ISGITLINK(ce->ce_mode))) {
540 * If CE_VALID is on, we assume worktree file and its
541 * cache entry are identical, even if worktree file has
542 * been modified, so use cache version instead
544 if (cached || (ce->ce_flags & CE_VALID)) {
545 if (ce_stage(ce) || ce_intent_to_add(ce))
546 continue;
547 hit |= grep_oid(opt, &ce->oid, name.buf,
548 0, name.buf);
549 } else {
550 hit |= grep_file(opt, name.buf);
552 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
553 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
554 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
555 ce->name, cached);
556 } else {
557 continue;
560 if (ce_stage(ce)) {
561 do {
562 nr++;
563 } while (nr < repo->index->cache_nr &&
564 !strcmp(ce->name, repo->index->cache[nr]->name));
565 nr--; /* compensate for loop control */
567 if (hit && opt->status_only)
568 break;
571 strbuf_release(&name);
572 return hit;
575 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
576 struct tree_desc *tree, struct strbuf *base, int tn_len,
577 int check_attr)
579 struct repository *repo = opt->repo;
580 int hit = 0;
581 enum interesting match = entry_not_interesting;
582 struct name_entry entry;
583 int old_baselen = base->len;
584 struct strbuf name = STRBUF_INIT;
585 int name_base_len = 0;
586 if (repo->submodule_prefix) {
587 strbuf_addstr(&name, repo->submodule_prefix);
588 name_base_len = name.len;
591 while (tree_entry(tree, &entry)) {
592 int te_len = tree_entry_len(&entry);
594 if (match != all_entries_interesting) {
595 strbuf_addstr(&name, base->buf + tn_len);
596 match = tree_entry_interesting(repo->index,
597 &entry, &name,
598 0, pathspec);
599 strbuf_setlen(&name, name_base_len);
601 if (match == all_entries_not_interesting)
602 break;
603 if (match == entry_not_interesting)
604 continue;
607 strbuf_add(base, entry.path, te_len);
609 if (S_ISREG(entry.mode)) {
610 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
611 check_attr ? base->buf + tn_len : NULL);
612 } else if (S_ISDIR(entry.mode)) {
613 enum object_type type;
614 struct tree_desc sub;
615 void *data;
616 unsigned long size;
618 data = read_object_file(&entry.oid, &type, &size);
619 if (!data)
620 die(_("unable to read tree (%s)"),
621 oid_to_hex(&entry.oid));
623 strbuf_addch(base, '/');
624 init_tree_desc(&sub, data, size);
625 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
626 check_attr);
627 free(data);
628 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
629 hit |= grep_submodule(opt, pathspec, &entry.oid,
630 base->buf, base->buf + tn_len,
631 1); /* ignored */
634 strbuf_setlen(base, old_baselen);
636 if (hit && opt->status_only)
637 break;
640 strbuf_release(&name);
641 return hit;
644 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
645 struct object *obj, const char *name, const char *path)
647 if (obj->type == OBJ_BLOB)
648 return grep_oid(opt, &obj->oid, name, 0, path);
649 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
650 struct tree_desc tree;
651 void *data;
652 unsigned long size;
653 struct strbuf base;
654 int hit, len;
656 data = read_object_with_reference(opt->repo,
657 &obj->oid, tree_type,
658 &size, NULL);
659 if (!data)
660 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
662 len = name ? strlen(name) : 0;
663 strbuf_init(&base, PATH_MAX + len + 1);
664 if (len) {
665 strbuf_add(&base, name, len);
666 strbuf_addch(&base, ':');
668 init_tree_desc(&tree, data, size);
669 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
670 obj->type == OBJ_COMMIT);
671 strbuf_release(&base);
672 free(data);
673 return hit;
675 die(_("unable to grep from object of type %s"), type_name(obj->type));
678 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
679 const struct object_array *list)
681 unsigned int i;
682 int hit = 0;
683 const unsigned int nr = list->nr;
685 for (i = 0; i < nr; i++) {
686 struct object *real_obj;
688 obj_read_lock();
689 real_obj = deref_tag(opt->repo, list->objects[i].item,
690 NULL, 0);
691 obj_read_unlock();
693 if (!real_obj) {
694 char hex[GIT_MAX_HEXSZ + 1];
695 const char *name = list->objects[i].name;
697 if (!name) {
698 oid_to_hex_r(hex, &list->objects[i].item->oid);
699 name = hex;
701 die(_("invalid object '%s' given."), name);
704 /* load the gitmodules file for this rev */
705 if (recurse_submodules) {
706 submodule_free(opt->repo);
707 obj_read_lock();
708 gitmodules_config_oid(&real_obj->oid);
709 obj_read_unlock();
711 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
712 list->objects[i].path)) {
713 hit = 1;
714 if (opt->status_only)
715 break;
718 return hit;
721 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
722 int exc_std, int use_index)
724 struct dir_struct dir = DIR_INIT;
725 int i, hit = 0;
727 if (!use_index)
728 dir.flags |= DIR_NO_GITLINKS;
729 if (exc_std)
730 setup_standard_excludes(&dir);
732 fill_directory(&dir, opt->repo->index, pathspec);
733 for (i = 0; i < dir.nr; i++) {
734 hit |= grep_file(opt, dir.entries[i]->name);
735 if (hit && opt->status_only)
736 break;
738 dir_clear(&dir);
739 return hit;
742 static int context_callback(const struct option *opt, const char *arg,
743 int unset)
745 struct grep_opt *grep_opt = opt->value;
746 int value;
747 const char *endp;
749 if (unset) {
750 grep_opt->pre_context = grep_opt->post_context = 0;
751 return 0;
753 value = strtol(arg, (char **)&endp, 10);
754 if (*endp) {
755 return error(_("switch `%c' expects a numerical value"),
756 opt->short_name);
758 grep_opt->pre_context = grep_opt->post_context = value;
759 return 0;
762 static int file_callback(const struct option *opt, const char *arg, int unset)
764 struct grep_opt *grep_opt = opt->value;
765 int from_stdin;
766 FILE *patterns;
767 int lno = 0;
768 struct strbuf sb = STRBUF_INIT;
770 BUG_ON_OPT_NEG(unset);
772 from_stdin = !strcmp(arg, "-");
773 patterns = from_stdin ? stdin : fopen(arg, "r");
774 if (!patterns)
775 die_errno(_("cannot open '%s'"), arg);
776 while (strbuf_getline(&sb, patterns) == 0) {
777 /* ignore empty line like grep does */
778 if (sb.len == 0)
779 continue;
781 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
782 GREP_PATTERN);
784 if (!from_stdin)
785 fclose(patterns);
786 strbuf_release(&sb);
787 return 0;
790 static int not_callback(const struct option *opt, const char *arg, int unset)
792 struct grep_opt *grep_opt = opt->value;
793 BUG_ON_OPT_NEG(unset);
794 BUG_ON_OPT_ARG(arg);
795 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
796 return 0;
799 static int and_callback(const struct option *opt, const char *arg, int unset)
801 struct grep_opt *grep_opt = opt->value;
802 BUG_ON_OPT_NEG(unset);
803 BUG_ON_OPT_ARG(arg);
804 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
805 return 0;
808 static int open_callback(const struct option *opt, const char *arg, int unset)
810 struct grep_opt *grep_opt = opt->value;
811 BUG_ON_OPT_NEG(unset);
812 BUG_ON_OPT_ARG(arg);
813 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
814 return 0;
817 static int close_callback(const struct option *opt, const char *arg, int unset)
819 struct grep_opt *grep_opt = opt->value;
820 BUG_ON_OPT_NEG(unset);
821 BUG_ON_OPT_ARG(arg);
822 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
823 return 0;
826 static int pattern_callback(const struct option *opt, const char *arg,
827 int unset)
829 struct grep_opt *grep_opt = opt->value;
830 BUG_ON_OPT_NEG(unset);
831 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
832 return 0;
835 int cmd_grep(int argc, const char **argv, const char *prefix)
837 int hit = 0;
838 int cached = 0, untracked = 0, opt_exclude = -1;
839 int seen_dashdash = 0;
840 int external_grep_allowed__ignored;
841 const char *show_in_pager = NULL, *default_pager = "dummy";
842 struct grep_opt opt;
843 struct object_array list = OBJECT_ARRAY_INIT;
844 struct pathspec pathspec;
845 struct string_list path_list = STRING_LIST_INIT_NODUP;
846 int i;
847 int dummy;
848 int use_index = 1;
849 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
850 int allow_revs;
852 struct option options[] = {
853 OPT_BOOL(0, "cached", &cached,
854 N_("search in index instead of in the work tree")),
855 OPT_NEGBIT(0, "no-index", &use_index,
856 N_("find in contents not managed by git"), 1),
857 OPT_BOOL(0, "untracked", &untracked,
858 N_("search in both tracked and untracked files")),
859 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
860 N_("ignore files specified via '.gitignore'"), 1),
861 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
862 N_("recursively search in each submodule")),
863 OPT_GROUP(""),
864 OPT_BOOL('v', "invert-match", &opt.invert,
865 N_("show non-matching lines")),
866 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
867 N_("case insensitive matching")),
868 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
869 N_("match patterns only at word boundaries")),
870 OPT_SET_INT('a', "text", &opt.binary,
871 N_("process binary files as text"), GREP_BINARY_TEXT),
872 OPT_SET_INT('I', NULL, &opt.binary,
873 N_("don't match patterns in binary files"),
874 GREP_BINARY_NOMATCH),
875 OPT_BOOL(0, "textconv", &opt.allow_textconv,
876 N_("process binary files with textconv filters")),
877 OPT_SET_INT('r', "recursive", &opt.max_depth,
878 N_("search in subdirectories (default)"), -1),
879 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
880 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
881 NULL, 1 },
882 OPT_GROUP(""),
883 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
884 N_("use extended POSIX regular expressions"),
885 GREP_PATTERN_TYPE_ERE),
886 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
887 N_("use basic POSIX regular expressions (default)"),
888 GREP_PATTERN_TYPE_BRE),
889 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
890 N_("interpret patterns as fixed strings"),
891 GREP_PATTERN_TYPE_FIXED),
892 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
893 N_("use Perl-compatible regular expressions"),
894 GREP_PATTERN_TYPE_PCRE),
895 OPT_GROUP(""),
896 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
897 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
898 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
899 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
900 OPT_NEGBIT(0, "full-name", &opt.relative,
901 N_("show filenames relative to top directory"), 1),
902 OPT_BOOL('l', "files-with-matches", &opt.name_only,
903 N_("show only filenames instead of matching lines")),
904 OPT_BOOL(0, "name-only", &opt.name_only,
905 N_("synonym for --files-with-matches")),
906 OPT_BOOL('L', "files-without-match",
907 &opt.unmatch_name_only,
908 N_("show only the names of files without match")),
909 OPT_BOOL_F('z', "null", &opt.null_following_name,
910 N_("print NUL after filenames"),
911 PARSE_OPT_NOCOMPLETE),
912 OPT_BOOL('o', "only-matching", &opt.only_matching,
913 N_("show only matching parts of a line")),
914 OPT_BOOL('c', "count", &opt.count,
915 N_("show the number of matches instead of matching lines")),
916 OPT__COLOR(&opt.color, N_("highlight matches")),
917 OPT_BOOL(0, "break", &opt.file_break,
918 N_("print empty line between matches from different files")),
919 OPT_BOOL(0, "heading", &opt.heading,
920 N_("show filename only once above matches from same file")),
921 OPT_GROUP(""),
922 OPT_CALLBACK('C', "context", &opt, N_("n"),
923 N_("show <n> context lines before and after matches"),
924 context_callback),
925 OPT_INTEGER('B', "before-context", &opt.pre_context,
926 N_("show <n> context lines before matches")),
927 OPT_INTEGER('A', "after-context", &opt.post_context,
928 N_("show <n> context lines after matches")),
929 OPT_INTEGER(0, "threads", &num_threads,
930 N_("use <n> worker threads")),
931 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
932 context_callback),
933 OPT_BOOL('p', "show-function", &opt.funcname,
934 N_("show a line with the function name before matches")),
935 OPT_BOOL('W', "function-context", &opt.funcbody,
936 N_("show the surrounding function")),
937 OPT_GROUP(""),
938 OPT_CALLBACK('f', NULL, &opt, N_("file"),
939 N_("read patterns from file"), file_callback),
940 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
941 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
942 OPT_CALLBACK_F(0, "and", &opt, NULL,
943 N_("combine patterns specified with -e"),
944 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
945 OPT_BOOL(0, "or", &dummy, ""),
946 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
947 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
948 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
949 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
950 open_callback),
951 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
952 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
953 close_callback),
954 OPT__QUIET(&opt.status_only,
955 N_("indicate hit with exit status without output")),
956 OPT_BOOL(0, "all-match", &opt.all_match,
957 N_("show only matches from files that match all patterns")),
958 OPT_GROUP(""),
959 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
960 N_("pager"), N_("show matching files in the pager"),
961 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
962 NULL, (intptr_t)default_pager },
963 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
964 N_("allow calling of grep(1) (ignored by this build)"),
965 PARSE_OPT_NOCOMPLETE),
966 OPT_END()
969 git_config(grep_cmd_config, NULL);
970 grep_init(&opt, the_repository, prefix);
973 * If there is no -- then the paths must exist in the working
974 * tree. If there is no explicit pattern specified with -e or
975 * -f, we take the first unrecognized non option to be the
976 * pattern, but then what follows it must be zero or more
977 * valid refs up to the -- (if exists), and then existing
978 * paths. If there is an explicit pattern, then the first
979 * unrecognized non option is the beginning of the refs list
980 * that continues up to the -- (if exists), and then paths.
982 argc = parse_options(argc, argv, prefix, options, grep_usage,
983 PARSE_OPT_KEEP_DASHDASH |
984 PARSE_OPT_STOP_AT_NON_OPTION);
985 grep_commit_pattern_type(pattern_type_arg, &opt);
987 if (use_index && !startup_info->have_repository) {
988 int fallback = 0;
989 git_config_get_bool("grep.fallbacktonoindex", &fallback);
990 if (fallback)
991 use_index = 0;
992 else
993 /* die the same way as if we did it at the beginning */
994 setup_git_directory();
996 /* Ignore --recurse-submodules if --no-index is given or implied */
997 if (!use_index)
998 recurse_submodules = 0;
1001 * skip a -- separator; we know it cannot be
1002 * separating revisions from pathnames if
1003 * we haven't even had any patterns yet
1005 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1006 argv++;
1007 argc--;
1010 /* First unrecognized non-option token */
1011 if (argc > 0 && !opt.pattern_list) {
1012 append_grep_pattern(&opt, argv[0], "command line", 0,
1013 GREP_PATTERN);
1014 argv++;
1015 argc--;
1018 if (show_in_pager == default_pager)
1019 show_in_pager = git_pager(1);
1020 if (show_in_pager) {
1021 opt.color = 0;
1022 opt.name_only = 1;
1023 opt.null_following_name = 1;
1024 opt.output_priv = &path_list;
1025 opt.output = append_path;
1026 string_list_append(&path_list, show_in_pager);
1029 if (!opt.pattern_list)
1030 die(_("no pattern given"));
1032 /* --only-matching has no effect with --invert. */
1033 if (opt.invert)
1034 opt.only_matching = 0;
1037 * We have to find "--" in a separate pass, because its presence
1038 * influences how we will parse arguments that come before it.
1040 for (i = 0; i < argc; i++) {
1041 if (!strcmp(argv[i], "--")) {
1042 seen_dashdash = 1;
1043 break;
1048 * Resolve any rev arguments. If we have a dashdash, then everything up
1049 * to it must resolve as a rev. If not, then we stop at the first
1050 * non-rev and assume everything else is a path.
1052 allow_revs = use_index && !untracked;
1053 for (i = 0; i < argc; i++) {
1054 const char *arg = argv[i];
1055 struct object_id oid;
1056 struct object_context oc;
1057 struct object *object;
1059 if (!strcmp(arg, "--")) {
1060 i++;
1061 break;
1064 if (!allow_revs) {
1065 if (seen_dashdash)
1066 die(_("--no-index or --untracked cannot be used with revs"));
1067 break;
1070 if (get_oid_with_context(the_repository, arg,
1071 GET_OID_RECORD_PATH,
1072 &oid, &oc)) {
1073 if (seen_dashdash)
1074 die(_("unable to resolve revision: %s"), arg);
1075 break;
1078 object = parse_object_or_die(&oid, arg);
1079 if (!seen_dashdash)
1080 verify_non_filename(prefix, arg);
1081 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1082 free(oc.path);
1086 * Anything left over is presumed to be a path. But in the non-dashdash
1087 * "do what I mean" case, we verify and complain when that isn't true.
1089 if (!seen_dashdash) {
1090 int j;
1091 for (j = i; j < argc; j++)
1092 verify_filename(prefix, argv[j], j == i && allow_revs);
1095 parse_pathspec(&pathspec, 0,
1096 PATHSPEC_PREFER_CWD |
1097 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1098 prefix, argv + i);
1099 pathspec.max_depth = opt.max_depth;
1100 pathspec.recursive = 1;
1101 pathspec.recurse_submodules = !!recurse_submodules;
1103 if (recurse_submodules && untracked)
1104 die(_("--untracked not supported with --recurse-submodules"));
1106 if (show_in_pager) {
1107 if (num_threads > 1)
1108 warning(_("invalid option combination, ignoring --threads"));
1109 num_threads = 1;
1110 } else if (!HAVE_THREADS && num_threads > 1) {
1111 warning(_("no threads support, ignoring --threads"));
1112 num_threads = 1;
1113 } else if (num_threads < 0)
1114 die(_("invalid number of threads specified (%d)"), num_threads);
1115 else if (num_threads == 0)
1116 num_threads = HAVE_THREADS ? online_cpus() : 1;
1118 if (num_threads > 1) {
1119 if (!HAVE_THREADS)
1120 BUG("Somebody got num_threads calculation wrong!");
1121 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1122 && (opt.pre_context || opt.post_context ||
1123 opt.file_break || opt.funcbody))
1124 skip_first_line = 1;
1127 * Pre-read gitmodules (if not read already) and force eager
1128 * initialization of packed_git to prevent racy lazy
1129 * reading/initialization once worker threads are started.
1131 if (recurse_submodules)
1132 repo_read_gitmodules(the_repository, 1);
1133 if (startup_info->have_repository)
1134 (void)get_packed_git(the_repository);
1136 start_threads(&opt);
1137 } else {
1139 * The compiled patterns on the main path are only
1140 * used when not using threading. Otherwise
1141 * start_threads() above calls compile_grep_patterns()
1142 * for each thread.
1144 compile_grep_patterns(&opt);
1147 if (show_in_pager && (cached || list.nr))
1148 die(_("--open-files-in-pager only works on the worktree"));
1150 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1151 const char *pager = path_list.items[0].string;
1152 int len = strlen(pager);
1154 if (len > 4 && is_dir_sep(pager[len - 5]))
1155 pager += len - 4;
1157 if (opt.ignore_case && !strcmp("less", pager))
1158 string_list_append(&path_list, "-I");
1160 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1161 struct strbuf buf = STRBUF_INIT;
1162 strbuf_addf(&buf, "+/%s%s",
1163 strcmp("less", pager) ? "" : "*",
1164 opt.pattern_list->pattern);
1165 string_list_append(&path_list,
1166 strbuf_detach(&buf, NULL));
1170 if (!show_in_pager && !opt.status_only)
1171 setup_pager();
1173 if (!use_index && (untracked || cached))
1174 die(_("--cached or --untracked cannot be used with --no-index"));
1176 if (untracked && cached)
1177 die(_("--untracked cannot be used with --cached"));
1179 if (!use_index || untracked) {
1180 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1181 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1182 } else if (0 <= opt_exclude) {
1183 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1184 } else if (!list.nr) {
1185 if (!cached)
1186 setup_work_tree();
1188 hit = grep_cache(&opt, &pathspec, cached);
1189 } else {
1190 if (cached)
1191 die(_("both --cached and trees are given"));
1193 hit = grep_objects(&opt, &pathspec, &list);
1196 if (num_threads > 1)
1197 hit |= wait_all();
1198 if (hit && show_in_pager)
1199 run_pager(&opt, prefix);
1200 clear_pathspec(&pathspec);
1201 free_grep_patterns(&opt);
1202 free_repos();
1203 return !hit;