log.c 37.7 KB
Newer Older
1 2 3 4 5 6 7
/*
 * Builtin "git log" and related commands (show, whatchanged)
 *
 * (C) Copyright 2006 Linus Torvalds
 *		 2006 Junio Hamano
 */
#include "cache.h"
8
#include "color.h"
9 10 11 12
#include "commit.h"
#include "diff.h"
#include "revision.h"
#include "log-tree.h"
13
#include "builtin.h"
14
#include "tag.h"
L
Linus Torvalds 已提交
15
#include "reflog-walk.h"
16
#include "patch-ids.h"
17
#include "run-command.h"
18
#include "shortlog.h"
19
#include "remote.h"
20
#include "string-list.h"
21
#include "parse-options.h"
22

H
Heikki Orsila 已提交
23 24 25
/* Set a default date-time format for git log ("log.date" config variable) */
static const char *default_date_mode = NULL;

26
static int default_show_root = 1;
J
Junio C Hamano 已提交
27
static int decoration_style;
28
static const char *fmt_patch_subject_prefix = "PATCH";
29
static const char *fmt_pretty;
30

31 32 33 34
static const char * const builtin_log_usage =
	"git log [<options>] [<since>..<until>] [[--] <path>...]\n"
	"   or: git show [options] <object>...";

J
Junio C Hamano 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
static int parse_decoration_style(const char *var, const char *value)
{
	switch (git_config_maybe_bool(var, value)) {
	case 1:
		return DECORATE_SHORT_REFS;
	case 0:
		return 0;
	default:
		break;
	}
	if (!strcmp(value, "full"))
		return DECORATE_FULL_REFS;
	else if (!strcmp(value, "short"))
		return DECORATE_SHORT_REFS;
	return -1;
}

52
static void cmd_log_init(int argc, const char **argv, const char *prefix,
53
			 struct rev_info *rev, struct setup_revision_opt *opt)
54
{
J
Junio C Hamano 已提交
55
	int i;
56
	int decoration_given = 0;
57
	struct userformat_want w;
J
Junio C Hamano 已提交
58

59 60
	rev->abbrev = DEFAULT_ABBREV;
	rev->commit_format = CMIT_FMT_DEFAULT;
61
	if (fmt_pretty)
62
		get_commit_format(fmt_pretty, rev);
63
	rev->verbose_header = 1;
64
	DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
65
	rev->show_root_diff = default_show_root;
66
	rev->subject_prefix = fmt_patch_subject_prefix;
J
Jeff King 已提交
67
	DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
H
Heikki Orsila 已提交
68 69 70 71

	if (default_date_mode)
		rev->date_mode = parse_date_format(default_date_mode);

72 73 74 75 76 77
	/*
	 * Check for -h before setup_revisions(), or "git log -h" will
	 * fail when run without a git directory.
	 */
	if (argc == 2 && !strcmp(argv[1], "-h"))
		usage(builtin_log_usage);
78
	argc = setup_revisions(argc, argv, rev, opt);
H
Heikki Orsila 已提交
79

80 81 82 83
	memset(&w, 0, sizeof(w));
	userformat_find_requirements(NULL, &w);

	if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
84
		rev->show_notes = 1;
85 86
	if (rev->show_notes)
		init_display_notes(&rev->notes_opt);
87

88 89
	if (rev->diffopt.pickaxe || rev->diffopt.filter)
		rev->always_show_header = 0;
90
	if (DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES)) {
91 92 93 94
		rev->always_show_header = 0;
		if (rev->diffopt.nr_paths != 1)
			usage("git logs can only follow renames on one pathname at a time");
	}
J
Junio C Hamano 已提交
95 96
	for (i = 1; i < argc; i++) {
		const char *arg = argv[i];
97
		if (!strcmp(arg, "--decorate")) {
98
			decoration_style = DECORATE_SHORT_REFS;
99
			decoration_given = 1;
100 101
		} else if (!prefixcmp(arg, "--decorate=")) {
			const char *v = skip_prefix(arg, "--decorate=");
J
Junio C Hamano 已提交
102 103
			decoration_style = parse_decoration_style(arg, v);
			if (decoration_style < 0)
104
				die("invalid --decorate option: %s", arg);
105
			decoration_given = 1;
J
Junio C Hamano 已提交
106 107
		} else if (!strcmp(arg, "--no-decorate")) {
			decoration_style = 0;
108 109
		} else if (!strcmp(arg, "--source")) {
			rev->show_source = 1;
110 111
		} else if (!strcmp(arg, "-h")) {
			usage(builtin_log_usage);
112
		} else
J
Junio C Hamano 已提交
113 114
			die("unrecognized argument: %s", arg);
	}
115 116

	/*
117
	 * defeat log.decorate configuration interacting with --pretty=raw
118 119
	 * from the command line.
	 */
120 121
	if (!decoration_given && rev->pretty_given
	    && rev->commit_format == CMIT_FMT_RAW)
122 123
		decoration_style = 0;

124 125 126 127
	if (decoration_style) {
		rev->show_decorations = 1;
		load_ref_decorations(decoration_style);
	}
128
	setup_pager();
129 130
}

L
Linus Torvalds 已提交
131 132 133 134 135 136 137 138 139 140 141 142
/*
 * This gives a rough estimate for how many commits we
 * will print out in the list.
 */
static int estimate_commit_count(struct rev_info *rev, struct commit_list *list)
{
	int n = 0;

	while (list) {
		struct commit *commit = list->item;
		unsigned int flags = commit->object.flags;
		list = list->next;
143
		if (!(flags & (TREESAME | UNINTERESTING)))
L
Linus Torvalds 已提交
144
			n++;
L
Linus Torvalds 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
	}
	return n;
}

static void show_early_header(struct rev_info *rev, const char *stage, int nr)
{
	if (rev->shown_one) {
		rev->shown_one = 0;
		if (rev->commit_format != CMIT_FMT_ONELINE)
			putchar(rev->diffopt.line_termination);
	}
	printf("Final output: %d %s\n", nr, stage);
}

159
static struct itimerval early_output_timer;
L
Linus Torvalds 已提交
160

