commit.c 50.7 KB
Newer Older
1 2 3 4 5 6 7
/*
 * Builtin "git commit"
 *
 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
 */

8
#define USE_THE_INDEX_COMPATIBILITY_MACROS
9
#include "cache.h"
10
#include "config.h"
11
#include "lockfile.h"
12
#include "cache-tree.h"
13
#include "color.h"
14
#include "dir.h"
15 16 17 18 19 20 21 22 23 24 25 26
#include "builtin.h"
#include "diff.h"
#include "diffcore.h"
#include "commit.h"
#include "revision.h"
#include "wt-status.h"
#include "run-command.h"
#include "refs.h"
#include "log-tree.h"
#include "strbuf.h"
#include "utf8.h"
#include "parse-options.h"
27
#include "string-list.h"
28
#include "rerere.h"
29
#include "unpack-trees.h"
30
#include "quote.h"
31
#include "submodule.h"
32
#include "gpg-interface.h"
Duy Nguyen's avatar
Duy Nguyen committed
33
#include "column.h"
34
#include "sequencer.h"
35
#include "mailmap.h"
36
#include "help.h"
37
#include "commit-reach.h"
38
#include "commit-graph.h"
39 40

static const char * const builtin_commit_usage[] = {
41
	N_("git commit [<options>] [--] <pathspec>..."),
42 43 44
	NULL
};

45
static const char * const builtin_status_usage[] = {
46
	N_("git status [<options>] [--] <pathspec>..."),
47 48 49
	NULL
};

50
static const char empty_amend_advice[] =
51
N_("You asked to amend the most recent commit, but doing so would make\n"
52
"it empty. You can repeat your command with --allow-empty, or you can\n"
53
"remove the commit entirely with \"git reset HEAD^\".\n");
54

55
static const char empty_cherry_pick_advice[] =
56
N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
57 58 59
"If you wish to commit it anyway, use:\n"
"\n"
"    git commit --allow-empty\n"
60 61 62 63 64 65 66
"\n");

static const char empty_cherry_pick_advice_single[] =
N_("Otherwise, please use 'git reset'\n");

static const char empty_cherry_pick_advice_multi[] =
N_("If you wish to skip this commit, use:\n"
67
"\n"
68 69 70 71
"    git reset\n"
"\n"
"Then \"git cherry-pick --continue\" will resume cherry-picking\n"
"the remaining commits.\n");
72

