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