161 162 163
static void log_show_early(struct rev_info *revs, struct commit_list *list)
{
	int i = revs->early_output;
L
Linus Torvalds 已提交
164
	int show_header = 1;
165 166 167 168

	sort_in_topological_order(&list, revs->lifo);
	while (list && i) {
		struct commit *commit = list->item;
L
Linus Torvalds 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
		switch (simplify_commit(revs, commit)) {
		case commit_show:
			if (show_header) {
				int n = estimate_commit_count(revs, list);
				show_early_header(revs, "incomplete", n);
				show_header = 0;
			}
			log_tree_commit(revs, commit);
			i--;
			break;
		case commit_ignore:
			break;
		case commit_error:
			return;
		}
184 185
		list = list->next;
	}
L
Linus Torvalds 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

	/* Did we already get enough commits for the early output? */
	if (!i)
		return;

	/*
	 * ..if no, then repeat it twice a second until we
	 * do.
	 *
	 * NOTE! We don't use "it_interval", because if the
	 * reader isn't listening, we want our output to be
	 * throttled by the writing, and not have the timer
	 * trigger every second even if we're blocked on a
	 * reader!
	 */
	early_output_timer.it_value.tv_sec = 0;
	early_output_timer.it_value.tv_usec = 500000;
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
}

static void early_output(int signal)
{
	show_early_output = log_show_early;
}

static void setup_early_output(struct rev_info *rev)
{
	struct sigaction sa;

	/*
	 * Set up the signal handler, minimally intrusively:
	 * we only set a single volatile integer word (not
	 * using sigatomic_t - trying to avoid unnecessary
	 * system dependencies and headers), and using
	 * SA_RESTART.
	 */
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = early_output;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	sigaction(SIGALRM, &sa, NULL);

	/*
	 * If we can get the whole output in less than a
	 * tenth of a second, don't even bother doing the
	 * early-output thing..
	 *
	 * This is a one-time-only trigger.
	 */
L
Linus Torvalds 已提交
235 236 237
	early_output_timer.it_value.tv_sec = 0;
	early_output_timer.it_value.tv_usec = 100000;
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
238 239 240 241
}

static void finish_early_output(struct rev_info *rev)
{
L
Linus Torvalds 已提交
242
	int n = estimate_commit_count(rev, rev->commits);
243
	signal(SIGALRM, SIG_IGN);
L
Linus Torvalds 已提交
244
	show_early_header(rev, "done", n);
245 246
}

247 248 249
static int cmd_log_walk(struct rev_info *rev)
{
	struct commit *commit;
250

251 252 253
	if (rev->early_output)
		setup_early_output(rev);

254 255
	if (prepare_revision_walk(rev))
		die("revision walk setup failed");
256 257 258 259

	if (rev->early_output)
		finish_early_output(rev);

260
	/*
261 262 263
	 * For --check and --exit-code, the exit code is based on CHECK_FAILED
	 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
	 * retain that state information if replacing rev->diffopt in this loop
264
	 */
265 266
	while ((commit = get_revision(rev)) != NULL) {
		log_tree_commit(rev, commit);
267 268 269 270 271
		if (!rev->reflog_info) {
			/* we allow cycles in reflog ancestry */
			free(commit->buffer);
			commit->buffer = NULL;
		}
L
Linus Torvalds 已提交
272 273
		free_commit_list(commit->parents);
		commit->parents = NULL;
274
	}
275 276 277 278
	if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
	    DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
		return 02;
	}
279
	return diff_result_code(&rev->diffopt, 0);
280 281
}

282
static int git_log_config(const char *var, const char *value, void *cb)
283
{
284 285
	if (!strcmp(var, "format.pretty"))
		return git_config_string(&fmt_pretty, var, value);
286 287
	if (!strcmp(var, "format.subjectprefix"))
		return git_config_string(&fmt_patch_subject_prefix, var, value);
H
Heikki Orsila 已提交
288 289
	if (!strcmp(var, "log.date"))
		return git_config_string(&default_date_mode, var, value);
290
	if (!strcmp(var, "log.decorate")) {
J
Junio C Hamano 已提交
291 292 293
		decoration_style = parse_decoration_style(var, value);
		if (decoration_style < 0)
			decoration_style = 0; /* maybe warn? */
294 295
		return 0;
	}
296 297 298 299
	if (!strcmp(var, "log.showroot")) {
		default_show_root = git_config_bool(var, value);
		return 0;
	}
300 301 302
	if (!prefixcmp(var, "color.decorate."))
		return parse_decorate_color_config(var, 15, value);

303
	return git_diff_ui_config(var, value, cb);
304 305
}

306
int cmd_whatchanged(int argc, const char **argv, const char *prefix)
307 308
{
	struct rev_info rev;
309
	struct setup_revision_opt opt;
310

311
	git_config(git_log_config, NULL);
312 313 314 315

	if (diff_use_color_default == -1)
		diff_use_color_default = git_use_color_default;

316
	init_revisions(&rev, prefix);
317
	rev.diff = 1;
L
Linus Torvalds 已提交
318
	rev.simplify_history = 0;
319 320 321
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
	cmd_log_init(argc, argv, prefix, &rev, &opt);
322 323 324
	if (!rev.diffopt.output_format)
		rev.diffopt.output_format = DIFF_FORMAT_RAW;
	return cmd_log_walk(&rev);
325 326
}

327 328
static void show_tagger(char *buf, int len, struct rev_info *rev)
{
329
	struct strbuf out = STRBUF_INIT;
330

331
	pp_user_info("Tagger", rev->commit_format, &out, buf, rev->date_mode,
332
		get_log_output_encoding());
333
	printf("%s", out.buf);
334
	strbuf_release(&out);
335 336 337 338
}

static int show_object(const unsigned char *sha1, int show_tag_object,
	struct rev_info *rev)
339 340
{
	unsigned long size;
341 342
	enum object_type type;
	char *buf = read_sha1_file(sha1, &type, &size);
343 344 345 346 347
	int offset = 0;

	if (!buf)
		return error("Could not read object %s", sha1_to_hex(sha1));

348 349 350
	if (show_tag_object)
		while (offset < size && buf[offset] != '\n') {
			int new_offset = offset + 1;
351 352
			while (new_offset < size && buf[new_offset++] != '\n')
				; /* do nothing */
353 354 355
			if (!prefixcmp(buf + offset, "tagger "))
				show_tagger(buf + offset + 7,
					    new_offset - offset - 7, rev);
356 357 358 359 360 361 362 363 364 365 366
			offset = new_offset;
		}

	if (offset < size)
		fwrite(buf + offset, size - offset, 1, stdout);
	free(buf);
	return 0;
}

static int show_tree_object(const unsigned char *sha1,
		const char *base, int baselen,
367
		const char *pathname, unsigned mode, int stage, void *context)
