4 * Based on git-am.sh by Junio C Hamano.
6 #define USE_THE_INDEX_COMPATIBILITY_MACROS
11 #include "parse-options.h"
13 #include "run-command.h"
17 #include "cache-tree.h"
22 #include "unpack-trees.h"
24 #include "sequencer.h"
26 #include "merge-recursive.h"
28 #include "notes-utils.h"
33 #include "string-list.h"
35 #include "repository.h"
38 * Returns the length of the first line of msg.
40 static int linelen(const char *msg)
42 return strchrnul(msg, '\n') - msg;
46 * Returns true if `str` consists of only whitespace, false otherwise.
48 static int str_isspace(const char *str)
58 PATCH_FORMAT_UNKNOWN = 0,
61 PATCH_FORMAT_STGIT_SERIES,
68 KEEP_TRUE, /* pass -k flag to git-mailinfo */
69 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
74 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
75 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
81 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
84 enum show_patch_type {
90 /* state directory path */
93 /* current and last patch numbers, 1-indexed */
97 /* commit metadata and message */
101 char *committer_name;
102 char *committer_email;
106 /* when --rebasing, records the original commit the patch came from */
107 struct object_id orig_commit;
109 /* number of digits in patch filename */
112 /* various operating modes and command line options */
116 int signoff; /* enum signoff_type */
118 int keep; /* enum keep_type */
120 int scissors; /* enum scissors_type */
121 struct strvec git_apply_opts;
122 const char *resolvemsg;
123 int committer_date_is_author_date;
125 int allow_rerere_autoupdate;
126 const char *sign_commit;
131 * Initializes am_state with the default values.
133 static void am_state_init(struct am_state *state)
135 const char *committer;
136 struct ident_split id;
139 memset(state, 0, sizeof(*state));
141 state->dir = git_pathdup("rebase-apply");
145 git_config_get_bool("am.threeway", &state->threeway);
149 git_config_get_bool("am.messageid", &state->message_id);
151 state->scissors = SCISSORS_UNSET;
153 strvec_init(&state->git_apply_opts);
155 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
156 state->sign_commit = gpgsign ? "" : NULL;
158 committer = git_committer_info(IDENT_STRICT);
159 if (split_ident_line(&id, committer, strlen(committer)) < 0)
160 die(_("invalid committer: %s"), committer);
161 state->committer_name =
162 xmemdupz(id.name_begin, id.name_end - id.name_begin);
163 state->committer_email =
164 xmemdupz(id.mail_begin, id.mail_end - id.mail_end);
168 * Releases memory allocated by an am_state.
170 static void am_state_release(struct am_state *state)
173 free(state->author_name);
174 free(state->author_email);
175 free(state->author_date);
176 free(state->committer_name);
177 free(state->committer_email);
179 strvec_clear(&state->git_apply_opts);
183 * Returns path relative to the am_state directory.
185 static inline const char *am_path(const struct am_state *state, const char *path)
187 return mkpath("%s/%s", state->dir, path);
191 * For convenience to call write_file()
193 static void write_state_text(const struct am_state *state,
194 const char *name, const char *string)
196 write_file(am_path(state, name), "%s", string);
199 static void write_state_count(const struct am_state *state,
200 const char *name, int value)
202 write_file(am_path(state, name), "%d", value);
205 static void write_state_bool(const struct am_state *state,
206 const char *name, int value)
208 write_state_text(state, name, value ? "t" : "f");
212 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
215 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
221 vfprintf(fp, fmt, ap);
228 * Returns 1 if there is an am session in progress, 0 otherwise.
230 static int am_in_progress(const struct am_state *state)
234 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
236 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
238 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
244 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
245 * number of bytes read on success, -1 if the file does not exist. If `trim` is
246 * set, trailing whitespace will be removed.
248 static int read_state_file(struct strbuf *sb, const struct am_state *state,
249 const char *file, int trim)
253 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
263 die_errno(_("could not read '%s'"), am_path(state, file));
267 * Reads and parses the state directory's "author-script" file, and sets
268 * state->author_name, state->author_email and state->author_date accordingly.
269 * Returns 0 on success, -1 if the file could not be parsed.
271 * The author script is of the format:
273 * GIT_AUTHOR_NAME='$author_name'
274 * GIT_AUTHOR_EMAIL='$author_email'
275 * GIT_AUTHOR_DATE='$author_date'
277 * where $author_name, $author_email and $author_date are quoted. We are strict
278 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
279 * script, and thus if the file differs from what this function expects, it is
280 * better to bail out than to do something that the user does not expect.
282 static int read_am_author_script(struct am_state *state)
284 const char *filename = am_path(state, "author-script");
286 assert(!state->author_name);
287 assert(!state->author_email);
288 assert(!state->author_date);
290 return read_author_script(filename, &state->author_name,
291 &state->author_email, &state->author_date, 1);
295 * Saves state->author_name, state->author_email and state->author_date in the
296 * state directory's "author-script" file.
298 static void write_author_script(const struct am_state *state)
300 struct strbuf sb = STRBUF_INIT;
302 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
303 sq_quote_buf(&sb, state->author_name);
304 strbuf_addch(&sb, '\n');
306 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
307 sq_quote_buf(&sb, state->author_email);
308 strbuf_addch(&sb, '\n');
310 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
311 sq_quote_buf(&sb, state->author_date);
312 strbuf_addch(&sb, '\n');
314 write_state_text(state, "author-script", sb.buf);
320 * Reads the commit message from the state directory's "final-commit" file,
321 * setting state->msg to its contents and state->msg_len to the length of its
324 * Returns 0 on success, -1 if the file does not exist.
326 static int read_commit_msg(struct am_state *state)
328 struct strbuf sb = STRBUF_INIT;
332 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
337 state->msg = strbuf_detach(&sb, &state->msg_len);
342 * Saves state->msg in the state directory's "final-commit" file.
344 static void write_commit_msg(const struct am_state *state)
346 const char *filename = am_path(state, "final-commit");
347 write_file_buf(filename, state->msg, state->msg_len);
351 * Loads state from disk.
353 static void am_load(struct am_state *state)
355 struct strbuf sb = STRBUF_INIT;
357 if (read_state_file(&sb, state, "next", 1) < 0)
358 BUG("state file 'next' does not exist");
359 state->cur = strtol(sb.buf, NULL, 10);
361 if (read_state_file(&sb, state, "last", 1) < 0)
362 BUG("state file 'last' does not exist");
363 state->last = strtol(sb.buf, NULL, 10);
365 if (read_am_author_script(state) < 0)
366 die(_("could not parse author script"));
368 read_commit_msg(state);
370 if (read_state_file(&sb, state, "original-commit", 1) < 0)
371 oidclr(&state->orig_commit);
372 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
373 die(_("could not parse %s"), am_path(state, "original-commit"));
375 read_state_file(&sb, state, "threeway", 1);
376 state->threeway = !strcmp(sb.buf, "t");
378 read_state_file(&sb, state, "quiet", 1);
379 state->quiet = !strcmp(sb.buf, "t");
381 read_state_file(&sb, state, "sign", 1);
382 state->signoff = !strcmp(sb.buf, "t");
384 read_state_file(&sb, state, "utf8", 1);
385 state->utf8 = !strcmp(sb.buf, "t");
387 if (file_exists(am_path(state, "rerere-autoupdate"))) {
388 read_state_file(&sb, state, "rerere-autoupdate", 1);
389 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
390 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
392 state->allow_rerere_autoupdate = 0;
395 read_state_file(&sb, state, "keep", 1);
396 if (!strcmp(sb.buf, "t"))
397 state->keep = KEEP_TRUE;
398 else if (!strcmp(sb.buf, "b"))
399 state->keep = KEEP_NON_PATCH;
401 state->keep = KEEP_FALSE;
403 read_state_file(&sb, state, "messageid", 1);
404 state->message_id = !strcmp(sb.buf, "t");
406 read_state_file(&sb, state, "scissors", 1);
407 if (!strcmp(sb.buf, "t"))
408 state->scissors = SCISSORS_TRUE;
409 else if (!strcmp(sb.buf, "f"))
410 state->scissors = SCISSORS_FALSE;
412 state->scissors = SCISSORS_UNSET;
414 read_state_file(&sb, state, "apply-opt", 1);
415 strvec_clear(&state->git_apply_opts);
416 if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
417 die(_("could not parse %s"), am_path(state, "apply-opt"));
419 state->rebasing = !!file_exists(am_path(state, "rebasing"));
425 * Removes the am_state directory, forcefully terminating the current am
428 static void am_destroy(const struct am_state *state)
430 struct strbuf sb = STRBUF_INIT;
432 strbuf_addstr(&sb, state->dir);
433 remove_dir_recursively(&sb, 0);
438 * Runs applypatch-msg hook. Returns its exit code.
440 static int run_applypatch_msg_hook(struct am_state *state)
445 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
448 FREE_AND_NULL(state->msg);
449 if (read_commit_msg(state) < 0)
450 die(_("'%s' was deleted by the applypatch-msg hook"),
451 am_path(state, "final-commit"));
458 * Runs post-rewrite hook. Returns it exit code.
460 static int run_post_rewrite_hook(const struct am_state *state)
462 struct child_process cp = CHILD_PROCESS_INIT;
463 const char *hook = find_hook("post-rewrite");
469 strvec_push(&cp.args, hook);
470 strvec_push(&cp.args, "rebase");
472 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
473 cp.stdout_to_stderr = 1;
474 cp.trace2_hook_name = "post-rewrite";
476 ret = run_command(&cp);
483 * Reads the state directory's "rewritten" file, and copies notes from the old
484 * commits listed in the file to their rewritten commits.
486 * Returns 0 on success, -1 on failure.
488 static int copy_notes_for_rebase(const struct am_state *state)
490 struct notes_rewrite_cfg *c;
491 struct strbuf sb = STRBUF_INIT;
492 const char *invalid_line = _("Malformed input line: '%s'.");
493 const char *msg = "Notes added by 'git rebase'";
497 assert(state->rebasing);
499 c = init_copy_notes_for_rewrite("rebase");
503 fp = xfopen(am_path(state, "rewritten"), "r");
505 while (!strbuf_getline_lf(&sb, fp)) {
506 struct object_id from_obj, to_obj;
509 if (sb.len != the_hash_algo->hexsz * 2 + 1) {
510 ret = error(invalid_line, sb.buf);
514 if (parse_oid_hex(sb.buf, &from_obj, &p)) {
515 ret = error(invalid_line, sb.buf);
520 ret = error(invalid_line, sb.buf);
524 if (get_oid_hex(p + 1, &to_obj)) {
525 ret = error(invalid_line, sb.buf);
529 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
530 ret = error(_("Failed to copy notes from '%s' to '%s'"),
531 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
535 finish_copy_notes_for_rewrite(the_repository, c, msg);
542 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
543 * non-indented lines and checking if they look like they begin with valid
544 * header field names.
546 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
548 static int is_mail(FILE *fp)
550 const char *header_regex = "^[!-9;-~]+:";
551 struct strbuf sb = STRBUF_INIT;
555 if (fseek(fp, 0L, SEEK_SET))
556 die_errno(_("fseek failed"));
558 if (regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED))
559 die("invalid pattern: %s", header_regex);
561 while (!strbuf_getline(&sb, fp)) {
563 break; /* End of header */
565 /* Ignore indented folded lines */
566 if (*sb.buf == '\t' || *sb.buf == ' ')
569 /* It's a header if it matches header_regex */
570 if (regexec(®ex, sb.buf, 0, NULL, 0)) {
583 * Attempts to detect the patch_format of the patches contained in `paths`,
584 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
587 static int detect_patch_format(const char **paths)
589 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
590 struct strbuf l1 = STRBUF_INIT;
591 struct strbuf l2 = STRBUF_INIT;
592 struct strbuf l3 = STRBUF_INIT;
596 * We default to mbox format if input is from stdin and for directories
598 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
599 return PATCH_FORMAT_MBOX;
602 * Otherwise, check the first few lines of the first patch, starting
603 * from the first non-blank line, to try to detect its format.
606 fp = xfopen(*paths, "r");
608 while (!strbuf_getline(&l1, fp)) {
613 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
614 ret = PATCH_FORMAT_MBOX;
618 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
619 ret = PATCH_FORMAT_STGIT_SERIES;
623 if (!strcmp(l1.buf, "# HG changeset patch")) {
624 ret = PATCH_FORMAT_HG;
628 strbuf_getline(&l2, fp);
629 strbuf_getline(&l3, fp);
632 * If the second line is empty and the third is a From, Author or Date
633 * entry, this is likely an StGit patch.
635 if (l1.len && !l2.len &&
636 (starts_with(l3.buf, "From:") ||
637 starts_with(l3.buf, "Author:") ||
638 starts_with(l3.buf, "Date:"))) {
639 ret = PATCH_FORMAT_STGIT;
643 if (l1.len && is_mail(fp)) {
644 ret = PATCH_FORMAT_MBOX;
657 * Splits out individual email patches from `paths`, where each path is either
658 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
660 static int split_mail_mbox(struct am_state *state, const char **paths,
661 int keep_cr, int mboxrd)
663 struct child_process cp = CHILD_PROCESS_INIT;
664 struct strbuf last = STRBUF_INIT;
668 strvec_push(&cp.args, "mailsplit");
669 strvec_pushf(&cp.args, "-d%d", state->prec);
670 strvec_pushf(&cp.args, "-o%s", state->dir);
671 strvec_push(&cp.args, "-b");
673 strvec_push(&cp.args, "--keep-cr");
675 strvec_push(&cp.args, "--mboxrd");
676 strvec_push(&cp.args, "--");
677 strvec_pushv(&cp.args, paths);
679 ret = capture_command(&cp, &last, 8);
684 state->last = strtol(last.buf, NULL, 10);
687 strbuf_release(&last);
692 * Callback signature for split_mail_conv(). The foreign patch should be
693 * read from `in`, and the converted patch (in RFC2822 mail format) should be
694 * written to `out`. Return 0 on success, or -1 on failure.
696 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
699 * Calls `fn` for each file in `paths` to convert the foreign patch to the
700 * RFC2822 mail format suitable for parsing with git-mailinfo.
702 * Returns 0 on success, -1 on failure.
704 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
705 const char **paths, int keep_cr)
707 static const char *stdin_only[] = {"-", NULL};
713 for (i = 0; *paths; paths++, i++) {
718 if (!strcmp(*paths, "-"))
721 in = fopen(*paths, "r");
724 return error_errno(_("could not open '%s' for reading"),
727 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
729 out = fopen(mail, "w");
733 return error_errno(_("could not open '%s' for writing"),
737 ret = fn(out, in, keep_cr);
744 return error(_("could not parse patch '%s'"), *paths);
753 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
754 * message suitable for parsing with git-mailinfo.
756 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
758 struct strbuf sb = STRBUF_INIT;
759 int subject_printed = 0;
761 while (!strbuf_getline_lf(&sb, in)) {
764 if (str_isspace(sb.buf))
766 else if (skip_prefix(sb.buf, "Author:", &str))
767 fprintf(out, "From:%s\n", str);
768 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
769 fprintf(out, "%s\n", sb.buf);
770 else if (!subject_printed) {
771 fprintf(out, "Subject: %s\n", sb.buf);
774 fprintf(out, "\n%s\n", sb.buf);
780 while (strbuf_fread(&sb, 8192, in) > 0) {
781 fwrite(sb.buf, 1, sb.len, out);
790 * This function only supports a single StGit series file in `paths`.
792 * Given an StGit series file, converts the StGit patches in the series into
793 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
794 * the state directory.
796 * Returns 0 on success, -1 on failure.
798 static int split_mail_stgit_series(struct am_state *state, const char **paths,
801 const char *series_dir;
802 char *series_dir_buf;
804 struct strvec patches = STRVEC_INIT;
805 struct strbuf sb = STRBUF_INIT;
808 if (!paths[0] || paths[1])
809 return error(_("Only one StGIT patch series can be applied at once"));
811 series_dir_buf = xstrdup(*paths);
812 series_dir = dirname(series_dir_buf);
814 fp = fopen(*paths, "r");
816 return error_errno(_("could not open '%s' for reading"), *paths);
818 while (!strbuf_getline_lf(&sb, fp)) {
820 continue; /* skip comment lines */
822 strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
827 free(series_dir_buf);
829 ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
831 strvec_clear(&patches);
836 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
837 * message suitable for parsing with git-mailinfo.
839 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
841 struct strbuf sb = STRBUF_INIT;
844 while (!strbuf_getline_lf(&sb, in)) {
847 if (skip_prefix(sb.buf, "# User ", &str))
848 fprintf(out, "From: %s\n", str);
849 else if (skip_prefix(sb.buf, "# Date ", &str)) {
850 timestamp_t timestamp;
855 timestamp = parse_timestamp(str, &end, 10);
857 rc = error(_("invalid timestamp"));
861 if (!skip_prefix(end, " ", &str)) {
862 rc = error(_("invalid Date line"));
867 tz = strtol(str, &end, 10);
869 rc = error(_("invalid timezone offset"));
874 rc = error(_("invalid Date line"));
879 * mercurial's timezone is in seconds west of UTC,
880 * however git's timezone is in hours + minutes east of
883 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
887 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
888 } else if (starts_with(sb.buf, "# ")) {
891 fprintf(out, "\n%s\n", sb.buf);
897 while (strbuf_fread(&sb, 8192, in) > 0) {
898 fwrite(sb.buf, 1, sb.len, out);
907 * Splits a list of files/directories into individual email patches. Each path
908 * in `paths` must be a file/directory that is formatted according to
911 * Once split out, the individual email patches will be stored in the state
912 * directory, with each patch's filename being its index, padded to state->prec
915 * state->cur will be set to the index of the first mail, and state->last will
916 * be set to the index of the last mail.
918 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
919 * to disable this behavior, -1 to use the default configured setting.
921 * Returns 0 on success, -1 on failure.
923 static int split_mail(struct am_state *state, enum patch_format patch_format,
924 const char **paths, int keep_cr)
928 git_config_get_bool("am.keepcr", &keep_cr);
931 switch (patch_format) {
932 case PATCH_FORMAT_MBOX:
933 return split_mail_mbox(state, paths, keep_cr, 0);
934 case PATCH_FORMAT_STGIT:
935 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
936 case PATCH_FORMAT_STGIT_SERIES:
937 return split_mail_stgit_series(state, paths, keep_cr);
938 case PATCH_FORMAT_HG:
939 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
940 case PATCH_FORMAT_MBOXRD:
941 return split_mail_mbox(state, paths, keep_cr, 1);
943 BUG("invalid patch_format");
949 * Setup a new am session for applying patches
951 static void am_setup(struct am_state *state, enum patch_format patch_format,
952 const char **paths, int keep_cr)
954 struct object_id curr_head;
956 struct strbuf sb = STRBUF_INIT;
959 patch_format = detect_patch_format(paths);
962 fprintf_ln(stderr, _("Patch format detection failed."));
966 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
967 die_errno(_("failed to create directory '%s'"), state->dir);
968 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
970 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
972 die(_("Failed to split patches."));
978 write_state_bool(state, "threeway", state->threeway);
979 write_state_bool(state, "quiet", state->quiet);
980 write_state_bool(state, "sign", state->signoff);
981 write_state_bool(state, "utf8", state->utf8);
983 if (state->allow_rerere_autoupdate)
984 write_state_bool(state, "rerere-autoupdate",
985 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
987 switch (state->keep) {
998 BUG("invalid value for state->keep");
1001 write_state_text(state, "keep", str);
1002 write_state_bool(state, "messageid", state->message_id);
1004 switch (state->scissors) {
1005 case SCISSORS_UNSET:
1008 case SCISSORS_FALSE:
1015 BUG("invalid value for state->scissors");
1017 write_state_text(state, "scissors", str);
1019 sq_quote_argv(&sb, state->git_apply_opts.v);
1020 write_state_text(state, "apply-opt", sb.buf);
1022 if (state->rebasing)
1023 write_state_text(state, "rebasing", "");
1025 write_state_text(state, "applying", "");
1027 if (!get_oid("HEAD", &curr_head)) {
1028 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1029 if (!state->rebasing)
1030 update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1031 UPDATE_REFS_DIE_ON_ERR);
1033 write_state_text(state, "abort-safety", "");
1034 if (!state->rebasing)
1035 delete_ref(NULL, "ORIG_HEAD", NULL, 0);
1039 * NOTE: Since the "next" and "last" files determine if an am_state
1040 * session is in progress, they should be written last.
1043 write_state_count(state, "next", state->cur);
1044 write_state_count(state, "last", state->last);
1046 strbuf_release(&sb);
1050 * Increments the patch pointer, and cleans am_state for the application of the
1053 static void am_next(struct am_state *state)
1055 struct object_id head;
1057 FREE_AND_NULL(state->author_name);
1058 FREE_AND_NULL(state->author_email);
1059 FREE_AND_NULL(state->author_date);
1060 FREE_AND_NULL(state->msg);
1063 unlink(am_path(state, "author-script"));
1064 unlink(am_path(state, "final-commit"));
1066 oidclr(&state->orig_commit);
1067 unlink(am_path(state, "original-commit"));
1068 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1070 if (!get_oid("HEAD", &head))
1071 write_state_text(state, "abort-safety", oid_to_hex(&head));
1073 write_state_text(state, "abort-safety", "");
1076 write_state_count(state, "next", state->cur);
1080 * Returns the filename of the current patch email.
1082 static const char *msgnum(const struct am_state *state)
1084 static struct strbuf sb = STRBUF_INIT;
1087 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1093 * Dies with a user-friendly message on how to proceed after resolving the
1094 * problem. This message can be overridden with state->resolvemsg.
1096 static void NORETURN die_user_resolve(const struct am_state *state)
1098 if (state->resolvemsg) {
1099 printf_ln("%s", state->resolvemsg);
1101 const char *cmdline = state->interactive ? "git am -i" : "git am";
1103 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1104 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1105 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1112 * Appends signoff to the "msg" field of the am_state.
1114 static void am_append_signoff(struct am_state *state)
1116 struct strbuf sb = STRBUF_INIT;
1118 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1119 append_signoff(&sb, 0, 0);
1120 state->msg = strbuf_detach(&sb, &state->msg_len);
1124 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1125 * state->msg will be set to the patch message. state->author_name,
1126 * state->author_email and state->author_date will be set to the patch author's
1127 * name, email and date respectively. The patch body will be written to the
1128 * state directory's "patch" file.
1130 * Returns 1 if the patch should be skipped, 0 otherwise.
1132 static int parse_mail(struct am_state *state, const char *mail)
1135 struct strbuf sb = STRBUF_INIT;
1136 struct strbuf msg = STRBUF_INIT;
1137 struct strbuf author_name = STRBUF_INIT;
1138 struct strbuf author_date = STRBUF_INIT;
1139 struct strbuf author_email = STRBUF_INIT;
1143 setup_mailinfo(&mi);
1146 mi.metainfo_charset = get_commit_output_encoding();
1148 mi.metainfo_charset = NULL;
1150 switch (state->keep) {
1154 mi.keep_subject = 1;
1156 case KEEP_NON_PATCH:
1157 mi.keep_non_patch_brackets_in_subject = 1;
1160 BUG("invalid value for state->keep");
1163 if (state->message_id)
1164 mi.add_message_id = 1;
1166 switch (state->scissors) {
1167 case SCISSORS_UNSET:
1169 case SCISSORS_FALSE:
1170 mi.use_scissors = 0;
1173 mi.use_scissors = 1;
1176 BUG("invalid value for state->scissors");
1179 mi.input = xfopen(mail, "r");
1180 mi.output = xfopen(am_path(state, "info"), "w");
1181 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1182 die("could not parse patch");
1187 if (mi.format_flowed)
1188 warning(_("Patch sent with format=flowed; "
1189 "space at the end of lines might be lost."));
1191 /* Extract message and author information */
1192 fp = xfopen(am_path(state, "info"), "r");
1193 while (!strbuf_getline_lf(&sb, fp)) {
1196 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1198 strbuf_addch(&msg, '\n');
1199 strbuf_addstr(&msg, x);
1200 } else if (skip_prefix(sb.buf, "Author: ", &x))
1201 strbuf_addstr(&author_name, x);
1202 else if (skip_prefix(sb.buf, "Email: ", &x))
1203 strbuf_addstr(&author_email, x);
1204 else if (skip_prefix(sb.buf, "Date: ", &x))
1205 strbuf_addstr(&author_date, x);
1209 /* Skip pine's internal folder data */
1210 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1215 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1216 printf_ln(_("Patch is empty."));
1217 die_user_resolve(state);
1220 strbuf_addstr(&msg, "\n\n");
1221 strbuf_addbuf(&msg, &mi.log_message);
1222 strbuf_stripspace(&msg, 0);
1224 assert(!state->author_name);
1225 state->author_name = strbuf_detach(&author_name, NULL);
1227 assert(!state->author_email);
1228 state->author_email = strbuf_detach(&author_email, NULL);
1230 assert(!state->author_date);
1231 state->author_date = strbuf_detach(&author_date, NULL);
1233 assert(!state->msg);
1234 state->msg = strbuf_detach(&msg, &state->msg_len);
1237 strbuf_release(&msg);
1238 strbuf_release(&author_date);
1239 strbuf_release(&author_email);
1240 strbuf_release(&author_name);
1241 strbuf_release(&sb);
1242 clear_mailinfo(&mi);
1247 * Sets commit_id to the commit hash where the mail was generated from.
1248 * Returns 0 on success, -1 on failure.
1250 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1252 struct strbuf sb = STRBUF_INIT;
1253 FILE *fp = xfopen(mail, "r");
1257 if (strbuf_getline_lf(&sb, fp) ||
1258 !skip_prefix(sb.buf, "From ", &x) ||
1259 get_oid_hex(x, commit_id) < 0)
1262 strbuf_release(&sb);
1268 * Sets state->msg, state->author_name, state->author_email, state->author_date
1269 * to the commit's respective info.
1271 static void get_commit_info(struct am_state *state, struct commit *commit)
1273 const char *buffer, *ident_line, *msg;
1275 struct ident_split id;
1277 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1279 ident_line = find_commit_header(buffer, "author", &ident_len);
1281 die(_("missing author line in commit %s"),
1282 oid_to_hex(&commit->object.oid));
1283 if (split_ident_line(&id, ident_line, ident_len) < 0)
1284 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1286 assert(!state->author_name);
1288 state->author_name =
1289 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1291 state->author_name = xstrdup("");
1293 assert(!state->author_email);
1295 state->author_email =
1296 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1298 state->author_email = xstrdup("");
1300 assert(!state->author_date);
1301 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1303 assert(!state->msg);
1304 msg = strstr(buffer, "\n\n");
1306 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1307 state->msg = xstrdup(msg + 2);
1308 state->msg_len = strlen(state->msg);
1309 unuse_commit_buffer(commit, buffer);
1313 * Writes `commit` as a patch to the state directory's "patch" file.
1315 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1317 struct rev_info rev_info;
1320 fp = xfopen(am_path(state, "patch"), "w");
1321 repo_init_revisions(the_repository, &rev_info, NULL);
1323 rev_info.abbrev = 0;
1324 rev_info.disable_stdin = 1;
1325 rev_info.show_root_diff = 1;
1326 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1327 rev_info.no_commit_id = 1;
1328 rev_info.diffopt.flags.binary = 1;
1329 rev_info.diffopt.flags.full_index = 1;
1330 rev_info.diffopt.use_color = 0;
1331 rev_info.diffopt.file = fp;
1332 rev_info.diffopt.close_file = 1;
1333 add_pending_object(&rev_info, &commit->object, "");
1334 diff_setup_done(&rev_info.diffopt);
1335 log_tree_commit(&rev_info, commit);
1339 * Writes the diff of the index against HEAD as a patch to the state
1340 * directory's "patch" file.
1342 static void write_index_patch(const struct am_state *state)
1345 struct object_id head;
1346 struct rev_info rev_info;
1349 if (!get_oid("HEAD", &head)) {
1350 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1351 tree = get_commit_tree(commit);
1353 tree = lookup_tree(the_repository,
1354 the_repository->hash_algo->empty_tree);
1356 fp = xfopen(am_path(state, "patch"), "w");
1357 repo_init_revisions(the_repository, &rev_info, NULL);
1359 rev_info.disable_stdin = 1;
1360 rev_info.no_commit_id = 1;
1361 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1362 rev_info.diffopt.use_color = 0;
1363 rev_info.diffopt.file = fp;
1364 rev_info.diffopt.close_file = 1;
1365 add_pending_object(&rev_info, &tree->object, "");
1366 diff_setup_done(&rev_info.diffopt);
1367 run_diff_index(&rev_info, 1);
1371 * Like parse_mail(), but parses the mail by looking up its commit ID
1372 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1375 * state->orig_commit will be set to the original commit ID.
1377 * Will always return 0 as the patch should never be skipped.
1379 static int parse_mail_rebase(struct am_state *state, const char *mail)
1381 struct commit *commit;
1382 struct object_id commit_oid;
1384 if (get_mail_commit_oid(&commit_oid, mail) < 0)
1385 die(_("could not parse %s"), mail);
1387 commit = lookup_commit_or_die(&commit_oid, mail);
1389 get_commit_info(state, commit);
1391 write_commit_patch(state, commit);
1393 oidcpy(&state->orig_commit, &commit_oid);
1394 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1395 update_ref("am", "REBASE_HEAD", &commit_oid,
1396 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1402 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1403 * `index_file` is not NULL, the patch will be applied to that index.
1405 static int run_apply(const struct am_state *state, const char *index_file)
1407 struct strvec apply_paths = STRVEC_INIT;
1408 struct strvec apply_opts = STRVEC_INIT;
1409 struct apply_state apply_state;
1411 int force_apply = 0;
1414 if (init_apply_state(&apply_state, the_repository, NULL))
1415 BUG("init_apply_state() failed");
1417 strvec_push(&apply_opts, "apply");
1418 strvec_pushv(&apply_opts, state->git_apply_opts.v);
1420 opts_left = apply_parse_options(apply_opts.nr, apply_opts.v,
1421 &apply_state, &force_apply, &options,
1425 die("unknown option passed through to git apply");
1428 apply_state.index_file = index_file;
1429 apply_state.cached = 1;
1431 apply_state.check_index = 1;
1434 * If we are allowed to fall back on 3-way merge, don't give false
1435 * errors during the initial attempt.
1437 if (state->threeway && !index_file)
1438 apply_state.apply_verbosity = verbosity_silent;
1440 if (check_apply_state(&apply_state, force_apply))
1441 BUG("check_apply_state() failed");
1443 strvec_push(&apply_paths, am_path(state, "patch"));
1445 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
1447 strvec_clear(&apply_paths);
1448 strvec_clear(&apply_opts);
1449 clear_apply_state(&apply_state);
1455 /* Reload index as apply_all_patches() will have modified it. */
1457 read_cache_from(index_file);
1464 * Builds an index that contains just the blobs needed for a 3way merge.
1466 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1468 struct child_process cp = CHILD_PROCESS_INIT;
1471 strvec_push(&cp.args, "apply");
1472 strvec_pushv(&cp.args, state->git_apply_opts.v);
1473 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1474 strvec_push(&cp.args, am_path(state, "patch"));
1476 if (run_command(&cp))
1483 * Attempt a threeway merge, using index_path as the temporary index.
1485 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1487 struct object_id orig_tree, their_tree, our_tree;
1488 const struct object_id *bases[1] = { &orig_tree };
1489 struct merge_options o;
1490 struct commit *result;
1491 char *their_tree_name;
1493 if (get_oid("HEAD", &our_tree) < 0)
1494 oidcpy(&our_tree, the_hash_algo->empty_tree);
1496 if (build_fake_ancestor(state, index_path))
1497 return error("could not build fake ancestor");
1500 read_cache_from(index_path);
1502 if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
1503 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1505 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1507 if (!state->quiet) {
1509 * List paths that needed 3-way fallback, so that the user can
1510 * review them with extra care to spot mismerges.
1512 struct rev_info rev_info;
1514 repo_init_revisions(the_repository, &rev_info, NULL);
1515 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1516 rev_info.diffopt.filter |= diff_filter_bit('A');
1517 rev_info.diffopt.filter |= diff_filter_bit('M');
1518 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1519 diff_setup_done(&rev_info.diffopt);
1520 run_diff_index(&rev_info, 1);
1523 if (run_apply(state, index_path))
1524 return error(_("Did you hand edit your patch?\n"
1525 "It does not apply to blobs recorded in its index."));
1527 if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
1528 return error("could not write tree");
1530 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1536 * This is not so wrong. Depending on which base we picked, orig_tree
1537 * may be wildly different from ours, but their_tree has the same set of
1538 * wildly different changes in parts the patch did not touch, so
1539 * recursive ends up canceling them, saying that we reverted all those
1543 init_merge_options(&o, the_repository);
1546 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1547 o.branch2 = their_tree_name;
1548 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
1553 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1554 repo_rerere(the_repository, state->allow_rerere_autoupdate);
1555 free(their_tree_name);
1556 return error(_("Failed to merge in the changes."));
1559 free(their_tree_name);
1564 * Commits the current index with state->msg as the commit message and
1565 * state->author_name, state->author_email and state->author_date as the author
1568 static void do_commit(const struct am_state *state)
1570 struct object_id tree, parent, commit;
1571 const struct object_id *old_oid;
1572 struct commit_list *parents = NULL;
1573 const char *reflog_msg, *author, *committer = NULL;
1574 struct strbuf sb = STRBUF_INIT;
1576 if (run_hook_le(NULL, "pre-applypatch", NULL))
1579 if (write_cache_as_tree(&tree, 0, NULL))
1580 die(_("git write-tree failed to write a tree"));
1582 if (!get_oid_commit("HEAD", &parent)) {
1584 commit_list_insert(lookup_commit(the_repository, &parent),
1588 say(state, stderr, _("applying to an empty history"));
1591 author = fmt_ident(state->author_name, state->author_email,
1593 state->ignore_date ? NULL : state->author_date,
1596 if (state->committer_date_is_author_date)
1597 committer = fmt_ident(state->committer_name,
1598 state->author_email, WANT_COMMITTER_IDENT,
1599 state->ignore_date ? NULL
1600 : state->author_date,
1603 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1604 &commit, author, committer, state->sign_commit,
1606 die(_("failed to write commit object"));
1608 reflog_msg = getenv("GIT_REFLOG_ACTION");
1612 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1615 update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1616 UPDATE_REFS_DIE_ON_ERR);
1618 if (state->rebasing) {
1619 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1621 assert(!is_null_oid(&state->orig_commit));
1622 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1623 fprintf(fp, "%s\n", oid_to_hex(&commit));
1627 run_hook_le(NULL, "post-applypatch", NULL);
1629 strbuf_release(&sb);
1633 * Validates the am_state for resuming -- the "msg" and authorship fields must
1636 static void validate_resume_state(const struct am_state *state)
1639 die(_("cannot resume: %s does not exist."),
1640 am_path(state, "final-commit"));
1642 if (!state->author_name || !state->author_email || !state->author_date)
1643 die(_("cannot resume: %s does not exist."),
1644 am_path(state, "author-script"));
1648 * Interactively prompt the user on whether the current patch should be
1651 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1654 static int do_interactive(struct am_state *state)
1661 puts(_("Commit Body is:"));
1662 puts("--------------------------");
1663 printf("%s", state->msg);
1664 puts("--------------------------");
1667 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1668 * in your translation. The program will only accept English
1669 * input at this point.
1671 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1672 if (!fgets(reply, sizeof(reply), stdin))
1673 die("unable to read from stdin; aborting");
1675 if (*reply == 'y' || *reply == 'Y') {
1677 } else if (*reply == 'a' || *reply == 'A') {
1678 state->interactive = 0;
1680 } else if (*reply == 'n' || *reply == 'N') {
1682 } else if (*reply == 'e' || *reply == 'E') {
1683 struct strbuf msg = STRBUF_INIT;
1685 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1687 state->msg = strbuf_detach(&msg, &state->msg_len);
1689 strbuf_release(&msg);
1690 } else if (*reply == 'v' || *reply == 'V') {
1691 const char *pager = git_pager(1);
1692 struct child_process cp = CHILD_PROCESS_INIT;
1696 prepare_pager_args(&cp, pager);
1697 strvec_push(&cp.args, am_path(state, "patch"));
1704 * Applies all queued mail.
1706 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1707 * well as the state directory's "patch" file is used as-is for applying the
1708 * patch and committing it.
1710 static void am_run(struct am_state *state, int resume)
1712 struct strbuf sb = STRBUF_INIT;
1714 unlink(am_path(state, "dirtyindex"));
1716 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0)
1717 die(_("unable to write index file"));
1719 if (repo_index_has_changes(the_repository, NULL, &sb)) {
1720 write_state_bool(state, "dirtyindex", 1);
1721 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1724 strbuf_release(&sb);
1726 while (state->cur <= state->last) {
1727 const char *mail = am_path(state, msgnum(state));
1732 if (!file_exists(mail))
1736 validate_resume_state(state);
1740 if (state->rebasing)
1741 skip = parse_mail_rebase(state, mail);
1743 skip = parse_mail(state, mail);
1746 goto next; /* mail should be skipped */
1749 am_append_signoff(state);
1751 write_author_script(state);
1752 write_commit_msg(state);
1755 if (state->interactive && do_interactive(state))
1758 if (run_applypatch_msg_hook(state))
1761 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1763 apply_status = run_apply(state, NULL);
1765 if (apply_status && state->threeway) {
1766 struct strbuf sb = STRBUF_INIT;
1768 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1769 apply_status = fall_back_threeway(state, sb.buf);
1770 strbuf_release(&sb);
1773 * Applying the patch to an earlier tree and merging
1774 * the result may have produced the same tree as ours.
1776 if (!apply_status &&
1777 !repo_index_has_changes(the_repository, NULL, NULL)) {
1778 say(state, stdout, _("No changes -- Patch already applied."));
1784 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1785 linelen(state->msg), state->msg);
1787 if (advice_amworkdir)
1788 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1790 die_user_resolve(state);
1803 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1804 assert(state->rebasing);
1805 copy_notes_for_rebase(state);
1806 run_post_rewrite_hook(state);
1810 * In rebasing mode, it's up to the caller to take care of
1813 if (!state->rebasing) {
1815 close_object_store(the_repository->objects);
1816 run_auto_gc(state->quiet);
1821 * Resume the current am session after patch application failure. The user did
1822 * all the hard work, and we do not have to do any patch application. Just
1823 * trust and commit what the user has in the index and working tree.
1825 static void am_resolve(struct am_state *state)
1827 validate_resume_state(state);
1829 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1831 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
1832 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1833 "If there is nothing left to stage, chances are that something else\n"
1834 "already introduced the same changes; you might want to skip this patch."));
1835 die_user_resolve(state);
1838 if (unmerged_cache()) {
1839 printf_ln(_("You still have unmerged paths in your index.\n"
1840 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1841 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1842 die_user_resolve(state);
1845 if (state->interactive) {
1846 write_index_patch(state);
1847 if (do_interactive(state))
1851 repo_rerere(the_repository, 0);
1862 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1863 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1866 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1868 struct lock_file lock_file = LOCK_INIT;
1869 struct unpack_trees_options opts;
1870 struct tree_desc t[2];
1872 if (parse_tree(head) || parse_tree(remote))
1875 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1877 refresh_cache(REFRESH_QUIET);
1879 memset(&opts, 0, sizeof(opts));
1881 opts.src_index = &the_index;
1882 opts.dst_index = &the_index;
1886 opts.fn = twoway_merge;
1887 init_tree_desc(&t[0], head->buffer, head->size);
1888 init_tree_desc(&t[1], remote->buffer, remote->size);
1890 if (unpack_trees(2, t, &opts)) {
1891 rollback_lock_file(&lock_file);
1895 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1896 die(_("unable to write new index file"));
1902 * Merges a tree into the index. The index's stat info will take precedence
1903 * over the merged tree's. Returns 0 on success, -1 on failure.
1905 static int merge_tree(struct tree *tree)
1907 struct lock_file lock_file = LOCK_INIT;
1908 struct unpack_trees_options opts;
1909 struct tree_desc t[1];
1911 if (parse_tree(tree))
1914 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1916 memset(&opts, 0, sizeof(opts));
1918 opts.src_index = &the_index;
1919 opts.dst_index = &the_index;
1921 opts.fn = oneway_merge;
1922 init_tree_desc(&t[0], tree->buffer, tree->size);
1924 if (unpack_trees(1, 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 * Clean the index without touching entries that are not modified between
1937 * `head` and `remote`.
1939 static int clean_index(const struct object_id *head, const struct object_id *remote)
1941 struct tree *head_tree, *remote_tree, *index_tree;
1942 struct object_id index;
1944 head_tree = parse_tree_indirect(head);
1946 return error(_("Could not parse object '%s'."), oid_to_hex(head));
1948 remote_tree = parse_tree_indirect(remote);
1950 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
1952 read_cache_unmerged();
1954 if (fast_forward_to(head_tree, head_tree, 1))
1957 if (write_cache_as_tree(&index, 0, NULL))
1960 index_tree = parse_tree_indirect(&index);
1962 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
1964 if (fast_forward_to(index_tree, remote_tree, 0))
1967 if (merge_tree(remote_tree))
1970 remove_branch_state(the_repository, 0);
1976 * Resets rerere's merge resolution metadata.
1978 static void am_rerere_clear(void)
1980 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1981 rerere_clear(the_repository, &merge_rr);
1982 string_list_clear(&merge_rr, 1);
1986 * Resume the current am session by skipping the current patch.
1988 static void am_skip(struct am_state *state)
1990 struct object_id head;
1994 if (get_oid("HEAD", &head))
1995 oidcpy(&head, the_hash_algo->empty_tree);
1997 if (clean_index(&head, &head))
1998 die(_("failed to clean index"));
2000 if (state->rebasing) {
2001 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2003 assert(!is_null_oid(&state->orig_commit));
2004 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2005 fprintf(fp, "%s\n", oid_to_hex(&head));
2015 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2017 * It is not safe to reset HEAD when:
2018 * 1. git-am previously failed because the index was dirty.
2019 * 2. HEAD has moved since git-am previously failed.
2021 static int safe_to_abort(const struct am_state *state)
2023 struct strbuf sb = STRBUF_INIT;
2024 struct object_id abort_safety, head;
2026 if (file_exists(am_path(state, "dirtyindex")))
2029 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2030 if (get_oid_hex(sb.buf, &abort_safety))
2031 die(_("could not parse %s"), am_path(state, "abort-safety"));
2033 oidclr(&abort_safety);
2034 strbuf_release(&sb);
2036 if (get_oid("HEAD", &head))
2039 if (oideq(&head, &abort_safety))
2042 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2043 "Not rewinding to ORIG_HEAD"));
2049 * Aborts the current am session if it is safe to do so.
2051 static void am_abort(struct am_state *state)
2053 struct object_id curr_head, orig_head;
2054 int has_curr_head, has_orig_head;
2057 if (!safe_to_abort(state)) {
2064 curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2065 has_curr_head = curr_branch && !is_null_oid(&curr_head);
2067 oidcpy(&curr_head, the_hash_algo->empty_tree);
2069 has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
2071 oidcpy(&orig_head, the_hash_algo->empty_tree);
2073 clean_index(&curr_head, &orig_head);
2076 update_ref("am --abort", "HEAD", &orig_head,
2077 has_curr_head ? &curr_head : NULL, 0,
2078 UPDATE_REFS_DIE_ON_ERR);
2079 else if (curr_branch)
2080 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
2086 static int show_patch(struct am_state *state, enum show_patch_type sub_mode)
2088 struct strbuf sb = STRBUF_INIT;
2089 const char *patch_path;
2092 if (!is_null_oid(&state->orig_commit)) {
2093 const char *av[4] = { "show", NULL, "--", NULL };
2097 av[1] = new_oid_str = xstrdup(oid_to_hex(&state->orig_commit));
2098 ret = run_command_v_opt(av, RUN_GIT_CMD);
2104 case SHOW_PATCH_RAW:
2105 patch_path = am_path(state, msgnum(state));
2107 case SHOW_PATCH_DIFF:
2108 patch_path = am_path(state, "patch");
2111 BUG("invalid mode for --show-current-patch");
2114 len = strbuf_read_file(&sb, patch_path, 0);
2116 die_errno(_("failed to read '%s'"), patch_path);
2119 write_in_full(1, sb.buf, sb.len);
2120 strbuf_release(&sb);
2125 * parse_options() callback that validates and sets opt->value to the
2126 * PATCH_FORMAT_* enum value corresponding to `arg`.
2128 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2130 int *opt_value = opt->value;
2133 *opt_value = PATCH_FORMAT_UNKNOWN;
2134 else if (!strcmp(arg, "mbox"))
2135 *opt_value = PATCH_FORMAT_MBOX;
2136 else if (!strcmp(arg, "stgit"))
2137 *opt_value = PATCH_FORMAT_STGIT;
2138 else if (!strcmp(arg, "stgit-series"))
2139 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2140 else if (!strcmp(arg, "hg"))
2141 *opt_value = PATCH_FORMAT_HG;
2142 else if (!strcmp(arg, "mboxrd"))
2143 *opt_value = PATCH_FORMAT_MBOXRD;
2145 * Please update $__git_patchformat in git-completion.bash
2146 * when you add new options
2149 return error(_("Invalid value for --patch-format: %s"), arg);
2163 struct resume_mode {
2164 enum resume_type mode;
2165 enum show_patch_type sub_mode;
2168 static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2170 int *opt_value = opt->value;
2171 struct resume_mode *resume = container_of(opt_value, struct resume_mode, mode);
2174 * Please update $__git_showcurrentpatch in git-completion.bash
2175 * when you add new options
2177 const char *valid_modes[] = {
2178 [SHOW_PATCH_DIFF] = "diff",
2179 [SHOW_PATCH_RAW] = "raw"
2181 int new_value = SHOW_PATCH_RAW;
2184 for (new_value = 0; new_value < ARRAY_SIZE(valid_modes); new_value++) {
2185 if (!strcmp(arg, valid_modes[new_value]))
2188 if (new_value >= ARRAY_SIZE(valid_modes))
2189 return error(_("Invalid value for --show-current-patch: %s"), arg);
2192 if (resume->mode == RESUME_SHOW_PATCH && new_value != resume->sub_mode)
2193 return error(_("--show-current-patch=%s is incompatible with "
2194 "--show-current-patch=%s"),
2195 arg, valid_modes[resume->sub_mode]);
2197 resume->mode = RESUME_SHOW_PATCH;
2198 resume->sub_mode = new_value;
2202 static int git_am_config(const char *k, const char *v, void *cb)
2206 status = git_gpg_config(k, v, NULL);
2210 return git_default_config(k, v, NULL);
2213 int cmd_am(int argc, const char **argv, const char *prefix)
2215 struct am_state state;
2218 int patch_format = PATCH_FORMAT_UNKNOWN;
2219 struct resume_mode resume = { .mode = RESUME_FALSE };
2223 const char * const usage[] = {
2224 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2225 N_("git am [<options>] (--continue | --skip | --abort)"),
2229 struct option options[] = {
2230 OPT_BOOL('i', "interactive", &state.interactive,
2231 N_("run interactively")),
2232 OPT_HIDDEN_BOOL('b', "binary", &binary,
2233 N_("historical option -- no-op")),
2234 OPT_BOOL('3', "3way", &state.threeway,
2235 N_("allow fall back on 3way merging if needed")),
2236 OPT__QUIET(&state.quiet, N_("be quiet")),
2237 OPT_SET_INT('s', "signoff", &state.signoff,
2238 N_("add a Signed-off-by line to the commit message"),
2240 OPT_BOOL('u', "utf8", &state.utf8,
2241 N_("recode into utf8 (default)")),
2242 OPT_SET_INT('k', "keep", &state.keep,
2243 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2244 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2245 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2246 OPT_BOOL('m', "message-id", &state.message_id,
2247 N_("pass -m flag to git-mailinfo")),
2248 OPT_SET_INT_F(0, "keep-cr", &keep_cr,
2249 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2250 1, PARSE_OPT_NONEG),
2251 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr,
2252 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2253 0, PARSE_OPT_NONEG),
2254 OPT_BOOL('c', "scissors", &state.scissors,
2255 N_("strip everything before a scissors line")),
2256 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2257 N_("pass it through git-apply"),
2259 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2260 N_("pass it through git-apply"),
2262 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2263 N_("pass it through git-apply"),
2265 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2266 N_("pass it through git-apply"),
2268 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2269 N_("pass it through git-apply"),
2271 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2272 N_("pass it through git-apply"),
2274 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2275 N_("pass it through git-apply"),
2277 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2278 N_("pass it through git-apply"),
2280 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2281 N_("format the patch(es) are in"),
2282 parse_opt_patchformat),
2283 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2284 N_("pass it through git-apply"),
2286 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2287 N_("override error message when patch failure occurs")),
2288 OPT_CMDMODE(0, "continue", &resume.mode,
2289 N_("continue applying patches after resolving a conflict"),
2291 OPT_CMDMODE('r', "resolved", &resume.mode,
2292 N_("synonyms for --continue"),
2294 OPT_CMDMODE(0, "skip", &resume.mode,
2295 N_("skip the current patch"),
2297 OPT_CMDMODE(0, "abort", &resume.mode,
2298 N_("restore the original branch and abort the patching operation."),
2300 OPT_CMDMODE(0, "quit", &resume.mode,
2301 N_("abort the patching operation but keep HEAD where it is."),
2303 { OPTION_CALLBACK, 0, "show-current-patch", &resume.mode,
2305 N_("show the patch being applied"),
2306 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2307 parse_opt_show_current_patch, RESUME_SHOW_PATCH },
2308 OPT_BOOL(0, "committer-date-is-author-date",
2309 &state.committer_date_is_author_date,
2310 N_("lie about committer date")),
2311 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2312 N_("use current timestamp for author date")),
2313 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2314 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2315 N_("GPG-sign commits"),
2316 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2317 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2318 N_("(internal use for git-rebase)")),
2322 if (argc == 2 && !strcmp(argv[1], "-h"))
2323 usage_with_options(usage, options);
2325 git_config(git_am_config, NULL);
2327 am_state_init(&state);
2329 in_progress = am_in_progress(&state);
2333 argc = parse_options(argc, argv, prefix, options, usage, 0);
2336 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2337 "it will be removed. Please do not use it anymore."));
2339 /* Ensure a valid committer ident can be constructed */
2340 git_committer_info(IDENT_STRICT);
2342 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
2343 die(_("failed to read the index"));
2347 * Catch user error to feed us patches when there is a session
2350 * 1. mbox path(s) are provided on the command-line.
2351 * 2. stdin is not a tty: the user is trying to feed us a patch
2352 * from standard input. This is somewhat unreliable -- stdin
2353 * could be /dev/null for example and the caller did not
2354 * intend to feed us a patch but wanted to continue
2357 if (argc || (resume.mode == RESUME_FALSE && !isatty(0)))
2358 die(_("previous rebase directory %s still exists but mbox given."),
2361 if (resume.mode == RESUME_FALSE)
2362 resume.mode = RESUME_APPLY;
2364 if (state.signoff == SIGNOFF_EXPLICIT)
2365 am_append_signoff(&state);
2367 struct strvec paths = STRVEC_INIT;
2371 * Handle stray state directory in the independent-run case. In
2372 * the --rebasing case, it is up to the caller to take care of
2373 * stray directories.
2375 if (file_exists(state.dir) && !state.rebasing) {
2376 if (resume.mode == RESUME_ABORT || resume.mode == RESUME_QUIT) {
2378 am_state_release(&state);
2382 die(_("Stray %s directory found.\n"
2383 "Use \"git am --abort\" to remove it."),
2388 die(_("Resolve operation not in progress, we are not resuming."));
2390 for (i = 0; i < argc; i++) {
2391 if (is_absolute_path(argv[i]) || !prefix)
2392 strvec_push(&paths, argv[i]);
2394 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2397 if (state.interactive && !paths.nr)
2398 die(_("interactive mode requires patches on the command line"));
2400 am_setup(&state, patch_format, paths.v, keep_cr);
2402 strvec_clear(&paths);
2405 switch (resume.mode) {
2412 case RESUME_RESOLVED:
2425 case RESUME_SHOW_PATCH:
2426 ret = show_patch(&state, resume.sub_mode);
2429 BUG("invalid resume value");
2432 am_state_release(&state);