4 * Copyright (c) 2006 Junio C Hamano
11 #include "tree-walk.h"
13 #include "parse-options.h"
18 #include "string-list.h"
21 #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 void add_work(enum work_type type
, char *name
, void *id
)
104 while ((todo_end
+1) % ARRAY_SIZE(todo
) == todo_done
) {
105 pthread_cond_wait(&cond_write
, &grep_mutex
);
108 todo
[todo_end
].type
= type
;
109 todo
[todo_end
].name
= name
;
110 todo
[todo_end
].identifier
= id
;
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 grep_sha1_async(struct grep_opt
*opt
, char *name
,
139 const unsigned char *sha1
)
144 add_work(WORK_SHA1
, name
, s
);
147 static void grep_file_async(struct grep_opt
*opt
, char *name
,
148 const char *filename
)
150 add_work(WORK_FILE
, name
, xstrdup(filename
));
153 static void work_done(struct work_item
*w
)
159 old_done
= todo_done
;
160 for(; todo
[todo_done
].done
&& todo_done
!= todo_start
;
161 todo_done
= (todo_done
+1) % ARRAY_SIZE(todo
)) {
162 w
= &todo
[todo_done
];
163 write_or_die(1, w
->out
.buf
, w
->out
.len
);
168 if (old_done
!= todo_done
)
169 pthread_cond_signal(&cond_write
);
171 if (all_work_added
&& todo_done
== todo_end
)
172 pthread_cond_signal(&cond_result
);
177 static void *run(void *arg
)
180 struct grep_opt
*opt
= arg
;
183 struct work_item
*w
= get_work();
187 opt
->output_priv
= w
;
188 if (w
->type
== WORK_SHA1
) {
190 void* data
= load_sha1(w
->identifier
, &sz
, w
->name
);
193 hit
|= grep_buffer(opt
, w
->name
, data
, sz
);
196 } else if (w
->type
== WORK_FILE
) {
198 void* data
= load_file(w
->identifier
, &sz
);
200 hit
|= grep_buffer(opt
, w
->name
, data
, sz
);
209 free_grep_patterns(arg
);
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(&read_sha1_mutex
, NULL
);
227 pthread_cond_init(&cond_add
, NULL
);
228 pthread_cond_init(&cond_write
, NULL
);
229 pthread_cond_init(&cond_result
, NULL
);
231 for (i
= 0; i
< ARRAY_SIZE(todo
); i
++) {
232 strbuf_init(&todo
[i
].out
, 0);
235 for (i
= 0; i
< ARRAY_SIZE(threads
); i
++) {
237 struct grep_opt
*o
= grep_opt_dup(opt
);
238 o
->output
= strbuf_out
;
239 compile_grep_patterns(o
);
240 err
= pthread_create(&threads
[i
], NULL
, run
, o
);
243 die("grep: failed to create thread: %s",
248 static int wait_all(void)
256 /* Wait until all work is done. */
257 while (todo_done
!= todo_end
)
258 pthread_cond_wait(&cond_result
, &grep_mutex
);
260 /* Wake up all the consumer threads so they can see that there
261 * is no more work to do.
263 pthread_cond_broadcast(&cond_add
);
266 for (i
= 0; i
< ARRAY_SIZE(threads
); i
++) {
268 pthread_join(threads
[i
], &h
);
269 hit
|= (int) (intptr_t) h
;
272 pthread_mutex_destroy(&grep_mutex
);
273 pthread_mutex_destroy(&read_sha1_mutex
);
274 pthread_cond_destroy(&cond_add
);
275 pthread_cond_destroy(&cond_write
);
276 pthread_cond_destroy(&cond_result
);
280 #else /* !NO_PTHREADS */
281 #define read_sha1_lock()
282 #define read_sha1_unlock()
284 static int wait_all(void)
290 static int grep_config(const char *var
, const char *value
, void *cb
)
292 struct grep_opt
*opt
= cb
;
294 switch (userdiff_config(var
, value
)) {
300 if (!strcmp(var
, "color.grep")) {
301 opt
->color
= git_config_colorbool(var
, value
, -1);
304 if (!strcmp(var
, "color.grep.match")) {
306 return config_error_nonbool(var
);
307 color_parse(value
, var
, opt
->color_match
);
310 return git_color_default_config(var
, value
, cb
);
314 * Return non-zero if max_depth is negative or path has no more then max_depth
317 static int accept_subdir(const char *path
, int max_depth
)
322 while ((path
= strchr(path
, '/')) != NULL
) {
332 * Return non-zero if name is a subdirectory of match and is not too deep.
334 static int is_subdir(const char *name
, int namelen
,
335 const char *match
, int matchlen
, int max_depth
)
337 if (matchlen
> namelen
|| strncmp(name
, match
, matchlen
))
340 if (name
[matchlen
] == '\0') /* exact match */
343 if (!matchlen
|| match
[matchlen
-1] == '/' || name
[matchlen
] == '/')
344 return accept_subdir(name
+ matchlen
+ 1, max_depth
);
350 * git grep pathspecs are somewhat different from diff-tree pathspecs;
351 * pathname wildcards are allowed.
353 static int pathspec_matches(const char **paths
, const char *name
, int max_depth
)
356 if (!paths
|| !*paths
)
357 return accept_subdir(name
, max_depth
);
358 namelen
= strlen(name
);
359 for (i
= 0; paths
[i
]; i
++) {
360 const char *match
= paths
[i
];
361 int matchlen
= strlen(match
);
362 const char *cp
, *meta
;
364 if (is_subdir(name
, namelen
, match
, matchlen
, max_depth
))
366 if (!fnmatch(match
, name
, 0))
368 if (name
[namelen
-1] != '/')
371 /* We are being asked if the directory ("name") is worth
374 * Find the longest leading directory name that does
375 * not have metacharacter in the pathspec; the name
376 * we are looking at must overlap with that directory.
378 for (cp
= match
, meta
= NULL
; cp
- match
< matchlen
; cp
++) {
380 if (ch
== '*' || ch
== '[' || ch
== '?') {
386 meta
= cp
; /* fully literal */
388 if (namelen
<= meta
- match
) {
389 /* Looking at "Documentation/" and
390 * the pattern says "Documentation/howto/", or
391 * "Documentation/diff*.txt". The name we
392 * have should match prefix.
394 if (!memcmp(match
, name
, namelen
))
399 if (meta
- match
< namelen
) {
400 /* Looking at "Documentation/howto/" and
401 * the pattern says "Documentation/h*";
402 * match up to "Do.../h"; this avoids descending
403 * into "Documentation/technical/".
405 if (!memcmp(match
, name
, meta
- match
))
413 static void *load_sha1(const unsigned char *sha1
, unsigned long *size
,
416 enum object_type type
;
420 data
= read_sha1_file(sha1
, &type
, size
);
424 error("'%s': unable to read %s", name
, sha1_to_hex(sha1
));
429 static int grep_sha1(struct grep_opt
*opt
, const unsigned char *sha1
,
430 const char *filename
, int tree_name_len
)
432 struct strbuf pathbuf
= STRBUF_INIT
;
435 if (opt
->relative
&& opt
->prefix_length
) {
436 quote_path_relative(filename
+ tree_name_len
, -1, &pathbuf
,
438 strbuf_insert(&pathbuf
, 0, filename
, tree_name_len
);
440 strbuf_addstr(&pathbuf
, filename
);
443 name
= strbuf_detach(&pathbuf
, NULL
);
447 grep_sha1_async(opt
, name
, sha1
);
454 void *data
= load_sha1(sha1
, &sz
, name
);
458 hit
= grep_buffer(opt
, name
, data
, sz
);
466 static void *load_file(const char *filename
, size_t *sz
)
472 if (lstat(filename
, &st
) < 0) {
475 error("'%s': %s", filename
, strerror(errno
));
478 if (!S_ISREG(st
.st_mode
))
480 *sz
= xsize_t(st
.st_size
);
481 i
= open(filename
, O_RDONLY
);
484 data
= xmalloc(*sz
+ 1);
485 if (st
.st_size
!= read_in_full(i
, data
, *sz
)) {
486 error("'%s': short read %s", filename
, strerror(errno
));
496 static int grep_file(struct grep_opt
*opt
, const char *filename
)
498 struct strbuf buf
= STRBUF_INIT
;
501 if (opt
->relative
&& opt
->prefix_length
)
502 quote_path_relative(filename
, -1, &buf
, opt
->prefix
);
504 strbuf_addstr(&buf
, filename
);
505 name
= strbuf_detach(&buf
, NULL
);
509 grep_file_async(opt
, name
, filename
);
516 void *data
= load_file(filename
, &sz
);
520 hit
= grep_buffer(opt
, name
, data
, sz
);
528 static void append_path(struct grep_opt
*opt
, const void *data
, size_t len
)
530 struct string_list
*path_list
= opt
->output_priv
;
532 if (len
== 1 && *(char *)data
== '\0')
534 string_list_append(xstrndup(data
, len
), path_list
);
537 static void run_pager(struct grep_opt
*opt
, const char *prefix
)
539 struct string_list
*path_list
= opt
->output_priv
;
540 char **argv
= xmalloc(sizeof(const char *) * (path_list
->nr
+ 1));
543 for (i
= 0; i
< path_list
->nr
; i
++)
544 argv
[i
] = path_list
->items
[i
].string
;
545 argv
[path_list
->nr
] = NULL
;
549 execvp(argv
[0], argv
);
550 error("Could not run pager %s: %s", argv
[0], strerror(errno
));
553 static void perform_substitutions(struct grep_opt
*opt
,
554 const char *substitute
, const char *prefix
, int cached
)
559 for (i
= 0; i
< opt
->collect_file_names
->nr
; i
++) {
566 static int grep_cache(struct grep_opt
*opt
, const char **paths
, int cached
)
572 for (nr
= 0; nr
< active_nr
; nr
++) {
573 struct cache_entry
*ce
= active_cache
[nr
];
574 if (!S_ISREG(ce
->ce_mode
))
576 if (!pathspec_matches(paths
, ce
->name
, opt
->max_depth
))
579 * If CE_VALID is on, we assume worktree file and its cache entry
580 * are identical, even if worktree file has been modified, so use
581 * cache version instead
583 if (cached
|| (ce
->ce_flags
& CE_VALID
) || ce_skip_worktree(ce
)) {
586 hit
|= grep_sha1(opt
, ce
->sha1
, ce
->name
, 0);
589 hit
|= grep_file(opt
, ce
->name
);
593 } while (nr
< active_nr
&&
594 !strcmp(ce
->name
, active_cache
[nr
]->name
));
595 nr
--; /* compensate for loop control */
597 if (hit
&& opt
->status_only
)
603 static int grep_tree(struct grep_opt
*opt
, const char **paths
,
604 struct tree_desc
*tree
,
605 const char *tree_name
, const char *base
)
609 struct name_entry entry
;
611 int tn_len
= strlen(tree_name
);
612 struct strbuf pathbuf
;
614 strbuf_init(&pathbuf
, PATH_MAX
+ tn_len
);
617 strbuf_add(&pathbuf
, tree_name
, tn_len
);
618 strbuf_addch(&pathbuf
, ':');
619 tn_len
= pathbuf
.len
;
621 strbuf_addstr(&pathbuf
, base
);
624 while (tree_entry(tree
, &entry
)) {
625 int te_len
= tree_entry_len(entry
.path
, entry
.sha1
);
627 strbuf_add(&pathbuf
, entry
.path
, te_len
);
629 if (S_ISDIR(entry
.mode
))
630 /* Match "abc/" against pathspec to
631 * decide if we want to descend into "abc"
634 strbuf_addch(&pathbuf
, '/');
636 down
= pathbuf
.buf
+ tn_len
;
637 if (!pathspec_matches(paths
, down
, opt
->max_depth
))
639 else if (S_ISREG(entry
.mode
))
640 hit
|= grep_sha1(opt
, entry
.sha1
, pathbuf
.buf
, tn_len
);
641 else if (S_ISDIR(entry
.mode
)) {
642 enum object_type type
;
643 struct tree_desc sub
;
648 data
= read_sha1_file(entry
.sha1
, &type
, &size
);
652 die("unable to read tree (%s)",
653 sha1_to_hex(entry
.sha1
));
654 init_tree_desc(&sub
, data
, size
);
655 hit
|= grep_tree(opt
, paths
, &sub
, tree_name
, down
);
658 if (hit
&& opt
->status_only
)
661 strbuf_release(&pathbuf
);
665 static int grep_object(struct grep_opt
*opt
, const char **paths
,
666 struct object
*obj
, const char *name
)
668 if (obj
->type
== OBJ_BLOB
)
669 return grep_sha1(opt
, obj
->sha1
, name
, 0);
670 if (obj
->type
== OBJ_COMMIT
|| obj
->type
== OBJ_TREE
) {
671 struct tree_desc tree
;
675 data
= read_object_with_reference(obj
->sha1
, tree_type
,
678 die("unable to read tree (%s)", sha1_to_hex(obj
->sha1
));
679 init_tree_desc(&tree
, data
, size
);
680 hit
= grep_tree(opt
, paths
, &tree
, name
, "");
684 die("unable to grep from object of type %s", typename(obj
->type
));
687 static int grep_directory(struct grep_opt
*opt
, const char **paths
)
689 struct dir_struct dir
;
692 memset(&dir
, 0, sizeof(dir
));
693 setup_standard_excludes(&dir
);
695 fill_directory(&dir
, paths
);
696 for (i
= 0; i
< dir
.nr
; i
++) {
697 hit
|= grep_file(opt
, dir
.entries
[i
]->name
);
698 if (hit
&& opt
->status_only
)
704 static int context_callback(const struct option
*opt
, const char *arg
,
707 struct grep_opt
*grep_opt
= opt
->value
;
712 grep_opt
->pre_context
= grep_opt
->post_context
= 0;
715 value
= strtol(arg
, (char **)&endp
, 10);
717 return error("switch `%c' expects a numerical value",
720 grep_opt
->pre_context
= grep_opt
->post_context
= value
;
724 static int file_callback(const struct option
*opt
, const char *arg
, int unset
)
726 struct grep_opt
*grep_opt
= opt
->value
;
729 struct strbuf sb
= STRBUF_INIT
;
731 patterns
= fopen(arg
, "r");
733 die_errno("cannot open '%s'", arg
);
734 while (strbuf_getline(&sb
, patterns
, '\n') == 0) {
735 /* ignore empty line like grep does */
738 append_grep_pattern(grep_opt
, strbuf_detach(&sb
, NULL
), arg
,
739 ++lno
, GREP_PATTERN
);
746 static int not_callback(const struct option
*opt
, const char *arg
, int unset
)
748 struct grep_opt
*grep_opt
= opt
->value
;
749 append_grep_pattern(grep_opt
, "--not", "command line", 0, GREP_NOT
);
753 static int and_callback(const struct option
*opt
, const char *arg
, int unset
)
755 struct grep_opt
*grep_opt
= opt
->value
;
756 append_grep_pattern(grep_opt
, "--and", "command line", 0, GREP_AND
);
760 static int open_callback(const struct option
*opt
, const char *arg
, int unset
)
762 struct grep_opt
*grep_opt
= opt
->value
;
763 append_grep_pattern(grep_opt
, "(", "command line", 0, GREP_OPEN_PAREN
);
767 static int close_callback(const struct option
*opt
, const char *arg
, int unset
)
769 struct grep_opt
*grep_opt
= opt
->value
;
770 append_grep_pattern(grep_opt
, ")", "command line", 0, GREP_CLOSE_PAREN
);
774 static int pattern_callback(const struct option
*opt
, const char *arg
,
777 struct grep_opt
*grep_opt
= opt
->value
;
778 append_grep_pattern(grep_opt
, arg
, "-e option", 0, GREP_PATTERN
);
782 static int help_callback(const struct option
*opt
, const char *arg
, int unset
)
787 int cmd_grep(int argc
, const char **argv
, const char *prefix
)
791 int seen_dashdash
= 0;
792 int external_grep_allowed__ignored
;
793 const char *show_in_pager
= NULL
, *default_pager
= "dummy";
794 const char *substitute
= NULL
;
796 struct object_array list
= { 0, 0, NULL
};
797 const char **paths
= NULL
;
798 struct string_list path_list
= { NULL
, 0, 0, 0 };
801 int nongit
= 0, use_index
= 1;
802 struct option options
[] = {
803 OPT_BOOLEAN(0, "cached", &cached
,
804 "search in index instead of in the work tree"),
805 OPT_BOOLEAN(0, "index", &use_index
,
806 "--no-index finds in contents not managed by git"),
808 OPT_BOOLEAN('v', "invert-match", &opt
.invert
,
809 "show non-matching lines"),
810 OPT_BOOLEAN('i', "ignore-case", &opt
.ignore_case
,
811 "case insensitive matching"),
812 OPT_BOOLEAN('w', "word-regexp", &opt
.word_regexp
,
813 "match patterns only at word boundaries"),
814 OPT_SET_INT('a', "text", &opt
.binary
,
815 "process binary files as text", GREP_BINARY_TEXT
),
816 OPT_SET_INT('I', NULL
, &opt
.binary
,
817 "don't match patterns in binary files",
818 GREP_BINARY_NOMATCH
),
819 { OPTION_INTEGER
, 0, "max-depth", &opt
.max_depth
, "depth",
820 "descend at most <depth> levels", PARSE_OPT_NONEG
,
823 OPT_BIT('E', "extended-regexp", &opt
.regflags
,
824 "use extended POSIX regular expressions", REG_EXTENDED
),
825 OPT_NEGBIT('G', "basic-regexp", &opt
.regflags
,
826 "use basic POSIX regular expressions (default)",
828 OPT_BOOLEAN('F', "fixed-strings", &opt
.fixed
,
829 "interpret patterns as fixed strings"),
831 OPT_BOOLEAN('n', NULL
, &opt
.linenum
, "show line numbers"),
832 OPT_NEGBIT('h', NULL
, &opt
.pathname
, "don't show filenames", 1),
833 OPT_BIT('H', NULL
, &opt
.pathname
, "show filenames", 1),
834 OPT_NEGBIT(0, "full-name", &opt
.relative
,
835 "show filenames relative to top directory", 1),
836 OPT_BOOLEAN('l', "files-with-matches", &opt
.name_only
,
837 "show only filenames instead of matching lines"),
838 OPT_BOOLEAN(0, "name-only", &opt
.name_only
,
839 "synonym for --files-with-matches"),
840 OPT_BOOLEAN('L', "files-without-match",
841 &opt
.unmatch_name_only
,
842 "show only the names of files without match"),
843 OPT_BOOLEAN('z', "null", &opt
.null_following_name
,
844 "print NUL after filenames"),
845 OPT_BOOLEAN('c', "count", &opt
.count
,
846 "show the number of matches instead of matching lines"),
847 OPT_SET_INT(0, "color", &opt
.color
, "highlight matches", 1),
849 OPT_CALLBACK('C', NULL
, &opt
, "n",
850 "show <n> context lines before and after matches",
852 OPT_INTEGER('B', NULL
, &opt
.pre_context
,
853 "show <n> context lines before matches"),
854 OPT_INTEGER('A', NULL
, &opt
.post_context
,
855 "show <n> context lines after matches"),
856 OPT_NUMBER_CALLBACK(&opt
, "shortcut for -C NUM",
858 OPT_BOOLEAN('p', "show-function", &opt
.funcname
,
859 "show a line with the function name before matches"),
861 OPT_CALLBACK('f', NULL
, &opt
, "file",
862 "read patterns from file", file_callback
),
863 { OPTION_CALLBACK
, 'e', NULL
, &opt
, "pattern",
864 "match <pattern>", PARSE_OPT_NONEG
, pattern_callback
},
865 { OPTION_CALLBACK
, 0, "and", &opt
, NULL
,
866 "combine patterns specified with -e",
867 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, and_callback
},
868 OPT_BOOLEAN(0, "or", &dummy
, ""),
869 { OPTION_CALLBACK
, 0, "not", &opt
, NULL
, "",
870 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, not_callback
},
871 { OPTION_CALLBACK
, '(', NULL
, &opt
, NULL
, "",
872 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
874 { OPTION_CALLBACK
, ')', NULL
, &opt
, NULL
, "",
875 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
| PARSE_OPT_NODASH
,
877 OPT_BOOLEAN('q', "quiet", &opt
.status_only
,
878 "indicate hit with exit status without output"),
879 OPT_BOOLEAN(0, "all-match", &opt
.all_match
,
880 "show only matches from files that match all patterns"),
882 { OPTION_STRING
, 'P', "open-files-in-pager", &show_in_pager
,
883 "pager", "show matching files in the pager",
884 PARSE_OPT_OPTARG
, NULL
, (intptr_t)default_pager
},
885 OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored
,
886 "allow calling of grep(1) (ignored by this build)"),
887 OPT_STRING(0, "--substitute", &substitute
,
888 "substitute (single) regular expression", NULL
),
889 { OPTION_CALLBACK
, 0, "help-all", &options
, NULL
, "show usage",
890 PARSE_OPT_HIDDEN
| PARSE_OPT_NOARG
, help_callback
},
894 prefix
= setup_git_directory_gently(&nongit
);
897 * 'git grep -h', unlike 'git grep -h <pattern>', is a request
898 * to show usage information and exit.
900 if (argc
== 2 && !strcmp(argv
[1], "-h"))
901 usage_with_options(grep_usage
, options
);
903 memset(&opt
, 0, sizeof(opt
));
905 opt
.prefix_length
= (prefix
&& *prefix
) ? strlen(prefix
) : 0;
908 opt
.pattern_tail
= &opt
.pattern_list
;
909 opt
.regflags
= REG_NEWLINE
;
912 strcpy(opt
.color_match
, GIT_COLOR_RED GIT_COLOR_BOLD
);
914 git_config(grep_config
, &opt
);
916 opt
.color
= git_use_color_default
;
919 * If there is no -- then the paths must exist in the working
920 * tree. If there is no explicit pattern specified with -e or
921 * -f, we take the first unrecognized non option to be the
922 * pattern, but then what follows it must be zero or more
923 * valid refs up to the -- (if exists), and then existing
924 * paths. If there is an explicit pattern, then the first
925 * unrecognized non option is the beginning of the refs list
926 * that continues up to the -- (if exists), and then paths.
928 argc
= parse_options(argc
, argv
, prefix
, options
, grep_usage
,
929 PARSE_OPT_KEEP_DASHDASH
|
930 PARSE_OPT_STOP_AT_NON_OPTION
|
931 PARSE_OPT_NO_INTERNAL_HELP
);
933 if (use_index
&& nongit
)
934 /* die the same way as if we did it at the beginning */
935 setup_git_directory();
937 /* First unrecognized non-option token */
938 if (argc
> 0 && !opt
.pattern_list
) {
939 append_grep_pattern(&opt
, argv
[0], "command line", 0,
946 if (show_in_pager
== default_pager
) {
947 show_in_pager
= getenv("GIT_PAGER");
949 show_in_pager
= getenv("PAGER");
951 show_in_pager
= "less";
954 opt
.null_following_name
= 1;
955 opt
.output_priv
= &path_list
;
956 opt
.output
= append_path
;
957 string_list_append(show_in_pager
, &path_list
);
961 if (!opt
.pattern_list
)
962 die("no pattern given.");
963 if (!opt
.fixed
&& opt
.ignore_case
)
964 opt
.regflags
|= REG_ICASE
;
965 if ((opt
.regflags
!= REG_NEWLINE
) && opt
.fixed
)
966 die("cannot mix --fixed-strings and regexp");
969 if (online_cpus() == 1 || !grep_threads_ok(&opt
))
978 compile_grep_patterns(&opt
);
980 /* Check revs and then paths */
981 for (i
= 0; i
< argc
; i
++) {
982 const char *arg
= argv
[i
];
983 unsigned char sha1
[20];
985 if (!get_sha1(arg
, sha1
)) {
986 struct object
*object
= parse_object(sha1
);
988 die("bad object %s", arg
);
989 add_object_array(object
, arg
, &list
);
992 if (!strcmp(arg
, "--")) {
999 /* The rest are paths */
1000 if (!seen_dashdash
) {
1002 for (j
= i
; j
< argc
; j
++)
1003 verify_filename(prefix
, argv
[j
]);
1007 paths
= get_pathspec(prefix
, argv
+ i
);
1009 paths
= xcalloc(2, sizeof(const char *));
1014 warning ("TODO: audit incompatible options");
1015 if (substitute
&& list
.nr
)
1016 die ("--substitute is incompatible with rev parameters");
1018 if (substitute
&& (!opt
.pattern_list
|| opt
.pattern_list
->next
))
1019 die ("--substitute needs exactly one pattern");
1021 if (show_in_pager
&& cached
)
1022 die ("--open-files-in-pager and --cached are incompatible");
1024 if (show_in_pager
&& opt
.pattern_list
&& !opt
.pattern_list
->next
) {
1025 const char *pager
= path_list
.items
[0].string
;
1026 int len
= strlen(pager
);
1028 if (len
> 4 && is_dir_sep(pager
[len
- 5]))
1031 if (!strcmp("less", pager
) || !strcmp("vi", pager
)) {
1032 struct strbuf buf
= STRBUF_INIT
;
1033 strbuf_addf(&buf
, "+/%s%s",
1034 strcmp("less", pager
) ? "" : "*",
1035 opt
.pattern_list
->pattern
);
1036 string_list_append(buf
.buf
, &path_list
);
1037 strbuf_detach(&buf
, NULL
);
1046 die("--cached cannot be used with --no-index.");
1048 die("--no-index cannot be used with revs.");
1049 hit
= grep_directory(&opt
, paths
);
1051 else if (!list
.nr
) {
1055 hit
= grep_cache(&opt
, paths
, cached
);
1058 die("both --cached and trees are given.");
1060 for (i
= 0; i
< list
.nr
; i
++) {
1061 struct object
*real_obj
;
1062 real_obj
= deref_tag(list
.objects
[i
].item
, NULL
, 0);
1063 if (grep_object(&opt
, paths
, real_obj
,
1064 list
.objects
[i
].name
)) {
1066 if (opt
.status_only
)
1074 if (hit
&& show_in_pager
)
1075 run_pager(&opt
, prefix
);
1077 if (hit
&& substitute
)
1078 perform_substitutions(&opt
, substitute
, prefix
, cached
);
1080 free_grep_patterns(&opt
);