First batch for 2.11
[git.git] / builtin / am.c
blobb36d1f047d8124e3aeab5fabb24dd2bb2a003fdf
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
6 #include "cache.h"
7 #include "builtin.h"
8 #include "exec_cmd.h"
9 #include "parse-options.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "quote.h"
13 #include "tempfile.h"
14 #include "lockfile.h"
15 #include "cache-tree.h"
16 #include "refs.h"
17 #include "commit.h"
18 #include "diff.h"
19 #include "diffcore.h"
20 #include "unpack-trees.h"
21 #include "branch.h"
22 #include "sequencer.h"
23 #include "revision.h"
24 #include "merge-recursive.h"
25 #include "revision.h"
26 #include "log-tree.h"
27 #include "notes-utils.h"
28 #include "rerere.h"
29 #include "prompt.h"
30 #include "mailinfo.h"
31 #include "string-list.h"
33 /**
34 * Returns 1 if the file is empty or does not exist, 0 otherwise.
36 static int is_empty_file(const char *filename)
38 struct stat st;
40 if (stat(filename, &st) < 0) {
41 if (errno == ENOENT)
42 return 1;
43 die_errno(_("could not stat %s"), filename);
46 return !st.st_size;
49 /**
50 * Returns the length of the first line of msg.
52 static int linelen(const char *msg)
54 return strchrnul(msg, '\n') - msg;
57 /**
58 * Returns true if `str` consists of only whitespace, false otherwise.
60 static int str_isspace(const char *str)
62 for (; *str; str++)
63 if (!isspace(*str))
64 return 0;
66 return 1;
69 enum patch_format {
70 PATCH_FORMAT_UNKNOWN = 0,
71 PATCH_FORMAT_MBOX,
72 PATCH_FORMAT_STGIT,
73 PATCH_FORMAT_STGIT_SERIES,
74 PATCH_FORMAT_HG,
75 PATCH_FORMAT_MBOXRD
78 enum keep_type {
79 KEEP_FALSE = 0,
80 KEEP_TRUE, /* pass -k flag to git-mailinfo */
81 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
84 enum scissors_type {
85 SCISSORS_UNSET = -1,
86 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
87 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
90 enum signoff_type {
91 SIGNOFF_FALSE = 0,
92 SIGNOFF_TRUE = 1,
93 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
96 struct am_state {
97 /* state directory path */
98 char *dir;
100 /* current and last patch numbers, 1-indexed */
101 int cur;
102 int last;
104 /* commit metadata and message */
105 char *author_name;
106 char *author_email;
107 char *author_date;
108 char *msg;
109 size_t msg_len;
111 /* when --rebasing, records the original commit the patch came from */
112 unsigned char orig_commit[GIT_SHA1_RAWSZ];
114 /* number of digits in patch filename */
115 int prec;
117 /* various operating modes and command line options */
118 int interactive;
119 int threeway;
120 int quiet;
121 int signoff; /* enum signoff_type */
122 int utf8;
123 int keep; /* enum keep_type */
124 int message_id;
125 int scissors; /* enum scissors_type */
126 struct argv_array git_apply_opts;
127 const char *resolvemsg;
128 int committer_date_is_author_date;
129 int ignore_date;
130 int allow_rerere_autoupdate;
131 const char *sign_commit;
132 int rebasing;
136 * Initializes am_state with the default values. The state directory is set to
137 * dir.
139 static void am_state_init(struct am_state *state, const char *dir)
141 int gpgsign;
143 memset(state, 0, sizeof(*state));
145 assert(dir);
146 state->dir = xstrdup(dir);
148 state->prec = 4;
150 git_config_get_bool("am.threeway", &state->threeway);
152 state->utf8 = 1;
154 git_config_get_bool("am.messageid", &state->message_id);
156 state->scissors = SCISSORS_UNSET;
158 argv_array_init(&state->git_apply_opts);
160 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
161 state->sign_commit = gpgsign ? "" : NULL;
165 * Releases memory allocated by an am_state.
167 static void am_state_release(struct am_state *state)
169 free(state->dir);
170 free(state->author_name);
171 free(state->author_email);
172 free(state->author_date);
173 free(state->msg);
174 argv_array_clear(&state->git_apply_opts);
178 * Returns path relative to the am_state directory.
180 static inline const char *am_path(const struct am_state *state, const char *path)
182 return mkpath("%s/%s", state->dir, path);
186 * For convenience to call write_file()
188 static void write_state_text(const struct am_state *state,
189 const char *name, const char *string)
191 write_file(am_path(state, name), "%s", string);
194 static void write_state_count(const struct am_state *state,
195 const char *name, int value)
197 write_file(am_path(state, name), "%d", value);
200 static void write_state_bool(const struct am_state *state,
201 const char *name, int value)
203 write_state_text(state, name, value ? "t" : "f");
207 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
208 * at the end.
210 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
212 va_list ap;
214 va_start(ap, fmt);
215 if (!state->quiet) {
216 vfprintf(fp, fmt, ap);
217 putc('\n', fp);
219 va_end(ap);
223 * Returns 1 if there is an am session in progress, 0 otherwise.
225 static int am_in_progress(const struct am_state *state)
227 struct stat st;
229 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
230 return 0;
231 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
232 return 0;
233 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
234 return 0;
235 return 1;
239 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
240 * number of bytes read on success, -1 if the file does not exist. If `trim` is
241 * set, trailing whitespace will be removed.
243 static int read_state_file(struct strbuf *sb, const struct am_state *state,
244 const char *file, int trim)
246 strbuf_reset(sb);
248 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
249 if (trim)
250 strbuf_trim(sb);
252 return sb->len;
255 if (errno == ENOENT)
256 return -1;
258 die_errno(_("could not read '%s'"), am_path(state, file));
262 * Take a series of KEY='VALUE' lines where VALUE part is
263 * sq-quoted, and append <KEY, VALUE> at the end of the string list
265 static int parse_key_value_squoted(char *buf, struct string_list *list)
267 while (*buf) {
268 struct string_list_item *item;
269 char *np;
270 char *cp = strchr(buf, '=');
271 if (!cp)
272 return -1;
273 np = strchrnul(cp, '\n');
274 *cp++ = '\0';
275 item = string_list_append(list, buf);
277 buf = np + (*np == '\n');
278 *np = '\0';
279 cp = sq_dequote(cp);
280 if (!cp)
281 return -1;
282 item->util = xstrdup(cp);
284 return 0;
288 * Reads and parses the state directory's "author-script" file, and sets
289 * state->author_name, state->author_email and state->author_date accordingly.
290 * Returns 0 on success, -1 if the file could not be parsed.
292 * The author script is of the format:
294 * GIT_AUTHOR_NAME='$author_name'
295 * GIT_AUTHOR_EMAIL='$author_email'
296 * GIT_AUTHOR_DATE='$author_date'
298 * where $author_name, $author_email and $author_date are quoted. We are strict
299 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
300 * script, and thus if the file differs from what this function expects, it is
301 * better to bail out than to do something that the user does not expect.
303 static int read_author_script(struct am_state *state)
305 const char *filename = am_path(state, "author-script");
306 struct strbuf buf = STRBUF_INIT;
307 struct string_list kv = STRING_LIST_INIT_DUP;
308 int retval = -1; /* assume failure */
309 int fd;
311 assert(!state->author_name);
312 assert(!state->author_email);
313 assert(!state->author_date);
315 fd = open(filename, O_RDONLY);
316 if (fd < 0) {
317 if (errno == ENOENT)
318 return 0;
319 die_errno(_("could not open '%s' for reading"), filename);
321 strbuf_read(&buf, fd, 0);
322 close(fd);
323 if (parse_key_value_squoted(buf.buf, &kv))
324 goto finish;
326 if (kv.nr != 3 ||
327 strcmp(kv.items[0].string, "GIT_AUTHOR_NAME") ||
328 strcmp(kv.items[1].string, "GIT_AUTHOR_EMAIL") ||
329 strcmp(kv.items[2].string, "GIT_AUTHOR_DATE"))
330 goto finish;
331 state->author_name = kv.items[0].util;
332 state->author_email = kv.items[1].util;
333 state->author_date = kv.items[2].util;
334 retval = 0;
335 finish:
336 string_list_clear(&kv, !!retval);
337 strbuf_release(&buf);
338 return retval;
342 * Saves state->author_name, state->author_email and state->author_date in the
343 * state directory's "author-script" file.
345 static void write_author_script(const struct am_state *state)
347 struct strbuf sb = STRBUF_INIT;
349 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
350 sq_quote_buf(&sb, state->author_name);
351 strbuf_addch(&sb, '\n');
353 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
354 sq_quote_buf(&sb, state->author_email);
355 strbuf_addch(&sb, '\n');
357 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
358 sq_quote_buf(&sb, state->author_date);
359 strbuf_addch(&sb, '\n');
361 write_state_text(state, "author-script", sb.buf);
363 strbuf_release(&sb);
367 * Reads the commit message from the state directory's "final-commit" file,
368 * setting state->msg to its contents and state->msg_len to the length of its
369 * contents in bytes.
371 * Returns 0 on success, -1 if the file does not exist.
373 static int read_commit_msg(struct am_state *state)
375 struct strbuf sb = STRBUF_INIT;
377 assert(!state->msg);
379 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
380 strbuf_release(&sb);
381 return -1;
384 state->msg = strbuf_detach(&sb, &state->msg_len);
385 return 0;
389 * Saves state->msg in the state directory's "final-commit" file.
391 static void write_commit_msg(const struct am_state *state)
393 const char *filename = am_path(state, "final-commit");
394 write_file_buf(filename, state->msg, state->msg_len);
398 * Loads state from disk.
400 static void am_load(struct am_state *state)
402 struct strbuf sb = STRBUF_INIT;
404 if (read_state_file(&sb, state, "next", 1) < 0)
405 die("BUG: state file 'next' does not exist");
406 state->cur = strtol(sb.buf, NULL, 10);
408 if (read_state_file(&sb, state, "last", 1) < 0)
409 die("BUG: state file 'last' does not exist");
410 state->last = strtol(sb.buf, NULL, 10);
412 if (read_author_script(state) < 0)
413 die(_("could not parse author script"));
415 read_commit_msg(state);
417 if (read_state_file(&sb, state, "original-commit", 1) < 0)
418 hashclr(state->orig_commit);
419 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
420 die(_("could not parse %s"), am_path(state, "original-commit"));
422 read_state_file(&sb, state, "threeway", 1);
423 state->threeway = !strcmp(sb.buf, "t");
425 read_state_file(&sb, state, "quiet", 1);
426 state->quiet = !strcmp(sb.buf, "t");
428 read_state_file(&sb, state, "sign", 1);
429 state->signoff = !strcmp(sb.buf, "t");
431 read_state_file(&sb, state, "utf8", 1);
432 state->utf8 = !strcmp(sb.buf, "t");
434 read_state_file(&sb, state, "keep", 1);
435 if (!strcmp(sb.buf, "t"))
436 state->keep = KEEP_TRUE;
437 else if (!strcmp(sb.buf, "b"))
438 state->keep = KEEP_NON_PATCH;
439 else
440 state->keep = KEEP_FALSE;
442 read_state_file(&sb, state, "messageid", 1);
443 state->message_id = !strcmp(sb.buf, "t");
445 read_state_file(&sb, state, "scissors", 1);
446 if (!strcmp(sb.buf, "t"))
447 state->scissors = SCISSORS_TRUE;
448 else if (!strcmp(sb.buf, "f"))
449 state->scissors = SCISSORS_FALSE;
450 else
451 state->scissors = SCISSORS_UNSET;
453 read_state_file(&sb, state, "apply-opt", 1);
454 argv_array_clear(&state->git_apply_opts);
455 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
456 die(_("could not parse %s"), am_path(state, "apply-opt"));
458 state->rebasing = !!file_exists(am_path(state, "rebasing"));
460 strbuf_release(&sb);
464 * Removes the am_state directory, forcefully terminating the current am
465 * session.
467 static void am_destroy(const struct am_state *state)
469 struct strbuf sb = STRBUF_INIT;
471 strbuf_addstr(&sb, state->dir);
472 remove_dir_recursively(&sb, 0);
473 strbuf_release(&sb);
477 * Runs applypatch-msg hook. Returns its exit code.
479 static int run_applypatch_msg_hook(struct am_state *state)
481 int ret;
483 assert(state->msg);
484 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
486 if (!ret) {
487 free(state->msg);
488 state->msg = NULL;
489 if (read_commit_msg(state) < 0)
490 die(_("'%s' was deleted by the applypatch-msg hook"),
491 am_path(state, "final-commit"));
494 return ret;
498 * Runs post-rewrite hook. Returns it exit code.
500 static int run_post_rewrite_hook(const struct am_state *state)
502 struct child_process cp = CHILD_PROCESS_INIT;
503 const char *hook = find_hook("post-rewrite");
504 int ret;
506 if (!hook)
507 return 0;
509 argv_array_push(&cp.args, hook);
510 argv_array_push(&cp.args, "rebase");
512 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
513 cp.stdout_to_stderr = 1;
515 ret = run_command(&cp);
517 close(cp.in);
518 return ret;
522 * Reads the state directory's "rewritten" file, and copies notes from the old
523 * commits listed in the file to their rewritten commits.
525 * Returns 0 on success, -1 on failure.
527 static int copy_notes_for_rebase(const struct am_state *state)
529 struct notes_rewrite_cfg *c;
530 struct strbuf sb = STRBUF_INIT;
531 const char *invalid_line = _("Malformed input line: '%s'.");
532 const char *msg = "Notes added by 'git rebase'";
533 FILE *fp;
534 int ret = 0;
536 assert(state->rebasing);
538 c = init_copy_notes_for_rewrite("rebase");
539 if (!c)
540 return 0;
542 fp = xfopen(am_path(state, "rewritten"), "r");
544 while (!strbuf_getline_lf(&sb, fp)) {
545 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
547 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
548 ret = error(invalid_line, sb.buf);
549 goto finish;
552 if (get_sha1_hex(sb.buf, from_obj)) {
553 ret = error(invalid_line, sb.buf);
554 goto finish;
557 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
558 ret = error(invalid_line, sb.buf);
559 goto finish;
562 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
563 ret = error(invalid_line, sb.buf);
564 goto finish;
567 if (copy_note_for_rewrite(c, from_obj, to_obj))
568 ret = error(_("Failed to copy notes from '%s' to '%s'"),
569 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
572 finish:
573 finish_copy_notes_for_rewrite(c, msg);
574 fclose(fp);
575 strbuf_release(&sb);
576 return ret;
580 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
581 * non-indented lines and checking if they look like they begin with valid
582 * header field names.
584 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
586 static int is_mail(FILE *fp)
588 const char *header_regex = "^[!-9;-~]+:";
589 struct strbuf sb = STRBUF_INIT;
590 regex_t regex;
591 int ret = 1;
593 if (fseek(fp, 0L, SEEK_SET))
594 die_errno(_("fseek failed"));
596 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
597 die("invalid pattern: %s", header_regex);
599 while (!strbuf_getline(&sb, fp)) {
600 if (!sb.len)
601 break; /* End of header */
603 /* Ignore indented folded lines */
604 if (*sb.buf == '\t' || *sb.buf == ' ')
605 continue;
607 /* It's a header if it matches header_regex */
608 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
609 ret = 0;
610 goto done;
614 done:
615 regfree(&regex);
616 strbuf_release(&sb);
617 return ret;
621 * Attempts to detect the patch_format of the patches contained in `paths`,
622 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
623 * detection fails.
625 static int detect_patch_format(const char **paths)
627 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
628 struct strbuf l1 = STRBUF_INIT;
629 struct strbuf l2 = STRBUF_INIT;
630 struct strbuf l3 = STRBUF_INIT;
631 FILE *fp;
634 * We default to mbox format if input is from stdin and for directories
636 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
637 return PATCH_FORMAT_MBOX;
640 * Otherwise, check the first few lines of the first patch, starting
641 * from the first non-blank line, to try to detect its format.
644 fp = xfopen(*paths, "r");
646 while (!strbuf_getline(&l1, fp)) {
647 if (l1.len)
648 break;
651 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
652 ret = PATCH_FORMAT_MBOX;
653 goto done;
656 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
657 ret = PATCH_FORMAT_STGIT_SERIES;
658 goto done;
661 if (!strcmp(l1.buf, "# HG changeset patch")) {
662 ret = PATCH_FORMAT_HG;
663 goto done;
666 strbuf_reset(&l2);
667 strbuf_getline(&l2, fp);
668 strbuf_reset(&l3);
669 strbuf_getline(&l3, fp);
672 * If the second line is empty and the third is a From, Author or Date
673 * entry, this is likely an StGit patch.
675 if (l1.len && !l2.len &&
676 (starts_with(l3.buf, "From:") ||
677 starts_with(l3.buf, "Author:") ||
678 starts_with(l3.buf, "Date:"))) {
679 ret = PATCH_FORMAT_STGIT;
680 goto done;
683 if (l1.len && is_mail(fp)) {
684 ret = PATCH_FORMAT_MBOX;
685 goto done;
688 done:
689 fclose(fp);
690 strbuf_release(&l1);
691 return ret;
695 * Splits out individual email patches from `paths`, where each path is either
696 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
698 static int split_mail_mbox(struct am_state *state, const char **paths,
699 int keep_cr, int mboxrd)
701 struct child_process cp = CHILD_PROCESS_INIT;
702 struct strbuf last = STRBUF_INIT;
704 cp.git_cmd = 1;
705 argv_array_push(&cp.args, "mailsplit");
706 argv_array_pushf(&cp.args, "-d%d", state->prec);
707 argv_array_pushf(&cp.args, "-o%s", state->dir);
708 argv_array_push(&cp.args, "-b");
709 if (keep_cr)
710 argv_array_push(&cp.args, "--keep-cr");
711 if (mboxrd)
712 argv_array_push(&cp.args, "--mboxrd");
713 argv_array_push(&cp.args, "--");
714 argv_array_pushv(&cp.args, paths);
716 if (capture_command(&cp, &last, 8))
717 return -1;
719 state->cur = 1;
720 state->last = strtol(last.buf, NULL, 10);
722 return 0;
726 * Callback signature for split_mail_conv(). The foreign patch should be
727 * read from `in`, and the converted patch (in RFC2822 mail format) should be
728 * written to `out`. Return 0 on success, or -1 on failure.
730 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
733 * Calls `fn` for each file in `paths` to convert the foreign patch to the
734 * RFC2822 mail format suitable for parsing with git-mailinfo.
736 * Returns 0 on success, -1 on failure.
738 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
739 const char **paths, int keep_cr)
741 static const char *stdin_only[] = {"-", NULL};
742 int i;
744 if (!*paths)
745 paths = stdin_only;
747 for (i = 0; *paths; paths++, i++) {
748 FILE *in, *out;
749 const char *mail;
750 int ret;
752 if (!strcmp(*paths, "-"))
753 in = stdin;
754 else
755 in = fopen(*paths, "r");
757 if (!in)
758 return error_errno(_("could not open '%s' for reading"),
759 *paths);
761 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
763 out = fopen(mail, "w");
764 if (!out)
765 return error_errno(_("could not open '%s' for writing"),
766 mail);
768 ret = fn(out, in, keep_cr);
770 fclose(out);
771 fclose(in);
773 if (ret)
774 return error(_("could not parse patch '%s'"), *paths);
777 state->cur = 1;
778 state->last = i;
779 return 0;
783 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
784 * message suitable for parsing with git-mailinfo.
786 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
788 struct strbuf sb = STRBUF_INIT;
789 int subject_printed = 0;
791 while (!strbuf_getline_lf(&sb, in)) {
792 const char *str;
794 if (str_isspace(sb.buf))
795 continue;
796 else if (skip_prefix(sb.buf, "Author:", &str))
797 fprintf(out, "From:%s\n", str);
798 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
799 fprintf(out, "%s\n", sb.buf);
800 else if (!subject_printed) {
801 fprintf(out, "Subject: %s\n", sb.buf);
802 subject_printed = 1;
803 } else {
804 fprintf(out, "\n%s\n", sb.buf);
805 break;
809 strbuf_reset(&sb);
810 while (strbuf_fread(&sb, 8192, in) > 0) {
811 fwrite(sb.buf, 1, sb.len, out);
812 strbuf_reset(&sb);
815 strbuf_release(&sb);
816 return 0;
820 * This function only supports a single StGit series file in `paths`.
822 * Given an StGit series file, converts the StGit patches in the series into
823 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
824 * the state directory.
826 * Returns 0 on success, -1 on failure.
828 static int split_mail_stgit_series(struct am_state *state, const char **paths,
829 int keep_cr)
831 const char *series_dir;
832 char *series_dir_buf;
833 FILE *fp;
834 struct argv_array patches = ARGV_ARRAY_INIT;
835 struct strbuf sb = STRBUF_INIT;
836 int ret;
838 if (!paths[0] || paths[1])
839 return error(_("Only one StGIT patch series can be applied at once"));
841 series_dir_buf = xstrdup(*paths);
842 series_dir = dirname(series_dir_buf);
844 fp = fopen(*paths, "r");
845 if (!fp)
846 return error_errno(_("could not open '%s' for reading"), *paths);
848 while (!strbuf_getline_lf(&sb, fp)) {
849 if (*sb.buf == '#')
850 continue; /* skip comment lines */
852 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
855 fclose(fp);
856 strbuf_release(&sb);
857 free(series_dir_buf);
859 ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
861 argv_array_clear(&patches);
862 return ret;
866 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
867 * message suitable for parsing with git-mailinfo.
869 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
871 struct strbuf sb = STRBUF_INIT;
873 while (!strbuf_getline_lf(&sb, in)) {
874 const char *str;
876 if (skip_prefix(sb.buf, "# User ", &str))
877 fprintf(out, "From: %s\n", str);
878 else if (skip_prefix(sb.buf, "# Date ", &str)) {
879 unsigned long timestamp;
880 long tz, tz2;
881 char *end;
883 errno = 0;
884 timestamp = strtoul(str, &end, 10);
885 if (errno)
886 return error(_("invalid timestamp"));
888 if (!skip_prefix(end, " ", &str))
889 return error(_("invalid Date line"));
891 errno = 0;
892 tz = strtol(str, &end, 10);
893 if (errno)
894 return error(_("invalid timezone offset"));
896 if (*end)
897 return error(_("invalid Date line"));
900 * mercurial's timezone is in seconds west of UTC,
901 * however git's timezone is in hours + minutes east of
902 * UTC. Convert it.
904 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
905 if (tz > 0)
906 tz2 = -tz2;
908 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
909 } else if (starts_with(sb.buf, "# ")) {
910 continue;
911 } else {
912 fprintf(out, "\n%s\n", sb.buf);
913 break;
917 strbuf_reset(&sb);
918 while (strbuf_fread(&sb, 8192, in) > 0) {
919 fwrite(sb.buf, 1, sb.len, out);
920 strbuf_reset(&sb);
923 strbuf_release(&sb);
924 return 0;
928 * Splits a list of files/directories into individual email patches. Each path
929 * in `paths` must be a file/directory that is formatted according to
930 * `patch_format`.
932 * Once split out, the individual email patches will be stored in the state
933 * directory, with each patch's filename being its index, padded to state->prec
934 * digits.
936 * state->cur will be set to the index of the first mail, and state->last will
937 * be set to the index of the last mail.
939 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
940 * to disable this behavior, -1 to use the default configured setting.
942 * Returns 0 on success, -1 on failure.
944 static int split_mail(struct am_state *state, enum patch_format patch_format,
945 const char **paths, int keep_cr)
947 if (keep_cr < 0) {
948 keep_cr = 0;
949 git_config_get_bool("am.keepcr", &keep_cr);
952 switch (patch_format) {
953 case PATCH_FORMAT_MBOX:
954 return split_mail_mbox(state, paths, keep_cr, 0);
955 case PATCH_FORMAT_STGIT:
956 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
957 case PATCH_FORMAT_STGIT_SERIES:
958 return split_mail_stgit_series(state, paths, keep_cr);
959 case PATCH_FORMAT_HG:
960 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
961 case PATCH_FORMAT_MBOXRD:
962 return split_mail_mbox(state, paths, keep_cr, 1);
963 default:
964 die("BUG: invalid patch_format");
966 return -1;
970 * Setup a new am session for applying patches
972 static void am_setup(struct am_state *state, enum patch_format patch_format,
973 const char **paths, int keep_cr)
975 unsigned char curr_head[GIT_SHA1_RAWSZ];
976 const char *str;
977 struct strbuf sb = STRBUF_INIT;
979 if (!patch_format)
980 patch_format = detect_patch_format(paths);
982 if (!patch_format) {
983 fprintf_ln(stderr, _("Patch format detection failed."));
984 exit(128);
987 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
988 die_errno(_("failed to create directory '%s'"), state->dir);
990 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
991 am_destroy(state);
992 die(_("Failed to split patches."));
995 if (state->rebasing)
996 state->threeway = 1;
998 write_state_bool(state, "threeway", state->threeway);
999 write_state_bool(state, "quiet", state->quiet);
1000 write_state_bool(state, "sign", state->signoff);
1001 write_state_bool(state, "utf8", state->utf8);
1003 switch (state->keep) {
1004 case KEEP_FALSE:
1005 str = "f";
1006 break;
1007 case KEEP_TRUE:
1008 str = "t";
1009 break;
1010 case KEEP_NON_PATCH:
1011 str = "b";
1012 break;
1013 default:
1014 die("BUG: invalid value for state->keep");
1017 write_state_text(state, "keep", str);
1018 write_state_bool(state, "messageid", state->message_id);
1020 switch (state->scissors) {
1021 case SCISSORS_UNSET:
1022 str = "";
1023 break;
1024 case SCISSORS_FALSE:
1025 str = "f";
1026 break;
1027 case SCISSORS_TRUE:
1028 str = "t";
1029 break;
1030 default:
1031 die("BUG: invalid value for state->scissors");
1033 write_state_text(state, "scissors", str);
1035 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1036 write_state_text(state, "apply-opt", sb.buf);
1038 if (state->rebasing)
1039 write_state_text(state, "rebasing", "");
1040 else
1041 write_state_text(state, "applying", "");
1043 if (!get_sha1("HEAD", curr_head)) {
1044 write_state_text(state, "abort-safety", sha1_to_hex(curr_head));
1045 if (!state->rebasing)
1046 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
1047 UPDATE_REFS_DIE_ON_ERR);
1048 } else {
1049 write_state_text(state, "abort-safety", "");
1050 if (!state->rebasing)
1051 delete_ref("ORIG_HEAD", NULL, 0);
1055 * NOTE: Since the "next" and "last" files determine if an am_state
1056 * session is in progress, they should be written last.
1059 write_state_count(state, "next", state->cur);
1060 write_state_count(state, "last", state->last);
1062 strbuf_release(&sb);
1066 * Increments the patch pointer, and cleans am_state for the application of the
1067 * next patch.
1069 static void am_next(struct am_state *state)
1071 unsigned char head[GIT_SHA1_RAWSZ];
1073 free(state->author_name);
1074 state->author_name = NULL;
1076 free(state->author_email);
1077 state->author_email = NULL;
1079 free(state->author_date);
1080 state->author_date = NULL;
1082 free(state->msg);
1083 state->msg = NULL;
1084 state->msg_len = 0;
1086 unlink(am_path(state, "author-script"));
1087 unlink(am_path(state, "final-commit"));
1089 hashclr(state->orig_commit);
1090 unlink(am_path(state, "original-commit"));
1092 if (!get_sha1("HEAD", head))
1093 write_state_text(state, "abort-safety", sha1_to_hex(head));
1094 else
1095 write_state_text(state, "abort-safety", "");
1097 state->cur++;
1098 write_state_count(state, "next", state->cur);
1102 * Returns the filename of the current patch email.
1104 static const char *msgnum(const struct am_state *state)
1106 static struct strbuf sb = STRBUF_INIT;
1108 strbuf_reset(&sb);
1109 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1111 return sb.buf;
1115 * Refresh and write index.
1117 static void refresh_and_write_cache(void)
1119 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1121 hold_locked_index(lock_file, 1);
1122 refresh_cache(REFRESH_QUIET);
1123 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1124 die(_("unable to write index file"));
1128 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1129 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1130 * strbuf is provided, the space-separated list of files that differ will be
1131 * appended to it.
1133 static int index_has_changes(struct strbuf *sb)
1135 unsigned char head[GIT_SHA1_RAWSZ];
1136 int i;
1138 if (!get_sha1_tree("HEAD", head)) {
1139 struct diff_options opt;
1141 diff_setup(&opt);
1142 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
1143 if (!sb)
1144 DIFF_OPT_SET(&opt, QUICK);
1145 do_diff_cache(head, &opt);
1146 diffcore_std(&opt);
1147 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1148 if (i)
1149 strbuf_addch(sb, ' ');
1150 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1152 diff_flush(&opt);
1153 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
1154 } else {
1155 for (i = 0; sb && i < active_nr; i++) {
1156 if (i)
1157 strbuf_addch(sb, ' ');
1158 strbuf_addstr(sb, active_cache[i]->name);
1160 return !!active_nr;
1165 * Dies with a user-friendly message on how to proceed after resolving the
1166 * problem. This message can be overridden with state->resolvemsg.
1168 static void NORETURN die_user_resolve(const struct am_state *state)
1170 if (state->resolvemsg) {
1171 printf_ln("%s", state->resolvemsg);
1172 } else {
1173 const char *cmdline = state->interactive ? "git am -i" : "git am";
1175 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1176 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1177 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1180 exit(128);
1183 static void am_signoff(struct strbuf *sb)
1185 char *cp;
1186 struct strbuf mine = STRBUF_INIT;
1188 /* Does it end with our own sign-off? */
1189 strbuf_addf(&mine, "\n%s%s\n",
1190 sign_off_header,
1191 fmt_name(getenv("GIT_COMMITTER_NAME"),
1192 getenv("GIT_COMMITTER_EMAIL")));
1193 if (mine.len < sb->len &&
1194 !strcmp(mine.buf, sb->buf + sb->len - mine.len))
1195 goto exit; /* no need to duplicate */
1197 /* Does it have any Signed-off-by: in the text */
1198 for (cp = sb->buf;
1199 cp && *cp && (cp = strstr(cp, sign_off_header)) != NULL;
1200 cp = strchr(cp, '\n')) {
1201 if (sb->buf == cp || cp[-1] == '\n')
1202 break;
1205 strbuf_addstr(sb, mine.buf + !!cp);
1206 exit:
1207 strbuf_release(&mine);
1211 * Appends signoff to the "msg" field of the am_state.
1213 static void am_append_signoff(struct am_state *state)
1215 struct strbuf sb = STRBUF_INIT;
1217 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1218 am_signoff(&sb);
1219 state->msg = strbuf_detach(&sb, &state->msg_len);
1223 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1224 * state->msg will be set to the patch message. state->author_name,
1225 * state->author_email and state->author_date will be set to the patch author's
1226 * name, email and date respectively. The patch body will be written to the
1227 * state directory's "patch" file.
1229 * Returns 1 if the patch should be skipped, 0 otherwise.
1231 static int parse_mail(struct am_state *state, const char *mail)
1233 FILE *fp;
1234 struct strbuf sb = STRBUF_INIT;
1235 struct strbuf msg = STRBUF_INIT;
1236 struct strbuf author_name = STRBUF_INIT;
1237 struct strbuf author_date = STRBUF_INIT;
1238 struct strbuf author_email = STRBUF_INIT;
1239 int ret = 0;
1240 struct mailinfo mi;
1242 setup_mailinfo(&mi);
1244 if (state->utf8)
1245 mi.metainfo_charset = get_commit_output_encoding();
1246 else
1247 mi.metainfo_charset = NULL;
1249 switch (state->keep) {
1250 case KEEP_FALSE:
1251 break;
1252 case KEEP_TRUE:
1253 mi.keep_subject = 1;
1254 break;
1255 case KEEP_NON_PATCH:
1256 mi.keep_non_patch_brackets_in_subject = 1;
1257 break;
1258 default:
1259 die("BUG: invalid value for state->keep");
1262 if (state->message_id)
1263 mi.add_message_id = 1;
1265 switch (state->scissors) {
1266 case SCISSORS_UNSET:
1267 break;
1268 case SCISSORS_FALSE:
1269 mi.use_scissors = 0;
1270 break;
1271 case SCISSORS_TRUE:
1272 mi.use_scissors = 1;
1273 break;
1274 default:
1275 die("BUG: invalid value for state->scissors");
1278 mi.input = fopen(mail, "r");
1279 if (!mi.input)
1280 die("could not open input");
1281 mi.output = fopen(am_path(state, "info"), "w");
1282 if (!mi.output)
1283 die("could not open output 'info'");
1284 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1285 die("could not parse patch");
1287 fclose(mi.input);
1288 fclose(mi.output);
1290 /* Extract message and author information */
1291 fp = xfopen(am_path(state, "info"), "r");
1292 while (!strbuf_getline_lf(&sb, fp)) {
1293 const char *x;
1295 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1296 if (msg.len)
1297 strbuf_addch(&msg, '\n');
1298 strbuf_addstr(&msg, x);
1299 } else if (skip_prefix(sb.buf, "Author: ", &x))
1300 strbuf_addstr(&author_name, x);
1301 else if (skip_prefix(sb.buf, "Email: ", &x))
1302 strbuf_addstr(&author_email, x);
1303 else if (skip_prefix(sb.buf, "Date: ", &x))
1304 strbuf_addstr(&author_date, x);
1306 fclose(fp);
1308 /* Skip pine's internal folder data */
1309 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1310 ret = 1;
1311 goto finish;
1314 if (is_empty_file(am_path(state, "patch"))) {
1315 printf_ln(_("Patch is empty. Was it split wrong?"));
1316 die_user_resolve(state);
1319 strbuf_addstr(&msg, "\n\n");
1320 strbuf_addbuf(&msg, &mi.log_message);
1321 strbuf_stripspace(&msg, 0);
1323 if (state->signoff)
1324 am_signoff(&msg);
1326 assert(!state->author_name);
1327 state->author_name = strbuf_detach(&author_name, NULL);
1329 assert(!state->author_email);
1330 state->author_email = strbuf_detach(&author_email, NULL);
1332 assert(!state->author_date);
1333 state->author_date = strbuf_detach(&author_date, NULL);
1335 assert(!state->msg);
1336 state->msg = strbuf_detach(&msg, &state->msg_len);
1338 finish:
1339 strbuf_release(&msg);
1340 strbuf_release(&author_date);
1341 strbuf_release(&author_email);
1342 strbuf_release(&author_name);
1343 strbuf_release(&sb);
1344 clear_mailinfo(&mi);
1345 return ret;
1349 * Sets commit_id to the commit hash where the mail was generated from.
1350 * Returns 0 on success, -1 on failure.
1352 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1354 struct strbuf sb = STRBUF_INIT;
1355 FILE *fp = xfopen(mail, "r");
1356 const char *x;
1358 if (strbuf_getline_lf(&sb, fp))
1359 return -1;
1361 if (!skip_prefix(sb.buf, "From ", &x))
1362 return -1;
1364 if (get_sha1_hex(x, commit_id) < 0)
1365 return -1;
1367 strbuf_release(&sb);
1368 fclose(fp);
1369 return 0;
1373 * Sets state->msg, state->author_name, state->author_email, state->author_date
1374 * to the commit's respective info.
1376 static void get_commit_info(struct am_state *state, struct commit *commit)
1378 const char *buffer, *ident_line, *author_date, *msg;
1379 size_t ident_len;
1380 struct ident_split ident_split;
1381 struct strbuf sb = STRBUF_INIT;
1383 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1385 ident_line = find_commit_header(buffer, "author", &ident_len);
1387 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1388 strbuf_add(&sb, ident_line, ident_len);
1389 die(_("invalid ident line: %s"), sb.buf);
1392 assert(!state->author_name);
1393 if (ident_split.name_begin) {
1394 strbuf_add(&sb, ident_split.name_begin,
1395 ident_split.name_end - ident_split.name_begin);
1396 state->author_name = strbuf_detach(&sb, NULL);
1397 } else
1398 state->author_name = xstrdup("");
1400 assert(!state->author_email);
1401 if (ident_split.mail_begin) {
1402 strbuf_add(&sb, ident_split.mail_begin,
1403 ident_split.mail_end - ident_split.mail_begin);
1404 state->author_email = strbuf_detach(&sb, NULL);
1405 } else
1406 state->author_email = xstrdup("");
1408 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1409 strbuf_addstr(&sb, author_date);
1410 assert(!state->author_date);
1411 state->author_date = strbuf_detach(&sb, NULL);
1413 assert(!state->msg);
1414 msg = strstr(buffer, "\n\n");
1415 if (!msg)
1416 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1417 state->msg = xstrdup(msg + 2);
1418 state->msg_len = strlen(state->msg);
1422 * Writes `commit` as a patch to the state directory's "patch" file.
1424 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1426 struct rev_info rev_info;
1427 FILE *fp;
1429 fp = xfopen(am_path(state, "patch"), "w");
1430 init_revisions(&rev_info, NULL);
1431 rev_info.diff = 1;
1432 rev_info.abbrev = 0;
1433 rev_info.disable_stdin = 1;
1434 rev_info.show_root_diff = 1;
1435 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1436 rev_info.no_commit_id = 1;
1437 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1438 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1439 rev_info.diffopt.use_color = 0;
1440 rev_info.diffopt.file = fp;
1441 rev_info.diffopt.close_file = 1;
1442 add_pending_object(&rev_info, &commit->object, "");
1443 diff_setup_done(&rev_info.diffopt);
1444 log_tree_commit(&rev_info, commit);
1448 * Writes the diff of the index against HEAD as a patch to the state
1449 * directory's "patch" file.
1451 static void write_index_patch(const struct am_state *state)
1453 struct tree *tree;
1454 unsigned char head[GIT_SHA1_RAWSZ];
1455 struct rev_info rev_info;
1456 FILE *fp;
1458 if (!get_sha1_tree("HEAD", head))
1459 tree = lookup_tree(head);
1460 else
1461 tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
1463 fp = xfopen(am_path(state, "patch"), "w");
1464 init_revisions(&rev_info, NULL);
1465 rev_info.diff = 1;
1466 rev_info.disable_stdin = 1;
1467 rev_info.no_commit_id = 1;
1468 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1469 rev_info.diffopt.use_color = 0;
1470 rev_info.diffopt.file = fp;
1471 rev_info.diffopt.close_file = 1;
1472 add_pending_object(&rev_info, &tree->object, "");
1473 diff_setup_done(&rev_info.diffopt);
1474 run_diff_index(&rev_info, 1);
1478 * Like parse_mail(), but parses the mail by looking up its commit ID
1479 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1480 * of patches.
1482 * state->orig_commit will be set to the original commit ID.
1484 * Will always return 0 as the patch should never be skipped.
1486 static int parse_mail_rebase(struct am_state *state, const char *mail)
1488 struct commit *commit;
1489 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1491 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1492 die(_("could not parse %s"), mail);
1494 commit = lookup_commit_or_die(commit_sha1, mail);
1496 get_commit_info(state, commit);
1498 write_commit_patch(state, commit);
1500 hashcpy(state->orig_commit, commit_sha1);
1501 write_state_text(state, "original-commit", sha1_to_hex(commit_sha1));
1503 return 0;
1507 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1508 * `index_file` is not NULL, the patch will be applied to that index.
1510 static int run_apply(const struct am_state *state, const char *index_file)
1512 struct child_process cp = CHILD_PROCESS_INIT;
1514 cp.git_cmd = 1;
1516 if (index_file)
1517 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1520 * If we are allowed to fall back on 3-way merge, don't give false
1521 * errors during the initial attempt.
1523 if (state->threeway && !index_file) {
1524 cp.no_stdout = 1;
1525 cp.no_stderr = 1;
1528 argv_array_push(&cp.args, "apply");
1530 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1532 if (index_file)
1533 argv_array_push(&cp.args, "--cached");
1534 else
1535 argv_array_push(&cp.args, "--index");
1537 argv_array_push(&cp.args, am_path(state, "patch"));
1539 if (run_command(&cp))
1540 return -1;
1542 /* Reload index as git-apply will have modified it. */
1543 discard_cache();
1544 read_cache_from(index_file ? index_file : get_index_file());
1546 return 0;
1550 * Builds an index that contains just the blobs needed for a 3way merge.
1552 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1554 struct child_process cp = CHILD_PROCESS_INIT;
1556 cp.git_cmd = 1;
1557 argv_array_push(&cp.args, "apply");
1558 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1559 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1560 argv_array_push(&cp.args, am_path(state, "patch"));
1562 if (run_command(&cp))
1563 return -1;
1565 return 0;
1569 * Attempt a threeway merge, using index_path as the temporary index.
1571 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1573 struct object_id orig_tree, their_tree, our_tree;
1574 const struct object_id *bases[1] = { &orig_tree };
1575 struct merge_options o;
1576 struct commit *result;
1577 char *their_tree_name;
1579 if (get_oid("HEAD", &our_tree) < 0)
1580 hashcpy(our_tree.hash, EMPTY_TREE_SHA1_BIN);
1582 if (build_fake_ancestor(state, index_path))
1583 return error("could not build fake ancestor");
1585 discard_cache();
1586 read_cache_from(index_path);
1588 if (write_index_as_tree(orig_tree.hash, &the_index, index_path, 0, NULL))
1589 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1591 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1593 if (!state->quiet) {
1595 * List paths that needed 3-way fallback, so that the user can
1596 * review them with extra care to spot mismerges.
1598 struct rev_info rev_info;
1599 const char *diff_filter_str = "--diff-filter=AM";
1601 init_revisions(&rev_info, NULL);
1602 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1603 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1604 add_pending_sha1(&rev_info, "HEAD", our_tree.hash, 0);
1605 diff_setup_done(&rev_info.diffopt);
1606 run_diff_index(&rev_info, 1);
1609 if (run_apply(state, index_path))
1610 return error(_("Did you hand edit your patch?\n"
1611 "It does not apply to blobs recorded in its index."));
1613 if (write_index_as_tree(their_tree.hash, &the_index, index_path, 0, NULL))
1614 return error("could not write tree");
1616 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1618 discard_cache();
1619 read_cache();
1622 * This is not so wrong. Depending on which base we picked, orig_tree
1623 * may be wildly different from ours, but their_tree has the same set of
1624 * wildly different changes in parts the patch did not touch, so
1625 * recursive ends up canceling them, saying that we reverted all those
1626 * changes.
1629 init_merge_options(&o);
1631 o.branch1 = "HEAD";
1632 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1633 o.branch2 = their_tree_name;
1635 if (state->quiet)
1636 o.verbosity = 0;
1638 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1639 rerere(state->allow_rerere_autoupdate);
1640 free(their_tree_name);
1641 return error(_("Failed to merge in the changes."));
1644 free(their_tree_name);
1645 return 0;
1649 * Commits the current index with state->msg as the commit message and
1650 * state->author_name, state->author_email and state->author_date as the author
1651 * information.
1653 static void do_commit(const struct am_state *state)
1655 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1656 commit[GIT_SHA1_RAWSZ];
1657 unsigned char *ptr;
1658 struct commit_list *parents = NULL;
1659 const char *reflog_msg, *author;
1660 struct strbuf sb = STRBUF_INIT;
1662 if (run_hook_le(NULL, "pre-applypatch", NULL))
1663 exit(1);
1665 if (write_cache_as_tree(tree, 0, NULL))
1666 die(_("git write-tree failed to write a tree"));
1668 if (!get_sha1_commit("HEAD", parent)) {
1669 ptr = parent;
1670 commit_list_insert(lookup_commit(parent), &parents);
1671 } else {
1672 ptr = NULL;
1673 say(state, stderr, _("applying to an empty history"));
1676 author = fmt_ident(state->author_name, state->author_email,
1677 state->ignore_date ? NULL : state->author_date,
1678 IDENT_STRICT);
1680 if (state->committer_date_is_author_date)
1681 setenv("GIT_COMMITTER_DATE",
1682 state->ignore_date ? "" : state->author_date, 1);
1684 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1685 author, state->sign_commit))
1686 die(_("failed to write commit object"));
1688 reflog_msg = getenv("GIT_REFLOG_ACTION");
1689 if (!reflog_msg)
1690 reflog_msg = "am";
1692 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1693 state->msg);
1695 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1697 if (state->rebasing) {
1698 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1700 assert(!is_null_sha1(state->orig_commit));
1701 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1702 fprintf(fp, "%s\n", sha1_to_hex(commit));
1703 fclose(fp);
1706 run_hook_le(NULL, "post-applypatch", NULL);
1708 strbuf_release(&sb);
1712 * Validates the am_state for resuming -- the "msg" and authorship fields must
1713 * be filled up.
1715 static void validate_resume_state(const struct am_state *state)
1717 if (!state->msg)
1718 die(_("cannot resume: %s does not exist."),
1719 am_path(state, "final-commit"));
1721 if (!state->author_name || !state->author_email || !state->author_date)
1722 die(_("cannot resume: %s does not exist."),
1723 am_path(state, "author-script"));
1727 * Interactively prompt the user on whether the current patch should be
1728 * applied.
1730 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1731 * skip it.
1733 static int do_interactive(struct am_state *state)
1735 assert(state->msg);
1737 if (!isatty(0))
1738 die(_("cannot be interactive without stdin connected to a terminal."));
1740 for (;;) {
1741 const char *reply;
1743 puts(_("Commit Body is:"));
1744 puts("--------------------------");
1745 printf("%s", state->msg);
1746 puts("--------------------------");
1749 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1750 * in your translation. The program will only accept English
1751 * input at this point.
1753 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1755 if (!reply) {
1756 continue;
1757 } else if (*reply == 'y' || *reply == 'Y') {
1758 return 0;
1759 } else if (*reply == 'a' || *reply == 'A') {
1760 state->interactive = 0;
1761 return 0;
1762 } else if (*reply == 'n' || *reply == 'N') {
1763 return 1;
1764 } else if (*reply == 'e' || *reply == 'E') {
1765 struct strbuf msg = STRBUF_INIT;
1767 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1768 free(state->msg);
1769 state->msg = strbuf_detach(&msg, &state->msg_len);
1771 strbuf_release(&msg);
1772 } else if (*reply == 'v' || *reply == 'V') {
1773 const char *pager = git_pager(1);
1774 struct child_process cp = CHILD_PROCESS_INIT;
1776 if (!pager)
1777 pager = "cat";
1778 prepare_pager_args(&cp, pager);
1779 argv_array_push(&cp.args, am_path(state, "patch"));
1780 run_command(&cp);
1786 * Applies all queued mail.
1788 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1789 * well as the state directory's "patch" file is used as-is for applying the
1790 * patch and committing it.
1792 static void am_run(struct am_state *state, int resume)
1794 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1795 struct strbuf sb = STRBUF_INIT;
1797 unlink(am_path(state, "dirtyindex"));
1799 refresh_and_write_cache();
1801 if (index_has_changes(&sb)) {
1802 write_state_bool(state, "dirtyindex", 1);
1803 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1806 strbuf_release(&sb);
1808 while (state->cur <= state->last) {
1809 const char *mail = am_path(state, msgnum(state));
1810 int apply_status;
1812 reset_ident_date();
1814 if (!file_exists(mail))
1815 goto next;
1817 if (resume) {
1818 validate_resume_state(state);
1819 } else {
1820 int skip;
1822 if (state->rebasing)
1823 skip = parse_mail_rebase(state, mail);
1824 else
1825 skip = parse_mail(state, mail);
1827 if (skip)
1828 goto next; /* mail should be skipped */
1830 write_author_script(state);
1831 write_commit_msg(state);
1834 if (state->interactive && do_interactive(state))
1835 goto next;
1837 if (run_applypatch_msg_hook(state))
1838 exit(1);
1840 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1842 apply_status = run_apply(state, NULL);
1844 if (apply_status && state->threeway) {
1845 struct strbuf sb = STRBUF_INIT;
1847 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1848 apply_status = fall_back_threeway(state, sb.buf);
1849 strbuf_release(&sb);
1852 * Applying the patch to an earlier tree and merging
1853 * the result may have produced the same tree as ours.
1855 if (!apply_status && !index_has_changes(NULL)) {
1856 say(state, stdout, _("No changes -- Patch already applied."));
1857 goto next;
1861 if (apply_status) {
1862 int advice_amworkdir = 1;
1864 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1865 linelen(state->msg), state->msg);
1867 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1869 if (advice_amworkdir)
1870 printf_ln(_("The copy of the patch that failed is found in: %s"),
1871 am_path(state, "patch"));
1873 die_user_resolve(state);
1876 do_commit(state);
1878 next:
1879 am_next(state);
1881 if (resume)
1882 am_load(state);
1883 resume = 0;
1886 if (!is_empty_file(am_path(state, "rewritten"))) {
1887 assert(state->rebasing);
1888 copy_notes_for_rebase(state);
1889 run_post_rewrite_hook(state);
1893 * In rebasing mode, it's up to the caller to take care of
1894 * housekeeping.
1896 if (!state->rebasing) {
1897 am_destroy(state);
1898 close_all_packs();
1899 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1904 * Resume the current am session after patch application failure. The user did
1905 * all the hard work, and we do not have to do any patch application. Just
1906 * trust and commit what the user has in the index and working tree.
1908 static void am_resolve(struct am_state *state)
1910 validate_resume_state(state);
1912 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1914 if (!index_has_changes(NULL)) {
1915 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1916 "If there is nothing left to stage, chances are that something else\n"
1917 "already introduced the same changes; you might want to skip this patch."));
1918 die_user_resolve(state);
1921 if (unmerged_cache()) {
1922 printf_ln(_("You still have unmerged paths in your index.\n"
1923 "Did you forget to use 'git add'?"));
1924 die_user_resolve(state);
1927 if (state->interactive) {
1928 write_index_patch(state);
1929 if (do_interactive(state))
1930 goto next;
1933 rerere(0);
1935 do_commit(state);
1937 next:
1938 am_next(state);
1939 am_load(state);
1940 am_run(state, 0);
1944 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1945 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1946 * failure.
1948 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1950 struct lock_file *lock_file;
1951 struct unpack_trees_options opts;
1952 struct tree_desc t[2];
1954 if (parse_tree(head) || parse_tree(remote))
1955 return -1;
1957 lock_file = xcalloc(1, sizeof(struct lock_file));
1958 hold_locked_index(lock_file, 1);
1960 refresh_cache(REFRESH_QUIET);
1962 memset(&opts, 0, sizeof(opts));
1963 opts.head_idx = 1;
1964 opts.src_index = &the_index;
1965 opts.dst_index = &the_index;
1966 opts.update = 1;
1967 opts.merge = 1;
1968 opts.reset = reset;
1969 opts.fn = twoway_merge;
1970 init_tree_desc(&t[0], head->buffer, head->size);
1971 init_tree_desc(&t[1], remote->buffer, remote->size);
1973 if (unpack_trees(2, t, &opts)) {
1974 rollback_lock_file(lock_file);
1975 return -1;
1978 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1979 die(_("unable to write new index file"));
1981 return 0;
1985 * Merges a tree into the index. The index's stat info will take precedence
1986 * over the merged tree's. Returns 0 on success, -1 on failure.
1988 static int merge_tree(struct tree *tree)
1990 struct lock_file *lock_file;
1991 struct unpack_trees_options opts;
1992 struct tree_desc t[1];
1994 if (parse_tree(tree))
1995 return -1;
1997 lock_file = xcalloc(1, sizeof(struct lock_file));
1998 hold_locked_index(lock_file, 1);
2000 memset(&opts, 0, sizeof(opts));
2001 opts.head_idx = 1;
2002 opts.src_index = &the_index;
2003 opts.dst_index = &the_index;
2004 opts.merge = 1;
2005 opts.fn = oneway_merge;
2006 init_tree_desc(&t[0], tree->buffer, tree->size);
2008 if (unpack_trees(1, t, &opts)) {
2009 rollback_lock_file(lock_file);
2010 return -1;
2013 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
2014 die(_("unable to write new index file"));
2016 return 0;
2020 * Clean the index without touching entries that are not modified between
2021 * `head` and `remote`.
2023 static int clean_index(const unsigned char *head, const unsigned char *remote)
2025 struct tree *head_tree, *remote_tree, *index_tree;
2026 unsigned char index[GIT_SHA1_RAWSZ];
2028 head_tree = parse_tree_indirect(head);
2029 if (!head_tree)
2030 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
2032 remote_tree = parse_tree_indirect(remote);
2033 if (!remote_tree)
2034 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
2036 read_cache_unmerged();
2038 if (fast_forward_to(head_tree, head_tree, 1))
2039 return -1;
2041 if (write_cache_as_tree(index, 0, NULL))
2042 return -1;
2044 index_tree = parse_tree_indirect(index);
2045 if (!index_tree)
2046 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
2048 if (fast_forward_to(index_tree, remote_tree, 0))
2049 return -1;
2051 if (merge_tree(remote_tree))
2052 return -1;
2054 remove_branch_state();
2056 return 0;
2060 * Resets rerere's merge resolution metadata.
2062 static void am_rerere_clear(void)
2064 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2065 rerere_clear(&merge_rr);
2066 string_list_clear(&merge_rr, 1);
2070 * Resume the current am session by skipping the current patch.
2072 static void am_skip(struct am_state *state)
2074 unsigned char head[GIT_SHA1_RAWSZ];
2076 am_rerere_clear();
2078 if (get_sha1("HEAD", head))
2079 hashcpy(head, EMPTY_TREE_SHA1_BIN);
2081 if (clean_index(head, head))
2082 die(_("failed to clean index"));
2084 am_next(state);
2085 am_load(state);
2086 am_run(state, 0);
2090 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2092 * It is not safe to reset HEAD when:
2093 * 1. git-am previously failed because the index was dirty.
2094 * 2. HEAD has moved since git-am previously failed.
2096 static int safe_to_abort(const struct am_state *state)
2098 struct strbuf sb = STRBUF_INIT;
2099 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
2101 if (file_exists(am_path(state, "dirtyindex")))
2102 return 0;
2104 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2105 if (get_sha1_hex(sb.buf, abort_safety))
2106 die(_("could not parse %s"), am_path(state, "abort_safety"));
2107 } else
2108 hashclr(abort_safety);
2110 if (get_sha1("HEAD", head))
2111 hashclr(head);
2113 if (!hashcmp(head, abort_safety))
2114 return 1;
2116 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2117 "Not rewinding to ORIG_HEAD"));
2119 return 0;
2123 * Aborts the current am session if it is safe to do so.
2125 static void am_abort(struct am_state *state)
2127 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
2128 int has_curr_head, has_orig_head;
2129 char *curr_branch;
2131 if (!safe_to_abort(state)) {
2132 am_destroy(state);
2133 return;
2136 am_rerere_clear();
2138 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
2139 has_curr_head = !is_null_sha1(curr_head);
2140 if (!has_curr_head)
2141 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
2143 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
2144 if (!has_orig_head)
2145 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
2147 clean_index(curr_head, orig_head);
2149 if (has_orig_head)
2150 update_ref("am --abort", "HEAD", orig_head,
2151 has_curr_head ? curr_head : NULL, 0,
2152 UPDATE_REFS_DIE_ON_ERR);
2153 else if (curr_branch)
2154 delete_ref(curr_branch, NULL, REF_NODEREF);
2156 free(curr_branch);
2157 am_destroy(state);
2161 * parse_options() callback that validates and sets opt->value to the
2162 * PATCH_FORMAT_* enum value corresponding to `arg`.
2164 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2166 int *opt_value = opt->value;
2168 if (!strcmp(arg, "mbox"))
2169 *opt_value = PATCH_FORMAT_MBOX;
2170 else if (!strcmp(arg, "stgit"))
2171 *opt_value = PATCH_FORMAT_STGIT;
2172 else if (!strcmp(arg, "stgit-series"))
2173 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2174 else if (!strcmp(arg, "hg"))
2175 *opt_value = PATCH_FORMAT_HG;
2176 else if (!strcmp(arg, "mboxrd"))
2177 *opt_value = PATCH_FORMAT_MBOXRD;
2178 else
2179 return error(_("Invalid value for --patch-format: %s"), arg);
2180 return 0;
2183 enum resume_mode {
2184 RESUME_FALSE = 0,
2185 RESUME_APPLY,
2186 RESUME_RESOLVED,
2187 RESUME_SKIP,
2188 RESUME_ABORT
2191 static int git_am_config(const char *k, const char *v, void *cb)
2193 int status;
2195 status = git_gpg_config(k, v, NULL);
2196 if (status)
2197 return status;
2199 return git_default_config(k, v, NULL);
2202 int cmd_am(int argc, const char **argv, const char *prefix)
2204 struct am_state state;
2205 int binary = -1;
2206 int keep_cr = -1;
2207 int patch_format = PATCH_FORMAT_UNKNOWN;
2208 enum resume_mode resume = RESUME_FALSE;
2209 int in_progress;
2211 const char * const usage[] = {
2212 N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
2213 N_("git am [<options>] (--continue | --skip | --abort)"),
2214 NULL
2217 struct option options[] = {
2218 OPT_BOOL('i', "interactive", &state.interactive,
2219 N_("run interactively")),
2220 OPT_HIDDEN_BOOL('b', "binary", &binary,
2221 N_("historical option -- no-op")),
2222 OPT_BOOL('3', "3way", &state.threeway,
2223 N_("allow fall back on 3way merging if needed")),
2224 OPT__QUIET(&state.quiet, N_("be quiet")),
2225 OPT_SET_INT('s', "signoff", &state.signoff,
2226 N_("add a Signed-off-by line to the commit message"),
2227 SIGNOFF_EXPLICIT),
2228 OPT_BOOL('u', "utf8", &state.utf8,
2229 N_("recode into utf8 (default)")),
2230 OPT_SET_INT('k', "keep", &state.keep,
2231 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2232 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2233 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2234 OPT_BOOL('m', "message-id", &state.message_id,
2235 N_("pass -m flag to git-mailinfo")),
2236 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2237 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2238 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2239 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2240 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2241 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2242 OPT_BOOL('c', "scissors", &state.scissors,
2243 N_("strip everything before a scissors line")),
2244 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2245 N_("pass it through git-apply"),
2247 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2248 N_("pass it through git-apply"),
2249 PARSE_OPT_NOARG),
2250 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2251 N_("pass it through git-apply"),
2252 PARSE_OPT_NOARG),
2253 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2254 N_("pass it through git-apply"),
2256 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2257 N_("pass it through git-apply"),
2259 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2260 N_("pass it through git-apply"),
2262 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2263 N_("pass it through git-apply"),
2265 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2266 N_("pass it through git-apply"),
2268 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2269 N_("format the patch(es) are in"),
2270 parse_opt_patchformat),
2271 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2272 N_("pass it through git-apply"),
2273 PARSE_OPT_NOARG),
2274 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2275 N_("override error message when patch failure occurs")),
2276 OPT_CMDMODE(0, "continue", &resume,
2277 N_("continue applying patches after resolving a conflict"),
2278 RESUME_RESOLVED),
2279 OPT_CMDMODE('r', "resolved", &resume,
2280 N_("synonyms for --continue"),
2281 RESUME_RESOLVED),
2282 OPT_CMDMODE(0, "skip", &resume,
2283 N_("skip the current patch"),
2284 RESUME_SKIP),
2285 OPT_CMDMODE(0, "abort", &resume,
2286 N_("restore the original branch and abort the patching operation."),
2287 RESUME_ABORT),
2288 OPT_BOOL(0, "committer-date-is-author-date",
2289 &state.committer_date_is_author_date,
2290 N_("lie about committer date")),
2291 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2292 N_("use current timestamp for author date")),
2293 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2294 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2295 N_("GPG-sign commits"),
2296 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2297 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2298 N_("(internal use for git-rebase)")),
2299 OPT_END()
2302 git_config(git_am_config, NULL);
2304 am_state_init(&state, git_path("rebase-apply"));
2306 in_progress = am_in_progress(&state);
2307 if (in_progress)
2308 am_load(&state);
2310 argc = parse_options(argc, argv, prefix, options, usage, 0);
2312 if (binary >= 0)
2313 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2314 "it will be removed. Please do not use it anymore."));
2316 /* Ensure a valid committer ident can be constructed */
2317 git_committer_info(IDENT_STRICT);
2319 if (read_index_preload(&the_index, NULL) < 0)
2320 die(_("failed to read the index"));
2322 if (in_progress) {
2324 * Catch user error to feed us patches when there is a session
2325 * in progress:
2327 * 1. mbox path(s) are provided on the command-line.
2328 * 2. stdin is not a tty: the user is trying to feed us a patch
2329 * from standard input. This is somewhat unreliable -- stdin
2330 * could be /dev/null for example and the caller did not
2331 * intend to feed us a patch but wanted to continue
2332 * unattended.
2334 if (argc || (resume == RESUME_FALSE && !isatty(0)))
2335 die(_("previous rebase directory %s still exists but mbox given."),
2336 state.dir);
2338 if (resume == RESUME_FALSE)
2339 resume = RESUME_APPLY;
2341 if (state.signoff == SIGNOFF_EXPLICIT)
2342 am_append_signoff(&state);
2343 } else {
2344 struct argv_array paths = ARGV_ARRAY_INIT;
2345 int i;
2348 * Handle stray state directory in the independent-run case. In
2349 * the --rebasing case, it is up to the caller to take care of
2350 * stray directories.
2352 if (file_exists(state.dir) && !state.rebasing) {
2353 if (resume == RESUME_ABORT) {
2354 am_destroy(&state);
2355 am_state_release(&state);
2356 return 0;
2359 die(_("Stray %s directory found.\n"
2360 "Use \"git am --abort\" to remove it."),
2361 state.dir);
2364 if (resume)
2365 die(_("Resolve operation not in progress, we are not resuming."));
2367 for (i = 0; i < argc; i++) {
2368 if (is_absolute_path(argv[i]) || !prefix)
2369 argv_array_push(&paths, argv[i]);
2370 else
2371 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2374 am_setup(&state, patch_format, paths.argv, keep_cr);
2376 argv_array_clear(&paths);
2379 switch (resume) {
2380 case RESUME_FALSE:
2381 am_run(&state, 0);
2382 break;
2383 case RESUME_APPLY:
2384 am_run(&state, 1);
2385 break;
2386 case RESUME_RESOLVED:
2387 am_resolve(&state);
2388 break;
2389 case RESUME_SKIP:
2390 am_skip(&state);
2391 break;
2392 case RESUME_ABORT:
2393 am_abort(&state);
2394 break;
2395 default:
2396 die("BUG: invalid resume value");
2399 am_state_release(&state);
2401 return 0;