4 * Based on git-am.sh by Junio C Hamano.
10 #include "parse-options.h"
12 #include "run-command.h"
16 #include "cache-tree.h"
21 #include "unpack-trees.h"
23 #include "sequencer.h"
25 #include "merge-recursive.h"
28 #include "notes-utils.h"
33 #include "string-list.h"
37 * Returns the length of the first line of msg.
39 static int linelen(const char *msg)
41 return strchrnul(msg, '\n') - msg;
45 * Returns true if `str` consists of only whitespace, false otherwise.
47 static int str_isspace(const char *str)
57 PATCH_FORMAT_UNKNOWN = 0,
60 PATCH_FORMAT_STGIT_SERIES,
67 KEEP_TRUE, /* pass -k flag to git-mailinfo */
68 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
73 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
74 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
80 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
84 /* state directory path */
87 /* current and last patch numbers, 1-indexed */
91 /* commit metadata and message */
98 /* when --rebasing, records the original commit the patch came from */
99 struct object_id orig_commit;
101 /* number of digits in patch filename */
104 /* various operating modes and command line options */
108 int signoff; /* enum signoff_type */
110 int keep; /* enum keep_type */
112 int scissors; /* enum scissors_type */
113 struct argv_array git_apply_opts;
114 const char *resolvemsg;
115 int committer_date_is_author_date;
117 int allow_rerere_autoupdate;
118 const char *sign_commit;
123 * Initializes am_state with the default values.
125 static void am_state_init(struct am_state *state)
129 memset(state, 0, sizeof(*state));
131 state->dir = git_pathdup("rebase-apply");
135 git_config_get_bool("am.threeway", &state->threeway);
139 git_config_get_bool("am.messageid", &state->message_id);
141 state->scissors = SCISSORS_UNSET;
143 argv_array_init(&state->git_apply_opts);
145 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
146 state->sign_commit = gpgsign ? "" : NULL;
150 * Releases memory allocated by an am_state.
152 static void am_state_release(struct am_state *state)
155 free(state->author_name);
156 free(state->author_email);
157 free(state->author_date);
159 argv_array_clear(&state->git_apply_opts);
163 * Returns path relative to the am_state directory.
165 static inline const char *am_path(const struct am_state *state, const char *path)
167 return mkpath("%s/%s", state->dir, path);
171 * For convenience to call write_file()
173 static void write_state_text(const struct am_state *state,
174 const char *name, const char *string)
176 write_file(am_path(state, name), "%s", string);
179 static void write_state_count(const struct am_state *state,
180 const char *name, int value)
182 write_file(am_path(state, name), "%d", value);
185 static void write_state_bool(const struct am_state *state,
186 const char *name, int value)
188 write_state_text(state, name, value ? "t" : "f");
192 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
195 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
201 vfprintf(fp, fmt, ap);
208 * Returns 1 if there is an am session in progress, 0 otherwise.
210 static int am_in_progress(const struct am_state *state)
214 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
216 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
218 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
224 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
225 * number of bytes read on success, -1 if the file does not exist. If `trim` is
226 * set, trailing whitespace will be removed.
228 static int read_state_file(struct strbuf *sb, const struct am_state *state,
229 const char *file, int trim)
233 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
243 die_errno(_("could not read '%s'"), am_path(state, file));
247 * Take a series of KEY='VALUE' lines where VALUE part is
248 * sq-quoted, and append <KEY, VALUE> at the end of the string list
250 static int parse_key_value_squoted(char *buf, struct string_list *list)
253 struct string_list_item *item;
255 char *cp = strchr(buf, '=');
258 np = strchrnul(cp, '\n');
260 item = string_list_append(list, buf);
262 buf = np + (*np == '\n');
267 item->util = xstrdup(cp);
273 * Reads and parses the state directory's "author-script" file, and sets
274 * state->author_name, state->author_email and state->author_date accordingly.
275 * Returns 0 on success, -1 if the file could not be parsed.
277 * The author script is of the format:
279 * GIT_AUTHOR_NAME='$author_name'
280 * GIT_AUTHOR_EMAIL='$author_email'
281 * GIT_AUTHOR_DATE='$author_date'
283 * where $author_name, $author_email and $author_date are quoted. We are strict
284 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
285 * script, and thus if the file differs from what this function expects, it is
286 * better to bail out than to do something that the user does not expect.
288 static int read_author_script(struct am_state *state)
290 const char *filename = am_path(state, "author-script");
291 struct strbuf buf = STRBUF_INIT;
292 struct string_list kv = STRING_LIST_INIT_DUP;
293 int retval = -1; /* assume failure */
296 assert(!state->author_name);
297 assert(!state->author_email);
298 assert(!state->author_date);
300 fd = open(filename, O_RDONLY);
304 die_errno(_("could not open '%s' for reading"), filename);
306 strbuf_read(&buf, fd, 0);
308 if (parse_key_value_squoted(buf.buf, &kv))
312 strcmp(kv.items[0].string, "GIT_AUTHOR_NAME") ||
313 strcmp(kv.items[1].string, "GIT_AUTHOR_EMAIL") ||
314 strcmp(kv.items[2].string, "GIT_AUTHOR_DATE"))
316 state->author_name = kv.items[0].util;
317 state->author_email = kv.items[1].util;
318 state->author_date = kv.items[2].util;
321 string_list_clear(&kv, !!retval);
322 strbuf_release(&buf);
327 * Saves state->author_name, state->author_email and state->author_date in the
328 * state directory's "author-script" file.
330 static void write_author_script(const struct am_state *state)
332 struct strbuf sb = STRBUF_INIT;
334 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
335 sq_quote_buf(&sb, state->author_name);
336 strbuf_addch(&sb, '\n');
338 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
339 sq_quote_buf(&sb, state->author_email);
340 strbuf_addch(&sb, '\n');
342 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
343 sq_quote_buf(&sb, state->author_date);
344 strbuf_addch(&sb, '\n');
346 write_state_text(state, "author-script", sb.buf);
352 * Reads the commit message from the state directory's "final-commit" file,
353 * setting state->msg to its contents and state->msg_len to the length of its
356 * Returns 0 on success, -1 if the file does not exist.
358 static int read_commit_msg(struct am_state *state)
360 struct strbuf sb = STRBUF_INIT;
364 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
369 state->msg = strbuf_detach(&sb, &state->msg_len);
374 * Saves state->msg in the state directory's "final-commit" file.
376 static void write_commit_msg(const struct am_state *state)
378 const char *filename = am_path(state, "final-commit");
379 write_file_buf(filename, state->msg, state->msg_len);
383 * Loads state from disk.
385 static void am_load(struct am_state *state)
387 struct strbuf sb = STRBUF_INIT;
389 if (read_state_file(&sb, state, "next", 1) < 0)
390 die("BUG: state file 'next' does not exist");
391 state->cur = strtol(sb.buf, NULL, 10);
393 if (read_state_file(&sb, state, "last", 1) < 0)
394 die("BUG: state file 'last' does not exist");
395 state->last = strtol(sb.buf, NULL, 10);
397 if (read_author_script(state) < 0)
398 die(_("could not parse author script"));
400 read_commit_msg(state);
402 if (read_state_file(&sb, state, "original-commit", 1) < 0)
403 oidclr(&state->orig_commit);
404 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
405 die(_("could not parse %s"), am_path(state, "original-commit"));
407 read_state_file(&sb, state, "threeway", 1);
408 state->threeway = !strcmp(sb.buf, "t");
410 read_state_file(&sb, state, "quiet", 1);
411 state->quiet = !strcmp(sb.buf, "t");
413 read_state_file(&sb, state, "sign", 1);
414 state->signoff = !strcmp(sb.buf, "t");
416 read_state_file(&sb, state, "utf8", 1);
417 state->utf8 = !strcmp(sb.buf, "t");
419 if (file_exists(am_path(state, "rerere-autoupdate"))) {
420 read_state_file(&sb, state, "rerere-autoupdate", 1);
421 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
422 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
424 state->allow_rerere_autoupdate = 0;
427 read_state_file(&sb, state, "keep", 1);
428 if (!strcmp(sb.buf, "t"))
429 state->keep = KEEP_TRUE;
430 else if (!strcmp(sb.buf, "b"))
431 state->keep = KEEP_NON_PATCH;
433 state->keep = KEEP_FALSE;
435 read_state_file(&sb, state, "messageid", 1);
436 state->message_id = !strcmp(sb.buf, "t");
438 read_state_file(&sb, state, "scissors", 1);
439 if (!strcmp(sb.buf, "t"))
440 state->scissors = SCISSORS_TRUE;
441 else if (!strcmp(sb.buf, "f"))
442 state->scissors = SCISSORS_FALSE;
444 state->scissors = SCISSORS_UNSET;
446 read_state_file(&sb, state, "apply-opt", 1);
447 argv_array_clear(&state->git_apply_opts);
448 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
449 die(_("could not parse %s"), am_path(state, "apply-opt"));
451 state->rebasing = !!file_exists(am_path(state, "rebasing"));
457 * Removes the am_state directory, forcefully terminating the current am
460 static void am_destroy(const struct am_state *state)
462 struct strbuf sb = STRBUF_INIT;
464 strbuf_addstr(&sb, state->dir);
465 remove_dir_recursively(&sb, 0);
470 * Runs applypatch-msg hook. Returns its exit code.
472 static int run_applypatch_msg_hook(struct am_state *state)
477 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
480 FREE_AND_NULL(state->msg);
481 if (read_commit_msg(state) < 0)
482 die(_("'%s' was deleted by the applypatch-msg hook"),
483 am_path(state, "final-commit"));
490 * Runs post-rewrite hook. Returns it exit code.
492 static int run_post_rewrite_hook(const struct am_state *state)
494 struct child_process cp = CHILD_PROCESS_INIT;
495 const char *hook = find_hook("post-rewrite");
501 argv_array_push(&cp.args, hook);
502 argv_array_push(&cp.args, "rebase");
504 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
505 cp.stdout_to_stderr = 1;
507 ret = run_command(&cp);
514 * Reads the state directory's "rewritten" file, and copies notes from the old
515 * commits listed in the file to their rewritten commits.
517 * Returns 0 on success, -1 on failure.
519 static int copy_notes_for_rebase(const struct am_state *state)
521 struct notes_rewrite_cfg *c;
522 struct strbuf sb = STRBUF_INIT;
523 const char *invalid_line = _("Malformed input line: '%s'.");
524 const char *msg = "Notes added by 'git rebase'";
528 assert(state->rebasing);
530 c = init_copy_notes_for_rewrite("rebase");
534 fp = xfopen(am_path(state, "rewritten"), "r");
536 while (!strbuf_getline_lf(&sb, fp)) {
537 struct object_id from_obj, to_obj;
539 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
540 ret = error(invalid_line, sb.buf);
544 if (get_oid_hex(sb.buf, &from_obj)) {
545 ret = error(invalid_line, sb.buf);
549 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
550 ret = error(invalid_line, sb.buf);
554 if (get_oid_hex(sb.buf + GIT_SHA1_HEXSZ + 1, &to_obj)) {
555 ret = error(invalid_line, sb.buf);
559 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
560 ret = error(_("Failed to copy notes from '%s' to '%s'"),
561 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
565 finish_copy_notes_for_rewrite(c, msg);
572 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
573 * non-indented lines and checking if they look like they begin with valid
574 * header field names.
576 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
578 static int is_mail(FILE *fp)
580 const char *header_regex = "^[!-9;-~]+:";
581 struct strbuf sb = STRBUF_INIT;
585 if (fseek(fp, 0L, SEEK_SET))
586 die_errno(_("fseek failed"));
588 if (regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED))
589 die("invalid pattern: %s", header_regex);
591 while (!strbuf_getline(&sb, fp)) {
593 break; /* End of header */
595 /* Ignore indented folded lines */
596 if (*sb.buf == '\t' || *sb.buf == ' ')
599 /* It's a header if it matches header_regex */
600 if (regexec(®ex, sb.buf, 0, NULL, 0)) {
613 * Attempts to detect the patch_format of the patches contained in `paths`,
614 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
617 static int detect_patch_format(const char **paths)
619 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
620 struct strbuf l1 = STRBUF_INIT;
621 struct strbuf l2 = STRBUF_INIT;
622 struct strbuf l3 = STRBUF_INIT;
626 * We default to mbox format if input is from stdin and for directories
628 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
629 return PATCH_FORMAT_MBOX;
632 * Otherwise, check the first few lines of the first patch, starting
633 * from the first non-blank line, to try to detect its format.
636 fp = xfopen(*paths, "r");
638 while (!strbuf_getline(&l1, fp)) {
643 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
644 ret = PATCH_FORMAT_MBOX;
648 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
649 ret = PATCH_FORMAT_STGIT_SERIES;
653 if (!strcmp(l1.buf, "# HG changeset patch")) {
654 ret = PATCH_FORMAT_HG;
658 strbuf_getline(&l2, fp);
659 strbuf_getline(&l3, fp);
662 * If the second line is empty and the third is a From, Author or Date
663 * entry, this is likely an StGit patch.
665 if (l1.len && !l2.len &&
666 (starts_with(l3.buf, "From:") ||
667 starts_with(l3.buf, "Author:") ||
668 starts_with(l3.buf, "Date:"))) {
669 ret = PATCH_FORMAT_STGIT;
673 if (l1.len && is_mail(fp)) {
674 ret = PATCH_FORMAT_MBOX;
687 * Splits out individual email patches from `paths`, where each path is either
688 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
690 static int split_mail_mbox(struct am_state *state, const char **paths,
691 int keep_cr, int mboxrd)
693 struct child_process cp = CHILD_PROCESS_INIT;
694 struct strbuf last = STRBUF_INIT;
698 argv_array_push(&cp.args, "mailsplit");
699 argv_array_pushf(&cp.args, "-d%d", state->prec);
700 argv_array_pushf(&cp.args, "-o%s", state->dir);
701 argv_array_push(&cp.args, "-b");
703 argv_array_push(&cp.args, "--keep-cr");
705 argv_array_push(&cp.args, "--mboxrd");
706 argv_array_push(&cp.args, "--");
707 argv_array_pushv(&cp.args, paths);
709 ret = capture_command(&cp, &last, 8);
714 state->last = strtol(last.buf, NULL, 10);
717 strbuf_release(&last);
722 * Callback signature for split_mail_conv(). The foreign patch should be
723 * read from `in`, and the converted patch (in RFC2822 mail format) should be
724 * written to `out`. Return 0 on success, or -1 on failure.
726 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
729 * Calls `fn` for each file in `paths` to convert the foreign patch to the
730 * RFC2822 mail format suitable for parsing with git-mailinfo.
732 * Returns 0 on success, -1 on failure.
734 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
735 const char **paths, int keep_cr)
737 static const char *stdin_only[] = {"-", NULL};
743 for (i = 0; *paths; paths++, i++) {
748 if (!strcmp(*paths, "-"))
751 in = fopen(*paths, "r");
754 return error_errno(_("could not open '%s' for reading"),
757 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
759 out = fopen(mail, "w");
763 return error_errno(_("could not open '%s' for writing"),
767 ret = fn(out, in, keep_cr);
774 return error(_("could not parse patch '%s'"), *paths);
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)) {
794 if (str_isspace(sb.buf))
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);
804 fprintf(out, "\n%s\n", sb.buf);
810 while (strbuf_fread(&sb, 8192, in) > 0) {
811 fwrite(sb.buf, 1, sb.len, out);
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,
831 const char *series_dir;
832 char *series_dir_buf;
834 struct argv_array patches = ARGV_ARRAY_INIT;
835 struct strbuf sb = STRBUF_INIT;
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");
846 return error_errno(_("could not open '%s' for reading"), *paths);
848 while (!strbuf_getline_lf(&sb, fp)) {
850 continue; /* skip comment lines */
852 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
857 free(series_dir_buf);
859 ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
861 argv_array_clear(&patches);
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;
874 while (!strbuf_getline_lf(&sb, in)) {
877 if (skip_prefix(sb.buf, "# User ", &str))
878 fprintf(out, "From: %s\n", str);
879 else if (skip_prefix(sb.buf, "# Date ", &str)) {
880 timestamp_t timestamp;
885 timestamp = parse_timestamp(str, &end, 10);
887 rc = error(_("invalid timestamp"));
891 if (!skip_prefix(end, " ", &str)) {
892 rc = error(_("invalid Date line"));
897 tz = strtol(str, &end, 10);
899 rc = error(_("invalid timezone offset"));
904 rc = error(_("invalid Date line"));
909 * mercurial's timezone is in seconds west of UTC,
910 * however git's timezone is in hours + minutes east of
913 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
917 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
918 } else if (starts_with(sb.buf, "# ")) {
921 fprintf(out, "\n%s\n", sb.buf);
927 while (strbuf_fread(&sb, 8192, in) > 0) {
928 fwrite(sb.buf, 1, sb.len, out);
937 * Splits a list of files/directories into individual email patches. Each path
938 * in `paths` must be a file/directory that is formatted according to
941 * Once split out, the individual email patches will be stored in the state
942 * directory, with each patch's filename being its index, padded to state->prec
945 * state->cur will be set to the index of the first mail, and state->last will
946 * be set to the index of the last mail.
948 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
949 * to disable this behavior, -1 to use the default configured setting.
951 * Returns 0 on success, -1 on failure.
953 static int split_mail(struct am_state *state, enum patch_format patch_format,
954 const char **paths, int keep_cr)
958 git_config_get_bool("am.keepcr", &keep_cr);
961 switch (patch_format) {
962 case PATCH_FORMAT_MBOX:
963 return split_mail_mbox(state, paths, keep_cr, 0);
964 case PATCH_FORMAT_STGIT:
965 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
966 case PATCH_FORMAT_STGIT_SERIES:
967 return split_mail_stgit_series(state, paths, keep_cr);
968 case PATCH_FORMAT_HG:
969 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
970 case PATCH_FORMAT_MBOXRD:
971 return split_mail_mbox(state, paths, keep_cr, 1);
973 die("BUG: invalid patch_format");
979 * Setup a new am session for applying patches
981 static void am_setup(struct am_state *state, enum patch_format patch_format,
982 const char **paths, int keep_cr)
984 struct object_id curr_head;
986 struct strbuf sb = STRBUF_INIT;
989 patch_format = detect_patch_format(paths);
992 fprintf_ln(stderr, _("Patch format detection failed."));
996 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
997 die_errno(_("failed to create directory '%s'"), state->dir);
998 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1000 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1002 die(_("Failed to split patches."));
1005 if (state->rebasing)
1006 state->threeway = 1;
1008 write_state_bool(state, "threeway", state->threeway);
1009 write_state_bool(state, "quiet", state->quiet);
1010 write_state_bool(state, "sign", state->signoff);
1011 write_state_bool(state, "utf8", state->utf8);
1013 if (state->allow_rerere_autoupdate)
1014 write_state_bool(state, "rerere-autoupdate",
1015 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1017 switch (state->keep) {
1024 case KEEP_NON_PATCH:
1028 die("BUG: invalid value for state->keep");
1031 write_state_text(state, "keep", str);
1032 write_state_bool(state, "messageid", state->message_id);
1034 switch (state->scissors) {
1035 case SCISSORS_UNSET:
1038 case SCISSORS_FALSE:
1045 die("BUG: invalid value for state->scissors");
1047 write_state_text(state, "scissors", str);
1049 sq_quote_argv(&sb, state->git_apply_opts.argv);
1050 write_state_text(state, "apply-opt", sb.buf);
1052 if (state->rebasing)
1053 write_state_text(state, "rebasing", "");
1055 write_state_text(state, "applying", "");
1057 if (!get_oid("HEAD", &curr_head)) {
1058 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1059 if (!state->rebasing)
1060 update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1061 UPDATE_REFS_DIE_ON_ERR);
1063 write_state_text(state, "abort-safety", "");
1064 if (!state->rebasing)
1065 delete_ref(NULL, "ORIG_HEAD", NULL, 0);
1069 * NOTE: Since the "next" and "last" files determine if an am_state
1070 * session is in progress, they should be written last.
1073 write_state_count(state, "next", state->cur);
1074 write_state_count(state, "last", state->last);
1076 strbuf_release(&sb);
1080 * Increments the patch pointer, and cleans am_state for the application of the
1083 static void am_next(struct am_state *state)
1085 struct object_id head;
1087 FREE_AND_NULL(state->author_name);
1088 FREE_AND_NULL(state->author_email);
1089 FREE_AND_NULL(state->author_date);
1090 FREE_AND_NULL(state->msg);
1093 unlink(am_path(state, "author-script"));
1094 unlink(am_path(state, "final-commit"));
1096 oidclr(&state->orig_commit);
1097 unlink(am_path(state, "original-commit"));
1098 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1100 if (!get_oid("HEAD", &head))
1101 write_state_text(state, "abort-safety", oid_to_hex(&head));
1103 write_state_text(state, "abort-safety", "");
1106 write_state_count(state, "next", state->cur);
1110 * Returns the filename of the current patch email.
1112 static const char *msgnum(const struct am_state *state)
1114 static struct strbuf sb = STRBUF_INIT;
1117 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1123 * Refresh and write index.
1125 static void refresh_and_write_cache(void)
1127 struct lock_file lock_file = LOCK_INIT;
1129 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1130 refresh_cache(REFRESH_QUIET);
1131 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1132 die(_("unable to write index file"));
1136 * Dies with a user-friendly message on how to proceed after resolving the
1137 * problem. This message can be overridden with state->resolvemsg.
1139 static void NORETURN die_user_resolve(const struct am_state *state)
1141 if (state->resolvemsg) {
1142 printf_ln("%s", state->resolvemsg);
1144 const char *cmdline = state->interactive ? "git am -i" : "git am";
1146 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1147 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1148 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1155 * Appends signoff to the "msg" field of the am_state.
1157 static void am_append_signoff(struct am_state *state)
1159 struct strbuf sb = STRBUF_INIT;
1161 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1162 append_signoff(&sb, 0, 0);
1163 state->msg = strbuf_detach(&sb, &state->msg_len);
1167 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1168 * state->msg will be set to the patch message. state->author_name,
1169 * state->author_email and state->author_date will be set to the patch author's
1170 * name, email and date respectively. The patch body will be written to the
1171 * state directory's "patch" file.
1173 * Returns 1 if the patch should be skipped, 0 otherwise.
1175 static int parse_mail(struct am_state *state, const char *mail)
1178 struct strbuf sb = STRBUF_INIT;
1179 struct strbuf msg = STRBUF_INIT;
1180 struct strbuf author_name = STRBUF_INIT;
1181 struct strbuf author_date = STRBUF_INIT;
1182 struct strbuf author_email = STRBUF_INIT;
1186 setup_mailinfo(&mi);
1189 mi.metainfo_charset = get_commit_output_encoding();
1191 mi.metainfo_charset = NULL;
1193 switch (state->keep) {
1197 mi.keep_subject = 1;
1199 case KEEP_NON_PATCH:
1200 mi.keep_non_patch_brackets_in_subject = 1;
1203 die("BUG: invalid value for state->keep");
1206 if (state->message_id)
1207 mi.add_message_id = 1;
1209 switch (state->scissors) {
1210 case SCISSORS_UNSET:
1212 case SCISSORS_FALSE:
1213 mi.use_scissors = 0;
1216 mi.use_scissors = 1;
1219 die("BUG: invalid value for state->scissors");
1222 mi.input = xfopen(mail, "r");
1223 mi.output = xfopen(am_path(state, "info"), "w");
1224 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1225 die("could not parse patch");
1230 /* Extract message and author information */
1231 fp = xfopen(am_path(state, "info"), "r");
1232 while (!strbuf_getline_lf(&sb, fp)) {
1235 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1237 strbuf_addch(&msg, '\n');
1238 strbuf_addstr(&msg, x);
1239 } else if (skip_prefix(sb.buf, "Author: ", &x))
1240 strbuf_addstr(&author_name, x);
1241 else if (skip_prefix(sb.buf, "Email: ", &x))
1242 strbuf_addstr(&author_email, x);
1243 else if (skip_prefix(sb.buf, "Date: ", &x))
1244 strbuf_addstr(&author_date, x);
1248 /* Skip pine's internal folder data */
1249 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1254 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1255 printf_ln(_("Patch is empty."));
1256 die_user_resolve(state);
1259 strbuf_addstr(&msg, "\n\n");
1260 strbuf_addbuf(&msg, &mi.log_message);
1261 strbuf_stripspace(&msg, 0);
1263 assert(!state->author_name);
1264 state->author_name = strbuf_detach(&author_name, NULL);
1266 assert(!state->author_email);
1267 state->author_email = strbuf_detach(&author_email, NULL);
1269 assert(!state->author_date);
1270 state->author_date = strbuf_detach(&author_date, NULL);
1272 assert(!state->msg);
1273 state->msg = strbuf_detach(&msg, &state->msg_len);
1276 strbuf_release(&msg);
1277 strbuf_release(&author_date);
1278 strbuf_release(&author_email);
1279 strbuf_release(&author_name);
1280 strbuf_release(&sb);
1281 clear_mailinfo(&mi);
1286 * Sets commit_id to the commit hash where the mail was generated from.
1287 * Returns 0 on success, -1 on failure.
1289 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1291 struct strbuf sb = STRBUF_INIT;
1292 FILE *fp = xfopen(mail, "r");
1296 if (strbuf_getline_lf(&sb, fp) ||
1297 !skip_prefix(sb.buf, "From ", &x) ||
1298 get_oid_hex(x, commit_id) < 0)
1301 strbuf_release(&sb);
1307 * Sets state->msg, state->author_name, state->author_email, state->author_date
1308 * to the commit's respective info.
1310 static void get_commit_info(struct am_state *state, struct commit *commit)
1312 const char *buffer, *ident_line, *msg;
1314 struct ident_split id;
1316 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1318 ident_line = find_commit_header(buffer, "author", &ident_len);
1320 if (split_ident_line(&id, ident_line, ident_len) < 0)
1321 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1323 assert(!state->author_name);
1325 state->author_name =
1326 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1328 state->author_name = xstrdup("");
1330 assert(!state->author_email);
1332 state->author_email =
1333 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1335 state->author_email = xstrdup("");
1337 assert(!state->author_date);
1338 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1340 assert(!state->msg);
1341 msg = strstr(buffer, "\n\n");
1343 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1344 state->msg = xstrdup(msg + 2);
1345 state->msg_len = strlen(state->msg);
1346 unuse_commit_buffer(commit, buffer);
1350 * Writes `commit` as a patch to the state directory's "patch" file.
1352 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1354 struct rev_info rev_info;
1357 fp = xfopen(am_path(state, "patch"), "w");
1358 init_revisions(&rev_info, NULL);
1360 rev_info.abbrev = 0;
1361 rev_info.disable_stdin = 1;
1362 rev_info.show_root_diff = 1;
1363 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1364 rev_info.no_commit_id = 1;
1365 rev_info.diffopt.flags.binary = 1;
1366 rev_info.diffopt.flags.full_index = 1;
1367 rev_info.diffopt.use_color = 0;
1368 rev_info.diffopt.file = fp;
1369 rev_info.diffopt.close_file = 1;
1370 add_pending_object(&rev_info, &commit->object, "");
1371 diff_setup_done(&rev_info.diffopt);
1372 log_tree_commit(&rev_info, commit);
1376 * Writes the diff of the index against HEAD as a patch to the state
1377 * directory's "patch" file.
1379 static void write_index_patch(const struct am_state *state)
1382 struct object_id head;
1383 struct rev_info rev_info;
1386 if (!get_oid_tree("HEAD", &head))
1387 tree = lookup_tree(&head);
1389 tree = lookup_tree(the_hash_algo->empty_tree);
1391 fp = xfopen(am_path(state, "patch"), "w");
1392 init_revisions(&rev_info, NULL);
1394 rev_info.disable_stdin = 1;
1395 rev_info.no_commit_id = 1;
1396 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1397 rev_info.diffopt.use_color = 0;
1398 rev_info.diffopt.file = fp;
1399 rev_info.diffopt.close_file = 1;
1400 add_pending_object(&rev_info, &tree->object, "");
1401 diff_setup_done(&rev_info.diffopt);
1402 run_diff_index(&rev_info, 1);
1406 * Like parse_mail(), but parses the mail by looking up its commit ID
1407 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1410 * state->orig_commit will be set to the original commit ID.
1412 * Will always return 0 as the patch should never be skipped.
1414 static int parse_mail_rebase(struct am_state *state, const char *mail)
1416 struct commit *commit;
1417 struct object_id commit_oid;
1419 if (get_mail_commit_oid(&commit_oid, mail) < 0)
1420 die(_("could not parse %s"), mail);
1422 commit = lookup_commit_or_die(&commit_oid, mail);
1424 get_commit_info(state, commit);
1426 write_commit_patch(state, commit);
1428 oidcpy(&state->orig_commit, &commit_oid);
1429 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1430 update_ref("am", "REBASE_HEAD", &commit_oid,
1431 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1437 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1438 * `index_file` is not NULL, the patch will be applied to that index.
1440 static int run_apply(const struct am_state *state, const char *index_file)
1442 struct argv_array apply_paths = ARGV_ARRAY_INIT;
1443 struct argv_array apply_opts = ARGV_ARRAY_INIT;
1444 struct apply_state apply_state;
1446 int force_apply = 0;
1449 if (init_apply_state(&apply_state, NULL))
1450 die("BUG: init_apply_state() failed");
1452 argv_array_push(&apply_opts, "apply");
1453 argv_array_pushv(&apply_opts, state->git_apply_opts.argv);
1455 opts_left = apply_parse_options(apply_opts.argc, apply_opts.argv,
1456 &apply_state, &force_apply, &options,
1460 die("unknown option passed through to git apply");
1463 apply_state.index_file = index_file;
1464 apply_state.cached = 1;
1466 apply_state.check_index = 1;
1469 * If we are allowed to fall back on 3-way merge, don't give false
1470 * errors during the initial attempt.
1472 if (state->threeway && !index_file)
1473 apply_state.apply_verbosity = verbosity_silent;
1475 if (check_apply_state(&apply_state, force_apply))
1476 die("BUG: check_apply_state() failed");
1478 argv_array_push(&apply_paths, am_path(state, "patch"));
1480 res = apply_all_patches(&apply_state, apply_paths.argc, apply_paths.argv, options);
1482 argv_array_clear(&apply_paths);
1483 argv_array_clear(&apply_opts);
1484 clear_apply_state(&apply_state);
1490 /* Reload index as apply_all_patches() will have modified it. */
1492 read_cache_from(index_file);
1499 * Builds an index that contains just the blobs needed for a 3way merge.
1501 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1503 struct child_process cp = CHILD_PROCESS_INIT;
1506 argv_array_push(&cp.args, "apply");
1507 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1508 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1509 argv_array_push(&cp.args, am_path(state, "patch"));
1511 if (run_command(&cp))
1518 * Attempt a threeway merge, using index_path as the temporary index.
1520 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1522 struct object_id orig_tree, their_tree, our_tree;
1523 const struct object_id *bases[1] = { &orig_tree };
1524 struct merge_options o;
1525 struct commit *result;
1526 char *their_tree_name;
1528 if (get_oid("HEAD", &our_tree) < 0)
1529 hashcpy(our_tree.hash, EMPTY_TREE_SHA1_BIN);
1531 if (build_fake_ancestor(state, index_path))
1532 return error("could not build fake ancestor");
1535 read_cache_from(index_path);
1537 if (write_index_as_tree(orig_tree.hash, &the_index, index_path, 0, NULL))
1538 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1540 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1542 if (!state->quiet) {
1544 * List paths that needed 3-way fallback, so that the user can
1545 * review them with extra care to spot mismerges.
1547 struct rev_info rev_info;
1548 const char *diff_filter_str = "--diff-filter=AM";
1550 init_revisions(&rev_info, NULL);
1551 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1552 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1553 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1554 diff_setup_done(&rev_info.diffopt);
1555 run_diff_index(&rev_info, 1);
1558 if (run_apply(state, index_path))
1559 return error(_("Did you hand edit your patch?\n"
1560 "It does not apply to blobs recorded in its index."));
1562 if (write_index_as_tree(their_tree.hash, &the_index, index_path, 0, NULL))
1563 return error("could not write tree");
1565 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1571 * This is not so wrong. Depending on which base we picked, orig_tree
1572 * may be wildly different from ours, but their_tree has the same set of
1573 * wildly different changes in parts the patch did not touch, so
1574 * recursive ends up canceling them, saying that we reverted all those
1578 init_merge_options(&o);
1581 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1582 o.branch2 = their_tree_name;
1587 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1588 rerere(state->allow_rerere_autoupdate);
1589 free(their_tree_name);
1590 return error(_("Failed to merge in the changes."));
1593 free(their_tree_name);
1598 * Commits the current index with state->msg as the commit message and
1599 * state->author_name, state->author_email and state->author_date as the author
1602 static void do_commit(const struct am_state *state)
1604 struct object_id tree, parent, commit;
1605 const struct object_id *old_oid;
1606 struct commit_list *parents = NULL;
1607 const char *reflog_msg, *author;
1608 struct strbuf sb = STRBUF_INIT;
1610 if (run_hook_le(NULL, "pre-applypatch", NULL))
1613 if (write_cache_as_tree(tree.hash, 0, NULL))
1614 die(_("git write-tree failed to write a tree"));
1616 if (!get_oid_commit("HEAD", &parent)) {
1618 commit_list_insert(lookup_commit(&parent), &parents);
1621 say(state, stderr, _("applying to an empty history"));
1624 author = fmt_ident(state->author_name, state->author_email,
1625 state->ignore_date ? NULL : state->author_date,
1628 if (state->committer_date_is_author_date)
1629 setenv("GIT_COMMITTER_DATE",
1630 state->ignore_date ? "" : state->author_date, 1);
1632 if (commit_tree(state->msg, state->msg_len, &tree, parents, &commit,
1633 author, state->sign_commit))
1634 die(_("failed to write commit object"));
1636 reflog_msg = getenv("GIT_REFLOG_ACTION");
1640 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1643 update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1644 UPDATE_REFS_DIE_ON_ERR);
1646 if (state->rebasing) {
1647 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1649 assert(!is_null_oid(&state->orig_commit));
1650 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1651 fprintf(fp, "%s\n", oid_to_hex(&commit));
1655 run_hook_le(NULL, "post-applypatch", NULL);
1657 strbuf_release(&sb);
1661 * Validates the am_state for resuming -- the "msg" and authorship fields must
1664 static void validate_resume_state(const struct am_state *state)
1667 die(_("cannot resume: %s does not exist."),
1668 am_path(state, "final-commit"));
1670 if (!state->author_name || !state->author_email || !state->author_date)
1671 die(_("cannot resume: %s does not exist."),
1672 am_path(state, "author-script"));
1676 * Interactively prompt the user on whether the current patch should be
1679 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1682 static int do_interactive(struct am_state *state)
1687 die(_("cannot be interactive without stdin connected to a terminal."));
1692 puts(_("Commit Body is:"));
1693 puts("--------------------------");
1694 printf("%s", state->msg);
1695 puts("--------------------------");
1698 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1699 * in your translation. The program will only accept English
1700 * input at this point.
1702 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1706 } else if (*reply == 'y' || *reply == 'Y') {
1708 } else if (*reply == 'a' || *reply == 'A') {
1709 state->interactive = 0;
1711 } else if (*reply == 'n' || *reply == 'N') {
1713 } else if (*reply == 'e' || *reply == 'E') {
1714 struct strbuf msg = STRBUF_INIT;
1716 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1718 state->msg = strbuf_detach(&msg, &state->msg_len);
1720 strbuf_release(&msg);
1721 } else if (*reply == 'v' || *reply == 'V') {
1722 const char *pager = git_pager(1);
1723 struct child_process cp = CHILD_PROCESS_INIT;
1727 prepare_pager_args(&cp, pager);
1728 argv_array_push(&cp.args, am_path(state, "patch"));
1735 * Applies all queued mail.
1737 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1738 * well as the state directory's "patch" file is used as-is for applying the
1739 * patch and committing it.
1741 static void am_run(struct am_state *state, int resume)
1743 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1744 struct strbuf sb = STRBUF_INIT;
1746 unlink(am_path(state, "dirtyindex"));
1748 refresh_and_write_cache();
1750 if (index_has_changes(&sb)) {
1751 write_state_bool(state, "dirtyindex", 1);
1752 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1755 strbuf_release(&sb);
1757 while (state->cur <= state->last) {
1758 const char *mail = am_path(state, msgnum(state));
1763 if (!file_exists(mail))
1767 validate_resume_state(state);
1771 if (state->rebasing)
1772 skip = parse_mail_rebase(state, mail);
1774 skip = parse_mail(state, mail);
1777 goto next; /* mail should be skipped */
1780 am_append_signoff(state);
1782 write_author_script(state);
1783 write_commit_msg(state);
1786 if (state->interactive && do_interactive(state))
1789 if (run_applypatch_msg_hook(state))
1792 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1794 apply_status = run_apply(state, NULL);
1796 if (apply_status && state->threeway) {
1797 struct strbuf sb = STRBUF_INIT;
1799 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1800 apply_status = fall_back_threeway(state, sb.buf);
1801 strbuf_release(&sb);
1804 * Applying the patch to an earlier tree and merging
1805 * the result may have produced the same tree as ours.
1807 if (!apply_status && !index_has_changes(NULL)) {
1808 say(state, stdout, _("No changes -- Patch already applied."));
1814 int advice_amworkdir = 1;
1816 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1817 linelen(state->msg), state->msg);
1819 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1821 if (advice_amworkdir)
1822 printf_ln(_("Use 'git am --show-current-patch' to see the failed patch"));
1824 die_user_resolve(state);
1837 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1838 assert(state->rebasing);
1839 copy_notes_for_rebase(state);
1840 run_post_rewrite_hook(state);
1844 * In rebasing mode, it's up to the caller to take care of
1847 if (!state->rebasing) {
1850 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1855 * Resume the current am session after patch application failure. The user did
1856 * all the hard work, and we do not have to do any patch application. Just
1857 * trust and commit what the user has in the index and working tree.
1859 static void am_resolve(struct am_state *state)
1861 validate_resume_state(state);
1863 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1865 if (!index_has_changes(NULL)) {
1866 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1867 "If there is nothing left to stage, chances are that something else\n"
1868 "already introduced the same changes; you might want to skip this patch."));
1869 die_user_resolve(state);
1872 if (unmerged_cache()) {
1873 printf_ln(_("You still have unmerged paths in your index.\n"
1874 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1875 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1876 die_user_resolve(state);
1879 if (state->interactive) {
1880 write_index_patch(state);
1881 if (do_interactive(state))
1896 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1897 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1900 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1902 struct lock_file lock_file = LOCK_INIT;
1903 struct unpack_trees_options opts;
1904 struct tree_desc t[2];
1906 if (parse_tree(head) || parse_tree(remote))
1909 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1911 refresh_cache(REFRESH_QUIET);
1913 memset(&opts, 0, sizeof(opts));
1915 opts.src_index = &the_index;
1916 opts.dst_index = &the_index;
1920 opts.fn = twoway_merge;
1921 init_tree_desc(&t[0], head->buffer, head->size);
1922 init_tree_desc(&t[1], remote->buffer, remote->size);
1924 if (unpack_trees(2, t, &opts)) {
1925 rollback_lock_file(&lock_file);
1929 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1930 die(_("unable to write new index file"));
1936 * Merges a tree into the index. The index's stat info will take precedence
1937 * over the merged tree's. Returns 0 on success, -1 on failure.
1939 static int merge_tree(struct tree *tree)
1941 struct lock_file lock_file = LOCK_INIT;
1942 struct unpack_trees_options opts;
1943 struct tree_desc t[1];
1945 if (parse_tree(tree))
1948 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1950 memset(&opts, 0, sizeof(opts));
1952 opts.src_index = &the_index;
1953 opts.dst_index = &the_index;
1955 opts.fn = oneway_merge;
1956 init_tree_desc(&t[0], tree->buffer, tree->size);
1958 if (unpack_trees(1, t, &opts)) {
1959 rollback_lock_file(&lock_file);
1963 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1964 die(_("unable to write new index file"));
1970 * Clean the index without touching entries that are not modified between
1971 * `head` and `remote`.
1973 static int clean_index(const struct object_id *head, const struct object_id *remote)
1975 struct tree *head_tree, *remote_tree, *index_tree;
1976 struct object_id index;
1978 head_tree = parse_tree_indirect(head);
1980 return error(_("Could not parse object '%s'."), oid_to_hex(head));
1982 remote_tree = parse_tree_indirect(remote);
1984 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
1986 read_cache_unmerged();
1988 if (fast_forward_to(head_tree, head_tree, 1))
1991 if (write_cache_as_tree(index.hash, 0, NULL))
1994 index_tree = parse_tree_indirect(&index);
1996 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
1998 if (fast_forward_to(index_tree, remote_tree, 0))
2001 if (merge_tree(remote_tree))
2004 remove_branch_state();
2010 * Resets rerere's merge resolution metadata.
2012 static void am_rerere_clear(void)
2014 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2015 rerere_clear(&merge_rr);
2016 string_list_clear(&merge_rr, 1);
2020 * Resume the current am session by skipping the current patch.
2022 static void am_skip(struct am_state *state)
2024 struct object_id head;
2028 if (get_oid("HEAD", &head))
2029 hashcpy(head.hash, EMPTY_TREE_SHA1_BIN);
2031 if (clean_index(&head, &head))
2032 die(_("failed to clean index"));
2040 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2042 * It is not safe to reset HEAD when:
2043 * 1. git-am previously failed because the index was dirty.
2044 * 2. HEAD has moved since git-am previously failed.
2046 static int safe_to_abort(const struct am_state *state)
2048 struct strbuf sb = STRBUF_INIT;
2049 struct object_id abort_safety, head;
2051 if (file_exists(am_path(state, "dirtyindex")))
2054 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2055 if (get_oid_hex(sb.buf, &abort_safety))
2056 die(_("could not parse %s"), am_path(state, "abort-safety"));
2058 oidclr(&abort_safety);
2059 strbuf_release(&sb);
2061 if (get_oid("HEAD", &head))
2064 if (!oidcmp(&head, &abort_safety))
2067 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2068 "Not rewinding to ORIG_HEAD"));
2074 * Aborts the current am session if it is safe to do so.
2076 static void am_abort(struct am_state *state)
2078 struct object_id curr_head, orig_head;
2079 int has_curr_head, has_orig_head;
2082 if (!safe_to_abort(state)) {
2089 curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2090 has_curr_head = curr_branch && !is_null_oid(&curr_head);
2092 hashcpy(curr_head.hash, EMPTY_TREE_SHA1_BIN);
2094 has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
2096 hashcpy(orig_head.hash, EMPTY_TREE_SHA1_BIN);
2098 clean_index(&curr_head, &orig_head);
2101 update_ref("am --abort", "HEAD", &orig_head,
2102 has_curr_head ? &curr_head : NULL, 0,
2103 UPDATE_REFS_DIE_ON_ERR);
2104 else if (curr_branch)
2105 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
2111 static int show_patch(struct am_state *state)
2113 struct strbuf sb = STRBUF_INIT;
2114 const char *patch_path;
2117 if (!is_null_oid(&state->orig_commit)) {
2118 const char *av[4] = { "show", NULL, "--", NULL };
2122 av[1] = new_oid_str = xstrdup(oid_to_hex(&state->orig_commit));
2123 ret = run_command_v_opt(av, RUN_GIT_CMD);
2128 patch_path = am_path(state, msgnum(state));
2129 len = strbuf_read_file(&sb, patch_path, 0);
2131 die_errno(_("failed to read '%s'"), patch_path);
2134 write_in_full(1, sb.buf, sb.len);
2135 strbuf_release(&sb);
2140 * parse_options() callback that validates and sets opt->value to the
2141 * PATCH_FORMAT_* enum value corresponding to `arg`.
2143 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2145 int *opt_value = opt->value;
2147 if (!strcmp(arg, "mbox"))
2148 *opt_value = PATCH_FORMAT_MBOX;
2149 else if (!strcmp(arg, "stgit"))
2150 *opt_value = PATCH_FORMAT_STGIT;
2151 else if (!strcmp(arg, "stgit-series"))
2152 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2153 else if (!strcmp(arg, "hg"))
2154 *opt_value = PATCH_FORMAT_HG;
2155 else if (!strcmp(arg, "mboxrd"))
2156 *opt_value = PATCH_FORMAT_MBOXRD;
2158 return error(_("Invalid value for --patch-format: %s"), arg);
2172 static int git_am_config(const char *k, const char *v, void *cb)
2176 status = git_gpg_config(k, v, NULL);
2180 return git_default_config(k, v, NULL);
2183 int cmd_am(int argc, const char **argv, const char *prefix)
2185 struct am_state state;
2188 int patch_format = PATCH_FORMAT_UNKNOWN;
2189 enum resume_mode resume = RESUME_FALSE;
2193 const char * const usage[] = {
2194 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2195 N_("git am [<options>] (--continue | --skip | --abort)"),
2199 struct option options[] = {
2200 OPT_BOOL('i', "interactive", &state.interactive,
2201 N_("run interactively")),
2202 OPT_HIDDEN_BOOL('b', "binary", &binary,
2203 N_("historical option -- no-op")),
2204 OPT_BOOL('3', "3way", &state.threeway,
2205 N_("allow fall back on 3way merging if needed")),
2206 OPT__QUIET(&state.quiet, N_("be quiet")),
2207 OPT_SET_INT('s', "signoff", &state.signoff,
2208 N_("add a Signed-off-by line to the commit message"),
2210 OPT_BOOL('u', "utf8", &state.utf8,
2211 N_("recode into utf8 (default)")),
2212 OPT_SET_INT('k', "keep", &state.keep,
2213 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2214 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2215 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2216 OPT_BOOL('m', "message-id", &state.message_id,
2217 N_("pass -m flag to git-mailinfo")),
2218 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2219 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2220 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2221 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2222 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2223 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2224 OPT_BOOL('c', "scissors", &state.scissors,
2225 N_("strip everything before a scissors line")),
2226 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2227 N_("pass it through git-apply"),
2229 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2230 N_("pass it through git-apply"),
2232 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2233 N_("pass it through git-apply"),
2235 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2236 N_("pass it through git-apply"),
2238 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2239 N_("pass it through git-apply"),
2241 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2242 N_("pass it through git-apply"),
2244 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2245 N_("pass it through git-apply"),
2247 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2248 N_("pass it through git-apply"),
2250 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2251 N_("format the patch(es) are in"),
2252 parse_opt_patchformat),
2253 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2254 N_("pass it through git-apply"),
2256 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2257 N_("override error message when patch failure occurs")),
2258 OPT_CMDMODE(0, "continue", &resume,
2259 N_("continue applying patches after resolving a conflict"),
2261 OPT_CMDMODE('r', "resolved", &resume,
2262 N_("synonyms for --continue"),
2264 OPT_CMDMODE(0, "skip", &resume,
2265 N_("skip the current patch"),
2267 OPT_CMDMODE(0, "abort", &resume,
2268 N_("restore the original branch and abort the patching operation."),
2270 OPT_CMDMODE(0, "quit", &resume,
2271 N_("abort the patching operation but keep HEAD where it is."),
2273 OPT_CMDMODE(0, "show-current-patch", &resume,
2274 N_("show the patch being applied."),
2276 OPT_BOOL(0, "committer-date-is-author-date",
2277 &state.committer_date_is_author_date,
2278 N_("lie about committer date")),
2279 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2280 N_("use current timestamp for author date")),
2281 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2282 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2283 N_("GPG-sign commits"),
2284 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2285 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2286 N_("(internal use for git-rebase)")),
2290 if (argc == 2 && !strcmp(argv[1], "-h"))
2291 usage_with_options(usage, options);
2293 git_config(git_am_config, NULL);
2295 am_state_init(&state);
2297 in_progress = am_in_progress(&state);
2301 argc = parse_options(argc, argv, prefix, options, usage, 0);
2304 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2305 "it will be removed. Please do not use it anymore."));
2307 /* Ensure a valid committer ident can be constructed */
2308 git_committer_info(IDENT_STRICT);
2310 if (read_index_preload(&the_index, NULL) < 0)
2311 die(_("failed to read the index"));
2315 * Catch user error to feed us patches when there is a session
2318 * 1. mbox path(s) are provided on the command-line.
2319 * 2. stdin is not a tty: the user is trying to feed us a patch
2320 * from standard input. This is somewhat unreliable -- stdin
2321 * could be /dev/null for example and the caller did not
2322 * intend to feed us a patch but wanted to continue
2325 if (argc || (resume == RESUME_FALSE && !isatty(0)))
2326 die(_("previous rebase directory %s still exists but mbox given."),
2329 if (resume == RESUME_FALSE)
2330 resume = RESUME_APPLY;
2332 if (state.signoff == SIGNOFF_EXPLICIT)
2333 am_append_signoff(&state);
2335 struct argv_array paths = ARGV_ARRAY_INIT;
2339 * Handle stray state directory in the independent-run case. In
2340 * the --rebasing case, it is up to the caller to take care of
2341 * stray directories.
2343 if (file_exists(state.dir) && !state.rebasing) {
2344 if (resume == RESUME_ABORT || resume == RESUME_QUIT) {
2346 am_state_release(&state);
2350 die(_("Stray %s directory found.\n"
2351 "Use \"git am --abort\" to remove it."),
2356 die(_("Resolve operation not in progress, we are not resuming."));
2358 for (i = 0; i < argc; i++) {
2359 if (is_absolute_path(argv[i]) || !prefix)
2360 argv_array_push(&paths, argv[i]);
2362 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2365 am_setup(&state, patch_format, paths.argv, keep_cr);
2367 argv_array_clear(&paths);
2377 case RESUME_RESOLVED:
2390 case RESUME_SHOW_PATCH:
2391 ret = show_patch(&state);
2394 die("BUG: invalid resume value");
2397 am_state_release(&state);