grep.c 24.4 KB
Newer Older
J
Junio C Hamano 已提交
1 2 3 4 5 6 7 8 9 10
/*
 * Builtin "git grep"
 *
 * Copyright (c) 2006 Junio C Hamano
 */
#include "cache.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
#include "tag.h"
11
#include "tree-walk.h"
J
Junio C Hamano 已提交
12
#include "builtin.h"
R
René Scharfe 已提交
13
#include "parse-options.h"
14 15
#include "string-list.h"
#include "run-command.h"
16
#include "userdiff.h"
17
#include "grep.h"
18
#include "quote.h"
J
Junio C Hamano 已提交
19
#include "dir.h"
20
#include "pathspec.h"
F
Fredrik Kuivinen 已提交
21

R
René Scharfe 已提交
22
static char const * const grep_usage[] = {
23
	N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
R
René Scharfe 已提交
24 25 26
	NULL
};

27 28
#define GREP_NUM_THREADS_DEFAULT 8
static int num_threads;
F
Fredrik Kuivinen 已提交
29 30

#ifndef NO_PTHREADS
31
static pthread_t *threads;
F
Fredrik Kuivinen 已提交
32 33 34 35 36

/* We use one producer thread and THREADS consumer
 * threads. The producer adds struct work_items to 'todo' and the
 * consumers pick work items from the same array.
 */
37
struct work_item {
38
	struct grep_source source;
F
Fredrik Kuivinen 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	char done;
	struct strbuf out;
};

/* In the range [todo_done, todo_start) in 'todo' we have work_items
 * that have been or are processed by a consumer thread. We haven't
 * written the result for these to stdout yet.
 *
 * The work_items in [todo_start, todo_end) are waiting to be picked
 * up by a consumer thread.
 *
 * The ranges are modulo TODO_SIZE.
 */
#define TODO_SIZE 128
static struct work_item todo[TODO_SIZE];
static int todo_start;
static int todo_end;
static int todo_done;

/* Has all work items been added? */
static int all_work_added;

/* This lock protects all the variables above. */
static pthread_mutex_t grep_mutex;

64 65
static inline void grep_lock(void)
{
66
	if (num_threads)
67 68 69 70 71
		pthread_mutex_lock(&grep_mutex);
}

static inline void grep_unlock(void)
{
72
	if (num_threads)
73 74 75
		pthread_mutex_unlock(&grep_mutex);
}

F
Fredrik Kuivinen 已提交
76 77 78 79 80 81 82 83 84 85 86
/* Signalled when a new work_item is added to todo. */
static pthread_cond_t cond_add;

/* Signalled when the result from one work_item is written to
 * stdout.
 */
static pthread_cond_t cond_write;

/* Signalled when we are finished with everything. */
static pthread_cond_t cond_result;

87
static int skip_first_line;
88

89
static void add_work(struct grep_opt *opt, enum grep_source_type type,
90
		     const char *name, const char *path, const void *id)
F
Fredrik Kuivinen 已提交
91 92 93 94 95 96 97
{
	grep_lock();

	while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
		pthread_cond_wait(&cond_write, &grep_mutex);
	}

98
	grep_source_init(&todo[todo_end].source, type, name, path, id);
99 100
	if (opt->binary != GREP_BINARY_TEXT)
		grep_source_load_driver(&todo[todo_end].source);
F
Fredrik Kuivinen 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	todo[todo_end].done = 0;
	strbuf_reset(&todo[todo_end].out);
	todo_end = (todo_end + 1) % ARRAY_SIZE(todo);

	pthread_cond_signal(&cond_add);
	grep_unlock();
}

static struct work_item *get_work(void)
{
	struct work_item *ret;

	grep_lock();
	while (todo_start == todo_end && !all_work_added) {
		pthread_cond_wait(&cond_add, &grep_mutex);
	}

	if (todo_start == todo_end && all_work_added) {
		ret = NULL;
	} else {
		ret = &todo[todo_start];
		todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
	}
	grep_unlock();
	return ret;
}