73 74 75 76 77 78 79 80 81 82 83 84
static const char *color_status_slots[] = {
	[WT_STATUS_HEADER]	  = "header",
	[WT_STATUS_UPDATED]	  = "updated",
	[WT_STATUS_CHANGED]	  = "changed",
	[WT_STATUS_UNTRACKED]	  = "untracked",
	[WT_STATUS_NOBRANCH]	  = "noBranch",
	[WT_STATUS_UNMERGED]	  = "unmerged",
	[WT_STATUS_LOCAL_BRANCH]  = "localBranch",
	[WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
	[WT_STATUS_ONBRANCH]	  = "branch",
};

85
static const char *use_message_buffer;
86 87 88 89 90
static struct lock_file index_lock; /* real index */
static struct lock_file false_lock; /* used only for partial commits */
static enum {
	COMMIT_AS_IS = 1,
	COMMIT_NORMAL,
91
	COMMIT_PARTIAL
92
} commit_style;
93

94
static const char *logfile, *force_author;
95
static const char *template_file;
96 97 98 99 100
/*
 * The _message variables are commit names from which to take
 * the commit message and/or authorship.
 */
static const char *author_message, *author_message_buffer;
101
static char *edit_message, *use_message;
102
static char *fixup_message, *squash_message;
103 104
static int all, also, interactive, patch_interactive, only, amend, signoff;
static int edit_flag = -1; /* unspecified */
105
static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
106
static int config_commit_verbose = -1; /* unspecified */
107
static int no_post_rewrite, allow_empty_message;
108
static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
109 110
static char *sign_commit;

111 112 113 114 115 116 117
/*
 * The default commit message cleanup mode will remove the lines
 * beginning with # (shell comments) and leading and trailing
 * whitespaces (empty lines or containing only whitespaces)
 * if editor is used, and only the whitespaces if the message
 * is specified explicitly.
 */
118
static enum commit_msg_cleanup_mode cleanup_mode;
119
static const char *cleanup_arg;
120

121
static enum commit_whence whence;
122
static int sequencer_in_use;
123
static int use_editor = 1, include_status = 1;
124
static int have_option_m;
125
static struct strbuf message = STRBUF_INIT;
126

127
static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
128

129 130 131 132 133 134 135 136 137
static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
{
	enum wt_status_format *value = (enum wt_status_format *)opt->value;
	if (unset)
		*value = STATUS_FORMAT_NONE;
	else if (!arg)
		*value = STATUS_FORMAT_PORCELAIN;
	else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
		*value = STATUS_FORMAT_PORCELAIN;
138 139
	else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
		*value = STATUS_FORMAT_PORCELAIN_V2;
140 141 142 143 144
	else
		die("unsupported porcelain version '%s'", arg);

	return 0;
}
145

146 147 148
static int opt_parse_m(const struct option *opt, const char *arg, int unset)
{
	struct strbuf *buf = opt->value;
149 150
	if (unset) {
		have_option_m = 0;
151
		strbuf_setlen(buf, 0);
152 153
	} else {
		have_option_m = 1;
154 155
		if (buf->len)
			strbuf_addch(buf, '\n');
156
		strbuf_addstr(buf, arg);
157
		strbuf_complete_line(buf);
158 159 160
	}
	return 0;
}
161

162 163 164
static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
{
	const char **value = opt->value;
165 166 167

	BUG_ON_OPT_NEG(unset);

168 169 170 171 172 173 174
	if (arg != NULL && *arg == '=')
		arg = arg + 1;

	*value = arg;
	return 0;
}

175 176
static void determine_whence(struct wt_status *s)
{
177
	if (file_exists(git_path_merge_head(the_repository)))
178
		whence = FROM_MERGE;
179
	else if (file_exists(git_path_cherry_pick_head(the_repository))) {
180
		whence = FROM_CHERRY_PICK;
181
		if (file_exists(git_path_seq_dir()))
182 183
			sequencer_in_use = 1;
	}
184 185 186 187 188 189
	else
		whence = FROM_COMMIT;
	if (s)
		s->whence = whence;
}

190 191
static void status_init_config(struct wt_status *s, config_fn_t fn)
{
192
	wt_status_prepare(the_repository, s);
193
	init_diff_ui_defaults();
194 195
	git_config(fn, s);
	determine_whence(s);
196
	s->hints = advice_status_hints; /* must come after git_config() */
197 198
}

199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
static void rollback_index_files(void)
{
	switch (commit_style) {
	case COMMIT_AS_IS:
		break; /* nothing to do */
	case COMMIT_NORMAL:
		rollback_lock_file(&index_lock);
		break;
	case COMMIT_PARTIAL:
		rollback_lock_file(&index_lock);
		rollback_lock_file(&false_lock);
		break;
	}
}

214
static int commit_index_files(void)
215
{
216 217
	int err = 0;

218 219 220 221
	switch (commit_style) {
	case COMMIT_AS_IS:
		break; /* nothing to do */
	case COMMIT_NORMAL:
222
		err = commit_lock_file(&index_lock);
223 224
		break;
	case COMMIT_PARTIAL:
225
		err = commit_lock_file(&index_lock);
226 227 228
		rollback_lock_file(&false_lock);
		break;
	}
229 230

	return err;
231 232 233 234 235 236
}

/*
 * Take a union of paths in the index and the named tree (typically, "HEAD"),
 * and return the paths that match the given pattern in list.
 */
237
static int list_paths(struct string_list *list, const char *with_tree,
238
		      const struct pathspec *pattern)
239
{
240
	int i, ret;
241 242
	char *m;

243
	if (!pattern->nr)
244 245
		return 0;

246
	m = xcalloc(1, pattern->nr);
247

248
	if (with_tree) {
249
		char *max_prefix = common_prefix(pattern);
250
		overlay_tree_on_index(&the_index, with_tree, max_prefix);
251
		free(max_prefix);
252
	}
253 254

	for (i = 0; i < active_nr; i++) {
255
		const struct cache_entry *ce = active_cache[i];
256 257
		struct string_list_item *item;

258
		if (ce->ce_flags & CE_UPDATE)
259
			continue;
260
		if (!ce_path_match(&the_index, ce, pattern, m))
261
			continue;
262
		item = string_list_insert(list, ce->name);
263 264
		if (ce_skip_worktree(ce))
			item->util = item; /* better a valid pointer than a fake one */
265 266
	}

267
	ret = report_path_error(m, pattern);
268 269
	free(m);
	return ret;
270 271
}

272
static void add_remove_files(struct string_list *list)
273 274 275
{
	int i;
	for (i = 0; i < list->nr; i++) {
276
		struct stat st;
277
		struct string_list_item *p = &(list->items[i]);
278

279 280
		/* p->util is skip-worktree */
		if (p->util)
281
			continue;
282

283 284
		if (!lstat(p->string, &st)) {
			if (add_to_cache(p->string, &st, 0))
285
				die(_("updating files failed"));
286
		} else
287
			remove_file_from_cache(p->string);
288 289 290
	}
}

291
static void create_base_index(const struct commit *current_head)
292 293 294 295 296
{
	struct tree *tree;
	struct unpack_trees_options opts;
	struct tree_desc t;

297
	if (!current_head) {
298 299 300 301 302 303 304 305
		discard_cache();
		return;
	}

	memset(&opts, 0, sizeof(opts));
	opts.head_idx = 1;
	opts.index_only = 1;
	opts.merge = 1;
306 307
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
308 309

	opts.fn = oneway_merge;
310
	tree = parse_tree_indirect(&current_head->object.oid);
311
	if (!tree)
312
		die(_("failed to unpack HEAD tree object"));
313 314
	parse_tree(tree);
	init_tree_desc(&t, tree->buffer, tree->size);
315 316
	if (unpack_trees(1, &t, &opts))
		exit(128); /* We've already reported the error, finish dying */
317 318
}

319 320 321 322 323 324 325 326 327 328
static void refresh_cache_or_die(int refresh_flags)
{
	/*
	 * refresh_flags contains REFRESH_QUIET, so the only errors
	 * are for unmerged entries.
	 */
	if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
		die_resolve_conflict("commit");
}

329 330
static const char *prepare_index(int argc, const char **argv, const char *prefix,
				 const struct commit *current_head, int is_status)
331
{
332
	struct string_list partial = STRING_LIST_INIT_DUP;
333
	struct pathspec pathspec;
334
	int refresh_flags = REFRESH_QUIET;
335
	const char *ret;
336

337 338
	if (is_status)
		refresh_flags |= REFRESH_UNMERGED;
339 340 341
	parse_pathspec(&pathspec, 0,
		       PATHSPEC_PREFER_FULL,
		       prefix, argv);
342

343
	if (read_cache_preload(&pathspec) < 0)
344
		die(_("index file corrupt"));
345

346
	if (interactive) {
347
		char *old_index_env = NULL;
348
		hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
349 350 351

		refresh_cache_or_die(refresh_flags);

352
		if (write_locked_index(&the_index, &index_lock, 0))
353 354
			die(_("unable to create temporary index"));

355
		old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
356
		setenv(INDEX_ENVIRONMENT, get_lock_file_path(&index_lock), 1);
357

358
		if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
359 360 361 362 363 364
			die(_("interactive add failed"));

		if (old_index_env && *old_index_env)
			setenv(INDEX_ENVIRONMENT, old_index_env, 1);
		else
			unsetenv(INDEX_ENVIRONMENT);
365
		FREE_AND_NULL(old_index_env);
366 367

		discard_cache();
368
		read_cache_from(get_lock_file_path(&index_lock));
369
		if (update_main_cache_tree(WRITE_TREE_SILENT) == 0) {
370
			if (reopen_lock_file(&index_lock) < 0)
371
				die(_("unable to write index file"));
372
			if (write_locked_index(&the_index, &index_lock, 0))
373
				die(_("unable to update temporary index"));
374 375
		} else
			warning(_("Failed to update main cache tree"));
376 377

		commit_style = COMMIT_NORMAL;
378 379
		ret = get_lock_file_path(&index_lock);
		goto out;
380 381
	}

382 383 384 385 386 387 388 389 390 391 392 393
	/*
	 * Non partial, non as-is commit.
	 *
	 * (1) get the real index;
	 * (2) update the_index as necessary;
	 * (3) write the_index out to the real index (still locked);
	 * (4) return the name of the locked index file.
	 *
	 * The caller should run hooks on the locked real index, and
	 * (A) if all goes well, commit the real index;
	 * (B) on failure, rollback the real index.
	 */
394
	if (all || (also && pathspec.nr)) {
395
		hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
396
		add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
397
		refresh_cache_or_die(refresh_flags);
398
		update_main_cache_tree(WRITE_TREE_SILENT);
399
		if (write_locked_index(&the_index, &index_lock, 0))
400
			die(_("unable to write new_index file"));
401
		commit_style = COMMIT_NORMAL;
402 403
		ret = get_lock_file_path(&index_lock);
		goto out;
404 405
	}

406 407 408 409 410
	/*
	 * As-is commit.
	 *
	 * (1) return the name of the real index file.
	 *
411 412
	 * The caller should run hooks on the real index,
	 * and create commit from the_index.
413 414
	 * We still need to refresh the index here.
	 */
415
	if (!only && !pathspec.nr) {
416
		hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
417
		refresh_cache_or_die(refresh_flags);
418
		if (active_cache_changed
419
		    || !cache_tree_fully_valid(active_cache_tree))
420
			update_main_cache_tree(WRITE_TREE_SILENT);
421 422 423
		if (write_locked_index(&the_index, &index_lock,
				       COMMIT_LOCK | SKIP_IF_UNCHANGED))
			die(_("unable to write new_index file"));
424
		commit_style = COMMIT_AS_IS;
425 426
		ret = get_index_file();
		goto out;
427 428
	}

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
	/*
	 * A partial commit.
	 *
	 * (0) find the set of affected paths;
	 * (1) get lock on the real index file;
	 * (2) update the_index with the given paths;
	 * (3) write the_index out to the real index (still locked);
	 * (4) get lock on the false index file;
	 * (5) reset the_index from HEAD;
	 * (6) update the_index the same way as (2);
	 * (7) write the_index out to the false index file;
	 * (8) return the name of the false index file (still locked);
	 *
	 * The caller should run hooks on the locked false index, and
	 * create commit from it.  Then
	 * (A) if all goes well, commit the real index;
	 * (B) on failure, rollback the real index;
	 * In either case, rollback the false index.
	 */
	commit_style = COMMIT_PARTIAL;

450 451 452 453 454 455
	if (whence != FROM_COMMIT) {
		if (whence == FROM_MERGE)
			die(_("cannot do a partial commit during a merge."));
		else if (whence == FROM_CHERRY_PICK)
			die(_("cannot do a partial commit during a cherry-pick."));
	}
456

457
	if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
458 459 460 461
		exit(1);

	discard_cache();
	if (read_cache() < 0)
462
		die(_("cannot read the index"));
463

464
	hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
465
	add_remove_files(&partial);
466
	refresh_cache(REFRESH_QUIET);
467
	update_main_cache_tree(WRITE_TREE_SILENT);
468
	if (write_locked_index(&the_index, &index_lock, 0))
469
		die(_("unable to write new_index file"));
470

471 472 473 474
	hold_lock_file_for_update(&false_lock,
				  git_path("next-index-%"PRIuMAX,
					   (uintmax_t) getpid()),
				  LOCK_DIE_ON_ERROR);
475

476
	create_base_index(current_head);
477
	add_remove_files(&partial);
478
	refresh_cache(REFRESH_QUIET);
479

480
	if (write_locked_index(&the_index, &false_lock, 0))
481
		die(_("unable to write temporary index file"));
482 483

	discard_cache();
484 485
	ret = get_lock_file_path(&false_lock);
	read_cache_from(ret);
486 487 488
out:
	string_list_clear(&partial, 0);
	clear_pathspec(&pathspec);
489
	return ret;
490 491
}

492 493
static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
		      struct wt_status *s)
