am.c 59.3 KB
Newer Older
1 2 3 4 5 6
/*
 * Builtin "git am"
 *
 * Based on git-am.sh by Junio C Hamano.
 */
#include "cache.h"
7
#include "config.h"
8 9
#include "builtin.h"
#include "exec_cmd.h"
10 11
#include "parse-options.h"
#include "dir.h"
12
#include "run-command.h"
13
#include "quote.h"
J
Junio C Hamano 已提交
14
#include "tempfile.h"
15
#include "lockfile.h"
16 17 18
#include "cache-tree.h"
#include "refs.h"
#include "commit.h"
19 20
#include "diff.h"
#include "diffcore.h"
P
Paul Tan 已提交
21 22
#include "unpack-trees.h"
#include "branch.h"
P
Paul Tan 已提交
23
#include "sequencer.h"
P
Paul Tan 已提交
24 25
#include "revision.h"
#include "merge-recursive.h"
26 27
#include "revision.h"
#include "log-tree.h"
28
#include "notes-utils.h"
P
Paul Tan 已提交
29
#include "rerere.h"
30
#include "prompt.h"
J
Junio C Hamano 已提交
31
#include "mailinfo.h"
32
#include "apply.h"
33
#include "string-list.h"
J
Jonathan Tan 已提交
34
#include "packfile.h"
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

/**
 * Returns 1 if the file is empty or does not exist, 0 otherwise.
 */
static int is_empty_file(const char *filename)
{
	struct stat st;

	if (stat(filename, &st) < 0) {
		if (errno == ENOENT)
			return 1;
		die_errno(_("could not stat %s"), filename);
	}

	return !st.st_size;
}
51

52 53 54 55 56 57 58 59
/**
 * Returns the length of the first line of msg.
 */
static int linelen(const char *msg)
{
	return strchrnul(msg, '\n') - msg;
}

60 61 62 63 64 65 66 67 68 69 70 71
/**
 * Returns true if `str` consists of only whitespace, false otherwise.
 */
static int str_isspace(const char *str)
{
	for (; *str; str++)
		if (!isspace(*str))
			return 0;

	return 1;
}

72 73
enum patch_format {
	PATCH_FORMAT_UNKNOWN = 0,
74
	PATCH_FORMAT_MBOX,
75
	PATCH_FORMAT_STGIT,
76
	PATCH_FORMAT_STGIT_SERIES,
E
Eric Wong 已提交
77 78
	PATCH_FORMAT_HG,
	PATCH_FORMAT_MBOXRD
79
};
80

81 82 83 84 85 86
enum keep_type {
	KEEP_FALSE = 0,
	KEEP_TRUE,      /* pass -k flag to git-mailinfo */
	KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
};

P
Paul Tan 已提交
87 88 89 90 91 92
enum scissors_type {
	SCISSORS_UNSET = -1,
	SCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */
	SCISSORS_TRUE        /* pass --scissors to git-mailinfo */
};

93 94 95 96 97 98
enum signoff_type {
	SIGNOFF_FALSE = 0,
	SIGNOFF_TRUE = 1,
	SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
};

99 100 101 102 103 104 105
struct am_state {
	/* state directory path */
	char *dir;

	/* current and last patch numbers, 1-indexed */
	int cur;
	int last;
106

107 108 109 110 111 112 113
	/* commit metadata and message */
	char *author_name;
	char *author_email;
	char *author_date;
	char *msg;
	size_t msg_len;

P
Paul Tan 已提交
114
	/* when --rebasing, records the original commit the patch came from */
115
	struct object_id orig_commit;
P
Paul Tan 已提交
116

117 118
	/* number of digits in patch filename */
	int prec;
P
Paul Tan 已提交
119 120

	/* various operating modes and command line options */
121
	int interactive;
P
Paul Tan 已提交
122
	int threeway;
P
Paul Tan 已提交
123
	int quiet;
124
	int signoff; /* enum signoff_type */
P
Paul Tan 已提交
125
	int utf8;
126
	int keep; /* enum keep_type */
127
	int message_id;
P
Paul Tan 已提交
128
	int scissors; /* enum scissors_type */
129
	struct argv_array git_apply_opts;
130
	const char *resolvemsg;
131
	int committer_date_is_author_date;
P
Paul Tan 已提交
132
	int ignore_date;
P
Paul Tan 已提交
133
	int allow_rerere_autoupdate;
134
	const char *sign_commit;
P
Paul Tan 已提交
135
	int rebasing;
136 137 138
};

/**
139
 * Initializes am_state with the default values.
140
 */
141
static void am_state_init(struct am_state *state)
142
{
143 144
	int gpgsign;

145 146
	memset(state, 0, sizeof(*state));

147
	state->dir = git_pathdup("rebase-apply");
148 149

	state->prec = 4;
P
Paul Tan 已提交
150

151 152
	git_config_get_bool("am.threeway", &state->threeway);

P
Paul Tan 已提交
153
	state->utf8 = 1;
154 155

	git_config_get_bool("am.messageid", &state->message_id);
P
Paul Tan 已提交
156 157

	state->scissors = SCISSORS_UNSET;
158 159

	argv_array_init(&state->git_apply_opts);
160 161 162

	if (!git_config_get_bool("commit.gpgsign", &gpgsign))
		state->sign_commit = gpgsign ? "" : NULL;
163 164 165 166 167 168 169 170
}

/**
 * Releases memory allocated by an am_state.
 */
static void am_state_release(struct am_state *state)
{
	free(state->dir);
171 172 173 174
	free(state->author_name);
	free(state->author_email);
	free(state->author_date);
	free(state->msg);
175
	argv_array_clear(&state->git_apply_opts);
176 177 178 179 180 181 182 183 184 185
}

/**
 * Returns path relative to the am_state directory.
 */
static inline const char *am_path(const struct am_state *state, const char *path)
{
	return mkpath("%s/%s", state->dir, path);
}

186 187 188
/**
 * For convenience to call write_file()
 */
189 190
static void write_state_text(const struct am_state *state,
			     const char *name, const char *string)
191
{
192
	write_file(am_path(state, name), "%s", string);
193 194
}

195 196
static void write_state_count(const struct am_state *state,
			      const char *name, int value)
197
{
198
	write_file(am_path(state, name), "%d", value);
199 200
}

201 202
static void write_state_bool(const struct am_state *state,
			     const char *name, int value)
203
{
204
	write_state_text(state, name, value ? "t" : "f");
205 206
}

P
Paul Tan 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
/**
 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
 * at the end.
 */
static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	if (!state->quiet) {
		vfprintf(fp, fmt, ap);
		putc('\n', fp);
	}
	va_end(ap);
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
/**
 * Returns 1 if there is an am session in progress, 0 otherwise.
 */
static int am_in_progress(const struct am_state *state)
{
	struct stat st;

	if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
		return 0;
	if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
		return 0;
	if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
		return 0;
	return 1;
}

/**
 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
 * number of bytes read on success, -1 if the file does not exist. If `trim` is
 * set, trailing whitespace will be removed.
 */
static int read_state_file(struct strbuf *sb, const struct am_state *state,
			const char *file, int trim)
{
	strbuf_reset(sb);

	if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
		if (trim)
			strbuf_trim(sb);

		return sb->len;
	}

	if (errno == ENOENT)
		return -1;

	die_errno(_("could not read '%s'"), am_path(state, file));
}

262
/**
263 264
 * Take a series of KEY='VALUE' lines where VALUE part is
 * sq-quoted, and append <KEY, VALUE> at the end of the string list
265
 */
266
static int parse_key_value_squoted(char *buf, struct string_list *list)
267
{
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
	while (*buf) {
		struct string_list_item *item;
		char *np;
		char *cp = strchr(buf, '=');
		if (!cp)
			return -1;
		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 -1;
		item->util = xstrdup(cp);
	}
	return 0;
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
}

/**
 * Reads and parses the state directory's "author-script" file, and sets
 * state->author_name, state->author_email and state->author_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
 * script, 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.
 */
static int read_author_script(struct am_state *state)
{
	const char *filename = am_path(state, "author-script");
307 308 309 310
	struct strbuf buf = STRBUF_INIT;
	struct string_list kv = STRING_LIST_INIT_DUP;
	int retval = -1; /* assume failure */
	int fd;
311 312 313 314 315

	assert(!state->author_name);
	assert(!state->author_email);
	assert(!state->author_date);

316 317
	fd = open(filename, O_RDONLY);
	if (fd < 0) {
318 319 320 321
		if (errno == ENOENT)
			return 0;
		die_errno(_("could not open '%s' for reading"), filename);
	}
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
	strbuf_read(&buf, fd, 0);
	close(fd);
	if (parse_key_value_squoted(buf.buf, &kv))
		goto finish;

	if (kv.nr != 3 ||
	    strcmp(kv.items[0].string, "GIT_AUTHOR_NAME") ||
	    strcmp(kv.items[1].string, "GIT_AUTHOR_EMAIL") ||
	    strcmp(kv.items[2].string, "GIT_AUTHOR_DATE"))
		goto finish;
	state->author_name = kv.items[0].util;
	state->author_email = kv.items[1].util;
	state->author_date = kv.items[2].util;
	retval = 0;
finish:
	string_list_clear(&kv, !!retval);
	strbuf_release(&buf);
	return retval;
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
}

/**
 * Saves state->author_name, state->author_email and state->author_date in the
 * state directory's "author-script" file.
 */
