log.c 56.0 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 "config.h"
9
#include "refs.h"
10
#include "object-store.h"
11
#include "color.h"
12 13 14 15
#include "commit.h"
#include "diff.h"
#include "revision.h"
#include "log-tree.h"
16
#include "builtin.h"
17
#include "tag.h"
L
Linus Torvalds 已提交
18
#include "reflog-walk.h"
19
#include "patch-ids.h"
20
#include "run-command.h"
21
#include "shortlog.h"
22
#include "remote.h"
23
#include "string-list.h"
24
#include "parse-options.h"
25
#include "line-log.h"
26
#include "branch.h"
27
#include "streaming.h"
28
#include "version.h"
A
Antoine Pelisse 已提交
29
#include "mailmap.h"
30
#include "gpg-interface.h"
31
#include "progress.h"
32
#include "commit-slab.h"
33
#include "repository.h"
34
#include "commit-reach.h"
35
#include "interdiff.h"
36
#include "range-diff.h"
37

38 39
#define MAIL_DEFAULT_WRAP 72

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

43
static int default_abbrev_commit;
44
static int default_show_root = 1;
45
static int default_follow;
46
static int default_show_signature;
J
Junio C Hamano 已提交
47
static int decoration_style;
48
static int decoration_given;
49
static int use_mailmap_config;
50
static const char *fmt_patch_subject_prefix = "PATCH";
51
static const char *fmt_pretty;
52

53
static const char * const builtin_log_usage[] = {
54
	N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
J
Junio C Hamano 已提交
55
	N_("git show [<options>] <object>..."),
56 57
	NULL
};
58

59 60 61 62 63 64
struct line_opt_callback_data {
	struct rev_info *rev;
	const char *prefix;
	struct string_list args;
};

65 66 67 68 69
static int auto_decoration_style(void)
{
	return (isatty(1) || pager_in_use()) ? DECORATE_SHORT_REFS : 0;
}

70
static int parse_decoration_style(const char *value)
J
Junio C Hamano 已提交
71
{
72
	switch (git_parse_maybe_bool(value)) {
J
Junio C Hamano 已提交
73 74 75 76 77 78 79 80 81 82 83
	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;
84
	else if (!strcmp(value, "auto"))
85
		return auto_decoration_style();
J
Junio C Hamano 已提交
86 87 88
	return -1;
}

89 90 91 92 93
static int decorate_callback(const struct option *opt, const char *arg, int unset)
{
	if (unset)
		decoration_style = 0;
	else if (arg)
94
		decoration_style = parse_decoration_style(arg);
95 96 97 98
	else
		decoration_style = DECORATE_SHORT_REFS;

	if (decoration_style < 0)
99
		die(_("invalid --decorate option: %s"), arg);
100 101 102 103 104 105

	decoration_given = 1;

	return 0;
}

106 107 108 109
static int log_line_range_callback(const struct option *option, const char *arg, int unset)
{
	struct line_opt_callback_data *data = option->value;

110 111
	BUG_ON_OPT_NEG(unset);

112 113 114 115 116 117 118 119 120
	if (!arg)
		return -1;

	data->rev->line_level_traverse = 1;
	string_list_append(&data->args, arg);

	return 0;
}

121 122
static void init_log_defaults(void)
{
123
	init_grep_defaults(the_repository);
124
	init_diff_ui_defaults();
125 126

	decoration_style = auto_decoration_style();
127 128
}

129
static void cmd_log_init_defaults(struct rev_info *rev)
130
{
131
	if (fmt_pretty)
132
		get_commit_format(fmt_pretty, rev);
133
	if (default_follow)
134
		rev->diffopt.flags.default_follow_renames = 1;
135
	rev->verbose_header = 1;
136
	rev->diffopt.flags.recursive = 1;
137
	rev->diffopt.stat_width = -1; /* use full terminal width */
138
	rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
139
	rev->abbrev_commit = default_abbrev_commit;
140
	rev->show_root_diff = default_show_root;
141
	rev->subject_prefix = fmt_patch_subject_prefix;
142
	rev->show_signature = default_show_signature;
143
	rev->diffopt.flags.allow_textconv = 1;
H
Heikki Orsila 已提交
144 145

	if (default_date_mode)
146
		parse_date_format(default_date_mode, &rev->date_mode);
147
}
H
Heikki Orsila 已提交
148

149 150 151 152
static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
			 struct rev_info *rev, struct setup_revision_opt *opt)
{
	struct userformat_want w;
A
Antoine Pelisse 已提交
153
	int quiet = 0, source = 0, mailmap = 0;
154
	static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
155 156 157 158
	static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
	static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
	struct decoration_filter decoration_filter = {&decorate_refs_include,
						      &decorate_refs_exclude};
159
	static struct revision_sources revision_sources;
160 161

	const struct option builtin_log_options[] = {
162
		OPT__QUIET(&quiet, N_("suppress diff output")),
F
Felipe Contreras 已提交
163 164
		OPT_BOOL(0, "source", &source, N_("show source")),
		OPT_BOOL(0, "use-mailmap", &mailmap, N_("Use mail map file")),
165 166 167 168
		OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
				N_("pattern"), N_("only decorate refs that match <pattern>")),
		OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
				N_("pattern"), N_("do not decorate refs that match <pattern>")),
169
		{ OPTION_CALLBACK, 0, "decorate", NULL, NULL, N_("decorate options"),
170
		  PARSE_OPT_OPTARG, decorate_callback},
171
		OPT_CALLBACK('L', NULL, &line_cb, "n,m:file",
172
			     N_("Process line range n,m in file, counting from 1"),
173
			     log_line_range_callback),
174 175 176
		OPT_END()
	};

177 178 179
	line_cb.rev = rev;
	line_cb.prefix = prefix;

180
	mailmap = use_mailmap_config;
181 182 183 184
	argc = parse_options(argc, argv, prefix,
			     builtin_log_options, builtin_log_usage,
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
			     PARSE_OPT_KEEP_DASHDASH);
J
Junio C Hamano 已提交
185

186 187
	if (quiet)
		rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
J
Jeff King 已提交
188
	argc = setup_revisions(argc, argv, rev, opt);
H
Heikki Orsila 已提交
189

190 191
	/* Any arguments at this point are not recognized */
	if (argc > 1)
192
		die(_("unrecognized argument: %s"), argv[1]);
193

194 195 196 197
	memset(&w, 0, sizeof(w));
	userformat_find_requirements(NULL, &w);

	if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
198
		rev->show_notes = 1;
199 200
	if (rev->show_notes)
		init_display_notes(&rev->notes_opt);
201

202 203
	if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
	    rev->diffopt.filter || rev->diffopt.flags.follow_renames)
204
		rev->always_show_header = 0;
205

206 207 208 209
	if (source) {
		init_revision_sources(&revision_sources);
		rev->sources = &revision_sources;
	}
210

A
Antoine Pelisse 已提交
211 212 213 214 215
	if (mailmap) {
		rev->mailmap = xcalloc(1, sizeof(struct string_list));
		read_mailmap(rev->mailmap, NULL);
	}

216 217 218 219 220 221 222 223 224 225
	if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
		/*
		 * "log --pretty=raw" is special; ignore UI oriented
		 * configuration variables such as decoration.
		 */
		if (!decoration_given)
			decoration_style = 0;
		if (!rev->abbrev_commit_given)
			rev->abbrev_commit = 0;
	}
226

227 228
	if (decoration_style) {
		rev->show_decorations = 1;
229
		load_ref_decorations(&decoration_filter, decoration_style);
230
	}
231 232 233 234

	if (rev->line_level_traverse)
		line_log_init(rev, line_cb.prefix, &line_cb.args);

235
	setup_pager();
236 237
}

238 239 240 241 242 243 244
static void cmd_log_init(int argc, const char **argv, const char *prefix,
			 struct rev_info *rev, struct setup_revision_opt *opt)
{
	cmd_log_init_defaults(rev);
	cmd_log_init_finish(argc, argv, prefix, rev, opt);
}

