]> git.ipfire.org Git - thirdparty/git.git/blame - builtin-grep.c
grep: remove global variable builtin_grep
[thirdparty/git.git] / builtin-grep.c
CommitLineData
5010cb5f
JH
1/*
2 * Builtin "git grep"
3 *
4 * Copyright (c) 2006 Junio C Hamano
5 */
6#include "cache.h"
7#include "blob.h"
8#include "tree.h"
9#include "commit.h"
10#include "tag.h"
1362671f 11#include "tree-walk.h"
5010cb5f 12#include "builtin.h"
83b5d2f5 13#include "grep.h"
5010cb5f 14
5f7c643a
JK
15#ifndef NO_EXTERNAL_GREP
16#ifdef __unix__
17#define NO_EXTERNAL_GREP 0
18#else
19#define NO_EXTERNAL_GREP 1
20#endif
21#endif
22
7e8f59d5
RS
23static int grep_config(const char *var, const char *value, void *cb)
24{
25 struct grep_opt *opt = cb;
26
fe3420b6 27 if (!strcmp(var, "color.grep")) {
7e8f59d5
RS
28 opt->color = git_config_colorbool(var, value, -1);
29 return 0;
30 }
fe3420b6 31 if (!strcmp(var, "color.grep.external"))
a94982ef 32 return git_config_string(&(opt->color_external), var, value);
fe3420b6 33 if (!strcmp(var, "color.grep.match")) {
7e8f59d5
RS
34 if (!value)
35 return config_error_nonbool(var);
36 color_parse(value, var, opt->color_match);
37 return 0;
38 }
39 return git_color_default_config(var, value, cb);
40}
41
e0eb889f
JH
42/*
43 * git grep pathspecs are somewhat different from diff-tree pathspecs;
44 * pathname wildcards are allowed.
45 */
1362671f 46static int pathspec_matches(const char **paths, const char *name)
5010cb5f 47{
e0eb889f 48 int namelen, i;
1362671f 49 if (!paths || !*paths)
5010cb5f
JH
50 return 1;
51 namelen = strlen(name);
1362671f
JH
52 for (i = 0; paths[i]; i++) {
53 const char *match = paths[i];
54 int matchlen = strlen(match);
1e3d90e0 55 const char *cp, *meta;
e0eb889f 56
bb9e15a8
UKK
57 if (!matchlen ||
58 ((matchlen <= namelen) &&
59 !strncmp(name, match, matchlen) &&
60 (match[matchlen-1] == '/' ||
61 name[matchlen] == '\0' || name[matchlen] == '/')))
e0eb889f
JH
62 return 1;
63 if (!fnmatch(match, name, 0))
64 return 1;
65 if (name[namelen-1] != '/')
5010cb5f 66 continue;
e0eb889f 67
1e3d90e0 68 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
69 * descending into.
70 *
71 * Find the longest leading directory name that does
72 * not have metacharacter in the pathspec; the name
73 * we are looking at must overlap with that directory.
5010cb5f 74 */
1e3d90e0 75 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 76 char ch = *cp;
1e3d90e0
JH
77 if (ch == '*' || ch == '[' || ch == '?') {
78 meta = cp;
5010cb5f 79 break;
1e3d90e0 80 }
e0eb889f 81 }
1e3d90e0
JH
82 if (!meta)
83 meta = cp; /* fully literal */
84
85 if (namelen <= meta - match) {
e0eb889f
JH
86 /* Looking at "Documentation/" and
87 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
88 * "Documentation/diff*.txt". The name we
89 * have should match prefix.
e0eb889f
JH
90 */
91 if (!memcmp(match, name, namelen))
92 return 1;
1e3d90e0 93 continue;
e0eb889f 94 }
1e3d90e0
JH
95
96 if (meta - match < namelen) {
e0eb889f 97 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
98 * the pattern says "Documentation/h*";
99 * match up to "Do.../h"; this avoids descending
100 * into "Documentation/technical/".
e0eb889f 101 */
1e3d90e0 102 if (!memcmp(match, name, meta - match))
e0eb889f 103 return 1;
1e3d90e0 104 continue;
e0eb889f 105 }
5010cb5f
JH
106 }
107 return 0;
108}
109
0d042fec 110static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
5010cb5f
JH
111{
112 unsigned long size;
113 char *data;
21666f1a 114 enum object_type type;
0d042fec 115 char *to_free = NULL;
5010cb5f 116 int hit;
0d042fec 117
21666f1a 118 data = read_sha1_file(sha1, &type, &size);
5010cb5f
JH
119 if (!data) {
120 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
121 return 0;
122 }
0d042fec
JH
123 if (opt->relative && opt->prefix_length) {
124 static char name_buf[PATH_MAX];
125 char *cp;
126 int name_len = strlen(name) - opt->prefix_length + 1;
127
128 if (!tree_name_len)
129 name += opt->prefix_length;
130 else {
131 if (ARRAY_SIZE(name_buf) <= name_len)
132 cp = to_free = xmalloc(name_len);
133 else
134 cp = name_buf;
135 memcpy(cp, name, tree_name_len);
136 strcpy(cp + tree_name_len,
137 name + tree_name_len + opt->prefix_length);
138 name = cp;
139 }
140 }
5010cb5f
JH
141 hit = grep_buffer(opt, name, data, size);
142 free(data);
0d042fec 143 free(to_free);
5010cb5f
JH
144 return hit;
145}
146
147static int grep_file(struct grep_opt *opt, const char *filename)
148{
149 struct stat st;
150 int i;
151 char *data;
dc49cd76
SP
152 size_t sz;
153
5010cb5f
JH
154 if (lstat(filename, &st) < 0) {
155 err_ret:
156 if (errno != ENOENT)
157 error("'%s': %s", filename, strerror(errno));
158 return 0;
159 }
160 if (!st.st_size)
161 return 0; /* empty file -- no grep hit */
162 if (!S_ISREG(st.st_mode))
163 return 0;
dc49cd76 164 sz = xsize_t(st.st_size);
5010cb5f
JH
165 i = open(filename, O_RDONLY);
166 if (i < 0)
167 goto err_ret;
dc49cd76
SP
168 data = xmalloc(sz + 1);
169 if (st.st_size != read_in_full(i, data, sz)) {
5010cb5f
JH
170 error("'%s': short read %s", filename, strerror(errno));
171 close(i);
172 free(data);
173 return 0;
174 }
175 close(i);
0d042fec
JH
176 if (opt->relative && opt->prefix_length)
177 filename += opt->prefix_length;
dc49cd76 178 i = grep_buffer(opt, filename, data, sz);
5010cb5f
JH
179 free(data);
180 return i;
181}
182
5f7c643a 183#if !NO_EXTERNAL_GREP
1e2398d7
LT
184static int exec_grep(int argc, const char **argv)
185{
186 pid_t pid;
187 int status;
188
189 argv[argc] = NULL;
190 pid = fork();
191 if (pid < 0)
192 return pid;
193 if (!pid) {
194 execvp("grep", (char **) argv);
195 exit(255);
196 }
197 while (waitpid(pid, &status, 0) < 0) {
198 if (errno == EINTR)
199 continue;
200 return -1;
201 }
202 if (WIFEXITED(status)) {
203 if (!WEXITSTATUS(status))
204 return 1;
205 return 0;
206 }
207 return -1;
208}
209
210#define MAXARGS 1000
ffa0a7ab
JH
211#define ARGBUF 4096
212#define push_arg(a) do { \
213 if (nr < MAXARGS) argv[nr++] = (a); \
214 else die("maximum number of args exceeded"); \
215 } while (0)
1e2398d7 216
d99ebf08
JH
217/*
218 * If you send a singleton filename to grep, it does not give
219 * the name of the file. GNU grep has "-H" but we would want
220 * that behaviour in a portable way.
221 *
222 * So we keep two pathnames in argv buffer unsent to grep in
223 * the main loop if we need to do more than one grep.
224 */
225static int flush_grep(struct grep_opt *opt,
226 int argc, int arg0, const char **argv, int *kept)
227{
228 int status;
229 int count = argc - arg0;
230 const char *kept_0 = NULL;
231
232 if (count <= 2) {
233 /*
234 * Because we keep at least 2 paths in the call from
235 * the main loop (i.e. kept != NULL), and MAXARGS is
236 * far greater than 2, this usually is a call to
237 * conclude the grep. However, the user could attempt
238 * to overflow the argv buffer by giving too many
239 * options to leave very small number of real
240 * arguments even for the call in the main loop.
241 */
242 if (kept)
243 die("insanely many options to grep");
244
245 /*
246 * If we have two or more paths, we do not have to do
247 * anything special, but we need to push /dev/null to
248 * get "-H" behaviour of GNU grep portably but when we
249 * are not doing "-l" nor "-L" nor "-c".
250 */
251 if (count == 1 &&
252 !opt->name_only &&
253 !opt->unmatch_name_only &&
254 !opt->count) {
255 argv[argc++] = "/dev/null";
256 argv[argc] = NULL;
257 }
258 }
259
260 else if (kept) {
261 /*
262 * Called because we found many paths and haven't finished
263 * iterating over the cache yet. We keep two paths
264 * for the concluding call. argv[argc-2] and argv[argc-1]
265 * has the last two paths, so save the first one away,
266 * replace it with NULL while sending the list to grep,
267 * and recover them after we are done.
268 */
269 *kept = 2;
270 kept_0 = argv[argc-2];
271 argv[argc-2] = NULL;
272 argc -= 2;
273 }
274
275 status = exec_grep(argc, argv);
276
277 if (kept_0) {
278 /*
279 * Then recover them. Now the last arg is beyond the
280 * terminating NULL which is at argc, and the second
281 * from the last is what we saved away in kept_0
282 */
283 argv[arg0++] = kept_0;
284 argv[arg0] = argv[argc+1];
285 }
286 return status;
287}
288
a94982ef
RS
289static void grep_add_color(struct strbuf *sb, const char *escape_seq)
290{
291 size_t orig_len = sb->len;
292
293 while (*escape_seq) {
294 if (*escape_seq == 'm')
295 strbuf_addch(sb, ';');
296 else if (*escape_seq != '\033' && *escape_seq != '[')
297 strbuf_addch(sb, *escape_seq);
298 escape_seq++;
299 }
300 if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
301 strbuf_setlen(sb, sb->len - 1);
302}
303
1e2398d7
LT
304static int external_grep(struct grep_opt *opt, const char **paths, int cached)
305{
fcfe34b5 306 int i, nr, argc, hit, len, status;
1e2398d7 307 const char *argv[MAXARGS+1];
ffa0a7ab
JH
308 char randarg[ARGBUF];
309 char *argptr = randarg;
1e2398d7
LT
310 struct grep_pat *p;
311
0d042fec 312 if (opt->extended || (opt->relative && opt->prefix_length))
79d3696c 313 return -1;
ffa0a7ab
JH
314 len = nr = 0;
315 push_arg("grep");
ffa0a7ab 316 if (opt->fixed)
f6647519 317 push_arg("-F");
ffa0a7ab
JH
318 if (opt->linenum)
319 push_arg("-n");
7977f0ea
LT
320 if (!opt->pathname)
321 push_arg("-h");
ffa0a7ab
JH
322 if (opt->regflags & REG_EXTENDED)
323 push_arg("-E");
3026402c
RF
324 if (opt->regflags & REG_ICASE)
325 push_arg("-i");
bc395643
JH
326 if (opt->binary == GREP_BINARY_NOMATCH)
327 push_arg("-I");
1e2398d7 328 if (opt->word_regexp)
ffa0a7ab 329 push_arg("-w");
1e2398d7 330 if (opt->name_only)
ffa0a7ab
JH
331 push_arg("-l");
332 if (opt->unmatch_name_only)
333 push_arg("-L");
83caecca
RZ
334 if (opt->null_following_name)
335 /* in GNU grep git's "-z" translates to "-Z" */
336 push_arg("-Z");
ffa0a7ab
JH
337 if (opt->count)
338 push_arg("-c");
339 if (opt->post_context || opt->pre_context) {
340 if (opt->post_context != opt->pre_context) {
341 if (opt->pre_context) {
342 push_arg("-B");
343 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 344 "%u", opt->pre_context) + 1;
ffa0a7ab
JH
345 if (sizeof(randarg) <= len)
346 die("maximum length of args exceeded");
347 push_arg(argptr);
348 argptr += len;
349 }
350 if (opt->post_context) {
351 push_arg("-A");
352 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 353 "%u", opt->post_context) + 1;
ffa0a7ab
JH
354 if (sizeof(randarg) <= len)
355 die("maximum length of args exceeded");
356 push_arg(argptr);
357 argptr += len;
358 }
359 }
360 else {
361 push_arg("-C");
362 len += snprintf(argptr, sizeof(randarg)-len,
4b87474b 363 "%u", opt->post_context) + 1;
ffa0a7ab
JH
364 if (sizeof(randarg) <= len)
365 die("maximum length of args exceeded");
366 push_arg(argptr);
367 argptr += len;
368 }
369 }
1e2398d7 370 for (p = opt->pattern_list; p; p = p->next) {
ffa0a7ab
JH
371 push_arg("-e");
372 push_arg(p->pattern);
1e2398d7 373 }
a94982ef
RS
374 if (opt->color) {
375 struct strbuf sb = STRBUF_INIT;
376
377 grep_add_color(&sb, opt->color_match);
378 setenv("GREP_COLOR", sb.buf, 1);
379
380 strbuf_reset(&sb);
381 strbuf_addstr(&sb, "mt=");
382 grep_add_color(&sb, opt->color_match);
383 strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
384 setenv("GREP_COLORS", sb.buf, 1);
385
386 strbuf_release(&sb);
387
388 if (opt->color_external && strlen(opt->color_external) > 0)
389 push_arg(opt->color_external);
390 }
bbb66c60 391
1e2398d7
LT
392 hit = 0;
393 argc = nr;
394 for (i = 0; i < active_nr; i++) {
395 struct cache_entry *ce = active_cache[i];
fbd01abf 396 char *name;
d99ebf08 397 int kept;
7a51ed66 398 if (!S_ISREG(ce->ce_mode))
1e2398d7
LT
399 continue;
400 if (!pathspec_matches(paths, ce->name))
401 continue;
bbb66c60
LT
402 name = ce->name;
403 if (name[0] == '-') {
404 int len = ce_namelen(ce);
405 name = xmalloc(len + 3);
406 memcpy(name, "./", 2);
407 memcpy(name + 2, ce->name, len + 1);
408 }
409 argv[argc++] = name;
6326cee5
JH
410 if (MAXARGS <= argc) {
411 status = flush_grep(opt, argc, nr, argv, &kept);
412 if (0 < status)
413 hit = 1;
414 argc = nr + kept;
415 }
36f2587f
JH
416 if (ce_stage(ce)) {
417 do {
418 i++;
419 } while (i < active_nr &&
420 !strcmp(ce->name, active_cache[i]->name));
421 i--; /* compensate for loop control */
422 }
1e2398d7 423 }
fcfe34b5 424 if (argc > nr) {
d99ebf08 425 status = flush_grep(opt, argc, nr, argv, NULL);
fcfe34b5
JH
426 if (0 < status)
427 hit = 1;
428 }
429 return hit;
1e2398d7 430}
ff1f9945 431#endif
1e2398d7 432
1b5fb44a
RS
433static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
434 int external_grep_allowed)
5010cb5f
JH
435{
436 int hit = 0;
437 int nr;
438 read_cache();
439
5f7c643a 440#if !NO_EXTERNAL_GREP
1e2398d7
LT
441 /*
442 * Use the external "grep" command for the case where
443 * we grep through the checked-out files. It tends to
444 * be a lot more optimized
445 */
1b5fb44a 446 if (!cached && external_grep_allowed) {
1e2398d7
LT
447 hit = external_grep(opt, paths, cached);
448 if (hit >= 0)
449 return hit;
450 }
451#endif
452
5010cb5f
JH
453 for (nr = 0; nr < active_nr; nr++) {
454 struct cache_entry *ce = active_cache[nr];
7a51ed66 455 if (!S_ISREG(ce->ce_mode))
5010cb5f 456 continue;
1362671f 457 if (!pathspec_matches(paths, ce->name))
5010cb5f 458 continue;
57d43466
NTND
459 /*
460 * If CE_VALID is on, we assume worktree file and its cache entry
461 * are identical, even if worktree file has been modified, so use
462 * cache version instead
463 */
464 if (cached || (ce->ce_flags & CE_VALID)) {
36f2587f
JH
465 if (ce_stage(ce))
466 continue;
0d042fec 467 hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
36f2587f 468 }
5010cb5f
JH
469 else
470 hit |= grep_file(opt, ce->name);
36f2587f
JH
471 if (ce_stage(ce)) {
472 do {
473 nr++;
474 } while (nr < active_nr &&
475 !strcmp(ce->name, active_cache[nr]->name));
476 nr--; /* compensate for loop control */
477 }
5010cb5f 478 }
b48fb5b6 479 free_grep_patterns(opt);
5010cb5f
JH
480 return hit;
481}
482
1362671f 483static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
484 struct tree_desc *tree,
485 const char *tree_name, const char *base)
486{
5010cb5f
JH
487 int len;
488 int hit = 0;
4c068a98 489 struct name_entry entry;
e0eb889f 490 char *down;
0d042fec 491 int tn_len = strlen(tree_name);
620e2bb9
DP
492 struct strbuf pathbuf;
493
494 strbuf_init(&pathbuf, PATH_MAX + tn_len);
5010cb5f 495
0d042fec 496 if (tn_len) {
620e2bb9
DP
497 strbuf_add(&pathbuf, tree_name, tn_len);
498 strbuf_addch(&pathbuf, ':');
499 tn_len = pathbuf.len;
5010cb5f 500 }
620e2bb9
DP
501 strbuf_addstr(&pathbuf, base);
502 len = pathbuf.len;
5010cb5f 503
4c068a98 504 while (tree_entry(tree, &entry)) {
620e2bb9
DP
505 int te_len = tree_entry_len(entry.path, entry.sha1);
506 pathbuf.len = len;
507 strbuf_add(&pathbuf, entry.path, te_len);
5010cb5f 508
4c068a98 509 if (S_ISDIR(entry.mode))
e0eb889f
JH
510 /* Match "abc/" against pathspec to
511 * decide if we want to descend into "abc"
512 * directory.
513 */
620e2bb9 514 strbuf_addch(&pathbuf, '/');
e0eb889f 515
620e2bb9 516 down = pathbuf.buf + tn_len;
1362671f 517 if (!pathspec_matches(paths, down))
5010cb5f 518 ;
4c068a98 519 else if (S_ISREG(entry.mode))
620e2bb9 520 hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
4c068a98 521 else if (S_ISDIR(entry.mode)) {
21666f1a 522 enum object_type type;
5010cb5f
JH
523 struct tree_desc sub;
524 void *data;
6fda5e51
LT
525 unsigned long size;
526
527 data = read_sha1_file(entry.sha1, &type, &size);
5010cb5f
JH
528 if (!data)
529 die("unable to read tree (%s)",
4c068a98 530 sha1_to_hex(entry.sha1));
6fda5e51 531 init_tree_desc(&sub, data, size);
1362671f 532 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
533 free(data);
534 }
5010cb5f 535 }
620e2bb9 536 strbuf_release(&pathbuf);
5010cb5f
JH
537 return hit;
538}
539
1362671f 540static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
541 struct object *obj, const char *name)
542{
1974632c 543 if (obj->type == OBJ_BLOB)
0d042fec 544 return grep_sha1(opt, obj->sha1, name, 0);
1974632c 545 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
5010cb5f
JH
546 struct tree_desc tree;
547 void *data;
6fda5e51 548 unsigned long size;
5010cb5f
JH
549 int hit;
550 data = read_object_with_reference(obj->sha1, tree_type,
6fda5e51 551 &size, NULL);
5010cb5f
JH
552 if (!data)
553 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
6fda5e51 554 init_tree_desc(&tree, data, size);
1362671f 555 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
556 free(data);
557 return hit;
558 }
885a86ab 559 die("unable to grep from object of type %s", typename(obj->type));
5010cb5f
JH
560}
561
562static const char builtin_grep_usage[] =
fa4946b5 563"git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
5010cb5f 564
088b084b
JH
565static const char emsg_invalid_context_len[] =
566"%s: invalid context length argument";
567static const char emsg_missing_context_len[] =
568"missing context length argument";
569static const char emsg_missing_argument[] =
570"option requires an argument -%s";
571
a633fca0 572int cmd_grep(int argc, const char **argv, const char *prefix)
5010cb5f 573{
5010cb5f 574 int hit = 0;
5010cb5f 575 int cached = 0;
1b5fb44a 576 int external_grep_allowed = 1;
5acd64ed 577 int seen_dashdash = 0;
5010cb5f 578 struct grep_opt opt;
1f1e895f 579 struct object_array list = { 0, 0, NULL };
1362671f 580 const char **paths = NULL;
5acd64ed 581 int i;
5010cb5f
JH
582
583 memset(&opt, 0, sizeof(opt));
0d042fec
JH
584 opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
585 opt.relative = 1;
7977f0ea 586 opt.pathname = 1;
f9b9faf6 587 opt.pattern_tail = &opt.pattern_list;
5010cb5f
JH
588 opt.regflags = REG_NEWLINE;
589
7e8f59d5
RS
590 strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
591 opt.color = -1;
592 git_config(grep_config, &opt);
593 if (opt.color == -1)
594 opt.color = git_use_color_default;
595
5010cb5f 596 /*
5acd64ed
JH
597 * If there is no -- then the paths must exist in the working
598 * tree. If there is no explicit pattern specified with -e or
599 * -f, we take the first unrecognized non option to be the
600 * pattern, but then what follows it must be zero or more
601 * valid refs up to the -- (if exists), and then existing
602 * paths. If there is an explicit pattern, then the first
82e5a82f 603 * unrecognized non option is the beginning of the refs list
5acd64ed 604 * that continues up to the -- (if exists), and then paths.
5010cb5f 605 */
5acd64ed 606
1362671f
JH
607 while (1 < argc) {
608 const char *arg = argv[1];
609 argc--; argv++;
610 if (!strcmp("--cached", arg)) {
611 cached = 1;
612 continue;
613 }
e70b9a8b 614 if (!strcmp("--no-ext-grep", arg)) {
1b5fb44a 615 external_grep_allowed = 0;
e70b9a8b
NTND
616 continue;
617 }
b8d0f5a0
JH
618 if (!strcmp("-a", arg) ||
619 !strcmp("--text", arg)) {
620 opt.binary = GREP_BINARY_TEXT;
621 continue;
622 }
1362671f
JH
623 if (!strcmp("-i", arg) ||
624 !strcmp("--ignore-case", arg)) {
625 opt.regflags |= REG_ICASE;
626 continue;
627 }
b8d0f5a0
JH
628 if (!strcmp("-I", arg)) {
629 opt.binary = GREP_BINARY_NOMATCH;
630 continue;
631 }
1362671f
JH
632 if (!strcmp("-v", arg) ||
633 !strcmp("--invert-match", arg)) {
634 opt.invert = 1;
635 continue;
636 }
637 if (!strcmp("-E", arg) ||
638 !strcmp("--extended-regexp", arg)) {
639 opt.regflags |= REG_EXTENDED;
640 continue;
641 }
07ea91d8
JH
642 if (!strcmp("-F", arg) ||
643 !strcmp("--fixed-strings", arg)) {
644 opt.fixed = 1;
645 continue;
646 }
1362671f
JH
647 if (!strcmp("-G", arg) ||
648 !strcmp("--basic-regexp", arg)) {
649 opt.regflags &= ~REG_EXTENDED;
650 continue;
651 }
652 if (!strcmp("-n", arg)) {
653 opt.linenum = 1;
654 continue;
655 }
7977f0ea
LT
656 if (!strcmp("-h", arg)) {
657 opt.pathname = 0;
658 continue;
659 }
1362671f 660 if (!strcmp("-H", arg)) {
7977f0ea 661 opt.pathname = 1;
1362671f
JH
662 continue;
663 }
664 if (!strcmp("-l", arg) ||
2cd5dfd2 665 !strcmp("--name-only", arg) ||
1362671f
JH
666 !strcmp("--files-with-matches", arg)) {
667 opt.name_only = 1;
668 continue;
669 }
e23d2d6b
JH
670 if (!strcmp("-L", arg) ||
671 !strcmp("--files-without-match", arg)) {
672 opt.unmatch_name_only = 1;
673 continue;
674 }
83caecca
RZ
675 if (!strcmp("-z", arg) ||
676 !strcmp("--null", arg)) {
677 opt.null_following_name = 1;
678 continue;
679 }
2c866cf1
JH
680 if (!strcmp("-c", arg) ||
681 !strcmp("--count", arg)) {
682 opt.count = 1;
683 continue;
684 }
7839a25e
JH
685 if (!strcmp("-w", arg) ||
686 !strcmp("--word-regexp", arg)) {
687 opt.word_regexp = 1;
688 continue;
689 }
599065a3
JH
690 if (!prefixcmp(arg, "-A") ||
691 !prefixcmp(arg, "-B") ||
692 !prefixcmp(arg, "-C") ||
f462ebb4 693 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1362671f 694 unsigned num;
f462ebb4
JH
695 const char *scan;
696 switch (arg[1]) {
697 case 'A': case 'B': case 'C':
698 if (!arg[2]) {
699 if (argc <= 1)
088b084b 700 die(emsg_missing_context_len);
f462ebb4
JH
701 scan = *++argv;
702 argc--;
703 }
704 else
705 scan = arg + 2;
706 break;
707 default:
708 scan = arg + 1;
709 break;
710 }
6aead43d 711 if (strtoul_ui(scan, 10, &num))
088b084b 712 die(emsg_invalid_context_len, scan);
1362671f
JH
713 switch (arg[1]) {
714 case 'A':
715 opt.post_context = num;
716 break;
f462ebb4 717 default:
1362671f
JH
718 case 'C':
719 opt.post_context = num;
720 case 'B':
721 opt.pre_context = num;
722 break;
5010cb5f 723 }
1362671f
JH
724 continue;
725 }
aa8c79ad
JH
726 if (!strcmp("-f", arg)) {
727 FILE *patterns;
728 int lno = 0;
729 char buf[1024];
730 if (argc <= 1)
088b084b 731 die(emsg_missing_argument, arg);
aa8c79ad
JH
732 patterns = fopen(argv[1], "r");
733 if (!patterns)
5acd64ed 734 die("'%s': %s", argv[1], strerror(errno));
aa8c79ad
JH
735 while (fgets(buf, sizeof(buf), patterns)) {
736 int len = strlen(buf);
872c930d 737 if (len && buf[len-1] == '\n')
aa8c79ad
JH
738 buf[len-1] = 0;
739 /* ignore empty line like grep does */
740 if (!buf[0])
741 continue;
83b5d2f5
JH
742 append_grep_pattern(&opt, xstrdup(buf),
743 argv[1], ++lno,
744 GREP_PATTERN);
aa8c79ad
JH
745 }
746 fclose(patterns);
747 argv++;
748 argc--;
749 continue;
750 }
79d3696c 751 if (!strcmp("--not", arg)) {
83b5d2f5
JH
752 append_grep_pattern(&opt, arg, "command line", 0,
753 GREP_NOT);
79d3696c
JH
754 continue;
755 }
756 if (!strcmp("--and", arg)) {
83b5d2f5
JH
757 append_grep_pattern(&opt, arg, "command line", 0,
758 GREP_AND);
79d3696c
JH
759 continue;
760 }
761 if (!strcmp("--or", arg))
762 continue; /* no-op */
763 if (!strcmp("(", arg)) {
83b5d2f5
JH
764 append_grep_pattern(&opt, arg, "command line", 0,
765 GREP_OPEN_PAREN);
79d3696c
JH
766 continue;
767 }
768 if (!strcmp(")", arg)) {
83b5d2f5
JH
769 append_grep_pattern(&opt, arg, "command line", 0,
770 GREP_CLOSE_PAREN);
79d3696c
JH
771 continue;
772 }
0ab7befa
JH
773 if (!strcmp("--all-match", arg)) {
774 opt.all_match = 1;
775 continue;
776 }
1362671f
JH
777 if (!strcmp("-e", arg)) {
778 if (1 < argc) {
83b5d2f5
JH
779 append_grep_pattern(&opt, argv[1],
780 "-e option", 0,
781 GREP_PATTERN);
f9b9faf6 782 argv++;
1362671f 783 argc--;
5010cb5f
JH
784 continue;
785 }
088b084b 786 die(emsg_missing_argument, arg);
1362671f 787 }
0d042fec
JH
788 if (!strcmp("--full-name", arg)) {
789 opt.relative = 0;
790 continue;
791 }
7e8f59d5
RS
792 if (!strcmp("--color", arg)) {
793 opt.color = 1;
794 continue;
795 }
796 if (!strcmp("--no-color", arg)) {
797 opt.color = 0;
798 continue;
799 }
5390590f
JH
800 if (!strcmp("--", arg)) {
801 /* later processing wants to have this at argv[1] */
802 argv--;
803 argc++;
5acd64ed 804 break;
5390590f 805 }
5acd64ed 806 if (*arg == '-')
1362671f 807 usage(builtin_grep_usage);
5acd64ed
JH
808
809 /* First unrecognized non-option token */
f9b9faf6 810 if (!opt.pattern_list) {
83b5d2f5
JH
811 append_grep_pattern(&opt, arg, "command line", 0,
812 GREP_PATTERN);
1362671f
JH
813 break;
814 }
815 else {
816 /* We are looking at the first path or rev;
5acd64ed 817 * it is found at argv[1] after leaving the
1362671f
JH
818 * loop.
819 */
820 argc++; argv--;
821 break;
5010cb5f 822 }
5010cb5f 823 }
5acd64ed 824
6e89ec0f 825 if (opt.color && !opt.color_external)
1b5fb44a 826 external_grep_allowed = 0;
f9b9faf6 827 if (!opt.pattern_list)
5010cb5f 828 die("no pattern given.");
07ea91d8
JH
829 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
830 die("cannot mix --fixed-strings and regexp");
83b5d2f5 831 compile_grep_patterns(&opt);
5acd64ed
JH
832
833 /* Check revs and then paths */
834 for (i = 1; i < argc; i++) {
835 const char *arg = argv[i];
1362671f 836 unsigned char sha1[20];
5acd64ed
JH
837 /* Is it a rev? */
838 if (!get_sha1(arg, sha1)) {
839 struct object *object = parse_object(sha1);
5acd64ed
JH
840 if (!object)
841 die("bad object %s", arg);
1f1e895f 842 add_object_array(object, arg, &list);
5acd64ed
JH
843 continue;
844 }
845 if (!strcmp(arg, "--")) {
846 i++;
847 seen_dashdash = 1;
848 }
849 break;
1362671f 850 }
5acd64ed
JH
851
852 /* The rest are paths */
853 if (!seen_dashdash) {
854 int j;
c39c4f47 855 for (j = i; j < argc; j++)
5acd64ed
JH
856 verify_filename(prefix, argv[j]);
857 }
858
0d042fec 859 if (i < argc) {
5acd64ed 860 paths = get_pathspec(prefix, argv + i);
0d042fec
JH
861 if (opt.prefix_length && opt.relative) {
862 /* Make sure we do not get outside of paths */
863 for (i = 0; paths[i]; i++)
864 if (strncmp(prefix, paths[i], opt.prefix_length))
7e44c935 865 die("git grep: cannot generate relative filenames containing '..'");
0d042fec
JH
866 }
867 }
1362671f
JH
868 else if (prefix) {
869 paths = xcalloc(2, sizeof(const char *));
870 paths[0] = prefix;
871 paths[1] = NULL;
872 }
5010cb5f 873
6577f542
NTND
874 if (!list.nr) {
875 if (!cached)
876 setup_work_tree();
1b5fb44a 877 return !grep_cache(&opt, paths, cached, external_grep_allowed);
6577f542 878 }
aa8c79ad 879
5010cb5f 880 if (cached)
aa8c79ad 881 die("both --cached and trees are given.");
5010cb5f 882
1f1e895f 883 for (i = 0; i < list.nr; i++) {
5010cb5f 884 struct object *real_obj;
1f1e895f
LT
885 real_obj = deref_tag(list.objects[i].item, NULL, 0);
886 if (grep_object(&opt, paths, real_obj, list.objects[i].name))
5010cb5f
JH
887 hit = 1;
888 }
b48fb5b6 889 free_grep_patterns(&opt);
5010cb5f
JH
890 return !hit;
891}