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