L
Linus Torvalds 已提交
245 246 247 248 249 250 251 252 253 254 255 256
/*
 * 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;
257
		if (!(flags & (TREESAME | UNINTERESTING)))
L
Linus Torvalds 已提交
258
			n++;
L
Linus Torvalds 已提交
259 260 261 262 263 264 265 266 267 268 269
	}
	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);
	}
270
	fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
L
Linus Torvalds 已提交
271 272
}

273
static struct itimerval early_output_timer;
L
Linus Torvalds 已提交
274

275 276
static void log_show_early(struct rev_info *revs, struct commit_list *list)
{
277
	int i = revs->early_output, close_file = revs->diffopt.close_file;
L
Linus Torvalds 已提交
278
	int show_header = 1;
279

280
	revs->diffopt.close_file = 0;
J
Junio C Hamano 已提交
281
	sort_in_topological_order(&list, revs->sort_order);
282 283
	while (list && i) {
		struct commit *commit = list->item;
L
Linus Torvalds 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296
		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:
297 298
			if (close_file)
				fclose(revs->diffopt.file);
L
Linus Torvalds 已提交
299 300
			return;
		}
301 302
		list = list->next;
	}
L
Linus Torvalds 已提交
303 304

	/* Did we already get enough commits for the early output? */
305 306 307
	if (!i) {
		if (close_file)
			fclose(revs->diffopt.file);
L
Linus Torvalds 已提交
308
		return;
309
	}
L
Linus Torvalds 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323

	/*
	 * ..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);
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 349 350 351 352 353 354
}

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 已提交
355 356 357
	early_output_timer.it_value.tv_sec = 0;
	early_output_timer.it_value.tv_usec = 100000;
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
358 359 360 361
}

static void finish_early_output(struct rev_info *rev)
{
L
Linus Torvalds 已提交
362
	int n = estimate_commit_count(rev, rev->commits);
363
	signal(SIGALRM, SIG_IGN);
L
Linus Torvalds 已提交
364
	show_early_header(rev, "done", n);
365 366
}

367 368 369
static int cmd_log_walk(struct rev_info *rev)
{
	struct commit *commit;
370
	int saved_nrl = 0;
371
	int saved_dcctc = 0, close_file = rev->diffopt.close_file;
372

373 374 375
	if (rev->early_output)
		setup_early_output(rev);

376
	if (prepare_revision_walk(rev))
377
		die(_("revision walk setup failed"));
378 379 380 381

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

382
	/*
383 384 385
	 * 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
386
	 */
387
	rev->diffopt.close_file = 0;
388
	while ((commit = get_revision(rev)) != NULL) {
J
Junio C Hamano 已提交
389
		if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
390 391 392 393 394
			/*
			 * We decremented max_count in get_revision,
			 * but we didn't actually show the commit.
			 */
			rev->max_count++;
395
		if (!rev->reflog_info) {
396 397 398 399
			/*
			 * We may show a given commit multiple times when
			 * walking the reflogs.
			 */
400
			free_commit_buffer(commit);
401 402
			free_commit_list(commit->parents);
			commit->parents = NULL;
403
		}
404 405 406 407
		if (saved_nrl < rev->diffopt.needed_rename_limit)
			saved_nrl = rev->diffopt.needed_rename_limit;
		if (rev->diffopt.degraded_cc_to_c)
			saved_dcctc = 1;
408
	}
409 410
	rev->diffopt.degraded_cc_to_c = saved_dcctc;
	rev->diffopt.needed_rename_limit = saved_nrl;
411 412
	if (close_file)
		fclose(rev->diffopt.file);
413

414
	if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
415
	    rev->diffopt.flags.check_failed) {
416 417
		return 02;
	}
418
	return diff_result_code(&rev->diffopt, 0);
419 420
}

421
static int git_log_config(const char *var, const char *value, void *cb)
422
{
423 424
	const char *slot_name;

425 426
	if (!strcmp(var, "format.pretty"))
		return git_config_string(&fmt_pretty, var, value);
427 428
	if (!strcmp(var, "format.subjectprefix"))
		return git_config_string(&fmt_patch_subject_prefix, var, value);
429 430 431 432
	if (!strcmp(var, "log.abbrevcommit")) {
		default_abbrev_commit = git_config_bool(var, value);
		return 0;
	}
H
Heikki Orsila 已提交
433 434
	if (!strcmp(var, "log.date"))
		return git_config_string(&default_date_mode, var, value);
435
	if (!strcmp(var, "log.decorate")) {
436
		decoration_style = parse_decoration_style(value);
J
Junio C Hamano 已提交
437 438
		if (decoration_style < 0)
			decoration_style = 0; /* maybe warn? */
439 440
		return 0;
	}
441 442 443 444
	if (!strcmp(var, "log.showroot")) {
		default_show_root = git_config_bool(var, value);
		return 0;
	}
445 446 447 448
	if (!strcmp(var, "log.follow")) {
		default_follow = git_config_bool(var, value);
		return 0;
	}
449
	if (skip_prefix(var, "color.decorate.", &slot_name))
450
		return parse_decorate_color_config(var, slot_name, value);
451 452 453 454
	if (!strcmp(var, "log.mailmap")) {
		use_mailmap_config = git_config_bool(var, value);
		return 0;
	}
455 456 457 458
	if (!strcmp(var, "log.showsignature")) {
		default_show_signature = git_config_bool(var, value);
		return 0;
	}
459

J
Junio C Hamano 已提交
460 461
	if (grep_config(var, value, cb) < 0)
		return -1;
462
	if (git_gpg_config(var, value, cb) < 0)
J
Junio C Hamano 已提交
463
		return -1;
464
	return git_diff_ui_config(var, value, cb);
465 466
}

467
int cmd_whatchanged(int argc, const char **argv, const char *prefix)
468 469
{
	struct rev_info rev;
470
	struct setup_revision_opt opt;
471

472
	init_log_defaults();
473
	git_config(git_log_config, NULL);
474

475
	repo_init_revisions(the_repository, &rev, prefix);
476
	rev.diff = 1;
L
Linus Torvalds 已提交
477
	rev.simplify_history = 0;
478 479
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
480
	opt.revarg_opt = REVARG_COMMITTISH;
481
	cmd_log_init(argc, argv, prefix, &rev, &opt);
482 483 484
	if (!rev.diffopt.output_format)
		rev.diffopt.output_format = DIFF_FORMAT_RAW;
	return cmd_log_walk(&rev);
485 486
}

487 488
static void show_tagger(char *buf, int len, struct rev_info *rev)
{
489
	struct strbuf out = STRBUF_INIT;
490
	struct pretty_print_context pp = {0};
491

492 493 494
	pp.fmt = rev->commit_format;
	pp.date_mode = rev->date_mode;
	pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
495
	fprintf(rev->diffopt.file, "%s", out.buf);
496
	strbuf_release(&out);
497 498
}

499
static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
500
{
501
	struct object_id oidc;
502 503 504 505
	struct object_context obj_context;
	char *buf;
	unsigned long size;

506
	fflush(rev->diffopt.file);
507 508
	if (!rev->diffopt.flags.textconv_set_via_cmdline ||
	    !rev->diffopt.flags.allow_textconv)
509
		return stream_blob_to_fd(1, oid, NULL, 0);
510

511
	if (get_oid_with_context(obj_name, GET_OID_RECORD_PATH,
512
				 &oidc, &obj_context))
513
		die(_("Not a valid object name %s"), obj_name);
514
	if (!obj_context.path ||
515 516
	    !textconv_object(the_repository, obj_context.path,
			     obj_context.mode, &oidc, 1, &buf, &size)) {
517
		free(obj_context.path);
518
		return stream_blob_to_fd(1, oid, NULL, 0);
519
	}
520 521

	if (!buf)
522
		die(_("git show %s: bad file"), obj_name);
523 524

	write_or_die(1, buf, size);
525
	free(obj_context.path);
526
	return 0;
527 528
}

529
static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
530 531
{
	unsigned long size;
532
	enum object_type type;
533
	char *buf = read_object_file(oid, &type, &size);
534 535 536
	int offset = 0;

	if (!buf)
537
		return error(_("Could not read object %s"), oid_to_hex(oid));
538

539 540 541 542 543
	assert(type == OBJ_TAG);
	while (offset < size && buf[offset] != '\n') {
		int new_offset = offset + 1;
		while (new_offset < size && buf[new_offset++] != '\n')
			; /* do nothing */
544
		if (starts_with(buf + offset, "tagger "))
545 546 547 548
			show_tagger(buf + offset + 7,
				    new_offset - offset - 7, rev);
		offset = new_offset;
	}
549 550

	if (offset < size)
551
		fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
552 553 554 555
	free(buf);
	return 0;
}

556
static int show_tree_object(const struct object_id *oid,
557
		struct strbuf *base,
558
		const char *pathname, unsigned mode, int stage, void *context)
559
{
560 561
	FILE *file = context;
	fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
562 563 564
	return 0;
}

J
Junio C Hamano 已提交
565 566
static void show_setup_revisions_tweak(struct rev_info *rev,
				       struct setup_revision_opt *opt)
