sequencer.c 137 KB
Newer Older
1
#include "cache.h"
2
#include "config.h"
3
#include "lockfile.h"
4
#include "dir.h"
5
#include "object-store.h"
6 7
#include "object.h"
#include "commit.h"
8
#include "sequencer.h"
9 10
#include "tag.h"
#include "run-command.h"
11
#include "exec-cmd.h"
12 13 14 15 16 17 18
#include "utf8.h"
#include "cache-tree.h"
#include "diff.h"
#include "revision.h"
#include "rerere.h"
#include "merge-recursive.h"
#include "refs.h"
19
#include "argv-array.h"
20
#include "quote.h"
21
#include "trailer.h"
22
#include "log-tree.h"
23
#include "wt-status.h"
24
#include "hashmap.h"
25 26
#include "notes-utils.h"
#include "sigchain.h"
27 28
#include "unpack-trees.h"
#include "worktree.h"
29 30
#include "oidmap.h"
#include "oidset.h"
31
#include "commit-slab.h"
32
#include "alias.h"
33
#include "commit-reach.h"
34
#include "rebase-interactive.h"
35 36

#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
37

38
static const char sign_off_header[] = "Signed-off-by: ";
39
static const char cherry_picked_prefix[] = "(cherry picked from commit ";
40

41 42
GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")

43 44 45 46 47
GIT_PATH_FUNC(git_path_seq_dir, "sequencer")

static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
48
static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
49

50 51 52 53 54 55 56
static GIT_PATH_FUNC(rebase_path, "rebase-merge")
/*
 * The file containing rebase commands, comments, and empty lines.
 * This file is created by "git rebase -i" then edited by the user. As
 * the lines are processed, they are removed from the front of this
 * file and written to the tail of 'done'.
 */
57
GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
58
GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
59

60 61 62 63 64 65
/*
 * The rebase command lines that have already been processed. A line
 * is moved here when it is first handled, before any associated user
 * actions.
 */
static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
66 67 68 69
/*
 * The file to keep track of how many commands were already processed (e.g.
 * for the prompt).
 */
70
static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
71 72 73 74
/*
 * The file to keep track of how many commands are to be processed in total
 * (e.g. for the prompt).
 */
75
static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
/*
 * The commit message that is planned to be used for any changes that
 * need to be committed following a user interaction.
 */
static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
/*
 * The file into which is accumulated the suggested commit message for
 * squash/fixup commands. When the first of a series of squash/fixups
 * is seen, the file is created and the commit message from the
 * previous commit and from the first squash/fixup commit are written
 * to it. The commit message for each subsequent squash/fixup commit
 * is appended to the file as it is processed.
 */
static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
/*
 * If the current series of squash/fixups has not yet included a squash
 * command, then this file exists and holds the commit message of the
 * original "pick" commit.  (If the series ends without a "squash"
 * command, then this can be used as the commit message of the combined
 * commit without opening the editor.)
 */
static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
98 99 100 101 102
/*
 * This file contains the list fixup/squash commands that have been
 * accumulated into message-fixup or message-squash so far.
 */
static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
103 104 105 106 107 108
/*
 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
 * GIT_AUTHOR_DATE that will be used for the commit that is currently
 * being rebased.
 */
static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
109 110 111 112 113 114 115 116 117 118 119 120 121 122
/*
 * When an "edit" rebase command is being processed, the SHA1 of the
 * commit to be edited is recorded in this file.  When "git rebase
 * --continue" is executed, if there are any staged changes then they
 * will be amended to the HEAD commit, but only provided the HEAD
 * commit is still the commit to be edited.  When any other rebase
 * command is processed, this file is deleted.
 */
static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
/*
 * When we stop at a given patch via the "edit" command, this file contains
 * the abbreviated commit name of the corresponding patch.
 */
static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
123 124 125 126 127 128 129 130 131
/*
 * For the post-rewrite hook, we make a list of rewritten commits and
 * their new sha1s.  The rewritten-pending list keeps the sha1s of
 * commits that have been processed, but not committed yet,
 * e.g. because they are waiting for a 'squash' command.
 */
static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
static GIT_PATH_FUNC(rebase_path_rewritten_pending,
	"rebase-merge/rewritten-pending")
132

133 134 135 136 137 138
/*
 * The path of the file containig the OID of the "squash onto" commit, i.e.
 * the dummy commit used for `reset [new root]`.
 */
static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")

139 140 141 142 143 144
/*
 * The path of the file listing refs that need to be deleted after the rebase
 * finishes. This is used by the `label` command to record the need for cleanup.
 */
static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")

145 146
/*
 * The following files are written by git-rebase just after parsing the
147
 * command-line.
148 149
 */
static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
150 151
static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
152
static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
153
static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
154 155
static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
156
static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
157 158
static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
159
static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
160
static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
static int git_sequencer_config(const char *k, const char *v, void *cb)
{
	struct replay_opts *opts = cb;
	int status;

	if (!strcmp(k, "commit.cleanup")) {
		const char *s;

		status = git_config_string(&s, k, v);
		if (status)
			return status;

		if (!strcmp(s, "verbatim"))
			opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
		else if (!strcmp(s, "whitespace"))
			opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
		else if (!strcmp(s, "strip"))
			opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
		else if (!strcmp(s, "scissors"))
			opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
		else
			warning(_("invalid commit message cleanup mode '%s'"),
				  s);

186
		free((char *)s);
187 188 189 190
		return status;
	}

	if (!strcmp(k, "commit.gpgsign")) {
191
		opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		return 0;
	}

	status = git_gpg_config(k, v, NULL);
	if (status)
		return status;

	return git_diff_basic_config(k, v, NULL);
}

