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

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

32
static int default_abbrev_commit;
33
static int default_show_root = 1;
J
Junio C Hamano 已提交
34
static int decoration_style;
35
static int decoration_given;
36
static int use_mailmap_config;
37
static const char *fmt_patch_subject_prefix = "PATCH";
38
static const char *fmt_pretty;
39

40
static const char * const builtin_log_usage[] = {
41
	N_("git log [<options>] [<revision range>] [[--] <path>...]\n")
42
	N_("   or: git show [options] <object>..."),
43 44
	NULL
};
45

46 47 48 49 50 51
struct line_opt_callback_data {
	struct rev_info *rev;
	const char *prefix;
	struct string_list args;
};

J
Junio C Hamano 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65
static int parse_decoration_style(const char *var, const char *value)
{
	switch (git_config_maybe_bool(var, value)) {
	case 1:
		return DECORATE_SHORT_REFS;
	case 0:
		return 0;
	default:
		break;
	}
	if (!strcmp(value, "full"))
		return DECORATE_FULL_REFS;
	else if (!strcmp(value, "short"))
		return DECORATE_SHORT_REFS;
66 67
	else if (!strcmp(value, "auto"))
		return (isatty(1) || pager_in_use()) ? DECORATE_SHORT_REFS : 0;
J
Junio C Hamano 已提交
68 69 70
	return -1;
}

71 72 73 74 75 76 77 78 79 80
static int decorate_callback(const struct option *opt, const char *arg, int unset)
{
	if (unset)
		decoration_style = 0;
	else if (arg)
		decoration_style = parse_decoration_style("command line", arg);
	else
		decoration_style = DECORATE_SHORT_REFS;

	if (decoration_style < 0)
81
		die(_("invalid --decorate option: %s"), arg);
82 83 84 85 86 87

	decoration_given = 1;

	return 0;
}

88 89 90 91 92 93 94 95 96 97 98 99 100
static int log_line_range_callback(const struct option *option, const char *arg, int unset)
{
	struct line_opt_callback_data *data = option->value;

	if (!arg)
		return -1;

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

	return 0;
}

101
static void cmd_log_init_defaults(struct rev_info *rev)
102
{
103
	if (fmt_pretty)
104
		get_commit_format(fmt_pretty, rev);
105
	rev->verbose_header = 1;
106
	DIFF_OPT_SET(&rev->diffopt, RECURSIVE);
107
	rev->diffopt.stat_width = -1; /* use full terminal width */
108
	rev->diffopt.stat_graph_width = -1; /* respect statGraphWidth config */
109
	rev->abbrev_commit = default_abbrev_commit;
110
	rev->show_root_diff = default_show_root;
111
	rev->subject_prefix = fmt_patch_subject_prefix;
J
Jeff King 已提交
112
	DIFF_OPT_SET(&rev->diffopt, ALLOW_TEXTCONV);
H
Heikki Orsila 已提交
113 114 115

	if (default_date_mode)
		rev->date_mode = parse_date_format(default_date_mode);
116
	rev->diffopt.touched_flags = 0;
117
}
H
Heikki Orsila 已提交
118

119 120 121 122
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 已提交
123
	int quiet = 0, source = 0, mailmap = 0;
124
	static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
125 126

	const struct option builtin_log_options[] = {
127
		OPT__QUIET(&quiet, N_("suppress diff output")),
F
Felipe Contreras 已提交
128 129
		OPT_BOOL(0, "source", &source, N_("show source")),
		OPT_BOOL(0, "use-mailmap", &mailmap, N_("Use mail map file")),
130
		{ OPTION_CALLBACK, 0, "decorate", NULL, NULL, N_("decorate options"),
131
		  PARSE_OPT_OPTARG, decorate_callback},
132
		OPT_CALLBACK('L', NULL, &line_cb, "n,m:file",
133
			     N_("Process line range n,m in file, counting from 1"),
134
			     log_line_range_callback),
135 136 137
		OPT_END()
	};

138 139 140
	line_cb.rev = rev;
	line_cb.prefix = prefix;

141
	mailmap = use_mailmap_config;
142 143 144 145
	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 已提交
146

147 148
	if (quiet)
		rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
J
Jeff King 已提交
149
	argc = setup_revisions(argc, argv, rev, opt);
H
Heikki Orsila 已提交
150

151 152
	/* Any arguments at this point are not recognized */
	if (argc > 1)
153
		die(_("unrecognized argument: %s"), argv[1]);
154

155 156 157 158
	memset(&w, 0, sizeof(w));
	userformat_find_requirements(NULL, &w);

	if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
159
		rev->show_notes = 1;
160 161
	if (rev->show_notes)
		init_display_notes(&rev->notes_opt);
162

163 164
	if (rev->diffopt.pickaxe || rev->diffopt.filter ||
	    DIFF_OPT_TST(&rev->diffopt, FOLLOW_RENAMES))
165
		rev->always_show_header = 0;
166 167 168

	if (source)
		rev->show_source = 1;
169

A
Antoine Pelisse 已提交
170 171 172 173 174
	if (mailmap) {
		rev->mailmap = xcalloc(1, sizeof(struct string_list));
		read_mailmap(rev->mailmap, NULL);
	}

175 176 177 178 179 180 181 182 183 184
	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;
	}
185

186 187 188 189
	if (decoration_style) {
		rev->show_decorations = 1;
		load_ref_decorations(decoration_style);
	}
190 191 192 193

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

194
	setup_pager();
195 196
}