J
Junio C Hamano 已提交
567
{
568 569 570 571
	if (rev->ignore_merges) {
		/* There was no "-m" on the command line */
		rev->ignore_merges = 0;
		if (!rev->first_parent_only && !rev->combine_merges) {
J
Justin Lebar 已提交
572
			/* No "--first-parent", "-c", or "--cc" */
573 574 575 576
			rev->combine_merges = 1;
			rev->dense_combined_merges = 1;
		}
	}
J
Junio C Hamano 已提交
577 578 579 580
	if (!rev->diffopt.output_format)
		rev->diffopt.output_format = DIFF_FORMAT_PATCH;
}

581
int cmd_show(int argc, const char **argv, const char *prefix)
582 583
{
	struct rev_info rev;
584
	struct object_array_entry *objects;
585
	struct setup_revision_opt opt;
586
	struct pathspec match_all;
587
	int i, count, ret = 0;
588

589
	init_log_defaults();
590
	git_config(git_log_config, NULL);
591

592
	memset(&match_all, 0, sizeof(match_all));
593
	repo_init_revisions(the_repository, &rev, prefix);
594 595
	rev.diff = 1;
	rev.always_show_header = 1;
596
	rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
597 598
	rev.diffopt.stat_width = -1; 	/* Scale to real terminal size */

599 600
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
J
Junio C Hamano 已提交
601
	opt.tweak = show_setup_revisions_tweak;
602
	cmd_log_init(argc, argv, prefix, &rev, &opt);
603

604 605 606
	if (!rev.no_walk)
		return cmd_log_walk(&rev);

607 608 609 610 611 612 613
	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:
614
			ret = show_blob_object(&o->oid, &rev, name);
615 616 617 618
			break;
		case OBJ_TAG: {
			struct tag *t = (struct tag *)o;

619 620
			if (rev.shown_one)
				putchar('\n');
621
			fprintf(rev.diffopt.file, "%stag %s%s\n",
622
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
623
					t->tag,
624
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
625
			ret = show_tag_object(&o->oid, &rev);
626
			rev.shown_one = 1;
627 628
			if (ret)
				break;
629
			o = parse_object(the_repository, &t->tagged->oid);
630
			if (!o)
631
				ret = error(_("Could not read object %s"),
632
					    oid_to_hex(&t->tagged->oid));
633
			objects[i].item = o;
634 635 636 637
			i--;
			break;
		}
		case OBJ_TREE:
638 639
			if (rev.shown_one)
				putchar('\n');
640
			fprintf(rev.diffopt.file, "%stree %s%s\n\n",
641
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
642
					name,
643
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
644
			read_tree_recursive((struct tree *)o, "", 0, 0, &match_all,
645
					show_tree_object, rev.diffopt.file);
646
			rev.shown_one = 1;
647 648 649 650 651 652 653 654
			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:
655
			ret = error(_("Unknown type: %d"), o->type);
656 657 658 659
		}
	}
	free(objects);
	return ret;
660 661
}

L
Linus Torvalds 已提交
662 663 664 665 666 667
/*
 * 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;
668
	struct setup_revision_opt opt;
L
Linus Torvalds 已提交
669

670
	init_log_defaults();
671
	git_config(git_log_config, NULL);
672

673
	repo_init_revisions(the_repository, &rev, prefix);
L
Linus Torvalds 已提交
674 675
	init_reflog_walk(&rev.reflog_info);
	rev.verbose_header = 1;
676 677
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
678
	cmd_log_init_defaults(&rev);
679
	rev.abbrev_commit = 1;
L
Linus Torvalds 已提交
680
	rev.commit_format = CMIT_FMT_ONELINE;
681
	rev.use_terminator = 1;
L
Linus Torvalds 已提交
682
	rev.always_show_header = 1;
683
	cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
L
Linus Torvalds 已提交
684 685 686 687

	return cmd_log_walk(&rev);
}

J
Junio C Hamano 已提交
688 689
static void log_setup_revisions_tweak(struct rev_info *rev,
				      struct setup_revision_opt *opt)
690
{
691
	if (rev->diffopt.flags.default_follow_renames &&
692
	    rev->prune_data.nr == 1)
693
		rev->diffopt.flags.follow_renames = 1;
694 695 696 697

	/* Turn --cc/-c into -p --cc/-c when -p was not given */
	if (!rev->diffopt.output_format && rev->combine_merges)
		rev->diffopt.output_format = DIFF_FORMAT_PATCH;
698 699 700 701

	/* Turn -m on when --cc/-c was given */
	if (rev->combine_merges)
		rev->ignore_merges = 0;
702 703
}

704
int cmd_log(int argc, const char **argv, const char *prefix)
705 706
{
	struct rev_info rev;
707
	struct setup_revision_opt opt;
708

709
	init_log_defaults();
710
	git_config(git_log_config, NULL);
711

712
	repo_init_revisions(the_repository, &rev, prefix);
713
	rev.always_show_header = 1;
714 715
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
716
	opt.revarg_opt = REVARG_COMMITTISH;
J
Junio C Hamano 已提交
717
	opt.tweak = log_setup_revisions_tweak;
718
	cmd_log_init(argc, argv, prefix, &rev, &opt);
719
	return cmd_log_walk(&rev);
720
}
721

722
/* format-patch */
723

724
static const char *fmt_patch_suffix = ".patch";
725
static int numbered = 0;
726
static int auto_number = 1;
727

728 729
static char *default_attach = NULL;

730 731 732
static struct string_list extra_hdr = STRING_LIST_INIT_NODUP;
static struct string_list extra_to = STRING_LIST_INIT_NODUP;
static struct string_list extra_cc = STRING_LIST_INIT_NODUP;
D
Daniel Barkalow 已提交
733 734 735

static void add_header(const char *value)
{
736
	struct string_list_item *item;
D
Daniel Barkalow 已提交
737
	int len = strlen(value);
738
	while (len && value[len - 1] == '\n')
D
Daniel Barkalow 已提交
739
		len--;
740

D
Daniel Barkalow 已提交
741
	if (!strncasecmp(value, "to: ", 4)) {
742
		item = string_list_append(&extra_to, value + 4);
743 744
		len -= 4;
	} else if (!strncasecmp(value, "cc: ", 4)) {
745
		item = string_list_append(&extra_cc, value + 4);
746 747
		len -= 4;
	} else {
748
		item = string_list_append(&extra_hdr, value);
D
Daniel Barkalow 已提交
749
	}
750 751

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

754 755
#define THREAD_SHALLOW 1
#define THREAD_DEEP 2
756 757
static int thread;
static int do_signoff;
758
static int base_auto;
759
static char *from;
760
static const char *signature = git_version_string;
761
static const char *signature_file;
762
static int config_cover_letter;
763
static const char *config_output_directory;
764 765 766 767 768 769 770

enum {
	COVER_UNSET,
	COVER_OFF,
	COVER_ON,
	COVER_AUTO
};
771

772
static int git_format_config(const char *var, const char *value, void *cb)
773 774
{
	if (!strcmp(var, "format.headers")) {
775
		if (!value)
776
			die(_("format.headers without value"));
D
Daniel Barkalow 已提交
777
		add_header(value);
778 779
		return 0;
	}
780 781
	if (!strcmp(var, "format.suffix"))
		return git_config_string(&fmt_patch_suffix, var, value);
782 783 784
	if (!strcmp(var, "format.to")) {
		if (!value)
			return config_error_nonbool(var);
785
		string_list_append(&extra_to, value);
786 787
		return 0;
	}
788 789 790
	if (!strcmp(var, "format.cc")) {
		if (!value)
			return config_error_nonbool(var);
791
		string_list_append(&extra_cc, value);
792 793
		return 0;
	}
P
Pang Yan Han 已提交
794
	if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
795
	    !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
796 797
		return 0;
	}
798
	if (!strcmp(var, "format.numbered")) {
799
		if (value && !strcasecmp(value, "auto")) {
800 801 802 803
			auto_number = 1;
			return 0;
		}
		numbered = git_config_bool(var, value);
804
		auto_number = auto_number && numbered;
805 806
		return 0;
	}
807 808 809 810 811 812 813
	if (!strcmp(var, "format.attach")) {
		if (value && *value)
			default_attach = xstrdup(value);
		else
			default_attach = xstrdup(git_version_string);
		return 0;
	}
814 815 816 817 818 819 820 821 822 823 824 825
	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;
	}
826 827 828 829
	if (!strcmp(var, "format.signoff")) {
		do_signoff = git_config_bool(var, value);
		return 0;
	}
830 831
	if (!strcmp(var, "format.signature"))
		return git_config_string(&signature, var, value);
