builtin-grep: use external grep when we can take advantage of it
[git/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
JH
12#include "builtin.h"
13#include <regex.h>
e0eb889f 14#include <fnmatch.h>
1e2398d7 15#include <sys/wait.h>
5010cb5f 16
e0eb889f
JH
17/*
18 * git grep pathspecs are somewhat different from diff-tree pathspecs;
19 * pathname wildcards are allowed.
20 */
1362671f 21static int pathspec_matches(const char **paths, const char *name)
5010cb5f 22{
e0eb889f 23 int namelen, i;
1362671f 24 if (!paths || !*paths)
5010cb5f
JH
25 return 1;
26 namelen = strlen(name);
1362671f
JH
27 for (i = 0; paths[i]; i++) {
28 const char *match = paths[i];
29 int matchlen = strlen(match);
1e3d90e0 30 const char *cp, *meta;
e0eb889f
JH
31
32 if ((matchlen <= namelen) &&
33 !strncmp(name, match, matchlen) &&
34 (match[matchlen-1] == '/' ||
35 name[matchlen] == '\0' || name[matchlen] == '/'))
36 return 1;
37 if (!fnmatch(match, name, 0))
38 return 1;
39 if (name[namelen-1] != '/')
5010cb5f 40 continue;
e0eb889f 41
1e3d90e0 42 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
43 * descending into.
44 *
45 * Find the longest leading directory name that does
46 * not have metacharacter in the pathspec; the name
47 * we are looking at must overlap with that directory.
5010cb5f 48 */
1e3d90e0 49 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 50 char ch = *cp;
1e3d90e0
JH
51 if (ch == '*' || ch == '[' || ch == '?') {
52 meta = cp;
5010cb5f 53 break;
1e3d90e0 54 }
e0eb889f 55 }
1e3d90e0
JH
56 if (!meta)
57 meta = cp; /* fully literal */
58
59 if (namelen <= meta - match) {
e0eb889f
JH
60 /* Looking at "Documentation/" and
61 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
62 * "Documentation/diff*.txt". The name we
63 * have should match prefix.
e0eb889f
JH
64 */
65 if (!memcmp(match, name, namelen))
66 return 1;
1e3d90e0 67 continue;
e0eb889f 68 }
1e3d90e0
JH
69
70 if (meta - match < namelen) {
e0eb889f 71 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
72 * the pattern says "Documentation/h*";
73 * match up to "Do.../h"; this avoids descending
74 * into "Documentation/technical/".
e0eb889f 75 */
1e3d90e0 76 if (!memcmp(match, name, meta - match))
e0eb889f 77 return 1;
1e3d90e0 78 continue;
e0eb889f 79 }
5010cb5f
JH
80 }
81 return 0;
82}
83
f9b9faf6
JH
84struct grep_pat {
85 struct grep_pat *next;
aa8c79ad
JH
86 const char *origin;
87 int no;
5010cb5f
JH
88 const char *pattern;
89 regex_t regexp;
f9b9faf6
JH
90};
91
92struct grep_opt {
93 struct grep_pat *pattern_list;
94 struct grep_pat **pattern_tail;
95 regex_t regexp;
5010cb5f
JH
96 unsigned linenum:1;
97 unsigned invert:1;
df0e7aa8 98 unsigned name_only:1;
e23d2d6b 99 unsigned unmatch_name_only:1;
2c866cf1 100 unsigned count:1;
7839a25e 101 unsigned word_regexp:1;
07ea91d8 102 unsigned fixed:1;
b8d0f5a0
JH
103#define GREP_BINARY_DEFAULT 0
104#define GREP_BINARY_NOMATCH 1
105#define GREP_BINARY_TEXT 2
106 unsigned binary:2;
5010cb5f
JH
107 int regflags;
108 unsigned pre_context;
109 unsigned post_context;
110};
111
aa8c79ad
JH
112static void add_pattern(struct grep_opt *opt, const char *pat,
113 const char *origin, int no)
f9b9faf6
JH
114{
115 struct grep_pat *p = xcalloc(1, sizeof(*p));
116 p->pattern = pat;
aa8c79ad
JH
117 p->origin = origin;
118 p->no = no;
f9b9faf6
JH
119 *opt->pattern_tail = p;
120 opt->pattern_tail = &p->next;
121 p->next = NULL;
122}
123
124static void compile_patterns(struct grep_opt *opt)
125{
126 struct grep_pat *p;
127 for (p = opt->pattern_list; p; p = p->next) {
128 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
129 if (err) {
130 char errbuf[1024];
aa8c79ad
JH
131 char where[1024];
132 if (p->no)
133 sprintf(where, "In '%s' at %d, ",
134 p->origin, p->no);
135 else if (p->origin)
136 sprintf(where, "%s, ", p->origin);
137 else
138 where[0] = 0;
f9b9faf6
JH
139 regerror(err, &p->regexp, errbuf, 1024);
140 regfree(&p->regexp);
aa8c79ad 141 die("%s'%s': %s", where, p->pattern, errbuf);
f9b9faf6
JH
142 }
143 }
144}
145
5010cb5f
JH
146static char *end_of_line(char *cp, unsigned long *left)
147{
148 unsigned long l = *left;
149 while (l && *cp != '\n') {
150 l--;
151 cp++;
152 }
153 *left = l;
154 return cp;
155}
156
7839a25e
JH
157static int word_char(char ch)
158{
159 return isalnum(ch) || ch == '_';
160}
161
5010cb5f
JH
162static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
163 const char *name, unsigned lno, char sign)
164{
165 printf("%s%c", name, sign);
166 if (opt->linenum)
167 printf("%d%c", lno, sign);
a24f1e25 168 printf("%.*s\n", (int)(eol-bol), bol);
5010cb5f
JH
169}
170
b8d0f5a0
JH
171/*
172 * NEEDSWORK: share code with diff.c
173 */
174#define FIRST_FEW_BYTES 8000
175static int buffer_is_binary(const char *ptr, unsigned long size)
176{
177 if (FIRST_FEW_BYTES < size)
178 size = FIRST_FEW_BYTES;
179 if (memchr(ptr, 0, size))
180 return 1;
181 return 0;
182}
183
07ea91d8
JH
184static int fixmatch(const char *pattern, char *line, regmatch_t *match)
185{
186 char *hit = strstr(line, pattern);
187 if (!hit) {
188 match->rm_so = match->rm_eo = -1;
189 return REG_NOMATCH;
190 }
191 else {
192 match->rm_so = hit - line;
193 match->rm_eo = match->rm_so + strlen(pattern);
194 return 0;
195 }
196}
197
5010cb5f
JH
198static int grep_buffer(struct grep_opt *opt, const char *name,
199 char *buf, unsigned long size)
200{
201 char *bol = buf;
202 unsigned long left = size;
203 unsigned lno = 1;
204 struct pre_context_line {
205 char *bol;
206 char *eol;
207 } *prev = NULL, *pcl;
208 unsigned last_hit = 0;
209 unsigned last_shown = 0;
b8d0f5a0 210 int binary_match_only = 0;
5010cb5f 211 const char *hunk_mark = "";
2c866cf1 212 unsigned count = 0;
5010cb5f 213
b8d0f5a0
JH
214 if (buffer_is_binary(buf, size)) {
215 switch (opt->binary) {
216 case GREP_BINARY_DEFAULT:
217 binary_match_only = 1;
218 break;
219 case GREP_BINARY_NOMATCH:
220 return 0; /* Assume unmatch */
221 break;
222 default:
223 break;
224 }
225 }
226
5010cb5f
JH
227 if (opt->pre_context)
228 prev = xcalloc(opt->pre_context, sizeof(*prev));
229 if (opt->pre_context || opt->post_context)
230 hunk_mark = "--\n";
231
232 while (left) {
233 regmatch_t pmatch[10];
234 char *eol, ch;
f9b9faf6
JH
235 int hit = 0;
236 struct grep_pat *p;
5010cb5f
JH
237
238 eol = end_of_line(bol, &left);
239 ch = *eol;
240 *eol = 0;
241
f9b9faf6 242 for (p = opt->pattern_list; p; p = p->next) {
07ea91d8
JH
243 if (!opt->fixed) {
244 regex_t *exp = &p->regexp;
245 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
246 pmatch, 0);
247 }
248 else {
249 hit = !fixmatch(p->pattern, bol, pmatch);
250 }
7839a25e
JH
251
252 if (hit && opt->word_regexp) {
253 /* Match beginning must be either
254 * beginning of the line, or at word
255 * boundary (i.e. the last char must
256 * not be alnum or underscore).
257 */
258 if ((pmatch[0].rm_so < 0) ||
259 (eol - bol) <= pmatch[0].rm_so ||
260 (pmatch[0].rm_eo < 0) ||
261 (eol - bol) < pmatch[0].rm_eo)
262 die("regexp returned nonsense");
263 if (pmatch[0].rm_so != 0 &&
264 word_char(bol[pmatch[0].rm_so-1]))
02ab1c49
JH
265 hit = 0;
266 if (pmatch[0].rm_eo != (eol-bol) &&
7839a25e 267 word_char(bol[pmatch[0].rm_eo]))
02ab1c49 268 hit = 0;
7839a25e 269 }
f9b9faf6
JH
270 if (hit)
271 break;
272 }
273 /* "grep -v -e foo -e bla" should list lines
274 * that do not have either, so inversion should
275 * be done outside.
276 */
5010cb5f
JH
277 if (opt->invert)
278 hit = !hit;
e23d2d6b
JH
279 if (opt->unmatch_name_only) {
280 if (hit)
281 return 0;
282 goto next_line;
283 }
5010cb5f 284 if (hit) {
2c866cf1 285 count++;
b8d0f5a0
JH
286 if (binary_match_only) {
287 printf("Binary file %s matches\n", name);
288 return 1;
289 }
df0e7aa8
JH
290 if (opt->name_only) {
291 printf("%s\n", name);
292 return 1;
293 }
5010cb5f
JH
294 /* Hit at this line. If we haven't shown the
295 * pre-context lines, we would need to show them.
2c866cf1
JH
296 * When asked to do "count", this still show
297 * the context which is nonsense, but the user
298 * deserves to get that ;-).
5010cb5f
JH
299 */
300 if (opt->pre_context) {
301 unsigned from;
302 if (opt->pre_context < lno)
303 from = lno - opt->pre_context;
304 else
305 from = 1;
306 if (from <= last_shown)
307 from = last_shown + 1;
308 if (last_shown && from != last_shown + 1)
309 printf(hunk_mark);
310 while (from < lno) {
311 pcl = &prev[lno-from-1];
312 show_line(opt, pcl->bol, pcl->eol,
313 name, from, '-');
314 from++;
315 }
316 last_shown = lno-1;
317 }
318 if (last_shown && lno != last_shown + 1)
319 printf(hunk_mark);
2c866cf1
JH
320 if (!opt->count)
321 show_line(opt, bol, eol, name, lno, ':');
5010cb5f
JH
322 last_shown = last_hit = lno;
323 }
324 else if (last_hit &&
325 lno <= last_hit + opt->post_context) {
326 /* If the last hit is within the post context,
327 * we need to show this line.
328 */
329 if (last_shown && lno != last_shown + 1)
330 printf(hunk_mark);
331 show_line(opt, bol, eol, name, lno, '-');
332 last_shown = lno;
333 }
334 if (opt->pre_context) {
335 memmove(prev+1, prev,
336 (opt->pre_context-1) * sizeof(*prev));
337 prev->bol = bol;
338 prev->eol = eol;
339 }
e23d2d6b
JH
340
341 next_line:
5010cb5f
JH
342 *eol = ch;
343 bol = eol + 1;
7ed36f56
JH
344 if (!left)
345 break;
5010cb5f
JH
346 left--;
347 lno++;
348 }
e23d2d6b
JH
349
350 if (opt->unmatch_name_only) {
351 /* We did not see any hit, so we want to show this */
352 printf("%s\n", name);
353 return 1;
354 }
355
2c866cf1
JH
356 /* NEEDSWORK:
357 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
358 * which feels mostly useless but sometimes useful. Maybe
359 * make it another option? For now suppress them.
360 */
361 if (opt->count && count)
362 printf("%s:%u\n", name, count);
5010cb5f
JH
363 return !!last_hit;
364}
365
366static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
367{
368 unsigned long size;
369 char *data;
370 char type[20];
371 int hit;
372 data = read_sha1_file(sha1, type, &size);
373 if (!data) {
374 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
375 return 0;
376 }
377 hit = grep_buffer(opt, name, data, size);
378 free(data);
379 return hit;
380}
381
382static int grep_file(struct grep_opt *opt, const char *filename)
383{
384 struct stat st;
385 int i;
386 char *data;
387 if (lstat(filename, &st) < 0) {
388 err_ret:
389 if (errno != ENOENT)
390 error("'%s': %s", filename, strerror(errno));
391 return 0;
392 }
393 if (!st.st_size)
394 return 0; /* empty file -- no grep hit */
395 if (!S_ISREG(st.st_mode))
396 return 0;
397 i = open(filename, O_RDONLY);
398 if (i < 0)
399 goto err_ret;
400 data = xmalloc(st.st_size + 1);
401 if (st.st_size != xread(i, data, st.st_size)) {
402 error("'%s': short read %s", filename, strerror(errno));
403 close(i);
404 free(data);
405 return 0;
406 }
407 close(i);
408 i = grep_buffer(opt, filename, data, st.st_size);
409 free(data);
410 return i;
411}
412
1e2398d7
LT
413static int exec_grep(int argc, const char **argv)
414{
415 pid_t pid;
416 int status;
417
418 argv[argc] = NULL;
419 pid = fork();
420 if (pid < 0)
421 return pid;
422 if (!pid) {
423 execvp("grep", (char **) argv);
424 exit(255);
425 }
426 while (waitpid(pid, &status, 0) < 0) {
427 if (errno == EINTR)
428 continue;
429 return -1;
430 }
431 if (WIFEXITED(status)) {
432 if (!WEXITSTATUS(status))
433 return 1;
434 return 0;
435 }
436 return -1;
437}
438
439#define MAXARGS 1000
440
441static int external_grep(struct grep_opt *opt, const char **paths, int cached)
442{
443 int i, nr, argc, hit;
444 const char *argv[MAXARGS+1];
445 struct grep_pat *p;
446
447 nr = 0;
448 argv[nr++] = "grep";
449 if (opt->word_regexp)
450 argv[nr++] = "-w";
451 if (opt->name_only)
452 argv[nr++] = "-l";
453 for (p = opt->pattern_list; p; p = p->next) {
454 argv[nr++] = "-e";
455 argv[nr++] = p->pattern;
456 }
457 argv[nr++] = "--";
458
459 hit = 0;
460 argc = nr;
461 for (i = 0; i < active_nr; i++) {
462 struct cache_entry *ce = active_cache[i];
463 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
464 continue;
465 if (!pathspec_matches(paths, ce->name))
466 continue;
467 argv[argc++] = ce->name;
468 if (argc < MAXARGS)
469 continue;
470 hit += exec_grep(argc, argv);
471 argc = nr;
472 }
473 if (argc > nr)
474 hit += exec_grep(argc, argv);
475 return 0;
476}
477
1362671f 478static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
5010cb5f
JH
479{
480 int hit = 0;
481 int nr;
482 read_cache();
483
1e2398d7
LT
484#ifdef __unix__
485 /*
486 * Use the external "grep" command for the case where
487 * we grep through the checked-out files. It tends to
488 * be a lot more optimized
489 */
490 if (!cached) {
491 hit = external_grep(opt, paths, cached);
492 if (hit >= 0)
493 return hit;
494 }
495#endif
496
5010cb5f
JH
497 for (nr = 0; nr < active_nr; nr++) {
498 struct cache_entry *ce = active_cache[nr];
499 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
500 continue;
1362671f 501 if (!pathspec_matches(paths, ce->name))
5010cb5f
JH
502 continue;
503 if (cached)
504 hit |= grep_sha1(opt, ce->sha1, ce->name);
505 else
506 hit |= grep_file(opt, ce->name);
507 }
508 return hit;
509}
510
1362671f 511static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
512 struct tree_desc *tree,
513 const char *tree_name, const char *base)
514{
515 unsigned mode;
516 int len;
517 int hit = 0;
518 const char *path;
519 const unsigned char *sha1;
e0eb889f 520 char *down;
5010cb5f
JH
521 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
522
523 if (tree_name[0]) {
524 int offset = sprintf(path_buf, "%s:", tree_name);
e0eb889f
JH
525 down = path_buf + offset;
526 strcat(down, base);
5010cb5f
JH
527 }
528 else {
e0eb889f
JH
529 down = path_buf;
530 strcpy(down, base);
5010cb5f
JH
531 }
532 len = strlen(path_buf);
533
534 while (tree->size) {
535 int pathlen;
536 sha1 = tree_entry_extract(tree, &path, &mode);
537 pathlen = strlen(path);
538 strcpy(path_buf + len, path);
539
e0eb889f
JH
540 if (S_ISDIR(mode))
541 /* Match "abc/" against pathspec to
542 * decide if we want to descend into "abc"
543 * directory.
544 */
545 strcpy(path_buf + len + pathlen, "/");
546
1362671f 547 if (!pathspec_matches(paths, down))
5010cb5f
JH
548 ;
549 else if (S_ISREG(mode))
550 hit |= grep_sha1(opt, sha1, path_buf);
551 else if (S_ISDIR(mode)) {
552 char type[20];
553 struct tree_desc sub;
554 void *data;
555 data = read_sha1_file(sha1, type, &sub.size);
556 if (!data)
557 die("unable to read tree (%s)",
558 sha1_to_hex(sha1));
5010cb5f 559 sub.buf = data;
1362671f 560 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
561 free(data);
562 }
563 update_tree_entry(tree);
564 }
565 return hit;
566}
567
1362671f 568static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
569 struct object *obj, const char *name)
570{
571 if (!strcmp(obj->type, blob_type))
572 return grep_sha1(opt, obj->sha1, name);
573 if (!strcmp(obj->type, commit_type) ||
574 !strcmp(obj->type, tree_type)) {
575 struct tree_desc tree;
576 void *data;
577 int hit;
578 data = read_object_with_reference(obj->sha1, tree_type,
579 &tree.size, NULL);
580 if (!data)
581 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
582 tree.buf = data;
1362671f 583 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
584 free(data);
585 return hit;
586 }
587 die("unable to grep from object of type %s", obj->type);
588}
589
590static const char builtin_grep_usage[] =
591"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
592
593int cmd_grep(int argc, const char **argv, char **envp)
594{
5010cb5f 595 int hit = 0;
5010cb5f 596 int cached = 0;
5acd64ed 597 int seen_dashdash = 0;
5010cb5f 598 struct grep_opt opt;
1362671f
JH
599 struct object_list *list, **tail, *object_list = NULL;
600 const char *prefix = setup_git_directory();
601 const char **paths = NULL;
5acd64ed 602 int i;
5010cb5f
JH
603
604 memset(&opt, 0, sizeof(opt));
f9b9faf6 605 opt.pattern_tail = &opt.pattern_list;
5010cb5f
JH
606 opt.regflags = REG_NEWLINE;
607
608 /*
5acd64ed
JH
609 * If there is no -- then the paths must exist in the working
610 * tree. If there is no explicit pattern specified with -e or
611 * -f, we take the first unrecognized non option to be the
612 * pattern, but then what follows it must be zero or more
613 * valid refs up to the -- (if exists), and then existing
614 * paths. If there is an explicit pattern, then the first
615 * unrecocnized non option is the beginning of the refs list
616 * that continues up to the -- (if exists), and then paths.
5010cb5f 617 */
5acd64ed
JH
618
619 tail = &object_list;
1362671f
JH
620 while (1 < argc) {
621 const char *arg = argv[1];
622 argc--; argv++;
623 if (!strcmp("--cached", arg)) {
624 cached = 1;
625 continue;
626 }
b8d0f5a0
JH
627 if (!strcmp("-a", arg) ||
628 !strcmp("--text", arg)) {
629 opt.binary = GREP_BINARY_TEXT;
630 continue;
631 }
1362671f
JH
632 if (!strcmp("-i", arg) ||
633 !strcmp("--ignore-case", arg)) {
634 opt.regflags |= REG_ICASE;
635 continue;
636 }
b8d0f5a0
JH
637 if (!strcmp("-I", arg)) {
638 opt.binary = GREP_BINARY_NOMATCH;
639 continue;
640 }
1362671f
JH
641 if (!strcmp("-v", arg) ||
642 !strcmp("--invert-match", arg)) {
643 opt.invert = 1;
644 continue;
645 }
646 if (!strcmp("-E", arg) ||
647 !strcmp("--extended-regexp", arg)) {
648 opt.regflags |= REG_EXTENDED;
649 continue;
650 }
07ea91d8
JH
651 if (!strcmp("-F", arg) ||
652 !strcmp("--fixed-strings", arg)) {
653 opt.fixed = 1;
654 continue;
655 }
1362671f
JH
656 if (!strcmp("-G", arg) ||
657 !strcmp("--basic-regexp", arg)) {
658 opt.regflags &= ~REG_EXTENDED;
659 continue;
660 }
661 if (!strcmp("-n", arg)) {
662 opt.linenum = 1;
663 continue;
664 }
665 if (!strcmp("-H", arg)) {
666 /* We always show the pathname, so this
667 * is a noop.
668 */
669 continue;
670 }
671 if (!strcmp("-l", arg) ||
672 !strcmp("--files-with-matches", arg)) {
673 opt.name_only = 1;
674 continue;
675 }
e23d2d6b
JH
676 if (!strcmp("-L", arg) ||
677 !strcmp("--files-without-match", arg)) {
678 opt.unmatch_name_only = 1;
679 continue;
680 }
2c866cf1
JH
681 if (!strcmp("-c", arg) ||
682 !strcmp("--count", arg)) {
683 opt.count = 1;
684 continue;
685 }
7839a25e
JH
686 if (!strcmp("-w", arg) ||
687 !strcmp("--word-regexp", arg)) {
688 opt.word_regexp = 1;
689 continue;
690 }
f462ebb4
JH
691 if (!strncmp("-A", arg, 2) ||
692 !strncmp("-B", arg, 2) ||
693 !strncmp("-C", arg, 2) ||
694 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1362671f 695 unsigned num;
f462ebb4
JH
696 const char *scan;
697 switch (arg[1]) {
698 case 'A': case 'B': case 'C':
699 if (!arg[2]) {
700 if (argc <= 1)
701 usage(builtin_grep_usage);
702 scan = *++argv;
703 argc--;
704 }
705 else
706 scan = arg + 2;
707 break;
708 default:
709 scan = arg + 1;
710 break;
711 }
712 if (sscanf(scan, "%u", &num) != 1)
5010cb5f 713 usage(builtin_grep_usage);
1362671f
JH
714 switch (arg[1]) {
715 case 'A':
716 opt.post_context = num;
717 break;
f462ebb4 718 default:
1362671f
JH
719 case 'C':
720 opt.post_context = num;
721 case 'B':
722 opt.pre_context = num;
723 break;
5010cb5f 724 }
1362671f
JH
725 continue;
726 }
aa8c79ad
JH
727 if (!strcmp("-f", arg)) {
728 FILE *patterns;
729 int lno = 0;
730 char buf[1024];
731 if (argc <= 1)
732 usage(builtin_grep_usage);
733 patterns = fopen(argv[1], "r");
734 if (!patterns)
5acd64ed 735 die("'%s': %s", argv[1], strerror(errno));
aa8c79ad
JH
736 while (fgets(buf, sizeof(buf), patterns)) {
737 int len = strlen(buf);
738 if (buf[len-1] == '\n')
739 buf[len-1] = 0;
740 /* ignore empty line like grep does */
741 if (!buf[0])
742 continue;
743 add_pattern(&opt, strdup(buf), argv[1], ++lno);
744 }
745 fclose(patterns);
746 argv++;
747 argc--;
748 continue;
749 }
1362671f
JH
750 if (!strcmp("-e", arg)) {
751 if (1 < argc) {
aa8c79ad 752 add_pattern(&opt, argv[1], "-e option", 0);
f9b9faf6 753 argv++;
1362671f 754 argc--;
5010cb5f
JH
755 continue;
756 }
1362671f
JH
757 usage(builtin_grep_usage);
758 }
5acd64ed
JH
759 if (!strcmp("--", arg))
760 break;
761 if (*arg == '-')
1362671f 762 usage(builtin_grep_usage);
5acd64ed
JH
763
764 /* First unrecognized non-option token */
f9b9faf6 765 if (!opt.pattern_list) {
aa8c79ad 766 add_pattern(&opt, arg, "command line", 0);
1362671f
JH
767 break;
768 }
769 else {
770 /* We are looking at the first path or rev;
5acd64ed 771 * it is found at argv[1] after leaving the
1362671f
JH
772 * loop.
773 */
774 argc++; argv--;
775 break;
5010cb5f 776 }
5010cb5f 777 }
5acd64ed 778
f9b9faf6 779 if (!opt.pattern_list)
5010cb5f 780 die("no pattern given.");
07ea91d8
JH
781 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
782 die("cannot mix --fixed-strings and regexp");
783 if (!opt.fixed)
784 compile_patterns(&opt);
5acd64ed
JH
785
786 /* Check revs and then paths */
787 for (i = 1; i < argc; i++) {
788 const char *arg = argv[i];
1362671f 789 unsigned char sha1[20];
5acd64ed
JH
790 /* Is it a rev? */
791 if (!get_sha1(arg, sha1)) {
792 struct object *object = parse_object(sha1);
793 struct object_list *elem;
794 if (!object)
795 die("bad object %s", arg);
796 elem = object_list_insert(object, tail);
797 elem->name = arg;
798 tail = &elem->next;
799 continue;
800 }
801 if (!strcmp(arg, "--")) {
802 i++;
803 seen_dashdash = 1;
804 }
805 break;
1362671f 806 }
5acd64ed
JH
807
808 /* The rest are paths */
809 if (!seen_dashdash) {
810 int j;
c39c4f47 811 for (j = i; j < argc; j++)
5acd64ed
JH
812 verify_filename(prefix, argv[j]);
813 }
814
815 if (i < argc)
816 paths = get_pathspec(prefix, argv + i);
1362671f
JH
817 else if (prefix) {
818 paths = xcalloc(2, sizeof(const char *));
819 paths[0] = prefix;
820 paths[1] = NULL;
821 }
5010cb5f 822
1362671f
JH
823 if (!object_list)
824 return !grep_cache(&opt, paths, cached);
aa8c79ad 825
5010cb5f 826 if (cached)
aa8c79ad 827 die("both --cached and trees are given.");
5010cb5f 828
1362671f 829 for (list = object_list; list; list = list->next) {
5010cb5f
JH
830 struct object *real_obj;
831 real_obj = deref_tag(list->item, NULL, 0);
1362671f 832 if (grep_object(&opt, paths, real_obj, list->name))
5010cb5f
JH
833 hit = 1;
834 }
835 return !hit;
836}