void sequencer_init_config(struct replay_opts *opts)
{
	opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
	git_config(git_sequencer_config, opts);
}

208 209
static inline int is_rebase_i(const struct replay_opts *opts)
{
210
	return opts->action == REPLAY_INTERACTIVE_REBASE;
211 212
}

213 214
static const char *get_dir(const struct replay_opts *opts)
{
215 216
	if (is_rebase_i(opts))
		return rebase_path();
217 218 219
	return git_path_seq_dir();
}

220 221
static const char *get_todo_path(const struct replay_opts *opts)
{
222 223
	if (is_rebase_i(opts))
		return rebase_path_todo();
224 225 226
	return git_path_todo_file();
}

227 228 229 230 231 232 233
/*
 * Returns 0 for non-conforming footer
 * Returns 1 for conforming footer
 * Returns 2 when sob exists within conforming footer
 * Returns 3 when sob exists within conforming footer as last entry
 */
static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
234
	size_t ignore_footer)
235
{
236
	struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
237
	struct trailer_info info;
238
	size_t i;
239
	int found_sob = 0, found_sob_last = 0;
240

241 242
	opts.no_divider = 1;

243
	trailer_info_get(&info, sb->buf, &opts);
244

245
	if (info.trailer_start == info.trailer_end)
246 247
		return 0;

248 249 250 251 252 253
	for (i = 0; i < info.trailer_nr; i++)
		if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
			found_sob = 1;
			if (i == info.trailer_nr - 1)
				found_sob_last = 1;
		}
254

255
	trailer_info_release(&info);
256

257
	if (found_sob_last)
258 259 260
		return 3;
	if (found_sob)
		return 2;
261 262
	return 1;
}
263

264 265 266 267 268 269 270 271 272 273
static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
{
	static struct strbuf buf = STRBUF_INIT;

	strbuf_reset(&buf);
	if (opts->gpg_sign)
		sq_quotef(&buf, "-S%s", opts->gpg_sign);
	return buf.buf;
}

274
int sequencer_remove_state(struct replay_opts *opts)
275
{
276
	struct strbuf buf = STRBUF_INIT;
277 278
	int i;

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
	if (is_rebase_i(opts) &&
	    strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
		char *p = buf.buf;
		while (*p) {
			char *eol = strchr(p, '\n');
			if (eol)
				*eol = '\0';
			if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
				warning(_("could not delete '%s'"), p);
			if (!eol)
				break;
			p = eol + 1;
		}
	}

294 295 296 297 298
	free(opts->gpg_sign);
	free(opts->strategy);
	for (i = 0; i < opts->xopts_nr; i++)
		free(opts->xopts[i]);
	free(opts->xopts);
299
	strbuf_release(&opts->current_fixups);
300

301 302 303 304
	strbuf_reset(&buf);
	strbuf_addstr(&buf, get_dir(opts));
	remove_dir_recursively(&buf, 0);
	strbuf_release(&buf);
305 306

	return 0;
307
}
308 309 310

static const char *action_name(const struct replay_opts *opts)
{
311 312 313 314 315 316 317 318
	switch (opts->action) {
	case REPLAY_REVERT:
		return N_("revert");
	case REPLAY_PICK:
		return N_("cherry-pick");
	case REPLAY_INTERACTIVE_REBASE:
		return N_("rebase -i");
	}
319
	die(_("unknown action: %d"), opts->action);
320 321 322 323
}

struct commit_message {
	char *parent_label;
324 325
	char *label;
	char *subject;
326 327 328
	const char *message;
};

329 330
static const char *short_commit_name(struct commit *commit)
{
331
	return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
332 333
}

334 335 336
static int get_message(struct commit *commit, struct commit_message *out)
{
	const char *abbrev, *subject;
337
	int subject_len;
338

339
	out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
340
	abbrev = short_commit_name(commit);
341 342 343

	subject_len = find_commit_subject(out->message, &subject);

344 345 346 347
	out->subject = xmemdupz(subject, subject_len);
	out->label = xstrfmt("%s... %s", abbrev, out->subject);
	out->parent_label = xstrfmt("parent of %s", out->label);

348 349 350
	return 0;
}

351
static void free_message(struct commit *commit, struct commit_message *msg)
352 353
{
	free(msg->parent_label);
354 355
	free(msg->label);
	free(msg->subject);
356
	unuse_commit_buffer(commit, msg->message);
357 358
}

359 360
static void print_advice(struct repository *r, int show_hint,
			 struct replay_opts *opts)
361 362 363 364 365 366
{
	char *msg = getenv("GIT_CHERRY_PICK_HELP");

	if (msg) {
		fprintf(stderr, "%s\n", msg);
		/*
367
		 * A conflict has occurred but the porcelain
368 369 370
		 * (typically rebase --interactive) wants to take care
		 * of the commit itself so remove CHERRY_PICK_HEAD
		 */
371
		unlink(git_path_cherry_pick_head(r));
372 373 374
		return;
	}

375 376 377 378 379 380 381 382 383
	if (show_hint) {
		if (opts->no_commit)
			advise(_("after resolving the conflicts, mark the corrected paths\n"
				 "with 'git add <paths>' or 'git rm <paths>'"));
		else
			advise(_("after resolving the conflicts, mark the corrected paths\n"
				 "with 'git add <paths>' or 'git rm <paths>'\n"
				 "and commit the result with 'git commit'"));
	}
384 385
}

386 387
static int write_message(const void *buf, size_t len, const char *filename,
			 int append_eol)