832 833
	if (!strcmp(var, "format.signaturefile"))
		return git_config_pathname(&signature_file, var, value);
834 835 836 837 838 839 840 841
	if (!strcmp(var, "format.coverletter")) {
		if (value && !strcasecmp(value, "auto")) {
			config_cover_letter = COVER_AUTO;
			return 0;
		}
		config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
		return 0;
	}
842 843
	if (!strcmp(var, "format.outputdirectory"))
		return git_config_string(&config_output_directory, var, value);
844 845 846 847
	if (!strcmp(var, "format.useautobase")) {
		base_auto = git_config_bool(var, value);
		return 0;
	}
848
	if (!strcmp(var, "format.from")) {
849
		int b = git_parse_maybe_bool(value);
850 851 852 853 854 855 856 857 858
		free(from);
		if (b < 0)
			from = xstrdup(value);
		else if (b)
			from = xstrdup(git_committer_info(IDENT_NO_DATE));
		else
			from = NULL;
		return 0;
	}
859

860
	return git_log_config(var, value, cb);
861 862
}

863
static const char *output_directory = NULL;
864
static int outdir_offset;
865

866
static int open_next_file(struct commit *commit, const char *subject,
867
			 struct rev_info *rev, int quiet)
868
{
869
	struct strbuf filename = STRBUF_INIT;
870
	int suffix_len = strlen(rev->patch_suffix) + 1;
871

872
	if (output_directory) {
873 874
		strbuf_addstr(&filename, output_directory);
		if (filename.len >=
875 876
		    PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len) {
			strbuf_release(&filename);
877
			return error(_("name of output directory is too long"));
878
		}
879
		strbuf_complete(&filename, '/');
880
	}
881

882 883
	if (rev->numbered_files)
		strbuf_addf(&filename, "%d", rev->nr);
884 885
	else if (commit)
		fmt_output_commit(&filename, commit, rev);
886
	else
887
		fmt_output_subject(&filename, subject, rev);
888

889
	if (!quiet)
890
		printf("%s\n", filename.buf + outdir_offset);
N
Nate Case 已提交
891

892 893 894 895 896
	if ((rev->diffopt.file = fopen(filename.buf, "w")) == NULL) {
		error_errno(_("Cannot open patch file %s"), filename.buf);
		strbuf_release(&filename);
		return -1;
	}
897

898
	strbuf_release(&filename);
899
	return 0;
900 901
}

902
static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
903 904
{
	struct rev_info check_rev;
905
	struct commit *commit, *c1, *c2;
906 907 908 909
	struct object *o1, *o2;
	unsigned flags1, flags2;

	if (rev->pending.nr != 2)
910
		die(_("Need exactly one range."));
911 912 913

	o1 = rev->pending.objects[0].item;
	o2 = rev->pending.objects[1].item;
914
	flags1 = o1->flags;
915
	flags2 = o2->flags;
916 917
	c1 = lookup_commit_reference(the_repository, &o1->oid);
	c2 = lookup_commit_reference(the_repository, &o2->oid);
918 919

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

922
	init_patch_ids(the_repository, ids);
923 924

	/* given a range a..b get all patch ids for b..a */
925
	repo_init_revisions(the_repository, &check_rev, rev->prefix);
926
	check_rev.max_parents = 1;
927 928 929 930
	o1->flags ^= UNINTERESTING;
	o2->flags ^= UNINTERESTING;
	add_pending_object(&check_rev, o1, "o1");
	add_pending_object(&check_rev, o2, "o2");
931
	if (prepare_revision_walk(&check_rev))
932
		die(_("revision walk setup failed"));
933 934

	while ((commit = get_revision(&check_rev)) != NULL) {
935
		add_commit_patch_id(commit, ids);
936 937 938
	}

	/* reset for next revision walk */
939 940
	clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
	clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
941 942 943 944
	o1->flags = flags1;
	o2->flags = flags2;
}

945
static void gen_message_id(struct rev_info *info, char *base)
946
{
947
	struct strbuf buf = STRBUF_INIT;
948
	strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
949
		    (timestamp_t) time(NULL),
950
		    git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
951
	info->message_id = strbuf_detach(&buf, NULL);
952 953
}

954
static void print_signature(FILE *file)
955
{
956 957 958
	if (!signature || !*signature)
		return;

959
	fprintf(file, "-- \n%s", signature);
960
	if (signature[strlen(signature)-1] != '\n')
961 962
		putc('\n', file);
	putc('\n', file);
963 964
}

965 966 967 968 969 970 971 972
static void add_branch_description(struct strbuf *buf, const char *branch_name)
{
	struct strbuf desc = STRBUF_INIT;
	if (!branch_name || !*branch_name)
		return;
	read_branch_desc(&desc, branch_name);
	if (desc.len) {
		strbuf_addch(buf, '\n');
973
		strbuf_addbuf(buf, &desc);
974 975
		strbuf_addch(buf, '\n');
	}
976
	strbuf_release(&desc);
977 978
}

979 980 981
static char *find_branch_name(struct rev_info *rev)
{
	int i, positive = -1;
982 983
	struct object_id branch_oid;
	const struct object_id *tip_oid;
984
	const char *ref, *v;
985 986 987 988 989 990 991 992 993 994 995 996 997
	char *full_ref, *branch = NULL;

	for (i = 0; i < rev->cmdline.nr; i++) {
		if (rev->cmdline.rev[i].flags & UNINTERESTING)
			continue;
		if (positive < 0)
			positive = i;
		else
			return NULL;
	}
	if (positive < 0)
		return NULL;
	ref = rev->cmdline.rev[positive].name;
998
	tip_oid = &rev->cmdline.rev[positive].item->oid;
999
	if (dwim_ref(ref, strlen(ref), &branch_oid, &full_ref) &&
1000
	    skip_prefix(full_ref, "refs/heads/", &v) &&
J
Jeff King 已提交
1001
	    oideq(tip_oid, &branch_oid))
1002
		branch = xstrdup(v);
1003 1004 1005 1006
	free(full_ref);
	return branch;
}

1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
static void show_diffstat(struct rev_info *rev,
			  struct commit *origin, struct commit *head)
{
	struct diff_options opts;

	memcpy(&opts, &rev->diffopt, sizeof(opts));
	opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
	opts.stat_width = MAIL_DEFAULT_WRAP;

	diff_setup_done(&opts);

	diff_tree_oid(get_commit_tree_oid(origin),
		      get_commit_tree_oid(head),
		      "", &opts);
	diffcore_std(&opts);
	diff_flush(&opts);

	fprintf(rev->diffopt.file, "\n");
}

1027 1028
static void make_cover_letter(struct rev_info *rev, int use_stdout,
			      struct commit *origin,
1029
			      int nr, struct commit **list,
1030
			      const char *branch_name,
1031
			      int quiet)
1032 1033 1034 1035
{
	const char *committer;
	const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
	const char *msg;
1036
	struct shortlog log;
1037
	struct strbuf sb = STRBUF_INIT;
1038
	int i;
1039
	const char *encoding = "UTF-8";
J
Junio C Hamano 已提交
1040
	int need_8bit_cte = 0;
1041
	struct pretty_print_context pp = {0};
1042
	struct commit *head = list[0];
1043

1044
	if (!cmit_fmt_is_mail(rev->commit_format))
1045
		die(_("Cover letter needs email format"));
1046

1047
	committer = git_committer_info(0);
1048

1049
	if (!use_stdout &&
1050
	    open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1051 1052
		return;

1053
	log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1054

J
Jeff King 已提交
1055
	for (i = 0; !need_8bit_cte && i < nr; i++) {
1056
		const char *buf = get_commit_buffer(list[i], NULL);
J
Jeff King 已提交
1057
		if (has_non_ascii(buf))
1058
			need_8bit_cte = 1;
J
Jeff King 已提交
1059 1060
		unuse_commit_buffer(list[i], buf);
	}
1061

1062 1063 1064
	if (!branch_name)
		branch_name = find_branch_name(rev);

1065
	msg = body;
1066
	pp.fmt = CMIT_FMT_EMAIL;
1067
	pp.date_mode.type = DATE_RFC2822;
1068 1069
	pp.rev = rev;
	pp.print_email_subject = 1;
1070 1071 1072
	pp_user_info(&pp, NULL, &sb, committer, encoding);
	pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
	pp_remainder(&pp, &msg, &sb, 0);
1073
	add_branch_description(&sb, branch_name);
1074
	fprintf(rev->diffopt.file, "%s\n", sb.buf);
1075 1076 1077

	strbuf_release(&sb);

1078
	shortlog_init(&log);
1079
	log.wrap_lines = 1;
1080
	log.wrap = MAIL_DEFAULT_WRAP;
1081 1082
	log.in1 = 2;
	log.in2 = 4;
1083
	log.file = rev->diffopt.file;
1084 1085 1086 1087 1088
	for (i = 0; i < nr; i++)
		shortlog_add_commit(&log, list[i]);

	shortlog_output(&log);

1089 1090 1091
	/* We can only do diffstat with a unique reference point */
	if (origin)
		show_diffstat(rev, origin, head);
1092

1093
	if (rev->idiff_oid1) {
1094
		fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1095
		show_interdiff(rev, 0);
1096
	}
1097 1098

	if (rev->rdiff1) {
1099
		fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1100 1101 1102
		show_range_diff(rev->rdiff1, rev->rdiff2,
				rev->creation_factor, 1, &rev->diffopt);
	}
1103 1104
}

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
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)
1121
		die(_("insane in-reply-to: %s"), msg_id);
