4 * Based on git-am.sh by Junio C Hamano.
9 #include "parse-options.h"
11 #include "run-command.h"
14 #include "cache-tree.h"
19 #include "unpack-trees.h"
21 #include "sequencer.h"
23 #include "merge-recursive.h"
26 #include "notes-utils.h"
31 * Returns 1 if the file is empty or does not exist, 0 otherwise.
33 static int is_empty_file(const char *filename
)
37 if (stat(filename
, &st
) < 0) {
40 die_errno(_("could not stat %s"), filename
);
47 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
49 static int strbuf_getline_crlf(struct strbuf
*sb
, FILE *fp
)
51 if (strbuf_getwholeline(sb
, fp
, '\n'))
53 if (sb
->buf
[sb
->len
- 1] == '\n') {
54 strbuf_setlen(sb
, sb
->len
- 1);
55 if (sb
->len
> 0 && sb
->buf
[sb
->len
- 1] == '\r')
56 strbuf_setlen(sb
, sb
->len
- 1);
62 * Returns the length of the first line of msg.
64 static int linelen(const char *msg
)
66 return strchrnul(msg
, '\n') - msg
;
70 * Returns true if `str` consists of only whitespace, false otherwise.
72 static int str_isspace(const char *str
)
82 PATCH_FORMAT_UNKNOWN
= 0,
85 PATCH_FORMAT_STGIT_SERIES
,
91 KEEP_TRUE
, /* pass -k flag to git-mailinfo */
92 KEEP_NON_PATCH
/* pass -b flag to git-mailinfo */
97 SCISSORS_FALSE
= 0, /* pass --no-scissors to git-mailinfo */
98 SCISSORS_TRUE
/* pass --scissors to git-mailinfo */
102 /* state directory path */
105 /* current and last patch numbers, 1-indexed */
109 /* commit metadata and message */
116 /* when --rebasing, records the original commit the patch came from */
117 unsigned char orig_commit
[GIT_SHA1_RAWSZ
];
119 /* number of digits in patch filename */
122 /* various operating modes and command line options */
128 int keep
; /* enum keep_type */
130 int scissors
; /* enum scissors_type */
131 struct argv_array git_apply_opts
;
132 const char *resolvemsg
;
133 int committer_date_is_author_date
;
135 int allow_rerere_autoupdate
;
136 const char *sign_commit
;
141 * Initializes am_state with the default values. The state directory is set to
144 static void am_state_init(struct am_state
*state
, const char *dir
)
148 memset(state
, 0, sizeof(*state
));
151 state
->dir
= xstrdup(dir
);
155 git_config_get_bool("am.threeway", &state
->threeway
);
159 git_config_get_bool("am.messageid", &state
->message_id
);
161 state
->scissors
= SCISSORS_UNSET
;
163 argv_array_init(&state
->git_apply_opts
);
165 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
166 state
->sign_commit
= gpgsign
? "" : NULL
;
170 * Releases memory allocated by an am_state.
172 static void am_state_release(struct am_state
*state
)
175 free(state
->author_name
);
176 free(state
->author_email
);
177 free(state
->author_date
);
179 argv_array_clear(&state
->git_apply_opts
);
183 * Returns path relative to the am_state directory.
185 static inline const char *am_path(const struct am_state
*state
, const char *path
)
187 return mkpath("%s/%s", state
->dir
, path
);
191 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
194 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
200 vfprintf(fp
, fmt
, ap
);
207 * Returns 1 if there is an am session in progress, 0 otherwise.
209 static int am_in_progress(const struct am_state
*state
)
213 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
215 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
217 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
223 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
224 * number of bytes read on success, -1 if the file does not exist. If `trim` is
225 * set, trailing whitespace will be removed.
227 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
228 const char *file
, int trim
)
232 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
242 die_errno(_("could not read '%s'"), am_path(state
, file
));
246 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
247 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
248 * match `key`. Returns NULL on failure.
250 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
253 static char *read_shell_var(FILE *fp
, const char *key
)
255 struct strbuf sb
= STRBUF_INIT
;
258 if (strbuf_getline(&sb
, fp
, '\n'))
261 if (!skip_prefix(sb
.buf
, key
, &str
))
264 if (!skip_prefix(str
, "=", &str
))
267 strbuf_remove(&sb
, 0, str
- sb
.buf
);
269 str
= sq_dequote(sb
.buf
);
273 return strbuf_detach(&sb
, NULL
);
281 * Reads and parses the state directory's "author-script" file, and sets
282 * state->author_name, state->author_email and state->author_date accordingly.
283 * Returns 0 on success, -1 if the file could not be parsed.
285 * The author script is of the format:
287 * GIT_AUTHOR_NAME='$author_name'
288 * GIT_AUTHOR_EMAIL='$author_email'
289 * GIT_AUTHOR_DATE='$author_date'
291 * where $author_name, $author_email and $author_date are quoted. We are strict
292 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
293 * script, and thus if the file differs from what this function expects, it is
294 * better to bail out than to do something that the user does not expect.
296 static int read_author_script(struct am_state
*state
)
298 const char *filename
= am_path(state
, "author-script");
301 assert(!state
->author_name
);
302 assert(!state
->author_email
);
303 assert(!state
->author_date
);
305 fp
= fopen(filename
, "r");
309 die_errno(_("could not open '%s' for reading"), filename
);
312 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
313 if (!state
->author_name
) {
318 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
319 if (!state
->author_email
) {
324 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
325 if (!state
->author_date
) {
330 if (fgetc(fp
) != EOF
) {
340 * Saves state->author_name, state->author_email and state->author_date in the
341 * state directory's "author-script" file.
343 static void write_author_script(const struct am_state
*state
)
345 struct strbuf sb
= STRBUF_INIT
;
347 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
348 sq_quote_buf(&sb
, state
->author_name
);
349 strbuf_addch(&sb
, '\n');
351 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
352 sq_quote_buf(&sb
, state
->author_email
);
353 strbuf_addch(&sb
, '\n');
355 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
356 sq_quote_buf(&sb
, state
->author_date
);
357 strbuf_addch(&sb
, '\n');
359 write_file(am_path(state
, "author-script"), 1, "%s", sb
.buf
);
365 * Reads the commit message from the state directory's "final-commit" file,
366 * setting state->msg to its contents and state->msg_len to the length of its
369 * Returns 0 on success, -1 if the file does not exist.
371 static int read_commit_msg(struct am_state
*state
)
373 struct strbuf sb
= STRBUF_INIT
;
377 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
382 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
387 * Saves state->msg in the state directory's "final-commit" file.
389 static void write_commit_msg(const struct am_state
*state
)
392 const char *filename
= am_path(state
, "final-commit");
394 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
395 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
396 die_errno(_("could not write to %s"), filename
);
401 * Loads state from disk.
403 static void am_load(struct am_state
*state
)
405 struct strbuf sb
= STRBUF_INIT
;
407 if (read_state_file(&sb
, state
, "next", 1) < 0)
408 die("BUG: state file 'next' does not exist");
409 state
->cur
= strtol(sb
.buf
, NULL
, 10);
411 if (read_state_file(&sb
, state
, "last", 1) < 0)
412 die("BUG: state file 'last' does not exist");
413 state
->last
= strtol(sb
.buf
, NULL
, 10);
415 if (read_author_script(state
) < 0)
416 die(_("could not parse author script"));
418 read_commit_msg(state
);
420 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
421 hashclr(state
->orig_commit
);
422 else if (get_sha1_hex(sb
.buf
, state
->orig_commit
) < 0)
423 die(_("could not parse %s"), am_path(state
, "original-commit"));
425 read_state_file(&sb
, state
, "threeway", 1);
426 state
->threeway
= !strcmp(sb
.buf
, "t");
428 read_state_file(&sb
, state
, "quiet", 1);
429 state
->quiet
= !strcmp(sb
.buf
, "t");
431 read_state_file(&sb
, state
, "sign", 1);
432 state
->signoff
= !strcmp(sb
.buf
, "t");
434 read_state_file(&sb
, state
, "utf8", 1);
435 state
->utf8
= !strcmp(sb
.buf
, "t");
437 read_state_file(&sb
, state
, "keep", 1);
438 if (!strcmp(sb
.buf
, "t"))
439 state
->keep
= KEEP_TRUE
;
440 else if (!strcmp(sb
.buf
, "b"))
441 state
->keep
= KEEP_NON_PATCH
;
443 state
->keep
= KEEP_FALSE
;
445 read_state_file(&sb
, state
, "messageid", 1);
446 state
->message_id
= !strcmp(sb
.buf
, "t");
448 read_state_file(&sb
, state
, "scissors", 1);
449 if (!strcmp(sb
.buf
, "t"))
450 state
->scissors
= SCISSORS_TRUE
;
451 else if (!strcmp(sb
.buf
, "f"))
452 state
->scissors
= SCISSORS_FALSE
;
454 state
->scissors
= SCISSORS_UNSET
;
456 read_state_file(&sb
, state
, "apply-opt", 1);
457 argv_array_clear(&state
->git_apply_opts
);
458 if (sq_dequote_to_argv_array(sb
.buf
, &state
->git_apply_opts
) < 0)
459 die(_("could not parse %s"), am_path(state
, "apply-opt"));
461 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
467 * Removes the am_state directory, forcefully terminating the current am
470 static void am_destroy(const struct am_state
*state
)
472 struct strbuf sb
= STRBUF_INIT
;
474 strbuf_addstr(&sb
, state
->dir
);
475 remove_dir_recursively(&sb
, 0);
480 * Runs applypatch-msg hook. Returns its exit code.
482 static int run_applypatch_msg_hook(struct am_state
*state
)
487 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
492 if (read_commit_msg(state
) < 0)
493 die(_("'%s' was deleted by the applypatch-msg hook"),
494 am_path(state
, "final-commit"));
501 * Runs post-rewrite hook. Returns it exit code.
503 static int run_post_rewrite_hook(const struct am_state
*state
)
505 struct child_process cp
= CHILD_PROCESS_INIT
;
506 const char *hook
= find_hook("post-rewrite");
512 argv_array_push(&cp
.args
, hook
);
513 argv_array_push(&cp
.args
, "rebase");
515 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
516 cp
.stdout_to_stderr
= 1;
518 ret
= run_command(&cp
);
525 * Reads the state directory's "rewritten" file, and copies notes from the old
526 * commits listed in the file to their rewritten commits.
528 * Returns 0 on success, -1 on failure.
530 static int copy_notes_for_rebase(const struct am_state
*state
)
532 struct notes_rewrite_cfg
*c
;
533 struct strbuf sb
= STRBUF_INIT
;
534 const char *invalid_line
= _("Malformed input line: '%s'.");
535 const char *msg
= "Notes added by 'git rebase'";
539 assert(state
->rebasing
);
541 c
= init_copy_notes_for_rewrite("rebase");
545 fp
= xfopen(am_path(state
, "rewritten"), "r");
547 while (!strbuf_getline(&sb
, fp
, '\n')) {
548 unsigned char from_obj
[GIT_SHA1_RAWSZ
], to_obj
[GIT_SHA1_RAWSZ
];
550 if (sb
.len
!= GIT_SHA1_HEXSZ
* 2 + 1) {
551 ret
= error(invalid_line
, sb
.buf
);
555 if (get_sha1_hex(sb
.buf
, from_obj
)) {
556 ret
= error(invalid_line
, sb
.buf
);
560 if (sb
.buf
[GIT_SHA1_HEXSZ
] != ' ') {
561 ret
= error(invalid_line
, sb
.buf
);
565 if (get_sha1_hex(sb
.buf
+ GIT_SHA1_HEXSZ
+ 1, to_obj
)) {
566 ret
= error(invalid_line
, sb
.buf
);
570 if (copy_note_for_rewrite(c
, from_obj
, to_obj
))
571 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
572 sha1_to_hex(from_obj
), sha1_to_hex(to_obj
));
576 finish_copy_notes_for_rewrite(c
, msg
);
583 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
584 * non-indented lines and checking if they look like they begin with valid
585 * header field names.
587 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
589 static int is_mail(FILE *fp
)
591 const char *header_regex
= "^[!-9;-~]+:";
592 struct strbuf sb
= STRBUF_INIT
;
596 if (fseek(fp
, 0L, SEEK_SET
))
597 die_errno(_("fseek failed"));
599 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
600 die("invalid pattern: %s", header_regex
);
602 while (!strbuf_getline_crlf(&sb
, fp
)) {
604 break; /* End of header */
606 /* Ignore indented folded lines */
607 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
610 /* It's a header if it matches header_regex */
611 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
624 * Attempts to detect the patch_format of the patches contained in `paths`,
625 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
628 static int detect_patch_format(const char **paths
)
630 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
631 struct strbuf l1
= STRBUF_INIT
;
632 struct strbuf l2
= STRBUF_INIT
;
633 struct strbuf l3
= STRBUF_INIT
;
637 * We default to mbox format if input is from stdin and for directories
639 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
640 return PATCH_FORMAT_MBOX
;
643 * Otherwise, check the first few lines of the first patch, starting
644 * from the first non-blank line, to try to detect its format.
647 fp
= xfopen(*paths
, "r");
649 while (!strbuf_getline_crlf(&l1
, fp
)) {
654 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
655 ret
= PATCH_FORMAT_MBOX
;
659 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
660 ret
= PATCH_FORMAT_STGIT_SERIES
;
664 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
665 ret
= PATCH_FORMAT_HG
;
670 strbuf_getline_crlf(&l2
, fp
);
672 strbuf_getline_crlf(&l3
, fp
);
675 * If the second line is empty and the third is a From, Author or Date
676 * entry, this is likely an StGit patch.
678 if (l1
.len
&& !l2
.len
&&
679 (starts_with(l3
.buf
, "From:") ||
680 starts_with(l3
.buf
, "Author:") ||
681 starts_with(l3
.buf
, "Date:"))) {
682 ret
= PATCH_FORMAT_STGIT
;
686 if (l1
.len
&& is_mail(fp
)) {
687 ret
= PATCH_FORMAT_MBOX
;
698 * Splits out individual email patches from `paths`, where each path is either
699 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
701 static int split_mail_mbox(struct am_state
*state
, const char **paths
, int keep_cr
)
703 struct child_process cp
= CHILD_PROCESS_INIT
;
704 struct strbuf last
= STRBUF_INIT
;
707 argv_array_push(&cp
.args
, "mailsplit");
708 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
709 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
710 argv_array_push(&cp
.args
, "-b");
712 argv_array_push(&cp
.args
, "--keep-cr");
713 argv_array_push(&cp
.args
, "--");
714 argv_array_pushv(&cp
.args
, paths
);
716 if (capture_command(&cp
, &last
, 8))
720 state
->last
= strtol(last
.buf
, NULL
, 10);
726 * Callback signature for split_mail_conv(). The foreign patch should be
727 * read from `in`, and the converted patch (in RFC2822 mail format) should be
728 * written to `out`. Return 0 on success, or -1 on failure.
730 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
733 * Calls `fn` for each file in `paths` to convert the foreign patch to the
734 * RFC2822 mail format suitable for parsing with git-mailinfo.
736 * Returns 0 on success, -1 on failure.
738 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
739 const char **paths
, int keep_cr
)
741 static const char *stdin_only
[] = {"-", NULL
};
747 for (i
= 0; *paths
; paths
++, i
++) {
752 if (!strcmp(*paths
, "-"))
755 in
= fopen(*paths
, "r");
758 return error(_("could not open '%s' for reading: %s"),
759 *paths
, strerror(errno
));
761 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
763 out
= fopen(mail
, "w");
765 return error(_("could not open '%s' for writing: %s"),
766 mail
, strerror(errno
));
768 ret
= fn(out
, in
, keep_cr
);
774 return error(_("could not parse patch '%s'"), *paths
);
783 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
784 * message suitable for parsing with git-mailinfo.
786 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
788 struct strbuf sb
= STRBUF_INIT
;
789 int subject_printed
= 0;
791 while (!strbuf_getline(&sb
, in
, '\n')) {
794 if (str_isspace(sb
.buf
))
796 else if (skip_prefix(sb
.buf
, "Author:", &str
))
797 fprintf(out
, "From:%s\n", str
);
798 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
799 fprintf(out
, "%s\n", sb
.buf
);
800 else if (!subject_printed
) {
801 fprintf(out
, "Subject: %s\n", sb
.buf
);
804 fprintf(out
, "\n%s\n", sb
.buf
);
810 while (strbuf_fread(&sb
, 8192, in
) > 0) {
811 fwrite(sb
.buf
, 1, sb
.len
, out
);
820 * This function only supports a single StGit series file in `paths`.
822 * Given an StGit series file, converts the StGit patches in the series into
823 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
824 * the state directory.
826 * Returns 0 on success, -1 on failure.
828 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
831 const char *series_dir
;
832 char *series_dir_buf
;
834 struct argv_array patches
= ARGV_ARRAY_INIT
;
835 struct strbuf sb
= STRBUF_INIT
;
838 if (!paths
[0] || paths
[1])
839 return error(_("Only one StGIT patch series can be applied at once"));
841 series_dir_buf
= xstrdup(*paths
);
842 series_dir
= dirname(series_dir_buf
);
844 fp
= fopen(*paths
, "r");
846 return error(_("could not open '%s' for reading: %s"), *paths
,
849 while (!strbuf_getline(&sb
, fp
, '\n')) {
851 continue; /* skip comment lines */
853 argv_array_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
858 free(series_dir_buf
);
860 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.argv
, keep_cr
);
862 argv_array_clear(&patches
);
867 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
868 * message suitable for parsing with git-mailinfo.
870 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
872 struct strbuf sb
= STRBUF_INIT
;
874 while (!strbuf_getline(&sb
, in
, '\n')) {
877 if (skip_prefix(sb
.buf
, "# User ", &str
))
878 fprintf(out
, "From: %s\n", str
);
879 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
880 unsigned long timestamp
;
885 timestamp
= strtoul(str
, &end
, 10);
887 return error(_("invalid timestamp"));
889 if (!skip_prefix(end
, " ", &str
))
890 return error(_("invalid Date line"));
893 tz
= strtol(str
, &end
, 10);
895 return error(_("invalid timezone offset"));
898 return error(_("invalid Date line"));
901 * mercurial's timezone is in seconds west of UTC,
902 * however git's timezone is in hours + minutes east of
905 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
909 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
910 } else if (starts_with(sb
.buf
, "# ")) {
913 fprintf(out
, "\n%s\n", sb
.buf
);
919 while (strbuf_fread(&sb
, 8192, in
) > 0) {
920 fwrite(sb
.buf
, 1, sb
.len
, out
);
929 * Splits a list of files/directories into individual email patches. Each path
930 * in `paths` must be a file/directory that is formatted according to
933 * Once split out, the individual email patches will be stored in the state
934 * directory, with each patch's filename being its index, padded to state->prec
937 * state->cur will be set to the index of the first mail, and state->last will
938 * be set to the index of the last mail.
940 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
941 * to disable this behavior, -1 to use the default configured setting.
943 * Returns 0 on success, -1 on failure.
945 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
946 const char **paths
, int keep_cr
)
950 git_config_get_bool("am.keepcr", &keep_cr
);
953 switch (patch_format
) {
954 case PATCH_FORMAT_MBOX
:
955 return split_mail_mbox(state
, paths
, keep_cr
);
956 case PATCH_FORMAT_STGIT
:
957 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
958 case PATCH_FORMAT_STGIT_SERIES
:
959 return split_mail_stgit_series(state
, paths
, keep_cr
);
960 case PATCH_FORMAT_HG
:
961 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
963 die("BUG: invalid patch_format");
969 * Setup a new am session for applying patches
971 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
972 const char **paths
, int keep_cr
)
974 unsigned char curr_head
[GIT_SHA1_RAWSZ
];
976 struct strbuf sb
= STRBUF_INIT
;
979 patch_format
= detect_patch_format(paths
);
982 fprintf_ln(stderr
, _("Patch format detection failed."));
986 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
987 die_errno(_("failed to create directory '%s'"), state
->dir
);
989 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
991 die(_("Failed to split patches."));
997 write_file(am_path(state
, "threeway"), 1, state
->threeway
? "t" : "f");
999 write_file(am_path(state
, "quiet"), 1, state
->quiet
? "t" : "f");
1001 write_file(am_path(state
, "sign"), 1, state
->signoff
? "t" : "f");
1003 write_file(am_path(state
, "utf8"), 1, state
->utf8
? "t" : "f");
1005 switch (state
->keep
) {
1012 case KEEP_NON_PATCH
:
1016 die("BUG: invalid value for state->keep");
1019 write_file(am_path(state
, "keep"), 1, "%s", str
);
1021 write_file(am_path(state
, "messageid"), 1, state
->message_id
? "t" : "f");
1023 switch (state
->scissors
) {
1024 case SCISSORS_UNSET
:
1027 case SCISSORS_FALSE
:
1034 die("BUG: invalid value for state->scissors");
1037 write_file(am_path(state
, "scissors"), 1, "%s", str
);
1039 sq_quote_argv(&sb
, state
->git_apply_opts
.argv
, 0);
1040 write_file(am_path(state
, "apply-opt"), 1, "%s", sb
.buf
);
1042 if (state
->rebasing
)
1043 write_file(am_path(state
, "rebasing"), 1, "%s", "");
1045 write_file(am_path(state
, "applying"), 1, "%s", "");
1047 if (!get_sha1("HEAD", curr_head
)) {
1048 write_file(am_path(state
, "abort-safety"), 1, "%s", sha1_to_hex(curr_head
));
1049 if (!state
->rebasing
)
1050 update_ref("am", "ORIG_HEAD", curr_head
, NULL
, 0,
1051 UPDATE_REFS_DIE_ON_ERR
);
1053 write_file(am_path(state
, "abort-safety"), 1, "%s", "");
1054 if (!state
->rebasing
)
1055 delete_ref("ORIG_HEAD", NULL
, 0);
1059 * NOTE: Since the "next" and "last" files determine if an am_state
1060 * session is in progress, they should be written last.
1063 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
1065 write_file(am_path(state
, "last"), 1, "%d", state
->last
);
1067 strbuf_release(&sb
);
1071 * Increments the patch pointer, and cleans am_state for the application of the
1074 static void am_next(struct am_state
*state
)
1076 unsigned char head
[GIT_SHA1_RAWSZ
];
1078 free(state
->author_name
);
1079 state
->author_name
= NULL
;
1081 free(state
->author_email
);
1082 state
->author_email
= NULL
;
1084 free(state
->author_date
);
1085 state
->author_date
= NULL
;
1091 unlink(am_path(state
, "author-script"));
1092 unlink(am_path(state
, "final-commit"));
1094 hashclr(state
->orig_commit
);
1095 unlink(am_path(state
, "original-commit"));
1097 if (!get_sha1("HEAD", head
))
1098 write_file(am_path(state
, "abort-safety"), 1, "%s", sha1_to_hex(head
));
1100 write_file(am_path(state
, "abort-safety"), 1, "%s", "");
1103 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
1107 * Returns the filename of the current patch email.
1109 static const char *msgnum(const struct am_state
*state
)
1111 static struct strbuf sb
= STRBUF_INIT
;
1114 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1120 * Refresh and write index.
1122 static void refresh_and_write_cache(void)
1124 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
1126 hold_locked_index(lock_file
, 1);
1127 refresh_cache(REFRESH_QUIET
);
1128 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1129 die(_("unable to write index file"));
1133 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1134 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1135 * strbuf is provided, the space-separated list of files that differ will be
1138 static int index_has_changes(struct strbuf
*sb
)
1140 unsigned char head
[GIT_SHA1_RAWSZ
];
1143 if (!get_sha1_tree("HEAD", head
)) {
1144 struct diff_options opt
;
1147 DIFF_OPT_SET(&opt
, EXIT_WITH_STATUS
);
1149 DIFF_OPT_SET(&opt
, QUICK
);
1150 do_diff_cache(head
, &opt
);
1152 for (i
= 0; sb
&& i
< diff_queued_diff
.nr
; i
++) {
1154 strbuf_addch(sb
, ' ');
1155 strbuf_addstr(sb
, diff_queued_diff
.queue
[i
]->two
->path
);
1158 return DIFF_OPT_TST(&opt
, HAS_CHANGES
) != 0;
1160 for (i
= 0; sb
&& i
< active_nr
; i
++) {
1162 strbuf_addch(sb
, ' ');
1163 strbuf_addstr(sb
, active_cache
[i
]->name
);
1170 * Dies with a user-friendly message on how to proceed after resolving the
1171 * problem. This message can be overridden with state->resolvemsg.
1173 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1175 if (state
->resolvemsg
) {
1176 printf_ln("%s", state
->resolvemsg
);
1178 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1180 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1181 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1182 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1189 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1190 * state->msg will be set to the patch message. state->author_name,
1191 * state->author_email and state->author_date will be set to the patch author's
1192 * name, email and date respectively. The patch body will be written to the
1193 * state directory's "patch" file.
1195 * Returns 1 if the patch should be skipped, 0 otherwise.
1197 static int parse_mail(struct am_state
*state
, const char *mail
)
1200 struct child_process cp
= CHILD_PROCESS_INIT
;
1201 struct strbuf sb
= STRBUF_INIT
;
1202 struct strbuf msg
= STRBUF_INIT
;
1203 struct strbuf author_name
= STRBUF_INIT
;
1204 struct strbuf author_date
= STRBUF_INIT
;
1205 struct strbuf author_email
= STRBUF_INIT
;
1209 cp
.in
= xopen(mail
, O_RDONLY
, 0);
1210 cp
.out
= xopen(am_path(state
, "info"), O_WRONLY
| O_CREAT
, 0777);
1212 argv_array_push(&cp
.args
, "mailinfo");
1213 argv_array_push(&cp
.args
, state
->utf8
? "-u" : "-n");
1215 switch (state
->keep
) {
1219 argv_array_push(&cp
.args
, "-k");
1221 case KEEP_NON_PATCH
:
1222 argv_array_push(&cp
.args
, "-b");
1225 die("BUG: invalid value for state->keep");
1228 if (state
->message_id
)
1229 argv_array_push(&cp
.args
, "-m");
1231 switch (state
->scissors
) {
1232 case SCISSORS_UNSET
:
1234 case SCISSORS_FALSE
:
1235 argv_array_push(&cp
.args
, "--no-scissors");
1238 argv_array_push(&cp
.args
, "--scissors");
1241 die("BUG: invalid value for state->scissors");
1244 argv_array_push(&cp
.args
, am_path(state
, "msg"));
1245 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1247 if (run_command(&cp
) < 0)
1248 die("could not parse patch");
1253 /* Extract message and author information */
1254 fp
= xfopen(am_path(state
, "info"), "r");
1255 while (!strbuf_getline(&sb
, fp
, '\n')) {
1258 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1260 strbuf_addch(&msg
, '\n');
1261 strbuf_addstr(&msg
, x
);
1262 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1263 strbuf_addstr(&author_name
, x
);
1264 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1265 strbuf_addstr(&author_email
, x
);
1266 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1267 strbuf_addstr(&author_date
, x
);
1271 /* Skip pine's internal folder data */
1272 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1277 if (is_empty_file(am_path(state
, "patch"))) {
1278 printf_ln(_("Patch is empty. Was it split wrong?"));
1279 die_user_resolve(state
);
1282 strbuf_addstr(&msg
, "\n\n");
1283 if (strbuf_read_file(&msg
, am_path(state
, "msg"), 0) < 0)
1284 die_errno(_("could not read '%s'"), am_path(state
, "msg"));
1285 stripspace(&msg
, 0);
1288 append_signoff(&msg
, 0, 0);
1290 assert(!state
->author_name
);
1291 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1293 assert(!state
->author_email
);
1294 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1296 assert(!state
->author_date
);
1297 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1299 assert(!state
->msg
);
1300 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1303 strbuf_release(&msg
);
1304 strbuf_release(&author_date
);
1305 strbuf_release(&author_email
);
1306 strbuf_release(&author_name
);
1307 strbuf_release(&sb
);
1312 * Sets commit_id to the commit hash where the mail was generated from.
1313 * Returns 0 on success, -1 on failure.
1315 static int get_mail_commit_sha1(unsigned char *commit_id
, const char *mail
)
1317 struct strbuf sb
= STRBUF_INIT
;
1318 FILE *fp
= xfopen(mail
, "r");
1321 if (strbuf_getline(&sb
, fp
, '\n'))
1324 if (!skip_prefix(sb
.buf
, "From ", &x
))
1327 if (get_sha1_hex(x
, commit_id
) < 0)
1330 strbuf_release(&sb
);
1336 * Sets state->msg, state->author_name, state->author_email, state->author_date
1337 * to the commit's respective info.
1339 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1341 const char *buffer
, *ident_line
, *author_date
, *msg
;
1343 struct ident_split ident_split
;
1344 struct strbuf sb
= STRBUF_INIT
;
1346 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1348 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1350 if (split_ident_line(&ident_split
, ident_line
, ident_len
) < 0) {
1351 strbuf_add(&sb
, ident_line
, ident_len
);
1352 die(_("invalid ident line: %s"), sb
.buf
);
1355 assert(!state
->author_name
);
1356 if (ident_split
.name_begin
) {
1357 strbuf_add(&sb
, ident_split
.name_begin
,
1358 ident_split
.name_end
- ident_split
.name_begin
);
1359 state
->author_name
= strbuf_detach(&sb
, NULL
);
1361 state
->author_name
= xstrdup("");
1363 assert(!state
->author_email
);
1364 if (ident_split
.mail_begin
) {
1365 strbuf_add(&sb
, ident_split
.mail_begin
,
1366 ident_split
.mail_end
- ident_split
.mail_begin
);
1367 state
->author_email
= strbuf_detach(&sb
, NULL
);
1369 state
->author_email
= xstrdup("");
1371 author_date
= show_ident_date(&ident_split
, DATE_MODE(NORMAL
));
1372 strbuf_addstr(&sb
, author_date
);
1373 assert(!state
->author_date
);
1374 state
->author_date
= strbuf_detach(&sb
, NULL
);
1376 assert(!state
->msg
);
1377 msg
= strstr(buffer
, "\n\n");
1379 die(_("unable to parse commit %s"), sha1_to_hex(commit
->object
.sha1
));
1380 state
->msg
= xstrdup(msg
+ 2);
1381 state
->msg_len
= strlen(state
->msg
);
1385 * Writes `commit` as a patch to the state directory's "patch" file.
1387 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1389 struct rev_info rev_info
;
1392 fp
= xfopen(am_path(state
, "patch"), "w");
1393 init_revisions(&rev_info
, NULL
);
1395 rev_info
.abbrev
= 0;
1396 rev_info
.disable_stdin
= 1;
1397 rev_info
.show_root_diff
= 1;
1398 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1399 rev_info
.no_commit_id
= 1;
1400 DIFF_OPT_SET(&rev_info
.diffopt
, BINARY
);
1401 DIFF_OPT_SET(&rev_info
.diffopt
, FULL_INDEX
);
1402 rev_info
.diffopt
.use_color
= 0;
1403 rev_info
.diffopt
.file
= fp
;
1404 rev_info
.diffopt
.close_file
= 1;
1405 add_pending_object(&rev_info
, &commit
->object
, "");
1406 diff_setup_done(&rev_info
.diffopt
);
1407 log_tree_commit(&rev_info
, commit
);
1411 * Writes the diff of the index against HEAD as a patch to the state
1412 * directory's "patch" file.
1414 static void write_index_patch(const struct am_state
*state
)
1417 unsigned char head
[GIT_SHA1_RAWSZ
];
1418 struct rev_info rev_info
;
1421 if (!get_sha1_tree("HEAD", head
))
1422 tree
= lookup_tree(head
);
1424 tree
= lookup_tree(EMPTY_TREE_SHA1_BIN
);
1426 fp
= xfopen(am_path(state
, "patch"), "w");
1427 init_revisions(&rev_info
, NULL
);
1429 rev_info
.disable_stdin
= 1;
1430 rev_info
.no_commit_id
= 1;
1431 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1432 rev_info
.diffopt
.use_color
= 0;
1433 rev_info
.diffopt
.file
= fp
;
1434 rev_info
.diffopt
.close_file
= 1;
1435 add_pending_object(&rev_info
, &tree
->object
, "");
1436 diff_setup_done(&rev_info
.diffopt
);
1437 run_diff_index(&rev_info
, 1);
1441 * Like parse_mail(), but parses the mail by looking up its commit ID
1442 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1445 * state->orig_commit will be set to the original commit ID.
1447 * Will always return 0 as the patch should never be skipped.
1449 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1451 struct commit
*commit
;
1452 unsigned char commit_sha1
[GIT_SHA1_RAWSZ
];
1454 if (get_mail_commit_sha1(commit_sha1
, mail
) < 0)
1455 die(_("could not parse %s"), mail
);
1457 commit
= lookup_commit_or_die(commit_sha1
, mail
);
1459 get_commit_info(state
, commit
);
1461 write_commit_patch(state
, commit
);
1463 hashcpy(state
->orig_commit
, commit_sha1
);
1464 write_file(am_path(state
, "original-commit"), 1, "%s",
1465 sha1_to_hex(commit_sha1
));
1471 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1472 * `index_file` is not NULL, the patch will be applied to that index.
1474 static int run_apply(const struct am_state
*state
, const char *index_file
)
1476 struct child_process cp
= CHILD_PROCESS_INIT
;
1481 argv_array_pushf(&cp
.env_array
, "GIT_INDEX_FILE=%s", index_file
);
1484 * If we are allowed to fall back on 3-way merge, don't give false
1485 * errors during the initial attempt.
1487 if (state
->threeway
&& !index_file
) {
1492 argv_array_push(&cp
.args
, "apply");
1494 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1497 argv_array_push(&cp
.args
, "--cached");
1499 argv_array_push(&cp
.args
, "--index");
1501 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1503 if (run_command(&cp
))
1506 /* Reload index as git-apply will have modified it. */
1508 read_cache_from(index_file
? index_file
: get_index_file());
1514 * Builds an index that contains just the blobs needed for a 3way merge.
1516 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1518 struct child_process cp
= CHILD_PROCESS_INIT
;
1521 argv_array_push(&cp
.args
, "apply");
1522 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1523 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1524 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1526 if (run_command(&cp
))
1533 * Attempt a threeway merge, using index_path as the temporary index.
1535 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1537 unsigned char orig_tree
[GIT_SHA1_RAWSZ
], his_tree
[GIT_SHA1_RAWSZ
],
1538 our_tree
[GIT_SHA1_RAWSZ
];
1539 const unsigned char *bases
[1] = {orig_tree
};
1540 struct merge_options o
;
1541 struct commit
*result
;
1542 char *his_tree_name
;
1544 if (get_sha1("HEAD", our_tree
) < 0)
1545 hashcpy(our_tree
, EMPTY_TREE_SHA1_BIN
);
1547 if (build_fake_ancestor(state
, index_path
))
1548 return error("could not build fake ancestor");
1551 read_cache_from(index_path
);
1553 if (write_index_as_tree(orig_tree
, &the_index
, index_path
, 0, NULL
))
1554 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1556 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1558 if (!state
->quiet
) {
1560 * List paths that needed 3-way fallback, so that the user can
1561 * review them with extra care to spot mismerges.
1563 struct rev_info rev_info
;
1564 const char *diff_filter_str
= "--diff-filter=AM";
1566 init_revisions(&rev_info
, NULL
);
1567 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1568 diff_opt_parse(&rev_info
.diffopt
, &diff_filter_str
, 1);
1569 add_pending_sha1(&rev_info
, "HEAD", our_tree
, 0);
1570 diff_setup_done(&rev_info
.diffopt
);
1571 run_diff_index(&rev_info
, 1);
1574 if (run_apply(state
, index_path
))
1575 return error(_("Did you hand edit your patch?\n"
1576 "It does not apply to blobs recorded in its index."));
1578 if (write_index_as_tree(his_tree
, &the_index
, index_path
, 0, NULL
))
1579 return error("could not write tree");
1581 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1587 * This is not so wrong. Depending on which base we picked, orig_tree
1588 * may be wildly different from ours, but his_tree has the same set of
1589 * wildly different changes in parts the patch did not touch, so
1590 * recursive ends up canceling them, saying that we reverted all those
1594 init_merge_options(&o
);
1597 his_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1598 o
.branch2
= his_tree_name
;
1603 if (merge_recursive_generic(&o
, our_tree
, his_tree
, 1, bases
, &result
)) {
1604 rerere(state
->allow_rerere_autoupdate
);
1605 free(his_tree_name
);
1606 return error(_("Failed to merge in the changes."));
1609 free(his_tree_name
);
1614 * Commits the current index with state->msg as the commit message and
1615 * state->author_name, state->author_email and state->author_date as the author
1618 static void do_commit(const struct am_state
*state
)
1620 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
1621 commit
[GIT_SHA1_RAWSZ
];
1623 struct commit_list
*parents
= NULL
;
1624 const char *reflog_msg
, *author
;
1625 struct strbuf sb
= STRBUF_INIT
;
1627 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1630 if (write_cache_as_tree(tree
, 0, NULL
))
1631 die(_("git write-tree failed to write a tree"));
1633 if (!get_sha1_commit("HEAD", parent
)) {
1635 commit_list_insert(lookup_commit(parent
), &parents
);
1638 say(state
, stderr
, _("applying to an empty history"));
1641 author
= fmt_ident(state
->author_name
, state
->author_email
,
1642 state
->ignore_date
? NULL
: state
->author_date
,
1645 if (state
->committer_date_is_author_date
)
1646 setenv("GIT_COMMITTER_DATE",
1647 state
->ignore_date
? "" : state
->author_date
, 1);
1649 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
1650 author
, state
->sign_commit
))
1651 die(_("failed to write commit object"));
1653 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1657 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1660 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
1662 if (state
->rebasing
) {
1663 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1665 assert(!is_null_sha1(state
->orig_commit
));
1666 fprintf(fp
, "%s ", sha1_to_hex(state
->orig_commit
));
1667 fprintf(fp
, "%s\n", sha1_to_hex(commit
));
1671 run_hook_le(NULL
, "post-applypatch", NULL
);
1673 strbuf_release(&sb
);
1677 * Validates the am_state for resuming -- the "msg" and authorship fields must
1680 static void validate_resume_state(const struct am_state
*state
)
1683 die(_("cannot resume: %s does not exist."),
1684 am_path(state
, "final-commit"));
1686 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1687 die(_("cannot resume: %s does not exist."),
1688 am_path(state
, "author-script"));
1692 * Interactively prompt the user on whether the current patch should be
1695 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1698 static int do_interactive(struct am_state
*state
)
1703 die(_("cannot be interactive without stdin connected to a terminal."));
1708 puts(_("Commit Body is:"));
1709 puts("--------------------------");
1710 printf("%s", state
->msg
);
1711 puts("--------------------------");
1714 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1715 * in your translation. The program will only accept English
1716 * input at this point.
1718 reply
= git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO
);
1722 } else if (*reply
== 'y' || *reply
== 'Y') {
1724 } else if (*reply
== 'a' || *reply
== 'A') {
1725 state
->interactive
= 0;
1727 } else if (*reply
== 'n' || *reply
== 'N') {
1729 } else if (*reply
== 'e' || *reply
== 'E') {
1730 struct strbuf msg
= STRBUF_INIT
;
1732 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1734 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1736 strbuf_release(&msg
);
1737 } else if (*reply
== 'v' || *reply
== 'V') {
1738 const char *pager
= git_pager(1);
1739 struct child_process cp
= CHILD_PROCESS_INIT
;
1743 argv_array_push(&cp
.args
, pager
);
1744 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1751 * Applies all queued mail.
1753 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1754 * well as the state directory's "patch" file is used as-is for applying the
1755 * patch and committing it.
1757 static void am_run(struct am_state
*state
, int resume
)
1759 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1760 struct strbuf sb
= STRBUF_INIT
;
1762 unlink(am_path(state
, "dirtyindex"));
1764 refresh_and_write_cache();
1766 if (index_has_changes(&sb
)) {
1767 write_file(am_path(state
, "dirtyindex"), 1, "t");
1768 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1771 strbuf_release(&sb
);
1773 while (state
->cur
<= state
->last
) {
1774 const char *mail
= am_path(state
, msgnum(state
));
1777 if (!file_exists(mail
))
1781 validate_resume_state(state
);
1785 if (state
->rebasing
)
1786 skip
= parse_mail_rebase(state
, mail
);
1788 skip
= parse_mail(state
, mail
);
1791 goto next
; /* mail should be skipped */
1793 write_author_script(state
);
1794 write_commit_msg(state
);
1797 if (state
->interactive
&& do_interactive(state
))
1800 if (run_applypatch_msg_hook(state
))
1803 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1805 apply_status
= run_apply(state
, NULL
);
1807 if (apply_status
&& state
->threeway
) {
1808 struct strbuf sb
= STRBUF_INIT
;
1810 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1811 apply_status
= fall_back_threeway(state
, sb
.buf
);
1812 strbuf_release(&sb
);
1815 * Applying the patch to an earlier tree and merging
1816 * the result may have produced the same tree as ours.
1818 if (!apply_status
&& !index_has_changes(NULL
)) {
1819 say(state
, stdout
, _("No changes -- Patch already applied."));
1825 int advice_amworkdir
= 1;
1827 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1828 linelen(state
->msg
), state
->msg
);
1830 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
1832 if (advice_amworkdir
)
1833 printf_ln(_("The copy of the patch that failed is found in: %s"),
1834 am_path(state
, "patch"));
1836 die_user_resolve(state
);
1849 if (!is_empty_file(am_path(state
, "rewritten"))) {
1850 assert(state
->rebasing
);
1851 copy_notes_for_rebase(state
);
1852 run_post_rewrite_hook(state
);
1856 * In rebasing mode, it's up to the caller to take care of
1859 if (!state
->rebasing
) {
1861 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1866 * Resume the current am session after patch application failure. The user did
1867 * all the hard work, and we do not have to do any patch application. Just
1868 * trust and commit what the user has in the index and working tree.
1870 static void am_resolve(struct am_state
*state
)
1872 validate_resume_state(state
);
1874 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1876 if (!index_has_changes(NULL
)) {
1877 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1878 "If there is nothing left to stage, chances are that something else\n"
1879 "already introduced the same changes; you might want to skip this patch."));
1880 die_user_resolve(state
);
1883 if (unmerged_cache()) {
1884 printf_ln(_("You still have unmerged paths in your index.\n"
1885 "Did you forget to use 'git add'?"));
1886 die_user_resolve(state
);
1889 if (state
->interactive
) {
1890 write_index_patch(state
);
1891 if (do_interactive(state
))
1906 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1907 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1910 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1912 struct lock_file
*lock_file
;
1913 struct unpack_trees_options opts
;
1914 struct tree_desc t
[2];
1916 if (parse_tree(head
) || parse_tree(remote
))
1919 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1920 hold_locked_index(lock_file
, 1);
1922 refresh_cache(REFRESH_QUIET
);
1924 memset(&opts
, 0, sizeof(opts
));
1926 opts
.src_index
= &the_index
;
1927 opts
.dst_index
= &the_index
;
1931 opts
.fn
= twoway_merge
;
1932 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1933 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1935 if (unpack_trees(2, t
, &opts
)) {
1936 rollback_lock_file(lock_file
);
1940 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1941 die(_("unable to write new index file"));
1947 * Clean the index without touching entries that are not modified between
1948 * `head` and `remote`.
1950 static int clean_index(const unsigned char *head
, const unsigned char *remote
)
1952 struct lock_file
*lock_file
;
1953 struct tree
*head_tree
, *remote_tree
, *index_tree
;
1954 unsigned char index
[GIT_SHA1_RAWSZ
];
1955 struct pathspec pathspec
;
1957 head_tree
= parse_tree_indirect(head
);
1959 return error(_("Could not parse object '%s'."), sha1_to_hex(head
));
1961 remote_tree
= parse_tree_indirect(remote
);
1963 return error(_("Could not parse object '%s'."), sha1_to_hex(remote
));
1965 read_cache_unmerged();
1967 if (fast_forward_to(head_tree
, head_tree
, 1))
1970 if (write_cache_as_tree(index
, 0, NULL
))
1973 index_tree
= parse_tree_indirect(index
);
1975 return error(_("Could not parse object '%s'."), sha1_to_hex(index
));
1977 if (fast_forward_to(index_tree
, remote_tree
, 0))
1980 memset(&pathspec
, 0, sizeof(pathspec
));
1982 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1983 hold_locked_index(lock_file
, 1);
1985 if (read_tree(remote_tree
, 0, &pathspec
)) {
1986 rollback_lock_file(lock_file
);
1990 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1991 die(_("unable to write new index file"));
1993 remove_branch_state();
1999 * Resets rerere's merge resolution metadata.
2001 static void am_rerere_clear(void)
2003 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
2004 int fd
= setup_rerere(&merge_rr
, 0);
2009 rerere_clear(&merge_rr
);
2010 string_list_clear(&merge_rr
, 1);
2014 * Resume the current am session by skipping the current patch.
2016 static void am_skip(struct am_state
*state
)
2018 unsigned char head
[GIT_SHA1_RAWSZ
];
2022 if (get_sha1("HEAD", head
))
2023 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
2025 if (clean_index(head
, head
))
2026 die(_("failed to clean index"));
2034 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2036 * It is not safe to reset HEAD when:
2037 * 1. git-am previously failed because the index was dirty.
2038 * 2. HEAD has moved since git-am previously failed.
2040 static int safe_to_abort(const struct am_state
*state
)
2042 struct strbuf sb
= STRBUF_INIT
;
2043 unsigned char abort_safety
[GIT_SHA1_RAWSZ
], head
[GIT_SHA1_RAWSZ
];
2045 if (file_exists(am_path(state
, "dirtyindex")))
2048 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2049 if (get_sha1_hex(sb
.buf
, abort_safety
))
2050 die(_("could not parse %s"), am_path(state
, "abort_safety"));
2052 hashclr(abort_safety
);
2054 if (get_sha1("HEAD", head
))
2057 if (!hashcmp(head
, abort_safety
))
2060 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2061 "Not rewinding to ORIG_HEAD"));
2067 * Aborts the current am session if it is safe to do so.
2069 static void am_abort(struct am_state
*state
)
2071 unsigned char curr_head
[GIT_SHA1_RAWSZ
], orig_head
[GIT_SHA1_RAWSZ
];
2072 int has_curr_head
, has_orig_head
;
2075 if (!safe_to_abort(state
)) {
2082 curr_branch
= resolve_refdup("HEAD", 0, curr_head
, NULL
);
2083 has_curr_head
= !is_null_sha1(curr_head
);
2085 hashcpy(curr_head
, EMPTY_TREE_SHA1_BIN
);
2087 has_orig_head
= !get_sha1("ORIG_HEAD", orig_head
);
2089 hashcpy(orig_head
, EMPTY_TREE_SHA1_BIN
);
2091 clean_index(curr_head
, orig_head
);
2094 update_ref("am --abort", "HEAD", orig_head
,
2095 has_curr_head
? curr_head
: NULL
, 0,
2096 UPDATE_REFS_DIE_ON_ERR
);
2097 else if (curr_branch
)
2098 delete_ref(curr_branch
, NULL
, REF_NODEREF
);
2105 * parse_options() callback that validates and sets opt->value to the
2106 * PATCH_FORMAT_* enum value corresponding to `arg`.
2108 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2110 int *opt_value
= opt
->value
;
2112 if (!strcmp(arg
, "mbox"))
2113 *opt_value
= PATCH_FORMAT_MBOX
;
2114 else if (!strcmp(arg
, "stgit"))
2115 *opt_value
= PATCH_FORMAT_STGIT
;
2116 else if (!strcmp(arg
, "stgit-series"))
2117 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2118 else if (!strcmp(arg
, "hg"))
2119 *opt_value
= PATCH_FORMAT_HG
;
2121 return error(_("Invalid value for --patch-format: %s"), arg
);
2133 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2135 struct am_state state
;
2138 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2139 enum resume_mode resume
= RESUME_FALSE
;
2142 const char * const usage
[] = {
2143 N_("git am [options] [(<mbox>|<Maildir>)...]"),
2144 N_("git am [options] (--continue | --skip | --abort)"),
2148 struct option options
[] = {
2149 OPT_BOOL('i', "interactive", &state
.interactive
,
2150 N_("run interactively")),
2151 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2152 N_("(historical option -- no-op")),
2153 OPT_BOOL('3', "3way", &state
.threeway
,
2154 N_("allow fall back on 3way merging if needed")),
2155 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2156 OPT_BOOL('s', "signoff", &state
.signoff
,
2157 N_("add a Signed-off-by line to the commit message")),
2158 OPT_BOOL('u', "utf8", &state
.utf8
,
2159 N_("recode into utf8 (default)")),
2160 OPT_SET_INT('k', "keep", &state
.keep
,
2161 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2162 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2163 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2164 OPT_BOOL('m', "message-id", &state
.message_id
,
2165 N_("pass -m flag to git-mailinfo")),
2166 { OPTION_SET_INT
, 0, "keep-cr", &keep_cr
, NULL
,
2167 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2168 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 1},
2169 { OPTION_SET_INT
, 0, "no-keep-cr", &keep_cr
, NULL
,
2170 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2171 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 0},
2172 OPT_BOOL('c', "scissors", &state
.scissors
,
2173 N_("strip everything before a scissors line")),
2174 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2175 N_("pass it through git-apply"),
2177 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2178 N_("pass it through git-apply"),
2180 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2181 N_("pass it through git-apply"),
2183 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2184 N_("pass it through git-apply"),
2186 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2187 N_("pass it through git-apply"),
2189 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2190 N_("pass it through git-apply"),
2192 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2193 N_("pass it through git-apply"),
2195 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2196 N_("pass it through git-apply"),
2198 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2199 N_("format the patch(es) are in"),
2200 parse_opt_patchformat
),
2201 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2202 N_("pass it through git-apply"),
2204 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2205 N_("override error message when patch failure occurs")),
2206 OPT_CMDMODE(0, "continue", &resume
,
2207 N_("continue applying patches after resolving a conflict"),
2209 OPT_CMDMODE('r', "resolved", &resume
,
2210 N_("synonyms for --continue"),
2212 OPT_CMDMODE(0, "skip", &resume
,
2213 N_("skip the current patch"),
2215 OPT_CMDMODE(0, "abort", &resume
,
2216 N_("restore the original branch and abort the patching operation."),
2218 OPT_BOOL(0, "committer-date-is-author-date",
2219 &state
.committer_date_is_author_date
,
2220 N_("lie about committer date")),
2221 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2222 N_("use current timestamp for author date")),
2223 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2224 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2225 N_("GPG-sign commits"),
2226 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2227 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2228 N_("(internal use for git-rebase)")),
2232 git_config(git_default_config
, NULL
);
2234 am_state_init(&state
, git_path("rebase-apply"));
2236 in_progress
= am_in_progress(&state
);
2240 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2243 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2244 "it will be removed. Please do not use it anymore."));
2246 /* Ensure a valid committer ident can be constructed */
2247 git_committer_info(IDENT_STRICT
);
2249 if (read_index_preload(&the_index
, NULL
) < 0)
2250 die(_("failed to read the index"));
2254 * Catch user error to feed us patches when there is a session
2257 * 1. mbox path(s) are provided on the command-line.
2258 * 2. stdin is not a tty: the user is trying to feed us a patch
2259 * from standard input. This is somewhat unreliable -- stdin
2260 * could be /dev/null for example and the caller did not
2261 * intend to feed us a patch but wanted to continue
2264 if (argc
|| (resume
== RESUME_FALSE
&& !isatty(0)))
2265 die(_("previous rebase directory %s still exists but mbox given."),
2268 if (resume
== RESUME_FALSE
)
2269 resume
= RESUME_APPLY
;
2271 struct argv_array paths
= ARGV_ARRAY_INIT
;
2275 * Handle stray state directory in the independent-run case. In
2276 * the --rebasing case, it is up to the caller to take care of
2277 * stray directories.
2279 if (file_exists(state
.dir
) && !state
.rebasing
) {
2280 if (resume
== RESUME_ABORT
) {
2282 am_state_release(&state
);
2286 die(_("Stray %s directory found.\n"
2287 "Use \"git am --abort\" to remove it."),
2292 die(_("Resolve operation not in progress, we are not resuming."));
2294 for (i
= 0; i
< argc
; i
++) {
2295 if (is_absolute_path(argv
[i
]) || !prefix
)
2296 argv_array_push(&paths
, argv
[i
]);
2298 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2301 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
2303 argv_array_clear(&paths
);
2313 case RESUME_RESOLVED
:
2323 die("BUG: invalid resume value");
2326 am_state_release(&state
);