197 198 199 200 201 202 203
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 已提交
204 205 206 207 208 209 210 211 212 213 214 215
/*
 * 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;
216
		if (!(flags & (TREESAME | UNINTERESTING)))
L
Linus Torvalds 已提交
217
			n++;
L
Linus Torvalds 已提交
218 219 220 221 222 223 224 225 226 227 228
	}
	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);
	}
229
	printf(_("Final output: %d %s\n"), nr, stage);
L
Linus Torvalds 已提交
230 231
}

232
static struct itimerval early_output_timer;
L
Linus Torvalds 已提交
233

234 235 236
static void log_show_early(struct rev_info *revs, struct commit_list *list)
{
	int i = revs->early_output;
L
Linus Torvalds 已提交
237
	int show_header = 1;
238

J
Junio C Hamano 已提交
239
	sort_in_topological_order(&list, revs->sort_order);
240 241
	while (list && i) {
		struct commit *commit = list->item;
L
Linus Torvalds 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
		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;
		}
257 258
		list = list->next;
	}
L
Linus Torvalds 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

	/* 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);
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
}

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 已提交
308 309 310
	early_output_timer.it_value.tv_sec = 0;
	early_output_timer.it_value.tv_usec = 100000;
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
311 312 313 314
}

static void finish_early_output(struct rev_info *rev)
{
L
Linus Torvalds 已提交
315
	int n = estimate_commit_count(rev, rev->commits);
316
	signal(SIGALRM, SIG_IGN);
L
Linus Torvalds 已提交
317
	show_early_header(rev, "done", n);
318 319
}

320 321 322
static int cmd_log_walk(struct rev_info *rev)
{
	struct commit *commit;
323 324
	int saved_nrl = 0;
	int saved_dcctc = 0;
325

326 327 328
	if (rev->early_output)
		setup_early_output(rev);

329
	if (prepare_revision_walk(rev))
330
		die(_("revision walk setup failed"));
331 332 333 334

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

335
	/*
336 337 338
	 * 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
339
	 */
340
	while ((commit = get_revision(rev)) != NULL) {
341 342 343 344 345 346 347
		if (!log_tree_commit(rev, commit) &&
		    rev->max_count >= 0)
			/*
			 * We decremented max_count in get_revision,
			 * but we didn't actually show the commit.
			 */
			rev->max_count++;
348 349
		if (!rev->reflog_info) {
			/* we allow cycles in reflog ancestry */
350
			free_commit_buffer(commit);
351
		}
L
Linus Torvalds 已提交
352 353
		free_commit_list(commit->parents);
		commit->parents = NULL;
354 355 356 357
		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;
358
	}
359 360 361
	rev->diffopt.degraded_cc_to_c = saved_dcctc;
	rev->diffopt.needed_rename_limit = saved_nrl;

362 363 364 365
	if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
	    DIFF_OPT_TST(&rev->diffopt, CHECK_FAILED)) {
		return 02;
	}
366
	return diff_result_code(&rev->diffopt, 0);
367 368
}

369
static int git_log_config(const char *var, const char *value, void *cb)
370
{
371 372
	const char *slot_name;

373 374
	if (!strcmp(var, "format.pretty"))
		return git_config_string(&fmt_pretty, var, value);
375 376
	if (!strcmp(var, "format.subjectprefix"))
		return git_config_string(&fmt_patch_subject_prefix, var, value);
377 378 379 380
	if (!strcmp(var, "log.abbrevcommit")) {
		default_abbrev_commit = git_config_bool(var, value);
		return 0;
	}
H
Heikki Orsila 已提交
381 382
	if (!strcmp(var, "log.date"))
		return git_config_string(&default_date_mode, var, value);
383
	if (!strcmp(var, "log.decorate")) {
J
Junio C Hamano 已提交
384 385 386
		decoration_style = parse_decoration_style(var, value);
		if (decoration_style < 0)
			decoration_style = 0; /* maybe warn? */
387 388
		return 0;
	}
389 390 391 392
	if (!strcmp(var, "log.showroot")) {
		default_show_root = git_config_bool(var, value);
		return 0;
	}
393
	if (skip_prefix(var, "color.decorate.", &slot_name))
394
		return parse_decorate_color_config(var, slot_name, value);
395 396 397 398 399
	if (!strcmp(var, "log.mailmap")) {
		use_mailmap_config = git_config_bool(var, value);
		return 0;
	}

J
Junio C Hamano 已提交
400 401
	if (grep_config(var, value, cb) < 0)
		return -1;
402
	if (git_gpg_config(var, value, cb) < 0)
J
Junio C Hamano 已提交
403
		return -1;
404
	return git_diff_ui_config(var, value, cb);
405 406
}

407
int cmd_whatchanged(int argc, const char **argv, const char *prefix)
408 409
{
	struct rev_info rev;
410
	struct setup_revision_opt opt;
411

J
Junio C Hamano 已提交
412
	init_grep_defaults();
413
	git_config(git_log_config, NULL);
414

415
	init_revisions(&rev, prefix);
416
	rev.diff = 1;
L
Linus Torvalds 已提交
417
	rev.simplify_history = 0;
418 419
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
420
	opt.revarg_opt = REVARG_COMMITTISH;
421
	cmd_log_init(argc, argv, prefix, &rev, &opt);
422 423 424
	if (!rev.diffopt.output_format)
		rev.diffopt.output_format = DIFF_FORMAT_RAW;
	return cmd_log_walk(&rev);
425 426
}

427 428
static void show_tagger(char *buf, int len, struct rev_info *rev)
{
429
	struct strbuf out = STRBUF_INIT;
430
	struct pretty_print_context pp = {0};
431

432 433 434
	pp.fmt = rev->commit_format;
	pp.date_mode = rev->date_mode;
	pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
435
	printf("%s", out.buf);
436
	strbuf_release(&out);
437 438
}

439
static int show_blob_object(const unsigned char *sha1, struct rev_info *rev, const char *obj_name)
440
{
441 442 443 444 445
	unsigned char sha1c[20];
	struct object_context obj_context;
	char *buf;
	unsigned long size;

446
	fflush(stdout);
447 448 449 450 451
	if (!DIFF_OPT_TOUCHED(&rev->diffopt, ALLOW_TEXTCONV) ||
	    !DIFF_OPT_TST(&rev->diffopt, ALLOW_TEXTCONV))
		return stream_blob_to_fd(1, sha1, NULL, 0);

	if (get_sha1_with_context(obj_name, 0, sha1c, &obj_context))
452
		die(_("Not a valid object name %s"), obj_name);
453 454 455 456 457
	if (!obj_context.path[0] ||
	    !textconv_object(obj_context.path, obj_context.mode, sha1c, 1, &buf, &size))
		return stream_blob_to_fd(1, sha1, NULL, 0);

	if (!buf)
458
		die(_("git show %s: bad file"), obj_name);
459 460 461

	write_or_die(1, buf, size);
	return 0;
462 463 464
}

