git

Форк
0
/
log.c 
2702 строки · 72.9 Кб
1
/*
2
 * Builtin "git log" and related commands (show, whatchanged)
3
 *
4
 * (C) Copyright 2006 Linus Torvalds
5
 *		 2006 Junio Hamano
6
 */
7
#include "builtin.h"
8
#include "abspath.h"
9
#include "config.h"
10
#include "environment.h"
11
#include "gettext.h"
12
#include "hex.h"
13
#include "refs.h"
14
#include "object-file.h"
15
#include "object-name.h"
16
#include "object-store-ll.h"
17
#include "pager.h"
18
#include "color.h"
19
#include "commit.h"
20
#include "diff.h"
21
#include "diff-merges.h"
22
#include "revision.h"
23
#include "log-tree.h"
24
#include "builtin.h"
25
#include "oid-array.h"
26
#include "tag.h"
27
#include "reflog-walk.h"
28
#include "patch-ids.h"
29
#include "shortlog.h"
30
#include "remote.h"
31
#include "string-list.h"
32
#include "parse-options.h"
33
#include "line-log.h"
34
#include "branch.h"
35
#include "streaming.h"
36
#include "version.h"
37
#include "mailmap.h"
38
#include "progress.h"
39
#include "commit-slab.h"
40
#include "repository.h"
41
#include "commit-reach.h"
42
#include "range-diff.h"
43
#include "tmp-objdir.h"
44
#include "tree.h"
45
#include "write-or-die.h"
46

47
#define MAIL_DEFAULT_WRAP 72
48
#define COVER_FROM_AUTO_MAX_SUBJECT_LEN 100
49
#define FORMAT_PATCH_NAME_MAX_DEFAULT 64
50

51
static unsigned int force_in_body_from;
52
static int stdout_mboxrd;
53
static int format_no_prefix;
54

55
static const char * const builtin_log_usage[] = {
56
	N_("git log [<options>] [<revision-range>] [[--] <path>...]"),
57
	N_("git show [<options>] <object>..."),
58
	NULL
59
};
60

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

67
static int session_is_interactive(void)
68
{
69
	return isatty(1) || pager_in_use();
70
}
71

72
static int auto_decoration_style(void)
73
{
74
	return session_is_interactive() ? DECORATE_SHORT_REFS : 0;
75
}
76

77
static int parse_decoration_style(const char *value)
78
{
79
	switch (git_parse_maybe_bool(value)) {
80
	case 1:
81
		return DECORATE_SHORT_REFS;
82
	case 0:
83
		return 0;
84
	default:
85
		break;
86
	}
87
	if (!strcmp(value, "full"))
88
		return DECORATE_FULL_REFS;
89
	else if (!strcmp(value, "short"))
90
		return DECORATE_SHORT_REFS;
91
	else if (!strcmp(value, "auto"))
92
		return auto_decoration_style();
93
	/*
94
	 * Please update _git_log() in git-completion.bash when you
95
	 * add new decoration styles.
96
	 */
97
	return -1;
98
}
99

100
struct log_config {
101
	int default_abbrev_commit;
102
	int default_show_root;
103
	int default_follow;
104
	int default_show_signature;
105
	int default_encode_email_headers;
106
	int decoration_style;
107
	int decoration_given;
108
	int use_mailmap_config;
109
	char *fmt_patch_subject_prefix;
110
	int fmt_patch_name_max;
111
	char *fmt_pretty;
112
	char *default_date_mode;
113
};
114

115
static void log_config_init(struct log_config *cfg)
116
{
117
	memset(cfg, 0, sizeof(*cfg));
118
	cfg->default_show_root = 1;
119
	cfg->default_encode_email_headers = 1;
120
	cfg->use_mailmap_config = 1;
121
	cfg->fmt_patch_subject_prefix = xstrdup("PATCH");
122
	cfg->fmt_patch_name_max = FORMAT_PATCH_NAME_MAX_DEFAULT;
123
	cfg->decoration_style = auto_decoration_style();
124
}
125

126
static void log_config_release(struct log_config *cfg)
127
{
128
	free(cfg->default_date_mode);
129
	free(cfg->fmt_pretty);
130
	free(cfg->fmt_patch_subject_prefix);
131
}
132

133
static int use_default_decoration_filter = 1;
134
static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
135
static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
136
static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
137

138
static int clear_decorations_callback(const struct option *opt UNUSED,
139
				      const char *arg, int unset)
140
{
141
	BUG_ON_OPT_NEG(unset);
142
	BUG_ON_OPT_ARG(arg);
143
	string_list_clear(&decorate_refs_include, 0);
144
	string_list_clear(&decorate_refs_exclude, 0);
145
	use_default_decoration_filter = 0;
146
	return 0;
147
}
148

149
static int decorate_callback(const struct option *opt, const char *arg,
150
			     int unset)
151
{
152
	struct log_config *cfg = opt->value;
153

154
	if (unset)
155
		cfg->decoration_style = 0;
156
	else if (arg)
157
		cfg->decoration_style = parse_decoration_style(arg);
158
	else
159
		cfg->decoration_style = DECORATE_SHORT_REFS;
160

161
	if (cfg->decoration_style < 0)
162
		die(_("invalid --decorate option: %s"), arg);
163

164
	cfg->decoration_given = 1;
165

166
	return 0;
167
}
168

169
static int log_line_range_callback(const struct option *option, const char *arg, int unset)
170
{
171
	struct line_opt_callback_data *data = option->value;
172

173
	BUG_ON_OPT_NEG(unset);
174

175
	if (!arg)
176
		return -1;
177

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

181
	return 0;
182
}
183

184
static void cmd_log_init_defaults(struct rev_info *rev,
185
				  struct log_config *cfg)
186
{
187
	if (cfg->fmt_pretty)
188
		get_commit_format(cfg->fmt_pretty, rev);
189
	if (cfg->default_follow)
190
		rev->diffopt.flags.default_follow_renames = 1;
191
	rev->verbose_header = 1;
192
	init_diffstat_widths(&rev->diffopt);
193
	rev->diffopt.flags.recursive = 1;
194
	rev->diffopt.flags.allow_textconv = 1;
195
	rev->abbrev_commit = cfg->default_abbrev_commit;
196
	rev->show_root_diff = cfg->default_show_root;
197
	rev->subject_prefix = cfg->fmt_patch_subject_prefix;
198
	rev->patch_name_max = cfg->fmt_patch_name_max;
199
	rev->show_signature = cfg->default_show_signature;
200
	rev->encode_email_headers = cfg->default_encode_email_headers;
201

202
	if (cfg->default_date_mode)
203
		parse_date_format(cfg->default_date_mode, &rev->date_mode);
204
}
205

206
static void set_default_decoration_filter(struct decoration_filter *decoration_filter)
207
{
208
	int i;
209
	char *value = NULL;
210
	struct string_list *include = decoration_filter->include_ref_pattern;
211
	const struct string_list *config_exclude;
212

213
	if (!git_config_get_string_multi("log.excludeDecoration",
214
					 &config_exclude)) {
215
		struct string_list_item *item;
216
		for_each_string_list_item(item, config_exclude)
217
			string_list_append(decoration_filter->exclude_ref_config_pattern,
218
					   item->string);
219
	}
220

221
	/*
222
	 * By default, decorate_all is disabled. Enable it if
223
	 * log.initialDecorationSet=all. Don't ever disable it by config,
224
	 * since the command-line takes precedent.
225
	 */
226
	if (use_default_decoration_filter &&
227
	    !git_config_get_string("log.initialdecorationset", &value) &&
228
	    !strcmp("all", value))
229
		use_default_decoration_filter = 0;
230
	free(value);
231

232
	if (!use_default_decoration_filter ||
233
	    decoration_filter->exclude_ref_pattern->nr ||
234
	    decoration_filter->include_ref_pattern->nr ||
235
	    decoration_filter->exclude_ref_config_pattern->nr)
236
		return;
237

238
	/*
239
	 * No command-line or config options were given, so
240
	 * populate with sensible defaults.
241
	 */
242
	for (i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
243
		if (!ref_namespace[i].decoration)
244
			continue;
245

246
		string_list_append(include, ref_namespace[i].ref);
247
	}
248
}
249

250
static void cmd_log_init_finish(int argc, const char **argv, const char *prefix,
251
			 struct rev_info *rev, struct setup_revision_opt *opt,
252
			 struct log_config *cfg)
253
{
254
	struct userformat_want w;
255
	int quiet = 0, source = 0, mailmap;
256
	static struct line_opt_callback_data line_cb = {NULL, NULL, STRING_LIST_INIT_DUP};
257
	struct decoration_filter decoration_filter = {
258
		.exclude_ref_pattern = &decorate_refs_exclude,
259
		.include_ref_pattern = &decorate_refs_include,
260
		.exclude_ref_config_pattern = &decorate_refs_exclude_config,
261
	};
262
	static struct revision_sources revision_sources;
263

264
	const struct option builtin_log_options[] = {
265
		OPT__QUIET(&quiet, N_("suppress diff output")),
266
		OPT_BOOL(0, "source", &source, N_("show source")),
267
		OPT_BOOL(0, "use-mailmap", &mailmap, N_("use mail map file")),
268
		OPT_ALIAS(0, "mailmap", "use-mailmap"),
269
		OPT_CALLBACK_F(0, "clear-decorations", NULL, NULL,
270
			       N_("clear all previously-defined decoration filters"),
271
			       PARSE_OPT_NOARG | PARSE_OPT_NONEG,
272
			       clear_decorations_callback),
273
		OPT_STRING_LIST(0, "decorate-refs", &decorate_refs_include,
274
				N_("pattern"), N_("only decorate refs that match <pattern>")),
275
		OPT_STRING_LIST(0, "decorate-refs-exclude", &decorate_refs_exclude,
276
				N_("pattern"), N_("do not decorate refs that match <pattern>")),
277
		OPT_CALLBACK_F(0, "decorate", cfg, NULL, N_("decorate options"),
278
			       PARSE_OPT_OPTARG, decorate_callback),
279
		OPT_CALLBACK('L', NULL, &line_cb, "range:file",
280
			     N_("trace the evolution of line range <start>,<end> or function :<funcname> in <file>"),
281
			     log_line_range_callback),
282
		OPT_END()
283
	};
284

285
	line_cb.rev = rev;
286
	line_cb.prefix = prefix;
287

288
	mailmap = cfg->use_mailmap_config;
289
	argc = parse_options(argc, argv, prefix,
290
			     builtin_log_options, builtin_log_usage,
291
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
292
			     PARSE_OPT_KEEP_DASHDASH);
293

294
	if (quiet)
295
		rev->diffopt.output_format |= DIFF_FORMAT_NO_OUTPUT;
296
	argc = setup_revisions(argc, argv, rev, opt);
297

298
	/* Any arguments at this point are not recognized */
299
	if (argc > 1)
300
		die(_("unrecognized argument: %s"), argv[1]);
301

302
	if (rev->line_level_traverse && rev->prune_data.nr)
303
		die(_("-L<range>:<file> cannot be used with pathspec"));
304

305
	memset(&w, 0, sizeof(w));
306
	userformat_find_requirements(NULL, &w);
307

308
	if (!rev->show_notes_given && (!rev->pretty_given || w.notes))
309
		rev->show_notes = 1;
310
	if (rev->show_notes)
311
		load_display_notes(&rev->notes_opt);
312

313
	if ((rev->diffopt.pickaxe_opts & DIFF_PICKAXE_KINDS_MASK) ||
314
	    rev->diffopt.filter || rev->diffopt.flags.follow_renames)
315
		rev->always_show_header = 0;
316

317
	if (source || w.source) {
318
		init_revision_sources(&revision_sources);
319
		rev->sources = &revision_sources;
320
	}
321

322
	if (mailmap) {
323
		rev->mailmap = xmalloc(sizeof(struct string_list));
324
		string_list_init_nodup(rev->mailmap);
325
		read_mailmap(rev->mailmap);
326
	}
327

328
	if (rev->pretty_given && rev->commit_format == CMIT_FMT_RAW) {
329
		/*
330
		 * "log --pretty=raw" is special; ignore UI oriented
331
		 * configuration variables such as decoration.
332
		 */
333
		if (!cfg->decoration_given)
334
			cfg->decoration_style = 0;
335
		if (!rev->abbrev_commit_given)
336
			rev->abbrev_commit = 0;
337
	}
338

339
	if (rev->commit_format == CMIT_FMT_USERFORMAT) {
340
		if (!w.decorate) {
341
			/*
342
			 * Disable decoration loading if the format will not
343
			 * show them anyway.
344
			 */
345
			cfg->decoration_style = 0;
346
		} else if (!cfg->decoration_style) {
347
			/*
348
			 * If we are going to show them, make sure we do load
349
			 * them here, but taking care not to override a
350
			 * specific style set by config or --decorate.
351
			 */
352
			cfg->decoration_style = DECORATE_SHORT_REFS;
353
		}
354
	}
355

356
	if (cfg->decoration_style || rev->simplify_by_decoration) {
357
		set_default_decoration_filter(&decoration_filter);
358

359
		if (cfg->decoration_style)
360
			rev->show_decorations = 1;
361

362
		load_ref_decorations(&decoration_filter, cfg->decoration_style);
363
	}
364

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

368
	setup_pager();
369
}
370