1122 1123
	if (++z == m)
		return a;
P
Pierre Habouzit 已提交
1124
	return xmemdupz(a, z - a);
1125 1126
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
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;

1144
	return prefix_filename(prefix, output_directory);
1145 1146
}

1147
static const char * const builtin_format_patch_usage[] = {
1148
	N_("git format-patch [<options>] [<since> | <revision-range>]"),
1149 1150 1151 1152 1153 1154 1155
	NULL
};

static int keep_subject = 0;

static int keep_callback(const struct option *opt, const char *arg, int unset)
{
1156 1157
	BUG_ON_OPT_NEG(unset);
	BUG_ON_OPT_ARG(arg);
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
	((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)
{
1168
	BUG_ON_OPT_NEG(unset);
1169 1170 1171 1172 1173
	subject_prefix = 1;
	((struct rev_info *)opt->value)->subject_prefix = arg;
	return 0;
}

1174 1175
static int rfc_callback(const struct option *opt, const char *arg, int unset)
{
1176 1177
	BUG_ON_OPT_NEG(unset);
	BUG_ON_OPT_ARG(arg);
1178 1179 1180
	return subject_prefix_callback(opt, "RFC PATCH", unset);
}

1181 1182
static int numbered_cmdline_opt = 0;

1183 1184 1185
static int numbered_callback(const struct option *opt, const char *arg,
			     int unset)
{
1186
	BUG_ON_OPT_ARG(arg);
1187
	*(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1188 1189 1190 1191 1192 1193 1194 1195
	if (unset)
		auto_number =  0;
	return 0;
}

static int no_numbered_callback(const struct option *opt, const char *arg,
				int unset)
{
1196
	BUG_ON_OPT_NEG(unset);
1197 1198 1199 1200 1201 1202 1203
	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;
1204
	BUG_ON_OPT_NEG(unset);
1205
	if (*dir)
1206
		die(_("Two output directories?"));
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
	*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)
{
1253 1254 1255 1256 1257 1258 1259
	if (unset) {
		string_list_clear(&extra_hdr, 0);
		string_list_clear(&extra_to, 0);
		string_list_clear(&extra_cc, 0);
	} else {
	    add_header(arg);
	}
1260 1261 1262
	return 0;
}

1263 1264
static int to_callback(const struct option *opt, const char *arg, int unset)
{
1265 1266 1267
	if (unset)
		string_list_clear(&extra_to, 0);
	else
1268
		string_list_append(&extra_to, arg);
1269 1270 1271 1272 1273
	return 0;
}

static int cc_callback(const struct option *opt, const char *arg, int unset)
{
1274 1275 1276
	if (unset)
		string_list_clear(&extra_cc, 0);
	else
1277
		string_list_append(&extra_cc, arg);
1278 1279 1280
	return 0;
}

1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
static int from_callback(const struct option *opt, const char *arg, int unset)
{
	char **from = opt->value;

	free(*from);

	if (unset)
		*from = NULL;
	else if (arg)
		*from = xstrdup(arg);
	else
		*from = xstrdup(git_committer_info(IDENT_NO_DATE));
	return 0;
}

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
struct base_tree_info {
	struct object_id base_commit;
	int nr_patch_id, alloc_patch_id;
	struct object_id *patch_id;
};

static struct commit *get_base_commit(const char *base_commit,
				      struct commit **list,
				      int total)
{
	struct commit *base = NULL;
	struct commit **rev;
	int i = 0, rev_nr = 0;

1310 1311 1312 1313 1314
	if (base_commit && strcmp(base_commit, "auto")) {
		base = lookup_commit_reference_by_name(base_commit);
		if (!base)
			die(_("Unknown commit %s"), base_commit);
	} else if ((base_commit && !strcmp(base_commit, "auto")) || base_auto) {
1315 1316 1317 1318 1319
		struct branch *curr_branch = branch_get(NULL);
		const char *upstream = branch_get_upstream(curr_branch, NULL);
		if (upstream) {
			struct commit_list *base_list;
			struct commit *commit;
1320
			struct object_id oid;
1321

1322
			if (get_oid(upstream, &oid))
1323
				die(_("Failed to resolve '%s' as a valid ref."), upstream);
1324
			commit = lookup_commit_or_die(&oid, "upstream base");
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
			base_list = get_merge_bases_many(commit, total, list);
			/* There should be one and only one merge base. */
			if (!base_list || base_list->next)
				die(_("Could not find exact merge base."));
			base = base_list->item;
			free_commit_list(base_list);
		} else {
			die(_("Failed to get upstream, if you want to record base commit automatically,\n"
			      "please use git branch --set-upstream-to to track a remote branch.\n"
			      "Or you could specify base commit by --base=<base-commit-id> manually."));
		}
	}
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358

	ALLOC_ARRAY(rev, total);
	for (i = 0; i < total; i++)
		rev[i] = list[i];

	rev_nr = total;
	/*
	 * Get merge base through pair-wise computations
	 * and store it in rev[0].
	 */
	while (rev_nr > 1) {
		for (i = 0; i < rev_nr / 2; i++) {
			struct commit_list *merge_base;
			merge_base = get_merge_bases(rev[2 * i], rev[2 * i + 1]);
			if (!merge_base || merge_base->next)
				die(_("Failed to find exact merge base"));

			rev[i] = merge_base->item;
		}

		if (rev_nr % 2)
			rev[i] = rev[2 * i];
R
René Scharfe 已提交
1359
		rev_nr = DIV_ROUND_UP(rev_nr, 2);
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	}

	if (!in_merge_bases(base, rev[0]))
		die(_("base commit should be the ancestor of revision list"));

	for (i = 0; i < total; i++) {
		if (base == list[i])
			die(_("base commit shouldn't be in revision list"));
	}

	free(rev);
	return base;
}

1374 1375
define_commit_slab(commit_base, int);

1376 1377 1378 1379 1380 1381 1382 1383
static void prepare_bases(struct base_tree_info *bases,
			  struct commit *base,
			  struct commit **list,
			  int total)
{
	struct commit *commit;
	struct rev_info revs;
	struct diff_options diffopt;
1384
	struct commit_base commit_base;
1385 1386 1387 1388 1389
	int i;

	if (!base)
		return;

1390
	init_commit_base(&commit_base);
1391
	repo_diff_setup(the_repository, &diffopt);
1392
	diffopt.flags.recursive = 1;
1393 1394 1395 1396
	diff_setup_done(&diffopt);

	oidcpy(&bases->base_commit, &base->object.oid);

1397
	repo_init_revisions(the_repository, &revs, NULL);
1398 1399 1400 1401 1402
	revs.max_parents = 1;
	revs.topo_order = 1;
	for (i = 0; i < total; i++) {
		list[i]->object.flags &= ~UNINTERESTING;
		add_pending_object(&revs, &list[i]->object, "rev_list");
1403
		*commit_base_at(&commit_base, list[i]) = 1;
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
	}
	base->object.flags |= UNINTERESTING;
	add_pending_object(&revs, &base->object, "base");

	if (prepare_revision_walk(&revs))
		die(_("revision walk setup failed"));
	/*
	 * Traverse the commits list, get prerequisite patch ids
	 * and stuff them in bases structure.
	 */
	while ((commit = get_revision(&revs)) != NULL) {
1415
		struct object_id oid;
1416
		struct object_id *patch_id;
1417
		if (*commit_base_at(&commit_base, commit))
1418
			continue;
1419
		if (commit_patch_id(commit, &diffopt, &oid, 0))
1420 1421 1422
			die(_("cannot get patch id"));
		ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
		patch_id = bases->patch_id + bases->nr_patch_id;
1423
		oidcpy(patch_id, &oid);
1424 1425
		bases->nr_patch_id++;
	}
1426
	clear_commit_base(&commit_base);
1427 1428
}

1429
static void print_bases(struct base_tree_info *bases, FILE *file)
1430 1431 1432 1433 1434 1435 1436 1437
{
	int i;

	/* Only do this once, either for the cover or for the first one */
	if (is_null_oid(&bases->base_commit))
		return;

	/* Show the base commit */
1438
	fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1439 1440 1441

	/* Show the prerequisite patches */
	for (i = bases->nr_patch_id - 1; i >= 0; i--)
1442
		fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1443 1444 1445 1446 1447 1448 1449

	free(bases->patch_id);
	bases->nr_patch_id = 0;
	bases->alloc_patch_id = 0;
	oidclr(&bases->base_commit);
}

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
static const char *diff_title(struct strbuf *sb, int reroll_count,
		       const char *generic, const char *rerolled)
{
	if (reroll_count <= 0)
		strbuf_addstr(sb, generic);
	else /* RFC may be v0, so allow -v1 to diff against v0 */
		strbuf_addf(sb, rerolled, reroll_count - 1);
	return sb->buf;
}

1460 1461 1462
static void infer_range_diff_ranges(struct strbuf *r1,
				    struct strbuf *r2,
				    const char *prev,
1463
				    struct commit *origin,
1464 1465 1466 1467
				    struct commit *head)
{
	const char *head_oid = oid_to_hex(&head->object.oid);

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
	if (!strstr(prev, "..")) {
		strbuf_addf(r1, "%s..%s", head_oid, prev);
		strbuf_addf(r2, "%s..%s", prev, head_oid);
	} else if (!origin) {
		die(_("failed to infer range-diff ranges"));
	} else {
		strbuf_addstr(r1, prev);
		strbuf_addf(r2, "%s..%s",
			    oid_to_hex(&origin->object.oid), head_oid);
	}
1478 1479
}

1480
int cmd_format_patch(int argc, const char **argv, const char *prefix)
1481 1482 1483 1484
{
	struct commit *commit;
	struct commit **list = NULL;
	struct rev_info rev;
1485
	struct setup_revision_opt s_r_opt;
1486
	int nr = 0, total, i;
1487
	int use_stdout = 0;
1488
	int start_number = -1;
1489
	int just_numbers = 0;
1490
	int ignore_if_in_upstream = 0;
1491
	int cover_letter = -1;
1492
	int boundary_count = 0;
1493
	int no_binary_diff = 0;
1494
	int zero_commit = 0;
1495
	struct commit *origin = NULL;
1496
	const char *in_reply_to = NULL;
1497
	struct patch_ids ids;
1498
	struct strbuf buf = STRBUF_INIT;
1499
	int use_patch_format = 0;
1500
	int quiet = 0;
1501
	int reroll_count = -1;
1502
	char *branch_name = NULL;
1503 1504
	char *base_commit = NULL;
	struct base_tree_info bases;
1505 1506
	int show_progress = 0;
	struct progress *progress = NULL;
1507
	struct oid_array idiff_prev = OID_ARRAY_INIT;
1508
	struct strbuf idiff_title = STRBUF_INIT;
1509 1510 1511
	const char *rdiff_prev = NULL;
	struct strbuf rdiff1 = STRBUF_INIT;
	struct strbuf rdiff2 = STRBUF_INIT;
1512
	struct strbuf rdiff_title = STRBUF_INIT;
1513
	int creation_factor = -1;
1514

1515 1516
	const struct option builtin_format_patch_options[] = {
		{ OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1517
			    N_("use [PATCH n/m] even with a single patch"),
1518 1519
			    PARSE_OPT_NOARG, numbered_callback },
		{ OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1520
			    N_("use [PATCH] even with multiple patches"),
1521
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback },
F
Felipe Contreras 已提交
1522 1523
		OPT_BOOL('s', "signoff", &do_signoff, N_("add Signed-off-by:")),
		OPT_BOOL(0, "stdout", &use_stdout,
1524
			    N_("print patches to standard out")),
F
Felipe Contreras 已提交
1525
		OPT_BOOL(0, "cover-letter", &cover_letter,
1526
			    N_("generate a cover letter")),
F
Felipe Contreras 已提交
1527
		OPT_BOOL(0, "numbered-files", &just_numbers,
1528 1529 1530
			    N_("use simple number sequence for output file names")),
		OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
			    N_("use <sfx> instead of '.patch'")),
1531
		OPT_INTEGER(0, "start-number", &start_number,
1532
			    N_("start numbering patches at <n> instead of 1")),
1533
		OPT_INTEGER('v', "reroll-count", &reroll_count,
1534
			    N_("mark the series as Nth re-roll")),
1535 1536 1537
		{ OPTION_CALLBACK, 0, "rfc", &rev, NULL,
			    N_("Use [RFC PATCH] instead of [PATCH]"),
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, rfc_callback },
1538 1539
		{ OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"),
			    N_("Use [<prefix>] instead of [PATCH]"),
1540 1541
			    PARSE_OPT_NONEG, subject_prefix_callback },
		{ OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1542
			    N_("dir"), N_("store resulting files in <dir>"),
1543 1544
			    PARSE_OPT_NONEG, output_directory_callback },
		{ OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1545
			    N_("don't strip/add [PATCH]"),
1546
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1547 1548
		OPT_BOOL(0, "no-binary", &no_binary_diff,
			 N_("don't output binary diffs")),
1549 1550
		OPT_BOOL(0, "zero-commit", &zero_commit,
			 N_("output all-zero hash in From header")),
1551 1552
		OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
			 N_("don't include a patch matching a commit upstream")),
1553 1554 1555
		OPT_SET_INT_F('p', "no-stat", &use_patch_format,
			      N_("show patch format instead of default (patch + stat)"),
			      1, PARSE_OPT_NONEG),
1556 1557 1558 1559
		OPT_GROUP(N_("Messaging")),
		{ OPTION_CALLBACK, 0, "add-header", NULL, N_("header"),
			    N_("add email header"), 0, header_callback },
		{ OPTION_CALLBACK, 0, "to", NULL, N_("email"), N_("add To: header"),
1560
			    0, to_callback },
1561
		{ OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"),
1562
			    0, cc_callback },
1563 1564 1565
		{ OPTION_CALLBACK, 0, "from", &from, N_("ident"),
			    N_("set From address to <ident> (or committer ident if absent)"),
			    PARSE_OPT_OPTARG, from_callback },
1566 1567 1568 1569
		OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
			    N_("make first mail a reply to <message-id>")),
		{ OPTION_CALLBACK, 0, "attach", &rev, N_("boundary"),
			    N_("attach the patch"), PARSE_OPT_OPTARG,
1570
			    attach_callback },
1571 1572
		{ OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"),
			    N_("inline the patch"),
1573 1574
			    PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
			    inline_callback },
1575 1576
		{ OPTION_CALLBACK, 0, "thread", &thread, N_("style"),
			    N_("enable message threading, styles: shallow, deep"),
1577
			    PARSE_OPT_OPTARG, thread_callback },
1578 1579
		OPT_STRING(0, "signature", &signature, N_("signature"),
			    N_("add a signature")),
1580 1581
		OPT_STRING(0, "base", &base_commit, N_("base-commit"),
			   N_("add prerequisite tree info to the patch series")),
1582 1583
		OPT_FILENAME(0, "signature-file", &signature_file,
				N_("add a signature from a file")),
1584
		OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1585 1586
		OPT_BOOL(0, "progress", &show_progress,
			 N_("show progress while generating patches")),
1587
		OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
1588
			     N_("show changes against <rev> in cover letter or single patch"),
1589
			     parse_opt_object_name),
1590
		OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
1591
			   N_("show changes against <refspec> in cover letter or single patch")),
1592 1593
		OPT_INTEGER(0, "creation-factor", &creation_factor,
			    N_("percentage by which creation is weighted")),
1594 1595
		OPT_END()
	};