static void write_author_script(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
	sq_quote_buf(&sb, state->author_name);
	strbuf_addch(&sb, '\n');

	strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
	sq_quote_buf(&sb, state->author_email);
	strbuf_addch(&sb, '\n');

	strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
	sq_quote_buf(&sb, state->author_date);
	strbuf_addch(&sb, '\n');

362
	write_state_text(state, "author-script", sb.buf);
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

	strbuf_release(&sb);
}

/**
 * Reads the commit message from the state directory's "final-commit" file,
 * setting state->msg to its contents and state->msg_len to the length of its
 * contents in bytes.
 *
 * Returns 0 on success, -1 if the file does not exist.
 */
static int read_commit_msg(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	assert(!state->msg);

	if (read_state_file(&sb, state, "final-commit", 0) < 0) {
		strbuf_release(&sb);
		return -1;
	}

	state->msg = strbuf_detach(&sb, &state->msg_len);
	return 0;
}

/**
 * Saves state->msg in the state directory's "final-commit" file.
 */
static void write_commit_msg(const struct am_state *state)
{
	const char *filename = am_path(state, "final-commit");
J
Jeff King 已提交
395
	write_file_buf(filename, state->msg, state->msg_len);
396 397
}

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
/**
 * Loads state from disk.
 */
static void am_load(struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	if (read_state_file(&sb, state, "next", 1) < 0)
		die("BUG: state file 'next' does not exist");
	state->cur = strtol(sb.buf, NULL, 10);

	if (read_state_file(&sb, state, "last", 1) < 0)
		die("BUG: state file 'last' does not exist");
	state->last = strtol(sb.buf, NULL, 10);

413 414 415 416 417
	if (read_author_script(state) < 0)
		die(_("could not parse author script"));

	read_commit_msg(state);

P
Paul Tan 已提交
418
	if (read_state_file(&sb, state, "original-commit", 1) < 0)
419 420
		oidclr(&state->orig_commit);
	else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
P
Paul Tan 已提交
421 422
		die(_("could not parse %s"), am_path(state, "original-commit"));

P
Paul Tan 已提交
423 424 425
	read_state_file(&sb, state, "threeway", 1);
	state->threeway = !strcmp(sb.buf, "t");

P
Paul Tan 已提交
426 427 428
	read_state_file(&sb, state, "quiet", 1);
	state->quiet = !strcmp(sb.buf, "t");

P
Paul Tan 已提交
429 430 431
	read_state_file(&sb, state, "sign", 1);
	state->signoff = !strcmp(sb.buf, "t");

P
Paul Tan 已提交
432 433 434
	read_state_file(&sb, state, "utf8", 1);
	state->utf8 = !strcmp(sb.buf, "t");

435 436 437 438 439 440 441 442
	if (file_exists(am_path(state, "rerere-autoupdate"))) {
		read_state_file(&sb, state, "rerere-autoupdate", 1);
		state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
			RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
	} else {
		state->allow_rerere_autoupdate = 0;
	}

443 444 445 446 447 448 449 450
	read_state_file(&sb, state, "keep", 1);
	if (!strcmp(sb.buf, "t"))
		state->keep = KEEP_TRUE;
	else if (!strcmp(sb.buf, "b"))
		state->keep = KEEP_NON_PATCH;
	else
		state->keep = KEEP_FALSE;

451 452 453
	read_state_file(&sb, state, "messageid", 1);
	state->message_id = !strcmp(sb.buf, "t");

P
Paul Tan 已提交
454 455 456 457 458 459 460 461
	read_state_file(&sb, state, "scissors", 1);
	if (!strcmp(sb.buf, "t"))
		state->scissors = SCISSORS_TRUE;
	else if (!strcmp(sb.buf, "f"))
		state->scissors = SCISSORS_FALSE;
	else
		state->scissors = SCISSORS_UNSET;

462 463 464 465 466
	read_state_file(&sb, state, "apply-opt", 1);
	argv_array_clear(&state->git_apply_opts);
	if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
		die(_("could not parse %s"), am_path(state, "apply-opt"));

P
Paul Tan 已提交
467 468
	state->rebasing = !!file_exists(am_path(state, "rebasing"));

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
	strbuf_release(&sb);
}

/**
 * Removes the am_state directory, forcefully terminating the current am
 * session.
 */
static void am_destroy(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;

	strbuf_addstr(&sb, state->dir);
	remove_dir_recursively(&sb, 0);
	strbuf_release(&sb);
}

485 486 487 488 489 490 491 492 493 494 495
/**
 * Runs applypatch-msg hook. Returns its exit code.
 */
static int run_applypatch_msg_hook(struct am_state *state)
{
	int ret;

	assert(state->msg);
	ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);

	if (!ret) {
496
		FREE_AND_NULL(state->msg);
497 498 499 500 501 502 503 504
		if (read_commit_msg(state) < 0)
			die(_("'%s' was deleted by the applypatch-msg hook"),
				am_path(state, "final-commit"));
	}

	return ret;
}

P
Paul Tan 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
/**
 * Runs post-rewrite hook. Returns it exit code.
 */
static int run_post_rewrite_hook(const struct am_state *state)
{
	struct child_process cp = CHILD_PROCESS_INIT;
	const char *hook = find_hook("post-rewrite");
	int ret;

	if (!hook)
		return 0;

	argv_array_push(&cp.args, hook);
	argv_array_push(&cp.args, "rebase");

	cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
	cp.stdout_to_stderr = 1;

	ret = run_command(&cp);

	close(cp.in);
	return ret;
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
/**
 * Reads the state directory's "rewritten" file, and copies notes from the old
 * commits listed in the file to their rewritten commits.
 *
 * Returns 0 on success, -1 on failure.
 */
static int copy_notes_for_rebase(const struct am_state *state)
{
	struct notes_rewrite_cfg *c;
	struct strbuf sb = STRBUF_INIT;
	const char *invalid_line = _("Malformed input line: '%s'.");
	const char *msg = "Notes added by 'git rebase'";
	FILE *fp;
	int ret = 0;

	assert(state->rebasing);

	c = init_copy_notes_for_rewrite("rebase");
	if (!c)
		return 0;

	fp = xfopen(am_path(state, "rewritten"), "r");

552
	while (!strbuf_getline_lf(&sb, fp)) {
553
		struct object_id from_obj, to_obj;
554 555 556 557 558 559

		if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

560
		if (get_oid_hex(sb.buf, &from_obj)) {
561 562 563 564 565 566 567 568 569
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

		if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

570
		if (get_oid_hex(sb.buf + GIT_SHA1_HEXSZ + 1, &to_obj)) {
571 572 573 574
			ret = error(invalid_line, sb.buf);
			goto finish;
		}

575
		if (copy_note_for_rewrite(c, &from_obj, &to_obj))
576
			ret = error(_("Failed to copy notes from '%s' to '%s'"),
577
					oid_to_hex(&from_obj), oid_to_hex(&to_obj));
578 579 580 581 582 583 584 585 586
	}

finish:
	finish_copy_notes_for_rewrite(c, msg);
	fclose(fp);
	strbuf_release(&sb);
	return ret;
}

P
Paul Tan 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
/**
 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
 * non-indented lines and checking if they look like they begin with valid
 * header field names.
 *
 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
 */
static int is_mail(FILE *fp)
{
	const char *header_regex = "^[!-9;-~]+:";
	struct strbuf sb = STRBUF_INIT;
	regex_t regex;
	int ret = 1;

	if (fseek(fp, 0L, SEEK_SET))
		die_errno(_("fseek failed"));

	if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
		die("invalid pattern: %s", header_regex);

607
	while (!strbuf_getline(&sb, fp)) {
P
Paul Tan 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
		if (!sb.len)
			break; /* End of header */

		/* Ignore indented folded lines */
		if (*sb.buf == '\t' || *sb.buf == ' ')
			continue;

		/* It's a header if it matches header_regex */
		if (regexec(&regex, sb.buf, 0, NULL, 0)) {
			ret = 0;
			goto done;
		}
	}

done:
	regfree(&regex);
	strbuf_release(&sb);
	return ret;
}

/**
 * Attempts to detect the patch_format of the patches contained in `paths`,
 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
 * detection fails.
 */
static int detect_patch_format(const char **paths)
{
	enum patch_format ret = PATCH_FORMAT_UNKNOWN;
	struct strbuf l1 = STRBUF_INIT;
637 638
	struct strbuf l2 = STRBUF_INIT;
	struct strbuf l3 = STRBUF_INIT;
P
Paul Tan 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
	FILE *fp;

	/*
	 * We default to mbox format if input is from stdin and for directories
	 */
	if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
		return PATCH_FORMAT_MBOX;

	/*
	 * Otherwise, check the first few lines of the first patch, starting
	 * from the first non-blank line, to try to detect its format.
	 */

	fp = xfopen(*paths, "r");

654
	while (!strbuf_getline(&l1, fp)) {
P
Paul Tan 已提交
655 656 657 658 659 660 661 662 663
		if (l1.len)
			break;
	}

	if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
		ret = PATCH_FORMAT_MBOX;
		goto done;
	}

664 665 666 667 668
	if (starts_with(l1.buf, "# This series applies on GIT commit")) {
		ret = PATCH_FORMAT_STGIT_SERIES;
		goto done;
	}

669 670 671 672 673
	if (!strcmp(l1.buf, "# HG changeset patch")) {
		ret = PATCH_FORMAT_HG;
		goto done;
	}

674 675
	strbuf_getline(&l2, fp);
	strbuf_getline(&l3, fp);
676 677 678 679 680 681 682 683 684 685 686 687 688

	/*
	 * If the second line is empty and the third is a From, Author or Date
	 * entry, this is likely an StGit patch.
	 */
	if (l1.len && !l2.len &&
		(starts_with(l3.buf, "From:") ||
		 starts_with(l3.buf, "Author:") ||
		 starts_with(l3.buf, "Date:"))) {
		ret = PATCH_FORMAT_STGIT;
		goto done;
	}

P
Paul Tan 已提交
689 690 691 692 693 694 695 696
	if (l1.len && is_mail(fp)) {
		ret = PATCH_FORMAT_MBOX;
		goto done;
	}

done:
	fclose(fp);
	strbuf_release(&l1);
697 698
	strbuf_release(&l2);
	strbuf_release(&l3);
P
Paul Tan 已提交
699 700 701
	return ret;
}

702 703 704 705
/**
 * Splits out individual email patches from `paths`, where each path is either
 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
 */
E
Eric Wong 已提交
706 707
static int split_mail_mbox(struct am_state *state, const char **paths,
				int keep_cr, int mboxrd)
708 709 710 711 712 713 714 715 716
{
	struct child_process cp = CHILD_PROCESS_INIT;
	struct strbuf last = STRBUF_INIT;

	cp.git_cmd = 1;
	argv_array_push(&cp.args, "mailsplit");
	argv_array_pushf(&cp.args, "-d%d", state->prec);
	argv_array_pushf(&cp.args, "-o%s", state->dir);
	argv_array_push(&cp.args, "-b");
717 718
	if (keep_cr)
		argv_array_push(&cp.args, "--keep-cr");
E
Eric Wong 已提交
719 720
	if (mboxrd)
		argv_array_push(&cp.args, "--mboxrd");
721 722 723 724 725 726 727 728 729 730 731 732
	argv_array_push(&cp.args, "--");
	argv_array_pushv(&cp.args, paths);

	if (capture_command(&cp, &last, 8))
		return -1;

	state->cur = 1;
	state->last = strtol(last.buf, NULL, 10);

	return 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
/**
 * Callback signature for split_mail_conv(). The foreign patch should be
 * read from `in`, and the converted patch (in RFC2822 mail format) should be
 * written to `out`. Return 0 on success, or -1 on failure.
 */
typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);

/**
 * Calls `fn` for each file in `paths` to convert the foreign patch to the
 * RFC2822 mail format suitable for parsing with git-mailinfo.
 *
 * Returns 0 on success, -1 on failure.
 */
static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
			const char **paths, int keep_cr)
{
	static const char *stdin_only[] = {"-", NULL};
	int i;

	if (!*paths)
		paths = stdin_only;

	for (i = 0; *paths; paths++, i++) {
		FILE *in, *out;
		const char *mail;
		int ret;

		if (!strcmp(*paths, "-"))
			in = stdin;
		else
			in = fopen(*paths, "r");

		if (!in)
766 767
			return error_errno(_("could not open '%s' for reading"),
					   *paths);
768 769 770 771

		mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);

		out = fopen(mail, "w");
772 773 774
		if (!out) {
			if (in != stdin)
				fclose(in);
775 776
			return error_errno(_("could not open '%s' for writing"),
					   mail);
777
		}
778 779 780 781

		ret = fn(out, in, keep_cr);

		fclose(out);
782 783
		if (in != stdin)
			fclose(in);
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

		if (ret)
			return error(_("could not parse patch '%s'"), *paths);
	}

	state->cur = 1;
	state->last = i;
	return 0;
}