371
static void cmd_log_init(int argc, const char **argv, const char *prefix,
372
			 struct rev_info *rev, struct setup_revision_opt *opt,
373
			 struct log_config *cfg)
374
{
375
	cmd_log_init_defaults(rev, cfg);
376
	cmd_log_init_finish(argc, argv, prefix, rev, opt, cfg);
377
}
378

379
/*
380
 * This gives a rough estimate for how many commits we
381
 * will print out in the list.
382
 */
383
static int estimate_commit_count(struct commit_list *list)
384
{
385
	int n = 0;
386

387
	while (list) {
388
		struct commit *commit = list->item;
389
		unsigned int flags = commit->object.flags;
390
		list = list->next;
391
		if (!(flags & (TREESAME | UNINTERESTING)))
392
			n++;
393
	}
394
	return n;
395
}
396

397
static void show_early_header(struct rev_info *rev, const char *stage, int nr)
398
{
399
	if (rev->shown_one) {
400
		rev->shown_one = 0;
401
		if (rev->commit_format != CMIT_FMT_ONELINE)
402
			putchar(rev->diffopt.line_termination);
403
	}
404
	fprintf(rev->diffopt.file, _("Final output: %d %s\n"), nr, stage);
405
}
406

407
static struct itimerval early_output_timer;
408

409
static void log_show_early(struct rev_info *revs, struct commit_list *list)
410
{
411
	int i = revs->early_output;
412
	int show_header = 1;
413
	int no_free = revs->diffopt.no_free;
414

415
	revs->diffopt.no_free = 0;
416
	sort_in_topological_order(&list, revs->sort_order);
417
	while (list && i) {
418
		struct commit *commit = list->item;
419
		switch (simplify_commit(revs, commit)) {
420
		case commit_show:
421
			if (show_header) {
422
				int n = estimate_commit_count(list);
423
				show_early_header(revs, "incomplete", n);
424
				show_header = 0;
425
			}
426
			log_tree_commit(revs, commit);
427
			i--;
428
			break;
429
		case commit_ignore:
430
			break;
431
		case commit_error:
432
			revs->diffopt.no_free = no_free;
433
			diff_free(&revs->diffopt);
434
			return;
435
		}
436
		list = list->next;
437
	}
438

439
	/* Did we already get enough commits for the early output? */
440
	if (!i) {
441
		revs->diffopt.no_free = 0;
442
		diff_free(&revs->diffopt);
443
		return;
444
	}
445

446
	/*
447
	 * ..if no, then repeat it twice a second until we
448
	 * do.
449
	 *
450
	 * NOTE! We don't use "it_interval", because if the
451
	 * reader isn't listening, we want our output to be
452
	 * throttled by the writing, and not have the timer
453
	 * trigger every second even if we're blocked on a
454
	 * reader!
455
	 */
456
	early_output_timer.it_value.tv_sec = 0;
457
	early_output_timer.it_value.tv_usec = 500000;
458
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
459
}
460

461
static void early_output(int signal UNUSED)
462
{
463
	show_early_output = log_show_early;
464
}
465

466
static void setup_early_output(void)
467
{
468
	struct sigaction sa;
469

470
	/*
471
	 * Set up the signal handler, minimally intrusively:
472
	 * we only set a single volatile integer word (not
473
	 * using sigatomic_t - trying to avoid unnecessary
474
	 * system dependencies and headers), and using
475
	 * SA_RESTART.
476
	 */
477
	memset(&sa, 0, sizeof(sa));
478
	sa.sa_handler = early_output;
479
	sigemptyset(&sa.sa_mask);
480
	sa.sa_flags = SA_RESTART;
481
	sigaction(SIGALRM, &sa, NULL);
482

483
	/*
484
	 * If we can get the whole output in less than a
485
	 * tenth of a second, don't even bother doing the
486
	 * early-output thing..
487
	 *
488
	 * This is a one-time-only trigger.
489
	 */
490
	early_output_timer.it_value.tv_sec = 0;
491
	early_output_timer.it_value.tv_usec = 100000;
492
	setitimer(ITIMER_REAL, &early_output_timer, NULL);
493
}
494

495
static void finish_early_output(struct rev_info *rev)
496
{
497
	int n = estimate_commit_count(rev->commits);
498
	signal(SIGALRM, SIG_IGN);
499
	show_early_header(rev, "done", n);
500
}
501

502
static int cmd_log_walk_no_free(struct rev_info *rev)
503
{
504
	struct commit *commit;
505
	int saved_nrl = 0;
506
	int saved_dcctc = 0;
507

508
	if (rev->remerge_diff) {
509
		rev->remerge_objdir = tmp_objdir_create("remerge-diff");
510
		if (!rev->remerge_objdir)
511
			die(_("unable to create temporary object directory"));
512
		tmp_objdir_replace_primary_odb(rev->remerge_objdir, 1);
513
	}
514

515
	if (rev->early_output)
516
		setup_early_output();
517

518
	if (prepare_revision_walk(rev))
519
		die(_("revision walk setup failed"));
520

521
	if (rev->early_output)
522
		finish_early_output(rev);
523

524
	/*
525
	 * For --check and --exit-code, the exit code is based on CHECK_FAILED
526
	 * and HAS_CHANGES being accumulated in rev->diffopt, so be careful to
527
	 * retain that state information if replacing rev->diffopt in this loop
528
	 */
529
	while ((commit = get_revision(rev)) != NULL) {
530
		if (!log_tree_commit(rev, commit) && rev->max_count >= 0)
531
			/*
532
			 * We decremented max_count in get_revision,
533
			 * but we didn't actually show the commit.
534
			 */
535
			rev->max_count++;
536
		if (!rev->reflog_info) {
537
			/*
538
			 * We may show a given commit multiple times when
539
			 * walking the reflogs.
540
			 */
541
			free_commit_buffer(the_repository->parsed_objects,
542
					   commit);
543
			free_commit_list(commit->parents);
544
			commit->parents = NULL;
545
		}
546
		if (saved_nrl < rev->diffopt.needed_rename_limit)
547
			saved_nrl = rev->diffopt.needed_rename_limit;
548
		if (rev->diffopt.degraded_cc_to_c)
549
			saved_dcctc = 1;
550
	}
551
	rev->diffopt.degraded_cc_to_c = saved_dcctc;
552
	rev->diffopt.needed_rename_limit = saved_nrl;
553

554
	if (rev->remerge_diff) {
555
		tmp_objdir_destroy(rev->remerge_objdir);
556
		rev->remerge_objdir = NULL;
557
	}
558

559
	if (rev->diffopt.output_format & DIFF_FORMAT_CHECKDIFF &&
560
	    rev->diffopt.flags.check_failed) {
561
		return 02;
562
	}
563
	return diff_result_code(&rev->diffopt);
564
}
565

566
static int cmd_log_walk(struct rev_info *rev)
567
{
568
	int retval;
569

570
	rev->diffopt.no_free = 1;
571
	retval = cmd_log_walk_no_free(rev);
572
	rev->diffopt.no_free = 0;
573
	diff_free(&rev->diffopt);
574
	return retval;
575
}
576

577
static int git_log_config(const char *var, const char *value,
578
			  const struct config_context *ctx, void *cb)
579
{
580
	struct log_config *cfg = cb;
581
	const char *slot_name;
582

583
	if (!strcmp(var, "format.pretty")) {
584
		FREE_AND_NULL(cfg->fmt_pretty);
585
		return git_config_string(&cfg->fmt_pretty, var, value);
586
	}
587
	if (!strcmp(var, "format.subjectprefix")) {
588
		FREE_AND_NULL(cfg->fmt_patch_subject_prefix);
589
		return git_config_string(&cfg->fmt_patch_subject_prefix, var, value);
590
	}
591
	if (!strcmp(var, "format.filenamemaxlength")) {
592
		cfg->fmt_patch_name_max = git_config_int(var, value, ctx->kvi);
593
		return 0;
594
	}
595
	if (!strcmp(var, "format.encodeemailheaders")) {
596
		cfg->default_encode_email_headers = git_config_bool(var, value);
597
		return 0;
598
	}
599
	if (!strcmp(var, "log.abbrevcommit")) {
600
		cfg->default_abbrev_commit = git_config_bool(var, value);
601
		return 0;
602
	}
603
	if (!strcmp(var, "log.date")) {
604
		FREE_AND_NULL(cfg->default_date_mode);
605
		return git_config_string(&cfg->default_date_mode, var, value);
606
	}
607
	if (!strcmp(var, "log.decorate")) {
608
		cfg->decoration_style = parse_decoration_style(value);
609
		if (cfg->decoration_style < 0)
610
			cfg->decoration_style = 0; /* maybe warn? */
611
		return 0;
612
	}
613
	if (!strcmp(var, "log.diffmerges")) {
614
		if (!value)
615
			return config_error_nonbool(var);
616
		return diff_merges_config(value);
617
	}
618
	if (!strcmp(var, "log.showroot")) {
619
		cfg->default_show_root = git_config_bool(var, value);
620
		return 0;
621
	}
622
	if (!strcmp(var, "log.follow")) {
623
		cfg->default_follow = git_config_bool(var, value);
624
		return 0;
625
	}
626
	if (skip_prefix(var, "color.decorate.", &slot_name))
627
		return parse_decorate_color_config(var, slot_name, value);
628
	if (!strcmp(var, "log.mailmap")) {
629
		cfg->use_mailmap_config = git_config_bool(var, value);
630
		return 0;
631
	}
632
	if (!strcmp(var, "log.showsignature")) {
633
		cfg->default_show_signature = git_config_bool(var, value);
634
		return 0;
635
	}
636

637
	return git_diff_ui_config(var, value, ctx, cb);
638
}
639

640
int cmd_whatchanged(int argc, const char **argv, const char *prefix)
641
{
642
	struct log_config cfg;
643
	struct rev_info rev;
644
	struct setup_revision_opt opt;
645
	int ret;
646

647
	log_config_init(&cfg);
648
	init_diff_ui_defaults();
649
	git_config(git_log_config, &cfg);
650

651
	repo_init_revisions(the_repository, &rev, prefix);
652
	git_config(grep_config, &rev.grep_filter);
653

654
	rev.diff = 1;
655
	rev.simplify_history = 0;
656
	memset(&opt, 0, sizeof(opt));
657
	opt.def = "HEAD";
658
	opt.revarg_opt = REVARG_COMMITTISH;
659
	cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
660
	if (!rev.diffopt.output_format)
661
		rev.diffopt.output_format = DIFF_FORMAT_RAW;
662

663
	ret = cmd_log_walk(&rev);
664

665
	release_revisions(&rev);
666
	log_config_release(&cfg);
667
	return ret;
668
}
669

670
static void show_tagger(const char *buf, struct rev_info *rev)
671
{
672
	struct strbuf out = STRBUF_INIT;
673
	struct pretty_print_context pp = {0};
674

675
	pp.fmt = rev->commit_format;
676
	pp.date_mode = rev->date_mode;
677
	pp_user_info(&pp, "Tagger", &out, buf, get_log_output_encoding());
678
	fprintf(rev->diffopt.file, "%s", out.buf);
679
	strbuf_release(&out);
680
}
681

682
static int show_blob_object(const struct object_id *oid, struct rev_info *rev, const char *obj_name)
683
{
684
	struct object_id oidc;
685
	struct object_context obj_context = {0};
686
	char *buf;
687
	unsigned long size;
688

689
	fflush(rev->diffopt.file);
690
	if (!rev->diffopt.flags.textconv_set_via_cmdline ||
691
	    !rev->diffopt.flags.allow_textconv)
692
		return stream_blob_to_fd(1, oid, NULL, 0);
693

694
	if (get_oid_with_context(the_repository, obj_name,
695
				 GET_OID_RECORD_PATH,
696
				 &oidc, &obj_context))
697
		die(_("not a valid object name %s"), obj_name);
698
	if (!obj_context.path ||
699
	    !textconv_object(the_repository, obj_context.path,
700
			     obj_context.mode, &oidc, 1, &buf, &size)) {
701
		object_context_release(&obj_context);
702
		return stream_blob_to_fd(1, oid, NULL, 0);
703
	}
704

705
	if (!buf)
706
		die(_("git show %s: bad file"), obj_name);
707

708
	write_or_die(1, buf, size);
709
	object_context_release(&obj_context);
710
	free(buf);
711
	return 0;
712
}
713

714
static int show_tag_object(const struct object_id *oid, struct rev_info *rev)
715
{
716
	unsigned long size;
717
	enum object_type type;
718
	char *buf = repo_read_object_file(the_repository, oid, &type, &size);
719
	int offset = 0;
720

721
	if (!buf)
722
		return error(_("could not read object %s"), oid_to_hex(oid));
723

724
	assert(type == OBJ_TAG);
725
	while (offset < size && buf[offset] != '\n') {
726
		int new_offset = offset + 1;
727
		const char *ident;
728
		while (new_offset < size && buf[new_offset++] != '\n')
729
			; /* do nothing */
730
		if (skip_prefix(buf + offset, "tagger ", &ident))
731
			show_tagger(ident, rev);
732
		offset = new_offset;
733
	}
734

735
	if (offset < size)
736
		fwrite(buf + offset, size - offset, 1, rev->diffopt.file);
737
	free(buf);
738
	return 0;
739
}
740

