builtin-log.c 22.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Builtin "git log" and related commands (show, whatchanged)
 *
 * (C) Copyright 2006 Linus Torvalds
 *		 2006 Junio Hamano
 */
#include "cache.h"
#include "commit.h"
#include "diff.h"
#include "revision.h"
#include "log-tree.h"
12
#include "builtin.h"
13
#include "tag.h"
L
Linus Torvalds 已提交
14
#include "reflog-walk.h"
15
#include "patch-ids.h"
16
#include "refs.h"
17

18
static int default_show_root = 1;
19
static const char *fmt_patch_subject_prefix = "PATCH";
20

21 22 23
/* this is in builtin-diff.c */
void add_head(struct rev_info *revs);

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
static void add_name_decoration(const char *prefix, const char *name, struct object *obj)
{
	int plen = strlen(prefix);
	int nlen = strlen(name);
	struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen);
	memcpy(res->name, prefix, plen);
	memcpy(res->name + plen, name, nlen + 1);
	res->next = add_decoration(&name_decoration, obj, res);
}

static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
{
	struct object *obj = parse_object(sha1);
	if (!obj)
		return 0;
	add_name_decoration("", refname, obj);
	while (obj->type == OBJ_TAG) {
		obj = ((struct tag *)obj)->tagged;
		if (!obj)
			break;
		add_name_decoration("tag: ", refname, obj);
	}
	return 0;
}

49
static void cmd_log_init(int argc, const char **argv, const char *prefix,
50 51
		      struct rev_info *rev)
{
J
Junio C Hamano 已提交
52
	int i;
53
	int decorate = 0;
J
Junio C Hamano 已提交
54

55 56 57
	rev->abbrev = DEFAULT_ABBREV;
	rev->commit_format = CMIT_FMT_DEFAULT;
	rev->verbose_header = 1;
58
	rev->diffopt.recursive = 1;
59
	rev->show_root_diff = default_show_root;
60
	rev->subject_prefix = fmt_patch_subject_prefix;
61
	argc = setup_revisions(argc, argv, rev, "HEAD");
62 63
	if (rev->diffopt.pickaxe || rev->diffopt.filter)
		rev->always_show_header = 0;
64 65 66 67 68
	if (rev->diffopt.follow_renames) {
		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 已提交
69 70
	for (i = 1; i < argc; i++) {
		const char *arg = argv[i];
71
		if (!strcmp(arg, "--decorate")) {
72 73 74 75
			if (!decorate)
				for_each_ref(add_ref_decoration, NULL);
			decorate = 1;
		} else
J
Junio C Hamano 已提交
76 77
			die("unrecognized argument: %s", arg);
	}
78 79
}

L
Linus Torvalds 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/*
 * 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;
		if (flags & UNINTERESTING)
			continue;
		if (rev->prune_fn && rev->dense && !(flags & TREECHANGE)) {
			if (commit->parents && !commit->parents->next)
				continue;
		}
		n++;
	}
	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);
}

struct itimerval early_output_timer;

116 117 118
static void log_show_early(struct rev_info *revs, struct commit_list *list)
{
	int i = revs->early_output;
L
Linus Torvalds 已提交
119
	int show_header = 1;
120 121 122 123

	sort_in_topological_order(&list, revs->lifo);
	while (list && i) {
		struct commit *commit = list->item;
L
Linus Torvalds 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
		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;
		}
139 140
		list = list->next;
	}
L
Linus Torvalds 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

	/* 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);
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

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 已提交
190 191 192
	early_output_timer.it_value.tv_sec = 0;
	early_output_timer.it_value.tv_usec = 100000;
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
193 194 195 196
}

static void finish_early_output(struct rev_info *rev)
{
L
Linus Torvalds 已提交
197
	int n = estimate_commit_count(rev, rev->commits);
198
	signal(SIGALRM, SIG_IGN);
L
Linus Torvalds 已提交
199
	show_early_header(rev, "done", n);
200 201
}

202 203 204
static int cmd_log_walk(struct rev_info *rev)
{
	struct commit *commit;
205

206 207 208
	if (rev->early_output)
		setup_early_output(rev);

209
	prepare_revision_walk(rev);
210 211 212 213

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

214 215
	while ((commit = get_revision(rev)) != NULL) {
		log_tree_commit(rev, commit);
216 217 218 219 220
		if (!rev->reflog_info) {
			/* we allow cycles in reflog ancestry */
			free(commit->buffer);
			commit->buffer = NULL;
		}