/**
 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
 * message suitable for parsing with git-mailinfo.
 */
static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
{
	struct strbuf sb = STRBUF_INIT;
	int subject_printed = 0;

803
	while (!strbuf_getline_lf(&sb, in)) {
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
		const char *str;

		if (str_isspace(sb.buf))
			continue;
		else if (skip_prefix(sb.buf, "Author:", &str))
			fprintf(out, "From:%s\n", str);
		else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
			fprintf(out, "%s\n", sb.buf);
		else if (!subject_printed) {
			fprintf(out, "Subject: %s\n", sb.buf);
			subject_printed = 1;
		} else {
			fprintf(out, "\n%s\n", sb.buf);
			break;
		}
	}

	strbuf_reset(&sb);
	while (strbuf_fread(&sb, 8192, in) > 0) {
		fwrite(sb.buf, 1, sb.len, out);
		strbuf_reset(&sb);
	}

	strbuf_release(&sb);
	return 0;
}

831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
/**
 * This function only supports a single StGit series file in `paths`.
 *
 * Given an StGit series file, converts the StGit patches in the series into
 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
 * the state directory.
 *
 * Returns 0 on success, -1 on failure.
 */
static int split_mail_stgit_series(struct am_state *state, const char **paths,
					int keep_cr)
{
	const char *series_dir;
	char *series_dir_buf;
	FILE *fp;
	struct argv_array patches = ARGV_ARRAY_INIT;
	struct strbuf sb = STRBUF_INIT;
	int ret;

	if (!paths[0] || paths[1])
		return error(_("Only one StGIT patch series can be applied at once"));

	series_dir_buf = xstrdup(*paths);
	series_dir = dirname(series_dir_buf);

	fp = fopen(*paths, "r");
	if (!fp)
858
		return error_errno(_("could not open '%s' for reading"), *paths);
859

860
	while (!strbuf_getline_lf(&sb, fp)) {
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
		if (*sb.buf == '#')
			continue; /* skip comment lines */

		argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
	}

	fclose(fp);
	strbuf_release(&sb);
	free(series_dir_buf);

	ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);

	argv_array_clear(&patches);
	return ret;
}

877 878 879 880 881 882 883
/**
 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
 * message suitable for parsing with git-mailinfo.
 */
static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
{
	struct strbuf sb = STRBUF_INIT;
884
	int rc = 0;
885

886
	while (!strbuf_getline_lf(&sb, in)) {
887 888 889 890 891
		const char *str;

		if (skip_prefix(sb.buf, "# User ", &str))
			fprintf(out, "From: %s\n", str);
		else if (skip_prefix(sb.buf, "# Date ", &str)) {
892
			timestamp_t timestamp;
893 894 895 896
			long tz, tz2;
			char *end;

			errno = 0;
897
			timestamp = parse_timestamp(str, &end, 10);
898 899 900 901
			if (errno) {
				rc = error(_("invalid timestamp"));
				goto exit;
			}
902

903 904 905 906
			if (!skip_prefix(end, " ", &str)) {
				rc = error(_("invalid Date line"));
				goto exit;
			}
907 908 909

			errno = 0;
			tz = strtol(str, &end, 10);
910 911 912 913
			if (errno) {
				rc = error(_("invalid timezone offset"));
				goto exit;
			}
914

915 916 917 918
			if (*end) {
				rc = error(_("invalid Date line"));
				goto exit;
			}
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942

			/*
			 * mercurial's timezone is in seconds west of UTC,
			 * however git's timezone is in hours + minutes east of
			 * UTC. Convert it.
			 */
			tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
			if (tz > 0)
				tz2 = -tz2;

			fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
		} else if (starts_with(sb.buf, "# ")) {
			continue;
		} else {
			fprintf(out, "\n%s\n", sb.buf);
			break;
		}
	}

	strbuf_reset(&sb);
	while (strbuf_fread(&sb, 8192, in) > 0) {
		fwrite(sb.buf, 1, sb.len, out);
		strbuf_reset(&sb);
	}
943
exit:
944
	strbuf_release(&sb);
945
	return rc;
946 947
}

948 949 950 951 952 953 954 955 956 957 958 959
/**
 * Splits a list of files/directories into individual email patches. Each path
 * in `paths` must be a file/directory that is formatted according to
 * `patch_format`.
 *
 * Once split out, the individual email patches will be stored in the state
 * directory, with each patch's filename being its index, padded to state->prec
 * digits.
 *
 * state->cur will be set to the index of the first mail, and state->last will
 * be set to the index of the last mail.
 *
960 961 962
 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
 * to disable this behavior, -1 to use the default configured setting.
 *
963 964 965
 * Returns 0 on success, -1 on failure.
 */
static int split_mail(struct am_state *state, enum patch_format patch_format,
966
			const char **paths, int keep_cr)
967
{
968 969 970 971 972
	if (keep_cr < 0) {
		keep_cr = 0;
		git_config_get_bool("am.keepcr", &keep_cr);
	}

973 974
	switch (patch_format) {
	case PATCH_FORMAT_MBOX:
E
Eric Wong 已提交
975
		return split_mail_mbox(state, paths, keep_cr, 0);
976 977
	case PATCH_FORMAT_STGIT:
		return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
978 979
	case PATCH_FORMAT_STGIT_SERIES:
		return split_mail_stgit_series(state, paths, keep_cr);
980 981
	case PATCH_FORMAT_HG:
		return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
E
Eric Wong 已提交
982 983
	case PATCH_FORMAT_MBOXRD:
		return split_mail_mbox(state, paths, keep_cr, 1);
984 985 986 987 988 989
	default:
		die("BUG: invalid patch_format");
	}
	return -1;
}

990 991 992
/**
 * Setup a new am session for applying patches
 */
993
static void am_setup(struct am_state *state, enum patch_format patch_format,
994
			const char **paths, int keep_cr)
995
{
996
	struct object_id curr_head;
997
	const char *str;
998
	struct strbuf sb = STRBUF_INIT;
P
Paul Tan 已提交
999

P
Paul Tan 已提交
1000 1001 1002 1003 1004 1005 1006 1007
	if (!patch_format)
		patch_format = detect_patch_format(paths);

	if (!patch_format) {
		fprintf_ln(stderr, _("Patch format detection failed."));
		exit(128);
	}

1008 1009 1010
	if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
		die_errno(_("failed to create directory '%s'"), state->dir);

1011
	if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1012 1013 1014 1015
		am_destroy(state);
		die(_("Failed to split patches."));
	}