741
static int show_tree_object(const struct object_id *oid UNUSED,
742
			    struct strbuf *base UNUSED,
743
			    const char *pathname, unsigned mode,
744
			    void *context)
745
{
746
	FILE *file = context;
747
	fprintf(file, "%s%s\n", pathname, S_ISDIR(mode) ? "/" : "");
748
	return 0;
749
}
750

751
static void show_setup_revisions_tweak(struct rev_info *rev)
752
{
753
	if (rev->first_parent_only)
754
		diff_merges_default_to_first_parent(rev);
755
	else
756
		diff_merges_default_to_dense_combined(rev);
757
	if (!rev->diffopt.output_format)
758
		rev->diffopt.output_format = DIFF_FORMAT_PATCH;
759
}
760

761
int cmd_show(int argc, const char **argv, const char *prefix)
762
{
763
	struct log_config cfg;
764
	struct rev_info rev;
765
	unsigned int i;
766
	struct setup_revision_opt opt;
767
	struct pathspec match_all;
768
	int ret = 0;
769

770
	log_config_init(&cfg);
771
	init_diff_ui_defaults();
772
	git_config(git_log_config, &cfg);
773

774
	if (the_repository->gitdir) {
775
		prepare_repo_settings(the_repository);
776
		the_repository->settings.command_requires_full_index = 0;
777
	}
778

779
	memset(&match_all, 0, sizeof(match_all));
780
	repo_init_revisions(the_repository, &rev, prefix);
781
	git_config(grep_config, &rev.grep_filter);
782

783
	rev.diff = 1;
784
	rev.always_show_header = 1;
785
	rev.no_walk = 1;
786
	rev.diffopt.stat_width = -1; 	/* Scale to real terminal size */
787

788
	memset(&opt, 0, sizeof(opt));
789
	opt.def = "HEAD";
790
	opt.tweak = show_setup_revisions_tweak;
791
	cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
792

793
	if (!rev.no_walk) {
794
		ret = cmd_log_walk(&rev);
795
		release_revisions(&rev);
796
		log_config_release(&cfg);
797
		return ret;
798
	}
799

800
	rev.diffopt.no_free = 1;
801
	for (i = 0; i < rev.pending.nr && !ret; i++) {
802
		struct object *o = rev.pending.objects[i].item;
803
		const char *name = rev.pending.objects[i].name;
804
		switch (o->type) {
805
		case OBJ_BLOB:
806
			ret = show_blob_object(&o->oid, &rev, name);
807
			break;
808
		case OBJ_TAG: {
809
			struct tag *t = (struct tag *)o;
810
			struct object_id *oid = get_tagged_oid(t);
811

812
			if (rev.shown_one)
813
				putchar('\n');
814
			fprintf(rev.diffopt.file, "%stag %s%s\n",
815
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
816
					t->tag,
817
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
818
			ret = show_tag_object(&o->oid, &rev);
819
			rev.shown_one = 1;
820
			if (ret)
821
				break;
822
			o = parse_object(the_repository, oid);
823
			if (!o)
824
				ret = error(_("could not read object %s"),
825
					    oid_to_hex(oid));
826
			rev.pending.objects[i].item = o;
827
			i--;
828
			break;
829
		}
830
		case OBJ_TREE:
831
			if (rev.shown_one)
832
				putchar('\n');
833
			fprintf(rev.diffopt.file, "%stree %s%s\n\n",
834
					diff_get_color_opt(&rev.diffopt, DIFF_COMMIT),
835
					name,
836
					diff_get_color_opt(&rev.diffopt, DIFF_RESET));
837
			read_tree(the_repository, (struct tree *)o,
838
				  &match_all, show_tree_object,
839
				  rev.diffopt.file);
840
			rev.shown_one = 1;
841
			break;
842
		case OBJ_COMMIT:
843
		{
844
			struct object_array old;
845
			struct object_array blank = OBJECT_ARRAY_INIT;
846

847
			memcpy(&old, &rev.pending, sizeof(old));
848
			memcpy(&rev.pending, &blank, sizeof(rev.pending));
849

850
			add_object_array(o, name, &rev.pending);
851
			ret = cmd_log_walk_no_free(&rev);
852

853
			/*
854
			 * No need for
855
			 * object_array_clear(&pending). It was
856
			 * cleared already in prepare_revision_walk()
857
			 */
858
			memcpy(&rev.pending, &old, sizeof(rev.pending));
859
			break;
860
		}
861
		default:
862
			ret = error(_("unknown type: %d"), o->type);
863
		}
864
	}
865

866
	rev.diffopt.no_free = 0;
867
	diff_free(&rev.diffopt);
868
	release_revisions(&rev);
869
	log_config_release(&cfg);
870

871
	return ret;
872
}
873

874
/*
875
 * This is equivalent to "git log -g --abbrev-commit --pretty=oneline"
876
 */
877
int cmd_log_reflog(int argc, const char **argv, const char *prefix)
878
{
879
	struct log_config cfg;
880
	struct rev_info rev;
881
	struct setup_revision_opt opt;
882
	int ret;
883

884
	log_config_init(&cfg);
885
	init_diff_ui_defaults();
886
	git_config(git_log_config, &cfg);
887

888
	repo_init_revisions(the_repository, &rev, prefix);
889
	init_reflog_walk(&rev.reflog_info);
890
	git_config(grep_config, &rev.grep_filter);
891

892
	rev.verbose_header = 1;
893
	memset(&opt, 0, sizeof(opt));
894
	opt.def = "HEAD";
895
	cmd_log_init_defaults(&rev, &cfg);
896
	rev.abbrev_commit = 1;
897
	rev.commit_format = CMIT_FMT_ONELINE;
898
	rev.use_terminator = 1;
899
	rev.always_show_header = 1;
900
	cmd_log_init_finish(argc, argv, prefix, &rev, &opt, &cfg);
901

902
	ret = cmd_log_walk(&rev);
903

904
	release_revisions(&rev);
905
	log_config_release(&cfg);
906
	return ret;
907
}
908

909
static void log_setup_revisions_tweak(struct rev_info *rev)
910
{
911
	if (rev->diffopt.flags.default_follow_renames &&
912
	    diff_check_follow_pathspec(&rev->prune_data, 0))
913
		rev->diffopt.flags.follow_renames = 1;
914

915
	if (rev->first_parent_only)
916
		diff_merges_default_to_first_parent(rev);
917
}
918

919
int cmd_log(int argc, const char **argv, const char *prefix)
920
{
921
	struct log_config cfg;
922
	struct rev_info rev;
923
	struct setup_revision_opt opt;
924
	int ret;
925

926
	log_config_init(&cfg);
927
	init_diff_ui_defaults();
928
	git_config(git_log_config, &cfg);
929

930
	repo_init_revisions(the_repository, &rev, prefix);
931
	git_config(grep_config, &rev.grep_filter);
932

933
	rev.always_show_header = 1;
934
	memset(&opt, 0, sizeof(opt));
935
	opt.def = "HEAD";
936
	opt.revarg_opt = REVARG_COMMITTISH;
937
	opt.tweak = log_setup_revisions_tweak;
938
	cmd_log_init(argc, argv, prefix, &rev, &opt, &cfg);
939

940
	ret = cmd_log_walk(&rev);
941

942
	release_revisions(&rev);
943
	log_config_release(&cfg);
944
	return ret;
945
}
946

947
/* format-patch */
948

949
enum cover_setting {
950
	COVER_UNSET,
951
	COVER_OFF,
952
	COVER_ON,
953
	COVER_AUTO
954
};
955

956
enum thread_level {
957
	THREAD_UNSET,
958
	THREAD_SHALLOW,
959
	THREAD_DEEP
960
};
961

962
enum cover_from_description {
963
	COVER_FROM_NONE,
964
	COVER_FROM_MESSAGE,
965
	COVER_FROM_SUBJECT,
966
	COVER_FROM_AUTO
967
};
968

969
enum auto_base_setting {
970
	AUTO_BASE_NEVER,
971
	AUTO_BASE_ALWAYS,
972
	AUTO_BASE_WHEN_ABLE
973
};
974

975
struct format_config {
976
	struct log_config log;
977
	enum thread_level thread;
978
	int do_signoff;
979
	enum auto_base_setting auto_base;
980
	char *base_commit;
981
	char *from;
982
	char *signature;
983
	char *signature_file;
984
	enum cover_setting config_cover_letter;
985
	char *config_output_directory;
986
	enum cover_from_description cover_from_description_mode;
987
	int show_notes;
988
	struct display_notes_opt notes_opt;
989
	int numbered_cmdline_opt;
990
	int numbered;
991
	int auto_number;
992
	char *default_attach;
993
	struct string_list extra_hdr;
994
	struct string_list extra_to;
995
	struct string_list extra_cc;
996
	int keep_subject;
997
	int subject_prefix;
998
	struct strbuf sprefix;
999
	char *fmt_patch_suffix;
1000
};
1001

1002
static void format_config_init(struct format_config *cfg)
1003
{
1004
	memset(cfg, 0, sizeof(*cfg));
1005
	log_config_init(&cfg->log);
1006
	cfg->cover_from_description_mode = COVER_FROM_MESSAGE;
1007
	cfg->auto_number = 1;
1008
	string_list_init_dup(&cfg->extra_hdr);
1009
	string_list_init_dup(&cfg->extra_to);
1010
	string_list_init_dup(&cfg->extra_cc);
1011
	strbuf_init(&cfg->sprefix, 0);
1012
	cfg->fmt_patch_suffix = xstrdup(".patch");
1013
}
1014

1015
static void format_config_release(struct format_config *cfg)
1016
{
1017
	log_config_release(&cfg->log);
1018
	free(cfg->base_commit);
1019
	free(cfg->from);
1020
	free(cfg->signature);
1021
	free(cfg->signature_file);
1022
	free(cfg->config_output_directory);
1023
	free(cfg->default_attach);
1024
	string_list_clear(&cfg->extra_hdr, 0);
1025
	string_list_clear(&cfg->extra_to, 0);
1026
	string_list_clear(&cfg->extra_cc, 0);
1027
	strbuf_release(&cfg->sprefix);
1028
	free(cfg->fmt_patch_suffix);
1029
}
1030

1031
static enum cover_from_description parse_cover_from_description(const char *arg)
1032
{
1033
	if (!arg || !strcmp(arg, "default"))
1034
		return COVER_FROM_MESSAGE;
1035
	else if (!strcmp(arg, "none"))
1036
		return COVER_FROM_NONE;
1037
	else if (!strcmp(arg, "message"))
1038
		return COVER_FROM_MESSAGE;
1039
	else if (!strcmp(arg, "subject"))
1040
		return COVER_FROM_SUBJECT;
1041
	else if (!strcmp(arg, "auto"))
1042
		return COVER_FROM_AUTO;
1043
	else
1044
		die(_("%s: invalid cover from description mode"), arg);
1045
}
1046

1047
static void add_header(struct format_config *cfg, const char *value)
1048
{
1049
	struct string_list_item *item;
1050
	int len = strlen(value);
1051
	while (len && value[len - 1] == '\n')
1052
		len--;
1053

1054
	if (!strncasecmp(value, "to: ", 4)) {
1055
		item = string_list_append(&cfg->extra_to, value + 4);
1056
		len -= 4;
1057
	} else if (!strncasecmp(value, "cc: ", 4)) {
1058
		item = string_list_append(&cfg->extra_cc, value + 4);
1059
		len -= 4;
1060
	} else {
1061
		item = string_list_append(&cfg->extra_hdr, value);
1062
	}
1063

1064
	item->string[len] = '\0';
1065
}
1066

1067
static int git_format_config(const char *var, const char *value,
1068
			     const struct config_context *ctx, void *cb)
1069
{
1070
	struct format_config *cfg = cb;
1071

1072
	if (!strcmp(var, "format.headers")) {
1073
		if (!value)
1074
			die(_("format.headers without value"));
1075
		add_header(cfg, value);
1076
		return 0;
1077
	}
1078
	if (!strcmp(var, "format.suffix")) {
1079
		FREE_AND_NULL(cfg->fmt_patch_suffix);
1080
		return git_config_string(&cfg->fmt_patch_suffix, var, value);
1081
	}
1082
	if (!strcmp(var, "format.to")) {
1083
		if (!value)
1084
			return config_error_nonbool(var);
1085
		string_list_append(&cfg->extra_to, value);
1086
		return 0;
1087
	}
1088
	if (!strcmp(var, "format.cc")) {
1089
		if (!value)
1090
			return config_error_nonbool(var);
1091
		string_list_append(&cfg->extra_cc, value);
1092
		return 0;
1093
	}
1094
	if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff") ||
1095
	    !strcmp(var, "color.ui") || !strcmp(var, "diff.submodule")) {
1096
		return 0;
1097
	}
1098
	if (!strcmp(var, "format.numbered")) {
1099
		if (value && !strcasecmp(value, "auto")) {
1100
			cfg->auto_number = 1;
1101
			return 0;
1102
		}
1103
		cfg->numbered = git_config_bool(var, value);
1104
		cfg->auto_number = cfg->auto_number && cfg->numbered;
1105
		return 0;
1106
	}
1107
	if (!strcmp(var, "format.attach")) {
1108
		if (value && *value) {
1109
			FREE_AND_NULL(cfg->default_attach);
1110
			cfg->default_attach = xstrdup(value);
1111
		} else if (value && !*value) {
1112
			FREE_AND_NULL(cfg->default_attach);
1113
		} else {
1114
			FREE_AND_NULL(cfg->default_attach);
1115
			cfg->default_attach = xstrdup(git_version_string);
1116
		}
1117
		return 0;
1118
	}
1119
	if (!strcmp(var, "format.thread")) {
1120
		if (value && !strcasecmp(value, "deep")) {
1121
			cfg->thread = THREAD_DEEP;
1122
			return 0;
1123
		}
1124
		if (value && !strcasecmp(value, "shallow")) {
1125
			cfg->thread = THREAD_SHALLOW;
1126
			return 0;
1127
		}
1128
		cfg->thread = git_config_bool(var, value) ? THREAD_SHALLOW : THREAD_UNSET;
1129
		return 0;
1130
	}
1131
	if (!strcmp(var, "format.signoff")) {
1132
		cfg->do_signoff = git_config_bool(var, value);
1133
		return 0;
1134
	}
1135
	if (!strcmp(var, "format.signature")) {
1136
		FREE_AND_NULL(cfg->signature);
1137
		return git_config_string(&cfg->signature, var, value);
1138
	}
1139
	if (!strcmp(var, "format.signaturefile")) {
1140
		FREE_AND_NULL(cfg->signature_file);
1141
		return git_config_pathname(&cfg->signature_file, var, value);
1142
	}
1143
	if (!strcmp(var, "format.coverletter")) {
1144
		if (value && !strcasecmp(value, "auto")) {
1145
			cfg->config_cover_letter = COVER_AUTO;
1146
			return 0;
1147
		}
1148
		cfg->config_cover_letter = git_config_bool(var, value) ? COVER_ON : COVER_OFF;
1149
		return 0;
1150
	}
1151
	if (!strcmp(var, "format.outputdirectory")) {
1152
		FREE_AND_NULL(cfg->config_output_directory);
1153
		return git_config_string(&cfg->config_output_directory, var, value);
1154
	}
1155
	if (!strcmp(var, "format.useautobase")) {
1156
		if (value && !strcasecmp(value, "whenAble")) {
1157
			cfg->auto_base = AUTO_BASE_WHEN_ABLE;
1158
			return 0;
1159
		}
1160
		cfg->auto_base = git_config_bool(var, value) ? AUTO_BASE_ALWAYS : AUTO_BASE_NEVER;
1161
		return 0;
1162
	}
1163
	if (!strcmp(var, "format.from")) {
1164
		int b = git_parse_maybe_bool(value);
1165
		FREE_AND_NULL(cfg->from);
1166
		if (b < 0)
1167
			cfg->from = xstrdup(value);
1168
		else if (b)
1169
			cfg->from = xstrdup(git_committer_info(IDENT_NO_DATE));
1170
		return 0;
1171
	}
1172
	if (!strcmp(var, "format.forceinbodyfrom")) {
1173
		force_in_body_from = git_config_bool(var, value);
1174
		return 0;
1175
	}
1176
	if (!strcmp(var, "format.notes")) {
1177
		int b = git_parse_maybe_bool(value);
1178
		if (b < 0)
1179
			enable_ref_display_notes(&cfg->notes_opt, &cfg->show_notes, value);
1180
		else if (b)
1181
			enable_default_display_notes(&cfg->notes_opt, &cfg->show_notes);
1182
		else
1183
			disable_display_notes(&cfg->notes_opt, &cfg->show_notes);
1184
		return 0;
1185
	}
1186
	if (!strcmp(var, "format.coverfromdescription")) {
1187
		cfg->cover_from_description_mode = parse_cover_from_description(value);
1188
		return 0;
1189
	}
1190
	if (!strcmp(var, "format.mboxrd")) {
1191
		stdout_mboxrd = git_config_bool(var, value);
1192
		return 0;
1193
	}
1194
	if (!strcmp(var, "format.noprefix")) {
1195
		format_no_prefix = 1;
1196
		return 0;
1197
	}
1198

1199
	/*
1200
	 * ignore some porcelain config which would otherwise be parsed by
1201
	 * git_diff_ui_config(), via git_log_config(); we can't just avoid
1202
	 * diff_ui_config completely, because we do care about some ui options
1203
	 * like color.
1204
	 */
1205
	if (!strcmp(var, "diff.noprefix"))
1206
		return 0;
1207

1208
	return git_log_config(var, value, ctx, &cfg->log);
1209
}
1210

