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"
33 * Returns 1 if the file is empty or does not exist, 0 otherwise.
35 static int is_empty_file(const char *filename
)
39 if (stat(filename
, &st
) < 0) {
42 die_errno(_("could not stat %s"), filename
);
49 * Returns the length of the first line of msg.
51 static int linelen(const char *msg
)
53 return strchrnul(msg
, '\n') - msg
;
57 * Returns true if `str` consists of only whitespace, false otherwise.
59 static int str_isspace(const char *str
)
69 PATCH_FORMAT_UNKNOWN
= 0,
72 PATCH_FORMAT_STGIT_SERIES
,
79 KEEP_TRUE
, /* pass -k flag to git-mailinfo */
80 KEEP_NON_PATCH
/* pass -b flag to git-mailinfo */
85 SCISSORS_FALSE
= 0, /* pass --no-scissors to git-mailinfo */
86 SCISSORS_TRUE
/* pass --scissors to git-mailinfo */
92 SIGNOFF_EXPLICIT
/* --signoff was set on the command-line */
96 /* state directory path */
99 /* current and last patch numbers, 1-indexed */
103 /* commit metadata and message */
110 /* when --rebasing, records the original commit the patch came from */
111 unsigned char orig_commit
[GIT_SHA1_RAWSZ
];
113 /* number of digits in patch filename */
116 /* various operating modes and command line options */
120 int signoff
; /* enum signoff_type */
122 int keep
; /* enum keep_type */
124 int scissors
; /* enum scissors_type */
125 struct argv_array git_apply_opts
;
126 const char *resolvemsg
;
127 int committer_date_is_author_date
;
129 int allow_rerere_autoupdate
;
130 const char *sign_commit
;
135 * Initializes am_state with the default values. The state directory is set to
138 static void am_state_init(struct am_state
*state
, const char *dir
)
142 memset(state
, 0, sizeof(*state
));
145 state
->dir
= xstrdup(dir
);
149 git_config_get_bool("am.threeway", &state
->threeway
);
153 git_config_get_bool("am.messageid", &state
->message_id
);
155 state
->scissors
= SCISSORS_UNSET
;
157 argv_array_init(&state
->git_apply_opts
);
159 if (!git_config_get_bool("commit.gpgsign", &gpgsign
))
160 state
->sign_commit
= gpgsign
? "" : NULL
;
164 * Releases memory allocated by an am_state.
166 static void am_state_release(struct am_state
*state
)
169 free(state
->author_name
);
170 free(state
->author_email
);
171 free(state
->author_date
);
173 argv_array_clear(&state
->git_apply_opts
);
177 * Returns path relative to the am_state directory.
179 static inline const char *am_path(const struct am_state
*state
, const char *path
)
181 return mkpath("%s/%s", state
->dir
, path
);
185 * For convenience to call write_file()
187 static int write_state_text(const struct am_state
*state
,
188 const char *name
, const char *string
)
190 return write_file(am_path(state
, name
), "%s", string
);
193 static int write_state_count(const struct am_state
*state
,
194 const char *name
, int value
)
196 return write_file(am_path(state
, name
), "%d", value
);
199 static int write_state_bool(const struct am_state
*state
,
200 const char *name
, int value
)
202 return write_state_text(state
, name
, value
? "t" : "f");
206 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
209 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
215 vfprintf(fp
, fmt
, ap
);
222 * Returns 1 if there is an am session in progress, 0 otherwise.
224 static int am_in_progress(const struct am_state
*state
)
228 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
230 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
232 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
238 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
239 * number of bytes read on success, -1 if the file does not exist. If `trim` is
240 * set, trailing whitespace will be removed.
242 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
243 const char *file
, int trim
)
247 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
257 die_errno(_("could not read '%s'"), am_path(state
, file
));
261 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
262 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
263 * match `key`. Returns NULL on failure.
265 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
268 static char *read_shell_var(FILE *fp
, const char *key
)
270 struct strbuf sb
= STRBUF_INIT
;
273 if (strbuf_getline_lf(&sb
, fp
))
276 if (!skip_prefix(sb
.buf
, key
, &str
))
279 if (!skip_prefix(str
, "=", &str
))
282 strbuf_remove(&sb
, 0, str
- sb
.buf
);
284 str
= sq_dequote(sb
.buf
);
288 return strbuf_detach(&sb
, NULL
);
296 * Reads and parses the state directory's "author-script" file, and sets
297 * state->author_name, state->author_email and state->author_date accordingly.
298 * Returns 0 on success, -1 if the file could not be parsed.
300 * The author script is of the format:
302 * GIT_AUTHOR_NAME='$author_name'
303 * GIT_AUTHOR_EMAIL='$author_email'
304 * GIT_AUTHOR_DATE='$author_date'
306 * where $author_name, $author_email and $author_date are quoted. We are strict
307 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
308 * script, and thus if the file differs from what this function expects, it is
309 * better to bail out than to do something that the user does not expect.
311 static int read_author_script(struct am_state
*state
)
313 const char *filename
= am_path(state
, "author-script");
316 assert(!state
->author_name
);
317 assert(!state
->author_email
);
318 assert(!state
->author_date
);
320 fp
= fopen(filename
, "r");
324 die_errno(_("could not open '%s' for reading"), filename
);
327 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
328 if (!state
->author_name
) {
333 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
334 if (!state
->author_email
) {
339 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
340 if (!state
->author_date
) {
345 if (fgetc(fp
) != EOF
) {
355 * Saves state->author_name, state->author_email and state->author_date in the
356 * state directory's "author-script" file.
358 static void write_author_script(const struct am_state
*state
)
360 struct strbuf sb
= STRBUF_INIT
;
362 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
363 sq_quote_buf(&sb
, state
->author_name
);
364 strbuf_addch(&sb
, '\n');
366 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
367 sq_quote_buf(&sb
, state
->author_email
);
368 strbuf_addch(&sb
, '\n');
370 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
371 sq_quote_buf(&sb
, state
->author_date
);
372 strbuf_addch(&sb
, '\n');
374 write_state_text(state
, "author-script", sb
.buf
);
380 * Reads the commit message from the state directory's "final-commit" file,
381 * setting state->msg to its contents and state->msg_len to the length of its
384 * Returns 0 on success, -1 if the file does not exist.
386 static int read_commit_msg(struct am_state
*state
)
388 struct strbuf sb
= STRBUF_INIT
;
392 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
397 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
402 * Saves state->msg in the state directory's "final-commit" file.
404 static void write_commit_msg(const struct am_state
*state
)
407 const char *filename
= am_path(state
, "final-commit");
409 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
410 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
411 die_errno(_("could not write to %s"), filename
);
416 * Loads state from disk.
418 static void am_load(struct am_state
*state
)
420 struct strbuf sb
= STRBUF_INIT
;
422 if (read_state_file(&sb
, state
, "next", 1) < 0)
423 die("BUG: state file 'next' does not exist");
424 state
->cur
= strtol(sb
.buf
, NULL
, 10);
426 if (read_state_file(&sb
, state
, "last", 1) < 0)
427 die("BUG: state file 'last' does not exist");
428 state
->last
= strtol(sb
.buf
, NULL
, 10);
430 if (read_author_script(state
) < 0)
431 die(_("could not parse author script"));
433 read_commit_msg(state
);
435 if (read_state_file(&sb
, state
, "original-commit", 1) < 0)
436 hashclr(state
->orig_commit
);
437 else if (get_sha1_hex(sb
.buf
, state
->orig_commit
) < 0)
438 die(_("could not parse %s"), am_path(state
, "original-commit"));
440 read_state_file(&sb
, state
, "threeway", 1);
441 state
->threeway
= !strcmp(sb
.buf
, "t");
443 read_state_file(&sb
, state
, "quiet", 1);
444 state
->quiet
= !strcmp(sb
.buf
, "t");
446 read_state_file(&sb
, state
, "sign", 1);
447 state
->signoff
= !strcmp(sb
.buf
, "t");
449 read_state_file(&sb
, state
, "utf8", 1);
450 state
->utf8
= !strcmp(sb
.buf
, "t");
452 read_state_file(&sb
, state
, "keep", 1);
453 if (!strcmp(sb
.buf
, "t"))
454 state
->keep
= KEEP_TRUE
;
455 else if (!strcmp(sb
.buf
, "b"))
456 state
->keep
= KEEP_NON_PATCH
;
458 state
->keep
= KEEP_FALSE
;
460 read_state_file(&sb
, state
, "messageid", 1);
461 state
->message_id
= !strcmp(sb
.buf
, "t");
463 read_state_file(&sb
, state
, "scissors", 1);
464 if (!strcmp(sb
.buf
, "t"))
465 state
->scissors
= SCISSORS_TRUE
;
466 else if (!strcmp(sb
.buf
, "f"))
467 state
->scissors
= SCISSORS_FALSE
;
469 state
->scissors
= SCISSORS_UNSET
;
471 read_state_file(&sb
, state
, "apply-opt", 1);
472 argv_array_clear(&state
->git_apply_opts
);
473 if (sq_dequote_to_argv_array(sb
.buf
, &state
->git_apply_opts
) < 0)
474 die(_("could not parse %s"), am_path(state
, "apply-opt"));
476 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
482 * Removes the am_state directory, forcefully terminating the current am
485 static void am_destroy(const struct am_state
*state
)
487 struct strbuf sb
= STRBUF_INIT
;
489 strbuf_addstr(&sb
, state
->dir
);
490 remove_dir_recursively(&sb
, 0);
495 * Runs applypatch-msg hook. Returns its exit code.
497 static int run_applypatch_msg_hook(struct am_state
*state
)
502 ret
= run_hook_le(NULL
, "applypatch-msg", am_path(state
, "final-commit"), NULL
);
507 if (read_commit_msg(state
) < 0)
508 die(_("'%s' was deleted by the applypatch-msg hook"),
509 am_path(state
, "final-commit"));
516 * Runs post-rewrite hook. Returns it exit code.
518 static int run_post_rewrite_hook(const struct am_state
*state
)
520 struct child_process cp
= CHILD_PROCESS_INIT
;
521 const char *hook
= find_hook("post-rewrite");
527 argv_array_push(&cp
.args
, hook
);
528 argv_array_push(&cp
.args
, "rebase");
530 cp
.in
= xopen(am_path(state
, "rewritten"), O_RDONLY
);
531 cp
.stdout_to_stderr
= 1;
533 ret
= run_command(&cp
);
540 * Reads the state directory's "rewritten" file, and copies notes from the old
541 * commits listed in the file to their rewritten commits.
543 * Returns 0 on success, -1 on failure.
545 static int copy_notes_for_rebase(const struct am_state
*state
)
547 struct notes_rewrite_cfg
*c
;
548 struct strbuf sb
= STRBUF_INIT
;
549 const char *invalid_line
= _("Malformed input line: '%s'.");
550 const char *msg
= "Notes added by 'git rebase'";
554 assert(state
->rebasing
);
556 c
= init_copy_notes_for_rewrite("rebase");
560 fp
= xfopen(am_path(state
, "rewritten"), "r");
562 while (!strbuf_getline_lf(&sb
, fp
)) {
563 unsigned char from_obj
[GIT_SHA1_RAWSZ
], to_obj
[GIT_SHA1_RAWSZ
];
565 if (sb
.len
!= GIT_SHA1_HEXSZ
* 2 + 1) {
566 ret
= error(invalid_line
, sb
.buf
);
570 if (get_sha1_hex(sb
.buf
, from_obj
)) {
571 ret
= error(invalid_line
, sb
.buf
);
575 if (sb
.buf
[GIT_SHA1_HEXSZ
] != ' ') {
576 ret
= error(invalid_line
, sb
.buf
);
580 if (get_sha1_hex(sb
.buf
+ GIT_SHA1_HEXSZ
+ 1, to_obj
)) {
581 ret
= error(invalid_line
, sb
.buf
);
585 if (copy_note_for_rewrite(c
, from_obj
, to_obj
))
586 ret
= error(_("Failed to copy notes from '%s' to '%s'"),
587 sha1_to_hex(from_obj
), sha1_to_hex(to_obj
));
591 finish_copy_notes_for_rewrite(c
, msg
);
598 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
599 * non-indented lines and checking if they look like they begin with valid
600 * header field names.
602 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
604 static int is_mail(FILE *fp
)
606 const char *header_regex
= "^[!-9;-~]+:";
607 struct strbuf sb
= STRBUF_INIT
;
611 if (fseek(fp
, 0L, SEEK_SET
))
612 die_errno(_("fseek failed"));
614 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
615 die("invalid pattern: %s", header_regex
);
617 while (!strbuf_getline(&sb
, fp
)) {
619 break; /* End of header */
621 /* Ignore indented folded lines */
622 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
625 /* It's a header if it matches header_regex */
626 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
639 * Attempts to detect the patch_format of the patches contained in `paths`,
640 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
643 static int detect_patch_format(const char **paths
)
645 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
646 struct strbuf l1
= STRBUF_INIT
;
647 struct strbuf l2
= STRBUF_INIT
;
648 struct strbuf l3
= STRBUF_INIT
;
652 * We default to mbox format if input is from stdin and for directories
654 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
655 return PATCH_FORMAT_MBOX
;
658 * Otherwise, check the first few lines of the first patch, starting
659 * from the first non-blank line, to try to detect its format.
662 fp
= xfopen(*paths
, "r");
664 while (!strbuf_getline(&l1
, fp
)) {
669 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
670 ret
= PATCH_FORMAT_MBOX
;
674 if (starts_with(l1
.buf
, "# This series applies on GIT commit")) {
675 ret
= PATCH_FORMAT_STGIT_SERIES
;
679 if (!strcmp(l1
.buf
, "# HG changeset patch")) {
680 ret
= PATCH_FORMAT_HG
;
685 strbuf_getline(&l2
, fp
);
687 strbuf_getline(&l3
, fp
);
690 * If the second line is empty and the third is a From, Author or Date
691 * entry, this is likely an StGit patch.
693 if (l1
.len
&& !l2
.len
&&
694 (starts_with(l3
.buf
, "From:") ||
695 starts_with(l3
.buf
, "Author:") ||
696 starts_with(l3
.buf
, "Date:"))) {
697 ret
= PATCH_FORMAT_STGIT
;
701 if (l1
.len
&& is_mail(fp
)) {
702 ret
= PATCH_FORMAT_MBOX
;
713 * Splits out individual email patches from `paths`, where each path is either
714 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
716 static int split_mail_mbox(struct am_state
*state
, const char **paths
,
717 int keep_cr
, int mboxrd
)
719 struct child_process cp
= CHILD_PROCESS_INIT
;
720 struct strbuf last
= STRBUF_INIT
;
723 argv_array_push(&cp
.args
, "mailsplit");
724 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
725 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
726 argv_array_push(&cp
.args
, "-b");
728 argv_array_push(&cp
.args
, "--keep-cr");
730 argv_array_push(&cp
.args
, "--mboxrd");
731 argv_array_push(&cp
.args
, "--");
732 argv_array_pushv(&cp
.args
, paths
);
734 if (capture_command(&cp
, &last
, 8))
738 state
->last
= strtol(last
.buf
, NULL
, 10);
744 * Callback signature for split_mail_conv(). The foreign patch should be
745 * read from `in`, and the converted patch (in RFC2822 mail format) should be
746 * written to `out`. Return 0 on success, or -1 on failure.
748 typedef int (*mail_conv_fn
)(FILE *out
, FILE *in
, int keep_cr
);
751 * Calls `fn` for each file in `paths` to convert the foreign patch to the
752 * RFC2822 mail format suitable for parsing with git-mailinfo.
754 * Returns 0 on success, -1 on failure.
756 static int split_mail_conv(mail_conv_fn fn
, struct am_state
*state
,
757 const char **paths
, int keep_cr
)
759 static const char *stdin_only
[] = {"-", NULL
};
765 for (i
= 0; *paths
; paths
++, i
++) {
770 if (!strcmp(*paths
, "-"))
773 in
= fopen(*paths
, "r");
776 return error_errno(_("could not open '%s' for reading"),
779 mail
= mkpath("%s/%0*d", state
->dir
, state
->prec
, i
+ 1);
781 out
= fopen(mail
, "w");
783 return error_errno(_("could not open '%s' for writing"),
786 ret
= fn(out
, in
, keep_cr
);
792 return error(_("could not parse patch '%s'"), *paths
);
801 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
802 * message suitable for parsing with git-mailinfo.
804 static int stgit_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
806 struct strbuf sb
= STRBUF_INIT
;
807 int subject_printed
= 0;
809 while (!strbuf_getline_lf(&sb
, in
)) {
812 if (str_isspace(sb
.buf
))
814 else if (skip_prefix(sb
.buf
, "Author:", &str
))
815 fprintf(out
, "From:%s\n", str
);
816 else if (starts_with(sb
.buf
, "From") || starts_with(sb
.buf
, "Date"))
817 fprintf(out
, "%s\n", sb
.buf
);
818 else if (!subject_printed
) {
819 fprintf(out
, "Subject: %s\n", sb
.buf
);
822 fprintf(out
, "\n%s\n", sb
.buf
);
828 while (strbuf_fread(&sb
, 8192, in
) > 0) {
829 fwrite(sb
.buf
, 1, sb
.len
, out
);
838 * This function only supports a single StGit series file in `paths`.
840 * Given an StGit series file, converts the StGit patches in the series into
841 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
842 * the state directory.
844 * Returns 0 on success, -1 on failure.
846 static int split_mail_stgit_series(struct am_state
*state
, const char **paths
,
849 const char *series_dir
;
850 char *series_dir_buf
;
852 struct argv_array patches
= ARGV_ARRAY_INIT
;
853 struct strbuf sb
= STRBUF_INIT
;
856 if (!paths
[0] || paths
[1])
857 return error(_("Only one StGIT patch series can be applied at once"));
859 series_dir_buf
= xstrdup(*paths
);
860 series_dir
= dirname(series_dir_buf
);
862 fp
= fopen(*paths
, "r");
864 return error_errno(_("could not open '%s' for reading"), *paths
);
866 while (!strbuf_getline_lf(&sb
, fp
)) {
868 continue; /* skip comment lines */
870 argv_array_push(&patches
, mkpath("%s/%s", series_dir
, sb
.buf
));
875 free(series_dir_buf
);
877 ret
= split_mail_conv(stgit_patch_to_mail
, state
, patches
.argv
, keep_cr
);
879 argv_array_clear(&patches
);
884 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
885 * message suitable for parsing with git-mailinfo.
887 static int hg_patch_to_mail(FILE *out
, FILE *in
, int keep_cr
)
889 struct strbuf sb
= STRBUF_INIT
;
891 while (!strbuf_getline_lf(&sb
, in
)) {
894 if (skip_prefix(sb
.buf
, "# User ", &str
))
895 fprintf(out
, "From: %s\n", str
);
896 else if (skip_prefix(sb
.buf
, "# Date ", &str
)) {
897 unsigned long timestamp
;
902 timestamp
= strtoul(str
, &end
, 10);
904 return error(_("invalid timestamp"));
906 if (!skip_prefix(end
, " ", &str
))
907 return error(_("invalid Date line"));
910 tz
= strtol(str
, &end
, 10);
912 return error(_("invalid timezone offset"));
915 return error(_("invalid Date line"));
918 * mercurial's timezone is in seconds west of UTC,
919 * however git's timezone is in hours + minutes east of
922 tz2
= labs(tz
) / 3600 * 100 + labs(tz
) % 3600 / 60;
926 fprintf(out
, "Date: %s\n", show_date(timestamp
, tz2
, DATE_MODE(RFC2822
)));
927 } else if (starts_with(sb
.buf
, "# ")) {
930 fprintf(out
, "\n%s\n", sb
.buf
);
936 while (strbuf_fread(&sb
, 8192, in
) > 0) {
937 fwrite(sb
.buf
, 1, sb
.len
, out
);
946 * Splits a list of files/directories into individual email patches. Each path
947 * in `paths` must be a file/directory that is formatted according to
950 * Once split out, the individual email patches will be stored in the state
951 * directory, with each patch's filename being its index, padded to state->prec
954 * state->cur will be set to the index of the first mail, and state->last will
955 * be set to the index of the last mail.
957 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
958 * to disable this behavior, -1 to use the default configured setting.
960 * Returns 0 on success, -1 on failure.
962 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
963 const char **paths
, int keep_cr
)
967 git_config_get_bool("am.keepcr", &keep_cr
);
970 switch (patch_format
) {
971 case PATCH_FORMAT_MBOX
:
972 return split_mail_mbox(state
, paths
, keep_cr
, 0);
973 case PATCH_FORMAT_STGIT
:
974 return split_mail_conv(stgit_patch_to_mail
, state
, paths
, keep_cr
);
975 case PATCH_FORMAT_STGIT_SERIES
:
976 return split_mail_stgit_series(state
, paths
, keep_cr
);
977 case PATCH_FORMAT_HG
:
978 return split_mail_conv(hg_patch_to_mail
, state
, paths
, keep_cr
);
979 case PATCH_FORMAT_MBOXRD
:
980 return split_mail_mbox(state
, paths
, keep_cr
, 1);
982 die("BUG: invalid patch_format");
988 * Setup a new am session for applying patches
990 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
991 const char **paths
, int keep_cr
)
993 unsigned char curr_head
[GIT_SHA1_RAWSZ
];
995 struct strbuf sb
= STRBUF_INIT
;
998 patch_format
= detect_patch_format(paths
);
1000 if (!patch_format
) {
1001 fprintf_ln(stderr
, _("Patch format detection failed."));
1005 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
1006 die_errno(_("failed to create directory '%s'"), state
->dir
);
1008 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
1010 die(_("Failed to split patches."));
1013 if (state
->rebasing
)
1014 state
->threeway
= 1;
1016 write_state_bool(state
, "threeway", state
->threeway
);
1017 write_state_bool(state
, "quiet", state
->quiet
);
1018 write_state_bool(state
, "sign", state
->signoff
);
1019 write_state_bool(state
, "utf8", state
->utf8
);
1021 switch (state
->keep
) {
1028 case KEEP_NON_PATCH
:
1032 die("BUG: invalid value for state->keep");
1035 write_state_text(state
, "keep", str
);
1036 write_state_bool(state
, "messageid", state
->message_id
);
1038 switch (state
->scissors
) {
1039 case SCISSORS_UNSET
:
1042 case SCISSORS_FALSE
:
1049 die("BUG: invalid value for state->scissors");
1051 write_state_text(state
, "scissors", str
);
1053 sq_quote_argv(&sb
, state
->git_apply_opts
.argv
, 0);
1054 write_state_text(state
, "apply-opt", sb
.buf
);
1056 if (state
->rebasing
)
1057 write_state_text(state
, "rebasing", "");
1059 write_state_text(state
, "applying", "");
1061 if (!get_sha1("HEAD", curr_head
)) {
1062 write_state_text(state
, "abort-safety", sha1_to_hex(curr_head
));
1063 if (!state
->rebasing
)
1064 update_ref("am", "ORIG_HEAD", curr_head
, NULL
, 0,
1065 UPDATE_REFS_DIE_ON_ERR
);
1067 write_state_text(state
, "abort-safety", "");
1068 if (!state
->rebasing
)
1069 delete_ref("ORIG_HEAD", NULL
, 0);
1073 * NOTE: Since the "next" and "last" files determine if an am_state
1074 * session is in progress, they should be written last.
1077 write_state_count(state
, "next", state
->cur
);
1078 write_state_count(state
, "last", state
->last
);
1080 strbuf_release(&sb
);
1084 * Increments the patch pointer, and cleans am_state for the application of the
1087 static void am_next(struct am_state
*state
)
1089 unsigned char head
[GIT_SHA1_RAWSZ
];
1091 free(state
->author_name
);
1092 state
->author_name
= NULL
;
1094 free(state
->author_email
);
1095 state
->author_email
= NULL
;
1097 free(state
->author_date
);
1098 state
->author_date
= NULL
;
1104 unlink(am_path(state
, "author-script"));
1105 unlink(am_path(state
, "final-commit"));
1107 hashclr(state
->orig_commit
);
1108 unlink(am_path(state
, "original-commit"));
1110 if (!get_sha1("HEAD", head
))
1111 write_state_text(state
, "abort-safety", sha1_to_hex(head
));
1113 write_state_text(state
, "abort-safety", "");
1116 write_state_count(state
, "next", state
->cur
);
1120 * Returns the filename of the current patch email.
1122 static const char *msgnum(const struct am_state
*state
)
1124 static struct strbuf sb
= STRBUF_INIT
;
1127 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
1133 * Refresh and write index.
1135 static void refresh_and_write_cache(void)
1137 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
1139 hold_locked_index(lock_file
, 1);
1140 refresh_cache(REFRESH_QUIET
);
1141 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1142 die(_("unable to write index file"));
1146 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1147 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1148 * strbuf is provided, the space-separated list of files that differ will be
1151 static int index_has_changes(struct strbuf
*sb
)
1153 unsigned char head
[GIT_SHA1_RAWSZ
];
1156 if (!get_sha1_tree("HEAD", head
)) {
1157 struct diff_options opt
;
1160 DIFF_OPT_SET(&opt
, EXIT_WITH_STATUS
);
1162 DIFF_OPT_SET(&opt
, QUICK
);
1163 do_diff_cache(head
, &opt
);
1165 for (i
= 0; sb
&& i
< diff_queued_diff
.nr
; i
++) {
1167 strbuf_addch(sb
, ' ');
1168 strbuf_addstr(sb
, diff_queued_diff
.queue
[i
]->two
->path
);
1171 return DIFF_OPT_TST(&opt
, HAS_CHANGES
) != 0;
1173 for (i
= 0; sb
&& i
< active_nr
; i
++) {
1175 strbuf_addch(sb
, ' ');
1176 strbuf_addstr(sb
, active_cache
[i
]->name
);
1183 * Dies with a user-friendly message on how to proceed after resolving the
1184 * problem. This message can be overridden with state->resolvemsg.
1186 static void NORETURN
die_user_resolve(const struct am_state
*state
)
1188 if (state
->resolvemsg
) {
1189 printf_ln("%s", state
->resolvemsg
);
1191 const char *cmdline
= state
->interactive
? "git am -i" : "git am";
1193 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
1194 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
1195 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
1201 static void am_signoff(struct strbuf
*sb
)
1204 struct strbuf mine
= STRBUF_INIT
;
1206 /* Does it end with our own sign-off? */
1207 strbuf_addf(&mine
, "\n%s%s\n",
1209 fmt_name(getenv("GIT_COMMITTER_NAME"),
1210 getenv("GIT_COMMITTER_EMAIL")));
1211 if (mine
.len
< sb
->len
&&
1212 !strcmp(mine
.buf
, sb
->buf
+ sb
->len
- mine
.len
))
1213 goto exit
; /* no need to duplicate */
1215 /* Does it have any Signed-off-by: in the text */
1217 cp
&& *cp
&& (cp
= strstr(cp
, sign_off_header
)) != NULL
;
1218 cp
= strchr(cp
, '\n')) {
1219 if (sb
->buf
== cp
|| cp
[-1] == '\n')
1223 strbuf_addstr(sb
, mine
.buf
+ !!cp
);
1225 strbuf_release(&mine
);
1229 * Appends signoff to the "msg" field of the am_state.
1231 static void am_append_signoff(struct am_state
*state
)
1233 struct strbuf sb
= STRBUF_INIT
;
1235 strbuf_attach(&sb
, state
->msg
, state
->msg_len
, state
->msg_len
);
1237 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
1241 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1242 * state->msg will be set to the patch message. state->author_name,
1243 * state->author_email and state->author_date will be set to the patch author's
1244 * name, email and date respectively. The patch body will be written to the
1245 * state directory's "patch" file.
1247 * Returns 1 if the patch should be skipped, 0 otherwise.
1249 static int parse_mail(struct am_state
*state
, const char *mail
)
1252 struct strbuf sb
= STRBUF_INIT
;
1253 struct strbuf msg
= STRBUF_INIT
;
1254 struct strbuf author_name
= STRBUF_INIT
;
1255 struct strbuf author_date
= STRBUF_INIT
;
1256 struct strbuf author_email
= STRBUF_INIT
;
1260 setup_mailinfo(&mi
);
1263 mi
.metainfo_charset
= get_commit_output_encoding();
1265 mi
.metainfo_charset
= NULL
;
1267 switch (state
->keep
) {
1271 mi
.keep_subject
= 1;
1273 case KEEP_NON_PATCH
:
1274 mi
.keep_non_patch_brackets_in_subject
= 1;
1277 die("BUG: invalid value for state->keep");
1280 if (state
->message_id
)
1281 mi
.add_message_id
= 1;
1283 switch (state
->scissors
) {
1284 case SCISSORS_UNSET
:
1286 case SCISSORS_FALSE
:
1287 mi
.use_scissors
= 0;
1290 mi
.use_scissors
= 1;
1293 die("BUG: invalid value for state->scissors");
1296 mi
.input
= fopen(mail
, "r");
1298 die("could not open input");
1299 mi
.output
= fopen(am_path(state
, "info"), "w");
1301 die("could not open output 'info'");
1302 if (mailinfo(&mi
, am_path(state
, "msg"), am_path(state
, "patch")))
1303 die("could not parse patch");
1308 /* Extract message and author information */
1309 fp
= xfopen(am_path(state
, "info"), "r");
1310 while (!strbuf_getline_lf(&sb
, fp
)) {
1313 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
1315 strbuf_addch(&msg
, '\n');
1316 strbuf_addstr(&msg
, x
);
1317 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
1318 strbuf_addstr(&author_name
, x
);
1319 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
1320 strbuf_addstr(&author_email
, x
);
1321 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
1322 strbuf_addstr(&author_date
, x
);
1326 /* Skip pine's internal folder data */
1327 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
1332 if (is_empty_file(am_path(state
, "patch"))) {
1333 printf_ln(_("Patch is empty. Was it split wrong?"));
1334 die_user_resolve(state
);
1337 strbuf_addstr(&msg
, "\n\n");
1338 strbuf_addbuf(&msg
, &mi
.log_message
);
1339 strbuf_stripspace(&msg
, 0);
1344 assert(!state
->author_name
);
1345 state
->author_name
= strbuf_detach(&author_name
, NULL
);
1347 assert(!state
->author_email
);
1348 state
->author_email
= strbuf_detach(&author_email
, NULL
);
1350 assert(!state
->author_date
);
1351 state
->author_date
= strbuf_detach(&author_date
, NULL
);
1353 assert(!state
->msg
);
1354 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1357 strbuf_release(&msg
);
1358 strbuf_release(&author_date
);
1359 strbuf_release(&author_email
);
1360 strbuf_release(&author_name
);
1361 strbuf_release(&sb
);
1362 clear_mailinfo(&mi
);
1367 * Sets commit_id to the commit hash where the mail was generated from.
1368 * Returns 0 on success, -1 on failure.
1370 static int get_mail_commit_sha1(unsigned char *commit_id
, const char *mail
)
1372 struct strbuf sb
= STRBUF_INIT
;
1373 FILE *fp
= xfopen(mail
, "r");
1376 if (strbuf_getline_lf(&sb
, fp
))
1379 if (!skip_prefix(sb
.buf
, "From ", &x
))
1382 if (get_sha1_hex(x
, commit_id
) < 0)
1385 strbuf_release(&sb
);
1391 * Sets state->msg, state->author_name, state->author_email, state->author_date
1392 * to the commit's respective info.
1394 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
1396 const char *buffer
, *ident_line
, *author_date
, *msg
;
1398 struct ident_split ident_split
;
1399 struct strbuf sb
= STRBUF_INIT
;
1401 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
1403 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
1405 if (split_ident_line(&ident_split
, ident_line
, ident_len
) < 0) {
1406 strbuf_add(&sb
, ident_line
, ident_len
);
1407 die(_("invalid ident line: %s"), sb
.buf
);
1410 assert(!state
->author_name
);
1411 if (ident_split
.name_begin
) {
1412 strbuf_add(&sb
, ident_split
.name_begin
,
1413 ident_split
.name_end
- ident_split
.name_begin
);
1414 state
->author_name
= strbuf_detach(&sb
, NULL
);
1416 state
->author_name
= xstrdup("");
1418 assert(!state
->author_email
);
1419 if (ident_split
.mail_begin
) {
1420 strbuf_add(&sb
, ident_split
.mail_begin
,
1421 ident_split
.mail_end
- ident_split
.mail_begin
);
1422 state
->author_email
= strbuf_detach(&sb
, NULL
);
1424 state
->author_email
= xstrdup("");
1426 author_date
= show_ident_date(&ident_split
, DATE_MODE(NORMAL
));
1427 strbuf_addstr(&sb
, author_date
);
1428 assert(!state
->author_date
);
1429 state
->author_date
= strbuf_detach(&sb
, NULL
);
1431 assert(!state
->msg
);
1432 msg
= strstr(buffer
, "\n\n");
1434 die(_("unable to parse commit %s"), oid_to_hex(&commit
->object
.oid
));
1435 state
->msg
= xstrdup(msg
+ 2);
1436 state
->msg_len
= strlen(state
->msg
);
1440 * Writes `commit` as a patch to the state directory's "patch" file.
1442 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
1444 struct rev_info rev_info
;
1447 fp
= xfopen(am_path(state
, "patch"), "w");
1448 init_revisions(&rev_info
, NULL
);
1450 rev_info
.abbrev
= 0;
1451 rev_info
.disable_stdin
= 1;
1452 rev_info
.show_root_diff
= 1;
1453 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1454 rev_info
.no_commit_id
= 1;
1455 DIFF_OPT_SET(&rev_info
.diffopt
, BINARY
);
1456 DIFF_OPT_SET(&rev_info
.diffopt
, FULL_INDEX
);
1457 rev_info
.diffopt
.use_color
= 0;
1458 rev_info
.diffopt
.file
= fp
;
1459 rev_info
.diffopt
.close_file
= 1;
1460 add_pending_object(&rev_info
, &commit
->object
, "");
1461 diff_setup_done(&rev_info
.diffopt
);
1462 log_tree_commit(&rev_info
, commit
);
1466 * Writes the diff of the index against HEAD as a patch to the state
1467 * directory's "patch" file.
1469 static void write_index_patch(const struct am_state
*state
)
1472 unsigned char head
[GIT_SHA1_RAWSZ
];
1473 struct rev_info rev_info
;
1476 if (!get_sha1_tree("HEAD", head
))
1477 tree
= lookup_tree(head
);
1479 tree
= lookup_tree(EMPTY_TREE_SHA1_BIN
);
1481 fp
= xfopen(am_path(state
, "patch"), "w");
1482 init_revisions(&rev_info
, NULL
);
1484 rev_info
.disable_stdin
= 1;
1485 rev_info
.no_commit_id
= 1;
1486 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1487 rev_info
.diffopt
.use_color
= 0;
1488 rev_info
.diffopt
.file
= fp
;
1489 rev_info
.diffopt
.close_file
= 1;
1490 add_pending_object(&rev_info
, &tree
->object
, "");
1491 diff_setup_done(&rev_info
.diffopt
);
1492 run_diff_index(&rev_info
, 1);
1496 * Like parse_mail(), but parses the mail by looking up its commit ID
1497 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1500 * state->orig_commit will be set to the original commit ID.
1502 * Will always return 0 as the patch should never be skipped.
1504 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1506 struct commit
*commit
;
1507 unsigned char commit_sha1
[GIT_SHA1_RAWSZ
];
1509 if (get_mail_commit_sha1(commit_sha1
, mail
) < 0)
1510 die(_("could not parse %s"), mail
);
1512 commit
= lookup_commit_or_die(commit_sha1
, mail
);
1514 get_commit_info(state
, commit
);
1516 write_commit_patch(state
, commit
);
1518 hashcpy(state
->orig_commit
, commit_sha1
);
1519 write_state_text(state
, "original-commit", sha1_to_hex(commit_sha1
));
1525 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1526 * `index_file` is not NULL, the patch will be applied to that index.
1528 static int run_apply(const struct am_state
*state
, const char *index_file
)
1530 struct child_process cp
= CHILD_PROCESS_INIT
;
1535 argv_array_pushf(&cp
.env_array
, "GIT_INDEX_FILE=%s", index_file
);
1538 * If we are allowed to fall back on 3-way merge, don't give false
1539 * errors during the initial attempt.
1541 if (state
->threeway
&& !index_file
) {
1546 argv_array_push(&cp
.args
, "apply");
1548 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1551 argv_array_push(&cp
.args
, "--cached");
1553 argv_array_push(&cp
.args
, "--index");
1555 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1557 if (run_command(&cp
))
1560 /* Reload index as git-apply will have modified it. */
1562 read_cache_from(index_file
? index_file
: get_index_file());
1568 * Builds an index that contains just the blobs needed for a 3way merge.
1570 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1572 struct child_process cp
= CHILD_PROCESS_INIT
;
1575 argv_array_push(&cp
.args
, "apply");
1576 argv_array_pushv(&cp
.args
, state
->git_apply_opts
.argv
);
1577 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1578 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1580 if (run_command(&cp
))
1587 * Do the three-way merge using fake ancestor, his tree constructed
1588 * from the fake ancestor and the postimage of the patch, and our
1591 static int run_fallback_merge_recursive(const struct am_state
*state
,
1592 unsigned char *orig_tree
,
1593 unsigned char *our_tree
,
1594 unsigned char *his_tree
)
1596 struct child_process cp
= CHILD_PROCESS_INIT
;
1601 argv_array_pushf(&cp
.env_array
, "GITHEAD_%s=%.*s",
1602 sha1_to_hex(his_tree
), linelen(state
->msg
), state
->msg
);
1604 argv_array_push(&cp
.env_array
, "GIT_MERGE_VERBOSITY=0");
1606 argv_array_push(&cp
.args
, "merge-recursive");
1607 argv_array_push(&cp
.args
, sha1_to_hex(orig_tree
));
1608 argv_array_push(&cp
.args
, "--");
1609 argv_array_push(&cp
.args
, sha1_to_hex(our_tree
));
1610 argv_array_push(&cp
.args
, sha1_to_hex(his_tree
));
1612 status
= run_command(&cp
) ? (-1) : 0;
1619 * Attempt a threeway merge, using index_path as the temporary index.
1621 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1623 unsigned char orig_tree
[GIT_SHA1_RAWSZ
], his_tree
[GIT_SHA1_RAWSZ
],
1624 our_tree
[GIT_SHA1_RAWSZ
];
1626 if (get_sha1("HEAD", our_tree
) < 0)
1627 hashcpy(our_tree
, EMPTY_TREE_SHA1_BIN
);
1629 if (build_fake_ancestor(state
, index_path
))
1630 return error("could not build fake ancestor");
1633 read_cache_from(index_path
);
1635 if (write_index_as_tree(orig_tree
, &the_index
, index_path
, 0, NULL
))
1636 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1638 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1640 if (!state
->quiet
) {
1642 * List paths that needed 3-way fallback, so that the user can
1643 * review them with extra care to spot mismerges.
1645 struct rev_info rev_info
;
1646 const char *diff_filter_str
= "--diff-filter=AM";
1648 init_revisions(&rev_info
, NULL
);
1649 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1650 diff_opt_parse(&rev_info
.diffopt
, &diff_filter_str
, 1, rev_info
.prefix
);
1651 add_pending_sha1(&rev_info
, "HEAD", our_tree
, 0);
1652 diff_setup_done(&rev_info
.diffopt
);
1653 run_diff_index(&rev_info
, 1);
1656 if (run_apply(state
, index_path
))
1657 return error(_("Did you hand edit your patch?\n"
1658 "It does not apply to blobs recorded in its index."));
1660 if (write_index_as_tree(his_tree
, &the_index
, index_path
, 0, NULL
))
1661 return error("could not write tree");
1663 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1669 * This is not so wrong. Depending on which base we picked, orig_tree
1670 * may be wildly different from ours, but his_tree has the same set of
1671 * wildly different changes in parts the patch did not touch, so
1672 * recursive ends up canceling them, saying that we reverted all those
1676 if (run_fallback_merge_recursive(state
, orig_tree
, our_tree
, his_tree
)) {
1677 rerere(state
->allow_rerere_autoupdate
);
1678 return error(_("Failed to merge in the changes."));
1685 * Commits the current index with state->msg as the commit message and
1686 * state->author_name, state->author_email and state->author_date as the author
1689 static void do_commit(const struct am_state
*state
)
1691 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
1692 commit
[GIT_SHA1_RAWSZ
];
1694 struct commit_list
*parents
= NULL
;
1695 const char *reflog_msg
, *author
;
1696 struct strbuf sb
= STRBUF_INIT
;
1698 if (run_hook_le(NULL
, "pre-applypatch", NULL
))
1701 if (write_cache_as_tree(tree
, 0, NULL
))
1702 die(_("git write-tree failed to write a tree"));
1704 if (!get_sha1_commit("HEAD", parent
)) {
1706 commit_list_insert(lookup_commit(parent
), &parents
);
1709 say(state
, stderr
, _("applying to an empty history"));
1712 author
= fmt_ident(state
->author_name
, state
->author_email
,
1713 state
->ignore_date
? NULL
: state
->author_date
,
1716 if (state
->committer_date_is_author_date
)
1717 setenv("GIT_COMMITTER_DATE",
1718 state
->ignore_date
? "" : state
->author_date
, 1);
1720 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
1721 author
, state
->sign_commit
))
1722 die(_("failed to write commit object"));
1724 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1728 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1731 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
1733 if (state
->rebasing
) {
1734 FILE *fp
= xfopen(am_path(state
, "rewritten"), "a");
1736 assert(!is_null_sha1(state
->orig_commit
));
1737 fprintf(fp
, "%s ", sha1_to_hex(state
->orig_commit
));
1738 fprintf(fp
, "%s\n", sha1_to_hex(commit
));
1742 run_hook_le(NULL
, "post-applypatch", NULL
);
1744 strbuf_release(&sb
);
1748 * Validates the am_state for resuming -- the "msg" and authorship fields must
1751 static void validate_resume_state(const struct am_state
*state
)
1754 die(_("cannot resume: %s does not exist."),
1755 am_path(state
, "final-commit"));
1757 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1758 die(_("cannot resume: %s does not exist."),
1759 am_path(state
, "author-script"));
1763 * Interactively prompt the user on whether the current patch should be
1766 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1769 static int do_interactive(struct am_state
*state
)
1774 die(_("cannot be interactive without stdin connected to a terminal."));
1779 puts(_("Commit Body is:"));
1780 puts("--------------------------");
1781 printf("%s", state
->msg
);
1782 puts("--------------------------");
1785 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1786 * in your translation. The program will only accept English
1787 * input at this point.
1789 reply
= git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO
);
1793 } else if (*reply
== 'y' || *reply
== 'Y') {
1795 } else if (*reply
== 'a' || *reply
== 'A') {
1796 state
->interactive
= 0;
1798 } else if (*reply
== 'n' || *reply
== 'N') {
1800 } else if (*reply
== 'e' || *reply
== 'E') {
1801 struct strbuf msg
= STRBUF_INIT
;
1803 if (!launch_editor(am_path(state
, "final-commit"), &msg
, NULL
)) {
1805 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
1807 strbuf_release(&msg
);
1808 } else if (*reply
== 'v' || *reply
== 'V') {
1809 const char *pager
= git_pager(1);
1810 struct child_process cp
= CHILD_PROCESS_INIT
;
1814 prepare_pager_args(&cp
, pager
);
1815 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1822 * Applies all queued mail.
1824 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1825 * well as the state directory's "patch" file is used as-is for applying the
1826 * patch and committing it.
1828 static void am_run(struct am_state
*state
, int resume
)
1830 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1831 struct strbuf sb
= STRBUF_INIT
;
1833 unlink(am_path(state
, "dirtyindex"));
1835 refresh_and_write_cache();
1837 if (index_has_changes(&sb
)) {
1838 write_state_bool(state
, "dirtyindex", 1);
1839 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1842 strbuf_release(&sb
);
1844 while (state
->cur
<= state
->last
) {
1845 const char *mail
= am_path(state
, msgnum(state
));
1848 if (!file_exists(mail
))
1852 validate_resume_state(state
);
1856 if (state
->rebasing
)
1857 skip
= parse_mail_rebase(state
, mail
);
1859 skip
= parse_mail(state
, mail
);
1862 goto next
; /* mail should be skipped */
1864 write_author_script(state
);
1865 write_commit_msg(state
);
1868 if (state
->interactive
&& do_interactive(state
))
1871 if (run_applypatch_msg_hook(state
))
1874 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1876 apply_status
= run_apply(state
, NULL
);
1878 if (apply_status
&& state
->threeway
) {
1879 struct strbuf sb
= STRBUF_INIT
;
1881 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1882 apply_status
= fall_back_threeway(state
, sb
.buf
);
1883 strbuf_release(&sb
);
1886 * Applying the patch to an earlier tree and merging
1887 * the result may have produced the same tree as ours.
1889 if (!apply_status
&& !index_has_changes(NULL
)) {
1890 say(state
, stdout
, _("No changes -- Patch already applied."));
1896 int advice_amworkdir
= 1;
1898 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1899 linelen(state
->msg
), state
->msg
);
1901 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
1903 if (advice_amworkdir
)
1904 printf_ln(_("The copy of the patch that failed is found in: %s"),
1905 am_path(state
, "patch"));
1907 die_user_resolve(state
);
1920 if (!is_empty_file(am_path(state
, "rewritten"))) {
1921 assert(state
->rebasing
);
1922 copy_notes_for_rebase(state
);
1923 run_post_rewrite_hook(state
);
1927 * In rebasing mode, it's up to the caller to take care of
1930 if (!state
->rebasing
) {
1933 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1938 * Resume the current am session after patch application failure. The user did
1939 * all the hard work, and we do not have to do any patch application. Just
1940 * trust and commit what the user has in the index and working tree.
1942 static void am_resolve(struct am_state
*state
)
1944 validate_resume_state(state
);
1946 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1948 if (!index_has_changes(NULL
)) {
1949 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1950 "If there is nothing left to stage, chances are that something else\n"
1951 "already introduced the same changes; you might want to skip this patch."));
1952 die_user_resolve(state
);
1955 if (unmerged_cache()) {
1956 printf_ln(_("You still have unmerged paths in your index.\n"
1957 "Did you forget to use 'git add'?"));
1958 die_user_resolve(state
);
1961 if (state
->interactive
) {
1962 write_index_patch(state
);
1963 if (do_interactive(state
))
1978 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1979 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1982 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1984 struct lock_file
*lock_file
;
1985 struct unpack_trees_options opts
;
1986 struct tree_desc t
[2];
1988 if (parse_tree(head
) || parse_tree(remote
))
1991 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1992 hold_locked_index(lock_file
, 1);
1994 refresh_cache(REFRESH_QUIET
);
1996 memset(&opts
, 0, sizeof(opts
));
1998 opts
.src_index
= &the_index
;
1999 opts
.dst_index
= &the_index
;
2003 opts
.fn
= twoway_merge
;
2004 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
2005 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
2007 if (unpack_trees(2, t
, &opts
)) {
2008 rollback_lock_file(lock_file
);
2012 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
2013 die(_("unable to write new index file"));
2019 * Merges a tree into the index. The index's stat info will take precedence
2020 * over the merged tree's. Returns 0 on success, -1 on failure.
2022 static int merge_tree(struct tree
*tree
)
2024 struct lock_file
*lock_file
;
2025 struct unpack_trees_options opts
;
2026 struct tree_desc t
[1];
2028 if (parse_tree(tree
))
2031 lock_file
= xcalloc(1, sizeof(struct lock_file
));
2032 hold_locked_index(lock_file
, 1);
2034 memset(&opts
, 0, sizeof(opts
));
2036 opts
.src_index
= &the_index
;
2037 opts
.dst_index
= &the_index
;
2039 opts
.fn
= oneway_merge
;
2040 init_tree_desc(&t
[0], tree
->buffer
, tree
->size
);
2042 if (unpack_trees(1, t
, &opts
)) {
2043 rollback_lock_file(lock_file
);
2047 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
2048 die(_("unable to write new index file"));
2054 * Clean the index without touching entries that are not modified between
2055 * `head` and `remote`.
2057 static int clean_index(const unsigned char *head
, const unsigned char *remote
)
2059 struct tree
*head_tree
, *remote_tree
, *index_tree
;
2060 unsigned char index
[GIT_SHA1_RAWSZ
];
2062 head_tree
= parse_tree_indirect(head
);
2064 return error(_("Could not parse object '%s'."), sha1_to_hex(head
));
2066 remote_tree
= parse_tree_indirect(remote
);
2068 return error(_("Could not parse object '%s'."), sha1_to_hex(remote
));
2070 read_cache_unmerged();
2072 if (fast_forward_to(head_tree
, head_tree
, 1))
2075 if (write_cache_as_tree(index
, 0, NULL
))
2078 index_tree
= parse_tree_indirect(index
);
2080 return error(_("Could not parse object '%s'."), sha1_to_hex(index
));
2082 if (fast_forward_to(index_tree
, remote_tree
, 0))
2085 if (merge_tree(remote_tree
))
2088 remove_branch_state();
2094 * Resets rerere's merge resolution metadata.
2096 static void am_rerere_clear(void)
2098 struct string_list merge_rr
= STRING_LIST_INIT_DUP
;
2099 rerere_clear(&merge_rr
);
2100 string_list_clear(&merge_rr
, 1);
2104 * Resume the current am session by skipping the current patch.
2106 static void am_skip(struct am_state
*state
)
2108 unsigned char head
[GIT_SHA1_RAWSZ
];
2112 if (get_sha1("HEAD", head
))
2113 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
2115 if (clean_index(head
, head
))
2116 die(_("failed to clean index"));
2124 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2126 * It is not safe to reset HEAD when:
2127 * 1. git-am previously failed because the index was dirty.
2128 * 2. HEAD has moved since git-am previously failed.
2130 static int safe_to_abort(const struct am_state
*state
)
2132 struct strbuf sb
= STRBUF_INIT
;
2133 unsigned char abort_safety
[GIT_SHA1_RAWSZ
], head
[GIT_SHA1_RAWSZ
];
2135 if (file_exists(am_path(state
, "dirtyindex")))
2138 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
2139 if (get_sha1_hex(sb
.buf
, abort_safety
))
2140 die(_("could not parse %s"), am_path(state
, "abort_safety"));
2142 hashclr(abort_safety
);
2144 if (get_sha1("HEAD", head
))
2147 if (!hashcmp(head
, abort_safety
))
2150 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2151 "Not rewinding to ORIG_HEAD"));
2157 * Aborts the current am session if it is safe to do so.
2159 static void am_abort(struct am_state
*state
)
2161 unsigned char curr_head
[GIT_SHA1_RAWSZ
], orig_head
[GIT_SHA1_RAWSZ
];
2162 int has_curr_head
, has_orig_head
;
2165 if (!safe_to_abort(state
)) {
2172 curr_branch
= resolve_refdup("HEAD", 0, curr_head
, NULL
);
2173 has_curr_head
= !is_null_sha1(curr_head
);
2175 hashcpy(curr_head
, EMPTY_TREE_SHA1_BIN
);
2177 has_orig_head
= !get_sha1("ORIG_HEAD", orig_head
);
2179 hashcpy(orig_head
, EMPTY_TREE_SHA1_BIN
);
2181 clean_index(curr_head
, orig_head
);
2184 update_ref("am --abort", "HEAD", orig_head
,
2185 has_curr_head
? curr_head
: NULL
, 0,
2186 UPDATE_REFS_DIE_ON_ERR
);
2187 else if (curr_branch
)
2188 delete_ref(curr_branch
, NULL
, REF_NODEREF
);
2195 * parse_options() callback that validates and sets opt->value to the
2196 * PATCH_FORMAT_* enum value corresponding to `arg`.
2198 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
2200 int *opt_value
= opt
->value
;
2202 if (!strcmp(arg
, "mbox"))
2203 *opt_value
= PATCH_FORMAT_MBOX
;
2204 else if (!strcmp(arg
, "stgit"))
2205 *opt_value
= PATCH_FORMAT_STGIT
;
2206 else if (!strcmp(arg
, "stgit-series"))
2207 *opt_value
= PATCH_FORMAT_STGIT_SERIES
;
2208 else if (!strcmp(arg
, "hg"))
2209 *opt_value
= PATCH_FORMAT_HG
;
2210 else if (!strcmp(arg
, "mboxrd"))
2211 *opt_value
= PATCH_FORMAT_MBOXRD
;
2213 return error(_("Invalid value for --patch-format: %s"), arg
);
2225 static int git_am_config(const char *k
, const char *v
, void *cb
)
2229 status
= git_gpg_config(k
, v
, NULL
);
2233 return git_default_config(k
, v
, NULL
);
2236 int cmd_am(int argc
, const char **argv
, const char *prefix
)
2238 struct am_state state
;
2241 int patch_format
= PATCH_FORMAT_UNKNOWN
;
2242 enum resume_mode resume
= RESUME_FALSE
;
2245 const char * const usage
[] = {
2246 N_("git am [<options>] [(<mbox>|<Maildir>)...]"),
2247 N_("git am [<options>] (--continue | --skip | --abort)"),
2251 struct option options
[] = {
2252 OPT_BOOL('i', "interactive", &state
.interactive
,
2253 N_("run interactively")),
2254 OPT_HIDDEN_BOOL('b', "binary", &binary
,
2255 N_("historical option -- no-op")),
2256 OPT_BOOL('3', "3way", &state
.threeway
,
2257 N_("allow fall back on 3way merging if needed")),
2258 OPT__QUIET(&state
.quiet
, N_("be quiet")),
2259 OPT_SET_INT('s', "signoff", &state
.signoff
,
2260 N_("add a Signed-off-by line to the commit message"),
2262 OPT_BOOL('u', "utf8", &state
.utf8
,
2263 N_("recode into utf8 (default)")),
2264 OPT_SET_INT('k', "keep", &state
.keep
,
2265 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
2266 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
2267 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
2268 OPT_BOOL('m', "message-id", &state
.message_id
,
2269 N_("pass -m flag to git-mailinfo")),
2270 { OPTION_SET_INT
, 0, "keep-cr", &keep_cr
, NULL
,
2271 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2272 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 1},
2273 { OPTION_SET_INT
, 0, "no-keep-cr", &keep_cr
, NULL
,
2274 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2275 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 0},
2276 OPT_BOOL('c', "scissors", &state
.scissors
,
2277 N_("strip everything before a scissors line")),
2278 OPT_PASSTHRU_ARGV(0, "whitespace", &state
.git_apply_opts
, N_("action"),
2279 N_("pass it through git-apply"),
2281 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state
.git_apply_opts
, NULL
,
2282 N_("pass it through git-apply"),
2284 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state
.git_apply_opts
, NULL
,
2285 N_("pass it through git-apply"),
2287 OPT_PASSTHRU_ARGV(0, "directory", &state
.git_apply_opts
, N_("root"),
2288 N_("pass it through git-apply"),
2290 OPT_PASSTHRU_ARGV(0, "exclude", &state
.git_apply_opts
, N_("path"),
2291 N_("pass it through git-apply"),
2293 OPT_PASSTHRU_ARGV(0, "include", &state
.git_apply_opts
, N_("path"),
2294 N_("pass it through git-apply"),
2296 OPT_PASSTHRU_ARGV('C', NULL
, &state
.git_apply_opts
, N_("n"),
2297 N_("pass it through git-apply"),
2299 OPT_PASSTHRU_ARGV('p', NULL
, &state
.git_apply_opts
, N_("num"),
2300 N_("pass it through git-apply"),
2302 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
2303 N_("format the patch(es) are in"),
2304 parse_opt_patchformat
),
2305 OPT_PASSTHRU_ARGV(0, "reject", &state
.git_apply_opts
, NULL
,
2306 N_("pass it through git-apply"),
2308 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
2309 N_("override error message when patch failure occurs")),
2310 OPT_CMDMODE(0, "continue", &resume
,
2311 N_("continue applying patches after resolving a conflict"),
2313 OPT_CMDMODE('r', "resolved", &resume
,
2314 N_("synonyms for --continue"),
2316 OPT_CMDMODE(0, "skip", &resume
,
2317 N_("skip the current patch"),
2319 OPT_CMDMODE(0, "abort", &resume
,
2320 N_("restore the original branch and abort the patching operation."),
2322 OPT_BOOL(0, "committer-date-is-author-date",
2323 &state
.committer_date_is_author_date
,
2324 N_("lie about committer date")),
2325 OPT_BOOL(0, "ignore-date", &state
.ignore_date
,
2326 N_("use current timestamp for author date")),
2327 OPT_RERERE_AUTOUPDATE(&state
.allow_rerere_autoupdate
),
2328 { OPTION_STRING
, 'S', "gpg-sign", &state
.sign_commit
, N_("key-id"),
2329 N_("GPG-sign commits"),
2330 PARSE_OPT_OPTARG
, NULL
, (intptr_t) "" },
2331 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
2332 N_("(internal use for git-rebase)")),
2336 git_config(git_am_config
, NULL
);
2338 am_state_init(&state
, git_path("rebase-apply"));
2340 in_progress
= am_in_progress(&state
);
2344 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
2347 fprintf_ln(stderr
, _("The -b/--binary option has been a no-op for long time, and\n"
2348 "it will be removed. Please do not use it anymore."));
2350 /* Ensure a valid committer ident can be constructed */
2351 git_committer_info(IDENT_STRICT
);
2353 if (read_index_preload(&the_index
, NULL
) < 0)
2354 die(_("failed to read the index"));
2358 * Catch user error to feed us patches when there is a session
2361 * 1. mbox path(s) are provided on the command-line.
2362 * 2. stdin is not a tty: the user is trying to feed us a patch
2363 * from standard input. This is somewhat unreliable -- stdin
2364 * could be /dev/null for example and the caller did not
2365 * intend to feed us a patch but wanted to continue
2368 if (argc
|| (resume
== RESUME_FALSE
&& !isatty(0)))
2369 die(_("previous rebase directory %s still exists but mbox given."),
2372 if (resume
== RESUME_FALSE
)
2373 resume
= RESUME_APPLY
;
2375 if (state
.signoff
== SIGNOFF_EXPLICIT
)
2376 am_append_signoff(&state
);
2378 struct argv_array paths
= ARGV_ARRAY_INIT
;
2382 * Handle stray state directory in the independent-run case. In
2383 * the --rebasing case, it is up to the caller to take care of
2384 * stray directories.
2386 if (file_exists(state
.dir
) && !state
.rebasing
) {
2387 if (resume
== RESUME_ABORT
) {
2389 am_state_release(&state
);
2393 die(_("Stray %s directory found.\n"
2394 "Use \"git am --abort\" to remove it."),
2399 die(_("Resolve operation not in progress, we are not resuming."));
2401 for (i
= 0; i
< argc
; i
++) {
2402 if (is_absolute_path(argv
[i
]) || !prefix
)
2403 argv_array_push(&paths
, argv
[i
]);
2405 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
2408 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
2410 argv_array_clear(&paths
);
2420 case RESUME_RESOLVED
:
2430 die("BUG: invalid resume value");
2433 am_state_release(&state
);