blob: 66111de5148c17a156fdbfbc0d92b0c93c2b2c34 [file] [log] [blame]
Junio C Hamano5010cb52006-04-30 23:28:15 -07001/*
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"
Junio C Hamano13626712006-05-01 15:58:29 -070011#include "tree-walk.h"
Junio C Hamano5010cb52006-04-30 23:28:15 -070012#include "builtin.h"
13#include <regex.h>
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070014#include <fnmatch.h>
Linus Torvalds1e2398d2006-05-14 20:49:15 -070015#include <sys/wait.h>
Junio C Hamano5010cb52006-04-30 23:28:15 -070016
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070017/*
18 * git grep pathspecs are somewhat different from diff-tree pathspecs;
19 * pathname wildcards are allowed.
20 */
Junio C Hamano13626712006-05-01 15:58:29 -070021static int pathspec_matches(const char **paths, const char *name)
Junio C Hamano5010cb52006-04-30 23:28:15 -070022{
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070023 int namelen, i;
Junio C Hamano13626712006-05-01 15:58:29 -070024 if (!paths || !*paths)
Junio C Hamano5010cb52006-04-30 23:28:15 -070025 return 1;
26 namelen = strlen(name);
Junio C Hamano13626712006-05-01 15:58:29 -070027 for (i = 0; paths[i]; i++) {
28 const char *match = paths[i];
29 int matchlen = strlen(match);
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070030 const char *cp, *meta;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070031
32 if ((matchlen <= namelen) &&
33 !strncmp(name, match, matchlen) &&
34 (match[matchlen-1] == '/' ||
35 name[matchlen] == '\0' || name[matchlen] == '/'))
Junio C Hamano5010cb52006-04-30 23:28:15 -070036 return 1;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070037 if (!fnmatch(match, name, 0))
38 return 1;
39 if (name[namelen-1] != '/')
40 continue;
41
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070042 /* We are being asked if the directory ("name") is worth
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070043 * 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.
48 */
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070049 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070050 char ch = *cp;
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070051 if (ch == '*' || ch == '[' || ch == '?') {
52 meta = cp;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070053 break;
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070054 }
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070055 }
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070056 if (!meta)
57 meta = cp; /* fully literal */
58
59 if (namelen <= meta - match) {
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070060 /* Looking at "Documentation/" and
61 * the pattern says "Documentation/howto/", or
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070062 * "Documentation/diff*.txt". The name we
63 * have should match prefix.
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070064 */
65 if (!memcmp(match, name, namelen))
66 return 1;
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070067 continue;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070068 }
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070069
70 if (meta - match < namelen) {
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070071 /* Looking at "Documentation/howto/" and
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070072 * the pattern says "Documentation/h*";
73 * match up to "Do.../h"; this avoids descending
74 * into "Documentation/technical/".
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070075 */
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070076 if (!memcmp(match, name, meta - match))
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070077 return 1;
Junio C Hamano1e3d90e2006-05-02 17:27:07 -070078 continue;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -070079 }
Junio C Hamano5010cb52006-04-30 23:28:15 -070080 }
81 return 0;
82}
83
Junio C Hamanof9b9faf2006-05-02 15:40:49 -070084struct grep_pat {
85 struct grep_pat *next;
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -070086 const char *origin;
87 int no;
Junio C Hamano5010cb52006-04-30 23:28:15 -070088 const char *pattern;
89 regex_t regexp;
Junio C Hamanof9b9faf2006-05-02 15:40:49 -070090};
91
92struct grep_opt {
93 struct grep_pat *pattern_list;
94 struct grep_pat **pattern_tail;
95 regex_t regexp;
Junio C Hamano5010cb52006-04-30 23:28:15 -070096 unsigned linenum:1;
97 unsigned invert:1;
Junio C Hamanodf0e7aa2006-05-01 12:39:21 -070098 unsigned name_only:1;
Junio C Hamanoe23d2d62006-05-03 21:46:29 -070099 unsigned unmatch_name_only:1;
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700100 unsigned count:1;
Junio C Hamano7839a252006-05-02 15:40:49 -0700101 unsigned word_regexp:1;
Junio C Hamano07ea91d2006-05-09 18:28:41 -0700102 unsigned fixed:1;
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700103#define GREP_BINARY_DEFAULT 0
104#define GREP_BINARY_NOMATCH 1
105#define GREP_BINARY_TEXT 2
106 unsigned binary:2;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700107 int regflags;
108 unsigned pre_context;
109 unsigned post_context;
110};
111
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700112static void add_pattern(struct grep_opt *opt, const char *pat,
113 const char *origin, int no)
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700114{
115 struct grep_pat *p = xcalloc(1, sizeof(*p));
116 p->pattern = pat;
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700117 p->origin = origin;
118 p->no = no;
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700119 *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];
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700131 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;
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700139 regerror(err, &p->regexp, errbuf, 1024);
140 regfree(&p->regexp);
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700141 die("%s'%s': %s", where, p->pattern, errbuf);
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700142 }
143 }
144}
145
Junio C Hamano5010cb52006-04-30 23:28:15 -0700146static 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
Junio C Hamano7839a252006-05-02 15:40:49 -0700157static int word_char(char ch)
158{
159 return isalnum(ch) || ch == '_';
160}
161
Junio C Hamano5010cb52006-04-30 23:28:15 -0700162static 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);
Junio C Hamanoa24f1e22006-05-02 01:28:02 -0700168 printf("%.*s\n", (int)(eol-bol), bol);
Junio C Hamano5010cb52006-04-30 23:28:15 -0700169}
170
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700171/*
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
Junio C Hamano07ea91d2006-05-09 18:28:41 -0700184static 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
Junio C Hamano5010cb52006-04-30 23:28:15 -0700198static 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;
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700210 int binary_match_only = 0;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700211 const char *hunk_mark = "";
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700212 unsigned count = 0;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700213
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700214 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
Junio C Hamano5010cb52006-04-30 23:28:15 -0700227 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;
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700235 int hit = 0;
236 struct grep_pat *p;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700237
238 eol = end_of_line(bol, &left);
239 ch = *eol;
240 *eol = 0;
241
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700242 for (p = opt->pattern_list; p; p = p->next) {
Junio C Hamano07ea91d2006-05-09 18:28:41 -0700243 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 }
Junio C Hamano7839a252006-05-02 15:40:49 -0700251
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]))
Junio C Hamano02ab1c42006-05-09 18:27:56 -0700265 hit = 0;
266 if (pmatch[0].rm_eo != (eol-bol) &&
Junio C Hamano7839a252006-05-02 15:40:49 -0700267 word_char(bol[pmatch[0].rm_eo]))
Junio C Hamano02ab1c42006-05-09 18:27:56 -0700268 hit = 0;
Junio C Hamano7839a252006-05-02 15:40:49 -0700269 }
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700270 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 */
Junio C Hamano5010cb52006-04-30 23:28:15 -0700277 if (opt->invert)
278 hit = !hit;
Junio C Hamanoe23d2d62006-05-03 21:46:29 -0700279 if (opt->unmatch_name_only) {
280 if (hit)
281 return 0;
282 goto next_line;
283 }
Junio C Hamano5010cb52006-04-30 23:28:15 -0700284 if (hit) {
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700285 count++;
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700286 if (binary_match_only) {
287 printf("Binary file %s matches\n", name);
288 return 1;
289 }
Junio C Hamanodf0e7aa2006-05-01 12:39:21 -0700290 if (opt->name_only) {
291 printf("%s\n", name);
292 return 1;
293 }
Junio C Hamano5010cb52006-04-30 23:28:15 -0700294 /* Hit at this line. If we haven't shown the
295 * pre-context lines, we would need to show them.
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700296 * When asked to do "count", this still show
297 * the context which is nonsense, but the user
298 * deserves to get that ;-).
Junio C Hamano5010cb52006-04-30 23:28:15 -0700299 */
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);
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700320 if (!opt->count)
321 show_line(opt, bol, eol, name, lno, ':');
Junio C Hamano5010cb52006-04-30 23:28:15 -0700322 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 }
Junio C Hamanoe23d2d62006-05-03 21:46:29 -0700340
341 next_line:
Junio C Hamano5010cb52006-04-30 23:28:15 -0700342 *eol = ch;
343 bol = eol + 1;
Junio C Hamano7ed36f52006-05-03 21:03:25 -0700344 if (!left)
345 break;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700346 left--;
347 lno++;
348 }
Junio C Hamanoe23d2d62006-05-03 21:46:29 -0700349
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
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700356 /* 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);
Junio C Hamano5010cb52006-04-30 23:28:15 -0700363 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
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700413static 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
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700440#define ARGBUF 4096
441#define push_arg(a) do { \
442 if (nr < MAXARGS) argv[nr++] = (a); \
443 else die("maximum number of args exceeded"); \
444 } while (0)
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700445
446static int external_grep(struct grep_opt *opt, const char **paths, int cached)
447{
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700448 int i, nr, argc, hit, len;
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700449 const char *argv[MAXARGS+1];
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700450 char randarg[ARGBUF];
451 char *argptr = randarg;
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700452 struct grep_pat *p;
453
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700454 len = nr = 0;
455 push_arg("grep");
456 push_arg("-H");
457 if (opt->fixed)
Linus Torvaldsf6647512006-05-15 17:54:01 -0700458 push_arg("-F");
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700459 if (opt->linenum)
460 push_arg("-n");
461 if (opt->regflags & REG_EXTENDED)
462 push_arg("-E");
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700463 if (opt->word_regexp)
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700464 push_arg("-w");
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700465 if (opt->name_only)
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700466 push_arg("-l");
467 if (opt->unmatch_name_only)
468 push_arg("-L");
469 if (opt->count)
470 push_arg("-c");
471 if (opt->post_context || opt->pre_context) {
472 if (opt->post_context != opt->pre_context) {
473 if (opt->pre_context) {
474 push_arg("-B");
475 len += snprintf(argptr, sizeof(randarg)-len,
476 "%u", opt->pre_context);
477 if (sizeof(randarg) <= len)
478 die("maximum length of args exceeded");
479 push_arg(argptr);
480 argptr += len;
481 }
482 if (opt->post_context) {
483 push_arg("-A");
484 len += snprintf(argptr, sizeof(randarg)-len,
485 "%u", opt->post_context);
486 if (sizeof(randarg) <= len)
487 die("maximum length of args exceeded");
488 push_arg(argptr);
489 argptr += len;
490 }
491 }
492 else {
493 push_arg("-C");
494 len += snprintf(argptr, sizeof(randarg)-len,
495 "%u", opt->post_context);
496 if (sizeof(randarg) <= len)
497 die("maximum length of args exceeded");
498 push_arg(argptr);
499 argptr += len;
500 }
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700501 }
Junio C Hamanoffa0a7a2006-05-15 13:28:01 -0700502 for (p = opt->pattern_list; p; p = p->next) {
503 push_arg("-e");
504 push_arg(p->pattern);
505 }
506 push_arg("--");
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700507
508 hit = 0;
509 argc = nr;
510 for (i = 0; i < active_nr; i++) {
511 struct cache_entry *ce = active_cache[i];
512 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
513 continue;
514 if (!pathspec_matches(paths, ce->name))
515 continue;
516 argv[argc++] = ce->name;
517 if (argc < MAXARGS)
518 continue;
519 hit += exec_grep(argc, argv);
520 argc = nr;
521 }
522 if (argc > nr)
523 hit += exec_grep(argc, argv);
524 return 0;
525}
526
Junio C Hamano13626712006-05-01 15:58:29 -0700527static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
Junio C Hamano5010cb52006-04-30 23:28:15 -0700528{
529 int hit = 0;
530 int nr;
531 read_cache();
532
Linus Torvalds1e2398d2006-05-14 20:49:15 -0700533#ifdef __unix__
534 /*
535 * Use the external "grep" command for the case where
536 * we grep through the checked-out files. It tends to
537 * be a lot more optimized
538 */
539 if (!cached) {
540 hit = external_grep(opt, paths, cached);
541 if (hit >= 0)
542 return hit;
543 }
544#endif
545
Junio C Hamano5010cb52006-04-30 23:28:15 -0700546 for (nr = 0; nr < active_nr; nr++) {
547 struct cache_entry *ce = active_cache[nr];
548 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
549 continue;
Junio C Hamano13626712006-05-01 15:58:29 -0700550 if (!pathspec_matches(paths, ce->name))
Junio C Hamano5010cb52006-04-30 23:28:15 -0700551 continue;
552 if (cached)
553 hit |= grep_sha1(opt, ce->sha1, ce->name);
554 else
555 hit |= grep_file(opt, ce->name);
556 }
557 return hit;
558}
559
Junio C Hamano13626712006-05-01 15:58:29 -0700560static int grep_tree(struct grep_opt *opt, const char **paths,
Junio C Hamano5010cb52006-04-30 23:28:15 -0700561 struct tree_desc *tree,
562 const char *tree_name, const char *base)
563{
564 unsigned mode;
565 int len;
566 int hit = 0;
567 const char *path;
568 const unsigned char *sha1;
Junio C Hamanoe0eb8892006-05-01 12:27:56 -0700569 char *down;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700570 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
571
572 if (tree_name[0]) {
573 int offset = sprintf(path_buf, "%s:", tree_name);
Junio C Hamanoe0eb8892006-05-01 12:27:56 -0700574 down = path_buf + offset;
575 strcat(down, base);
Junio C Hamano5010cb52006-04-30 23:28:15 -0700576 }
577 else {
Junio C Hamanoe0eb8892006-05-01 12:27:56 -0700578 down = path_buf;
579 strcpy(down, base);
Junio C Hamano5010cb52006-04-30 23:28:15 -0700580 }
581 len = strlen(path_buf);
582
583 while (tree->size) {
584 int pathlen;
585 sha1 = tree_entry_extract(tree, &path, &mode);
586 pathlen = strlen(path);
587 strcpy(path_buf + len, path);
588
Junio C Hamanoe0eb8892006-05-01 12:27:56 -0700589 if (S_ISDIR(mode))
590 /* Match "abc/" against pathspec to
591 * decide if we want to descend into "abc"
592 * directory.
593 */
594 strcpy(path_buf + len + pathlen, "/");
595
Junio C Hamano13626712006-05-01 15:58:29 -0700596 if (!pathspec_matches(paths, down))
Junio C Hamano5010cb52006-04-30 23:28:15 -0700597 ;
598 else if (S_ISREG(mode))
599 hit |= grep_sha1(opt, sha1, path_buf);
600 else if (S_ISDIR(mode)) {
601 char type[20];
602 struct tree_desc sub;
603 void *data;
604 data = read_sha1_file(sha1, type, &sub.size);
605 if (!data)
606 die("unable to read tree (%s)",
607 sha1_to_hex(sha1));
Junio C Hamano5010cb52006-04-30 23:28:15 -0700608 sub.buf = data;
Junio C Hamano13626712006-05-01 15:58:29 -0700609 hit |= grep_tree(opt, paths, &sub, tree_name, down);
Junio C Hamano5010cb52006-04-30 23:28:15 -0700610 free(data);
611 }
612 update_tree_entry(tree);
613 }
614 return hit;
615}
616
Junio C Hamano13626712006-05-01 15:58:29 -0700617static int grep_object(struct grep_opt *opt, const char **paths,
Junio C Hamano5010cb52006-04-30 23:28:15 -0700618 struct object *obj, const char *name)
619{
620 if (!strcmp(obj->type, blob_type))
621 return grep_sha1(opt, obj->sha1, name);
622 if (!strcmp(obj->type, commit_type) ||
623 !strcmp(obj->type, tree_type)) {
624 struct tree_desc tree;
625 void *data;
626 int hit;
627 data = read_object_with_reference(obj->sha1, tree_type,
628 &tree.size, NULL);
629 if (!data)
630 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
631 tree.buf = data;
Junio C Hamano13626712006-05-01 15:58:29 -0700632 hit = grep_tree(opt, paths, &tree, name, "");
Junio C Hamano5010cb52006-04-30 23:28:15 -0700633 free(data);
634 return hit;
635 }
636 die("unable to grep from object of type %s", obj->type);
637}
638
639static const char builtin_grep_usage[] =
640"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
641
642int cmd_grep(int argc, const char **argv, char **envp)
643{
Junio C Hamano5010cb52006-04-30 23:28:15 -0700644 int hit = 0;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700645 int cached = 0;
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700646 int seen_dashdash = 0;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700647 struct grep_opt opt;
Junio C Hamano13626712006-05-01 15:58:29 -0700648 struct object_list *list, **tail, *object_list = NULL;
649 const char *prefix = setup_git_directory();
650 const char **paths = NULL;
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700651 int i;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700652
653 memset(&opt, 0, sizeof(opt));
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700654 opt.pattern_tail = &opt.pattern_list;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700655 opt.regflags = REG_NEWLINE;
656
657 /*
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700658 * If there is no -- then the paths must exist in the working
659 * tree. If there is no explicit pattern specified with -e or
660 * -f, we take the first unrecognized non option to be the
661 * pattern, but then what follows it must be zero or more
662 * valid refs up to the -- (if exists), and then existing
663 * paths. If there is an explicit pattern, then the first
664 * unrecocnized non option is the beginning of the refs list
665 * that continues up to the -- (if exists), and then paths.
Junio C Hamano5010cb52006-04-30 23:28:15 -0700666 */
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700667
668 tail = &object_list;
Junio C Hamano13626712006-05-01 15:58:29 -0700669 while (1 < argc) {
670 const char *arg = argv[1];
671 argc--; argv++;
672 if (!strcmp("--cached", arg)) {
673 cached = 1;
674 continue;
Junio C Hamano5010cb52006-04-30 23:28:15 -0700675 }
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700676 if (!strcmp("-a", arg) ||
677 !strcmp("--text", arg)) {
678 opt.binary = GREP_BINARY_TEXT;
679 continue;
680 }
Junio C Hamano13626712006-05-01 15:58:29 -0700681 if (!strcmp("-i", arg) ||
682 !strcmp("--ignore-case", arg)) {
683 opt.regflags |= REG_ICASE;
684 continue;
685 }
Junio C Hamanob8d0f5a2006-05-03 21:05:29 -0700686 if (!strcmp("-I", arg)) {
687 opt.binary = GREP_BINARY_NOMATCH;
688 continue;
689 }
Junio C Hamano13626712006-05-01 15:58:29 -0700690 if (!strcmp("-v", arg) ||
691 !strcmp("--invert-match", arg)) {
692 opt.invert = 1;
693 continue;
694 }
695 if (!strcmp("-E", arg) ||
696 !strcmp("--extended-regexp", arg)) {
697 opt.regflags |= REG_EXTENDED;
698 continue;
699 }
Junio C Hamano07ea91d2006-05-09 18:28:41 -0700700 if (!strcmp("-F", arg) ||
701 !strcmp("--fixed-strings", arg)) {
702 opt.fixed = 1;
703 continue;
704 }
Junio C Hamano13626712006-05-01 15:58:29 -0700705 if (!strcmp("-G", arg) ||
706 !strcmp("--basic-regexp", arg)) {
707 opt.regflags &= ~REG_EXTENDED;
708 continue;
709 }
710 if (!strcmp("-n", arg)) {
711 opt.linenum = 1;
712 continue;
713 }
714 if (!strcmp("-H", arg)) {
715 /* We always show the pathname, so this
716 * is a noop.
717 */
718 continue;
719 }
720 if (!strcmp("-l", arg) ||
721 !strcmp("--files-with-matches", arg)) {
722 opt.name_only = 1;
723 continue;
724 }
Junio C Hamanoe23d2d62006-05-03 21:46:29 -0700725 if (!strcmp("-L", arg) ||
726 !strcmp("--files-without-match", arg)) {
727 opt.unmatch_name_only = 1;
728 continue;
729 }
Junio C Hamano2c866cf2006-05-02 15:40:49 -0700730 if (!strcmp("-c", arg) ||
731 !strcmp("--count", arg)) {
732 opt.count = 1;
733 continue;
734 }
Junio C Hamano7839a252006-05-02 15:40:49 -0700735 if (!strcmp("-w", arg) ||
736 !strcmp("--word-regexp", arg)) {
737 opt.word_regexp = 1;
738 continue;
739 }
Junio C Hamanof462ebb2006-05-02 15:17:05 -0700740 if (!strncmp("-A", arg, 2) ||
741 !strncmp("-B", arg, 2) ||
742 !strncmp("-C", arg, 2) ||
743 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
Junio C Hamano13626712006-05-01 15:58:29 -0700744 unsigned num;
Junio C Hamanof462ebb2006-05-02 15:17:05 -0700745 const char *scan;
746 switch (arg[1]) {
747 case 'A': case 'B': case 'C':
748 if (!arg[2]) {
749 if (argc <= 1)
750 usage(builtin_grep_usage);
751 scan = *++argv;
752 argc--;
753 }
754 else
755 scan = arg + 2;
756 break;
757 default:
758 scan = arg + 1;
759 break;
760 }
761 if (sscanf(scan, "%u", &num) != 1)
Junio C Hamano13626712006-05-01 15:58:29 -0700762 usage(builtin_grep_usage);
Junio C Hamano13626712006-05-01 15:58:29 -0700763 switch (arg[1]) {
764 case 'A':
765 opt.post_context = num;
766 break;
Junio C Hamanof462ebb2006-05-02 15:17:05 -0700767 default:
Junio C Hamano13626712006-05-01 15:58:29 -0700768 case 'C':
769 opt.post_context = num;
770 case 'B':
771 opt.pre_context = num;
772 break;
773 }
774 continue;
775 }
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700776 if (!strcmp("-f", arg)) {
777 FILE *patterns;
778 int lno = 0;
779 char buf[1024];
780 if (argc <= 1)
781 usage(builtin_grep_usage);
782 patterns = fopen(argv[1], "r");
783 if (!patterns)
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700784 die("'%s': %s", argv[1], strerror(errno));
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700785 while (fgets(buf, sizeof(buf), patterns)) {
786 int len = strlen(buf);
787 if (buf[len-1] == '\n')
788 buf[len-1] = 0;
789 /* ignore empty line like grep does */
790 if (!buf[0])
791 continue;
792 add_pattern(&opt, strdup(buf), argv[1], ++lno);
793 }
794 fclose(patterns);
795 argv++;
796 argc--;
797 continue;
798 }
Junio C Hamano13626712006-05-01 15:58:29 -0700799 if (!strcmp("-e", arg)) {
800 if (1 < argc) {
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700801 add_pattern(&opt, argv[1], "-e option", 0);
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700802 argv++;
Junio C Hamano13626712006-05-01 15:58:29 -0700803 argc--;
804 continue;
805 }
806 usage(builtin_grep_usage);
807 }
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700808 if (!strcmp("--", arg))
809 break;
810 if (*arg == '-')
Junio C Hamano13626712006-05-01 15:58:29 -0700811 usage(builtin_grep_usage);
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700812
813 /* First unrecognized non-option token */
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700814 if (!opt.pattern_list) {
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700815 add_pattern(&opt, arg, "command line", 0);
Junio C Hamano13626712006-05-01 15:58:29 -0700816 break;
817 }
818 else {
819 /* We are looking at the first path or rev;
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700820 * it is found at argv[1] after leaving the
Junio C Hamano13626712006-05-01 15:58:29 -0700821 * loop.
822 */
823 argc++; argv--;
824 break;
825 }
Junio C Hamano5010cb52006-04-30 23:28:15 -0700826 }
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700827
Junio C Hamanof9b9faf2006-05-02 15:40:49 -0700828 if (!opt.pattern_list)
Junio C Hamano5010cb52006-04-30 23:28:15 -0700829 die("no pattern given.");
Junio C Hamano07ea91d2006-05-09 18:28:41 -0700830 if ((opt.regflags != REG_NEWLINE) && opt.fixed)
831 die("cannot mix --fixed-strings and regexp");
832 if (!opt.fixed)
833 compile_patterns(&opt);
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700834
835 /* Check revs and then paths */
836 for (i = 1; i < argc; i++) {
837 const char *arg = argv[i];
Junio C Hamano13626712006-05-01 15:58:29 -0700838 unsigned char sha1[20];
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700839 /* Is it a rev? */
840 if (!get_sha1(arg, sha1)) {
841 struct object *object = parse_object(sha1);
842 struct object_list *elem;
843 if (!object)
844 die("bad object %s", arg);
845 elem = object_list_insert(object, tail);
846 elem->name = arg;
847 tail = &elem->next;
848 continue;
849 }
850 if (!strcmp(arg, "--")) {
851 i++;
852 seen_dashdash = 1;
853 }
854 break;
Junio C Hamano13626712006-05-01 15:58:29 -0700855 }
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700856
857 /* The rest are paths */
858 if (!seen_dashdash) {
859 int j;
Junio C Hamanoc39c4f42006-05-09 18:15:21 -0700860 for (j = i; j < argc; j++)
Junio C Hamano5acd64e2006-05-08 23:55:47 -0700861 verify_filename(prefix, argv[j]);
862 }
863
864 if (i < argc)
865 paths = get_pathspec(prefix, argv + i);
Junio C Hamano13626712006-05-01 15:58:29 -0700866 else if (prefix) {
867 paths = xcalloc(2, sizeof(const char *));
868 paths[0] = prefix;
869 paths[1] = NULL;
870 }
Junio C Hamano5010cb52006-04-30 23:28:15 -0700871
Junio C Hamano13626712006-05-01 15:58:29 -0700872 if (!object_list)
873 return !grep_cache(&opt, paths, cached);
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700874
Junio C Hamano5010cb52006-04-30 23:28:15 -0700875 if (cached)
Junio C Hamanoaa8c79a2006-05-08 13:28:27 -0700876 die("both --cached and trees are given.");
Junio C Hamano5010cb52006-04-30 23:28:15 -0700877
Junio C Hamano13626712006-05-01 15:58:29 -0700878 for (list = object_list; list; list = list->next) {
Junio C Hamano5010cb52006-04-30 23:28:15 -0700879 struct object *real_obj;
880 real_obj = deref_tag(list->item, NULL, 0);
Junio C Hamano13626712006-05-01 15:58:29 -0700881 if (grep_object(&opt, paths, real_obj, list->name))
Junio C Hamano5010cb52006-04-30 23:28:15 -0700882 hit = 1;
883 }
884 return !hit;
885}