1211
static const char *output_directory = NULL;
1212
static int outdir_offset;
1213

1214
static int open_next_file(struct commit *commit, const char *subject,
1215
			 struct rev_info *rev, int quiet)
1216
{
1217
	struct strbuf filename = STRBUF_INIT;
1218

1219
	if (output_directory) {
1220
		strbuf_addstr(&filename, output_directory);
1221
		strbuf_complete(&filename, '/');
1222
	}
1223

1224
	if (rev->numbered_files)
1225
		strbuf_addf(&filename, "%d", rev->nr);
1226
	else if (commit)
1227
		fmt_output_commit(&filename, commit, rev);
1228
	else
1229
		fmt_output_subject(&filename, subject, rev);
1230

1231
	if (!quiet)
1232
		printf("%s\n", filename.buf + outdir_offset);
1233

1234
	if (!(rev->diffopt.file = fopen(filename.buf, "w"))) {
1235
		error_errno(_("cannot open patch file %s"), filename.buf);
1236
		strbuf_release(&filename);
1237
		return -1;
1238
	}
1239

1240
	strbuf_release(&filename);
1241
	return 0;
1242
}
1243

1244
static void get_patch_ids(struct rev_info *rev, struct patch_ids *ids)
1245
{
1246
	struct rev_info check_rev;
1247
	struct commit *commit, *c1, *c2;
1248
	struct object *o1, *o2;
1249
	unsigned flags1, flags2;
1250

1251
	if (rev->pending.nr != 2)
1252
		die(_("need exactly one range"));
1253

1254
	o1 = rev->pending.objects[0].item;
1255
	o2 = rev->pending.objects[1].item;
1256
	flags1 = o1->flags;
1257
	flags2 = o2->flags;
1258
	c1 = lookup_commit_reference(the_repository, &o1->oid);
1259
	c2 = lookup_commit_reference(the_repository, &o2->oid);
1260

1261
	if ((flags1 & UNINTERESTING) == (flags2 & UNINTERESTING))
1262
		die(_("not a range"));
1263

1264
	init_patch_ids(the_repository, ids);
1265

1266
	/* given a range a..b get all patch ids for b..a */
1267
	repo_init_revisions(the_repository, &check_rev, rev->prefix);
1268
	check_rev.max_parents = 1;
1269
	o1->flags ^= UNINTERESTING;
1270
	o2->flags ^= UNINTERESTING;
1271
	add_pending_object(&check_rev, o1, "o1");
1272
	add_pending_object(&check_rev, o2, "o2");
1273
	if (prepare_revision_walk(&check_rev))
1274
		die(_("revision walk setup failed"));
1275

1276
	while ((commit = get_revision(&check_rev)) != NULL) {
1277
		add_commit_patch_id(commit, ids);
1278
	}
1279

1280
	/* reset for next revision walk */
1281
	clear_commit_marks(c1, SEEN | UNINTERESTING | SHOWN | ADDED);
1282
	clear_commit_marks(c2, SEEN | UNINTERESTING | SHOWN | ADDED);
1283
	o1->flags = flags1;
1284
	o2->flags = flags2;
1285
}
1286

1287
static void gen_message_id(struct rev_info *info, const char *base)
1288
{
1289
	struct strbuf buf = STRBUF_INIT;
1290
	strbuf_addf(&buf, "%s.%"PRItime".git.%s", base,
1291
		    (timestamp_t) time(NULL),
1292
		    git_committer_info(IDENT_NO_NAME|IDENT_NO_DATE|IDENT_STRICT));
1293
	info->message_id = strbuf_detach(&buf, NULL);
1294
}
1295

1296
static void print_signature(const char *signature, FILE *file)
1297
{
1298
	if (!signature || !*signature)
1299
		return;
1300

1301
	fprintf(file, "-- \n%s", signature);
1302
	if (signature[strlen(signature)-1] != '\n')
1303
		putc('\n', file);
1304
	putc('\n', file);
1305
}
1306

1307
static char *find_branch_name(struct rev_info *rev)
1308
{
1309
	int i, positive = -1;
1310
	struct object_id branch_oid;
1311
	const struct object_id *tip_oid;
1312
	const char *ref, *v;
1313
	char *full_ref, *branch = NULL;
1314

1315
	for (i = 0; i < rev->cmdline.nr; i++) {
1316
		if (rev->cmdline.rev[i].flags & UNINTERESTING)
1317
			continue;
1318
		if (positive < 0)
1319
			positive = i;
1320
		else
1321
			return NULL;
1322
	}
1323
	if (positive < 0)
1324
		return NULL;
1325
	ref = rev->cmdline.rev[positive].name;
1326
	tip_oid = &rev->cmdline.rev[positive].item->oid;
1327
	if (repo_dwim_ref(the_repository, ref, strlen(ref), &branch_oid,
1328
			  &full_ref, 0) &&
1329
	    skip_prefix(full_ref, "refs/heads/", &v) &&
1330
	    oideq(tip_oid, &branch_oid))
1331
		branch = xstrdup(v);
1332
	free(full_ref);
1333
	return branch;
1334
}
1335

1336
static void show_diffstat(struct rev_info *rev,
1337
			  struct commit *origin, struct commit *head)