1596

1597 1598 1599
	extra_hdr.strdup_strings = 1;
	extra_to.strdup_strings = 1;
	extra_cc.strdup_strings = 1;
1600
	init_log_defaults();
1601
	git_config(git_format_config, NULL);
1602
	repo_init_revisions(the_repository, &rev, prefix);
1603
	rev.commit_format = CMIT_FMT_EMAIL;
1604
	rev.expand_tabs_in_log_default = 0;
1605 1606
	rev.verbose_header = 1;
	rev.diff = 1;
1607
	rev.max_parents = 1;
1608
	rev.diffopt.flags.recursive = 1;
1609
	rev.subject_prefix = fmt_patch_subject_prefix;
1610 1611
	memset(&s_r_opt, 0, sizeof(s_r_opt));
	s_r_opt.def = "HEAD";
1612
	s_r_opt.revarg_opt = REVARG_COMMITTISH;
1613

1614 1615 1616 1617 1618
	if (default_attach) {
		rev.mime_boundary = default_attach;
		rev.no_inline = 1;
	}

1619 1620
	/*
	 * Parse the arguments before setup_revisions(), or something
1621
	 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1622 1623
	 * possibly a valid SHA1.
	 */
1624
	argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1625
			     builtin_format_patch_usage,
1626 1627
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
			     PARSE_OPT_KEEP_DASHDASH);
