Merge branch 'js/trace2-raise-format-version'
[git/debian.git] / builtin / grep.c
blob9e34a820ad4d837937a0ecb2bc712de972506b50
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(opt);
203 free(opt);
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_nodup(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 struct grep_opt subopt;
437 int hit = 0;
439 if (!is_submodule_active(superproject, path))
440 return 0;
442 subrepo = xmalloc(sizeof(*subrepo));
443 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
444 free(subrepo);
445 return 0;
447 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
448 repos_to_free[repos_to_free_nr++] = subrepo;
451 * NEEDSWORK: repo_read_gitmodules() might call
452 * add_to_alternates_memory() via config_from_gitmodules(). This
453 * operation causes a race condition with concurrent object readings
454 * performed by the worker threads. That's why we need obj_read_lock()
455 * here. It should be removed once it's no longer necessary to add the
456 * subrepo's odbs to the in-memory alternates list.
458 obj_read_lock();
459 repo_read_gitmodules(subrepo, 0);
462 * All code paths tested by test code no longer need submodule ODBs to
463 * be added as alternates, but add it to the list just in case.
464 * Submodule ODBs added through add_submodule_odb_by_path() will be
465 * lazily registered as alternates when needed (and except in an
466 * unexpected code interaction, it won't be needed).
468 add_submodule_odb_by_path(subrepo->objects->odb->path);
469 obj_read_unlock();
471 memcpy(&subopt, opt, sizeof(subopt));
472 subopt.repo = subrepo;
474 if (oid) {
475 enum object_type object_type;
476 struct tree_desc tree;
477 void *data;
478 unsigned long size;
479 struct strbuf base = STRBUF_INIT;
481 obj_read_lock();
482 object_type = oid_object_info(subrepo, oid, NULL);
483 obj_read_unlock();
484 data = read_object_with_reference(subrepo,
485 oid, tree_type,
486 &size, NULL);
487 if (!data)
488 die(_("unable to read tree (%s)"), oid_to_hex(oid));
490 strbuf_addstr(&base, filename);
491 strbuf_addch(&base, '/');
493 init_tree_desc(&tree, data, size);
494 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
495 object_type == OBJ_COMMIT);
496 strbuf_release(&base);
497 free(data);
498 } else {
499 hit = grep_cache(&subopt, pathspec, cached);
502 return hit;
505 static int grep_cache(struct grep_opt *opt,
506 const struct pathspec *pathspec, int cached)
508 struct repository *repo = opt->repo;
509 int hit = 0;
510 int nr;
511 struct strbuf name = STRBUF_INIT;
512 int name_base_len = 0;
513 if (repo->submodule_prefix) {
514 name_base_len = strlen(repo->submodule_prefix);
515 strbuf_addstr(&name, repo->submodule_prefix);
518 if (repo_read_index(repo) < 0)
519 die(_("index file corrupt"));
521 /* TODO: audit for interaction with sparse-index. */
522 ensure_full_index(repo->index);
523 for (nr = 0; nr < repo->index->cache_nr; nr++) {
524 const struct cache_entry *ce = repo->index->cache[nr];
526 if (!cached && ce_skip_worktree(ce))
527 continue;
529 strbuf_setlen(&name, name_base_len);
530 strbuf_addstr(&name, ce->name);
532 if (S_ISREG(ce->ce_mode) &&
533 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
534 S_ISDIR(ce->ce_mode) ||
535 S_ISGITLINK(ce->ce_mode))) {
537 * If CE_VALID is on, we assume worktree file and its
538 * cache entry are identical, even if worktree file has
539 * been modified, so use cache version instead
541 if (cached || (ce->ce_flags & CE_VALID)) {
542 if (ce_stage(ce) || ce_intent_to_add(ce))
543 continue;
544 hit |= grep_oid(opt, &ce->oid, name.buf,
545 0, name.buf);
546 } else {
547 hit |= grep_file(opt, name.buf);
549 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
550 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
551 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
552 ce->name, cached);
553 } else {
554 continue;
557 if (ce_stage(ce)) {
558 do {
559 nr++;
560 } while (nr < repo->index->cache_nr &&
561 !strcmp(ce->name, repo->index->cache[nr]->name));
562 nr--; /* compensate for loop control */
564 if (hit && opt->status_only)
565 break;
568 strbuf_release(&name);
569 return hit;
572 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
573 struct tree_desc *tree, struct strbuf *base, int tn_len,
574 int check_attr)
576 struct repository *repo = opt->repo;
577 int hit = 0;
578 enum interesting match = entry_not_interesting;
579 struct name_entry entry;
580 int old_baselen = base->len;
581 struct strbuf name = STRBUF_INIT;
582 int name_base_len = 0;
583 if (repo->submodule_prefix) {
584 strbuf_addstr(&name, repo->submodule_prefix);
585 name_base_len = name.len;
588 while (tree_entry(tree, &entry)) {
589 int te_len = tree_entry_len(&entry);
591 if (match != all_entries_interesting) {
592 strbuf_addstr(&name, base->buf + tn_len);
593 match = tree_entry_interesting(repo->index,
594 &entry, &name,
595 0, pathspec);
596 strbuf_setlen(&name, name_base_len);
598 if (match == all_entries_not_interesting)
599 break;
600 if (match == entry_not_interesting)
601 continue;
604 strbuf_add(base, entry.path, te_len);
606 if (S_ISREG(entry.mode)) {
607 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
608 check_attr ? base->buf + tn_len : NULL);
609 } else if (S_ISDIR(entry.mode)) {
610 enum object_type type;
611 struct tree_desc sub;
612 void *data;
613 unsigned long size;
615 data = read_object_file(&entry.oid, &type, &size);
616 if (!data)
617 die(_("unable to read tree (%s)"),
618 oid_to_hex(&entry.oid));
620 strbuf_addch(base, '/');
621 init_tree_desc(&sub, data, size);
622 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
623 check_attr);
624 free(data);
625 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
626 hit |= grep_submodule(opt, pathspec, &entry.oid,
627 base->buf, base->buf + tn_len,
628 1); /* ignored */
631 strbuf_setlen(base, old_baselen);
633 if (hit && opt->status_only)
634 break;
637 strbuf_release(&name);
638 return hit;
641 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
642 struct object *obj, const char *name, const char *path)
644 if (obj->type == OBJ_BLOB)
645 return grep_oid(opt, &obj->oid, name, 0, path);
646 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
647 struct tree_desc tree;
648 void *data;
649 unsigned long size;
650 struct strbuf base;
651 int hit, len;
653 data = read_object_with_reference(opt->repo,
654 &obj->oid, tree_type,
655 &size, NULL);
656 if (!data)
657 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
659 len = name ? strlen(name) : 0;
660 strbuf_init(&base, PATH_MAX + len + 1);
661 if (len) {
662 strbuf_add(&base, name, len);
663 strbuf_addch(&base, ':');
665 init_tree_desc(&tree, data, size);
666 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
667 obj->type == OBJ_COMMIT);
668 strbuf_release(&base);
669 free(data);
670 return hit;
672 die(_("unable to grep from object of type %s"), type_name(obj->type));
675 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
676 const struct object_array *list)
678 unsigned int i;
679 int hit = 0;
680 const unsigned int nr = list->nr;
682 for (i = 0; i < nr; i++) {
683 struct object *real_obj;
685 obj_read_lock();
686 real_obj = deref_tag(opt->repo, list->objects[i].item,
687 NULL, 0);
688 obj_read_unlock();
690 if (!real_obj) {
691 char hex[GIT_MAX_HEXSZ + 1];
692 const char *name = list->objects[i].name;
694 if (!name) {
695 oid_to_hex_r(hex, &list->objects[i].item->oid);
696 name = hex;
698 die(_("invalid object '%s' given."), name);
701 /* load the gitmodules file for this rev */
702 if (recurse_submodules) {
703 submodule_free(opt->repo);
704 obj_read_lock();
705 gitmodules_config_oid(&real_obj->oid);
706 obj_read_unlock();
708 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
709 list->objects[i].path)) {
710 hit = 1;
711 if (opt->status_only)
712 break;
715 return hit;
718 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
719 int exc_std, int use_index)
721 struct dir_struct dir = DIR_INIT;
722 int i, hit = 0;
724 if (!use_index)
725 dir.flags |= DIR_NO_GITLINKS;
726 if (exc_std)
727 setup_standard_excludes(&dir);
729 fill_directory(&dir, opt->repo->index, pathspec);
730 for (i = 0; i < dir.nr; i++) {
731 hit |= grep_file(opt, dir.entries[i]->name);
732 if (hit && opt->status_only)
733 break;
735 dir_clear(&dir);
736 return hit;
739 static int context_callback(const struct option *opt, const char *arg,
740 int unset)
742 struct grep_opt *grep_opt = opt->value;
743 int value;
744 const char *endp;
746 if (unset) {
747 grep_opt->pre_context = grep_opt->post_context = 0;
748 return 0;
750 value = strtol(arg, (char **)&endp, 10);
751 if (*endp) {
752 return error(_("switch `%c' expects a numerical value"),
753 opt->short_name);
755 grep_opt->pre_context = grep_opt->post_context = value;
756 return 0;
759 static int file_callback(const struct option *opt, const char *arg, int unset)
761 struct grep_opt *grep_opt = opt->value;
762 int from_stdin;
763 FILE *patterns;
764 int lno = 0;
765 struct strbuf sb = STRBUF_INIT;
767 BUG_ON_OPT_NEG(unset);
769 from_stdin = !strcmp(arg, "-");
770 patterns = from_stdin ? stdin : fopen(arg, "r");
771 if (!patterns)
772 die_errno(_("cannot open '%s'"), arg);
773 while (strbuf_getline(&sb, patterns) == 0) {
774 /* ignore empty line like grep does */
775 if (sb.len == 0)
776 continue;
778 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
779 GREP_PATTERN);
781 if (!from_stdin)
782 fclose(patterns);
783 strbuf_release(&sb);
784 return 0;
787 static int not_callback(const struct option *opt, const char *arg, int unset)
789 struct grep_opt *grep_opt = opt->value;
790 BUG_ON_OPT_NEG(unset);
791 BUG_ON_OPT_ARG(arg);
792 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
793 return 0;
796 static int and_callback(const struct option *opt, const char *arg, int unset)
798 struct grep_opt *grep_opt = opt->value;
799 BUG_ON_OPT_NEG(unset);
800 BUG_ON_OPT_ARG(arg);
801 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
802 return 0;
805 static int open_callback(const struct option *opt, const char *arg, int unset)
807 struct grep_opt *grep_opt = opt->value;
808 BUG_ON_OPT_NEG(unset);
809 BUG_ON_OPT_ARG(arg);
810 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
811 return 0;
814 static int close_callback(const struct option *opt, const char *arg, int unset)
816 struct grep_opt *grep_opt = opt->value;
817 BUG_ON_OPT_NEG(unset);
818 BUG_ON_OPT_ARG(arg);
819 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
820 return 0;
823 static int pattern_callback(const struct option *opt, const char *arg,
824 int unset)
826 struct grep_opt *grep_opt = opt->value;
827 BUG_ON_OPT_NEG(unset);
828 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
829 return 0;
832 int cmd_grep(int argc, const char **argv, const char *prefix)
834 int hit = 0;
835 int cached = 0, untracked = 0, opt_exclude = -1;
836 int seen_dashdash = 0;
837 int external_grep_allowed__ignored;
838 const char *show_in_pager = NULL, *default_pager = "dummy";
839 struct grep_opt opt;
840 struct object_array list = OBJECT_ARRAY_INIT;
841 struct pathspec pathspec;
842 struct string_list path_list = STRING_LIST_INIT_DUP;
843 int i;
844 int dummy;
845 int use_index = 1;
846 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
847 int allow_revs;
849 struct option options[] = {
850 OPT_BOOL(0, "cached", &cached,
851 N_("search in index instead of in the work tree")),
852 OPT_NEGBIT(0, "no-index", &use_index,
853 N_("find in contents not managed by git"), 1),
854 OPT_BOOL(0, "untracked", &untracked,
855 N_("search in both tracked and untracked files")),
856 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
857 N_("ignore files specified via '.gitignore'"), 1),
858 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
859 N_("recursively search in each submodule")),
860 OPT_GROUP(""),
861 OPT_BOOL('v', "invert-match", &opt.invert,
862 N_("show non-matching lines")),
863 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
864 N_("case insensitive matching")),
865 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
866 N_("match patterns only at word boundaries")),
867 OPT_SET_INT('a', "text", &opt.binary,
868 N_("process binary files as text"), GREP_BINARY_TEXT),
869 OPT_SET_INT('I', NULL, &opt.binary,
870 N_("don't match patterns in binary files"),
871 GREP_BINARY_NOMATCH),
872 OPT_BOOL(0, "textconv", &opt.allow_textconv,
873 N_("process binary files with textconv filters")),
874 OPT_SET_INT('r', "recursive", &opt.max_depth,
875 N_("search in subdirectories (default)"), -1),
876 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
877 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
878 NULL, 1 },
879 OPT_GROUP(""),
880 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
881 N_("use extended POSIX regular expressions"),
882 GREP_PATTERN_TYPE_ERE),
883 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
884 N_("use basic POSIX regular expressions (default)"),
885 GREP_PATTERN_TYPE_BRE),
886 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
887 N_("interpret patterns as fixed strings"),
888 GREP_PATTERN_TYPE_FIXED),
889 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
890 N_("use Perl-compatible regular expressions"),
891 GREP_PATTERN_TYPE_PCRE),
892 OPT_GROUP(""),
893 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
894 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
895 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
896 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
897 OPT_NEGBIT(0, "full-name", &opt.relative,
898 N_("show filenames relative to top directory"), 1),
899 OPT_BOOL('l', "files-with-matches", &opt.name_only,
900 N_("show only filenames instead of matching lines")),
901 OPT_BOOL(0, "name-only", &opt.name_only,
902 N_("synonym for --files-with-matches")),
903 OPT_BOOL('L', "files-without-match",
904 &opt.unmatch_name_only,
905 N_("show only the names of files without match")),
906 OPT_BOOL_F('z', "null", &opt.null_following_name,
907 N_("print NUL after filenames"),
908 PARSE_OPT_NOCOMPLETE),
909 OPT_BOOL('o', "only-matching", &opt.only_matching,
910 N_("show only matching parts of a line")),
911 OPT_BOOL('c', "count", &opt.count,
912 N_("show the number of matches instead of matching lines")),
913 OPT__COLOR(&opt.color, N_("highlight matches")),
914 OPT_BOOL(0, "break", &opt.file_break,
915 N_("print empty line between matches from different files")),
916 OPT_BOOL(0, "heading", &opt.heading,
917 N_("show filename only once above matches from same file")),
918 OPT_GROUP(""),
919 OPT_CALLBACK('C', "context", &opt, N_("n"),
920 N_("show <n> context lines before and after matches"),
921 context_callback),
922 OPT_INTEGER('B', "before-context", &opt.pre_context,
923 N_("show <n> context lines before matches")),
924 OPT_INTEGER('A', "after-context", &opt.post_context,
925 N_("show <n> context lines after matches")),
926 OPT_INTEGER(0, "threads", &num_threads,
927 N_("use <n> worker threads")),
928 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
929 context_callback),
930 OPT_BOOL('p', "show-function", &opt.funcname,
931 N_("show a line with the function name before matches")),
932 OPT_BOOL('W', "function-context", &opt.funcbody,
933 N_("show the surrounding function")),
934 OPT_GROUP(""),
935 OPT_CALLBACK('f', NULL, &opt, N_("file"),
936 N_("read patterns from file"), file_callback),
937 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
938 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
939 OPT_CALLBACK_F(0, "and", &opt, NULL,
940 N_("combine patterns specified with -e"),
941 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
942 OPT_BOOL(0, "or", &dummy, ""),
943 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
944 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
945 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
946 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
947 open_callback),
948 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
949 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
950 close_callback),
951 OPT__QUIET(&opt.status_only,
952 N_("indicate hit with exit status without output")),
953 OPT_BOOL(0, "all-match", &opt.all_match,
954 N_("show only matches from files that match all patterns")),
955 OPT_GROUP(""),
956 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
957 N_("pager"), N_("show matching files in the pager"),
958 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
959 NULL, (intptr_t)default_pager },
960 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
961 N_("allow calling of grep(1) (ignored by this build)"),
962 PARSE_OPT_NOCOMPLETE),
963 OPT_END()
966 git_config(grep_cmd_config, NULL);
967 grep_init(&opt, the_repository, prefix);
970 * If there is no -- then the paths must exist in the working
971 * tree. If there is no explicit pattern specified with -e or
972 * -f, we take the first unrecognized non option to be the
973 * pattern, but then what follows it must be zero or more
974 * valid refs up to the -- (if exists), and then existing
975 * paths. If there is an explicit pattern, then the first
976 * unrecognized non option is the beginning of the refs list
977 * that continues up to the -- (if exists), and then paths.
979 argc = parse_options(argc, argv, prefix, options, grep_usage,
980 PARSE_OPT_KEEP_DASHDASH |
981 PARSE_OPT_STOP_AT_NON_OPTION);
982 grep_commit_pattern_type(pattern_type_arg, &opt);
984 if (use_index && !startup_info->have_repository) {
985 int fallback = 0;
986 git_config_get_bool("grep.fallbacktonoindex", &fallback);
987 if (fallback)
988 use_index = 0;
989 else
990 /* die the same way as if we did it at the beginning */
991 setup_git_directory();
993 /* Ignore --recurse-submodules if --no-index is given or implied */
994 if (!use_index)
995 recurse_submodules = 0;
998 * skip a -- separator; we know it cannot be
999 * separating revisions from pathnames if
1000 * we haven't even had any patterns yet
1002 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1003 argv++;
1004 argc--;
1007 /* First unrecognized non-option token */
1008 if (argc > 0 && !opt.pattern_list) {
1009 append_grep_pattern(&opt, argv[0], "command line", 0,
1010 GREP_PATTERN);
1011 argv++;
1012 argc--;
1015 if (show_in_pager == default_pager)
1016 show_in_pager = git_pager(1);
1017 if (show_in_pager) {
1018 opt.color = 0;
1019 opt.name_only = 1;
1020 opt.null_following_name = 1;
1021 opt.output_priv = &path_list;
1022 opt.output = append_path;
1023 string_list_append(&path_list, show_in_pager);
1026 if (!opt.pattern_list)
1027 die(_("no pattern given"));
1029 /* --only-matching has no effect with --invert. */
1030 if (opt.invert)
1031 opt.only_matching = 0;
1034 * We have to find "--" in a separate pass, because its presence
1035 * influences how we will parse arguments that come before it.
1037 for (i = 0; i < argc; i++) {
1038 if (!strcmp(argv[i], "--")) {
1039 seen_dashdash = 1;
1040 break;
1045 * Resolve any rev arguments. If we have a dashdash, then everything up
1046 * to it must resolve as a rev. If not, then we stop at the first
1047 * non-rev and assume everything else is a path.
1049 allow_revs = use_index && !untracked;
1050 for (i = 0; i < argc; i++) {
1051 const char *arg = argv[i];
1052 struct object_id oid;
1053 struct object_context oc;
1054 struct object *object;
1056 if (!strcmp(arg, "--")) {
1057 i++;
1058 break;
1061 if (!allow_revs) {
1062 if (seen_dashdash)
1063 die(_("--no-index or --untracked cannot be used with revs"));
1064 break;
1067 if (get_oid_with_context(the_repository, arg,
1068 GET_OID_RECORD_PATH,
1069 &oid, &oc)) {
1070 if (seen_dashdash)
1071 die(_("unable to resolve revision: %s"), arg);
1072 break;
1075 object = parse_object_or_die(&oid, arg);
1076 if (!seen_dashdash)
1077 verify_non_filename(prefix, arg);
1078 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1079 free(oc.path);
1083 * Anything left over is presumed to be a path. But in the non-dashdash
1084 * "do what I mean" case, we verify and complain when that isn't true.
1086 if (!seen_dashdash) {
1087 int j;
1088 for (j = i; j < argc; j++)
1089 verify_filename(prefix, argv[j], j == i && allow_revs);
1092 parse_pathspec(&pathspec, 0,
1093 PATHSPEC_PREFER_CWD |
1094 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1095 prefix, argv + i);
1096 pathspec.max_depth = opt.max_depth;
1097 pathspec.recursive = 1;
1098 pathspec.recurse_submodules = !!recurse_submodules;
1100 if (recurse_submodules && untracked)
1101 die(_("--untracked not supported with --recurse-submodules"));
1103 if (show_in_pager) {
1104 if (num_threads > 1)
1105 warning(_("invalid option combination, ignoring --threads"));
1106 num_threads = 1;
1107 } else if (!HAVE_THREADS && num_threads > 1) {
1108 warning(_("no threads support, ignoring --threads"));
1109 num_threads = 1;
1110 } else if (num_threads < 0)
1111 die(_("invalid number of threads specified (%d)"), num_threads);
1112 else if (num_threads == 0)
1113 num_threads = HAVE_THREADS ? online_cpus() : 1;
1115 if (num_threads > 1) {
1116 if (!HAVE_THREADS)
1117 BUG("Somebody got num_threads calculation wrong!");
1118 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1119 && (opt.pre_context || opt.post_context ||
1120 opt.file_break || opt.funcbody))
1121 skip_first_line = 1;
1124 * Pre-read gitmodules (if not read already) and force eager
1125 * initialization of packed_git to prevent racy lazy
1126 * reading/initialization once worker threads are started.
1128 if (recurse_submodules)
1129 repo_read_gitmodules(the_repository, 1);
1130 if (startup_info->have_repository)
1131 (void)get_packed_git(the_repository);
1133 start_threads(&opt);
1134 } else {
1136 * The compiled patterns on the main path are only
1137 * used when not using threading. Otherwise
1138 * start_threads() above calls compile_grep_patterns()
1139 * for each thread.
1141 compile_grep_patterns(&opt);
1144 if (show_in_pager && (cached || list.nr))
1145 die(_("--open-files-in-pager only works on the worktree"));
1147 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1148 const char *pager = path_list.items[0].string;
1149 int len = strlen(pager);
1151 if (len > 4 && is_dir_sep(pager[len - 5]))
1152 pager += len - 4;
1154 if (opt.ignore_case && !strcmp("less", pager))
1155 string_list_append(&path_list, "-I");
1157 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1158 struct strbuf buf = STRBUF_INIT;
1159 strbuf_addf(&buf, "+/%s%s",
1160 strcmp("less", pager) ? "" : "*",
1161 opt.pattern_list->pattern);
1162 string_list_append_nodup(&path_list,
1163 strbuf_detach(&buf, NULL));
1167 if (!show_in_pager && !opt.status_only)
1168 setup_pager();
1170 if (!use_index && (untracked || cached))
1171 die(_("--cached or --untracked cannot be used with --no-index"));
1173 if (untracked && cached)
1174 die(_("--untracked cannot be used with --cached"));
1176 if (!use_index || untracked) {
1177 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1178 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1179 } else if (0 <= opt_exclude) {
1180 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1181 } else if (!list.nr) {
1182 if (!cached)
1183 setup_work_tree();
1185 hit = grep_cache(&opt, &pathspec, cached);
1186 } else {
1187 if (cached)
1188 die(_("both --cached and trees are given"));
1190 hit = grep_objects(&opt, &pathspec, &list);
1193 if (num_threads > 1)
1194 hit |= wait_all();
1195 if (hit && show_in_pager)
1196 run_pager(&opt, prefix);
1197 clear_pathspec(&pathspec);
1198 string_list_clear(&path_list, 0);
1199 free_grep_patterns(&opt);
1200 object_array_clear(&list);
1201 free_repos();
1202 return !hit;