1338
{
1339
	struct diff_options opts;
1340

1341
	memcpy(&opts, &rev->diffopt, sizeof(opts));
1342
	opts.output_format = DIFF_FORMAT_SUMMARY | DIFF_FORMAT_DIFFSTAT;
1343
	diff_setup_done(&opts);
1344

1345
	diff_tree_oid(get_commit_tree_oid(origin),
1346
		      get_commit_tree_oid(head),
1347
		      "", &opts);
1348
	diffcore_std(&opts);
1349
	diff_flush(&opts);
1350

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

1354
static void read_desc_file(struct strbuf *buf, const char *desc_file)
1355
{
1356
	if (strbuf_read_file(buf, desc_file, 0) < 0)
1357
		die_errno(_("unable to read branch description file '%s'"),
1358
			  desc_file);
1359
}
1360

1361
static void prepare_cover_text(struct pretty_print_context *pp,
1362
			       const char *description_file,
1363
			       const char *branch_name,
1364
			       struct strbuf *sb,
1365
			       const char *encoding,
1366
			       int need_8bit_cte,
1367
			       const struct format_config *cfg)
1368
{
1369
	const char *subject = "*** SUBJECT HERE ***";
1370
	const char *body = "*** BLURB HERE ***";
1371
	struct strbuf description_sb = STRBUF_INIT;
1372
	struct strbuf subject_sb = STRBUF_INIT;
1373

1374
	if (cfg->cover_from_description_mode == COVER_FROM_NONE)
1375
		goto do_pp;
1376

1377
	if (description_file && *description_file)
1378
		read_desc_file(&description_sb, description_file);
1379
	else if (branch_name && *branch_name)
1380
		read_branch_desc(&description_sb, branch_name);
1381
	if (!description_sb.len)
1382
		goto do_pp;
1383

1384
	if (cfg->cover_from_description_mode == COVER_FROM_SUBJECT ||
1385
	    cfg->cover_from_description_mode == COVER_FROM_AUTO)
1386
		body = format_subject(&subject_sb, description_sb.buf, " ");
1387

1388
	if (cfg->cover_from_description_mode == COVER_FROM_MESSAGE ||
1389
	    (cfg->cover_from_description_mode == COVER_FROM_AUTO &&
1390
	     subject_sb.len > COVER_FROM_AUTO_MAX_SUBJECT_LEN))
1391
		body = description_sb.buf;
1392
	else
1393
		subject = subject_sb.buf;
1394

1395
do_pp:
1396
	pp_email_subject(pp, &subject, sb, encoding, need_8bit_cte);
1397
	pp_remainder(pp, &body, sb, 0);
1398

1399
	strbuf_release(&description_sb);
1400
	strbuf_release(&subject_sb);
1401
}
1402

1403
static int get_notes_refs(struct string_list_item *item, void *arg)
1404
{
1405
	strvec_pushf(arg, "--notes=%s", item->string);
1406
	return 0;
1407
}
1408

1409
static void get_notes_args(struct strvec *arg, struct rev_info *rev)
1410
{
1411
	if (!rev->show_notes) {
1412
		strvec_push(arg, "--no-notes");
1413
	} else if (rev->notes_opt.use_default_notes > 0 ||
1414
		   (rev->notes_opt.use_default_notes == -1 &&
1415
		    !rev->notes_opt.extra_notes_refs.nr)) {
1416
		strvec_push(arg, "--notes");
1417
	} else {
1418
		for_each_string_list(&rev->notes_opt.extra_notes_refs, get_notes_refs, arg);
1419
	}
1420
}
1421

1422
static void make_cover_letter(struct rev_info *rev, int use_separate_file,
1423
			      struct commit *origin,
1424
			      int nr, struct commit **list,
1425
			      const char *description_file,
1426
			      const char *branch_name,
1427
			      int quiet,
1428
			      const struct format_config *cfg)
1429
{
1430
	const char *committer;
1431
	struct shortlog log;
1432
	struct strbuf sb = STRBUF_INIT;
1433
	int i;
1434
	const char *encoding = "UTF-8";
1435
	int need_8bit_cte = 0;
1436
	struct pretty_print_context pp = {0};
1437
	struct commit *head = list[0];
1438
	char *to_free = NULL;
1439

1440
	if (!cmit_fmt_is_mail(rev->commit_format))
1441
		die(_("cover letter needs email format"));
1442

1443
	committer = git_committer_info(0);
1444

1445
	if (use_separate_file &&
1446
	    open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
1447
		die(_("failed to create cover-letter file"));
1448

1449
	log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
1450

1451
	for (i = 0; !need_8bit_cte && i < nr; i++) {
1452
		const char *buf = repo_get_commit_buffer(the_repository,
1453
							 list[i], NULL);
1454
		if (has_non_ascii(buf))
1455
			need_8bit_cte = 1;
1456
		repo_unuse_commit_buffer(the_repository, list[i], buf);
1457
	}
1458

1459
	if (!branch_name)
1460
		branch_name = to_free = find_branch_name(rev);
1461

1462
	pp.fmt = CMIT_FMT_EMAIL;
1463
	pp.date_mode.type = DATE_RFC2822;
1464
	pp.rev = rev;
1465
	pp.encode_email_headers = rev->encode_email_headers;
1466
	pp_user_info(&pp, NULL, &sb, committer, encoding);
1467
	prepare_cover_text(&pp, description_file, branch_name, &sb,
1468
			   encoding, need_8bit_cte, cfg);
1469
	fprintf(rev->diffopt.file, "%s\n", sb.buf);
1470

1471
	free(to_free);
1472
	free(pp.after_subject);
1473
	strbuf_release(&sb);
1474

1475
	shortlog_init(&log);
1476
	log.wrap_lines = 1;
1477
	log.wrap = MAIL_DEFAULT_WRAP;
1478
	log.in1 = 2;
1479
	log.in2 = 4;
1480
	log.file = rev->diffopt.file;
1481
	log.groups = SHORTLOG_GROUP_AUTHOR;
1482
	shortlog_finish_setup(&log);
1483
	for (i = 0; i < nr; i++)
1484
		shortlog_add_commit(&log, list[i]);
1485

1486
	shortlog_output(&log);
1487

1488
	/* We can only do diffstat with a unique reference point */
1489
	if (origin)
1490
		show_diffstat(rev, origin, head);
1491

1492
	if (rev->idiff_oid1) {
1493
		fprintf_ln(rev->diffopt.file, "%s", rev->idiff_title);
1494
		show_interdiff(rev->idiff_oid1, rev->idiff_oid2, 0,
1495
			       &rev->diffopt);
1496
	}
1497

1498
	if (rev->rdiff1) {
1499
		/*
1500
		 * Pass minimum required diff-options to range-diff; others
1501
		 * can be added later if deemed desirable.
1502
		 */
1503
		struct diff_options opts;
1504
		struct strvec other_arg = STRVEC_INIT;
1505
		struct range_diff_options range_diff_opts = {
1506
			.creation_factor = rev->creation_factor,
1507
			.dual_color = 1,
1508
			.diffopt = &opts,
1509
			.other_arg = &other_arg
1510
		};
1511

1512
		repo_diff_setup(the_repository, &opts);
1513
		opts.file = rev->diffopt.file;
1514
		opts.use_color = rev->diffopt.use_color;
1515
		diff_setup_done(&opts);
1516
		fprintf_ln(rev->diffopt.file, "%s", rev->rdiff_title);
1517
		get_notes_args(&other_arg, rev);
1518
		show_range_diff(rev->rdiff1, rev->rdiff2, &range_diff_opts);
1519
		strvec_clear(&other_arg);
1520
	}
1521
}
1522

1523
static char *clean_message_id(const char *msg_id)
1524
{
1525
	char ch;
1526
	const char *a, *z, *m;
1527

1528
	m = msg_id;
1529
	while ((ch = *m) && (isspace(ch) || (ch == '<')))
1530
		m++;
1531
	a = m;
1532
	z = NULL;
1533
	while ((ch = *m)) {
1534
		if (!isspace(ch) && (ch != '>'))
1535
			z = m;
1536
		m++;
1537
	}
1538
	if (!z)
1539
		die(_("insane in-reply-to: %s"), msg_id);
1540
	if (++z == m)
1541
		return xstrdup(a);
1542
	return xmemdupz(a, z - a);
1543
}
1544

1545
static const char *set_outdir(const char *prefix, const char *output_directory)
1546
{
1547
	if (output_directory && is_absolute_path(output_directory))
1548
		return output_directory;
1549

1550
	if (!prefix || !*prefix) {
1551
		if (output_directory)
1552
			return output_directory;
1553
		/* The user did not explicitly ask for "./" */
1554
		outdir_offset = 2;
1555
		return "./";
1556
	}
1557

1558
	outdir_offset = strlen(prefix);
1559
	if (!output_directory)
1560
		return prefix;
1561

1562
	return prefix_filename(prefix, output_directory);
1563
}
1564

1565
static const char * const builtin_format_patch_usage[] = {
1566
	N_("git format-patch [<options>] [<since> | <revision-range>]"),
1567
	NULL
1568
};
1569

1570
struct keep_callback_data {
1571
	struct format_config *cfg;
1572
	struct rev_info *revs;
1573
};
1574

1575
static int keep_callback(const struct option *opt, const char *arg, int unset)
1576
{
1577
	struct keep_callback_data *data = opt->value;
1578
	BUG_ON_OPT_NEG(unset);
1579
	BUG_ON_OPT_ARG(arg);
1580
	data->revs->total = -1;
1581
	data->cfg->keep_subject = 1;
1582
	return 0;
1583
}
1584

1585
static int subject_prefix_callback(const struct option *opt, const char *arg,
1586
			    int unset)
1587
{
1588
	struct format_config *cfg = opt->value;
1589

1590
	BUG_ON_OPT_NEG(unset);
1591
	cfg->subject_prefix = 1;
1592
	strbuf_reset(&cfg->sprefix);
1593
	strbuf_addstr(&cfg->sprefix, arg);
1594
	return 0;
1595
}
1596

1597
static int rfc_callback(const struct option *opt, const char *arg,
1598
			int unset)
1599
{
1600
	const char **rfc = opt->value;
1601

1602
	*rfc = opt->value;
1603
	if (unset)
1604
		*rfc = NULL;
1605
	else
1606
		*rfc = arg ? arg : "RFC";
1607
	return 0;
1608
}
1609

1610
static int numbered_callback(const struct option *opt, const char *arg,
1611
			     int unset)
1612
{
1613
	struct format_config *cfg = opt->value;
1614
	BUG_ON_OPT_ARG(arg);
1615
	cfg->numbered = cfg->numbered_cmdline_opt = unset ? 0 : 1;
1616
	if (unset)
1617
		cfg->auto_number =  0;
1618
	return 0;
1619
}
1620

1621
static int no_numbered_callback(const struct option *opt, const char *arg,
1622
				int unset)
1623
{
1624
	BUG_ON_OPT_NEG(unset);
1625
	return numbered_callback(opt, arg, 1);
1626
}
1627

1628
static int output_directory_callback(const struct option *opt, const char *arg,
1629
			      int unset)
1630
{
1631
	const char **dir = (const char **)opt->value;
1632
	BUG_ON_OPT_NEG(unset);
1633
	if (*dir)
1634
		die(_("two output directories?"));
1635
	*dir = arg;
1636
	return 0;
1637
}
1638

1639
static int thread_callback(const struct option *opt, const char *arg, int unset)
1640
{
1641
	struct format_config *cfg = opt->value;
1642

1643
	if (unset)
1644
		cfg->thread = THREAD_UNSET;
1645
	else if (!arg || !strcmp(arg, "shallow"))
1646
		cfg->thread = THREAD_SHALLOW;
1647
	else if (!strcmp(arg, "deep"))
1648
		cfg->thread = THREAD_DEEP;
1649
	/*
1650
	 * Please update _git_formatpatch() in git-completion.bash
1651
	 * when you add new options.
1652
	 */
1653
	else
1654
		return 1;
1655
	return 0;
1656
}
1657

1658
static int attach_callback(const struct option *opt, const char *arg, int unset)
1659
{
1660
	struct rev_info *rev = (struct rev_info *)opt->value;
1661
	if (unset)
1662
		rev->mime_boundary = NULL;
1663
	else if (arg)
1664
		rev->mime_boundary = arg;
1665
	else
1666
		rev->mime_boundary = git_version_string;
1667
	rev->no_inline = unset ? 0 : 1;
1668
	return 0;
1669
}
1670

1671
static int inline_callback(const struct option *opt, const char *arg, int unset)
1672
{
1673
	struct rev_info *rev = (struct rev_info *)opt->value;
1674
	if (unset)
1675
		rev->mime_boundary = NULL;
1676
	else if (arg)
1677
		rev->mime_boundary = arg;
1678
	else
1679
		rev->mime_boundary = git_version_string;
1680
	rev->no_inline = 0;
1681
	return 0;
1682
}
1683

1684
static int header_callback(const struct option *opt, const char *arg,
1685
			   int unset)
1686
{
1687
	struct format_config *cfg = opt->value;
1688

1689
	if (unset) {
1690
		string_list_clear(&cfg->extra_hdr, 0);
1691
		string_list_clear(&cfg->extra_to, 0);
1692
		string_list_clear(&cfg->extra_cc, 0);
1693
	} else {
1694
		add_header(cfg, arg);
1695
	}
1696
	return 0;
1697
}
1698

1699
static int from_callback(const struct option *opt, const char *arg, int unset)
1700
{
1701
	char **from = opt->value;
1702

1703
	free(*from);
1704

1705
	if (unset)
1706
		*from = NULL;
1707
	else if (arg)
1708
		*from = xstrdup(arg);
1709
	else
1710
		*from = xstrdup(git_committer_info(IDENT_NO_DATE));
1711
	return 0;
1712
}
1713

1714
static int base_callback(const struct option *opt, const char *arg, int unset)
1715
{
1716
	struct format_config *cfg = opt->value;
1717

1718
	if (unset) {
1719
		cfg->auto_base = AUTO_BASE_NEVER;
1720
		FREE_AND_NULL(cfg->base_commit);
1721
	} else if (!strcmp(arg, "auto")) {
1722
		cfg->auto_base = AUTO_BASE_ALWAYS;
1723
		FREE_AND_NULL(cfg->base_commit);
1724
	} else {
1725
		cfg->auto_base = AUTO_BASE_NEVER;
1726
		cfg->base_commit = xstrdup(arg);
1727
	}
1728
	return 0;
1729
}
1730

1731
struct base_tree_info {
1732
	struct object_id base_commit;
1733
	int nr_patch_id, alloc_patch_id;
1734
	struct object_id *patch_id;
1735
};
1736

1737
static struct commit *get_base_commit(const struct format_config *cfg,
1738
				      struct commit **list,
1739
				      int total)
1740
{
1741
	struct commit *base = NULL;
1742
	struct commit **rev;
1743
	int i = 0, rev_nr = 0, auto_select, die_on_failure, ret;
1744

1745
	switch (cfg->auto_base) {
1746
	case AUTO_BASE_NEVER:
1747
		if (cfg->base_commit) {
1748
			auto_select = 0;
1749
			die_on_failure = 1;
1750
		} else {
1751
			/* no base information is requested */
1752
			return NULL;
1753
		}
1754
		break;
1755
	case AUTO_BASE_ALWAYS:
1756
	case AUTO_BASE_WHEN_ABLE:
1757
		if (cfg->base_commit) {
1758
			BUG("requested automatic base selection but a commit was provided");
1759
		} else {
1760
			auto_select = 1;
1761
			die_on_failure = cfg->auto_base == AUTO_BASE_ALWAYS;
1762
		}
1763
		break;
1764
	default:
1765
		BUG("unexpected automatic base selection method");
1766
	}
1767

1768
	if (!auto_select) {
1769
		base = lookup_commit_reference_by_name(cfg->base_commit);
1770
		if (!base)
1771
			die(_("unknown commit %s"), cfg->base_commit);
1772
	} else {
1773
		struct branch *curr_branch = branch_get(NULL);
1774
		const char *upstream = branch_get_upstream(curr_branch, NULL);
1775
		if (upstream) {
1776
			struct commit_list *base_list = NULL;
1777
			struct commit *commit;
1778
			struct object_id oid;
1779

1780
			if (repo_get_oid(the_repository, upstream, &oid)) {
1781
				if (die_on_failure)
1782
					die(_("failed to resolve '%s' as a valid ref"), upstream);
1783
				else
1784
					return NULL;
1785
			}
1786
			commit = lookup_commit_or_die(&oid, "upstream base");
1787
			if (repo_get_merge_bases_many(the_repository,
1788
						      commit, total,
1789
						      list,
1790
						      &base_list) < 0 ||
1791
			    /* There should be one and only one merge base. */
1792
			    !base_list || base_list->next) {
1793
				if (die_on_failure) {
1794
					die(_("could not find exact merge base"));
1795
				} else {
1796
					free_commit_list(base_list);
1797
					return NULL;
1798
				}
1799
			}
1800
			base = base_list->item;
1801
			free_commit_list(base_list);
1802
		} else {
1803
			if (die_on_failure)
1804
				die(_("failed to get upstream, if you want to record base commit automatically,\n"
1805
				      "please use git branch --set-upstream-to to track a remote branch.\n"
1806
				      "Or you could specify base commit by --base=<base-commit-id> manually"));
1807
			else
1808
				return NULL;
1809
		}
1810
	}
1811

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

1816
	rev_nr = total;
1817
	/*
1818
	 * Get merge base through pair-wise computations
1819
	 * and store it in rev[0].
1820
	 */
1821
	while (rev_nr > 1) {
1822
		for (i = 0; i < rev_nr / 2; i++) {
1823
			struct commit_list *merge_base = NULL;
1824
			if (repo_get_merge_bases(the_repository,
1825
						 rev[2 * i],
1826
						 rev[2 * i + 1], &merge_base) < 0 ||
1827
			    !merge_base || merge_base->next) {
1828
				if (die_on_failure) {
1829
					die(_("failed to find exact merge base"));
1830
				} else {
1831
					free_commit_list(merge_base);
1832
					free(rev);
1833
					return NULL;
1834
				}
1835
			}
1836

1837
			rev[i] = merge_base->item;
1838
			free_commit_list(merge_base);
1839
		}
1840

1841
		if (rev_nr % 2)
1842
			rev[i] = rev[2 * i];
1843
		rev_nr = DIV_ROUND_UP(rev_nr, 2);
1844
	}
1845

1846
	ret = repo_in_merge_bases(the_repository, base, rev[0]);
1847
	if (ret < 0)
1848
		exit(128);
1849
	if (!ret) {
1850
		if (die_on_failure) {
1851
			die(_("base commit should be the ancestor of revision list"));
1852
		} else {
1853
			free(rev);
1854
			return NULL;
1855
		}
1856
	}
1857

1858
	for (i = 0; i < total; i++) {
1859
		if (base == list[i]) {
1860
			if (die_on_failure) {
1861
				die(_("base commit shouldn't be in revision list"));
1862
			} else {
1863
				free(rev);
1864
				return NULL;
1865
			}
1866
		}
1867
	}
1868

1869
	free(rev);
1870
	return base;
1871
}
1872

1873
define_commit_slab(commit_base, int);
1874

1875
static void prepare_bases(struct base_tree_info *bases,
1876
			  struct commit *base,
1877
			  struct commit **list,
1878
			  int total)
1879
{
1880
	struct commit *commit;
1881
	struct rev_info revs;
1882
	struct diff_options diffopt;
1883
	struct commit_base commit_base;
1884
	int i;
1885

1886
	if (!base)
1887
		return;
1888

1889
	init_commit_base(&commit_base);
1890
	repo_diff_setup(the_repository, &diffopt);
1891
	diffopt.flags.recursive = 1;
1892
	diff_setup_done(&diffopt);
1893

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

1896
	repo_init_revisions(the_repository, &revs, NULL);
1897
	revs.max_parents = 1;
1898
	revs.topo_order = 1;
1899
	for (i = 0; i < total; i++) {
1900
		list[i]->object.flags &= ~UNINTERESTING;
1901
		add_pending_object(&revs, &list[i]->object, "rev_list");
1902
		*commit_base_at(&commit_base, list[i]) = 1;
1903
	}
1904
	base->object.flags |= UNINTERESTING;
1905
	add_pending_object(&revs, &base->object, "base");
1906

1907
	if (prepare_revision_walk(&revs))
1908
		die(_("revision walk setup failed"));
1909
	/*
1910
	 * Traverse the commits list, get prerequisite patch ids
1911
	 * and stuff them in bases structure.
1912
	 */
1913
	while ((commit = get_revision(&revs)) != NULL) {
1914
		struct object_id oid;
1915
		struct object_id *patch_id;
1916
		if (*commit_base_at(&commit_base, commit))
1917
			continue;
1918
		if (commit_patch_id(commit, &diffopt, &oid, 0))
1919
			die(_("cannot get patch id"));
1920
		ALLOC_GROW(bases->patch_id, bases->nr_patch_id + 1, bases->alloc_patch_id);
1921
		patch_id = bases->patch_id + bases->nr_patch_id;
1922
		oidcpy(patch_id, &oid);
1923
		bases->nr_patch_id++;
1924
	}
1925
	clear_commit_base(&commit_base);
1926
}
1927

1928
static void print_bases(struct base_tree_info *bases, FILE *file)
1929
{
1930
	int i;
1931

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

1936
	/* Show the base commit */
1937
	fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
1938

1939
	/* Show the prerequisite patches */
1940
	for (i = bases->nr_patch_id - 1; i >= 0; i--)
1941
		fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
1942

1943
	free(bases->patch_id);
1944
	bases->nr_patch_id = 0;
1945
	bases->alloc_patch_id = 0;
1946
	oidclr(&bases->base_commit, the_repository->hash_algo);
1947
}
1948

1949
static const char *diff_title(struct strbuf *sb,
1950
			      const char *reroll_count,
1951
			      const char *generic,
1952
			      const char *rerolled)
1953
{
1954
	int v;
1955

1956
	/* RFC may be v0, so allow -v1 to diff against v0 */
1957
	if (reroll_count && !strtol_i(reroll_count, 10, &v) &&
1958
	    v >= 1)
1959
		strbuf_addf(sb, rerolled, v - 1);
1960
	else
1961
		strbuf_addstr(sb, generic);
1962
	return sb->buf;
1963
}
1964

1965
static void infer_range_diff_ranges(struct strbuf *r1,
1966
				    struct strbuf *r2,
1967
				    const char *prev,
1968
				    struct commit *origin,
1969
				    struct commit *head)
1970
{
1971
	const char *head_oid = oid_to_hex(&head->object.oid);
1972
	int prev_is_range = is_range_diff_range(prev);
1973

1974
	if (prev_is_range)
1975
		strbuf_addstr(r1, prev);
1976
	else
1977
		strbuf_addf(r1, "%s..%s", head_oid, prev);
1978

1979
	if (origin)
1980
		strbuf_addf(r2, "%s..%s", oid_to_hex(&origin->object.oid), head_oid);
1981
	else if (prev_is_range)
1982
		die(_("failed to infer range-diff origin of current series"));
1983
	else {
1984
		warning(_("using '%s' as range-diff origin of current series"), prev);
1985
		strbuf_addf(r2, "%s..%s", prev, head_oid);
1986
	}
1987
}
1988

1989
int cmd_format_patch(int argc, const char **argv, const char *prefix)
1990
{
1991
	struct format_config cfg;
1992
	struct commit *commit;
1993
	struct commit **list = NULL;
1994
	struct rev_info rev;
1995
	char *to_free = NULL;
1996
	struct setup_revision_opt s_r_opt;
1997
	int nr = 0, total, i;
1998
	int use_stdout = 0;
1999
	int start_number = -1;
2000
	int just_numbers = 0;
2001
	int ignore_if_in_upstream = 0;
2002
	int cover_letter = -1;
2003
	int boundary_count = 0;
2004
	int no_binary_diff = 0;
2005
	int zero_commit = 0;
2006
	struct commit *origin = NULL;
2007
	const char *in_reply_to = NULL;
2008
	struct patch_ids ids;
2009
	struct strbuf buf = STRBUF_INIT;
2010
	int use_patch_format = 0;
2011
	int quiet = 0;
2012
	const char *reroll_count = NULL;
2013
	char *cover_from_description_arg = NULL;
2014
	char *description_file = NULL;
2015
	char *branch_name = NULL;
2016
	struct base_tree_info bases;
2017
	struct commit *base;
2018
	int show_progress = 0;
2019
	struct progress *progress = NULL;
2020
	struct oid_array idiff_prev = OID_ARRAY_INIT;
2021
	struct strbuf idiff_title = STRBUF_INIT;
2022
	const char *rdiff_prev = NULL;
2023
	struct strbuf rdiff1 = STRBUF_INIT;
2024
	struct strbuf rdiff2 = STRBUF_INIT;
2025
	struct strbuf rdiff_title = STRBUF_INIT;
2026
	const char *rfc = NULL;
2027
	int creation_factor = -1;
2028
	const char *signature = git_version_string;
2029
	char *signature_to_free = NULL;
2030
	char *signature_file_arg = NULL;
2031
	struct keep_callback_data keep_callback_data = {
2032
		.cfg = &cfg,
2033
		.revs = &rev,
2034
	};
2035
	const char *fmt_patch_suffix = NULL;
2036

2037
	const struct option builtin_format_patch_options[] = {
2038
		OPT_CALLBACK_F('n', "numbered", &cfg, NULL,
2039
			    N_("use [PATCH n/m] even with a single patch"),
2040
			    PARSE_OPT_NOARG, numbered_callback),
2041
		OPT_CALLBACK_F('N', "no-numbered", &cfg, NULL,
2042
			    N_("use [PATCH] even with multiple patches"),
2043
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, no_numbered_callback),
2044
		OPT_BOOL('s', "signoff", &cfg.do_signoff, N_("add a Signed-off-by trailer")),
2045
		OPT_BOOL(0, "stdout", &use_stdout,
2046
			    N_("print patches to standard out")),
2047
		OPT_BOOL(0, "cover-letter", &cover_letter,
2048
			    N_("generate a cover letter")),
2049
		OPT_BOOL(0, "numbered-files", &just_numbers,
2050
			    N_("use simple number sequence for output file names")),
2051
		OPT_STRING(0, "suffix", &fmt_patch_suffix, N_("sfx"),
2052
			    N_("use <sfx> instead of '.patch'")),
2053
		OPT_INTEGER(0, "start-number", &start_number,
2054
			    N_("start numbering patches at <n> instead of 1")),
2055
		OPT_STRING('v', "reroll-count", &reroll_count, N_("reroll-count"),
2056
			    N_("mark the series as Nth re-roll")),
2057
		OPT_INTEGER(0, "filename-max-length", &cfg.log.fmt_patch_name_max,
2058
			    N_("max length of output filename")),
2059
		OPT_CALLBACK_F(0, "rfc", &rfc, N_("rfc"),
2060
			       N_("add <rfc> (default 'RFC') before 'PATCH'"),
2061
			       PARSE_OPT_OPTARG, rfc_callback),
2062
		OPT_STRING(0, "cover-from-description", &cover_from_description_arg,
2063
			    N_("cover-from-description-mode"),
2064
			    N_("generate parts of a cover letter based on a branch's description")),
2065
		OPT_FILENAME(0, "description-file", &description_file,
2066
			     N_("use branch description from file")),
2067
		OPT_CALLBACK_F(0, "subject-prefix", &cfg, N_("prefix"),
2068
			    N_("use [<prefix>] instead of [PATCH]"),
2069
			    PARSE_OPT_NONEG, subject_prefix_callback),
2070
		OPT_CALLBACK_F('o', "output-directory", &output_directory,
2071
			    N_("dir"), N_("store resulting files in <dir>"),
2072
			    PARSE_OPT_NONEG, output_directory_callback),
2073
		OPT_CALLBACK_F('k', "keep-subject", &keep_callback_data, NULL,
2074
			    N_("don't strip/add [PATCH]"),
2075
			    PARSE_OPT_NOARG | PARSE_OPT_NONEG, keep_callback),
2076
		OPT_BOOL(0, "no-binary", &no_binary_diff,
2077
			 N_("don't output binary diffs")),
2078
		OPT_BOOL(0, "zero-commit", &zero_commit,
2079
			 N_("output all-zero hash in From header")),
2080
		OPT_BOOL(0, "ignore-if-in-upstream", &ignore_if_in_upstream,
2081
			 N_("don't include a patch matching a commit upstream")),
2082
		OPT_SET_INT_F('p', "no-stat", &use_patch_format,
2083
			      N_("show patch format instead of default (patch + stat)"),
2084
			      1, PARSE_OPT_NONEG),
2085
		OPT_GROUP(N_("Messaging")),
2086
		OPT_CALLBACK(0, "add-header", &cfg, N_("header"),
2087
			    N_("add email header"), header_callback),
2088
		OPT_STRING_LIST(0, "to", &cfg.extra_to, N_("email"), N_("add To: header")),
2089
		OPT_STRING_LIST(0, "cc", &cfg.extra_cc, N_("email"), N_("add Cc: header")),
2090
		OPT_CALLBACK_F(0, "from", &cfg.from, N_("ident"),
2091
			    N_("set From address to <ident> (or committer ident if absent)"),
2092
			    PARSE_OPT_OPTARG, from_callback),
2093
		OPT_STRING(0, "in-reply-to", &in_reply_to, N_("message-id"),
2094
			    N_("make first mail a reply to <message-id>")),
2095
		OPT_CALLBACK_F(0, "attach", &rev, N_("boundary"),
2096
			    N_("attach the patch"), PARSE_OPT_OPTARG,
2097
			    attach_callback),
2098
		OPT_CALLBACK_F(0, "inline", &rev, N_("boundary"),
2099
			    N_("inline the patch"),
2100
			    PARSE_OPT_OPTARG | PARSE_OPT_NONEG,
2101
			    inline_callback),
2102
		OPT_CALLBACK_F(0, "thread", &cfg, N_("style"),
2103
			    N_("enable message threading, styles: shallow, deep"),
2104
			    PARSE_OPT_OPTARG, thread_callback),
2105
		OPT_STRING(0, "signature", &signature, N_("signature"),
2106
			    N_("add a signature")),
2107
		OPT_CALLBACK_F(0, "base", &cfg, N_("base-commit"),
2108
			       N_("add prerequisite tree info to the patch series"),
2109
			       0, base_callback),
2110
		OPT_FILENAME(0, "signature-file", &signature_file_arg,
2111
				N_("add a signature from a file")),
2112
		OPT__QUIET(&quiet, N_("don't print the patch filenames")),
2113
		OPT_BOOL(0, "progress", &show_progress,
2114
			 N_("show progress while generating patches")),
2115
		OPT_CALLBACK(0, "interdiff", &idiff_prev, N_("rev"),
2116
			     N_("show changes against <rev> in cover letter or single patch"),
2117
			     parse_opt_object_name),
2118
		OPT_STRING(0, "range-diff", &rdiff_prev, N_("refspec"),
2119
			   N_("show changes against <refspec> in cover letter or single patch")),
2120
		OPT_INTEGER(0, "creation-factor", &creation_factor,
2121
			    N_("percentage by which creation is weighted")),
2122
		OPT_BOOL(0, "force-in-body-from", &force_in_body_from,
2123
			 N_("show in-body From: even if identical to the e-mail header")),
2124
		OPT_END()
2125
	};
2126

2127
	format_config_init(&cfg);
2128
	init_diff_ui_defaults();
2129
	init_display_notes(&cfg.notes_opt);
2130
	git_config(git_format_config, &cfg);
2131
	repo_init_revisions(the_repository, &rev, prefix);
2132
	git_config(grep_config, &rev.grep_filter);
2133

2134
	rev.show_notes = cfg.show_notes;
2135
	memcpy(&rev.notes_opt, &cfg.notes_opt, sizeof(cfg.notes_opt));
2136
	rev.commit_format = CMIT_FMT_EMAIL;
2137
	rev.encode_email_headers = cfg.log.default_encode_email_headers;
2138
	rev.expand_tabs_in_log_default = 0;
2139
	rev.verbose_header = 1;
2140
	rev.diff = 1;
2141
	rev.max_parents = 1;
2142
	rev.diffopt.flags.recursive = 1;
2143
	rev.diffopt.no_free = 1;
2144
	memset(&s_r_opt, 0, sizeof(s_r_opt));
2145
	s_r_opt.def = "HEAD";
2146
	s_r_opt.revarg_opt = REVARG_COMMITTISH;
2147

2148
	strbuf_addstr(&cfg.sprefix, cfg.log.fmt_patch_subject_prefix);
2149
	if (format_no_prefix)
2150
		diff_set_noprefix(&rev.diffopt);
2151

2152
	if (cfg.default_attach) {
2153
		rev.mime_boundary = cfg.default_attach;
2154
		rev.no_inline = 1;
2155
	}
2156

2157
	/*
2158
	 * Parse the arguments before setup_revisions(), or something
2159
	 * like "git format-patch -o a123 HEAD^.." may fail; a123 is
2160
	 * possibly a valid SHA1.
2161
	 */
2162
	argc = parse_options(argc, argv, prefix, builtin_format_patch_options,
2163
			     builtin_format_patch_usage,
2164
			     PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
2165
			     PARSE_OPT_KEEP_DASHDASH);
2166

2167
	rev.force_in_body_from = force_in_body_from;
2168

2169
	if (!fmt_patch_suffix)
2170
		fmt_patch_suffix = cfg.fmt_patch_suffix;
2171

2172
	/* Make sure "0000-$sub.patch" gives non-negative length for $sub */
2173
	if (cfg.log.fmt_patch_name_max <= strlen("0000-") + strlen(fmt_patch_suffix))
2174
		cfg.log.fmt_patch_name_max = strlen("0000-") + strlen(fmt_patch_suffix);
2175

2176
	if (cover_from_description_arg)
2177
		cfg.cover_from_description_mode = parse_cover_from_description(cover_from_description_arg);
2178

2179
	if (rfc && rfc[0]) {
2180
		cfg.subject_prefix = 1;
2181
		if (rfc[0] == '-')
2182
			strbuf_addf(&cfg.sprefix, " %s", rfc + 1);
2183
		else
2184
			strbuf_insertf(&cfg.sprefix, 0, "%s ", rfc);
2185
	}
2186

2187
	if (reroll_count) {
2188
		strbuf_addf(&cfg.sprefix, " v%s", reroll_count);
2189
		rev.reroll_count = reroll_count;
2190
	}
2191

2192
	rev.subject_prefix = cfg.sprefix.buf;
2193

2194
	for (i = 0; i < cfg.extra_hdr.nr; i++) {
2195
		strbuf_addstr(&buf, cfg.extra_hdr.items[i].string);
2196
		strbuf_addch(&buf, '\n');
2197
	}
2198

2199
	if (cfg.extra_to.nr)
2200
		strbuf_addstr(&buf, "To: ");
2201
	for (i = 0; i < cfg.extra_to.nr; i++) {
2202
		if (i)
2203
			strbuf_addstr(&buf, "    ");
2204
		strbuf_addstr(&buf, cfg.extra_to.items[i].string);
2205
		if (i + 1 < cfg.extra_to.nr)
2206
			strbuf_addch(&buf, ',');
2207
		strbuf_addch(&buf, '\n');
2208
	}
2209

2210
	if (cfg.extra_cc.nr)
2211
		strbuf_addstr(&buf, "Cc: ");
2212
	for (i = 0; i < cfg.extra_cc.nr; i++) {
2213
		if (i)
2214
			strbuf_addstr(&buf, "    ");
2215
		strbuf_addstr(&buf, cfg.extra_cc.items[i].string);
2216
		if (i + 1 < cfg.extra_cc.nr)
2217
			strbuf_addch(&buf, ',');
2218
		strbuf_addch(&buf, '\n');
2219
	}
2220

2221
	rev.extra_headers = to_free = strbuf_detach(&buf, NULL);
2222

2223
	if (cfg.from) {
2224
		if (split_ident_line(&rev.from_ident, cfg.from, strlen(cfg.from)))
2225
			die(_("invalid ident line: %s"), cfg.from);
2226
	}
2227

2228
	if (start_number < 0)
2229
		start_number = 1;
2230

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

2239
	if (cfg.numbered && cfg.keep_subject)
2240
		die(_("options '%s' and '%s' cannot be used together"), "-n", "-k");
2241
	if (cfg.keep_subject && cfg.subject_prefix)
2242
		die(_("options '%s' and '%s' cannot be used together"), "--subject-prefix/--rfc", "-k");
2243
	rev.preserve_subject = cfg.keep_subject;
2244

2245
	argc = setup_revisions(argc, argv, &rev, &s_r_opt);
2246
	if (argc > 1)
2247
		die(_("unrecognized argument: %s"), argv[1]);
2248

2249
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME)
2250
		die(_("--name-only does not make sense"));
2251
	if (rev.diffopt.output_format & DIFF_FORMAT_NAME_STATUS)
2252
		die(_("--name-status does not make sense"));
2253
	if (rev.diffopt.output_format & DIFF_FORMAT_CHECKDIFF)
2254
		die(_("--check does not make sense"));
2255
	if (rev.remerge_diff)
2256
		die(_("--remerge-diff does not make sense"));
2257

2258
	if (!use_patch_format &&
2259
		(!rev.diffopt.output_format ||
2260
		 rev.diffopt.output_format == DIFF_FORMAT_PATCH))
2261
		rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT | DIFF_FORMAT_SUMMARY;
2262
	if (!rev.diffopt.stat_width)
2263
		rev.diffopt.stat_width = MAIL_DEFAULT_WRAP;
2264

2265
	/* Always generate a patch */
2266
	rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
2267
	rev.always_show_header = 1;
2268

2269
	rev.zero_commit = zero_commit;
2270
	rev.patch_name_max = cfg.log.fmt_patch_name_max;
2271

2272
	if (!rev.diffopt.flags.text && !no_binary_diff)
2273
		rev.diffopt.flags.binary = 1;
2274

2275
	if (rev.show_notes)
2276
		load_display_notes(&rev.notes_opt);
2277

2278
	die_for_incompatible_opt3(use_stdout, "--stdout",
2279
				  rev.diffopt.close_file, "--output",
2280
				  !!output_directory, "--output-directory");
2281

2282
	if (use_stdout && stdout_mboxrd)
2283
		rev.commit_format = CMIT_FMT_MBOXRD;
2284

2285
	if (use_stdout) {
2286
		setup_pager();
2287
	} else if (!rev.diffopt.close_file) {
2288
		int saved;
2289

2290
		if (!output_directory)
2291
			output_directory = cfg.config_output_directory;
2292
		output_directory = set_outdir(prefix, output_directory);
2293

2294
		if (rev.diffopt.use_color != GIT_COLOR_ALWAYS)
2295
			rev.diffopt.use_color = GIT_COLOR_NEVER;
2296
		/*
2297
		 * We consider <outdir> as 'outside of gitdir', therefore avoid
2298
		 * applying adjust_shared_perm in s-c-l-d.
2299
		 */
2300
		saved = get_shared_repository();
2301
		set_shared_repository(0);
2302
		switch (safe_create_leading_directories_const(output_directory)) {
2303
		case SCLD_OK:
2304
		case SCLD_EXISTS:
2305
			break;
2306
		default:
2307
			die(_("could not create leading directories "
2308
			      "of '%s'"), output_directory);
2309
		}
2310
		set_shared_repository(saved);
2311
		if (mkdir(output_directory, 0777) < 0 && errno != EEXIST)
2312
			die_errno(_("could not create directory '%s'"),
2313
				  output_directory);
2314
	}
2315

2316
	if (rev.pending.nr == 1) {
2317
		int check_head = 0;
2318

2319
		if (rev.max_count < 0 && !rev.show_root_diff) {
2320
			/*
2321
			 * This is traditional behaviour of "git format-patch
2322
			 * origin" that prepares what the origin side still
2323
			 * does not have.
2324
			 */
2325
			rev.pending.objects[0].item->flags |= UNINTERESTING;
2326
			add_head_to_pending(&rev);
2327
			check_head = 1;
2328
		}
2329
		/*
2330
		 * Otherwise, it is "format-patch -22 HEAD", and/or
2331
		 * "format-patch --root HEAD".  The user wants
2332
		 * get_revision() to do the usual traversal.
2333
		 */
2334

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

2338
		if (check_head) {
2339
			const char *ref, *v;
2340
			ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
2341
						      "HEAD",
2342
						      RESOLVE_REF_READING,
2343
						      NULL, NULL);
2344
			if (ref && skip_prefix(ref, "refs/heads/", &v))
2345
				branch_name = xstrdup(v);
2346
			else
2347
				branch_name = xstrdup(""); /* no branch */
2348
		}
2349
	}
2350

2351
	/*
2352
	 * We cannot move this anywhere earlier because we do want to
2353
	 * know if --root was given explicitly from the command line.
2354
	 */
2355
	rev.show_root_diff = 1;
2356

2357
	if (ignore_if_in_upstream) {
2358
		/* Don't say anything if head and upstream are the same. */
2359
		if (rev.pending.nr == 2) {
2360
			struct object_array_entry *o = rev.pending.objects;
2361
			if (oideq(&o[0].item->oid, &o[1].item->oid))
2362
				goto done;
2363
		}
2364
		get_patch_ids(&rev, &ids);
2365
	}
2366

2367
	if (prepare_revision_walk(&rev))
2368
		die(_("revision walk setup failed"));
2369
	rev.boundary = 1;
2370
	while ((commit = get_revision(&rev)) != NULL) {
2371
		if (commit->object.flags & BOUNDARY) {
2372
			boundary_count++;
2373
			origin = (boundary_count == 1) ? commit : NULL;
2374
			continue;
2375
		}
2376

2377
		if (ignore_if_in_upstream && has_commit_patch_id(commit, &ids))
2378
			continue;
2379

2380
		nr++;
2381
		REALLOC_ARRAY(list, nr);
2382
		list[nr - 1] = commit;
2383
	}
2384
	if (nr == 0)
2385
		/* nothing to do */
2386
		goto done;
2387
	total = nr;
2388
	if (cover_letter == -1) {
2389
		if (cfg.config_cover_letter == COVER_AUTO)
2390
			cover_letter = (total > 1);
2391
		else if ((idiff_prev.nr || rdiff_prev) && (total > 1))
2392
			cover_letter = (cfg.config_cover_letter != COVER_OFF);
2393
		else
2394
			cover_letter = (cfg.config_cover_letter == COVER_ON);
2395
	}
2396
	if (!cfg.keep_subject && cfg.auto_number && (total > 1 || cover_letter))
2397
		cfg.numbered = 1;
2398
	if (cfg.numbered)
2399
		rev.total = total + start_number - 1;
2400

2401
	if (idiff_prev.nr) {
2402
		if (!cover_letter && total != 1)
2403
			die(_("--interdiff requires --cover-letter or single patch"));
2404
		rev.idiff_oid1 = &idiff_prev.oid[idiff_prev.nr - 1];
2405
		rev.idiff_oid2 = get_commit_tree_oid(list[0]);
2406
		rev.idiff_title = diff_title(&idiff_title, reroll_count,
2407
					     _("Interdiff:"),
2408
					     _("Interdiff against v%d:"));
2409
	}
2410

2411
	if (creation_factor < 0)
2412
		creation_factor = CREATION_FACTOR_FOR_THE_SAME_SERIES;
2413
	else if (!rdiff_prev)
2414
		die(_("the option '%s' requires '%s'"), "--creation-factor", "--range-diff");
2415

2416
	if (rdiff_prev) {
2417
		if (!cover_letter && total != 1)
2418
			die(_("--range-diff requires --cover-letter or single patch"));
2419

2420
		infer_range_diff_ranges(&rdiff1, &rdiff2, rdiff_prev,
2421
					origin, list[0]);
2422
		rev.rdiff1 = rdiff1.buf;
2423
		rev.rdiff2 = rdiff2.buf;
2424
		rev.creation_factor = creation_factor;
2425
		rev.rdiff_title = diff_title(&rdiff_title, reroll_count,
2426
					     _("Range-diff:"),
2427
					     _("Range-diff against v%d:"));
2428
	}
2429

2430
	/*
2431
	 * The order of precedence is:
2432
	 *
2433
	 *   1. The `--signature` and `--no-signature` options.
2434
	 *   2. The `--signature-file` option.
2435
	 *   3. The `format.signature` config.
2436
	 *   4. The `format.signatureFile` config.
2437
	 *   5. Default `git_version_string`.
2438
	 */
2439
	if (!signature) {
2440
		; /* --no-signature inhibits all signatures */
2441
	} else if (signature && signature != git_version_string) {
2442
		; /* non-default signature already set */
2443
	} else if (signature_file_arg || (cfg.signature_file && !cfg.signature)) {
2444
		struct strbuf buf = STRBUF_INIT;
2445
		const char *signature_file = signature_file_arg ?
2446
			signature_file_arg : cfg.signature_file;
2447

2448
		if (strbuf_read_file(&buf, signature_file, 128) < 0)
2449
			die_errno(_("unable to read signature file '%s'"), signature_file);
2450
		signature = signature_to_free = strbuf_detach(&buf, NULL);
2451
	} else if (cfg.signature) {
2452
		signature = cfg.signature;
2453
	}
2454

2455
	memset(&bases, 0, sizeof(bases));
2456
	base = get_base_commit(&cfg, list, nr);
2457
	if (base) {
2458
		reset_revision_walk();
2459
		clear_object_flags(UNINTERESTING);
2460
		prepare_bases(&bases, base, list, nr);
2461
	}
2462

2463
	if (in_reply_to || cfg.thread || cover_letter) {
2464
		rev.ref_message_ids = xmalloc(sizeof(*rev.ref_message_ids));
2465
		string_list_init_dup(rev.ref_message_ids);
2466
	}
2467
	if (in_reply_to) {
2468
		char *msgid = clean_message_id(in_reply_to);
2469
		string_list_append_nodup(rev.ref_message_ids, msgid);
2470
	}
2471
	rev.numbered_files = just_numbers;
2472
	rev.patch_suffix = fmt_patch_suffix;
2473
	if (cover_letter) {
2474
		if (cfg.thread)
2475
			gen_message_id(&rev, "cover");
2476
		make_cover_letter(&rev, !!output_directory,
2477
				  origin, nr, list, description_file, branch_name, quiet, &cfg);
2478
		print_bases(&bases, rev.diffopt.file);
2479
		print_signature(signature, rev.diffopt.file);
2480
		total++;
2481
		start_number--;
2482
		/* interdiff/range-diff in cover-letter; omit from patches */
2483
		rev.idiff_oid1 = NULL;
2484
		rev.rdiff1 = NULL;
2485
	}
2486
	rev.add_signoff = cfg.do_signoff;
2487

2488
	if (show_progress)
2489
		progress = start_delayed_progress(_("Generating patches"), total);
2490
	while (0 <= --nr) {
2491
		int shown;
2492
		display_progress(progress, total - nr);
2493
		commit = list[nr];
2494
		rev.nr = total - nr + (start_number - 1);
2495
		/* Make the second and subsequent mails replies to the first */
2496
		if (cfg.thread) {
2497
			/* Have we already had a message ID? */
2498
			if (rev.message_id) {
2499
				/*
2500
				 * For deep threading: make every mail
2501
				 * a reply to the previous one, no
2502
				 * matter what other options are set.
2503
				 *
2504
				 * For shallow threading:
2505
				 *
2506
				 * Without --cover-letter and
2507
				 * --in-reply-to, make every mail a
2508
				 * reply to the one before.
2509
				 *
2510
				 * With --in-reply-to but no
2511
				 * --cover-letter, make every mail a
2512
				 * reply to the <reply-to>.
2513
				 *
2514
				 * With --cover-letter, make every
2515
				 * mail but the cover letter a reply
2516
				 * to the cover letter.  The cover
2517
				 * letter is a reply to the
2518
				 * --in-reply-to, if specified.
2519
				 */
2520
				if (cfg.thread == THREAD_SHALLOW
2521
				    && rev.ref_message_ids->nr > 0
2522
				    && (!cover_letter || rev.nr > 1))
2523
					free(rev.message_id);
2524
				else
2525
					string_list_append_nodup(rev.ref_message_ids,
2526
								 rev.message_id);
2527
			}
2528
			gen_message_id(&rev, oid_to_hex(&commit->object.oid));
2529
		}
2530

2531
		if (output_directory &&
2532
		    open_next_file(rev.numbered_files ? NULL : commit, NULL, &rev, quiet))
2533
			die(_("failed to create output files"));
2534
		shown = log_tree_commit(&rev, commit);
2535
		free_commit_buffer(the_repository->parsed_objects,
2536
				   commit);
2537

2538
		/* We put one extra blank line between formatted
2539
		 * patches and this flag is used by log-tree code
2540
		 * to see if it needs to emit a LF before showing
2541
		 * the log; when using one file per patch, we do
2542
		 * not want the extra blank line.
2543
		 */
2544
		if (output_directory)
2545
			rev.shown_one = 0;
2546
		if (shown) {
2547
			print_bases(&bases, rev.diffopt.file);
2548
			if (rev.mime_boundary)
2549
				fprintf(rev.diffopt.file, "\n--%s%s--\n\n\n",
2550
				       mime_boundary_leader,
2551
				       rev.mime_boundary);
2552
			else
2553
				print_signature(signature, rev.diffopt.file);
2554
		}
2555
		if (output_directory) {
2556
			fclose(rev.diffopt.file);
2557
			rev.diffopt.file = NULL;
2558
		}
2559
	}
2560
	stop_progress(&progress);
2561
	free(list);
2562
	if (ignore_if_in_upstream)
2563
		free_patch_ids(&ids);
2564

2565
done:
2566
	oid_array_clear(&idiff_prev);
2567
	strbuf_release(&idiff_title);
2568
	strbuf_release(&rdiff1);
2569
	strbuf_release(&rdiff2);
2570
	strbuf_release(&rdiff_title);
2571
	free(description_file);
2572
	free(signature_file_arg);
2573
	free(signature_to_free);
2574
	free(branch_name);
2575
	free(to_free);
2576
	free(rev.message_id);
2577
	if (rev.ref_message_ids)
2578
		string_list_clear(rev.ref_message_ids, 0);
2579
	free(rev.ref_message_ids);
2580
	rev.diffopt.no_free = 0;
2581
	release_revisions(&rev);
2582
	format_config_release(&cfg);
2583
	return 0;
2584
}
2585

