]> git.ipfire.org Git - thirdparty/git.git/blame - builtin-grep.c
builtin-grep: terminate correctly at EOF
[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
JH
12#include "builtin.h"
13#include <regex.h>
e0eb889f 14#include <fnmatch.h>
5010cb5f 15
e0eb889f
JH
16/*
17 * git grep pathspecs are somewhat different from diff-tree pathspecs;
18 * pathname wildcards are allowed.
19 */
1362671f 20static int pathspec_matches(const char **paths, const char *name)
5010cb5f 21{
e0eb889f 22 int namelen, i;
1362671f 23 if (!paths || !*paths)
5010cb5f
JH
24 return 1;
25 namelen = strlen(name);
1362671f
JH
26 for (i = 0; paths[i]; i++) {
27 const char *match = paths[i];
28 int matchlen = strlen(match);
1e3d90e0 29 const char *cp, *meta;
e0eb889f
JH
30
31 if ((matchlen <= namelen) &&
32 !strncmp(name, match, matchlen) &&
33 (match[matchlen-1] == '/' ||
34 name[matchlen] == '\0' || name[matchlen] == '/'))
35 return 1;
36 if (!fnmatch(match, name, 0))
37 return 1;
38 if (name[namelen-1] != '/')
5010cb5f 39 continue;
e0eb889f 40
1e3d90e0 41 /* We are being asked if the directory ("name") is worth
e0eb889f
JH
42 * descending into.
43 *
44 * Find the longest leading directory name that does
45 * not have metacharacter in the pathspec; the name
46 * we are looking at must overlap with that directory.
5010cb5f 47 */
1e3d90e0 48 for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
e0eb889f 49 char ch = *cp;
1e3d90e0
JH
50 if (ch == '*' || ch == '[' || ch == '?') {
51 meta = cp;
5010cb5f 52 break;
1e3d90e0 53 }
e0eb889f 54 }
1e3d90e0
JH
55 if (!meta)
56 meta = cp; /* fully literal */
57
58 if (namelen <= meta - match) {
e0eb889f
JH
59 /* Looking at "Documentation/" and
60 * the pattern says "Documentation/howto/", or
1e3d90e0
JH
61 * "Documentation/diff*.txt". The name we
62 * have should match prefix.
e0eb889f
JH
63 */
64 if (!memcmp(match, name, namelen))
65 return 1;
1e3d90e0 66 continue;
e0eb889f 67 }
1e3d90e0
JH
68
69 if (meta - match < namelen) {
e0eb889f 70 /* Looking at "Documentation/howto/" and
1e3d90e0
JH
71 * the pattern says "Documentation/h*";
72 * match up to "Do.../h"; this avoids descending
73 * into "Documentation/technical/".
e0eb889f 74 */
1e3d90e0 75 if (!memcmp(match, name, meta - match))
e0eb889f 76 return 1;
1e3d90e0 77 continue;
e0eb889f 78 }
5010cb5f
JH
79 }
80 return 0;
81}
82
f9b9faf6
JH
83struct grep_pat {
84 struct grep_pat *next;
5010cb5f
JH
85 const char *pattern;
86 regex_t regexp;
f9b9faf6
JH
87};
88
89struct grep_opt {
90 struct grep_pat *pattern_list;
91 struct grep_pat **pattern_tail;
92 regex_t regexp;
5010cb5f
JH
93 unsigned linenum:1;
94 unsigned invert:1;
df0e7aa8 95 unsigned name_only:1;
2c866cf1 96 unsigned count:1;
7839a25e 97 unsigned word_regexp:1;
5010cb5f
JH
98 int regflags;
99 unsigned pre_context;
100 unsigned post_context;
101};
102
f9b9faf6
JH
103static void add_pattern(struct grep_opt *opt, const char *pat)
104{
105 struct grep_pat *p = xcalloc(1, sizeof(*p));
106 p->pattern = pat;
107 *opt->pattern_tail = p;
108 opt->pattern_tail = &p->next;
109 p->next = NULL;
110}
111
112static void compile_patterns(struct grep_opt *opt)
113{
114 struct grep_pat *p;
115 for (p = opt->pattern_list; p; p = p->next) {
116 int err = regcomp(&p->regexp, p->pattern, opt->regflags);
117 if (err) {
118 char errbuf[1024];
119 regerror(err, &p->regexp, errbuf, 1024);
120 regfree(&p->regexp);
121 die("'%s': %s", p->pattern, errbuf);
122 }
123 }
124}
125
5010cb5f
JH
126static char *end_of_line(char *cp, unsigned long *left)
127{
128 unsigned long l = *left;
129 while (l && *cp != '\n') {
130 l--;
131 cp++;
132 }
133 *left = l;
134 return cp;
135}
136
7839a25e
JH
137static int word_char(char ch)
138{
139 return isalnum(ch) || ch == '_';
140}
141
5010cb5f
JH
142static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
143 const char *name, unsigned lno, char sign)
144{
145 printf("%s%c", name, sign);
146 if (opt->linenum)
147 printf("%d%c", lno, sign);
a24f1e25 148 printf("%.*s\n", (int)(eol-bol), bol);
5010cb5f
JH
149}
150
151static int grep_buffer(struct grep_opt *opt, const char *name,
152 char *buf, unsigned long size)
153{
154 char *bol = buf;
155 unsigned long left = size;
156 unsigned lno = 1;
157 struct pre_context_line {
158 char *bol;
159 char *eol;
160 } *prev = NULL, *pcl;
161 unsigned last_hit = 0;
162 unsigned last_shown = 0;
163 const char *hunk_mark = "";
2c866cf1 164 unsigned count = 0;
5010cb5f
JH
165
166 if (opt->pre_context)
167 prev = xcalloc(opt->pre_context, sizeof(*prev));
168 if (opt->pre_context || opt->post_context)
169 hunk_mark = "--\n";
170
171 while (left) {
172 regmatch_t pmatch[10];
173 char *eol, ch;
f9b9faf6
JH
174 int hit = 0;
175 struct grep_pat *p;
5010cb5f
JH
176
177 eol = end_of_line(bol, &left);
178 ch = *eol;
179 *eol = 0;
180
f9b9faf6
JH
181 for (p = opt->pattern_list; p; p = p->next) {
182 regex_t *exp = &p->regexp;
183 hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
184 pmatch, 0);
7839a25e
JH
185
186 if (hit && opt->word_regexp) {
187 /* Match beginning must be either
188 * beginning of the line, or at word
189 * boundary (i.e. the last char must
190 * not be alnum or underscore).
191 */
192 if ((pmatch[0].rm_so < 0) ||
193 (eol - bol) <= pmatch[0].rm_so ||
194 (pmatch[0].rm_eo < 0) ||
195 (eol - bol) < pmatch[0].rm_eo)
196 die("regexp returned nonsense");
197 if (pmatch[0].rm_so != 0 &&
198 word_char(bol[pmatch[0].rm_so-1]))
199 continue; /* not a word boundary */
200 if ((eol-bol) < pmatch[0].rm_eo &&
201 word_char(bol[pmatch[0].rm_eo]))
202 continue; /* not a word boundary */
203 }
f9b9faf6
JH
204 if (hit)
205 break;
206 }
207 /* "grep -v -e foo -e bla" should list lines
208 * that do not have either, so inversion should
209 * be done outside.
210 */
5010cb5f
JH
211 if (opt->invert)
212 hit = !hit;
213 if (hit) {
2c866cf1 214 count++;
df0e7aa8
JH
215 if (opt->name_only) {
216 printf("%s\n", name);
217 return 1;
218 }
5010cb5f
JH
219 /* Hit at this line. If we haven't shown the
220 * pre-context lines, we would need to show them.
2c866cf1
JH
221 * When asked to do "count", this still show
222 * the context which is nonsense, but the user
223 * deserves to get that ;-).
5010cb5f
JH
224 */
225 if (opt->pre_context) {
226 unsigned from;
227 if (opt->pre_context < lno)
228 from = lno - opt->pre_context;
229 else
230 from = 1;
231 if (from <= last_shown)
232 from = last_shown + 1;
233 if (last_shown && from != last_shown + 1)
234 printf(hunk_mark);
235 while (from < lno) {
236 pcl = &prev[lno-from-1];
237 show_line(opt, pcl->bol, pcl->eol,
238 name, from, '-');
239 from++;
240 }
241 last_shown = lno-1;
242 }
243 if (last_shown && lno != last_shown + 1)
244 printf(hunk_mark);
2c866cf1
JH
245 if (!opt->count)
246 show_line(opt, bol, eol, name, lno, ':');
5010cb5f
JH
247 last_shown = last_hit = lno;
248 }
249 else if (last_hit &&
250 lno <= last_hit + opt->post_context) {
251 /* If the last hit is within the post context,
252 * we need to show this line.
253 */
254 if (last_shown && lno != last_shown + 1)
255 printf(hunk_mark);
256 show_line(opt, bol, eol, name, lno, '-');
257 last_shown = lno;
258 }
259 if (opt->pre_context) {
260 memmove(prev+1, prev,
261 (opt->pre_context-1) * sizeof(*prev));
262 prev->bol = bol;
263 prev->eol = eol;
264 }
265 *eol = ch;
266 bol = eol + 1;
7ed36f56
JH
267 if (!left)
268 break;
5010cb5f
JH
269 left--;
270 lno++;
271 }
2c866cf1
JH
272 /* NEEDSWORK:
273 * The real "grep -c foo *.c" gives many "bar.c:0" lines,
274 * which feels mostly useless but sometimes useful. Maybe
275 * make it another option? For now suppress them.
276 */
277 if (opt->count && count)
278 printf("%s:%u\n", name, count);
5010cb5f
JH
279 return !!last_hit;
280}
281
282static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
283{
284 unsigned long size;
285 char *data;
286 char type[20];
287 int hit;
288 data = read_sha1_file(sha1, type, &size);
289 if (!data) {
290 error("'%s': unable to read %s", name, sha1_to_hex(sha1));
291 return 0;
292 }
293 hit = grep_buffer(opt, name, data, size);
294 free(data);
295 return hit;
296}
297
298static int grep_file(struct grep_opt *opt, const char *filename)
299{
300 struct stat st;
301 int i;
302 char *data;
303 if (lstat(filename, &st) < 0) {
304 err_ret:
305 if (errno != ENOENT)
306 error("'%s': %s", filename, strerror(errno));
307 return 0;
308 }
309 if (!st.st_size)
310 return 0; /* empty file -- no grep hit */
311 if (!S_ISREG(st.st_mode))
312 return 0;
313 i = open(filename, O_RDONLY);
314 if (i < 0)
315 goto err_ret;
316 data = xmalloc(st.st_size + 1);
317 if (st.st_size != xread(i, data, st.st_size)) {
318 error("'%s': short read %s", filename, strerror(errno));
319 close(i);
320 free(data);
321 return 0;
322 }
323 close(i);
324 i = grep_buffer(opt, filename, data, st.st_size);
325 free(data);
326 return i;
327}
328
1362671f 329static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
5010cb5f
JH
330{
331 int hit = 0;
332 int nr;
333 read_cache();
334
335 for (nr = 0; nr < active_nr; nr++) {
336 struct cache_entry *ce = active_cache[nr];
337 if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
338 continue;
1362671f 339 if (!pathspec_matches(paths, ce->name))
5010cb5f
JH
340 continue;
341 if (cached)
342 hit |= grep_sha1(opt, ce->sha1, ce->name);
343 else
344 hit |= grep_file(opt, ce->name);
345 }
346 return hit;
347}
348
1362671f 349static int grep_tree(struct grep_opt *opt, const char **paths,
5010cb5f
JH
350 struct tree_desc *tree,
351 const char *tree_name, const char *base)
352{
353 unsigned mode;
354 int len;
355 int hit = 0;
356 const char *path;
357 const unsigned char *sha1;
e0eb889f 358 char *down;
5010cb5f
JH
359 char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
360
361 if (tree_name[0]) {
362 int offset = sprintf(path_buf, "%s:", tree_name);
e0eb889f
JH
363 down = path_buf + offset;
364 strcat(down, base);
5010cb5f
JH
365 }
366 else {
e0eb889f
JH
367 down = path_buf;
368 strcpy(down, base);
5010cb5f
JH
369 }
370 len = strlen(path_buf);
371
372 while (tree->size) {
373 int pathlen;
374 sha1 = tree_entry_extract(tree, &path, &mode);
375 pathlen = strlen(path);
376 strcpy(path_buf + len, path);
377
e0eb889f
JH
378 if (S_ISDIR(mode))
379 /* Match "abc/" against pathspec to
380 * decide if we want to descend into "abc"
381 * directory.
382 */
383 strcpy(path_buf + len + pathlen, "/");
384
1362671f 385 if (!pathspec_matches(paths, down))
5010cb5f
JH
386 ;
387 else if (S_ISREG(mode))
388 hit |= grep_sha1(opt, sha1, path_buf);
389 else if (S_ISDIR(mode)) {
390 char type[20];
391 struct tree_desc sub;
392 void *data;
393 data = read_sha1_file(sha1, type, &sub.size);
394 if (!data)
395 die("unable to read tree (%s)",
396 sha1_to_hex(sha1));
5010cb5f 397 sub.buf = data;
1362671f 398 hit |= grep_tree(opt, paths, &sub, tree_name, down);
5010cb5f
JH
399 free(data);
400 }
401 update_tree_entry(tree);
402 }
403 return hit;
404}
405
1362671f 406static int grep_object(struct grep_opt *opt, const char **paths,
5010cb5f
JH
407 struct object *obj, const char *name)
408{
409 if (!strcmp(obj->type, blob_type))
410 return grep_sha1(opt, obj->sha1, name);
411 if (!strcmp(obj->type, commit_type) ||
412 !strcmp(obj->type, tree_type)) {
413 struct tree_desc tree;
414 void *data;
415 int hit;
416 data = read_object_with_reference(obj->sha1, tree_type,
417 &tree.size, NULL);
418 if (!data)
419 die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
420 tree.buf = data;
1362671f 421 hit = grep_tree(opt, paths, &tree, name, "");
5010cb5f
JH
422 free(data);
423 return hit;
424 }
425 die("unable to grep from object of type %s", obj->type);
426}
427
428static const char builtin_grep_usage[] =
429"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
430
431int cmd_grep(int argc, const char **argv, char **envp)
432{
5010cb5f 433 int hit = 0;
1362671f 434 int no_more_flags = 0;
5010cb5f
JH
435 int seen_noncommit = 0;
436 int cached = 0;
437 struct grep_opt opt;
1362671f
JH
438 struct object_list *list, **tail, *object_list = NULL;
439 const char *prefix = setup_git_directory();
440 const char **paths = NULL;
5010cb5f
JH
441
442 memset(&opt, 0, sizeof(opt));
f9b9faf6 443 opt.pattern_tail = &opt.pattern_list;
5010cb5f
JH
444 opt.regflags = REG_NEWLINE;
445
446 /*
1362671f 447 * No point using rev_info, really.
5010cb5f 448 */
1362671f
JH
449 while (1 < argc) {
450 const char *arg = argv[1];
451 argc--; argv++;
452 if (!strcmp("--cached", arg)) {
453 cached = 1;
454 continue;
455 }
456 if (!strcmp("-i", arg) ||
457 !strcmp("--ignore-case", arg)) {
458 opt.regflags |= REG_ICASE;
459 continue;
460 }
461 if (!strcmp("-v", arg) ||
462 !strcmp("--invert-match", arg)) {
463 opt.invert = 1;
464 continue;
465 }
466 if (!strcmp("-E", arg) ||
467 !strcmp("--extended-regexp", arg)) {
468 opt.regflags |= REG_EXTENDED;
469 continue;
470 }
471 if (!strcmp("-G", arg) ||
472 !strcmp("--basic-regexp", arg)) {
473 opt.regflags &= ~REG_EXTENDED;
474 continue;
475 }
476 if (!strcmp("-n", arg)) {
477 opt.linenum = 1;
478 continue;
479 }
480 if (!strcmp("-H", arg)) {
481 /* We always show the pathname, so this
482 * is a noop.
483 */
484 continue;
485 }
486 if (!strcmp("-l", arg) ||
487 !strcmp("--files-with-matches", arg)) {
488 opt.name_only = 1;
489 continue;
490 }
2c866cf1
JH
491 if (!strcmp("-c", arg) ||
492 !strcmp("--count", arg)) {
493 opt.count = 1;
494 continue;
495 }
7839a25e
JH
496 if (!strcmp("-w", arg) ||
497 !strcmp("--word-regexp", arg)) {
498 opt.word_regexp = 1;
499 continue;
500 }
f462ebb4
JH
501 if (!strncmp("-A", arg, 2) ||
502 !strncmp("-B", arg, 2) ||
503 !strncmp("-C", arg, 2) ||
504 (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1362671f 505 unsigned num;
f462ebb4
JH
506 const char *scan;
507 switch (arg[1]) {
508 case 'A': case 'B': case 'C':
509 if (!arg[2]) {
510 if (argc <= 1)
511 usage(builtin_grep_usage);
512 scan = *++argv;
513 argc--;
514 }
515 else
516 scan = arg + 2;
517 break;
518 default:
519 scan = arg + 1;
520 break;
521 }
522 if (sscanf(scan, "%u", &num) != 1)
5010cb5f 523 usage(builtin_grep_usage);
1362671f
JH
524 switch (arg[1]) {
525 case 'A':
526 opt.post_context = num;
527 break;
f462ebb4 528 default:
1362671f
JH
529 case 'C':
530 opt.post_context = num;
531 case 'B':
532 opt.pre_context = num;
533 break;
5010cb5f 534 }
1362671f
JH
535 continue;
536 }
537 if (!strcmp("-e", arg)) {
538 if (1 < argc) {
f9b9faf6
JH
539 add_pattern(&opt, argv[1]);
540 argv++;
1362671f 541 argc--;
5010cb5f
JH
542 continue;
543 }
1362671f
JH
544 usage(builtin_grep_usage);
545 }
546 if (!strcmp("--", arg)) {
547 no_more_flags = 1;
548 continue;
549 }
550 /* Either unrecognized option or a single pattern */
551 if (!no_more_flags && *arg == '-')
552 usage(builtin_grep_usage);
f9b9faf6
JH
553 if (!opt.pattern_list) {
554 add_pattern(&opt, arg);
1362671f
JH
555 break;
556 }
557 else {
558 /* We are looking at the first path or rev;
559 * it is found at argv[0] after leaving the
560 * loop.
561 */
562 argc++; argv--;
563 break;
5010cb5f 564 }
5010cb5f 565 }
f9b9faf6 566 if (!opt.pattern_list)
5010cb5f 567 die("no pattern given.");
f9b9faf6 568 compile_patterns(&opt);
1362671f
JH
569 tail = &object_list;
570 while (1 < argc) {
571 struct object *object;
572 struct object_list *elem;
573 const char *arg = argv[1];
574 unsigned char sha1[20];
575 if (get_sha1(arg, sha1) < 0)
576 break;
577 object = parse_object(sha1);
578 if (!object)
579 die("bad object %s", arg);
580 elem = object_list_insert(object, tail);
581 elem->name = arg;
582 tail = &elem->next;
583 argc--; argv++;
584 }
585 if (1 < argc)
586 paths = get_pathspec(prefix, argv + 1);
587 else if (prefix) {
588 paths = xcalloc(2, sizeof(const char *));
589 paths[0] = prefix;
590 paths[1] = NULL;
591 }
5010cb5f 592
1362671f
JH
593 if (!object_list)
594 return !grep_cache(&opt, paths, cached);
5010cb5f
JH
595 /*
596 * Do not walk "grep -e foo master next pu -- Documentation/"
597 * but do walk "grep -e foo master..next -- Documentation/".
598 * Ranged request mixed with a blob or tree object, like
599 * "grep -e foo v1.0.0:Documentation/ master..next"
600 * so detect that and complain.
601 */
1362671f 602 for (list = object_list; list; list = list->next) {
5010cb5f 603 struct object *real_obj;
5010cb5f
JH
604 real_obj = deref_tag(list->item, NULL, 0);
605 if (strcmp(real_obj->type, commit_type))
606 seen_noncommit = 1;
607 }
5010cb5f
JH
608 if (cached)
609 die("both --cached and revisions given.");
610
1362671f 611 for (list = object_list; list; list = list->next) {
5010cb5f
JH
612 struct object *real_obj;
613 real_obj = deref_tag(list->item, NULL, 0);
1362671f 614 if (grep_object(&opt, paths, real_obj, list->name))
5010cb5f
JH
615 hit = 1;
616 }
617 return !hit;
618}