368 369 370 371 372
{
	printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
	return 0;
}

J
Junio C Hamano 已提交
373 374
static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
{
375 376 377 378 379 380 381 382 383
	if (rev->ignore_merges) {
		/* There was no "-m" on the command line */
		rev->ignore_merges = 0;
		if (!rev->first_parent_only && !rev->combine_merges) {
			/* No "--first-parent", "-c", nor "--cc" */
			rev->combine_merges = 1;
			rev->dense_combined_merges = 1;
		}
	}
J
Junio C Hamano 已提交
384 385 386 387
	if (!rev->diffopt.output_format)
		rev->diffopt.output_format = DIFF_FORMAT_PATCH;
}

388
int cmd_show(int argc, const char **argv, const char *prefix)
389 390
{
	struct rev_info rev;
391
	struct object_array_entry *objects;
392
	struct setup_revision_opt opt;
393
	int i, count, ret = 0;
394

395
	git_config(git_log_config, NULL);
396 397 398 399

	if (diff_use_color_default == -1)
		diff_use_color_default = git_use_color_default;

400
	init_revisions(&rev, prefix);
401 402 403
	rev.diff = 1;
	rev.always_show_header = 1;
	rev.no_walk = 1;
404 405
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
J
Junio C Hamano 已提交
406
	opt.tweak = show_rev_tweak_rev;
407
	cmd_log_init(argc, argv, prefix, &rev, &opt);
408 409 410 411 412 413 414 415

	count = rev.pending.nr;
	objects = rev.pending.objects;
	for (i = 0; i < count && !ret; i++) {
		struct object *o = objects[i].item;
		const char *name = objects[i].name;
		switch (o->type) {
		case OBJ_BLOB:
416
			ret = show_object(o->sha1, 0, NULL);
417 418 419 420
			break;
		case OBJ_TAG: {
			struct tag *t = (struct tag *)o;

421 422
			if (rev.shown_one)
				putchar('\n');
423
			printf("%stag %s%s\n",
424
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
425
					t->tag,
426
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
427
			ret = show_object(o->sha1, 1, &rev);
428
			rev.shown_one = 1;
429 430 431 432 433 434 435
			if (ret)
				break;
			o = parse_object(t->tagged->sha1);
			if (!o)
				ret = error("Could not read object %s",
					    sha1_to_hex(t->tagged->sha1));
			objects[i].item = o;
436 437 438 439
			i--;
			break;
		}
		case OBJ_TREE:
440 441
			if (rev.shown_one)
				putchar('\n');
442
			printf("%stree %s%s\n\n",
443
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
444
					name,
445
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
446
			read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
447
					show_tree_object, NULL);
448
			rev.shown_one = 1;
449 450 451 452 453 454 455 456 457 458 459 460 461
			break;
		case OBJ_COMMIT:
			rev.pending.nr = rev.pending.alloc = 0;
			rev.pending.objects = NULL;
			add_object_array(o, name, &rev.pending);
			ret = cmd_log_walk(&rev);
			break;
		default:
			ret = error("Unknown type: %d", o->type);
		}
	}
	free(objects);
	return ret;
462 463
}

L
Linus Torvalds 已提交
464 465 466 467 468 469
/*
 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
 */
int cmd_log_reflog(int argc, const char **argv, const char *prefix)
{
	struct rev_info rev;
470
	struct setup_revision_opt opt;
L
Linus Torvalds 已提交
471

472
	git_config(git_log_config, NULL);
473 474 475 476

	if (diff_use_color_default == -1)
		diff_use_color_default = git_use_color_default;

L
Linus Torvalds 已提交
477 478 479 480
	init_revisions(&rev, prefix);
	init_reflog_walk(&rev.reflog_info);
	rev.abbrev_commit = 1;
	rev.verbose_header = 1;
481 482 483
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
	cmd_log_init(argc, argv, prefix, &rev, &opt);
L
Linus Torvalds 已提交
484 485 486 487 488 489 490

	/*
	 * This means that we override whatever commit format the user gave
	 * on the cmd line.  Sad, but cmd_log_init() currently doesn't
	 * allow us to set a different default.
	 */
	rev.commit_format = CMIT_FMT_ONELINE;
491
	rev.use_terminator = 1;
L
Linus Torvalds 已提交
492 493 494 495 496
	rev.always_show_header = 1;

	return cmd_log_walk(&rev);
}

497
int cmd_log(int argc, const char **argv, const char *prefix)
498 499
{
	struct rev_info rev;
500
	struct setup_revision_opt opt;
501

502
	git_config(git_log_config, NULL);
503 504 505 506

	if (diff_use_color_default == -1)
		diff_use_color_default = git_use_color_default;

507
	init_revisions(&rev, prefix);
508
	rev.always_show_header = 1;
509 510 511
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
	cmd_log_init(argc, argv, prefix, &rev, &opt);
512
	return cmd_log_walk(&rev);
513
}
514

515
/* format-patch */
516

517
static const char *fmt_patch_suffix = ".patch";
518
static int numbered = 0;
519
static int auto_number = 1;
520

521 522
static char *default_attach = NULL;

523 524 525
static struct string_list extra_hdr;
static struct string_list extra_to;
static struct string_list extra_cc;
D
Daniel Barkalow 已提交
526 527 528

static void add_header(const char *value)
{
529
	struct string_list_item *item;
D
Daniel Barkalow 已提交
530
	int len = strlen(value);
531
	while (len && value[len - 1] == '\n')
D
Daniel Barkalow 已提交
532
		len--;
533

D
Daniel Barkalow 已提交
534
	if (!strncasecmp(value, "to: ", 4)) {
535
		item = string_list_append(&extra_to, value + 4);
536 537
		len -= 4;
	} else if (!strncasecmp(value, "cc: ", 4)) {
538
		item = string_list_append(&extra_cc, value + 4);
539 540
		len -= 4;
	} else {
541
		item = string_list_append(&extra_hdr, value);
D
Daniel Barkalow 已提交
542
	}
543 544

	item->string[len] = '\0';
D
Daniel Barkalow 已提交
545 546
}

547 548
#define THREAD_SHALLOW 1
#define THREAD_DEEP 2
549 550 551
static int thread;
static int do_signoff;
static const char *signature = git_version_string;
552

553
static int git_format_config(const char *var, const char *value, void *cb)
554 555
{
	if (!strcmp(var, "format.headers")) {
556 557
		if (!value)
			die("format.headers without value");
D
Daniel Barkalow 已提交
558
		add_header(value);
559 560
		return 0;
	}
561 562
	if (!strcmp(var, "format.suffix"))
		return git_config_string(&fmt_patch_suffix, var, value);
563 564 565
	if (!strcmp(var, "format.to")) {
		if (!value)
			return config_error_nonbool(var);
566
		string_list_append(&extra_to, value);
567 568
		return 0;
	}
569 570 571
	if (!strcmp(var, "format.cc")) {
		if (!value)
			return config_error_nonbool(var);
572
		string_list_append(&extra_cc, value);
573 574
		return 0;
	}
575
	if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
576 577
		return 0;
	}
578
	if (!strcmp(var, "format.numbered")) {
579
		if (value && !strcasecmp(value, "auto")) {
580 581 582 583
			auto_number = 1;
			return 0;
		}
		numbered = git_config_bool(var, value);
584
		auto_number = auto_number && numbered;
585 586
		return 0;
	}
587 588 589 590 591 592 593
	if (!strcmp(var, "format.attach")) {
		if (value && *value)
			default_attach = xstrdup(value);
		else
			default_attach = xstrdup(git_version_string);
		return 0;
	}
594 595 596 597 598 599 600 601 602 603 604 605
	if (!strcmp(var, "format.thread")) {
		if (value && !strcasecmp(value, "deep")) {
			thread = THREAD_DEEP;
			return 0;
		}
		if (value && !strcasecmp(value, "shallow")) {
			thread = THREAD_SHALLOW;
			return 0;
		}
		thread = git_config_bool(var, value) && THREAD_SHALLOW;
		return 0;
	}
606 607 608 609
	if (!strcmp(var, "format.signoff")) {
		do_signoff = git_config_bool(var, value);
		return 0;
	}
610 611
	if (!strcmp(var, "format.signature"))
		return git_config_string(&signature, var, value);
612

613
	return git_log_config(var, value, cb);
614 615
}

