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 struct argv_array git_apply_opts
;
120 const char *resolvemsg
;
121 int committer_date_is_author_date
;
123 int allow_rerere_autoupdate
;
124 const char *sign_commit
;
129 * Initializes am_state with the default values.
131 static void am_state_init(struct am_state
*state
)
135 memset(state
, 0, sizeof(*state
));
137 state
->dir
= git_pathdup("rebase-apply");
141 git_config_get_bool("am.threeway", &state
->threeway
);
145 git_config_get_bool("am.messageid", &state
->message_id
);
147 state
->scissors
= SCISSORS_UNSET
;
149 argv_array_init(&state
->git_apply_opts
);
151 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
152 state
->sign_commit
= gpgsign
? "" : NULL
;
156 * Releases memory allocated by an am_state.
158 static void am_state_release(struct am_state
*state
)
161 free(state
->author_name
);
162 free(state
->author_email
);
163 free(state
->author_date
);
165 argv_array_clear(&state
->git_apply_opts
);
169 * Returns path relative to the am_state directory.
171 static inline const char *am_path(const struct am_state
*state
, const char *path
)
173 return mkpath("%s/%s", state
->dir
, path
);
177 * For convenience to call write_file()
179 static void write_state_text(const struct am_state
*state
,
180 const char *name
, const char *string
)
182 write_file(am_path(state
, name
), "%s", string
);
185 static void write_state_count(const struct am_state
*state
,
186 const char *name
, int value
)
188 write_file(am_path(state
, name
), "%d", value
);
191 static void write_state_bool(const struct am_state
*state
,
192 const char *name
, int value
)
194 write_state_text(state
, name
, value
? "t" : "f");
198 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
201 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
207 vfprintf(fp
, fmt
, ap
);
214 * Returns 1 if there is an am session in progress, 0 otherwise.
216 static int am_in_progress(const struct am_state
*state
)
220 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
222 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
224 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
230 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
231 * number of bytes read on success, -1 if the file does not exist. If `trim` is
232 * set, trailing whitespace will be removed.
234 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
235 const char *file
, int trim
)
239 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
249 die_errno(_("could not read '%s'"), am_path(state
, file
));
253 * Reads and parses the state directory's "author-script" file, and sets
254 * state->author_name, state->author_email and state->author_date accordingly.
255 * Returns 0 on success, -1 if the file could not be parsed.
257 * The author script is of the format:
259 * GIT_AUTHOR_NAME='$author_name'
260 * GIT_AUTHOR_EMAIL='$author_email'
261 * GIT_AUTHOR_DATE='$author_date'
263 * where $author_name, $author_email and $author_date are quoted. We are strict
264 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
265 * script, and thus if the file differs from what this function expects, it is
266 * better to bail out than to do something that the user does not expect.
268 static int read_am_author_script(struct am_state
*state
)
270 const char *filename
= am_path(state
, "author-script");
272 assert(!state
->author_name
);
273 assert(!state
->author_email
);
274 assert(!state
->author_date
);
276 return read_author_script(filename
, &state
->author_name
,
277 &state
->author_email
, &state
->author_date
, 1);
281 * Saves state->author_name, state->author_email and state->author_date in the
282 * state directory's "author-script" file.
284 static void write_author_script(const struct am_state
*state
)
286 struct strbuf sb
= STRBUF_INIT
;
288 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
289 sq_quote_buf(&sb
, state
->author_name
);
290 strbuf_addch(&sb
, '\n');
292 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
293 sq_quote_buf(&sb
, state
->author_email
);
294 strbuf_addch(&sb
, '\n');
296 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
297 sq_quote_buf(&sb
, state
->author_date
);
298 strbuf_addch(&sb
, '\n');
300 write_state_text(state
, "author-script", sb
.buf
);
306 * Reads the commit message from the state directory's "final-commit" file,
307 * setting state->msg to its contents and state->msg_len to the length of its
310 * Returns 0 on success, -1 if the file does not exist.
312 static int read_commit_msg(struct am_state
*state
)
314 struct strbuf sb
= STRBUF_INIT
;
318 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
323 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
328 * Saves state->msg in the state directory's "final-commit" file.
330 static void write_commit_msg(const struct am_state
*state
)
332 const char *filename
= am_path(state
, "final-commit");
333 write_file_buf(filename
, state
->msg
, state
->msg_len
);
337 * Loads state from disk.
339 static void am_load(struct am_state
*state
)
341 struct strbuf sb
= STRBUF_INIT
;
343 if (read_state_file(&sb
, state
, "next", 1) < 0)
344 BUG("state file 'next' does not exist");
345 state
->cur
= strtol(sb
.buf
, NULL
, 10);
347 if (read_state_file(&sb
, state
, "last", 1) < 0)
348 BUG("state file 'last' does not exist");
349 state
->last
= strtol(sb
.buf
, NULL
, 10);
351 if (read_am_author_script(state
) < 0)
352 die(_("could not parse author script"));
354 read_commit_msg(state
);
356 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
357 oidclr(&state
->orig_commit
);
358 else if (get_oid_hex(sb
.buf
, &state
->orig_commit
) < 0)
359 die(_("could not parse %s"), am_path(state
, "original-commit"));
361 read_state_file(&sb
, state
, "threeway", 1);
362 state
->threeway
= !strcmp(sb
.buf
, "t");
364 read_state_file(&sb
, state
, "quiet", 1);
365 state
->quiet
= !strcmp(sb
.buf
, "t");
367 read_state_file(&sb
, state
, "sign", 1);
368 state
->signoff
= !strcmp(sb
.buf
, "t");
370 read_state_file(&sb
, state
, "utf8", 1);
371 state
->utf8
= !strcmp(sb
.buf
, "t");
373 if (file_exists(am_path(state
, "rerere-autoupdate"))) {
374 read_state_file(&sb
, state
, "rerere-autoupdate", 1);
375 state
->allow_rerere_autoupdate
= strcmp(sb
.buf
, "t") ?
376 RERERE_NOAUTOUPDATE
: RERERE_AUTOUPDATE
;
378 state
->allow_rerere_autoupdate
= 0;
381 read_state_file(&sb
, state
, "keep", 1);
382 if (!strcmp(sb
.buf
, "t"))
383 state
->keep
= KEEP_TRUE
;
384 else if (!strcmp(sb
.buf
, "b"))
385 state
->keep
= KEEP_NON_PATCH
;
387 state
->keep
= KEEP_FALSE
;
389 read_state_file(&sb
, state
, "messageid", 1);
390 state
->message_id
= !strcmp(sb
.buf
, "t");
392 read_state_file(&sb
, state
, "scissors", 1);
393 if (!strcmp(sb
.buf
, "t"))
394 state
->scissors
= SCISSORS_TRUE
;
395 else if (!strcmp(sb
.buf
, "f"))
396 state
->scissors
= SCISSORS_FALSE
;
398 state
->scissors
= SCISSORS_UNSET
;
400 read_state_file(&sb
, state
, "apply-opt", 1);
401 argv_array_clear(&state
->git_apply_opts
);
402 if (sq_dequote_to_argv_array(sb
.buf
, &state
->git_apply_opts
) < 0)
403 die(_("could not parse %s"), am_path(state
, "apply-opt"));
405 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
411 * Removes the am_state directory, forcefully terminating the current am
414 static void am_destroy(const struct am_state
*state
)
416 struct strbuf sb
= STRBUF_INIT
;
418 strbuf_addstr(&sb
, state
->dir
);
419 remove_dir_recursively(&sb
, 0);
424 * Runs applypatch-msg hook. Returns its exit code.
426 static int run_applypatch_msg_hook(struct am_state
*state
)
431 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
434 FREE_AND_NULL(state
->msg
);
435 if (read_commit_msg(state
) < 0)
436 die(_("'%s' was deleted by the applypatch-msg hook"),
437 am_path(state
, "final-commit"));
444 * Runs post-rewrite hook. Returns it exit code.
446 static int run_post_rewrite_hook(const struct am_state
*state
)
448 struct child_process cp
= CHILD_PROCESS_INIT
;
449 const char *hook
= find_hook("post-rewrite");
455 argv_array_push(&cp
.args
, hook
);
456 argv_array_push(&cp
.args
, "rebase");
458 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
459 cp
.stdout_to_stderr
= 1;
460 cp
.trace2_hook_name
= "post-rewrite";
462 ret
= run_command(&cp
);
469 * Reads the state directory's "rewritten" file, and copies notes from the old
470 * commits listed in the file to their rewritten commits.
472 * Returns 0 on success, -1 on failure.
474 static int copy_notes_for_rebase(const struct am_state
*state
)
476 struct notes_rewrite_cfg
*c
;
477 struct strbuf sb
= STRBUF_INIT
;
478 const char *invalid_line
= _("Malformed input line: '%s'.");
479 const char *msg
= "Notes added by 'git rebase'";
483 assert(state
->rebasing
);
485 c
= init_copy_notes_for_rewrite("rebase");
489 fp
= xfopen(am_path(state
, "rewritten"), "r");
491 while (!strbuf_getline_lf(&sb
, fp
)) {
492 struct object_id from_obj
, to_obj
;
495 if (sb
.len
!= the_hash_algo
->hexsz
* 2 + 1) {
496 ret
= error(invalid_line
, sb
.buf
);
500 if (parse_oid_hex(sb
.buf
, &from_obj
, &p
)) {
501 ret
= error(invalid_line
, sb
.buf
);
506 ret
= error(invalid_line
, sb
.buf
);
510 if (get_oid_hex(p
+ 1, &to_obj
)) {
511 ret
= error(invalid_line
, sb
.buf
);
515 if (copy_note_for_rewrite(c
, &from_obj
, &to_obj
))
516 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
517 oid_to_hex(&from_obj
), oid_to_hex(&to_obj
));
521 finish_copy_notes_for_rewrite(the_repository
, c
, msg
);
528 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
529 * non-indented lines and checking if they look like they begin with valid
530 * header field names.
532 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
534 static int is_mail(FILE *fp
)
536 const char *header_regex
= "^[!-9;-~]+:";
537 struct strbuf sb
= STRBUF_INIT
;
541 if (fseek(fp
, 0L, SEEK_SET
))
542 die_errno(_("fseek failed"));
544 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
545 die("invalid pattern: %s", header_regex
);
547 while (!strbuf_getline(&sb
, fp
)) {
549 break; /* End of header */
551 /* Ignore indented folded lines */
552 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
555 /* It's a header if it matches header_regex */
556 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
569 * Attempts to detect the patch_format of the patches contained in `paths`,
570 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
573 static int detect_patch_format(const char **paths
)
575 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
576 struct strbuf l1
= STRBUF_INIT
;
577 struct strbuf l2
= STRBUF_INIT
;
578 struct strbuf l3
= STRBUF_INIT
;
582 * We default to mbox format if input is from stdin and for directories
584 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
585 return PATCH_FORMAT_MBOX
;
588 * Otherwise, check the first few lines of the first patch, starting
589 * from the first non-blank line, to try to detect its format.
592 fp
= xfopen(*paths
, "r");
594 while (!strbuf_getline(&l1
, fp
)) {
599 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
600 ret
= PATCH_FORMAT_MBOX
;
604 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
605 ret
= PATCH_FORMAT_STGIT_SERIES
;
609 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
610 ret
= PATCH_FORMAT_HG
;
614 strbuf_getline(&l2
, fp
);
615 strbuf_getline(&l3
, fp
);
618 * If the second line is empty and the third is a From, Author or Date
619 * entry, this is likely an StGit patch.
621 if (l1
.len
&& !l2
.len
&&
622 (starts_with(l3
.buf
, "From:") ||
623 starts_with(l3
.buf
, "Author:") ||
624 starts_with(l3
.buf
, "Date:"))) {
625 ret
= PATCH_FORMAT_STGIT
;
629 if (l1
.len
&& is_mail(fp
)) {
630 ret
= PATCH_FORMAT_MBOX
;
643 * Splits out individual email patches from `paths`, where each path is either
644 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
646 static int split_mail_mbox(struct am_state
*state
, const char **paths
,
647 int keep_cr
, int mboxrd
)
649 struct child_process cp
= CHILD_PROCESS_INIT
;
650 struct strbuf last
= STRBUF_INIT
;
654 argv_array_push(&cp
.args
, "mailsplit");
655 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
656 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
657 argv_array_push(&cp
.args
, "-b");
659 argv_array_push(&cp
.args
, "--keep-cr");
661 argv_array_push(&cp
.args
, "--mboxrd");
662 argv_array_push(&cp
.args
, "--");
663 argv_array_pushv(&cp
.args
, paths
);
665 ret
= capture_command(&cp
, &last
, 8);
670 state
->last
= strtol(last
.buf
, NULL
, 10);
673 strbuf_release(&last
);
678 * Callback signature for split_mail_conv(). The foreign patch should be
679 * read from `in`, and the converted patch (in RFC2822 mail format) should be
680 * written to `out`. Return 0 on success, or -1 on failure.
682 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
685 * Calls `fn` for each file in `paths` to convert the foreign patch to the
686 * RFC2822 mail format suitable for parsing with git-mailinfo.
688 * Returns 0 on success, -1 on failure.
690 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
691 const char **paths
, int keep_cr
)
693 static const char *stdin_only
[] = {"-", NULL
};
699 for (i
= 0; *paths
; paths
++, i
++) {
704 if (!strcmp(*paths
, "-"))
707 in
= fopen(*paths
, "r");
710 return error_errno(_("could not open '%s' for reading"),
713 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
715 out
= fopen(mail
, "w");
719 return error_errno(_("could not open '%s' for writing"),
723 ret
= fn(out
, in
, keep_cr
);
730 return error(_("could not parse patch '%s'"), *paths
);
739 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
740 * message suitable for parsing with git-mailinfo.
742 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
744 struct strbuf sb
= STRBUF_INIT
;
745 int subject_printed
= 0;
747 while (!strbuf_getline_lf(&sb
, in
)) {
750 if (str_isspace(sb
.buf
))
752 else if (skip_prefix(sb
.buf
, "Author:", &str
))
753 fprintf(out
, "From:%s\n", str
);
754 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
755 fprintf(out
, "%s\n", sb
.buf
);
756 else if (!subject_printed
) {
757 fprintf(out
, "Subject: %s\n", sb
.buf
);
760 fprintf(out
, "\n%s\n", sb
.buf
);
766 while (strbuf_fread(&sb
, 8192, in
) > 0) {
767 fwrite(sb
.buf
, 1, sb
.len
, out
);
776 * This function only supports a single StGit series file in `paths`.
778 * Given an StGit series file, converts the StGit patches in the series into
779 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
780 * the state directory.
782 * Returns 0 on success, -1 on failure.
784 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
787 const char *series_dir
;
788 char *series_dir_buf
;
790 struct argv_array patches
= ARGV_ARRAY_INIT
;
791 struct strbuf sb
= STRBUF_INIT
;
794 if (!paths
[0] || paths
[1])
795 return error(_("Only one StGIT patch series can be applied at once"));
797 series_dir_buf
= xstrdup(*paths
);
798 series_dir
= dirname(series_dir_buf
);
800 fp
= fopen(*paths
, "r");
802 return error_errno(_("could not open '%s' for reading"), *paths
);
804 while (!strbuf_getline_lf(&sb
, fp
)) {
806 continue; /* skip comment lines */
808 argv_array_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
813 free(series_dir_buf
);
815 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.argv
, keep_cr
);
817 argv_array_clear(&patches
);
822 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
823 * message suitable for parsing with git-mailinfo.
825 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
827 struct strbuf sb
= STRBUF_INIT
;
830 while (!strbuf_getline_lf(&sb
, in
)) {
833 if (skip_prefix(sb
.buf
, "# User ", &str
))
834 fprintf(out
, "From: %s\n", str
);
835 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
836 timestamp_t timestamp
;
841 timestamp
= parse_timestamp(str
, &end
, 10);
843 rc
= error(_("invalid timestamp"));
847 if (!skip_prefix(end
, " ", &str
)) {
848 rc
= error(_("invalid Date line"));
853 tz
= strtol(str
, &end
, 10);
855 rc
= error(_("invalid timezone offset"));
860 rc
= error(_("invalid Date line"));
865 * mercurial's timezone is in seconds west of UTC,
866 * however git's timezone is in hours + minutes east of
869 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
873 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
874 } else if (starts_with(sb
.buf
, "# ")) {
877 fprintf(out
, "\n%s\n", sb
.buf
);
883 while (strbuf_fread(&sb
, 8192, in
) > 0) {
884 fwrite(sb
.buf
, 1, sb
.len
, out
);
893 * Splits a list of files/directories into individual email patches. Each path
894 * in `paths` must be a file/directory that is formatted according to
897 * Once split out, the individual email patches will be stored in the state
898 * directory, with each patch's filename being its index, padded to state->prec
901 * state->cur will be set to the index of the first mail, and state->last will
902 * be set to the index of the last mail.
904 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
905 * to disable this behavior, -1 to use the default configured setting.
907 * Returns 0 on success, -1 on failure.
909 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
910 const char **paths
, int keep_cr
)
914 git_config_get_bool("am.keepcr", &keep_cr
);
917 switch (patch_format
) {
918 case PATCH_FORMAT_MBOX
:
919 return split_mail_mbox(state
, paths
, keep_cr
, 0);
920 case PATCH_FORMAT_STGIT
:
921 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
922 case PATCH_FORMAT_STGIT_SERIES
:
923 return split_mail_stgit_series(state
, paths
, keep_cr
);
924 case PATCH_FORMAT_HG
:
925 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
926 case PATCH_FORMAT_MBOXRD
:
927 return split_mail_mbox(state
, paths
, keep_cr
, 1);
929 BUG("invalid patch_format");
935 * Setup a new am session for applying patches
937 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
938 const char **paths
, int keep_cr
)
940 struct object_id curr_head
;
942 struct strbuf sb
= STRBUF_INIT
;
945 patch_format
= detect_patch_format(paths
);
948 fprintf_ln(stderr
, _("Patch format detection failed."));
952 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
953 die_errno(_("failed to create directory '%s'"), state
->dir
);
954 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
956 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
958 die(_("Failed to split patches."));
964 write_state_bool(state
, "threeway", state
->threeway
);
965 write_state_bool(state
, "quiet", state
->quiet
);
966 write_state_bool(state
, "sign", state
->signoff
);
967 write_state_bool(state
, "utf8", state
->utf8
);
969 if (state
->allow_rerere_autoupdate
)
970 write_state_bool(state
, "rerere-autoupdate",
971 state
->allow_rerere_autoupdate
== RERERE_AUTOUPDATE
);
973 switch (state
->keep
) {
984 BUG("invalid value for state->keep");
987 write_state_text(state
, "keep", str
);
988 write_state_bool(state
, "messageid", state
->message_id
);
990 switch (state
->scissors
) {
1001 BUG("invalid value for state->scissors");
1003 write_state_text(state
, "scissors", str
);
1005 sq_quote_argv(&sb
, state
->git_apply_opts
.argv
);
1006 write_state_text(state
, "apply-opt", sb
.buf
);
1008 if (state
->rebasing
)
1009 write_state_text(state
, "rebasing", "");
1011 write_state_text(state
, "applying", "");
1013 if (!get_oid("HEAD", &curr_head
)) {
1014 write_state_text(state
, "abort-safety", oid_to_hex(&curr_head
));
1015 if (!state
->rebasing
)
1016 update_ref("am", "ORIG_HEAD", &curr_head
, NULL
, 0,
1017 UPDATE_REFS_DIE_ON_ERR
);
1019 write_state_text(state
, "abort-safety", "");
1020 if (!state
->rebasing
)
1021 delete_ref(NULL
, "ORIG_HEAD", NULL
, 0);
1025 * NOTE: Since the "next" and "last" files determine if an am_state
1026 * session is in progress, they should be written last.
1029 write_state_count(state
, "next", state
->cur
);
1030 write_state_count(state
, "last", state
->last
);
1032 strbuf_release(&sb
);
1036 * Increments the patch pointer, and cleans am_state for the application of the
1039 static void am_next(struct am_state
*state
)
1041 struct object_id head
;
1043 FREE_AND_NULL(state
->author_name
);
1044 FREE_AND_NULL(state
->author_email
);
1045 FREE_AND_NULL(state
->author_date
);
1046 FREE_AND_NULL(state
->msg
);
1049 unlink(am_path(state
, "author-script"));
1050 unlink(am_path(state
, "final-commit"));
1052 oidclr(&state
->orig_commit
);
1053 unlink(am_path(state
, "original-commit"));
1054 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
1056 if (!get_oid("HEAD", &head
))
1057 write_state_text(state
, "abort-safety", oid_to_hex(&head
));
1059 write_state_text(state
, "abort-safety", "");
1062 write_state_count(state
, "next", state
->cur
);
1066 * Returns the filename of the current patch email.
1068 static const char *msgnum(const struct am_state
*state
)
1070 static struct strbuf sb
= STRBUF_INIT
;
1073 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1079 * Dies with a user-friendly message on how to proceed after resolving the
1080 * problem. This message can be overridden with state->resolvemsg.
1082 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1084 if (state
->resolvemsg
) {
1085 printf_ln("%s", state
->resolvemsg
);
1087 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1089 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1090 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1091 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1098 * Appends signoff to the "msg" field of the am_state.
1100 static void am_append_signoff(struct am_state
*state
)
1102 struct strbuf sb
= STRBUF_INIT
;
1104 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1105 append_signoff(&sb
, 0, 0);
1106 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1110 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1111 * state->msg will be set to the patch message. state->author_name,
1112 * state->author_email and state->author_date will be set to the patch author's
1113 * name, email and date respectively. The patch body will be written to the
1114 * state directory's "patch" file.
1116 * Returns 1 if the patch should be skipped, 0 otherwise.
1118 static int parse_mail(struct am_state
*state
, const char *mail
)
1121 struct strbuf sb
= STRBUF_INIT
;
1122 struct strbuf msg
= STRBUF_INIT
;
1123 struct strbuf author_name
= STRBUF_INIT
;
1124 struct strbuf author_date
= STRBUF_INIT
;
1125 struct strbuf author_email
= STRBUF_INIT
;
1129 setup_mailinfo(&mi
);
1132 mi
.metainfo_charset
= get_commit_output_encoding();
1134 mi
.metainfo_charset
= NULL
;
1136 switch (state
->keep
) {
1140 mi
.keep_subject
= 1;
1142 case KEEP_NON_PATCH
:
1143 mi
.keep_non_patch_brackets_in_subject
= 1;
1146 BUG("invalid value for state->keep");
1149 if (state
->message_id
)
1150 mi
.add_message_id
= 1;
1152 switch (state
->scissors
) {
1153 case SCISSORS_UNSET
:
1155 case SCISSORS_FALSE
:
1156 mi
.use_scissors
= 0;
1159 mi
.use_scissors
= 1;
1162 BUG("invalid value for state->scissors");
1165 mi
.input
= xfopen(mail
, "r");
1166 mi
.output
= xfopen(am_path(state
, "info"), "w");
1167 if (mailinfo(&mi
, am_path(state
, "msg"), am_path(state
, "patch")))
1168 die("could not parse patch");
1173 if (mi
.format_flowed
)
1174 warning(_("Patch sent with format=flowed; "
1175 "space at the end of lines might be lost."));
1177 /* Extract message and author information */
1178 fp
= xfopen(am_path(state
, "info"), "r");
1179 while (!strbuf_getline_lf(&sb
, fp
)) {
1182 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1184 strbuf_addch(&msg
, '\n');
1185 strbuf_addstr(&msg
, x
);
1186 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1187 strbuf_addstr(&author_name
, x
);
1188 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1189 strbuf_addstr(&author_email
, x
);
1190 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1191 strbuf_addstr(&author_date
, x
);
1195 /* Skip pine's internal folder data */
1196 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1201 if (is_empty_or_missing_file(am_path(state
, "patch"))) {
1202 printf_ln(_("Patch is empty."));
1203 die_user_resolve(state
);
1206 strbuf_addstr(&msg
, "\n\n");
1207 strbuf_addbuf(&msg
, &mi
.log_message
);
1208 strbuf_stripspace(&msg
, 0);
1210 assert(!state
->author_name
);
1211 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1213 assert(!state
->author_email
);
1214 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1216 assert(!state
->author_date
);
1217 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1219 assert(!state
->msg
);
1220 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1223 strbuf_release(&msg
);
1224 strbuf_release(&author_date
);
1225 strbuf_release(&author_email
);
1226 strbuf_release(&author_name
);
1227 strbuf_release(&sb
);
1228 clear_mailinfo(&mi
);
1233 * Sets commit_id to the commit hash where the mail was generated from.
1234 * Returns 0 on success, -1 on failure.
1236 static int get_mail_commit_oid(struct object_id
*commit_id
, const char *mail
)
1238 struct strbuf sb
= STRBUF_INIT
;
1239 FILE *fp
= xfopen(mail
, "r");
1243 if (strbuf_getline_lf(&sb
, fp
) ||
1244 !skip_prefix(sb
.buf
, "From ", &x
) ||
1245 get_oid_hex(x
, commit_id
) < 0)
1248 strbuf_release(&sb
);
1254 * Sets state->msg, state->author_name, state->author_email, state->author_date
1255 * to the commit's respective info.
1257 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1259 const char *buffer
, *ident_line
, *msg
;
1261 struct ident_split id
;
1263 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1265 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1267 die(_("missing author line in commit %s"),
1268 oid_to_hex(&commit
->object
.oid
));
1269 if (split_ident_line(&id
, ident_line
, ident_len
) < 0)
1270 die(_("invalid ident line: %.*s"), (int)ident_len
, ident_line
);
1272 assert(!state
->author_name
);
1274 state
->author_name
=
1275 xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1277 state
->author_name
= xstrdup("");
1279 assert(!state
->author_email
);
1281 state
->author_email
=
1282 xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1284 state
->author_email
= xstrdup("");
1286 assert(!state
->author_date
);
1287 state
->author_date
= xstrdup(show_ident_date(&id
, DATE_MODE(NORMAL
)));
1289 assert(!state
->msg
);
1290 msg
= strstr(buffer
, "\n\n");
1292 die(_("unable to parse commit %s"), oid_to_hex(&commit
->object
.oid
));
1293 state
->msg
= xstrdup(msg
+ 2);
1294 state
->msg_len
= strlen(state
->msg
);
1295 unuse_commit_buffer(commit
, buffer
);
1299 * Writes `commit` as a patch to the state directory's "patch" file.
1301 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1303 struct rev_info rev_info
;
1306 fp
= xfopen(am_path(state
, "patch"), "w");
1307 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1309 rev_info
.abbrev
= 0;
1310 rev_info
.disable_stdin
= 1;
1311 rev_info
.show_root_diff
= 1;
1312 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1313 rev_info
.no_commit_id
= 1;
1314 rev_info
.diffopt
.flags
.binary
= 1;
1315 rev_info
.diffopt
.flags
.full_index
= 1;
1316 rev_info
.diffopt
.use_color
= 0;
1317 rev_info
.diffopt
.file
= fp
;
1318 rev_info
.diffopt
.close_file
= 1;
1319 add_pending_object(&rev_info
, &commit
->object
, "");
1320 diff_setup_done(&rev_info
.diffopt
);
1321 log_tree_commit(&rev_info
, commit
);
1325 * Writes the diff of the index against HEAD as a patch to the state
1326 * directory's "patch" file.
1328 static void write_index_patch(const struct am_state
*state
)
1331 struct object_id head
;
1332 struct rev_info rev_info
;
1335 if (!get_oid("HEAD", &head
)) {
1336 struct commit
*commit
= lookup_commit_or_die(&head
, "HEAD");
1337 tree
= get_commit_tree(commit
);
1339 tree
= lookup_tree(the_repository
,
1340 the_repository
->hash_algo
->empty_tree
);
1342 fp
= xfopen(am_path(state
, "patch"), "w");
1343 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1345 rev_info
.disable_stdin
= 1;
1346 rev_info
.no_commit_id
= 1;
1347 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1348 rev_info
.diffopt
.use_color
= 0;
1349 rev_info
.diffopt
.file
= fp
;
1350 rev_info
.diffopt
.close_file
= 1;
1351 add_pending_object(&rev_info
, &tree
->object
, "");
1352 diff_setup_done(&rev_info
.diffopt
);
1353 run_diff_index(&rev_info
, 1);
1357 * Like parse_mail(), but parses the mail by looking up its commit ID
1358 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1361 * state->orig_commit will be set to the original commit ID.
1363 * Will always return 0 as the patch should never be skipped.
1365 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1367 struct commit
*commit
;
1368 struct object_id commit_oid
;
1370 if (get_mail_commit_oid(&commit_oid
, mail
) < 0)
1371 die(_("could not parse %s"), mail
);
1373 commit
= lookup_commit_or_die(&commit_oid
, mail
);
1375 get_commit_info(state
, commit
);
1377 write_commit_patch(state
, commit
);
1379 oidcpy(&state
->orig_commit
, &commit_oid
);
1380 write_state_text(state
, "original-commit", oid_to_hex(&commit_oid
));
1381 update_ref("am", "REBASE_HEAD", &commit_oid
,
1382 NULL
, REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1388 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1389 * `index_file` is not NULL, the patch will be applied to that index.
1391 static int run_apply(const struct am_state
*state
, const char *index_file
)
1393 struct argv_array apply_paths
= ARGV_ARRAY_INIT
;
1394 struct argv_array apply_opts
= ARGV_ARRAY_INIT
;
1395 struct apply_state apply_state
;
1397 int force_apply
= 0;
1400 if (init_apply_state(&apply_state
, the_repository
, NULL
))
1401 BUG("init_apply_state() failed");
1403 argv_array_push(&apply_opts
, "apply");
1404 argv_array_pushv(&apply_opts
, state
->git_apply_opts
.argv
);
1406 opts_left
= apply_parse_options(apply_opts
.argc
, apply_opts
.argv
,
1407 &apply_state
, &force_apply
, &options
,
1411 die("unknown option passed through to git apply");
1414 apply_state
.index_file
= index_file
;
1415 apply_state
.cached
= 1;
1417 apply_state
.check_index
= 1;
1420 * If we are allowed to fall back on 3-way merge, don't give false
1421 * errors during the initial attempt.
1423 if (state
->threeway
&& !index_file
)
1424 apply_state
.apply_verbosity
= verbosity_silent
;
1426 if (check_apply_state(&apply_state
, force_apply
))
1427 BUG("check_apply_state() failed");
1429 argv_array_push(&apply_paths
, am_path(state
, "patch"));
1431 res
= apply_all_patches(&apply_state
, apply_paths
.argc
, apply_paths
.argv
, options
);
1433 argv_array_clear(&apply_paths
);
1434 argv_array_clear(&apply_opts
);
1435 clear_apply_state(&apply_state
);
1441 /* Reload index as apply_all_patches() will have modified it. */
1443 read_cache_from(index_file
);
1450 * Builds an index that contains just the blobs needed for a 3way merge.
1452 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1454 struct child_process cp
= CHILD_PROCESS_INIT
;
1457 argv_array_push(&cp
.args
, "apply");
1458 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1459 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1460 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1462 if (run_command(&cp
))
1469 * Attempt a threeway merge, using index_path as the temporary index.
1471 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1473 struct object_id orig_tree
, their_tree
, our_tree
;
1474 const struct object_id
*bases
[1] = { &orig_tree
};
1475 struct merge_options o
;
1476 struct commit
*result
;
1477 char *their_tree_name
;
1479 if (get_oid("HEAD", &our_tree
) < 0)
1480 oidcpy(&our_tree
, the_hash_algo
->empty_tree
);
1482 if (build_fake_ancestor(state
, index_path
))
1483 return error("could not build fake ancestor");
1486 read_cache_from(index_path
);
1488 if (write_index_as_tree(&orig_tree
, &the_index
, index_path
, 0, NULL
))
1489 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1491 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1493 if (!state
->quiet
) {
1495 * List paths that needed 3-way fallback, so that the user can
1496 * review them with extra care to spot mismerges.
1498 struct rev_info rev_info
;
1500 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1501 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1502 rev_info
.diffopt
.filter
|= diff_filter_bit('A');
1503 rev_info
.diffopt
.filter
|= diff_filter_bit('M');
1504 add_pending_oid(&rev_info
, "HEAD", &our_tree
, 0);
1505 diff_setup_done(&rev_info
.diffopt
);
1506 run_diff_index(&rev_info
, 1);
1509 if (run_apply(state
, index_path
))
1510 return error(_("Did you hand edit your patch?\n"
1511 "It does not apply to blobs recorded in its index."));
1513 if (write_index_as_tree(&their_tree
, &the_index
, index_path
, 0, NULL
))
1514 return error("could not write tree");
1516 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1522 * This is not so wrong. Depending on which base we picked, orig_tree
1523 * may be wildly different from ours, but their_tree has the same set of
1524 * wildly different changes in parts the patch did not touch, so
1525 * recursive ends up canceling them, saying that we reverted all those
1529 init_merge_options(&o
, the_repository
);
1532 their_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1533 o
.branch2
= their_tree_name
;
1534 o
.detect_directory_renames
= MERGE_DIRECTORY_RENAMES_NONE
;
1539 if (merge_recursive_generic(&o
, &our_tree
, &their_tree
, 1, bases
, &result
)) {
1540 repo_rerere(the_repository
, state
->allow_rerere_autoupdate
);
1541 free(their_tree_name
);
1542 return error(_("Failed to merge in the changes."));
1545 free(their_tree_name
);
1550 * Commits the current index with state->msg as the commit message and
1551 * state->author_name, state->author_email and state->author_date as the author
1554 static void do_commit(const struct am_state
*state
)
1556 struct object_id tree
, parent
, commit
;
1557 const struct object_id
*old_oid
;
1558 struct commit_list
*parents
= NULL
;
1559 const char *reflog_msg
, *author
;
1560 struct strbuf sb
= STRBUF_INIT
;
1562 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1565 if (write_cache_as_tree(&tree
, 0, NULL
))
1566 die(_("git write-tree failed to write a tree"));
1568 if (!get_oid_commit("HEAD", &parent
)) {
1570 commit_list_insert(lookup_commit(the_repository
, &parent
),
1574 say(state
, stderr
, _("applying to an empty history"));
1577 author
= fmt_ident(state
->author_name
, state
->author_email
,
1579 state
->ignore_date
? NULL
: state
->author_date
,
1582 if (state
->committer_date_is_author_date
)
1583 setenv("GIT_COMMITTER_DATE",
1584 state
->ignore_date
? "" : state
->author_date
, 1);
1586 if (commit_tree(state
->msg
, state
->msg_len
, &tree
, parents
, &commit
,
1587 author
, state
->sign_commit
))
1588 die(_("failed to write commit object"));
1590 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1594 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1597 update_ref(sb
.buf
, "HEAD", &commit
, old_oid
, 0,
1598 UPDATE_REFS_DIE_ON_ERR
);
1600 if (state
->rebasing
) {
1601 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1603 assert(!is_null_oid(&state
->orig_commit
));
1604 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
1605 fprintf(fp
, "%s\n", oid_to_hex(&commit
));
1609 run_hook_le(NULL
, "post-applypatch", NULL
);
1611 strbuf_release(&sb
);
1615 * Validates the am_state for resuming -- the "msg" and authorship fields must
1618 static void validate_resume_state(const struct am_state
*state
)
1621 die(_("cannot resume: %s does not exist."),
1622 am_path(state
, "final-commit"));
1624 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1625 die(_("cannot resume: %s does not exist."),
1626 am_path(state
, "author-script"));
1630 * Interactively prompt the user on whether the current patch should be
1633 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1636 static int do_interactive(struct am_state
*state
)
1643 puts(_("Commit Body is:"));
1644 puts("--------------------------");
1645 printf("%s", state
->msg
);
1646 puts("--------------------------");
1649 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1650 * in your translation. The program will only accept English
1651 * input at this point.
1653 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1654 if (!fgets(reply
, sizeof(reply
), stdin
))
1655 die("unable to read from stdin; aborting");
1657 if (*reply
== 'y' || *reply
== 'Y') {
1659 } else if (*reply
== 'a' || *reply
== 'A') {
1660 state
->interactive
= 0;
1662 } else if (*reply
== 'n' || *reply
== 'N') {
1664 } else if (*reply
== 'e' || *reply
== 'E') {
1665 struct strbuf msg
= STRBUF_INIT
;
1667 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1669 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1671 strbuf_release(&msg
);
1672 } else if (*reply
== 'v' || *reply
== 'V') {
1673 const char *pager
= git_pager(1);
1674 struct child_process cp
= CHILD_PROCESS_INIT
;
1678 prepare_pager_args(&cp
, pager
);
1679 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1686 * Applies all queued mail.
1688 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1689 * well as the state directory's "patch" file is used as-is for applying the
1690 * patch and committing it.
1692 static void am_run(struct am_state
*state
, int resume
)
1694 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1695 struct strbuf sb
= STRBUF_INIT
;
1697 unlink(am_path(state
, "dirtyindex"));
1699 if (refresh_and_write_cache(REFRESH_QUIET
, 0, 0) < 0)
1700 die(_("unable to write index file"));
1702 if (repo_index_has_changes(the_repository
, NULL
, &sb
)) {
1703 write_state_bool(state
, "dirtyindex", 1);
1704 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1707 strbuf_release(&sb
);
1709 while (state
->cur
<= state
->last
) {
1710 const char *mail
= am_path(state
, msgnum(state
));
1715 if (!file_exists(mail
))
1719 validate_resume_state(state
);
1723 if (state
->rebasing
)
1724 skip
= parse_mail_rebase(state
, mail
);
1726 skip
= parse_mail(state
, mail
);
1729 goto next
; /* mail should be skipped */
1732 am_append_signoff(state
);
1734 write_author_script(state
);
1735 write_commit_msg(state
);
1738 if (state
->interactive
&& do_interactive(state
))
1741 if (run_applypatch_msg_hook(state
))
1744 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1746 apply_status
= run_apply(state
, NULL
);
1748 if (apply_status
&& state
->threeway
) {
1749 struct strbuf sb
= STRBUF_INIT
;
1751 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1752 apply_status
= fall_back_threeway(state
, sb
.buf
);
1753 strbuf_release(&sb
);
1756 * Applying the patch to an earlier tree and merging
1757 * the result may have produced the same tree as ours.
1759 if (!apply_status
&&
1760 !repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1761 say(state
, stdout
, _("No changes -- Patch already applied."));
1767 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1768 linelen(state
->msg
), state
->msg
);
1770 if (advice_amworkdir
)
1771 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1773 die_user_resolve(state
);
1786 if (!is_empty_or_missing_file(am_path(state
, "rewritten"))) {
1787 assert(state
->rebasing
);
1788 copy_notes_for_rebase(state
);
1789 run_post_rewrite_hook(state
);
1793 * In rebasing mode, it's up to the caller to take care of
1796 if (!state
->rebasing
) {
1798 close_object_store(the_repository
->objects
);
1799 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1804 * Resume the current am session after patch application failure. The user did
1805 * all the hard work, and we do not have to do any patch application. Just
1806 * trust and commit what the user has in the index and working tree.
1808 static void am_resolve(struct am_state
*state
)
1810 validate_resume_state(state
);
1812 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1814 if (!repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1815 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1816 "If there is nothing left to stage, chances are that something else\n"
1817 "already introduced the same changes; you might want to skip this patch."));
1818 die_user_resolve(state
);
1821 if (unmerged_cache()) {
1822 printf_ln(_("You still have unmerged paths in your index.\n"
1823 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1824 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1825 die_user_resolve(state
);
1828 if (state
->interactive
) {
1829 write_index_patch(state
);
1830 if (do_interactive(state
))
1834 repo_rerere(the_repository
, 0);
1845 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1846 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1849 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1851 struct lock_file lock_file
= LOCK_INIT
;
1852 struct unpack_trees_options opts
;
1853 struct tree_desc t
[2];
1855 if (parse_tree(head
) || parse_tree(remote
))
1858 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1860 refresh_cache(REFRESH_QUIET
);
1862 memset(&opts
, 0, sizeof(opts
));
1864 opts
.src_index
= &the_index
;
1865 opts
.dst_index
= &the_index
;
1869 opts
.fn
= twoway_merge
;
1870 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1871 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1873 if (unpack_trees(2, t
, &opts
)) {
1874 rollback_lock_file(&lock_file
);
1878 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1879 die(_("unable to write new index file"));
1885 * Merges a tree into the index. The index's stat info will take precedence
1886 * over the merged tree's. Returns 0 on success, -1 on failure.
1888 static int merge_tree(struct tree
*tree
)
1890 struct lock_file lock_file
= LOCK_INIT
;
1891 struct unpack_trees_options opts
;
1892 struct tree_desc t
[1];
1894 if (parse_tree(tree
))
1897 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1899 memset(&opts
, 0, sizeof(opts
));
1901 opts
.src_index
= &the_index
;
1902 opts
.dst_index
= &the_index
;
1904 opts
.fn
= oneway_merge
;
1905 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
1907 if (unpack_trees(1, t
, &opts
)) {
1908 rollback_lock_file(&lock_file
);
1912 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1913 die(_("unable to write new index file"));
1919 * Clean the index without touching entries that are not modified between
1920 * `head` and `remote`.
1922 static int clean_index(const struct object_id
*head
, const struct object_id
*remote
)
1924 struct tree
*head_tree
, *remote_tree
, *index_tree
;
1925 struct object_id index
;
1927 head_tree
= parse_tree_indirect(head
);
1929 return error(_("Could not parse object '%s'."), oid_to_hex(head
));
1931 remote_tree
= parse_tree_indirect(remote
);
1933 return error(_("Could not parse object '%s'."), oid_to_hex(remote
));
1935 read_cache_unmerged();
1937 if (fast_forward_to(head_tree
, head_tree
, 1))
1940 if (write_cache_as_tree(&index
, 0, NULL
))
1943 index_tree
= parse_tree_indirect(&index
);
1945 return error(_("Could not parse object '%s'."), oid_to_hex(&index
));
1947 if (fast_forward_to(index_tree
, remote_tree
, 0))
1950 if (merge_tree(remote_tree
))
1953 remove_branch_state(the_repository
, 0);
1959 * Resets rerere's merge resolution metadata.
1961 static void am_rerere_clear(void)
1963 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
1964 rerere_clear(the_repository
, &merge_rr
);
1965 string_list_clear(&merge_rr
, 1);
1969 * Resume the current am session by skipping the current patch.
1971 static void am_skip(struct am_state
*state
)
1973 struct object_id head
;
1977 if (get_oid("HEAD", &head
))
1978 oidcpy(&head
, the_hash_algo
->empty_tree
);
1980 if (clean_index(&head
, &head
))
1981 die(_("failed to clean index"));
1983 if (state
->rebasing
) {
1984 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1986 assert(!is_null_oid(&state
->orig_commit
));
1987 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
1988 fprintf(fp
, "%s\n", oid_to_hex(&head
));
1998 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2000 * It is not safe to reset HEAD when:
2001 * 1. git-am previously failed because the index was dirty.
2002 * 2. HEAD has moved since git-am previously failed.
2004 static int safe_to_abort(const struct am_state
*state
)
2006 struct strbuf sb
= STRBUF_INIT
;
2007 struct object_id abort_safety
, head
;
2009 if (file_exists(am_path(state
, "dirtyindex")))
2012 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2013 if (get_oid_hex(sb
.buf
, &abort_safety
))
2014 die(_("could not parse %s"), am_path(state
, "abort-safety"));
2016 oidclr(&abort_safety
);
2017 strbuf_release(&sb
);
2019 if (get_oid("HEAD", &head
))
2022 if (oideq(&head
, &abort_safety
))
2025 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2026 "Not rewinding to ORIG_HEAD"));
2032 * Aborts the current am session if it is safe to do so.
2034 static void am_abort(struct am_state
*state
)
2036 struct object_id curr_head
, orig_head
;
2037 int has_curr_head
, has_orig_head
;
2040 if (!safe_to_abort(state
)) {
2047 curr_branch
= resolve_refdup("HEAD", 0, &curr_head
, NULL
);
2048 has_curr_head
= curr_branch
&& !is_null_oid(&curr_head
);
2050 oidcpy(&curr_head
, the_hash_algo
->empty_tree
);
2052 has_orig_head
= !get_oid("ORIG_HEAD", &orig_head
);
2054 oidcpy(&orig_head
, the_hash_algo
->empty_tree
);
2056 clean_index(&curr_head
, &orig_head
);
2059 update_ref("am --abort", "HEAD", &orig_head
,
2060 has_curr_head
? &curr_head
: NULL
, 0,
2061 UPDATE_REFS_DIE_ON_ERR
);
2062 else if (curr_branch
)
2063 delete_ref(NULL
, curr_branch
, NULL
, REF_NO_DEREF
);
2069 static int show_patch(struct am_state
*state
, enum show_patch_type sub_mode
)
2071 struct strbuf sb
= STRBUF_INIT
;
2072 const char *patch_path
;
2075 if (!is_null_oid(&state
->orig_commit
)) {
2076 const char *av
[4] = { "show", NULL
, "--", NULL
};
2080 av
[1] = new_oid_str
= xstrdup(oid_to_hex(&state
->orig_commit
));
2081 ret
= run_command_v_opt(av
, RUN_GIT_CMD
);
2087 case SHOW_PATCH_RAW
:
2088 patch_path
= am_path(state
, msgnum(state
));
2090 case SHOW_PATCH_DIFF
:
2091 patch_path
= am_path(state
, "patch");
2094 BUG("invalid mode for --show-current-patch");
2097 len
= strbuf_read_file(&sb
, patch_path
, 0);
2099 die_errno(_("failed to read '%s'"), patch_path
);
2102 write_in_full(1, sb
.buf
, sb
.len
);
2103 strbuf_release(&sb
);
2108 * parse_options() callback that validates and sets opt->value to the
2109 * PATCH_FORMAT_* enum value corresponding to `arg`.
2111 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2113 int *opt_value
= opt
->value
;
2116 *opt_value
= PATCH_FORMAT_UNKNOWN
;
2117 else if (!strcmp(arg
, "mbox"))
2118 *opt_value
= PATCH_FORMAT_MBOX
;
2119 else if (!strcmp(arg
, "stgit"))
2120 *opt_value
= PATCH_FORMAT_STGIT
;
2121 else if (!strcmp(arg
, "stgit-series"))
2122 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2123 else if (!strcmp(arg
, "hg"))
2124 *opt_value
= PATCH_FORMAT_HG
;
2125 else if (!strcmp(arg
, "mboxrd"))
2126 *opt_value
= PATCH_FORMAT_MBOXRD
;
2128 * Please update $__git_patchformat in git-completion.bash
2129 * when you add new options
2132 return error(_("Invalid value for --patch-format: %s"), arg
);
2146 struct resume_mode
{
2147 enum resume_type mode
;
2148 enum show_patch_type sub_mode
;
2151 static int parse_opt_show_current_patch(const struct option
*opt
, const char *arg
, int unset
)
2153 int *opt_value
= opt
->value
;
2154 struct resume_mode
*resume
= container_of(opt_value
, struct resume_mode
, mode
);
2157 * Please update $__git_showcurrentpatch in git-completion.bash
2158 * when you add new options
2160 const char *valid_modes
[] = {
2161 [SHOW_PATCH_DIFF
] = "diff",
2162 [SHOW_PATCH_RAW
] = "raw"
2164 int new_value
= SHOW_PATCH_RAW
;
2167 for (new_value
= 0; new_value
< ARRAY_SIZE(valid_modes
); new_value
++) {
2168 if (!strcmp(arg
, valid_modes
[new_value
]))
2171 if (new_value
>= ARRAY_SIZE(valid_modes
))
2172 return error(_("Invalid value for --show-current-patch: %s"), arg
);
2175 if (resume
->mode
== RESUME_SHOW_PATCH
&& new_value
!= resume
->sub_mode
)
2176 return error(_("--show-current-patch=%s is incompatible with "
2177 "--show-current-patch=%s"),
2178 arg
, valid_modes
[resume
->sub_mode
]);
2180 resume
->mode
= RESUME_SHOW_PATCH
;
2181 resume
->sub_mode
= new_value
;
2185 static int git_am_config(const char *k
, const char *v
, void *cb
)
2189 status
= git_gpg_config(k
, v
, NULL
);
2193 return git_default_config(k
, v
, NULL
);
2196 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2198 struct am_state state
;
2201 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2202 struct resume_mode resume
= { .mode
= RESUME_FALSE
};
2206 const char * const usage
[] = {
2207 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2208 N_("git am [<options>] (--continue | --skip | --abort)"),
2212 struct option options
[] = {
2213 OPT_BOOL('i', "interactive", &state
.interactive
,
2214 N_("run interactively")),
2215 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2216 N_("historical option -- no-op")),
2217 OPT_BOOL('3', "3way", &state
.threeway
,
2218 N_("allow fall back on 3way merging if needed")),
2219 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2220 OPT_SET_INT('s', "signoff", &state
.signoff
,
2221 N_("add a Signed-off-by line to the commit message"),
2223 OPT_BOOL('u', "utf8", &state
.utf8
,
2224 N_("recode into utf8 (default)")),
2225 OPT_SET_INT('k', "keep", &state
.keep
,
2226 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2227 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2228 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2229 OPT_BOOL('m', "message-id", &state
.message_id
,
2230 N_("pass -m flag to git-mailinfo")),
2231 OPT_SET_INT_F(0, "keep-cr", &keep_cr
,
2232 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2233 1, PARSE_OPT_NONEG
),
2234 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr
,
2235 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2236 0, PARSE_OPT_NONEG
),
2237 OPT_BOOL('c', "scissors", &state
.scissors
,
2238 N_("strip everything before a scissors line")),
2239 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2240 N_("pass it through git-apply"),
2242 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2243 N_("pass it through git-apply"),
2245 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2246 N_("pass it through git-apply"),
2248 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2249 N_("pass it through git-apply"),
2251 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2252 N_("pass it through git-apply"),
2254 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2255 N_("pass it through git-apply"),
2257 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2258 N_("pass it through git-apply"),
2260 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2261 N_("pass it through git-apply"),
2263 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2264 N_("format the patch(es) are in"),
2265 parse_opt_patchformat
),
2266 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2267 N_("pass it through git-apply"),
2269 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2270 N_("override error message when patch failure occurs")),
2271 OPT_CMDMODE(0, "continue", &resume
.mode
,
2272 N_("continue applying patches after resolving a conflict"),
2274 OPT_CMDMODE('r', "resolved", &resume
.mode
,
2275 N_("synonyms for --continue"),
2277 OPT_CMDMODE(0, "skip", &resume
.mode
,
2278 N_("skip the current patch"),
2280 OPT_CMDMODE(0, "abort", &resume
.mode
,
2281 N_("restore the original branch and abort the patching operation."),
2283 OPT_CMDMODE(0, "quit", &resume
.mode
,
2284 N_("abort the patching operation but keep HEAD where it is."),
2286 { OPTION_CALLBACK
, 0, "show-current-patch", &resume
.mode
,
2288 N_("show the patch being applied"),
2289 PARSE_OPT_CMDMODE
| PARSE_OPT_OPTARG
| PARSE_OPT_NONEG
| PARSE_OPT_LITERAL_ARGHELP
,
2290 parse_opt_show_current_patch
, RESUME_SHOW_PATCH
},
2291 OPT_BOOL(0, "committer-date-is-author-date",
2292 &state
.committer_date_is_author_date
,
2293 N_("lie about committer date")),
2294 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2295 N_("use current timestamp for author date")),
2296 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2297 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2298 N_("GPG-sign commits"),
2299 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2300 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2301 N_("(internal use for git-rebase)")),
2305 if (argc
== 2 && !strcmp(argv
[1], "-h"))
2306 usage_with_options(usage
, options
);
2308 git_config(git_am_config
, NULL
);
2310 am_state_init(&state
);
2312 in_progress
= am_in_progress(&state
);
2316 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2319 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2320 "it will be removed. Please do not use it anymore."));
2322 /* Ensure a valid committer ident can be constructed */
2323 git_committer_info(IDENT_STRICT
);
2325 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
2326 die(_("failed to read the index"));
2330 * Catch user error to feed us patches when there is a session
2333 * 1. mbox path(s) are provided on the command-line.
2334 * 2. stdin is not a tty: the user is trying to feed us a patch
2335 * from standard input. This is somewhat unreliable -- stdin
2336 * could be /dev/null for example and the caller did not
2337 * intend to feed us a patch but wanted to continue
2340 if (argc
|| (resume
.mode
== RESUME_FALSE
&& !isatty(0)))
2341 die(_("previous rebase directory %s still exists but mbox given."),
2344 if (resume
.mode
== RESUME_FALSE
)
2345 resume
.mode
= RESUME_APPLY
;
2347 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2348 am_append_signoff(&state
);
2350 struct argv_array paths
= ARGV_ARRAY_INIT
;
2354 * Handle stray state directory in the independent-run case. In
2355 * the --rebasing case, it is up to the caller to take care of
2356 * stray directories.
2358 if (file_exists(state
.dir
) && !state
.rebasing
) {
2359 if (resume
.mode
== RESUME_ABORT
|| resume
.mode
== RESUME_QUIT
) {
2361 am_state_release(&state
);
2365 die(_("Stray %s directory found.\n"
2366 "Use \"git am --abort\" to remove it."),
2371 die(_("Resolve operation not in progress, we are not resuming."));
2373 for (i
= 0; i
< argc
; i
++) {
2374 if (is_absolute_path(argv
[i
]) || !prefix
)
2375 argv_array_push(&paths
, argv
[i
]);
2377 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2380 if (state
.interactive
&& !paths
.argc
)
2381 die(_("interactive mode requires patches on the command line"));
2383 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
2385 argv_array_clear(&paths
);
2388 switch (resume
.mode
) {
2395 case RESUME_RESOLVED
:
2408 case RESUME_SHOW_PATCH
:
2409 ret
= show_patch(&state
, resume
.sub_mode
);
2412 BUG("invalid resume value");
2415 am_state_release(&state
);