static void work_done(struct work_item *w)
{
	int old_done;

	grep_lock();
	w->done = 1;
	old_done = todo_done;
	for(; todo[todo_done].done && todo_done != todo_start;
	    todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
		w = &todo[todo_done];
138
		if (w->out.len) {
139 140 141 142 143 144 145 146 147 148 149 150 151 152
			const char *p = w->out.buf;
			size_t len = w->out.len;

			/* Skip the leading hunk mark of the first file. */
			if (skip_first_line) {
				while (len) {
					len--;
					if (*p++ == '\n')
						break;
				}
				skip_first_line = 0;
			}

			write_or_die(1, p, len);
153
		}
154
		grep_source_clear(&w->source);
F
Fredrik Kuivinen 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
	}

	if (old_done != todo_done)
		pthread_cond_signal(&cond_write);

	if (all_work_added && todo_done == todo_end)
		pthread_cond_signal(&cond_result);

	grep_unlock();
}

static void *run(void *arg)
{
	int hit = 0;
	struct grep_opt *opt = arg;

	while (1) {
		struct work_item *w = get_work();
		if (!w)
			break;

		opt->output_priv = w;
177 178
		hit |= grep_source(opt, &w->source);
		grep_source_clear_data(&w->source);
F
Fredrik Kuivinen 已提交
179 180
		work_done(w);
	}
D
Dan McGee 已提交
181 182
	free_grep_patterns(arg);
	free(arg);
F
Fredrik Kuivinen 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

	return (void*) (intptr_t) hit;
}

static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
{
	struct work_item *w = opt->output_priv;
	strbuf_add(&w->out, buf, size);
}

static void start_threads(struct grep_opt *opt)
{
	int i;

	pthread_mutex_init(&grep_mutex, NULL);
198
	pthread_mutex_init(&grep_read_mutex, NULL);
199
	pthread_mutex_init(&grep_attr_mutex, NULL);
F
Fredrik Kuivinen 已提交
200 201 202
	pthread_cond_init(&cond_add, NULL);
	pthread_cond_init(&cond_write, NULL);
	pthread_cond_init(&cond_result, NULL);
J
Jeff King 已提交
203
	grep_use_locks = 1;
F
Fredrik Kuivinen 已提交
204 205 206 207 208

	for (i = 0; i < ARRAY_SIZE(todo); i++) {
		strbuf_init(&todo[i].out, 0);
	}

209 210
	threads = xcalloc(num_threads, sizeof(*threads));
	for (i = 0; i < num_threads; i++) {
F
Fredrik Kuivinen 已提交
211 212 213
		int err;
		struct grep_opt *o = grep_opt_dup(opt);
		o->output = strbuf_out;
214
		o->debug = 0;
F
Fredrik Kuivinen 已提交
215 216 217 218
		compile_grep_patterns(o);
		err = pthread_create(&threads[i], NULL, run, o);

		if (err)
219
			die(_("grep: failed to create thread: %s"),
F
Fredrik Kuivinen 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
			    strerror(err));
	}
}

static int wait_all(void)
{
	int hit = 0;
	int i;

	grep_lock();
	all_work_added = 1;

	/* Wait until all work is done. */
	while (todo_done != todo_end)
		pthread_cond_wait(&cond_result, &grep_mutex);

	/* Wake up all the consumer threads so they can see that there
	 * is no more work to do.
	 */
	pthread_cond_broadcast(&cond_add);
	grep_unlock();

242
	for (i = 0; i < num_threads; i++) {
F
Fredrik Kuivinen 已提交
243 244 245 246 247
		void *h;
		pthread_join(threads[i], &h);
		hit |= (int) (intptr_t) h;
	}

248 249
	free(threads);

F
Fredrik Kuivinen 已提交
250
	pthread_mutex_destroy(&grep_mutex);
251
	pthread_mutex_destroy(&grep_read_mutex);
252
	pthread_mutex_destroy(&grep_attr_mutex);
F
Fredrik Kuivinen 已提交
253 254 255
	pthread_cond_destroy(&cond_add);
	pthread_cond_destroy(&cond_write);
	pthread_cond_destroy(&cond_result);
J
Jeff King 已提交
256
	grep_use_locks = 0;
F
Fredrik Kuivinen 已提交
257 258 259 260 261 262 263 264 265 266 267

	return hit;
}
#else /* !NO_PTHREADS */

static int wait_all(void)
{
	return 0;
}
#endif

268 269 270 271 272
static int grep_cmd_config(const char *var, const char *value, void *cb)
{
	int st = grep_config(var, value, cb);
	if (git_color_default_config(var, value, cb) < 0)
		st = -1;
273 274 275 276 277 278 279 280

	if (!strcmp(var, "grep.threads")) {
		num_threads = git_config_int(var, value);
		if (num_threads < 0)
			die(_("invalid number of threads specified (%d) for %s"),
			    num_threads, var);
	}

281 282 283
	return st;
}

