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"
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 */
85 /* state directory path */
88 /* current and last patch numbers, 1-indexed */
92 /* commit metadata and message */
99 /* when --rebasing, records the original commit the patch came from */
100 struct object_id orig_commit
;
102 /* number of digits in patch filename */
105 /* various operating modes and command line options */
109 int signoff
; /* enum signoff_type */
111 int keep
; /* enum keep_type */
113 int scissors
; /* enum scissors_type */
114 struct argv_array git_apply_opts
;
115 const char *resolvemsg
;
116 int committer_date_is_author_date
;
118 int allow_rerere_autoupdate
;
119 const char *sign_commit
;
124 * Initializes am_state with the default values.
126 static void am_state_init(struct am_state
*state
)
130 memset(state
, 0, sizeof(*state
));
132 state
->dir
= git_pathdup("rebase-apply");
136 git_config_get_bool("am.threeway", &state
->threeway
);
140 git_config_get_bool("am.messageid", &state
->message_id
);
142 state
->scissors
= SCISSORS_UNSET
;
144 argv_array_init(&state
->git_apply_opts
);
146 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
147 state
->sign_commit
= gpgsign
? "" : NULL
;
151 * Releases memory allocated by an am_state.
153 static void am_state_release(struct am_state
*state
)
156 free(state
->author_name
);
157 free(state
->author_email
);
158 free(state
->author_date
);
160 argv_array_clear(&state
->git_apply_opts
);
164 * Returns path relative to the am_state directory.
166 static inline const char *am_path(const struct am_state
*state
, const char *path
)
168 return mkpath("%s/%s", state
->dir
, path
);
172 * For convenience to call write_file()
174 static void write_state_text(const struct am_state
*state
,
175 const char *name
, const char *string
)
177 write_file(am_path(state
, name
), "%s", string
);
180 static void write_state_count(const struct am_state
*state
,
181 const char *name
, int value
)
183 write_file(am_path(state
, name
), "%d", value
);
186 static void write_state_bool(const struct am_state
*state
,
187 const char *name
, int value
)
189 write_state_text(state
, name
, value
? "t" : "f");
193 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
196 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
202 vfprintf(fp
, fmt
, ap
);
209 * Returns 1 if there is an am session in progress, 0 otherwise.
211 static int am_in_progress(const struct am_state
*state
)
215 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
217 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
219 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
225 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
226 * number of bytes read on success, -1 if the file does not exist. If `trim` is
227 * set, trailing whitespace will be removed.
229 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
230 const char *file
, int trim
)
234 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
244 die_errno(_("could not read '%s'"), am_path(state
, file
));
248 * Reads and parses the state directory's "author-script" file, and sets
249 * state->author_name, state->author_email and state->author_date accordingly.
250 * Returns 0 on success, -1 if the file could not be parsed.
252 * The author script is of the format:
254 * GIT_AUTHOR_NAME='$author_name'
255 * GIT_AUTHOR_EMAIL='$author_email'
256 * GIT_AUTHOR_DATE='$author_date'
258 * where $author_name, $author_email and $author_date are quoted. We are strict
259 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
260 * script, and thus if the file differs from what this function expects, it is
261 * better to bail out than to do something that the user does not expect.
263 static int read_am_author_script(struct am_state
*state
)
265 const char *filename
= am_path(state
, "author-script");
267 assert(!state
->author_name
);
268 assert(!state
->author_email
);
269 assert(!state
->author_date
);
271 return read_author_script(filename
, &state
->author_name
,
272 &state
->author_email
, &state
->author_date
, 1);
276 * Saves state->author_name, state->author_email and state->author_date in the
277 * state directory's "author-script" file.
279 static void write_author_script(const struct am_state
*state
)
281 struct strbuf sb
= STRBUF_INIT
;
283 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
284 sq_quote_buf(&sb
, state
->author_name
);
285 strbuf_addch(&sb
, '\n');
287 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
288 sq_quote_buf(&sb
, state
->author_email
);
289 strbuf_addch(&sb
, '\n');
291 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
292 sq_quote_buf(&sb
, state
->author_date
);
293 strbuf_addch(&sb
, '\n');
295 write_state_text(state
, "author-script", sb
.buf
);
301 * Reads the commit message from the state directory's "final-commit" file,
302 * setting state->msg to its contents and state->msg_len to the length of its
305 * Returns 0 on success, -1 if the file does not exist.
307 static int read_commit_msg(struct am_state
*state
)
309 struct strbuf sb
= STRBUF_INIT
;
313 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
318 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
323 * Saves state->msg in the state directory's "final-commit" file.
325 static void write_commit_msg(const struct am_state
*state
)
327 const char *filename
= am_path(state
, "final-commit");
328 write_file_buf(filename
, state
->msg
, state
->msg_len
);
332 * Loads state from disk.
334 static void am_load(struct am_state
*state
)
336 struct strbuf sb
= STRBUF_INIT
;
338 if (read_state_file(&sb
, state
, "next", 1) < 0)
339 BUG("state file 'next' does not exist");
340 state
->cur
= strtol(sb
.buf
, NULL
, 10);
342 if (read_state_file(&sb
, state
, "last", 1) < 0)
343 BUG("state file 'last' does not exist");
344 state
->last
= strtol(sb
.buf
, NULL
, 10);
346 if (read_am_author_script(state
) < 0)
347 die(_("could not parse author script"));
349 read_commit_msg(state
);
351 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
352 oidclr(&state
->orig_commit
);
353 else if (get_oid_hex(sb
.buf
, &state
->orig_commit
) < 0)
354 die(_("could not parse %s"), am_path(state
, "original-commit"));
356 read_state_file(&sb
, state
, "threeway", 1);
357 state
->threeway
= !strcmp(sb
.buf
, "t");
359 read_state_file(&sb
, state
, "quiet", 1);
360 state
->quiet
= !strcmp(sb
.buf
, "t");
362 read_state_file(&sb
, state
, "sign", 1);
363 state
->signoff
= !strcmp(sb
.buf
, "t");
365 read_state_file(&sb
, state
, "utf8", 1);
366 state
->utf8
= !strcmp(sb
.buf
, "t");
368 if (file_exists(am_path(state
, "rerere-autoupdate"))) {
369 read_state_file(&sb
, state
, "rerere-autoupdate", 1);
370 state
->allow_rerere_autoupdate
= strcmp(sb
.buf
, "t") ?
371 RERERE_NOAUTOUPDATE
: RERERE_AUTOUPDATE
;
373 state
->allow_rerere_autoupdate
= 0;
376 read_state_file(&sb
, state
, "keep", 1);
377 if (!strcmp(sb
.buf
, "t"))
378 state
->keep
= KEEP_TRUE
;
379 else if (!strcmp(sb
.buf
, "b"))
380 state
->keep
= KEEP_NON_PATCH
;
382 state
->keep
= KEEP_FALSE
;
384 read_state_file(&sb
, state
, "messageid", 1);
385 state
->message_id
= !strcmp(sb
.buf
, "t");
387 read_state_file(&sb
, state
, "scissors", 1);
388 if (!strcmp(sb
.buf
, "t"))
389 state
->scissors
= SCISSORS_TRUE
;
390 else if (!strcmp(sb
.buf
, "f"))
391 state
->scissors
= SCISSORS_FALSE
;
393 state
->scissors
= SCISSORS_UNSET
;
395 read_state_file(&sb
, state
, "apply-opt", 1);
396 argv_array_clear(&state
->git_apply_opts
);
397 if (sq_dequote_to_argv_array(sb
.buf
, &state
->git_apply_opts
) < 0)
398 die(_("could not parse %s"), am_path(state
, "apply-opt"));
400 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
406 * Removes the am_state directory, forcefully terminating the current am
409 static void am_destroy(const struct am_state
*state
)
411 struct strbuf sb
= STRBUF_INIT
;
413 strbuf_addstr(&sb
, state
->dir
);
414 remove_dir_recursively(&sb
, 0);
419 * Runs applypatch-msg hook. Returns its exit code.
421 static int run_applypatch_msg_hook(struct am_state
*state
)
426 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
429 FREE_AND_NULL(state
->msg
);
430 if (read_commit_msg(state
) < 0)
431 die(_("'%s' was deleted by the applypatch-msg hook"),
432 am_path(state
, "final-commit"));
439 * Runs post-rewrite hook. Returns it exit code.
441 static int run_post_rewrite_hook(const struct am_state
*state
)
443 struct child_process cp
= CHILD_PROCESS_INIT
;
444 const char *hook
= find_hook("post-rewrite");
450 argv_array_push(&cp
.args
, hook
);
451 argv_array_push(&cp
.args
, "rebase");
453 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
454 cp
.stdout_to_stderr
= 1;
456 ret
= run_command(&cp
);
463 * Reads the state directory's "rewritten" file, and copies notes from the old
464 * commits listed in the file to their rewritten commits.
466 * Returns 0 on success, -1 on failure.
468 static int copy_notes_for_rebase(const struct am_state
*state
)
470 struct notes_rewrite_cfg
*c
;
471 struct strbuf sb
= STRBUF_INIT
;
472 const char *invalid_line
= _("Malformed input line: '%s'.");
473 const char *msg
= "Notes added by 'git rebase'";
477 assert(state
->rebasing
);
479 c
= init_copy_notes_for_rewrite("rebase");
483 fp
= xfopen(am_path(state
, "rewritten"), "r");
485 while (!strbuf_getline_lf(&sb
, fp
)) {
486 struct object_id from_obj
, to_obj
;
488 if (sb
.len
!= GIT_SHA1_HEXSZ
* 2 + 1) {
489 ret
= error(invalid_line
, sb
.buf
);
493 if (get_oid_hex(sb
.buf
, &from_obj
)) {
494 ret
= error(invalid_line
, sb
.buf
);
498 if (sb
.buf
[GIT_SHA1_HEXSZ
] != ' ') {
499 ret
= error(invalid_line
, sb
.buf
);
503 if (get_oid_hex(sb
.buf
+ GIT_SHA1_HEXSZ
+ 1, &to_obj
)) {
504 ret
= error(invalid_line
, sb
.buf
);
508 if (copy_note_for_rewrite(c
, &from_obj
, &to_obj
))
509 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
510 oid_to_hex(&from_obj
), oid_to_hex(&to_obj
));
514 finish_copy_notes_for_rewrite(c
, msg
);
521 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
522 * non-indented lines and checking if they look like they begin with valid
523 * header field names.
525 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
527 static int is_mail(FILE *fp
)
529 const char *header_regex
= "^[!-9;-~]+:";
530 struct strbuf sb
= STRBUF_INIT
;
534 if (fseek(fp
, 0L, SEEK_SET
))
535 die_errno(_("fseek failed"));
537 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
538 die("invalid pattern: %s", header_regex
);
540 while (!strbuf_getline(&sb
, fp
)) {
542 break; /* End of header */
544 /* Ignore indented folded lines */
545 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
548 /* It's a header if it matches header_regex */
549 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
562 * Attempts to detect the patch_format of the patches contained in `paths`,
563 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
566 static int detect_patch_format(const char **paths
)
568 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
569 struct strbuf l1
= STRBUF_INIT
;
570 struct strbuf l2
= STRBUF_INIT
;
571 struct strbuf l3
= STRBUF_INIT
;
575 * We default to mbox format if input is from stdin and for directories
577 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
578 return PATCH_FORMAT_MBOX
;
581 * Otherwise, check the first few lines of the first patch, starting
582 * from the first non-blank line, to try to detect its format.
585 fp
= xfopen(*paths
, "r");
587 while (!strbuf_getline(&l1
, fp
)) {
592 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
593 ret
= PATCH_FORMAT_MBOX
;
597 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
598 ret
= PATCH_FORMAT_STGIT_SERIES
;
602 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
603 ret
= PATCH_FORMAT_HG
;
607 strbuf_getline(&l2
, fp
);
608 strbuf_getline(&l3
, fp
);
611 * If the second line is empty and the third is a From, Author or Date
612 * entry, this is likely an StGit patch.
614 if (l1
.len
&& !l2
.len
&&
615 (starts_with(l3
.buf
, "From:") ||
616 starts_with(l3
.buf
, "Author:") ||
617 starts_with(l3
.buf
, "Date:"))) {
618 ret
= PATCH_FORMAT_STGIT
;
622 if (l1
.len
&& is_mail(fp
)) {
623 ret
= PATCH_FORMAT_MBOX
;
636 * Splits out individual email patches from `paths`, where each path is either
637 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
639 static int split_mail_mbox(struct am_state
*state
, const char **paths
,
640 int keep_cr
, int mboxrd
)
642 struct child_process cp
= CHILD_PROCESS_INIT
;
643 struct strbuf last
= STRBUF_INIT
;
647 argv_array_push(&cp
.args
, "mailsplit");
648 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
649 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
650 argv_array_push(&cp
.args
, "-b");
652 argv_array_push(&cp
.args
, "--keep-cr");
654 argv_array_push(&cp
.args
, "--mboxrd");
655 argv_array_push(&cp
.args
, "--");
656 argv_array_pushv(&cp
.args
, paths
);
658 ret
= capture_command(&cp
, &last
, 8);
663 state
->last
= strtol(last
.buf
, NULL
, 10);
666 strbuf_release(&last
);
671 * Callback signature for split_mail_conv(). The foreign patch should be
672 * read from `in`, and the converted patch (in RFC2822 mail format) should be
673 * written to `out`. Return 0 on success, or -1 on failure.
675 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
678 * Calls `fn` for each file in `paths` to convert the foreign patch to the
679 * RFC2822 mail format suitable for parsing with git-mailinfo.
681 * Returns 0 on success, -1 on failure.
683 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
684 const char **paths
, int keep_cr
)
686 static const char *stdin_only
[] = {"-", NULL
};
692 for (i
= 0; *paths
; paths
++, i
++) {
697 if (!strcmp(*paths
, "-"))
700 in
= fopen(*paths
, "r");
703 return error_errno(_("could not open '%s' for reading"),
706 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
708 out
= fopen(mail
, "w");
712 return error_errno(_("could not open '%s' for writing"),
716 ret
= fn(out
, in
, keep_cr
);
723 return error(_("could not parse patch '%s'"), *paths
);
732 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
733 * message suitable for parsing with git-mailinfo.
735 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
737 struct strbuf sb
= STRBUF_INIT
;
738 int subject_printed
= 0;
740 while (!strbuf_getline_lf(&sb
, in
)) {
743 if (str_isspace(sb
.buf
))
745 else if (skip_prefix(sb
.buf
, "Author:", &str
))
746 fprintf(out
, "From:%s\n", str
);
747 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
748 fprintf(out
, "%s\n", sb
.buf
);
749 else if (!subject_printed
) {
750 fprintf(out
, "Subject: %s\n", sb
.buf
);
753 fprintf(out
, "\n%s\n", sb
.buf
);
759 while (strbuf_fread(&sb
, 8192, in
) > 0) {
760 fwrite(sb
.buf
, 1, sb
.len
, out
);
769 * This function only supports a single StGit series file in `paths`.
771 * Given an StGit series file, converts the StGit patches in the series into
772 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
773 * the state directory.
775 * Returns 0 on success, -1 on failure.
777 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
780 const char *series_dir
;
781 char *series_dir_buf
;
783 struct argv_array patches
= ARGV_ARRAY_INIT
;
784 struct strbuf sb
= STRBUF_INIT
;
787 if (!paths
[0] || paths
[1])
788 return error(_("Only one StGIT patch series can be applied at once"));
790 series_dir_buf
= xstrdup(*paths
);
791 series_dir
= dirname(series_dir_buf
);
793 fp
= fopen(*paths
, "r");
795 return error_errno(_("could not open '%s' for reading"), *paths
);
797 while (!strbuf_getline_lf(&sb
, fp
)) {
799 continue; /* skip comment lines */
801 argv_array_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
806 free(series_dir_buf
);
808 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.argv
, keep_cr
);
810 argv_array_clear(&patches
);
815 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
816 * message suitable for parsing with git-mailinfo.
818 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
820 struct strbuf sb
= STRBUF_INIT
;
823 while (!strbuf_getline_lf(&sb
, in
)) {
826 if (skip_prefix(sb
.buf
, "# User ", &str
))
827 fprintf(out
, "From: %s\n", str
);
828 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
829 timestamp_t timestamp
;
834 timestamp
= parse_timestamp(str
, &end
, 10);
836 rc
= error(_("invalid timestamp"));
840 if (!skip_prefix(end
, " ", &str
)) {
841 rc
= error(_("invalid Date line"));
846 tz
= strtol(str
, &end
, 10);
848 rc
= error(_("invalid timezone offset"));
853 rc
= error(_("invalid Date line"));
858 * mercurial's timezone is in seconds west of UTC,
859 * however git's timezone is in hours + minutes east of
862 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
866 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
867 } else if (starts_with(sb
.buf
, "# ")) {
870 fprintf(out
, "\n%s\n", sb
.buf
);
876 while (strbuf_fread(&sb
, 8192, in
) > 0) {
877 fwrite(sb
.buf
, 1, sb
.len
, out
);
886 * Splits a list of files/directories into individual email patches. Each path
887 * in `paths` must be a file/directory that is formatted according to
890 * Once split out, the individual email patches will be stored in the state
891 * directory, with each patch's filename being its index, padded to state->prec
894 * state->cur will be set to the index of the first mail, and state->last will
895 * be set to the index of the last mail.
897 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
898 * to disable this behavior, -1 to use the default configured setting.
900 * Returns 0 on success, -1 on failure.
902 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
903 const char **paths
, int keep_cr
)
907 git_config_get_bool("am.keepcr", &keep_cr
);
910 switch (patch_format
) {
911 case PATCH_FORMAT_MBOX
:
912 return split_mail_mbox(state
, paths
, keep_cr
, 0);
913 case PATCH_FORMAT_STGIT
:
914 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
915 case PATCH_FORMAT_STGIT_SERIES
:
916 return split_mail_stgit_series(state
, paths
, keep_cr
);
917 case PATCH_FORMAT_HG
:
918 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
919 case PATCH_FORMAT_MBOXRD
:
920 return split_mail_mbox(state
, paths
, keep_cr
, 1);
922 BUG("invalid patch_format");
928 * Setup a new am session for applying patches
930 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
931 const char **paths
, int keep_cr
)
933 struct object_id curr_head
;
935 struct strbuf sb
= STRBUF_INIT
;
938 patch_format
= detect_patch_format(paths
);
941 fprintf_ln(stderr
, _("Patch format detection failed."));
945 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
946 die_errno(_("failed to create directory '%s'"), state
->dir
);
947 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
949 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
951 die(_("Failed to split patches."));
957 write_state_bool(state
, "threeway", state
->threeway
);
958 write_state_bool(state
, "quiet", state
->quiet
);
959 write_state_bool(state
, "sign", state
->signoff
);
960 write_state_bool(state
, "utf8", state
->utf8
);
962 if (state
->allow_rerere_autoupdate
)
963 write_state_bool(state
, "rerere-autoupdate",
964 state
->allow_rerere_autoupdate
== RERERE_AUTOUPDATE
);
966 switch (state
->keep
) {
977 BUG("invalid value for state->keep");
980 write_state_text(state
, "keep", str
);
981 write_state_bool(state
, "messageid", state
->message_id
);
983 switch (state
->scissors
) {
994 BUG("invalid value for state->scissors");
996 write_state_text(state
, "scissors", str
);
998 sq_quote_argv(&sb
, state
->git_apply_opts
.argv
);
999 write_state_text(state
, "apply-opt", sb
.buf
);
1001 if (state
->rebasing
)
1002 write_state_text(state
, "rebasing", "");
1004 write_state_text(state
, "applying", "");
1006 if (!get_oid("HEAD", &curr_head
)) {
1007 write_state_text(state
, "abort-safety", oid_to_hex(&curr_head
));
1008 if (!state
->rebasing
)
1009 update_ref("am", "ORIG_HEAD", &curr_head
, NULL
, 0,
1010 UPDATE_REFS_DIE_ON_ERR
);
1012 write_state_text(state
, "abort-safety", "");
1013 if (!state
->rebasing
)
1014 delete_ref(NULL
, "ORIG_HEAD", NULL
, 0);
1018 * NOTE: Since the "next" and "last" files determine if an am_state
1019 * session is in progress, they should be written last.
1022 write_state_count(state
, "next", state
->cur
);
1023 write_state_count(state
, "last", state
->last
);
1025 strbuf_release(&sb
);
1029 * Increments the patch pointer, and cleans am_state for the application of the
1032 static void am_next(struct am_state
*state
)
1034 struct object_id head
;
1036 FREE_AND_NULL(state
->author_name
);
1037 FREE_AND_NULL(state
->author_email
);
1038 FREE_AND_NULL(state
->author_date
);
1039 FREE_AND_NULL(state
->msg
);
1042 unlink(am_path(state
, "author-script"));
1043 unlink(am_path(state
, "final-commit"));
1045 oidclr(&state
->orig_commit
);
1046 unlink(am_path(state
, "original-commit"));
1047 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
1049 if (!get_oid("HEAD", &head
))
1050 write_state_text(state
, "abort-safety", oid_to_hex(&head
));
1052 write_state_text(state
, "abort-safety", "");
1055 write_state_count(state
, "next", state
->cur
);
1059 * Returns the filename of the current patch email.
1061 static const char *msgnum(const struct am_state
*state
)
1063 static struct strbuf sb
= STRBUF_INIT
;
1066 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1072 * Refresh and write index.
1074 static void refresh_and_write_cache(void)
1076 struct lock_file lock_file
= LOCK_INIT
;
1078 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1079 refresh_cache(REFRESH_QUIET
);
1080 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1081 die(_("unable to write index file"));
1085 * Dies with a user-friendly message on how to proceed after resolving the
1086 * problem. This message can be overridden with state->resolvemsg.
1088 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1090 if (state
->resolvemsg
) {
1091 printf_ln("%s", state
->resolvemsg
);
1093 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1095 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1096 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1097 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1104 * Appends signoff to the "msg" field of the am_state.
1106 static void am_append_signoff(struct am_state
*state
)
1108 struct strbuf sb
= STRBUF_INIT
;
1110 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1111 append_signoff(&sb
, 0, 0);
1112 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1116 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1117 * state->msg will be set to the patch message. state->author_name,
1118 * state->author_email and state->author_date will be set to the patch author's
1119 * name, email and date respectively. The patch body will be written to the
1120 * state directory's "patch" file.
1122 * Returns 1 if the patch should be skipped, 0 otherwise.
1124 static int parse_mail(struct am_state
*state
, const char *mail
)
1127 struct strbuf sb
= STRBUF_INIT
;
1128 struct strbuf msg
= STRBUF_INIT
;
1129 struct strbuf author_name
= STRBUF_INIT
;
1130 struct strbuf author_date
= STRBUF_INIT
;
1131 struct strbuf author_email
= STRBUF_INIT
;
1135 setup_mailinfo(&mi
);
1138 mi
.metainfo_charset
= get_commit_output_encoding();
1140 mi
.metainfo_charset
= NULL
;
1142 switch (state
->keep
) {
1146 mi
.keep_subject
= 1;
1148 case KEEP_NON_PATCH
:
1149 mi
.keep_non_patch_brackets_in_subject
= 1;
1152 BUG("invalid value for state->keep");
1155 if (state
->message_id
)
1156 mi
.add_message_id
= 1;
1158 switch (state
->scissors
) {
1159 case SCISSORS_UNSET
:
1161 case SCISSORS_FALSE
:
1162 mi
.use_scissors
= 0;
1165 mi
.use_scissors
= 1;
1168 BUG("invalid value for state->scissors");
1171 mi
.input
= xfopen(mail
, "r");
1172 mi
.output
= xfopen(am_path(state
, "info"), "w");
1173 if (mailinfo(&mi
, am_path(state
, "msg"), am_path(state
, "patch")))
1174 die("could not parse patch");
1179 if (mi
.format_flowed
)
1180 warning(_("Patch sent with format=flowed; "
1181 "space at the end of lines might be lost."));
1183 /* Extract message and author information */
1184 fp
= xfopen(am_path(state
, "info"), "r");
1185 while (!strbuf_getline_lf(&sb
, fp
)) {
1188 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1190 strbuf_addch(&msg
, '\n');
1191 strbuf_addstr(&msg
, x
);
1192 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1193 strbuf_addstr(&author_name
, x
);
1194 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1195 strbuf_addstr(&author_email
, x
);
1196 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1197 strbuf_addstr(&author_date
, x
);
1201 /* Skip pine's internal folder data */
1202 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1207 if (is_empty_or_missing_file(am_path(state
, "patch"))) {
1208 printf_ln(_("Patch is empty."));
1209 die_user_resolve(state
);
1212 strbuf_addstr(&msg
, "\n\n");
1213 strbuf_addbuf(&msg
, &mi
.log_message
);
1214 strbuf_stripspace(&msg
, 0);
1216 assert(!state
->author_name
);
1217 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1219 assert(!state
->author_email
);
1220 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1222 assert(!state
->author_date
);
1223 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1225 assert(!state
->msg
);
1226 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1229 strbuf_release(&msg
);
1230 strbuf_release(&author_date
);
1231 strbuf_release(&author_email
);
1232 strbuf_release(&author_name
);
1233 strbuf_release(&sb
);
1234 clear_mailinfo(&mi
);
1239 * Sets commit_id to the commit hash where the mail was generated from.
1240 * Returns 0 on success, -1 on failure.
1242 static int get_mail_commit_oid(struct object_id
*commit_id
, const char *mail
)
1244 struct strbuf sb
= STRBUF_INIT
;
1245 FILE *fp
= xfopen(mail
, "r");
1249 if (strbuf_getline_lf(&sb
, fp
) ||
1250 !skip_prefix(sb
.buf
, "From ", &x
) ||
1251 get_oid_hex(x
, commit_id
) < 0)
1254 strbuf_release(&sb
);
1260 * Sets state->msg, state->author_name, state->author_email, state->author_date
1261 * to the commit's respective info.
1263 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1265 const char *buffer
, *ident_line
, *msg
;
1267 struct ident_split id
;
1269 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1271 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1273 if (split_ident_line(&id
, ident_line
, ident_len
) < 0)
1274 die(_("invalid ident line: %.*s"), (int)ident_len
, ident_line
);
1276 assert(!state
->author_name
);
1278 state
->author_name
=
1279 xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1281 state
->author_name
= xstrdup("");
1283 assert(!state
->author_email
);
1285 state
->author_email
=
1286 xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1288 state
->author_email
= xstrdup("");
1290 assert(!state
->author_date
);
1291 state
->author_date
= xstrdup(show_ident_date(&id
, DATE_MODE(NORMAL
)));
1293 assert(!state
->msg
);
1294 msg
= strstr(buffer
, "\n\n");
1296 die(_("unable to parse commit %s"), oid_to_hex(&commit
->object
.oid
));
1297 state
->msg
= xstrdup(msg
+ 2);
1298 state
->msg_len
= strlen(state
->msg
);
1299 unuse_commit_buffer(commit
, buffer
);
1303 * Writes `commit` as a patch to the state directory's "patch" file.
1305 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1307 struct rev_info rev_info
;
1310 fp
= xfopen(am_path(state
, "patch"), "w");
1311 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1313 rev_info
.abbrev
= 0;
1314 rev_info
.disable_stdin
= 1;
1315 rev_info
.show_root_diff
= 1;
1316 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1317 rev_info
.no_commit_id
= 1;
1318 rev_info
.diffopt
.flags
.binary
= 1;
1319 rev_info
.diffopt
.flags
.full_index
= 1;
1320 rev_info
.diffopt
.use_color
= 0;
1321 rev_info
.diffopt
.file
= fp
;
1322 rev_info
.diffopt
.close_file
= 1;
1323 add_pending_object(&rev_info
, &commit
->object
, "");
1324 diff_setup_done(&rev_info
.diffopt
);
1325 log_tree_commit(&rev_info
, commit
);
1329 * Writes the diff of the index against HEAD as a patch to the state
1330 * directory's "patch" file.
1332 static void write_index_patch(const struct am_state
*state
)
1335 struct object_id head
;
1336 struct rev_info rev_info
;
1339 if (!get_oid_tree("HEAD", &head
))
1340 tree
= lookup_tree(the_repository
, &head
);
1342 tree
= lookup_tree(the_repository
,
1343 the_repository
->hash_algo
->empty_tree
);
1345 fp
= xfopen(am_path(state
, "patch"), "w");
1346 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1348 rev_info
.disable_stdin
= 1;
1349 rev_info
.no_commit_id
= 1;
1350 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1351 rev_info
.diffopt
.use_color
= 0;
1352 rev_info
.diffopt
.file
= fp
;
1353 rev_info
.diffopt
.close_file
= 1;
1354 add_pending_object(&rev_info
, &tree
->object
, "");
1355 diff_setup_done(&rev_info
.diffopt
);
1356 run_diff_index(&rev_info
, 1);
1360 * Like parse_mail(), but parses the mail by looking up its commit ID
1361 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1364 * state->orig_commit will be set to the original commit ID.
1366 * Will always return 0 as the patch should never be skipped.
1368 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1370 struct commit
*commit
;
1371 struct object_id commit_oid
;
1373 if (get_mail_commit_oid(&commit_oid
, mail
) < 0)
1374 die(_("could not parse %s"), mail
);
1376 commit
= lookup_commit_or_die(&commit_oid
, mail
);
1378 get_commit_info(state
, commit
);
1380 write_commit_patch(state
, commit
);
1382 oidcpy(&state
->orig_commit
, &commit_oid
);
1383 write_state_text(state
, "original-commit", oid_to_hex(&commit_oid
));
1384 update_ref("am", "REBASE_HEAD", &commit_oid
,
1385 NULL
, REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1391 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1392 * `index_file` is not NULL, the patch will be applied to that index.
1394 static int run_apply(const struct am_state
*state
, const char *index_file
)
1396 struct argv_array apply_paths
= ARGV_ARRAY_INIT
;
1397 struct argv_array apply_opts
= ARGV_ARRAY_INIT
;
1398 struct apply_state apply_state
;
1400 int force_apply
= 0;
1403 if (init_apply_state(&apply_state
, the_repository
, NULL
))
1404 BUG("init_apply_state() failed");
1406 argv_array_push(&apply_opts
, "apply");
1407 argv_array_pushv(&apply_opts
, state
->git_apply_opts
.argv
);
1409 opts_left
= apply_parse_options(apply_opts
.argc
, apply_opts
.argv
,
1410 &apply_state
, &force_apply
, &options
,
1414 die("unknown option passed through to git apply");
1417 apply_state
.index_file
= index_file
;
1418 apply_state
.cached
= 1;
1420 apply_state
.check_index
= 1;
1423 * If we are allowed to fall back on 3-way merge, don't give false
1424 * errors during the initial attempt.
1426 if (state
->threeway
&& !index_file
)
1427 apply_state
.apply_verbosity
= verbosity_silent
;
1429 if (check_apply_state(&apply_state
, force_apply
))
1430 BUG("check_apply_state() failed");
1432 argv_array_push(&apply_paths
, am_path(state
, "patch"));
1434 res
= apply_all_patches(&apply_state
, apply_paths
.argc
, apply_paths
.argv
, options
);
1436 argv_array_clear(&apply_paths
);
1437 argv_array_clear(&apply_opts
);
1438 clear_apply_state(&apply_state
);
1444 /* Reload index as apply_all_patches() will have modified it. */
1446 read_cache_from(index_file
);
1453 * Builds an index that contains just the blobs needed for a 3way merge.
1455 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1457 struct child_process cp
= CHILD_PROCESS_INIT
;
1460 argv_array_push(&cp
.args
, "apply");
1461 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1462 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1463 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1465 if (run_command(&cp
))
1472 * Attempt a threeway merge, using index_path as the temporary index.
1474 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1476 struct object_id orig_tree
, their_tree
, our_tree
;
1477 const struct object_id
*bases
[1] = { &orig_tree
};
1478 struct merge_options o
;
1479 struct commit
*result
;
1480 char *their_tree_name
;
1482 if (get_oid("HEAD", &our_tree
) < 0)
1483 oidcpy(&our_tree
, the_hash_algo
->empty_tree
);
1485 if (build_fake_ancestor(state
, index_path
))
1486 return error("could not build fake ancestor");
1489 read_cache_from(index_path
);
1491 if (write_index_as_tree(&orig_tree
, &the_index
, index_path
, 0, NULL
))
1492 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1494 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1496 if (!state
->quiet
) {
1498 * List paths that needed 3-way fallback, so that the user can
1499 * review them with extra care to spot mismerges.
1501 struct rev_info rev_info
;
1502 const char *diff_filter_str
= "--diff-filter=AM";
1504 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1505 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1506 diff_opt_parse(&rev_info
.diffopt
, &diff_filter_str
, 1, rev_info
.prefix
);
1507 add_pending_oid(&rev_info
, "HEAD", &our_tree
, 0);
1508 diff_setup_done(&rev_info
.diffopt
);
1509 run_diff_index(&rev_info
, 1);
1512 if (run_apply(state
, index_path
))
1513 return error(_("Did you hand edit your patch?\n"
1514 "It does not apply to blobs recorded in its index."));
1516 if (write_index_as_tree(&their_tree
, &the_index
, index_path
, 0, NULL
))
1517 return error("could not write tree");
1519 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1525 * This is not so wrong. Depending on which base we picked, orig_tree
1526 * may be wildly different from ours, but their_tree has the same set of
1527 * wildly different changes in parts the patch did not touch, so
1528 * recursive ends up canceling them, saying that we reverted all those
1532 init_merge_options(&o
);
1535 their_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1536 o
.branch2
= their_tree_name
;
1537 o
.detect_directory_renames
= 0;
1542 if (merge_recursive_generic(&o
, &our_tree
, &their_tree
, 1, bases
, &result
)) {
1543 repo_rerere(the_repository
, state
->allow_rerere_autoupdate
);
1544 free(their_tree_name
);
1545 return error(_("Failed to merge in the changes."));
1548 free(their_tree_name
);
1553 * Commits the current index with state->msg as the commit message and
1554 * state->author_name, state->author_email and state->author_date as the author
1557 static void do_commit(const struct am_state
*state
)
1559 struct object_id tree
, parent
, commit
;
1560 const struct object_id
*old_oid
;
1561 struct commit_list
*parents
= NULL
;
1562 const char *reflog_msg
, *author
;
1563 struct strbuf sb
= STRBUF_INIT
;
1565 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1568 if (write_cache_as_tree(&tree
, 0, NULL
))
1569 die(_("git write-tree failed to write a tree"));
1571 if (!get_oid_commit("HEAD", &parent
)) {
1573 commit_list_insert(lookup_commit(the_repository
, &parent
),
1577 say(state
, stderr
, _("applying to an empty history"));
1580 author
= fmt_ident(state
->author_name
, state
->author_email
,
1581 state
->ignore_date
? NULL
: state
->author_date
,
1584 if (state
->committer_date_is_author_date
)
1585 setenv("GIT_COMMITTER_DATE",
1586 state
->ignore_date
? "" : state
->author_date
, 1);
1588 if (commit_tree(state
->msg
, state
->msg_len
, &tree
, parents
, &commit
,
1589 author
, state
->sign_commit
))
1590 die(_("failed to write commit object"));
1592 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1596 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1599 update_ref(sb
.buf
, "HEAD", &commit
, old_oid
, 0,
1600 UPDATE_REFS_DIE_ON_ERR
);
1602 if (state
->rebasing
) {
1603 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1605 assert(!is_null_oid(&state
->orig_commit
));
1606 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
1607 fprintf(fp
, "%s\n", oid_to_hex(&commit
));
1611 run_hook_le(NULL
, "post-applypatch", NULL
);
1613 strbuf_release(&sb
);
1617 * Validates the am_state for resuming -- the "msg" and authorship fields must
1620 static void validate_resume_state(const struct am_state
*state
)
1623 die(_("cannot resume: %s does not exist."),
1624 am_path(state
, "final-commit"));
1626 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1627 die(_("cannot resume: %s does not exist."),
1628 am_path(state
, "author-script"));
1632 * Interactively prompt the user on whether the current patch should be
1635 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1638 static int do_interactive(struct am_state
*state
)
1643 die(_("cannot be interactive without stdin connected to a terminal."));
1648 puts(_("Commit Body is:"));
1649 puts("--------------------------");
1650 printf("%s", state
->msg
);
1651 puts("--------------------------");
1654 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1655 * in your translation. The program will only accept English
1656 * input at this point.
1658 reply
= git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO
);
1662 } else if (*reply
== 'y' || *reply
== 'Y') {
1664 } else if (*reply
== 'a' || *reply
== 'A') {
1665 state
->interactive
= 0;
1667 } else if (*reply
== 'n' || *reply
== 'N') {
1669 } else if (*reply
== 'e' || *reply
== 'E') {
1670 struct strbuf msg
= STRBUF_INIT
;
1672 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1674 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1676 strbuf_release(&msg
);
1677 } else if (*reply
== 'v' || *reply
== 'V') {
1678 const char *pager
= git_pager(1);
1679 struct child_process cp
= CHILD_PROCESS_INIT
;
1683 prepare_pager_args(&cp
, pager
);
1684 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1691 * Applies all queued mail.
1693 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1694 * well as the state directory's "patch" file is used as-is for applying the
1695 * patch and committing it.
1697 static void am_run(struct am_state
*state
, int resume
)
1699 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1700 struct strbuf sb
= STRBUF_INIT
;
1702 unlink(am_path(state
, "dirtyindex"));
1704 refresh_and_write_cache();
1706 if (index_has_changes(&the_index
, NULL
, &sb
)) {
1707 write_state_bool(state
, "dirtyindex", 1);
1708 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1711 strbuf_release(&sb
);
1713 while (state
->cur
<= state
->last
) {
1714 const char *mail
= am_path(state
, msgnum(state
));
1719 if (!file_exists(mail
))
1723 validate_resume_state(state
);
1727 if (state
->rebasing
)
1728 skip
= parse_mail_rebase(state
, mail
);
1730 skip
= parse_mail(state
, mail
);
1733 goto next
; /* mail should be skipped */
1736 am_append_signoff(state
);
1738 write_author_script(state
);
1739 write_commit_msg(state
);
1742 if (state
->interactive
&& do_interactive(state
))
1745 if (run_applypatch_msg_hook(state
))
1748 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1750 apply_status
= run_apply(state
, NULL
);
1752 if (apply_status
&& state
->threeway
) {
1753 struct strbuf sb
= STRBUF_INIT
;
1755 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1756 apply_status
= fall_back_threeway(state
, sb
.buf
);
1757 strbuf_release(&sb
);
1760 * Applying the patch to an earlier tree and merging
1761 * the result may have produced the same tree as ours.
1763 if (!apply_status
&&
1764 !index_has_changes(&the_index
, NULL
, NULL
)) {
1765 say(state
, stdout
, _("No changes -- Patch already applied."));
1771 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1772 linelen(state
->msg
), state
->msg
);
1774 if (advice_amworkdir
)
1775 advise(_("Use 'git am --show-current-patch' to see the failed patch"));
1777 die_user_resolve(state
);
1790 if (!is_empty_or_missing_file(am_path(state
, "rewritten"))) {
1791 assert(state
->rebasing
);
1792 copy_notes_for_rebase(state
);
1793 run_post_rewrite_hook(state
);
1797 * In rebasing mode, it's up to the caller to take care of
1800 if (!state
->rebasing
) {
1802 close_all_packs(the_repository
->objects
);
1803 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1808 * Resume the current am session after patch application failure. The user did
1809 * all the hard work, and we do not have to do any patch application. Just
1810 * trust and commit what the user has in the index and working tree.
1812 static void am_resolve(struct am_state
*state
)
1814 validate_resume_state(state
);
1816 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1818 if (!index_has_changes(&the_index
, NULL
, NULL
)) {
1819 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1820 "If there is nothing left to stage, chances are that something else\n"
1821 "already introduced the same changes; you might want to skip this patch."));
1822 die_user_resolve(state
);
1825 if (unmerged_cache()) {
1826 printf_ln(_("You still have unmerged paths in your index.\n"
1827 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1828 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1829 die_user_resolve(state
);
1832 if (state
->interactive
) {
1833 write_index_patch(state
);
1834 if (do_interactive(state
))
1838 repo_rerere(the_repository
, 0);
1849 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1850 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1853 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1855 struct lock_file lock_file
= LOCK_INIT
;
1856 struct unpack_trees_options opts
;
1857 struct tree_desc t
[2];
1859 if (parse_tree(head
) || parse_tree(remote
))
1862 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1864 refresh_cache(REFRESH_QUIET
);
1866 memset(&opts
, 0, sizeof(opts
));
1868 opts
.src_index
= &the_index
;
1869 opts
.dst_index
= &the_index
;
1873 opts
.fn
= twoway_merge
;
1874 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1875 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1877 if (unpack_trees(2, t
, &opts
)) {
1878 rollback_lock_file(&lock_file
);
1882 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1883 die(_("unable to write new index file"));
1889 * Merges a tree into the index. The index's stat info will take precedence
1890 * over the merged tree's. Returns 0 on success, -1 on failure.
1892 static int merge_tree(struct tree
*tree
)
1894 struct lock_file lock_file
= LOCK_INIT
;
1895 struct unpack_trees_options opts
;
1896 struct tree_desc t
[1];
1898 if (parse_tree(tree
))
1901 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1903 memset(&opts
, 0, sizeof(opts
));
1905 opts
.src_index
= &the_index
;
1906 opts
.dst_index
= &the_index
;
1908 opts
.fn
= oneway_merge
;
1909 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
1911 if (unpack_trees(1, t
, &opts
)) {
1912 rollback_lock_file(&lock_file
);
1916 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1917 die(_("unable to write new index file"));
1923 * Clean the index without touching entries that are not modified between
1924 * `head` and `remote`.
1926 static int clean_index(const struct object_id
*head
, const struct object_id
*remote
)
1928 struct tree
*head_tree
, *remote_tree
, *index_tree
;
1929 struct object_id index
;
1931 head_tree
= parse_tree_indirect(head
);
1933 return error(_("Could not parse object '%s'."), oid_to_hex(head
));
1935 remote_tree
= parse_tree_indirect(remote
);
1937 return error(_("Could not parse object '%s'."), oid_to_hex(remote
));
1939 read_cache_unmerged();
1941 if (fast_forward_to(head_tree
, head_tree
, 1))
1944 if (write_cache_as_tree(&index
, 0, NULL
))
1947 index_tree
= parse_tree_indirect(&index
);
1949 return error(_("Could not parse object '%s'."), oid_to_hex(&index
));
1951 if (fast_forward_to(index_tree
, remote_tree
, 0))
1954 if (merge_tree(remote_tree
))
1957 remove_branch_state();
1963 * Resets rerere's merge resolution metadata.
1965 static void am_rerere_clear(void)
1967 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
1968 rerere_clear(&merge_rr
);
1969 string_list_clear(&merge_rr
, 1);
1973 * Resume the current am session by skipping the current patch.
1975 static void am_skip(struct am_state
*state
)
1977 struct object_id head
;
1981 if (get_oid("HEAD", &head
))
1982 oidcpy(&head
, the_hash_algo
->empty_tree
);
1984 if (clean_index(&head
, &head
))
1985 die(_("failed to clean index"));
1993 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1995 * It is not safe to reset HEAD when:
1996 * 1. git-am previously failed because the index was dirty.
1997 * 2. HEAD has moved since git-am previously failed.
1999 static int safe_to_abort(const struct am_state
*state
)
2001 struct strbuf sb
= STRBUF_INIT
;
2002 struct object_id abort_safety
, head
;
2004 if (file_exists(am_path(state
, "dirtyindex")))
2007 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2008 if (get_oid_hex(sb
.buf
, &abort_safety
))
2009 die(_("could not parse %s"), am_path(state
, "abort-safety"));
2011 oidclr(&abort_safety
);
2012 strbuf_release(&sb
);
2014 if (get_oid("HEAD", &head
))
2017 if (oideq(&head
, &abort_safety
))
2020 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2021 "Not rewinding to ORIG_HEAD"));
2027 * Aborts the current am session if it is safe to do so.
2029 static void am_abort(struct am_state
*state
)
2031 struct object_id curr_head
, orig_head
;
2032 int has_curr_head
, has_orig_head
;
2035 if (!safe_to_abort(state
)) {
2042 curr_branch
= resolve_refdup("HEAD", 0, &curr_head
, NULL
);
2043 has_curr_head
= curr_branch
&& !is_null_oid(&curr_head
);
2045 oidcpy(&curr_head
, the_hash_algo
->empty_tree
);
2047 has_orig_head
= !get_oid("ORIG_HEAD", &orig_head
);
2049 oidcpy(&orig_head
, the_hash_algo
->empty_tree
);
2051 clean_index(&curr_head
, &orig_head
);
2054 update_ref("am --abort", "HEAD", &orig_head
,
2055 has_curr_head
? &curr_head
: NULL
, 0,
2056 UPDATE_REFS_DIE_ON_ERR
);
2057 else if (curr_branch
)
2058 delete_ref(NULL
, curr_branch
, NULL
, REF_NO_DEREF
);
2064 static int show_patch(struct am_state
*state
)
2066 struct strbuf sb
= STRBUF_INIT
;
2067 const char *patch_path
;
2070 if (!is_null_oid(&state
->orig_commit
)) {
2071 const char *av
[4] = { "show", NULL
, "--", NULL
};
2075 av
[1] = new_oid_str
= xstrdup(oid_to_hex(&state
->orig_commit
));
2076 ret
= run_command_v_opt(av
, RUN_GIT_CMD
);
2081 patch_path
= am_path(state
, msgnum(state
));
2082 len
= strbuf_read_file(&sb
, patch_path
, 0);
2084 die_errno(_("failed to read '%s'"), patch_path
);
2087 write_in_full(1, sb
.buf
, sb
.len
);
2088 strbuf_release(&sb
);
2093 * parse_options() callback that validates and sets opt->value to the
2094 * PATCH_FORMAT_* enum value corresponding to `arg`.
2096 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2098 int *opt_value
= opt
->value
;
2101 *opt_value
= PATCH_FORMAT_UNKNOWN
;
2102 else if (!strcmp(arg
, "mbox"))
2103 *opt_value
= PATCH_FORMAT_MBOX
;
2104 else if (!strcmp(arg
, "stgit"))
2105 *opt_value
= PATCH_FORMAT_STGIT
;
2106 else if (!strcmp(arg
, "stgit-series"))
2107 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2108 else if (!strcmp(arg
, "hg"))
2109 *opt_value
= PATCH_FORMAT_HG
;
2110 else if (!strcmp(arg
, "mboxrd"))
2111 *opt_value
= PATCH_FORMAT_MBOXRD
;
2113 return error(_("Invalid value for --patch-format: %s"), arg
);
2127 static int git_am_config(const char *k
, const char *v
, void *cb
)
2131 status
= git_gpg_config(k
, v
, NULL
);
2135 return git_default_config(k
, v
, NULL
);
2138 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2140 struct am_state state
;
2143 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2144 enum resume_mode resume
= RESUME_FALSE
;
2148 const char * const usage
[] = {
2149 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2150 N_("git am [<options>] (--continue | --skip | --abort)"),
2154 struct option options
[] = {
2155 OPT_BOOL('i', "interactive", &state
.interactive
,
2156 N_("run interactively")),
2157 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2158 N_("historical option -- no-op")),
2159 OPT_BOOL('3', "3way", &state
.threeway
,
2160 N_("allow fall back on 3way merging if needed")),
2161 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2162 OPT_SET_INT('s', "signoff", &state
.signoff
,
2163 N_("add a Signed-off-by line to the commit message"),
2165 OPT_BOOL('u', "utf8", &state
.utf8
,
2166 N_("recode into utf8 (default)")),
2167 OPT_SET_INT('k', "keep", &state
.keep
,
2168 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2169 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2170 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2171 OPT_BOOL('m', "message-id", &state
.message_id
,
2172 N_("pass -m flag to git-mailinfo")),
2173 OPT_SET_INT_F(0, "keep-cr", &keep_cr
,
2174 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2175 1, PARSE_OPT_NONEG
),
2176 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr
,
2177 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2178 0, PARSE_OPT_NONEG
),
2179 OPT_BOOL('c', "scissors", &state
.scissors
,
2180 N_("strip everything before a scissors line")),
2181 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2182 N_("pass it through git-apply"),
2184 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2185 N_("pass it through git-apply"),
2187 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2188 N_("pass it through git-apply"),
2190 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2191 N_("pass it through git-apply"),
2193 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2194 N_("pass it through git-apply"),
2196 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2197 N_("pass it through git-apply"),
2199 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2200 N_("pass it through git-apply"),
2202 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2203 N_("pass it through git-apply"),
2205 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2206 N_("format the patch(es) are in"),
2207 parse_opt_patchformat
),
2208 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2209 N_("pass it through git-apply"),
2211 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2212 N_("override error message when patch failure occurs")),
2213 OPT_CMDMODE(0, "continue", &resume
,
2214 N_("continue applying patches after resolving a conflict"),
2216 OPT_CMDMODE('r', "resolved", &resume
,
2217 N_("synonyms for --continue"),
2219 OPT_CMDMODE(0, "skip", &resume
,
2220 N_("skip the current patch"),
2222 OPT_CMDMODE(0, "abort", &resume
,
2223 N_("restore the original branch and abort the patching operation."),
2225 OPT_CMDMODE(0, "quit", &resume
,
2226 N_("abort the patching operation but keep HEAD where it is."),
2228 OPT_CMDMODE(0, "show-current-patch", &resume
,
2229 N_("show the patch being applied."),
2231 OPT_BOOL(0, "committer-date-is-author-date",
2232 &state
.committer_date_is_author_date
,
2233 N_("lie about committer date")),
2234 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2235 N_("use current timestamp for author date")),
2236 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2237 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2238 N_("GPG-sign commits"),
2239 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2240 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2241 N_("(internal use for git-rebase)")),
2245 if (argc
== 2 && !strcmp(argv
[1], "-h"))
2246 usage_with_options(usage
, options
);
2248 git_config(git_am_config
, NULL
);
2250 am_state_init(&state
);
2252 in_progress
= am_in_progress(&state
);
2256 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2259 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2260 "it will be removed. Please do not use it anymore."));
2262 /* Ensure a valid committer ident can be constructed */
2263 git_committer_info(IDENT_STRICT
);
2265 if (read_index_preload(&the_index
, NULL
, 0) < 0)
2266 die(_("failed to read the index"));
2270 * Catch user error to feed us patches when there is a session
2273 * 1. mbox path(s) are provided on the command-line.
2274 * 2. stdin is not a tty: the user is trying to feed us a patch
2275 * from standard input. This is somewhat unreliable -- stdin
2276 * could be /dev/null for example and the caller did not
2277 * intend to feed us a patch but wanted to continue
2280 if (argc
|| (resume
== RESUME_FALSE
&& !isatty(0)))
2281 die(_("previous rebase directory %s still exists but mbox given."),
2284 if (resume
== RESUME_FALSE
)
2285 resume
= RESUME_APPLY
;
2287 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2288 am_append_signoff(&state
);
2290 struct argv_array paths
= ARGV_ARRAY_INIT
;
2294 * Handle stray state directory in the independent-run case. In
2295 * the --rebasing case, it is up to the caller to take care of
2296 * stray directories.
2298 if (file_exists(state
.dir
) && !state
.rebasing
) {
2299 if (resume
== RESUME_ABORT
|| resume
== RESUME_QUIT
) {
2301 am_state_release(&state
);
2305 die(_("Stray %s directory found.\n"
2306 "Use \"git am --abort\" to remove it."),
2311 die(_("Resolve operation not in progress, we are not resuming."));
2313 for (i
= 0; i
< argc
; i
++) {
2314 if (is_absolute_path(argv
[i
]) || !prefix
)
2315 argv_array_push(&paths
, argv
[i
]);
2317 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2320 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
2322 argv_array_clear(&paths
);
2332 case RESUME_RESOLVED
:
2345 case RESUME_SHOW_PATCH
:
2346 ret
= show_patch(&state
);
2349 BUG("invalid resume value");
2352 am_state_release(&state
);