P
Paul Tan 已提交
1016 1017 1018
	if (state->rebasing)
		state->threeway = 1;

1019 1020 1021 1022
	write_state_bool(state, "threeway", state->threeway);
	write_state_bool(state, "quiet", state->quiet);
	write_state_bool(state, "sign", state->signoff);
	write_state_bool(state, "utf8", state->utf8);
P
Paul Tan 已提交
1023

1024 1025 1026 1027
	if (state->allow_rerere_autoupdate)
		write_state_bool(state, "rerere-autoupdate",
			 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
	switch (state->keep) {
	case KEEP_FALSE:
		str = "f";
		break;
	case KEEP_TRUE:
		str = "t";
		break;
	case KEEP_NON_PATCH:
		str = "b";
		break;
	default:
		die("BUG: invalid value for state->keep");
	}

1042 1043
	write_state_text(state, "keep", str);
	write_state_bool(state, "messageid", state->message_id);
1044

P
Paul Tan 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
	switch (state->scissors) {
	case SCISSORS_UNSET:
		str = "";
		break;
	case SCISSORS_FALSE:
		str = "f";
		break;
	case SCISSORS_TRUE:
		str = "t";
		break;
	default:
		die("BUG: invalid value for state->scissors");
	}
1058
	write_state_text(state, "scissors", str);
P
Paul Tan 已提交
1059

1060
	sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1061
	write_state_text(state, "apply-opt", sb.buf);
1062

P
Paul Tan 已提交
1063
	if (state->rebasing)
1064
		write_state_text(state, "rebasing", "");
P
Paul Tan 已提交
1065
	else
1066
		write_state_text(state, "applying", "");
P
Paul Tan 已提交
1067

1068 1069
	if (!get_oid("HEAD", &curr_head)) {
		write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
P
Paul Tan 已提交
1070
		if (!state->rebasing)
1071 1072
			update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
				   UPDATE_REFS_DIE_ON_ERR);
P
Paul Tan 已提交
1073
	} else {
1074
		write_state_text(state, "abort-safety", "");
P
Paul Tan 已提交
1075
		if (!state->rebasing)
1076
			delete_ref(NULL, "ORIG_HEAD", NULL, 0);
P
Paul Tan 已提交
1077 1078
	}

1079 1080 1081 1082 1083
	/*
	 * NOTE: Since the "next" and "last" files determine if an am_state
	 * session is in progress, they should be written last.
	 */

1084 1085
	write_state_count(state, "next", state->cur);
	write_state_count(state, "last", state->last);
1086 1087

	strbuf_release(&sb);
1088 1089 1090 1091 1092 1093 1094 1095
}

/**
 * Increments the patch pointer, and cleans am_state for the application of the
 * next patch.
 */
static void am_next(struct am_state *state)
{
1096
	struct object_id head;
P
Paul Tan 已提交
1097

1098 1099 1100 1101
	FREE_AND_NULL(state->author_name);
	FREE_AND_NULL(state->author_email);
	FREE_AND_NULL(state->author_date);
	FREE_AND_NULL(state->msg);
1102 1103 1104 1105 1106
	state->msg_len = 0;

	unlink(am_path(state, "author-script"));
	unlink(am_path(state, "final-commit"));

1107
	oidclr(&state->orig_commit);
P
Paul Tan 已提交
1108 1109
	unlink(am_path(state, "original-commit"));

1110 1111
	if (!get_oid("HEAD", &head))
		write_state_text(state, "abort-safety", oid_to_hex(&head));
P
Paul Tan 已提交
1112
	else
1113
		write_state_text(state, "abort-safety", "");
P
Paul Tan 已提交
1114

1115
	state->cur++;
1116
	write_state_count(state, "next", state->cur);
1117 1118
}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
/**
 * Returns the filename of the current patch email.
 */
static const char *msgnum(const struct am_state *state)
{
	static struct strbuf sb = STRBUF_INIT;

	strbuf_reset(&sb);
	strbuf_addf(&sb, "%0*d", state->prec, state->cur);

	return sb.buf;
}

1132 1133 1134 1135 1136
/**
 * Refresh and write index.
 */
static void refresh_and_write_cache(void)
{
1137
	struct lock_file lock_file = LOCK_INIT;
1138

1139
	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1140
	refresh_cache(REFRESH_QUIET);
1141
	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1142 1143 1144
		die(_("unable to write index file"));
}

1145 1146 1147 1148 1149 1150 1151 1152
/**
 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
 * strbuf is provided, the space-separated list of files that differ will be
 * appended to it.
 */
static int index_has_changes(struct strbuf *sb)
{
1153
	struct object_id head;
1154 1155
	int i;

1156
	if (!get_oid_tree("HEAD", &head)) {
1157 1158 1159
		struct diff_options opt;

		diff_setup(&opt);
1160
		opt.flags.exit_with_status = 1;
1161
		if (!sb)
1162
			opt.flags.quick = 1;
1163
		do_diff_cache(&head, &opt);
1164 1165 1166 1167 1168 1169 1170
		diffcore_std(&opt);
		for (i = 0; sb && i < diff_queued_diff.nr; i++) {
			if (i)
				strbuf_addch(sb, ' ');
			strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
		}
		diff_flush(&opt);
1171
		return opt.flags.has_changes != 0;
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	} else {
		for (i = 0; sb && i < active_nr; i++) {
			if (i)
				strbuf_addch(sb, ' ');
			strbuf_addstr(sb, active_cache[i]->name);
		}
		return !!active_nr;
	}
}

1182 1183 1184 1185 1186 1187 1188 1189 1190
/**
 * Dies with a user-friendly message on how to proceed after resolving the
 * problem. This message can be overridden with state->resolvemsg.
 */
static void NORETURN die_user_resolve(const struct am_state *state)
{
	if (state->resolvemsg) {
		printf_ln("%s", state->resolvemsg);
	} else {
1191
		const char *cmdline = state->interactive ? "git am -i" : "git am";
1192 1193 1194 1195 1196 1197 1198 1199 1200

		printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
		printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
		printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
	}

	exit(128);
}

1201 1202 1203 1204
/**
 * Appends signoff to the "msg" field of the am_state.
 */
static void am_append_signoff(struct am_state *state)
1205
{
1206
	struct strbuf sb = STRBUF_INIT;
1207

1208
	strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1209
	append_signoff(&sb, 0, 0);
1210 1211 1212
	state->msg = strbuf_detach(&sb, &state->msg_len);
}

1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
/**
 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
 * state->msg will be set to the patch message. state->author_name,
 * state->author_email and state->author_date will be set to the patch author's
 * name, email and date respectively. The patch body will be written to the
 * state directory's "patch" file.
 *
 * Returns 1 if the patch should be skipped, 0 otherwise.
 */
static int parse_mail(struct am_state *state, const char *mail)
{
	FILE *fp;
	struct strbuf sb = STRBUF_INIT;
	struct strbuf msg = STRBUF_INIT;
	struct strbuf author_name = STRBUF_INIT;
	struct strbuf author_date = STRBUF_INIT;
	struct strbuf author_email = STRBUF_INIT;
	int ret = 0;
J
Junio C Hamano 已提交
1231
	struct mailinfo mi;
1232

J
Junio C Hamano 已提交
1233
	setup_mailinfo(&mi);
1234

J
Junio C Hamano 已提交
1235 1236 1237 1238
	if (state->utf8)
		mi.metainfo_charset = get_commit_output_encoding();
	else
		mi.metainfo_charset = NULL;
1239 1240 1241 1242 1243

	switch (state->keep) {
	case KEEP_FALSE:
		break;
	case KEEP_TRUE:
J
Junio C Hamano 已提交
1244
		mi.keep_subject = 1;
1245 1246
		break;
	case KEEP_NON_PATCH:
J
Junio C Hamano 已提交
1247
		mi.keep_non_patch_brackets_in_subject = 1;
1248 1249 1250 1251 1252
		break;
	default:
		die("BUG: invalid value for state->keep");
	}

1253
	if (state->message_id)
J
Junio C Hamano 已提交
1254
		mi.add_message_id = 1;
1255

P
Paul Tan 已提交
1256 1257 1258 1259
	switch (state->scissors) {
	case SCISSORS_UNSET:
		break;
	case SCISSORS_FALSE:
J
Junio C Hamano 已提交
1260
		mi.use_scissors = 0;
P
Paul Tan 已提交
1261 1262
		break;
	case SCISSORS_TRUE:
J
Junio C Hamano 已提交
1263
		mi.use_scissors = 1;
P
Paul Tan 已提交
1264 1265 1266 1267 1268
		break;
	default:
		die("BUG: invalid value for state->scissors");
	}

1269 1270
	mi.input = xfopen(mail, "r");
	mi.output = xfopen(am_path(state, "info"), "w");
J
Junio C Hamano 已提交
1271
	if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1272 1273
		die("could not parse patch");

J
Junio C Hamano 已提交
1274 1275
	fclose(mi.input);
	fclose(mi.output);
1276 1277 1278

	/* Extract message and author information */
	fp = xfopen(am_path(state, "info"), "r");
1279
	while (!strbuf_getline_lf(&sb, fp)) {
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
		const char *x;

		if (skip_prefix(sb.buf, "Subject: ", &x)) {
			if (msg.len)
				strbuf_addch(&msg, '\n');
			strbuf_addstr(&msg, x);
		} else if (skip_prefix(sb.buf, "Author: ", &x))
			strbuf_addstr(&author_name, x);
		else if (skip_prefix(sb.buf, "Email: ", &x))
			strbuf_addstr(&author_email, x);
		else if (skip_prefix(sb.buf, "Date: ", &x))
			strbuf_addstr(&author_date, x);
	}
	fclose(fp);

	/* Skip pine's internal folder data */
	if (!strcmp(author_name.buf, "Mail System Internal Data")) {
		ret = 1;
		goto finish;
	}

	if (is_empty_file(am_path(state, "patch"))) {
1302
		printf_ln(_("Patch is empty."));
1303
		die_user_resolve(state);
1304 1305 1306
	}

	strbuf_addstr(&msg, "\n\n");
J
Junio C Hamano 已提交
1307
	strbuf_addbuf(&msg, &mi.log_message);
1308
	strbuf_stripspace(&msg, 0);
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

	assert(!state->author_name);
	state->author_name = strbuf_detach(&author_name, NULL);

	assert(!state->author_email);
	state->author_email = strbuf_detach(&author_email, NULL);

	assert(!state->author_date);
	state->author_date = strbuf_detach(&author_date, NULL);

	assert(!state->msg);
	state->msg = strbuf_detach(&msg, &state->msg_len);

finish:
	strbuf_release(&msg);
	strbuf_release(&author_date);
	strbuf_release(&author_email);
	strbuf_release(&author_name);
	strbuf_release(&sb);
J
Junio C Hamano 已提交
1328
	clear_mailinfo(&mi);
1329 1330 1331
	return ret;
}