284 285 286 287
static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
{
	void *data;

288
	grep_read_lock();
289
	data = read_sha1_file(sha1, type, size);
290
	grep_read_unlock();
F
Fredrik Kuivinen 已提交
291 292 293 294
	return data;
}

static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
295 296
		     const char *filename, int tree_name_len,
		     const char *path)
F
Fredrik Kuivinen 已提交
297 298 299
{
	struct strbuf pathbuf = STRBUF_INIT;

300
	if (opt->relative && opt->prefix_length) {
301
		quote_path_relative(filename + tree_name_len, opt->prefix, &pathbuf);
F
Fredrik Kuivinen 已提交
302 303 304 305 306 307
		strbuf_insert(&pathbuf, 0, filename, tree_name_len);
	} else {
		strbuf_addstr(&pathbuf, filename);
	}

#ifndef NO_PTHREADS
308
	if (num_threads) {
309
		add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
310
		strbuf_release(&pathbuf);
F
Fredrik Kuivinen 已提交
311 312 313 314
		return 0;
	} else
#endif
	{
315
		struct grep_source gs;
F
Fredrik Kuivinen 已提交
316
		int hit;
J
Junio C Hamano 已提交
317

318
		grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
319 320
		strbuf_release(&pathbuf);
		hit = grep_source(opt, &gs);
321

322 323
		grep_source_clear(&gs);
		return hit;
J
Junio C Hamano 已提交
324
	}
F
Fredrik Kuivinen 已提交
325 326 327 328 329 330
}

static int grep_file(struct grep_opt *opt, const char *filename)
{
	struct strbuf buf = STRBUF_INIT;

331
	if (opt->relative && opt->prefix_length)
332
		quote_path_relative(filename, opt->prefix, &buf);
F
Fredrik Kuivinen 已提交
333 334 335 336
	else
		strbuf_addstr(&buf, filename);

#ifndef NO_PTHREADS
337
	if (num_threads) {
338
		add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
339
		strbuf_release(&buf);
F
Fredrik Kuivinen 已提交
340 341 342 343
		return 0;
	} else
#endif
	{
344
		struct grep_source gs;
F
Fredrik Kuivinen 已提交
345 346
		int hit;

347
		grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
348 349 350 351
		strbuf_release(&buf);
		hit = grep_source(opt, &gs);

		grep_source_clear(&gs);
F
Fredrik Kuivinen 已提交
352 353
		return hit;
	}
J
Junio C Hamano 已提交
354 355
}

356 357 358 359 360 361
static void append_path(struct grep_opt *opt, const void *data, size_t len)
{
	struct string_list *path_list = opt->output_priv;

	if (len == 1 && *(const char *)data == '\0')
		return;
362
	string_list_append(path_list, xstrndup(data, len));
363 364 365 366 367
}

static void run_pager(struct grep_opt *opt, const char *prefix)
{
	struct string_list *path_list = opt->output_priv;
368
	struct child_process child = CHILD_PROCESS_INIT;
369 370 371
	int i, status;

	for (i = 0; i < path_list->nr; i++)
372 373 374
		argv_array_push(&child.args, path_list->items[i].string);
	child.dir = prefix;
	child.use_shell = 1;
375

376
	status = run_command(&child);
377 378 379 380
	if (status)
		exit(status);
}

381
static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec, int cached)
J
Junio C Hamano 已提交
382 383 384 385 386 387
{
	int hit = 0;
	int nr;
	read_cache();

	for (nr = 0; nr < active_nr; nr++) {
388
		const struct cache_entry *ce = active_cache[nr];
389
		if (!S_ISREG(ce->ce_mode) || ce_intent_to_add(ce))
J
Junio C Hamano 已提交
390
			continue;
391
		if (!ce_path_match(ce, pathspec, NULL))
J
Junio C Hamano 已提交
392
			continue;
393 394 395 396 397
		/*
		 * If CE_VALID is on, we assume worktree file and its cache entry
		 * are identical, even if worktree file has been modified, so use
		 * cache version instead
		 */
398
		if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
399 400
			if (ce_stage(ce))
				continue;
401
			hit |= grep_sha1(opt, ce->sha1, ce->name, 0, ce->name);
402
		}
J
Junio C Hamano 已提交
403 404
		else
			hit |= grep_file(opt, ce->name);
405 406 407 408 409 410 411
		if (ce_stage(ce)) {
			do {
				nr++;
			} while (nr < active_nr &&
				 !strcmp(ce->name, active_cache[nr]->name));
			nr--; /* compensate for loop control */
		}
412 413
		if (hit && opt->status_only)
			break;
J
Junio C Hamano 已提交
414 415 416 417
	}
	return hit;
}