static int show_tag_object(const unsigned char *sha1, struct rev_info *rev)
465 466
{
	unsigned long size;
467 468
	enum object_type type;
	char *buf = read_sha1_file(sha1, &type, &size);
469 470 471
	int offset = 0;

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

474 475 476 477 478
	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 */
479
		if (starts_with(buf + offset, "tagger "))
480 481 482 483
			show_tagger(buf + offset + 7,
				    new_offset - offset - 7, rev);
		offset = new_offset;
	}
484 485 486 487 488 489 490 491 492

	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,
493
		const char *pathname, unsigned mode, int stage, void *context)
494 495 496 497 498
{
	printf("%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
	return 0;
}

J
Junio C Hamano 已提交
499 500
static void show_rev_tweak_rev(struct rev_info *rev, struct setup_revision_opt *opt)
{
501 502 503 504
	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 已提交
505
			/* No "--first-parent", "-c", or "--cc" */
506 507 508 509
			rev->combine_merges = 1;
			rev->dense_combined_merges = 1;
		}
	}
J
Junio C Hamano 已提交
510 511 512 513
	if (!rev->diffopt.output_format)
		rev->diffopt.output_format = DIFF_FORMAT_PATCH;
}

514
int cmd_show(int argc, const char **argv, const char *prefix)
515 516
{
	struct rev_info rev;
517
	struct object_array_entry *objects;
518
	struct setup_revision_opt opt;
519
	struct pathspec match_all;
520
	int i, count, ret = 0;
521

J
Junio C Hamano 已提交
522
	init_grep_defaults();
523
	git_config(git_log_config, NULL);
524

525
	memset(&match_all, 0, sizeof(match_all));
526
	init_revisions(&rev, prefix);
527 528
	rev.diff = 1;
	rev.always_show_header = 1;
529
	rev.no_walk = REVISION_WALK_NO_WALK_SORTED;
530 531
	rev.diffopt.stat_width = -1; 	/* Scale to real terminal size */

532 533
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
J
Junio C Hamano 已提交
534
	opt.tweak = show_rev_tweak_rev;
535
	cmd_log_init(argc, argv, prefix, &rev, &opt);
536

537 538 539
	if (!rev.no_walk)
		return cmd_log_walk(&rev);

540 541 542 543 544 545 546
	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:
547
			ret = show_blob_object(o->sha1, &rev, name);
548 549 550 551
			break;
		case OBJ_TAG: {
			struct tag *t = (struct tag *)o;

552 553
			if (rev.shown_one)
				putchar('\n');
554
			printf("%stag %s%s\n",
555
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
556
					t->tag,
557
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
558
			ret = show_tag_object(o->sha1, &rev);
559
			rev.shown_one = 1;
560 561 562 563
			if (ret)
				break;
			o = parse_object(t->tagged->sha1);
			if (!o)
564
				ret = error(_("Could not read object %s"),
565 566
					    sha1_to_hex(t->tagged->sha1));
			objects[i].item = o;
567 568 569 570
			i--;
			break;
		}
		case OBJ_TREE:
571 572
			if (rev.shown_one)
				putchar('\n');
573
			printf("%stree %s%s\n\n",
574
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
575
					name,
576
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
577
			read_tree_recursive((struct tree *)o, "", 0, 0, &match_all,
578
					show_tree_object, NULL);
579
			rev.shown_one = 1;
580 581 582 583 584 585 586 587
			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:
588
			ret = error(_("Unknown type: %d"), o->type);
589 590 591 592
		}
	}
	free(objects);
	return ret;
593 594
}

L
Linus Torvalds 已提交
595 596 597 598 599 600
/*
 * 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;
601
	struct setup_revision_opt opt;
L
Linus Torvalds 已提交
602

J
Junio C Hamano 已提交
603
	init_grep_defaults();
604
	git_config(git_log_config, NULL);
605

L
Linus Torvalds 已提交
606 607 608
	init_revisions(&rev, prefix);
	init_reflog_walk(&rev.reflog_info);
	rev.verbose_header = 1;
609 610
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
611
	cmd_log_init_defaults(&rev);
612
	rev.abbrev_commit = 1;
L
Linus Torvalds 已提交
613
	rev.commit_format = CMIT_FMT_ONELINE;
614
	rev.use_terminator = 1;
L
Linus Torvalds 已提交
615
	rev.always_show_header = 1;
616
	cmd_log_init_finish(argc, argv, prefix, &rev, &opt);
L
Linus Torvalds 已提交
617 618 619 620

	return cmd_log_walk(&rev);
}

621
int cmd_log(int argc, const char **argv, const char *prefix)
622 623
{
	struct rev_info rev;
624
	struct setup_revision_opt opt;
625

J
Junio C Hamano 已提交
626
	init_grep_defaults();
627
	git_config(git_log_config, NULL);
628

629
	init_revisions(&rev, prefix);
630
	rev.always_show_header = 1;
631 632
	memset(&opt, 0, sizeof(opt));
	opt.def = "HEAD";
633
	opt.revarg_opt = REVARG_COMMITTISH;
634
	cmd_log_init(argc, argv, prefix, &rev, &opt);
635
	return cmd_log_walk(&rev);
636
}
637

638
/* format-patch */
639

640
static const char *fmt_patch_suffix = ".patch";
641
static int numbered = 0;
642
static int auto_number = 1;
643

644 645
static char *default_attach = NULL;

646 647 648
static struct string_list extra_hdr;
static struct string_list extra_to;
static struct string_list extra_cc;
D
Daniel Barkalow 已提交
649 650 651

