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 */
104 /* when --rebasing, records the original commit the patch came from */
105 struct object_id orig_commit
;
107 /* number of digits in patch filename */
110 /* various operating modes and command line options */
114 int signoff
; /* enum signoff_type */
116 int keep
; /* enum keep_type */
118 int scissors
; /* enum scissors_type */
119 int quoted_cr
; /* enum quoted_cr_action */
120 struct strvec git_apply_opts
;
121 const char *resolvemsg
;
122 int committer_date_is_author_date
;
124 int allow_rerere_autoupdate
;
125 const char *sign_commit
;
130 * Initializes am_state with the default values.
132 static void am_state_init(struct am_state
*state
)
136 memset(state
, 0, sizeof(*state
));
138 state
->dir
= git_pathdup("rebase-apply");
142 git_config_get_bool("am.threeway", &state
->threeway
);
146 git_config_get_bool("am.messageid", &state
->message_id
);
148 state
->scissors
= SCISSORS_UNSET
;
149 state
->quoted_cr
= quoted_cr_unset
;
151 strvec_init(&state
->git_apply_opts
);
153 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
154 state
->sign_commit
= gpgsign
? "" : NULL
;
158 * Releases memory allocated by an am_state.
160 static void am_state_release(struct am_state
*state
)
163 free(state
->author_name
);
164 free(state
->author_email
);
165 free(state
->author_date
);
167 strvec_clear(&state
->git_apply_opts
);
170 static int am_option_parse_quoted_cr(const struct option
*opt
,
171 const char *arg
, int unset
)
173 BUG_ON_OPT_NEG(unset
);
175 if (mailinfo_parse_quoted_cr_action(arg
, opt
->value
) != 0)
176 return error(_("bad action '%s' for '%s'"), arg
, "--quoted-cr");
181 * Returns path relative to the am_state directory.
183 static inline const char *am_path(const struct am_state
*state
, const char *path
)
185 return mkpath("%s/%s", state
->dir
, path
);
189 * For convenience to call write_file()
191 static void write_state_text(const struct am_state
*state
,
192 const char *name
, const char *string
)
194 write_file(am_path(state
, name
), "%s", string
);
197 static void write_state_count(const struct am_state
*state
,
198 const char *name
, int value
)
200 write_file(am_path(state
, name
), "%d", value
);
203 static void write_state_bool(const struct am_state
*state
,
204 const char *name
, int value
)
206 write_state_text(state
, name
, value
? "t" : "f");
210 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
213 __attribute__((format (printf
, 3, 4)))
214 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
220 vfprintf(fp
, fmt
, ap
);
227 * Returns 1 if there is an am session in progress, 0 otherwise.
229 static int am_in_progress(const struct am_state
*state
)
233 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
235 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
237 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
243 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
244 * number of bytes read on success, -1 if the file does not exist. If `trim` is
245 * set, trailing whitespace will be removed.
247 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
248 const char *file
, int trim
)
252 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
262 die_errno(_("could not read '%s'"), am_path(state
, file
));
266 * Reads and parses the state directory's "author-script" file, and sets
267 * state->author_name, state->author_email and state->author_date accordingly.
268 * Returns 0 on success, -1 if the file could not be parsed.
270 * The author script is of the format:
272 * GIT_AUTHOR_NAME='$author_name'
273 * GIT_AUTHOR_EMAIL='$author_email'
274 * GIT_AUTHOR_DATE='$author_date'
276 * where $author_name, $author_email and $author_date are quoted. We are strict
277 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
278 * script, and thus if the file differs from what this function expects, it is
279 * better to bail out than to do something that the user does not expect.
281 static int read_am_author_script(struct am_state
*state
)
283 const char *filename
= am_path(state
, "author-script");
285 assert(!state
->author_name
);
286 assert(!state
->author_email
);
287 assert(!state
->author_date
);
289 return read_author_script(filename
, &state
->author_name
,
290 &state
->author_email
, &state
->author_date
, 1);
294 * Saves state->author_name, state->author_email and state->author_date in the
295 * state directory's "author-script" file.
297 static void write_author_script(const struct am_state
*state
)
299 struct strbuf sb
= STRBUF_INIT
;
301 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
302 sq_quote_buf(&sb
, state
->author_name
);
303 strbuf_addch(&sb
, '\n');
305 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
306 sq_quote_buf(&sb
, state
->author_email
);
307 strbuf_addch(&sb
, '\n');
309 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
310 sq_quote_buf(&sb
, state
->author_date
);
311 strbuf_addch(&sb
, '\n');
313 write_state_text(state
, "author-script", sb
.buf
);
319 * Reads the commit message from the state directory's "final-commit" file,
320 * setting state->msg to its contents and state->msg_len to the length of its
323 * Returns 0 on success, -1 if the file does not exist.
325 static int read_commit_msg(struct am_state
*state
)
327 struct strbuf sb
= STRBUF_INIT
;
331 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
336 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
341 * Saves state->msg in the state directory's "final-commit" file.
343 static void write_commit_msg(const struct am_state
*state
)
345 const char *filename
= am_path(state
, "final-commit");
346 write_file_buf(filename
, state
->msg
, state
->msg_len
);
350 * Loads state from disk.
352 static void am_load(struct am_state
*state
)
354 struct strbuf sb
= STRBUF_INIT
;
356 if (read_state_file(&sb
, state
, "next", 1) < 0)
357 BUG("state file 'next' does not exist");
358 state
->cur
= strtol(sb
.buf
, NULL
, 10);
360 if (read_state_file(&sb
, state
, "last", 1) < 0)
361 BUG("state file 'last' does not exist");
362 state
->last
= strtol(sb
.buf
, NULL
, 10);
364 if (read_am_author_script(state
) < 0)
365 die(_("could not parse author script"));
367 read_commit_msg(state
);
369 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
370 oidclr(&state
->orig_commit
);
371 else if (get_oid_hex(sb
.buf
, &state
->orig_commit
) < 0)
372 die(_("could not parse %s"), am_path(state
, "original-commit"));
374 read_state_file(&sb
, state
, "threeway", 1);
375 state
->threeway
= !strcmp(sb
.buf
, "t");
377 read_state_file(&sb
, state
, "quiet", 1);
378 state
->quiet
= !strcmp(sb
.buf
, "t");
380 read_state_file(&sb
, state
, "sign", 1);
381 state
->signoff
= !strcmp(sb
.buf
, "t");
383 read_state_file(&sb
, state
, "utf8", 1);
384 state
->utf8
= !strcmp(sb
.buf
, "t");
386 if (file_exists(am_path(state
, "rerere-autoupdate"))) {
387 read_state_file(&sb
, state
, "rerere-autoupdate", 1);
388 state
->allow_rerere_autoupdate
= strcmp(sb
.buf
, "t") ?
389 RERERE_NOAUTOUPDATE
: RERERE_AUTOUPDATE
;
391 state
->allow_rerere_autoupdate
= 0;
394 read_state_file(&sb
, state
, "keep", 1);
395 if (!strcmp(sb
.buf
, "t"))
396 state
->keep
= KEEP_TRUE
;
397 else if (!strcmp(sb
.buf
, "b"))
398 state
->keep
= KEEP_NON_PATCH
;
400 state
->keep
= KEEP_FALSE
;
402 read_state_file(&sb
, state
, "messageid", 1);
403 state
->message_id
= !strcmp(sb
.buf
, "t");
405 read_state_file(&sb
, state
, "scissors", 1);
406 if (!strcmp(sb
.buf
, "t"))
407 state
->scissors
= SCISSORS_TRUE
;
408 else if (!strcmp(sb
.buf
, "f"))
409 state
->scissors
= SCISSORS_FALSE
;
411 state
->scissors
= SCISSORS_UNSET
;
413 read_state_file(&sb
, state
, "quoted-cr", 1);
415 state
->quoted_cr
= quoted_cr_unset
;
416 else if (mailinfo_parse_quoted_cr_action(sb
.buf
, &state
->quoted_cr
) != 0)
417 die(_("could not parse %s"), am_path(state
, "quoted-cr"));
419 read_state_file(&sb
, state
, "apply-opt", 1);
420 strvec_clear(&state
->git_apply_opts
);
421 if (sq_dequote_to_strvec(sb
.buf
, &state
->git_apply_opts
) < 0)
422 die(_("could not parse %s"), am_path(state
, "apply-opt"));
424 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
430 * Removes the am_state directory, forcefully terminating the current am
433 static void am_destroy(const struct am_state
*state
)
435 struct strbuf sb
= STRBUF_INIT
;
437 strbuf_addstr(&sb
, state
->dir
);
438 remove_dir_recursively(&sb
, 0);
443 * Runs applypatch-msg hook. Returns its exit code.
445 static int run_applypatch_msg_hook(struct am_state
*state
)
450 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
453 FREE_AND_NULL(state
->msg
);
454 if (read_commit_msg(state
) < 0)
455 die(_("'%s' was deleted by the applypatch-msg hook"),
456 am_path(state
, "final-commit"));
463 * Runs post-rewrite hook. Returns it exit code.
465 static int run_post_rewrite_hook(const struct am_state
*state
)
467 struct child_process cp
= CHILD_PROCESS_INIT
;
468 const char *hook
= find_hook("post-rewrite");
474 strvec_push(&cp
.args
, hook
);
475 strvec_push(&cp
.args
, "rebase");
477 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
478 cp
.stdout_to_stderr
= 1;
479 cp
.trace2_hook_name
= "post-rewrite";
481 ret
= run_command(&cp
);
488 * Reads the state directory's "rewritten" file, and copies notes from the old
489 * commits listed in the file to their rewritten commits.
491 * Returns 0 on success, -1 on failure.
493 static int copy_notes_for_rebase(const struct am_state
*state
)
495 struct notes_rewrite_cfg
*c
;
496 struct strbuf sb
= STRBUF_INIT
;
497 const char *invalid_line
= _("Malformed input line: '%s'.");
498 const char *msg
= "Notes added by 'git rebase'";
502 assert(state
->rebasing
);
504 c
= init_copy_notes_for_rewrite("rebase");
508 fp
= xfopen(am_path(state
, "rewritten"), "r");
510 while (!strbuf_getline_lf(&sb
, fp
)) {
511 struct object_id from_obj
, to_obj
;
514 if (sb
.len
!= the_hash_algo
->hexsz
* 2 + 1) {
515 ret
= error(invalid_line
, sb
.buf
);
519 if (parse_oid_hex(sb
.buf
, &from_obj
, &p
)) {
520 ret
= error(invalid_line
, sb
.buf
);
525 ret
= error(invalid_line
, sb
.buf
);
529 if (get_oid_hex(p
+ 1, &to_obj
)) {
530 ret
= error(invalid_line
, sb
.buf
);
534 if (copy_note_for_rewrite(c
, &from_obj
, &to_obj
))
535 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
536 oid_to_hex(&from_obj
), oid_to_hex(&to_obj
));
540 finish_copy_notes_for_rewrite(the_repository
, c
, msg
);
547 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
548 * non-indented lines and checking if they look like they begin with valid
549 * header field names.
551 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
553 static int is_mail(FILE *fp
)
555 const char *header_regex
= "^[!-9;-~]+:";
556 struct strbuf sb
= STRBUF_INIT
;
560 if (fseek(fp
, 0L, SEEK_SET
))
561 die_errno(_("fseek failed"));
563 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
564 die("invalid pattern: %s", header_regex
);
566 while (!strbuf_getline(&sb
, fp
)) {
568 break; /* End of header */
570 /* Ignore indented folded lines */
571 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
574 /* It's a header if it matches header_regex */
575 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
588 * Attempts to detect the patch_format of the patches contained in `paths`,
589 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
592 static int detect_patch_format(const char **paths
)
594 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
595 struct strbuf l1
= STRBUF_INIT
;
596 struct strbuf l2
= STRBUF_INIT
;
597 struct strbuf l3
= STRBUF_INIT
;
601 * We default to mbox format if input is from stdin and for directories
603 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
604 return PATCH_FORMAT_MBOX
;
607 * Otherwise, check the first few lines of the first patch, starting
608 * from the first non-blank line, to try to detect its format.
611 fp
= xfopen(*paths
, "r");
613 while (!strbuf_getline(&l1
, fp
)) {
618 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
619 ret
= PATCH_FORMAT_MBOX
;
623 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
624 ret
= PATCH_FORMAT_STGIT_SERIES
;
628 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
629 ret
= PATCH_FORMAT_HG
;
633 strbuf_getline(&l2
, fp
);
634 strbuf_getline(&l3
, fp
);
637 * If the second line is empty and the third is a From, Author or Date
638 * entry, this is likely an StGit patch.
640 if (l1
.len
&& !l2
.len
&&
641 (starts_with(l3
.buf
, "From:") ||
642 starts_with(l3
.buf
, "Author:") ||
643 starts_with(l3
.buf
, "Date:"))) {
644 ret
= PATCH_FORMAT_STGIT
;
648 if (l1
.len
&& is_mail(fp
)) {
649 ret
= PATCH_FORMAT_MBOX
;
662 * Splits out individual email patches from `paths`, where each path is either
663 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
665 static int split_mail_mbox(struct am_state
*state
, const char **paths
,
666 int keep_cr
, int mboxrd
)
668 struct child_process cp
= CHILD_PROCESS_INIT
;
669 struct strbuf last
= STRBUF_INIT
;
673 strvec_push(&cp
.args
, "mailsplit");
674 strvec_pushf(&cp
.args
, "-d%d", state
->prec
);
675 strvec_pushf(&cp
.args
, "-o%s", state
->dir
);
676 strvec_push(&cp
.args
, "-b");
678 strvec_push(&cp
.args
, "--keep-cr");
680 strvec_push(&cp
.args
, "--mboxrd");
681 strvec_push(&cp
.args
, "--");
682 strvec_pushv(&cp
.args
, paths
);
684 ret
= capture_command(&cp
, &last
, 8);
689 state
->last
= strtol(last
.buf
, NULL
, 10);
692 strbuf_release(&last
);
697 * Callback signature for split_mail_conv(). The foreign patch should be
698 * read from `in`, and the converted patch (in RFC2822 mail format) should be
699 * written to `out`. Return 0 on success, or -1 on failure.
701 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
704 * Calls `fn` for each file in `paths` to convert the foreign patch to the
705 * RFC2822 mail format suitable for parsing with git-mailinfo.
707 * Returns 0 on success, -1 on failure.
709 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
710 const char **paths
, int keep_cr
)
712 static const char *stdin_only
[] = {"-", NULL
};
718 for (i
= 0; *paths
; paths
++, i
++) {
723 if (!strcmp(*paths
, "-"))
726 in
= fopen(*paths
, "r");
729 return error_errno(_("could not open '%s' for reading"),
732 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
734 out
= fopen(mail
, "w");
738 return error_errno(_("could not open '%s' for writing"),
742 ret
= fn(out
, in
, keep_cr
);
749 return error(_("could not parse patch '%s'"), *paths
);
758 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
759 * message suitable for parsing with git-mailinfo.
761 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
763 struct strbuf sb
= STRBUF_INIT
;
764 int subject_printed
= 0;
766 while (!strbuf_getline_lf(&sb
, in
)) {
769 if (str_isspace(sb
.buf
))
771 else if (skip_prefix(sb
.buf
, "Author:", &str
))
772 fprintf(out
, "From:%s\n", str
);
773 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
774 fprintf(out
, "%s\n", sb
.buf
);
775 else if (!subject_printed
) {
776 fprintf(out
, "Subject: %s\n", sb
.buf
);
779 fprintf(out
, "\n%s\n", sb
.buf
);
785 while (strbuf_fread(&sb
, 8192, in
) > 0) {
786 fwrite(sb
.buf
, 1, sb
.len
, out
);
795 * This function only supports a single StGit series file in `paths`.
797 * Given an StGit series file, converts the StGit patches in the series into
798 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
799 * the state directory.
801 * Returns 0 on success, -1 on failure.
803 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
806 const char *series_dir
;
807 char *series_dir_buf
;
809 struct strvec patches
= STRVEC_INIT
;
810 struct strbuf sb
= STRBUF_INIT
;
813 if (!paths
[0] || paths
[1])
814 return error(_("Only one StGIT patch series can be applied at once"));
816 series_dir_buf
= xstrdup(*paths
);
817 series_dir
= dirname(series_dir_buf
);
819 fp
= fopen(*paths
, "r");
821 return error_errno(_("could not open '%s' for reading"), *paths
);
823 while (!strbuf_getline_lf(&sb
, fp
)) {
825 continue; /* skip comment lines */
827 strvec_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
832 free(series_dir_buf
);
834 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.v
, keep_cr
);
836 strvec_clear(&patches
);
841 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
842 * message suitable for parsing with git-mailinfo.
844 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
846 struct strbuf sb
= STRBUF_INIT
;
849 while (!strbuf_getline_lf(&sb
, in
)) {
852 if (skip_prefix(sb
.buf
, "# User ", &str
))
853 fprintf(out
, "From: %s\n", str
);
854 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
855 timestamp_t timestamp
;
860 timestamp
= parse_timestamp(str
, &end
, 10);
862 rc
= error(_("invalid timestamp"));
866 if (!skip_prefix(end
, " ", &str
)) {
867 rc
= error(_("invalid Date line"));
872 tz
= strtol(str
, &end
, 10);
874 rc
= error(_("invalid timezone offset"));
879 rc
= error(_("invalid Date line"));
884 * mercurial's timezone is in seconds west of UTC,
885 * however git's timezone is in hours + minutes east of
888 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
892 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
893 } else if (starts_with(sb
.buf
, "# ")) {
896 fprintf(out
, "\n%s\n", sb
.buf
);
902 while (strbuf_fread(&sb
, 8192, in
) > 0) {
903 fwrite(sb
.buf
, 1, sb
.len
, out
);
912 * Splits a list of files/directories into individual email patches. Each path
913 * in `paths` must be a file/directory that is formatted according to
916 * Once split out, the individual email patches will be stored in the state
917 * directory, with each patch's filename being its index, padded to state->prec
920 * state->cur will be set to the index of the first mail, and state->last will
921 * be set to the index of the last mail.
923 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
924 * to disable this behavior, -1 to use the default configured setting.
926 * Returns 0 on success, -1 on failure.
928 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
929 const char **paths
, int keep_cr
)
933 git_config_get_bool("am.keepcr", &keep_cr
);
936 switch (patch_format
) {
937 case PATCH_FORMAT_MBOX
:
938 return split_mail_mbox(state
, paths
, keep_cr
, 0);
939 case PATCH_FORMAT_STGIT
:
940 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
941 case PATCH_FORMAT_STGIT_SERIES
:
942 return split_mail_stgit_series(state
, paths
, keep_cr
);
943 case PATCH_FORMAT_HG
:
944 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
945 case PATCH_FORMAT_MBOXRD
:
946 return split_mail_mbox(state
, paths
, keep_cr
, 1);
948 BUG("invalid patch_format");
954 * Setup a new am session for applying patches
956 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
957 const char **paths
, int keep_cr
)
959 struct object_id curr_head
;
961 struct strbuf sb
= STRBUF_INIT
;
964 patch_format
= detect_patch_format(paths
);
967 fprintf_ln(stderr
, _("Patch format detection failed."));
971 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
972 die_errno(_("failed to create directory '%s'"), state
->dir
);
973 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
975 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
977 die(_("Failed to split patches."));
983 write_state_bool(state
, "threeway", state
->threeway
);
984 write_state_bool(state
, "quiet", state
->quiet
);
985 write_state_bool(state
, "sign", state
->signoff
);
986 write_state_bool(state
, "utf8", state
->utf8
);
988 if (state
->allow_rerere_autoupdate
)
989 write_state_bool(state
, "rerere-autoupdate",
990 state
->allow_rerere_autoupdate
== RERERE_AUTOUPDATE
);
992 switch (state
->keep
) {
1003 BUG("invalid value for state->keep");
1006 write_state_text(state
, "keep", str
);
1007 write_state_bool(state
, "messageid", state
->message_id
);
1009 switch (state
->scissors
) {
1010 case SCISSORS_UNSET
:
1013 case SCISSORS_FALSE
:
1020 BUG("invalid value for state->scissors");
1022 write_state_text(state
, "scissors", str
);
1024 switch (state
->quoted_cr
) {
1025 case quoted_cr_unset
:
1028 case quoted_cr_nowarn
:
1031 case quoted_cr_warn
:
1034 case quoted_cr_strip
:
1038 BUG("invalid value for state->quoted_cr");
1040 write_state_text(state
, "quoted-cr", str
);
1042 sq_quote_argv(&sb
, state
->git_apply_opts
.v
);
1043 write_state_text(state
, "apply-opt", sb
.buf
);
1045 if (state
->rebasing
)
1046 write_state_text(state
, "rebasing", "");
1048 write_state_text(state
, "applying", "");
1050 if (!get_oid("HEAD", &curr_head
)) {
1051 write_state_text(state
, "abort-safety", oid_to_hex(&curr_head
));
1052 if (!state
->rebasing
)
1053 update_ref("am", "ORIG_HEAD", &curr_head
, NULL
, 0,
1054 UPDATE_REFS_DIE_ON_ERR
);
1056 write_state_text(state
, "abort-safety", "");
1057 if (!state
->rebasing
)
1058 delete_ref(NULL
, "ORIG_HEAD", NULL
, 0);
1062 * NOTE: Since the "next" and "last" files determine if an am_state
1063 * session is in progress, they should be written last.
1066 write_state_count(state
, "next", state
->cur
);
1067 write_state_count(state
, "last", state
->last
);
1069 strbuf_release(&sb
);
1073 * Increments the patch pointer, and cleans am_state for the application of the
1076 static void am_next(struct am_state
*state
)
1078 struct object_id head
;
1080 FREE_AND_NULL(state
->author_name
);
1081 FREE_AND_NULL(state
->author_email
);
1082 FREE_AND_NULL(state
->author_date
);
1083 FREE_AND_NULL(state
->msg
);
1086 unlink(am_path(state
, "author-script"));
1087 unlink(am_path(state
, "final-commit"));
1089 oidclr(&state
->orig_commit
);
1090 unlink(am_path(state
, "original-commit"));
1091 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
1093 if (!get_oid("HEAD", &head
))
1094 write_state_text(state
, "abort-safety", oid_to_hex(&head
));
1096 write_state_text(state
, "abort-safety", "");
1099 write_state_count(state
, "next", state
->cur
);
1103 * Returns the filename of the current patch email.
1105 static const char *msgnum(const struct am_state
*state
)
1107 static struct strbuf sb
= STRBUF_INIT
;
1110 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1116 * Dies with a user-friendly message on how to proceed after resolving the
1117 * problem. This message can be overridden with state->resolvemsg.
1119 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1121 if (state
->resolvemsg
) {
1122 printf_ln("%s", state
->resolvemsg
);
1124 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1126 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1127 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1128 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1135 * Appends signoff to the "msg" field of the am_state.
1137 static void am_append_signoff(struct am_state
*state
)
1139 struct strbuf sb
= STRBUF_INIT
;
1141 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1142 append_signoff(&sb
, 0, 0);
1143 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1147 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1148 * state->msg will be set to the patch message. state->author_name,
1149 * state->author_email and state->author_date will be set to the patch author's
1150 * name, email and date respectively. The patch body will be written to the
1151 * state directory's "patch" file.
1153 * Returns 1 if the patch should be skipped, 0 otherwise.
1155 static int parse_mail(struct am_state
*state
, const char *mail
)
1158 struct strbuf sb
= STRBUF_INIT
;
1159 struct strbuf msg
= STRBUF_INIT
;
1160 struct strbuf author_name
= STRBUF_INIT
;
1161 struct strbuf author_date
= STRBUF_INIT
;
1162 struct strbuf author_email
= STRBUF_INIT
;
1166 setup_mailinfo(&mi
);
1169 mi
.metainfo_charset
= get_commit_output_encoding();
1171 mi
.metainfo_charset
= NULL
;
1173 switch (state
->keep
) {
1177 mi
.keep_subject
= 1;
1179 case KEEP_NON_PATCH
:
1180 mi
.keep_non_patch_brackets_in_subject
= 1;
1183 BUG("invalid value for state->keep");
1186 if (state
->message_id
)
1187 mi
.add_message_id
= 1;
1189 switch (state
->scissors
) {
1190 case SCISSORS_UNSET
:
1192 case SCISSORS_FALSE
:
1193 mi
.use_scissors
= 0;
1196 mi
.use_scissors
= 1;
1199 BUG("invalid value for state->scissors");
1202 switch (state
->quoted_cr
) {
1203 case quoted_cr_unset
:
1205 case quoted_cr_nowarn
:
1206 case quoted_cr_warn
:
1207 case quoted_cr_strip
:
1208 mi
.quoted_cr
= state
->quoted_cr
;
1211 BUG("invalid value for state->quoted_cr");
1214 mi
.input
= xfopen(mail
, "r");
1215 mi
.output
= xfopen(am_path(state
, "info"), "w");
1216 if (mailinfo(&mi
, am_path(state
, "msg"), am_path(state
, "patch")))
1217 die("could not parse patch");
1222 if (mi
.format_flowed
)
1223 warning(_("Patch sent with format=flowed; "
1224 "space at the end of lines might be lost."));
1226 /* Extract message and author information */
1227 fp
= xfopen(am_path(state
, "info"), "r");
1228 while (!strbuf_getline_lf(&sb
, fp
)) {
1231 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1233 strbuf_addch(&msg
, '\n');
1234 strbuf_addstr(&msg
, x
);
1235 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1236 strbuf_addstr(&author_name
, x
);
1237 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1238 strbuf_addstr(&author_email
, x
);
1239 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1240 strbuf_addstr(&author_date
, x
);
1244 /* Skip pine's internal folder data */
1245 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1250 if (is_empty_or_missing_file(am_path(state
, "patch"))) {
1251 printf_ln(_("Patch is empty."));
1252 die_user_resolve(state
);
1255 strbuf_addstr(&msg
, "\n\n");
1256 strbuf_addbuf(&msg
, &mi
.log_message
);
1257 strbuf_stripspace(&msg
, 0);
1259 assert(!state
->author_name
);
1260 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1262 assert(!state
->author_email
);
1263 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1265 assert(!state
->author_date
);
1266 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1268 assert(!state
->msg
);
1269 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1272 strbuf_release(&msg
);
1273 strbuf_release(&author_date
);
1274 strbuf_release(&author_email
);
1275 strbuf_release(&author_name
);
1276 strbuf_release(&sb
);
1277 clear_mailinfo(&mi
);
1282 * Sets commit_id to the commit hash where the mail was generated from.
1283 * Returns 0 on success, -1 on failure.
1285 static int get_mail_commit_oid(struct object_id
*commit_id
, const char *mail
)
1287 struct strbuf sb
= STRBUF_INIT
;
1288 FILE *fp
= xfopen(mail
, "r");
1292 if (strbuf_getline_lf(&sb
, fp
) ||
1293 !skip_prefix(sb
.buf
, "From ", &x
) ||
1294 get_oid_hex(x
, commit_id
) < 0)
1297 strbuf_release(&sb
);
1303 * Sets state->msg, state->author_name, state->author_email, state->author_date
1304 * to the commit's respective info.
1306 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1308 const char *buffer
, *ident_line
, *msg
;
1310 struct ident_split id
;
1312 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1314 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1316 die(_("missing author line in commit %s"),
1317 oid_to_hex(&commit
->object
.oid
));
1318 if (split_ident_line(&id
, ident_line
, ident_len
) < 0)
1319 die(_("invalid ident line: %.*s"), (int)ident_len
, ident_line
);
1321 assert(!state
->author_name
);
1323 state
->author_name
=
1324 xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1326 state
->author_name
= xstrdup("");
1328 assert(!state
->author_email
);
1330 state
->author_email
=
1331 xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1333 state
->author_email
= xstrdup("");
1335 assert(!state
->author_date
);
1336 state
->author_date
= xstrdup(show_ident_date(&id
, DATE_MODE(NORMAL
)));
1338 assert(!state
->msg
);
1339 msg
= strstr(buffer
, "\n\n");
1341 die(_("unable to parse commit %s"), oid_to_hex(&commit
->object
.oid
));
1342 state
->msg
= xstrdup(msg
+ 2);
1343 state
->msg_len
= strlen(state
->msg
);
1344 unuse_commit_buffer(commit
, buffer
);
1348 * Writes `commit` as a patch to the state directory's "patch" file.
1350 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1352 struct rev_info rev_info
;
1355 fp
= xfopen(am_path(state
, "patch"), "w");
1356 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1358 rev_info
.abbrev
= 0;
1359 rev_info
.disable_stdin
= 1;
1360 rev_info
.show_root_diff
= 1;
1361 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1362 rev_info
.no_commit_id
= 1;
1363 rev_info
.diffopt
.flags
.binary
= 1;
1364 rev_info
.diffopt
.flags
.full_index
= 1;
1365 rev_info
.diffopt
.use_color
= 0;
1366 rev_info
.diffopt
.file
= fp
;
1367 rev_info
.diffopt
.close_file
= 1;
1368 add_pending_object(&rev_info
, &commit
->object
, "");
1369 diff_setup_done(&rev_info
.diffopt
);
1370 log_tree_commit(&rev_info
, commit
);
1374 * Writes the diff of the index against HEAD as a patch to the state
1375 * directory's "patch" file.
1377 static void write_index_patch(const struct am_state
*state
)
1380 struct object_id head
;
1381 struct rev_info rev_info
;
1384 if (!get_oid("HEAD", &head
)) {
1385 struct commit
*commit
= lookup_commit_or_die(&head
, "HEAD");
1386 tree
= get_commit_tree(commit
);
1388 tree
= lookup_tree(the_repository
,
1389 the_repository
->hash_algo
->empty_tree
);
1391 fp
= xfopen(am_path(state
, "patch"), "w");
1392 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1394 rev_info
.disable_stdin
= 1;
1395 rev_info
.no_commit_id
= 1;
1396 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1397 rev_info
.diffopt
.use_color
= 0;
1398 rev_info
.diffopt
.file
= fp
;
1399 rev_info
.diffopt
.close_file
= 1;
1400 add_pending_object(&rev_info
, &tree
->object
, "");
1401 diff_setup_done(&rev_info
.diffopt
);
1402 run_diff_index(&rev_info
, 1);
1406 * Like parse_mail(), but parses the mail by looking up its commit ID
1407 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1410 * state->orig_commit will be set to the original commit ID.
1412 * Will always return 0 as the patch should never be skipped.
1414 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1416 struct commit
*commit
;
1417 struct object_id commit_oid
;
1419 if (get_mail_commit_oid(&commit_oid
, mail
) < 0)
1420 die(_("could not parse %s"), mail
);
1422 commit
= lookup_commit_or_die(&commit_oid
, mail
);
1424 get_commit_info(state
, commit
);
1426 write_commit_patch(state
, commit
);
1428 oidcpy(&state
->orig_commit
, &commit_oid
);
1429 write_state_text(state
, "original-commit", oid_to_hex(&commit_oid
));
1430 update_ref("am", "REBASE_HEAD", &commit_oid
,
1431 NULL
, REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1437 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1438 * `index_file` is not NULL, the patch will be applied to that index.
1440 static int run_apply(const struct am_state
*state
, const char *index_file
)
1442 struct strvec apply_paths
= STRVEC_INIT
;
1443 struct strvec apply_opts
= STRVEC_INIT
;
1444 struct apply_state apply_state
;
1446 int force_apply
= 0;
1449 if (init_apply_state(&apply_state
, the_repository
, NULL
))
1450 BUG("init_apply_state() failed");
1452 strvec_push(&apply_opts
, "apply");
1453 strvec_pushv(&apply_opts
, state
->git_apply_opts
.v
);
1455 opts_left
= apply_parse_options(apply_opts
.nr
, apply_opts
.v
,
1456 &apply_state
, &force_apply
, &options
,
1460 die("unknown option passed through to git apply");
1463 apply_state
.index_file
= index_file
;
1464 apply_state
.cached
= 1;
1466 apply_state
.check_index
= 1;
1469 * If we are allowed to fall back on 3-way merge, don't give false
1470 * errors during the initial attempt.
1472 if (state
->threeway
&& !index_file
)
1473 apply_state
.apply_verbosity
= verbosity_silent
;
1475 if (check_apply_state(&apply_state
, force_apply
))
1476 BUG("check_apply_state() failed");
1478 strvec_push(&apply_paths
, am_path(state
, "patch"));
1480 res
= apply_all_patches(&apply_state
, apply_paths
.nr
, apply_paths
.v
, options
);
1482 strvec_clear(&apply_paths
);
1483 strvec_clear(&apply_opts
);
1484 clear_apply_state(&apply_state
);
1490 /* Reload index as apply_all_patches() will have modified it. */
1492 read_cache_from(index_file
);
1499 * Builds an index that contains just the blobs needed for a 3way merge.
1501 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1503 struct child_process cp
= CHILD_PROCESS_INIT
;
1506 strvec_push(&cp
.args
, "apply");
1507 strvec_pushv(&cp
.args
, state
->git_apply_opts
.v
);
1508 strvec_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1509 strvec_push(&cp
.args
, am_path(state
, "patch"));
1511 if (run_command(&cp
))
1518 * Attempt a threeway merge, using index_path as the temporary index.
1520 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1522 struct object_id orig_tree
, their_tree
, our_tree
;
1523 const struct object_id
*bases
[1] = { &orig_tree
};
1524 struct merge_options o
;
1525 struct commit
*result
;
1526 char *their_tree_name
;
1528 if (get_oid("HEAD", &our_tree
) < 0)
1529 oidcpy(&our_tree
, the_hash_algo
->empty_tree
);
1531 if (build_fake_ancestor(state
, index_path
))
1532 return error("could not build fake ancestor");
1535 read_cache_from(index_path
);
1537 if (write_index_as_tree(&orig_tree
, &the_index
, index_path
, 0, NULL
))
1538 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1540 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1542 if (!state
->quiet
) {
1544 * List paths that needed 3-way fallback, so that the user can
1545 * review them with extra care to spot mismerges.
1547 struct rev_info rev_info
;
1549 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1550 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1551 rev_info
.diffopt
.filter
|= diff_filter_bit('A');
1552 rev_info
.diffopt
.filter
|= diff_filter_bit('M');
1553 add_pending_oid(&rev_info
, "HEAD", &our_tree
, 0);
1554 diff_setup_done(&rev_info
.diffopt
);
1555 run_diff_index(&rev_info
, 1);
1558 if (run_apply(state
, index_path
))
1559 return error(_("Did you hand edit your patch?\n"
1560 "It does not apply to blobs recorded in its index."));
1562 if (write_index_as_tree(&their_tree
, &the_index
, index_path
, 0, NULL
))
1563 return error("could not write tree");
1565 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1571 * This is not so wrong. Depending on which base we picked, orig_tree
1572 * may be wildly different from ours, but their_tree has the same set of
1573 * wildly different changes in parts the patch did not touch, so
1574 * recursive ends up canceling them, saying that we reverted all those
1578 init_merge_options(&o
, the_repository
);
1581 their_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1582 o
.branch2
= their_tree_name
;
1583 o
.detect_directory_renames
= MERGE_DIRECTORY_RENAMES_NONE
;
1588 if (merge_recursive_generic(&o
, &our_tree
, &their_tree
, 1, bases
, &result
)) {
1589 repo_rerere(the_repository
, state
->allow_rerere_autoupdate
);
1590 free(their_tree_name
);
1591 return error(_("Failed to merge in the changes."));
1594 free(their_tree_name
);
1599 * Commits the current index with state->msg as the commit message and
1600 * state->author_name, state->author_email and state->author_date as the author
1603 static void do_commit(const struct am_state
*state
)
1605 struct object_id tree
, parent
, commit
;
1606 const struct object_id
*old_oid
;
1607 struct commit_list
*parents
= NULL
;
1608 const char *reflog_msg
, *author
, *committer
= NULL
;
1609 struct strbuf sb
= STRBUF_INIT
;
1611 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1614 if (write_cache_as_tree(&tree
, 0, NULL
))
1615 die(_("git write-tree failed to write a tree"));
1617 if (!get_oid_commit("HEAD", &parent
)) {
1619 commit_list_insert(lookup_commit(the_repository
, &parent
),
1623 say(state
, stderr
, _("applying to an empty history"));
1626 author
= fmt_ident(state
->author_name
, state
->author_email
,
1628 state
->ignore_date
? NULL
: state
->author_date
,
1631 if (state
->committer_date_is_author_date
)
1632 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1633 getenv("GIT_COMMITTER_EMAIL"),
1634 WANT_COMMITTER_IDENT
,
1635 state
->ignore_date
? NULL
1636 : state
->author_date
,
1639 if (commit_tree_extended(state
->msg
, state
->msg_len
, &tree
, parents
,
1640 &commit
, author
, committer
, state
->sign_commit
,
1642 die(_("failed to write commit object"));
1644 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1648 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1651 update_ref(sb
.buf
, "HEAD", &commit
, old_oid
, 0,
1652 UPDATE_REFS_DIE_ON_ERR
);
1654 if (state
->rebasing
) {
1655 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1657 assert(!is_null_oid(&state
->orig_commit
));
1658 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
1659 fprintf(fp
, "%s\n", oid_to_hex(&commit
));
1663 run_hook_le(NULL
, "post-applypatch", NULL
);
1665 strbuf_release(&sb
);
1669 * Validates the am_state for resuming -- the "msg" and authorship fields must
1672 static void validate_resume_state(const struct am_state
*state
)
1675 die(_("cannot resume: %s does not exist."),
1676 am_path(state
, "final-commit"));
1678 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1679 die(_("cannot resume: %s does not exist."),
1680 am_path(state
, "author-script"));
1684 * Interactively prompt the user on whether the current patch should be
1687 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1690 static int do_interactive(struct am_state
*state
)
1697 puts(_("Commit Body is:"));
1698 puts("--------------------------");
1699 printf("%s", state
->msg
);
1700 puts("--------------------------");
1703 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1704 * in your translation. The program will only accept English
1705 * input at this point.
1707 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1708 if (!fgets(reply
, sizeof(reply
), stdin
))
1709 die("unable to read from stdin; aborting");
1711 if (*reply
== 'y' || *reply
== 'Y') {
1713 } else if (*reply
== 'a' || *reply
== 'A') {
1714 state
->interactive
= 0;
1716 } else if (*reply
== 'n' || *reply
== 'N') {
1718 } else if (*reply
== 'e' || *reply
== 'E') {
1719 struct strbuf msg
= STRBUF_INIT
;
1721 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1723 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1725 strbuf_release(&msg
);
1726 } else if (*reply
== 'v' || *reply
== 'V') {
1727 const char *pager
= git_pager(1);
1728 struct child_process cp
= CHILD_PROCESS_INIT
;
1732 prepare_pager_args(&cp
, pager
);
1733 strvec_push(&cp
.args
, am_path(state
, "patch"));
1740 * Applies all queued mail.
1742 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1743 * well as the state directory's "patch" file is used as-is for applying the
1744 * patch and committing it.
1746 static void am_run(struct am_state
*state
, int resume
)
1748 struct strbuf sb
= STRBUF_INIT
;
1750 unlink(am_path(state
, "dirtyindex"));
1752 if (refresh_and_write_cache(REFRESH_QUIET
, 0, 0) < 0)
1753 die(_("unable to write index file"));
1755 if (repo_index_has_changes(the_repository
, NULL
, &sb
)) {
1756 write_state_bool(state
, "dirtyindex", 1);
1757 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1760 strbuf_release(&sb
);
1762 while (state
->cur
<= state
->last
) {
1763 const char *mail
= am_path(state
, msgnum(state
));
1768 if (!file_exists(mail
))
1772 validate_resume_state(state
);
1776 if (state
->rebasing
)
1777 skip
= parse_mail_rebase(state
, mail
);
1779 skip
= parse_mail(state
, mail
);
1782 goto next
; /* mail should be skipped */
1785 am_append_signoff(state
);
1787 write_author_script(state
);
1788 write_commit_msg(state
);
1791 if (state
->interactive
&& do_interactive(state
))
1794 if (run_applypatch_msg_hook(state
))
1797 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1799 apply_status
= run_apply(state
, NULL
);
1801 if (apply_status
&& state
->threeway
) {
1802 struct strbuf sb
= STRBUF_INIT
;
1804 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1805 apply_status
= fall_back_threeway(state
, sb
.buf
);
1806 strbuf_release(&sb
);
1809 * Applying the patch to an earlier tree and merging
1810 * the result may have produced the same tree as ours.
1812 if (!apply_status
&&
1813 !repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1814 say(state
, stdout
, _("No changes -- Patch already applied."));
1820 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1821 linelen(state
->msg
), state
->msg
);
1823 if (advice_amworkdir
)
1824 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1826 die_user_resolve(state
);
1839 if (!is_empty_or_missing_file(am_path(state
, "rewritten"))) {
1840 assert(state
->rebasing
);
1841 copy_notes_for_rebase(state
);
1842 run_post_rewrite_hook(state
);
1846 * In rebasing mode, it's up to the caller to take care of
1849 if (!state
->rebasing
) {
1851 close_object_store(the_repository
->objects
);
1852 run_auto_maintenance(state
->quiet
);
1857 * Resume the current am session after patch application failure. The user did
1858 * all the hard work, and we do not have to do any patch application. Just
1859 * trust and commit what the user has in the index and working tree.
1861 static void am_resolve(struct am_state
*state
)
1863 validate_resume_state(state
);
1865 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1867 if (!repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1868 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1869 "If there is nothing left to stage, chances are that something else\n"
1870 "already introduced the same changes; you might want to skip this patch."));
1871 die_user_resolve(state
);
1874 if (unmerged_cache()) {
1875 printf_ln(_("You still have unmerged paths in your index.\n"
1876 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1877 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1878 die_user_resolve(state
);
1881 if (state
->interactive
) {
1882 write_index_patch(state
);
1883 if (do_interactive(state
))
1887 repo_rerere(the_repository
, 0);
1898 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1899 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1902 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1904 struct lock_file lock_file
= LOCK_INIT
;
1905 struct unpack_trees_options opts
;
1906 struct tree_desc t
[2];
1908 if (parse_tree(head
) || parse_tree(remote
))
1911 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1913 refresh_cache(REFRESH_QUIET
);
1915 memset(&opts
, 0, sizeof(opts
));
1917 opts
.src_index
= &the_index
;
1918 opts
.dst_index
= &the_index
;
1922 opts
.fn
= twoway_merge
;
1923 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1924 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1926 if (unpack_trees(2, t
, &opts
)) {
1927 rollback_lock_file(&lock_file
);
1931 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1932 die(_("unable to write new index file"));
1938 * Merges a tree into the index. The index's stat info will take precedence
1939 * over the merged tree's. Returns 0 on success, -1 on failure.
1941 static int merge_tree(struct tree
*tree
)
1943 struct lock_file lock_file
= LOCK_INIT
;
1944 struct unpack_trees_options opts
;
1945 struct tree_desc t
[1];
1947 if (parse_tree(tree
))
1950 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1952 memset(&opts
, 0, sizeof(opts
));
1954 opts
.src_index
= &the_index
;
1955 opts
.dst_index
= &the_index
;
1957 opts
.fn
= oneway_merge
;
1958 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
1960 if (unpack_trees(1, t
, &opts
)) {
1961 rollback_lock_file(&lock_file
);
1965 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1966 die(_("unable to write new index file"));
1972 * Clean the index without touching entries that are not modified between
1973 * `head` and `remote`.
1975 static int clean_index(const struct object_id
*head
, const struct object_id
*remote
)
1977 struct tree
*head_tree
, *remote_tree
, *index_tree
;
1978 struct object_id index
;
1980 head_tree
= parse_tree_indirect(head
);
1982 return error(_("Could not parse object '%s'."), oid_to_hex(head
));
1984 remote_tree
= parse_tree_indirect(remote
);
1986 return error(_("Could not parse object '%s'."), oid_to_hex(remote
));
1988 read_cache_unmerged();
1990 if (fast_forward_to(head_tree
, head_tree
, 1))
1993 if (write_cache_as_tree(&index
, 0, NULL
))
1996 index_tree
= parse_tree_indirect(&index
);
1998 return error(_("Could not parse object '%s'."), oid_to_hex(&index
));
2000 if (fast_forward_to(index_tree
, remote_tree
, 0))
2003 if (merge_tree(remote_tree
))
2006 remove_branch_state(the_repository
, 0);
2012 * Resets rerere's merge resolution metadata.
2014 static void am_rerere_clear(void)
2016 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
2017 rerere_clear(the_repository
, &merge_rr
);
2018 string_list_clear(&merge_rr
, 1);
2022 * Resume the current am session by skipping the current patch.
2024 static void am_skip(struct am_state
*state
)
2026 struct object_id head
;
2030 if (get_oid("HEAD", &head
))
2031 oidcpy(&head
, the_hash_algo
->empty_tree
);
2033 if (clean_index(&head
, &head
))
2034 die(_("failed to clean index"));
2036 if (state
->rebasing
) {
2037 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
2039 assert(!is_null_oid(&state
->orig_commit
));
2040 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
2041 fprintf(fp
, "%s\n", oid_to_hex(&head
));
2051 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2053 * It is not safe to reset HEAD when:
2054 * 1. git-am previously failed because the index was dirty.
2055 * 2. HEAD has moved since git-am previously failed.
2057 static int safe_to_abort(const struct am_state
*state
)
2059 struct strbuf sb
= STRBUF_INIT
;
2060 struct object_id abort_safety
, head
;
2062 if (file_exists(am_path(state
, "dirtyindex")))
2065 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2066 if (get_oid_hex(sb
.buf
, &abort_safety
))
2067 die(_("could not parse %s"), am_path(state
, "abort-safety"));
2069 oidclr(&abort_safety
);
2070 strbuf_release(&sb
);
2072 if (get_oid("HEAD", &head
))
2075 if (oideq(&head
, &abort_safety
))
2078 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2079 "Not rewinding to ORIG_HEAD"));
2085 * Aborts the current am session if it is safe to do so.
2087 static void am_abort(struct am_state
*state
)
2089 struct object_id curr_head
, orig_head
;
2090 int has_curr_head
, has_orig_head
;
2093 if (!safe_to_abort(state
)) {
2100 curr_branch
= resolve_refdup("HEAD", 0, &curr_head
, NULL
);
2101 has_curr_head
= curr_branch
&& !is_null_oid(&curr_head
);
2103 oidcpy(&curr_head
, the_hash_algo
->empty_tree
);
2105 has_orig_head
= !get_oid("ORIG_HEAD", &orig_head
);
2107 oidcpy(&orig_head
, the_hash_algo
->empty_tree
);
2109 if (clean_index(&curr_head
, &orig_head
))
2110 die(_("failed to clean index"));
2113 update_ref("am --abort", "HEAD", &orig_head
,
2114 has_curr_head
? &curr_head
: NULL
, 0,
2115 UPDATE_REFS_DIE_ON_ERR
);
2116 else if (curr_branch
)
2117 delete_ref(NULL
, curr_branch
, NULL
, REF_NO_DEREF
);
2123 static int show_patch(struct am_state
*state
, enum show_patch_type sub_mode
)
2125 struct strbuf sb
= STRBUF_INIT
;
2126 const char *patch_path
;
2129 if (!is_null_oid(&state
->orig_commit
)) {
2130 const char *av
[4] = { "show", NULL
, "--", NULL
};
2134 av
[1] = new_oid_str
= xstrdup(oid_to_hex(&state
->orig_commit
));
2135 ret
= run_command_v_opt(av
, RUN_GIT_CMD
);
2141 case SHOW_PATCH_RAW
:
2142 patch_path
= am_path(state
, msgnum(state
));
2144 case SHOW_PATCH_DIFF
:
2145 patch_path
= am_path(state
, "patch");
2148 BUG("invalid mode for --show-current-patch");
2151 len
= strbuf_read_file(&sb
, patch_path
, 0);
2153 die_errno(_("failed to read '%s'"), patch_path
);
2156 write_in_full(1, sb
.buf
, sb
.len
);
2157 strbuf_release(&sb
);
2162 * parse_options() callback that validates and sets opt->value to the
2163 * PATCH_FORMAT_* enum value corresponding to `arg`.
2165 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2167 int *opt_value
= opt
->value
;
2170 *opt_value
= PATCH_FORMAT_UNKNOWN
;
2171 else if (!strcmp(arg
, "mbox"))
2172 *opt_value
= PATCH_FORMAT_MBOX
;
2173 else if (!strcmp(arg
, "stgit"))
2174 *opt_value
= PATCH_FORMAT_STGIT
;
2175 else if (!strcmp(arg
, "stgit-series"))
2176 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2177 else if (!strcmp(arg
, "hg"))
2178 *opt_value
= PATCH_FORMAT_HG
;
2179 else if (!strcmp(arg
, "mboxrd"))
2180 *opt_value
= PATCH_FORMAT_MBOXRD
;
2182 * Please update $__git_patchformat in git-completion.bash
2183 * when you add new options
2186 return error(_("Invalid value for --patch-format: %s"), arg
);
2200 struct resume_mode
{
2201 enum resume_type mode
;
2202 enum show_patch_type sub_mode
;
2205 static int parse_opt_show_current_patch(const struct option
*opt
, const char *arg
, int unset
)
2207 int *opt_value
= opt
->value
;
2208 struct resume_mode
*resume
= container_of(opt_value
, struct resume_mode
, mode
);
2211 * Please update $__git_showcurrentpatch in git-completion.bash
2212 * when you add new options
2214 const char *valid_modes
[] = {
2215 [SHOW_PATCH_DIFF
] = "diff",
2216 [SHOW_PATCH_RAW
] = "raw"
2218 int new_value
= SHOW_PATCH_RAW
;
2220 BUG_ON_OPT_NEG(unset
);
2223 for (new_value
= 0; new_value
< ARRAY_SIZE(valid_modes
); new_value
++) {
2224 if (!strcmp(arg
, valid_modes
[new_value
]))
2227 if (new_value
>= ARRAY_SIZE(valid_modes
))
2228 return error(_("Invalid value for --show-current-patch: %s"), arg
);
2231 if (resume
->mode
== RESUME_SHOW_PATCH
&& new_value
!= resume
->sub_mode
)
2232 return error(_("--show-current-patch=%s is incompatible with "
2233 "--show-current-patch=%s"),
2234 arg
, valid_modes
[resume
->sub_mode
]);
2236 resume
->mode
= RESUME_SHOW_PATCH
;
2237 resume
->sub_mode
= new_value
;
2241 static int git_am_config(const char *k
, const char *v
, void *cb
)
2245 status
= git_gpg_config(k
, v
, NULL
);
2249 return git_default_config(k
, v
, NULL
);
2252 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2254 struct am_state state
;
2257 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2258 struct resume_mode resume
= { .mode
= RESUME_FALSE
};
2262 const char * const usage
[] = {
2263 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2264 N_("git am [<options>] (--continue | --skip | --abort)"),
2268 struct option options
[] = {
2269 OPT_BOOL('i', "interactive", &state
.interactive
,
2270 N_("run interactively")),
2271 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2272 N_("historical option -- no-op")),
2273 OPT_BOOL('3', "3way", &state
.threeway
,
2274 N_("allow fall back on 3way merging if needed")),
2275 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2276 OPT_SET_INT('s', "signoff", &state
.signoff
,
2277 N_("add a Signed-off-by trailer to the commit message"),
2279 OPT_BOOL('u', "utf8", &state
.utf8
,
2280 N_("recode into utf8 (default)")),
2281 OPT_SET_INT('k', "keep", &state
.keep
,
2282 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2283 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2284 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2285 OPT_BOOL('m', "message-id", &state
.message_id
,
2286 N_("pass -m flag to git-mailinfo")),
2287 OPT_SET_INT_F(0, "keep-cr", &keep_cr
,
2288 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2289 1, PARSE_OPT_NONEG
),
2290 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr
,
2291 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2292 0, PARSE_OPT_NONEG
),
2293 OPT_BOOL('c', "scissors", &state
.scissors
,
2294 N_("strip everything before a scissors line")),
2295 OPT_CALLBACK_F(0, "quoted-cr", &state
.quoted_cr
, N_("action"),
2296 N_("pass it through git-mailinfo"),
2297 PARSE_OPT_NONEG
, am_option_parse_quoted_cr
),
2298 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2299 N_("pass it through git-apply"),
2301 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2302 N_("pass it through git-apply"),
2304 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2305 N_("pass it through git-apply"),
2307 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2308 N_("pass it through git-apply"),
2310 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2311 N_("pass it through git-apply"),
2313 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2314 N_("pass it through git-apply"),
2316 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2317 N_("pass it through git-apply"),
2319 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2320 N_("pass it through git-apply"),
2322 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2323 N_("format the patch(es) are in"),
2324 parse_opt_patchformat
),
2325 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2326 N_("pass it through git-apply"),
2328 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2329 N_("override error message when patch failure occurs")),
2330 OPT_CMDMODE(0, "continue", &resume
.mode
,
2331 N_("continue applying patches after resolving a conflict"),
2333 OPT_CMDMODE('r', "resolved", &resume
.mode
,
2334 N_("synonyms for --continue"),
2336 OPT_CMDMODE(0, "skip", &resume
.mode
,
2337 N_("skip the current patch"),
2339 OPT_CMDMODE(0, "abort", &resume
.mode
,
2340 N_("restore the original branch and abort the patching operation"),
2342 OPT_CMDMODE(0, "quit", &resume
.mode
,
2343 N_("abort the patching operation but keep HEAD where it is"),
2345 { OPTION_CALLBACK
, 0, "show-current-patch", &resume
.mode
,
2347 N_("show the patch being applied"),
2348 PARSE_OPT_CMDMODE
| PARSE_OPT_OPTARG
| PARSE_OPT_NONEG
| PARSE_OPT_LITERAL_ARGHELP
,
2349 parse_opt_show_current_patch
, RESUME_SHOW_PATCH
},
2350 OPT_BOOL(0, "committer-date-is-author-date",
2351 &state
.committer_date_is_author_date
,
2352 N_("lie about committer date")),
2353 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2354 N_("use current timestamp for author date")),
2355 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2356 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2357 N_("GPG-sign commits"),
2358 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2359 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2360 N_("(internal use for git-rebase)")),
2364 if (argc
== 2 && !strcmp(argv
[1], "-h"))
2365 usage_with_options(usage
, options
);
2367 git_config(git_am_config
, NULL
);
2369 am_state_init(&state
);
2371 in_progress
= am_in_progress(&state
);
2375 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2378 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2379 "it will be removed. Please do not use it anymore."));
2381 /* Ensure a valid committer ident can be constructed */
2382 git_committer_info(IDENT_STRICT
);
2384 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
2385 die(_("failed to read the index"));
2389 * Catch user error to feed us patches when there is a session
2392 * 1. mbox path(s) are provided on the command-line.
2393 * 2. stdin is not a tty: the user is trying to feed us a patch
2394 * from standard input. This is somewhat unreliable -- stdin
2395 * could be /dev/null for example and the caller did not
2396 * intend to feed us a patch but wanted to continue
2399 if (argc
|| (resume
.mode
== RESUME_FALSE
&& !isatty(0)))
2400 die(_("previous rebase directory %s still exists but mbox given."),
2403 if (resume
.mode
== RESUME_FALSE
)
2404 resume
.mode
= RESUME_APPLY
;
2406 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2407 am_append_signoff(&state
);
2409 struct strvec paths
= STRVEC_INIT
;
2413 * Handle stray state directory in the independent-run case. In
2414 * the --rebasing case, it is up to the caller to take care of
2415 * stray directories.
2417 if (file_exists(state
.dir
) && !state
.rebasing
) {
2418 if (resume
.mode
== RESUME_ABORT
|| resume
.mode
== RESUME_QUIT
) {
2420 am_state_release(&state
);
2424 die(_("Stray %s directory found.\n"
2425 "Use \"git am --abort\" to remove it."),
2430 die(_("Resolve operation not in progress, we are not resuming."));
2432 for (i
= 0; i
< argc
; i
++) {
2433 if (is_absolute_path(argv
[i
]) || !prefix
)
2434 strvec_push(&paths
, argv
[i
]);
2436 strvec_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2439 if (state
.interactive
&& !paths
.nr
)
2440 die(_("interactive mode requires patches on the command line"));
2442 am_setup(&state
, patch_format
, paths
.v
, keep_cr
);
2444 strvec_clear(&paths
);
2447 switch (resume
.mode
) {
2454 case RESUME_RESOLVED
:
2467 case RESUME_SHOW_PATCH
:
2468 ret
= show_patch(&state
, resume
.sub_mode
);
2471 BUG("invalid resume value");
2474 am_state_release(&state
);