am: support --patch-format=mboxrd
[git/git-svn.git] / builtin / am.c
blobd5da5fe0900c6138337ee3f185884e454049eecd
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"
32 /**
33 * Returns 1 if the file is empty or does not exist, 0 otherwise.
35 static int is_empty_file(const char *filename)
37 struct stat st;
39 if (stat(filename, &st) < 0) {
40 if (errno == ENOENT)
41 return 1;
42 die_errno(_("could not stat %s"), filename);
45 return !st.st_size;
48 /**
49 * Returns the length of the first line of msg.
51 static int linelen(const char *msg)
53 return strchrnul(msg, '\n') - msg;
56 /**
57 * Returns true if `str` consists of only whitespace, false otherwise.
59 static int str_isspace(const char *str)
61 for (; *str; str++)
62 if (!isspace(*str))
63 return 0;
65 return 1;
68 enum patch_format {
69 PATCH_FORMAT_UNKNOWN = 0,
70 PATCH_FORMAT_MBOX,
71 PATCH_FORMAT_STGIT,
72 PATCH_FORMAT_STGIT_SERIES,
73 PATCH_FORMAT_HG,
74 PATCH_FORMAT_MBOXRD
77 enum keep_type {
78 KEEP_FALSE = 0,
79 KEEP_TRUE, /* pass -k flag to git-mailinfo */
80 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
83 enum scissors_type {
84 SCISSORS_UNSET = -1,
85 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
86 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
89 enum signoff_type {
90 SIGNOFF_FALSE = 0,
91 SIGNOFF_TRUE = 1,
92 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
95 struct am_state {
96 /* state directory path */
97 char *dir;
99 /* current and last patch numbers, 1-indexed */
100 int cur;
101 int last;
103 /* commit metadata and message */
104 char *author_name;
105 char *author_email;
106 char *author_date;
107 char *msg;
108 size_t msg_len;
110 /* when --rebasing, records the original commit the patch came from */
111 unsigned char orig_commit[GIT_SHA1_RAWSZ];
113 /* number of digits in patch filename */
114 int prec;
116 /* various operating modes and command line options */
117 int interactive;
118 int threeway;
119 int quiet;
120 int signoff; /* enum signoff_type */
121 int utf8;
122 int keep; /* enum keep_type */
123 int message_id;
124 int scissors; /* enum scissors_type */
125 struct argv_array git_apply_opts;
126 const char *resolvemsg;
127 int committer_date_is_author_date;
128 int ignore_date;
129 int allow_rerere_autoupdate;
130 const char *sign_commit;
131 int rebasing;
135 * Initializes am_state with the default values. The state directory is set to
136 * dir.
138 static void am_state_init(struct am_state *state, const char *dir)
140 int gpgsign;
142 memset(state, 0, sizeof(*state));
144 assert(dir);
145 state->dir = xstrdup(dir);
147 state->prec = 4;
149 git_config_get_bool("am.threeway", &state->threeway);
151 state->utf8 = 1;
153 git_config_get_bool("am.messageid", &state->message_id);
155 state->scissors = SCISSORS_UNSET;
157 argv_array_init(&state->git_apply_opts);
159 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
160 state->sign_commit = gpgsign ? "" : NULL;
164 * Releases memory allocated by an am_state.
166 static void am_state_release(struct am_state *state)
168 free(state->dir);
169 free(state->author_name);
170 free(state->author_email);
171 free(state->author_date);
172 free(state->msg);
173 argv_array_clear(&state->git_apply_opts);
177 * Returns path relative to the am_state directory.
179 static inline const char *am_path(const struct am_state *state, const char *path)
181 return mkpath("%s/%s", state->dir, path);
185 * For convenience to call write_file()
187 static int write_state_text(const struct am_state *state,
188 const char *name, const char *string)
190 return write_file(am_path(state, name), "%s", string);
193 static int write_state_count(const struct am_state *state,
194 const char *name, int value)
196 return write_file(am_path(state, name), "%d", value);
199 static int write_state_bool(const struct am_state *state,
200 const char *name, int value)
202 return write_state_text(state, name, value ? "t" : "f");
206 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
207 * at the end.
209 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
211 va_list ap;
213 va_start(ap, fmt);
214 if (!state->quiet) {
215 vfprintf(fp, fmt, ap);
216 putc('\n', fp);
218 va_end(ap);
222 * Returns 1 if there is an am session in progress, 0 otherwise.
224 static int am_in_progress(const struct am_state *state)
226 struct stat st;
228 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
229 return 0;
230 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
231 return 0;
232 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
233 return 0;
234 return 1;
238 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
239 * number of bytes read on success, -1 if the file does not exist. If `trim` is
240 * set, trailing whitespace will be removed.
242 static int read_state_file(struct strbuf *sb, const struct am_state *state,
243 const char *file, int trim)
245 strbuf_reset(sb);
247 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
248 if (trim)
249 strbuf_trim(sb);
251 return sb->len;
254 if (errno == ENOENT)
255 return -1;
257 die_errno(_("could not read '%s'"), am_path(state, file));
261 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
262 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
263 * match `key`. Returns NULL on failure.
265 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
266 * the author-script.
268 static char *read_shell_var(FILE *fp, const char *key)
270 struct strbuf sb = STRBUF_INIT;
271 const char *str;
273 if (strbuf_getline_lf(&sb, fp))
274 goto fail;
276 if (!skip_prefix(sb.buf, key, &str))
277 goto fail;
279 if (!skip_prefix(str, "=", &str))
280 goto fail;
282 strbuf_remove(&sb, 0, str - sb.buf);
284 str = sq_dequote(sb.buf);
285 if (!str)
286 goto fail;
288 return strbuf_detach(&sb, NULL);
290 fail:
291 strbuf_release(&sb);
292 return NULL;
296 * Reads and parses the state directory's "author-script" file, and sets
297 * state->author_name, state->author_email and state->author_date accordingly.
298 * Returns 0 on success, -1 if the file could not be parsed.
300 * The author script is of the format:
302 * GIT_AUTHOR_NAME='$author_name'
303 * GIT_AUTHOR_EMAIL='$author_email'
304 * GIT_AUTHOR_DATE='$author_date'
306 * where $author_name, $author_email and $author_date are quoted. We are strict
307 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
308 * script, and thus if the file differs from what this function expects, it is
309 * better to bail out than to do something that the user does not expect.
311 static int read_author_script(struct am_state *state)
313 const char *filename = am_path(state, "author-script");
314 FILE *fp;
316 assert(!state->author_name);
317 assert(!state->author_email);
318 assert(!state->author_date);
320 fp = fopen(filename, "r");
321 if (!fp) {
322 if (errno == ENOENT)
323 return 0;
324 die_errno(_("could not open '%s' for reading"), filename);
327 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
328 if (!state->author_name) {
329 fclose(fp);
330 return -1;
333 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
334 if (!state->author_email) {
335 fclose(fp);
336 return -1;
339 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
340 if (!state->author_date) {
341 fclose(fp);
342 return -1;
345 if (fgetc(fp) != EOF) {
346 fclose(fp);
347 return -1;
350 fclose(fp);
351 return 0;
355 * Saves state->author_name, state->author_email and state->author_date in the
356 * state directory's "author-script" file.
358 static void write_author_script(const struct am_state *state)
360 struct strbuf sb = STRBUF_INIT;
362 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
363 sq_quote_buf(&sb, state->author_name);
364 strbuf_addch(&sb, '\n');
366 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
367 sq_quote_buf(&sb, state->author_email);
368 strbuf_addch(&sb, '\n');
370 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
371 sq_quote_buf(&sb, state->author_date);
372 strbuf_addch(&sb, '\n');
374 write_state_text(state, "author-script", sb.buf);
376 strbuf_release(&sb);
380 * Reads the commit message from the state directory's "final-commit" file,
381 * setting state->msg to its contents and state->msg_len to the length of its
382 * contents in bytes.
384 * Returns 0 on success, -1 if the file does not exist.
386 static int read_commit_msg(struct am_state *state)
388 struct strbuf sb = STRBUF_INIT;
390 assert(!state->msg);
392 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
393 strbuf_release(&sb);
394 return -1;
397 state->msg = strbuf_detach(&sb, &state->msg_len);
398 return 0;
402 * Saves state->msg in the state directory's "final-commit" file.
404 static void write_commit_msg(const struct am_state *state)
406 int fd;
407 const char *filename = am_path(state, "final-commit");
409 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
410 if (write_in_full(fd, state->msg, state->msg_len) < 0)
411 die_errno(_("could not write to %s"), filename);
412 close(fd);
416 * Loads state from disk.
418 static void am_load(struct am_state *state)
420 struct strbuf sb = STRBUF_INIT;
422 if (read_state_file(&sb, state, "next", 1) < 0)
423 die("BUG: state file 'next' does not exist");
424 state->cur = strtol(sb.buf, NULL, 10);
426 if (read_state_file(&sb, state, "last", 1) < 0)
427 die("BUG: state file 'last' does not exist");
428 state->last = strtol(sb.buf, NULL, 10);
430 if (read_author_script(state) < 0)
431 die(_("could not parse author script"));
433 read_commit_msg(state);
435 if (read_state_file(&sb, state, "original-commit", 1) < 0)
436 hashclr(state->orig_commit);
437 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
438 die(_("could not parse %s"), am_path(state, "original-commit"));
440 read_state_file(&sb, state, "threeway", 1);
441 state->threeway = !strcmp(sb.buf, "t");
443 read_state_file(&sb, state, "quiet", 1);
444 state->quiet = !strcmp(sb.buf, "t");
446 read_state_file(&sb, state, "sign", 1);
447 state->signoff = !strcmp(sb.buf, "t");
449 read_state_file(&sb, state, "utf8", 1);
450 state->utf8 = !strcmp(sb.buf, "t");
452 read_state_file(&sb, state, "keep", 1);
453 if (!strcmp(sb.buf, "t"))
454 state->keep = KEEP_TRUE;
455 else if (!strcmp(sb.buf, "b"))
456 state->keep = KEEP_NON_PATCH;
457 else
458 state->keep = KEEP_FALSE;
460 read_state_file(&sb, state, "messageid", 1);
461 state->message_id = !strcmp(sb.buf, "t");
463 read_state_file(&sb, state, "scissors", 1);
464 if (!strcmp(sb.buf, "t"))
465 state->scissors = SCISSORS_TRUE;
466 else if (!strcmp(sb.buf, "f"))
467 state->scissors = SCISSORS_FALSE;
468 else
469 state->scissors = SCISSORS_UNSET;
471 read_state_file(&sb, state, "apply-opt", 1);
472 argv_array_clear(&state->git_apply_opts);
473 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
474 die(_("could not parse %s"), am_path(state, "apply-opt"));
476 state->rebasing = !!file_exists(am_path(state, "rebasing"));
478 strbuf_release(&sb);
482 * Removes the am_state directory, forcefully terminating the current am
483 * session.
485 static void am_destroy(const struct am_state *state)
487 struct strbuf sb = STRBUF_INIT;
489 strbuf_addstr(&sb, state->dir);
490 remove_dir_recursively(&sb, 0);
491 strbuf_release(&sb);
495 * Runs applypatch-msg hook. Returns its exit code.
497 static int run_applypatch_msg_hook(struct am_state *state)
499 int ret;
501 assert(state->msg);
502 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
504 if (!ret) {
505 free(state->msg);
506 state->msg = NULL;
507 if (read_commit_msg(state) < 0)
508 die(_("'%s' was deleted by the applypatch-msg hook"),
509 am_path(state, "final-commit"));
512 return ret;
516 * Runs post-rewrite hook. Returns it exit code.
518 static int run_post_rewrite_hook(const struct am_state *state)
520 struct child_process cp = CHILD_PROCESS_INIT;
521 const char *hook = find_hook("post-rewrite");
522 int ret;
524 if (!hook)
525 return 0;
527 argv_array_push(&cp.args, hook);
528 argv_array_push(&cp.args, "rebase");
530 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
531 cp.stdout_to_stderr = 1;
533 ret = run_command(&cp);
535 close(cp.in);
536 return ret;
540 * Reads the state directory's "rewritten" file, and copies notes from the old
541 * commits listed in the file to their rewritten commits.
543 * Returns 0 on success, -1 on failure.
545 static int copy_notes_for_rebase(const struct am_state *state)
547 struct notes_rewrite_cfg *c;
548 struct strbuf sb = STRBUF_INIT;
549 const char *invalid_line = _("Malformed input line: '%s'.");
550 const char *msg = "Notes added by 'git rebase'";
551 FILE *fp;
552 int ret = 0;
554 assert(state->rebasing);
556 c = init_copy_notes_for_rewrite("rebase");
557 if (!c)
558 return 0;
560 fp = xfopen(am_path(state, "rewritten"), "r");
562 while (!strbuf_getline_lf(&sb, fp)) {
563 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
565 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
566 ret = error(invalid_line, sb.buf);
567 goto finish;
570 if (get_sha1_hex(sb.buf, from_obj)) {
571 ret = error(invalid_line, sb.buf);
572 goto finish;
575 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
576 ret = error(invalid_line, sb.buf);
577 goto finish;
580 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
581 ret = error(invalid_line, sb.buf);
582 goto finish;
585 if (copy_note_for_rewrite(c, from_obj, to_obj))
586 ret = error(_("Failed to copy notes from '%s' to '%s'"),
587 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
590 finish:
591 finish_copy_notes_for_rewrite(c, msg);
592 fclose(fp);
593 strbuf_release(&sb);
594 return ret;
598 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
599 * non-indented lines and checking if they look like they begin with valid
600 * header field names.
602 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
604 static int is_mail(FILE *fp)
606 const char *header_regex = "^[!-9;-~]+:";
607 struct strbuf sb = STRBUF_INIT;
608 regex_t regex;
609 int ret = 1;
611 if (fseek(fp, 0L, SEEK_SET))
612 die_errno(_("fseek failed"));
614 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
615 die("invalid pattern: %s", header_regex);
617 while (!strbuf_getline(&sb, fp)) {
618 if (!sb.len)
619 break; /* End of header */
621 /* Ignore indented folded lines */
622 if (*sb.buf == '\t' || *sb.buf == ' ')
623 continue;
625 /* It's a header if it matches header_regex */
626 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
627 ret = 0;
628 goto done;
632 done:
633 regfree(&regex);
634 strbuf_release(&sb);
635 return ret;
639 * Attempts to detect the patch_format of the patches contained in `paths`,
640 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
641 * detection fails.
643 static int detect_patch_format(const char **paths)
645 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
646 struct strbuf l1 = STRBUF_INIT;
647 struct strbuf l2 = STRBUF_INIT;
648 struct strbuf l3 = STRBUF_INIT;
649 FILE *fp;
652 * We default to mbox format if input is from stdin and for directories
654 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
655 return PATCH_FORMAT_MBOX;
658 * Otherwise, check the first few lines of the first patch, starting
659 * from the first non-blank line, to try to detect its format.
662 fp = xfopen(*paths, "r");
664 while (!strbuf_getline(&l1, fp)) {
665 if (l1.len)
666 break;
669 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
670 ret = PATCH_FORMAT_MBOX;
671 goto done;
674 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
675 ret = PATCH_FORMAT_STGIT_SERIES;
676 goto done;
679 if (!strcmp(l1.buf, "# HG changeset patch")) {
680 ret = PATCH_FORMAT_HG;
681 goto done;
684 strbuf_reset(&l2);
685 strbuf_getline(&l2, fp);
686 strbuf_reset(&l3);
687 strbuf_getline(&l3, fp);
690 * If the second line is empty and the third is a From, Author or Date
691 * entry, this is likely an StGit patch.
693 if (l1.len && !l2.len &&
694 (starts_with(l3.buf, "From:") ||
695 starts_with(l3.buf, "Author:") ||
696 starts_with(l3.buf, "Date:"))) {
697 ret = PATCH_FORMAT_STGIT;
698 goto done;
701 if (l1.len && is_mail(fp)) {
702 ret = PATCH_FORMAT_MBOX;
703 goto done;
706 done:
707 fclose(fp);
708 strbuf_release(&l1);
709 return ret;
713 * Splits out individual email patches from `paths`, where each path is either
714 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
716 static int split_mail_mbox(struct am_state *state, const char **paths,
717 int keep_cr, int mboxrd)
719 struct child_process cp = CHILD_PROCESS_INIT;
720 struct strbuf last = STRBUF_INIT;
722 cp.git_cmd = 1;
723 argv_array_push(&cp.args, "mailsplit");
724 argv_array_pushf(&cp.args, "-d%d", state->prec);
725 argv_array_pushf(&cp.args, "-o%s", state->dir);
726 argv_array_push(&cp.args, "-b");
727 if (keep_cr)
728 argv_array_push(&cp.args, "--keep-cr");
729 if (mboxrd)
730 argv_array_push(&cp.args, "--mboxrd");
731 argv_array_push(&cp.args, "--");
732 argv_array_pushv(&cp.args, paths);
734 if (capture_command(&cp, &last, 8))
735 return -1;
737 state->cur = 1;
738 state->last = strtol(last.buf, NULL, 10);
740 return 0;
744 * Callback signature for split_mail_conv(). The foreign patch should be
745 * read from `in`, and the converted patch (in RFC2822 mail format) should be
746 * written to `out`. Return 0 on success, or -1 on failure.
748 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
751 * Calls `fn` for each file in `paths` to convert the foreign patch to the
752 * RFC2822 mail format suitable for parsing with git-mailinfo.
754 * Returns 0 on success, -1 on failure.
756 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
757 const char **paths, int keep_cr)
759 static const char *stdin_only[] = {"-", NULL};
760 int i;
762 if (!*paths)
763 paths = stdin_only;
765 for (i = 0; *paths; paths++, i++) {
766 FILE *in, *out;
767 const char *mail;
768 int ret;
770 if (!strcmp(*paths, "-"))
771 in = stdin;
772 else
773 in = fopen(*paths, "r");
775 if (!in)
776 return error_errno(_("could not open '%s' for reading"),
777 *paths);
779 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
781 out = fopen(mail, "w");
782 if (!out)
783 return error_errno(_("could not open '%s' for writing"),
784 mail);
786 ret = fn(out, in, keep_cr);
788 fclose(out);
789 fclose(in);
791 if (ret)
792 return error(_("could not parse patch '%s'"), *paths);
795 state->cur = 1;
796 state->last = i;
797 return 0;
801 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
802 * message suitable for parsing with git-mailinfo.
804 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
806 struct strbuf sb = STRBUF_INIT;
807 int subject_printed = 0;
809 while (!strbuf_getline_lf(&sb, in)) {
810 const char *str;
812 if (str_isspace(sb.buf))
813 continue;
814 else if (skip_prefix(sb.buf, "Author:", &str))
815 fprintf(out, "From:%s\n", str);
816 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
817 fprintf(out, "%s\n", sb.buf);
818 else if (!subject_printed) {
819 fprintf(out, "Subject: %s\n", sb.buf);
820 subject_printed = 1;
821 } else {
822 fprintf(out, "\n%s\n", sb.buf);
823 break;
827 strbuf_reset(&sb);
828 while (strbuf_fread(&sb, 8192, in) > 0) {
829 fwrite(sb.buf, 1, sb.len, out);
830 strbuf_reset(&sb);
833 strbuf_release(&sb);
834 return 0;
838 * This function only supports a single StGit series file in `paths`.
840 * Given an StGit series file, converts the StGit patches in the series into
841 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
842 * the state directory.
844 * Returns 0 on success, -1 on failure.
846 static int split_mail_stgit_series(struct am_state *state, const char **paths,
847 int keep_cr)
849 const char *series_dir;
850 char *series_dir_buf;
851 FILE *fp;
852 struct argv_array patches = ARGV_ARRAY_INIT;
853 struct strbuf sb = STRBUF_INIT;
854 int ret;
856 if (!paths[0] || paths[1])
857 return error(_("Only one StGIT patch series can be applied at once"));
859 series_dir_buf = xstrdup(*paths);
860 series_dir = dirname(series_dir_buf);
862 fp = fopen(*paths, "r");
863 if (!fp)
864 return error_errno(_("could not open '%s' for reading"), *paths);
866 while (!strbuf_getline_lf(&sb, fp)) {
867 if (*sb.buf == '#')
868 continue; /* skip comment lines */
870 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
873 fclose(fp);
874 strbuf_release(&sb);
875 free(series_dir_buf);
877 ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
879 argv_array_clear(&patches);
880 return ret;
884 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
885 * message suitable for parsing with git-mailinfo.
887 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
889 struct strbuf sb = STRBUF_INIT;
891 while (!strbuf_getline_lf(&sb, in)) {
892 const char *str;
894 if (skip_prefix(sb.buf, "# User ", &str))
895 fprintf(out, "From: %s\n", str);
896 else if (skip_prefix(sb.buf, "# Date ", &str)) {
897 unsigned long timestamp;
898 long tz, tz2;
899 char *end;
901 errno = 0;
902 timestamp = strtoul(str, &end, 10);
903 if (errno)
904 return error(_("invalid timestamp"));
906 if (!skip_prefix(end, " ", &str))
907 return error(_("invalid Date line"));
909 errno = 0;
910 tz = strtol(str, &end, 10);
911 if (errno)
912 return error(_("invalid timezone offset"));
914 if (*end)
915 return error(_("invalid Date line"));
918 * mercurial's timezone is in seconds west of UTC,
919 * however git's timezone is in hours + minutes east of
920 * UTC. Convert it.
922 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
923 if (tz > 0)
924 tz2 = -tz2;
926 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
927 } else if (starts_with(sb.buf, "# ")) {
928 continue;
929 } else {
930 fprintf(out, "\n%s\n", sb.buf);
931 break;
935 strbuf_reset(&sb);
936 while (strbuf_fread(&sb, 8192, in) > 0) {
937 fwrite(sb.buf, 1, sb.len, out);
938 strbuf_reset(&sb);
941 strbuf_release(&sb);
942 return 0;
946 * Splits a list of files/directories into individual email patches. Each path
947 * in `paths` must be a file/directory that is formatted according to
948 * `patch_format`.
950 * Once split out, the individual email patches will be stored in the state
951 * directory, with each patch's filename being its index, padded to state->prec
952 * digits.
954 * state->cur will be set to the index of the first mail, and state->last will
955 * be set to the index of the last mail.
957 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
958 * to disable this behavior, -1 to use the default configured setting.
960 * Returns 0 on success, -1 on failure.
962 static int split_mail(struct am_state *state, enum patch_format patch_format,
963 const char **paths, int keep_cr)
965 if (keep_cr < 0) {
966 keep_cr = 0;
967 git_config_get_bool("am.keepcr", &keep_cr);
970 switch (patch_format) {
971 case PATCH_FORMAT_MBOX:
972 return split_mail_mbox(state, paths, keep_cr, 0);
973 case PATCH_FORMAT_STGIT:
974 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
975 case PATCH_FORMAT_STGIT_SERIES:
976 return split_mail_stgit_series(state, paths, keep_cr);
977 case PATCH_FORMAT_HG:
978 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
979 case PATCH_FORMAT_MBOXRD:
980 return split_mail_mbox(state, paths, keep_cr, 1);
981 default:
982 die("BUG: invalid patch_format");
984 return -1;
988 * Setup a new am session for applying patches
990 static void am_setup(struct am_state *state, enum patch_format patch_format,
991 const char **paths, int keep_cr)
993 unsigned char curr_head[GIT_SHA1_RAWSZ];
994 const char *str;
995 struct strbuf sb = STRBUF_INIT;
997 if (!patch_format)
998 patch_format = detect_patch_format(paths);
1000 if (!patch_format) {
1001 fprintf_ln(stderr, _("Patch format detection failed."));
1002 exit(128);
1005 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1006 die_errno(_("failed to create directory '%s'"), state->dir);
1008 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1009 am_destroy(state);
1010 die(_("Failed to split patches."));
1013 if (state->rebasing)
1014 state->threeway = 1;
1016 write_state_bool(state, "threeway", state->threeway);
1017 write_state_bool(state, "quiet", state->quiet);
1018 write_state_bool(state, "sign", state->signoff);
1019 write_state_bool(state, "utf8", state->utf8);
1021 switch (state->keep) {
1022 case KEEP_FALSE:
1023 str = "f";
1024 break;
1025 case KEEP_TRUE:
1026 str = "t";
1027 break;
1028 case KEEP_NON_PATCH:
1029 str = "b";
1030 break;
1031 default:
1032 die("BUG: invalid value for state->keep");
1035 write_state_text(state, "keep", str);
1036 write_state_bool(state, "messageid", state->message_id);
1038 switch (state->scissors) {
1039 case SCISSORS_UNSET:
1040 str = "";
1041 break;
1042 case SCISSORS_FALSE:
1043 str = "f";
1044 break;
1045 case SCISSORS_TRUE:
1046 str = "t";
1047 break;
1048 default:
1049 die("BUG: invalid value for state->scissors");
1051 write_state_text(state, "scissors", str);
1053 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1054 write_state_text(state, "apply-opt", sb.buf);
1056 if (state->rebasing)
1057 write_state_text(state, "rebasing", "");
1058 else
1059 write_state_text(state, "applying", "");
1061 if (!get_sha1("HEAD", curr_head)) {
1062 write_state_text(state, "abort-safety", sha1_to_hex(curr_head));
1063 if (!state->rebasing)
1064 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
1065 UPDATE_REFS_DIE_ON_ERR);
1066 } else {
1067 write_state_text(state, "abort-safety", "");
1068 if (!state->rebasing)
1069 delete_ref("ORIG_HEAD", NULL, 0);
1073 * NOTE: Since the "next" and "last" files determine if an am_state
1074 * session is in progress, they should be written last.
1077 write_state_count(state, "next", state->cur);
1078 write_state_count(state, "last", state->last);
1080 strbuf_release(&sb);
1084 * Increments the patch pointer, and cleans am_state for the application of the
1085 * next patch.
1087 static void am_next(struct am_state *state)
1089 unsigned char head[GIT_SHA1_RAWSZ];
1091 free(state->author_name);
1092 state->author_name = NULL;
1094 free(state->author_email);
1095 state->author_email = NULL;
1097 free(state->author_date);
1098 state->author_date = NULL;
1100 free(state->msg);
1101 state->msg = NULL;
1102 state->msg_len = 0;
1104 unlink(am_path(state, "author-script"));
1105 unlink(am_path(state, "final-commit"));
1107 hashclr(state->orig_commit);
1108 unlink(am_path(state, "original-commit"));
1110 if (!get_sha1("HEAD", head))
1111 write_state_text(state, "abort-safety", sha1_to_hex(head));
1112 else
1113 write_state_text(state, "abort-safety", "");
1115 state->cur++;
1116 write_state_count(state, "next", state->cur);
1120 * Returns the filename of the current patch email.
1122 static const char *msgnum(const struct am_state *state)
1124 static struct strbuf sb = STRBUF_INIT;
1126 strbuf_reset(&sb);
1127 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1129 return sb.buf;
1133 * Refresh and write index.
1135 static void refresh_and_write_cache(void)
1137 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1139 hold_locked_index(lock_file, 1);
1140 refresh_cache(REFRESH_QUIET);
1141 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1142 die(_("unable to write index file"));
1146 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1147 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1148 * strbuf is provided, the space-separated list of files that differ will be
1149 * appended to it.
1151 static int index_has_changes(struct strbuf *sb)
1153 unsigned char head[GIT_SHA1_RAWSZ];
1154 int i;
1156 if (!get_sha1_tree("HEAD", head)) {
1157 struct diff_options opt;
1159 diff_setup(&opt);
1160 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
1161 if (!sb)
1162 DIFF_OPT_SET(&opt, QUICK);
1163 do_diff_cache(head, &opt);
1164 diffcore_std(&opt);
1165 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1166 if (i)
1167 strbuf_addch(sb, ' ');
1168 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1170 diff_flush(&opt);
1171 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
1172 } else {
1173 for (i = 0; sb && i < active_nr; i++) {
1174 if (i)
1175 strbuf_addch(sb, ' ');
1176 strbuf_addstr(sb, active_cache[i]->name);
1178 return !!active_nr;
1183 * Dies with a user-friendly message on how to proceed after resolving the
1184 * problem. This message can be overridden with state->resolvemsg.
1186 static void NORETURN die_user_resolve(const struct am_state *state)
1188 if (state->resolvemsg) {
1189 printf_ln("%s", state->resolvemsg);
1190 } else {
1191 const char *cmdline = state->interactive ? "git am -i" : "git am";
1193 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1194 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1195 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1198 exit(128);
1201 static void am_signoff(struct strbuf *sb)
1203 char *cp;
1204 struct strbuf mine = STRBUF_INIT;
1206 /* Does it end with our own sign-off? */
1207 strbuf_addf(&mine, "\n%s%s\n",
1208 sign_off_header,
1209 fmt_name(getenv("GIT_COMMITTER_NAME"),
1210 getenv("GIT_COMMITTER_EMAIL")));
1211 if (mine.len < sb->len &&
1212 !strcmp(mine.buf, sb->buf + sb->len - mine.len))
1213 goto exit; /* no need to duplicate */
1215 /* Does it have any Signed-off-by: in the text */
1216 for (cp = sb->buf;
1217 cp && *cp && (cp = strstr(cp, sign_off_header)) != NULL;
1218 cp = strchr(cp, '\n')) {
1219 if (sb->buf == cp || cp[-1] == '\n')
1220 break;
1223 strbuf_addstr(sb, mine.buf + !!cp);
1224 exit:
1225 strbuf_release(&mine);
1229 * Appends signoff to the "msg" field of the am_state.
1231 static void am_append_signoff(struct am_state *state)
1233 struct strbuf sb = STRBUF_INIT;
1235 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1236 am_signoff(&sb);
1237 state->msg = strbuf_detach(&sb, &state->msg_len);
1241 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1242 * state->msg will be set to the patch message. state->author_name,
1243 * state->author_email and state->author_date will be set to the patch author's
1244 * name, email and date respectively. The patch body will be written to the
1245 * state directory's "patch" file.
1247 * Returns 1 if the patch should be skipped, 0 otherwise.
1249 static int parse_mail(struct am_state *state, const char *mail)
1251 FILE *fp;
1252 struct strbuf sb = STRBUF_INIT;
1253 struct strbuf msg = STRBUF_INIT;
1254 struct strbuf author_name = STRBUF_INIT;
1255 struct strbuf author_date = STRBUF_INIT;
1256 struct strbuf author_email = STRBUF_INIT;
1257 int ret = 0;
1258 struct mailinfo mi;
1260 setup_mailinfo(&mi);
1262 if (state->utf8)
1263 mi.metainfo_charset = get_commit_output_encoding();
1264 else
1265 mi.metainfo_charset = NULL;
1267 switch (state->keep) {
1268 case KEEP_FALSE:
1269 break;
1270 case KEEP_TRUE:
1271 mi.keep_subject = 1;
1272 break;
1273 case KEEP_NON_PATCH:
1274 mi.keep_non_patch_brackets_in_subject = 1;
1275 break;
1276 default:
1277 die("BUG: invalid value for state->keep");
1280 if (state->message_id)
1281 mi.add_message_id = 1;
1283 switch (state->scissors) {
1284 case SCISSORS_UNSET:
1285 break;
1286 case SCISSORS_FALSE:
1287 mi.use_scissors = 0;
1288 break;
1289 case SCISSORS_TRUE:
1290 mi.use_scissors = 1;
1291 break;
1292 default:
1293 die("BUG: invalid value for state->scissors");
1296 mi.input = fopen(mail, "r");
1297 if (!mi.input)
1298 die("could not open input");
1299 mi.output = fopen(am_path(state, "info"), "w");
1300 if (!mi.output)
1301 die("could not open output 'info'");
1302 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1303 die("could not parse patch");
1305 fclose(mi.input);
1306 fclose(mi.output);
1308 /* Extract message and author information */
1309 fp = xfopen(am_path(state, "info"), "r");
1310 while (!strbuf_getline_lf(&sb, fp)) {
1311 const char *x;
1313 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1314 if (msg.len)
1315 strbuf_addch(&msg, '\n');
1316 strbuf_addstr(&msg, x);
1317 } else if (skip_prefix(sb.buf, "Author: ", &x))
1318 strbuf_addstr(&author_name, x);
1319 else if (skip_prefix(sb.buf, "Email: ", &x))
1320 strbuf_addstr(&author_email, x);
1321 else if (skip_prefix(sb.buf, "Date: ", &x))
1322 strbuf_addstr(&author_date, x);
1324 fclose(fp);
1326 /* Skip pine's internal folder data */
1327 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1328 ret = 1;
1329 goto finish;
1332 if (is_empty_file(am_path(state, "patch"))) {
1333 printf_ln(_("Patch is empty. Was it split wrong?"));
1334 die_user_resolve(state);
1337 strbuf_addstr(&msg, "\n\n");
1338 strbuf_addbuf(&msg, &mi.log_message);
1339 strbuf_stripspace(&msg, 0);
1341 if (state->signoff)
1342 am_signoff(&msg);
1344 assert(!state->author_name);
1345 state->author_name = strbuf_detach(&author_name, NULL);
1347 assert(!state->author_email);
1348 state->author_email = strbuf_detach(&author_email, NULL);
1350 assert(!state->author_date);
1351 state->author_date = strbuf_detach(&author_date, NULL);
1353 assert(!state->msg);
1354 state->msg = strbuf_detach(&msg, &state->msg_len);
1356 finish:
1357 strbuf_release(&msg);
1358 strbuf_release(&author_date);
1359 strbuf_release(&author_email);
1360 strbuf_release(&author_name);
1361 strbuf_release(&sb);
1362 clear_mailinfo(&mi);
1363 return ret;
1367 * Sets commit_id to the commit hash where the mail was generated from.
1368 * Returns 0 on success, -1 on failure.
1370 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1372 struct strbuf sb = STRBUF_INIT;
1373 FILE *fp = xfopen(mail, "r");
1374 const char *x;
1376 if (strbuf_getline_lf(&sb, fp))
1377 return -1;
1379 if (!skip_prefix(sb.buf, "From ", &x))
1380 return -1;
1382 if (get_sha1_hex(x, commit_id) < 0)
1383 return -1;
1385 strbuf_release(&sb);
1386 fclose(fp);
1387 return 0;
1391 * Sets state->msg, state->author_name, state->author_email, state->author_date
1392 * to the commit's respective info.
1394 static void get_commit_info(struct am_state *state, struct commit *commit)
1396 const char *buffer, *ident_line, *author_date, *msg;
1397 size_t ident_len;
1398 struct ident_split ident_split;
1399 struct strbuf sb = STRBUF_INIT;
1401 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1403 ident_line = find_commit_header(buffer, "author", &ident_len);
1405 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1406 strbuf_add(&sb, ident_line, ident_len);
1407 die(_("invalid ident line: %s"), sb.buf);
1410 assert(!state->author_name);
1411 if (ident_split.name_begin) {
1412 strbuf_add(&sb, ident_split.name_begin,
1413 ident_split.name_end - ident_split.name_begin);
1414 state->author_name = strbuf_detach(&sb, NULL);
1415 } else
1416 state->author_name = xstrdup("");
1418 assert(!state->author_email);
1419 if (ident_split.mail_begin) {
1420 strbuf_add(&sb, ident_split.mail_begin,
1421 ident_split.mail_end - ident_split.mail_begin);
1422 state->author_email = strbuf_detach(&sb, NULL);
1423 } else
1424 state->author_email = xstrdup("");
1426 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1427 strbuf_addstr(&sb, author_date);
1428 assert(!state->author_date);
1429 state->author_date = strbuf_detach(&sb, NULL);
1431 assert(!state->msg);
1432 msg = strstr(buffer, "\n\n");
1433 if (!msg)
1434 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1435 state->msg = xstrdup(msg + 2);
1436 state->msg_len = strlen(state->msg);
1440 * Writes `commit` as a patch to the state directory's "patch" file.
1442 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1444 struct rev_info rev_info;
1445 FILE *fp;
1447 fp = xfopen(am_path(state, "patch"), "w");
1448 init_revisions(&rev_info, NULL);
1449 rev_info.diff = 1;
1450 rev_info.abbrev = 0;
1451 rev_info.disable_stdin = 1;
1452 rev_info.show_root_diff = 1;
1453 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1454 rev_info.no_commit_id = 1;
1455 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1456 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1457 rev_info.diffopt.use_color = 0;
1458 rev_info.diffopt.file = fp;
1459 rev_info.diffopt.close_file = 1;
1460 add_pending_object(&rev_info, &commit->object, "");
1461 diff_setup_done(&rev_info.diffopt);
1462 log_tree_commit(&rev_info, commit);
1466 * Writes the diff of the index against HEAD as a patch to the state
1467 * directory's "patch" file.
1469 static void write_index_patch(const struct am_state *state)
1471 struct tree *tree;
1472 unsigned char head[GIT_SHA1_RAWSZ];
1473 struct rev_info rev_info;
1474 FILE *fp;
1476 if (!get_sha1_tree("HEAD", head))
1477 tree = lookup_tree(head);
1478 else
1479 tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
1481 fp = xfopen(am_path(state, "patch"), "w");
1482 init_revisions(&rev_info, NULL);
1483 rev_info.diff = 1;
1484 rev_info.disable_stdin = 1;
1485 rev_info.no_commit_id = 1;
1486 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1487 rev_info.diffopt.use_color = 0;
1488 rev_info.diffopt.file = fp;
1489 rev_info.diffopt.close_file = 1;
1490 add_pending_object(&rev_info, &tree->object, "");
1491 diff_setup_done(&rev_info.diffopt);
1492 run_diff_index(&rev_info, 1);
1496 * Like parse_mail(), but parses the mail by looking up its commit ID
1497 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1498 * of patches.
1500 * state->orig_commit will be set to the original commit ID.
1502 * Will always return 0 as the patch should never be skipped.
1504 static int parse_mail_rebase(struct am_state *state, const char *mail)
1506 struct commit *commit;
1507 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1509 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1510 die(_("could not parse %s"), mail);
1512 commit = lookup_commit_or_die(commit_sha1, mail);
1514 get_commit_info(state, commit);
1516 write_commit_patch(state, commit);
1518 hashcpy(state->orig_commit, commit_sha1);
1519 write_state_text(state, "original-commit", sha1_to_hex(commit_sha1));
1521 return 0;
1525 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1526 * `index_file` is not NULL, the patch will be applied to that index.
1528 static int run_apply(const struct am_state *state, const char *index_file)
1530 struct child_process cp = CHILD_PROCESS_INIT;
1532 cp.git_cmd = 1;
1534 if (index_file)
1535 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1538 * If we are allowed to fall back on 3-way merge, don't give false
1539 * errors during the initial attempt.
1541 if (state->threeway && !index_file) {
1542 cp.no_stdout = 1;
1543 cp.no_stderr = 1;
1546 argv_array_push(&cp.args, "apply");
1548 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1550 if (index_file)
1551 argv_array_push(&cp.args, "--cached");
1552 else
1553 argv_array_push(&cp.args, "--index");
1555 argv_array_push(&cp.args, am_path(state, "patch"));
1557 if (run_command(&cp))
1558 return -1;
1560 /* Reload index as git-apply will have modified it. */
1561 discard_cache();
1562 read_cache_from(index_file ? index_file : get_index_file());
1564 return 0;
1568 * Builds an index that contains just the blobs needed for a 3way merge.
1570 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1572 struct child_process cp = CHILD_PROCESS_INIT;
1574 cp.git_cmd = 1;
1575 argv_array_push(&cp.args, "apply");
1576 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1577 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1578 argv_array_push(&cp.args, am_path(state, "patch"));
1580 if (run_command(&cp))
1581 return -1;
1583 return 0;
1587 * Do the three-way merge using fake ancestor, his tree constructed
1588 * from the fake ancestor and the postimage of the patch, and our
1589 * state.
1591 static int run_fallback_merge_recursive(const struct am_state *state,
1592 unsigned char *orig_tree,
1593 unsigned char *our_tree,
1594 unsigned char *his_tree)
1596 struct child_process cp = CHILD_PROCESS_INIT;
1597 int status;
1599 cp.git_cmd = 1;
1601 argv_array_pushf(&cp.env_array, "GITHEAD_%s=%.*s",
1602 sha1_to_hex(his_tree), linelen(state->msg), state->msg);
1603 if (state->quiet)
1604 argv_array_push(&cp.env_array, "GIT_MERGE_VERBOSITY=0");
1606 argv_array_push(&cp.args, "merge-recursive");
1607 argv_array_push(&cp.args, sha1_to_hex(orig_tree));
1608 argv_array_push(&cp.args, "--");
1609 argv_array_push(&cp.args, sha1_to_hex(our_tree));
1610 argv_array_push(&cp.args, sha1_to_hex(his_tree));
1612 status = run_command(&cp) ? (-1) : 0;
1613 discard_cache();
1614 read_cache();
1615 return status;
1619 * Attempt a threeway merge, using index_path as the temporary index.
1621 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1623 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1624 our_tree[GIT_SHA1_RAWSZ];
1626 if (get_sha1("HEAD", our_tree) < 0)
1627 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1629 if (build_fake_ancestor(state, index_path))
1630 return error("could not build fake ancestor");
1632 discard_cache();
1633 read_cache_from(index_path);
1635 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1636 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1638 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1640 if (!state->quiet) {
1642 * List paths that needed 3-way fallback, so that the user can
1643 * review them with extra care to spot mismerges.
1645 struct rev_info rev_info;
1646 const char *diff_filter_str = "--diff-filter=AM";
1648 init_revisions(&rev_info, NULL);
1649 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1650 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1651 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1652 diff_setup_done(&rev_info.diffopt);
1653 run_diff_index(&rev_info, 1);
1656 if (run_apply(state, index_path))
1657 return error(_("Did you hand edit your patch?\n"
1658 "It does not apply to blobs recorded in its index."));
1660 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1661 return error("could not write tree");
1663 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1665 discard_cache();
1666 read_cache();
1669 * This is not so wrong. Depending on which base we picked, orig_tree
1670 * may be wildly different from ours, but his_tree has the same set of
1671 * wildly different changes in parts the patch did not touch, so
1672 * recursive ends up canceling them, saying that we reverted all those
1673 * changes.
1676 if (run_fallback_merge_recursive(state, orig_tree, our_tree, his_tree)) {
1677 rerere(state->allow_rerere_autoupdate);
1678 return error(_("Failed to merge in the changes."));
1681 return 0;
1685 * Commits the current index with state->msg as the commit message and
1686 * state->author_name, state->author_email and state->author_date as the author
1687 * information.
1689 static void do_commit(const struct am_state *state)
1691 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1692 commit[GIT_SHA1_RAWSZ];
1693 unsigned char *ptr;
1694 struct commit_list *parents = NULL;
1695 const char *reflog_msg, *author;
1696 struct strbuf sb = STRBUF_INIT;
1698 if (run_hook_le(NULL, "pre-applypatch", NULL))
1699 exit(1);
1701 if (write_cache_as_tree(tree, 0, NULL))
1702 die(_("git write-tree failed to write a tree"));
1704 if (!get_sha1_commit("HEAD", parent)) {
1705 ptr = parent;
1706 commit_list_insert(lookup_commit(parent), &parents);
1707 } else {
1708 ptr = NULL;
1709 say(state, stderr, _("applying to an empty history"));
1712 author = fmt_ident(state->author_name, state->author_email,
1713 state->ignore_date ? NULL : state->author_date,
1714 IDENT_STRICT);
1716 if (state->committer_date_is_author_date)
1717 setenv("GIT_COMMITTER_DATE",
1718 state->ignore_date ? "" : state->author_date, 1);
1720 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1721 author, state->sign_commit))
1722 die(_("failed to write commit object"));
1724 reflog_msg = getenv("GIT_REFLOG_ACTION");
1725 if (!reflog_msg)
1726 reflog_msg = "am";
1728 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1729 state->msg);
1731 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1733 if (state->rebasing) {
1734 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1736 assert(!is_null_sha1(state->orig_commit));
1737 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1738 fprintf(fp, "%s\n", sha1_to_hex(commit));
1739 fclose(fp);
1742 run_hook_le(NULL, "post-applypatch", NULL);
1744 strbuf_release(&sb);
1748 * Validates the am_state for resuming -- the "msg" and authorship fields must
1749 * be filled up.
1751 static void validate_resume_state(const struct am_state *state)
1753 if (!state->msg)
1754 die(_("cannot resume: %s does not exist."),
1755 am_path(state, "final-commit"));
1757 if (!state->author_name || !state->author_email || !state->author_date)
1758 die(_("cannot resume: %s does not exist."),
1759 am_path(state, "author-script"));
1763 * Interactively prompt the user on whether the current patch should be
1764 * applied.
1766 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1767 * skip it.
1769 static int do_interactive(struct am_state *state)
1771 assert(state->msg);
1773 if (!isatty(0))
1774 die(_("cannot be interactive without stdin connected to a terminal."));
1776 for (;;) {
1777 const char *reply;
1779 puts(_("Commit Body is:"));
1780 puts("--------------------------");
1781 printf("%s", state->msg);
1782 puts("--------------------------");
1785 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1786 * in your translation. The program will only accept English
1787 * input at this point.
1789 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1791 if (!reply) {
1792 continue;
1793 } else if (*reply == 'y' || *reply == 'Y') {
1794 return 0;
1795 } else if (*reply == 'a' || *reply == 'A') {
1796 state->interactive = 0;
1797 return 0;
1798 } else if (*reply == 'n' || *reply == 'N') {
1799 return 1;
1800 } else if (*reply == 'e' || *reply == 'E') {
1801 struct strbuf msg = STRBUF_INIT;
1803 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1804 free(state->msg);
1805 state->msg = strbuf_detach(&msg, &state->msg_len);
1807 strbuf_release(&msg);
1808 } else if (*reply == 'v' || *reply == 'V') {
1809 const char *pager = git_pager(1);
1810 struct child_process cp = CHILD_PROCESS_INIT;
1812 if (!pager)
1813 pager = "cat";
1814 prepare_pager_args(&cp, pager);
1815 argv_array_push(&cp.args, am_path(state, "patch"));
1816 run_command(&cp);
1822 * Applies all queued mail.
1824 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1825 * well as the state directory's "patch" file is used as-is for applying the
1826 * patch and committing it.
1828 static void am_run(struct am_state *state, int resume)
1830 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1831 struct strbuf sb = STRBUF_INIT;
1833 unlink(am_path(state, "dirtyindex"));
1835 refresh_and_write_cache();
1837 if (index_has_changes(&sb)) {
1838 write_state_bool(state, "dirtyindex", 1);
1839 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1842 strbuf_release(&sb);
1844 while (state->cur <= state->last) {
1845 const char *mail = am_path(state, msgnum(state));
1846 int apply_status;
1848 if (!file_exists(mail))
1849 goto next;
1851 if (resume) {
1852 validate_resume_state(state);
1853 } else {
1854 int skip;
1856 if (state->rebasing)
1857 skip = parse_mail_rebase(state, mail);
1858 else
1859 skip = parse_mail(state, mail);
1861 if (skip)
1862 goto next; /* mail should be skipped */
1864 write_author_script(state);
1865 write_commit_msg(state);
1868 if (state->interactive && do_interactive(state))
1869 goto next;
1871 if (run_applypatch_msg_hook(state))
1872 exit(1);
1874 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1876 apply_status = run_apply(state, NULL);
1878 if (apply_status && state->threeway) {
1879 struct strbuf sb = STRBUF_INIT;
1881 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1882 apply_status = fall_back_threeway(state, sb.buf);
1883 strbuf_release(&sb);
1886 * Applying the patch to an earlier tree and merging
1887 * the result may have produced the same tree as ours.
1889 if (!apply_status && !index_has_changes(NULL)) {
1890 say(state, stdout, _("No changes -- Patch already applied."));
1891 goto next;
1895 if (apply_status) {
1896 int advice_amworkdir = 1;
1898 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1899 linelen(state->msg), state->msg);
1901 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1903 if (advice_amworkdir)
1904 printf_ln(_("The copy of the patch that failed is found in: %s"),
1905 am_path(state, "patch"));
1907 die_user_resolve(state);
1910 do_commit(state);
1912 next:
1913 am_next(state);
1915 if (resume)
1916 am_load(state);
1917 resume = 0;
1920 if (!is_empty_file(am_path(state, "rewritten"))) {
1921 assert(state->rebasing);
1922 copy_notes_for_rebase(state);
1923 run_post_rewrite_hook(state);
1927 * In rebasing mode, it's up to the caller to take care of
1928 * housekeeping.
1930 if (!state->rebasing) {
1931 am_destroy(state);
1932 close_all_packs();
1933 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1938 * Resume the current am session after patch application failure. The user did
1939 * all the hard work, and we do not have to do any patch application. Just
1940 * trust and commit what the user has in the index and working tree.
1942 static void am_resolve(struct am_state *state)
1944 validate_resume_state(state);
1946 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1948 if (!index_has_changes(NULL)) {
1949 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1950 "If there is nothing left to stage, chances are that something else\n"
1951 "already introduced the same changes; you might want to skip this patch."));
1952 die_user_resolve(state);
1955 if (unmerged_cache()) {
1956 printf_ln(_("You still have unmerged paths in your index.\n"
1957 "Did you forget to use 'git add'?"));
1958 die_user_resolve(state);
1961 if (state->interactive) {
1962 write_index_patch(state);
1963 if (do_interactive(state))
1964 goto next;
1967 rerere(0);
1969 do_commit(state);
1971 next:
1972 am_next(state);
1973 am_load(state);
1974 am_run(state, 0);
1978 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1979 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1980 * failure.
1982 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1984 struct lock_file *lock_file;
1985 struct unpack_trees_options opts;
1986 struct tree_desc t[2];
1988 if (parse_tree(head) || parse_tree(remote))
1989 return -1;
1991 lock_file = xcalloc(1, sizeof(struct lock_file));
1992 hold_locked_index(lock_file, 1);
1994 refresh_cache(REFRESH_QUIET);
1996 memset(&opts, 0, sizeof(opts));
1997 opts.head_idx = 1;
1998 opts.src_index = &the_index;
1999 opts.dst_index = &the_index;
2000 opts.update = 1;
2001 opts.merge = 1;
2002 opts.reset = reset;
2003 opts.fn = twoway_merge;
2004 init_tree_desc(&t[0], head->buffer, head->size);
2005 init_tree_desc(&t[1], remote->buffer, remote->size);
2007 if (unpack_trees(2, t, &opts)) {
2008 rollback_lock_file(lock_file);
2009 return -1;
2012 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
2013 die(_("unable to write new index file"));
2015 return 0;
2019 * Merges a tree into the index. The index's stat info will take precedence
2020 * over the merged tree's. Returns 0 on success, -1 on failure.
2022 static int merge_tree(struct tree *tree)
2024 struct lock_file *lock_file;
2025 struct unpack_trees_options opts;
2026 struct tree_desc t[1];
2028 if (parse_tree(tree))
2029 return -1;
2031 lock_file = xcalloc(1, sizeof(struct lock_file));
2032 hold_locked_index(lock_file, 1);
2034 memset(&opts, 0, sizeof(opts));
2035 opts.head_idx = 1;
2036 opts.src_index = &the_index;
2037 opts.dst_index = &the_index;
2038 opts.merge = 1;
2039 opts.fn = oneway_merge;
2040 init_tree_desc(&t[0], tree->buffer, tree->size);
2042 if (unpack_trees(1, t, &opts)) {
2043 rollback_lock_file(lock_file);
2044 return -1;
2047 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
2048 die(_("unable to write new index file"));
2050 return 0;
2054 * Clean the index without touching entries that are not modified between
2055 * `head` and `remote`.
2057 static int clean_index(const unsigned char *head, const unsigned char *remote)
2059 struct tree *head_tree, *remote_tree, *index_tree;
2060 unsigned char index[GIT_SHA1_RAWSZ];
2062 head_tree = parse_tree_indirect(head);
2063 if (!head_tree)
2064 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
2066 remote_tree = parse_tree_indirect(remote);
2067 if (!remote_tree)
2068 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
2070 read_cache_unmerged();
2072 if (fast_forward_to(head_tree, head_tree, 1))
2073 return -1;
2075 if (write_cache_as_tree(index, 0, NULL))
2076 return -1;
2078 index_tree = parse_tree_indirect(index);
2079 if (!index_tree)
2080 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
2082 if (fast_forward_to(index_tree, remote_tree, 0))
2083 return -1;
2085 if (merge_tree(remote_tree))
2086 return -1;
2088 remove_branch_state();
2090 return 0;
2094 * Resets rerere's merge resolution metadata.
2096 static void am_rerere_clear(void)
2098 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2099 rerere_clear(&merge_rr);
2100 string_list_clear(&merge_rr, 1);
2104 * Resume the current am session by skipping the current patch.
2106 static void am_skip(struct am_state *state)
2108 unsigned char head[GIT_SHA1_RAWSZ];
2110 am_rerere_clear();
2112 if (get_sha1("HEAD", head))
2113 hashcpy(head, EMPTY_TREE_SHA1_BIN);
2115 if (clean_index(head, head))
2116 die(_("failed to clean index"));
2118 am_next(state);
2119 am_load(state);
2120 am_run(state, 0);
2124 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2126 * It is not safe to reset HEAD when:
2127 * 1. git-am previously failed because the index was dirty.
2128 * 2. HEAD has moved since git-am previously failed.
2130 static int safe_to_abort(const struct am_state *state)
2132 struct strbuf sb = STRBUF_INIT;
2133 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
2135 if (file_exists(am_path(state, "dirtyindex")))
2136 return 0;
2138 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2139 if (get_sha1_hex(sb.buf, abort_safety))
2140 die(_("could not parse %s"), am_path(state, "abort_safety"));
2141 } else
2142 hashclr(abort_safety);
2144 if (get_sha1("HEAD", head))
2145 hashclr(head);
2147 if (!hashcmp(head, abort_safety))
2148 return 1;
2150 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2151 "Not rewinding to ORIG_HEAD"));
2153 return 0;
2157 * Aborts the current am session if it is safe to do so.
2159 static void am_abort(struct am_state *state)
2161 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
2162 int has_curr_head, has_orig_head;
2163 char *curr_branch;
2165 if (!safe_to_abort(state)) {
2166 am_destroy(state);
2167 return;
2170 am_rerere_clear();
2172 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
2173 has_curr_head = !is_null_sha1(curr_head);
2174 if (!has_curr_head)
2175 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
2177 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
2178 if (!has_orig_head)
2179 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
2181 clean_index(curr_head, orig_head);
2183 if (has_orig_head)
2184 update_ref("am --abort", "HEAD", orig_head,
2185 has_curr_head ? curr_head : NULL, 0,
2186 UPDATE_REFS_DIE_ON_ERR);
2187 else if (curr_branch)
2188 delete_ref(curr_branch, NULL, REF_NODEREF);
2190 free(curr_branch);
2191 am_destroy(state);
2195 * parse_options() callback that validates and sets opt->value to the
2196 * PATCH_FORMAT_* enum value corresponding to `arg`.
2198 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2200 int *opt_value = opt->value;
2202 if (!strcmp(arg, "mbox"))
2203 *opt_value = PATCH_FORMAT_MBOX;
2204 else if (!strcmp(arg, "stgit"))
2205 *opt_value = PATCH_FORMAT_STGIT;
2206 else if (!strcmp(arg, "stgit-series"))
2207 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2208 else if (!strcmp(arg, "hg"))
2209 *opt_value = PATCH_FORMAT_HG;
2210 else if (!strcmp(arg, "mboxrd"))
2211 *opt_value = PATCH_FORMAT_MBOXRD;
2212 else
2213 return error(_("Invalid value for --patch-format: %s"), arg);
2214 return 0;
2217 enum resume_mode {
2218 RESUME_FALSE = 0,
2219 RESUME_APPLY,
2220 RESUME_RESOLVED,
2221 RESUME_SKIP,
2222 RESUME_ABORT
2225 static int git_am_config(const char *k, const char *v, void *cb)
2227 int status;
2229 status = git_gpg_config(k, v, NULL);
2230 if (status)
2231 return status;
2233 return git_default_config(k, v, NULL);
2236 int cmd_am(int argc, const char **argv, const char *prefix)
2238 struct am_state state;
2239 int binary = -1;
2240 int keep_cr = -1;
2241 int patch_format = PATCH_FORMAT_UNKNOWN;
2242 enum resume_mode resume = RESUME_FALSE;
2243 int in_progress;
2245 const char * const usage[] = {
2246 N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
2247 N_("git am [<options>] (--continue | --skip | --abort)"),
2248 NULL
2251 struct option options[] = {
2252 OPT_BOOL('i', "interactive", &state.interactive,
2253 N_("run interactively")),
2254 OPT_HIDDEN_BOOL('b', "binary", &binary,
2255 N_("historical option -- no-op")),
2256 OPT_BOOL('3', "3way", &state.threeway,
2257 N_("allow fall back on 3way merging if needed")),
2258 OPT__QUIET(&state.quiet, N_("be quiet")),
2259 OPT_SET_INT('s', "signoff", &state.signoff,
2260 N_("add a Signed-off-by line to the commit message"),
2261 SIGNOFF_EXPLICIT),
2262 OPT_BOOL('u', "utf8", &state.utf8,
2263 N_("recode into utf8 (default)")),
2264 OPT_SET_INT('k', "keep", &state.keep,
2265 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2266 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2267 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2268 OPT_BOOL('m', "message-id", &state.message_id,
2269 N_("pass -m flag to git-mailinfo")),
2270 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2271 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2272 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2273 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2274 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2275 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2276 OPT_BOOL('c', "scissors", &state.scissors,
2277 N_("strip everything before a scissors line")),
2278 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2279 N_("pass it through git-apply"),
2281 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2282 N_("pass it through git-apply"),
2283 PARSE_OPT_NOARG),
2284 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2285 N_("pass it through git-apply"),
2286 PARSE_OPT_NOARG),
2287 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2288 N_("pass it through git-apply"),
2290 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2291 N_("pass it through git-apply"),
2293 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2294 N_("pass it through git-apply"),
2296 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2297 N_("pass it through git-apply"),
2299 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2300 N_("pass it through git-apply"),
2302 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2303 N_("format the patch(es) are in"),
2304 parse_opt_patchformat),
2305 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2306 N_("pass it through git-apply"),
2307 PARSE_OPT_NOARG),
2308 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2309 N_("override error message when patch failure occurs")),
2310 OPT_CMDMODE(0, "continue", &resume,
2311 N_("continue applying patches after resolving a conflict"),
2312 RESUME_RESOLVED),
2313 OPT_CMDMODE('r', "resolved", &resume,
2314 N_("synonyms for --continue"),
2315 RESUME_RESOLVED),
2316 OPT_CMDMODE(0, "skip", &resume,
2317 N_("skip the current patch"),
2318 RESUME_SKIP),
2319 OPT_CMDMODE(0, "abort", &resume,
2320 N_("restore the original branch and abort the patching operation."),
2321 RESUME_ABORT),
2322 OPT_BOOL(0, "committer-date-is-author-date",
2323 &state.committer_date_is_author_date,
2324 N_("lie about committer date")),
2325 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2326 N_("use current timestamp for author date")),
2327 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2328 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2329 N_("GPG-sign commits"),
2330 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2331 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2332 N_("(internal use for git-rebase)")),
2333 OPT_END()
2336 git_config(git_am_config, NULL);
2338 am_state_init(&state, git_path("rebase-apply"));
2340 in_progress = am_in_progress(&state);
2341 if (in_progress)
2342 am_load(&state);
2344 argc = parse_options(argc, argv, prefix, options, usage, 0);
2346 if (binary >= 0)
2347 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2348 "it will be removed. Please do not use it anymore."));
2350 /* Ensure a valid committer ident can be constructed */
2351 git_committer_info(IDENT_STRICT);
2353 if (read_index_preload(&the_index, NULL) < 0)
2354 die(_("failed to read the index"));
2356 if (in_progress) {
2358 * Catch user error to feed us patches when there is a session
2359 * in progress:
2361 * 1. mbox path(s) are provided on the command-line.
2362 * 2. stdin is not a tty: the user is trying to feed us a patch
2363 * from standard input. This is somewhat unreliable -- stdin
2364 * could be /dev/null for example and the caller did not
2365 * intend to feed us a patch but wanted to continue
2366 * unattended.
2368 if (argc || (resume == RESUME_FALSE && !isatty(0)))
2369 die(_("previous rebase directory %s still exists but mbox given."),
2370 state.dir);
2372 if (resume == RESUME_FALSE)
2373 resume = RESUME_APPLY;
2375 if (state.signoff == SIGNOFF_EXPLICIT)
2376 am_append_signoff(&state);
2377 } else {
2378 struct argv_array paths = ARGV_ARRAY_INIT;
2379 int i;
2382 * Handle stray state directory in the independent-run case. In
2383 * the --rebasing case, it is up to the caller to take care of
2384 * stray directories.
2386 if (file_exists(state.dir) && !state.rebasing) {
2387 if (resume == RESUME_ABORT) {
2388 am_destroy(&state);
2389 am_state_release(&state);
2390 return 0;
2393 die(_("Stray %s directory found.\n"
2394 "Use \"git am --abort\" to remove it."),
2395 state.dir);
2398 if (resume)
2399 die(_("Resolve operation not in progress, we are not resuming."));
2401 for (i = 0; i < argc; i++) {
2402 if (is_absolute_path(argv[i]) || !prefix)
2403 argv_array_push(&paths, argv[i]);
2404 else
2405 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2408 am_setup(&state, patch_format, paths.argv, keep_cr);
2410 argv_array_clear(&paths);
2413 switch (resume) {
2414 case RESUME_FALSE:
2415 am_run(&state, 0);
2416 break;
2417 case RESUME_APPLY:
2418 am_run(&state, 1);
2419 break;
2420 case RESUME_RESOLVED:
2421 am_resolve(&state);
2422 break;
2423 case RESUME_SKIP:
2424 am_skip(&state);
2425 break;
2426 case RESUME_ABORT:
2427 am_abort(&state);
2428 break;
2429 default:
2430 die("BUG: invalid resume value");
2433 am_state_release(&state);
2435 return 0;