1332 1333 1334 1335
/**
 * Sets commit_id to the commit hash where the mail was generated from.
 * Returns 0 on success, -1 on failure.
 */
1336
static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1337 1338 1339 1340
{
	struct strbuf sb = STRBUF_INIT;
	FILE *fp = xfopen(mail, "r");
	const char *x;
1341
	int ret = 0;
1342

1343 1344 1345 1346
	if (strbuf_getline_lf(&sb, fp) ||
	    !skip_prefix(sb.buf, "From ", &x) ||
	    get_oid_hex(x, commit_id) < 0)
		ret = -1;
1347 1348 1349

	strbuf_release(&sb);
	fclose(fp);
1350
	return ret;
1351 1352 1353 1354 1355 1356 1357 1358
}

/**
 * Sets state->msg, state->author_name, state->author_email, state->author_date
 * to the commit's respective info.
 */
static void get_commit_info(struct am_state *state, struct commit *commit)
{
1359
	const char *buffer, *ident_line, *msg;
1360
	size_t ident_len;
1361
	struct ident_split id;
1362 1363 1364 1365 1366

	buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());

	ident_line = find_commit_header(buffer, "author", &ident_len);

1367
	if (split_ident_line(&id, ident_line, ident_len) < 0)
1368
		die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1369 1370

	assert(!state->author_name);
1371
	if (id.name_begin)
1372
		state->author_name =
1373 1374
			xmemdupz(id.name_begin, id.name_end - id.name_begin);
	else
1375 1376 1377
		state->author_name = xstrdup("");

	assert(!state->author_email);
1378
	if (id.mail_begin)
1379
		state->author_email =
1380 1381
			xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
	else
1382 1383 1384
		state->author_email = xstrdup("");

	assert(!state->author_date);
1385
	state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1386 1387 1388 1389

	assert(!state->msg);
	msg = strstr(buffer, "\n\n");
	if (!msg)
1390
		die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1391 1392
	state->msg = xstrdup(msg + 2);
	state->msg_len = strlen(state->msg);
1393
	unuse_commit_buffer(commit, buffer);
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
}

/**
 * Writes `commit` as a patch to the state directory's "patch" file.
 */
static void write_commit_patch(const struct am_state *state, struct commit *commit)
{
	struct rev_info rev_info;
	FILE *fp;

	fp = xfopen(am_path(state, "patch"), "w");
	init_revisions(&rev_info, NULL);
	rev_info.diff = 1;
	rev_info.abbrev = 0;
	rev_info.disable_stdin = 1;
	rev_info.show_root_diff = 1;
	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
	rev_info.no_commit_id = 1;
1412 1413
	rev_info.diffopt.flags.binary = 1;
	rev_info.diffopt.flags.full_index = 1;
1414 1415 1416 1417 1418 1419 1420 1421
	rev_info.diffopt.use_color = 0;
	rev_info.diffopt.file = fp;
	rev_info.diffopt.close_file = 1;
	add_pending_object(&rev_info, &commit->object, "");
	diff_setup_done(&rev_info.diffopt);
	log_tree_commit(&rev_info, commit);
}

1422 1423 1424 1425 1426 1427 1428
/**
 * Writes the diff of the index against HEAD as a patch to the state
 * directory's "patch" file.
 */
static void write_index_patch(const struct am_state *state)
{
	struct tree *tree;
1429
	struct object_id head;
1430 1431 1432
	struct rev_info rev_info;
	FILE *fp;

1433
	if (!get_oid_tree("HEAD", &head))
1434
		tree = lookup_tree(&head);
1435
	else
1436
		tree = lookup_tree(the_hash_algo->empty_tree);
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451

	fp = xfopen(am_path(state, "patch"), "w");
	init_revisions(&rev_info, NULL);
	rev_info.diff = 1;
	rev_info.disable_stdin = 1;
	rev_info.no_commit_id = 1;
	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
	rev_info.diffopt.use_color = 0;
	rev_info.diffopt.file = fp;
	rev_info.diffopt.close_file = 1;
	add_pending_object(&rev_info, &tree->object, "");
	diff_setup_done(&rev_info.diffopt);
	run_diff_index(&rev_info, 1);
}

1452 1453 1454 1455 1456
/**
 * Like parse_mail(), but parses the mail by looking up its commit ID
 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
 * of patches.
 *
P
Paul Tan 已提交
1457 1458
 * state->orig_commit will be set to the original commit ID.
 *
1459 1460 1461 1462 1463
 * Will always return 0 as the patch should never be skipped.
 */
static int parse_mail_rebase(struct am_state *state, const char *mail)
{
	struct commit *commit;
1464
	struct object_id commit_oid;
1465

1466
	if (get_mail_commit_oid(&commit_oid, mail) < 0)
1467 1468
		die(_("could not parse %s"), mail);

1469
	commit = lookup_commit_or_die(&commit_oid, mail);
1470 1471 1472 1473 1474

	get_commit_info(state, commit);

	write_commit_patch(state, commit);

1475 1476
	oidcpy(&state->orig_commit, &commit_oid);
	write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
P
Paul Tan 已提交
1477

1478 1479 1480
	return 0;
}

1481
/**
P
Paul Tan 已提交
1482 1483
 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
 * `index_file` is not NULL, the patch will be applied to that index.
1484
 */
P
Paul Tan 已提交
1485
static int run_apply(const struct am_state *state, const char *index_file)
1486
{
1487 1488 1489 1490 1491 1492 1493
	struct argv_array apply_paths = ARGV_ARRAY_INIT;
	struct argv_array apply_opts = ARGV_ARRAY_INIT;
	struct apply_state apply_state;
	int res, opts_left;
	int force_apply = 0;
	int options = 0;

1494
	if (init_apply_state(&apply_state, NULL))
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
		die("BUG: init_apply_state() failed");

	argv_array_push(&apply_opts, "apply");
	argv_array_pushv(&apply_opts, state->git_apply_opts.argv);

	opts_left = apply_parse_options(apply_opts.argc, apply_opts.argv,
					&apply_state, &force_apply, &options,
					NULL);

	if (opts_left != 0)
		die("unknown option passed through to git apply");

	if (index_file) {
		apply_state.index_file = index_file;
		apply_state.cached = 1;
	} else
		apply_state.check_index = 1;
P
Paul Tan 已提交
1512 1513 1514 1515 1516

	/*
	 * If we are allowed to fall back on 3-way merge, don't give false
	 * errors during the initial attempt.
	 */
1517 1518
	if (state->threeway && !index_file)
		apply_state.apply_verbosity = verbosity_silent;
P
Paul Tan 已提交
1519

1520 1521
	if (check_apply_state(&apply_state, force_apply))
		die("BUG: check_apply_state() failed");
P
Paul Tan 已提交
1522

1523
	argv_array_push(&apply_paths, am_path(state, "patch"));
1524

1525
	res = apply_all_patches(&apply_state, apply_paths.argc, apply_paths.argv, options);
P
Paul Tan 已提交
1526

1527 1528 1529
	argv_array_clear(&apply_paths);
	argv_array_clear(&apply_opts);
	clear_apply_state(&apply_state);
1530

1531 1532
	if (res)
		return res;
1533

1534 1535 1536 1537 1538
	if (index_file) {
		/* Reload index as apply_all_patches() will have modified it. */
		discard_cache();
		read_cache_from(index_file);
	}
P
Paul Tan 已提交
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551

	return 0;
}

/**
 * Builds an index that contains just the blobs needed for a 3way merge.
 */
static int build_fake_ancestor(const struct am_state *state, const char *index_file)
{
	struct child_process cp = CHILD_PROCESS_INIT;

	cp.git_cmd = 1;
	argv_array_push(&cp.args, "apply");
1552
	argv_array_pushv(&cp.args, state->git_apply_opts.argv);
P
Paul Tan 已提交
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
	argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
	argv_array_push(&cp.args, am_path(state, "patch"));

	if (run_command(&cp))
		return -1;

	return 0;
}