616
static FILE *realstdout = NULL;
617
static const char *output_directory = NULL;
618
static int outdir_offset;
619

620
static int reopen_stdout(struct commit *commit, struct rev_info *rev)
621
{
622
	struct strbuf filename = STRBUF_INIT;
623
	int suffix_len = strlen(fmt_patch_suffix) + 1;
624

625
	if (output_directory) {
626 627 628
		strbuf_addstr(&filename, output_directory);
		if (filename.len >=
		    PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
629
			return error("name of output directory is too long");
630 631
		if (filename.buf[filename.len - 1] != '/')
			strbuf_addch(&filename, '/');
632
	}
633

634
	get_patch_filename(commit, rev->nr, fmt_patch_suffix, &filename);
635

636
	if (!DIFF_OPT_TST(&rev->diffopt, QUICK))
637
		fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
N
Nate Case 已提交
638

639 640
	if (freopen(filename.buf, "w", stdout) == NULL)
		return error("Cannot open patch file %s", filename.buf);
641

642
	strbuf_release(&filename);
643
	return 0;
644 645
}

646
static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
{
	struct rev_info check_rev;
	struct commit *commit;
	struct object *o1, *o2;
	unsigned flags1, flags2;

	if (rev->pending.nr != 2)
		die("Need exactly one range.");

	o1 = rev->pending.objects[0].item;
	flags1 = o1->flags;
	o2 = rev->pending.objects[1].item;
	flags2 = o2->flags;

	if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
		die("Not a range.");

664
	init_patch_ids(ids);
665 666

	/* given a range a..b get all patch ids for b..a */
667
	init_revisions(&check_rev, prefix);
668 669 670 671
	o1->flags ^= UNINTERESTING;
	o2->flags ^= UNINTERESTING;
	add_pending_object(&check_rev, o1, "o1");
	add_pending_object(&check_rev, o2, "o2");
672 673
	if (prepare_revision_walk(&check_rev))
		die("revision walk setup failed");
674 675 676 677 678 679

	while ((commit = get_revision(&check_rev)) != NULL) {
		/* ignore merges */
		if (commit->parents && commit->parents->next)
			continue;

680
		add_commit_patch_id(commit, ids);
681 682 683
	}

	/* reset for next revision walk */
684 685 686 687
	clear_commit_marks((struct commit *)o1,
			SEEN | UNINTERESTING | SHOWN | ADDED);
	clear_commit_marks((struct commit *)o2,
			SEEN | UNINTERESTING | SHOWN | ADDED);
688 689 690 691
	o1->flags = flags1;
	o2->flags = flags2;
}

692
static void gen_message_id(struct rev_info *info, char *base)
693
{
694
	const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME);
695 696
	const char *email_start = strrchr(committer, '<');
	const char *email_end = strrchr(committer, '>');
697
	struct strbuf buf = STRBUF_INIT;
698
	if (!email_start || !email_end || email_start > email_end - 1)
699
		die("Could not extract email from committer identity.");
700 701 702 703
	strbuf_addf(&buf, "%s.%lu.git.%.*s", base,
		    (unsigned long) time(NULL),
		    (int)(email_end - email_start - 1), email_start + 1);
	info->message_id = strbuf_detach(&buf, NULL);
704 705
}

706 707 708 709 710 711
static void print_signature(void)
{
	if (signature && *signature)
		printf("-- \n%s\n\n", signature);
}

712 713 714 715
static void make_cover_letter(struct rev_info *rev, int use_stdout,
			      int numbered, int numbered_files,
			      struct commit *origin,
			      int nr, struct commit **list, struct commit *head)
716 717 718 719 720 721
{
	const char *committer;
	const char *subject_start = NULL;
	const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
	const char *msg;
	const char *extra_headers = rev->extra_headers;
722
	struct shortlog log;
723
	struct strbuf sb = STRBUF_INIT;
724
	int i;
725
	const char *encoding = "UTF-8";
726
	struct diff_options opts;
J
Junio C Hamano 已提交
727
	int need_8bit_cte = 0;
728
	struct commit *commit = NULL;
729 730 731 732

	if (rev->commit_format != CMIT_FMT_EMAIL)
		die("Cover letter needs email format");

733
	committer = git_committer_info(0);
734

735 736 737 738 739 740 741 742 743 744 745 746 747
	if (!numbered_files) {
		/*
		 * We fake a commit for the cover letter so we get the filename
		 * desired.
		 */
		commit = xcalloc(1, sizeof(*commit));
		commit->buffer = xmalloc(400);
		snprintf(commit->buffer, 400,
			"tree 0000000000000000000000000000000000000000\n"
			"parent %s\n"
			"author %s\n"
			"committer %s\n\n"
			"cover letter\n",
748
			sha1_to_hex(head->object.sha1), committer, committer);
749 750 751
	}

	if (!use_stdout && reopen_stdout(commit, rev))
752 753
		return;

754
	if (commit) {
755

756 757 758
		free(commit->buffer);
		free(commit);
	}
759

760
	log_write_email_headers(rev, head, &subject_start, &extra_headers,
J
Junio C Hamano 已提交
761
				&need_8bit_cte);
762

763 764 765 766
	for (i = 0; !need_8bit_cte && i < nr; i++)
		if (has_non_ascii(list[i]->buffer))
			need_8bit_cte = 1;

767 768 769 770
	msg = body;
	pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822,
		     encoding);
	pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers,