2586
static int add_pending_commit(const char *arg, struct rev_info *revs, int flags)
2587
{
2588
	struct object_id oid;
2589
	if (repo_get_oid(the_repository, arg, &oid) == 0) {
2590
		struct commit *commit = lookup_commit_reference(the_repository,
2591
								&oid);
2592
		if (commit) {
2593
			commit->object.flags |= flags;
2594
			add_pending_object(revs, &commit->object, arg);
2595
			return 0;
2596
		}
2597
	}
2598
	return -1;
2599
}
2600

2601
static const char * const cherry_usage[] = {
2602
	N_("git cherry [-v] [<upstream> [<head> [<limit>]]]"),
2603
	NULL
2604
};
2605

2606
static void print_commit(char sign, struct commit *commit, int verbose,
2607
			 int abbrev, FILE *file)
2608
{
2609
	if (!verbose) {
2610
		fprintf(file, "%c %s\n", sign,
2611
		       repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev));
2612
	} else {
2613
		struct strbuf buf = STRBUF_INIT;
2614
		pp_commit_easy(CMIT_FMT_ONELINE, commit, &buf);
2615
		fprintf(file, "%c %s %s\n", sign,
2616
		       repo_find_unique_abbrev(the_repository, &commit->object.oid, abbrev),
2617
		       buf.buf);
2618
		strbuf_release(&buf);
2619
	}