388
{
389
	struct lock_file msg_file = LOCK_INIT;
390

391 392
	int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
	if (msg_fd < 0)
393
		return error_errno(_("could not lock '%s'"), filename);
394
	if (write_in_full(msg_fd, buf, len) < 0) {
395
		error_errno(_("could not write to '%s'"), filename);
396
		rollback_lock_file(&msg_file);
397
		return -1;
398
	}
399
	if (append_eol && write(msg_fd, "\n", 1) < 0) {
400
		error_errno(_("could not write eol to '%s'"), filename);
401
		rollback_lock_file(&msg_file);
402
		return -1;
403
	}
404 405
	if (commit_lock_file(&msg_file) < 0)
		return error(_("failed to finalize '%s'"), filename);
406 407

	return 0;
408 409
}

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
/*
 * Reads a file that was presumably written by a shell script, i.e. with an
 * end-of-line marker that needs to be stripped.
 *
 * Note that only the last end-of-line marker is stripped, consistent with the
 * behavior of "$(cat path)" in a shell script.
 *
 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
 */
static int read_oneliner(struct strbuf *buf,
	const char *path, int skip_if_empty)
{
	int orig_len = buf->len;

	if (!file_exists(path))
		return 0;

	if (strbuf_read_file(buf, path, 0) < 0) {
		warning_errno(_("could not read '%s'"), path);
		return 0;
	}

	if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
		if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
			--buf->len;
		buf->buf[buf->len] = '\0';
	}

	if (skip_if_empty && buf->len == orig_len)
		return 0;

	return 1;
}

444
static struct tree *empty_tree(struct repository *r)
445
{
446
	return lookup_tree(r, the_hash_algo->empty_tree);
447 448
}

449
static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
450
{
451
	if (repo_read_index_unmerged(repo))
452
		return error_resolve_conflict(_(action_name(opts)));
453

454
	error(_("your local changes would be overwritten by %s."),
455
		_(action_name(opts)));
456 457

	if (advice_commit_before_merge)
458
		advise(_("commit your changes or stash them to proceed."));
459 460 461
	return -1;
}

462 463 464 465 466 467 468 469 470 471 472 473 474 475
static void update_abort_safety_file(void)
{
	struct object_id head;

	/* Do nothing on a single-pick */
	if (!file_exists(git_path_seq_dir()))
		return;

	if (!get_oid("HEAD", &head))
		write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
	else
		write_file(git_path_abort_safety_file(), "%s", "");
}

476 477 478 479 480
static int fast_forward_to(struct repository *r,
			   const struct object_id *to,
			   const struct object_id *from,
			   int unborn,
			   struct replay_opts *opts)
481
{
482
	struct ref_transaction *transaction;
483
	struct strbuf sb = STRBUF_INIT;
484
	struct strbuf err = STRBUF_INIT;
485

486
	repo_read_index(r);
487
	if (checkout_fast_forward(r, from, to, 1))
488
		return -1; /* the callee should have complained already */
489

490
	strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
491 492 493 494

	transaction = ref_transaction_begin(&err);
	if (!transaction ||
	    ref_transaction_update(transaction, "HEAD",
495 496
				   to, unborn && !is_rebase_i(opts) ?
				   &null_oid : from,
497
				   0, sb.buf, &err) ||
498
	    ref_transaction_commit(transaction, &err)) {
499 500 501 502 503 504
		ref_transaction_free(transaction);
		error("%s", err.buf);
		strbuf_release(&sb);
		strbuf_release(&err);
		return -1;
	}
505

506
	strbuf_release(&sb);
507 508
	strbuf_release(&err);
	ref_transaction_free(transaction);
509
	update_abort_safety_file();
510
	return 0;
511 512
}

513 514
void append_conflicts_hint(struct index_state *istate,
			   struct strbuf *msgbuf)
515 516 517
{
	int i;

518 519
	strbuf_addch(msgbuf, '\n');
	strbuf_commented_addf(msgbuf, "Conflicts:\n");
520 521
	for (i = 0; i < istate->cache_nr;) {
		const struct cache_entry *ce = istate->cache[i++];
522
		if (ce_stage(ce)) {
523
			strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
524 525
			while (i < istate->cache_nr &&
			       !strcmp(ce->name, istate->cache[i]->name))
526 527 528 529 530
				i++;
		}
	}
}

531 532
static int do_recursive_merge(struct repository *r,
			      struct commit *base, struct commit *next,
533
			      const char *base_label, const char *next_label,
534
			      struct object_id *head, struct strbuf *msgbuf,
535 536 537 538
			      struct replay_opts *opts)
{
	struct merge_options o;
	struct tree *result, *next_tree, *base_tree, *head_tree;
539
	int clean;
540
	char **xopt;
541
	struct lock_file index_lock = LOCK_INIT;
542

543
	if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
544
		return -1;
545

546
	repo_read_index(r);
547

548
	init_merge_options(&o, r);
549 550 551
	o.ancestor = base ? base_label : "(empty tree)";
	o.branch1 = "HEAD";
	o.branch2 = next ? next_label : "(empty tree)";
552 553
	if (is_rebase_i(opts))
		o.buffer_output = 2;
554
	o.show_rename_progress = 1;
555 556

	head_tree = parse_tree_indirect(head);
557 558
	next_tree = next ? get_commit_tree(next) : empty_tree(r);
	base_tree = base ? get_commit_tree(base) : empty_tree(r);
559 560 561 562 563 564 565

	for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
		parse_merge_opt(&o, *xopt);