J
Junio C Hamano 已提交
771
		      encoding, need_8bit_cte);
772 773 774 775 776
	pp_remainder(CMIT_FMT_EMAIL, &msg, &sb, 0);
	printf("%s\n", sb.buf);

	strbuf_release(&sb);

777
	shortlog_init(&log);
778 779 780 781
	log.wrap_lines = 1;
	log.wrap = 72;
	log.in1 = 2;
	log.in2 = 4;
782 783 784 785 786
	for (i = 0; i < nr; i++)
		shortlog_add_commit(&log, list[i]);

	shortlog_output(&log);

787
	/*
788
	 * We can only do diffstat with a unique reference point
789 790 791 792
	 */
	if (!origin)
		return;

793 794
	memcpy(&opts, &rev->diffopt, sizeof(opts));
	opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
795

796 797 798 799 800 801 802
	diff_setup_done(&opts);

	diff_tree_sha1(origin->tree->object.sha1,
		       head->tree->object.sha1,
		       "", &opts);
	diffcore_std(&opts);
	diff_flush(&opts);
803 804

	printf("\n");
805
	print_signature();
806 807
}

808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
static const char *clean_message_id(const char *msg_id)
{
	char ch;
	const char *a, *z, *m;

	m = msg_id;
	while ((ch = *m) && (isspace(ch) || (ch == '<')))
		m++;
	a = m;
	z = NULL;
	while ((ch = *m)) {
		if (!isspace(ch) && (ch != '>'))
			z = m;
		m++;
	}
	if (!z)
		die("insane in-reply-to: %s", msg_id);
	if (++z == m)
		return a;
P
Pierre Habouzit 已提交
827
	return xmemdupz(a, z - a);
828 829
}

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
static const char *set_outdir(const char *prefix, const char *output_directory)
{
	if (output_directory && is_absolute_path(output_directory))
		return output_directory;

	if (!prefix || !*prefix) {
		if (output_directory)
			return output_directory;
		/* The user did not explicitly ask for "./" */
		outdir_offset = 2;
		return "./";
	}

	outdir_offset = strlen(prefix);
	if (!output_directory)
		return prefix;

	return xstrdup(prefix_filename(prefix, outdir_offset,
				       output_directory));
}

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
static const char * const builtin_format_patch_usage[] = {
	"git format-patch [options] [<since> | <revision range>]",
	NULL
};

static int keep_subject = 0;

static int keep_callback(const struct option *opt, const char *arg, int unset)
{
	((struct rev_info *)opt->value)->total = -1;
	keep_subject = 1;
	return 0;
}

static int subject_prefix = 0;

static int subject_prefix_callback(const struct option *opt, const char *arg,
			    int unset)
{
	subject_prefix = 1;
	((struct rev_info *)opt->value)->subject_prefix = arg;
	return 0;
}

875 876
static int numbered_cmdline_opt = 0;