static void add_header(const char *value)
{
652
	struct string_list_item *item;
D
Daniel Barkalow 已提交
653
	int len = strlen(value);
654
	while (len && value[len - 1] == '\n')
D
Daniel Barkalow 已提交
655
		len--;
656

D
Daniel Barkalow 已提交
657
	if (!strncasecmp(value, "to: ", 4)) {
658
		item = string_list_append(&extra_to, value + 4);
659 660
		len -= 4;
	} else if (!strncasecmp(value, "cc: ", 4)) {
661
		item = string_list_append(&extra_cc, value + 4);
662 663
		len -= 4;
	} else {
664
		item = string_list_append(&extra_hdr, value);
D
Daniel Barkalow 已提交
665
	}
666 667

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

670 671
#define THREAD_SHALLOW 1
#define THREAD_DEEP 2
672 673 674
static int thread;
static int do_signoff;
static const char *signature = git_version_string;
675
static const char *signature_file;
676 677 678 679 680 681 682 683
static int config_cover_letter;

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

685
static int git_format_config(const char *var, const char *value, void *cb)
686 687
{
	if (!strcmp(var, "format.headers")) {
688
		if (!value)
689
			die(_("format.headers without value"));
D
Daniel Barkalow 已提交
690
		add_header(value);
691 692
		return 0;
	}
693 694
	if (!strcmp(var, "format.suffix"))
		return git_config_string(&fmt_patch_suffix, var, value);
695 696 697
	if (!strcmp(var, "format.to")) {
		if (!value)
			return config_error_nonbool(var);
698
		string_list_append(&extra_to, value);
699 700
		return 0;
	}
701 702 703
	if (!strcmp(var, "format.cc")) {
		if (!value)
			return config_error_nonbool(var);
704
		string_list_append(&extra_cc, value);
705 706
		return 0;
	}
P
Pang Yan Han 已提交
707 708
	if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
	    !strcmp(var, "color.ui")) {
709 710
		return 0;
	}
711
	if (!strcmp(var, "format.numbered")) {
712
		if (value && !strcasecmp(value, "auto")) {
713 714 715 716
			auto_number = 1;
			return 0;
		}
		numbered = git_config_bool(var, value);
717
		auto_number = auto_number && numbered;
718 719
		return 0;
	}
720 721 722 723 724 725 726
	if (!strcmp(var, "format.attach")) {
		if (value && *value)
			default_attach = xstrdup(value);
		else
			default_attach = xstrdup(git_version_string);
		return 0;
	}
727 728 729 730 731 732 733 734 735 736 737 738
	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;
	}
739 740 741 742
	if (!strcmp(var, "format.signoff")) {
		do_signoff = git_config_bool(var, value);
		return 0;
	}
743 744
	if (!strcmp(var, "format.signature"))
		return git_config_string(&signature, var, value);
745 746
	if (!strcmp(var, "format.signaturefile"))
		return git_config_pathname(&signature_file, var, value);
747 748 749 750 751 752 753 754
	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;
	}
755

756
	return git_log_config(var, value, cb);
757 758
}

759
static FILE *realstdout = NULL;
760
static const char *output_directory = NULL;
761
static int outdir_offset;
762

763 764
static int reopen_stdout(struct commit *commit, const char *subject,
			 struct rev_info *rev, int quiet)
765
{
766
	struct strbuf filename = STRBUF_INIT;
767
	int suffix_len = strlen(rev->patch_suffix) + 1;
768

769
	if (output_directory) {
770 771 772
		strbuf_addstr(&filename, output_directory);
		if (filename.len >=
		    PATH_MAX - FORMAT_PATCH_NAME_MAX - suffix_len)
773
			return error(_("name of output directory is too long"));
774 775
		if (filename.buf[filename.len - 1] != '/')
			strbuf_addch(&filename, '/');
776
	}
777

778 779
	if (rev->numbered_files)
		strbuf_addf(&filename, "%d", rev->nr);
780 781
	else if (commit)
		fmt_output_commit(&filename, commit, rev);
782
	else
783
		fmt_output_subject(&filename, subject, rev);
784

785
	if (!quiet)
786
		fprintf(realstdout, "%s\n", filename.buf + outdir_offset);
N
Nate Case 已提交
787

788
	if (freopen(filename.buf, "w", stdout) == NULL)
789
		return error(_("Cannot open patch file %s"), filename.buf);
790

791
	strbuf_release(&filename);
792
	return 0;
793 794
}

795
static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
796 797 798 799 800 801 802
{
	struct rev_info check_rev;
	struct commit *commit;
	struct object *o1, *o2;
	unsigned flags1, flags2;

	if (rev->pending.nr != 2)
803
		die(_("Need exactly one range."));
804 805 806 807 808 809 810

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

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

813
	init_patch_ids(ids);
814 815

	/* given a range a..b get all patch ids for b..a */
816
	init_revisions(&check_rev, rev->prefix);
817
	check_rev.max_parents = 1;
818 819 820 821
	o1->flags ^= UNINTERESTING;
	o2->flags ^= UNINTERESTING;
	add_pending_object(&check_rev, o1, "o1");
	add_pending_object(&check_rev, o2, "o2");
822
	if (prepare_revision_walk(&check_rev))
823
		die(_("revision walk setup failed"));
824 825

	while ((commit = get_revision(&check_rev)) != NULL) {
826
		add_commit_patch_id(commit, ids);
827 828 829
	}

	/* reset for next revision walk */
830 831 832 833
	clear_commit_marks((struct commit *)o1,
			SEEN | UNINTERESTING | SHOWN | ADDED);
	clear_commit_marks((struct commit *)o2,
			SEEN | UNINTERESTING | SHOWN | ADDED);
834 835 836 837
	o1->flags = flags1;
	o2->flags = flags2;
}

838
static void gen_message_id(struct rev_info *info, char *base)
839
{
840
	struct strbuf buf = STRBUF_INIT;
841
	strbuf_addf(&buf, "%s.%lu.git.%s", base,
842
		    (unsigned long) time(NULL),
843
		    git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
844
	info->message_id = strbuf_detach(&buf, NULL);
845 846
}

847 848
static void print_signature(void)
{
849 850 851 852 853 854 855
	if (!signature || !*signature)
		return;

	printf("-- \n%s", signature);
	if (signature[strlen(signature)-1] != '\n')
		putchar('\n');
	putchar('\n');
856 857
}

858 859 860 861 862 863 864 865
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');
866
		strbuf_addbuf(buf, &desc);
867 868
		strbuf_addch(buf, '\n');
	}
869
	strbuf_release(&desc);
870 871
}