/**
 * Attempt a threeway merge, using index_path as the temporary index.
 */
static int fall_back_threeway(const struct am_state *state, const char *index_path)
{
1567 1568 1569 1570 1571
	struct object_id orig_tree, their_tree, our_tree;
	const struct object_id *bases[1] = { &orig_tree };
	struct merge_options o;
	struct commit *result;
	char *their_tree_name;
P
Paul Tan 已提交
1572

1573 1574
	if (get_oid("HEAD", &our_tree) < 0)
		hashcpy(our_tree.hash, EMPTY_TREE_SHA1_BIN);
P
Paul Tan 已提交
1575 1576 1577 1578 1579 1580 1581

	if (build_fake_ancestor(state, index_path))
		return error("could not build fake ancestor");

	discard_cache();
	read_cache_from(index_path);

1582
	if (write_index_as_tree(orig_tree.hash, &the_index, index_path, 0, NULL))
P
Paul Tan 已提交
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
		return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));

	say(state, stdout, _("Using index info to reconstruct a base tree..."));

	if (!state->quiet) {
		/*
		 * List paths that needed 3-way fallback, so that the user can
		 * review them with extra care to spot mismerges.
		 */
		struct rev_info rev_info;
		const char *diff_filter_str = "--diff-filter=AM";

		init_revisions(&rev_info, NULL);
		rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1597
		diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1598
		add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
P
Paul Tan 已提交
1599 1600 1601 1602 1603 1604 1605 1606
		diff_setup_done(&rev_info.diffopt);
		run_diff_index(&rev_info, 1);
	}

	if (run_apply(state, index_path))
		return error(_("Did you hand edit your patch?\n"
				"It does not apply to blobs recorded in its index."));

1607
	if (write_index_as_tree(their_tree.hash, &the_index, index_path, 0, NULL))
P
Paul Tan 已提交
1608 1609 1610 1611
		return error("could not write tree");

	say(state, stdout, _("Falling back to patching base and 3-way merge..."));

1612 1613 1614
	discard_cache();
	read_cache();

P
Paul Tan 已提交
1615 1616
	/*
	 * This is not so wrong. Depending on which base we picked, orig_tree
J
Johannes Schindelin 已提交
1617
	 * may be wildly different from ours, but their_tree has the same set of
P
Paul Tan 已提交
1618 1619 1620 1621 1622
	 * wildly different changes in parts the patch did not touch, so
	 * recursive ends up canceling them, saying that we reverted all those
	 * changes.
	 */

1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
	init_merge_options(&o);

	o.branch1 = "HEAD";
	their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
	o.branch2 = their_tree_name;

	if (state->quiet)
		o.verbosity = 0;

	if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
P
Paul Tan 已提交
1633
		rerere(state->allow_rerere_autoupdate);
1634
		free(their_tree_name);
P
Paul Tan 已提交
1635 1636 1637
		return error(_("Failed to merge in the changes."));
	}

1638
	free(their_tree_name);
1639 1640 1641
	return 0;
}

1642 1643 1644 1645 1646 1647 1648
/**
 * Commits the current index with state->msg as the commit message and
 * state->author_name, state->author_email and state->author_date as the author
 * information.
 */
static void do_commit(const struct am_state *state)
{
1649 1650
	struct object_id tree, parent, commit;
	const struct object_id *old_oid;
1651 1652 1653 1654
	struct commit_list *parents = NULL;
	const char *reflog_msg, *author;
	struct strbuf sb = STRBUF_INIT;

1655 1656 1657
	if (run_hook_le(NULL, "pre-applypatch", NULL))
		exit(1);

1658
	if (write_cache_as_tree(tree.hash, 0, NULL))
1659 1660
		die(_("git write-tree failed to write a tree"));

1661
	if (!get_oid_commit("HEAD", &parent)) {
1662
		old_oid = &parent;
1663
		commit_list_insert(lookup_commit(&parent), &parents);
1664
	} else {
1665
		old_oid = NULL;
P
Paul Tan 已提交
1666
		say(state, stderr, _("applying to an empty history"));
1667 1668 1669
	}

	author = fmt_ident(state->author_name, state->author_email,
P
Paul Tan 已提交
1670 1671
			state->ignore_date ? NULL : state->author_date,
			IDENT_STRICT);
1672

1673 1674 1675 1676
	if (state->committer_date_is_author_date)
		setenv("GIT_COMMITTER_DATE",
			state->ignore_date ? "" : state->author_date, 1);

1677
	if (commit_tree(state->msg, state->msg_len, tree.hash, parents, commit.hash,
1678
				author, state->sign_commit))
1679 1680 1681 1682 1683 1684 1685 1686 1687
		die(_("failed to write commit object"));

	reflog_msg = getenv("GIT_REFLOG_ACTION");
	if (!reflog_msg)
		reflog_msg = "am";

	strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
			state->msg);

1688 1689
	update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
		   UPDATE_REFS_DIE_ON_ERR);
1690

P
Paul Tan 已提交
1691 1692 1693
	if (state->rebasing) {
		FILE *fp = xfopen(am_path(state, "rewritten"), "a");

1694 1695 1696
		assert(!is_null_oid(&state->orig_commit));
		fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
		fprintf(fp, "%s\n", oid_to_hex(&commit));
P
Paul Tan 已提交
1697 1698 1699
		fclose(fp);
	}

1700 1701
	run_hook_le(NULL, "post-applypatch", NULL);

1702 1703 1704
	strbuf_release(&sb);
}

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
/**
 * Validates the am_state for resuming -- the "msg" and authorship fields must
 * be filled up.
 */
static void validate_resume_state(const struct am_state *state)
{
	if (!state->msg)
		die(_("cannot resume: %s does not exist."),
			am_path(state, "final-commit"));

	if (!state->author_name || !state->author_email || !state->author_date)
		die(_("cannot resume: %s does not exist."),
			am_path(state, "author-script"));
}

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
/**
 * Interactively prompt the user on whether the current patch should be
 * applied.
 *
 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
 * skip it.
 */
static int do_interactive(struct am_state *state)
{
	assert(state->msg);

	if (!isatty(0))
		die(_("cannot be interactive without stdin connected to a terminal."));

	for (;;) {
		const char *reply;

		puts(_("Commit Body is:"));
		puts("--------------------------");
		printf("%s", state->msg);
		puts("--------------------------");

		/*
		 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
		 * in your translation. The program will only accept English
		 * input at this point.
		 */
		reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);

		if (!reply) {
			continue;
		} else if (*reply == 'y' || *reply == 'Y') {
			return 0;
		} else if (*reply == 'a' || *reply == 'A') {
			state->interactive = 0;
			return 0;
		} else if (*reply == 'n' || *reply == 'N') {
			return 1;
		} else if (*reply == 'e' || *reply == 'E') {
			struct strbuf msg = STRBUF_INIT;

			if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
				free(state->msg);
				state->msg = strbuf_detach(&msg, &state->msg_len);
			}
			strbuf_release(&msg);
		} else if (*reply == 'v' || *reply == 'V') {
			const char *pager = git_pager(1);
			struct child_process cp = CHILD_PROCESS_INIT;

			if (!pager)
				pager = "cat";
J
Junio C Hamano 已提交
1772
			prepare_pager_args(&cp, pager);
1773 1774 1775 1776 1777 1778
			argv_array_push(&cp.args, am_path(state, "patch"));
			run_command(&cp);
		}
	}
}

1779 1780
/**
 * Applies all queued mail.
1781 1782 1783 1784
 *
 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
 * well as the state directory's "patch" file is used as-is for applying the
 * patch and committing it.
1785
 */
1786
static void am_run(struct am_state *state, int resume)
1787
{
1788
	const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1789
	struct strbuf sb = STRBUF_INIT;
1790

P
Paul Tan 已提交
1791 1792
	unlink(am_path(state, "dirtyindex"));

1793 1794
	refresh_and_write_cache();

P
Paul Tan 已提交
1795
	if (index_has_changes(&sb)) {
1796
		write_state_bool(state, "dirtyindex", 1);
1797
		die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
P
Paul Tan 已提交
1798
	}
1799 1800 1801

	strbuf_release(&sb);

1802
	while (state->cur <= state->last) {
1803
		const char *mail = am_path(state, msgnum(state));
P
Paul Tan 已提交
1804
		int apply_status;
1805

1806 1807
		reset_ident_date();

1808 1809 1810
		if (!file_exists(mail))
			goto next;

1811 1812 1813
		if (resume) {
			validate_resume_state(state);
		} else {
1814 1815 1816 1817 1818 1819 1820 1821
			int skip;

			if (state->rebasing)
				skip = parse_mail_rebase(state, mail);
			else
				skip = parse_mail(state, mail);

			if (skip)
1822
				goto next; /* mail should be skipped */
1823

1824 1825 1826
			if (state->signoff)
				am_append_signoff(state);

1827 1828 1829
			write_author_script(state);
			write_commit_msg(state);
		}
1830

1831 1832 1833
		if (state->interactive && do_interactive(state))
			goto next;

1834 1835 1836
		if (run_applypatch_msg_hook(state))
			exit(1);

P
Paul Tan 已提交
1837
		say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1838

P
Paul Tan 已提交
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
		apply_status = run_apply(state, NULL);

		if (apply_status && state->threeway) {
			struct strbuf sb = STRBUF_INIT;

			strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
			apply_status = fall_back_threeway(state, sb.buf);
			strbuf_release(&sb);

			/*
			 * Applying the patch to an earlier tree and merging
			 * the result may have produced the same tree as ours.
			 */
			if (!apply_status && !index_has_changes(NULL)) {
				say(state, stdout, _("No changes -- Patch already applied."));
				goto next;
			}
		}

		if (apply_status) {
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
			int advice_amworkdir = 1;

			printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
				linelen(state->msg), state->msg);

			git_config_get_bool("advice.amworkdir", &advice_amworkdir);

			if (advice_amworkdir)
				printf_ln(_("The copy of the patch that failed is found in: %s"),
						am_path(state, "patch"));

1870
			die_user_resolve(state);
1871 1872
		}

1873
		do_commit(state);
1874

1875
next:
1876
		am_next(state);
1877 1878 1879 1880

		if (resume)
			am_load(state);
		resume = 0;
1881 1882
	}