494
{
495
	struct object_id oid;
496

497 498
	if (s->relative_paths)
		s->prefix = prefix;
499 500

	if (amend) {
501 502
		s->amend = 1;
		s->reference = "HEAD^1";
503
	}
504 505 506 507
	s->verbose = verbose;
	s->index_file = index_file;
	s->fp = fp;
	s->nowarn = nowarn;
508
	s->is_initial = get_oid(s->reference, &oid) ? 1 : 0;
509
	if (!s->is_initial)
510
		hashcpy(s->sha1_commit, oid.hash);
511 512
	s->status_format = status_format;
	s->ignore_submodule_arg = ignore_submodule_arg;
513

514
	wt_status_collect(s);
515
	wt_status_print(s);
516
	wt_status_collect_free_buffers(s);
517

518
	return s->committable;
519 520
}

521
static int is_a_merge(const struct commit *current_head)
522
{
523
	return !!(current_head->parents && current_head->parents->next);
524 525
}

526 527
static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
{
528
	if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
529
		BUG("unable to parse our own ident: %s", buf->buf);
530 531
}

532 533 534 535 536 537 538 539 540 541
static void export_one(const char *var, const char *s, const char *e, int hack)
{
	struct strbuf buf = STRBUF_INIT;
	if (hack)
		strbuf_addch(&buf, hack);
	strbuf_addf(&buf, "%.*s", (int)(e - s), s);
	setenv(var, buf.buf, 1);
	strbuf_release(&buf);
}