872 873 874 875 876
static char *find_branch_name(struct rev_info *rev)
{
	int i, positive = -1;
	unsigned char branch_sha1[20];
	const unsigned char *tip_sha1;
877
	const char *ref, *v;
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	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;
	tip_sha1 = rev->cmdline.rev[positive].item->sha1;
	if (dwim_ref(ref, strlen(ref), branch_sha1, &full_ref) &&
893
	    skip_prefix(full_ref, "refs/heads/", &v) &&
894
	    !hashcmp(tip_sha1, branch_sha1))
895
		branch = xstrdup(v);
896 897 898 899
	free(full_ref);
	return branch;
}

900 901
static void make_cover_letter(struct rev_info *rev, int use_stdout,
			      struct commit *origin,
902
			      int nr, struct commit **list,
903
			      const char *branch_name,
904
			      int quiet)
905 906 907 908
{
	const char *committer;
	const char *body = "*** SUBJECT HERE ***\n\n*** BLURB HERE ***\n";
	const char *msg;
909
	struct shortlog log;
910
	struct strbuf sb = STRBUF_INIT;
911
	int i;
912
	const char *encoding = "UTF-8";
913
	struct diff_options opts;
J
Junio C Hamano 已提交
914
	int need_8bit_cte = 0;
915
	struct pretty_print_context pp = {0};
916
	struct commit *head = list[0];
917 918

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

921
	committer = git_committer_info(0);
922

923
	if (!use_stdout &&
924
	    reopen_stdout(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
925 926
		return;

927
	log_write_email_headers(rev, head, &pp.subject, &pp.after_subject,
J
Junio C Hamano 已提交
928
				&need_8bit_cte);
929

J
Jeff King 已提交
930
	for (i = 0; !need_8bit_cte && i < nr; i++) {
931
		const char *buf = get_commit_buffer(list[i], NULL);
J
Jeff King 已提交
932
		if (has_non_ascii(buf))
933
			need_8bit_cte = 1;
J
Jeff King 已提交
934 935
		unuse_commit_buffer(list[i], buf);
	}
936

937 938 939
	if (!branch_name)
		branch_name = find_branch_name(rev);

940
	msg = body;
941 942 943 944 945
	pp.fmt = CMIT_FMT_EMAIL;
	pp.date_mode = DATE_RFC2822;
	pp_user_info(&pp, NULL, &sb, committer, encoding);
	pp_title_line(&pp, &msg, &sb, encoding, need_8bit_cte);
	pp_remainder(&pp, &msg, &sb, 0);
946
	add_branch_description(&sb, branch_name);
947 948 949 950
	printf("%s\n", sb.buf);

	strbuf_release(&sb);

951
	shortlog_init(&log);
952 953 954 955
	log.wrap_lines = 1;
	log.wrap = 72;
	log.in1 = 2;
	log.in2 = 4;
956 957 958 959 960
	for (i = 0; i < nr; i++)
		shortlog_add_commit(&log, list[i]);

	shortlog_output(&log);

961
	/*
962
	 * We can only do diffstat with a unique reference point
963 964 965 966
	 */
	if (!origin)
		return;

967 968
	memcpy(&opts, &rev->diffopt, sizeof(opts));
	opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
969

970 971 972 973 974 975 976
	diff_setup_done(&opts);

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

	printf("\n");
979
	print_signature();
980 981
}

982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
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)
998
		die(_("insane in-reply-to: %s"), msg_id);
999 1000
	if (++z == m)
		return a;
P
Pierre Habouzit 已提交
1001
	return xmemdupz(a, z - a);
1002 1003
}

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
static const char *set_outdir(const char *prefix, const char *output_directory)
{
	if (output_directory && is_absolute_path(output_directory))
		return output_directory;

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

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

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

1025
static const char * const builtin_format_patch_usage[] = {
1026
	N_("git format-patch [options] [<since> | <revision range>]"),
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	NULL
};

static int keep_subject = 0;

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

static int subject_prefix = 0;

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

1049 1050
static int numbered_cmdline_opt = 0;

1051 1052 1053
static int numbered_callback(const struct option *opt, const char *arg,
			     int unset)
{
1054
	*(int *)opt->value = numbered_cmdline_opt = unset ? 0 : 1;
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
	if (unset)
		auto_number =  0;
	return 0;
}

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

static int output_directory_callback(const struct option *opt, const char *arg,
			      int unset)
{
	const char **dir = (const char **)opt->value;
	if (*dir)
1071
		die(_("Two output directories?"));
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
	*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)
{
1118 1119 1120 1121 1122 1123 1124
	if (unset) {
		string_list_clear(&extra_hdr, 0);
		string_list_clear(&extra_to, 0);
		string_list_clear(&extra_cc, 0);
	} else {
	    add_header(arg);
	}
1125 1126 1127
	return 0;
}

1128 1129
static int to_callback(const struct option *opt, const char *arg, int unset)
{
1130 1131 1132
	if (unset)
		string_list_clear(&extra_to, 0);
	else
1133
		string_list_append(&extra_to, arg);
1134 1135 1136 1137 1138
	return 0;
}

static int cc_callback(const struct option *opt, const char *arg, int unset)
{
1139 1140 1141
	if (unset)
		string_list_clear(&extra_cc, 0);
	else
1142
		string_list_append(&extra_cc, arg);
1143 1144 1145
	return 0;
}

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
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;
}

