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"
18 #include "cache-tree.h"
23 #include "unpack-trees.h"
25 #include "sequencer.h"
27 #include "merge-recursive.h"
29 #include "notes-utils.h"
34 #include "string-list.h"
36 #include "repository.h"
39 * Returns the length of the first line of msg.
41 static int linelen(const char *msg
)
43 return strchrnul(msg
, '\n') - msg
;
47 * Returns true if `str` consists of only whitespace, false otherwise.
49 static int str_isspace(const char *str
)
59 PATCH_FORMAT_UNKNOWN
= 0,
62 PATCH_FORMAT_STGIT_SERIES
,
69 KEEP_TRUE
, /* pass -k flag to git-mailinfo */
70 KEEP_NON_PATCH
/* pass -b flag to git-mailinfo */
75 SCISSORS_FALSE
= 0, /* pass --no-scissors to git-mailinfo */
76 SCISSORS_TRUE
/* pass --scissors to git-mailinfo */
82 SIGNOFF_EXPLICIT
/* --signoff was set on the command-line */
85 enum show_patch_type
{
91 STOP_ON_EMPTY_COMMIT
= 0, /* output errors and stop in the middle of an am session */
92 DROP_EMPTY_COMMIT
, /* skip with a notice message, unless "--quiet" has been passed */
93 KEEP_EMPTY_COMMIT
, /* keep recording as empty commits */
97 /* state directory path */
100 /* current and last patch numbers, 1-indexed */
104 /* commit metadata and message */
111 /* when --rebasing, records the original commit the patch came from */
112 struct object_id orig_commit
;
114 /* number of digits in patch filename */
117 /* various operating modes and command line options */
121 int signoff
; /* enum signoff_type */
123 int keep
; /* enum keep_type */
125 int scissors
; /* enum scissors_type */
126 int quoted_cr
; /* enum quoted_cr_action */
127 int empty_type
; /* enum empty_action */
128 struct strvec git_apply_opts
;
129 const char *resolvemsg
;
130 int committer_date_is_author_date
;
132 int allow_rerere_autoupdate
;
133 const char *sign_commit
;
138 * Initializes am_state with the default values.
140 static void am_state_init(struct am_state
*state
)
144 memset(state
, 0, sizeof(*state
));
146 state
->dir
= git_pathdup("rebase-apply");
150 git_config_get_bool("am.threeway", &state
->threeway
);
154 git_config_get_bool("am.messageid", &state
->message_id
);
156 state
->scissors
= SCISSORS_UNSET
;
157 state
->quoted_cr
= quoted_cr_unset
;
159 strvec_init(&state
->git_apply_opts
);
161 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
162 state
->sign_commit
= gpgsign
? "" : NULL
;
166 * Releases memory allocated by an am_state.
168 static void am_state_release(struct am_state
*state
)
171 free(state
->author_name
);
172 free(state
->author_email
);
173 free(state
->author_date
);
175 strvec_clear(&state
->git_apply_opts
);
178 static int am_option_parse_quoted_cr(const struct option
*opt
,
179 const char *arg
, int unset
)
181 BUG_ON_OPT_NEG(unset
);
183 if (mailinfo_parse_quoted_cr_action(arg
, opt
->value
) != 0)
184 return error(_("bad action '%s' for '%s'"), arg
, "--quoted-cr");
188 static int am_option_parse_empty(const struct option
*opt
,
189 const char *arg
, int unset
)
191 int *opt_value
= opt
->value
;
193 BUG_ON_OPT_NEG(unset
);
195 if (!strcmp(arg
, "stop"))
196 *opt_value
= STOP_ON_EMPTY_COMMIT
;
197 else if (!strcmp(arg
, "drop"))
198 *opt_value
= DROP_EMPTY_COMMIT
;
199 else if (!strcmp(arg
, "keep"))
200 *opt_value
= KEEP_EMPTY_COMMIT
;
202 return error(_("Invalid value for --empty: %s"), arg
);
208 * Returns path relative to the am_state directory.
210 static inline const char *am_path(const struct am_state
*state
, const char *path
)
212 return mkpath("%s/%s", state
->dir
, path
);
216 * For convenience to call write_file()
218 static void write_state_text(const struct am_state
*state
,
219 const char *name
, const char *string
)
221 write_file(am_path(state
, name
), "%s", string
);
224 static void write_state_count(const struct am_state
*state
,
225 const char *name
, int value
)
227 write_file(am_path(state
, name
), "%d", value
);
230 static void write_state_bool(const struct am_state
*state
,
231 const char *name
, int value
)
233 write_state_text(state
, name
, value
? "t" : "f");
237 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
240 __attribute__((format (printf
, 3, 4)))
241 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
247 vfprintf(fp
, fmt
, ap
);
254 * Returns 1 if there is an am session in progress, 0 otherwise.
256 static int am_in_progress(const struct am_state
*state
)
260 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
262 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
264 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
270 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
271 * number of bytes read on success, -1 if the file does not exist. If `trim` is
272 * set, trailing whitespace will be removed.
274 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
275 const char *file
, int trim
)
279 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
289 die_errno(_("could not read '%s'"), am_path(state
, file
));
293 * Reads and parses the state directory's "author-script" file, and sets
294 * state->author_name, state->author_email and state->author_date accordingly.
295 * Returns 0 on success, -1 if the file could not be parsed.
297 * The author script is of the format:
299 * GIT_AUTHOR_NAME='$author_name'
300 * GIT_AUTHOR_EMAIL='$author_email'
301 * GIT_AUTHOR_DATE='$author_date'
303 * where $author_name, $author_email and $author_date are quoted. We are strict
304 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
305 * script, and thus if the file differs from what this function expects, it is
306 * better to bail out than to do something that the user does not expect.
308 static int read_am_author_script(struct am_state
*state
)
310 const char *filename
= am_path(state
, "author-script");
312 assert(!state
->author_name
);
313 assert(!state
->author_email
);
314 assert(!state
->author_date
);
316 return read_author_script(filename
, &state
->author_name
,
317 &state
->author_email
, &state
->author_date
, 1);
321 * Saves state->author_name, state->author_email and state->author_date in the
322 * state directory's "author-script" file.
324 static void write_author_script(const struct am_state
*state
)
326 struct strbuf sb
= STRBUF_INIT
;
328 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
329 sq_quote_buf(&sb
, state
->author_name
);
330 strbuf_addch(&sb
, '\n');
332 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
333 sq_quote_buf(&sb
, state
->author_email
);
334 strbuf_addch(&sb
, '\n');
336 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
337 sq_quote_buf(&sb
, state
->author_date
);
338 strbuf_addch(&sb
, '\n');
340 write_state_text(state
, "author-script", sb
.buf
);
346 * Reads the commit message from the state directory's "final-commit" file,
347 * setting state->msg to its contents and state->msg_len to the length of its
350 * Returns 0 on success, -1 if the file does not exist.
352 static int read_commit_msg(struct am_state
*state
)
354 struct strbuf sb
= STRBUF_INIT
;
358 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
363 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
368 * Saves state->msg in the state directory's "final-commit" file.
370 static void write_commit_msg(const struct am_state
*state
)
372 const char *filename
= am_path(state
, "final-commit");
373 write_file_buf(filename
, state
->msg
, state
->msg_len
);
377 * Loads state from disk.
379 static void am_load(struct am_state
*state
)
381 struct strbuf sb
= STRBUF_INIT
;
383 if (read_state_file(&sb
, state
, "next", 1) < 0)
384 BUG("state file 'next' does not exist");
385 state
->cur
= strtol(sb
.buf
, NULL
, 10);
387 if (read_state_file(&sb
, state
, "last", 1) < 0)
388 BUG("state file 'last' does not exist");
389 state
->last
= strtol(sb
.buf
, NULL
, 10);
391 if (read_am_author_script(state
) < 0)
392 die(_("could not parse author script"));
394 read_commit_msg(state
);
396 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
397 oidclr(&state
->orig_commit
);
398 else if (get_oid_hex(sb
.buf
, &state
->orig_commit
) < 0)
399 die(_("could not parse %s"), am_path(state
, "original-commit"));
401 read_state_file(&sb
, state
, "threeway", 1);
402 state
->threeway
= !strcmp(sb
.buf
, "t");
404 read_state_file(&sb
, state
, "quiet", 1);
405 state
->quiet
= !strcmp(sb
.buf
, "t");
407 read_state_file(&sb
, state
, "sign", 1);
408 state
->signoff
= !strcmp(sb
.buf
, "t");
410 read_state_file(&sb
, state
, "utf8", 1);
411 state
->utf8
= !strcmp(sb
.buf
, "t");
413 if (file_exists(am_path(state
, "rerere-autoupdate"))) {
414 read_state_file(&sb
, state
, "rerere-autoupdate", 1);
415 state
->allow_rerere_autoupdate
= strcmp(sb
.buf
, "t") ?
416 RERERE_NOAUTOUPDATE
: RERERE_AUTOUPDATE
;
418 state
->allow_rerere_autoupdate
= 0;
421 read_state_file(&sb
, state
, "keep", 1);
422 if (!strcmp(sb
.buf
, "t"))
423 state
->keep
= KEEP_TRUE
;
424 else if (!strcmp(sb
.buf
, "b"))
425 state
->keep
= KEEP_NON_PATCH
;
427 state
->keep
= KEEP_FALSE
;
429 read_state_file(&sb
, state
, "messageid", 1);
430 state
->message_id
= !strcmp(sb
.buf
, "t");
432 read_state_file(&sb
, state
, "scissors", 1);
433 if (!strcmp(sb
.buf
, "t"))
434 state
->scissors
= SCISSORS_TRUE
;
435 else if (!strcmp(sb
.buf
, "f"))
436 state
->scissors
= SCISSORS_FALSE
;
438 state
->scissors
= SCISSORS_UNSET
;
440 read_state_file(&sb
, state
, "quoted-cr", 1);
442 state
->quoted_cr
= quoted_cr_unset
;
443 else if (mailinfo_parse_quoted_cr_action(sb
.buf
, &state
->quoted_cr
) != 0)
444 die(_("could not parse %s"), am_path(state
, "quoted-cr"));
446 read_state_file(&sb
, state
, "apply-opt", 1);
447 strvec_clear(&state
->git_apply_opts
);
448 if (sq_dequote_to_strvec(sb
.buf
, &state
->git_apply_opts
) < 0)
449 die(_("could not parse %s"), am_path(state
, "apply-opt"));
451 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
457 * Removes the am_state directory, forcefully terminating the current am
460 static void am_destroy(const struct am_state
*state
)
462 struct strbuf sb
= STRBUF_INIT
;
464 strbuf_addstr(&sb
, state
->dir
);
465 remove_dir_recursively(&sb
, 0);
470 * Runs applypatch-msg hook. Returns its exit code.
472 static int run_applypatch_msg_hook(struct am_state
*state
)
477 ret
= run_hooks_l("applypatch-msg", am_path(state
, "final-commit"), NULL
);
480 FREE_AND_NULL(state
->msg
);
481 if (read_commit_msg(state
) < 0)
482 die(_("'%s' was deleted by the applypatch-msg hook"),
483 am_path(state
, "final-commit"));
490 * Runs post-rewrite hook. Returns it exit code.
492 static int run_post_rewrite_hook(const struct am_state
*state
)
494 struct child_process cp
= CHILD_PROCESS_INIT
;
495 const char *hook
= find_hook("post-rewrite");
501 strvec_push(&cp
.args
, hook
);
502 strvec_push(&cp
.args
, "rebase");
504 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
505 cp
.stdout_to_stderr
= 1;
506 cp
.trace2_hook_name
= "post-rewrite";
508 ret
= run_command(&cp
);
515 * Reads the state directory's "rewritten" file, and copies notes from the old
516 * commits listed in the file to their rewritten commits.
518 * Returns 0 on success, -1 on failure.
520 static int copy_notes_for_rebase(const struct am_state
*state
)
522 struct notes_rewrite_cfg
*c
;
523 struct strbuf sb
= STRBUF_INIT
;
524 const char *invalid_line
= _("Malformed input line: '%s'.");
525 const char *msg
= "Notes added by 'git rebase'";
529 assert(state
->rebasing
);
531 c
= init_copy_notes_for_rewrite("rebase");
535 fp
= xfopen(am_path(state
, "rewritten"), "r");
537 while (!strbuf_getline_lf(&sb
, fp
)) {
538 struct object_id from_obj
, to_obj
;
541 if (sb
.len
!= the_hash_algo
->hexsz
* 2 + 1) {
542 ret
= error(invalid_line
, sb
.buf
);
546 if (parse_oid_hex(sb
.buf
, &from_obj
, &p
)) {
547 ret
= error(invalid_line
, sb
.buf
);
552 ret
= error(invalid_line
, sb
.buf
);
556 if (get_oid_hex(p
+ 1, &to_obj
)) {
557 ret
= error(invalid_line
, sb
.buf
);
561 if (copy_note_for_rewrite(c
, &from_obj
, &to_obj
))
562 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
563 oid_to_hex(&from_obj
), oid_to_hex(&to_obj
));
567 finish_copy_notes_for_rewrite(the_repository
, c
, msg
);
574 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
575 * non-indented lines and checking if they look like they begin with valid
576 * header field names.
578 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
580 static int is_mail(FILE *fp
)
582 const char *header_regex
= "^[!-9;-~]+:";
583 struct strbuf sb
= STRBUF_INIT
;
587 if (fseek(fp
, 0L, SEEK_SET
))
588 die_errno(_("fseek failed"));
590 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
591 die("invalid pattern: %s", header_regex
);
593 while (!strbuf_getline(&sb
, fp
)) {
595 break; /* End of header */
597 /* Ignore indented folded lines */
598 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
601 /* It's a header if it matches header_regex */
602 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
615 * Attempts to detect the patch_format of the patches contained in `paths`,
616 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
619 static int detect_patch_format(const char **paths
)
621 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
622 struct strbuf l1
= STRBUF_INIT
;
623 struct strbuf l2
= STRBUF_INIT
;
624 struct strbuf l3
= STRBUF_INIT
;
628 * We default to mbox format if input is from stdin and for directories
630 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
631 return PATCH_FORMAT_MBOX
;
634 * Otherwise, check the first few lines of the first patch, starting
635 * from the first non-blank line, to try to detect its format.
638 fp
= xfopen(*paths
, "r");
640 while (!strbuf_getline(&l1
, fp
)) {
645 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
646 ret
= PATCH_FORMAT_MBOX
;
650 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
651 ret
= PATCH_FORMAT_STGIT_SERIES
;
655 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
656 ret
= PATCH_FORMAT_HG
;
660 strbuf_getline(&l2
, fp
);
661 strbuf_getline(&l3
, fp
);
664 * If the second line is empty and the third is a From, Author or Date
665 * entry, this is likely an StGit patch.
667 if (l1
.len
&& !l2
.len
&&
668 (starts_with(l3
.buf
, "From:") ||
669 starts_with(l3
.buf
, "Author:") ||
670 starts_with(l3
.buf
, "Date:"))) {
671 ret
= PATCH_FORMAT_STGIT
;
675 if (l1
.len
&& is_mail(fp
)) {
676 ret
= PATCH_FORMAT_MBOX
;
689 * Splits out individual email patches from `paths`, where each path is either
690 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
692 static int split_mail_mbox(struct am_state
*state
, const char **paths
,
693 int keep_cr
, int mboxrd
)
695 struct child_process cp
= CHILD_PROCESS_INIT
;
696 struct strbuf last
= STRBUF_INIT
;
700 strvec_push(&cp
.args
, "mailsplit");
701 strvec_pushf(&cp
.args
, "-d%d", state
->prec
);
702 strvec_pushf(&cp
.args
, "-o%s", state
->dir
);
703 strvec_push(&cp
.args
, "-b");
705 strvec_push(&cp
.args
, "--keep-cr");
707 strvec_push(&cp
.args
, "--mboxrd");
708 strvec_push(&cp
.args
, "--");
709 strvec_pushv(&cp
.args
, paths
);
711 ret
= capture_command(&cp
, &last
, 8);
716 state
->last
= strtol(last
.buf
, NULL
, 10);
719 strbuf_release(&last
);
724 * Callback signature for split_mail_conv(). The foreign patch should be
725 * read from `in`, and the converted patch (in RFC2822 mail format) should be
726 * written to `out`. Return 0 on success, or -1 on failure.
728 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
731 * Calls `fn` for each file in `paths` to convert the foreign patch to the
732 * RFC2822 mail format suitable for parsing with git-mailinfo.
734 * Returns 0 on success, -1 on failure.
736 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
737 const char **paths
, int keep_cr
)
739 static const char *stdin_only
[] = {"-", NULL
};
745 for (i
= 0; *paths
; paths
++, i
++) {
750 if (!strcmp(*paths
, "-"))
753 in
= fopen(*paths
, "r");
756 return error_errno(_("could not open '%s' for reading"),
759 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
761 out
= fopen(mail
, "w");
765 return error_errno(_("could not open '%s' for writing"),
769 ret
= fn(out
, in
, keep_cr
);
776 return error(_("could not parse patch '%s'"), *paths
);
785 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
786 * message suitable for parsing with git-mailinfo.
788 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
790 struct strbuf sb
= STRBUF_INIT
;
791 int subject_printed
= 0;
793 while (!strbuf_getline_lf(&sb
, in
)) {
796 if (str_isspace(sb
.buf
))
798 else if (skip_prefix(sb
.buf
, "Author:", &str
))
799 fprintf(out
, "From:%s\n", str
);
800 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
801 fprintf(out
, "%s\n", sb
.buf
);
802 else if (!subject_printed
) {
803 fprintf(out
, "Subject: %s\n", sb
.buf
);
806 fprintf(out
, "\n%s\n", sb
.buf
);
812 while (strbuf_fread(&sb
, 8192, in
) > 0) {
813 fwrite(sb
.buf
, 1, sb
.len
, out
);
822 * This function only supports a single StGit series file in `paths`.
824 * Given an StGit series file, converts the StGit patches in the series into
825 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
826 * the state directory.
828 * Returns 0 on success, -1 on failure.
830 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
833 const char *series_dir
;
834 char *series_dir_buf
;
836 struct strvec patches
= STRVEC_INIT
;
837 struct strbuf sb
= STRBUF_INIT
;
840 if (!paths
[0] || paths
[1])
841 return error(_("Only one StGIT patch series can be applied at once"));
843 series_dir_buf
= xstrdup(*paths
);
844 series_dir
= dirname(series_dir_buf
);
846 fp
= fopen(*paths
, "r");
848 return error_errno(_("could not open '%s' for reading"), *paths
);
850 while (!strbuf_getline_lf(&sb
, fp
)) {
852 continue; /* skip comment lines */
854 strvec_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
859 free(series_dir_buf
);
861 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.v
, keep_cr
);
863 strvec_clear(&patches
);
868 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
869 * message suitable for parsing with git-mailinfo.
871 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
873 struct strbuf sb
= STRBUF_INIT
;
876 while (!strbuf_getline_lf(&sb
, in
)) {
879 if (skip_prefix(sb
.buf
, "# User ", &str
))
880 fprintf(out
, "From: %s\n", str
);
881 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
882 timestamp_t timestamp
;
887 timestamp
= parse_timestamp(str
, &end
, 10);
889 rc
= error(_("invalid timestamp"));
893 if (!skip_prefix(end
, " ", &str
)) {
894 rc
= error(_("invalid Date line"));
899 tz
= strtol(str
, &end
, 10);
901 rc
= error(_("invalid timezone offset"));
906 rc
= error(_("invalid Date line"));
911 * mercurial's timezone is in seconds west of UTC,
912 * however git's timezone is in hours + minutes east of
915 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
919 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
920 } else if (starts_with(sb
.buf
, "# ")) {
923 fprintf(out
, "\n%s\n", sb
.buf
);
929 while (strbuf_fread(&sb
, 8192, in
) > 0) {
930 fwrite(sb
.buf
, 1, sb
.len
, out
);
939 * Splits a list of files/directories into individual email patches. Each path
940 * in `paths` must be a file/directory that is formatted according to
943 * Once split out, the individual email patches will be stored in the state
944 * directory, with each patch's filename being its index, padded to state->prec
947 * state->cur will be set to the index of the first mail, and state->last will
948 * be set to the index of the last mail.
950 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
951 * to disable this behavior, -1 to use the default configured setting.
953 * Returns 0 on success, -1 on failure.
955 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
956 const char **paths
, int keep_cr
)
960 git_config_get_bool("am.keepcr", &keep_cr
);
963 switch (patch_format
) {
964 case PATCH_FORMAT_MBOX
:
965 return split_mail_mbox(state
, paths
, keep_cr
, 0);
966 case PATCH_FORMAT_STGIT
:
967 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
968 case PATCH_FORMAT_STGIT_SERIES
:
969 return split_mail_stgit_series(state
, paths
, keep_cr
);
970 case PATCH_FORMAT_HG
:
971 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
972 case PATCH_FORMAT_MBOXRD
:
973 return split_mail_mbox(state
, paths
, keep_cr
, 1);
975 BUG("invalid patch_format");
981 * Setup a new am session for applying patches
983 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
984 const char **paths
, int keep_cr
)
986 struct object_id curr_head
;
988 struct strbuf sb
= STRBUF_INIT
;
991 patch_format
= detect_patch_format(paths
);
994 fprintf_ln(stderr
, _("Patch format detection failed."));
998 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
999 die_errno(_("failed to create directory '%s'"), state
->dir
);
1000 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
1002 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
1004 die(_("Failed to split patches."));
1007 if (state
->rebasing
)
1008 state
->threeway
= 1;
1010 write_state_bool(state
, "threeway", state
->threeway
);
1011 write_state_bool(state
, "quiet", state
->quiet
);
1012 write_state_bool(state
, "sign", state
->signoff
);
1013 write_state_bool(state
, "utf8", state
->utf8
);
1015 if (state
->allow_rerere_autoupdate
)
1016 write_state_bool(state
, "rerere-autoupdate",
1017 state
->allow_rerere_autoupdate
== RERERE_AUTOUPDATE
);
1019 switch (state
->keep
) {
1026 case KEEP_NON_PATCH
:
1030 BUG("invalid value for state->keep");
1033 write_state_text(state
, "keep", str
);
1034 write_state_bool(state
, "messageid", state
->message_id
);
1036 switch (state
->scissors
) {
1037 case SCISSORS_UNSET
:
1040 case SCISSORS_FALSE
:
1047 BUG("invalid value for state->scissors");
1049 write_state_text(state
, "scissors", str
);
1051 switch (state
->quoted_cr
) {
1052 case quoted_cr_unset
:
1055 case quoted_cr_nowarn
:
1058 case quoted_cr_warn
:
1061 case quoted_cr_strip
:
1065 BUG("invalid value for state->quoted_cr");
1067 write_state_text(state
, "quoted-cr", str
);
1069 sq_quote_argv(&sb
, state
->git_apply_opts
.v
);
1070 write_state_text(state
, "apply-opt", sb
.buf
);
1072 if (state
->rebasing
)
1073 write_state_text(state
, "rebasing", "");
1075 write_state_text(state
, "applying", "");
1077 if (!get_oid("HEAD", &curr_head
)) {
1078 write_state_text(state
, "abort-safety", oid_to_hex(&curr_head
));
1079 if (!state
->rebasing
)
1080 update_ref("am", "ORIG_HEAD", &curr_head
, NULL
, 0,
1081 UPDATE_REFS_DIE_ON_ERR
);
1083 write_state_text(state
, "abort-safety", "");
1084 if (!state
->rebasing
)
1085 delete_ref(NULL
, "ORIG_HEAD", NULL
, 0);
1089 * NOTE: Since the "next" and "last" files determine if an am_state
1090 * session is in progress, they should be written last.
1093 write_state_count(state
, "next", state
->cur
);
1094 write_state_count(state
, "last", state
->last
);
1096 strbuf_release(&sb
);
1100 * Increments the patch pointer, and cleans am_state for the application of the
1103 static void am_next(struct am_state
*state
)
1105 struct object_id head
;
1107 FREE_AND_NULL(state
->author_name
);
1108 FREE_AND_NULL(state
->author_email
);
1109 FREE_AND_NULL(state
->author_date
);
1110 FREE_AND_NULL(state
->msg
);
1113 unlink(am_path(state
, "author-script"));
1114 unlink(am_path(state
, "final-commit"));
1116 oidclr(&state
->orig_commit
);
1117 unlink(am_path(state
, "original-commit"));
1118 delete_ref(NULL
, "REBASE_HEAD", NULL
, REF_NO_DEREF
);
1120 if (!get_oid("HEAD", &head
))
1121 write_state_text(state
, "abort-safety", oid_to_hex(&head
));
1123 write_state_text(state
, "abort-safety", "");
1126 write_state_count(state
, "next", state
->cur
);
1130 * Returns the filename of the current patch email.
1132 static const char *msgnum(const struct am_state
*state
)
1134 static struct strbuf sb
= STRBUF_INIT
;
1137 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1143 * Dies with a user-friendly message on how to proceed after resolving the
1144 * problem. This message can be overridden with state->resolvemsg.
1146 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1148 if (state
->resolvemsg
) {
1149 printf_ln("%s", state
->resolvemsg
);
1151 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1153 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1154 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1156 if (advice_enabled(ADVICE_AM_WORK_DIR
) &&
1157 is_empty_or_missing_file(am_path(state
, "patch")) &&
1158 !repo_index_has_changes(the_repository
, NULL
, NULL
))
1159 printf_ln(_("To record the empty patch as an empty commit, run \"%s --allow-empty\"."), cmdline
);
1161 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1168 * Appends signoff to the "msg" field of the am_state.
1170 static void am_append_signoff(struct am_state
*state
)
1172 struct strbuf sb
= STRBUF_INIT
;
1174 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1175 append_signoff(&sb
, 0, 0);
1176 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1180 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1181 * state->msg will be set to the patch message. state->author_name,
1182 * state->author_email and state->author_date will be set to the patch author's
1183 * name, email and date respectively. The patch body will be written to the
1184 * state directory's "patch" file.
1186 * Returns 1 if the patch should be skipped, 0 otherwise.
1188 static int parse_mail(struct am_state
*state
, const char *mail
)
1191 struct strbuf sb
= STRBUF_INIT
;
1192 struct strbuf msg
= STRBUF_INIT
;
1193 struct strbuf author_name
= STRBUF_INIT
;
1194 struct strbuf author_date
= STRBUF_INIT
;
1195 struct strbuf author_email
= STRBUF_INIT
;
1199 setup_mailinfo(&mi
);
1202 mi
.metainfo_charset
= get_commit_output_encoding();
1204 mi
.metainfo_charset
= NULL
;
1206 switch (state
->keep
) {
1210 mi
.keep_subject
= 1;
1212 case KEEP_NON_PATCH
:
1213 mi
.keep_non_patch_brackets_in_subject
= 1;
1216 BUG("invalid value for state->keep");
1219 if (state
->message_id
)
1220 mi
.add_message_id
= 1;
1222 switch (state
->scissors
) {
1223 case SCISSORS_UNSET
:
1225 case SCISSORS_FALSE
:
1226 mi
.use_scissors
= 0;
1229 mi
.use_scissors
= 1;
1232 BUG("invalid value for state->scissors");
1235 switch (state
->quoted_cr
) {
1236 case quoted_cr_unset
:
1238 case quoted_cr_nowarn
:
1239 case quoted_cr_warn
:
1240 case quoted_cr_strip
:
1241 mi
.quoted_cr
= state
->quoted_cr
;
1244 BUG("invalid value for state->quoted_cr");
1247 mi
.input
= xfopen(mail
, "r");
1248 mi
.output
= xfopen(am_path(state
, "info"), "w");
1249 if (mailinfo(&mi
, am_path(state
, "msg"), am_path(state
, "patch")))
1250 die("could not parse patch");
1255 if (mi
.format_flowed
)
1256 warning(_("Patch sent with format=flowed; "
1257 "space at the end of lines might be lost."));
1259 /* Extract message and author information */
1260 fp
= xfopen(am_path(state
, "info"), "r");
1261 while (!strbuf_getline_lf(&sb
, fp
)) {
1264 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1266 strbuf_addch(&msg
, '\n');
1267 strbuf_addstr(&msg
, x
);
1268 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1269 strbuf_addstr(&author_name
, x
);
1270 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1271 strbuf_addstr(&author_email
, x
);
1272 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1273 strbuf_addstr(&author_date
, x
);
1277 /* Skip pine's internal folder data */
1278 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1283 strbuf_addstr(&msg
, "\n\n");
1284 strbuf_addbuf(&msg
, &mi
.log_message
);
1285 strbuf_stripspace(&msg
, 0);
1287 assert(!state
->author_name
);
1288 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1290 assert(!state
->author_email
);
1291 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1293 assert(!state
->author_date
);
1294 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1296 assert(!state
->msg
);
1297 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1300 strbuf_release(&msg
);
1301 strbuf_release(&author_date
);
1302 strbuf_release(&author_email
);
1303 strbuf_release(&author_name
);
1304 strbuf_release(&sb
);
1305 clear_mailinfo(&mi
);
1310 * Sets commit_id to the commit hash where the mail was generated from.
1311 * Returns 0 on success, -1 on failure.
1313 static int get_mail_commit_oid(struct object_id
*commit_id
, const char *mail
)
1315 struct strbuf sb
= STRBUF_INIT
;
1316 FILE *fp
= xfopen(mail
, "r");
1320 if (strbuf_getline_lf(&sb
, fp
) ||
1321 !skip_prefix(sb
.buf
, "From ", &x
) ||
1322 get_oid_hex(x
, commit_id
) < 0)
1325 strbuf_release(&sb
);
1331 * Sets state->msg, state->author_name, state->author_email, state->author_date
1332 * to the commit's respective info.
1334 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1336 const char *buffer
, *ident_line
, *msg
;
1338 struct ident_split id
;
1340 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1342 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1344 die(_("missing author line in commit %s"),
1345 oid_to_hex(&commit
->object
.oid
));
1346 if (split_ident_line(&id
, ident_line
, ident_len
) < 0)
1347 die(_("invalid ident line: %.*s"), (int)ident_len
, ident_line
);
1349 assert(!state
->author_name
);
1351 state
->author_name
=
1352 xmemdupz(id
.name_begin
, id
.name_end
- id
.name_begin
);
1354 state
->author_name
= xstrdup("");
1356 assert(!state
->author_email
);
1358 state
->author_email
=
1359 xmemdupz(id
.mail_begin
, id
.mail_end
- id
.mail_begin
);
1361 state
->author_email
= xstrdup("");
1363 assert(!state
->author_date
);
1364 state
->author_date
= xstrdup(show_ident_date(&id
, DATE_MODE(NORMAL
)));
1366 assert(!state
->msg
);
1367 msg
= strstr(buffer
, "\n\n");
1369 die(_("unable to parse commit %s"), oid_to_hex(&commit
->object
.oid
));
1370 state
->msg
= xstrdup(msg
+ 2);
1371 state
->msg_len
= strlen(state
->msg
);
1372 unuse_commit_buffer(commit
, buffer
);
1376 * Writes `commit` as a patch to the state directory's "patch" file.
1378 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1380 struct rev_info rev_info
;
1383 fp
= xfopen(am_path(state
, "patch"), "w");
1384 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1386 rev_info
.abbrev
= 0;
1387 rev_info
.disable_stdin
= 1;
1388 rev_info
.show_root_diff
= 1;
1389 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1390 rev_info
.no_commit_id
= 1;
1391 rev_info
.diffopt
.flags
.binary
= 1;
1392 rev_info
.diffopt
.flags
.full_index
= 1;
1393 rev_info
.diffopt
.use_color
= 0;
1394 rev_info
.diffopt
.file
= fp
;
1395 rev_info
.diffopt
.close_file
= 1;
1396 add_pending_object(&rev_info
, &commit
->object
, "");
1397 diff_setup_done(&rev_info
.diffopt
);
1398 log_tree_commit(&rev_info
, commit
);
1402 * Writes the diff of the index against HEAD as a patch to the state
1403 * directory's "patch" file.
1405 static void write_index_patch(const struct am_state
*state
)
1408 struct object_id head
;
1409 struct rev_info rev_info
;
1412 if (!get_oid("HEAD", &head
)) {
1413 struct commit
*commit
= lookup_commit_or_die(&head
, "HEAD");
1414 tree
= get_commit_tree(commit
);
1416 tree
= lookup_tree(the_repository
,
1417 the_repository
->hash_algo
->empty_tree
);
1419 fp
= xfopen(am_path(state
, "patch"), "w");
1420 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1422 rev_info
.disable_stdin
= 1;
1423 rev_info
.no_commit_id
= 1;
1424 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1425 rev_info
.diffopt
.use_color
= 0;
1426 rev_info
.diffopt
.file
= fp
;
1427 rev_info
.diffopt
.close_file
= 1;
1428 add_pending_object(&rev_info
, &tree
->object
, "");
1429 diff_setup_done(&rev_info
.diffopt
);
1430 run_diff_index(&rev_info
, 1);
1434 * Like parse_mail(), but parses the mail by looking up its commit ID
1435 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1438 * state->orig_commit will be set to the original commit ID.
1440 * Will always return 0 as the patch should never be skipped.
1442 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1444 struct commit
*commit
;
1445 struct object_id commit_oid
;
1447 if (get_mail_commit_oid(&commit_oid
, mail
) < 0)
1448 die(_("could not parse %s"), mail
);
1450 commit
= lookup_commit_or_die(&commit_oid
, mail
);
1452 get_commit_info(state
, commit
);
1454 write_commit_patch(state
, commit
);
1456 oidcpy(&state
->orig_commit
, &commit_oid
);
1457 write_state_text(state
, "original-commit", oid_to_hex(&commit_oid
));
1458 update_ref("am", "REBASE_HEAD", &commit_oid
,
1459 NULL
, REF_NO_DEREF
, UPDATE_REFS_DIE_ON_ERR
);
1465 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1466 * `index_file` is not NULL, the patch will be applied to that index.
1468 static int run_apply(const struct am_state
*state
, const char *index_file
)
1470 struct strvec apply_paths
= STRVEC_INIT
;
1471 struct strvec apply_opts
= STRVEC_INIT
;
1472 struct apply_state apply_state
;
1474 int force_apply
= 0;
1477 if (init_apply_state(&apply_state
, the_repository
, NULL
))
1478 BUG("init_apply_state() failed");
1480 strvec_push(&apply_opts
, "apply");
1481 strvec_pushv(&apply_opts
, state
->git_apply_opts
.v
);
1483 opts_left
= apply_parse_options(apply_opts
.nr
, apply_opts
.v
,
1484 &apply_state
, &force_apply
, &options
,
1488 die("unknown option passed through to git apply");
1491 apply_state
.index_file
= index_file
;
1492 apply_state
.cached
= 1;
1494 apply_state
.check_index
= 1;
1497 * If we are allowed to fall back on 3-way merge, don't give false
1498 * errors during the initial attempt.
1500 if (state
->threeway
&& !index_file
)
1501 apply_state
.apply_verbosity
= verbosity_silent
;
1503 if (check_apply_state(&apply_state
, force_apply
))
1504 BUG("check_apply_state() failed");
1506 strvec_push(&apply_paths
, am_path(state
, "patch"));
1508 res
= apply_all_patches(&apply_state
, apply_paths
.nr
, apply_paths
.v
, options
);
1510 strvec_clear(&apply_paths
);
1511 strvec_clear(&apply_opts
);
1512 clear_apply_state(&apply_state
);
1518 /* Reload index as apply_all_patches() will have modified it. */
1520 read_cache_from(index_file
);
1527 * Builds an index that contains just the blobs needed for a 3way merge.
1529 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1531 struct child_process cp
= CHILD_PROCESS_INIT
;
1534 strvec_push(&cp
.args
, "apply");
1535 strvec_pushv(&cp
.args
, state
->git_apply_opts
.v
);
1536 strvec_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1537 strvec_push(&cp
.args
, am_path(state
, "patch"));
1539 if (run_command(&cp
))
1546 * Attempt a threeway merge, using index_path as the temporary index.
1548 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1550 struct object_id orig_tree
, their_tree
, our_tree
;
1551 const struct object_id
*bases
[1] = { &orig_tree
};
1552 struct merge_options o
;
1553 struct commit
*result
;
1554 char *their_tree_name
;
1556 if (get_oid("HEAD", &our_tree
) < 0)
1557 oidcpy(&our_tree
, the_hash_algo
->empty_tree
);
1559 if (build_fake_ancestor(state
, index_path
))
1560 return error("could not build fake ancestor");
1563 read_cache_from(index_path
);
1565 if (write_index_as_tree(&orig_tree
, &the_index
, index_path
, 0, NULL
))
1566 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1568 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1570 if (!state
->quiet
) {
1572 * List paths that needed 3-way fallback, so that the user can
1573 * review them with extra care to spot mismerges.
1575 struct rev_info rev_info
;
1577 repo_init_revisions(the_repository
, &rev_info
, NULL
);
1578 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1579 rev_info
.diffopt
.filter
|= diff_filter_bit('A');
1580 rev_info
.diffopt
.filter
|= diff_filter_bit('M');
1581 add_pending_oid(&rev_info
, "HEAD", &our_tree
, 0);
1582 diff_setup_done(&rev_info
.diffopt
);
1583 run_diff_index(&rev_info
, 1);
1586 if (run_apply(state
, index_path
))
1587 return error(_("Did you hand edit your patch?\n"
1588 "It does not apply to blobs recorded in its index."));
1590 if (write_index_as_tree(&their_tree
, &the_index
, index_path
, 0, NULL
))
1591 return error("could not write tree");
1593 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1599 * This is not so wrong. Depending on which base we picked, orig_tree
1600 * may be wildly different from ours, but their_tree has the same set of
1601 * wildly different changes in parts the patch did not touch, so
1602 * recursive ends up canceling them, saying that we reverted all those
1606 init_merge_options(&o
, the_repository
);
1609 their_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1610 o
.branch2
= their_tree_name
;
1611 o
.detect_directory_renames
= MERGE_DIRECTORY_RENAMES_NONE
;
1616 if (merge_recursive_generic(&o
, &our_tree
, &their_tree
, 1, bases
, &result
)) {
1617 repo_rerere(the_repository
, state
->allow_rerere_autoupdate
);
1618 free(their_tree_name
);
1619 return error(_("Failed to merge in the changes."));
1622 free(their_tree_name
);
1627 * Commits the current index with state->msg as the commit message and
1628 * state->author_name, state->author_email and state->author_date as the author
1631 static void do_commit(const struct am_state
*state
)
1633 struct object_id tree
, parent
, commit
;
1634 const struct object_id
*old_oid
;
1635 struct commit_list
*parents
= NULL
;
1636 const char *reflog_msg
, *author
, *committer
= NULL
;
1637 struct strbuf sb
= STRBUF_INIT
;
1639 if (run_hooks("pre-applypatch"))
1642 if (write_cache_as_tree(&tree
, 0, NULL
))
1643 die(_("git write-tree failed to write a tree"));
1645 if (!get_oid_commit("HEAD", &parent
)) {
1647 commit_list_insert(lookup_commit(the_repository
, &parent
),
1651 say(state
, stderr
, _("applying to an empty history"));
1654 author
= fmt_ident(state
->author_name
, state
->author_email
,
1656 state
->ignore_date
? NULL
: state
->author_date
,
1659 if (state
->committer_date_is_author_date
)
1660 committer
= fmt_ident(getenv("GIT_COMMITTER_NAME"),
1661 getenv("GIT_COMMITTER_EMAIL"),
1662 WANT_COMMITTER_IDENT
,
1663 state
->ignore_date
? NULL
1664 : state
->author_date
,
1667 if (commit_tree_extended(state
->msg
, state
->msg_len
, &tree
, parents
,
1668 &commit
, author
, committer
, state
->sign_commit
,
1670 die(_("failed to write commit object"));
1672 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1676 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1679 update_ref(sb
.buf
, "HEAD", &commit
, old_oid
, 0,
1680 UPDATE_REFS_DIE_ON_ERR
);
1682 if (state
->rebasing
) {
1683 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1685 assert(!is_null_oid(&state
->orig_commit
));
1686 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
1687 fprintf(fp
, "%s\n", oid_to_hex(&commit
));
1691 run_hooks("post-applypatch");
1693 strbuf_release(&sb
);
1697 * Validates the am_state for resuming -- the "msg" and authorship fields must
1700 static void validate_resume_state(const struct am_state
*state
)
1703 die(_("cannot resume: %s does not exist."),
1704 am_path(state
, "final-commit"));
1706 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1707 die(_("cannot resume: %s does not exist."),
1708 am_path(state
, "author-script"));
1712 * Interactively prompt the user on whether the current patch should be
1715 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1718 static int do_interactive(struct am_state
*state
)
1725 puts(_("Commit Body is:"));
1726 puts("--------------------------");
1727 printf("%s", state
->msg
);
1728 puts("--------------------------");
1731 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1732 * in your translation. The program will only accept English
1733 * input at this point.
1735 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1736 if (!fgets(reply
, sizeof(reply
), stdin
))
1737 die("unable to read from stdin; aborting");
1739 if (*reply
== 'y' || *reply
== 'Y') {
1741 } else if (*reply
== 'a' || *reply
== 'A') {
1742 state
->interactive
= 0;
1744 } else if (*reply
== 'n' || *reply
== 'N') {
1746 } else if (*reply
== 'e' || *reply
== 'E') {
1747 struct strbuf msg
= STRBUF_INIT
;
1749 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1751 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1753 strbuf_release(&msg
);
1754 } else if (*reply
== 'v' || *reply
== 'V') {
1755 const char *pager
= git_pager(1);
1756 struct child_process cp
= CHILD_PROCESS_INIT
;
1760 prepare_pager_args(&cp
, pager
);
1761 strvec_push(&cp
.args
, am_path(state
, "patch"));
1768 * Applies all queued mail.
1770 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1771 * well as the state directory's "patch" file is used as-is for applying the
1772 * patch and committing it.
1774 static void am_run(struct am_state
*state
, int resume
)
1776 struct strbuf sb
= STRBUF_INIT
;
1778 unlink(am_path(state
, "dirtyindex"));
1780 if (refresh_and_write_cache(REFRESH_QUIET
, 0, 0) < 0)
1781 die(_("unable to write index file"));
1783 if (repo_index_has_changes(the_repository
, NULL
, &sb
)) {
1784 write_state_bool(state
, "dirtyindex", 1);
1785 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1788 strbuf_release(&sb
);
1790 while (state
->cur
<= state
->last
) {
1791 const char *mail
= am_path(state
, msgnum(state
));
1797 if (!file_exists(mail
))
1801 validate_resume_state(state
);
1805 if (state
->rebasing
)
1806 skip
= parse_mail_rebase(state
, mail
);
1808 skip
= parse_mail(state
, mail
);
1811 goto next
; /* mail should be skipped */
1814 am_append_signoff(state
);
1816 write_author_script(state
);
1817 write_commit_msg(state
);
1820 if (state
->interactive
&& do_interactive(state
))
1824 if (is_empty_or_missing_file(am_path(state
, "patch"))) {
1825 switch (state
->empty_type
) {
1826 case DROP_EMPTY_COMMIT
:
1827 say(state
, stdout
, _("Skipping: %.*s"), linelen(state
->msg
), state
->msg
);
1830 case KEEP_EMPTY_COMMIT
:
1832 say(state
, stdout
, _("Creating an empty commit: %.*s"),
1833 linelen(state
->msg
), state
->msg
);
1835 case STOP_ON_EMPTY_COMMIT
:
1836 printf_ln(_("Patch is empty."));
1837 die_user_resolve(state
);
1842 if (run_applypatch_msg_hook(state
))
1847 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1849 apply_status
= run_apply(state
, NULL
);
1851 if (apply_status
&& state
->threeway
) {
1852 struct strbuf sb
= STRBUF_INIT
;
1854 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1855 apply_status
= fall_back_threeway(state
, sb
.buf
);
1856 strbuf_release(&sb
);
1859 * Applying the patch to an earlier tree and merging
1860 * the result may have produced the same tree as ours.
1862 if (!apply_status
&&
1863 !repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1864 say(state
, stdout
, _("No changes -- Patch already applied."));
1870 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1871 linelen(state
->msg
), state
->msg
);
1873 if (advice_enabled(ADVICE_AM_WORK_DIR
))
1874 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1876 die_user_resolve(state
);
1890 if (!is_empty_or_missing_file(am_path(state
, "rewritten"))) {
1891 assert(state
->rebasing
);
1892 copy_notes_for_rebase(state
);
1893 run_post_rewrite_hook(state
);
1897 * In rebasing mode, it's up to the caller to take care of
1900 if (!state
->rebasing
) {
1902 run_auto_maintenance(state
->quiet
);
1907 * Resume the current am session after patch application failure. The user did
1908 * all the hard work, and we do not have to do any patch application. Just
1909 * trust and commit what the user has in the index and working tree. If `allow_empty`
1910 * is true, commit as an empty commit when index has not changed and lacking a patch.
1912 static void am_resolve(struct am_state
*state
, int allow_empty
)
1914 validate_resume_state(state
);
1916 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1918 if (!repo_index_has_changes(the_repository
, NULL
, NULL
)) {
1919 if (allow_empty
&& is_empty_or_missing_file(am_path(state
, "patch"))) {
1920 printf_ln(_("No changes - recorded it as an empty commit."));
1922 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1923 "If there is nothing left to stage, chances are that something else\n"
1924 "already introduced the same changes; you might want to skip this patch."));
1925 die_user_resolve(state
);
1929 if (unmerged_cache()) {
1930 printf_ln(_("You still have unmerged paths in your index.\n"
1931 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1932 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1933 die_user_resolve(state
);
1936 if (state
->interactive
) {
1937 write_index_patch(state
);
1938 if (do_interactive(state
))
1942 repo_rerere(the_repository
, 0);
1953 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1954 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1957 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1959 struct lock_file lock_file
= LOCK_INIT
;
1960 struct unpack_trees_options opts
;
1961 struct tree_desc t
[2];
1963 if (parse_tree(head
) || parse_tree(remote
))
1966 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
1968 refresh_cache(REFRESH_QUIET
);
1970 memset(&opts
, 0, sizeof(opts
));
1972 opts
.src_index
= &the_index
;
1973 opts
.dst_index
= &the_index
;
1976 opts
.reset
= reset
? UNPACK_RESET_PROTECT_UNTRACKED
: 0;
1977 opts
.preserve_ignored
= 0; /* FIXME: !overwrite_ignore */
1978 opts
.fn
= twoway_merge
;
1979 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1980 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1982 if (unpack_trees(2, t
, &opts
)) {
1983 rollback_lock_file(&lock_file
);
1987 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
1988 die(_("unable to write new index file"));
1994 * Merges a tree into the index. The index's stat info will take precedence
1995 * over the merged tree's. Returns 0 on success, -1 on failure.
1997 static int merge_tree(struct tree
*tree
)
1999 struct lock_file lock_file
= LOCK_INIT
;
2000 struct unpack_trees_options opts
;
2001 struct tree_desc t
[1];
2003 if (parse_tree(tree
))
2006 hold_locked_index(&lock_file
, LOCK_DIE_ON_ERROR
);
2008 memset(&opts
, 0, sizeof(opts
));
2010 opts
.src_index
= &the_index
;
2011 opts
.dst_index
= &the_index
;
2013 opts
.fn
= oneway_merge
;
2014 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
2016 if (unpack_trees(1, t
, &opts
)) {
2017 rollback_lock_file(&lock_file
);
2021 if (write_locked_index(&the_index
, &lock_file
, COMMIT_LOCK
))
2022 die(_("unable to write new index file"));
2028 * Clean the index without touching entries that are not modified between
2029 * `head` and `remote`.
2031 static int clean_index(const struct object_id
*head
, const struct object_id
*remote
)
2033 struct tree
*head_tree
, *remote_tree
, *index_tree
;
2034 struct object_id index
;
2036 head_tree
= parse_tree_indirect(head
);
2038 return error(_("Could not parse object '%s'."), oid_to_hex(head
));
2040 remote_tree
= parse_tree_indirect(remote
);
2042 return error(_("Could not parse object '%s'."), oid_to_hex(remote
));
2044 read_cache_unmerged();
2046 if (fast_forward_to(head_tree
, head_tree
, 1))
2049 if (write_cache_as_tree(&index
, 0, NULL
))
2052 index_tree
= parse_tree_indirect(&index
);
2054 return error(_("Could not parse object '%s'."), oid_to_hex(&index
));
2056 if (fast_forward_to(index_tree
, remote_tree
, 0))
2059 if (merge_tree(remote_tree
))
2062 remove_branch_state(the_repository
, 0);
2068 * Resets rerere's merge resolution metadata.
2070 static void am_rerere_clear(void)
2072 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
2073 rerere_clear(the_repository
, &merge_rr
);
2074 string_list_clear(&merge_rr
, 1);
2078 * Resume the current am session by skipping the current patch.
2080 static void am_skip(struct am_state
*state
)
2082 struct object_id head
;
2086 if (get_oid("HEAD", &head
))
2087 oidcpy(&head
, the_hash_algo
->empty_tree
);
2089 if (clean_index(&head
, &head
))
2090 die(_("failed to clean index"));
2092 if (state
->rebasing
) {
2093 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
2095 assert(!is_null_oid(&state
->orig_commit
));
2096 fprintf(fp
, "%s ", oid_to_hex(&state
->orig_commit
));
2097 fprintf(fp
, "%s\n", oid_to_hex(&head
));
2107 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2109 * It is not safe to reset HEAD when:
2110 * 1. git-am previously failed because the index was dirty.
2111 * 2. HEAD has moved since git-am previously failed.
2113 static int safe_to_abort(const struct am_state
*state
)
2115 struct strbuf sb
= STRBUF_INIT
;
2116 struct object_id abort_safety
, head
;
2118 if (file_exists(am_path(state
, "dirtyindex")))
2121 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2122 if (get_oid_hex(sb
.buf
, &abort_safety
))
2123 die(_("could not parse %s"), am_path(state
, "abort-safety"));
2125 oidclr(&abort_safety
);
2126 strbuf_release(&sb
);
2128 if (get_oid("HEAD", &head
))
2131 if (oideq(&head
, &abort_safety
))
2134 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2135 "Not rewinding to ORIG_HEAD"));
2141 * Aborts the current am session if it is safe to do so.
2143 static void am_abort(struct am_state
*state
)
2145 struct object_id curr_head
, orig_head
;
2146 int has_curr_head
, has_orig_head
;
2149 if (!safe_to_abort(state
)) {
2156 curr_branch
= resolve_refdup("HEAD", 0, &curr_head
, NULL
);
2157 has_curr_head
= curr_branch
&& !is_null_oid(&curr_head
);
2159 oidcpy(&curr_head
, the_hash_algo
->empty_tree
);
2161 has_orig_head
= !get_oid("ORIG_HEAD", &orig_head
);
2163 oidcpy(&orig_head
, the_hash_algo
->empty_tree
);
2165 if (clean_index(&curr_head
, &orig_head
))
2166 die(_("failed to clean index"));
2169 update_ref("am --abort", "HEAD", &orig_head
,
2170 has_curr_head
? &curr_head
: NULL
, 0,
2171 UPDATE_REFS_DIE_ON_ERR
);
2172 else if (curr_branch
)
2173 delete_ref(NULL
, curr_branch
, NULL
, REF_NO_DEREF
);
2179 static int show_patch(struct am_state
*state
, enum show_patch_type sub_mode
)
2181 struct strbuf sb
= STRBUF_INIT
;
2182 const char *patch_path
;
2185 if (!is_null_oid(&state
->orig_commit
)) {
2186 const char *av
[4] = { "show", NULL
, "--", NULL
};
2190 av
[1] = new_oid_str
= xstrdup(oid_to_hex(&state
->orig_commit
));
2191 ret
= run_command_v_opt(av
, RUN_GIT_CMD
);
2197 case SHOW_PATCH_RAW
:
2198 patch_path
= am_path(state
, msgnum(state
));
2200 case SHOW_PATCH_DIFF
:
2201 patch_path
= am_path(state
, "patch");
2204 BUG("invalid mode for --show-current-patch");
2207 len
= strbuf_read_file(&sb
, patch_path
, 0);
2209 die_errno(_("failed to read '%s'"), patch_path
);
2212 write_in_full(1, sb
.buf
, sb
.len
);
2213 strbuf_release(&sb
);
2218 * parse_options() callback that validates and sets opt->value to the
2219 * PATCH_FORMAT_* enum value corresponding to `arg`.
2221 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2223 int *opt_value
= opt
->value
;
2226 *opt_value
= PATCH_FORMAT_UNKNOWN
;
2227 else if (!strcmp(arg
, "mbox"))
2228 *opt_value
= PATCH_FORMAT_MBOX
;
2229 else if (!strcmp(arg
, "stgit"))
2230 *opt_value
= PATCH_FORMAT_STGIT
;
2231 else if (!strcmp(arg
, "stgit-series"))
2232 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2233 else if (!strcmp(arg
, "hg"))
2234 *opt_value
= PATCH_FORMAT_HG
;
2235 else if (!strcmp(arg
, "mboxrd"))
2236 *opt_value
= PATCH_FORMAT_MBOXRD
;
2238 * Please update $__git_patchformat in git-completion.bash
2239 * when you add new options
2242 return error(_("Invalid value for --patch-format: %s"), arg
);
2257 struct resume_mode
{
2258 enum resume_type mode
;
2259 enum show_patch_type sub_mode
;
2262 static int parse_opt_show_current_patch(const struct option
*opt
, const char *arg
, int unset
)
2264 int *opt_value
= opt
->value
;
2265 struct resume_mode
*resume
= container_of(opt_value
, struct resume_mode
, mode
);
2268 * Please update $__git_showcurrentpatch in git-completion.bash
2269 * when you add new options
2271 const char *valid_modes
[] = {
2272 [SHOW_PATCH_DIFF
] = "diff",
2273 [SHOW_PATCH_RAW
] = "raw"
2275 int new_value
= SHOW_PATCH_RAW
;
2277 BUG_ON_OPT_NEG(unset
);
2280 for (new_value
= 0; new_value
< ARRAY_SIZE(valid_modes
); new_value
++) {
2281 if (!strcmp(arg
, valid_modes
[new_value
]))
2284 if (new_value
>= ARRAY_SIZE(valid_modes
))
2285 return error(_("Invalid value for --show-current-patch: %s"), arg
);
2288 if (resume
->mode
== RESUME_SHOW_PATCH
&& new_value
!= resume
->sub_mode
)
2289 return error(_("options '%s=%s' and '%s=%s' "
2290 "cannot be used together"),
2291 "--show-current-patch", "--show-current-patch", arg
, valid_modes
[resume
->sub_mode
]);
2293 resume
->mode
= RESUME_SHOW_PATCH
;
2294 resume
->sub_mode
= new_value
;
2298 static int git_am_config(const char *k
, const char *v
, void *cb
)
2302 status
= git_gpg_config(k
, v
, NULL
);
2306 return git_default_config(k
, v
, NULL
);
2309 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2311 struct am_state state
;
2314 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2315 struct resume_mode resume
= { .mode
= RESUME_FALSE
};
2319 const char * const usage
[] = {
2320 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2321 N_("git am [<options>] (--continue | --skip | --abort)"),
2325 struct option options
[] = {
2326 OPT_BOOL('i', "interactive", &state
.interactive
,
2327 N_("run interactively")),
2328 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2329 N_("historical option -- no-op")),
2330 OPT_BOOL('3', "3way", &state
.threeway
,
2331 N_("allow fall back on 3way merging if needed")),
2332 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2333 OPT_SET_INT('s', "signoff", &state
.signoff
,
2334 N_("add a Signed-off-by trailer to the commit message"),
2336 OPT_BOOL('u', "utf8", &state
.utf8
,
2337 N_("recode into utf8 (default)")),
2338 OPT_SET_INT('k', "keep", &state
.keep
,
2339 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2340 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2341 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2342 OPT_BOOL('m', "message-id", &state
.message_id
,
2343 N_("pass -m flag to git-mailinfo")),
2344 OPT_SET_INT_F(0, "keep-cr", &keep_cr
,
2345 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2346 1, PARSE_OPT_NONEG
),
2347 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr
,
2348 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2349 0, PARSE_OPT_NONEG
),
2350 OPT_BOOL('c', "scissors", &state
.scissors
,
2351 N_("strip everything before a scissors line")),
2352 OPT_CALLBACK_F(0, "quoted-cr", &state
.quoted_cr
, N_("action"),
2353 N_("pass it through git-mailinfo"),
2354 PARSE_OPT_NONEG
, am_option_parse_quoted_cr
),
2355 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2356 N_("pass it through git-apply"),
2358 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2359 N_("pass it through git-apply"),
2361 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2362 N_("pass it through git-apply"),
2364 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2365 N_("pass it through git-apply"),
2367 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2368 N_("pass it through git-apply"),
2370 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2371 N_("pass it through git-apply"),
2373 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2374 N_("pass it through git-apply"),
2376 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2377 N_("pass it through git-apply"),
2379 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2380 N_("format the patch(es) are in"),
2381 parse_opt_patchformat
),
2382 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2383 N_("pass it through git-apply"),
2385 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2386 N_("override error message when patch failure occurs")),
2387 OPT_CMDMODE(0, "continue", &resume
.mode
,
2388 N_("continue applying patches after resolving a conflict"),
2390 OPT_CMDMODE('r', "resolved", &resume
.mode
,
2391 N_("synonyms for --continue"),
2393 OPT_CMDMODE(0, "skip", &resume
.mode
,
2394 N_("skip the current patch"),
2396 OPT_CMDMODE(0, "abort", &resume
.mode
,
2397 N_("restore the original branch and abort the patching operation"),
2399 OPT_CMDMODE(0, "quit", &resume
.mode
,
2400 N_("abort the patching operation but keep HEAD where it is"),
2402 { OPTION_CALLBACK
, 0, "show-current-patch", &resume
.mode
,
2404 N_("show the patch being applied"),
2405 PARSE_OPT_CMDMODE
| PARSE_OPT_OPTARG
| PARSE_OPT_NONEG
| PARSE_OPT_LITERAL_ARGHELP
,
2406 parse_opt_show_current_patch
, RESUME_SHOW_PATCH
},
2407 OPT_CMDMODE(0, "allow-empty", &resume
.mode
,
2408 N_("record the empty patch as an empty commit"),
2409 RESUME_ALLOW_EMPTY
),
2410 OPT_BOOL(0, "committer-date-is-author-date",
2411 &state
.committer_date_is_author_date
,
2412 N_("lie about committer date")),
2413 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2414 N_("use current timestamp for author date")),
2415 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2416 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2417 N_("GPG-sign commits"),
2418 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2419 OPT_CALLBACK_F(STOP_ON_EMPTY_COMMIT
, "empty", &state
.empty_type
, "{stop,drop,keep}",
2420 N_("how to handle empty patches"),
2421 PARSE_OPT_NONEG
, am_option_parse_empty
),
2422 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2423 N_("(internal use for git-rebase)")),
2427 if (argc
== 2 && !strcmp(argv
[1], "-h"))
2428 usage_with_options(usage
, options
);
2430 git_config(git_am_config
, NULL
);
2432 am_state_init(&state
);
2434 in_progress
= am_in_progress(&state
);
2438 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2441 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2442 "it will be removed. Please do not use it anymore."));
2444 /* Ensure a valid committer ident can be constructed */
2445 git_committer_info(IDENT_STRICT
);
2447 if (repo_read_index_preload(the_repository
, NULL
, 0) < 0)
2448 die(_("failed to read the index"));
2452 * Catch user error to feed us patches when there is a session
2455 * 1. mbox path(s) are provided on the command-line.
2456 * 2. stdin is not a tty: the user is trying to feed us a patch
2457 * from standard input. This is somewhat unreliable -- stdin
2458 * could be /dev/null for example and the caller did not
2459 * intend to feed us a patch but wanted to continue
2462 if (argc
|| (resume
.mode
== RESUME_FALSE
&& !isatty(0)))
2463 die(_("previous rebase directory %s still exists but mbox given."),
2466 if (resume
.mode
== RESUME_FALSE
)
2467 resume
.mode
= RESUME_APPLY
;
2469 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2470 am_append_signoff(&state
);
2472 struct strvec paths
= STRVEC_INIT
;
2476 * Handle stray state directory in the independent-run case. In
2477 * the --rebasing case, it is up to the caller to take care of
2478 * stray directories.
2480 if (file_exists(state
.dir
) && !state
.rebasing
) {
2481 if (resume
.mode
== RESUME_ABORT
|| resume
.mode
== RESUME_QUIT
) {
2483 am_state_release(&state
);
2487 die(_("Stray %s directory found.\n"
2488 "Use \"git am --abort\" to remove it."),
2493 die(_("Resolve operation not in progress, we are not resuming."));
2495 for (i
= 0; i
< argc
; i
++) {
2496 if (is_absolute_path(argv
[i
]) || !prefix
)
2497 strvec_push(&paths
, argv
[i
]);
2499 strvec_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2502 if (state
.interactive
&& !paths
.nr
)
2503 die(_("interactive mode requires patches on the command line"));
2505 am_setup(&state
, patch_format
, paths
.v
, keep_cr
);
2507 strvec_clear(&paths
);
2510 switch (resume
.mode
) {
2517 case RESUME_RESOLVED
:
2518 case RESUME_ALLOW_EMPTY
:
2519 am_resolve(&state
, resume
.mode
== RESUME_ALLOW_EMPTY
? 1 : 0);
2531 case RESUME_SHOW_PATCH
:
2532 ret
= show_patch(&state
, resume
.sub_mode
);
2535 BUG("invalid resume value");
2538 am_state_release(&state
);