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