	clean = merge_trees(&o,
			    head_tree,
			    next_tree, base_tree, &result);
566 567
	if (is_rebase_i(opts) && clean <= 0)
		fputs(o.obuf.buf, stdout);
568
	strbuf_release(&o.obuf);
569
	diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
570 571
	if (clean < 0) {
		rollback_lock_file(&index_lock);
572
		return clean;
573
	}
574

575
	if (write_locked_index(r->index, &index_lock,
576
			       COMMIT_LOCK | SKIP_IF_UNCHANGED))
577 578
		/*
		 * TRANSLATORS: %s will be "revert", "cherry-pick" or
579 580
		 * "rebase -i".
		 */
581
		return error(_("%s: Unable to write new index file"),
582
			_(action_name(opts)));
583

584
	if (!clean)
585
		append_conflicts_hint(r->index, msgbuf);
586 587 588 589

	return !clean;
}

590
static struct object_id *get_cache_tree_oid(struct index_state *istate)
591
{
592 593
	if (!istate->cache_tree)
		istate->cache_tree = cache_tree();
594

595 596
	if (!cache_tree_fully_valid(istate->cache_tree))
		if (cache_tree_update(istate, 0)) {
597 598 599 600
			error(_("unable to update cache tree"));
			return NULL;
		}

601
	return &istate->cache_tree->oid;
602 603
}

604
static int is_index_unchanged(struct repository *r)
605
{
606
	struct object_id head_oid, *cache_tree_oid;
607
	struct commit *head_commit;
608
	struct index_state *istate = r->index;
609

610
	if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
611
		return error(_("could not resolve HEAD commit"));
612

613
	head_commit = lookup_commit(r, &head_oid);
614 615 616 617 618 619 620 621 622 623 624

	/*
	 * If head_commit is NULL, check_commit, called from
	 * lookup_commit, would have indicated that head_commit is not
	 * a commit object already.  parse_commit() will return failure
	 * without further complaints in such a case.  Otherwise, if
	 * the commit is invalid, parse_commit() will complain.  So
	 * there is nothing for us to say here.  Just return failure.
	 */
	if (parse_commit(head_commit))
		return -1;
625

626
	if (!(cache_tree_oid = get_cache_tree_oid(istate)))
627
		return -1;
628

629
	return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
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 int write_author_script(const char *message)
{
	struct strbuf buf = STRBUF_INIT;
	const char *eol;
	int res;

	for (;;)
		if (!*message || starts_with(message, "\n")) {
missing_author:
			/* Missing 'author' line? */
			unlink(rebase_path_author_script());
			return 0;
		} else if (skip_prefix(message, "author ", &message))
			break;
		else if ((eol = strchr(message, '\n')))
			message = eol + 1;
		else
			goto missing_author;

	strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
	while (*message && *message != '\n' && *message != '\r')
		if (skip_prefix(message, " <", &message))
			break;
		else if (*message != '\'')
			strbuf_addch(&buf, *(message++));
		else
658
			strbuf_addf(&buf, "'\\%c'", *(message++));
659 660 661 662 663 664 665
	strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
	while (*message && *message != '\n' && *message != '\r')
		if (skip_prefix(message, "> ", &message))
			break;
		else if (*message != '\'')
			strbuf_addch(&buf, *(message++));
		else
666
			strbuf_addf(&buf, "'\\%c'", *(message++));
667 668 669 670 671
	strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
	while (*message && *message != '\n' && *message != '\r')
		if (*message != '\'')
			strbuf_addch(&buf, *(message++));
		else
672
			strbuf_addf(&buf, "'\\%c'", *(message++));
673
	strbuf_addch(&buf, '\'');
674 675 676 677 678
	res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
	strbuf_release(&buf);
	return res;
}

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
/**
 * Take a series of KEY='VALUE' lines where VALUE part is
 * sq-quoted, and append <KEY, VALUE> at the end of the string list
 */
static int parse_key_value_squoted(char *buf, struct string_list *list)
{
	while (*buf) {
		struct string_list_item *item;
		char *np;
		char *cp = strchr(buf, '=');
		if (!cp) {
			np = strchrnul(buf, '\n');
			return error(_("no key present in '%.*s'"),
				     (int) (np - buf), buf);
		}
		np = strchrnul(cp, '\n');
		*cp++ = '\0';
		item = string_list_append(list, buf);

		buf = np + (*np == '\n');
		*np = '\0';
		cp = sq_dequote(cp);
		if (!cp)
			return error(_("unable to dequote value of '%s'"),
				     item->string);
		item->util = xstrdup(cp);
	}
	return 0;
}
708

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
/**
 * Reads and parses the state directory's "author-script" file, and sets name,
 * email and date accordingly.
 * Returns 0 on success, -1 if the file could not be parsed.
 *
 * The author script is of the format:
 *
 *	GIT_AUTHOR_NAME='$author_name'
 *	GIT_AUTHOR_EMAIL='$author_email'
 *	GIT_AUTHOR_DATE='$author_date'
 *
 * where $author_name, $author_email and $author_date are quoted. We are strict
 * with our parsing, as the file was meant to be eval'd in the old
 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
 * from what this function expects, it is better to bail out than to do
 * something that the user does not expect.
725
 */
726 727
int read_author_script(const char *path, char **name, char **email, char **date,
		       int allow_missing)
728
{
729 730 731 732
	struct strbuf buf = STRBUF_INIT;
	struct string_list kv = STRING_LIST_INIT_DUP;
	int retval = -1; /* assume failure */
	int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
733

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
	if (strbuf_read_file(&buf, path, 256) <= 0) {
		strbuf_release(&buf);
		if (errno == ENOENT && allow_missing)
			return 0;
		else
			return error_errno(_("could not open '%s' for reading"),
					   path);
	}

	if (parse_key_value_squoted(buf.buf, &kv))
		goto finish;

	for (i = 0; i < kv.nr; i++) {
		if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
			if (name_i != -2)
				name_i = error(_("'GIT_AUTHOR_NAME' already given"));
			else
				name_i = i;
		} else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
			if (email_i != -2)
				email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
			else
				email_i = i;
		} else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
			if (date_i != -2)
				date_i = error(_("'GIT_AUTHOR_DATE' already given"));
			else
				date_i = i;
		} else {
			err = error(_("unknown variable '%s'"),
				    kv.items[i].string);
		}
	}
	if (name_i == -2)
		error(_("missing 'GIT_AUTHOR_NAME'"));
	if (email_i == -2)
		error(_("missing 'GIT_AUTHOR_EMAIL'"));
	if (date_i == -2)
		error(_("missing 'GIT_AUTHOR_DATE'"));
	if (date_i < 0 || email_i < 0 || date_i < 0 || err)
		goto finish;
	*name = kv.items[name_i].util;
	*email = kv.items[email_i].util;
	*date = kv.items[date_i].util;
	retval = 0;