2620
}
2621

2622
int cmd_cherry(int argc, const char **argv, const char *prefix)
2623
{
2624
	struct rev_info revs;
2625
	struct patch_ids ids;
2626
	struct commit *commit;
2627
	struct commit_list *list = NULL;
2628
	struct branch *current_branch;
2629
	const char *upstream;
2630
	const char *head = "HEAD";
2631
	const char *limit = NULL;
2632
	int verbose = 0, abbrev = 0;
2633

2634
	struct option options[] = {
2635
		OPT__ABBREV(&abbrev),
2636
		OPT__VERBOSE(&verbose, N_("be verbose")),
2637
		OPT_END()
2638
	};
2639

2640
	argc = parse_options(argc, argv, prefix, options, cherry_usage, 0);
2641

2642
	switch (argc) {
2643
	case 3:
2644
		limit = argv[2];
2645
		/* FALLTHROUGH */
2646
	case 2:
2647
		head = argv[1];
2648
		/* FALLTHROUGH */
2649
	case 1:
2650
		upstream = argv[0];
2651
		break;
2652
	default:
2653
		current_branch = branch_get(NULL);
2654
		upstream = branch_get_upstream(current_branch, NULL);
2655
		if (!upstream) {
2656
			fprintf(stderr, _("Could not find a tracked"
2657
					" remote branch, please"
2658
					" specify <upstream> manually.\n"));
2659
			usage_with_options(cherry_usage, options);
2660
		}
2661
	}
2662

2663
	repo_init_revisions(the_repository, &revs, prefix);
2664
	revs.max_parents = 1;
2665

2666
	if (add_pending_commit(head, &revs, 0))
2667
		die(_("unknown commit %s"), head);
2668
	if (add_pending_commit(upstream, &revs, UNINTERESTING))
2669
		die(_("unknown commit %s"), upstream);
2670

2671
	/* Don't say anything if head and upstream are the same. */
2672
	if (revs.pending.nr == 2) {
2673
		struct object_array_entry *o = revs.pending.objects;
2674
		if (oideq(&o[0].item->oid, &o[1].item->oid))
2675
			return 0;
2676
	}
2677

2678
	get_patch_ids(&revs, &ids);
2679

2680
	if (limit && add_pending_commit(limit, &revs, UNINTERESTING))
2681
		die(_("unknown commit %s"), limit);
2682

2683
	/* reverse the list of commits */
2684
	if (prepare_revision_walk(&revs))
2685
		die(_("revision walk setup failed"));
2686
	while ((commit = get_revision(&revs)) != NULL) {
2687
		commit_list_insert(commit, &list);
2688
	}
2689

2690
	for (struct commit_list *l = list; l; l = l->next) {
2691
		char sign = '+';
2692

2693
		commit = l->item;
2694
		if (has_commit_patch_id(commit, &ids))
2695
			sign = '-';
2696
		print_commit(sign, commit, verbose, abbrev, revs.diffopt.file);
2697
	}
2698

2699
	free_commit_list(list);
2700
	free_patch_ids(&ids);
2701
	return 0;
2702
}
2703

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.