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