finish:
	string_list_clear(&kv, !!retval);
	strbuf_release(&buf);
	return retval;
783 784
}

785
/*
786 787 788
 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
 * file with shell quoting into struct argv_array. Returns -1 on
 * error, 0 otherwise.
789
 */
790
static int read_env_script(struct argv_array *env)
791
{
792
	char *name, *email, *date;
793

794 795
	if (read_author_script(rebase_path_author_script(),
			       &name, &email, &date, 0))
796
		return -1;
797

798 799 800 801 802 803
	argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
	argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
	argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
	free(name);
	free(email);
	free(date);
804

805
	return 0;
806 807
}

808 809 810 811 812 813 814 815 816 817 818 819
static char *get_author(const char *message)
{
	size_t len;
	const char *a;

	a = find_commit_header(message, "author", &len);
	if (a)
		return xmemdupz(a, len);

	return NULL;
}

820 821 822
/* Read author-script and return an ident line (author <email> timestamp) */
static const char *read_author_ident(struct strbuf *buf)
{
823
	struct strbuf out = STRBUF_INIT;
824
	char *name, *email, *date;
825

826 827
	if (read_author_script(rebase_path_author_script(),
			       &name, &email, &date, 0))
828 829
		return NULL;

830
	/* validate date since fmt_ident() will die() on bad value */
831
	if (parse_date(date, &out)){
832
		warning(_("invalid date format '%s' in '%s'"),
833
			date, rebase_path_author_script());
834 835 836 837 838
		strbuf_release(&out);
		return NULL;
	}

	strbuf_reset(&out);
839
	strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
840 841
	strbuf_swap(buf, &out);
	strbuf_release(&out);
842 843 844
	free(name);
	free(email);
	free(date);
845 846 847
	return buf->buf;
}

848 849 850 851 852 853 854 855 856 857 858 859 860 861
static const char staged_changes_advice[] =
N_("you have staged changes in your working tree\n"
"If these changes are meant to be squashed into the previous commit, run:\n"
"\n"
"  git commit --amend %s\n"
"\n"
"If they are meant to go into a new commit, run:\n"
"\n"
"  git commit %s\n"
"\n"
"In both cases, once you're done, continue with:\n"
"\n"
"  git rebase --continue\n");

862 863 864 865
#define ALLOW_EMPTY (1<<0)
#define EDIT_MSG    (1<<1)
#define AMEND_MSG   (1<<2)
#define CLEANUP_MSG (1<<3)
866
#define VERIFY_MSG  (1<<4)
867
#define CREATE_ROOT_COMMIT (1<<5)
868

869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
static int run_command_silent_on_success(struct child_process *cmd)
{
	struct strbuf buf = STRBUF_INIT;
	int rc;

	cmd->stdout_to_stderr = 1;
	rc = pipe_command(cmd,
			  NULL, 0,
			  NULL, 0,
			  &buf, 0);

	if (rc)
		fputs(buf.buf, stderr);
	strbuf_release(&buf);
	return rc;
}

886 887 888 889
/*
 * If we are cherry-pick, and if the merge did not result in
 * hand-editing, we will hit this commit and inherit the original
 * author date and name.
890
 *
891 892
 * If we are revert, or if our cherry-pick results in a hand merge,
 * we had better say that the current user is responsible for that.
893 894 895 896
 *
 * An exception is when run_git_commit() is called during an
 * interactive rebase: in that case, we will want to retain the
 * author metadata.
897
 */
898 899 900
static int run_git_commit(struct repository *r,
			  const char *defmsg,
			  struct replay_opts *opts,
901
			  unsigned int flags)
902
{
903
	struct child_process cmd = CHILD_PROCESS_INIT;
904
	const char *value;
905

906
	if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
907
		struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
908
		const char *author = NULL;
909 910 911
		struct object_id root_commit, *cache_tree_oid;
		int res = 0;

912 913 914 915 916 917 918 919
		if (is_rebase_i(opts)) {
			author = read_author_ident(&script);
			if (!author) {
				strbuf_release(&script);
				return -1;
			}
		}

920 921 922
		if (!defmsg)
			BUG("root commit without message");

923
		if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
			res = -1;

		if (!res)
			res = strbuf_read_file(&msg, defmsg, 0);

		if (res <= 0)
			res = error_errno(_("could not read '%s'"), defmsg);
		else
			res = commit_tree(msg.buf, msg.len, cache_tree_oid,
					  NULL, &root_commit, author,
					  opts->gpg_sign);

		strbuf_release(&msg);
		strbuf_release(&script);
		if (!res) {
			update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
				   REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
			res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
					 UPDATE_REFS_MSG_ON_ERR);
		}
		return res < 0 ? error(_("writing root commit")) : 0;
	}