1161
int cmd_format_patch(int argc, const char **argv, const char *prefix)
1162 1163 1164 1165
{
	struct commit *commit;
	struct commit **list = NULL;
	struct rev_info rev;
1166
	struct setup_revision_opt s_r_opt;
1167
	int nr = 0, total, i;
1168
	int use_stdout = 0;
1169
	int start_number = -1;
1170
	int just_numbers = 0;
1171
	int ignore_if_in_upstream = 0;
1172
	int cover_letter = -1;
1173
	int boundary_count = 0;
1174
	int no_binary_diff = 0;
1175
	struct commit *origin = NULL;
1176
	const char *in_reply_to = NULL;
1177
	struct patch_ids ids;
1178
	struct strbuf buf = STRBUF_INIT;
1179
	int use_patch_format = 0;
1180
	int quiet = 0;
1181
	int reroll_count = -1;
1182
	char *branch_name = NULL;
1183
	char *from = NULL;
1184 1185
	const struct option builtin_format_patch_options[] = {
		{ OPTION_CALLBACK, 'n', "numbered", &numbered, NULL,
1186
			    N_("use [PATCH n/m] even with a single patch"),
1187 1188
			    PARSE_OPT_NOARG, numbered_callback },
		{ OPTION_CALLBACK, 'N', "no-numbered", &numbered, NULL,
1189
			    N_("use [PATCH] even with multiple patches"),
1190
			    PARSE_OPT_NOARG, no_numbered_callback },
F
Felipe Contreras 已提交
1191 1192
		OPT_BOOL('s', "signoff", &do_signoff, N_("add Signed-off-by:")),
		OPT_BOOL(0, "stdout", &use_stdout,
1193
			    N_("print patches to standard out")),
F
Felipe Contreras 已提交
1194
		OPT_BOOL(0, "cover-letter", &cover_letter,
1195
			    N_("generate a cover letter")),
F
Felipe Contreras 已提交
1196
		OPT_BOOL(0, "numbered-files", &just_numbers,
1197 1198 1199
			    N_("use simple number sequence for output file names")),
		OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
			    N_("use <sfx> instead of '.patch'")),
1200
		OPT_INTEGER(0, "start-number", &start_number,
1201
			    N_("start numbering patches at <n> instead of 1")),
1202
		OPT_INTEGER('v', "reroll-count", &reroll_count,
1203
			    N_("mark the series as Nth re-roll")),
1204 1205
		{ OPTION_CALLBACK, 0, "subject-prefix", &rev, N_("prefix"),
			    N_("Use [<prefix>] instead of [PATCH]"),
1206 1207
			    PARSE_OPT_NONEG, subject_prefix_callback },
		{ OPTION_CALLBACK, 'o', "output-directory", &output_directory,
1208
			    N_("dir"), N_("store resulting files in <dir>"),
1209 1210
			    PARSE_OPT_NONEG, output_directory_callback },
		{ OPTION_CALLBACK, 'k', "keep-subject", &rev, NULL,
1211
			    N_("don't strip/add [PATCH]"),
1212
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback },
1213 1214 1215 1216
		OPT_BOOL(0, "no-binary", &no_binary_diff,
			 N_("don't output binary diffs")),
		OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
			 N_("don't include a patch matching a commit upstream")),
1217
		{ OPTION_SET_INT, 'p', "no-stat", &use_patch_format, NULL,
1218
		  N_("show patch format instead of default (patch + stat)"),
1219
		  PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1},
1220 1221 1222 1223
		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"),
1224
			    0, to_callback },
1225
		{ OPTION_CALLBACK, 0, "cc", NULL, N_("email"), N_("add Cc: header"),
1226
			    0, cc_callback },
1227 1228 1229
		{ OPTION_CALLBACK, 0, "from", &from, N_("ident"),
			    N_("set From address to <ident> (or committer ident if absent)"),
			    PARSE_OPT_OPTARG, from_callback },
1230 1231 1232 1233
		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,
1234
			    attach_callback },
1235 1236
		{ OPTION_CALLBACK, 0, "inline", &rev, N_("boundary"),
			    N_("inline the patch"),
1237 1238
			    PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
			    inline_callback },
1239 1240
		{ OPTION_CALLBACK, 0, "thread", &thread, N_("style"),
			    N_("enable message threading, styles: shallow, deep"),
1241
			    PARSE_OPT_OPTARG, thread_callback },
1242 1243
		OPT_STRING(0, "signature", &signature, N_("signature"),
			    N_("add a signature")),
1244 1245
		OPT_FILENAME(0, "signature-file", &signature_file,
				N_("add a signature from a file")),
1246
		OPT__QUIET(&quiet, N_("don't print the patch filenames")),
1247 1248
		OPT_END()
	};
1249

1250 1251 1252
	extra_hdr.strdup_strings = 1;
	extra_to.strdup_strings = 1;
	extra_cc.strdup_strings = 1;
J
Junio C Hamano 已提交
1253
	init_grep_defaults();
1254
	git_config(git_format_config, NULL);
1255
	init_revisions(&rev, prefix);
1256 1257 1258
	rev.commit_format = CMIT_FMT_EMAIL;
	rev.verbose_header = 1;
	rev.diff = 1;
1259
	rev.max_parents = 1;
1260
	DIFF_OPT_SET(&rev.diffopt, RECURSIVE);
1261
	rev.subject_prefix = fmt_patch_subject_prefix;
1262 1263
	memset(&s_r_opt, 0, sizeof(s_r_opt));
	s_r_opt.def = "HEAD";
1264
	s_r_opt.revarg_opt = REVARG_COMMITTISH;
1265

1266 1267 1268 1269 1270
	if (default_attach) {
		rev.mime_boundary = default_attach;
		rev.no_inline = 1;
	}

1271 1272
	/*
	 * Parse the arguments before setup_revisions(), or something
1273
	 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
1274 1275
	 * possibly a valid SHA1.
	 */
1276
	argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
1277
			     builtin_format_patch_usage,
1278 1279
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
			     PARSE_OPT_KEEP_DASHDASH);
1280

1281 1282 1283 1284 1285 1286 1287 1288
	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);
	}

1289 1290
	for (i = 0; i < extra_hdr.nr; i++) {
		strbuf_addstr(&buf, extra_hdr.items[i].string);
D
Daniel Barkalow 已提交
1291 1292 1293
		strbuf_addch(&buf, '\n');
	}

1294
	if (extra_to.nr)
D
Daniel Barkalow 已提交
1295
		strbuf_addstr(&buf, "To: ");
