4 * Based on git-am.sh by Junio C Hamano.
9 #include "parse-options.h"
11 #include "run-command.h"
15 #include "cache-tree.h"
20 #include "unpack-trees.h"
22 #include "sequencer.h"
24 #include "merge-recursive.h"
27 #include "notes-utils.h"
32 * Returns 1 if the file is empty or does not exist, 0 otherwise.
34 static int is_empty_file(const char *filename
)
38 if (stat(filename
, &st
) < 0) {
41 die_errno(_("could not stat %s"), filename
);
48 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
50 static int strbuf_getline_crlf(struct strbuf
*sb
, FILE *fp
)
52 if (strbuf_getwholeline(sb
, fp
, '\n'))
54 if (sb
->buf
[sb
->len
- 1] == '\n') {
55 strbuf_setlen(sb
, sb
->len
- 1);
56 if (sb
->len
> 0 && sb
->buf
[sb
->len
- 1] == '\r')
57 strbuf_setlen(sb
, sb
->len
- 1);
63 * Returns the length of the first line of msg.
65 static int linelen(const char *msg
)
67 return strchrnul(msg
, '\n') - msg
;
71 * Returns true if `str` consists of only whitespace, false otherwise.
73 static int str_isspace(const char *str
)
83 PATCH_FORMAT_UNKNOWN
= 0,
86 PATCH_FORMAT_STGIT_SERIES
,
92 KEEP_TRUE
, /* pass -k flag to git-mailinfo */
93 KEEP_NON_PATCH
/* pass -b flag to git-mailinfo */
98 SCISSORS_FALSE
= 0, /* pass --no-scissors to git-mailinfo */
99 SCISSORS_TRUE
/* pass --scissors to git-mailinfo */
105 SIGNOFF_EXPLICIT
/* --signoff was set on the command-line */
109 /* state directory path */
112 /* current and last patch numbers, 1-indexed */
116 /* commit metadata and message */
123 /* when --rebasing, records the original commit the patch came from */
124 unsigned char orig_commit
[GIT_SHA1_RAWSZ
];
126 /* number of digits in patch filename */
129 /* various operating modes and command line options */
133 int signoff
; /* enum signoff_type */
135 int keep
; /* enum keep_type */
137 int scissors
; /* enum scissors_type */
138 struct argv_array git_apply_opts
;
139 const char *resolvemsg
;
140 int committer_date_is_author_date
;
142 int allow_rerere_autoupdate
;
143 const char *sign_commit
;
148 * Initializes am_state with the default values. The state directory is set to
151 static void am_state_init(struct am_state
*state
, const char *dir
)
155 memset(state
, 0, sizeof(*state
));
158 state
->dir
= xstrdup(dir
);
162 git_config_get_bool("am.threeway", &state
->threeway
);
166 git_config_get_bool("am.messageid", &state
->message_id
);
168 state
->scissors
= SCISSORS_UNSET
;
170 argv_array_init(&state
->git_apply_opts
);
172 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
173 state
->sign_commit
= gpgsign
? "" : NULL
;
177 * Releases memory allocated by an am_state.
179 static void am_state_release(struct am_state
*state
)
182 free(state
->author_name
);
183 free(state
->author_email
);
184 free(state
->author_date
);
186 argv_array_clear(&state
->git_apply_opts
);
190 * Returns path relative to the am_state directory.
192 static inline const char *am_path(const struct am_state
*state
, const char *path
)
194 return mkpath("%s/%s", state
->dir
, path
);
198 * For convenience to call write_file()
200 static int write_state_text(const struct am_state
*state
,
201 const char *name
, const char *string
)
203 return write_file(am_path(state
, name
), "%s", string
);
206 static int write_state_count(const struct am_state
*state
,
207 const char *name
, int value
)
209 return write_file(am_path(state
, name
), "%d", value
);
212 static int write_state_bool(const struct am_state
*state
,
213 const char *name
, int value
)
215 return write_state_text(state
, name
, value
? "t" : "f");
219 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
222 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
228 vfprintf(fp
, fmt
, ap
);
235 * Returns 1 if there is an am session in progress, 0 otherwise.
237 static int am_in_progress(const struct am_state
*state
)
241 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
243 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
245 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
251 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
252 * number of bytes read on success, -1 if the file does not exist. If `trim` is
253 * set, trailing whitespace will be removed.
255 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
256 const char *file
, int trim
)
260 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
270 die_errno(_("could not read '%s'"), am_path(state
, file
));
274 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
275 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
276 * match `key`. Returns NULL on failure.
278 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
281 static char *read_shell_var(FILE *fp
, const char *key
)
283 struct strbuf sb
= STRBUF_INIT
;
286 if (strbuf_getline(&sb
, fp
, '\n'))
289 if (!skip_prefix(sb
.buf
, key
, &str
))
292 if (!skip_prefix(str
, "=", &str
))
295 strbuf_remove(&sb
, 0, str
- sb
.buf
);
297 str
= sq_dequote(sb
.buf
);
301 return strbuf_detach(&sb
, NULL
);
309 * Reads and parses the state directory's "author-script" file, and sets
310 * state->author_name, state->author_email and state->author_date accordingly.
311 * Returns 0 on success, -1 if the file could not be parsed.
313 * The author script is of the format:
315 * GIT_AUTHOR_NAME='$author_name'
316 * GIT_AUTHOR_EMAIL='$author_email'
317 * GIT_AUTHOR_DATE='$author_date'
319 * where $author_name, $author_email and $author_date are quoted. We are strict
320 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
321 * script, and thus if the file differs from what this function expects, it is
322 * better to bail out than to do something that the user does not expect.
324 static int read_author_script(struct am_state
*state
)
326 const char *filename
= am_path(state
, "author-script");
329 assert(!state
->author_name
);
330 assert(!state
->author_email
);
331 assert(!state
->author_date
);
333 fp
= fopen(filename
, "r");
337 die_errno(_("could not open '%s' for reading"), filename
);
340 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
341 if (!state
->author_name
) {
346 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
347 if (!state
->author_email
) {
352 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
353 if (!state
->author_date
) {
358 if (fgetc(fp
) != EOF
) {
368 * Saves state->author_name, state->author_email and state->author_date in the
369 * state directory's "author-script" file.
371 static void write_author_script(const struct am_state
*state
)
373 struct strbuf sb
= STRBUF_INIT
;
375 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
376 sq_quote_buf(&sb
, state
->author_name
);
377 strbuf_addch(&sb
, '\n');
379 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
380 sq_quote_buf(&sb
, state
->author_email
);
381 strbuf_addch(&sb
, '\n');
383 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
384 sq_quote_buf(&sb
, state
->author_date
);
385 strbuf_addch(&sb
, '\n');
387 write_state_text(state
, "author-script", sb
.buf
);
393 * Reads the commit message from the state directory's "final-commit" file,
394 * setting state->msg to its contents and state->msg_len to the length of its
397 * Returns 0 on success, -1 if the file does not exist.
399 static int read_commit_msg(struct am_state
*state
)
401 struct strbuf sb
= STRBUF_INIT
;
405 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
410 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
415 * Saves state->msg in the state directory's "final-commit" file.
417 static void write_commit_msg(const struct am_state
*state
)
420 const char *filename
= am_path(state
, "final-commit");
422 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
423 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
424 die_errno(_("could not write to %s"), filename
);
429 * Loads state from disk.
431 static void am_load(struct am_state
*state
)
433 struct strbuf sb
= STRBUF_INIT
;
435 if (read_state_file(&sb
, state
, "next", 1) < 0)
436 die("BUG: state file 'next' does not exist");
437 state
->cur
= strtol(sb
.buf
, NULL
, 10);
439 if (read_state_file(&sb
, state
, "last", 1) < 0)
440 die("BUG: state file 'last' does not exist");
441 state
->last
= strtol(sb
.buf
, NULL
, 10);
443 if (read_author_script(state
) < 0)
444 die(_("could not parse author script"));
446 read_commit_msg(state
);
448 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
449 hashclr(state
->orig_commit
);
450 else if (get_sha1_hex(sb
.buf
, state
->orig_commit
) < 0)
451 die(_("could not parse %s"), am_path(state
, "original-commit"));
453 read_state_file(&sb
, state
, "threeway", 1);
454 state
->threeway
= !strcmp(sb
.buf
, "t");
456 read_state_file(&sb
, state
, "quiet", 1);
457 state
->quiet
= !strcmp(sb
.buf
, "t");
459 read_state_file(&sb
, state
, "sign", 1);
460 state
->signoff
= !strcmp(sb
.buf
, "t");
462 read_state_file(&sb
, state
, "utf8", 1);
463 state
->utf8
= !strcmp(sb
.buf
, "t");
465 read_state_file(&sb
, state
, "keep", 1);
466 if (!strcmp(sb
.buf
, "t"))
467 state
->keep
= KEEP_TRUE
;
468 else if (!strcmp(sb
.buf
, "b"))
469 state
->keep
= KEEP_NON_PATCH
;
471 state
->keep
= KEEP_FALSE
;
473 read_state_file(&sb
, state
, "messageid", 1);
474 state
->message_id
= !strcmp(sb
.buf
, "t");
476 read_state_file(&sb
, state
, "scissors", 1);
477 if (!strcmp(sb
.buf
, "t"))
478 state
->scissors
= SCISSORS_TRUE
;
479 else if (!strcmp(sb
.buf
, "f"))
480 state
->scissors
= SCISSORS_FALSE
;
482 state
->scissors
= SCISSORS_UNSET
;
484 read_state_file(&sb
, state
, "apply-opt", 1);
485 argv_array_clear(&state
->git_apply_opts
);
486 if (sq_dequote_to_argv_array(sb
.buf
, &state
->git_apply_opts
) < 0)
487 die(_("could not parse %s"), am_path(state
, "apply-opt"));
489 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
495 * Removes the am_state directory, forcefully terminating the current am
498 static void am_destroy(const struct am_state
*state
)
500 struct strbuf sb
= STRBUF_INIT
;
502 strbuf_addstr(&sb
, state
->dir
);
503 remove_dir_recursively(&sb
, 0);
508 * Runs applypatch-msg hook. Returns its exit code.
510 static int run_applypatch_msg_hook(struct am_state
*state
)
515 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
520 if (read_commit_msg(state
) < 0)
521 die(_("'%s' was deleted by the applypatch-msg hook"),
522 am_path(state
, "final-commit"));
529 * Runs post-rewrite hook. Returns it exit code.
531 static int run_post_rewrite_hook(const struct am_state
*state
)
533 struct child_process cp
= CHILD_PROCESS_INIT
;
534 const char *hook
= find_hook("post-rewrite");
540 argv_array_push(&cp
.args
, hook
);
541 argv_array_push(&cp
.args
, "rebase");
543 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
544 cp
.stdout_to_stderr
= 1;
546 ret
= run_command(&cp
);
553 * Reads the state directory's "rewritten" file, and copies notes from the old
554 * commits listed in the file to their rewritten commits.
556 * Returns 0 on success, -1 on failure.
558 static int copy_notes_for_rebase(const struct am_state
*state
)
560 struct notes_rewrite_cfg
*c
;
561 struct strbuf sb
= STRBUF_INIT
;
562 const char *invalid_line
= _("Malformed input line: '%s'.");
563 const char *msg
= "Notes added by 'git rebase'";
567 assert(state
->rebasing
);
569 c
= init_copy_notes_for_rewrite("rebase");
573 fp
= xfopen(am_path(state
, "rewritten"), "r");
575 while (!strbuf_getline(&sb
, fp
, '\n')) {
576 unsigned char from_obj
[GIT_SHA1_RAWSZ
], to_obj
[GIT_SHA1_RAWSZ
];
578 if (sb
.len
!= GIT_SHA1_HEXSZ
* 2 + 1) {
579 ret
= error(invalid_line
, sb
.buf
);
583 if (get_sha1_hex(sb
.buf
, from_obj
)) {
584 ret
= error(invalid_line
, sb
.buf
);
588 if (sb
.buf
[GIT_SHA1_HEXSZ
] != ' ') {
589 ret
= error(invalid_line
, sb
.buf
);
593 if (get_sha1_hex(sb
.buf
+ GIT_SHA1_HEXSZ
+ 1, to_obj
)) {
594 ret
= error(invalid_line
, sb
.buf
);
598 if (copy_note_for_rewrite(c
, from_obj
, to_obj
))
599 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
600 sha1_to_hex(from_obj
), sha1_to_hex(to_obj
));
604 finish_copy_notes_for_rewrite(c
, msg
);
611 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
612 * non-indented lines and checking if they look like they begin with valid
613 * header field names.
615 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
617 static int is_mail(FILE *fp
)
619 const char *header_regex
= "^[!-9;-~]+:";
620 struct strbuf sb
= STRBUF_INIT
;
624 if (fseek(fp
, 0L, SEEK_SET
))
625 die_errno(_("fseek failed"));
627 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
628 die("invalid pattern: %s", header_regex
);
630 while (!strbuf_getline_crlf(&sb
, fp
)) {
632 break; /* End of header */
634 /* Ignore indented folded lines */
635 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
638 /* It's a header if it matches header_regex */
639 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
652 * Attempts to detect the patch_format of the patches contained in `paths`,
653 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
656 static int detect_patch_format(const char **paths
)
658 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
659 struct strbuf l1
= STRBUF_INIT
;
660 struct strbuf l2
= STRBUF_INIT
;
661 struct strbuf l3
= STRBUF_INIT
;
665 * We default to mbox format if input is from stdin and for directories
667 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
668 return PATCH_FORMAT_MBOX
;
671 * Otherwise, check the first few lines of the first patch, starting
672 * from the first non-blank line, to try to detect its format.
675 fp
= xfopen(*paths
, "r");
677 while (!strbuf_getline_crlf(&l1
, fp
)) {
682 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
683 ret
= PATCH_FORMAT_MBOX
;
687 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
688 ret
= PATCH_FORMAT_STGIT_SERIES
;
692 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
693 ret
= PATCH_FORMAT_HG
;
698 strbuf_getline_crlf(&l2
, fp
);
700 strbuf_getline_crlf(&l3
, fp
);
703 * If the second line is empty and the third is a From, Author or Date
704 * entry, this is likely an StGit patch.
706 if (l1
.len
&& !l2
.len
&&
707 (starts_with(l3
.buf
, "From:") ||
708 starts_with(l3
.buf
, "Author:") ||
709 starts_with(l3
.buf
, "Date:"))) {
710 ret
= PATCH_FORMAT_STGIT
;
714 if (l1
.len
&& is_mail(fp
)) {
715 ret
= PATCH_FORMAT_MBOX
;
726 * Splits out individual email patches from `paths`, where each path is either
727 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
729 static int split_mail_mbox(struct am_state
*state
, const char **paths
, int keep_cr
)
731 struct child_process cp
= CHILD_PROCESS_INIT
;
732 struct strbuf last
= STRBUF_INIT
;
735 argv_array_push(&cp
.args
, "mailsplit");
736 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
737 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
738 argv_array_push(&cp
.args
, "-b");
740 argv_array_push(&cp
.args
, "--keep-cr");
741 argv_array_push(&cp
.args
, "--");
742 argv_array_pushv(&cp
.args
, paths
);
744 if (capture_command(&cp
, &last
, 8))
748 state
->last
= strtol(last
.buf
, NULL
, 10);
754 * Callback signature for split_mail_conv(). The foreign patch should be
755 * read from `in`, and the converted patch (in RFC2822 mail format) should be
756 * written to `out`. Return 0 on success, or -1 on failure.
758 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
761 * Calls `fn` for each file in `paths` to convert the foreign patch to the
762 * RFC2822 mail format suitable for parsing with git-mailinfo.
764 * Returns 0 on success, -1 on failure.
766 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
767 const char **paths
, int keep_cr
)
769 static const char *stdin_only
[] = {"-", NULL
};
775 for (i
= 0; *paths
; paths
++, i
++) {
780 if (!strcmp(*paths
, "-"))
783 in
= fopen(*paths
, "r");
786 return error(_("could not open '%s' for reading: %s"),
787 *paths
, strerror(errno
));
789 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
791 out
= fopen(mail
, "w");
793 return error(_("could not open '%s' for writing: %s"),
794 mail
, strerror(errno
));
796 ret
= fn(out
, in
, keep_cr
);
802 return error(_("could not parse patch '%s'"), *paths
);
811 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
812 * message suitable for parsing with git-mailinfo.
814 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
816 struct strbuf sb
= STRBUF_INIT
;
817 int subject_printed
= 0;
819 while (!strbuf_getline(&sb
, in
, '\n')) {
822 if (str_isspace(sb
.buf
))
824 else if (skip_prefix(sb
.buf
, "Author:", &str
))
825 fprintf(out
, "From:%s\n", str
);
826 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
827 fprintf(out
, "%s\n", sb
.buf
);
828 else if (!subject_printed
) {
829 fprintf(out
, "Subject: %s\n", sb
.buf
);
832 fprintf(out
, "\n%s\n", sb
.buf
);
838 while (strbuf_fread(&sb
, 8192, in
) > 0) {
839 fwrite(sb
.buf
, 1, sb
.len
, out
);
848 * This function only supports a single StGit series file in `paths`.
850 * Given an StGit series file, converts the StGit patches in the series into
851 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
852 * the state directory.
854 * Returns 0 on success, -1 on failure.
856 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
859 const char *series_dir
;
860 char *series_dir_buf
;
862 struct argv_array patches
= ARGV_ARRAY_INIT
;
863 struct strbuf sb
= STRBUF_INIT
;
866 if (!paths
[0] || paths
[1])
867 return error(_("Only one StGIT patch series can be applied at once"));
869 series_dir_buf
= xstrdup(*paths
);
870 series_dir
= dirname(series_dir_buf
);
872 fp
= fopen(*paths
, "r");
874 return error(_("could not open '%s' for reading: %s"), *paths
,
877 while (!strbuf_getline(&sb
, fp
, '\n')) {
879 continue; /* skip comment lines */
881 argv_array_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
886 free(series_dir_buf
);
888 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.argv
, keep_cr
);
890 argv_array_clear(&patches
);
895 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
896 * message suitable for parsing with git-mailinfo.
898 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
900 struct strbuf sb
= STRBUF_INIT
;
902 while (!strbuf_getline(&sb
, in
, '\n')) {
905 if (skip_prefix(sb
.buf
, "# User ", &str
))
906 fprintf(out
, "From: %s\n", str
);
907 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
908 unsigned long timestamp
;
913 timestamp
= strtoul(str
, &end
, 10);
915 return error(_("invalid timestamp"));
917 if (!skip_prefix(end
, " ", &str
))
918 return error(_("invalid Date line"));
921 tz
= strtol(str
, &end
, 10);
923 return error(_("invalid timezone offset"));
926 return error(_("invalid Date line"));
929 * mercurial's timezone is in seconds west of UTC,
930 * however git's timezone is in hours + minutes east of
933 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
937 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
938 } else if (starts_with(sb
.buf
, "# ")) {
941 fprintf(out
, "\n%s\n", sb
.buf
);
947 while (strbuf_fread(&sb
, 8192, in
) > 0) {
948 fwrite(sb
.buf
, 1, sb
.len
, out
);
957 * Splits a list of files/directories into individual email patches. Each path
958 * in `paths` must be a file/directory that is formatted according to
961 * Once split out, the individual email patches will be stored in the state
962 * directory, with each patch's filename being its index, padded to state->prec
965 * state->cur will be set to the index of the first mail, and state->last will
966 * be set to the index of the last mail.
968 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
969 * to disable this behavior, -1 to use the default configured setting.
971 * Returns 0 on success, -1 on failure.
973 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
974 const char **paths
, int keep_cr
)
978 git_config_get_bool("am.keepcr", &keep_cr
);
981 switch (patch_format
) {
982 case PATCH_FORMAT_MBOX
:
983 return split_mail_mbox(state
, paths
, keep_cr
);
984 case PATCH_FORMAT_STGIT
:
985 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
986 case PATCH_FORMAT_STGIT_SERIES
:
987 return split_mail_stgit_series(state
, paths
, keep_cr
);
988 case PATCH_FORMAT_HG
:
989 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
991 die("BUG: invalid patch_format");
997 * Setup a new am session for applying patches
999 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
1000 const char **paths
, int keep_cr
)
1002 unsigned char curr_head
[GIT_SHA1_RAWSZ
];
1004 struct strbuf sb
= STRBUF_INIT
;
1007 patch_format
= detect_patch_format(paths
);
1009 if (!patch_format
) {
1010 fprintf_ln(stderr
, _("Patch format detection failed."));
1014 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
1015 die_errno(_("failed to create directory '%s'"), state
->dir
);
1017 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
1019 die(_("Failed to split patches."));
1022 if (state
->rebasing
)
1023 state
->threeway
= 1;
1025 write_state_bool(state
, "threeway", state
->threeway
);
1026 write_state_bool(state
, "quiet", state
->quiet
);
1027 write_state_bool(state
, "sign", state
->signoff
);
1028 write_state_bool(state
, "utf8", state
->utf8
);
1030 switch (state
->keep
) {
1037 case KEEP_NON_PATCH
:
1041 die("BUG: invalid value for state->keep");
1044 write_state_text(state
, "keep", str
);
1045 write_state_bool(state
, "messageid", state
->message_id
);
1047 switch (state
->scissors
) {
1048 case SCISSORS_UNSET
:
1051 case SCISSORS_FALSE
:
1058 die("BUG: invalid value for state->scissors");
1060 write_state_text(state
, "scissors", str
);
1062 sq_quote_argv(&sb
, state
->git_apply_opts
.argv
, 0);
1063 write_state_text(state
, "apply-opt", sb
.buf
);
1065 if (state
->rebasing
)
1066 write_state_text(state
, "rebasing", "");
1068 write_state_text(state
, "applying", "");
1070 if (!get_sha1("HEAD", curr_head
)) {
1071 write_state_text(state
, "abort-safety", sha1_to_hex(curr_head
));
1072 if (!state
->rebasing
)
1073 update_ref("am", "ORIG_HEAD", curr_head
, NULL
, 0,
1074 UPDATE_REFS_DIE_ON_ERR
);
1076 write_state_text(state
, "abort-safety", "");
1077 if (!state
->rebasing
)
1078 delete_ref("ORIG_HEAD", NULL
, 0);
1082 * NOTE: Since the "next" and "last" files determine if an am_state
1083 * session is in progress, they should be written last.
1086 write_state_count(state
, "next", state
->cur
);
1087 write_state_count(state
, "last", state
->last
);
1089 strbuf_release(&sb
);
1093 * Increments the patch pointer, and cleans am_state for the application of the
1096 static void am_next(struct am_state
*state
)
1098 unsigned char head
[GIT_SHA1_RAWSZ
];
1100 free(state
->author_name
);
1101 state
->author_name
= NULL
;
1103 free(state
->author_email
);
1104 state
->author_email
= NULL
;
1106 free(state
->author_date
);
1107 state
->author_date
= NULL
;
1113 unlink(am_path(state
, "author-script"));
1114 unlink(am_path(state
, "final-commit"));
1116 hashclr(state
->orig_commit
);
1117 unlink(am_path(state
, "original-commit"));
1119 if (!get_sha1("HEAD", head
))
1120 write_state_text(state
, "abort-safety", sha1_to_hex(head
));
1122 write_state_text(state
, "abort-safety", "");
1125 write_state_count(state
, "next", state
->cur
);
1129 * Returns the filename of the current patch email.
1131 static const char *msgnum(const struct am_state
*state
)
1133 static struct strbuf sb
= STRBUF_INIT
;
1136 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1142 * Refresh and write index.
1144 static void refresh_and_write_cache(void)
1146 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
1148 hold_locked_index(lock_file
, 1);
1149 refresh_cache(REFRESH_QUIET
);
1150 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1151 die(_("unable to write index file"));
1155 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1156 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1157 * strbuf is provided, the space-separated list of files that differ will be
1160 static int index_has_changes(struct strbuf
*sb
)
1162 unsigned char head
[GIT_SHA1_RAWSZ
];
1165 if (!get_sha1_tree("HEAD", head
)) {
1166 struct diff_options opt
;
1169 DIFF_OPT_SET(&opt
, EXIT_WITH_STATUS
);
1171 DIFF_OPT_SET(&opt
, QUICK
);
1172 do_diff_cache(head
, &opt
);
1174 for (i
= 0; sb
&& i
< diff_queued_diff
.nr
; i
++) {
1176 strbuf_addch(sb
, ' ');
1177 strbuf_addstr(sb
, diff_queued_diff
.queue
[i
]->two
->path
);
1180 return DIFF_OPT_TST(&opt
, HAS_CHANGES
) != 0;
1182 for (i
= 0; sb
&& i
< active_nr
; i
++) {
1184 strbuf_addch(sb
, ' ');
1185 strbuf_addstr(sb
, active_cache
[i
]->name
);
1192 * Dies with a user-friendly message on how to proceed after resolving the
1193 * problem. This message can be overridden with state->resolvemsg.
1195 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1197 if (state
->resolvemsg
) {
1198 printf_ln("%s", state
->resolvemsg
);
1200 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1202 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1203 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1204 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1210 static void am_signoff(struct strbuf
*sb
)
1213 struct strbuf mine
= STRBUF_INIT
;
1215 /* Does it end with our own sign-off? */
1216 strbuf_addf(&mine
, "\n%s%s\n",
1218 fmt_name(getenv("GIT_COMMITTER_NAME"),
1219 getenv("GIT_COMMITTER_EMAIL")));
1220 if (mine
.len
< sb
->len
&&
1221 !strcmp(mine
.buf
, sb
->buf
+ sb
->len
- mine
.len
))
1222 goto exit
; /* no need to duplicate */
1224 /* Does it have any Signed-off-by: in the text */
1226 cp
&& *cp
&& (cp
= strstr(cp
, sign_off_header
)) != NULL
;
1227 cp
= strchr(cp
, '\n')) {
1228 if (sb
->buf
== cp
|| cp
[-1] == '\n')
1232 strbuf_addstr(sb
, mine
.buf
+ !!cp
);
1234 strbuf_release(&mine
);
1238 * Appends signoff to the "msg" field of the am_state.
1240 static void am_append_signoff(struct am_state
*state
)
1242 struct strbuf sb
= STRBUF_INIT
;
1244 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1246 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1250 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1251 * state->msg will be set to the patch message. state->author_name,
1252 * state->author_email and state->author_date will be set to the patch author's
1253 * name, email and date respectively. The patch body will be written to the
1254 * state directory's "patch" file.
1256 * Returns 1 if the patch should be skipped, 0 otherwise.
1258 static int parse_mail(struct am_state
*state
, const char *mail
)
1261 struct child_process cp
= CHILD_PROCESS_INIT
;
1262 struct strbuf sb
= STRBUF_INIT
;
1263 struct strbuf msg
= STRBUF_INIT
;
1264 struct strbuf author_name
= STRBUF_INIT
;
1265 struct strbuf author_date
= STRBUF_INIT
;
1266 struct strbuf author_email
= STRBUF_INIT
;
1270 cp
.in
= xopen(mail
, O_RDONLY
, 0);
1271 cp
.out
= xopen(am_path(state
, "info"), O_WRONLY
| O_CREAT
, 0777);
1273 argv_array_push(&cp
.args
, "mailinfo");
1274 argv_array_push(&cp
.args
, state
->utf8
? "-u" : "-n");
1276 switch (state
->keep
) {
1280 argv_array_push(&cp
.args
, "-k");
1282 case KEEP_NON_PATCH
:
1283 argv_array_push(&cp
.args
, "-b");
1286 die("BUG: invalid value for state->keep");
1289 if (state
->message_id
)
1290 argv_array_push(&cp
.args
, "-m");
1292 switch (state
->scissors
) {
1293 case SCISSORS_UNSET
:
1295 case SCISSORS_FALSE
:
1296 argv_array_push(&cp
.args
, "--no-scissors");
1299 argv_array_push(&cp
.args
, "--scissors");
1302 die("BUG: invalid value for state->scissors");
1305 argv_array_push(&cp
.args
, am_path(state
, "msg"));
1306 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1308 if (run_command(&cp
) < 0)
1309 die("could not parse patch");
1314 /* Extract message and author information */
1315 fp
= xfopen(am_path(state
, "info"), "r");
1316 while (!strbuf_getline(&sb
, fp
, '\n')) {
1319 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1321 strbuf_addch(&msg
, '\n');
1322 strbuf_addstr(&msg
, x
);
1323 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1324 strbuf_addstr(&author_name
, x
);
1325 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1326 strbuf_addstr(&author_email
, x
);
1327 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1328 strbuf_addstr(&author_date
, x
);
1332 /* Skip pine's internal folder data */
1333 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1338 if (is_empty_file(am_path(state
, "patch"))) {
1339 printf_ln(_("Patch is empty. Was it split wrong?"));
1340 die_user_resolve(state
);
1343 strbuf_addstr(&msg
, "\n\n");
1344 if (strbuf_read_file(&msg
, am_path(state
, "msg"), 0) < 0)
1345 die_errno(_("could not read '%s'"), am_path(state
, "msg"));
1346 strbuf_stripspace(&msg
, 0);
1351 assert(!state
->author_name
);
1352 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1354 assert(!state
->author_email
);
1355 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1357 assert(!state
->author_date
);
1358 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1360 assert(!state
->msg
);
1361 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1364 strbuf_release(&msg
);
1365 strbuf_release(&author_date
);
1366 strbuf_release(&author_email
);
1367 strbuf_release(&author_name
);
1368 strbuf_release(&sb
);
1373 * Sets commit_id to the commit hash where the mail was generated from.
1374 * Returns 0 on success, -1 on failure.
1376 static int get_mail_commit_sha1(unsigned char *commit_id
, const char *mail
)
1378 struct strbuf sb
= STRBUF_INIT
;
1379 FILE *fp
= xfopen(mail
, "r");
1382 if (strbuf_getline(&sb
, fp
, '\n'))
1385 if (!skip_prefix(sb
.buf
, "From ", &x
))
1388 if (get_sha1_hex(x
, commit_id
) < 0)
1391 strbuf_release(&sb
);
1397 * Sets state->msg, state->author_name, state->author_email, state->author_date
1398 * to the commit's respective info.
1400 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1402 const char *buffer
, *ident_line
, *author_date
, *msg
;
1404 struct ident_split ident_split
;
1405 struct strbuf sb
= STRBUF_INIT
;
1407 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1409 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1411 if (split_ident_line(&ident_split
, ident_line
, ident_len
) < 0) {
1412 strbuf_add(&sb
, ident_line
, ident_len
);
1413 die(_("invalid ident line: %s"), sb
.buf
);
1416 assert(!state
->author_name
);
1417 if (ident_split
.name_begin
) {
1418 strbuf_add(&sb
, ident_split
.name_begin
,
1419 ident_split
.name_end
- ident_split
.name_begin
);
1420 state
->author_name
= strbuf_detach(&sb
, NULL
);
1422 state
->author_name
= xstrdup("");
1424 assert(!state
->author_email
);
1425 if (ident_split
.mail_begin
) {
1426 strbuf_add(&sb
, ident_split
.mail_begin
,
1427 ident_split
.mail_end
- ident_split
.mail_begin
);
1428 state
->author_email
= strbuf_detach(&sb
, NULL
);
1430 state
->author_email
= xstrdup("");
1432 author_date
= show_ident_date(&ident_split
, DATE_MODE(NORMAL
));
1433 strbuf_addstr(&sb
, author_date
);
1434 assert(!state
->author_date
);
1435 state
->author_date
= strbuf_detach(&sb
, NULL
);
1437 assert(!state
->msg
);
1438 msg
= strstr(buffer
, "\n\n");
1440 die(_("unable to parse commit %s"), sha1_to_hex(commit
->object
.sha1
));
1441 state
->msg
= xstrdup(msg
+ 2);
1442 state
->msg_len
= strlen(state
->msg
);
1446 * Writes `commit` as a patch to the state directory's "patch" file.
1448 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1450 struct rev_info rev_info
;
1453 fp
= xfopen(am_path(state
, "patch"), "w");
1454 init_revisions(&rev_info
, NULL
);
1456 rev_info
.abbrev
= 0;
1457 rev_info
.disable_stdin
= 1;
1458 rev_info
.show_root_diff
= 1;
1459 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1460 rev_info
.no_commit_id
= 1;
1461 DIFF_OPT_SET(&rev_info
.diffopt
, BINARY
);
1462 DIFF_OPT_SET(&rev_info
.diffopt
, FULL_INDEX
);
1463 rev_info
.diffopt
.use_color
= 0;
1464 rev_info
.diffopt
.file
= fp
;
1465 rev_info
.diffopt
.close_file
= 1;
1466 add_pending_object(&rev_info
, &commit
->object
, "");
1467 diff_setup_done(&rev_info
.diffopt
);
1468 log_tree_commit(&rev_info
, commit
);
1472 * Writes the diff of the index against HEAD as a patch to the state
1473 * directory's "patch" file.
1475 static void write_index_patch(const struct am_state
*state
)
1478 unsigned char head
[GIT_SHA1_RAWSZ
];
1479 struct rev_info rev_info
;
1482 if (!get_sha1_tree("HEAD", head
))
1483 tree
= lookup_tree(head
);
1485 tree
= lookup_tree(EMPTY_TREE_SHA1_BIN
);
1487 fp
= xfopen(am_path(state
, "patch"), "w");
1488 init_revisions(&rev_info
, NULL
);
1490 rev_info
.disable_stdin
= 1;
1491 rev_info
.no_commit_id
= 1;
1492 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1493 rev_info
.diffopt
.use_color
= 0;
1494 rev_info
.diffopt
.file
= fp
;
1495 rev_info
.diffopt
.close_file
= 1;
1496 add_pending_object(&rev_info
, &tree
->object
, "");
1497 diff_setup_done(&rev_info
.diffopt
);
1498 run_diff_index(&rev_info
, 1);
1502 * Like parse_mail(), but parses the mail by looking up its commit ID
1503 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1506 * state->orig_commit will be set to the original commit ID.
1508 * Will always return 0 as the patch should never be skipped.
1510 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1512 struct commit
*commit
;
1513 unsigned char commit_sha1
[GIT_SHA1_RAWSZ
];
1515 if (get_mail_commit_sha1(commit_sha1
, mail
) < 0)
1516 die(_("could not parse %s"), mail
);
1518 commit
= lookup_commit_or_die(commit_sha1
, mail
);
1520 get_commit_info(state
, commit
);
1522 write_commit_patch(state
, commit
);
1524 hashcpy(state
->orig_commit
, commit_sha1
);
1525 write_state_text(state
, "original-commit", sha1_to_hex(commit_sha1
));
1531 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1532 * `index_file` is not NULL, the patch will be applied to that index.
1534 static int run_apply(const struct am_state
*state
, const char *index_file
)
1536 struct child_process cp
= CHILD_PROCESS_INIT
;
1541 argv_array_pushf(&cp
.env_array
, "GIT_INDEX_FILE=%s", index_file
);
1544 * If we are allowed to fall back on 3-way merge, don't give false
1545 * errors during the initial attempt.
1547 if (state
->threeway
&& !index_file
) {
1552 argv_array_push(&cp
.args
, "apply");
1554 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1557 argv_array_push(&cp
.args
, "--cached");
1559 argv_array_push(&cp
.args
, "--index");
1561 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1563 if (run_command(&cp
))
1566 /* Reload index as git-apply will have modified it. */
1568 read_cache_from(index_file
? index_file
: get_index_file());
1574 * Builds an index that contains just the blobs needed for a 3way merge.
1576 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1578 struct child_process cp
= CHILD_PROCESS_INIT
;
1581 argv_array_push(&cp
.args
, "apply");
1582 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1583 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1584 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1586 if (run_command(&cp
))
1593 * Do the three-way merge using fake ancestor, his tree constructed
1594 * from the fake ancestor and the postimage of the patch, and our
1597 static int run_fallback_merge_recursive(const struct am_state
*state
,
1598 unsigned char *orig_tree
,
1599 unsigned char *our_tree
,
1600 unsigned char *his_tree
)
1602 struct child_process cp
= CHILD_PROCESS_INIT
;
1607 argv_array_pushf(&cp
.env_array
, "GITHEAD_%s=%.*s",
1608 sha1_to_hex(his_tree
), linelen(state
->msg
), state
->msg
);
1610 argv_array_push(&cp
.env_array
, "GIT_MERGE_VERBOSITY=0");
1612 argv_array_push(&cp
.args
, "merge-recursive");
1613 argv_array_push(&cp
.args
, sha1_to_hex(orig_tree
));
1614 argv_array_push(&cp
.args
, "--");
1615 argv_array_push(&cp
.args
, sha1_to_hex(our_tree
));
1616 argv_array_push(&cp
.args
, sha1_to_hex(his_tree
));
1618 status
= run_command(&cp
) ? (-1) : 0;
1625 * Attempt a threeway merge, using index_path as the temporary index.
1627 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1629 unsigned char orig_tree
[GIT_SHA1_RAWSZ
], his_tree
[GIT_SHA1_RAWSZ
],
1630 our_tree
[GIT_SHA1_RAWSZ
];
1632 if (get_sha1("HEAD", our_tree
) < 0)
1633 hashcpy(our_tree
, EMPTY_TREE_SHA1_BIN
);
1635 if (build_fake_ancestor(state
, index_path
))
1636 return error("could not build fake ancestor");
1639 read_cache_from(index_path
);
1641 if (write_index_as_tree(orig_tree
, &the_index
, index_path
, 0, NULL
))
1642 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1644 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1646 if (!state
->quiet
) {
1648 * List paths that needed 3-way fallback, so that the user can
1649 * review them with extra care to spot mismerges.
1651 struct rev_info rev_info
;
1652 const char *diff_filter_str
= "--diff-filter=AM";
1654 init_revisions(&rev_info
, NULL
);
1655 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1656 diff_opt_parse(&rev_info
.diffopt
, &diff_filter_str
, 1, rev_info
.prefix
);
1657 add_pending_sha1(&rev_info
, "HEAD", our_tree
, 0);
1658 diff_setup_done(&rev_info
.diffopt
);
1659 run_diff_index(&rev_info
, 1);
1662 if (run_apply(state
, index_path
))
1663 return error(_("Did you hand edit your patch?\n"
1664 "It does not apply to blobs recorded in its index."));
1666 if (write_index_as_tree(his_tree
, &the_index
, index_path
, 0, NULL
))
1667 return error("could not write tree");
1669 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1675 * This is not so wrong. Depending on which base we picked, orig_tree
1676 * may be wildly different from ours, but his_tree has the same set of
1677 * wildly different changes in parts the patch did not touch, so
1678 * recursive ends up canceling them, saying that we reverted all those
1682 if (run_fallback_merge_recursive(state
, orig_tree
, our_tree
, his_tree
)) {
1683 rerere(state
->allow_rerere_autoupdate
);
1684 return error(_("Failed to merge in the changes."));
1691 * Commits the current index with state->msg as the commit message and
1692 * state->author_name, state->author_email and state->author_date as the author
1695 static void do_commit(const struct am_state
*state
)
1697 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
1698 commit
[GIT_SHA1_RAWSZ
];
1700 struct commit_list
*parents
= NULL
;
1701 const char *reflog_msg
, *author
;
1702 struct strbuf sb
= STRBUF_INIT
;
1704 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1707 if (write_cache_as_tree(tree
, 0, NULL
))
1708 die(_("git write-tree failed to write a tree"));
1710 if (!get_sha1_commit("HEAD", parent
)) {
1712 commit_list_insert(lookup_commit(parent
), &parents
);
1715 say(state
, stderr
, _("applying to an empty history"));
1718 author
= fmt_ident(state
->author_name
, state
->author_email
,
1719 state
->ignore_date
? NULL
: state
->author_date
,
1722 if (state
->committer_date_is_author_date
)
1723 setenv("GIT_COMMITTER_DATE",
1724 state
->ignore_date
? "" : state
->author_date
, 1);
1726 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
1727 author
, state
->sign_commit
))
1728 die(_("failed to write commit object"));
1730 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1734 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1737 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
1739 if (state
->rebasing
) {
1740 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1742 assert(!is_null_sha1(state
->orig_commit
));
1743 fprintf(fp
, "%s ", sha1_to_hex(state
->orig_commit
));
1744 fprintf(fp
, "%s\n", sha1_to_hex(commit
));
1748 run_hook_le(NULL
, "post-applypatch", NULL
);
1750 strbuf_release(&sb
);
1754 * Validates the am_state for resuming -- the "msg" and authorship fields must
1757 static void validate_resume_state(const struct am_state
*state
)
1760 die(_("cannot resume: %s does not exist."),
1761 am_path(state
, "final-commit"));
1763 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1764 die(_("cannot resume: %s does not exist."),
1765 am_path(state
, "author-script"));
1769 * Interactively prompt the user on whether the current patch should be
1772 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1775 static int do_interactive(struct am_state
*state
)
1780 die(_("cannot be interactive without stdin connected to a terminal."));
1785 puts(_("Commit Body is:"));
1786 puts("--------------------------");
1787 printf("%s", state
->msg
);
1788 puts("--------------------------");
1791 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1792 * in your translation. The program will only accept English
1793 * input at this point.
1795 reply
= git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO
);
1799 } else if (*reply
== 'y' || *reply
== 'Y') {
1801 } else if (*reply
== 'a' || *reply
== 'A') {
1802 state
->interactive
= 0;
1804 } else if (*reply
== 'n' || *reply
== 'N') {
1806 } else if (*reply
== 'e' || *reply
== 'E') {
1807 struct strbuf msg
= STRBUF_INIT
;
1809 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1811 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1813 strbuf_release(&msg
);
1814 } else if (*reply
== 'v' || *reply
== 'V') {
1815 const char *pager
= git_pager(1);
1816 struct child_process cp
= CHILD_PROCESS_INIT
;
1820 argv_array_push(&cp
.args
, pager
);
1821 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1828 * Applies all queued mail.
1830 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1831 * well as the state directory's "patch" file is used as-is for applying the
1832 * patch and committing it.
1834 static void am_run(struct am_state
*state
, int resume
)
1836 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1837 struct strbuf sb
= STRBUF_INIT
;
1839 unlink(am_path(state
, "dirtyindex"));
1841 refresh_and_write_cache();
1843 if (index_has_changes(&sb
)) {
1844 write_state_bool(state
, "dirtyindex", 1);
1845 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1848 strbuf_release(&sb
);
1850 while (state
->cur
<= state
->last
) {
1851 const char *mail
= am_path(state
, msgnum(state
));
1854 if (!file_exists(mail
))
1858 validate_resume_state(state
);
1862 if (state
->rebasing
)
1863 skip
= parse_mail_rebase(state
, mail
);
1865 skip
= parse_mail(state
, mail
);
1868 goto next
; /* mail should be skipped */
1870 write_author_script(state
);
1871 write_commit_msg(state
);
1874 if (state
->interactive
&& do_interactive(state
))
1877 if (run_applypatch_msg_hook(state
))
1880 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1882 apply_status
= run_apply(state
, NULL
);
1884 if (apply_status
&& state
->threeway
) {
1885 struct strbuf sb
= STRBUF_INIT
;
1887 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1888 apply_status
= fall_back_threeway(state
, sb
.buf
);
1889 strbuf_release(&sb
);
1892 * Applying the patch to an earlier tree and merging
1893 * the result may have produced the same tree as ours.
1895 if (!apply_status
&& !index_has_changes(NULL
)) {
1896 say(state
, stdout
, _("No changes -- Patch already applied."));
1902 int advice_amworkdir
= 1;
1904 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1905 linelen(state
->msg
), state
->msg
);
1907 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
1909 if (advice_amworkdir
)
1910 printf_ln(_("The copy of the patch that failed is found in: %s"),
1911 am_path(state
, "patch"));
1913 die_user_resolve(state
);
1926 if (!is_empty_file(am_path(state
, "rewritten"))) {
1927 assert(state
->rebasing
);
1928 copy_notes_for_rebase(state
);
1929 run_post_rewrite_hook(state
);
1933 * In rebasing mode, it's up to the caller to take care of
1936 if (!state
->rebasing
) {
1938 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1943 * Resume the current am session after patch application failure. The user did
1944 * all the hard work, and we do not have to do any patch application. Just
1945 * trust and commit what the user has in the index and working tree.
1947 static void am_resolve(struct am_state
*state
)
1949 validate_resume_state(state
);
1951 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1953 if (!index_has_changes(NULL
)) {
1954 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1955 "If there is nothing left to stage, chances are that something else\n"
1956 "already introduced the same changes; you might want to skip this patch."));
1957 die_user_resolve(state
);
1960 if (unmerged_cache()) {
1961 printf_ln(_("You still have unmerged paths in your index.\n"
1962 "Did you forget to use 'git add'?"));
1963 die_user_resolve(state
);
1966 if (state
->interactive
) {
1967 write_index_patch(state
);
1968 if (do_interactive(state
))
1983 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1984 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1987 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1989 struct lock_file
*lock_file
;
1990 struct unpack_trees_options opts
;
1991 struct tree_desc t
[2];
1993 if (parse_tree(head
) || parse_tree(remote
))
1996 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1997 hold_locked_index(lock_file
, 1);
1999 refresh_cache(REFRESH_QUIET
);
2001 memset(&opts
, 0, sizeof(opts
));
2003 opts
.src_index
= &the_index
;
2004 opts
.dst_index
= &the_index
;
2008 opts
.fn
= twoway_merge
;
2009 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
2010 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
2012 if (unpack_trees(2, t
, &opts
)) {
2013 rollback_lock_file(lock_file
);
2017 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
2018 die(_("unable to write new index file"));
2024 * Merges a tree into the index. The index's stat info will take precedence
2025 * over the merged tree's. Returns 0 on success, -1 on failure.
2027 static int merge_tree(struct tree
*tree
)
2029 struct lock_file
*lock_file
;
2030 struct unpack_trees_options opts
;
2031 struct tree_desc t
[1];
2033 if (parse_tree(tree
))
2036 lock_file
= xcalloc(1, sizeof(struct lock_file
));
2037 hold_locked_index(lock_file
, 1);
2039 memset(&opts
, 0, sizeof(opts
));
2041 opts
.src_index
= &the_index
;
2042 opts
.dst_index
= &the_index
;
2044 opts
.fn
= oneway_merge
;
2045 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
2047 if (unpack_trees(1, t
, &opts
)) {
2048 rollback_lock_file(lock_file
);
2052 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
2053 die(_("unable to write new index file"));
2059 * Clean the index without touching entries that are not modified between
2060 * `head` and `remote`.
2062 static int clean_index(const unsigned char *head
, const unsigned char *remote
)
2064 struct tree
*head_tree
, *remote_tree
, *index_tree
;
2065 unsigned char index
[GIT_SHA1_RAWSZ
];
2067 head_tree
= parse_tree_indirect(head
);
2069 return error(_("Could not parse object '%s'."), sha1_to_hex(head
));
2071 remote_tree
= parse_tree_indirect(remote
);
2073 return error(_("Could not parse object '%s'."), sha1_to_hex(remote
));
2075 read_cache_unmerged();
2077 if (fast_forward_to(head_tree
, head_tree
, 1))
2080 if (write_cache_as_tree(index
, 0, NULL
))
2083 index_tree
= parse_tree_indirect(index
);
2085 return error(_("Could not parse object '%s'."), sha1_to_hex(index
));
2087 if (fast_forward_to(index_tree
, remote_tree
, 0))
2090 if (merge_tree(remote_tree
))
2093 remove_branch_state();
2099 * Resets rerere's merge resolution metadata.
2101 static void am_rerere_clear(void)
2103 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
2104 rerere_clear(&merge_rr
);
2105 string_list_clear(&merge_rr
, 1);
2109 * Resume the current am session by skipping the current patch.
2111 static void am_skip(struct am_state
*state
)
2113 unsigned char head
[GIT_SHA1_RAWSZ
];
2117 if (get_sha1("HEAD", head
))
2118 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
2120 if (clean_index(head
, head
))
2121 die(_("failed to clean index"));
2129 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2131 * It is not safe to reset HEAD when:
2132 * 1. git-am previously failed because the index was dirty.
2133 * 2. HEAD has moved since git-am previously failed.
2135 static int safe_to_abort(const struct am_state
*state
)
2137 struct strbuf sb
= STRBUF_INIT
;
2138 unsigned char abort_safety
[GIT_SHA1_RAWSZ
], head
[GIT_SHA1_RAWSZ
];
2140 if (file_exists(am_path(state
, "dirtyindex")))
2143 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2144 if (get_sha1_hex(sb
.buf
, abort_safety
))
2145 die(_("could not parse %s"), am_path(state
, "abort_safety"));
2147 hashclr(abort_safety
);
2149 if (get_sha1("HEAD", head
))
2152 if (!hashcmp(head
, abort_safety
))
2155 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2156 "Not rewinding to ORIG_HEAD"));
2162 * Aborts the current am session if it is safe to do so.
2164 static void am_abort(struct am_state
*state
)
2166 unsigned char curr_head
[GIT_SHA1_RAWSZ
], orig_head
[GIT_SHA1_RAWSZ
];
2167 int has_curr_head
, has_orig_head
;
2170 if (!safe_to_abort(state
)) {
2177 curr_branch
= resolve_refdup("HEAD", 0, curr_head
, NULL
);
2178 has_curr_head
= !is_null_sha1(curr_head
);
2180 hashcpy(curr_head
, EMPTY_TREE_SHA1_BIN
);
2182 has_orig_head
= !get_sha1("ORIG_HEAD", orig_head
);
2184 hashcpy(orig_head
, EMPTY_TREE_SHA1_BIN
);
2186 clean_index(curr_head
, orig_head
);
2189 update_ref("am --abort", "HEAD", orig_head
,
2190 has_curr_head
? curr_head
: NULL
, 0,
2191 UPDATE_REFS_DIE_ON_ERR
);
2192 else if (curr_branch
)
2193 delete_ref(curr_branch
, NULL
, REF_NODEREF
);
2200 * parse_options() callback that validates and sets opt->value to the
2201 * PATCH_FORMAT_* enum value corresponding to `arg`.
2203 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2205 int *opt_value
= opt
->value
;
2207 if (!strcmp(arg
, "mbox"))
2208 *opt_value
= PATCH_FORMAT_MBOX
;
2209 else if (!strcmp(arg
, "stgit"))
2210 *opt_value
= PATCH_FORMAT_STGIT
;
2211 else if (!strcmp(arg
, "stgit-series"))
2212 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2213 else if (!strcmp(arg
, "hg"))
2214 *opt_value
= PATCH_FORMAT_HG
;
2216 return error(_("Invalid value for --patch-format: %s"), arg
);
2228 static int git_am_config(const char *k
, const char *v
, void *cb
)
2232 status
= git_gpg_config(k
, v
, NULL
);
2236 return git_default_config(k
, v
, NULL
);
2239 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2241 struct am_state state
;
2244 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2245 enum resume_mode resume
= RESUME_FALSE
;
2248 const char * const usage
[] = {
2249 N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
2250 N_("git am [<options>] (--continue | --skip | --abort)"),
2254 struct option options
[] = {
2255 OPT_BOOL('i', "interactive", &state
.interactive
,
2256 N_("run interactively")),
2257 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2258 N_("historical option -- no-op")),
2259 OPT_BOOL('3', "3way", &state
.threeway
,
2260 N_("allow fall back on 3way merging if needed")),
2261 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2262 OPT_SET_INT('s', "signoff", &state
.signoff
,
2263 N_("add a Signed-off-by line to the commit message"),
2265 OPT_BOOL('u', "utf8", &state
.utf8
,
2266 N_("recode into utf8 (default)")),
2267 OPT_SET_INT('k', "keep", &state
.keep
,
2268 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2269 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2270 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2271 OPT_BOOL('m', "message-id", &state
.message_id
,
2272 N_("pass -m flag to git-mailinfo")),
2273 { OPTION_SET_INT
, 0, "keep-cr", &keep_cr
, NULL
,
2274 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2275 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 1},
2276 { OPTION_SET_INT
, 0, "no-keep-cr", &keep_cr
, NULL
,
2277 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2278 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 0},
2279 OPT_BOOL('c', "scissors", &state
.scissors
,
2280 N_("strip everything before a scissors line")),
2281 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2282 N_("pass it through git-apply"),
2284 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2285 N_("pass it through git-apply"),
2287 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2288 N_("pass it through git-apply"),
2290 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2291 N_("pass it through git-apply"),
2293 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2294 N_("pass it through git-apply"),
2296 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2297 N_("pass it through git-apply"),
2299 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2300 N_("pass it through git-apply"),
2302 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2303 N_("pass it through git-apply"),
2305 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2306 N_("format the patch(es) are in"),
2307 parse_opt_patchformat
),
2308 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2309 N_("pass it through git-apply"),
2311 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2312 N_("override error message when patch failure occurs")),
2313 OPT_CMDMODE(0, "continue", &resume
,
2314 N_("continue applying patches after resolving a conflict"),
2316 OPT_CMDMODE('r', "resolved", &resume
,
2317 N_("synonyms for --continue"),
2319 OPT_CMDMODE(0, "skip", &resume
,
2320 N_("skip the current patch"),
2322 OPT_CMDMODE(0, "abort", &resume
,
2323 N_("restore the original branch and abort the patching operation."),
2325 OPT_BOOL(0, "committer-date-is-author-date",
2326 &state
.committer_date_is_author_date
,
2327 N_("lie about committer date")),
2328 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2329 N_("use current timestamp for author date")),
2330 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2331 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2332 N_("GPG-sign commits"),
2333 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2334 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2335 N_("(internal use for git-rebase)")),
2339 git_config(git_am_config
, NULL
);
2341 am_state_init(&state
, git_path("rebase-apply"));
2343 in_progress
= am_in_progress(&state
);
2347 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2350 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2351 "it will be removed. Please do not use it anymore."));
2353 /* Ensure a valid committer ident can be constructed */
2354 git_committer_info(IDENT_STRICT
);
2356 if (read_index_preload(&the_index
, NULL
) < 0)
2357 die(_("failed to read the index"));
2361 * Catch user error to feed us patches when there is a session
2364 * 1. mbox path(s) are provided on the command-line.
2365 * 2. stdin is not a tty: the user is trying to feed us a patch
2366 * from standard input. This is somewhat unreliable -- stdin
2367 * could be /dev/null for example and the caller did not
2368 * intend to feed us a patch but wanted to continue
2371 if (argc
|| (resume
== RESUME_FALSE
&& !isatty(0)))
2372 die(_("previous rebase directory %s still exists but mbox given."),
2375 if (resume
== RESUME_FALSE
)
2376 resume
= RESUME_APPLY
;
2378 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2379 am_append_signoff(&state
);
2381 struct argv_array paths
= ARGV_ARRAY_INIT
;
2385 * Handle stray state directory in the independent-run case. In
2386 * the --rebasing case, it is up to the caller to take care of
2387 * stray directories.
2389 if (file_exists(state
.dir
) && !state
.rebasing
) {
2390 if (resume
== RESUME_ABORT
) {
2392 am_state_release(&state
);
2396 die(_("Stray %s directory found.\n"
2397 "Use \"git am --abort\" to remove it."),
2402 die(_("Resolve operation not in progress, we are not resuming."));
2404 for (i
= 0; i
< argc
; i
++) {
2405 if (is_absolute_path(argv
[i
]) || !prefix
)
2406 argv_array_push(&paths
, argv
[i
]);
2408 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2411 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
2413 argv_array_clear(&paths
);
2423 case RESUME_RESOLVED
:
2433 die("BUG: invalid resume value");
2436 am_state_release(&state
);