418
static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
419 420
		     struct tree_desc *tree, struct strbuf *base, int tn_len,
		     int check_attr)
J
Junio C Hamano 已提交
421
{
422 423
	int hit = 0;
	enum interesting match = entry_not_interesting;
424
	struct name_entry entry;
425
	int old_baselen = base->len;
J
Junio C Hamano 已提交
426

427
	while (tree_entry(tree, &entry)) {
428
		int te_len = tree_entry_len(&entry);
429

430
		if (match != all_entries_interesting) {
431
			match = tree_entry_interesting(&entry, base, tn_len, pathspec);
432
			if (match == all_entries_not_interesting)
433
				break;
434
			if (match == entry_not_interesting)
435 436
				continue;
		}
J
Junio C Hamano 已提交
437

438
		strbuf_add(base, entry.path, te_len);
439

440
		if (S_ISREG(entry.mode)) {
441 442
			hit |= grep_sha1(opt, entry.sha1, base->buf, tn_len,
					 check_attr ? base->buf + tn_len : NULL);
443
		}
444
		else if (S_ISDIR(entry.mode)) {
445
			enum object_type type;
J
Junio C Hamano 已提交
446 447
			struct tree_desc sub;
			void *data;
448 449
			unsigned long size;

450
			data = lock_and_read_sha1_file(entry.sha1, &type, &size);
J
Junio C Hamano 已提交
451
			if (!data)
452
				die(_("unable to read tree (%s)"),
453
				    sha1_to_hex(entry.sha1));
454 455

			strbuf_addch(base, '/');
456
			init_tree_desc(&sub, data, size);
457 458
			hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
					 check_attr);
J
Junio C Hamano 已提交
459 460
			free(data);
		}
461 462
		strbuf_setlen(base, old_baselen);

463 464
		if (hit && opt->status_only)
			break;
J
Junio C Hamano 已提交
465 466 467 468
	}
	return hit;
}

469
static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
470
		       struct object *obj, const char *name, const char *path)
J
Junio C Hamano 已提交
471
{
472
	if (obj->type == OBJ_BLOB)
B
brian m. carlson 已提交
473
		return grep_sha1(opt, obj->oid.hash, name, 0, path);
474
	if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
J
Junio C Hamano 已提交
475 476
		struct tree_desc tree;
		void *data;
477
		unsigned long size;
478 479 480
		struct strbuf base;
		int hit, len;

481
		grep_read_lock();
482
		data = read_object_with_reference(obj->oid.hash, tree_type,
483
						  &size, NULL);
484
		grep_read_unlock();
485

J
Junio C Hamano 已提交
486
		if (!data)
487
			die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
488 489 490 491 492 493 494

		len = name ? strlen(name) : 0;
		strbuf_init(&base, PATH_MAX + len + 1);
		if (len) {
			strbuf_add(&base, name, len);
			strbuf_addch(&base, ':');
		}
495
		init_tree_desc(&tree, data, size);
496 497
		hit = grep_tree(opt, pathspec, &tree, &base, base.len,
				obj->type == OBJ_COMMIT);
498
		strbuf_release(&base);
J
Junio C Hamano 已提交
499 500 501
		free(data);
		return hit;
	}
502
	die(_("unable to grep from object of type %s"), typename(obj->type));
J
Junio C Hamano 已提交
503 504
}

505
static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
506 507 508 509 510 511 512 513 514
			const struct object_array *list)
{
	unsigned int i;
	int hit = 0;
	const unsigned int nr = list->nr;

	for (i = 0; i < nr; i++) {
		struct object *real_obj;
		real_obj = deref_tag(list->objects[i].item, NULL, 0);
515
		if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
516 517 518 519 520 521 522 523
			hit = 1;
			if (opt->status_only)
				break;
		}
	}
	return hit;
}