542
static int parse_force_date(const char *in, struct strbuf *out)
543
{
544
	strbuf_addch(out, '@');
545

546
	if (parse_date(in, out) < 0) {
547 548 549 550
		int errors = 0;
		unsigned long t = approxidate_careful(in, &errors);
		if (errors)
			return -1;
551
		strbuf_addf(out, "%lu", t);
552 553 554 555 556
	}

	return 0;
}

557 558 559 560 561 562
static void set_ident_var(char **buf, char *val)
{
	free(*buf);
	*buf = val;
}

563
static void determine_author_info(struct strbuf *author_ident)
564 565
{
	char *name, *email, *date;
566
	struct ident_split author;
567

568 569 570
	name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
	email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
	date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
571

572
	if (author_message) {
573
		struct ident_split ident;
574
		size_t len;
575
		const char *a;
576

577
		a = find_commit_header(author_message_buffer, "author", &len);
578
		if (!a)
579 580 581 582
			die(_("commit '%s' lacks author header"), author_message);
		if (split_ident_line(&ident, a, len) < 0)
			die(_("commit '%s' has malformed author line"), author_message);

583 584 585
		set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
		set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));

586
		if (ident.date_begin) {
587
			struct strbuf date_buf = STRBUF_INIT;
588 589 590 591
			strbuf_addch(&date_buf, '@');
			strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
			strbuf_addch(&date_buf, ' ');
			strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
592
			set_ident_var(&date, strbuf_detach(&date_buf, NULL));
593
		}