L
Linus Torvalds 已提交
221 222
		free_commit_list(commit->parents);
		commit->parents = NULL;
223 224 225 226
	}
	return 0;
}

227 228
static int git_log_config(const char *var, const char *value)
{
229 230 231 232 233 234
	if (!strcmp(var, "format.subjectprefix")) {
		if (!value)
			die("format.subjectprefix without value");
		fmt_patch_subject_prefix = xstrdup(value);
		return 0;
	}
235 236 237 238 239 240 241
	if (!strcmp(var, "log.showroot")) {
		default_show_root = git_config_bool(var, value);
		return 0;
	}
	return git_diff_ui_config(var, value);
}

242
int cmd_whatchanged(int argc, const char **argv, const char *prefix)
243 244 245
{
	struct rev_info rev;

246
	git_config(git_log_config);
247
	init_revisions(&rev, prefix);
248
	rev.diff = 1;
L
Linus Torvalds 已提交
249
	rev.simplify_history = 0;
250
	cmd_log_init(argc, argv, prefix, &rev);
251 252 253
	if (!rev.diffopt.output_format)
		rev.diffopt.output_format = DIFF_FORMAT_RAW;
	return cmd_log_walk(&rev);
254 255
}

256 257 258
static int show_object(const unsigned char *sha1, int suppress_header)
{
	unsigned long size;
259 260
	enum object_type type;
	char *buf = read_sha1_file(sha1, &type, &size);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	int offset = 0;

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

	if (suppress_header)
		while (offset < size && buf[offset++] != '\n') {
			int new_offset = offset;
			while (new_offset < size && buf[new_offset++] != '\n')
				; /* do nothing */
			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,
		const char *pathname, unsigned mode, int stage)
{
	printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
	return 0;
}

288
int cmd_show(int argc, const char **argv, const char *prefix)
289 290
{
	struct rev_info rev;
291 292
	struct object_array_entry *objects;
	int i, count, ret = 0;
293

294
	git_config(git_log_config);
295
	init_revisions(&rev, prefix);
296 297 298 299 300 301
	rev.diff = 1;
	rev.combine_merges = 1;
	rev.dense_combined_merges = 1;
	rev.always_show_header = 1;
	rev.ignore_merges = 0;
	rev.no_walk = 1;
302
	cmd_log_init(argc, argv, prefix, &rev);
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

	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:
			ret = show_object(o->sha1, 0);
			break;
		case OBJ_TAG: {
			struct tag *t = (struct tag *)o;

			printf("%stag %s%s\n\n",
					diff_get_color(rev.diffopt.color_diff,
						DIFF_COMMIT),
					t->tag,
					diff_get_color(rev.diffopt.color_diff,
						DIFF_RESET));
			ret = show_object(o->sha1, 1);
			objects[i].item = (struct object *)t->tagged;
			i--;
			break;
		}
		case OBJ_TREE:
			printf("%stree %s%s\n\n",
					diff_get_color(rev.diffopt.color_diff,
						DIFF_COMMIT),
					name,
					diff_get_color(rev.diffopt.color_diff,
						DIFF_RESET));
			read_tree_recursive((struct tree *)o, "", 0, 0, NULL,
					show_tree_object);
			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;
349 350
}

L
Linus Torvalds 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
/*
 * 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;

	git_config(git_log_config);
	init_revisions(&rev, prefix);
	init_reflog_walk(&rev.reflog_info);
	rev.abbrev_commit = 1;
	rev.verbose_header = 1;
	cmd_log_init(argc, argv, prefix, &rev);

	/*
	 * 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;
	rev.always_show_header = 1;

	/*
	 * We get called through "git reflog", so unlike the other log
	 * routines, we need to set up our pager manually..
	 */
	setup_pager();

	return cmd_log_walk(&rev);
}