524
static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
525
			  int exc_std, int use_index)
J
Junio C Hamano 已提交
526 527 528 529 530
{
	struct dir_struct dir;
	int i, hit = 0;

	memset(&dir, 0, sizeof(dir));
531 532
	if (!use_index)
		dir.flags |= DIR_NO_GITLINKS;
533 534
	if (exc_std)
		setup_standard_excludes(&dir);
J
Junio C Hamano 已提交
535

536
	fill_directory(&dir, pathspec);
J
Junio C Hamano 已提交
537
	for (i = 0; i < dir.nr; i++) {
538
		if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
539
			continue;
J
Junio C Hamano 已提交
540 541 542 543 544 545 546
		hit |= grep_file(opt, dir.entries[i]->name);
		if (hit && opt->status_only)
			break;
	}
	return hit;
}

547 548
static int context_callback(const struct option *opt, const char *arg,
			    int unset)
R
René Scharfe 已提交
549 550 551 552 553 554 555 556 557 558 559
{
	struct grep_opt *grep_opt = opt->value;
	int value;
	const char *endp;

	if (unset) {
		grep_opt->pre_context = grep_opt->post_context = 0;
		return 0;
	}
	value = strtol(arg, (char **)&endp, 10);
	if (*endp) {
560
		return error(_("switch `%c' expects a numerical value"),
R
René Scharfe 已提交
561 562 563 564 565 566
			     opt->short_name);
	}
	grep_opt->pre_context = grep_opt->post_context = value;
	return 0;
}

567
static int file_callback(const struct option *opt, const char *arg, int unset)
R
René Scharfe 已提交
568 569
{
	struct grep_opt *grep_opt = opt->value;
570
	int from_stdin = !strcmp(arg, "-");
R
René Scharfe 已提交
571 572
	FILE *patterns;
	int lno = 0;
M
Matt Kraai 已提交
573
	struct strbuf sb = STRBUF_INIT;
R
René Scharfe 已提交
574

575
	patterns = from_stdin ? stdin : fopen(arg, "r");
R
René Scharfe 已提交
576
	if (!patterns)
577
		die_errno(_("cannot open '%s'"), arg);
578
	while (strbuf_getline(&sb, patterns) == 0) {
R
René Scharfe 已提交
579 580 581
		/* ignore empty line like grep does */
		if (sb.len == 0)
			continue;
582

583 584
		append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
				GREP_PATTERN);
R
René Scharfe 已提交
585
	}
586 587
	if (!from_stdin)
		fclose(patterns);
R
René Scharfe 已提交
588 589 590 591
	strbuf_release(&sb);
	return 0;
}

592
static int not_callback(const struct option *opt, const char *arg, int unset)
R
René Scharfe 已提交
593 594 595 596 597 598
{
	struct grep_opt *grep_opt = opt->value;
	append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
	return 0;
}

599
static int and_callback(const struct option *opt, const char *arg, int unset)
R
René Scharfe 已提交
600 601 602 603 604 605
{
	struct grep_opt *grep_opt = opt->value;
	append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
	return 0;
}

606
static int open_callback(const struct option *opt, const char *arg, int unset)
R
René Scharfe 已提交
607 608 609 610 611 612
{
	struct grep_opt *grep_opt = opt->value;
	append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
	return 0;
}

613
static int close_callback(const struct option *opt, const char *arg, int unset)
R
René Scharfe 已提交
614 615 616 617 618 619
{
	struct grep_opt *grep_opt = opt->value;
	append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
	return 0;
}

620 621
static int pattern_callback(const struct option *opt, const char *arg,
			    int unset)
R
René Scharfe 已提交
622 623 624 625 626
{
	struct grep_opt *grep_opt = opt->value;
	append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
	return 0;
}
J
Junio C Hamano 已提交
627