947 948
	cmd.git_cmd = 1;

949 950
	if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
		const char *gpg_opt = gpg_sign_opt_quoted(opts);
951

952 953
		return error(_(staged_changes_advice),
			     gpg_opt, gpg_opt);
954 955
	}

956
	argv_array_push(&cmd.args, "commit");
957

958 959
	if (!(flags & VERIFY_MSG))
		argv_array_push(&cmd.args, "-n");
960
	if ((flags & AMEND_MSG))
961
		argv_array_push(&cmd.args, "--amend");
962
	if (opts->gpg_sign)
963
		argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
964
	if (defmsg)
965
		argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
966 967
	else if (!(flags & EDIT_MSG))
		argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
968
	if ((flags & CLEANUP_MSG))
969
		argv_array_push(&cmd.args, "--cleanup=strip");
970
	if ((flags & EDIT_MSG))
971
		argv_array_push(&cmd.args, "-e");
972
	else if (!(flags & CLEANUP_MSG) &&
973
		 !opts->signoff && !opts->record_origin &&
974
		 git_config_get_value("commit.cleanup", &value))
975
		argv_array_push(&cmd.args, "--cleanup=verbatim");
976

977
	if ((flags & ALLOW_EMPTY))
978
		argv_array_push(&cmd.args, "--allow-empty");
979

980
	if (!(flags & EDIT_MSG))
981
		argv_array_push(&cmd.args, "--allow-empty-message");
982

983 984 985 986
	if (is_rebase_i(opts) && !(flags & EDIT_MSG))
		return run_command_silent_on_success(&cmd);
	else
		return run_command(&cmd);
987 988
}

989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
static int rest_is_empty(const struct strbuf *sb, int start)
{
	int i, eol;
	const char *nl;

	/* Check if the rest is just whitespace and Signed-off-by's. */
	for (i = start; i < sb->len; i++) {
		nl = memchr(sb->buf + i, '\n', sb->len - i);
		if (nl)
			eol = nl - sb->buf;
		else
			eol = sb->len;

		if (strlen(sign_off_header) <= eol - i &&
		    starts_with(sb->buf + i, sign_off_header)) {
			i = eol;
			continue;
		}
		while (i < eol)
			if (!isspace(sb->buf[i++]))
				return 0;
	}

	return 1;
}

/*
 * Find out if the message in the strbuf contains only whitespace and
 * Signed-off-by lines.
 */
int message_is_empty(const struct strbuf *sb,
		     enum commit_msg_cleanup_mode cleanup_mode)
{
	if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
		return 0;
	return rest_is_empty(sb, 0);
}

/*
 * See if the user edited the message in the editor or left what
 * was in the template intact
 */
int template_untouched(const struct strbuf *sb, const char *template_file,
		       enum commit_msg_cleanup_mode cleanup_mode)
{
	struct strbuf tmpl = STRBUF_INIT;
	const char *start;

	if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
		return 0;

	if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
		return 0;

	strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
	if (!skip_prefix(sb->buf, tmpl.buf, &start))
		start = sb->buf;
	strbuf_release(&tmpl);
	return rest_is_empty(sb, start - sb->buf);
}

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
int update_head_with_reflog(const struct commit *old_head,
			    const struct object_id *new_head,
			    const char *action, const struct strbuf *msg,
			    struct strbuf *err)
{
	struct ref_transaction *transaction;
	struct strbuf sb = STRBUF_INIT;
	const char *nl;
	int ret = 0;

	if (action) {
		strbuf_addstr(&sb, action);
		strbuf_addstr(&sb, ": ");
	}

	nl = strchr(msg->buf, '\n');
	if (nl) {
		strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
	} else {
		strbuf_addbuf(&sb, msg);
		strbuf_addch(&sb, '\n');
	}

	transaction = ref_transaction_begin(err);
	if (!transaction ||
	    ref_transaction_update(transaction, "HEAD", new_head,
				   old_head ? &old_head->object.oid : &null_oid,
				   0, sb.buf, err) ||
	    ref_transaction_commit(transaction, err)) {
		ret = -1;
	}
	ref_transaction_free(transaction);
	strbuf_release(&sb);

	return ret;
}

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
static int run_rewrite_hook(const struct object_id *oldoid,
			    const struct object_id *newoid)
{
	struct child_process proc = CHILD_PROCESS_INIT;
	const char *argv[3];
	int code;
	struct strbuf sb = STRBUF_INIT;

	argv[0] = find_hook("post-rewrite");
	if (!argv[0])
		return 0;

	argv[1] = "amend";
	argv[2] = NULL;

	proc.argv = argv;
	proc.in = -1;
	proc.stdout_to_stderr = 1;
1105
	proc.trace2_hook_name = "post-rewrite";
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

	code = start_command(&proc);
	if (code)
		return code;
	strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
	sigchain_push(SIGPIPE, SIG_IGN);
	write_in_full(proc.in, sb.buf, sb.len);
	close(proc.in);
	strbuf_release(&sb);
	sigchain_pop(SIGPIPE);
	return finish_command(&proc);
}

1119 1120
void commit_post_rewrite(struct repository *r,
			 const struct commit *old_head,
1121 1122 1123 1124 1125 1126 1127 1128
			 const struct object_id *new_head)
{
	struct notes_rewrite_cfg *cfg;

	cfg = init_copy_notes_for_rewrite("amend");
	if (cfg) {
		/* we are amending, so old_head is not NULL */
		copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1129
		finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1130 1131 1132 1133
	}
	run_rewrite_hook(&old_head->object.oid, new_head);
}