594 595 596
	}

	if (force_author) {
597
		struct ident_split ident;
598

599
		if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
600
			die(_("malformed --author parameter"));
601 602
		set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
		set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
603 604
	}

605
	if (force_date) {
606
		struct strbuf date_buf = STRBUF_INIT;
607
		if (parse_force_date(force_date, &date_buf))
608
			die(_("invalid date format: %s"), force_date);
609
		set_ident_var(&date, strbuf_detach(&date_buf, NULL));
610 611
	}

612 613
	strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
				IDENT_STRICT));
614 615 616 617
	assert_split_ident(&author, author_ident);
	export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
	export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
	export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
618 619 620
	free(name);
	free(email);
	free(date);
621 622
}

623 624 625
static int author_date_is_interesting(void)
{
	return author_message || force_date;
626 627
}

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
static void adjust_comment_line_char(const struct strbuf *sb)
{
	char candidates[] = "#;@!$%^&|:";
	char *candidate;
	const char *p;

	comment_line_char = candidates[0];
	if (!memchr(sb->buf, comment_line_char, sb->len))
		return;

	p = sb->buf;
	candidate = strchr(candidates, *p);
	if (candidate)
		*candidate = ' ';
	for (p = sb->buf; *p; p++) {
		if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
			candidate = strchr(candidates, p[1]);
			if (candidate)
				*candidate = ' ';
		}
	}

	for (p = candidates; *p == ' '; p++)
		;
	if (!*p)
		die(_("unable to select a comment character that is not used\n"
		      "in the current commit message"));
	comment_line_char = *p;
}

658
static int prepare_to_commit(const char *index_file, const char *prefix,
659
			     struct commit *current_head,
660 661
			     struct wt_status *s,
			     struct strbuf *author_ident)
662 663
{
	struct stat statbuf;
664
	struct strbuf committer_ident = STRBUF_INIT;
665
	int committable;
666
	struct strbuf sb = STRBUF_INIT;
667 668
	const char *hook_arg1 = NULL;
	const char *hook_arg2 = NULL;
669
	int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
670
	int old_display_comment_prefix;
671

672 673 674
	/* This checks and barfs if author is badly specified */
	determine_author_info(author_ident);

675
	if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
676
		return 0;
677

678 679 680 681 682 683 684 685 686 687 688 689
	if (squash_message) {
		/*
		 * Insert the proper subject line before other commit
		 * message options add their content.
		 */
		if (use_message && !strcmp(use_message, squash_message))
			strbuf_addstr(&sb, "squash! ");
		else {
			struct pretty_print_context ctx = {0};
			struct commit *c;
			c = lookup_commit_reference_by_name(squash_message);
			if (!c)
690
				die(_("could not lookup commit %s"), squash_message);
691 692 693 694 695 696
			ctx.output_encoding = get_commit_output_encoding();
			format_commit_message(c, "squash! %s\n\n", &sb,
					      &ctx);
		}
	}

697
	if (have_option_m && !fixup_message) {
698
		strbuf_addbuf(&sb, &message);
699
		hook_arg1 = "message";
700 701
	} else if (logfile && !strcmp(logfile, "-")) {
		if (isatty(0))
702
			fprintf(stderr, _("(reading log message from standard input)\n"));
703
		if (strbuf_read(&sb, 0, 0) < 0)
704
			die_errno(_("could not read log from standard input"));
705
		hook_arg1 = "message";
706 707
	} else if (logfile) {
		if (strbuf_read_file(&sb, logfile, 0) < 0)
708
			die_errno(_("could not read log file '%s'"),
709
				  logfile);
710
		hook_arg1 = "message";
711
	} else if (use_message) {
712
		char *buffer;
713
		buffer = strstr(use_message_buffer, "\n\n");
714
		if (buffer)
715
			strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
716 717
		hook_arg1 = "commit";
		hook_arg2 = use_message;
718 719 720 721 722
	} else if (fixup_message) {
		struct pretty_print_context ctx = {0};
		struct commit *commit;
		commit = lookup_commit_reference_by_name(fixup_message);
		if (!commit)
723
			die(_("could not lookup commit %s"), fixup_message);
724 725 726
		ctx.output_encoding = get_commit_output_encoding();
		format_commit_message(commit, "fixup! %s\n\n",
				      &sb, &ctx);
727 728
		if (have_option_m)
			strbuf_addbuf(&sb, &message);
729
		hook_arg1 = "message";
730
	} else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
731 732 733 734
		/*
		 * prepend SQUASH_MSG here if it exists and a
		 * "merge --squash" was originally performed
		 */
735 736
		if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
			if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
737 738 739 740
				die_errno(_("could not read SQUASH_MSG"));
			hook_arg1 = "squash";
		} else
			hook_arg1 = "merge";
