]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/grep.c
Merge branch 'ss/pull-v-recurse-fix'
[thirdparty/git.git] / builtin / grep.c
1 /*
2 * Builtin "git grep"
3 *
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "cache.h"
7 #include "repository.h"
8 #include "config.h"
9 #include "blob.h"
10 #include "tree.h"
11 #include "commit.h"
12 #include "tag.h"
13 #include "tree-walk.h"
14 #include "builtin.h"
15 #include "parse-options.h"
16 #include "string-list.h"
17 #include "run-command.h"
18 #include "userdiff.h"
19 #include "grep.h"
20 #include "quote.h"
21 #include "dir.h"
22 #include "pathspec.h"
23 #include "submodule.h"
24 #include "submodule-config.h"
25 #include "object-store.h"
26 #include "packfile.h"
27
28 static const char *grep_prefix;
29
30 static char const * const grep_usage[] = {
31 N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
32 NULL
33 };
34
35 static int recurse_submodules;
36
37 static int num_threads;
38
39 static pthread_t *threads;
40
41 /* We use one producer thread and THREADS consumer
42 * threads. The producer adds struct work_items to 'todo' and the
43 * consumers pick work items from the same array.
44 */
45 struct work_item {
46 struct grep_source source;
47 char done;
48 struct strbuf out;
49 };
50
51 /* In the range [todo_done, todo_start) in 'todo' we have work_items
52 * that have been or are processed by a consumer thread. We haven't
53 * written the result for these to stdout yet.
54 *
55 * The work_items in [todo_start, todo_end) are waiting to be picked
56 * up by a consumer thread.
57 *
58 * The ranges are modulo TODO_SIZE.
59 */
60 #define TODO_SIZE 128
61 static struct work_item todo[TODO_SIZE];
62 static int todo_start;
63 static int todo_end;
64 static int todo_done;
65
66 /* Has all work items been added? */
67 static int all_work_added;
68
69 static struct repository **repos_to_free;
70 static size_t repos_to_free_nr, repos_to_free_alloc;
71
72 /* This lock protects all the variables above. */
73 static pthread_mutex_t grep_mutex;
74
75 static inline void grep_lock(void)
76 {
77 pthread_mutex_lock(&grep_mutex);
78 }
79
80 static inline void grep_unlock(void)
81 {
82 pthread_mutex_unlock(&grep_mutex);
83 }
84
85 /* Signalled when a new work_item is added to todo. */
86 static pthread_cond_t cond_add;
87
88 /* Signalled when the result from one work_item is written to
89 * stdout.
90 */
91 static pthread_cond_t cond_write;
92
93 /* Signalled when we are finished with everything. */
94 static pthread_cond_t cond_result;
95
96 static int skip_first_line;
97
98 static void add_work(struct grep_opt *opt, struct grep_source *gs)
99 {
100 if (opt->binary != GREP_BINARY_TEXT)
101 grep_source_load_driver(gs, opt->repo->index);
102
103 grep_lock();
104
105 while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
106 pthread_cond_wait(&cond_write, &grep_mutex);
107 }
108
109 todo[todo_end].source = *gs;
110 todo[todo_end].done = 0;
111 strbuf_reset(&todo[todo_end].out);
112 todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
113
114 pthread_cond_signal(&cond_add);
115 grep_unlock();
116 }
117
118 static struct work_item *get_work(void)
119 {
120 struct work_item *ret;
121
122 grep_lock();
123 while (todo_start == todo_end && !all_work_added) {
124 pthread_cond_wait(&cond_add, &grep_mutex);
125 }
126
127 if (todo_start == todo_end && all_work_added) {
128 ret = NULL;
129 } else {
130 ret = &todo[todo_start];
131 todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
132 }
133 grep_unlock();
134 return ret;
135 }
136
137 static void work_done(struct work_item *w)
138 {
139 int old_done;
140
141 grep_lock();
142 w->done = 1;
143 old_done = todo_done;
144 for(; todo[todo_done].done && todo_done != todo_start;
145 todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
146 w = &todo[todo_done];
147 if (w->out.len) {
148 const char *p = w->out.buf;
149 size_t len = w->out.len;
150
151 /* Skip the leading hunk mark of the first file. */
152 if (skip_first_line) {
153 while (len) {
154 len--;
155 if (*p++ == '\n')
156 break;
157 }
158 skip_first_line = 0;
159 }
160
161 write_or_die(1, p, len);
162 }
163 grep_source_clear(&w->source);
164 }
165
166 if (old_done != todo_done)
167 pthread_cond_signal(&cond_write);
168
169 if (all_work_added && todo_done == todo_end)
170 pthread_cond_signal(&cond_result);
171
172 grep_unlock();
173 }
174
175 static void free_repos(void)
176 {
177 int i;
178
179 for (i = 0; i < repos_to_free_nr; i++) {
180 repo_clear(repos_to_free[i]);
181 free(repos_to_free[i]);
182 }
183 FREE_AND_NULL(repos_to_free);
184 repos_to_free_nr = 0;
185 repos_to_free_alloc = 0;
186 }
187
188 static void *run(void *arg)
189 {
190 int hit = 0;
191 struct grep_opt *opt = arg;
192
193 while (1) {
194 struct work_item *w = get_work();
195 if (!w)
196 break;
197
198 opt->output_priv = w;
199 hit |= grep_source(opt, &w->source);
200 grep_source_clear_data(&w->source);
201 work_done(w);
202 }
203 free_grep_patterns(opt);
204 free(opt);
205
206 return (void*) (intptr_t) hit;
207 }
208
209 static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
210 {
211 struct work_item *w = opt->output_priv;
212 strbuf_add(&w->out, buf, size);
213 }
214
215 static void start_threads(struct grep_opt *opt)
216 {
217 int i;
218
219 pthread_mutex_init(&grep_mutex, NULL);
220 pthread_mutex_init(&grep_attr_mutex, NULL);
221 pthread_cond_init(&cond_add, NULL);
222 pthread_cond_init(&cond_write, NULL);
223 pthread_cond_init(&cond_result, NULL);
224 grep_use_locks = 1;
225 enable_obj_read_lock();
226
227 for (i = 0; i < ARRAY_SIZE(todo); i++) {
228 strbuf_init(&todo[i].out, 0);
229 }
230
231 CALLOC_ARRAY(threads, num_threads);
232 for (i = 0; i < num_threads; i++) {
233 int err;
234 struct grep_opt *o = grep_opt_dup(opt);
235 o->output = strbuf_out;
236 compile_grep_patterns(o);
237 err = pthread_create(&threads[i], NULL, run, o);
238
239 if (err)
240 die(_("grep: failed to create thread: %s"),
241 strerror(err));
242 }
243 }
244
245 static int wait_all(void)
246 {
247 int hit = 0;
248 int i;
249
250 if (!HAVE_THREADS)
251 BUG("Never call this function unless you have started threads");
252
253 grep_lock();
254 all_work_added = 1;
255
256 /* Wait until all work is done. */
257 while (todo_done != todo_end)
258 pthread_cond_wait(&cond_result, &grep_mutex);
259
260 /* Wake up all the consumer threads so they can see that there
261 * is no more work to do.
262 */
263 pthread_cond_broadcast(&cond_add);
264 grep_unlock();
265
266 for (i = 0; i < num_threads; i++) {
267 void *h;
268 pthread_join(threads[i], &h);
269 hit |= (int) (intptr_t) h;
270 }
271
272 free(threads);
273
274 pthread_mutex_destroy(&grep_mutex);
275 pthread_mutex_destroy(&grep_attr_mutex);
276 pthread_cond_destroy(&cond_add);
277 pthread_cond_destroy(&cond_write);
278 pthread_cond_destroy(&cond_result);
279 grep_use_locks = 0;
280 disable_obj_read_lock();
281
282 return hit;
283 }
284
285 static int grep_cmd_config(const char *var, const char *value, void *cb)
286 {
287 int st = grep_config(var, value, cb);
288 if (git_color_default_config(var, value, NULL) < 0)
289 st = -1;
290
291 if (!strcmp(var, "grep.threads")) {
292 num_threads = git_config_int(var, value);
293 if (num_threads < 0)
294 die(_("invalid number of threads specified (%d) for %s"),
295 num_threads, var);
296 else if (!HAVE_THREADS && num_threads > 1) {
297 /*
298 * TRANSLATORS: %s is the configuration
299 * variable for tweaking threads, currently
300 * grep.threads
301 */
302 warning(_("no threads support, ignoring %s"), var);
303 num_threads = 1;
304 }
305 }
306
307 if (!strcmp(var, "submodule.recurse"))
308 recurse_submodules = git_config_bool(var, value);
309
310 return st;
311 }
312
313 static void grep_source_name(struct grep_opt *opt, const char *filename,
314 int tree_name_len, struct strbuf *out)
315 {
316 strbuf_reset(out);
317
318 if (opt->null_following_name) {
319 if (opt->relative && grep_prefix) {
320 struct strbuf rel_buf = STRBUF_INIT;
321 const char *rel_name =
322 relative_path(filename + tree_name_len,
323 grep_prefix, &rel_buf);
324
325 if (tree_name_len)
326 strbuf_add(out, filename, tree_name_len);
327
328 strbuf_addstr(out, rel_name);
329 strbuf_release(&rel_buf);
330 } else {
331 strbuf_addstr(out, filename);
332 }
333 return;
334 }
335
336 if (opt->relative && grep_prefix)
337 quote_path(filename + tree_name_len, grep_prefix, out, 0);
338 else
339 quote_c_style(filename + tree_name_len, out, NULL, 0);
340
341 if (tree_name_len)
342 strbuf_insert(out, 0, filename, tree_name_len);
343 }
344
345 static int grep_oid(struct grep_opt *opt, const struct object_id *oid,
346 const char *filename, int tree_name_len,
347 const char *path)
348 {
349 struct strbuf pathbuf = STRBUF_INIT;
350 struct grep_source gs;
351
352 grep_source_name(opt, filename, tree_name_len, &pathbuf);
353 grep_source_init_oid(&gs, pathbuf.buf, path, oid, opt->repo);
354 strbuf_release(&pathbuf);
355
356 if (num_threads > 1) {
357 /*
358 * add_work() copies gs and thus assumes ownership of
359 * its fields, so do not call grep_source_clear()
360 */
361 add_work(opt, &gs);
362 return 0;
363 } else {
364 int hit;
365
366 hit = grep_source(opt, &gs);
367
368 grep_source_clear(&gs);
369 return hit;
370 }
371 }
372
373 static int grep_file(struct grep_opt *opt, const char *filename)
374 {
375 struct strbuf buf = STRBUF_INIT;
376 struct grep_source gs;
377
378 grep_source_name(opt, filename, 0, &buf);
379 grep_source_init_file(&gs, buf.buf, filename);
380 strbuf_release(&buf);
381
382 if (num_threads > 1) {
383 /*
384 * add_work() copies gs and thus assumes ownership of
385 * its fields, so do not call grep_source_clear()
386 */
387 add_work(opt, &gs);
388 return 0;
389 } else {
390 int hit;
391
392 hit = grep_source(opt, &gs);
393
394 grep_source_clear(&gs);
395 return hit;
396 }
397 }
398
399 static void append_path(struct grep_opt *opt, const void *data, size_t len)
400 {
401 struct string_list *path_list = opt->output_priv;
402
403 if (len == 1 && *(const char *)data == '\0')
404 return;
405 string_list_append_nodup(path_list, xstrndup(data, len));
406 }
407
408 static void run_pager(struct grep_opt *opt, const char *prefix)
409 {
410 struct string_list *path_list = opt->output_priv;
411 struct child_process child = CHILD_PROCESS_INIT;
412 int i, status;
413
414 for (i = 0; i < path_list->nr; i++)
415 strvec_push(&child.args, path_list->items[i].string);
416 child.dir = prefix;
417 child.use_shell = 1;
418
419 status = run_command(&child);
420 if (status)
421 exit(status);
422 }
423
424 static int grep_cache(struct grep_opt *opt,
425 const struct pathspec *pathspec, int cached);
426 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
427 struct tree_desc *tree, struct strbuf *base, int tn_len,
428 int check_attr);
429
430 static int grep_submodule(struct grep_opt *opt,
431 const struct pathspec *pathspec,
432 const struct object_id *oid,
433 const char *filename, const char *path, int cached)
434 {
435 struct repository *subrepo;
436 struct repository *superproject = opt->repo;
437 struct grep_opt subopt;
438 int hit = 0;
439
440 if (!is_submodule_active(superproject, path))
441 return 0;
442
443 subrepo = xmalloc(sizeof(*subrepo));
444 if (repo_submodule_init(subrepo, superproject, path, null_oid())) {
445 free(subrepo);
446 return 0;
447 }
448 ALLOC_GROW(repos_to_free, repos_to_free_nr + 1, repos_to_free_alloc);
449 repos_to_free[repos_to_free_nr++] = subrepo;
450
451 /*
452 * NEEDSWORK: repo_read_gitmodules() might call
453 * add_to_alternates_memory() via config_from_gitmodules(). This
454 * operation causes a race condition with concurrent object readings
455 * performed by the worker threads. That's why we need obj_read_lock()
456 * here. It should be removed once it's no longer necessary to add the
457 * subrepo's odbs to the in-memory alternates list.
458 */
459 obj_read_lock();
460
461 /*
462 * NEEDSWORK: when reading a submodule, the sparsity settings in the
463 * superproject are incorrectly forgotten or misused. For example:
464 *
465 * 1. "command_requires_full_index"
466 * When this setting is turned on for `grep`, only the superproject
467 * knows it. All the submodules are read with their own configs
468 * and get prepare_repo_settings()'d. Therefore, these submodules
469 * "forget" the sparse-index feature switch. As a result, the index
470 * of these submodules are expanded unexpectedly.
471 *
472 * 2. "core_apply_sparse_checkout"
473 * When running `grep` in the superproject, this setting is
474 * populated using the superproject's configs. However, once
475 * initialized, this config is globally accessible and is read by
476 * prepare_repo_settings() for the submodules. For instance, if a
477 * submodule is using a sparse-checkout, however, the superproject
478 * is not, the result is that the config from the superproject will
479 * dictate the behavior for the submodule, making it "forget" its
480 * sparse-checkout state.
481 *
482 * 3. "core_sparse_checkout_cone"
483 * ditto.
484 *
485 * Note that this list is not exhaustive.
486 */
487 repo_read_gitmodules(subrepo, 0);
488
489 /*
490 * All code paths tested by test code no longer need submodule ODBs to
491 * be added as alternates, but add it to the list just in case.
492 * Submodule ODBs added through add_submodule_odb_by_path() will be
493 * lazily registered as alternates when needed (and except in an
494 * unexpected code interaction, it won't be needed).
495 */
496 add_submodule_odb_by_path(subrepo->objects->odb->path);
497 obj_read_unlock();
498
499 memcpy(&subopt, opt, sizeof(subopt));
500 subopt.repo = subrepo;
501
502 if (oid) {
503 enum object_type object_type;
504 struct tree_desc tree;
505 void *data;
506 unsigned long size;
507 struct strbuf base = STRBUF_INIT;
508
509 obj_read_lock();
510 object_type = oid_object_info(subrepo, oid, NULL);
511 obj_read_unlock();
512 data = read_object_with_reference(subrepo,
513 oid, OBJ_TREE,
514 &size, NULL);
515 if (!data)
516 die(_("unable to read tree (%s)"), oid_to_hex(oid));
517
518 strbuf_addstr(&base, filename);
519 strbuf_addch(&base, '/');
520
521 init_tree_desc(&tree, data, size);
522 hit = grep_tree(&subopt, pathspec, &tree, &base, base.len,
523 object_type == OBJ_COMMIT);
524 strbuf_release(&base);
525 free(data);
526 } else {
527 hit = grep_cache(&subopt, pathspec, cached);
528 }
529
530 return hit;
531 }
532
533 static int grep_cache(struct grep_opt *opt,
534 const struct pathspec *pathspec, int cached)
535 {
536 struct repository *repo = opt->repo;
537 int hit = 0;
538 int nr;
539 struct strbuf name = STRBUF_INIT;
540 int name_base_len = 0;
541 if (repo->submodule_prefix) {
542 name_base_len = strlen(repo->submodule_prefix);
543 strbuf_addstr(&name, repo->submodule_prefix);
544 }
545
546 if (repo_read_index(repo) < 0)
547 die(_("index file corrupt"));
548
549 for (nr = 0; nr < repo->index->cache_nr; nr++) {
550 const struct cache_entry *ce = repo->index->cache[nr];
551
552 if (!cached && ce_skip_worktree(ce))
553 continue;
554
555 strbuf_setlen(&name, name_base_len);
556 strbuf_addstr(&name, ce->name);
557 if (S_ISSPARSEDIR(ce->ce_mode)) {
558 enum object_type type;
559 struct tree_desc tree;
560 void *data;
561 unsigned long size;
562
563 data = read_object_file(&ce->oid, &type, &size);
564 init_tree_desc(&tree, data, size);
565
566 hit |= grep_tree(opt, pathspec, &tree, &name, 0, 0);
567 strbuf_setlen(&name, name_base_len);
568 strbuf_addstr(&name, ce->name);
569 free(data);
570 } else if (S_ISREG(ce->ce_mode) &&
571 match_pathspec(repo->index, pathspec, name.buf, name.len, 0, NULL,
572 S_ISDIR(ce->ce_mode) ||
573 S_ISGITLINK(ce->ce_mode))) {
574 /*
575 * If CE_VALID is on, we assume worktree file and its
576 * cache entry are identical, even if worktree file has
577 * been modified, so use cache version instead
578 */
579 if (cached || (ce->ce_flags & CE_VALID)) {
580 if (ce_stage(ce) || ce_intent_to_add(ce))
581 continue;
582 hit |= grep_oid(opt, &ce->oid, name.buf,
583 0, name.buf);
584 } else {
585 hit |= grep_file(opt, name.buf);
586 }
587 } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
588 submodule_path_match(repo->index, pathspec, name.buf, NULL)) {
589 hit |= grep_submodule(opt, pathspec, NULL, ce->name,
590 ce->name, cached);
591 } else {
592 continue;
593 }
594
595 if (ce_stage(ce)) {
596 do {
597 nr++;
598 } while (nr < repo->index->cache_nr &&
599 !strcmp(ce->name, repo->index->cache[nr]->name));
600 nr--; /* compensate for loop control */
601 }
602 if (hit && opt->status_only)
603 break;
604 }
605
606 strbuf_release(&name);
607 return hit;
608 }
609
610 static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
611 struct tree_desc *tree, struct strbuf *base, int tn_len,
612 int check_attr)
613 {
614 struct repository *repo = opt->repo;
615 int hit = 0;
616 enum interesting match = entry_not_interesting;
617 struct name_entry entry;
618 int old_baselen = base->len;
619 struct strbuf name = STRBUF_INIT;
620 int name_base_len = 0;
621 if (repo->submodule_prefix) {
622 strbuf_addstr(&name, repo->submodule_prefix);
623 name_base_len = name.len;
624 }
625
626 while (tree_entry(tree, &entry)) {
627 int te_len = tree_entry_len(&entry);
628
629 if (match != all_entries_interesting) {
630 strbuf_addstr(&name, base->buf + tn_len);
631 match = tree_entry_interesting(repo->index,
632 &entry, &name,
633 0, pathspec);
634 strbuf_setlen(&name, name_base_len);
635
636 if (match == all_entries_not_interesting)
637 break;
638 if (match == entry_not_interesting)
639 continue;
640 }
641
642 strbuf_add(base, entry.path, te_len);
643
644 if (S_ISREG(entry.mode)) {
645 hit |= grep_oid(opt, &entry.oid, base->buf, tn_len,
646 check_attr ? base->buf + tn_len : NULL);
647 } else if (S_ISDIR(entry.mode)) {
648 enum object_type type;
649 struct tree_desc sub;
650 void *data;
651 unsigned long size;
652
653 data = read_object_file(&entry.oid, &type, &size);
654 if (!data)
655 die(_("unable to read tree (%s)"),
656 oid_to_hex(&entry.oid));
657
658 strbuf_addch(base, '/');
659 init_tree_desc(&sub, data, size);
660 hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
661 check_attr);
662 free(data);
663 } else if (recurse_submodules && S_ISGITLINK(entry.mode)) {
664 hit |= grep_submodule(opt, pathspec, &entry.oid,
665 base->buf, base->buf + tn_len,
666 1); /* ignored */
667 }
668
669 strbuf_setlen(base, old_baselen);
670
671 if (hit && opt->status_only)
672 break;
673 }
674
675 strbuf_release(&name);
676 return hit;
677 }
678
679 static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
680 struct object *obj, const char *name, const char *path)
681 {
682 if (obj->type == OBJ_BLOB)
683 return grep_oid(opt, &obj->oid, name, 0, path);
684 if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
685 struct tree_desc tree;
686 void *data;
687 unsigned long size;
688 struct strbuf base;
689 int hit, len;
690
691 data = read_object_with_reference(opt->repo,
692 &obj->oid, OBJ_TREE,
693 &size, NULL);
694 if (!data)
695 die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
696
697 len = name ? strlen(name) : 0;
698 strbuf_init(&base, PATH_MAX + len + 1);
699 if (len) {
700 strbuf_add(&base, name, len);
701 strbuf_addch(&base, ':');
702 }
703 init_tree_desc(&tree, data, size);
704 hit = grep_tree(opt, pathspec, &tree, &base, base.len,
705 obj->type == OBJ_COMMIT);
706 strbuf_release(&base);
707 free(data);
708 return hit;
709 }
710 die(_("unable to grep from object of type %s"), type_name(obj->type));
711 }
712
713 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
714 const struct object_array *list)
715 {
716 unsigned int i;
717 int hit = 0;
718 const unsigned int nr = list->nr;
719
720 for (i = 0; i < nr; i++) {
721 struct object *real_obj;
722
723 obj_read_lock();
724 real_obj = deref_tag(opt->repo, list->objects[i].item,
725 NULL, 0);
726 obj_read_unlock();
727
728 if (!real_obj) {
729 char hex[GIT_MAX_HEXSZ + 1];
730 const char *name = list->objects[i].name;
731
732 if (!name) {
733 oid_to_hex_r(hex, &list->objects[i].item->oid);
734 name = hex;
735 }
736 die(_("invalid object '%s' given."), name);
737 }
738
739 /* load the gitmodules file for this rev */
740 if (recurse_submodules) {
741 submodule_free(opt->repo);
742 obj_read_lock();
743 gitmodules_config_oid(&real_obj->oid);
744 obj_read_unlock();
745 }
746 if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
747 list->objects[i].path)) {
748 hit = 1;
749 if (opt->status_only)
750 break;
751 }
752 }
753 return hit;
754 }
755
756 static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
757 int exc_std, int use_index)
758 {
759 struct dir_struct dir = DIR_INIT;
760 int i, hit = 0;
761
762 if (!use_index)
763 dir.flags |= DIR_NO_GITLINKS;
764 if (exc_std)
765 setup_standard_excludes(&dir);
766
767 fill_directory(&dir, opt->repo->index, pathspec);
768 for (i = 0; i < dir.nr; i++) {
769 hit |= grep_file(opt, dir.entries[i]->name);
770 if (hit && opt->status_only)
771 break;
772 }
773 dir_clear(&dir);
774 return hit;
775 }
776
777 static int context_callback(const struct option *opt, const char *arg,
778 int unset)
779 {
780 struct grep_opt *grep_opt = opt->value;
781 int value;
782 const char *endp;
783
784 if (unset) {
785 grep_opt->pre_context = grep_opt->post_context = 0;
786 return 0;
787 }
788 value = strtol(arg, (char **)&endp, 10);
789 if (*endp) {
790 return error(_("switch `%c' expects a numerical value"),
791 opt->short_name);
792 }
793 grep_opt->pre_context = grep_opt->post_context = value;
794 return 0;
795 }
796
797 static int file_callback(const struct option *opt, const char *arg, int unset)
798 {
799 struct grep_opt *grep_opt = opt->value;
800 int from_stdin;
801 FILE *patterns;
802 int lno = 0;
803 struct strbuf sb = STRBUF_INIT;
804
805 BUG_ON_OPT_NEG(unset);
806
807 from_stdin = !strcmp(arg, "-");
808 patterns = from_stdin ? stdin : fopen(arg, "r");
809 if (!patterns)
810 die_errno(_("cannot open '%s'"), arg);
811 while (strbuf_getline(&sb, patterns) == 0) {
812 /* ignore empty line like grep does */
813 if (sb.len == 0)
814 continue;
815
816 append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
817 GREP_PATTERN);
818 }
819 if (!from_stdin)
820 fclose(patterns);
821 strbuf_release(&sb);
822 return 0;
823 }
824
825 static int not_callback(const struct option *opt, const char *arg, int unset)
826 {
827 struct grep_opt *grep_opt = opt->value;
828 BUG_ON_OPT_NEG(unset);
829 BUG_ON_OPT_ARG(arg);
830 append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
831 return 0;
832 }
833
834 static int and_callback(const struct option *opt, const char *arg, int unset)
835 {
836 struct grep_opt *grep_opt = opt->value;
837 BUG_ON_OPT_NEG(unset);
838 BUG_ON_OPT_ARG(arg);
839 append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
840 return 0;
841 }
842
843 static int open_callback(const struct option *opt, const char *arg, int unset)
844 {
845 struct grep_opt *grep_opt = opt->value;
846 BUG_ON_OPT_NEG(unset);
847 BUG_ON_OPT_ARG(arg);
848 append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
849 return 0;
850 }
851
852 static int close_callback(const struct option *opt, const char *arg, int unset)
853 {
854 struct grep_opt *grep_opt = opt->value;
855 BUG_ON_OPT_NEG(unset);
856 BUG_ON_OPT_ARG(arg);
857 append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
858 return 0;
859 }
860
861 static int pattern_callback(const struct option *opt, const char *arg,
862 int unset)
863 {
864 struct grep_opt *grep_opt = opt->value;
865 BUG_ON_OPT_NEG(unset);
866 append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
867 return 0;
868 }
869
870 int cmd_grep(int argc, const char **argv, const char *prefix)
871 {
872 int hit = 0;
873 int cached = 0, untracked = 0, opt_exclude = -1;
874 int seen_dashdash = 0;
875 int external_grep_allowed__ignored;
876 const char *show_in_pager = NULL, *default_pager = "dummy";
877 struct grep_opt opt;
878 struct object_array list = OBJECT_ARRAY_INIT;
879 struct pathspec pathspec;
880 struct string_list path_list = STRING_LIST_INIT_DUP;
881 int i;
882 int dummy;
883 int use_index = 1;
884 int allow_revs;
885
886 struct option options[] = {
887 OPT_BOOL(0, "cached", &cached,
888 N_("search in index instead of in the work tree")),
889 OPT_NEGBIT(0, "no-index", &use_index,
890 N_("find in contents not managed by git"), 1),
891 OPT_BOOL(0, "untracked", &untracked,
892 N_("search in both tracked and untracked files")),
893 OPT_SET_INT(0, "exclude-standard", &opt_exclude,
894 N_("ignore files specified via '.gitignore'"), 1),
895 OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
896 N_("recursively search in each submodule")),
897 OPT_GROUP(""),
898 OPT_BOOL('v', "invert-match", &opt.invert,
899 N_("show non-matching lines")),
900 OPT_BOOL('i', "ignore-case", &opt.ignore_case,
901 N_("case insensitive matching")),
902 OPT_BOOL('w', "word-regexp", &opt.word_regexp,
903 N_("match patterns only at word boundaries")),
904 OPT_SET_INT('a', "text", &opt.binary,
905 N_("process binary files as text"), GREP_BINARY_TEXT),
906 OPT_SET_INT('I', NULL, &opt.binary,
907 N_("don't match patterns in binary files"),
908 GREP_BINARY_NOMATCH),
909 OPT_BOOL(0, "textconv", &opt.allow_textconv,
910 N_("process binary files with textconv filters")),
911 OPT_SET_INT('r', "recursive", &opt.max_depth,
912 N_("search in subdirectories (default)"), -1),
913 { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
914 N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
915 NULL, 1 },
916 OPT_GROUP(""),
917 OPT_SET_INT('E', "extended-regexp", &opt.pattern_type_option,
918 N_("use extended POSIX regular expressions"),
919 GREP_PATTERN_TYPE_ERE),
920 OPT_SET_INT('G', "basic-regexp", &opt.pattern_type_option,
921 N_("use basic POSIX regular expressions (default)"),
922 GREP_PATTERN_TYPE_BRE),
923 OPT_SET_INT('F', "fixed-strings", &opt.pattern_type_option,
924 N_("interpret patterns as fixed strings"),
925 GREP_PATTERN_TYPE_FIXED),
926 OPT_SET_INT('P', "perl-regexp", &opt.pattern_type_option,
927 N_("use Perl-compatible regular expressions"),
928 GREP_PATTERN_TYPE_PCRE),
929 OPT_GROUP(""),
930 OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
931 OPT_BOOL(0, "column", &opt.columnnum, N_("show column number of first match")),
932 OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
933 OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
934 OPT_NEGBIT(0, "full-name", &opt.relative,
935 N_("show filenames relative to top directory"), 1),
936 OPT_BOOL('l', "files-with-matches", &opt.name_only,
937 N_("show only filenames instead of matching lines")),
938 OPT_BOOL(0, "name-only", &opt.name_only,
939 N_("synonym for --files-with-matches")),
940 OPT_BOOL('L', "files-without-match",
941 &opt.unmatch_name_only,
942 N_("show only the names of files without match")),
943 OPT_BOOL_F('z', "null", &opt.null_following_name,
944 N_("print NUL after filenames"),
945 PARSE_OPT_NOCOMPLETE),
946 OPT_BOOL('o', "only-matching", &opt.only_matching,
947 N_("show only matching parts of a line")),
948 OPT_BOOL('c', "count", &opt.count,
949 N_("show the number of matches instead of matching lines")),
950 OPT__COLOR(&opt.color, N_("highlight matches")),
951 OPT_BOOL(0, "break", &opt.file_break,
952 N_("print empty line between matches from different files")),
953 OPT_BOOL(0, "heading", &opt.heading,
954 N_("show filename only once above matches from same file")),
955 OPT_GROUP(""),
956 OPT_CALLBACK('C', "context", &opt, N_("n"),
957 N_("show <n> context lines before and after matches"),
958 context_callback),
959 OPT_INTEGER('B', "before-context", &opt.pre_context,
960 N_("show <n> context lines before matches")),
961 OPT_INTEGER('A', "after-context", &opt.post_context,
962 N_("show <n> context lines after matches")),
963 OPT_INTEGER(0, "threads", &num_threads,
964 N_("use <n> worker threads")),
965 OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
966 context_callback),
967 OPT_BOOL('p', "show-function", &opt.funcname,
968 N_("show a line with the function name before matches")),
969 OPT_BOOL('W', "function-context", &opt.funcbody,
970 N_("show the surrounding function")),
971 OPT_GROUP(""),
972 OPT_CALLBACK('f', NULL, &opt, N_("file"),
973 N_("read patterns from file"), file_callback),
974 OPT_CALLBACK_F('e', NULL, &opt, N_("pattern"),
975 N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback),
976 OPT_CALLBACK_F(0, "and", &opt, NULL,
977 N_("combine patterns specified with -e"),
978 PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback),
979 OPT_BOOL(0, "or", &dummy, ""),
980 OPT_CALLBACK_F(0, "not", &opt, NULL, "",
981 PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback),
982 OPT_CALLBACK_F('(', NULL, &opt, NULL, "",
983 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
984 open_callback),
985 OPT_CALLBACK_F(')', NULL, &opt, NULL, "",
986 PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
987 close_callback),
988 OPT__QUIET(&opt.status_only,
989 N_("indicate hit with exit status without output")),
990 OPT_BOOL(0, "all-match", &opt.all_match,
991 N_("show only matches from files that match all patterns")),
992 OPT_GROUP(""),
993 { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
994 N_("pager"), N_("show matching files in the pager"),
995 PARSE_OPT_OPTARG | PARSE_OPT_NOCOMPLETE,
996 NULL, (intptr_t)default_pager },
997 OPT_BOOL_F(0, "ext-grep", &external_grep_allowed__ignored,
998 N_("allow calling of grep(1) (ignored by this build)"),
999 PARSE_OPT_NOCOMPLETE),
1000 OPT_INTEGER('m', "max-count", &opt.max_count,
1001 N_("maximum number of results per file")),
1002 OPT_END()
1003 };
1004 grep_prefix = prefix;
1005
1006 grep_init(&opt, the_repository);
1007 git_config(grep_cmd_config, &opt);
1008
1009 /*
1010 * If there is no -- then the paths must exist in the working
1011 * tree. If there is no explicit pattern specified with -e or
1012 * -f, we take the first unrecognized non option to be the
1013 * pattern, but then what follows it must be zero or more
1014 * valid refs up to the -- (if exists), and then existing
1015 * paths. If there is an explicit pattern, then the first
1016 * unrecognized non option is the beginning of the refs list
1017 * that continues up to the -- (if exists), and then paths.
1018 */
1019 argc = parse_options(argc, argv, prefix, options, grep_usage,
1020 PARSE_OPT_KEEP_DASHDASH |
1021 PARSE_OPT_STOP_AT_NON_OPTION);
1022
1023 if (the_repository->gitdir) {
1024 prepare_repo_settings(the_repository);
1025 the_repository->settings.command_requires_full_index = 0;
1026 }
1027
1028 if (use_index && !startup_info->have_repository) {
1029 int fallback = 0;
1030 git_config_get_bool("grep.fallbacktonoindex", &fallback);
1031 if (fallback)
1032 use_index = 0;
1033 else
1034 /* die the same way as if we did it at the beginning */
1035 setup_git_directory();
1036 }
1037 /* Ignore --recurse-submodules if --no-index is given or implied */
1038 if (!use_index)
1039 recurse_submodules = 0;
1040
1041 /*
1042 * skip a -- separator; we know it cannot be
1043 * separating revisions from pathnames if
1044 * we haven't even had any patterns yet
1045 */
1046 if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1047 argv++;
1048 argc--;
1049 }
1050
1051 /* First unrecognized non-option token */
1052 if (argc > 0 && !opt.pattern_list) {
1053 append_grep_pattern(&opt, argv[0], "command line", 0,
1054 GREP_PATTERN);
1055 argv++;
1056 argc--;
1057 }
1058
1059 if (show_in_pager == default_pager)
1060 show_in_pager = git_pager(1);
1061 if (show_in_pager) {
1062 opt.color = 0;
1063 opt.name_only = 1;
1064 opt.null_following_name = 1;
1065 opt.output_priv = &path_list;
1066 opt.output = append_path;
1067 string_list_append(&path_list, show_in_pager);
1068 }
1069
1070 if (!opt.pattern_list)
1071 die(_("no pattern given"));
1072
1073 /* --only-matching has no effect with --invert. */
1074 if (opt.invert)
1075 opt.only_matching = 0;
1076
1077 /*
1078 * We have to find "--" in a separate pass, because its presence
1079 * influences how we will parse arguments that come before it.
1080 */
1081 for (i = 0; i < argc; i++) {
1082 if (!strcmp(argv[i], "--")) {
1083 seen_dashdash = 1;
1084 break;
1085 }
1086 }
1087
1088 /*
1089 * Resolve any rev arguments. If we have a dashdash, then everything up
1090 * to it must resolve as a rev. If not, then we stop at the first
1091 * non-rev and assume everything else is a path.
1092 */
1093 allow_revs = use_index && !untracked;
1094 for (i = 0; i < argc; i++) {
1095 const char *arg = argv[i];
1096 struct object_id oid;
1097 struct object_context oc;
1098 struct object *object;
1099
1100 if (!strcmp(arg, "--")) {
1101 i++;
1102 break;
1103 }
1104
1105 if (!allow_revs) {
1106 if (seen_dashdash)
1107 die(_("--no-index or --untracked cannot be used with revs"));
1108 break;
1109 }
1110
1111 if (get_oid_with_context(the_repository, arg,
1112 GET_OID_RECORD_PATH,
1113 &oid, &oc)) {
1114 if (seen_dashdash)
1115 die(_("unable to resolve revision: %s"), arg);
1116 break;
1117 }
1118
1119 object = parse_object_or_die(&oid, arg);
1120 if (!seen_dashdash)
1121 verify_non_filename(prefix, arg);
1122 add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1123 free(oc.path);
1124 }
1125
1126 /*
1127 * Anything left over is presumed to be a path. But in the non-dashdash
1128 * "do what I mean" case, we verify and complain when that isn't true.
1129 */
1130 if (!seen_dashdash) {
1131 int j;
1132 for (j = i; j < argc; j++)
1133 verify_filename(prefix, argv[j], j == i && allow_revs);
1134 }
1135
1136 parse_pathspec(&pathspec, 0,
1137 PATHSPEC_PREFER_CWD |
1138 (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1139 prefix, argv + i);
1140 pathspec.max_depth = opt.max_depth;
1141 pathspec.recursive = 1;
1142 pathspec.recurse_submodules = !!recurse_submodules;
1143
1144 if (recurse_submodules && untracked)
1145 die(_("--untracked not supported with --recurse-submodules"));
1146
1147 /*
1148 * Optimize out the case where the amount of matches is limited to zero.
1149 * We do this to keep results consistent with GNU grep(1).
1150 */
1151 if (opt.max_count == 0)
1152 return 1;
1153
1154 if (show_in_pager) {
1155 if (num_threads > 1)
1156 warning(_("invalid option combination, ignoring --threads"));
1157 num_threads = 1;
1158 } else if (!HAVE_THREADS && num_threads > 1) {
1159 warning(_("no threads support, ignoring --threads"));
1160 num_threads = 1;
1161 } else if (num_threads < 0)
1162 die(_("invalid number of threads specified (%d)"), num_threads);
1163 else if (num_threads == 0)
1164 num_threads = HAVE_THREADS ? online_cpus() : 1;
1165
1166 if (num_threads > 1) {
1167 if (!HAVE_THREADS)
1168 BUG("Somebody got num_threads calculation wrong!");
1169 if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1170 && (opt.pre_context || opt.post_context ||
1171 opt.file_break || opt.funcbody))
1172 skip_first_line = 1;
1173
1174 /*
1175 * Pre-read gitmodules (if not read already) and force eager
1176 * initialization of packed_git to prevent racy lazy
1177 * reading/initialization once worker threads are started.
1178 */
1179 if (recurse_submodules)
1180 repo_read_gitmodules(the_repository, 1);
1181 if (startup_info->have_repository)
1182 (void)get_packed_git(the_repository);
1183
1184 start_threads(&opt);
1185 } else {
1186 /*
1187 * The compiled patterns on the main path are only
1188 * used when not using threading. Otherwise
1189 * start_threads() above calls compile_grep_patterns()
1190 * for each thread.
1191 */
1192 compile_grep_patterns(&opt);
1193 }
1194
1195 if (show_in_pager && (cached || list.nr))
1196 die(_("--open-files-in-pager only works on the worktree"));
1197
1198 if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1199 const char *pager = path_list.items[0].string;
1200 int len = strlen(pager);
1201
1202 if (len > 4 && is_dir_sep(pager[len - 5]))
1203 pager += len - 4;
1204
1205 if (opt.ignore_case && !strcmp("less", pager))
1206 string_list_append(&path_list, "-I");
1207
1208 if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1209 struct strbuf buf = STRBUF_INIT;
1210 strbuf_addf(&buf, "+/%s%s",
1211 strcmp("less", pager) ? "" : "*",
1212 opt.pattern_list->pattern);
1213 string_list_append_nodup(&path_list,
1214 strbuf_detach(&buf, NULL));
1215 }
1216 }
1217
1218 if (!show_in_pager && !opt.status_only)
1219 setup_pager();
1220
1221 die_for_incompatible_opt3(!use_index, "--no-index",
1222 untracked, "--untracked",
1223 cached, "--cached");
1224
1225 if (!use_index || untracked) {
1226 int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1227 hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1228 } else if (0 <= opt_exclude) {
1229 die(_("--[no-]exclude-standard cannot be used for tracked contents"));
1230 } else if (!list.nr) {
1231 if (!cached)
1232 setup_work_tree();
1233
1234 hit = grep_cache(&opt, &pathspec, cached);
1235 } else {
1236 if (cached)
1237 die(_("both --cached and trees are given"));
1238
1239 hit = grep_objects(&opt, &pathspec, &list);
1240 }
1241
1242 if (num_threads > 1)
1243 hit |= wait_all();
1244 if (hit && show_in_pager)
1245 run_pager(&opt, prefix);
1246 clear_pathspec(&pathspec);
1247 string_list_clear(&path_list, 0);
1248 free_grep_patterns(&opt);
1249 object_array_clear(&list);
1250 free_repos();
1251 return !hit;
1252 }