382
int cmd_log(int argc, const char **argv, const char *prefix)
383 384 385
{
	struct rev_info rev;

386
	git_config(git_log_config);
387
	init_revisions(&rev, prefix);
388
	rev.always_show_header = 1;
389
	cmd_log_init(argc, argv, prefix, &rev);
390
	return cmd_log_walk(&rev);
391
}
392

393 394 395
/* format-patch */
#define FORMAT_PATCH_NAME_MAX 64

396 397 398 399 400 401
static int istitlechar(char c)
{
	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
		(c >= '0' && c <= '9') || c == '.' || c == '_';
}

402 403
static char *extra_headers = NULL;
static int extra_headers_size = 0;
404
static const char *fmt_patch_suffix = ".patch";
405 406 407 408

static int git_format_config(const char *var, const char *value)
{
	if (!strcmp(var, "format.headers")) {
409 410 411 412 413
		int len;

		if (!value)
			die("format.headers without value");
		len = strlen(value);
414
		extra_headers_size += len + 1;
J
Jonas Fonseca 已提交
415
		extra_headers = xrealloc(extra_headers, extra_headers_size);
416 417 418 419
		extra_headers[extra_headers_size - len - 1] = 0;
		strcat(extra_headers, value);
		return 0;
	}
420 421 422 423 424 425
	if (!strcmp(var, "format.suffix")) {
		if (!value)
			die("format.suffix without value");
		fmt_patch_suffix = xstrdup(value);
		return 0;
	}
426
	if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
427 428
		return 0;
	}
429

430
	return git_log_config(var, value);
431 432 433
}


434
static FILE *realstdout = NULL;
435
static const char *output_directory = NULL;
436

437 438
static int reopen_stdout(struct commit *commit, int nr, int keep_subject,
			 int numbered_files)
439
{
440
	char filename[PATH_MAX];
441
	char *sol;
442
	int len = 0;
443
	int suffix_len = strlen(fmt_patch_suffix) + 1;
444

445
	if (output_directory) {
446 447 448 449
		if (strlen(output_directory) >=
		    sizeof(filename) - FORMAT_PATCH_NAME_MAX - suffix_len)
			return error("name of output directory is too long");
		strlcpy(filename, output_directory, sizeof(filename) - suffix_len);
450 451 452 453
		len = strlen(filename);
		if (filename[len - 1] != '/')
			filename[len++] = '/';
	}
454

455 456 457
	if (numbered_files) {
		sprintf(filename + len, "%d", nr);
		len = strlen(filename);
458

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
	} else {
		sprintf(filename + len, "%04d", nr);
		len = strlen(filename);

		sol = strstr(commit->buffer, "\n\n");
		if (sol) {
			int j, space = 1;

			sol += 2;
			/* strip [PATCH] or [PATCH blabla] */
			if (!keep_subject && !prefixcmp(sol, "[PATCH")) {
				char *eos = strchr(sol + 6, ']');
				if (eos) {
					while (isspace(*eos))
						eos++;
					sol = eos;
475
				}
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
			}

			for (j = 0;
			     j < FORMAT_PATCH_NAME_MAX - suffix_len - 5 &&
				     len < sizeof(filename) - suffix_len &&
				     sol[j] && sol[j] != '\n';
			     j++) {
				if (istitlechar(sol[j])) {
					if (space) {
						filename[len++] = '-';
						space = 0;
					}
					filename[len++] = sol[j];
					if (sol[j] == '.')
						while (sol[j + 1] == '.')
							j++;
				} else
					space = 1;
			}
			while (filename[len - 1] == '.'
			       || filename[len - 1] == '-')
				len--;
			filename[len] = 0;
499
		}
500 501 502
		if (len + suffix_len >= sizeof(filename))
			return error("Patch pathname too long");
		strcpy(filename + len, fmt_patch_suffix);
503
	}
504

505
	fprintf(realstdout, "%s\n", filename);
506 507 508
	if (freopen(filename, "w", stdout) == NULL)
		return error("Cannot open patch file %s",filename);

509
	return 0;
510 511
}