628
int cmd_grep(int argc, const char **argv, const char *prefix)
J
Junio C Hamano 已提交
629 630
{
	int hit = 0;
631
	int cached = 0, untracked = 0, opt_exclude = -1;
632
	int seen_dashdash = 0;
633
	int external_grep_allowed__ignored;
634
	const char *show_in_pager = NULL, *default_pager = "dummy";
J
Junio C Hamano 已提交
635
	struct grep_opt opt;
636
	struct object_array list = OBJECT_ARRAY_INIT;
637
	struct pathspec pathspec;
638
	struct string_list path_list = STRING_LIST_INIT_NODUP;
639
	int i;
R
René Scharfe 已提交
640
	int dummy;
641
	int use_index = 1;
642
	int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
643

R
René Scharfe 已提交
644
	struct option options[] = {
645
		OPT_BOOL(0, "cached", &cached,
646
			N_("search in index instead of in the work tree")),
647
		OPT_NEGBIT(0, "no-index", &use_index,
648
			 N_("find in contents not managed by git"), 1),
649
		OPT_BOOL(0, "untracked", &untracked,
650
			N_("search in both tracked and untracked files")),
651
		OPT_SET_INT(0, "exclude-standard", &opt_exclude,
652
			    N_("ignore files specified via '.gitignore'"), 1),
R
René Scharfe 已提交
653
		OPT_GROUP(""),
654
		OPT_BOOL('v', "invert-match", &opt.invert,
655
			N_("show non-matching lines")),
656
		OPT_BOOL('i', "ignore-case", &opt.ignore_case,
657
			N_("case insensitive matching")),
658
		OPT_BOOL('w', "word-regexp", &opt.word_regexp,
659
			N_("match patterns only at word boundaries")),
R
René Scharfe 已提交
660
		OPT_SET_INT('a', "text", &opt.binary,
661
			N_("process binary files as text"), GREP_BINARY_TEXT),
R
René Scharfe 已提交
662
		OPT_SET_INT('I', NULL, &opt.binary,
663
			N_("don't match patterns in binary files"),
R
René Scharfe 已提交
664
			GREP_BINARY_NOMATCH),
J
Jeff King 已提交
665 666
		OPT_BOOL(0, "textconv", &opt.allow_textconv,
			 N_("process binary files with textconv filters")),
667 668
		{ OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
			N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
669
			NULL, 1 },
R
René Scharfe 已提交
670
		OPT_GROUP(""),
671
		OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
672
			    N_("use extended POSIX regular expressions"),
673 674
			    GREP_PATTERN_TYPE_ERE),
		OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
675
			    N_("use basic POSIX regular expressions (default)"),
676 677
			    GREP_PATTERN_TYPE_BRE),
		OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
678
			    N_("interpret patterns as fixed strings"),
679 680
			    GREP_PATTERN_TYPE_FIXED),
		OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
681
			    N_("use Perl-compatible regular expressions"),
682
			    GREP_PATTERN_TYPE_PCRE),
R
René Scharfe 已提交
683
		OPT_GROUP(""),
684
		OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
685 686
		OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
		OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
R
René Scharfe 已提交
687
		OPT_NEGBIT(0, "full-name", &opt.relative,
688
			N_("show filenames relative to top directory"), 1),
689
		OPT_BOOL('l', "files-with-matches", &opt.name_only,
690
			N_("show only filenames instead of matching lines")),
691
		OPT_BOOL(0, "name-only", &opt.name_only,
692
			N_("synonym for --files-with-matches")),
693
		OPT_BOOL('L', "files-without-match",
R
René Scharfe 已提交
694
			&opt.unmatch_name_only,
695
			N_("show only the names of files without match")),
696
		OPT_BOOL('z', "null", &opt.null_following_name,
697
			N_("print NUL after filenames")),
698
		OPT_BOOL('c', "count", &opt.count,
699 700
			N_("show the number of matches instead of matching lines")),
		OPT__COLOR(&opt.color, N_("highlight matches")),
701
		OPT_BOOL(0, "break", &opt.file_break,
702
			N_("print empty line between matches from different files")),
703
		OPT_BOOL(0, "heading", &opt.heading,
704
			N_("show filename only once above matches from same file")),
R
René Scharfe 已提交
705
		OPT_GROUP(""),
706 707
		OPT_CALLBACK('C', "context", &opt, N_("n"),
			N_("show <n> context lines before and after matches"),
R
René Scharfe 已提交
708
			context_callback),
R
René Scharfe 已提交
709
		OPT_INTEGER('B', "before-context", &opt.pre_context,
710
			N_("show <n> context lines before matches")),
R
René Scharfe 已提交
711
		OPT_INTEGER('A', "after-context", &opt.post_context,
712
			N_("show <n> context lines after matches")),
713 714
		OPT_INTEGER(0, "threads", &num_threads,
			N_("use <n> worker threads")),
