1 /*
2  * Builtin "git am"
3  *
4  * Based on git-am.sh by Junio C Hamano.
5  */
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
7 #include "cache.h"
8 #include "config.h"
9 #include "builtin.h"
10 #include "exec-cmd.h"
11 #include "parse-options.h"
12 #include "dir.h"
13 #include "run-command.h"
14 #include "hook.h"
15 #include "quote.h"
16 #include "tempfile.h"
17 #include "lockfile.h"
18 #include "cache-tree.h"
19 #include "refs.h"
20 #include "commit.h"
21 #include "diff.h"
22 #include "diffcore.h"
23 #include "unpack-trees.h"
24 #include "branch.h"
25 #include "sequencer.h"
26 #include "revision.h"
27 #include "merge-recursive.h"
28 #include "log-tree.h"
29 #include "notes-utils.h"
30 #include "rerere.h"
31 #include "prompt.h"
32 #include "mailinfo.h"
33 #include "apply.h"
34 #include "string-list.h"
35 #include "packfile.h"
36 #include "repository.h"
37 
38 /**
39  * Returns the length of the first line of msg.
40  */
linelen(const char * msg)41 static int linelen(const char *msg)
42 {
43 	return strchrnul(msg, '\n') - msg;
44 }
45 
46 /**
47  * Returns true if `str` consists of only whitespace, false otherwise.
48  */
str_isspace(const char * str)49 static int str_isspace(const char *str)
50 {
51 	for (; *str; str++)
52 		if (!isspace(*str))
53 			return 0;
54 
55 	return 1;
56 }
57 
58 enum patch_format {
59 	PATCH_FORMAT_UNKNOWN = 0,
60 	PATCH_FORMAT_MBOX,
61 	PATCH_FORMAT_STGIT,
62 	PATCH_FORMAT_STGIT_SERIES,
63 	PATCH_FORMAT_HG,
64 	PATCH_FORMAT_MBOXRD
65 };
66 
67 enum keep_type {
68 	KEEP_FALSE = 0,
69 	KEEP_TRUE,      /* pass -k flag to git-mailinfo */
70 	KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
71 };
72 
73 enum scissors_type {
74 	SCISSORS_UNSET = -1,
75 	SCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */
76 	SCISSORS_TRUE        /* pass --scissors to git-mailinfo */
77 };
78 
79 enum signoff_type {
80 	SIGNOFF_FALSE = 0,
81 	SIGNOFF_TRUE = 1,
82 	SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
83 };
84 
85 enum show_patch_type {
86 	SHOW_PATCH_RAW = 0,
87 	SHOW_PATCH_DIFF = 1,
88 };
89 
90 struct am_state {
91 	/* state directory path */
92 	char *dir;
93 
94 	/* current and last patch numbers, 1-indexed */
95 	int cur;
96 	int last;
97 
98 	/* commit metadata and message */
99 	char *author_name;
100 	char *author_email;
101 	char *author_date;
102 	char *msg;
103 	size_t msg_len;
104 
105 	/* when --rebasing, records the original commit the patch came from */
106 	struct object_id orig_commit;
107 
108 	/* number of digits in patch filename */
109 	int prec;
110 
111 	/* various operating modes and command line options */
112 	int interactive;
113 	int threeway;
114 	int quiet;
115 	int signoff; /* enum signoff_type */
116 	int utf8;
117 	int keep; /* enum keep_type */
118 	int message_id;
119 	int scissors; /* enum scissors_type */
120 	int quoted_cr; /* enum quoted_cr_action */
121 	struct strvec git_apply_opts;
122 	const char *resolvemsg;
123 	int committer_date_is_author_date;
124 	int ignore_date;
125 	int allow_rerere_autoupdate;
126 	const char *sign_commit;
127 	int rebasing;
128 };
129 
130 /**
131  * Initializes am_state with the default values.
132  */
am_state_init(struct am_state * state)133 static void am_state_init(struct am_state *state)
134 {
135 	int gpgsign;
136 
137 	memset(state, 0, sizeof(*state));
138 
139 	state->dir = git_pathdup("rebase-apply");
140 
141 	state->prec = 4;
142 
143 	git_config_get_bool("am.threeway", &state->threeway);
144 
145 	state->utf8 = 1;
146 
147 	git_config_get_bool("am.messageid", &state->message_id);
148 
149 	state->scissors = SCISSORS_UNSET;
150 	state->quoted_cr = quoted_cr_unset;
151 
152 	strvec_init(&state->git_apply_opts);
153 
154 	if (!git_config_get_bool("commit.gpgsign", &gpgsign))
155 		state->sign_commit = gpgsign ? "" : NULL;
156 }
157 
158 /**
159  * Releases memory allocated by an am_state.
160  */
am_state_release(struct am_state * state)161 static void am_state_release(struct am_state *state)
162 {
163 	free(state->dir);
164 	free(state->author_name);
165 	free(state->author_email);
166 	free(state->author_date);
167 	free(state->msg);
168 	strvec_clear(&state->git_apply_opts);
169 }
170 
am_option_parse_quoted_cr(const struct option * opt,const char * arg,int unset)171 static int am_option_parse_quoted_cr(const struct option *opt,
172 				     const char *arg, int unset)
173 {
174 	BUG_ON_OPT_NEG(unset);
175 
176 	if (mailinfo_parse_quoted_cr_action(arg, opt->value) != 0)
177 		return error(_("bad action '%s' for '%s'"), arg, "--quoted-cr");
178 	return 0;
179 }
180 
181 /**
182  * Returns path relative to the am_state directory.
183  */
am_path(const struct am_state * state,const char * path)184 static inline const char *am_path(const struct am_state *state, const char *path)
185 {
186 	return mkpath("%s/%s", state->dir, path);
187 }
188 
189 /**
190  * For convenience to call write_file()
191  */
write_state_text(const struct am_state * state,const char * name,const char * string)192 static void write_state_text(const struct am_state *state,
193 			     const char *name, const char *string)
194 {
195 	write_file(am_path(state, name), "%s", string);
196 }
197 
write_state_count(const struct am_state * state,const char * name,int value)198 static void write_state_count(const struct am_state *state,
199 			      const char *name, int value)
200 {
201 	write_file(am_path(state, name), "%d", value);
202 }
203 
write_state_bool(const struct am_state * state,const char * name,int value)204 static void write_state_bool(const struct am_state *state,
205 			     const char *name, int value)
206 {
207 	write_state_text(state, name, value ? "t" : "f");
208 }
209 
210 /**
211  * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
212  * at the end.
213  */
214 __attribute__((format (printf, 3, 4)))
say(const struct am_state * state,FILE * fp,const char * fmt,...)215 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
216 {
217 	va_list ap;
218 
219 	va_start(ap, fmt);
220 	if (!state->quiet) {
221 		vfprintf(fp, fmt, ap);
222 		putc('\n', fp);
223 	}
224 	va_end(ap);
225 }
226 
227 /**
228  * Returns 1 if there is an am session in progress, 0 otherwise.
229  */
am_in_progress(const struct am_state * state)230 static int am_in_progress(const struct am_state *state)
231 {
232 	struct stat st;
233 
234 	if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
235 		return 0;
236 	if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
237 		return 0;
238 	if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
239 		return 0;
240 	return 1;
241 }
242 
243 /**
244  * Reads the contents of `file` in the `state` directory into `sb`. Returns the
245  * number of bytes read on success, -1 if the file does not exist. If `trim` is
246  * set, trailing whitespace will be removed.
247  */
read_state_file(struct strbuf * sb,const struct am_state * state,const char * file,int trim)248 static int read_state_file(struct strbuf *sb, const struct am_state *state,
249 			const char *file, int trim)
250 {
251 	strbuf_reset(sb);
252 
253 	if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
254 		if (trim)
255 			strbuf_trim(sb);
256 
257 		return sb->len;
258 	}
259 
260 	if (errno == ENOENT)
261 		return -1;
262 
263 	die_errno(_("could not read '%s'"), am_path(state, file));
264 }
265 
266 /**
267  * Reads and parses the state directory's "author-script" file, and sets
268  * state->author_name, state->author_email and state->author_date accordingly.
269  * Returns 0 on success, -1 if the file could not be parsed.
270  *
271  * The author script is of the format:
272  *
273  *	GIT_AUTHOR_NAME='$author_name'
274  *	GIT_AUTHOR_EMAIL='$author_email'
275  *	GIT_AUTHOR_DATE='$author_date'
276  *
277  * where $author_name, $author_email and $author_date are quoted. We are strict
278  * with our parsing, as the file was meant to be eval'd in the old git-am.sh
279  * script, and thus if the file differs from what this function expects, it is
280  * better to bail out than to do something that the user does not expect.
281  */
read_am_author_script(struct am_state * state)282 static int read_am_author_script(struct am_state *state)
283 {
284 	const char *filename = am_path(state, "author-script");
285 
286 	assert(!state->author_name);
287 	assert(!state->author_email);
288 	assert(!state->author_date);
289 
290 	return read_author_script(filename, &state->author_name,
291 				  &state->author_email, &state->author_date, 1);
292 }
293 
294 /**
295  * Saves state->author_name, state->author_email and state->author_date in the
296  * state directory's "author-script" file.
297  */
write_author_script(const struct am_state * state)298 static void write_author_script(const struct am_state *state)
299 {
300 	struct strbuf sb = STRBUF_INIT;
301 
302 	strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
303 	sq_quote_buf(&sb, state->author_name);
304 	strbuf_addch(&sb, '\n');
305 
306 	strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
307 	sq_quote_buf(&sb, state->author_email);
308 	strbuf_addch(&sb, '\n');
309 
310 	strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
311 	sq_quote_buf(&sb, state->author_date);
312 	strbuf_addch(&sb, '\n');
313 
314 	write_state_text(state, "author-script", sb.buf);
315 
316 	strbuf_release(&sb);
317 }
318 
319 /**
320  * Reads the commit message from the state directory's "final-commit" file,
321  * setting state->msg to its contents and state->msg_len to the length of its
322  * contents in bytes.
323  *
324  * Returns 0 on success, -1 if the file does not exist.
325  */
read_commit_msg(struct am_state * state)326 static int read_commit_msg(struct am_state *state)
327 {
328 	struct strbuf sb = STRBUF_INIT;
329 
330 	assert(!state->msg);
331 
332 	if (read_state_file(&sb, state, "final-commit", 0) < 0) {
333 		strbuf_release(&sb);
334 		return -1;
335 	}
336 
337 	state->msg = strbuf_detach(&sb, &state->msg_len);
338 	return 0;
339 }
340 
341 /**
342  * Saves state->msg in the state directory's "final-commit" file.
343  */
write_commit_msg(const struct am_state * state)344 static void write_commit_msg(const struct am_state *state)
345 {
346 	const char *filename = am_path(state, "final-commit");
347 	write_file_buf(filename, state->msg, state->msg_len);
348 }
349 
350 /**
351  * Loads state from disk.
352  */
am_load(struct am_state * state)353 static void am_load(struct am_state *state)
354 {
355 	struct strbuf sb = STRBUF_INIT;
356 
357 	if (read_state_file(&sb, state, "next", 1) < 0)
358 		BUG("state file 'next' does not exist");
359 	state->cur = strtol(sb.buf, NULL, 10);
360 
361 	if (read_state_file(&sb, state, "last", 1) < 0)
362 		BUG("state file 'last' does not exist");
363 	state->last = strtol(sb.buf, NULL, 10);
364 
365 	if (read_am_author_script(state) < 0)
366 		die(_("could not parse author script"));
367 
368 	read_commit_msg(state);
369 
370 	if (read_state_file(&sb, state, "original-commit", 1) < 0)
371 		oidclr(&state->orig_commit);
372 	else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
373 		die(_("could not parse %s"), am_path(state, "original-commit"));
374 
375 	read_state_file(&sb, state, "threeway", 1);
376 	state->threeway = !strcmp(sb.buf, "t");
377 
378 	read_state_file(&sb, state, "quiet", 1);
379 	state->quiet = !strcmp(sb.buf, "t");
380 
381 	read_state_file(&sb, state, "sign", 1);
382 	state->signoff = !strcmp(sb.buf, "t");
383 
384 	read_state_file(&sb, state, "utf8", 1);
385 	state->utf8 = !strcmp(sb.buf, "t");
386 
387 	if (file_exists(am_path(state, "rerere-autoupdate"))) {
388 		read_state_file(&sb, state, "rerere-autoupdate", 1);
389 		state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
390 			RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
391 	} else {
392 		state->allow_rerere_autoupdate = 0;
393 	}
394 
395 	read_state_file(&sb, state, "keep", 1);
396 	if (!strcmp(sb.buf, "t"))
397 		state->keep = KEEP_TRUE;
398 	else if (!strcmp(sb.buf, "b"))
399 		state->keep = KEEP_NON_PATCH;
400 	else
401 		state->keep = KEEP_FALSE;
402 
403 	read_state_file(&sb, state, "messageid", 1);
404 	state->message_id = !strcmp(sb.buf, "t");
405 
406 	read_state_file(&sb, state, "scissors", 1);
407 	if (!strcmp(sb.buf, "t"))
408 		state->scissors = SCISSORS_TRUE;
409 	else if (!strcmp(sb.buf, "f"))
410 		state->scissors = SCISSORS_FALSE;
411 	else
412 		state->scissors = SCISSORS_UNSET;
413 
414 	read_state_file(&sb, state, "quoted-cr", 1);
415 	if (!*sb.buf)
416 		state->quoted_cr = quoted_cr_unset;
417 	else if (mailinfo_parse_quoted_cr_action(sb.buf, &state->quoted_cr) != 0)
418 		die(_("could not parse %s"), am_path(state, "quoted-cr"));
419 
420 	read_state_file(&sb, state, "apply-opt", 1);
421 	strvec_clear(&state->git_apply_opts);
422 	if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
423 		die(_("could not parse %s"), am_path(state, "apply-opt"));
424 
425 	state->rebasing = !!file_exists(am_path(state, "rebasing"));
426 
427 	strbuf_release(&sb);
428 }
429 
430 /**
431  * Removes the am_state directory, forcefully terminating the current am
432  * session.
433  */
am_destroy(const struct am_state * state)434 static void am_destroy(const struct am_state *state)
435 {
436 	struct strbuf sb = STRBUF_INIT;
437 
438 	strbuf_addstr(&sb, state->dir);
439 	remove_dir_recursively(&sb, 0);
440 	strbuf_release(&sb);
441 }
442 
443 /**
444  * Runs applypatch-msg hook. Returns its exit code.
445  */
run_applypatch_msg_hook(struct am_state * state)446 static int run_applypatch_msg_hook(struct am_state *state)
447 {
448 	int ret;
449 
450 	assert(state->msg);
451 	ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
452 
453 	if (!ret) {
454 		FREE_AND_NULL(state->msg);
455 		if (read_commit_msg(state) < 0)
456 			die(_("'%s' was deleted by the applypatch-msg hook"),
457 				am_path(state, "final-commit"));
458 	}
459 
460 	return ret;
461 }
462 
463 /**
464  * Runs post-rewrite hook. Returns it exit code.
465  */
run_post_rewrite_hook(const struct am_state * state)466 static int run_post_rewrite_hook(const struct am_state *state)
467 {
468 	struct child_process cp = CHILD_PROCESS_INIT;
469 	const char *hook = find_hook("post-rewrite");
470 	int ret;
471 
472 	if (!hook)
473 		return 0;
474 
475 	strvec_push(&cp.args, hook);
476 	strvec_push(&cp.args, "rebase");
477 
478 	cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
479 	cp.stdout_to_stderr = 1;
480 	cp.trace2_hook_name = "post-rewrite";
481 
482 	ret = run_command(&cp);
483 
484 	close(cp.in);
485 	return ret;
486 }
487 
488 /**
489  * Reads the state directory's "rewritten" file, and copies notes from the old
490  * commits listed in the file to their rewritten commits.
491  *
492  * Returns 0 on success, -1 on failure.
493  */
copy_notes_for_rebase(const struct am_state * state)494 static int copy_notes_for_rebase(const struct am_state *state)
495 {
496 	struct notes_rewrite_cfg *c;
497 	struct strbuf sb = STRBUF_INIT;
498 	const char *invalid_line = _("Malformed input line: '%s'.");
499 	const char *msg = "Notes added by 'git rebase'";
500 	FILE *fp;
501 	int ret = 0;
502 
503 	assert(state->rebasing);
504 
505 	c = init_copy_notes_for_rewrite("rebase");
506 	if (!c)
507 		return 0;
508 
509 	fp = xfopen(am_path(state, "rewritten"), "r");
510 
511 	while (!strbuf_getline_lf(&sb, fp)) {
512 		struct object_id from_obj, to_obj;
513 		const char *p;
514 
515 		if (sb.len != the_hash_algo->hexsz * 2 + 1) {
516 			ret = error(invalid_line, sb.buf);
517 			goto finish;
518 		}
519 
520 		if (parse_oid_hex(sb.buf, &from_obj, &p)) {
521 			ret = error(invalid_line, sb.buf);
522 			goto finish;
523 		}
524 
525 		if (*p != ' ') {
526 			ret = error(invalid_line, sb.buf);
527 			goto finish;
528 		}
529 
530 		if (get_oid_hex(p + 1, &to_obj)) {
531 			ret = error(invalid_line, sb.buf);
532 			goto finish;
533 		}
534 
535 		if (copy_note_for_rewrite(c, &from_obj, &to_obj))
536 			ret = error(_("Failed to copy notes from '%s' to '%s'"),
537 					oid_to_hex(&from_obj), oid_to_hex(&to_obj));
538 	}
539 
540 finish:
541 	finish_copy_notes_for_rewrite(the_repository, c, msg);
542 	fclose(fp);
543 	strbuf_release(&sb);
544 	return ret;
545 }
546 
547 /**
548  * Determines if the file looks like a piece of RFC2822 mail by grabbing all
549  * non-indented lines and checking if they look like they begin with valid
550  * header field names.
551  *
552  * Returns 1 if the file looks like a piece of mail, 0 otherwise.
553  */
is_mail(FILE * fp)554 static int is_mail(FILE *fp)
555 {
556 	const char *header_regex = "^[!-9;-~]+:";
557 	struct strbuf sb = STRBUF_INIT;
558 	regex_t regex;
559 	int ret = 1;
560 
561 	if (fseek(fp, 0L, SEEK_SET))
562 		die_errno(_("fseek failed"));
563 
564 	if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
565 		die("invalid pattern: %s", header_regex);
566 
567 	while (!strbuf_getline(&sb, fp)) {
568 		if (!sb.len)
569 			break; /* End of header */
570 
571 		/* Ignore indented folded lines */
572 		if (*sb.buf == '\t' || *sb.buf == ' ')
573 			continue;
574 
575 		/* It's a header if it matches header_regex */
576 		if (regexec(&regex, sb.buf, 0, NULL, 0)) {
577 			ret = 0;
578 			goto done;
579 		}
580 	}
581 
582 done:
583 	regfree(&regex);
584 	strbuf_release(&sb);
585 	return ret;
586 }
587 
588 /**
589  * Attempts to detect the patch_format of the patches contained in `paths`,
590  * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
591  * detection fails.
592  */
detect_patch_format(const char ** paths)593 static int detect_patch_format(const char **paths)
594 {
595 	enum patch_format ret = PATCH_FORMAT_UNKNOWN;
596 	struct strbuf l1 = STRBUF_INIT;
597 	struct strbuf l2 = STRBUF_INIT;
598 	struct strbuf l3 = STRBUF_INIT;
599 	FILE *fp;
600 
601 	/*
602 	 * We default to mbox format if input is from stdin and for directories
603 	 */
604 	if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
605 		return PATCH_FORMAT_MBOX;
606 
607 	/*
608 	 * Otherwise, check the first few lines of the first patch, starting
609 	 * from the first non-blank line, to try to detect its format.
610 	 */
611 
612 	fp = xfopen(*paths, "r");
613 
614 	while (!strbuf_getline(&l1, fp)) {
615 		if (l1.len)
616 			break;
617 	}
618 
619 	if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
620 		ret = PATCH_FORMAT_MBOX;
621 		goto done;
622 	}
623 
624 	if (starts_with(l1.buf, "# This series applies on GIT commit")) {
625 		ret = PATCH_FORMAT_STGIT_SERIES;
626 		goto done;
627 	}
628 
629 	if (!strcmp(l1.buf, "# HG changeset patch")) {
630 		ret = PATCH_FORMAT_HG;
631 		goto done;
632 	}
633 
634 	strbuf_getline(&l2, fp);
635 	strbuf_getline(&l3, fp);
636 
637 	/*
638 	 * If the second line is empty and the third is a From, Author or Date
639 	 * entry, this is likely an StGit patch.
640 	 */
641 	if (l1.len && !l2.len &&
642 		(starts_with(l3.buf, "From:") ||
643 		 starts_with(l3.buf, "Author:") ||
644 		 starts_with(l3.buf, "Date:"))) {
645 		ret = PATCH_FORMAT_STGIT;
646 		goto done;
647 	}
648 
649 	if (l1.len && is_mail(fp)) {
650 		ret = PATCH_FORMAT_MBOX;
651 		goto done;
652 	}
653 
654 done:
655 	fclose(fp);
656 	strbuf_release(&l1);
657 	strbuf_release(&l2);
658 	strbuf_release(&l3);
659 	return ret;
660 }
661 
662 /**
663  * Splits out individual email patches from `paths`, where each path is either
664  * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
665  */
split_mail_mbox(struct am_state * state,const char ** paths,int keep_cr,int mboxrd)666 static int split_mail_mbox(struct am_state *state, const char **paths,
667 				int keep_cr, int mboxrd)
668 {
669 	struct child_process cp = CHILD_PROCESS_INIT;
670 	struct strbuf last = STRBUF_INIT;
671 	int ret;
672 
673 	cp.git_cmd = 1;
674 	strvec_push(&cp.args, "mailsplit");
675 	strvec_pushf(&cp.args, "-d%d", state->prec);
676 	strvec_pushf(&cp.args, "-o%s", state->dir);
677 	strvec_push(&cp.args, "-b");
678 	if (keep_cr)
679 		strvec_push(&cp.args, "--keep-cr");
680 	if (mboxrd)
681 		strvec_push(&cp.args, "--mboxrd");
682 	strvec_push(&cp.args, "--");
683 	strvec_pushv(&cp.args, paths);
684 
685 	ret = capture_command(&cp, &last, 8);
686 	if (ret)
687 		goto exit;
688 
689 	state->cur = 1;
690 	state->last = strtol(last.buf, NULL, 10);
691 
692 exit:
693 	strbuf_release(&last);
694 	return ret ? -1 : 0;
695 }
696 
697 /**
698  * Callback signature for split_mail_conv(). The foreign patch should be
699  * read from `in`, and the converted patch (in RFC2822 mail format) should be
700  * written to `out`. Return 0 on success, or -1 on failure.
701  */
702 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
703 
704 /**
705  * Calls `fn` for each file in `paths` to convert the foreign patch to the
706  * RFC2822 mail format suitable for parsing with git-mailinfo.
707  *
708  * Returns 0 on success, -1 on failure.
709  */
split_mail_conv(mail_conv_fn fn,struct am_state * state,const char ** paths,int keep_cr)710 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
711 			const char **paths, int keep_cr)
712 {
713 	static const char *stdin_only[] = {"-", NULL};
714 	int i;
715 
716 	if (!*paths)
717 		paths = stdin_only;
718 
719 	for (i = 0; *paths; paths++, i++) {
720 		FILE *in, *out;
721 		const char *mail;
722 		int ret;
723 
724 		if (!strcmp(*paths, "-"))
725 			in = stdin;
726 		else
727 			in = fopen(*paths, "r");
728 
729 		if (!in)
730 			return error_errno(_("could not open '%s' for reading"),
731 					   *paths);
732 
733 		mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
734 
735 		out = fopen(mail, "w");
736 		if (!out) {
737 			if (in != stdin)
738 				fclose(in);
739 			return error_errno(_("could not open '%s' for writing"),
740 					   mail);
741 		}
742 
743 		ret = fn(out, in, keep_cr);
744 
745 		fclose(out);
746 		if (in != stdin)
747 			fclose(in);
748 
749 		if (ret)
750 			return error(_("could not parse patch '%s'"), *paths);
751 	}
752 
753 	state->cur = 1;
754 	state->last = i;
755 	return 0;
756 }
757 
758 /**
759  * A split_mail_conv() callback that converts an StGit patch to an RFC2822
760  * message suitable for parsing with git-mailinfo.
761  */
stgit_patch_to_mail(FILE * out,FILE * in,int keep_cr)762 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
763 {
764 	struct strbuf sb = STRBUF_INIT;
765 	int subject_printed = 0;
766 
767 	while (!strbuf_getline_lf(&sb, in)) {
768 		const char *str;
769 
770 		if (str_isspace(sb.buf))
771 			continue;
772 		else if (skip_prefix(sb.buf, "Author:", &str))
773 			fprintf(out, "From:%s\n", str);
774 		else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
775 			fprintf(out, "%s\n", sb.buf);
776 		else if (!subject_printed) {
777 			fprintf(out, "Subject: %s\n", sb.buf);
778 			subject_printed = 1;
779 		} else {
780 			fprintf(out, "\n%s\n", sb.buf);
781 			break;
782 		}
783 	}
784 
785 	strbuf_reset(&sb);
786 	while (strbuf_fread(&sb, 8192, in) > 0) {
787 		fwrite(sb.buf, 1, sb.len, out);
788 		strbuf_reset(&sb);
789 	}
790 
791 	strbuf_release(&sb);
792 	return 0;
793 }
794 
795 /**
796  * This function only supports a single StGit series file in `paths`.
797  *
798  * Given an StGit series file, converts the StGit patches in the series into
799  * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
800  * the state directory.
801  *
802  * Returns 0 on success, -1 on failure.
803  */
split_mail_stgit_series(struct am_state * state,const char ** paths,int keep_cr)804 static int split_mail_stgit_series(struct am_state *state, const char **paths,
805 					int keep_cr)
806 {
807 	const char *series_dir;
808 	char *series_dir_buf;
809 	FILE *fp;
810 	struct strvec patches = STRVEC_INIT;
811 	struct strbuf sb = STRBUF_INIT;
812 	int ret;
813 
814 	if (!paths[0] || paths[1])
815 		return error(_("Only one StGIT patch series can be applied at once"));
816 
817 	series_dir_buf = xstrdup(*paths);
818 	series_dir = dirname(series_dir_buf);
819 
820 	fp = fopen(*paths, "r");
821 	if (!fp)
822 		return error_errno(_("could not open '%s' for reading"), *paths);
823 
824 	while (!strbuf_getline_lf(&sb, fp)) {
825 		if (*sb.buf == '#')
826 			continue; /* skip comment lines */
827 
828 		strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
829 	}
830 
831 	fclose(fp);
832 	strbuf_release(&sb);
833 	free(series_dir_buf);
834 
835 	ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
836 
837 	strvec_clear(&patches);
838 	return ret;
839 }
840 
841 /**
842  * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
843  * message suitable for parsing with git-mailinfo.
844  */
hg_patch_to_mail(FILE * out,FILE * in,int keep_cr)845 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
846 {
847 	struct strbuf sb = STRBUF_INIT;
848 	int rc = 0;
849 
850 	while (!strbuf_getline_lf(&sb, in)) {
851 		const char *str;
852 
853 		if (skip_prefix(sb.buf, "# User ", &str))
854 			fprintf(out, "From: %s\n", str);
855 		else if (skip_prefix(sb.buf, "# Date ", &str)) {
856 			timestamp_t timestamp;
857 			long tz, tz2;
858 			char *end;
859 
860 			errno = 0;
861 			timestamp = parse_timestamp(str, &end, 10);
862 			if (errno) {
863 				rc = error(_("invalid timestamp"));
864 				goto exit;
865 			}
866 
867 			if (!skip_prefix(end, " ", &str)) {
868 				rc = error(_("invalid Date line"));
869 				goto exit;
870 			}
871 
872 			errno = 0;
873 			tz = strtol(str, &end, 10);
874 			if (errno) {
875 				rc = error(_("invalid timezone offset"));
876 				goto exit;
877 			}
878 
879 			if (*end) {
880 				rc = error(_("invalid Date line"));
881 				goto exit;
882 			}
883 
884 			/*
885 			 * mercurial's timezone is in seconds west of UTC,
886 			 * however git's timezone is in hours + minutes east of
887 			 * UTC. Convert it.
888 			 */
889 			tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
890 			if (tz > 0)
891 				tz2 = -tz2;
892 
893 			fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
894 		} else if (starts_with(sb.buf, "# ")) {
895 			continue;
896 		} else {
897 			fprintf(out, "\n%s\n", sb.buf);
898 			break;
899 		}
900 	}
901 
902 	strbuf_reset(&sb);
903 	while (strbuf_fread(&sb, 8192, in) > 0) {
904 		fwrite(sb.buf, 1, sb.len, out);
905 		strbuf_reset(&sb);
906 	}
907 exit:
908 	strbuf_release(&sb);
909 	return rc;
910 }
911 
912 /**
913  * Splits a list of files/directories into individual email patches. Each path
914  * in `paths` must be a file/directory that is formatted according to
915  * `patch_format`.
916  *
917  * Once split out, the individual email patches will be stored in the state
918  * directory, with each patch's filename being its index, padded to state->prec
919  * digits.
920  *
921  * state->cur will be set to the index of the first mail, and state->last will
922  * be set to the index of the last mail.
923  *
924  * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
925  * to disable this behavior, -1 to use the default configured setting.
926  *
927  * Returns 0 on success, -1 on failure.
928  */
split_mail(struct am_state * state,enum patch_format patch_format,const char ** paths,int keep_cr)929 static int split_mail(struct am_state *state, enum patch_format patch_format,
930 			const char **paths, int keep_cr)
931 {
932 	if (keep_cr < 0) {
933 		keep_cr = 0;
934 		git_config_get_bool("am.keepcr", &keep_cr);
935 	}
936 
937 	switch (patch_format) {
938 	case PATCH_FORMAT_MBOX:
939 		return split_mail_mbox(state, paths, keep_cr, 0);
940 	case PATCH_FORMAT_STGIT:
941 		return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
942 	case PATCH_FORMAT_STGIT_SERIES:
943 		return split_mail_stgit_series(state, paths, keep_cr);
944 	case PATCH_FORMAT_HG:
945 		return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
946 	case PATCH_FORMAT_MBOXRD:
947 		return split_mail_mbox(state, paths, keep_cr, 1);
948 	default:
949 		BUG("invalid patch_format");
950 	}
951 	return -1;
952 }
953 
954 /**
955  * Setup a new am session for applying patches
956  */
am_setup(struct am_state * state,enum patch_format patch_format,const char ** paths,int keep_cr)957 static void am_setup(struct am_state *state, enum patch_format patch_format,
958 			const char **paths, int keep_cr)
959 {
960 	struct object_id curr_head;
961 	const char *str;
962 	struct strbuf sb = STRBUF_INIT;
963 
964 	if (!patch_format)
965 		patch_format = detect_patch_format(paths);
966 
967 	if (!patch_format) {
968 		fprintf_ln(stderr, _("Patch format detection failed."));
969 		exit(128);
970 	}
971 
972 	if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
973 		die_errno(_("failed to create directory '%s'"), state->dir);
974 	delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
975 
976 	if (split_mail(state, patch_format, paths, keep_cr) < 0) {
977 		am_destroy(state);
978 		die(_("Failed to split patches."));
979 	}
980 
981 	if (state->rebasing)
982 		state->threeway = 1;
983 
984 	write_state_bool(state, "threeway", state->threeway);
985 	write_state_bool(state, "quiet", state->quiet);
986 	write_state_bool(state, "sign", state->signoff);
987 	write_state_bool(state, "utf8", state->utf8);
988 
989 	if (state->allow_rerere_autoupdate)
990 		write_state_bool(state, "rerere-autoupdate",
991 			 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
992 
993 	switch (state->keep) {
994 	case KEEP_FALSE:
995 		str = "f";
996 		break;
997 	case KEEP_TRUE:
998 		str = "t";
999 		break;
1000 	case KEEP_NON_PATCH:
1001 		str = "b";
1002 		break;
1003 	default:
1004 		BUG("invalid value for state->keep");
1005 	}
1006 
1007 	write_state_text(state, "keep", str);
1008 	write_state_bool(state, "messageid", state->message_id);
1009 
1010 	switch (state->scissors) {
1011 	case SCISSORS_UNSET:
1012 		str = "";
1013 		break;
1014 	case SCISSORS_FALSE:
1015 		str = "f";
1016 		break;
1017 	case SCISSORS_TRUE:
1018 		str = "t";
1019 		break;
1020 	default:
1021 		BUG("invalid value for state->scissors");
1022 	}
1023 	write_state_text(state, "scissors", str);
1024 
1025 	switch (state->quoted_cr) {
1026 	case quoted_cr_unset:
1027 		str = "";
1028 		break;
1029 	case quoted_cr_nowarn:
1030 		str = "nowarn";
1031 		break;
1032 	case quoted_cr_warn:
1033 		str = "warn";
1034 		break;
1035 	case quoted_cr_strip:
1036 		str = "strip";
1037 		break;
1038 	default:
1039 		BUG("invalid value for state->quoted_cr");
1040 	}
1041 	write_state_text(state, "quoted-cr", str);
1042 
1043 	sq_quote_argv(&sb, state->git_apply_opts.v);
1044 	write_state_text(state, "apply-opt", sb.buf);
1045 
1046 	if (state->rebasing)
1047 		write_state_text(state, "rebasing", "");
1048 	else
1049 		write_state_text(state, "applying", "");
1050 
1051 	if (!get_oid("HEAD", &curr_head)) {
1052 		write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1053 		if (!state->rebasing)
1054 			update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1055 				   UPDATE_REFS_DIE_ON_ERR);
1056 	} else {
1057 		write_state_text(state, "abort-safety", "");
1058 		if (!state->rebasing)
1059 			delete_ref(NULL, "ORIG_HEAD", NULL, 0);
1060 	}
1061 
1062 	/*
1063 	 * NOTE: Since the "next" and "last" files determine if an am_state
1064 	 * session is in progress, they should be written last.
1065 	 */
1066 
1067 	write_state_count(state, "next", state->cur);
1068 	write_state_count(state, "last", state->last);
1069 
1070 	strbuf_release(&sb);
1071 }
1072 
1073 /**
1074  * Increments the patch pointer, and cleans am_state for the application of the
1075  * next patch.
1076  */
am_next(struct am_state * state)1077 static void am_next(struct am_state *state)
1078 {
1079 	struct object_id head;
1080 
1081 	FREE_AND_NULL(state->author_name);
1082 	FREE_AND_NULL(state->author_email);
1083 	FREE_AND_NULL(state->author_date);
1084 	FREE_AND_NULL(state->msg);
1085 	state->msg_len = 0;
1086 
1087 	unlink(am_path(state, "author-script"));
1088 	unlink(am_path(state, "final-commit"));
1089 
1090 	oidclr(&state->orig_commit);
1091 	unlink(am_path(state, "original-commit"));
1092 	delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1093 
1094 	if (!get_oid("HEAD", &head))
1095 		write_state_text(state, "abort-safety", oid_to_hex(&head));
1096 	else
1097 		write_state_text(state, "abort-safety", "");
1098 
1099 	state->cur++;
1100 	write_state_count(state, "next", state->cur);
1101 }
1102 
1103 /**
1104  * Returns the filename of the current patch email.
1105  */
msgnum(const struct am_state * state)1106 static const char *msgnum(const struct am_state *state)
1107 {
1108 	static struct strbuf sb = STRBUF_INIT;
1109 
1110 	strbuf_reset(&sb);
1111 	strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1112 
1113 	return sb.buf;
1114 }
1115 
1116 /**
1117  * Dies with a user-friendly message on how to proceed after resolving the
1118  * problem. This message can be overridden with state->resolvemsg.
1119  */
die_user_resolve(const struct am_state * state)1120 static void NORETURN die_user_resolve(const struct am_state *state)
1121 {
1122 	if (state->resolvemsg) {
1123 		printf_ln("%s", state->resolvemsg);
1124 	} else {
1125 		const char *cmdline = state->interactive ? "git am -i" : "git am";
1126 
1127 		printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1128 		printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1129 		printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1130 	}
1131 
1132 	exit(128);
1133 }
1134 
1135 /**
1136  * Appends signoff to the "msg" field of the am_state.
1137  */
am_append_signoff(struct am_state * state)1138 static void am_append_signoff(struct am_state *state)
1139 {
1140 	struct strbuf sb = STRBUF_INIT;
1141 
1142 	strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1143 	append_signoff(&sb, 0, 0);
1144 	state->msg = strbuf_detach(&sb, &state->msg_len);
1145 }
1146 
1147 /**
1148  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1149  * state->msg will be set to the patch message. state->author_name,
1150  * state->author_email and state->author_date will be set to the patch author's
1151  * name, email and date respectively. The patch body will be written to the
1152  * state directory's "patch" file.
1153  *
1154  * Returns 1 if the patch should be skipped, 0 otherwise.
1155  */
parse_mail(struct am_state * state,const char * mail)1156 static int parse_mail(struct am_state *state, const char *mail)
1157 {
1158 	FILE *fp;
1159 	struct strbuf sb = STRBUF_INIT;
1160 	struct strbuf msg = STRBUF_INIT;
1161 	struct strbuf author_name = STRBUF_INIT;
1162 	struct strbuf author_date = STRBUF_INIT;
1163 	struct strbuf author_email = STRBUF_INIT;
1164 	int ret = 0;
1165 	struct mailinfo mi;
1166 
1167 	setup_mailinfo(&mi);
1168 
1169 	if (state->utf8)
1170 		mi.metainfo_charset = get_commit_output_encoding();
1171 	else
1172 		mi.metainfo_charset = NULL;
1173 
1174 	switch (state->keep) {
1175 	case KEEP_FALSE:
1176 		break;
1177 	case KEEP_TRUE:
1178 		mi.keep_subject = 1;
1179 		break;
1180 	case KEEP_NON_PATCH:
1181 		mi.keep_non_patch_brackets_in_subject = 1;
1182 		break;
1183 	default:
1184 		BUG("invalid value for state->keep");
1185 	}
1186 
1187 	if (state->message_id)
1188 		mi.add_message_id = 1;
1189 
1190 	switch (state->scissors) {
1191 	case SCISSORS_UNSET:
1192 		break;
1193 	case SCISSORS_FALSE:
1194 		mi.use_scissors = 0;
1195 		break;
1196 	case SCISSORS_TRUE:
1197 		mi.use_scissors = 1;
1198 		break;
1199 	default:
1200 		BUG("invalid value for state->scissors");
1201 	}
1202 
1203 	switch (state->quoted_cr) {
1204 	case quoted_cr_unset:
1205 		break;
1206 	case quoted_cr_nowarn:
1207 	case quoted_cr_warn:
1208 	case quoted_cr_strip:
1209 		mi.quoted_cr = state->quoted_cr;
1210 		break;
1211 	default:
1212 		BUG("invalid value for state->quoted_cr");
1213 	}
1214 
1215 	mi.input = xfopen(mail, "r");
1216 	mi.output = xfopen(am_path(state, "info"), "w");
1217 	if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1218 		die("could not parse patch");
1219 
1220 	fclose(mi.input);
1221 	fclose(mi.output);
1222 
1223 	if (mi.format_flowed)
1224 		warning(_("Patch sent with format=flowed; "
1225 			  "space at the end of lines might be lost."));
1226 
1227 	/* Extract message and author information */
1228 	fp = xfopen(am_path(state, "info"), "r");
1229 	while (!strbuf_getline_lf(&sb, fp)) {
1230 		const char *x;
1231 
1232 		if (skip_prefix(sb.buf, "Subject: ", &x)) {
1233 			if (msg.len)
1234 				strbuf_addch(&msg, '\n');
1235 			strbuf_addstr(&msg, x);
1236 		} else if (skip_prefix(sb.buf, "Author: ", &x))
1237 			strbuf_addstr(&author_name, x);
1238 		else if (skip_prefix(sb.buf, "Email: ", &x))
1239 			strbuf_addstr(&author_email, x);
1240 		else if (skip_prefix(sb.buf, "Date: ", &x))
1241 			strbuf_addstr(&author_date, x);
1242 	}
1243 	fclose(fp);
1244 
1245 	/* Skip pine's internal folder data */
1246 	if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1247 		ret = 1;
1248 		goto finish;
1249 	}
1250 
1251 	if (is_empty_or_missing_file(am_path(state, "patch"))) {
1252 		printf_ln(_("Patch is empty."));
1253 		die_user_resolve(state);
1254 	}
1255 
1256 	strbuf_addstr(&msg, "\n\n");
1257 	strbuf_addbuf(&msg, &mi.log_message);
1258 	strbuf_stripspace(&msg, 0);
1259 
1260 	assert(!state->author_name);
1261 	state->author_name = strbuf_detach(&author_name, NULL);
1262 
1263 	assert(!state->author_email);
1264 	state->author_email = strbuf_detach(&author_email, NULL);
1265 
1266 	assert(!state->author_date);
1267 	state->author_date = strbuf_detach(&author_date, NULL);
1268 
1269 	assert(!state->msg);
1270 	state->msg = strbuf_detach(&msg, &state->msg_len);
1271 
1272 finish:
1273 	strbuf_release(&msg);
1274 	strbuf_release(&author_date);
1275 	strbuf_release(&author_email);
1276 	strbuf_release(&author_name);
1277 	strbuf_release(&sb);
1278 	clear_mailinfo(&mi);
1279 	return ret;
1280 }
1281 
1282 /**
1283  * Sets commit_id to the commit hash where the mail was generated from.
1284  * Returns 0 on success, -1 on failure.
1285  */
get_mail_commit_oid(struct object_id * commit_id,const char * mail)1286 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1287 {
1288 	struct strbuf sb = STRBUF_INIT;
1289 	FILE *fp = xfopen(mail, "r");
1290 	const char *x;
1291 	int ret = 0;
1292 
1293 	if (strbuf_getline_lf(&sb, fp) ||
1294 	    !skip_prefix(sb.buf, "From ", &x) ||
1295 	    get_oid_hex(x, commit_id) < 0)
1296 		ret = -1;
1297 
1298 	strbuf_release(&sb);
1299 	fclose(fp);
1300 	return ret;
1301 }
1302 
1303 /**
1304  * Sets state->msg, state->author_name, state->author_email, state->author_date
1305  * to the commit's respective info.
1306  */
get_commit_info(struct am_state * state,struct commit * commit)1307 static void get_commit_info(struct am_state *state, struct commit *commit)
1308 {
1309 	const char *buffer, *ident_line, *msg;
1310 	size_t ident_len;
1311 	struct ident_split id;
1312 
1313 	buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1314 
1315 	ident_line = find_commit_header(buffer, "author", &ident_len);
1316 	if (!ident_line)
1317 		die(_("missing author line in commit %s"),
1318 		      oid_to_hex(&commit->object.oid));
1319 	if (split_ident_line(&id, ident_line, ident_len) < 0)
1320 		die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1321 
1322 	assert(!state->author_name);
1323 	if (id.name_begin)
1324 		state->author_name =
1325 			xmemdupz(id.name_begin, id.name_end - id.name_begin);
1326 	else
1327 		state->author_name = xstrdup("");
1328 
1329 	assert(!state->author_email);
1330 	if (id.mail_begin)
1331 		state->author_email =
1332 			xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1333 	else
1334 		state->author_email = xstrdup("");
1335 
1336 	assert(!state->author_date);
1337 	state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1338 
1339 	assert(!state->msg);
1340 	msg = strstr(buffer, "\n\n");
1341 	if (!msg)
1342 		die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1343 	state->msg = xstrdup(msg + 2);
1344 	state->msg_len = strlen(state->msg);
1345 	unuse_commit_buffer(commit, buffer);
1346 }
1347 
1348 /**
1349  * Writes `commit` as a patch to the state directory's "patch" file.
1350  */
write_commit_patch(const struct am_state * state,struct commit * commit)1351 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1352 {
1353 	struct rev_info rev_info;
1354 	FILE *fp;
1355 
1356 	fp = xfopen(am_path(state, "patch"), "w");
1357 	repo_init_revisions(the_repository, &rev_info, NULL);
1358 	rev_info.diff = 1;
1359 	rev_info.abbrev = 0;
1360 	rev_info.disable_stdin = 1;
1361 	rev_info.show_root_diff = 1;
1362 	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1363 	rev_info.no_commit_id = 1;
1364 	rev_info.diffopt.flags.binary = 1;
1365 	rev_info.diffopt.flags.full_index = 1;
1366 	rev_info.diffopt.use_color = 0;
1367 	rev_info.diffopt.file = fp;
1368 	rev_info.diffopt.close_file = 1;
1369 	add_pending_object(&rev_info, &commit->object, "");
1370 	diff_setup_done(&rev_info.diffopt);
1371 	log_tree_commit(&rev_info, commit);
1372 }
1373 
1374 /**
1375  * Writes the diff of the index against HEAD as a patch to the state
1376  * directory's "patch" file.
1377  */
write_index_patch(const struct am_state * state)1378 static void write_index_patch(const struct am_state *state)
1379 {
1380 	struct tree *tree;
1381 	struct object_id head;
1382 	struct rev_info rev_info;
1383 	FILE *fp;
1384 
1385 	if (!get_oid("HEAD", &head)) {
1386 		struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1387 		tree = get_commit_tree(commit);
1388 	} else
1389 		tree = lookup_tree(the_repository,
1390 				   the_repository->hash_algo->empty_tree);
1391 
1392 	fp = xfopen(am_path(state, "patch"), "w");
1393 	repo_init_revisions(the_repository, &rev_info, NULL);
1394 	rev_info.diff = 1;
1395 	rev_info.disable_stdin = 1;
1396 	rev_info.no_commit_id = 1;
1397 	rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1398 	rev_info.diffopt.use_color = 0;
1399 	rev_info.diffopt.file = fp;
1400 	rev_info.diffopt.close_file = 1;
1401 	add_pending_object(&rev_info, &tree->object, "");
1402 	diff_setup_done(&rev_info.diffopt);
1403 	run_diff_index(&rev_info, 1);
1404 }
1405 
1406 /**
1407  * Like parse_mail(), but parses the mail by looking up its commit ID
1408  * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1409  * of patches.
1410  *
1411  * state->orig_commit will be set to the original commit ID.
1412  *
1413  * Will always return 0 as the patch should never be skipped.
1414  */
parse_mail_rebase(struct am_state * state,const char * mail)1415 static int parse_mail_rebase(struct am_state *state, const char *mail)
1416 {
1417 	struct commit *commit;
1418 	struct object_id commit_oid;
1419 
1420 	if (get_mail_commit_oid(&commit_oid, mail) < 0)
1421 		die(_("could not parse %s"), mail);
1422 
1423 	commit = lookup_commit_or_die(&commit_oid, mail);
1424 
1425 	get_commit_info(state, commit);
1426 
1427 	write_commit_patch(state, commit);
1428 
1429 	oidcpy(&state->orig_commit, &commit_oid);
1430 	write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1431 	update_ref("am", "REBASE_HEAD", &commit_oid,
1432 		   NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1433 
1434 	return 0;
1435 }
1436 
1437 /**
1438  * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1439  * `index_file` is not NULL, the patch will be applied to that index.
1440  */
run_apply(const struct am_state * state,const char * index_file)1441 static int run_apply(const struct am_state *state, const char *index_file)
1442 {
1443 	struct strvec apply_paths = STRVEC_INIT;
1444 	struct strvec apply_opts = STRVEC_INIT;
1445 	struct apply_state apply_state;
1446 	int res, opts_left;
1447 	int force_apply = 0;
1448 	int options = 0;
1449 
1450 	if (init_apply_state(&apply_state, the_repository, NULL))
1451 		BUG("init_apply_state() failed");
1452 
1453 	strvec_push(&apply_opts, "apply");
1454 	strvec_pushv(&apply_opts, state->git_apply_opts.v);
1455 
1456 	opts_left = apply_parse_options(apply_opts.nr, apply_opts.v,
1457 					&apply_state, &force_apply, &options,
1458 					NULL);
1459 
1460 	if (opts_left != 0)
1461 		die("unknown option passed through to git apply");
1462 
1463 	if (index_file) {
1464 		apply_state.index_file = index_file;
1465 		apply_state.cached = 1;
1466 	} else
1467 		apply_state.check_index = 1;
1468 
1469 	/*
1470 	 * If we are allowed to fall back on 3-way merge, don't give false
1471 	 * errors during the initial attempt.
1472 	 */
1473 	if (state->threeway && !index_file)
1474 		apply_state.apply_verbosity = verbosity_silent;
1475 
1476 	if (check_apply_state(&apply_state, force_apply))
1477 		BUG("check_apply_state() failed");
1478 
1479 	strvec_push(&apply_paths, am_path(state, "patch"));
1480 
1481 	res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
1482 
1483 	strvec_clear(&apply_paths);
1484 	strvec_clear(&apply_opts);
1485 	clear_apply_state(&apply_state);
1486 
1487 	if (res)
1488 		return res;
1489 
1490 	if (index_file) {
1491 		/* Reload index as apply_all_patches() will have modified it. */
1492 		discard_cache();
1493 		read_cache_from(index_file);
1494 	}
1495 
1496 	return 0;
1497 }
1498 
1499 /**
1500  * Builds an index that contains just the blobs needed for a 3way merge.
1501  */
build_fake_ancestor(const struct am_state * state,const char * index_file)1502 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1503 {
1504 	struct child_process cp = CHILD_PROCESS_INIT;
1505 
1506 	cp.git_cmd = 1;
1507 	strvec_push(&cp.args, "apply");
1508 	strvec_pushv(&cp.args, state->git_apply_opts.v);
1509 	strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1510 	strvec_push(&cp.args, am_path(state, "patch"));
1511 
1512 	if (run_command(&cp))
1513 		return -1;
1514 
1515 	return 0;
1516 }
1517 
1518 /**
1519  * Attempt a threeway merge, using index_path as the temporary index.
1520  */
fall_back_threeway(const struct am_state * state,const char * index_path)1521 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1522 {
1523 	struct object_id orig_tree, their_tree, our_tree;
1524 	const struct object_id *bases[1] = { &orig_tree };
1525 	struct merge_options o;
1526 	struct commit *result;
1527 	char *their_tree_name;
1528 
1529 	if (get_oid("HEAD", &our_tree) < 0)
1530 		oidcpy(&our_tree, the_hash_algo->empty_tree);
1531 
1532 	if (build_fake_ancestor(state, index_path))
1533 		return error("could not build fake ancestor");
1534 
1535 	discard_cache();
1536 	read_cache_from(index_path);
1537 
1538 	if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
1539 		return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1540 
1541 	say(state, stdout, _("Using index info to reconstruct a base tree..."));
1542 
1543 	if (!state->quiet) {
1544 		/*
1545 		 * List paths that needed 3-way fallback, so that the user can
1546 		 * review them with extra care to spot mismerges.
1547 		 */
1548 		struct rev_info rev_info;
1549 
1550 		repo_init_revisions(the_repository, &rev_info, NULL);
1551 		rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1552 		rev_info.diffopt.filter |= diff_filter_bit('A');
1553 		rev_info.diffopt.filter |= diff_filter_bit('M');
1554 		add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1555 		diff_setup_done(&rev_info.diffopt);
1556 		run_diff_index(&rev_info, 1);
1557 	}
1558 
1559 	if (run_apply(state, index_path))
1560 		return error(_("Did you hand edit your patch?\n"
1561 				"It does not apply to blobs recorded in its index."));
1562 
1563 	if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
1564 		return error("could not write tree");
1565 
1566 	say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1567 
1568 	discard_cache();
1569 	read_cache();
1570 
1571 	/*
1572 	 * This is not so wrong. Depending on which base we picked, orig_tree
1573 	 * may be wildly different from ours, but their_tree has the same set of
1574 	 * wildly different changes in parts the patch did not touch, so
1575 	 * recursive ends up canceling them, saying that we reverted all those
1576 	 * changes.
1577 	 */
1578 
1579 	init_merge_options(&o, the_repository);
1580 
1581 	o.branch1 = "HEAD";
1582 	their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1583 	o.branch2 = their_tree_name;
1584 	o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
1585 
1586 	if (state->quiet)
1587 		o.verbosity = 0;
1588 
1589 	if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1590 		repo_rerere(the_repository, state->allow_rerere_autoupdate);
1591 		free(their_tree_name);
1592 		return error(_("Failed to merge in the changes."));
1593 	}
1594 
1595 	free(their_tree_name);
1596 	return 0;
1597 }
1598 
1599 /**
1600  * Commits the current index with state->msg as the commit message and
1601  * state->author_name, state->author_email and state->author_date as the author
1602  * information.
1603  */
do_commit(const struct am_state * state)1604 static void do_commit(const struct am_state *state)
1605 {
1606 	struct object_id tree, parent, commit;
1607 	const struct object_id *old_oid;
1608 	struct commit_list *parents = NULL;
1609 	const char *reflog_msg, *author, *committer = NULL;
1610 	struct strbuf sb = STRBUF_INIT;
1611 
1612 	if (run_hook_le(NULL, "pre-applypatch", NULL))
1613 		exit(1);
1614 
1615 	if (write_cache_as_tree(&tree, 0, NULL))
1616 		die(_("git write-tree failed to write a tree"));
1617 
1618 	if (!get_oid_commit("HEAD", &parent)) {
1619 		old_oid = &parent;
1620 		commit_list_insert(lookup_commit(the_repository, &parent),
1621 				   &parents);
1622 	} else {
1623 		old_oid = NULL;
1624 		say(state, stderr, _("applying to an empty history"));
1625 	}
1626 
1627 	author = fmt_ident(state->author_name, state->author_email,
1628 		WANT_AUTHOR_IDENT,
1629 			state->ignore_date ? NULL : state->author_date,
1630 			IDENT_STRICT);
1631 
1632 	if (state->committer_date_is_author_date)
1633 		committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1634 				      getenv("GIT_COMMITTER_EMAIL"),
1635 				      WANT_COMMITTER_IDENT,
1636 				      state->ignore_date ? NULL
1637 							 : state->author_date,
1638 				      IDENT_STRICT);
1639 
1640 	if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1641 				 &commit, author, committer, state->sign_commit,
1642 				 NULL))
1643 		die(_("failed to write commit object"));
1644 
1645 	reflog_msg = getenv("GIT_REFLOG_ACTION");
1646 	if (!reflog_msg)
1647 		reflog_msg = "am";
1648 
1649 	strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1650 			state->msg);
1651 
1652 	update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1653 		   UPDATE_REFS_DIE_ON_ERR);
1654 
1655 	if (state->rebasing) {
1656 		FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1657 
1658 		assert(!is_null_oid(&state->orig_commit));
1659 		fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1660 		fprintf(fp, "%s\n", oid_to_hex(&commit));
1661 		fclose(fp);
1662 	}
1663 
1664 	run_hook_le(NULL, "post-applypatch", NULL);
1665 
1666 	strbuf_release(&sb);
1667 }
1668 
1669 /**
1670  * Validates the am_state for resuming -- the "msg" and authorship fields must
1671  * be filled up.
1672  */
validate_resume_state(const struct am_state * state)1673 static void validate_resume_state(const struct am_state *state)
1674 {
1675 	if (!state->msg)
1676 		die(_("cannot resume: %s does not exist."),
1677 			am_path(state, "final-commit"));
1678 
1679 	if (!state->author_name || !state->author_email || !state->author_date)
1680 		die(_("cannot resume: %s does not exist."),
1681 			am_path(state, "author-script"));
1682 }
1683 
1684 /**
1685  * Interactively prompt the user on whether the current patch should be
1686  * applied.
1687  *
1688  * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1689  * skip it.
1690  */
do_interactive(struct am_state * state)1691 static int do_interactive(struct am_state *state)
1692 {
1693 	assert(state->msg);
1694 
1695 	for (;;) {
1696 		char reply[64];
1697 
1698 		puts(_("Commit Body is:"));
1699 		puts("--------------------------");
1700 		printf("%s", state->msg);
1701 		puts("--------------------------");
1702 
1703 		/*
1704 		 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1705 		 * in your translation. The program will only accept English
1706 		 * input at this point.
1707 		 */
1708 		printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1709 		if (!fgets(reply, sizeof(reply), stdin))
1710 			die("unable to read from stdin; aborting");
1711 
1712 		if (*reply == 'y' || *reply == 'Y') {
1713 			return 0;
1714 		} else if (*reply == 'a' || *reply == 'A') {
1715 			state->interactive = 0;
1716 			return 0;
1717 		} else if (*reply == 'n' || *reply == 'N') {
1718 			return 1;
1719 		} else if (*reply == 'e' || *reply == 'E') {
1720 			struct strbuf msg = STRBUF_INIT;
1721 
1722 			if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1723 				free(state->msg);
1724 				state->msg = strbuf_detach(&msg, &state->msg_len);
1725 			}
1726 			strbuf_release(&msg);
1727 		} else if (*reply == 'v' || *reply == 'V') {
1728 			const char *pager = git_pager(1);
1729 			struct child_process cp = CHILD_PROCESS_INIT;
1730 
1731 			if (!pager)
1732 				pager = "cat";
1733 			prepare_pager_args(&cp, pager);
1734 			strvec_push(&cp.args, am_path(state, "patch"));
1735 			run_command(&cp);
1736 		}
1737 	}
1738 }
1739 
1740 /**
1741  * Applies all queued mail.
1742  *
1743  * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1744  * well as the state directory's "patch" file is used as-is for applying the
1745  * patch and committing it.
1746  */
am_run(struct am_state * state,int resume)1747 static void am_run(struct am_state *state, int resume)
1748 {
1749 	struct strbuf sb = STRBUF_INIT;
1750 
1751 	unlink(am_path(state, "dirtyindex"));
1752 
1753 	if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0)
1754 		die(_("unable to write index file"));
1755 
1756 	if (repo_index_has_changes(the_repository, NULL, &sb)) {
1757 		write_state_bool(state, "dirtyindex", 1);
1758 		die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1759 	}
1760 
1761 	strbuf_release(&sb);
1762 
1763 	while (state->cur <= state->last) {
1764 		const char *mail = am_path(state, msgnum(state));
1765 		int apply_status;
1766 
1767 		reset_ident_date();
1768 
1769 		if (!file_exists(mail))
1770 			goto next;
1771 
1772 		if (resume) {
1773 			validate_resume_state(state);
1774 		} else {
1775 			int skip;
1776 
1777 			if (state->rebasing)
1778 				skip = parse_mail_rebase(state, mail);
1779 			else
1780 				skip = parse_mail(state, mail);
1781 
1782 			if (skip)
1783 				goto next; /* mail should be skipped */
1784 
1785 			if (state->signoff)
1786 				am_append_signoff(state);
1787 
1788 			write_author_script(state);
1789 			write_commit_msg(state);
1790 		}
1791 
1792 		if (state->interactive && do_interactive(state))
1793 			goto next;
1794 
1795 		if (run_applypatch_msg_hook(state))
1796 			exit(1);
1797 
1798 		say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1799 
1800 		apply_status = run_apply(state, NULL);
1801 
1802 		if (apply_status && state->threeway) {
1803 			struct strbuf sb = STRBUF_INIT;
1804 
1805 			strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1806 			apply_status = fall_back_threeway(state, sb.buf);
1807 			strbuf_release(&sb);
1808 
1809 			/*
1810 			 * Applying the patch to an earlier tree and merging
1811 			 * the result may have produced the same tree as ours.
1812 			 */
1813 			if (!apply_status &&
1814 			    !repo_index_has_changes(the_repository, NULL, NULL)) {
1815 				say(state, stdout, _("No changes -- Patch already applied."));
1816 				goto next;
1817 			}
1818 		}
1819 
1820 		if (apply_status) {
1821 			printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1822 				linelen(state->msg), state->msg);
1823 
1824 			if (advice_enabled(ADVICE_AM_WORK_DIR))
1825 				advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1826 
1827 			die_user_resolve(state);
1828 		}
1829 
1830 		do_commit(state);
1831 
1832 next:
1833 		am_next(state);
1834 
1835 		if (resume)
1836 			am_load(state);
1837 		resume = 0;
1838 	}
1839 
1840 	if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1841 		assert(state->rebasing);
1842 		copy_notes_for_rebase(state);
1843 		run_post_rewrite_hook(state);
1844 	}
1845 
1846 	/*
1847 	 * In rebasing mode, it's up to the caller to take care of
1848 	 * housekeeping.
1849 	 */
1850 	if (!state->rebasing) {
1851 		am_destroy(state);
1852 		run_auto_maintenance(state->quiet);
1853 	}
1854 }
1855 
1856 /**
1857  * Resume the current am session after patch application failure. The user did
1858  * all the hard work, and we do not have to do any patch application. Just
1859  * trust and commit what the user has in the index and working tree.
1860  */
am_resolve(struct am_state * state)1861 static void am_resolve(struct am_state *state)
1862 {
1863 	validate_resume_state(state);
1864 
1865 	say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1866 
1867 	if (!repo_index_has_changes(the_repository, NULL, NULL)) {
1868 		printf_ln(_("No changes - did you forget to use 'git add'?\n"
1869 			"If there is nothing left to stage, chances are that something else\n"
1870 			"already introduced the same changes; you might want to skip this patch."));
1871 		die_user_resolve(state);
1872 	}
1873 
1874 	if (unmerged_cache()) {
1875 		printf_ln(_("You still have unmerged paths in your index.\n"
1876 			"You should 'git add' each file with resolved conflicts to mark them as such.\n"
1877 			"You might run `git rm` on a file to accept \"deleted by them\" for it."));
1878 		die_user_resolve(state);
1879 	}
1880 
1881 	if (state->interactive) {
1882 		write_index_patch(state);
1883 		if (do_interactive(state))
1884 			goto next;
1885 	}
1886 
1887 	repo_rerere(the_repository, 0);
1888 
1889 	do_commit(state);
1890 
1891 next:
1892 	am_next(state);
1893 	am_load(state);
1894 	am_run(state, 0);
1895 }
1896 
1897 /**
1898  * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1899  * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1900  * failure.
1901  */
fast_forward_to(struct tree * head,struct tree * remote,int reset)1902 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1903 {
1904 	struct lock_file lock_file = LOCK_INIT;
1905 	struct unpack_trees_options opts;
1906 	struct tree_desc t[2];
1907 
1908 	if (parse_tree(head) || parse_tree(remote))
1909 		return -1;
1910 
1911 	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1912 
1913 	refresh_cache(REFRESH_QUIET);
1914 
1915 	memset(&opts, 0, sizeof(opts));
1916 	opts.head_idx = 1;
1917 	opts.src_index = &the_index;
1918 	opts.dst_index = &the_index;
1919 	opts.update = 1;
1920 	opts.merge = 1;
1921 	opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
1922 	opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
1923 	opts.fn = twoway_merge;
1924 	init_tree_desc(&t[0], head->buffer, head->size);
1925 	init_tree_desc(&t[1], remote->buffer, remote->size);
1926 
1927 	if (unpack_trees(2, t, &opts)) {
1928 		rollback_lock_file(&lock_file);
1929 		return -1;
1930 	}
1931 
1932 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1933 		die(_("unable to write new index file"));
1934 
1935 	return 0;
1936 }
1937 
1938 /**
1939  * Merges a tree into the index. The index's stat info will take precedence
1940  * over the merged tree's. Returns 0 on success, -1 on failure.
1941  */
merge_tree(struct tree * tree)1942 static int merge_tree(struct tree *tree)
1943 {
1944 	struct lock_file lock_file = LOCK_INIT;
1945 	struct unpack_trees_options opts;
1946 	struct tree_desc t[1];
1947 
1948 	if (parse_tree(tree))
1949 		return -1;
1950 
1951 	hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1952 
1953 	memset(&opts, 0, sizeof(opts));
1954 	opts.head_idx = 1;
1955 	opts.src_index = &the_index;
1956 	opts.dst_index = &the_index;
1957 	opts.merge = 1;
1958 	opts.fn = oneway_merge;
1959 	init_tree_desc(&t[0], tree->buffer, tree->size);
1960 
1961 	if (unpack_trees(1, t, &opts)) {
1962 		rollback_lock_file(&lock_file);
1963 		return -1;
1964 	}
1965 
1966 	if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1967 		die(_("unable to write new index file"));
1968 
1969 	return 0;
1970 }
1971 
1972 /**
1973  * Clean the index without touching entries that are not modified between
1974  * `head` and `remote`.
1975  */
clean_index(const struct object_id * head,const struct object_id * remote)1976 static int clean_index(const struct object_id *head, const struct object_id *remote)
1977 {
1978 	struct tree *head_tree, *remote_tree, *index_tree;
1979 	struct object_id index;
1980 
1981 	head_tree = parse_tree_indirect(head);
1982 	if (!head_tree)
1983 		return error(_("Could not parse object '%s'."), oid_to_hex(head));
1984 
1985 	remote_tree = parse_tree_indirect(remote);
1986 	if (!remote_tree)
1987 		return error(_("Could not parse object '%s'."), oid_to_hex(remote));
1988 
1989 	read_cache_unmerged();
1990 
1991 	if (fast_forward_to(head_tree, head_tree, 1))
1992 		return -1;
1993 
1994 	if (write_cache_as_tree(&index, 0, NULL))
1995 		return -1;
1996 
1997 	index_tree = parse_tree_indirect(&index);
1998 	if (!index_tree)
1999 		return error(_("Could not parse object '%s'."), oid_to_hex(&index));
2000 
2001 	if (fast_forward_to(index_tree, remote_tree, 0))
2002 		return -1;
2003 
2004 	if (merge_tree(remote_tree))
2005 		return -1;
2006 
2007 	remove_branch_state(the_repository, 0);
2008 
2009 	return 0;
2010 }
2011 
2012 /**
2013  * Resets rerere's merge resolution metadata.
2014  */
am_rerere_clear(void)2015 static void am_rerere_clear(void)
2016 {
2017 	struct string_list merge_rr = STRING_LIST_INIT_DUP;
2018 	rerere_clear(the_repository, &merge_rr);
2019 	string_list_clear(&merge_rr, 1);
2020 }
2021 
2022 /**
2023  * Resume the current am session by skipping the current patch.
2024  */
am_skip(struct am_state * state)2025 static void am_skip(struct am_state *state)
2026 {
2027 	struct object_id head;
2028 
2029 	am_rerere_clear();
2030 
2031 	if (get_oid("HEAD", &head))
2032 		oidcpy(&head, the_hash_algo->empty_tree);
2033 
2034 	if (clean_index(&head, &head))
2035 		die(_("failed to clean index"));
2036 
2037 	if (state->rebasing) {
2038 		FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2039 
2040 		assert(!is_null_oid(&state->orig_commit));
2041 		fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2042 		fprintf(fp, "%s\n", oid_to_hex(&head));
2043 		fclose(fp);
2044 	}
2045 
2046 	am_next(state);
2047 	am_load(state);
2048 	am_run(state, 0);
2049 }
2050 
2051 /**
2052  * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2053  *
2054  * It is not safe to reset HEAD when:
2055  * 1. git-am previously failed because the index was dirty.
2056  * 2. HEAD has moved since git-am previously failed.
2057  */
safe_to_abort(const struct am_state * state)2058 static int safe_to_abort(const struct am_state *state)
2059 {
2060 	struct strbuf sb = STRBUF_INIT;
2061 	struct object_id abort_safety, head;
2062 
2063 	if (file_exists(am_path(state, "dirtyindex")))
2064 		return 0;
2065 
2066 	if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2067 		if (get_oid_hex(sb.buf, &abort_safety))
2068 			die(_("could not parse %s"), am_path(state, "abort-safety"));
2069 	} else
2070 		oidclr(&abort_safety);
2071 	strbuf_release(&sb);
2072 
2073 	if (get_oid("HEAD", &head))
2074 		oidclr(&head);
2075 
2076 	if (oideq(&head, &abort_safety))
2077 		return 1;
2078 
2079 	warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2080 		"Not rewinding to ORIG_HEAD"));
2081 
2082 	return 0;
2083 }
2084 
2085 /**
2086  * Aborts the current am session if it is safe to do so.
2087  */
am_abort(struct am_state * state)2088 static void am_abort(struct am_state *state)
2089 {
2090 	struct object_id curr_head, orig_head;
2091 	int has_curr_head, has_orig_head;
2092 	char *curr_branch;
2093 
2094 	if (!safe_to_abort(state)) {
2095 		am_destroy(state);
2096 		return;
2097 	}
2098 
2099 	am_rerere_clear();
2100 
2101 	curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2102 	has_curr_head = curr_branch && !is_null_oid(&curr_head);
2103 	if (!has_curr_head)
2104 		oidcpy(&curr_head, the_hash_algo->empty_tree);
2105 
2106 	has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
2107 	if (!has_orig_head)
2108 		oidcpy(&orig_head, the_hash_algo->empty_tree);
2109 
2110 	if (clean_index(&curr_head, &orig_head))
2111 		die(_("failed to clean index"));
2112 
2113 	if (has_orig_head)
2114 		update_ref("am --abort", "HEAD", &orig_head,
2115 			   has_curr_head ? &curr_head : NULL, 0,
2116 			   UPDATE_REFS_DIE_ON_ERR);
2117 	else if (curr_branch)
2118 		delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
2119 
2120 	free(curr_branch);
2121 	am_destroy(state);
2122 }
2123 
show_patch(struct am_state * state,enum show_patch_type sub_mode)2124 static int show_patch(struct am_state *state, enum show_patch_type sub_mode)
2125 {
2126 	struct strbuf sb = STRBUF_INIT;
2127 	const char *patch_path;
2128 	int len;
2129 
2130 	if (!is_null_oid(&state->orig_commit)) {
2131 		const char *av[4] = { "show", NULL, "--", NULL };
2132 		char *new_oid_str;
2133 		int ret;
2134 
2135 		av[1] = new_oid_str = xstrdup(oid_to_hex(&state->orig_commit));
2136 		ret = run_command_v_opt(av, RUN_GIT_CMD);
2137 		free(new_oid_str);
2138 		return ret;
2139 	}
2140 
2141 	switch (sub_mode) {
2142 	case SHOW_PATCH_RAW:
2143 		patch_path = am_path(state, msgnum(state));
2144 		break;
2145 	case SHOW_PATCH_DIFF:
2146 		patch_path = am_path(state, "patch");
2147 		break;
2148 	default:
2149 		BUG("invalid mode for --show-current-patch");
2150 	}
2151 
2152 	len = strbuf_read_file(&sb, patch_path, 0);
2153 	if (len < 0)
2154 		die_errno(_("failed to read '%s'"), patch_path);
2155 
2156 	setup_pager();
2157 	write_in_full(1, sb.buf, sb.len);
2158 	strbuf_release(&sb);
2159 	return 0;
2160 }
2161 
2162 /**
2163  * parse_options() callback that validates and sets opt->value to the
2164  * PATCH_FORMAT_* enum value corresponding to `arg`.
2165  */
parse_opt_patchformat(const struct option * opt,const char * arg,int unset)2166 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2167 {
2168 	int *opt_value = opt->value;
2169 
2170 	if (unset)
2171 		*opt_value = PATCH_FORMAT_UNKNOWN;
2172 	else if (!strcmp(arg, "mbox"))
2173 		*opt_value = PATCH_FORMAT_MBOX;
2174 	else if (!strcmp(arg, "stgit"))
2175 		*opt_value = PATCH_FORMAT_STGIT;
2176 	else if (!strcmp(arg, "stgit-series"))
2177 		*opt_value = PATCH_FORMAT_STGIT_SERIES;
2178 	else if (!strcmp(arg, "hg"))
2179 		*opt_value = PATCH_FORMAT_HG;
2180 	else if (!strcmp(arg, "mboxrd"))
2181 		*opt_value = PATCH_FORMAT_MBOXRD;
2182 	/*
2183 	 * Please update $__git_patchformat in git-completion.bash
2184 	 * when you add new options
2185 	 */
2186 	else
2187 		return error(_("Invalid value for --patch-format: %s"), arg);
2188 	return 0;
2189 }
2190 
2191 enum resume_type {
2192 	RESUME_FALSE = 0,
2193 	RESUME_APPLY,
2194 	RESUME_RESOLVED,
2195 	RESUME_SKIP,
2196 	RESUME_ABORT,
2197 	RESUME_QUIT,
2198 	RESUME_SHOW_PATCH
2199 };
2200 
2201 struct resume_mode {
2202 	enum resume_type mode;
2203 	enum show_patch_type sub_mode;
2204 };
2205 
parse_opt_show_current_patch(const struct option * opt,const char * arg,int unset)2206 static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2207 {
2208 	int *opt_value = opt->value;
2209 	struct resume_mode *resume = container_of(opt_value, struct resume_mode, mode);
2210 
2211 	/*
2212 	 * Please update $__git_showcurrentpatch in git-completion.bash
2213 	 * when you add new options
2214 	 */
2215 	const char *valid_modes[] = {
2216 		[SHOW_PATCH_DIFF] = "diff",
2217 		[SHOW_PATCH_RAW] = "raw"
2218 	};
2219 	int new_value = SHOW_PATCH_RAW;
2220 
2221 	BUG_ON_OPT_NEG(unset);
2222 
2223 	if (arg) {
2224 		for (new_value = 0; new_value < ARRAY_SIZE(valid_modes); new_value++) {
2225 			if (!strcmp(arg, valid_modes[new_value]))
2226 				break;
2227 		}
2228 		if (new_value >= ARRAY_SIZE(valid_modes))
2229 			return error(_("Invalid value for --show-current-patch: %s"), arg);
2230 	}
2231 
2232 	if (resume->mode == RESUME_SHOW_PATCH && new_value != resume->sub_mode)
2233 		return error(_("--show-current-patch=%s is incompatible with "
2234 			       "--show-current-patch=%s"),
2235 			     arg, valid_modes[resume->sub_mode]);
2236 
2237 	resume->mode = RESUME_SHOW_PATCH;
2238 	resume->sub_mode = new_value;
2239 	return 0;
2240 }
2241 
git_am_config(const char * k,const char * v,void * cb)2242 static int git_am_config(const char *k, const char *v, void *cb)
2243 {
2244 	int status;
2245 
2246 	status = git_gpg_config(k, v, NULL);
2247 	if (status)
2248 		return status;
2249 
2250 	return git_default_config(k, v, NULL);
2251 }
2252 
cmd_am(int argc,const char ** argv,const char * prefix)2253 int cmd_am(int argc, const char **argv, const char *prefix)
2254 {
2255 	struct am_state state;
2256 	int binary = -1;
2257 	int keep_cr = -1;
2258 	int patch_format = PATCH_FORMAT_UNKNOWN;
2259 	struct resume_mode resume = { .mode = RESUME_FALSE };
2260 	int in_progress;
2261 	int ret = 0;
2262 
2263 	const char * const usage[] = {
2264 		N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2265 		N_("git am [<options>] (--continue | --skip | --abort)"),
2266 		NULL
2267 	};
2268 
2269 	struct option options[] = {
2270 		OPT_BOOL('i', "interactive", &state.interactive,
2271 			N_("run interactively")),
2272 		OPT_HIDDEN_BOOL('b', "binary", &binary,
2273 			N_("historical option -- no-op")),
2274 		OPT_BOOL('3', "3way", &state.threeway,
2275 			N_("allow fall back on 3way merging if needed")),
2276 		OPT__QUIET(&state.quiet, N_("be quiet")),
2277 		OPT_SET_INT('s', "signoff", &state.signoff,
2278 			N_("add a Signed-off-by trailer to the commit message"),
2279 			SIGNOFF_EXPLICIT),
2280 		OPT_BOOL('u', "utf8", &state.utf8,
2281 			N_("recode into utf8 (default)")),
2282 		OPT_SET_INT('k', "keep", &state.keep,
2283 			N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2284 		OPT_SET_INT(0, "keep-non-patch", &state.keep,
2285 			N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2286 		OPT_BOOL('m', "message-id", &state.message_id,
2287 			N_("pass -m flag to git-mailinfo")),
2288 		OPT_SET_INT_F(0, "keep-cr", &keep_cr,
2289 			N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2290 			1, PARSE_OPT_NONEG),
2291 		OPT_SET_INT_F(0, "no-keep-cr", &keep_cr,
2292 			N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2293 			0, PARSE_OPT_NONEG),
2294 		OPT_BOOL('c', "scissors", &state.scissors,
2295 			N_("strip everything before a scissors line")),
2296 		OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2297 			       N_("pass it through git-mailinfo"),
2298 			       PARSE_OPT_NONEG, am_option_parse_quoted_cr),
2299 		OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2300 			N_("pass it through git-apply"),
2301 			0),
2302 		OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2303 			N_("pass it through git-apply"),
2304 			PARSE_OPT_NOARG),
2305 		OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2306 			N_("pass it through git-apply"),
2307 			PARSE_OPT_NOARG),
2308 		OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2309 			N_("pass it through git-apply"),
2310 			0),
2311 		OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2312 			N_("pass it through git-apply"),
2313 			0),
2314 		OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2315 			N_("pass it through git-apply"),
2316 			0),
2317 		OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2318 			N_("pass it through git-apply"),
2319 			0),
2320 		OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2321 			N_("pass it through git-apply"),
2322 			0),
2323 		OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2324 			N_("format the patch(es) are in"),
2325 			parse_opt_patchformat),
2326 		OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2327 			N_("pass it through git-apply"),
2328 			PARSE_OPT_NOARG),
2329 		OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2330 			N_("override error message when patch failure occurs")),
2331 		OPT_CMDMODE(0, "continue", &resume.mode,
2332 			N_("continue applying patches after resolving a conflict"),
2333 			RESUME_RESOLVED),
2334 		OPT_CMDMODE('r', "resolved", &resume.mode,
2335 			N_("synonyms for --continue"),
2336 			RESUME_RESOLVED),
2337 		OPT_CMDMODE(0, "skip", &resume.mode,
2338 			N_("skip the current patch"),
2339 			RESUME_SKIP),
2340 		OPT_CMDMODE(0, "abort", &resume.mode,
2341 			N_("restore the original branch and abort the patching operation"),
2342 			RESUME_ABORT),
2343 		OPT_CMDMODE(0, "quit", &resume.mode,
2344 			N_("abort the patching operation but keep HEAD where it is"),
2345 			RESUME_QUIT),
2346 		{ OPTION_CALLBACK, 0, "show-current-patch", &resume.mode,
2347 		  "(diff|raw)",
2348 		  N_("show the patch being applied"),
2349 		  PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2350 		  parse_opt_show_current_patch, RESUME_SHOW_PATCH },
2351 		OPT_BOOL(0, "committer-date-is-author-date",
2352 			&state.committer_date_is_author_date,
2353 			N_("lie about committer date")),
2354 		OPT_BOOL(0, "ignore-date", &state.ignore_date,
2355 			N_("use current timestamp for author date")),
2356 		OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2357 		{ OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2358 		  N_("GPG-sign commits"),
2359 		  PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2360 		OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2361 			N_("(internal use for git-rebase)")),
2362 		OPT_END()
2363 	};
2364 
2365 	if (argc == 2 && !strcmp(argv[1], "-h"))
2366 		usage_with_options(usage, options);
2367 
2368 	git_config(git_am_config, NULL);
2369 
2370 	am_state_init(&state);
2371 
2372 	in_progress = am_in_progress(&state);
2373 	if (in_progress)
2374 		am_load(&state);
2375 
2376 	argc = parse_options(argc, argv, prefix, options, usage, 0);
2377 
2378 	if (binary >= 0)
2379 		fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2380 				"it will be removed. Please do not use it anymore."));
2381 
2382 	/* Ensure a valid committer ident can be constructed */
2383 	git_committer_info(IDENT_STRICT);
2384 
2385 	if (repo_read_index_preload(the_repository, NULL, 0) < 0)
2386 		die(_("failed to read the index"));
2387 
2388 	if (in_progress) {
2389 		/*
2390 		 * Catch user error to feed us patches when there is a session
2391 		 * in progress:
2392 		 *
2393 		 * 1. mbox path(s) are provided on the command-line.
2394 		 * 2. stdin is not a tty: the user is trying to feed us a patch
2395 		 *    from standard input. This is somewhat unreliable -- stdin
2396 		 *    could be /dev/null for example and the caller did not
2397 		 *    intend to feed us a patch but wanted to continue
2398 		 *    unattended.
2399 		 */
2400 		if (argc || (resume.mode == RESUME_FALSE && !isatty(0)))
2401 			die(_("previous rebase directory %s still exists but mbox given."),
2402 				state.dir);
2403 
2404 		if (resume.mode == RESUME_FALSE)
2405 			resume.mode = RESUME_APPLY;
2406 
2407 		if (state.signoff == SIGNOFF_EXPLICIT)
2408 			am_append_signoff(&state);
2409 	} else {
2410 		struct strvec paths = STRVEC_INIT;
2411 		int i;
2412 
2413 		/*
2414 		 * Handle stray state directory in the independent-run case. In
2415 		 * the --rebasing case, it is up to the caller to take care of
2416 		 * stray directories.
2417 		 */
2418 		if (file_exists(state.dir) && !state.rebasing) {
2419 			if (resume.mode == RESUME_ABORT || resume.mode == RESUME_QUIT) {
2420 				am_destroy(&state);
2421 				am_state_release(&state);
2422 				return 0;
2423 			}
2424 
2425 			die(_("Stray %s directory found.\n"
2426 				"Use \"git am --abort\" to remove it."),
2427 				state.dir);
2428 		}
2429 
2430 		if (resume.mode)
2431 			die(_("Resolve operation not in progress, we are not resuming."));
2432 
2433 		for (i = 0; i < argc; i++) {
2434 			if (is_absolute_path(argv[i]) || !prefix)
2435 				strvec_push(&paths, argv[i]);
2436 			else
2437 				strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2438 		}
2439 
2440 		if (state.interactive && !paths.nr)
2441 			die(_("interactive mode requires patches on the command line"));
2442 
2443 		am_setup(&state, patch_format, paths.v, keep_cr);
2444 
2445 		strvec_clear(&paths);
2446 	}
2447 
2448 	switch (resume.mode) {
2449 	case RESUME_FALSE:
2450 		am_run(&state, 0);
2451 		break;
2452 	case RESUME_APPLY:
2453 		am_run(&state, 1);
2454 		break;
2455 	case RESUME_RESOLVED:
2456 		am_resolve(&state);
2457 		break;
2458 	case RESUME_SKIP:
2459 		am_skip(&state);
2460 		break;
2461 	case RESUME_ABORT:
2462 		am_abort(&state);
2463 		break;
2464 	case RESUME_QUIT:
2465 		am_rerere_clear();
2466 		am_destroy(&state);
2467 		break;
2468 	case RESUME_SHOW_PATCH:
2469 		ret = show_patch(&state, resume.sub_mode);
2470 		break;
2471 	default:
2472 		BUG("invalid resume value");
2473 	}
2474 
2475 	am_state_release(&state);
2476 
2477 	return ret;
2478 }
2479