512
static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids, const char *prefix)
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
{
	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.");

530
	init_patch_ids(ids);
531 532

	/* given a range a..b get all patch ids for b..a */
533
	init_revisions(&check_rev, prefix);
534 535 536 537 538 539 540 541 542 543 544
	o1->flags ^= UNINTERESTING;
	o2->flags ^= UNINTERESTING;
	add_pending_object(&check_rev, o1, "o1");
	add_pending_object(&check_rev, o2, "o2");
	prepare_revision_walk(&check_rev);

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

545
		add_commit_patch_id(commit, ids);
546 547 548
	}

	/* reset for next revision walk */
549 550 551 552
	clear_commit_marks((struct commit *)o1,
			SEEN | UNINTERESTING | SHOWN | ADDED);
	clear_commit_marks((struct commit *)o2,
			SEEN | UNINTERESTING | SHOWN | ADDED);
553 554 555 556
	o1->flags = flags1;
	o2->flags = flags2;
}

557 558
static void gen_message_id(char *dest, unsigned int length, char *base)
{
559
	const char *committer = git_committer_info(-1);
560 561 562 563
	const char *email_start = strrchr(committer, '<');
	const char *email_end = strrchr(committer, '>');
	if(!email_start || !email_end || email_start > email_end - 1)
		die("Could not extract email from committer identity.");
564 565 566
	snprintf(dest, length, "%s.%lu.git.%.*s", base,
		 (unsigned long) time(NULL),
		 (int)(email_end - email_start - 1), email_start + 1);
567 568
}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
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 已提交
588
	return xmemdupz(a, z - a);
589 590
}