741
		if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
742
			die_errno(_("could not read MERGE_MSG"));
743 744
	} else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
		if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
745
			die_errno(_("could not read SQUASH_MSG"));
746
		hook_arg1 = "squash";
747
	} else if (template_file) {
748
		if (strbuf_read_file(&sb, template_file, 0) < 0)
749
			die_errno(_("could not read '%s'"), template_file);
750
		hook_arg1 = "template";
751
		clean_message_contents = 0;
752 753
	}

754
	/*
755 756
	 * The remaining cases don't modify the template message, but
	 * just set the argument(s) to the prepare-commit-msg hook.
757
	 */
758
	else if (whence == FROM_MERGE)
759
		hook_arg1 = "merge";
760 761 762 763
	else if (whence == FROM_CHERRY_PICK) {
		hook_arg1 = "commit";
		hook_arg2 = "CHERRY_PICK_HEAD";
	}
764

765 766 767 768 769 770 771 772 773 774
	if (squash_message) {
		/*
		 * If squash_commit was used for the commit subject,
		 * then we're possibly hijacking other commit log options.
		 * Reset the hook args to tell the real story.
		 */
		hook_arg1 = "message";
		hook_arg2 = "";
	}

775
	s->fp = fopen_for_writing(git_path_commit_editmsg());
776
	if (s->fp == NULL)
777
		die_errno(_("could not open '%s'"), git_path_commit_editmsg());
778

779 780 781 782
	/* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
	old_display_comment_prefix = s->display_comment_prefix;
	s->display_comment_prefix = 1;

783 784 785 786 787 788
	/*
	 * Most hints are counter-productive when the commit has
	 * already started.
	 */
	s->hints = 0;

789
	if (clean_message_contents)
790
		strbuf_stripspace(&sb, 0);
791

792
	if (signoff)
793
		append_signoff(&sb, ignore_non_trailer(sb.buf, sb.len), 0);
794

795
	if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
796
		die_errno(_("could not write commit template"));
797

798 799
	if (auto_comment_line_char)
		adjust_comment_line_char(&sb);
800 801
	strbuf_release(&sb);

802
	/* This checks if committer ident is explicitly given */
803
	strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
804
	if (use_editor && include_status) {
805 806
		int ident_shown = 0;
		int saved_color_setting;
807 808
		struct ident_split ci, ai;

809
		if (whence != FROM_COMMIT) {
810
			if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
811
				wt_status_add_cut_line(s->fp);
812
			status_printf_ln(s, GIT_COLOR_NORMAL,
813 814 815 816 817 818 819 820 821 822 823
			    whence == FROM_MERGE
				? _("\n"
					"It looks like you may be committing a merge.\n"
					"If this is not correct, please remove the file\n"
					"	%s\n"
					"and try again.\n")
				: _("\n"
					"It looks like you may be committing a cherry-pick.\n"
					"If this is not correct, please remove the file\n"
					"	%s\n"
					"and try again.\n"),
824
				whence == FROM_MERGE ?
825 826
					git_path_merge_head(the_repository) :
					git_path_cherry_pick_head(the_repository));
827
		}
828

829
		fprintf(s->fp, "\n");
830
		if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
831 832
			status_printf(s, GIT_COLOR_NORMAL,
				_("Please enter the commit message for your changes."
833 834
				  " Lines starting\nwith '%c' will be ignored, and an empty"
				  " message aborts the commit.\n"), comment_line_char);
835 836
		else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
			 whence == FROM_COMMIT)
837
			wt_status_add_cut_line(s->fp);
838
		else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
839 840
			status_printf(s, GIT_COLOR_NORMAL,
				_("Please enter the commit message for your changes."
841 842 843 844
				  " Lines starting\n"
				  "with '%c' will be kept; you may remove them"
				  " yourself if you want to.\n"
				  "An empty message aborts the commit.\n"), comment_line_char);
845

846 847 848 849 850 851 852 853
		/*
		 * These should never fail because they come from our own
		 * fmt_ident. They may fail the sane_ident test, but we know
		 * that the name and mail pointers will at least be valid,
		 * which is enough for our tests and printing here.
		 */
		assert_split_ident(&ai, author_ident);
		assert_split_ident(&ci, &committer_ident);