1134 1135 1136
static int run_prepare_commit_msg_hook(struct repository *r,
				       struct strbuf *msg,
				       const char *commit)
1137 1138 1139 1140 1141 1142 1143 1144 1145
{
	struct argv_array hook_env = ARGV_ARRAY_INIT;
	int ret;
	const char *name;

	name = git_path_commit_editmsg();
	if (write_message(msg->buf, msg->len, name, 0))
		return -1;

1146
	argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
	argv_array_push(&hook_env, "GIT_EDITOR=:");
	if (commit)
		ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
				  "commit", commit, NULL);
	else
		ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
				  "message", NULL);
	if (ret)
		ret = error(_("'prepare-commit-msg' hook failed"));
	argv_array_clear(&hook_env);

	return ret;
}

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
static const char implicit_ident_advice_noconfig[] =
N_("Your name and email address were configured automatically based\n"
"on your username and hostname. Please check that they are accurate.\n"
"You can suppress this message by setting them explicitly. Run the\n"
"following command and follow the instructions in your editor to edit\n"
"your configuration file:\n"
"\n"
"    git config --global --edit\n"
"\n"
"After doing this, you may fix the identity used for this commit with:\n"
"\n"
"    git commit --amend --reset-author\n");

static const char implicit_ident_advice_config[] =
N_("Your name and email address were configured automatically based\n"
"on your username and hostname. Please check that they are accurate.\n"
"You can suppress this message by setting them explicitly:\n"
"\n"
"    git config --global user.name \"Your Name\"\n"
"    git config --global user.email you@example.com\n"
"\n"
"After doing this, you may fix the identity used for this commit with:\n"
"\n"
"    git commit --amend --reset-author\n");

static const char *implicit_ident_advice(void)
{
	char *user_config = expand_user_path("~/.gitconfig", 0);
	char *xdg_config = xdg_config_home("config");
	int config_exists = file_exists(user_config) || file_exists(xdg_config);

	free(user_config);
	free(xdg_config);

	if (config_exists)
		return _(implicit_ident_advice_config);
	else
		return _(implicit_ident_advice_noconfig);

}

1202 1203 1204
void print_commit_summary(struct repository *r,
			  const char *prefix,
			  const struct object_id *oid,
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
			  unsigned int flags)
{
	struct rev_info rev;
	struct commit *commit;
	struct strbuf format = STRBUF_INIT;
	const char *head;
	struct pretty_print_context pctx = {0};
	struct strbuf author_ident = STRBUF_INIT;
	struct strbuf committer_ident = STRBUF_INIT;

1215
	commit = lookup_commit(r, oid);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
	if (!commit)
		die(_("couldn't look up newly created commit"));
	if (parse_commit(commit))
		die(_("could not parse newly created commit"));

	strbuf_addstr(&format, "format:%h] %s");

	format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
	format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
	if (strbuf_cmp(&author_ident, &committer_ident)) {
		strbuf_addstr(&format, "\n Author: ");
		strbuf_addbuf_percentquote(&format, &author_ident);
	}
	if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
		struct strbuf date = STRBUF_INIT;

		format_commit_message(commit, "%ad", &date, &pctx);
		strbuf_addstr(&format, "\n Date: ");
		strbuf_addbuf_percentquote(&format, &date);
		strbuf_release(&date);
	}
	if (!committer_ident_sufficiently_given()) {
		strbuf_addstr(&format, "\n Committer: ");
		strbuf_addbuf_percentquote(&format, &committer_ident);
		if (advice_implicit_identity) {
			strbuf_addch(&format, '\n');
			strbuf_addstr(&format, implicit_ident_advice());
		}
	}
	strbuf_release(&author_ident);
	strbuf_release(&committer_ident);

1248
	repo_init_revisions(r, &rev, prefix);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
	setup_revisions(0, NULL, &rev, NULL);

	rev.diff = 1;
	rev.diffopt.output_format =
		DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;

	rev.verbose_header = 1;
	rev.show_root_diff = 1;
	get_commit_format(format.buf, &rev);
	rev.always_show_header = 0;
1259
	rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
	rev.diffopt.break_opt = 0;
	diff_setup_done(&rev.diffopt);

	head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
	if (!head)
		die_errno(_("unable to resolve HEAD after creating commit"));
	if (!strcmp(head, "HEAD"))
		head = _("detached HEAD");
	else
		skip_prefix(head, "refs/heads/", &head);
	printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
						_(" (root-commit)") : "");

	if (!log_tree_commit(&rev, commit)) {
		rev.always_show_header = 1;
		rev.use_terminator = 1;
		log_tree_commit(&rev, commit);
	}

	strbuf_release(&format);
}

1282
static int parse_head(struct repository *r, struct commit **head)
1283 1284 1285 1286 1287 1288 1289
{
	struct commit *current_head;
	struct object_id oid;

	if (get_oid("HEAD", &oid)) {
		current_head = NULL;
	} else {
1290
		current_head = lookup_commit_reference(r, &oid);
1291 1292
		if (!current_head)
			return error(_("could not parse HEAD"));
1293
		if (!oideq(&oid, &current_head->object.oid)) {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
			warning(_("HEAD %s is not a commit!"),
				oid_to_hex(&oid));
		}
		if (parse_commit(current_head))
			return error(_("could not parse HEAD commit"));
	}
	*head = current_head;

	return 0;
}

