4 * Based on git-am.sh by Junio C Hamano.
9 #include "parse-options.h"
11 #include "run-command.h"
14 #include "cache-tree.h"
19 #include "unpack-trees.h"
21 #include "sequencer.h"
23 #include "merge-recursive.h"
28 * Returns 1 if the file is empty or does not exist, 0 otherwise.
30 static int is_empty_file(const char *filename
)
34 if (stat(filename
, &st
) < 0) {
37 die_errno(_("could not stat %s"), filename
);
44 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
46 static int strbuf_getline_crlf(struct strbuf
*sb
, FILE *fp
)
48 if (strbuf_getwholeline(sb
, fp
, '\n'))
50 if (sb
->buf
[sb
->len
- 1] == '\n') {
51 strbuf_setlen(sb
, sb
->len
- 1);
52 if (sb
->len
> 0 && sb
->buf
[sb
->len
- 1] == '\r')
53 strbuf_setlen(sb
, sb
->len
- 1);
59 * Returns the length of the first line of msg.
61 static int linelen(const char *msg
)
63 return strchrnul(msg
, '\n') - msg
;
67 PATCH_FORMAT_UNKNOWN
= 0,
73 KEEP_TRUE
, /* pass -k flag to git-mailinfo */
74 KEEP_NON_PATCH
/* pass -b flag to git-mailinfo */
79 SCISSORS_FALSE
= 0, /* pass --no-scissors to git-mailinfo */
80 SCISSORS_TRUE
/* pass --scissors to git-mailinfo */
84 /* state directory path */
87 /* current and last patch numbers, 1-indexed */
91 /* commit metadata and message */
98 /* number of digits in patch filename */
101 /* various operating modes and command line options */
106 int keep
; /* enum keep_type */
108 int scissors
; /* enum scissors_type */
109 const char *resolvemsg
;
114 * Initializes am_state with the default values. The state directory is set to
117 static void am_state_init(struct am_state
*state
, const char *dir
)
119 memset(state
, 0, sizeof(*state
));
122 state
->dir
= xstrdup(dir
);
128 git_config_get_bool("am.messageid", &state
->message_id
);
130 state
->scissors
= SCISSORS_UNSET
;
134 * Releases memory allocated by an am_state.
136 static void am_state_release(struct am_state
*state
)
139 free(state
->author_name
);
140 free(state
->author_email
);
141 free(state
->author_date
);
146 * Returns path relative to the am_state directory.
148 static inline const char *am_path(const struct am_state
*state
, const char *path
)
150 return mkpath("%s/%s", state
->dir
, path
);
154 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
157 static void say(const struct am_state
*state
, FILE *fp
, const char *fmt
, ...)
163 vfprintf(fp
, fmt
, ap
);
170 * Returns 1 if there is an am session in progress, 0 otherwise.
172 static int am_in_progress(const struct am_state
*state
)
176 if (lstat(state
->dir
, &st
) < 0 || !S_ISDIR(st
.st_mode
))
178 if (lstat(am_path(state
, "last"), &st
) || !S_ISREG(st
.st_mode
))
180 if (lstat(am_path(state
, "next"), &st
) || !S_ISREG(st
.st_mode
))
186 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
187 * number of bytes read on success, -1 if the file does not exist. If `trim` is
188 * set, trailing whitespace will be removed.
190 static int read_state_file(struct strbuf
*sb
, const struct am_state
*state
,
191 const char *file
, int trim
)
195 if (strbuf_read_file(sb
, am_path(state
, file
), 0) >= 0) {
205 die_errno(_("could not read '%s'"), am_path(state
, file
));
209 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
210 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
211 * match `key`. Returns NULL on failure.
213 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
216 static char *read_shell_var(FILE *fp
, const char *key
)
218 struct strbuf sb
= STRBUF_INIT
;
221 if (strbuf_getline(&sb
, fp
, '\n'))
224 if (!skip_prefix(sb
.buf
, key
, &str
))
227 if (!skip_prefix(str
, "=", &str
))
230 strbuf_remove(&sb
, 0, str
- sb
.buf
);
232 str
= sq_dequote(sb
.buf
);
236 return strbuf_detach(&sb
, NULL
);
244 * Reads and parses the state directory's "author-script" file, and sets
245 * state->author_name, state->author_email and state->author_date accordingly.
246 * Returns 0 on success, -1 if the file could not be parsed.
248 * The author script is of the format:
250 * GIT_AUTHOR_NAME='$author_name'
251 * GIT_AUTHOR_EMAIL='$author_email'
252 * GIT_AUTHOR_DATE='$author_date'
254 * where $author_name, $author_email and $author_date are quoted. We are strict
255 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
256 * script, and thus if the file differs from what this function expects, it is
257 * better to bail out than to do something that the user does not expect.
259 static int read_author_script(struct am_state
*state
)
261 const char *filename
= am_path(state
, "author-script");
264 assert(!state
->author_name
);
265 assert(!state
->author_email
);
266 assert(!state
->author_date
);
268 fp
= fopen(filename
, "r");
272 die_errno(_("could not open '%s' for reading"), filename
);
275 state
->author_name
= read_shell_var(fp
, "GIT_AUTHOR_NAME");
276 if (!state
->author_name
) {
281 state
->author_email
= read_shell_var(fp
, "GIT_AUTHOR_EMAIL");
282 if (!state
->author_email
) {
287 state
->author_date
= read_shell_var(fp
, "GIT_AUTHOR_DATE");
288 if (!state
->author_date
) {
293 if (fgetc(fp
) != EOF
) {
303 * Saves state->author_name, state->author_email and state->author_date in the
304 * state directory's "author-script" file.
306 static void write_author_script(const struct am_state
*state
)
308 struct strbuf sb
= STRBUF_INIT
;
310 strbuf_addstr(&sb
, "GIT_AUTHOR_NAME=");
311 sq_quote_buf(&sb
, state
->author_name
);
312 strbuf_addch(&sb
, '\n');
314 strbuf_addstr(&sb
, "GIT_AUTHOR_EMAIL=");
315 sq_quote_buf(&sb
, state
->author_email
);
316 strbuf_addch(&sb
, '\n');
318 strbuf_addstr(&sb
, "GIT_AUTHOR_DATE=");
319 sq_quote_buf(&sb
, state
->author_date
);
320 strbuf_addch(&sb
, '\n');
322 write_file(am_path(state
, "author-script"), 1, "%s", sb
.buf
);
328 * Reads the commit message from the state directory's "final-commit" file,
329 * setting state->msg to its contents and state->msg_len to the length of its
332 * Returns 0 on success, -1 if the file does not exist.
334 static int read_commit_msg(struct am_state
*state
)
336 struct strbuf sb
= STRBUF_INIT
;
340 if (read_state_file(&sb
, state
, "final-commit", 0) < 0) {
345 state
->msg
= strbuf_detach(&sb
, &state
->msg_len
);
350 * Saves state->msg in the state directory's "final-commit" file.
352 static void write_commit_msg(const struct am_state
*state
)
355 const char *filename
= am_path(state
, "final-commit");
357 fd
= xopen(filename
, O_WRONLY
| O_CREAT
, 0666);
358 if (write_in_full(fd
, state
->msg
, state
->msg_len
) < 0)
359 die_errno(_("could not write to %s"), filename
);
364 * Loads state from disk.
366 static void am_load(struct am_state
*state
)
368 struct strbuf sb
= STRBUF_INIT
;
370 if (read_state_file(&sb
, state
, "next", 1) < 0)
371 die("BUG: state file 'next' does not exist");
372 state
->cur
= strtol(sb
.buf
, NULL
, 10);
374 if (read_state_file(&sb
, state
, "last", 1) < 0)
375 die("BUG: state file 'last' does not exist");
376 state
->last
= strtol(sb
.buf
, NULL
, 10);
378 if (read_author_script(state
) < 0)
379 die(_("could not parse author script"));
381 read_commit_msg(state
);
383 read_state_file(&sb
, state
, "threeway", 1);
384 state
->threeway
= !strcmp(sb
.buf
, "t");
386 read_state_file(&sb
, state
, "quiet", 1);
387 state
->quiet
= !strcmp(sb
.buf
, "t");
389 read_state_file(&sb
, state
, "sign", 1);
390 state
->signoff
= !strcmp(sb
.buf
, "t");
392 read_state_file(&sb
, state
, "utf8", 1);
393 state
->utf8
= !strcmp(sb
.buf
, "t");
395 read_state_file(&sb
, state
, "keep", 1);
396 if (!strcmp(sb
.buf
, "t"))
397 state
->keep
= KEEP_TRUE
;
398 else if (!strcmp(sb
.buf
, "b"))
399 state
->keep
= KEEP_NON_PATCH
;
401 state
->keep
= KEEP_FALSE
;
403 read_state_file(&sb
, state
, "messageid", 1);
404 state
->message_id
= !strcmp(sb
.buf
, "t");
406 read_state_file(&sb
, state
, "scissors", 1);
407 if (!strcmp(sb
.buf
, "t"))
408 state
->scissors
= SCISSORS_TRUE
;
409 else if (!strcmp(sb
.buf
, "f"))
410 state
->scissors
= SCISSORS_FALSE
;
412 state
->scissors
= SCISSORS_UNSET
;
414 state
->rebasing
= !!file_exists(am_path(state
, "rebasing"));
420 * Removes the am_state directory, forcefully terminating the current am
423 static void am_destroy(const struct am_state
*state
)
425 struct strbuf sb
= STRBUF_INIT
;
427 strbuf_addstr(&sb
, state
->dir
);
428 remove_dir_recursively(&sb
, 0);
433 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
434 * non-indented lines and checking if they look like they begin with valid
435 * header field names.
437 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
439 static int is_mail(FILE *fp
)
441 const char *header_regex
= "^[!-9;-~]+:";
442 struct strbuf sb
= STRBUF_INIT
;
446 if (fseek(fp
, 0L, SEEK_SET
))
447 die_errno(_("fseek failed"));
449 if (regcomp(®ex
, header_regex
, REG_NOSUB
| REG_EXTENDED
))
450 die("invalid pattern: %s", header_regex
);
452 while (!strbuf_getline_crlf(&sb
, fp
)) {
454 break; /* End of header */
456 /* Ignore indented folded lines */
457 if (*sb
.buf
== '\t' || *sb
.buf
== ' ')
460 /* It's a header if it matches header_regex */
461 if (regexec(®ex
, sb
.buf
, 0, NULL
, 0)) {
474 * Attempts to detect the patch_format of the patches contained in `paths`,
475 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
478 static int detect_patch_format(const char **paths
)
480 enum patch_format ret
= PATCH_FORMAT_UNKNOWN
;
481 struct strbuf l1
= STRBUF_INIT
;
485 * We default to mbox format if input is from stdin and for directories
487 if (!*paths
|| !strcmp(*paths
, "-") || is_directory(*paths
))
488 return PATCH_FORMAT_MBOX
;
491 * Otherwise, check the first few lines of the first patch, starting
492 * from the first non-blank line, to try to detect its format.
495 fp
= xfopen(*paths
, "r");
497 while (!strbuf_getline_crlf(&l1
, fp
)) {
502 if (starts_with(l1
.buf
, "From ") || starts_with(l1
.buf
, "From: ")) {
503 ret
= PATCH_FORMAT_MBOX
;
507 if (l1
.len
&& is_mail(fp
)) {
508 ret
= PATCH_FORMAT_MBOX
;
519 * Splits out individual email patches from `paths`, where each path is either
520 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
522 static int split_mail_mbox(struct am_state
*state
, const char **paths
, int keep_cr
)
524 struct child_process cp
= CHILD_PROCESS_INIT
;
525 struct strbuf last
= STRBUF_INIT
;
528 argv_array_push(&cp
.args
, "mailsplit");
529 argv_array_pushf(&cp
.args
, "-d%d", state
->prec
);
530 argv_array_pushf(&cp
.args
, "-o%s", state
->dir
);
531 argv_array_push(&cp
.args
, "-b");
533 argv_array_push(&cp
.args
, "--keep-cr");
534 argv_array_push(&cp
.args
, "--");
535 argv_array_pushv(&cp
.args
, paths
);
537 if (capture_command(&cp
, &last
, 8))
541 state
->last
= strtol(last
.buf
, NULL
, 10);
547 * Splits a list of files/directories into individual email patches. Each path
548 * in `paths` must be a file/directory that is formatted according to
551 * Once split out, the individual email patches will be stored in the state
552 * directory, with each patch's filename being its index, padded to state->prec
555 * state->cur will be set to the index of the first mail, and state->last will
556 * be set to the index of the last mail.
558 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
559 * to disable this behavior, -1 to use the default configured setting.
561 * Returns 0 on success, -1 on failure.
563 static int split_mail(struct am_state
*state
, enum patch_format patch_format
,
564 const char **paths
, int keep_cr
)
568 git_config_get_bool("am.keepcr", &keep_cr
);
571 switch (patch_format
) {
572 case PATCH_FORMAT_MBOX
:
573 return split_mail_mbox(state
, paths
, keep_cr
);
575 die("BUG: invalid patch_format");
581 * Setup a new am session for applying patches
583 static void am_setup(struct am_state
*state
, enum patch_format patch_format
,
584 const char **paths
, int keep_cr
)
586 unsigned char curr_head
[GIT_SHA1_RAWSZ
];
590 patch_format
= detect_patch_format(paths
);
593 fprintf_ln(stderr
, _("Patch format detection failed."));
597 if (mkdir(state
->dir
, 0777) < 0 && errno
!= EEXIST
)
598 die_errno(_("failed to create directory '%s'"), state
->dir
);
600 if (split_mail(state
, patch_format
, paths
, keep_cr
) < 0) {
602 die(_("Failed to split patches."));
608 write_file(am_path(state
, "threeway"), 1, state
->threeway
? "t" : "f");
610 write_file(am_path(state
, "quiet"), 1, state
->quiet
? "t" : "f");
612 write_file(am_path(state
, "sign"), 1, state
->signoff
? "t" : "f");
614 write_file(am_path(state
, "utf8"), 1, state
->utf8
? "t" : "f");
616 switch (state
->keep
) {
627 die("BUG: invalid value for state->keep");
630 write_file(am_path(state
, "keep"), 1, "%s", str
);
632 write_file(am_path(state
, "messageid"), 1, state
->message_id
? "t" : "f");
634 switch (state
->scissors
) {
645 die("BUG: invalid value for state->scissors");
648 write_file(am_path(state
, "scissors"), 1, "%s", str
);
651 write_file(am_path(state
, "rebasing"), 1, "%s", "");
653 write_file(am_path(state
, "applying"), 1, "%s", "");
655 if (!get_sha1("HEAD", curr_head
)) {
656 write_file(am_path(state
, "abort-safety"), 1, "%s", sha1_to_hex(curr_head
));
657 if (!state
->rebasing
)
658 update_ref("am", "ORIG_HEAD", curr_head
, NULL
, 0,
659 UPDATE_REFS_DIE_ON_ERR
);
661 write_file(am_path(state
, "abort-safety"), 1, "%s", "");
662 if (!state
->rebasing
)
663 delete_ref("ORIG_HEAD", NULL
, 0);
667 * NOTE: Since the "next" and "last" files determine if an am_state
668 * session is in progress, they should be written last.
671 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
673 write_file(am_path(state
, "last"), 1, "%d", state
->last
);
677 * Increments the patch pointer, and cleans am_state for the application of the
680 static void am_next(struct am_state
*state
)
682 unsigned char head
[GIT_SHA1_RAWSZ
];
684 free(state
->author_name
);
685 state
->author_name
= NULL
;
687 free(state
->author_email
);
688 state
->author_email
= NULL
;
690 free(state
->author_date
);
691 state
->author_date
= NULL
;
697 unlink(am_path(state
, "author-script"));
698 unlink(am_path(state
, "final-commit"));
700 if (!get_sha1("HEAD", head
))
701 write_file(am_path(state
, "abort-safety"), 1, "%s", sha1_to_hex(head
));
703 write_file(am_path(state
, "abort-safety"), 1, "%s", "");
706 write_file(am_path(state
, "next"), 1, "%d", state
->cur
);
710 * Returns the filename of the current patch email.
712 static const char *msgnum(const struct am_state
*state
)
714 static struct strbuf sb
= STRBUF_INIT
;
717 strbuf_addf(&sb
, "%0*d", state
->prec
, state
->cur
);
723 * Refresh and write index.
725 static void refresh_and_write_cache(void)
727 struct lock_file
*lock_file
= xcalloc(1, sizeof(struct lock_file
));
729 hold_locked_index(lock_file
, 1);
730 refresh_cache(REFRESH_QUIET
);
731 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
732 die(_("unable to write index file"));
736 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
737 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
738 * strbuf is provided, the space-separated list of files that differ will be
741 static int index_has_changes(struct strbuf
*sb
)
743 unsigned char head
[GIT_SHA1_RAWSZ
];
746 if (!get_sha1_tree("HEAD", head
)) {
747 struct diff_options opt
;
750 DIFF_OPT_SET(&opt
, EXIT_WITH_STATUS
);
752 DIFF_OPT_SET(&opt
, QUICK
);
753 do_diff_cache(head
, &opt
);
755 for (i
= 0; sb
&& i
< diff_queued_diff
.nr
; i
++) {
757 strbuf_addch(sb
, ' ');
758 strbuf_addstr(sb
, diff_queued_diff
.queue
[i
]->two
->path
);
761 return DIFF_OPT_TST(&opt
, HAS_CHANGES
) != 0;
763 for (i
= 0; sb
&& i
< active_nr
; i
++) {
765 strbuf_addch(sb
, ' ');
766 strbuf_addstr(sb
, active_cache
[i
]->name
);
773 * Dies with a user-friendly message on how to proceed after resolving the
774 * problem. This message can be overridden with state->resolvemsg.
776 static void NORETURN
die_user_resolve(const struct am_state
*state
)
778 if (state
->resolvemsg
) {
779 printf_ln("%s", state
->resolvemsg
);
781 const char *cmdline
= "git am";
783 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline
);
784 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline
);
785 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline
);
792 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
793 * state->msg will be set to the patch message. state->author_name,
794 * state->author_email and state->author_date will be set to the patch author's
795 * name, email and date respectively. The patch body will be written to the
796 * state directory's "patch" file.
798 * Returns 1 if the patch should be skipped, 0 otherwise.
800 static int parse_mail(struct am_state
*state
, const char *mail
)
803 struct child_process cp
= CHILD_PROCESS_INIT
;
804 struct strbuf sb
= STRBUF_INIT
;
805 struct strbuf msg
= STRBUF_INIT
;
806 struct strbuf author_name
= STRBUF_INIT
;
807 struct strbuf author_date
= STRBUF_INIT
;
808 struct strbuf author_email
= STRBUF_INIT
;
812 cp
.in
= xopen(mail
, O_RDONLY
, 0);
813 cp
.out
= xopen(am_path(state
, "info"), O_WRONLY
| O_CREAT
, 0777);
815 argv_array_push(&cp
.args
, "mailinfo");
816 argv_array_push(&cp
.args
, state
->utf8
? "-u" : "-n");
818 switch (state
->keep
) {
822 argv_array_push(&cp
.args
, "-k");
825 argv_array_push(&cp
.args
, "-b");
828 die("BUG: invalid value for state->keep");
831 if (state
->message_id
)
832 argv_array_push(&cp
.args
, "-m");
834 switch (state
->scissors
) {
838 argv_array_push(&cp
.args
, "--no-scissors");
841 argv_array_push(&cp
.args
, "--scissors");
844 die("BUG: invalid value for state->scissors");
847 argv_array_push(&cp
.args
, am_path(state
, "msg"));
848 argv_array_push(&cp
.args
, am_path(state
, "patch"));
850 if (run_command(&cp
) < 0)
851 die("could not parse patch");
856 /* Extract message and author information */
857 fp
= xfopen(am_path(state
, "info"), "r");
858 while (!strbuf_getline(&sb
, fp
, '\n')) {
861 if (skip_prefix(sb
.buf
, "Subject: ", &x
)) {
863 strbuf_addch(&msg
, '\n');
864 strbuf_addstr(&msg
, x
);
865 } else if (skip_prefix(sb
.buf
, "Author: ", &x
))
866 strbuf_addstr(&author_name
, x
);
867 else if (skip_prefix(sb
.buf
, "Email: ", &x
))
868 strbuf_addstr(&author_email
, x
);
869 else if (skip_prefix(sb
.buf
, "Date: ", &x
))
870 strbuf_addstr(&author_date
, x
);
874 /* Skip pine's internal folder data */
875 if (!strcmp(author_name
.buf
, "Mail System Internal Data")) {
880 if (is_empty_file(am_path(state
, "patch"))) {
881 printf_ln(_("Patch is empty. Was it split wrong?"));
882 die_user_resolve(state
);
885 strbuf_addstr(&msg
, "\n\n");
886 if (strbuf_read_file(&msg
, am_path(state
, "msg"), 0) < 0)
887 die_errno(_("could not read '%s'"), am_path(state
, "msg"));
891 append_signoff(&msg
, 0, 0);
893 assert(!state
->author_name
);
894 state
->author_name
= strbuf_detach(&author_name
, NULL
);
896 assert(!state
->author_email
);
897 state
->author_email
= strbuf_detach(&author_email
, NULL
);
899 assert(!state
->author_date
);
900 state
->author_date
= strbuf_detach(&author_date
, NULL
);
903 state
->msg
= strbuf_detach(&msg
, &state
->msg_len
);
906 strbuf_release(&msg
);
907 strbuf_release(&author_date
);
908 strbuf_release(&author_email
);
909 strbuf_release(&author_name
);
915 * Sets commit_id to the commit hash where the mail was generated from.
916 * Returns 0 on success, -1 on failure.
918 static int get_mail_commit_sha1(unsigned char *commit_id
, const char *mail
)
920 struct strbuf sb
= STRBUF_INIT
;
921 FILE *fp
= xfopen(mail
, "r");
924 if (strbuf_getline(&sb
, fp
, '\n'))
927 if (!skip_prefix(sb
.buf
, "From ", &x
))
930 if (get_sha1_hex(x
, commit_id
) < 0)
939 * Sets state->msg, state->author_name, state->author_email, state->author_date
940 * to the commit's respective info.
942 static void get_commit_info(struct am_state
*state
, struct commit
*commit
)
944 const char *buffer
, *ident_line
, *author_date
, *msg
;
946 struct ident_split ident_split
;
947 struct strbuf sb
= STRBUF_INIT
;
949 buffer
= logmsg_reencode(commit
, NULL
, get_commit_output_encoding());
951 ident_line
= find_commit_header(buffer
, "author", &ident_len
);
953 if (split_ident_line(&ident_split
, ident_line
, ident_len
) < 0) {
954 strbuf_add(&sb
, ident_line
, ident_len
);
955 die(_("invalid ident line: %s"), sb
.buf
);
958 assert(!state
->author_name
);
959 if (ident_split
.name_begin
) {
960 strbuf_add(&sb
, ident_split
.name_begin
,
961 ident_split
.name_end
- ident_split
.name_begin
);
962 state
->author_name
= strbuf_detach(&sb
, NULL
);
964 state
->author_name
= xstrdup("");
966 assert(!state
->author_email
);
967 if (ident_split
.mail_begin
) {
968 strbuf_add(&sb
, ident_split
.mail_begin
,
969 ident_split
.mail_end
- ident_split
.mail_begin
);
970 state
->author_email
= strbuf_detach(&sb
, NULL
);
972 state
->author_email
= xstrdup("");
974 author_date
= show_ident_date(&ident_split
, DATE_MODE(NORMAL
));
975 strbuf_addstr(&sb
, author_date
);
976 assert(!state
->author_date
);
977 state
->author_date
= strbuf_detach(&sb
, NULL
);
980 msg
= strstr(buffer
, "\n\n");
982 die(_("unable to parse commit %s"), sha1_to_hex(commit
->object
.sha1
));
983 state
->msg
= xstrdup(msg
+ 2);
984 state
->msg_len
= strlen(state
->msg
);
988 * Writes `commit` as a patch to the state directory's "patch" file.
990 static void write_commit_patch(const struct am_state
*state
, struct commit
*commit
)
992 struct rev_info rev_info
;
995 fp
= xfopen(am_path(state
, "patch"), "w");
996 init_revisions(&rev_info
, NULL
);
999 rev_info
.disable_stdin
= 1;
1000 rev_info
.show_root_diff
= 1;
1001 rev_info
.diffopt
.output_format
= DIFF_FORMAT_PATCH
;
1002 rev_info
.no_commit_id
= 1;
1003 DIFF_OPT_SET(&rev_info
.diffopt
, BINARY
);
1004 DIFF_OPT_SET(&rev_info
.diffopt
, FULL_INDEX
);
1005 rev_info
.diffopt
.use_color
= 0;
1006 rev_info
.diffopt
.file
= fp
;
1007 rev_info
.diffopt
.close_file
= 1;
1008 add_pending_object(&rev_info
, &commit
->object
, "");
1009 diff_setup_done(&rev_info
.diffopt
);
1010 log_tree_commit(&rev_info
, commit
);
1014 * Like parse_mail(), but parses the mail by looking up its commit ID
1015 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1018 * Will always return 0 as the patch should never be skipped.
1020 static int parse_mail_rebase(struct am_state
*state
, const char *mail
)
1022 struct commit
*commit
;
1023 unsigned char commit_sha1
[GIT_SHA1_RAWSZ
];
1025 if (get_mail_commit_sha1(commit_sha1
, mail
) < 0)
1026 die(_("could not parse %s"), mail
);
1028 commit
= lookup_commit_or_die(commit_sha1
, mail
);
1030 get_commit_info(state
, commit
);
1032 write_commit_patch(state
, commit
);
1038 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1039 * `index_file` is not NULL, the patch will be applied to that index.
1041 static int run_apply(const struct am_state
*state
, const char *index_file
)
1043 struct child_process cp
= CHILD_PROCESS_INIT
;
1048 argv_array_pushf(&cp
.env_array
, "GIT_INDEX_FILE=%s", index_file
);
1051 * If we are allowed to fall back on 3-way merge, don't give false
1052 * errors during the initial attempt.
1054 if (state
->threeway
&& !index_file
) {
1059 argv_array_push(&cp
.args
, "apply");
1062 argv_array_push(&cp
.args
, "--cached");
1064 argv_array_push(&cp
.args
, "--index");
1066 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1068 if (run_command(&cp
))
1071 /* Reload index as git-apply will have modified it. */
1073 read_cache_from(index_file
? index_file
: get_index_file());
1079 * Builds an index that contains just the blobs needed for a 3way merge.
1081 static int build_fake_ancestor(const struct am_state
*state
, const char *index_file
)
1083 struct child_process cp
= CHILD_PROCESS_INIT
;
1086 argv_array_push(&cp
.args
, "apply");
1087 argv_array_pushf(&cp
.args
, "--build-fake-ancestor=%s", index_file
);
1088 argv_array_push(&cp
.args
, am_path(state
, "patch"));
1090 if (run_command(&cp
))
1097 * Attempt a threeway merge, using index_path as the temporary index.
1099 static int fall_back_threeway(const struct am_state
*state
, const char *index_path
)
1101 unsigned char orig_tree
[GIT_SHA1_RAWSZ
], his_tree
[GIT_SHA1_RAWSZ
],
1102 our_tree
[GIT_SHA1_RAWSZ
];
1103 const unsigned char *bases
[1] = {orig_tree
};
1104 struct merge_options o
;
1105 struct commit
*result
;
1106 char *his_tree_name
;
1108 if (get_sha1("HEAD", our_tree
) < 0)
1109 hashcpy(our_tree
, EMPTY_TREE_SHA1_BIN
);
1111 if (build_fake_ancestor(state
, index_path
))
1112 return error("could not build fake ancestor");
1115 read_cache_from(index_path
);
1117 if (write_index_as_tree(orig_tree
, &the_index
, index_path
, 0, NULL
))
1118 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1120 say(state
, stdout
, _("Using index info to reconstruct a base tree..."));
1122 if (!state
->quiet
) {
1124 * List paths that needed 3-way fallback, so that the user can
1125 * review them with extra care to spot mismerges.
1127 struct rev_info rev_info
;
1128 const char *diff_filter_str
= "--diff-filter=AM";
1130 init_revisions(&rev_info
, NULL
);
1131 rev_info
.diffopt
.output_format
= DIFF_FORMAT_NAME_STATUS
;
1132 diff_opt_parse(&rev_info
.diffopt
, &diff_filter_str
, 1);
1133 add_pending_sha1(&rev_info
, "HEAD", our_tree
, 0);
1134 diff_setup_done(&rev_info
.diffopt
);
1135 run_diff_index(&rev_info
, 1);
1138 if (run_apply(state
, index_path
))
1139 return error(_("Did you hand edit your patch?\n"
1140 "It does not apply to blobs recorded in its index."));
1142 if (write_index_as_tree(his_tree
, &the_index
, index_path
, 0, NULL
))
1143 return error("could not write tree");
1145 say(state
, stdout
, _("Falling back to patching base and 3-way merge..."));
1151 * This is not so wrong. Depending on which base we picked, orig_tree
1152 * may be wildly different from ours, but his_tree has the same set of
1153 * wildly different changes in parts the patch did not touch, so
1154 * recursive ends up canceling them, saying that we reverted all those
1158 init_merge_options(&o
);
1161 his_tree_name
= xstrfmt("%.*s", linelen(state
->msg
), state
->msg
);
1162 o
.branch2
= his_tree_name
;
1167 if (merge_recursive_generic(&o
, our_tree
, his_tree
, 1, bases
, &result
)) {
1168 free(his_tree_name
);
1169 return error(_("Failed to merge in the changes."));
1172 free(his_tree_name
);
1177 * Commits the current index with state->msg as the commit message and
1178 * state->author_name, state->author_email and state->author_date as the author
1181 static void do_commit(const struct am_state
*state
)
1183 unsigned char tree
[GIT_SHA1_RAWSZ
], parent
[GIT_SHA1_RAWSZ
],
1184 commit
[GIT_SHA1_RAWSZ
];
1186 struct commit_list
*parents
= NULL
;
1187 const char *reflog_msg
, *author
;
1188 struct strbuf sb
= STRBUF_INIT
;
1190 if (write_cache_as_tree(tree
, 0, NULL
))
1191 die(_("git write-tree failed to write a tree"));
1193 if (!get_sha1_commit("HEAD", parent
)) {
1195 commit_list_insert(lookup_commit(parent
), &parents
);
1198 say(state
, stderr
, _("applying to an empty history"));
1201 author
= fmt_ident(state
->author_name
, state
->author_email
,
1202 state
->author_date
, IDENT_STRICT
);
1204 if (commit_tree(state
->msg
, state
->msg_len
, tree
, parents
, commit
,
1206 die(_("failed to write commit object"));
1208 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1212 strbuf_addf(&sb
, "%s: %.*s", reflog_msg
, linelen(state
->msg
),
1215 update_ref(sb
.buf
, "HEAD", commit
, ptr
, 0, UPDATE_REFS_DIE_ON_ERR
);
1217 strbuf_release(&sb
);
1221 * Validates the am_state for resuming -- the "msg" and authorship fields must
1224 static void validate_resume_state(const struct am_state
*state
)
1227 die(_("cannot resume: %s does not exist."),
1228 am_path(state
, "final-commit"));
1230 if (!state
->author_name
|| !state
->author_email
|| !state
->author_date
)
1231 die(_("cannot resume: %s does not exist."),
1232 am_path(state
, "author-script"));
1236 * Applies all queued mail.
1238 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1239 * well as the state directory's "patch" file is used as-is for applying the
1240 * patch and committing it.
1242 static void am_run(struct am_state
*state
, int resume
)
1244 const char *argv_gc_auto
[] = {"gc", "--auto", NULL
};
1245 struct strbuf sb
= STRBUF_INIT
;
1247 unlink(am_path(state
, "dirtyindex"));
1249 refresh_and_write_cache();
1251 if (index_has_changes(&sb
)) {
1252 write_file(am_path(state
, "dirtyindex"), 1, "t");
1253 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb
.buf
);
1256 strbuf_release(&sb
);
1258 while (state
->cur
<= state
->last
) {
1259 const char *mail
= am_path(state
, msgnum(state
));
1262 if (!file_exists(mail
))
1266 validate_resume_state(state
);
1271 if (state
->rebasing
)
1272 skip
= parse_mail_rebase(state
, mail
);
1274 skip
= parse_mail(state
, mail
);
1277 goto next
; /* mail should be skipped */
1279 write_author_script(state
);
1280 write_commit_msg(state
);
1283 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1285 apply_status
= run_apply(state
, NULL
);
1287 if (apply_status
&& state
->threeway
) {
1288 struct strbuf sb
= STRBUF_INIT
;
1290 strbuf_addstr(&sb
, am_path(state
, "patch-merge-index"));
1291 apply_status
= fall_back_threeway(state
, sb
.buf
);
1292 strbuf_release(&sb
);
1295 * Applying the patch to an earlier tree and merging
1296 * the result may have produced the same tree as ours.
1298 if (!apply_status
&& !index_has_changes(NULL
)) {
1299 say(state
, stdout
, _("No changes -- Patch already applied."));
1305 int advice_amworkdir
= 1;
1307 printf_ln(_("Patch failed at %s %.*s"), msgnum(state
),
1308 linelen(state
->msg
), state
->msg
);
1310 git_config_get_bool("advice.amworkdir", &advice_amworkdir
);
1312 if (advice_amworkdir
)
1313 printf_ln(_("The copy of the patch that failed is found in: %s"),
1314 am_path(state
, "patch"));
1316 die_user_resolve(state
);
1326 * In rebasing mode, it's up to the caller to take care of
1329 if (!state
->rebasing
) {
1331 run_command_v_opt(argv_gc_auto
, RUN_GIT_CMD
);
1336 * Resume the current am session after patch application failure. The user did
1337 * all the hard work, and we do not have to do any patch application. Just
1338 * trust and commit what the user has in the index and working tree.
1340 static void am_resolve(struct am_state
*state
)
1342 validate_resume_state(state
);
1344 say(state
, stdout
, _("Applying: %.*s"), linelen(state
->msg
), state
->msg
);
1346 if (!index_has_changes(NULL
)) {
1347 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1348 "If there is nothing left to stage, chances are that something else\n"
1349 "already introduced the same changes; you might want to skip this patch."));
1350 die_user_resolve(state
);
1353 if (unmerged_cache()) {
1354 printf_ln(_("You still have unmerged paths in your index.\n"
1355 "Did you forget to use 'git add'?"));
1356 die_user_resolve(state
);
1366 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1367 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1370 static int fast_forward_to(struct tree
*head
, struct tree
*remote
, int reset
)
1372 struct lock_file
*lock_file
;
1373 struct unpack_trees_options opts
;
1374 struct tree_desc t
[2];
1376 if (parse_tree(head
) || parse_tree(remote
))
1379 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1380 hold_locked_index(lock_file
, 1);
1382 refresh_cache(REFRESH_QUIET
);
1384 memset(&opts
, 0, sizeof(opts
));
1386 opts
.src_index
= &the_index
;
1387 opts
.dst_index
= &the_index
;
1391 opts
.fn
= twoway_merge
;
1392 init_tree_desc(&t
[0], head
->buffer
, head
->size
);
1393 init_tree_desc(&t
[1], remote
->buffer
, remote
->size
);
1395 if (unpack_trees(2, t
, &opts
)) {
1396 rollback_lock_file(lock_file
);
1400 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1401 die(_("unable to write new index file"));
1407 * Clean the index without touching entries that are not modified between
1408 * `head` and `remote`.
1410 static int clean_index(const unsigned char *head
, const unsigned char *remote
)
1412 struct lock_file
*lock_file
;
1413 struct tree
*head_tree
, *remote_tree
, *index_tree
;
1414 unsigned char index
[GIT_SHA1_RAWSZ
];
1415 struct pathspec pathspec
;
1417 head_tree
= parse_tree_indirect(head
);
1419 return error(_("Could not parse object '%s'."), sha1_to_hex(head
));
1421 remote_tree
= parse_tree_indirect(remote
);
1423 return error(_("Could not parse object '%s'."), sha1_to_hex(remote
));
1425 read_cache_unmerged();
1427 if (fast_forward_to(head_tree
, head_tree
, 1))
1430 if (write_cache_as_tree(index
, 0, NULL
))
1433 index_tree
= parse_tree_indirect(index
);
1435 return error(_("Could not parse object '%s'."), sha1_to_hex(index
));
1437 if (fast_forward_to(index_tree
, remote_tree
, 0))
1440 memset(&pathspec
, 0, sizeof(pathspec
));
1442 lock_file
= xcalloc(1, sizeof(struct lock_file
));
1443 hold_locked_index(lock_file
, 1);
1445 if (read_tree(remote_tree
, 0, &pathspec
)) {
1446 rollback_lock_file(lock_file
);
1450 if (write_locked_index(&the_index
, lock_file
, COMMIT_LOCK
))
1451 die(_("unable to write new index file"));
1453 remove_branch_state();
1459 * Resume the current am session by skipping the current patch.
1461 static void am_skip(struct am_state
*state
)
1463 unsigned char head
[GIT_SHA1_RAWSZ
];
1465 if (get_sha1("HEAD", head
))
1466 hashcpy(head
, EMPTY_TREE_SHA1_BIN
);
1468 if (clean_index(head
, head
))
1469 die(_("failed to clean index"));
1476 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1478 * It is not safe to reset HEAD when:
1479 * 1. git-am previously failed because the index was dirty.
1480 * 2. HEAD has moved since git-am previously failed.
1482 static int safe_to_abort(const struct am_state
*state
)
1484 struct strbuf sb
= STRBUF_INIT
;
1485 unsigned char abort_safety
[GIT_SHA1_RAWSZ
], head
[GIT_SHA1_RAWSZ
];
1487 if (file_exists(am_path(state
, "dirtyindex")))
1490 if (read_state_file(&sb
, state
, "abort-safety", 1) > 0) {
1491 if (get_sha1_hex(sb
.buf
, abort_safety
))
1492 die(_("could not parse %s"), am_path(state
, "abort_safety"));
1494 hashclr(abort_safety
);
1496 if (get_sha1("HEAD", head
))
1499 if (!hashcmp(head
, abort_safety
))
1502 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1503 "Not rewinding to ORIG_HEAD"));
1509 * Aborts the current am session if it is safe to do so.
1511 static void am_abort(struct am_state
*state
)
1513 unsigned char curr_head
[GIT_SHA1_RAWSZ
], orig_head
[GIT_SHA1_RAWSZ
];
1514 int has_curr_head
, has_orig_head
;
1517 if (!safe_to_abort(state
)) {
1522 curr_branch
= resolve_refdup("HEAD", 0, curr_head
, NULL
);
1523 has_curr_head
= !is_null_sha1(curr_head
);
1525 hashcpy(curr_head
, EMPTY_TREE_SHA1_BIN
);
1527 has_orig_head
= !get_sha1("ORIG_HEAD", orig_head
);
1529 hashcpy(orig_head
, EMPTY_TREE_SHA1_BIN
);
1531 clean_index(curr_head
, orig_head
);
1534 update_ref("am --abort", "HEAD", orig_head
,
1535 has_curr_head
? curr_head
: NULL
, 0,
1536 UPDATE_REFS_DIE_ON_ERR
);
1537 else if (curr_branch
)
1538 delete_ref(curr_branch
, NULL
, REF_NODEREF
);
1545 * parse_options() callback that validates and sets opt->value to the
1546 * PATCH_FORMAT_* enum value corresponding to `arg`.
1548 static int parse_opt_patchformat(const struct option
*opt
, const char *arg
, int unset
)
1550 int *opt_value
= opt
->value
;
1552 if (!strcmp(arg
, "mbox"))
1553 *opt_value
= PATCH_FORMAT_MBOX
;
1555 return error(_("Invalid value for --patch-format: %s"), arg
);
1567 int cmd_am(int argc
, const char **argv
, const char *prefix
)
1569 struct am_state state
;
1571 int patch_format
= PATCH_FORMAT_UNKNOWN
;
1572 enum resume_mode resume
= RESUME_FALSE
;
1574 const char * const usage
[] = {
1575 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1576 N_("git am [options] (--continue | --skip | --abort)"),
1580 struct option options
[] = {
1581 OPT_BOOL('3', "3way", &state
.threeway
,
1582 N_("allow fall back on 3way merging if needed")),
1583 OPT__QUIET(&state
.quiet
, N_("be quiet")),
1584 OPT_BOOL('s', "signoff", &state
.signoff
,
1585 N_("add a Signed-off-by line to the commit message")),
1586 OPT_BOOL('u', "utf8", &state
.utf8
,
1587 N_("recode into utf8 (default)")),
1588 OPT_SET_INT('k', "keep", &state
.keep
,
1589 N_("pass -k flag to git-mailinfo"), KEEP_TRUE
),
1590 OPT_SET_INT(0, "keep-non-patch", &state
.keep
,
1591 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH
),
1592 OPT_BOOL('m', "message-id", &state
.message_id
,
1593 N_("pass -m flag to git-mailinfo")),
1594 { OPTION_SET_INT
, 0, "keep-cr", &keep_cr
, NULL
,
1595 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1596 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 1},
1597 { OPTION_SET_INT
, 0, "no-keep-cr", &keep_cr
, NULL
,
1598 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1599 PARSE_OPT_NOARG
| PARSE_OPT_NONEG
, NULL
, 0},
1600 OPT_BOOL('c', "scissors", &state
.scissors
,
1601 N_("strip everything before a scissors line")),
1602 OPT_CALLBACK(0, "patch-format", &patch_format
, N_("format"),
1603 N_("format the patch(es) are in"),
1604 parse_opt_patchformat
),
1605 OPT_STRING(0, "resolvemsg", &state
.resolvemsg
, NULL
,
1606 N_("override error message when patch failure occurs")),
1607 OPT_CMDMODE(0, "continue", &resume
,
1608 N_("continue applying patches after resolving a conflict"),
1610 OPT_CMDMODE('r', "resolved", &resume
,
1611 N_("synonyms for --continue"),
1613 OPT_CMDMODE(0, "skip", &resume
,
1614 N_("skip the current patch"),
1616 OPT_CMDMODE(0, "abort", &resume
,
1617 N_("restore the original branch and abort the patching operation."),
1619 OPT_HIDDEN_BOOL(0, "rebasing", &state
.rebasing
,
1620 N_("(internal use for git-rebase)")),
1625 * NEEDSWORK: Once all the features of git-am.sh have been
1626 * re-implemented in builtin/am.c, this preamble can be removed.
1628 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1629 const char *path
= mkpath("%s/git-am", git_exec_path());
1631 if (sane_execvp(path
, (char **)argv
) < 0)
1632 die_errno("could not exec %s", path
);
1634 prefix
= setup_git_directory();
1635 trace_repo_setup(prefix
);
1639 git_config(git_default_config
, NULL
);
1641 am_state_init(&state
, git_path("rebase-apply"));
1643 argc
= parse_options(argc
, argv
, prefix
, options
, usage
, 0);
1645 if (read_index_preload(&the_index
, NULL
) < 0)
1646 die(_("failed to read the index"));
1648 if (am_in_progress(&state
)) {
1650 * Catch user error to feed us patches when there is a session
1653 * 1. mbox path(s) are provided on the command-line.
1654 * 2. stdin is not a tty: the user is trying to feed us a patch
1655 * from standard input. This is somewhat unreliable -- stdin
1656 * could be /dev/null for example and the caller did not
1657 * intend to feed us a patch but wanted to continue
1660 if (argc
|| (resume
== RESUME_FALSE
&& !isatty(0)))
1661 die(_("previous rebase directory %s still exists but mbox given."),
1664 if (resume
== RESUME_FALSE
)
1665 resume
= RESUME_APPLY
;
1669 struct argv_array paths
= ARGV_ARRAY_INIT
;
1673 * Handle stray state directory in the independent-run case. In
1674 * the --rebasing case, it is up to the caller to take care of
1675 * stray directories.
1677 if (file_exists(state
.dir
) && !state
.rebasing
) {
1678 if (resume
== RESUME_ABORT
) {
1680 am_state_release(&state
);
1684 die(_("Stray %s directory found.\n"
1685 "Use \"git am --abort\" to remove it."),
1690 die(_("Resolve operation not in progress, we are not resuming."));
1692 for (i
= 0; i
< argc
; i
++) {
1693 if (is_absolute_path(argv
[i
]) || !prefix
)
1694 argv_array_push(&paths
, argv
[i
]);
1696 argv_array_push(&paths
, mkpath("%s/%s", prefix
, argv
[i
]));
1699 am_setup(&state
, patch_format
, paths
.argv
, keep_cr
);
1701 argv_array_clear(&paths
);
1711 case RESUME_RESOLVED
:
1721 die("BUG: invalid resume value");
1724 am_state_release(&state
);