854 855

		if (ident_cmp(&ai, &ci))
856
			status_printf_ln(s, GIT_COLOR_NORMAL,
857
				_("%s"
858
				"Author:    %.*s <%.*s>"),
859
				ident_shown++ ? "" : "\n",
860 861
				(int)(ai.name_end - ai.name_begin), ai.name_begin,
				(int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
862

863 864 865 866 867
		if (author_date_is_interesting())
			status_printf_ln(s, GIT_COLOR_NORMAL,
				_("%s"
				"Date:      %s"),
				ident_shown++ ? "" : "\n",
868
				show_ident_date(&ai, DATE_MODE(NORMAL)));
869

870
		if (!committer_ident_sufficiently_given())
871
			status_printf_ln(s, GIT_COLOR_NORMAL,
872
				_("%s"
873
				"Committer: %.*s <%.*s>"),
874
				ident_shown++ ? "" : "\n",
875 876
				(int)(ci.name_end - ci.name_begin), ci.name_begin,
				(int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
877

878
		status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
879

880 881
		saved_color_setting = s->use_color;
		s->use_color = 0;
882
		committable = run_status(s->fp, index_file, prefix, 1, s);
883
		s->use_color = saved_color_setting;
884
		string_list_clear(&s->change, 1);
885
	} else {
886
		struct object_id oid;
887
		const char *parent = "HEAD";
888 889

		if (!active_nr && read_cache() < 0)
890
			die(_("Cannot read index"));
891

892 893 894
		if (amend)
			parent = "HEAD^1";

895
		if (get_oid(parent, &oid)) {
896 897 898 899 900
			int i, ita_nr = 0;

			for (i = 0; i < active_nr; i++)
				if (ce_intent_to_add(active_cache[i]))
					ita_nr++;
901
			committable = active_nr - ita_nr > 0;
902
		} else {
903 904 905 906 907 908 909 910 911
			/*
			 * Unless the user did explicitly request a submodule
			 * ignore mode by passing a command line option we do
			 * not ignore any changed submodule SHA-1s when
			 * comparing index and parent, no matter what is
			 * configured. Otherwise we won't commit any
			 * submodules which were manually staged, which would
			 * be really confusing.
			 */
912
			struct diff_flags flags = DIFF_FLAGS_INIT;
913
			flags.override_submodule_config = 1;
914 915
			if (ignore_submodule_arg &&
			    !strcmp(ignore_submodule_arg, "all"))
916
				flags.ignore_submodules = 1;
917 918
			committable = index_differs_from(the_repository,
							 parent, &flags, 1);
919
		}
920
	}
921
	strbuf_release(&committer_ident);
922

923
	fclose(s->fp);
924

925 926 927 928 929
	/*
	 * Reject an attempt to record a non-merge empty commit without
	 * explicit --allow-empty. In the cherry-pick case, it may be
	 * empty due to conflict resolution, which the user should okay.
	 */
930
	if (!committable && whence != FROM_MERGE && !allow_empty &&
931
	    !(amend && is_a_merge(current_head))) {
932
		s->display_comment_prefix = old_display_comment_prefix;
933
		run_status(stdout, index_file, prefix, 0, s);
934
		if (amend)
935
			fputs(_(empty_amend_advice), stderr);
936
		else if (whence == FROM_CHERRY_PICK) {
937
			fputs(_(empty_cherry_pick_advice), stderr);
938 939 940 941 942
			if (!sequencer_in_use)
				fputs(_(empty_cherry_pick_advice_single), stderr);
			else
				fputs(_(empty_cherry_pick_advice_multi), stderr);
		}
943
		return 0;
944 945
	}

946 947 948 949 950 951 952 953
	if (!no_verify && find_hook("pre-commit")) {
		/*
		 * Re-read the index as pre-commit hook could have updated it,
		 * and write it out as a tree.  We must do this before we invoke
		 * the editor and after we invoke run_status above.
		 */
		discard_cache();
	}
954
	read_cache_from(index_file);
955

956
	if (update_main_cache_tree(0)) {
957
		error(_("Error building trees"));
958
		return 0;
959
	}
960

961
	if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
962
			    git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
963
		return 0;
964

965
	if (use_editor) {
966 967 968 969
		struct argv_array env = ARGV_ARRAY_INIT;

		argv_array_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
		if (launch_editor(git_path_commit_editmsg(), NULL, env.argv)) {
970
			fprintf(stderr,
971
			_("Please supply the message using either -m or -F option.\n"));
972 973
			exit(1);
		}
974
		argv_array_clear(&env);
975
	}
976

977
	if (!no_verify &&
978
	    run_commit_hook(use_editor, index_file, "commit-msg", git_path_commit_editmsg(), NULL)) {
979 980
		return 0;
	}
981

982
	return 1;
983 984
}

985 986 987 988 989
static const char *find_author_by_nickname(const char *name)
{
	struct rev_info revs;
	struct commit *commit;
	struct strbuf buf = STRBUF_INIT;
990
	struct string_list mailmap = STRING_LIST_INIT_NODUP;
991 992 993
	const char *av[20];
	int ac = 0;

994
	repo_init_revisions(the_repository, &revs, NULL);
995 996 997 998 999 1000
	strbuf_addf(&buf, "--author=%s", name);
	av[++ac] = "--all";
	av[++ac] = "-i";
	av[++ac] = buf.buf;
	av[++ac] = NULL;
	setup_revisions(ac, av, &revs, NULL);
1001 1002 1003
	revs.mailmap = &mailmap;
	read_mailmap(revs.mailmap, NULL);

1004 1005
	if (prepare_revision_walk(&revs))
		die(_("revision walk setup failed"));
1006 1007
	commit = get_revision(&revs);
	if (commit) {
1008
		struct pretty_print_context ctx = {0};
1009
		ctx.date_mode.type = DATE_NORMAL;
1010
		strbuf_release(&buf);
1011 1012
		format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
		clear_mailmap(&mailmap);
1013 1014
		return strbuf_detach(&buf, NULL);
	}
1015
	die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1016 1017
}

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
static void handle_ignored_arg(struct wt_status *s)
{
	if (!ignored_arg)
		; /* default already initialized */
	else if (!strcmp(ignored_arg, "traditional"))
		s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
	else if (!strcmp(ignored_arg, "no"))
		s->show_ignored_mode = SHOW_NO_IGNORED;
	else if (!strcmp(ignored_arg, "matching"))
		s->show_ignored_mode = SHOW_MATCHING_IGNORED;
	else
		die(_("Invalid ignored mode '%s'"), ignored_arg);
}
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

static void handle_untracked_files_arg(struct wt_status *s)
{
	if (!untracked_files_arg)
		; /* default already initialized */
	else if (!strcmp(untracked_files_arg, "no"))
		s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
	else if (!strcmp(untracked_files_arg, "normal"))
		s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
	else if (!strcmp(untracked_files_arg, "all"))
		s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1042 1043 1044 1045
	/*
	 * Please update $__git_untracked_file_modes in
	 * git-completion.bash when you add new options
	 */
1046
	else
1047
		die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1048 1049
}

1050 1051
static const char *read_commit_message(const char *name)
{
1052
	const char *out_enc;
1053 1054 1055 1056
	struct commit *commit;

	commit = lookup_commit_reference_by_name(name);
	if (!commit)
1057
		die(_("could not lookup commit %s"), name);
1058
	out_enc = get_commit_output_encoding();
1059
	return logmsg_reencode(commit, NULL, out_enc);
1060 1061
}

1062 1063 1064 1065 1066
/*
 * Enumerate what needs to be propagated when --porcelain
 * is not in effect here.
 */
static struct status_deferred_config {
1067
	enum wt_status_format status_format;
1068 1069 1070 1071 1072 1073 1074 1075 1076
	int show_branch;
} status_deferred_config = {
	STATUS_FORMAT_UNSPECIFIED,
	-1 /* unspecified */
};

static void finalize_deferred_config(struct wt_status *s)
{
	int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1077
				   status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
				   !s->null_termination);

	if (s->null_termination) {
		if (status_format == STATUS_FORMAT_NONE ||
		    status_format == STATUS_FORMAT_UNSPECIFIED)
			status_format = STATUS_FORMAT_PORCELAIN;
		else if (status_format == STATUS_FORMAT_LONG)
			die(_("--long and -z are incompatible"));
	}

	if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
		status_format = status_deferred_config.status_format;
	if (status_format == STATUS_FORMAT_UNSPECIFIED)
		status_format = STATUS_FORMAT_NONE;

	if (use_deferred_config && s->show_branch < 0)
		s->show_branch = status_deferred_config.show_branch;
	if (s->show_branch < 0)
		s->show_branch = 0;
1097 1098 1099

	if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
		s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1100 1101
}

1102
static int parse_and_validate_options(int argc, const char *argv[],
1103
				      const struct option *options,
1104
				      const char * const usage[],
1105
				      const char *prefix,
1106
				      struct commit *current_head,
1107
				      struct wt_status *s)
1108 1109 1110
{
	int f = 0;

1111
	argc = parse_options(argc, argv, prefix, options, usage, 0);
1112
	finalize_deferred_config(s);
1113

1114 1115 1116
	if (force_author && !strchr(force_author, '>'))
		force_author = find_author_by_nickname(force_au