/*
 * Try to commit without forking 'git commit'. In some cases we need
 * to run 'git commit' to display an error message
 *
 * Returns:
 *  -1 - error unable to commit
 *   0 - success
 *   1 - run 'git commit'
 */
1314 1315
static int try_to_commit(struct repository *r,
			 struct strbuf *msg, const char *author,
1316 1317 1318 1319 1320 1321 1322 1323
			 struct replay_opts *opts, unsigned int flags,
			 struct object_id *oid)
{
	struct object_id tree;
	struct commit *current_head;
	struct commit_list *parents = NULL;
	struct commit_extra_header *extra = NULL;
	struct strbuf err = STRBUF_INIT;
1324
	struct strbuf commit_msg = STRBUF_INIT;
1325
	char *amend_author = NULL;
1326
	const char *hook_commit = NULL;
1327 1328 1329
	enum commit_msg_cleanup_mode cleanup;
	int res = 0;

1330
	if (parse_head(r, &current_head))
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
		return -1;

	if (flags & AMEND_MSG) {
		const char *exclude_gpgsig[] = { "gpgsig", NULL };
		const char *out_enc = get_commit_output_encoding();
		const char *message = logmsg_reencode(current_head, NULL,
						      out_enc);

		if (!msg) {
			const char *orig_message = NULL;

			find_commit_subject(message, &orig_message);
1343
			msg = &commit_msg;
1344
			strbuf_addstr(msg, orig_message);
1345
			hook_commit = "HEAD";
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
		}
		author = amend_author = get_author(message);
		unuse_commit_buffer(current_head, message);
		if (!author) {
			res = error(_("unable to parse commit author"));
			goto out;
		}
		parents = copy_commit_list(current_head->parents);
		extra = read_commit_extra_headers(current_head, exclude_gpgsig);
	} else if (current_head) {
		commit_list_insert(current_head, &parents);
	}

1359
	if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1360 1361 1362 1363
		res = error(_("git write-tree failed to write a tree"));
		goto out;
	}

1364 1365 1366
	if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
					    get_commit_tree_oid(current_head) :
					    the_hash_algo->empty_tree, &tree)) {
1367 1368 1369 1370
		res = 1; /* run 'git commit' to display error message */
		goto out;
	}

1371
	if (find_hook("prepare-commit-msg")) {
1372
		res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
		if (res)
			goto out;
		if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
				     2048) < 0) {
			res = error_errno(_("unable to read commit message "
					      "from '%s'"),
					    git_path_commit_editmsg());
			goto out;
		}
		msg = &commit_msg;
	}

	cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
					  opts->default_msg_cleanup;

	if (cleanup != COMMIT_MSG_CLEANUP_NONE)
		strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1390
	if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1391 1392 1393 1394
		res = 1; /* run 'git commit' to display error message */
		goto out;
	}

1395 1396
	reset_ident_date();

1397 1398
	if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
				 oid, author, opts->gpg_sign, extra)) {
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
		res = error(_("failed to write commit object"));
		goto out;
	}

	if (update_head_with_reflog(current_head, oid,
				    getenv("GIT_REFLOG_ACTION"), msg, &err)) {
		res = error("%s", err.buf);
		goto out;
	}

	if (flags & AMEND_MSG)
1410
		commit_post_rewrite(r, current_head, oid);
1411 1412 1413 1414

out:
	free_commit_extra_headers(extra);
	strbuf_release(&err);
1415
	strbuf_release(&commit_msg);
1416 1417 1418 1419 1420
	free(amend_author);

	return res;
}

1421 1422
static int do_commit(struct repository *r,
		     const char *msg_file, const char *author,
1423 1424 1425 1426
		     struct replay_opts *opts, unsigned int flags)
{
	int res = 1;

1427 1428
	if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
	    !(flags & CREATE_ROOT_COMMIT)) {
1429 1430 1431 1432 1433 1434 1435 1436
		struct object_id oid;
		struct strbuf sb = STRBUF_INIT;

		if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
			return error_errno(_("unable to read commit message "
					     "from '%s'"),
					   msg_file);

1437 1438
		res = try_to_commit(r, msg_file ? &sb : NULL,
				    author, opts, flags, &oid);
1439 1440
		strbuf_release(&sb);
		if (!res) {
1441 1442
			unlink(git_path_cherry_pick_head(r));
			unlink(git_path_merge_msg(r));
1443
			if (!is_rebase_i(opts))
1444
				print_commit_summary(r, NULL, &oid,
1445 1446 1447 1448 1449
						SUMMARY_SHOW_AUTHOR_DATE);
			return res;
		}
	}
	if (res == 1)
1450
		return run_git_commit(r, msg_file, opts, flags);
1451 1452 1453 1454

	return res;
}

1455 1456
static int is_original_commit_empty(struct commit *commit)
{
1457
	const struct object_id *ptree_oid;
1458 1459

	if (parse_commit(commit))
1460
		return error(_("could not parse commit %s"),
1461
			     oid_to_hex(&commit->object.oid));
1462 1463 1464
	if (commit->parents) {
		struct commit *parent = commit->parents->item;
		if (parse_commit(parent))
1465
			return error(_("could not parse parent commit %s"),
1466
				oid_to_hex(&parent->object.oid));
1467
		ptree_oid = get_commit_tree_oid(parent);
1468
	} else {
1469
		ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1470 1471
	}

1472
	return oideq(ptree_oid, get_commit_tree_oid(commit));
1473 1474
}

1475 1476 1477
/*
 * Do we run "git commit" with "--allow-empty"?
 */
1478 1479 1480
static int allow_empty(struct repository *r,
		       struct replay_opts *opts,
		       struct commit *commit)