1628

1629 1630 1631 1632 1633 1634 1635 1636
	if (0 < reroll_count) {
		struct strbuf sprefix = STRBUF_INIT;
		strbuf_addf(&sprefix, "%s v%d",
			    rev.subject_prefix, reroll_count);
		rev.reroll_count = reroll_count;
		rev.subject_prefix = strbuf_detach(&sprefix, NULL);
	}

1637 1638
	for (i = 0; i < extra_hdr.nr; i++) {
		strbuf_addstr(&buf, extra_hdr.items[i].string);
D
Daniel Barkalow 已提交
1639 1640 1641
		strbuf_addch(&buf, '\n');
	}

1642
	if (extra_to.nr)
D
Daniel Barkalow 已提交
1643
		strbuf_addstr(&buf, "To: ");
1644
	for (i = 0; i < extra_to.nr; i++) {
D
Daniel Barkalow 已提交
1645 1646
		if (i)
			strbuf_addstr(&buf, "    ");
1647 1648
		strbuf_addstr(&buf, extra_to.items[i].string);
		if (i + 1 < extra_to.nr)
D
Daniel Barkalow 已提交
1649 1650 1651 1652
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

1653
	if (extra_cc.nr)
D
Daniel Barkalow 已提交
1654
		strbuf_addstr(&buf, "Cc: ");
1655
	for (i = 0; i < extra_cc.nr; i++) {
D
Daniel Barkalow 已提交
1656 1657
		if (i)
			strbuf_addstr(&buf, "    ");
1658 1659
		strbuf_addstr(&buf, extra_cc.items[i].string);
		if (i + 1 < extra_cc.nr)
D
Daniel Barkalow 已提交
1660 1661 1662 1663
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

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

1666 1667 1668 1669 1670
	if (from) {
		if (split_ident_line(&rev.from_ident, from, strlen(from)))
			die(_("invalid ident line: %s"), from);
	}

1671
	if (start_number < 0)
1672
		start_number = 1;
1673 1674 1675 1676 1677 1678 1679 1680 1681

	/*
	 * 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;

1682
	if (numbered && keep_subject)
1683
		die(_("-n and -k are mutually exclusive"));
1684
	if (keep_subject && subject_prefix)
1685
		die(_("--subject-prefix/--rfc and -k are mutually exclusive"));
1686
	rev.preserve_subject = keep_subject;
1687

1688
	argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1689
	if (argc > 1)
1690
		die(_("unrecognized argument: %s"), argv[1]);
1691

1692
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1693
		die(_("--name-only does not make sense"));
1694
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1695
		die(_("--name-status does not make sense"));
1696
	if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1697
		die(_("--check does not make sense"));
1698 1699 1700 1701 1702

	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;
1703 1704
	if (!rev.diffopt.stat_width)
		rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
1705 1706 1707

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

1709 1710
	rev.zero_commit = zero_commit;

1711 1712
	if (!rev.diffopt.flags.text && !no_binary_diff)
		rev.diffopt.flags.binary = 1;
1713

1714 1715 1716
	if (rev.show_notes)
		init_display_notes(&rev.notes_opt);

1717 1718 1719
	if (!output_directory && !use_stdout)
		output_directory = config_output_directory;

1720 1721
	if (!use_stdout)
		output_directory = set_outdir(prefix, output_directory);
1722 1723
	else
		setup_pager();
1724

1725
	if (output_directory) {
1726 1727
		if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
			rev.diffopt.use_color = GIT_COLOR_NEVER;
1728
		if (use_stdout)
1729
			die(_("standard output, or directory, which one?"));
1730
		if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1731
			die_errno(_("Could not create directory '%s'"),
1732
				  output_directory);
1733 1734
	}

1735
	if (rev.pending.nr == 1) {
1736 1737
		int check_head = 0;

1738 1739 1740 1741 1742 1743
		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 已提交
1744
			rev.pending.objects[0].item->flags |= UNINTERESTING;
1745
			add_head_to_pending(&rev);
1746
			check_head = 1;
J
Junio C Hamano 已提交
1747
		}
1748 1749 1750 1751
		/*
		 * 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 已提交
1752
		 */
1753 1754 1755 1756 1757

		if (!strcmp(rev.pending.objects[0].name, "HEAD"))
			check_head = 1;

		if (check_head) {
1758
			const char *ref, *v;
1759
			ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1760
						 NULL, NULL);
1761 1762
			if (ref && skip_prefix(ref, "refs/heads/", &v))
				branch_name = xstrdup(v);
1763 1764 1765
			else
				branch_name = xstrdup(""); /* no branch */
		}
1766
	}
1767 1768 1769

	/*
	 * We cannot move this anywhere earlier because we do want to
1770
	 * know if --root was given explicitly from the command line.
1771 1772 1773
	 */
	rev.show_root_diff = 1;

1774 1775 1776 1777
	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;
J
Jeff King 已提交
1778
			if (oideq(&o[0].item->oid, &o[1].item->oid))
1779
				goto done;
1780
		}
1781
		get_patch_ids(&rev, &ids);
1782
	}
1783

1784
	if (prepare_revision_walk(&rev))
1785
		die(_("revision walk setup failed"));
1786
	rev.boundary = 1;
1787
	while ((commit = get_revision(&rev)) != NULL) {
1788 1789 1790 1791 1792 1793
		if (commit->object.flags & BOUNDARY) {
			boundary_count++;
			origin = (boundary_count == 1) ? commit : NULL;
			continue;
		}

J
Junio C Hamano 已提交
1794
		if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
1795 1796
			continue;

1797
		nr++;
1798
		REALLOC_ARRAY(list, nr);
1799 1800
		list[nr - 1] = commit;
	}
1801 1802
	if (nr == 0)
		/* nothing to do */
1803
		goto done;
1804
	total = nr;
1805 1806 1807 1808 1809 1810
	if (cover_letter == -1) {
		if (config_cover_letter == COVER_AUTO)
			cover_letter = (total > 1);
		else
			cover_letter = (config_cover_letter == COVER_ON);
	}
1811 1812 1813 1814
	if (!keep_subject && auto_number && (total > 1 || cover_letter))
		numbered = 1;
	if (numbered)
		rev.total = total + start_number - 1;
1815

1816
	if (idiff_prev.nr) {
1817 1818
		if (!cover_letter && total != 1)
			die(_("--interdiff requires --cover-letter or single patch"));
1819 1820
		rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
		rev.idiff_oid2 = get_commit_tree_oid(list[0]);
1821 1822 1823
		rev.idiff_title = diff_title(&idiff_title, reroll_count,
					     _("Interdiff:"),
					     _("Interdiff against v%d:"));
1824 1825
	}

1826 1827 1828 1829 1830
	if (creation_factor < 0)
		creation_factor = RANGE_DIFF_CREATION_FACTOR_DEFAULT;
	else if (!rdiff_prev)
		die(_("--creation-factor requires --range-diff"));

1831
	if (rdiff_prev) {
1832 1833
		if (!cover_letter && total != 1)
			die(_("--range-diff requires --cover-letter or single patch"));
1834

1835 1836
		infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
					origin, list[0]);
1837 1838
		rev.rdiff1 = rdiff1.buf;
		rev.rdiff2 = rdiff2.buf;
1839
		rev.creation_factor = creation_factor;
1840 1841 1842
		rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
					     _("Range-diff:"),
					     _("Range-diff against v%d:"));
1843 1844
	}

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
	if (!signature) {
		; /* --no-signature inhibits all signatures */
	} else if (signature && signature != git_version_string) {
		; /* non-default signature already set */
	} else if (signature_file) {
		struct strbuf buf = STRBUF_INIT;

		if (strbuf_read_file(&buf, signature_file, 128) < 0)
			die_errno(_("unable to read signature file '%s'"), signature_file);
		signature = strbuf_detach(&buf, NULL);
	}

1857
	memset(&bases, 0, sizeof(bases));