591
int cmd_format_patch(int argc, const char **argv, const char *prefix)
592 593 594 595
{
	struct commit *commit;
	struct commit **list = NULL;
	struct rev_info rev;
596
	int nr = 0, total, i, j;
597
	int use_stdout = 0;
598
	int numbered = 0;
599
	int start_number = -1;
600
	int keep_subject = 0;
601
	int numbered_files = 0;		/* _just_ numbers */
602
	int subject_prefix = 0;
603
	int ignore_if_in_upstream = 0;
604
	int thread = 0;
605
	const char *in_reply_to = NULL;
606
	struct patch_ids ids;
J
Junio C Hamano 已提交
607
	char *add_signoff = NULL;
608 609
	char message_id[1024];
	char ref_message_id[1024];
610

611
	git_config(git_format_config);
612
	init_revisions(&rev, prefix);
613 614 615 616 617
	rev.commit_format = CMIT_FMT_EMAIL;
	rev.verbose_header = 1;
	rev.diff = 1;
	rev.combine_merges = 0;
	rev.ignore_merges = 1;
618 619
	rev.diffopt.msg_sep = "";
	rev.diffopt.recursive = 1;
620

621
	rev.subject_prefix = fmt_patch_subject_prefix;
622 623
	rev.extra_headers = extra_headers;

624 625
	/*
	 * Parse the arguments before setup_revisions(), or something
626
	 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
627 628 629 630
	 * possibly a valid SHA1.
	 */
	for (i = 1, j = 1; i < argc; i++) {
		if (!strcmp(argv[i], "--stdout"))
631
			use_stdout = 1;
632 633 634
		else if (!strcmp(argv[i], "-n") ||
				!strcmp(argv[i], "--numbered"))
			numbered = 1;
635
		else if (!prefixcmp(argv[i], "--start-number="))
636
			start_number = strtol(argv[i] + 15, NULL, 10);
637 638
		else if (!strcmp(argv[i], "--numbered-files"))
			numbered_files = 1;
639 640 641 642 643
		else if (!strcmp(argv[i], "--start-number")) {
			i++;
			if (i == argc)
				die("Need a number for --start-number");
			start_number = strtol(argv[i], NULL, 10);
J
Junio C Hamano 已提交
644 645
		}
		else if (!strcmp(argv[i], "-k") ||
646 647 648
				!strcmp(argv[i], "--keep-subject")) {
			keep_subject = 1;
			rev.total = -1;
J
Junio C Hamano 已提交
649
		}
650 651
		else if (!strcmp(argv[i], "--output-directory") ||
			 !strcmp(argv[i], "-o")) {
652
			i++;
653 654 655 656 657
			if (argc <= i)
				die("Which directory?");
			if (output_directory)
				die("Two output directories?");
			output_directory = argv[i];
658
		}
J
Junio C Hamano 已提交
659 660
		else if (!strcmp(argv[i], "--signoff") ||
			 !strcmp(argv[i], "-s")) {
E
Eric W. Biederman 已提交
661 662 663 664
			const char *committer;
			const char *endpos;
			committer = git_committer_info(1);
			endpos = strchr(committer, '>');
J
Junio C Hamano 已提交
665 666
			if (!endpos)
				die("bogos committer info %s\n", committer);
P
Pierre Habouzit 已提交
667
			add_signoff = xmemdupz(committer, endpos - committer + 1);
J
Junio C Hamano 已提交
668
		}
669
		else if (!strcmp(argv[i], "--attach")) {
670
			rev.mime_boundary = git_version_string;
671 672 673 674 675 676 677 678 679 680 681
			rev.no_inline = 1;
		}
		else if (!prefixcmp(argv[i], "--attach=")) {
			rev.mime_boundary = argv[i] + 9;
			rev.no_inline = 1;
		}
		else if (!strcmp(argv[i], "--inline")) {
			rev.mime_boundary = git_version_string;
			rev.no_inline = 0;
		}
		else if (!prefixcmp(argv[i], "--inline=")) {
682
			rev.mime_boundary = argv[i] + 9;
683 684
			rev.no_inline = 0;
		}
685 686
		else if (!strcmp(argv[i], "--ignore-if-in-upstream"))
			ignore_if_in_upstream = 1;
687 688
		else if (!strcmp(argv[i], "--thread"))
			thread = 1;
689
		else if (!prefixcmp(argv[i], "--in-reply-to="))
690 691 692 693 694 695
			in_reply_to = argv[i] + 14;
		else if (!strcmp(argv[i], "--in-reply-to")) {
			i++;
			if (i == argc)
				die("Need a Message-Id for --in-reply-to");
			in_reply_to = argv[i];
696 697 698 699
		} else if (!prefixcmp(argv[i], "--subject-prefix=")) {
			subject_prefix = 1;
			rev.subject_prefix = argv[i] + 17;
		} else if (!prefixcmp(argv[i], "--suffix="))
700
			fmt_patch_suffix = argv[i] + 9;
701
		else
702
			argv[j++] = argv[i];
703
	}
704 705
	argc = j;

706
	if (start_number < 0)
707
		start_number = 1;
708
	if (numbered && keep_subject)
709
		die ("-n and -k are mutually exclusive.");
710 711
	if (keep_subject && subject_prefix)
		die ("--subject-prefix and -k are mutually exclusive.");
712 713
	if (numbered_files && use_stdout)
		die ("--numbered-files and --stdout are mutually exclusive.");
714

715 716 717
	argc = setup_revisions(argc, argv, &rev, "HEAD");
	if (argc > 1)
		die ("unrecognized argument: %s", argv[1]);
718

719
	if (!rev.diffopt.output_format)
720
		rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY | DIFF_FORMAT_PATCH;
721

722 723 724
	if (!rev.diffopt.text)
		rev.diffopt.binary = 1;

725
	if (!output_directory && !use_stdout)
726 727
		output_directory = prefix;

728 729 730 731 732 733 734 735
	if (output_directory) {
		if (use_stdout)
			die("standard output, or directory, which one?");
		if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
			die("Could not create directory %s",
			    output_directory);
	}

736
	if (rev.pending.nr == 1) {
737 738 739 740 741 742
		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 已提交
743 744 745
			rev.pending.objects[0].item->flags |= UNINTERESTING;
			add_head(&rev);
		}
746 747 748 749
		/*
		 * 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 已提交
750
		 */
751 752
	}

753
	if (ignore_if_in_upstream)
754
		get_patch_ids(&rev, &ids, prefix);
755

756
	if (!use_stdout)
757
		realstdout = xfdopen(xdup(1), "w");
758

759 760
	prepare_revision_walk(&rev);
	while ((commit = get_revision(&rev)) != NULL) {
761 762 763
		/* ignore merges */
		if (commit->parents && commit->parents->next)
			continue;
764 765

		if (ignore_if_in_upstream &&
766
				has_commit_patch_id(commit, &ids))
767 768
			continue;

769
		nr++;
J
Jonas Fonseca 已提交
770
		list = xrealloc(list, nr * sizeof(list[0]));
771 772
		list[nr - 1] = commit;
	}
