4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
18 #include "string-list.h"
22 #include "thread-utils.h"
25 static char const * const grep_usage
[] = {
26 "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
30 static int use_threads
= 1;
34 static pthread_t threads
[THREADS
];
36 static void *load_sha1(const unsigned char *sha1
, unsigned long *size
,
38 static void *load_file(const char *filename
, size_t *sz
);
40 enum work_type
{WORK_SHA1
, WORK_FILE
};
42 /* We use one producer thread and THREADS consumer
43 * threads. The producer adds struct work_items to 'todo' and the
44 * consumers pick work items from the same array.
51 /* if type == WORK_SHA1, then 'identifier' is a SHA1,
52 * otherwise type == WORK_FILE, and 'identifier' is a NUL
53 * terminated filename.
60 /* In the range [todo_done, todo_start) in 'todo' we have work_items
61 * that have been or are processed by a consumer thread. We haven't
62 * written the result for these to stdout yet.
64 * The work_items in [todo_start, todo_end) are waiting to be picked
65 * up by a consumer thread.
67 * The ranges are modulo TODO_SIZE.
70 static struct work_item todo
[TODO_SIZE
];
71 static int todo_start
;
75 /* Has all work items been added? */
76 static int all_work_added
;
78 /* This lock protects all the variables above. */
79 static pthread_mutex_t grep_mutex
;
81 /* Used to serialize calls to read_sha1_file. */
82 static pthread_mutex_t read_sha1_mutex
;
84 #define grep_lock() pthread_mutex_lock(&grep_mutex)
85 #define grep_unlock() pthread_mutex_unlock(&grep_mutex)
86 #define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
87 #define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
89 /* Signalled when a new work_item is added to todo. */
90 static pthread_cond_t cond_add
;
92 /* Signalled when the result from one work_item is written to
95 static pthread_cond_t cond_write
;
97 /* Signalled when we are finished with everything. */
98 static pthread_cond_t cond_result
;
100 static int print_hunk_marks_between_files
;
101 static int printed_something
;
103 static void add_work(enum work_type type
, char *name
, void *id
)
107 while ((todo_end
+1) % ARRAY_SIZE(todo
) == todo_done
) {
108 pthread_cond_wait(&cond_write
, &grep_mutex
);
111 todo
[todo_end
].type
= type
;
112 todo
[todo_end
].name
= name
;
113 todo
[todo_end
].identifier
= id
;
114 todo
[todo_end
].done
= 0;
115 strbuf_reset(&todo
[todo_end
].out
);
116 todo_end
= (todo_end
+ 1) % ARRAY_SIZE(todo
);
118 pthread_cond_signal(&cond_add
);
122 static struct work_item
*get_work(void)
124 struct work_item
*ret
;
127 while (todo_start
== todo_end
&& !all_work_added
) {
128 pthread_cond_wait(&cond_add
, &grep_mutex
);
131 if (todo_start
== todo_end
&& all_work_added
) {
134 ret
= &todo
[todo_start
];
135 todo_start
= (todo_start
+ 1) % ARRAY_SIZE(todo
);
141 static void grep_sha1_async(struct grep_opt
*opt
, char *name
,
142 const unsigned char *sha1
)
147 add_work(WORK_SHA1
, name
, s
);
150 static void grep_file_async(struct grep_opt
*opt
, char *name
,
151 const char *filename
)
153 add_work(WORK_FILE
, name
, xstrdup(filename
));
156 static void work_done(struct work_item
*w
)
162 old_done
= todo_done
;
163 for(; todo
[todo_done
].done
&& todo_done
!= todo_start
;
164 todo_done
= (todo_done
+1) % ARRAY_SIZE(todo
)) {
165 w
= &todo
[todo_done
];
167 if (print_hunk_marks_between_files
&& printed_something
)
168 write_or_die(1, "--\n", 3);
169 write_or_die(1, w
->out
.buf
, w
->out
.len
);
170 printed_something
= 1;
176 if (old_done
!= todo_done
)
177 pthread_cond_signal(&cond_write
);
179 if (all_work_added
&& todo_done
== todo_end
)
180 pthread_cond_signal(&cond_result
);
185 static void *run(void *arg
)
188 struct grep_opt
*opt
= arg
;
191 struct work_item
*w
= get_work();
195 opt
->output_priv
= w
;
196 if (w
->type
== WORK_SHA1
) {
198 void* data
= load_sha1(w
->identifier
, &sz
, w
->name
);
201 hit
|= grep_buffer(opt
, w
->name
, data
, sz
);
204 } else if (w
->type
== WORK_FILE
) {
206 void* data
= load_file(w
->identifier
, &sz
);
208 hit
|= grep_buffer(opt
, w
->name
, data
, sz
);
217 free_grep_patterns(arg
);
220 return (void*) (intptr_t) hit
;
223 static void strbuf_out(struct grep_opt
*opt
, const void *buf
, size_t size
)
225 struct work_item
*w
= opt
->output_priv
;
226 strbuf_add(&w
->out
, buf
, size
);
229 static void start_threads(struct grep_opt
*opt
)
233 pthread_mutex_init(&grep_mutex
, NULL
);
234 pthread_mutex_init(&read_sha1_mutex
, NULL
);
235 pthread_cond_init(&cond_add
, NULL
);
236 pthread_cond_init(&cond_write
, NULL
);
237 pthread_cond_init(&cond_result
, NULL
);
239 for (i
= 0; i
< ARRAY_SIZE(todo
); i
++) {
240 strbuf_init(&todo
[i
].out
, 0);
243 for (i
= 0; i
< ARRAY_SIZE(threads
); i
++) {
245 struct grep_opt
*o
= grep_opt_dup(opt
);
246 o
->output
= strbuf_out
;
247 compile_grep_patterns(o
);
248 err
= pthread_create(&threads
[i
], NULL
, run
, o
);
251 die("grep: failed to create thread: %s",
256 static int wait_all(void)
264 /* Wait until all work is done. */
265 while (todo_done
!= todo_end
)
266 pthread_cond_wait(&cond_result
, &grep_mutex
);
268 /* Wake up all the consumer threads so they can see that there
269 * is no more work to do.
271 pthread_cond_broadcast(&cond_add
);
274 for (i
= 0; i
< ARRAY_SIZE(threads
); i
++) {
276 pthread_join(threads
[i
], &h
);
277 hit
|= (int) (intptr_t) h
;
280 pthread_mutex_destroy(&grep_mutex
);
281 pthread_mutex_destroy(&read_sha1_mutex
);
282 pthread_cond_destroy(&cond_add
);
283 pthread_cond_destroy(&cond_write
);
284 pthread_cond_destroy(&cond_result
);
288 #else /* !NO_PTHREADS */
289 #define read_sha1_lock()
290 #define read_sha1_unlock()
292 static int wait_all(void)
298 static int grep_config(const char *var
, const char *value
, void *cb
)
300 struct grep_opt
*opt
= cb
;
303 switch (userdiff_config(var
, value
)) {
309 if (!strcmp(var
, "color.grep"))
310 opt
->color
= git_config_colorbool(var
, value
, -1);
311 else if (!strcmp(var
, "color.grep.context"))
312 color
= opt
->color_context
;
313 else if (!strcmp(var
, "color.grep.filename"))
314 color
= opt
->color_filename
;
315 else if (!strcmp(var
, "color.grep.function"))
316 color
= opt
->color_function
;
317 else if (!strcmp(var
, "color.grep.linenumber"))
318 color
= opt
->color_lineno
;
319 else if (!strcmp(var
, "color.grep.match"))
320 color
= opt
->color_match
;
321 else if (!strcmp(var
, "color.grep.selected"))
322 color
= opt
->color_selected
;
323 else if (!strcmp(var
, "color.grep.separator"))
324 color
= opt
->color_sep
;
326 return git_color_default_config(var
, value
, cb
);
329 return config_error_nonbool(var
);
330 color_parse(value
, var
, color
);
336 * Return non-zero if max_depth is negative or path has no more then max_depth
339 static int accept_subdir(const char *path
, int max_depth
)
344 while ((path
= strchr(path
, '/')) != NULL
) {
354 * Return non-zero if name is a subdirectory of match and is not too deep.
356 static int is_subdir(const char *name
, int namelen
,
357 const char *match
, int matchlen
, int max_depth
)
359 if (matchlen
> namelen
|| strncmp(name
, match
, matchlen
))
362 if (name
[matchlen
] == '\0') /* exact match */
365 if (!matchlen
|| match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
366 return accept_subdir(name
+ matchlen
+ 1, max_depth
);
372 * git grep pathspecs are somewhat different from diff-tree pathspecs;
373 * pathname wildcards are allowed.
375 static int pathspec_matches(const char **paths
, const char *name
, int max_depth
)
378 if (!paths
|| !*paths
)
379 return accept_subdir(name
, max_depth
);
380 namelen
= strlen(name
);
381 for (i
= 0; paths
[i
]; i
++) {
382 const char *match
= paths
[i
];
383 int matchlen
= strlen(match
);
384 const char *cp
, *meta
;
386 if (is_subdir(name
, namelen
, match
, matchlen
, max_depth
))
388 if (!fnmatch(match
, name
, 0))
390 if (name
[namelen
-1] != '/')
393 /* We are being asked if the directory ("name") is worth
396 * Find the longest leading directory name that does
397 * not have metacharacter in the pathspec; the name
398 * we are looking at must overlap with that directory.
400 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
402 if (ch
== '*' || ch
== '[' || ch
== '?') {
408 meta
= cp
; /* fully literal */
410 if (namelen
<= meta
- match
) {
411 /* Looking at "Documentation/" and
412 * the pattern says "Documentation/howto/", or
413 * "Documentation/diff*.txt". The name we
414 * have should match prefix.
416 if (!memcmp(match
, name
, namelen
))
421 if (meta
- match
< namelen
) {
422 /* Looking at "Documentation/howto/" and
423 * the pattern says "Documentation/h*";
424 * match up to "Do.../h"; this avoids descending
425 * into "Documentation/technical/".
427 if (!memcmp(match
, name
, meta
- match
))
435 static void *lock_and_read_sha1_file(const unsigned char *sha1
, enum object_type
*type
, unsigned long *size
)
441 data
= read_sha1_file(sha1
, type
, size
);
444 data
= read_sha1_file(sha1
, type
, size
);
449 static void *load_sha1(const unsigned char *sha1
, unsigned long *size
,
452 enum object_type type
;
453 void *data
= lock_and_read_sha1_file(sha1
, &type
, size
);
456 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
461 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
,
462 const char *filename
, int tree_name_len
)
464 struct strbuf pathbuf
= STRBUF_INIT
;
467 if (opt
->relative
&& opt
->prefix_length
) {
468 quote_path_relative(filename
+ tree_name_len
, -1, &pathbuf
,
470 strbuf_insert(&pathbuf
, 0, filename
, tree_name_len
);
472 strbuf_addstr(&pathbuf
, filename
);
475 name
= strbuf_detach(&pathbuf
, NULL
);
479 grep_sha1_async(opt
, name
, sha1
);
486 void *data
= load_sha1(sha1
, &sz
, name
);
490 hit
= grep_buffer(opt
, name
, data
, sz
);
498 static void *load_file(const char *filename
, size_t *sz
)
504 if (lstat(filename
, &st
) < 0) {
507 error("'%s': %s", filename
, strerror(errno
));
510 if (!S_ISREG(st
.st_mode
))
512 *sz
= xsize_t(st
.st_size
);
513 i
= open(filename
, O_RDONLY
);
516 data
= xmalloc(*sz
+ 1);
517 if (st
.st_size
!= read_in_full(i
, data
, *sz
)) {
518 error("'%s': short read %s", filename
, strerror(errno
));
528 static int grep_file(struct grep_opt
*opt
, const char *filename
)
530 struct strbuf buf
= STRBUF_INIT
;
533 if (opt
->relative
&& opt
->prefix_length
)
534 quote_path_relative(filename
, -1, &buf
, opt
->prefix
);
536 strbuf_addstr(&buf
, filename
);
537 name
= strbuf_detach(&buf
, NULL
);
541 grep_file_async(opt
, name
, filename
);
548 void *data
= load_file(filename
, &sz
);
552 hit
= grep_buffer(opt
, name
, data
, sz
);
560 static void append_path(struct grep_opt
*opt
, const void *data
, size_t len
)
562 struct string_list
*path_list
= opt
->output_priv
;
564 if (len
== 1 && *(char *)data
== '\0')
566 string_list_append(xstrndup(data
, len
), path_list
);
569 static void run_pager(struct grep_opt
*opt
, const char *prefix
)
571 struct string_list
*path_list
= opt
->output_priv
;
572 char **argv
= xmalloc(sizeof(const char *) * (path_list
->nr
+ 1));
575 for (i
= 0; i
< path_list
->nr
; i
++)
576 argv
[i
] = path_list
->items
[i
].string
;
577 argv
[path_list
->nr
] = NULL
;
581 execvp(argv
[0], argv
);
582 error("Could not run pager %s: %s", argv
[0], strerror(errno
));
585 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
591 for (nr
= 0; nr
< active_nr
; nr
++) {
592 struct cache_entry
*ce
= active_cache
[nr
];
593 if (!S_ISREG(ce
->ce_mode
))
595 if (!pathspec_matches(paths
, ce
->name
, opt
->max_depth
))
598 * If CE_VALID is on, we assume worktree file and its cache entry
599 * are identical, even if worktree file has been modified, so use
600 * cache version instead
602 if (cached
|| (ce
->ce_flags
& CE_VALID
) || ce_skip_worktree(ce
)) {
605 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
608 hit
|= grep_file(opt
, ce
->name
);
612 } while (nr
< active_nr
&&
613 !strcmp(ce
->name
, active_cache
[nr
]->name
));
614 nr
--; /* compensate for loop control */
616 if (hit
&& opt
->status_only
)
622 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
623 struct tree_desc
*tree
,
624 const char *tree_name
, const char *base
)
628 struct name_entry entry
;
630 int tn_len
= strlen(tree_name
);
631 struct strbuf pathbuf
;
633 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
636 strbuf_add(&pathbuf
, tree_name
, tn_len
);
637 strbuf_addch(&pathbuf
, ':');
638 tn_len
= pathbuf
.len
;
640 strbuf_addstr(&pathbuf
, base
);
643 while (tree_entry(tree
, &entry
)) {
644 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
646 strbuf_add(&pathbuf
, entry
.path
, te_len
);
648 if (S_ISDIR(entry
.mode
))
649 /* Match "abc/" against pathspec to
650 * decide if we want to descend into "abc"
653 strbuf_addch(&pathbuf
, '/');
655 down
= pathbuf
.buf
+ tn_len
;
656 if (!pathspec_matches(paths
, down
, opt
->max_depth
))
658 else if (S_ISREG(entry
.mode
))
659 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
660 else if (S_ISDIR(entry
.mode
)) {
661 enum object_type type
;
662 struct tree_desc sub
;
666 data
= lock_and_read_sha1_file(entry
.sha1
, &type
, &size
);
668 die("unable to read tree (%s)",
669 sha1_to_hex(entry
.sha1
));
670 init_tree_desc(&sub
, data
, size
);
671 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
674 if (hit
&& opt
->status_only
)
677 strbuf_release(&pathbuf
);
681 static int grep_object(struct grep_opt
*opt
, const char **paths
,
682 struct object
*obj
, const char *name
)
684 if (obj
->type
== OBJ_BLOB
)
685 return grep_sha1(opt
, obj
->sha1
, name
, 0);
686 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
687 struct tree_desc tree
;
691 data
= read_object_with_reference(obj
->sha1
, tree_type
,
694 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
695 init_tree_desc(&tree
, data
, size
);
696 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
700 die("unable to grep from object of type %s", typename(obj
->type
));
703 static int grep_directory(struct grep_opt
*opt
, const char **paths
)
705 struct dir_struct dir
;
708 memset(&dir
, 0, sizeof(dir
));
709 setup_standard_excludes(&dir
);
711 fill_directory(&dir
, paths
);
712 for (i
= 0; i
< dir
.nr
; i
++) {
713 hit
|= grep_file(opt
, dir
.entries
[i
]->name
);
714 if (hit
&& opt
->status_only
)
717 free_grep_patterns(opt
);
721 static int context_callback(const struct option
*opt
, const char *arg
,
724 struct grep_opt
*grep_opt
= opt
->value
;
729 grep_opt
->pre_context
= grep_opt
->post_context
= 0;
732 value
= strtol(arg
, (char **)&endp
, 10);
734 return error("switch `%c' expects a numerical value",
737 grep_opt
->pre_context
= grep_opt
->post_context
= value
;
741 static int file_callback(const struct option
*opt
, const char *arg
, int unset
)
743 struct grep_opt
*grep_opt
= opt
->value
;
746 struct strbuf sb
= STRBUF_INIT
;
748 patterns
= fopen(arg
, "r");
750 die_errno("cannot open '%s'", arg
);
751 while (strbuf_getline(&sb
, patterns
, '\n') == 0) {
755 /* ignore empty line like grep does */
759 s
= strbuf_detach(&sb
, &len
);
760 append_grep_pat(grep_opt
, s
, len
, arg
, ++lno
, GREP_PATTERN
);
767 static int not_callback(const struct option
*opt
, const char *arg
, int unset
)
769 struct grep_opt
*grep_opt
= opt
->value
;
770 append_grep_pattern(grep_opt
, "--not", "command line", 0, GREP_NOT
);
774 static int and_callback(const struct option
*opt
, const char *arg
, int unset
)
776 struct grep_opt
*grep_opt
= opt
->value
;
777 append_grep_pattern(grep_opt
, "--and", "command line", 0, GREP_AND
);
781 static int open_callback(const struct option
*opt
, const char *arg
, int unset
)
783 struct grep_opt
*grep_opt
= opt
->value
;
784 append_grep_pattern(grep_opt
, "(", "command line", 0, GREP_OPEN_PAREN
);
788 static int close_callback(const struct option
*opt
, const char *arg
, int unset
)
790 struct grep_opt
*grep_opt
= opt
->value
;
791 append_grep_pattern(grep_opt
, ")", "command line", 0, GREP_CLOSE_PAREN
);
795 static int pattern_callback(const struct option
*opt
, const char *arg
,
798 struct grep_opt
*grep_opt
= opt
->value
;
799 append_grep_pattern(grep_opt
, arg
, "-e option", 0, GREP_PATTERN
);
803 static int help_callback(const struct option
*opt
, const char *arg
, int unset
)
808 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
812 int seen_dashdash
= 0;
813 int external_grep_allowed__ignored
;
814 const char *show_in_pager
= NULL
, *default_pager
= "dummy";
816 struct object_array list
= { 0, 0, NULL
};
817 const char **paths
= NULL
;
818 struct string_list path_list
= { NULL
, 0, 0, 0 };
821 int nongit
= 0, use_index
= 1;
822 struct option options
[] = {
823 OPT_BOOLEAN(0, "cached", &cached
,
824 "search in index instead of in the work tree"),
825 OPT_BOOLEAN(0, "index", &use_index
,
826 "--no-index finds in contents not managed by git"),
828 OPT_BOOLEAN('v', "invert-match", &opt
.invert
,
829 "show non-matching lines"),
830 OPT_BOOLEAN('i', "ignore-case", &opt
.ignore_case
,
831 "case insensitive matching"),
832 OPT_BOOLEAN('w', "word-regexp", &opt
.word_regexp
,
833 "match patterns only at word boundaries"),
834 OPT_SET_INT('a', "text", &opt
.binary
,
835 "process binary files as text", GREP_BINARY_TEXT
),
836 OPT_SET_INT('I', NULL
, &opt
.binary
,
837 "don't match patterns in binary files",
838 GREP_BINARY_NOMATCH
),
839 { OPTION_INTEGER
, 0, "max-depth", &opt
.max_depth
, "depth",
840 "descend at most <depth> levels", PARSE_OPT_NONEG
,
843 OPT_BIT('E', "extended-regexp", &opt
.regflags
,
844 "use extended POSIX regular expressions", REG_EXTENDED
),
845 OPT_NEGBIT('G', "basic-regexp", &opt
.regflags
,
846 "use basic POSIX regular expressions (default)",
848 OPT_BOOLEAN('F', "fixed-strings", &opt
.fixed
,
849 "interpret patterns as fixed strings"),
851 OPT_BOOLEAN('n', NULL
, &opt
.linenum
, "show line numbers"),
852 OPT_NEGBIT('h', NULL
, &opt
.pathname
, "don't show filenames", 1),
853 OPT_BIT('H', NULL
, &opt
.pathname
, "show filenames", 1),
854 OPT_NEGBIT(0, "full-name", &opt
.relative
,
855 "show filenames relative to top directory", 1),
856 OPT_BOOLEAN('l', "files-with-matches", &opt
.name_only
,
857 "show only filenames instead of matching lines"),
858 OPT_BOOLEAN(0, "name-only", &opt
.name_only
,
859 "synonym for --files-with-matches"),
860 OPT_BOOLEAN('L', "files-without-match",
861 &opt
.unmatch_name_only
,
862 "show only the names of files without match"),
863 OPT_BOOLEAN('z', "null", &opt
.null_following_name
,
864 "print NUL after filenames"),
865 OPT_BOOLEAN('c', "count", &opt
.count
,
866 "show the number of matches instead of matching lines"),
867 OPT__COLOR(&opt
.color
, "highlight matches"),
869 OPT_CALLBACK('C', NULL
, &opt
, "n",
870 "show <n> context lines before and after matches",
872 OPT_INTEGER('B', NULL
, &opt
.pre_context
,
873 "show <n> context lines before matches"),
874 OPT_INTEGER('A', NULL
, &opt
.post_context
,
875 "show <n> context lines after matches"),
876 OPT_NUMBER_CALLBACK(&opt
, "shortcut for -C NUM",
878 OPT_BOOLEAN('p', "show-function", &opt
.funcname
,
879 "show a line with the function name before matches"),
881 OPT_CALLBACK('f', NULL
, &opt
, "file",
882 "read patterns from file", file_callback
),
883 { OPTION_CALLBACK
, 'e', NULL
, &opt
, "pattern",
884 "match <pattern>", PARSE_OPT_NONEG
, pattern_callback
},
885 { OPTION_CALLBACK
, 0, "and", &opt
, NULL
,
886 "combine patterns specified with -e",
887 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, and_callback
},
888 OPT_BOOLEAN(0, "or", &dummy
, ""),
889 { OPTION_CALLBACK
, 0, "not", &opt
, NULL
, "",
890 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, not_callback
},
891 { OPTION_CALLBACK
, '(', NULL
, &opt
, NULL
, "",
892 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
894 { OPTION_CALLBACK
, ')', NULL
, &opt
, NULL
, "",
895 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
897 OPT_BOOLEAN('q', "quiet", &opt
.status_only
,
898 "indicate hit with exit status without output"),
899 OPT_BOOLEAN(0, "all-match", &opt
.all_match
,
900 "show only matches from files that match all patterns"),
902 { OPTION_STRING
, 'O', "open-files-in-pager", &show_in_pager
,
903 "pager", "show matching files in the pager",
904 PARSE_OPT_OPTARG
, NULL
, (intptr_t)default_pager
},
905 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored
,
906 "allow calling of grep(1) (ignored by this build)"),
907 { OPTION_CALLBACK
, 0, "help-all", &options
, NULL
, "show usage",
908 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
, help_callback
},
912 prefix
= setup_git_directory_gently(&nongit
);
915 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
916 * to show usage information and exit.
918 if (argc
== 2 && !strcmp(argv
[1], "-h"))
919 usage_with_options(grep_usage
, options
);
921 memset(&opt
, 0, sizeof(opt
));
923 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
926 opt
.pattern_tail
= &opt
.pattern_list
;
927 opt
.header_tail
= &opt
.header_list
;
928 opt
.regflags
= REG_NEWLINE
;
931 strcpy(opt
.color_context
, "");
932 strcpy(opt
.color_filename
, "");
933 strcpy(opt
.color_function
, "");
934 strcpy(opt
.color_lineno
, "");
935 strcpy(opt
.color_match
, GIT_COLOR_BOLD_RED
);
936 strcpy(opt
.color_selected
, "");
937 strcpy(opt
.color_sep
, GIT_COLOR_CYAN
);
939 git_config(grep_config
, &opt
);
941 opt
.color
= git_use_color_default
;
944 * If there is no -- then the paths must exist in the working
945 * tree. If there is no explicit pattern specified with -e or
946 * -f, we take the first unrecognized non option to be the
947 * pattern, but then what follows it must be zero or more
948 * valid refs up to the -- (if exists), and then existing
949 * paths. If there is an explicit pattern, then the first
950 * unrecognized non option is the beginning of the refs list
951 * that continues up to the -- (if exists), and then paths.
953 argc
= parse_options(argc
, argv
, prefix
, options
, grep_usage
,
954 PARSE_OPT_KEEP_DASHDASH
|
955 PARSE_OPT_STOP_AT_NON_OPTION
|
956 PARSE_OPT_NO_INTERNAL_HELP
);
958 if (use_index
&& nongit
)
959 /* die the same way as if we did it at the beginning */
960 setup_git_directory();
963 * skip a -- separator; we know it cannot be
964 * separating revisions from pathnames if
965 * we haven't even had any patterns yet
967 if (argc
> 0 && !opt
.pattern_list
&& !strcmp(argv
[0], "--")) {
972 /* First unrecognized non-option token */
973 if (argc
> 0 && !opt
.pattern_list
) {
974 append_grep_pattern(&opt
, argv
[0], "command line", 0,
981 if (show_in_pager
== default_pager
) {
982 show_in_pager
= getenv("GIT_PAGER");
984 show_in_pager
= getenv("PAGER");
986 show_in_pager
= "less";
989 opt
.null_following_name
= 1;
990 opt
.output_priv
= &path_list
;
991 opt
.output
= append_path
;
992 string_list_append(show_in_pager
, &path_list
);
996 if (!opt
.pattern_list
)
997 die("no pattern given.");
998 if (!opt
.fixed
&& opt
.ignore_case
)
999 opt
.regflags
|= REG_ICASE
;
1000 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
1001 die("cannot mix --fixed-strings and regexp");
1004 if (online_cpus() == 1 || !grep_threads_ok(&opt
))
1008 if (opt
.pre_context
|| opt
.post_context
)
1009 print_hunk_marks_between_files
= 1;
1010 start_threads(&opt
);
1016 compile_grep_patterns(&opt
);
1018 /* Check revs and then paths */
1019 for (i
= 0; i
< argc
; i
++) {
1020 const char *arg
= argv
[i
];
1021 unsigned char sha1
[20];
1023 if (!get_sha1(arg
, sha1
)) {
1024 struct object
*object
= parse_object(sha1
);
1026 die("bad object %s", arg
);
1027 add_object_array(object
, arg
, &list
);
1030 if (!strcmp(arg
, "--")) {
1037 /* The rest are paths */
1038 if (!seen_dashdash
) {
1040 for (j
= i
; j
< argc
; j
++)
1041 verify_filename(prefix
, argv
[j
]);
1045 paths
= get_pathspec(prefix
, argv
+ i
);
1047 paths
= xcalloc(2, sizeof(const char *));
1055 die("--cached cannot be used with --no-index.");
1057 die("--no-index cannot be used with revs.");
1058 hit
= grep_directory(&opt
, paths
);
1064 if (show_in_pager
&& (cached
|| list
.nr
))
1065 die ("--open-files-in-pager only works on the worktree");
1067 if (show_in_pager
&& opt
.pattern_list
&& !opt
.pattern_list
->next
) {
1068 const char *pager
= path_list
.items
[0].string
;
1069 int len
= strlen(pager
);
1071 if (len
> 4 && is_dir_sep(pager
[len
- 5]))
1074 if (!strcmp("less", pager
) || !strcmp("vi", pager
)) {
1075 struct strbuf buf
= STRBUF_INIT
;
1076 strbuf_addf(&buf
, "+/%s%s",
1077 strcmp("less", pager
) ? "" : "*",
1078 opt
.pattern_list
->pattern
);
1079 string_list_append(buf
.buf
, &path_list
);
1080 strbuf_detach(&buf
, NULL
);
1091 hit
= grep_cache(&opt
, paths
, cached
);
1094 die("both --cached and trees are given.");
1096 for (i
= 0; i
< list
.nr
; i
++) {
1097 struct object
*real_obj
;
1098 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
1099 if (grep_object(&opt
, paths
, real_obj
,
1100 list
.objects
[i
].name
)) {
1102 if (opt
.status_only
)
1110 if (hit
&& show_in_pager
)
1111 run_pager(&opt
, prefix
);
1113 free_grep_patterns(&opt
);