1858
	if (base_commit || base_auto) {
1859 1860
		struct commit *base = get_base_commit(base_commit, list, nr);
		reset_revision_walk();
1861
		clear_object_flags(UNINTERESTING);
1862 1863 1864
		prepare_bases(&bases, base, list, nr);
	}

1865 1866 1867 1868
	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);
1869
		string_list_append(rev.ref_message_ids, msgid);
1870
	}
1871
	rev.numbered_files = just_numbers;
1872
	rev.patch_suffix = fmt_patch_suffix;
1873 1874 1875
	if (cover_letter) {
		if (thread)
			gen_message_id(&rev, "cover");
1876
		make_cover_letter(&rev, use_stdout,
1877
				  origin, nr, list, branch_name, quiet);
1878
		print_bases(&bases, rev.diffopt.file);
1879
		print_signature(rev.diffopt.file);
1880 1881
		total++;
		start_number--;
1882
		/* interdiff/range-diff in cover-letter; omit from patches */
1883
		rev.idiff_oid1 = NULL;
1884
		rev.rdiff1 = NULL;
1885
	}
1886
	rev.add_signoff = do_signoff;
1887 1888

	if (show_progress)
1889
		progress = start_delayed_progress(_("Generating patches"), total);
1890 1891
	while (0 <= --nr) {
		int shown;
1892
		display_progress(progress, total - nr);
1893
		commit = list[nr];
1894
		rev.nr = total - nr + (start_number - 1);
1895
		/* Make the second and subsequent mails replies to the first */
1896
		if (thread) {
1897
			/* Have we already had a message ID? */
1898
			if (rev.message_id) {
1899
				/*
1900 1901 1902 1903 1904 1905
				 * For deep threading: make every mail
				 * a reply to the previous one, no
				 * matter what other options are set.
				 *
				 * For shallow threading:
				 *
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
				 * 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.
1919
				 */
1920 1921
				if (thread == THREAD_SHALLOW
				    && rev.ref_message_ids->nr > 0
1922
				    && (!cover_letter || rev.nr > 1))
1923 1924
					free(rev.message_id);
				else
1925 1926
					string_list_append(rev.ref_message_ids,
							   rev.message_id);
1927
			}
1928
			gen_message_id(&rev, oid_to_hex(&commit->object.oid));
1929
		}
1930

1931
		if (!use_stdout &&
1932
		    open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
1933
			die(_("Failed to create output files"));
1934
		shown = log_tree_commit(&rev, commit);
1935
		free_commit_buffer(commit);
1936 1937 1938 1939 1940 1941 1942 1943 1944

		/* 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;
1945
		if (shown) {
1946
			print_bases(&bases, rev.diffopt.file);
1947
			if (rev.mime_boundary)
1948
				fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
1949 1950 1951
				       mime_boundary_leader,
				       rev.mime_boundary);
			else
1952
				print_signature(rev.diffopt.file);
1953
		}
1954
		if (!use_stdout)
1955
			fclose(rev.diffopt.file);
1956
	}
1957
	stop_progress(&progress);
1958
	free(list);
1959
	free(branch_name);
1960 1961 1962
	string_list_clear(&extra_to, 0);
	string_list_clear(&extra_cc, 0);
	string_list_clear(&extra_hdr, 0);
1963 1964
	if (ignore_if_in_upstream)
		free_patch_ids(&ids);
1965 1966 1967

done:
	oid_array_clear(&idiff_prev);
1968
	strbuf_release(&idiff_title);
1969 1970
	strbuf_release(&rdiff1);
	strbuf_release(&rdiff2);
1971
	strbuf_release(&rdiff_title);
1972 1973 1974
	return 0;
}

R
Rene Scharfe 已提交
1975 1976
static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
{
1977 1978
	struct object_id oid;
	if (get_oid(arg, &oid) == 0) {
1979 1980
		struct commit *commit = lookup_commit_reference(the_repository,
								&oid);
R
Rene Scharfe 已提交
1981 1982 1983 1984 1985 1986 1987 1988 1989
		if (commit) {
			commit->object.flags |= flags;
			add_pending_object(revs, &commit->object, arg);
			return 0;
		}
	}
	return -1;
}

E
Erik Faye-Lund 已提交
1990
static const char * const cherry_usage[] = {
1991
	N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
E
Erik Faye-Lund 已提交
1992 1993 1994
	NULL
};

1995
static void print_commit(char sign, struct commit *commit, int verbose,
1996
			 int abbrev, FILE *file)
1997 1998
{
	if (!verbose) {
1999
		fprintf(file, "%c %s\n", sign,
2000
		       find_unique_abbrev(&commit->object.oid, abbrev));
2001 2002
	} else {
		struct strbuf buf = STRBUF_INIT;
2003
		pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2004
		fprintf(file, "%c %s %s\n", sign,
2005
		       find_unique_abbrev(&commit->object.oid, abbrev),
2006 2007 2008 2009 2010
		       buf.buf);
		strbuf_release(&buf);
	}
}

R
Rene Scharfe 已提交
2011 2012 2013
int cmd_cherry(int argc, const char **argv, const char *prefix)
{
	struct rev_info revs;
2014
	struct patch_ids ids;
R
Rene Scharfe 已提交
2015 2016
	struct commit *commit;
	struct commit_list *list = NULL;
2017
	struct branch *current_branch;
R
Rene Scharfe 已提交
2018 2019 2020
	const char *upstream;
	const char *head = "HEAD";
	const char *limit = NULL;
E
Erik Faye-Lund 已提交
2021
	int verbose = 0, abbrev = 0;
R
Rene Scharfe 已提交
2022

E
Erik Faye-Lund 已提交
2023 2024
	struct option options[] = {
		OPT__ABBREV(&abbrev),
2025
		OPT__VERBOSE(&verbose, N_("be verbose")),
E
Erik Faye-Lund 已提交
2026 2027
		OPT_END()
	};
R
Rene Scharfe 已提交
2028

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

R
Rene Scharfe 已提交
2031 2032
	switch (argc) {
	case 3:
E
Erik Faye-Lund 已提交
2033
		limit = argv[2];
R
Rene Scharfe 已提交
2034 2035
		/* FALLTHROUGH */
	case 2:
E
Erik Faye-Lund 已提交
2036 2037 2038 2039
		head = argv[1];
		/* FALLTHROUGH */
	case 1:
		upstream = argv[0];
R
Rene Scharfe 已提交
2040 2041
		break;
	default:
2042
		current_branch = branch_get(NULL);
2043
		upstream = branch_get_upstream(current_branch, NULL);
2044
		if (!upstream) {
2045
			fprintf(stderr, _("Could not find a tracked"
2046
					" remote branch, please"
2047
					" specify <upstream> manually.\n"));
E
Erik Faye-Lund 已提交
2048
			usage_with_options(cherry_usage, options);
2049
		}
R
Rene Scharfe 已提交
2050 2051
	}

2052
	repo_init_revisions(the_repository, &revs, prefix);
2053
	revs.max_parents = 1;
R
Rene Scharfe 已提交
2054 2055

	if (add_pending_commit(head, &revs, 0))
2056
		die(_("Unknown commit %s"), head);
R
Rene Scharfe 已提交
2057
	if (add_pending_commit(upstream, &revs, UNINTERESTING))
2058
		die(_("Unknown commit %s"), upstream);
R
Rene Scharfe 已提交
2059 2060 2061 2062

	/* Don't say anything if head and upstream are the same. */
	if (revs.pending.nr == 2) {
		struct object_array_entry *o = revs.pending.objects;
J
Jeff King 已提交
2063
		if (oideq(&o[0].item->oid, &o[1].item->oid))
R
Rene Scharfe 已提交
2064 2065 2066
			return 0;
	}

2067
	get_patch_ids(&revs, &ids);
R
Rene Scharfe 已提交
2068 2069

	if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2070
		die(_("Unknown commit %s"), limit);
R
Rene Scharfe 已提交
2071 2072

	/* reverse the list of commits */
2073
	if (prepare_revision_walk(&revs))
2074
		die(_("revision walk setup failed"));
R
Rene Scharfe 已提交
2075 2076 2077 2078 2079 2080 2081 2082
	while ((commit = get_revision(&revs)) != NULL) {
		commit_list_insert(commit, &list);
	}

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

		commit = list->item;
2083
		if (has_commit_patch_id(commit, &ids))
R
Rene Scharfe 已提交
2084
			sign = '-';
2085
		print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
R
Rene Scharfe 已提交
2086 2087 2088
		list = list->next;
	}

2089
	free_patch_ids(&ids);
R
Rene Scharfe 已提交
2090 2091
	return 0;
}