4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
14 #include "string-list.h"
15 #include "run-command.h"
21 #include "submodule.h"
22 #include "submodule-config.h"
24 static char const * const grep_usage[] = {
25 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
29 static const char *super_prefix;
30 static int recurse_submodules;
31 static struct argv_array submodule_options = ARGV_ARRAY_INIT;
32 static const char *parent_basename;
34 static int grep_submodule_launch(struct grep_opt *opt,
35 const struct grep_source *gs);
37 #define GREP_NUM_THREADS_DEFAULT 8
38 static int num_threads;
41 static pthread_t *threads;
43 /* We use one producer thread and THREADS consumer
44 * threads. The producer adds struct work_items to 'todo' and the
45 * consumers pick work items from the same array.
48 struct grep_source source;
53 /* In the range [todo_done, todo_start) in 'todo' we have work_items
54 * that have been or are processed by a consumer thread. We haven't
55 * written the result for these to stdout yet.
57 * The work_items in [todo_start, todo_end) are waiting to be picked
58 * up by a consumer thread.
60 * The ranges are modulo TODO_SIZE.
63 static struct work_item todo[TODO_SIZE];
64 static int todo_start;
68 /* Has all work items been added? */
69 static int all_work_added;
71 /* This lock protects all the variables above. */
72 static pthread_mutex_t grep_mutex;
74 static inline void grep_lock(void)
77 pthread_mutex_lock(&grep_mutex);
80 static inline void grep_unlock(void)
83 pthread_mutex_unlock(&grep_mutex);
86 /* Signalled when a new work_item is added to todo. */
87 static pthread_cond_t cond_add;
89 /* Signalled when the result from one work_item is written to
92 static pthread_cond_t cond_write;
94 /* Signalled when we are finished with everything. */
95 static pthread_cond_t cond_result;
97 static int skip_first_line;
99 static void add_work(struct grep_opt *opt, enum grep_source_type type,
100 const char *name, const char *path, const void *id)
104 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
105 pthread_cond_wait(&cond_write, &grep_mutex);
108 grep_source_init(&todo[todo_end].source, type, name, path, id);
109 if (opt->binary != GREP_BINARY_TEXT)
110 grep_source_load_driver(&todo[todo_end].source);
111 todo[todo_end].done = 0;
112 strbuf_reset(&todo[todo_end].out);
113 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
115 pthread_cond_signal(&cond_add);
119 static struct work_item *get_work(void)
121 struct work_item *ret;
124 while (todo_start == todo_end && !all_work_added) {
125 pthread_cond_wait(&cond_add, &grep_mutex);
128 if (todo_start == todo_end && all_work_added) {
131 ret = &todo[todo_start];
132 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
138 static void work_done(struct work_item *w)
144 old_done = todo_done;
145 for(; todo[todo_done].done && todo_done != todo_start;
146 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
147 w = &todo[todo_done];
149 const char *p = w->out.buf;
150 size_t len = w->out.len;
152 /* Skip the leading hunk mark of the first file. */
153 if (skip_first_line) {
162 write_or_die(1, p, len);
164 grep_source_clear(&w->source);
167 if (old_done != todo_done)
168 pthread_cond_signal(&cond_write);
170 if (all_work_added && todo_done == todo_end)
171 pthread_cond_signal(&cond_result);
176 static void *run(void *arg)
179 struct grep_opt *opt = arg;
182 struct work_item *w = get_work();
186 opt->output_priv = w;
187 if (w->source.type == GREP_SOURCE_SUBMODULE)
188 hit |= grep_submodule_launch(opt, &w->source);
190 hit |= grep_source(opt, &w->source);
191 grep_source_clear_data(&w->source);
194 free_grep_patterns(arg);
197 return (void*) (intptr_t) hit;
200 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
202 struct work_item *w = opt->output_priv;
203 strbuf_add(&w->out, buf, size);
206 static void start_threads(struct grep_opt *opt)
210 pthread_mutex_init(&grep_mutex, NULL);
211 pthread_mutex_init(&grep_read_mutex, NULL);
212 pthread_mutex_init(&grep_attr_mutex, NULL);
213 pthread_cond_init(&cond_add, NULL);
214 pthread_cond_init(&cond_write, NULL);
215 pthread_cond_init(&cond_result, NULL);
218 for (i = 0; i < ARRAY_SIZE(todo); i++) {
219 strbuf_init(&todo[i].out, 0);
222 threads = xcalloc(num_threads, sizeof(*threads));
223 for (i = 0; i < num_threads; i++) {
225 struct grep_opt *o = grep_opt_dup(opt);
226 o->output = strbuf_out;
228 compile_grep_patterns(o);
229 err = pthread_create(&threads[i], NULL, run, o);
232 die(_("grep: failed to create thread: %s"),
237 static int wait_all(void)
245 /* Wait until all work is done. */
246 while (todo_done != todo_end)
247 pthread_cond_wait(&cond_result, &grep_mutex);
249 /* Wake up all the consumer threads so they can see that there
250 * is no more work to do.
252 pthread_cond_broadcast(&cond_add);
255 for (i = 0; i < num_threads; i++) {
257 pthread_join(threads[i], &h);
258 hit |= (int) (intptr_t) h;
263 pthread_mutex_destroy(&grep_mutex);
264 pthread_mutex_destroy(&grep_read_mutex);
265 pthread_mutex_destroy(&grep_attr_mutex);
266 pthread_cond_destroy(&cond_add);
267 pthread_cond_destroy(&cond_write);
268 pthread_cond_destroy(&cond_result);
273 #else /* !NO_PTHREADS */
275 static int wait_all(void)
281 static int grep_cmd_config(const char *var, const char *value, void *cb)
283 int st = grep_config(var, value, cb);
284 if (git_color_default_config(var, value, cb) < 0)
287 if (!strcmp(var, "grep.threads")) {
288 num_threads = git_config_int(var, value);
290 die(_("invalid number of threads specified (%d) for %s"),
297 static void *lock_and_read_oid_file(const struct object_id *oid, enum object_type *type, unsigned long *size)
302 data = read_sha1_file(oid->hash, type, size);
307 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
308 const char *filename, int tree_name_len,
311 struct strbuf pathbuf = STRBUF_INIT;
314 strbuf_add(&pathbuf, filename, tree_name_len);
315 strbuf_addstr(&pathbuf, super_prefix);
316 strbuf_addstr(&pathbuf, filename + tree_name_len);
318 strbuf_addstr(&pathbuf, filename);
321 if (opt->relative && opt->prefix_length) {
322 char *name = strbuf_detach(&pathbuf, NULL);
323 quote_path_relative(name + tree_name_len, opt->prefix, &pathbuf);
324 strbuf_insert(&pathbuf, 0, name, tree_name_len);
330 add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, path, oid);
331 strbuf_release(&pathbuf);
336 struct grep_source gs;
339 grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, path, oid);
340 strbuf_release(&pathbuf);
341 hit = grep_source(opt, &gs);
343 grep_source_clear(&gs);
348 static int grep_file(struct grep_opt *opt, const char *filename)
350 struct strbuf buf = STRBUF_INIT;
353 strbuf_addstr(&buf, super_prefix);
354 strbuf_addstr(&buf, filename);
356 if (opt->relative && opt->prefix_length) {
357 char *name = strbuf_detach(&buf, NULL);
358 quote_path_relative(name, opt->prefix, &buf);
364 add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
365 strbuf_release(&buf);
370 struct grep_source gs;
373 grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
374 strbuf_release(&buf);
375 hit = grep_source(opt, &gs);
377 grep_source_clear(&gs);
382 static void append_path(struct grep_opt *opt, const void *data, size_t len)
384 struct string_list *path_list = opt->output_priv;
386 if (len == 1 && *(const char *)data == '\0')
388 string_list_append(path_list, xstrndup(data, len));
391 static void run_pager(struct grep_opt *opt, const char *prefix)
393 struct string_list *path_list = opt->output_priv;
394 struct child_process child = CHILD_PROCESS_INIT;
397 for (i = 0; i < path_list->nr; i++)
398 argv_array_push(&child.args, path_list->items[i].string);
402 status = run_command(&child);
407 static void compile_submodule_options(const struct grep_opt *opt,
409 int cached, int untracked,
410 int opt_exclude, int use_index,
411 int pattern_type_arg)
413 struct grep_pat *pattern;
415 if (recurse_submodules)
416 argv_array_push(&submodule_options, "--recurse-submodules");
419 argv_array_push(&submodule_options, "--cached");
421 argv_array_push(&submodule_options, "--no-index");
423 argv_array_push(&submodule_options, "--untracked");
425 argv_array_push(&submodule_options, "--exclude-standard");
428 argv_array_push(&submodule_options, "-v");
429 if (opt->ignore_case)
430 argv_array_push(&submodule_options, "-i");
431 if (opt->word_regexp)
432 argv_array_push(&submodule_options, "-w");
433 switch (opt->binary) {
434 case GREP_BINARY_NOMATCH:
435 argv_array_push(&submodule_options, "-I");
437 case GREP_BINARY_TEXT:
438 argv_array_push(&submodule_options, "-a");
443 if (opt->allow_textconv)
444 argv_array_push(&submodule_options, "--textconv");
445 if (opt->max_depth != -1)
446 argv_array_pushf(&submodule_options, "--max-depth=%d",
449 argv_array_push(&submodule_options, "-n");
451 argv_array_push(&submodule_options, "-h");
453 argv_array_push(&submodule_options, "--full-name");
455 argv_array_push(&submodule_options, "-l");
456 if (opt->unmatch_name_only)
457 argv_array_push(&submodule_options, "-L");
458 if (opt->null_following_name)
459 argv_array_push(&submodule_options, "-z");
461 argv_array_push(&submodule_options, "-c");
463 argv_array_push(&submodule_options, "--break");
465 argv_array_push(&submodule_options, "--heading");
466 if (opt->pre_context)
467 argv_array_pushf(&submodule_options, "--before-context=%d",
469 if (opt->post_context)
470 argv_array_pushf(&submodule_options, "--after-context=%d",
473 argv_array_push(&submodule_options, "-p");
475 argv_array_push(&submodule_options, "-W");
477 argv_array_push(&submodule_options, "--all-match");
479 argv_array_push(&submodule_options, "--debug");
480 if (opt->status_only)
481 argv_array_push(&submodule_options, "-q");
483 switch (pattern_type_arg) {
484 case GREP_PATTERN_TYPE_BRE:
485 argv_array_push(&submodule_options, "-G");
487 case GREP_PATTERN_TYPE_ERE:
488 argv_array_push(&submodule_options, "-E");
490 case GREP_PATTERN_TYPE_FIXED:
491 argv_array_push(&submodule_options, "-F");
493 case GREP_PATTERN_TYPE_PCRE:
494 argv_array_push(&submodule_options, "-P");
496 case GREP_PATTERN_TYPE_UNSPECIFIED:
500 for (pattern = opt->pattern_list; pattern != NULL;
501 pattern = pattern->next) {
502 switch (pattern->token) {
504 argv_array_pushf(&submodule_options, "-e%s",
508 case GREP_OPEN_PAREN:
509 case GREP_CLOSE_PAREN:
512 argv_array_push(&submodule_options, pattern->pattern);
514 /* BODY and HEAD are not used by git-grep */
515 case GREP_PATTERN_BODY:
516 case GREP_PATTERN_HEAD:
522 * Limit number of threads for child process to use.
523 * This is to prevent potential fork-bomb behavior of git-grep as each
524 * submodule process has its own thread pool.
526 argv_array_pushf(&submodule_options, "--threads=%d",
527 (num_threads + 1) / 2);
530 argv_array_push(&submodule_options, "--");
531 for (; *argv; argv++)
532 argv_array_push(&submodule_options, *argv);
536 * Launch child process to grep contents of a submodule
538 static int grep_submodule_launch(struct grep_opt *opt,
539 const struct grep_source *gs)
541 struct child_process cp = CHILD_PROCESS_INIT;
543 const char *end_of_base;
545 struct strbuf child_output = STRBUF_INIT;
547 end_of_base = strchr(gs->name, ':');
548 if (gs->identifier && end_of_base)
549 name = end_of_base + 1;
553 prepare_submodule_repo_env(&cp.env_array);
554 argv_array_push(&cp.env_array, GIT_DIR_ENVIRONMENT);
556 if (opt->relative && opt->prefix_length)
557 argv_array_pushf(&cp.env_array, "%s=%s",
558 GIT_TOPLEVEL_PREFIX_ENVIRONMENT,
561 /* Add super prefix */
562 argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
563 super_prefix ? super_prefix : "",
565 argv_array_push(&cp.args, "grep");
568 * Add basename of parent project
569 * When performing grep on a tree object the filename is prefixed
570 * with the object's name: 'tree-name:filename'. In order to
571 * provide uniformity of output we want to pass the name of the
572 * parent project's object name to the submodule so the submodule can
573 * prefix its output with the parent's name and not its own SHA1.
575 if (gs->identifier && end_of_base)
576 argv_array_pushf(&cp.args, "--parent-basename=%.*s",
577 (int) (end_of_base - gs->name),
581 for (i = 0; i < submodule_options.argc; i++) {
583 * If there is a tree identifier for the submodule, add the
584 * rev after adding the submodule options but before the
585 * pathspecs. To do this we listen for the '--' and insert the
586 * sha1 before pushing the '--' onto the child process argv
589 if (gs->identifier &&
590 !strcmp("--", submodule_options.argv[i])) {
591 argv_array_push(&cp.args, sha1_to_hex(gs->identifier));
594 argv_array_push(&cp.args, submodule_options.argv[i]);
601 * Capture output to output buffer and check the return code from the
602 * child process. A '0' indicates a hit, a '1' indicates no hit and
603 * anything else is an error.
605 status = capture_command(&cp, &child_output, 0);
606 if (status && (status != 1)) {
607 /* flush the buffer */
608 write_or_die(1, child_output.buf, child_output.len);
609 die("process for submodule '%s' failed with exit code: %d",
613 opt->output(opt, child_output.buf, child_output.len);
614 strbuf_release(&child_output);
615 /* invert the return code to make a hit equal to 1 */
620 * Prep grep structures for a submodule grep
621 * sha1: the sha1 of the submodule or NULL if using the working tree
622 * filename: name of the submodule including tree name of parent
623 * path: location of the submodule
625 static int grep_submodule(struct grep_opt *opt, const unsigned char *sha1,
626 const char *filename, const char *path)
628 if (!is_submodule_initialized(path))
630 if (!is_submodule_populated_gently(path, NULL)) {
632 * If searching history, check for the presense of the
633 * submodule's gitdir before skipping the submodule.
636 const struct submodule *sub =
637 submodule_from_path(null_sha1, path);
639 path = git_path("modules/%s", sub->name);
641 if (!(is_directory(path) && is_git_directory(path)))
650 add_work(opt, GREP_SOURCE_SUBMODULE, filename, path, sha1);
655 struct grep_source gs;
658 grep_source_init(&gs, GREP_SOURCE_SUBMODULE,
659 filename, path, sha1);
660 hit = grep_submodule_launch(opt, &gs);
662 grep_source_clear(&gs);
667 static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec,
672 struct strbuf name = STRBUF_INIT;
673 int name_base_len = 0;
675 name_base_len = strlen(super_prefix);
676 strbuf_addstr(&name, super_prefix);
681 for (nr = 0; nr < active_nr; nr++) {
682 const struct cache_entry *ce = active_cache[nr];
683 strbuf_setlen(&name, name_base_len);
684 strbuf_addstr(&name, ce->name);
686 if (S_ISREG(ce->ce_mode) &&
687 match_pathspec(pathspec, name.buf, name.len, 0, NULL,
688 S_ISDIR(ce->ce_mode) ||
689 S_ISGITLINK(ce->ce_mode))) {
691 * If CE_VALID is on, we assume worktree file and its
692 * cache entry are identical, even if worktree file has
693 * been modified, so use cache version instead
695 if (cached || (ce->ce_flags & CE_VALID) ||
696 ce_skip_worktree(ce)) {
697 if (ce_stage(ce) || ce_intent_to_add(ce))
699 hit |= grep_oid(opt, &ce->oid, ce->name,
702 hit |= grep_file(opt, ce->name);
704 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
705 submodule_path_match(pathspec, name.buf, NULL)) {
706 hit |= grep_submodule(opt, NULL, ce->name, ce->name);
714 } while (nr < active_nr &&
715 !strcmp(ce->name, active_cache[nr]->name));
716 nr--; /* compensate for loop control */
718 if (hit && opt->status_only)
722 strbuf_release(&name);
726 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
727 struct tree_desc *tree, struct strbuf *base, int tn_len,
731 enum interesting match = entry_not_interesting;
732 struct name_entry entry;
733 int old_baselen = base->len;
734 struct strbuf name = STRBUF_INIT;
735 int name_base_len = 0;
737 strbuf_addstr(&name, super_prefix);
738 name_base_len = name.len;
741 while (tree_entry(tree, &entry)) {
742 int te_len = tree_entry_len(&entry);
744 if (match != all_entries_interesting) {
745 strbuf_addstr(&name, base->buf + tn_len);
746 match = tree_entry_interesting(&entry, &name,
748 strbuf_setlen(&name, name_base_len);
750 if (match == all_entries_not_interesting)
752 if (match == entry_not_interesting)
756 strbuf_add(base, entry.path, te_len);
758 if (S_ISREG(entry.mode)) {
759 hit |= grep_oid(opt, entry.oid, base->buf, tn_len,
760 check_attr ? base->buf + tn_len : NULL);
761 } else if (S_ISDIR(entry.mode)) {
762 enum object_type type;
763 struct tree_desc sub;
767 data = lock_and_read_oid_file(entry.oid, &type, &size);
769 die(_("unable to read tree (%s)"),
770 oid_to_hex(entry.oid));
772 strbuf_addch(base, '/');
773 init_tree_desc(&sub, data, size);
774 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
777 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
778 hit |= grep_submodule(opt, entry.oid->hash, base->buf,
782 strbuf_setlen(base, old_baselen);
784 if (hit && opt->status_only)
788 strbuf_release(&name);
792 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
793 struct object *obj, const char *name, const char *path)
795 if (obj->type == OBJ_BLOB)
796 return grep_oid(opt, &obj->oid, name, 0, path);
797 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
798 struct tree_desc tree;
805 data = read_object_with_reference(obj->oid.hash, tree_type,
810 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
812 /* Use parent's name as base when recursing submodules */
813 if (recurse_submodules && parent_basename)
814 name = parent_basename;
816 len = name ? strlen(name) : 0;
817 strbuf_init(&base, PATH_MAX + len + 1);
819 strbuf_add(&base, name, len);
820 strbuf_addch(&base, ':');
822 init_tree_desc(&tree, data, size);
823 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
824 obj->type == OBJ_COMMIT);
825 strbuf_release(&base);
829 die(_("unable to grep from object of type %s"), typename(obj->type));
832 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
833 const struct object_array *list)
837 const unsigned int nr = list->nr;
839 for (i = 0; i < nr; i++) {
840 struct object *real_obj;
841 real_obj = deref_tag(list->objects[i].item, NULL, 0);
843 /* load the gitmodules file for this rev */
844 if (recurse_submodules) {
846 gitmodules_config_sha1(real_obj->oid.hash);
848 if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
850 if (opt->status_only)
857 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
858 int exc_std, int use_index)
860 struct dir_struct dir;
863 memset(&dir, 0, sizeof(dir));
865 dir.flags |= DIR_NO_GITLINKS;
867 setup_standard_excludes(&dir);
869 fill_directory(&dir, pathspec);
870 for (i = 0; i < dir.nr; i++) {
871 if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
873 hit |= grep_file(opt, dir.entries[i]->name);
874 if (hit && opt->status_only)
880 static int context_callback(const struct option *opt, const char *arg,
883 struct grep_opt *grep_opt = opt->value;
888 grep_opt->pre_context = grep_opt->post_context = 0;
891 value = strtol(arg, (char **)&endp, 10);
893 return error(_("switch `%c' expects a numerical value"),
896 grep_opt->pre_context = grep_opt->post_context = value;
900 static int file_callback(const struct option *opt, const char *arg, int unset)
902 struct grep_opt *grep_opt = opt->value;
903 int from_stdin = !strcmp(arg, "-");
906 struct strbuf sb = STRBUF_INIT;
908 patterns = from_stdin ? stdin : fopen(arg, "r");
910 die_errno(_("cannot open '%s'"), arg);
911 while (strbuf_getline(&sb, patterns) == 0) {
912 /* ignore empty line like grep does */
916 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
925 static int not_callback(const struct option *opt, const char *arg, int unset)
927 struct grep_opt *grep_opt = opt->value;
928 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
932 static int and_callback(const struct option *opt, const char *arg, int unset)
934 struct grep_opt *grep_opt = opt->value;
935 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
939 static int open_callback(const struct option *opt, const char *arg, int unset)
941 struct grep_opt *grep_opt = opt->value;
942 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
946 static int close_callback(const struct option *opt, const char *arg, int unset)
948 struct grep_opt *grep_opt = opt->value;
949 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
953 static int pattern_callback(const struct option *opt, const char *arg,
956 struct grep_opt *grep_opt = opt->value;
957 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
961 int cmd_grep(int argc, const char **argv, const char *prefix)
964 int cached = 0, untracked = 0, opt_exclude = -1;
965 int seen_dashdash = 0;
966 int external_grep_allowed__ignored;
967 const char *show_in_pager = NULL, *default_pager = "dummy";
969 struct object_array list = OBJECT_ARRAY_INIT;
970 struct pathspec pathspec;
971 struct string_list path_list = STRING_LIST_INIT_NODUP;
975 int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
978 struct option options[] = {
979 OPT_BOOL(0, "cached", &cached,
980 N_("search in index instead of in the work tree")),
981 OPT_NEGBIT(0, "no-index", &use_index,
982 N_("find in contents not managed by git"), 1),
983 OPT_BOOL(0, "untracked", &untracked,
984 N_("search in both tracked and untracked files")),
985 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
986 N_("ignore files specified via '.gitignore'"), 1),
987 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
988 N_("recursively search in each submodule")),
989 OPT_STRING(0, "parent-basename", &parent_basename,
991 N_("prepend parent project's basename to output")),
993 OPT_BOOL('v', "invert-match", &opt.invert,
994 N_("show non-matching lines")),
995 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
996 N_("case insensitive matching")),
997 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
998 N_("match patterns only at word boundaries")),
999 OPT_SET_INT('a', "text", &opt.binary,
1000 N_("process binary files as text"), GREP_BINARY_TEXT),
1001 OPT_SET_INT('I', NULL, &opt.binary,
1002 N_("don't match patterns in binary files"),
1003 GREP_BINARY_NOMATCH),
1004 OPT_BOOL(0, "textconv", &opt.allow_textconv,
1005 N_("process binary files with textconv filters")),
1006 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
1007 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
1010 OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
1011 N_("use extended POSIX regular expressions"),
1012 GREP_PATTERN_TYPE_ERE),
1013 OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
1014 N_("use basic POSIX regular expressions (default)"),
1015 GREP_PATTERN_TYPE_BRE),
1016 OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
1017 N_("interpret patterns as fixed strings"),
1018 GREP_PATTERN_TYPE_FIXED),
1019 OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
1020 N_("use Perl-compatible regular expressions"),
1021 GREP_PATTERN_TYPE_PCRE),
1023 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
1024 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
1025 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
1026 OPT_NEGBIT(0, "full-name", &opt.relative,
1027 N_("show filenames relative to top directory"), 1),
1028 OPT_BOOL('l', "files-with-matches", &opt.name_only,
1029 N_("show only filenames instead of matching lines")),
1030 OPT_BOOL(0, "name-only", &opt.name_only,
1031 N_("synonym for --files-with-matches")),
1032 OPT_BOOL('L', "files-without-match",
1033 &opt.unmatch_name_only,
1034 N_("show only the names of files without match")),
1035 OPT_BOOL('z', "null", &opt.null_following_name,
1036 N_("print NUL after filenames")),
1037 OPT_BOOL('c', "count", &opt.count,
1038 N_("show the number of matches instead of matching lines")),
1039 OPT__COLOR(&opt.color, N_("highlight matches")),
1040 OPT_BOOL(0, "break", &opt.file_break,
1041 N_("print empty line between matches from different files")),
1042 OPT_BOOL(0, "heading", &opt.heading,
1043 N_("show filename only once above matches from same file")),
1045 OPT_CALLBACK('C', "context", &opt, N_("n"),
1046 N_("show <n> context lines before and after matches"),
1048 OPT_INTEGER('B', "before-context", &opt.pre_context,
1049 N_("show <n> context lines before matches")),
1050 OPT_INTEGER('A', "after-context", &opt.post_context,
1051 N_("show <n> context lines after matches")),
1052 OPT_INTEGER(0, "threads", &num_threads,
1053 N_("use <n> worker threads")),
1054 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
1056 OPT_BOOL('p', "show-function", &opt.funcname,
1057 N_("show a line with the function name before matches")),
1058 OPT_BOOL('W', "function-context", &opt.funcbody,
1059 N_("show the surrounding function")),
1061 OPT_CALLBACK('f', NULL, &opt, N_("file"),
1062 N_("read patterns from file"), file_callback),
1063 { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
1064 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
1065 { OPTION_CALLBACK, 0, "and", &opt, NULL,
1066 N_("combine patterns specified with -e"),
1067 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
1068 OPT_BOOL(0, "or", &dummy, ""),
1069 { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
1070 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
1071 { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
1072 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1074 { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
1075 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
1077 OPT__QUIET(&opt.status_only,
1078 N_("indicate hit with exit status without output")),
1079 OPT_BOOL(0, "all-match", &opt.all_match,
1080 N_("show only matches from files that match all patterns")),
1081 { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
1082 N_("show parse tree for grep expression"),
1083 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
1085 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
1086 N_("pager"), N_("show matching files in the pager"),
1087 PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
1088 OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
1089 N_("allow calling of grep(1) (ignored by this build)")),
1093 init_grep_defaults();
1094 git_config(grep_cmd_config, NULL);
1095 grep_init(&opt, prefix);
1096 super_prefix = get_super_prefix();
1099 * If there is no -- then the paths must exist in the working
1100 * tree. If there is no explicit pattern specified with -e or
1101 * -f, we take the first unrecognized non option to be the
1102 * pattern, but then what follows it must be zero or more
1103 * valid refs up to the -- (if exists), and then existing
1104 * paths. If there is an explicit pattern, then the first
1105 * unrecognized non option is the beginning of the refs list
1106 * that continues up to the -- (if exists), and then paths.
1108 argc = parse_options(argc, argv, prefix, options, grep_usage,
1109 PARSE_OPT_KEEP_DASHDASH |
1110 PARSE_OPT_STOP_AT_NON_OPTION);
1111 grep_commit_pattern_type(pattern_type_arg, &opt);
1113 if (use_index && !startup_info->have_repository) {
1115 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1119 /* die the same way as if we did it at the beginning */
1120 setup_git_directory();
1124 * skip a -- separator; we know it cannot be
1125 * separating revisions from pathnames if
1126 * we haven't even had any patterns yet
1128 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1133 /* First unrecognized non-option token */
1134 if (argc > 0 && !opt.pattern_list) {
1135 append_grep_pattern(&opt, argv[0], "command line", 0,
1141 if (show_in_pager == default_pager)
1142 show_in_pager = git_pager(1);
1143 if (show_in_pager) {
1146 opt.null_following_name = 1;
1147 opt.output_priv = &path_list;
1148 opt.output = append_path;
1149 string_list_append(&path_list, show_in_pager);
1152 if (!opt.pattern_list)
1153 die(_("no pattern given."));
1154 if (!opt.fixed && opt.ignore_case)
1155 opt.regflags |= REG_ICASE;
1157 compile_grep_patterns(&opt);
1160 * We have to find "--" in a separate pass, because its presence
1161 * influences how we will parse arguments that come before it.
1163 for (i = 0; i < argc; i++) {
1164 if (!strcmp(argv[i], "--")) {
1171 * Resolve any rev arguments. If we have a dashdash, then everything up
1172 * to it must resolve as a rev. If not, then we stop at the first
1173 * non-rev and assume everything else is a path.
1175 allow_revs = use_index && !untracked;
1176 for (i = 0; i < argc; i++) {
1177 const char *arg = argv[i];
1178 struct object_id oid;
1179 struct object_context oc;
1180 struct object *object;
1182 if (!strcmp(arg, "--")) {
1189 die(_("--no-index or --untracked cannot be used with revs"));
1193 if (get_sha1_with_context(arg, 0, oid.hash, &oc)) {
1195 die(_("unable to resolve revision: %s"), arg);
1199 object = parse_object_or_die(oid.hash, arg);
1201 verify_non_filename(prefix, arg);
1202 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1206 * Anything left over is presumed to be a path. But in the non-dashdash
1207 * "do what I mean" case, we verify and complain when that isn't true.
1209 if (!seen_dashdash) {
1211 for (j = i; j < argc; j++)
1212 verify_filename(prefix, argv[j], j == i && allow_revs);
1215 parse_pathspec(&pathspec, 0,
1216 PATHSPEC_PREFER_CWD |
1217 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1219 pathspec.max_depth = opt.max_depth;
1220 pathspec.recursive = 1;
1223 if (list.nr || cached || show_in_pager)
1225 else if (num_threads == 0)
1226 num_threads = GREP_NUM_THREADS_DEFAULT;
1227 else if (num_threads < 0)
1228 die(_("invalid number of threads specified (%d)"), num_threads);
1235 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1236 && (opt.pre_context || opt.post_context ||
1237 opt.file_break || opt.funcbody))
1238 skip_first_line = 1;
1239 start_threads(&opt);
1243 if (recurse_submodules) {
1244 gitmodules_config();
1245 compile_submodule_options(&opt, argv + i, cached, untracked,
1246 opt_exclude, use_index,
1250 if (show_in_pager && (cached || list.nr))
1251 die(_("--open-files-in-pager only works on the worktree"));
1253 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1254 const char *pager = path_list.items[0].string;
1255 int len = strlen(pager);
1257 if (len > 4 && is_dir_sep(pager[len - 5]))
1260 if (opt.ignore_case && !strcmp("less", pager))
1261 string_list_append(&path_list, "-I");
1263 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1264 struct strbuf buf = STRBUF_INIT;
1265 strbuf_addf(&buf, "+/%s%s",
1266 strcmp("less", pager) ? "" : "*",
1267 opt.pattern_list->pattern);
1268 string_list_append(&path_list, buf.buf);
1269 strbuf_detach(&buf, NULL);
1273 if (recurse_submodules && (!use_index || untracked))
1274 die(_("option not supported with --recurse-submodules."));
1276 if (!show_in_pager && !opt.status_only)
1279 if (!use_index && (untracked || cached))
1280 die(_("--cached or --untracked cannot be used with --no-index."));
1282 if (!use_index || untracked) {
1283 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1284 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1285 } else if (0 <= opt_exclude) {
1286 die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1287 } else if (!list.nr) {
1291 hit = grep_cache(&opt, &pathspec, cached);
1294 die(_("both --cached and trees are given."));
1295 hit = grep_objects(&opt, &pathspec, &list);
1300 if (hit && show_in_pager)
1301 run_pager(&opt, prefix);
1302 clear_pathspec(&pathspec);
1303 free_grep_patterns(&opt);