4 * Copyright (c) 2006 Junio C Hamano
10 #include "repository.h"
16 #include "tree-walk.h"
18 #include "parse-options.h"
19 #include "string-list.h"
20 #include "run-command.h"
27 #include "submodule.h"
28 #include "submodule-config.h"
29 #include "object-name.h"
30 #include "object-store.h"
32 #include "write-or-die.h"
34 static const char *grep_prefix
;
36 static char const * const grep_usage
[] = {
37 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
41 static int recurse_submodules
;
43 static int num_threads
;
45 static pthread_t
*threads
;
47 /* We use one producer thread and THREADS consumer
48 * threads. The producer adds struct work_items to 'todo' and the
49 * consumers pick work items from the same array.
52 struct grep_source source
;
57 /* In the range [todo_done, todo_start) in 'todo' we have work_items
58 * that have been or are processed by a consumer thread. We haven't
59 * written the result for these to stdout yet.
61 * The work_items in [todo_start, todo_end) are waiting to be picked
62 * up by a consumer thread.
64 * The ranges are modulo TODO_SIZE.
67 static struct work_item todo
[TODO_SIZE
];
68 static int todo_start
;
72 /* Has all work items been added? */
73 static int all_work_added
;
75 static struct repository
**repos_to_free
;
76 static size_t repos_to_free_nr
, repos_to_free_alloc
;
78 /* This lock protects all the variables above. */
79 static pthread_mutex_t grep_mutex
;
81 static inline void grep_lock(void)
83 pthread_mutex_lock(&grep_mutex
);
86 static inline void grep_unlock(void)
88 pthread_mutex_unlock(&grep_mutex
);
91 /* Signalled when a new work_item is added to todo. */
92 static pthread_cond_t cond_add
;
94 /* Signalled when the result from one work_item is written to
97 static pthread_cond_t cond_write
;
99 /* Signalled when we are finished with everything. */
100 static pthread_cond_t cond_result
;
102 static int skip_first_line
;
104 static void add_work(struct grep_opt
*opt
, struct grep_source
*gs
)
106 if (opt
->binary
!= GREP_BINARY_TEXT
)
107 grep_source_load_driver(gs
, opt
->repo
->index
);
111 while ((todo_end
+1) % ARRAY_SIZE(todo
) == todo_done
) {
112 pthread_cond_wait(&cond_write
, &grep_mutex
);
115 todo
[todo_end
].source
= *gs
;
116 todo
[todo_end
].done
= 0;
117 strbuf_reset(&todo
[todo_end
].out
);
118 todo_end
= (todo_end
+ 1) % ARRAY_SIZE(todo
);
120 pthread_cond_signal(&cond_add
);
124 static struct work_item
*get_work(void)
126 struct work_item
*ret
;
129 while (todo_start
== todo_end
&& !all_work_added
) {
130 pthread_cond_wait(&cond_add
, &grep_mutex
);
133 if (todo_start
== todo_end
&& all_work_added
) {
136 ret
= &todo
[todo_start
];
137 todo_start
= (todo_start
+ 1) % ARRAY_SIZE(todo
);
143 static void work_done(struct work_item
*w
)
149 old_done
= todo_done
;
150 for(; todo
[todo_done
].done
&& todo_done
!= todo_start
;
151 todo_done
= (todo_done
+1) % ARRAY_SIZE(todo
)) {
152 w
= &todo
[todo_done
];
154 const char *p
= w
->out
.buf
;
155 size_t len
= w
->out
.len
;
157 /* Skip the leading hunk mark of the first file. */
158 if (skip_first_line
) {
167 write_or_die(1, p
, len
);
169 grep_source_clear(&w
->source
);
172 if (old_done
!= todo_done
)
173 pthread_cond_signal(&cond_write
);
175 if (all_work_added
&& todo_done
== todo_end
)
176 pthread_cond_signal(&cond_result
);
181 static void free_repos(void)
185 for (i
= 0; i
< repos_to_free_nr
; i
++) {
186 repo_clear(repos_to_free
[i
]);
187 free(repos_to_free
[i
]);
189 FREE_AND_NULL(repos_to_free
);
190 repos_to_free_nr
= 0;
191 repos_to_free_alloc
= 0;
194 static void *run(void *arg
)
197 struct grep_opt
*opt
= arg
;
200 struct work_item
*w
= get_work();
204 opt
->output_priv
= w
;
205 hit
|= grep_source(opt
, &w
->source
);
206 grep_source_clear_data(&w
->source
);
209 free_grep_patterns(opt
);
212 return (void*) (intptr_t) hit
;
215 static void strbuf_out(struct grep_opt
*opt
, const void *buf
, size_t size
)
217 struct work_item
*w
= opt
->output_priv
;
218 strbuf_add(&w
->out
, buf
, size
);
221 static void start_threads(struct grep_opt
*opt
)
225 pthread_mutex_init(&grep_mutex
, NULL
);
226 pthread_mutex_init(&grep_attr_mutex
, NULL
);
227 pthread_cond_init(&cond_add
, NULL
);
228 pthread_cond_init(&cond_write
, NULL
);
229 pthread_cond_init(&cond_result
, NULL
);
231 enable_obj_read_lock();
233 for (i
= 0; i
< ARRAY_SIZE(todo
); i
++) {
234 strbuf_init(&todo
[i
].out
, 0);
237 CALLOC_ARRAY(threads
, num_threads
);
238 for (i
= 0; i
< num_threads
; i
++) {
240 struct grep_opt
*o
= grep_opt_dup(opt
);
241 o
->output
= strbuf_out
;
242 compile_grep_patterns(o
);
243 err
= pthread_create(&threads
[i
], NULL
, run
, o
);
246 die(_("grep: failed to create thread: %s"),
251 static int wait_all(void)
257 BUG("Never call this function unless you have started threads");
262 /* Wait until all work is done. */
263 while (todo_done
!= todo_end
)
264 pthread_cond_wait(&cond_result
, &grep_mutex
);
266 /* Wake up all the consumer threads so they can see that there
267 * is no more work to do.
269 pthread_cond_broadcast(&cond_add
);
272 for (i
= 0; i
< num_threads
; i
++) {
274 pthread_join(threads
[i
], &h
);
275 hit
|= (int) (intptr_t) h
;
280 pthread_mutex_destroy(&grep_mutex
);
281 pthread_mutex_destroy(&grep_attr_mutex
);
282 pthread_cond_destroy(&cond_add
);
283 pthread_cond_destroy(&cond_write
);
284 pthread_cond_destroy(&cond_result
);
286 disable_obj_read_lock();
291 static int grep_cmd_config(const char *var
, const char *value
, void *cb
)
293 int st
= grep_config(var
, value
, cb
);
294 if (git_color_default_config(var
, value
, NULL
) < 0)
297 if (!strcmp(var
, "grep.threads")) {
298 num_threads
= git_config_int(var
, value
);
300 die(_("invalid number of threads specified (%d) for %s"),
302 else if (!HAVE_THREADS
&& num_threads
> 1) {
304 * TRANSLATORS: %s is the configuration
305 * variable for tweaking threads, currently
308 warning(_("no threads support, ignoring %s"), var
);
313 if (!strcmp(var
, "submodule.recurse"))
314 recurse_submodules
= git_config_bool(var
, value
);
319 static void grep_source_name(struct grep_opt
*opt
, const char *filename
,
320 int tree_name_len
, struct strbuf
*out
)
324 if (opt
->null_following_name
) {
325 if (opt
->relative
&& grep_prefix
) {
326 struct strbuf rel_buf
= STRBUF_INIT
;
327 const char *rel_name
=
328 relative_path(filename
+ tree_name_len
,
329 grep_prefix
, &rel_buf
);
332 strbuf_add(out
, filename
, tree_name_len
);
334 strbuf_addstr(out
, rel_name
);
335 strbuf_release(&rel_buf
);
337 strbuf_addstr(out
, filename
);
342 if (opt
->relative
&& grep_prefix
)
343 quote_path(filename
+ tree_name_len
, grep_prefix
, out
, 0);
345 quote_c_style(filename
+ tree_name_len
, out
, NULL
, 0);
348 strbuf_insert(out
, 0, filename
, tree_name_len
);
351 static int grep_oid(struct grep_opt
*opt
, const struct object_id
*oid
,
352 const char *filename
, int tree_name_len
,
355 struct strbuf pathbuf
= STRBUF_INIT
;
356 struct grep_source gs
;
358 grep_source_name(opt
, filename
, tree_name_len
, &pathbuf
);
359 grep_source_init_oid(&gs
, pathbuf
.buf
, path
, oid
, opt
->repo
);
360 strbuf_release(&pathbuf
);
362 if (num_threads
> 1) {
364 * add_work() copies gs and thus assumes ownership of
365 * its fields, so do not call grep_source_clear()
372 hit
= grep_source(opt
, &gs
);
374 grep_source_clear(&gs
);
379 static int grep_file(struct grep_opt
*opt
, const char *filename
)
381 struct strbuf buf
= STRBUF_INIT
;
382 struct grep_source gs
;
384 grep_source_name(opt
, filename
, 0, &buf
);
385 grep_source_init_file(&gs
, buf
.buf
, filename
);
386 strbuf_release(&buf
);
388 if (num_threads
> 1) {
390 * add_work() copies gs and thus assumes ownership of
391 * its fields, so do not call grep_source_clear()
398 hit
= grep_source(opt
, &gs
);
400 grep_source_clear(&gs
);
405 static void append_path(struct grep_opt
*opt
, const void *data
, size_t len
)
407 struct string_list
*path_list
= opt
->output_priv
;
409 if (len
== 1 && *(const char *)data
== '\0')
411 string_list_append_nodup(path_list
, xstrndup(data
, len
));
414 static void run_pager(struct grep_opt
*opt
, const char *prefix
)
416 struct string_list
*path_list
= opt
->output_priv
;
417 struct child_process child
= CHILD_PROCESS_INIT
;
420 for (i
= 0; i
< path_list
->nr
; i
++)
421 strvec_push(&child
.args
, path_list
->items
[i
].string
);
425 status
= run_command(&child
);
430 static int grep_cache(struct grep_opt
*opt
,
431 const struct pathspec
*pathspec
, int cached
);
432 static int grep_tree(struct grep_opt
*opt
, const struct pathspec
*pathspec
,
433 struct tree_desc
*tree
, struct strbuf
*base
, int tn_len
,
436 static int grep_submodule(struct grep_opt
*opt
,
437 const struct pathspec
*pathspec
,
438 const struct object_id
*oid
,
439 const char *filename
, const char *path
, int cached
)
441 struct repository
*subrepo
;
442 struct repository
*superproject
= opt
->repo
;
443 struct grep_opt subopt
;
446 if (!is_submodule_active(superproject
, path
))
449 subrepo
= xmalloc(sizeof(*subrepo
));
450 if (repo_submodule_init(subrepo
, superproject
, path
, null_oid())) {
454 ALLOC_GROW(repos_to_free
, repos_to_free_nr
+ 1, repos_to_free_alloc
);
455 repos_to_free
[repos_to_free_nr
++] = subrepo
;
458 * NEEDSWORK: repo_read_gitmodules() might call
459 * add_to_alternates_memory() via config_from_gitmodules(). This
460 * operation causes a race condition with concurrent object readings
461 * performed by the worker threads. That's why we need obj_read_lock()
462 * here. It should be removed once it's no longer necessary to add the
463 * subrepo's odbs to the in-memory alternates list.
468 * NEEDSWORK: when reading a submodule, the sparsity settings in the
469 * superproject are incorrectly forgotten or misused. For example:
471 * 1. "command_requires_full_index"
472 * When this setting is turned on for `grep`, only the superproject
473 * knows it. All the submodules are read with their own configs
474 * and get prepare_repo_settings()'d. Therefore, these submodules
475 * "forget" the sparse-index feature switch. As a result, the index
476 * of these submodules are expanded unexpectedly.
478 * 2. "core_apply_sparse_checkout"
479 * When running `grep` in the superproject, this setting is
480 * populated using the superproject's configs. However, once
481 * initialized, this config is globally accessible and is read by
482 * prepare_repo_settings() for the submodules. For instance, if a
483 * submodule is using a sparse-checkout, however, the superproject
484 * is not, the result is that the config from the superproject will
485 * dictate the behavior for the submodule, making it "forget" its
486 * sparse-checkout state.
488 * 3. "core_sparse_checkout_cone"
491 * Note that this list is not exhaustive.
493 repo_read_gitmodules(subrepo
, 0);
496 * All code paths tested by test code no longer need submodule ODBs to
497 * be added as alternates, but add it to the list just in case.
498 * Submodule ODBs added through add_submodule_odb_by_path() will be
499 * lazily registered as alternates when needed (and except in an
500 * unexpected code interaction, it won't be needed).
502 add_submodule_odb_by_path(subrepo
->objects
->odb
->path
);
505 memcpy(&subopt
, opt
, sizeof(subopt
));
506 subopt
.repo
= subrepo
;
509 enum object_type object_type
;
510 struct tree_desc tree
;
513 struct strbuf base
= STRBUF_INIT
;
516 object_type
= oid_object_info(subrepo
, oid
, NULL
);
518 data
= read_object_with_reference(subrepo
,
522 die(_("unable to read tree (%s)"), oid_to_hex(oid
));
524 strbuf_addstr(&base
, filename
);
525 strbuf_addch(&base
, '/');
527 init_tree_desc(&tree
, data
, size
);
528 hit
= grep_tree(&subopt
, pathspec
, &tree
, &base
, base
.len
,
529 object_type
== OBJ_COMMIT
);
530 strbuf_release(&base
);
533 hit
= grep_cache(&subopt
, pathspec
, cached
);
539 static int grep_cache(struct grep_opt
*opt
,
540 const struct pathspec
*pathspec
, int cached
)
542 struct repository
*repo
= opt
->repo
;
545 struct strbuf name
= STRBUF_INIT
;
546 int name_base_len
= 0;
547 if (repo
->submodule_prefix
) {
548 name_base_len
= strlen(repo
->submodule_prefix
);
549 strbuf_addstr(&name
, repo
->submodule_prefix
);
552 if (repo_read_index(repo
) < 0)
553 die(_("index file corrupt"));
555 for (nr
= 0; nr
< repo
->index
->cache_nr
; nr
++) {
556 const struct cache_entry
*ce
= repo
->index
->cache
[nr
];
558 if (!cached
&& ce_skip_worktree(ce
))
561 strbuf_setlen(&name
, name_base_len
);
562 strbuf_addstr(&name
, ce
->name
);
563 if (S_ISSPARSEDIR(ce
->ce_mode
)) {
564 enum object_type type
;
565 struct tree_desc tree
;
569 data
= repo_read_object_file(the_repository
, &ce
->oid
,
571 init_tree_desc(&tree
, data
, size
);
573 hit
|= grep_tree(opt
, pathspec
, &tree
, &name
, 0, 0);
574 strbuf_setlen(&name
, name_base_len
);
575 strbuf_addstr(&name
, ce
->name
);
577 } else if (S_ISREG(ce
->ce_mode
) &&
578 match_pathspec(repo
->index
, pathspec
, name
.buf
, name
.len
, 0, NULL
,
579 S_ISDIR(ce
->ce_mode
) ||
580 S_ISGITLINK(ce
->ce_mode
))) {
582 * If CE_VALID is on, we assume worktree file and its
583 * cache entry are identical, even if worktree file has
584 * been modified, so use cache version instead
586 if (cached
|| (ce
->ce_flags
& CE_VALID
)) {
587 if (ce_stage(ce
) || ce_intent_to_add(ce
))
589 hit
|= grep_oid(opt
, &ce
->oid
, name
.buf
,
592 hit
|= grep_file(opt
, name
.buf
);
594 } else if (recurse_submodules
&& S_ISGITLINK(ce
->ce_mode
) &&
595 submodule_path_match(repo
->index
, pathspec
, name
.buf
, NULL
)) {
596 hit
|= grep_submodule(opt
, pathspec
, NULL
, ce
->name
,
605 } while (nr
< repo
->index
->cache_nr
&&
606 !strcmp(ce
->name
, repo
->index
->cache
[nr
]->name
));
607 nr
--; /* compensate for loop control */
609 if (hit
&& opt
->status_only
)
613 strbuf_release(&name
);
617 static int grep_tree(struct grep_opt
*opt
, const struct pathspec
*pathspec
,
618 struct tree_desc
*tree
, struct strbuf
*base
, int tn_len
,
621 struct repository
*repo
= opt
->repo
;
623 enum interesting match
= entry_not_interesting
;
624 struct name_entry entry
;
625 int old_baselen
= base
->len
;
626 struct strbuf name
= STRBUF_INIT
;
627 int name_base_len
= 0;
628 if (repo
->submodule_prefix
) {
629 strbuf_addstr(&name
, repo
->submodule_prefix
);
630 name_base_len
= name
.len
;
633 while (tree_entry(tree
, &entry
)) {
634 int te_len
= tree_entry_len(&entry
);
636 if (match
!= all_entries_interesting
) {
637 strbuf_addstr(&name
, base
->buf
+ tn_len
);
638 match
= tree_entry_interesting(repo
->index
,
641 strbuf_setlen(&name
, name_base_len
);
643 if (match
== all_entries_not_interesting
)
645 if (match
== entry_not_interesting
)
649 strbuf_add(base
, entry
.path
, te_len
);
651 if (S_ISREG(entry
.mode
)) {
652 hit
|= grep_oid(opt
, &entry
.oid
, base
->buf
, tn_len
,
653 check_attr
? base
->buf
+ tn_len
: NULL
);
654 } else if (S_ISDIR(entry
.mode
)) {
655 enum object_type type
;
656 struct tree_desc sub
;
660 data
= repo_read_object_file(the_repository
,
661 &entry
.oid
, &type
, &size
);
663 die(_("unable to read tree (%s)"),
664 oid_to_hex(&entry
.oid
));
666 strbuf_addch(base
, '/');
667 init_tree_desc(&sub
, data
, size
);
668 hit
|= grep_tree(opt
, pathspec
, &sub
, base
, tn_len
,
671 } else if (recurse_submodules
&& S_ISGITLINK(entry
.mode
)) {
672 hit
|= grep_submodule(opt
, pathspec
, &entry
.oid
,
673 base
->buf
, base
->buf
+ tn_len
,
677 strbuf_setlen(base
, old_baselen
);
679 if (hit
&& opt
->status_only
)
683 strbuf_release(&name
);
687 static int grep_object(struct grep_opt
*opt
, const struct pathspec
*pathspec
,
688 struct object
*obj
, const char *name
, const char *path
)
690 if (obj
->type
== OBJ_BLOB
)
691 return grep_oid(opt
, &obj
->oid
, name
, 0, path
);
692 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
693 struct tree_desc tree
;
699 data
= read_object_with_reference(opt
->repo
,
703 die(_("unable to read tree (%s)"), oid_to_hex(&obj
->oid
));
705 len
= name
? strlen(name
) : 0;
706 strbuf_init(&base
, PATH_MAX
+ len
+ 1);
708 strbuf_add(&base
, name
, len
);
709 strbuf_addch(&base
, ':');
711 init_tree_desc(&tree
, data
, size
);
712 hit
= grep_tree(opt
, pathspec
, &tree
, &base
, base
.len
,
713 obj
->type
== OBJ_COMMIT
);
714 strbuf_release(&base
);
718 die(_("unable to grep from object of type %s"), type_name(obj
->type
));
721 static int grep_objects(struct grep_opt
*opt
, const struct pathspec
*pathspec
,
722 const struct object_array
*list
)
726 const unsigned int nr
= list
->nr
;
728 for (i
= 0; i
< nr
; i
++) {
729 struct object
*real_obj
;
732 real_obj
= deref_tag(opt
->repo
, list
->objects
[i
].item
,
737 char hex
[GIT_MAX_HEXSZ
+ 1];
738 const char *name
= list
->objects
[i
].name
;
741 oid_to_hex_r(hex
, &list
->objects
[i
].item
->oid
);
744 die(_("invalid object '%s' given."), name
);
747 /* load the gitmodules file for this rev */
748 if (recurse_submodules
) {
749 submodule_free(opt
->repo
);
751 gitmodules_config_oid(&real_obj
->oid
);
754 if (grep_object(opt
, pathspec
, real_obj
, list
->objects
[i
].name
,
755 list
->objects
[i
].path
)) {
757 if (opt
->status_only
)
764 static int grep_directory(struct grep_opt
*opt
, const struct pathspec
*pathspec
,
765 int exc_std
, int use_index
)
767 struct dir_struct dir
= DIR_INIT
;
771 dir
.flags
|= DIR_NO_GITLINKS
;
773 setup_standard_excludes(&dir
);
775 fill_directory(&dir
, opt
->repo
->index
, pathspec
);
776 for (i
= 0; i
< dir
.nr
; i
++) {
777 hit
|= grep_file(opt
, dir
.entries
[i
]->name
);
778 if (hit
&& opt
->status_only
)
785 static int context_callback(const struct option
*opt
, const char *arg
,
788 struct grep_opt
*grep_opt
= opt
->value
;
793 grep_opt
->pre_context
= grep_opt
->post_context
= 0;
796 value
= strtol(arg
, (char **)&endp
, 10);
798 return error(_("switch `%c' expects a numerical value"),
801 grep_opt
->pre_context
= grep_opt
->post_context
= value
;
805 static int file_callback(const struct option
*opt
, const char *arg
, int unset
)
807 struct grep_opt
*grep_opt
= opt
->value
;
811 struct strbuf sb
= STRBUF_INIT
;
813 BUG_ON_OPT_NEG(unset
);
815 from_stdin
= !strcmp(arg
, "-");
816 patterns
= from_stdin
? stdin
: fopen(arg
, "r");
818 die_errno(_("cannot open '%s'"), arg
);
819 while (strbuf_getline(&sb
, patterns
) == 0) {
820 /* ignore empty line like grep does */
824 append_grep_pat(grep_opt
, sb
.buf
, sb
.len
, arg
, ++lno
,
833 static int not_callback(const struct option
*opt
, const char *arg
, int unset
)
835 struct grep_opt
*grep_opt
= opt
->value
;
836 BUG_ON_OPT_NEG(unset
);
838 append_grep_pattern(grep_opt
, "--not", "command line", 0, GREP_NOT
);
842 static int and_callback(const struct option
*opt
, const char *arg
, int unset
)
844 struct grep_opt
*grep_opt
= opt
->value
;
845 BUG_ON_OPT_NEG(unset
);
847 append_grep_pattern(grep_opt
, "--and", "command line", 0, GREP_AND
);
851 static int open_callback(const struct option
*opt
, const char *arg
, int unset
)
853 struct grep_opt
*grep_opt
= opt
->value
;
854 BUG_ON_OPT_NEG(unset
);
856 append_grep_pattern(grep_opt
, "(", "command line", 0, GREP_OPEN_PAREN
);
860 static int close_callback(const struct option
*opt
, const char *arg
, int unset
)
862 struct grep_opt
*grep_opt
= opt
->value
;
863 BUG_ON_OPT_NEG(unset
);
865 append_grep_pattern(grep_opt
, ")", "command line", 0, GREP_CLOSE_PAREN
);
869 static int pattern_callback(const struct option
*opt
, const char *arg
,
872 struct grep_opt
*grep_opt
= opt
->value
;
873 BUG_ON_OPT_NEG(unset
);
874 append_grep_pattern(grep_opt
, arg
, "-e option", 0, GREP_PATTERN
);
878 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
881 int cached
= 0, untracked
= 0, opt_exclude
= -1;
882 int seen_dashdash
= 0;
883 int external_grep_allowed__ignored
;
884 const char *show_in_pager
= NULL
, *default_pager
= "dummy";
886 struct object_array list
= OBJECT_ARRAY_INIT
;
887 struct pathspec pathspec
;
888 struct string_list path_list
= STRING_LIST_INIT_DUP
;
894 struct option options
[] = {
895 OPT_BOOL(0, "cached", &cached
,
896 N_("search in index instead of in the work tree")),
897 OPT_NEGBIT(0, "no-index", &use_index
,
898 N_("find in contents not managed by git"), 1),
899 OPT_BOOL(0, "untracked", &untracked
,
900 N_("search in both tracked and untracked files")),
901 OPT_SET_INT(0, "exclude-standard", &opt_exclude
,
902 N_("ignore files specified via '.gitignore'"), 1),
903 OPT_BOOL(0, "recurse-submodules", &recurse_submodules
,
904 N_("recursively search in each submodule")),
906 OPT_BOOL('v', "invert-match", &opt
.invert
,
907 N_("show non-matching lines")),
908 OPT_BOOL('i', "ignore-case", &opt
.ignore_case
,
909 N_("case insensitive matching")),
910 OPT_BOOL('w', "word-regexp", &opt
.word_regexp
,
911 N_("match patterns only at word boundaries")),
912 OPT_SET_INT('a', "text", &opt
.binary
,
913 N_("process binary files as text"), GREP_BINARY_TEXT
),
914 OPT_SET_INT('I', NULL
, &opt
.binary
,
915 N_("don't match patterns in binary files"),
916 GREP_BINARY_NOMATCH
),
917 OPT_BOOL(0, "textconv", &opt
.allow_textconv
,
918 N_("process binary files with textconv filters")),
919 OPT_SET_INT('r', "recursive", &opt
.max_depth
,
920 N_("search in subdirectories (default)"), -1),
921 { OPTION_INTEGER
, 0, "max-depth", &opt
.max_depth
, N_("depth"),
922 N_("descend at most <depth> levels"), PARSE_OPT_NONEG
,
925 OPT_SET_INT('E', "extended-regexp", &opt
.pattern_type_option
,
926 N_("use extended POSIX regular expressions"),
927 GREP_PATTERN_TYPE_ERE
),
928 OPT_SET_INT('G', "basic-regexp", &opt
.pattern_type_option
,
929 N_("use basic POSIX regular expressions (default)"),
930 GREP_PATTERN_TYPE_BRE
),
931 OPT_SET_INT('F', "fixed-strings", &opt
.pattern_type_option
,
932 N_("interpret patterns as fixed strings"),
933 GREP_PATTERN_TYPE_FIXED
),
934 OPT_SET_INT('P', "perl-regexp", &opt
.pattern_type_option
,
935 N_("use Perl-compatible regular expressions"),
936 GREP_PATTERN_TYPE_PCRE
),
938 OPT_BOOL('n', "line-number", &opt
.linenum
, N_("show line numbers")),
939 OPT_BOOL(0, "column", &opt
.columnnum
, N_("show column number of first match")),
940 OPT_NEGBIT('h', NULL
, &opt
.pathname
, N_("don't show filenames"), 1),
941 OPT_BIT('H', NULL
, &opt
.pathname
, N_("show filenames"), 1),
942 OPT_NEGBIT(0, "full-name", &opt
.relative
,
943 N_("show filenames relative to top directory"), 1),
944 OPT_BOOL('l', "files-with-matches", &opt
.name_only
,
945 N_("show only filenames instead of matching lines")),
946 OPT_BOOL(0, "name-only", &opt
.name_only
,
947 N_("synonym for --files-with-matches")),
948 OPT_BOOL('L', "files-without-match",
949 &opt
.unmatch_name_only
,
950 N_("show only the names of files without match")),
951 OPT_BOOL_F('z', "null", &opt
.null_following_name
,
952 N_("print NUL after filenames"),
953 PARSE_OPT_NOCOMPLETE
),
954 OPT_BOOL('o', "only-matching", &opt
.only_matching
,
955 N_("show only matching parts of a line")),
956 OPT_BOOL('c', "count", &opt
.count
,
957 N_("show the number of matches instead of matching lines")),
958 OPT__COLOR(&opt
.color
, N_("highlight matches")),
959 OPT_BOOL(0, "break", &opt
.file_break
,
960 N_("print empty line between matches from different files")),
961 OPT_BOOL(0, "heading", &opt
.heading
,
962 N_("show filename only once above matches from same file")),
964 OPT_CALLBACK('C', "context", &opt
, N_("n"),
965 N_("show <n> context lines before and after matches"),
967 OPT_INTEGER('B', "before-context", &opt
.pre_context
,
968 N_("show <n> context lines before matches")),
969 OPT_INTEGER('A', "after-context", &opt
.post_context
,
970 N_("show <n> context lines after matches")),
971 OPT_INTEGER(0, "threads", &num_threads
,
972 N_("use <n> worker threads")),
973 OPT_NUMBER_CALLBACK(&opt
, N_("shortcut for -C NUM"),
975 OPT_BOOL('p', "show-function", &opt
.funcname
,
976 N_("show a line with the function name before matches")),
977 OPT_BOOL('W', "function-context", &opt
.funcbody
,
978 N_("show the surrounding function")),
980 OPT_CALLBACK('f', NULL
, &opt
, N_("file"),
981 N_("read patterns from file"), file_callback
),
982 OPT_CALLBACK_F('e', NULL
, &opt
, N_("pattern"),
983 N_("match <pattern>"), PARSE_OPT_NONEG
, pattern_callback
),
984 OPT_CALLBACK_F(0, "and", &opt
, NULL
,
985 N_("combine patterns specified with -e"),
986 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, and_callback
),
987 OPT_BOOL(0, "or", &dummy
, ""),
988 OPT_CALLBACK_F(0, "not", &opt
, NULL
, "",
989 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, not_callback
),
990 OPT_CALLBACK_F('(', NULL
, &opt
, NULL
, "",
991 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
993 OPT_CALLBACK_F(')', NULL
, &opt
, NULL
, "",
994 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
996 OPT__QUIET(&opt
.status_only
,
997 N_("indicate hit with exit status without output")),
998 OPT_BOOL(0, "all-match", &opt
.all_match
,
999 N_("show only matches from files that match all patterns")),
1001 { OPTION_STRING
, 'O', "open-files-in-pager", &show_in_pager
,
1002 N_("pager"), N_("show matching files in the pager"),
1003 PARSE_OPT_OPTARG
| PARSE_OPT_NOCOMPLETE
,
1004 NULL
, (intptr_t)default_pager
},
1005 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored
,
1006 N_("allow calling of grep(1) (ignored by this build)"),
1007 PARSE_OPT_NOCOMPLETE
),
1008 OPT_INTEGER('m', "max-count", &opt
.max_count
,
1009 N_("maximum number of results per file")),
1012 grep_prefix
= prefix
;
1014 grep_init(&opt
, the_repository
);
1015 git_config(grep_cmd_config
, &opt
);
1018 * If there is no -- then the paths must exist in the working
1019 * tree. If there is no explicit pattern specified with -e or
1020 * -f, we take the first unrecognized non option to be the
1021 * pattern, but then what follows it must be zero or more
1022 * valid refs up to the -- (if exists), and then existing
1023 * paths. If there is an explicit pattern, then the first
1024 * unrecognized non option is the beginning of the refs list
1025 * that continues up to the -- (if exists), and then paths.
1027 argc
= parse_options(argc
, argv
, prefix
, options
, grep_usage
,
1028 PARSE_OPT_KEEP_DASHDASH
|
1029 PARSE_OPT_STOP_AT_NON_OPTION
);
1031 if (the_repository
->gitdir
) {
1032 prepare_repo_settings(the_repository
);
1033 the_repository
->settings
.command_requires_full_index
= 0;
1036 if (use_index
&& !startup_info
->have_repository
) {
1038 git_config_get_bool("grep.fallbacktonoindex", &fallback
);
1042 /* die the same way as if we did it at the beginning */
1043 setup_git_directory();
1045 /* Ignore --recurse-submodules if --no-index is given or implied */
1047 recurse_submodules
= 0;
1050 * skip a -- separator; we know it cannot be
1051 * separating revisions from pathnames if
1052 * we haven't even had any patterns yet
1054 if (argc
> 0 && !opt
.pattern_list
&& !strcmp(argv
[0], "--")) {
1059 /* First unrecognized non-option token */
1060 if (argc
> 0 && !opt
.pattern_list
) {
1061 append_grep_pattern(&opt
, argv
[0], "command line", 0,
1067 if (show_in_pager
== default_pager
)
1068 show_in_pager
= git_pager(1);
1069 if (show_in_pager
) {
1072 opt
.null_following_name
= 1;
1073 opt
.output_priv
= &path_list
;
1074 opt
.output
= append_path
;
1075 string_list_append(&path_list
, show_in_pager
);
1078 if (!opt
.pattern_list
)
1079 die(_("no pattern given"));
1081 /* --only-matching has no effect with --invert. */
1083 opt
.only_matching
= 0;
1086 * We have to find "--" in a separate pass, because its presence
1087 * influences how we will parse arguments that come before it.
1089 for (i
= 0; i
< argc
; i
++) {
1090 if (!strcmp(argv
[i
], "--")) {
1097 * Resolve any rev arguments. If we have a dashdash, then everything up
1098 * to it must resolve as a rev. If not, then we stop at the first
1099 * non-rev and assume everything else is a path.
1101 allow_revs
= use_index
&& !untracked
;
1102 for (i
= 0; i
< argc
; i
++) {
1103 const char *arg
= argv
[i
];
1104 struct object_id oid
;
1105 struct object_context oc
;
1106 struct object
*object
;
1108 if (!strcmp(arg
, "--")) {
1115 die(_("--no-index or --untracked cannot be used with revs"));
1119 if (get_oid_with_context(the_repository
, arg
,
1120 GET_OID_RECORD_PATH
,
1123 die(_("unable to resolve revision: %s"), arg
);
1127 object
= parse_object_or_die(&oid
, arg
);
1129 verify_non_filename(prefix
, arg
);
1130 add_object_array_with_path(object
, arg
, &list
, oc
.mode
, oc
.path
);
1135 * Anything left over is presumed to be a path. But in the non-dashdash
1136 * "do what I mean" case, we verify and complain when that isn't true.
1138 if (!seen_dashdash
) {
1140 for (j
= i
; j
< argc
; j
++)
1141 verify_filename(prefix
, argv
[j
], j
== i
&& allow_revs
);
1144 parse_pathspec(&pathspec
, 0,
1145 PATHSPEC_PREFER_CWD
|
1146 (opt
.max_depth
!= -1 ? PATHSPEC_MAXDEPTH_VALID
: 0),
1148 pathspec
.max_depth
= opt
.max_depth
;
1149 pathspec
.recursive
= 1;
1150 pathspec
.recurse_submodules
= !!recurse_submodules
;
1152 if (recurse_submodules
&& untracked
)
1153 die(_("--untracked not supported with --recurse-submodules"));
1156 * Optimize out the case where the amount of matches is limited to zero.
1157 * We do this to keep results consistent with GNU grep(1).
1159 if (opt
.max_count
== 0)
1162 if (show_in_pager
) {
1163 if (num_threads
> 1)
1164 warning(_("invalid option combination, ignoring --threads"));
1166 } else if (!HAVE_THREADS
&& num_threads
> 1) {
1167 warning(_("no threads support, ignoring --threads"));
1169 } else if (num_threads
< 0)
1170 die(_("invalid number of threads specified (%d)"), num_threads
);
1171 else if (num_threads
== 0)
1172 num_threads
= HAVE_THREADS
? online_cpus() : 1;
1174 if (num_threads
> 1) {
1176 BUG("Somebody got num_threads calculation wrong!");
1177 if (!(opt
.name_only
|| opt
.unmatch_name_only
|| opt
.count
)
1178 && (opt
.pre_context
|| opt
.post_context
||
1179 opt
.file_break
|| opt
.funcbody
))
1180 skip_first_line
= 1;
1183 * Pre-read gitmodules (if not read already) and force eager
1184 * initialization of packed_git to prevent racy lazy
1185 * reading/initialization once worker threads are started.
1187 if (recurse_submodules
)
1188 repo_read_gitmodules(the_repository
, 1);
1189 if (startup_info
->have_repository
)
1190 (void)get_packed_git(the_repository
);
1192 start_threads(&opt
);
1195 * The compiled patterns on the main path are only
1196 * used when not using threading. Otherwise
1197 * start_threads() above calls compile_grep_patterns()
1200 compile_grep_patterns(&opt
);
1203 if (show_in_pager
&& (cached
|| list
.nr
))
1204 die(_("--open-files-in-pager only works on the worktree"));
1206 if (show_in_pager
&& opt
.pattern_list
&& !opt
.pattern_list
->next
) {
1207 const char *pager
= path_list
.items
[0].string
;
1208 int len
= strlen(pager
);
1210 if (len
> 4 && is_dir_sep(pager
[len
- 5]))
1213 if (opt
.ignore_case
&& !strcmp("less", pager
))
1214 string_list_append(&path_list
, "-I");
1216 if (!strcmp("less", pager
) || !strcmp("vi", pager
)) {
1217 struct strbuf buf
= STRBUF_INIT
;
1218 strbuf_addf(&buf
, "+/%s%s",
1219 strcmp("less", pager
) ? "" : "*",
1220 opt
.pattern_list
->pattern
);
1221 string_list_append_nodup(&path_list
,
1222 strbuf_detach(&buf
, NULL
));
1226 if (!show_in_pager
&& !opt
.status_only
)
1229 die_for_incompatible_opt3(!use_index
, "--no-index",
1230 untracked
, "--untracked",
1231 cached
, "--cached");
1233 if (!use_index
|| untracked
) {
1234 int use_exclude
= (opt_exclude
< 0) ? use_index
: !!opt_exclude
;
1235 hit
= grep_directory(&opt
, &pathspec
, use_exclude
, use_index
);
1236 } else if (0 <= opt_exclude
) {
1237 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1238 } else if (!list
.nr
) {
1242 hit
= grep_cache(&opt
, &pathspec
, cached
);
1245 die(_("both --cached and trees are given"));
1247 hit
= grep_objects(&opt
, &pathspec
, &list
);
1250 if (num_threads
> 1)
1252 if (hit
&& show_in_pager
)
1253 run_pager(&opt
, prefix
);
1254 clear_pathspec(&pathspec
);
1255 string_list_clear(&path_list
, 0);
1256 free_grep_patterns(&opt
);
1257 object_array_clear(&list
);