715
		OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
R
René Scharfe 已提交
716
			context_callback),
717
		OPT_BOOL('p', "show-function", &opt.funcname,
718
			N_("show a line with the function name before matches")),
719
		OPT_BOOL('W', "function-context", &opt.funcbody,
720
			N_("show the surrounding function")),
R
René Scharfe 已提交
721
		OPT_GROUP(""),
722 723 724 725
		OPT_CALLBACK('f', NULL, &opt, N_("file"),
			N_("read patterns from file"), file_callback),
		{ OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
			N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
R
René Scharfe 已提交
726
		{ OPTION_CALLBACK, 0, "and", &opt, NULL,
727
		  N_("combine patterns specified with -e"),
R
René Scharfe 已提交
728
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
729
		OPT_BOOL(0, "or", &dummy, ""),
R
René Scharfe 已提交
730 731 732 733 734 735 736 737
		{ OPTION_CALLBACK, 0, "not", &opt, NULL, "",
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
		{ OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
		  open_callback },
		{ OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
		  close_callback },
738
		OPT__QUIET(&opt.status_only,
739
			   N_("indicate hit with exit status without output")),
740
		OPT_BOOL(0, "all-match", &opt.all_match,
741
			N_("show only matches from files that match all patterns")),
742
		{ OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
743
		  N_("show parse tree for grep expression"),
744
		  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
R
René Scharfe 已提交
745
		OPT_GROUP(""),
746
		{ OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
747
			N_("pager"), N_("show matching files in the pager"),
748
			PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
749 750
		OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
			 N_("allow calling of grep(1) (ignored by this build)")),
R
René Scharfe 已提交
751 752
		OPT_END()
	};
J
Junio C Hamano 已提交
753

754 755 756
	init_grep_defaults();
	git_config(grep_cmd_config, NULL);
	grep_init(&opt, prefix);
R
René Scharfe 已提交
757

J
Junio C Hamano 已提交
758
	/*
759 760 761 762 763 764
	 * If there is no -- then the paths must exist in the working
	 * tree.  If there is no explicit pattern specified with -e or
	 * -f, we take the first unrecognized non option to be the
	 * pattern, but then what follows it must be zero or more
	 * valid refs up to the -- (if exists), and then existing
	 * paths.  If there is an explicit pattern, then the first
765
	 * unrecognized non option is the beginning of the refs list
766
	 * that continues up to the -- (if exists), and then paths.
J
Junio C Hamano 已提交
767
	 */
768
	argc = parse_options(argc, argv, prefix, options, grep_usage,
R
René Scharfe 已提交
769
			     PARSE_OPT_KEEP_DASHDASH |
770
			     PARSE_OPT_STOP_AT_NON_OPTION);
771
	grep_commit_pattern_type(pattern_type_arg, &opt);
R
René Scharfe 已提交
772

773 774 775 776 777 778 779 780 781
	if (use_index && !startup_info->have_repository) {
		int fallback = 0;
		git_config_get_bool("grep.fallbacktonoindex", &fallback);
		if (fallback)
			use_index = 0;
		else
			/* die the same way as if we did it at the beginning */
			setup_git_directory();
	}
J
Junio C Hamano 已提交
782

J
Jeff King 已提交
783 784 785 786 787 788 789 790 791 792
	/*
	 * skip a -- separator; we know it cannot be
	 * separating revisions from pathnames if
	 * we haven't even had any patterns yet
	 */
	if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
		argv++;
		argc--;
	}

R
René Scharfe 已提交
793 794 795 796 797 798
	/* First unrecognized non-option token */
	if (argc > 0 && !opt.pattern_list) {
		append_grep_pattern(&opt, argv[0], "command line", 0,
				    GREP_PATTERN);
		argv++;
		argc--;
J
Junio C Hamano 已提交
799
	}
800

801 802
	if (show_in_pager == default_pager)
		show_in_pager = git_pager(1);
803
	if (show_in_pager) {
804
		opt.color = 0;
805 806 807 808
		opt.name_only = 1;
		opt.null_following_name = 1;
		opt.output_priv = &path_list;
		opt.output = append_path;
809
		string_list_append(&path_list, show_in_pager);
810 811
	}

812
	if (!opt.pattern_list)
813
		die(_("no pattern given."));
814 815
	if (!opt.fixed && opt.ignore_case)
		opt.regflags |= REG_ICASE;
F
Fredrik Kuivinen 已提交
816

817
	compile_grep_patterns(&opt);
818 819

	/* Check revs and then paths */
R
René Scharfe 已提交
820
	for (i = 0; i < argc; i++) {
821
		const char *arg = argv[i];
822
		unsigned char sha1[20];
823
		struct object_context oc;
824
		/* Is it a rev? */
825
		if (!get_sha1_with_context(arg, 0, sha1, &oc)) {
826
			struct object *object = parse_object_or_die(sha1, arg);
827 828
			if (!seen_dashdash)
				verify_non_filename(prefix, arg);
829
			add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
830 831 832 833 834 835 836
			continue;
		}
		if (!strcmp(arg, "--")) {
			i++;
			seen_dashdash = 1;
		}
		break;
837
	}
838

839
#ifndef NO_PTHREADS
840
	if (list.nr || cached || show_in_pager)
841 842 843 844 845
		num_threads = 0;
	else if (num_threads == 0)
		num_threads = GREP_NUM_THREADS_DEFAULT;
	else if (num_threads < 0)
		die(_("invalid number of threads specified (%d)"), num_threads);
846
#else
847
	num_threads = 0;
848 849 850
#endif

#ifndef NO_PTHREADS
851
	if (num_threads) {
852 853 854
		if (!(opt.name_only || opt.unmatch_name_only || opt.count)
		    && (opt.pre_context || opt.post_context ||
			opt.file_break || opt.funcbody))
855 856 857 858 859
			skip_first_line = 1;
		start_threads(&opt);
	}
#endif

860 861 862
	/* The rest are paths */
	if (!seen_dashdash) {
		int j;
J
Junio C Hamano 已提交
863
		for (j = i; j < argc; j++)
864
			verify_filename(prefix, argv[j], j == i);
865 866
	}

867
	parse_pathspec(&pathspec, 0,
868 869
		       PATHSPEC_PREFER_CWD |
		       (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
870
		       prefix, argv + i);
871 872
	pathspec.max_depth = opt.max_depth;
	pathspec.recursive = 1;
J
Junio C Hamano 已提交
873

874
	if (show_in_pager && (cached || list.nr))
875
		die(_("--open-files-in-pager only works on the worktree"));
876 877 878 879 880 881 882 883

	if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
		const char *pager = path_list.items[0].string;
		int len = strlen(pager);

		if (len > 4 && is_dir_sep(pager[len - 5]))
			pager += len - 4;

884 885 886
		if (opt.ignore_case && !strcmp("less", pager))
			string_list_append(&path_list, "-I");

887 888 889 890 891
		if (!strcmp("less", pager) || !strcmp("vi", pager)) {
			struct strbuf buf = STRBUF_INIT;
			strbuf_addf(&buf, "+/%s%s",
					strcmp("less", pager) ? "" : "*",
					opt.pattern_list->pattern);
892
			string_list_append(&path_list, buf.buf);
893 894 895 896
			strbuf_detach(&buf, NULL);
		}
	}

897
	if (!show_in_pager && !opt.status_only)
898 899
		setup_pager();

900
	if (!use_index && (untracked || cached))
901
		die(_("--cached or --untracked cannot be used with --no-index."));
902

903 904
	if (!use_index || untracked) {
		int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
J
Junio C Hamano 已提交
905
		if (list.nr)
906
			die(_("--no-index or --untracked cannot be used with revs."));
907
		hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
908
	} else if (0 <= opt_exclude) {
909
		die(_("--[no-]exclude-standard cannot be used for tracked contents."));
910
	} else if (!list.nr) {
911 912
		if (!cached)
			setup_work_tree();
F
Fredrik Kuivinen 已提交
913

914
		hit = grep_cache(&opt, &pathspec, cached);
915 916
	} else {
		if (cached)
917
			die(_("both --cached and trees are given."));
918
		hit = grep_objects(&opt, &pathspec, &list);
J
Junio C Hamano 已提交
919
	}
F
Fredrik Kuivinen 已提交
920

921
	if (num_threads)
F
Fredrik Kuivinen 已提交
922
		hit |= wait_all();
923 924
	if (hit && show_in_pager)
		run_pager(&opt, prefix);
925
	free_grep_patterns(&opt);
J
Junio C Hamano 已提交
926 927
	return !hit;
}