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