1296
	for (i = 0; i < extra_to.nr; i++) {
D
Daniel Barkalow 已提交
1297 1298
		if (i)
			strbuf_addstr(&buf, "    ");
1299 1300
		strbuf_addstr(&buf, extra_to.items[i].string);
		if (i + 1 < extra_to.nr)
D
Daniel Barkalow 已提交
1301 1302 1303 1304
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

1305
	if (extra_cc.nr)
D
Daniel Barkalow 已提交
1306
		strbuf_addstr(&buf, "Cc: ");
1307
	for (i = 0; i < extra_cc.nr; i++) {
D
Daniel Barkalow 已提交
1308 1309
		if (i)
			strbuf_addstr(&buf, "    ");
1310 1311
		strbuf_addstr(&buf, extra_cc.items[i].string);
		if (i + 1 < extra_cc.nr)
D
Daniel Barkalow 已提交
1312 1313 1314 1315
			strbuf_addch(&buf, ',');
		strbuf_addch(&buf, '\n');
	}

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

1318 1319 1320 1321 1322
	if (from) {
		if (split_ident_line(&rev.from_ident, from, strlen(from)))
			die(_("invalid ident line: %s"), from);
	}

1323
	if (start_number < 0)
1324
		start_number = 1;
1325 1326 1327 1328 1329 1330 1331 1332 1333

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

1334
	if (numbered && keep_subject)
1335
		die (_("-n and -k are mutually exclusive."));
1336
	if (keep_subject && subject_prefix)
1337
		die (_("--subject-prefix and -k are mutually exclusive."));
1338
	rev.preserve_subject = keep_subject;
1339

1340
	argc = setup_revisions(argc, argv, &rev, &s_r_opt);
1341
	if (argc > 1)
1342
		die (_("unrecognized argument: %s"), argv[1]);
1343

1344
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
1345
		die(_("--name-only does not make sense"));
1346
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
1347
		die(_("--name-status does not make sense"));
1348
	if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
1349
		die(_("--check does not make sense"));
1350 1351 1352 1353 1354 1355 1356 1357

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

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

1359
	if (!DIFF_OPT_TST(&rev.diffopt, TEXT) && !no_binary_diff)
1360
		DIFF_OPT_SET(&rev.diffopt, BINARY);
1361

1362 1363 1364
	if (rev.show_notes)
		init_display_notes(&rev.notes_opt);

1365 1366
	if (!use_stdout)
		output_directory = set_outdir(prefix, output_directory);
1367 1368
	else
		setup_pager();
1369

1370 1371
	if (output_directory) {
		if (use_stdout)
1372
			die(_("standard output, or directory, which one?"));
1373
		if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
1374
			die_errno(_("Could not create directory '%s'"),
1375
				  output_directory);
1376 1377
	}

1378
	if (rev.pending.nr == 1) {
1379 1380
		int check_head = 0;

1381 1382 1383 1384 1385 1386
		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 已提交
1387
			rev.pending.objects[0].item->flags |= UNINTERESTING;
1388
			add_head_to_pending(&rev);
1389
			check_head = 1;
J
Junio C Hamano 已提交
1390
		}
1391 1392 1393 1394
		/*
		 * 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 已提交
1395
		 */
1396 1397 1398 1399 1400 1401

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

		if (check_head) {
			unsigned char sha1[20];
1402
			const char *ref, *v;
1403 1404
			ref = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
						 sha1, NULL);
1405 1406
			if (ref && skip_prefix(ref, "refs/heads/", &v))
				branch_name = xstrdup(v);
1407 1408 1409
			else
				branch_name = xstrdup(""); /* no branch */
		}
1410
	}
1411 1412 1413

	/*
	 * We cannot move this anywhere earlier because we do want to
1414
	 * know if --root was given explicitly from the command line.
1415 1416 1417
	 */
	rev.show_root_diff = 1;

1418 1419 1420 1421 1422 1423 1424
	if (ignore_if_in_upstream) {
		/* Don't say anything if head and upstream are the same. */
		if (rev.pending.nr == 2) {
			struct object_array_entry *o = rev.pending.objects;
			if (hashcmp(o[0].item->sha1, o[1].item->sha1) == 0)
				return 0;
		}
1425
		get_patch_ids(&rev, &ids);
1426
	}
1427

1428
	if (!use_stdout)
1429
		realstdout = xfdopen(xdup(1), "w");
1430

1431
	if (prepare_revision_walk(&rev))
1432
		die(_("revision walk setup failed"));
1433
	rev.boundary = 1;
1434
	while ((commit = get_revision(&rev)) != NULL) {
1435 1436 1437 1438 1439 1440
		if (commit->object.flags & BOUNDARY) {
			boundary_count++;
			origin = (boundary_count == 1) ? commit : NULL;
			continue;
		}

1441
		if (ignore_if_in_upstream &&
1442
				has_commit_patch_id(commit, &ids))
1443 1444
			continue;

1445
		nr++;
1446
		REALLOC_ARRAY(list, nr);
1447 1448
		list[nr - 1] = commit;
	}
1449 1450 1451
	if (nr == 0)
		/* nothing to do */
		return 0;
1452
	total = nr;
1453 1454
	if (!keep_subject && auto_number && total > 1)
		numbered = 1;
1455
	if (numbered)
1456
		rev.total = total + start_number - 1;
1457 1458 1459 1460 1461 1462 1463
	if (cover_letter == -1) {
		if (config_cover_letter == COVER_AUTO)
			cover_letter = (total > 1);
		else
			cover_letter = (config_cover_letter == COVER_ON);
	}

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
	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);
	}

1476 1477 1478 1479
	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);
1480
		string_list_append(rev.ref_message_ids, msgid);
1481
	}
1482
	rev.numbered_files = just_numbers;
1483
	rev.patch_suffix = fmt_patch_suffix;
1484 1485 1486
	if (cover_letter) {
		if (thread)
			gen_message_id(&rev, "cover");
1487
		make_cover_letter(&rev, use_stdout,
1488
				  origin, nr, list, branch_name, quiet);
1489 1490 1491
		total++;
		start_number--;
	}
1492
	rev.add_signoff = do_signoff;