P
Paul Tan 已提交
1883 1884
	if (!is_empty_file(am_path(state, "rewritten"))) {
		assert(state->rebasing);
1885
		copy_notes_for_rebase(state);
P
Paul Tan 已提交
1886 1887 1888
		run_post_rewrite_hook(state);
	}

P
Paul Tan 已提交
1889 1890 1891 1892 1893 1894
	/*
	 * In rebasing mode, it's up to the caller to take care of
	 * housekeeping.
	 */
	if (!state->rebasing) {
		am_destroy(state);
1895
		close_all_packs();
P
Paul Tan 已提交
1896 1897
		run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
	}
1898
}
1899

1900 1901 1902 1903 1904 1905 1906 1907 1908
/**
 * Resume the current am session after patch application failure. The user did
 * all the hard work, and we do not have to do any patch application. Just
 * trust and commit what the user has in the index and working tree.
 */
static void am_resolve(struct am_state *state)
{
	validate_resume_state(state);

P
Paul Tan 已提交
1909
	say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1910 1911 1912 1913 1914

	if (!index_has_changes(NULL)) {
		printf_ln(_("No changes - did you forget to use 'git add'?\n"
			"If there is nothing left to stage, chances are that something else\n"
			"already introduced the same changes; you might want to skip this patch."));
1915
		die_user_resolve(state);
1916 1917 1918 1919
	}

	if (unmerged_cache()) {
		printf_ln(_("You still have unmerged paths in your index.\n"
1920 1921
			"You should 'git add' each file with resolved conflicts to mark them as such.\n"
			"You might run `git rm` on a file to accept \"deleted by them\" for it."));
1922
		die_user_resolve(state);
1923 1924
	}

1925 1926 1927 1928 1929 1930
	if (state->interactive) {
		write_index_patch(state);
		if (do_interactive(state))
			goto next;
	}

P
Paul Tan 已提交
1931 1932
	rerere(0);

1933 1934
	do_commit(state);

1935
next:
1936
	am_next(state);
1937
	am_load(state);
1938
	am_run(state, 0);
1939 1940
}

P
Paul Tan 已提交
1941 1942 1943 1944 1945 1946 1947
/**
 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
 * failure.
 */
static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
{
1948
	struct lock_file lock_file = LOCK_INIT;
P
Paul Tan 已提交
1949 1950 1951 1952 1953 1954
	struct unpack_trees_options opts;
	struct tree_desc t[2];

	if (parse_tree(head) || parse_tree(remote))
		return -1;

1955
	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
P
Paul Tan 已提交
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970

	refresh_cache(REFRESH_QUIET);

	memset(&opts, 0, sizeof(opts));
	opts.head_idx = 1;
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
	opts.update = 1;
	opts.merge = 1;
	opts.reset = reset;
	opts.fn = twoway_merge;
	init_tree_desc(&t[0], head->buffer, head->size);
	init_tree_desc(&t[1], remote->buffer, remote->size);

	if (unpack_trees(2, t, &opts)) {
1971
		rollback_lock_file(&lock_file);
P
Paul Tan 已提交
1972 1973 1974
		return -1;
	}

1975
	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
P
Paul Tan 已提交
1976 1977 1978 1979 1980
		die(_("unable to write new index file"));

	return 0;
}

1981 1982 1983 1984 1985 1986
/**
 * Merges a tree into the index. The index's stat info will take precedence
 * over the merged tree's. Returns 0 on success, -1 on failure.
 */
static int merge_tree(struct tree *tree)
{
1987
	struct lock_file lock_file = LOCK_INIT;
1988 1989 1990 1991 1992 1993
	struct unpack_trees_options opts;
	struct tree_desc t[1];

	if (parse_tree(tree))
		return -1;

1994
	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004

	memset(&opts, 0, sizeof(opts));
	opts.head_idx = 1;
	opts.src_index = &the_index;
	opts.dst_index = &the_index;
	opts.merge = 1;
	opts.fn = oneway_merge;
	init_tree_desc(&t[0], tree->buffer, tree->size);

	if (unpack_trees(1, t, &opts)) {
2005
		rollback_lock_file(&lock_file);
2006 2007 2008
		return -1;
	}

2009
	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
2010 2011 2012 2013 2014
		die(_("unable to write new index file"));

	return 0;
}

P
Paul Tan 已提交
2015 2016 2017 2018
/**
 * Clean the index without touching entries that are not modified between
 * `head` and `remote`.
 */
2019
static int clean_index(const struct object_id *head, const struct object_id *remote)
P
Paul Tan 已提交
2020 2021
{
	struct tree *head_tree, *remote_tree, *index_tree;
2022
	struct object_id index;
P
Paul Tan 已提交
2023

2024
	head_tree = parse_tree_indirect(head);
P
Paul Tan 已提交
2025
	if (!head_tree)
2026
		return error(_("Could not parse object '%s'."), oid_to_hex(head));
P
Paul Tan 已提交
2027

2028
	remote_tree = parse_tree_indirect(remote);
P
Paul Tan 已提交
2029
	if (!remote_tree)
2030
		return error(_("Could not parse object '%s'."), oid_to_hex(remote));
P
Paul Tan 已提交
2031 2032 2033 2034 2035 2036

	read_cache_unmerged();

	if (fast_forward_to(head_tree, head_tree, 1))
		return -1;

2037
	if (write_cache_as_tree(index.hash, 0, NULL))
P
Paul Tan 已提交
2038 2039
		return -1;

2040
	index_tree = parse_tree_indirect(&index);
P
Paul Tan 已提交
2041
	if (!index_tree)
2042
		return error(_("Could not parse object '%s'."), oid_to_hex(&index));
P
Paul Tan 已提交
2043 2044 2045 2046

	if (fast_forward_to(index_tree, remote_tree, 0))
		return -1;

2047
	if (merge_tree(remote_tree))
P
Paul Tan 已提交
2048 2049 2050 2051 2052 2053 2054
		return -1;

	remove_branch_state();

	return 0;
}

P
Paul Tan 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
/**
 * Resets rerere's merge resolution metadata.
 */
static void am_rerere_clear(void)
{
	struct string_list merge_rr = STRING_LIST_INIT_DUP;
	rerere_clear(&merge_rr);
	string_list_clear(&merge_rr, 1);
}

P
Paul Tan 已提交
2065 2066 2067 2068 2069
/**
 * Resume the current am session by skipping the current patch.
 */
static void am_skip(struct am_state *state)
{
2070
	struct object_id head;
P
Paul Tan 已提交
2071

P
Paul Tan 已提交
2072 2073
	am_rerere_clear();

2074 2075
	if (get_oid("HEAD", &head))
		hashcpy(head.hash, EMPTY_TREE_SHA1_BIN);
P
Paul Tan 已提交
2076

2077
	if (clean_index(&head, &head))
P
Paul Tan 已提交
2078 2079 2080
		die(_("failed to clean index"));

	am_next(state);
2081
	am_load(state);
P
Paul Tan 已提交
2082 2083 2084
	am_run(state, 0);
}

P
Paul Tan 已提交
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
/**
 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
 *
 * It is not safe to reset HEAD when:
 * 1. git-am previously failed because the index was dirty.
 * 2. HEAD has moved since git-am previously failed.
 */
static int safe_to_abort(const struct am_state *state)
{
	struct strbuf sb = STRBUF_INIT;
2095
	struct object_id abort_safety, head;
P
Paul Tan 已提交
2096 2097 2098 2099 2100

	if (file_exists(am_path(state, "dirtyindex")))
		return 0;

	if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2101
		if (get_oid_hex(sb.buf, &abort_safety))
2102
			die(_("could not parse %s"), am_path(state, "abort-safety"));
P
Paul Tan 已提交
2103
	} else
2104
		oidclr(&abort_safety);
2105
	strbuf_release(&sb);
P
Paul Tan 已提交
2106

2107 2108
	if (get_oid("HEAD", &head))
		oidclr(&head);
P
Paul Tan 已提交
2109

2110
	if (!oidcmp(&head, &abort_safety))
P
Paul Tan 已提交
2111 2112
		return 1;

2113
	warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
P
Paul Tan 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
		"Not rewinding to ORIG_HEAD"));

	return 0;
}

/**
 * Aborts the current am session if it is safe to do so.
 */