877 878 879
static int numbered_callback(const struct option *opt, const char *arg,
			     int unset)
{
880
	*(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
	if (unset)
		auto_number =  0;
	return 0;
}

static int no_numbered_callback(const struct option *opt, const char *arg,
				int unset)
{
	return numbered_callback(opt, arg, 1);
}

static int output_directory_callback(const struct option *opt, const char *arg,
			      int unset)
{
	const char **dir = (const char **)opt->value;
	if (*dir)
		die("Two output directories?");
	*dir = arg;
	return 0;
}

static int thread_callback(const struct option *opt, const char *arg, int unset)
{
	int *thread = (int *)opt->value;
	if (unset)
		*thread = 0;
	else if (!arg || !strcmp(arg, "shallow"))
		*thread = THREAD_SHALLOW;
	else if (!strcmp(arg, "deep"))
		*thread = THREAD_DEEP;
	else
		return 1;
	return 0;
}

static int attach_callback(const struct option *opt, const char *arg, int unset)
{
	struct rev_info *rev = (struct rev_info *)opt->value;
	if (unset)
		rev->mime_boundary = NULL;
	else if (arg)
		rev->mime_boundary = arg;
	else
		rev->mime_boundary = git_version_string;
	rev->no_inline = unset ? 0 : 1;
	return 0;
}

static int inline_callback(const struct option *opt, const char *arg, int unset)
{
	struct rev_info *rev = (struct rev_info *)opt->value;
	if (unset)
		rev->mime_boundary = NULL;
	else if (arg)
		rev->mime_boundary = arg;
	else
		rev->mime_boundary = git_version_string;
	rev->no_inline = 0;
	return 0;
}

static int header_callback(const struct option *opt, const char *arg, int unset)
{
944 945 946 947 948 949 950
	if (unset) {
		string_list_clear(&extra_hdr, 0);
		string_list_clear(&extra_to, 0);
		string_list_clear(&extra_cc, 0);
	} else {
	    add_header(arg);
	}
951 952 953
	return 0;
}

954 955
static int to_callback(const struct option *opt, const char *arg, int unset)
{
956 957 958
	if (unset)
		string_list_clear(&extra_to, 0);
	else
959
		string_list_append(&extra_to, arg);
960 961 962 963 964
	return 0;
}

static int cc_callback(const struct option *opt, const char *arg, int unset)
{
965 966 967
	if (unset)
		string_list_clear(&extra_cc, 0);
	else
968
		string_list_append(&extra_cc, arg);
969 970 971
	return 0;
}

972
int cmd_format_patch(int argc, const char **argv, const char *prefix)
973 974 975 976
{
	struct commit *commit;
	struct commit **list = NULL;
	struct rev_info rev;
977
	struct setup_revision_opt s_r_opt;
978
	int nr = 0, total, i;
979
	int use_stdout = 0;
980
	int start_number = -1;
981
	int numbered_files = 0;		/* _just_ numbers */
982
	int ignore_if_in_upstream = 0;
983
	int cover_letter = 0;
984
	int boundary_count = 0;
985
	int no_binary_diff = 0;
986
	struct commit *origin = NULL, *head = NULL;
987
	const char *in_reply_to = NULL;
988
	struct patch_ids ids;
J
Junio C Hamano 已提交
989
	char *add_signoff = NULL;
990
	struct strbuf buf = STRBUF_INIT;
991
	int use_patch_format = 0;
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
	const struct option builtin_format_patch_options[] = {
		{ OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
			    "use [PATCH n/m] even with a single patch",
			    PARSE_OPT_NOARG, numbered_callback },
		{ OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
			    "use [PATCH] even with multiple patches",
			    PARSE_OPT_NOARG, no_numbered_callback },
		OPT_BOOLEAN('s', "signoff", &do_signoff, "add Signed-off-by:"),
		OPT_BOOLEAN(0, "stdout", &use_stdout,
			    "print patches to standard out"),
		OPT_BOOLEAN(0, "cover-letter", &cover_letter,
			    "generate a cover letter"),
		OPT_BOOLEAN(0, "numbered-files", &numbered_files,
			    "use simple number sequence for output file names"),
		OPT_STRING(0, "suffix", &fmt_patch_suffix, "sfx",
			    "use <sfx> instead of '.patch'"),
		OPT_INTEGER(0, "start-number", &start_number,
			    "start numbering patches at <n> instead of 1"),
		{ OPTION_CALLBACK, 0, "subject-prefix", &rev, "prefix",
			    "Use [<prefix>] instead of [PATCH]",
			    PARSE_OPT_NONEG, subject_prefix_callback },
		{ OPTION_CALLBACK, 'o', "output-directory", &output_directory,
			    "dir", "store resulting files in <dir>",
			    PARSE_OPT_NONEG, output_directory_callback },
		{ OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
			    "don't strip/add [PATCH]",
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
		OPT_BOOLEAN(0, "no-binary", &no_binary_diff,
			    "don't output binary diffs"),
		OPT_BOOLEAN(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
			    "don't include a patch matching a commit upstream"),
1023 1024 1025
		{ OPTION_BOOLEAN, 'p', "no-stat", &use_patch_format, NULL,
		  "show patch format instead of default (patch + stat)",
		  PARSE_OPT_NONEG | PARSE_OPT_NOARG },
1026 1027
		OPT_GROUP("Messaging"),
		{ OPTION_CALLBACK, 0, "add-header", NULL, "header",
1028
			    "add email header", 0, header_callback },
1029
		{ OPTION_CALLBACK, 0, "to", NULL, "email", "add To: header",
1030
			    0, to_callback },
1031
		{ OPTION_CALLBACK, 0, "cc", NULL, "email", "add Cc: header",
1032
			    0, cc_callback },
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
		OPT_STRING(0, "in-reply-to", &in_reply_to, "message-id",
			    "make first mail a reply to <message-id>"),
		{ OPTION_CALLBACK, 0, "attach", &rev, "boundary",
			    "attach the patch", PARSE_OPT_OPTARG,
			    attach_callback },
		{ OPTION_CALLBACK, 0, "inline", &rev, "boundary",
			    "inline the patch",
			    PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
			    inline_callback },
		{ OPTION_CALLBACK, 0, "thread", &thread, "style",
			    "enable message threading, styles: shallow, deep",
			    PARSE_OPT_OPTARG, thread_callback },
1045 1046
		OPT_STRING(0, "signature", &signature, "signature",
			    "add a signature"),
1047 1048
		OPT_END()
	};
1049

1050 1051 1052
	extra_hdr.strdup_strings = 1;
	extra_to.strdup_strings = 1;
	extra_cc.strdup_strings = 1;
1053
	git_config(git_format_config, NULL);
1054
	init_revisions(&rev, prefix);
1055 1056 1057
	rev.commit_format = CMIT_FMT_EMAIL;
	rev.verbose_header = 1;
	rev.diff = 1;
1058
	rev.no_merges = 1;
1059
	DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1060
	rev.subject_prefix = fmt_patch_subject_prefix;
1061 1062
	memset(&s_r_opt, 0, sizeof(s_r_opt));
	s_r_opt.def = "HEAD";
1063

1064 1065 1066 1067 1068
	if (default_attach) {
		rev.mime_boundary = default_attach;
		rev.no_inline = 1;
	}

1069 1070
	/*
	 * Parse the arguments before setup_revisions(), or something
1071
	 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1072 1073
	 * possibly a valid SHA1.
	 */
1074
	argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1075
			     builtin_format_patch_usage,
1076 1077
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
			     PARSE_OPT_KEEP_DASHDASH);
1078

1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
	if (do_signoff) {
		const char *committer;
		const char *endpos;
		committer = git_committer_info(IDENT_ERROR_ON_NO_NAME);
		endpos = strchr(committer, '>');
		if (!endpos)
			die("bogus committer info %s", committer);
		add_signoff = xmemdupz(committer, endpos - committer + 1);
	}

1089 1090
	for (i = 0; i < extra_hdr.nr; i++) {
		strbuf_addstr(&buf, extra_hdr.items[i].string);
D
Daniel Barkalow 已提交
1091 1092 1093
		strbuf_addch(&buf, '\n');
	}

1094
	if (extra_to.nr)
D
Daniel Barkalow 已提交
1095
		strbuf_addstr(&buf, "To: ");
1096
	for (i = 0; i < extra_to.nr; i++) {
D
Daniel Barkalow 已提交
1097 1098
		if (i)
			strbuf_addstr(&buf, "    ");
1099 1100
		strbuf_addstr(&buf, extra_to.items[i].string);
		if (i + 1 < extra_to.nr)
D
Daniel Barkalow 已提交
1101 1102 1103 1104
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

1105
	if (extra_cc.nr)
D
Daniel Barkalow 已提交
1106
		strbuf_addstr(&buf, "Cc: ");
1107
	for (i = 0; i < extra_cc.nr; i++) {
D
Daniel Barkalow 已提交
1108 1109
		if (i)
			strbuf_addstr(&buf, "    ");
1110 1111
		strbuf_addstr(&buf, extra_cc.items[i].string);
		if (i + 1 < extra_cc.nr)
D
Daniel Barkalow 已提交
1112 1113 1114 1115
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

1116
	rev.extra_headers = strbuf_detach(&buf, NULL);
D
Daniel Barkalow 已提交
1117

1118
	if (start_number < 0)
1119
		start_number = 1;
1120 1121 1122 1123 1124 1125 1126 1127 1128

	/*
	 * If numbered is set solely due to format.numbered in config,
	 * and it would conflict with --keep-subject (-k) from the
	 * command line, reset "numbered".
	 */
	if (numbered && keep_subject && !numbered_cmdline_opt)
		numbered = 0;

1129
	if (numbered && keep_subject)
1130
		die ("-n and -k are mutually exclusive.");
1131 1132
	if (keep_subject && subject_prefix)
		die ("--subject-prefix and -k are mutually exclusive.");
1133

1134
	argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1135 1136
	if (argc > 1)
		die ("unrecognized argument: %s", argv[1]);
1137

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
		die("--name-only does not make sense");
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
		die("--name-status does not make sense");
	if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
		die("--check does not make sense");

	if (!use_patch_format &&
		(!rev.diffopt.output_format ||
		 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
		rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;

	/* Always generate a patch */
	rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
1152

1153
	if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1154
		DIFF_OPT_SET(&rev.diffopt, BINARY);
1155

1156 1157 1158
	if (rev.show_notes)
		init_display_notes(&rev.notes_opt);

1159 1160
	if (!use_stdout)
		output_directory = set_outdir(prefix, output_directory);
1161 1162
	else
		setup_pager();
1163

1164 1165 1166 1167
	if (output_directory) {
		if (use_stdout)
			die("standard output, or directory, which one?");
		if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1168 1169
			die_errno("Could not create directory '%s'",
				  output_directory);
1170 1171
	}

1172
	if (rev.pending.nr == 1) {
1173 1174 1175 1176 1177 1178
		if (rev.max_count < 0 && !rev.show_root_diff) {
			/*
			 * This is traditional behaviour of "git format-patch
			 * origin" that prepares what the origin side still
			 * does not have.
			 */
J
Junio C Hamano 已提交
1179
			rev.pending.objects[0].item->flags |= UNINTERESTING;
1180
			add_head_to_pending(&rev);
J
Junio C Hamano 已提交
1181
		}
1182 1183 1184 1185
		/*
		 * Otherwise, it is "format-patch -22 HEAD", and/or
		 * "format-patch --root HEAD".  The user wants
		 * get_revision() to do the usual traversal.
J
Junio C Hamano 已提交
1186
		 */
1187
	}
1188 1189 1190

	/*
	 * We cannot move this anywhere earlier because we do want to
1191
	 * know if --root was given explicitly from the command line.
1192 1193 1194
	 */
	rev.show_root_diff = 1;

1195 1196 1197 1198 1199
	if (cover_letter) {
		/* remember the range */
		int i;
		for (i = 0; i < rev.pending.nr; i++) {
			struct object *o = rev.pending.objects[i].item;
1200
			if (!(o->flags & UNINTERESTING))
1201 1202 1203 1204 1205 1206
				head = (struct commit *)o;
		}
		/* We can't generate a cover letter without any patches */
		if (!head)
			return 0;
	}
1207

1208 1209 1210 1211 1212 1213 1214
	if (ignore_if_in_upstream) {
		/* Don't say anything if head and upstream are the same. */
		if (rev.pending.nr == 2) {
			struct object_array_entry *o = rev.pending.objects;
			if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
				return 0;
		}
1215
		get_patch_ids(&rev, &ids, prefix);
1216
	}
1217

1218
	if (!use_stdout)
1219
		realstdout = xfdopen(xdup(1), "w");
1220

1221 1222
	if (prepare_revision_walk(&rev))
		die("revision walk setup failed");
1223
	rev.boundary = 1;
1224
	while ((commit = get_revision(&rev)) != NULL) {
1225 1226 1227 1228 1229 1230
		if (commit->object.flags & BOUNDARY) {
			boundary_count++;
			origin = (boundary_count == 1) ? commit : NULL;
			continue;
		}

1231
		if (ignore_if_in_upstream &&
1232
				has_commit_patch_id(commit, &ids))
1233 1234
			continue;

1235
		nr++;
J
Jonas Fonseca 已提交
1236
		list = xrealloc(list, nr * sizeof(list[0]));
1237 1238
		list[nr - 1] = commit;
	}
1239
	total = nr;
1240 1241
	if (!keep_subject && auto_number && total > 1)
		numbered = 1;
1242
	if (numbered)
1243
		rev.total = total + start_number - 1;
1244 1245 1246 1247
	if (in_reply_to || thread || cover_letter)
		rev.ref_message_ids = xcalloc(1, sizeof(struct string_list));
	if (in_reply_to) {
		const char *msgid = clean_message_id(in_reply_to);
1248
		string_list_append(rev.ref_message_ids, msgid);
1249
	}
1250 1251
	rev.numbered_files = numbered_files;
	rev.patch_suffix = fmt_patch_suffix;
1252 1253 1254 1255
	if (cover_letter) {
		if (thread)
			gen_message_id(&rev, "cover");
		make_cover_letter(&rev, use_stdout, numbered, numbered_files,
1256
				  origin, nr, list, head);
1257 1258 1259 1260
		total++;
		start_number--;
	}
	rev.add_signoff = add_signoff;
1261 1262 1263
	while (0 <= --nr) {
		int shown;
		commit = list[nr];
1264
		rev.nr = total - nr + (start_number - 1);
1265
		/* Make the second and subsequent mails replies to the first */
1266
		if (thread) {
1267
			/* Have we already had a message ID? */
1268
			if (rev.message_id) {
1269
				/*
1270 1271 1272 1273 1274 1275
				 * For deep threading: make every mail
				 * a reply to the previous one, no
				 * matter what other options are set.
				 *
				 * For shallow threading:
				 *
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
				 * Without --cover-letter and
				 * --in-reply-to, make every mail a
				 * reply to the one before.
				 *
				 * With --in-reply-to but no
				 * --cover-letter, make every mail a
				 * reply to the <reply-to>.
				 *
				 * With --cover-letter, make every
				 * mail but the cover letter a reply
				 * to the cover letter.  The cover
				 * letter is a reply to the
				 * --in-reply-to, if specified.
1289
				 */
1290 1291
				if (thread == THREAD_SHALLOW
				    && rev.ref_message_ids->nr > 0
1292
				    && (!cover_letter || rev.nr > 1))
1293 1294
					free(rev.message_id);
				else
1295 1296
					string_list_append(rev.ref_message_ids,
							   rev.message_id);
1297
			}
1298
			gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1299
		}
1300

1301 1302
		if (!use_stdout && reopen_stdout(numbered_files ? NULL : commit,
						 &rev))
1303
			die("Failed to create output files");
1304 1305 1306
		shown = log_tree_commit(&rev, commit);
		free(commit->buffer);
		commit->buffer = NULL;
1307 1308 1309 1310 1311 1312 1313 1314 1315

		/* We put one extra blank line between formatted
		 * patches and this flag is used by log-tree code
		 * to see if it needs to emit a LF before showing
		 * the log; when using one file per patch, we do
		 * not want the extra blank line.
		 */
		if (!use_stdout)
			rev.shown_one = 0;
1316 1317 1318 1319 1320 1321
		if (shown) {
			if (rev.mime_boundary)
				printf("\n--%s%s--\n\n\n",
				       mime_boundary_leader,
				       rev.mime_boundary);
			else
1322
				print_signature();
1323
		}
1324 1325
		if (!use_stdout)
			fclose(stdout);
1326 1327
	}
	free(list);
1328 1329 1330
	string_list_clear(&extra_to, 0);
	string_list_clear(&extra_cc, 0);
	string_list_clear(&extra_hdr, 0);
1331 1332
	if (ignore_if_in_upstream)
		free_patch_ids(&ids);
1333 1334 1335
	return 0;
}

R
Rene Scharfe 已提交
1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
{
	unsigned char sha1[20];
	if (get_sha1(arg, sha1) == 0) {
		struct commit *commit = lookup_commit_reference(sha1);
		if (commit) {
			commit->object.flags |= flags;
			add_pending_object(revs, &commit->object, arg);
			return 0;
		}
	}
	return -1;
}

E
Erik Faye-Lund 已提交
1350 1351 1352 1353 1354
static const char * const cherry_usage[] = {
	"git cherry [-v] [<upstream> [<head> [<limit>]]]",
	NULL
};

R
Rene Scharfe 已提交
1355 1356 1357
int cmd_cherry(int argc, const char **argv, const char *prefix)
{
	struct rev_info revs;
1358
	struct patch_ids ids;
R
Rene Scharfe 已提交
1359 1360
	struct commit *commit;
	struct commit_list *list = NULL;
1361
	struct branch *current_branch;
R
Rene Scharfe 已提交
1362 1363 1364
	const char *upstream;
	const char *head = "HEAD";
	const char *limit = NULL;
E
Erik Faye-Lund 已提交
1365
	int verbose = 0, abbrev = 0;
R
Rene Scharfe 已提交
1366

E
Erik Faye-Lund 已提交
1367 1368
	struct option options[] = {
		OPT__ABBREV(&abbrev),
1369
		OPT__VERBOSE(&verbose, "be verbose"),
E
Erik Faye-Lund 已提交
1370 1371
		OPT_END()
	};
R
Rene Scharfe 已提交
1372

E
Erik Faye-Lund 已提交
1373
	argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
1374

R
Rene Scharfe 已提交
1375 1376
	switch (argc) {
	case 3:
E
Erik Faye-Lund 已提交
1377
		limit = argv[2];
R
Rene Scharfe 已提交
1378 1379
		/* FALLTHROUGH */
	case 2:
E
Erik Faye-Lund 已提交
1380 1381 1382 1383
		head = argv[1];
		/* FALLTHROUGH */
	case 1:
		upstream = argv[0];
R
Rene Scharfe 已提交
1384 1385
		break;
	default:
1386 1387 1388 1389 1390 1391 1392
		current_branch = branch_get(NULL);
		if (!current_branch || !current_branch->merge
					|| !current_branch->merge[0]
					|| !current_branch->merge[0]->dst) {
			fprintf(stderr, "Could not find a tracked"
					" remote branch, please"
					" specify <upstream> manually.\n");
E
Erik Faye-Lund 已提交
1393
			usage_with_options(cherry_usage, options);
1394 1395 1396
		}

		upstream = current_branch->merge[0]->dst;
R
Rene Scharfe 已提交
1397 1398 1399 1400 1401 1402
	}

	init_revisions(&revs, prefix);
	revs.diff = 1;
	revs.combine_merges = 0;
	revs.ignore_merges = 1;
1403
	DIFF_OPT_SET(&revs.diffopt, RECURSIVE);
R
Rene Scharfe 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416

	if (add_pending_commit(head, &revs, 0))
		die("Unknown commit %s", head);
	if (add_pending_commit(upstream, &revs, UNINTERESTING))
		die("Unknown commit %s", upstream);

	/* Don't say anything if head and upstream are the same. */
	if (revs.pending.nr == 2) {
		struct object_array_entry *o = revs.pending.objects;
		if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
			return 0;
	}

1417
	get_patch_ids(&revs, &ids, prefix);
R
Rene Scharfe 已提交
1418 1419 1420 1421 1422

	if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
		die("Unknown commit %s", limit);

	/* reverse the list of commits */
1423 1424
	if (prepare_revision_walk(&revs))
		die("revision walk setup failed");
R
Rene Scharfe 已提交
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
	while ((commit = get_revision(&revs)) != NULL) {
		/* ignore merges */
		if (commit->parents && commit->parents->next)
			continue;

		commit_list_insert(commit, &list);
	}

	while (list) {
		char sign = '+';

		commit = list->item;
1437
		if (has_commit_patch_id(commit, &ids))
R
Rene Scharfe 已提交
1438 1439 1440
			sign = '-';

		if (verbose) {
1441
			struct strbuf buf = STRBUF_INIT;
1442
			struct pretty_print_context ctx = {0};
1443
			pretty_print_commit(CMIT_FMT_ONELINE, commit,
1444
					    &buf, &ctx);
R
Rene Scharfe 已提交
1445
			printf("%c %s %s\n", sign,
E
Erik Faye-Lund 已提交
1446 1447
			       find_unique_abbrev(commit->object.sha1, abbrev),
			       buf.buf);
1448
			strbuf_release(&buf);
R
Rene Scharfe 已提交
1449 1450 1451
		}
		else {
			printf("%c %s\n", sign,
E
Erik Faye-Lund 已提交
1452
			       find_unique_abbrev(commit->object.sha1, abbrev));
R
Rene Scharfe 已提交
1453 1454 1455 1456 1457
		}

		list = list->next;
	}

1458
	free_patch_ids(&ids);
R
Rene Scharfe 已提交
1459 1460
	return 0;
}