773
	total = nr;
774
	if (numbered)
775
		rev.total = total + start_number - 1;
J
Junio C Hamano 已提交
776
	rev.add_signoff = add_signoff;
777 778
	if (in_reply_to)
		rev.ref_message_id = clean_message_id(in_reply_to);
779 780 781
	while (0 <= --nr) {
		int shown;
		commit = list[nr];
782
		rev.nr = total - nr + (start_number - 1);
783
		/* Make the second and subsequent mails replies to the first */
784 785 786 787 788 789 790 791 792 793
		if (thread) {
			if (nr == (total - 2)) {
				strncpy(ref_message_id, message_id,
					sizeof(ref_message_id));
				ref_message_id[sizeof(ref_message_id)-1]='\0';
				rev.ref_message_id = ref_message_id;
			}
			gen_message_id(message_id, sizeof(message_id),
				       sha1_to_hex(commit->object.sha1));
			rev.message_id = message_id;
794
		}
795
		if (!use_stdout)
796 797
			if (reopen_stdout(commit, rev.nr, keep_subject,
					  numbered_files))
798
				die("Failed to create output files");
799 800 801
		shown = log_tree_commit(&rev, commit);
		free(commit->buffer);
		commit->buffer = NULL;
802 803 804 805 806 807 808 809 810

		/* 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;
811 812 813 814 815 816 817 818
		if (shown) {
			if (rev.mime_boundary)
				printf("\n--%s%s--\n\n\n",
				       mime_boundary_leader,
				       rev.mime_boundary);
			else
				printf("-- \n%s\n\n", git_version_string);
		}
819 820
		if (!use_stdout)
			fclose(stdout);
821 822
	}
	free(list);
823 824
	if (ignore_if_in_upstream)
		free_patch_ids(&ids);
825 826 827
	return 0;
}

R
Rene Scharfe 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
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;
}

static const char cherry_usage[] =
"git-cherry [-v] <upstream> [<head>] [<limit>]";
int cmd_cherry(int argc, const char **argv, const char *prefix)
{
	struct rev_info revs;
847
	struct patch_ids ids;
R
Rene Scharfe 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	struct commit *commit;
	struct commit_list *list = NULL;
	const char *upstream;
	const char *head = "HEAD";
	const char *limit = NULL;
	int verbose = 0;

	if (argc > 1 && !strcmp(argv[1], "-v")) {
		verbose = 1;
		argc--;
		argv++;
	}

	switch (argc) {
	case 4:
		limit = argv[3];
		/* FALLTHROUGH */
	case 3:
		head = argv[2];
		/* FALLTHROUGH */
	case 2:
		upstream = argv[1];
		break;
	default:
		usage(cherry_usage);
	}

	init_revisions(&revs, prefix);
	revs.diff = 1;
	revs.combine_merges = 0;
	revs.ignore_merges = 1;
	revs.diffopt.recursive = 1;

	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;
	}

893
	get_patch_ids(&revs, &ids, prefix);
R
Rene Scharfe 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

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

	/* reverse the list of commits */
	prepare_revision_walk(&revs);
	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;
912
		if (has_commit_patch_id(commit, &ids))
R
Rene Scharfe 已提交
913 914 915
			sign = '-';

		if (verbose) {
916 917 918
			struct strbuf buf;
			strbuf_init(&buf, 0);
			pretty_print_commit(CMIT_FMT_ONELINE, commit,
919
			                    &buf, 0, NULL, NULL, 0, 0);
R
Rene Scharfe 已提交
920
			printf("%c %s %s\n", sign,
921 922
			       sha1_to_hex(commit->object.sha1), buf.buf);
			strbuf_release(&buf);
R
Rene Scharfe 已提交
923 924 925 926 927 928 929 930 931
		}
		else {
			printf("%c %s\n", sign,
			       sha1_to_hex(commit->object.sha1));
		}

		list = list->next;
	}

932
	free_patch_ids(&ids);
R
Rene Scharfe 已提交
933 934
	return 0;
}