1493 1494 1495
	while (0 <= --nr) {
		int shown;
		commit = list[nr];
1496
		rev.nr = total - nr + (start_number - 1);
1497
		/* Make the second and subsequent mails replies to the first */
1498
		if (thread) {
1499
			/* Have we already had a message ID? */
1500
			if (rev.message_id) {
1501
				/*
1502 1503 1504 1505 1506 1507
				 * For deep threading: make every mail
				 * a reply to the previous one, no
				 * matter what other options are set.
				 *
				 * For shallow threading:
				 *
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520
				 * 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.
1521
				 */
1522 1523
				if (thread == THREAD_SHALLOW
				    && rev.ref_message_ids->nr > 0
1524
				    && (!cover_letter || rev.nr > 1))
1525 1526
					free(rev.message_id);
				else
1527 1528
					string_list_append(rev.ref_message_ids,
							   rev.message_id);
1529
			}
1530
			gen_message_id(&rev, sha1_to_hex(commit->object.sha1));
1531
		}
1532

1533
		if (!use_stdout &&
1534
		    reopen_stdout(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
1535
			die(_("Failed to create output files"));
1536
		shown = log_tree_commit(&rev, commit);
1537
		free_commit_buffer(commit);
1538 1539 1540 1541 1542 1543 1544 1545 1546

		/* 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;
1547 1548 1549 1550 1551 1552
		if (shown) {
			if (rev.mime_boundary)
				printf("\n--%s%s--\n\n\n",
				       mime_boundary_leader,
				       rev.mime_boundary);
			else
1553
				print_signature();
1554
		}
1555 1556
		if (!use_stdout)
			fclose(stdout);
1557 1558
	}
	free(list);
1559
	free(branch_name);
1560 1561 1562
	string_list_clear(&extra_to, 0);
	string_list_clear(&extra_cc, 0);
	string_list_clear(&extra_hdr, 0);
1563 1564
	if (ignore_if_in_upstream)
		free_patch_ids(&ids);
1565 1566 1567
	return 0;
}

R
Rene Scharfe 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
{
	unsigned char sha1[20];
	if (get_sha1(arg, sha1) == 0) {
		struct commit *commit = lookup_commit_reference(sha1);
		if (commit) {
			commit->object.flags |= flags;
			add_pending_object(revs, &commit->object, arg);
			return 0;
		}
	}
	return -1;
}

E
Erik Faye-Lund 已提交
1582
static const char * const cherry_usage[] = {
1583
	N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
E
Erik Faye-Lund 已提交
1584 1585 1586
	NULL
};

1587 1588 1589 1590 1591 1592 1593 1594
static void print_commit(char sign, struct commit *commit, int verbose,
			 int abbrev)
{
	if (!verbose) {
		printf("%c %s\n", sign,
		       find_unique_abbrev(commit->object.sha1, abbrev));
	} else {
		struct strbuf buf = STRBUF_INIT;
1595
		pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
1596 1597 1598 1599 1600 1601 1602
		printf("%c %s %s\n", sign,
		       find_unique_abbrev(commit->object.sha1, abbrev),
		       buf.buf);
		strbuf_release(&buf);
	}
}

R
Rene Scharfe 已提交
1603 1604 1605
int cmd_cherry(int argc, const char **argv, const char *prefix)
{
	struct rev_info revs;
1606
	struct patch_ids ids;
R
Rene Scharfe 已提交
1607 1608
	struct commit *commit;
	struct commit_list *list = NULL;
1609
	struct branch *current_branch;
R
Rene Scharfe 已提交
1610 1611 1612
	const char *upstream;
	const char *head = "HEAD";
	const char *limit = NULL;
E
Erik Faye-Lund 已提交
1613
	int verbose = 0, abbrev = 0;
R
Rene Scharfe 已提交
1614

E
Erik Faye-Lund 已提交
1615 1616
	struct option options[] = {
		OPT__ABBREV(&abbrev),
1617
		OPT__VERBOSE(&verbose, N_("be verbose")),
E
Erik Faye-Lund 已提交
1618 1619
		OPT_END()
	};
R
Rene Scharfe 已提交
1620

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

R
Rene Scharfe 已提交
1623 1624
	switch (argc) {
	case 3:
E
Erik Faye-Lund 已提交
1625
		limit = argv[2];
R
Rene Scharfe 已提交
1626 1627
		/* FALLTHROUGH */
	case 2:
E
Erik Faye-Lund 已提交
1628 1629 1630 1631
		head = argv[1];
		/* FALLTHROUGH */
	case 1:
		upstream = argv[0];
R
Rene Scharfe 已提交
1632 1633
		break;
	default:
1634 1635 1636 1637
		current_branch = branch_get(NULL);
		if (!current_branch || !current_branch->merge
					|| !current_branch->merge[0]
					|| !current_branch->merge[0]->dst) {
1638
			fprintf(stderr, _("Could not find a tracked"
1639
					" remote branch, please"
1640
					" specify <upstream> manually.\n"));
E
Erik Faye-Lund 已提交
1641
			usage_with_options(cherry_usage, options);
1642 1643 1644
		}

		upstream = current_branch->merge[0]->dst;
R
Rene Scharfe 已提交
1645 1646 1647
	}

	init_revisions(&revs, prefix);
1648
	revs.max_parents = 1;
R
Rene Scharfe 已提交
1649 1650

	if (add_pending_commit(head, &revs, 0))
1651
		die(_("Unknown commit %s"), head);
R
Rene Scharfe 已提交
1652
	if (add_pending_commit(upstream, &revs, UNINTERESTING))
1653
		die(_("Unknown commit %s"), upstream);
R
Rene Scharfe 已提交
1654 1655 1656 1657 1658 1659 1660 1661

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

1662
	get_patch_ids(&revs, &ids);
R
Rene Scharfe 已提交
1663 1664

	if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
1665
		die(_("Unknown commit %s"), limit);
R
Rene Scharfe 已提交
1666 1667

	/* reverse the list of commits */
1668
	if (prepare_revision_walk(&revs))
1669
		die(_("revision walk setup failed"));
R
Rene Scharfe 已提交
1670 1671 1672 1673 1674 1675 1676 1677
	while ((commit = get_revision(&revs)) != NULL) {
		commit_list_insert(commit, &list);
	}

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

		commit = list->item;
1678
		if (has_commit_patch_id(commit, &ids))
R
Rene Scharfe 已提交
1679
			sign = '-';
1680
		print_commit(sign, commit, verbose, abbrev);
R
Rene Scharfe 已提交
1681 1682 1683
		list = list->next;
	}

1684
	free_patch_ids(&ids);
R
Rene Scharfe 已提交
1685 1686
	return 0;
}