static void am_abort(struct am_state *state)
{
2124
	struct object_id curr_head, orig_head;
P
Paul Tan 已提交
2125 2126 2127 2128 2129 2130 2131 2132
	int has_curr_head, has_orig_head;
	char *curr_branch;

	if (!safe_to_abort(state)) {
		am_destroy(state);
		return;
	}

P
Paul Tan 已提交
2133 2134
	am_rerere_clear();

2135
	curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2136
	has_curr_head = curr_branch && !is_null_oid(&curr_head);
P
Paul Tan 已提交
2137
	if (!has_curr_head)
2138
		hashcpy(curr_head.hash, EMPTY_TREE_SHA1_BIN);
P
Paul Tan 已提交
2139

2140
	has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
P
Paul Tan 已提交
2141
	if (!has_orig_head)
2142
		hashcpy(orig_head.hash, EMPTY_TREE_SHA1_BIN);
P
Paul Tan 已提交
2143

2144
	clean_index(&curr_head, &orig_head);
P
Paul Tan 已提交
2145 2146

	if (has_orig_head)
2147 2148 2149
		update_ref("am --abort", "HEAD", &orig_head,
			   has_curr_head ? &curr_head : NULL, 0,
			   UPDATE_REFS_DIE_ON_ERR);
P
Paul Tan 已提交
2150
	else if (curr_branch)
2151
		delete_ref(NULL, curr_branch, NULL, REF_NODEREF);
P
Paul Tan 已提交
2152 2153 2154 2155 2156

	free(curr_branch);
	am_destroy(state);
}

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166
/**
 * parse_options() callback that validates and sets opt->value to the
 * PATCH_FORMAT_* enum value corresponding to `arg`.
 */
static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
{
	int *opt_value = opt->value;

	if (!strcmp(arg, "mbox"))
		*opt_value = PATCH_FORMAT_MBOX;
2167 2168
	else if (!strcmp(arg, "stgit"))
		*opt_value = PATCH_FORMAT_STGIT;
2169 2170
	else if (!strcmp(arg, "stgit-series"))
		*opt_value = PATCH_FORMAT_STGIT_SERIES;
2171 2172
	else if (!strcmp(arg, "hg"))
		*opt_value = PATCH_FORMAT_HG;
E
Eric Wong 已提交
2173 2174
	else if (!strcmp(arg, "mboxrd"))
		*opt_value = PATCH_FORMAT_MBOXRD;
2175 2176 2177 2178 2179
	else
		return error(_("Invalid value for --patch-format: %s"), arg);
	return 0;
}

2180 2181
enum resume_mode {
	RESUME_FALSE = 0,
2182
	RESUME_APPLY,
P
Paul Tan 已提交
2183
	RESUME_RESOLVED,
P
Paul Tan 已提交
2184 2185
	RESUME_SKIP,
	RESUME_ABORT
2186 2187
};

2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
static int git_am_config(const char *k, const char *v, void *cb)
{
	int status;

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

	return git_default_config(k, v, NULL);
}

2199 2200
int cmd_am(int argc, const char **argv, const char *prefix)
{
2201
	struct am_state state;
2202
	int binary = -1;
2203
	int keep_cr = -1;
2204
	int patch_format = PATCH_FORMAT_UNKNOWN;
2205
	enum resume_mode resume = RESUME_FALSE;
2206
	int in_progress;
2207 2208

	const char * const usage[] = {
2209
		N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2210
		N_("git am [<options>] (--continue | --skip | --abort)"),
2211 2212 2213 2214
		NULL
	};

	struct option options[] = {
2215 2216
		OPT_BOOL('i', "interactive", &state.interactive,
			N_("run interactively")),
2217
		OPT_HIDDEN_BOOL('b', "binary", &binary,
2218
			N_("historical option -- no-op")),
P
Paul Tan 已提交
2219 2220
		OPT_BOOL('3', "3way", &state.threeway,
			N_("allow fall back on 3way merging if needed")),
P
Paul Tan 已提交
2221
		OPT__QUIET(&state.quiet, N_("be quiet")),
2222 2223 2224
		OPT_SET_INT('s', "signoff", &state.signoff,
			N_("add a Signed-off-by line to the commit message"),
			SIGNOFF_EXPLICIT),
P
Paul Tan 已提交
2225 2226
		OPT_BOOL('u', "utf8", &state.utf8,
			N_("recode into utf8 (default)")),
2227 2228 2229 2230
		OPT_SET_INT('k', "keep", &state.keep,
			N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
		OPT_SET_INT(0, "keep-non-patch", &state.keep,
			N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2231 2232
		OPT_BOOL('m', "message-id", &state.message_id,
			N_("pass -m flag to git-mailinfo")),
2233 2234 2235 2236 2237 2238
		{ OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
		  N_("pass --keep-cr flag to git-mailsplit for mbox format"),
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
		{ OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
		  N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
		  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
P
Paul Tan 已提交
2239 2240
		OPT_BOOL('c', "scissors", &state.scissors,
			N_("strip everything before a scissors line")),
2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
		OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
		OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
		OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
			N_("pass it through git-apply"),
			0),
		OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
			N_("pass it through git-apply"),
			0),
2265 2266 2267
		OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
			N_("format the patch(es) are in"),
			parse_opt_patchformat),
2268 2269 2270
		OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
			N_("pass it through git-apply"),
			PARSE_OPT_NOARG),
2271 2272
		OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
			N_("override error message when patch failure occurs")),
2273 2274 2275 2276 2277 2278
		OPT_CMDMODE(0, "continue", &resume,
			N_("continue applying patches after resolving a conflict"),
			RESUME_RESOLVED),
		OPT_CMDMODE('r', "resolved", &resume,
			N_("synonyms for --continue"),
			RESUME_RESOLVED),
P
Paul Tan 已提交
2279 2280 2281
		OPT_CMDMODE(0, "skip", &resume,
			N_("skip the current patch"),
			RESUME_SKIP),
P
Paul Tan 已提交
2282 2283 2284
		OPT_CMDMODE(0, "abort", &resume,
			N_("restore the original branch and abort the patching operation."),
			RESUME_ABORT),
2285 2286 2287
		OPT_BOOL(0, "committer-date-is-author-date",
			&state.committer_date_is_author_date,
			N_("lie about committer date")),
P
Paul Tan 已提交
2288 2289
		OPT_BOOL(0, "ignore-date", &state.ignore_date,
			N_("use current timestamp for author date")),
P
Paul Tan 已提交
2290
		OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2291 2292 2293
		{ OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
		  N_("GPG-sign commits"),
		  PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
P
Paul Tan 已提交
2294 2295
		OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
			N_("(internal use for git-rebase)")),
2296 2297
		OPT_END()
	};
2298

J
Jeff King 已提交
2299 2300 2301
	if (argc == 2 && !strcmp(argv[1], "-h"))
		usage_with_options(usage, options);

2302
	git_config(git_am_config, NULL);
2303

2304
	am_state_init(&state);
2305

2306 2307 2308 2309
	in_progress = am_in_progress(&state);
	if (in_progress)
		am_load(&state);

2310 2311
	argc = parse_options(argc, argv, prefix, options, usage, 0);

2312 2313 2314 2315
	if (binary >= 0)
		fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
				"it will be removed. Please do not use it anymore."));

2316 2317 2318
	/* Ensure a valid committer ident can be constructed */
	git_committer_info(IDENT_STRICT);

2319 2320 2321
	if (read_index_preload(&the_index, NULL) < 0)
		die(_("failed to read the index"));

2322
	if (in_progress) {
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
		/*
		 * Catch user error to feed us patches when there is a session
		 * in progress:
		 *
		 * 1. mbox path(s) are provided on the command-line.
		 * 2. stdin is not a tty: the user is trying to feed us a patch
		 *    from standard input. This is somewhat unreliable -- stdin
		 *    could be /dev/null for example and the caller did not
		 *    intend to feed us a patch but wanted to continue
		 *    unattended.
		 */
		if (argc || (resume == RESUME_FALSE && !isatty(0)))
			die(_("previous rebase directory %s still exists but mbox given."),
				state.dir);

2338 2339
		if (resume == RESUME_FALSE)
			resume = RESUME_APPLY;
2340 2341 2342

		if (state.signoff == SIGNOFF_EXPLICIT)
			am_append_signoff(&state);
2343
	} else {
2344 2345 2346
		struct argv_array paths = ARGV_ARRAY_INIT;
		int i;

2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
		/*
		 * Handle stray state directory in the independent-run case. In
		 * the --rebasing case, it is up to the caller to take care of
		 * stray directories.
		 */
		if (file_exists(state.dir) && !state.rebasing) {
			if (resume == RESUME_ABORT) {
				am_destroy(&state);
				am_state_release(&state);
				return 0;
			}

			die(_("Stray %s directory found.\n"
				"Use \"git am --abort\" to remove it."),
				state.dir);
		}

2364 2365 2366
		if (resume)
			die(_("Resolve operation not in progress, we are not resuming."));

2367 2368 2369 2370 2371 2372 2373
		for (i = 0; i < argc; i++) {
			if (is_absolute_path(argv[i]) || !prefix)
				argv_array_push(&paths, argv[i]);
			else
				argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
		}

2374
		am_setup(&state, patch_format, paths.argv, keep_cr);
2375 2376 2377

		argv_array_clear(&paths);
	}
2378

2379 2380
	switch (resume) {
	case RESUME_FALSE:
2381 2382 2383 2384
		am_run(&state, 0);
		break;
	case RESUME_APPLY:
		am_run(&state, 1);
2385 2386 2387 2388
		break;
	case RESUME_RESOLVED:
		am_resolve(&state);
		break;
P
Paul Tan 已提交
2389 2390 2391
	case RESUME_SKIP:
		am_skip(&state);
		break;
P
Paul Tan 已提交
2392 2393 2394
	case RESUME_ABORT:
		am_abort(&state);
		break;
2395 2396 2397
	default:
		die("BUG: invalid resume value");
	}
2398 2399 2400

	am_state_release(&state);

2401 2402
	return 0;
}