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 struct argv_array git_apply_opts;
110 const char *resolvemsg;
111 int committer_date_is_author_date;
113 const char *sign_commit;
118 * Initializes am_state with the default values. The state directory is set to
121 static void am_state_init(struct am_state *state, const char *dir)
125 memset(state, 0, sizeof(*state));
128 state->dir = xstrdup(dir);
134 git_config_get_bool("am.messageid", &state->message_id);
136 state->scissors = SCISSORS_UNSET;
138 argv_array_init(&state->git_apply_opts);
140 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
141 state->sign_commit = gpgsign ? "" : NULL;
145 * Releases memory allocated by an am_state.
147 static void am_state_release(struct am_state *state)
150 free(state->author_name);
151 free(state->author_email);
152 free(state->author_date);
154 argv_array_clear(&state->git_apply_opts);
158 * Returns path relative to the am_state directory.
160 static inline const char *am_path(const struct am_state *state, const char *path)
162 return mkpath("%s/%s", state->dir, path);
166 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
169 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
175 vfprintf(fp, fmt, ap);
182 * Returns 1 if there is an am session in progress, 0 otherwise.
184 static int am_in_progress(const struct am_state *state)
188 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
190 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
192 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
198 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
199 * number of bytes read on success, -1 if the file does not exist. If `trim` is
200 * set, trailing whitespace will be removed.
202 static int read_state_file(struct strbuf *sb, const struct am_state *state,
203 const char *file, int trim)
207 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
217 die_errno(_("could not read '%s'"), am_path(state, file));
221 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
222 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
223 * match `key`. Returns NULL on failure.
225 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
228 static char *read_shell_var(FILE *fp, const char *key)
230 struct strbuf sb = STRBUF_INIT;
233 if (strbuf_getline(&sb, fp, '\n'))
236 if (!skip_prefix(sb.buf, key, &str))
239 if (!skip_prefix(str, "=", &str))
242 strbuf_remove(&sb, 0, str - sb.buf);
244 str = sq_dequote(sb.buf);
248 return strbuf_detach(&sb, NULL);
256 * Reads and parses the state directory's "author-script" file, and sets
257 * state->author_name, state->author_email and state->author_date accordingly.
258 * Returns 0 on success, -1 if the file could not be parsed.
260 * The author script is of the format:
262 * GIT_AUTHOR_NAME='$author_name'
263 * GIT_AUTHOR_EMAIL='$author_email'
264 * GIT_AUTHOR_DATE='$author_date'
266 * where $author_name, $author_email and $author_date are quoted. We are strict
267 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
268 * script, and thus if the file differs from what this function expects, it is
269 * better to bail out than to do something that the user does not expect.
271 static int read_author_script(struct am_state *state)
273 const char *filename = am_path(state, "author-script");
276 assert(!state->author_name);
277 assert(!state->author_email);
278 assert(!state->author_date);
280 fp = fopen(filename, "r");
284 die_errno(_("could not open '%s' for reading"), filename);
287 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
288 if (!state->author_name) {
293 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
294 if (!state->author_email) {
299 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
300 if (!state->author_date) {
305 if (fgetc(fp) != EOF) {
315 * Saves state->author_name, state->author_email and state->author_date in the
316 * state directory's "author-script" file.
318 static void write_author_script(const struct am_state *state)
320 struct strbuf sb = STRBUF_INIT;
322 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
323 sq_quote_buf(&sb, state->author_name);
324 strbuf_addch(&sb, '\n');
326 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
327 sq_quote_buf(&sb, state->author_email);
328 strbuf_addch(&sb, '\n');
330 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
331 sq_quote_buf(&sb, state->author_date);
332 strbuf_addch(&sb, '\n');
334 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
340 * Reads the commit message from the state directory's "final-commit" file,
341 * setting state->msg to its contents and state->msg_len to the length of its
344 * Returns 0 on success, -1 if the file does not exist.
346 static int read_commit_msg(struct am_state *state)
348 struct strbuf sb = STRBUF_INIT;
352 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
357 state->msg = strbuf_detach(&sb, &state->msg_len);
362 * Saves state->msg in the state directory's "final-commit" file.
364 static void write_commit_msg(const struct am_state *state)
367 const char *filename = am_path(state, "final-commit");
369 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
370 if (write_in_full(fd, state->msg, state->msg_len) < 0)
371 die_errno(_("could not write to %s"), filename);
376 * Loads state from disk.
378 static void am_load(struct am_state *state)
380 struct strbuf sb = STRBUF_INIT;
382 if (read_state_file(&sb, state, "next", 1) < 0)
383 die("BUG: state file 'next' does not exist");
384 state->cur = strtol(sb.buf, NULL, 10);
386 if (read_state_file(&sb, state, "last", 1) < 0)
387 die("BUG: state file 'last' does not exist");
388 state->last = strtol(sb.buf, NULL, 10);
390 if (read_author_script(state) < 0)
391 die(_("could not parse author script"));
393 read_commit_msg(state);
395 read_state_file(&sb, state, "threeway", 1);
396 state->threeway = !strcmp(sb.buf, "t");
398 read_state_file(&sb, state, "quiet", 1);
399 state->quiet = !strcmp(sb.buf, "t");
401 read_state_file(&sb, state, "sign", 1);
402 state->signoff = !strcmp(sb.buf, "t");
404 read_state_file(&sb, state, "utf8", 1);
405 state->utf8 = !strcmp(sb.buf, "t");
407 read_state_file(&sb, state, "keep", 1);
408 if (!strcmp(sb.buf, "t"))
409 state->keep = KEEP_TRUE;
410 else if (!strcmp(sb.buf, "b"))
411 state->keep = KEEP_NON_PATCH;
413 state->keep = KEEP_FALSE;
415 read_state_file(&sb, state, "messageid", 1);
416 state->message_id = !strcmp(sb.buf, "t");
418 read_state_file(&sb, state, "scissors", 1);
419 if (!strcmp(sb.buf, "t"))
420 state->scissors = SCISSORS_TRUE;
421 else if (!strcmp(sb.buf, "f"))
422 state->scissors = SCISSORS_FALSE;
424 state->scissors = SCISSORS_UNSET;
426 read_state_file(&sb, state, "apply-opt", 1);
427 argv_array_clear(&state->git_apply_opts);
428 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
429 die(_("could not parse %s"), am_path(state, "apply-opt"));
431 state->rebasing = !!file_exists(am_path(state, "rebasing"));
437 * Removes the am_state directory, forcefully terminating the current am
440 static void am_destroy(const struct am_state *state)
442 struct strbuf sb = STRBUF_INIT;
444 strbuf_addstr(&sb, state->dir);
445 remove_dir_recursively(&sb, 0);
450 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
451 * non-indented lines and checking if they look like they begin with valid
452 * header field names.
454 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
456 static int is_mail(FILE *fp)
458 const char *header_regex = "^[!-9;-~]+:";
459 struct strbuf sb = STRBUF_INIT;
463 if (fseek(fp, 0L, SEEK_SET))
464 die_errno(_("fseek failed"));
466 if (regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED))
467 die("invalid pattern: %s", header_regex);
469 while (!strbuf_getline_crlf(&sb, fp)) {
471 break; /* End of header */
473 /* Ignore indented folded lines */
474 if (*sb.buf == '\t' || *sb.buf == ' ')
477 /* It's a header if it matches header_regex */
478 if (regexec(®ex, sb.buf, 0, NULL, 0)) {
491 * Attempts to detect the patch_format of the patches contained in `paths`,
492 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
495 static int detect_patch_format(const char **paths)
497 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
498 struct strbuf l1 = STRBUF_INIT;
502 * We default to mbox format if input is from stdin and for directories
504 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
505 return PATCH_FORMAT_MBOX;
508 * Otherwise, check the first few lines of the first patch, starting
509 * from the first non-blank line, to try to detect its format.
512 fp = xfopen(*paths, "r");
514 while (!strbuf_getline_crlf(&l1, fp)) {
519 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
520 ret = PATCH_FORMAT_MBOX;
524 if (l1.len && is_mail(fp)) {
525 ret = PATCH_FORMAT_MBOX;
536 * Splits out individual email patches from `paths`, where each path is either
537 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
539 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
541 struct child_process cp = CHILD_PROCESS_INIT;
542 struct strbuf last = STRBUF_INIT;
545 argv_array_push(&cp.args, "mailsplit");
546 argv_array_pushf(&cp.args, "-d%d", state->prec);
547 argv_array_pushf(&cp.args, "-o%s", state->dir);
548 argv_array_push(&cp.args, "-b");
550 argv_array_push(&cp.args, "--keep-cr");
551 argv_array_push(&cp.args, "--");
552 argv_array_pushv(&cp.args, paths);
554 if (capture_command(&cp, &last, 8))
558 state->last = strtol(last.buf, NULL, 10);
564 * Splits a list of files/directories into individual email patches. Each path
565 * in `paths` must be a file/directory that is formatted according to
568 * Once split out, the individual email patches will be stored in the state
569 * directory, with each patch's filename being its index, padded to state->prec
572 * state->cur will be set to the index of the first mail, and state->last will
573 * be set to the index of the last mail.
575 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
576 * to disable this behavior, -1 to use the default configured setting.
578 * Returns 0 on success, -1 on failure.
580 static int split_mail(struct am_state *state, enum patch_format patch_format,
581 const char **paths, int keep_cr)
585 git_config_get_bool("am.keepcr", &keep_cr);
588 switch (patch_format) {
589 case PATCH_FORMAT_MBOX:
590 return split_mail_mbox(state, paths, keep_cr);
592 die("BUG: invalid patch_format");
598 * Setup a new am session for applying patches
600 static void am_setup(struct am_state *state, enum patch_format patch_format,
601 const char **paths, int keep_cr)
603 unsigned char curr_head[GIT_SHA1_RAWSZ];
605 struct strbuf sb = STRBUF_INIT;
608 patch_format = detect_patch_format(paths);
611 fprintf_ln(stderr, _("Patch format detection failed."));
615 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
616 die_errno(_("failed to create directory '%s'"), state->dir);
618 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
620 die(_("Failed to split patches."));
626 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
628 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
630 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
632 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
634 switch (state->keep) {
645 die("BUG: invalid value for state->keep");
648 write_file(am_path(state, "keep"), 1, "%s", str);
650 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
652 switch (state->scissors) {
663 die("BUG: invalid value for state->scissors");
666 write_file(am_path(state, "scissors"), 1, "%s", str);
668 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
669 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
672 write_file(am_path(state, "rebasing"), 1, "%s", "");
674 write_file(am_path(state, "applying"), 1, "%s", "");
676 if (!get_sha1("HEAD", curr_head)) {
677 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
678 if (!state->rebasing)
679 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
680 UPDATE_REFS_DIE_ON_ERR);
682 write_file(am_path(state, "abort-safety"), 1, "%s", "");
683 if (!state->rebasing)
684 delete_ref("ORIG_HEAD", NULL, 0);
688 * NOTE: Since the "next" and "last" files determine if an am_state
689 * session is in progress, they should be written last.
692 write_file(am_path(state, "next"), 1, "%d", state->cur);
694 write_file(am_path(state, "last"), 1, "%d", state->last);
700 * Increments the patch pointer, and cleans am_state for the application of the
703 static void am_next(struct am_state *state)
705 unsigned char head[GIT_SHA1_RAWSZ];
707 free(state->author_name);
708 state->author_name = NULL;
710 free(state->author_email);
711 state->author_email = NULL;
713 free(state->author_date);
714 state->author_date = NULL;
720 unlink(am_path(state, "author-script"));
721 unlink(am_path(state, "final-commit"));
723 if (!get_sha1("HEAD", head))
724 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
726 write_file(am_path(state, "abort-safety"), 1, "%s", "");
729 write_file(am_path(state, "next"), 1, "%d", state->cur);
733 * Returns the filename of the current patch email.
735 static const char *msgnum(const struct am_state *state)
737 static struct strbuf sb = STRBUF_INIT;
740 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
746 * Refresh and write index.
748 static void refresh_and_write_cache(void)
750 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
752 hold_locked_index(lock_file, 1);
753 refresh_cache(REFRESH_QUIET);
754 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
755 die(_("unable to write index file"));
759 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
760 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
761 * strbuf is provided, the space-separated list of files that differ will be
764 static int index_has_changes(struct strbuf *sb)
766 unsigned char head[GIT_SHA1_RAWSZ];
769 if (!get_sha1_tree("HEAD", head)) {
770 struct diff_options opt;
773 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
775 DIFF_OPT_SET(&opt, QUICK);
776 do_diff_cache(head, &opt);
778 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
780 strbuf_addch(sb, ' ');
781 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
784 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
786 for (i = 0; sb && i < active_nr; i++) {
788 strbuf_addch(sb, ' ');
789 strbuf_addstr(sb, active_cache[i]->name);
796 * Dies with a user-friendly message on how to proceed after resolving the
797 * problem. This message can be overridden with state->resolvemsg.
799 static void NORETURN die_user_resolve(const struct am_state *state)
801 if (state->resolvemsg) {
802 printf_ln("%s", state->resolvemsg);
804 const char *cmdline = "git am";
806 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
807 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
808 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
815 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
816 * state->msg will be set to the patch message. state->author_name,
817 * state->author_email and state->author_date will be set to the patch author's
818 * name, email and date respectively. The patch body will be written to the
819 * state directory's "patch" file.
821 * Returns 1 if the patch should be skipped, 0 otherwise.
823 static int parse_mail(struct am_state *state, const char *mail)
826 struct child_process cp = CHILD_PROCESS_INIT;
827 struct strbuf sb = STRBUF_INIT;
828 struct strbuf msg = STRBUF_INIT;
829 struct strbuf author_name = STRBUF_INIT;
830 struct strbuf author_date = STRBUF_INIT;
831 struct strbuf author_email = STRBUF_INIT;
835 cp.in = xopen(mail, O_RDONLY, 0);
836 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
838 argv_array_push(&cp.args, "mailinfo");
839 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
841 switch (state->keep) {
845 argv_array_push(&cp.args, "-k");
848 argv_array_push(&cp.args, "-b");
851 die("BUG: invalid value for state->keep");
854 if (state->message_id)
855 argv_array_push(&cp.args, "-m");
857 switch (state->scissors) {
861 argv_array_push(&cp.args, "--no-scissors");
864 argv_array_push(&cp.args, "--scissors");
867 die("BUG: invalid value for state->scissors");
870 argv_array_push(&cp.args, am_path(state, "msg"));
871 argv_array_push(&cp.args, am_path(state, "patch"));
873 if (run_command(&cp) < 0)
874 die("could not parse patch");
879 /* Extract message and author information */
880 fp = xfopen(am_path(state, "info"), "r");
881 while (!strbuf_getline(&sb, fp, '\n')) {
884 if (skip_prefix(sb.buf, "Subject: ", &x)) {
886 strbuf_addch(&msg, '\n');
887 strbuf_addstr(&msg, x);
888 } else if (skip_prefix(sb.buf, "Author: ", &x))
889 strbuf_addstr(&author_name, x);
890 else if (skip_prefix(sb.buf, "Email: ", &x))
891 strbuf_addstr(&author_email, x);
892 else if (skip_prefix(sb.buf, "Date: ", &x))
893 strbuf_addstr(&author_date, x);
897 /* Skip pine's internal folder data */
898 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
903 if (is_empty_file(am_path(state, "patch"))) {
904 printf_ln(_("Patch is empty. Was it split wrong?"));
905 die_user_resolve(state);
908 strbuf_addstr(&msg, "\n\n");
909 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
910 die_errno(_("could not read '%s'"), am_path(state, "msg"));
914 append_signoff(&msg, 0, 0);
916 assert(!state->author_name);
917 state->author_name = strbuf_detach(&author_name, NULL);
919 assert(!state->author_email);
920 state->author_email = strbuf_detach(&author_email, NULL);
922 assert(!state->author_date);
923 state->author_date = strbuf_detach(&author_date, NULL);
926 state->msg = strbuf_detach(&msg, &state->msg_len);
929 strbuf_release(&msg);
930 strbuf_release(&author_date);
931 strbuf_release(&author_email);
932 strbuf_release(&author_name);
938 * Sets commit_id to the commit hash where the mail was generated from.
939 * Returns 0 on success, -1 on failure.
941 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
943 struct strbuf sb = STRBUF_INIT;
944 FILE *fp = xfopen(mail, "r");
947 if (strbuf_getline(&sb, fp, '\n'))
950 if (!skip_prefix(sb.buf, "From ", &x))
953 if (get_sha1_hex(x, commit_id) < 0)
962 * Sets state->msg, state->author_name, state->author_email, state->author_date
963 * to the commit's respective info.
965 static void get_commit_info(struct am_state *state, struct commit *commit)
967 const char *buffer, *ident_line, *author_date, *msg;
969 struct ident_split ident_split;
970 struct strbuf sb = STRBUF_INIT;
972 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
974 ident_line = find_commit_header(buffer, "author", &ident_len);
976 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
977 strbuf_add(&sb, ident_line, ident_len);
978 die(_("invalid ident line: %s"), sb.buf);
981 assert(!state->author_name);
982 if (ident_split.name_begin) {
983 strbuf_add(&sb, ident_split.name_begin,
984 ident_split.name_end - ident_split.name_begin);
985 state->author_name = strbuf_detach(&sb, NULL);
987 state->author_name = xstrdup("");
989 assert(!state->author_email);
990 if (ident_split.mail_begin) {
991 strbuf_add(&sb, ident_split.mail_begin,
992 ident_split.mail_end - ident_split.mail_begin);
993 state->author_email = strbuf_detach(&sb, NULL);
995 state->author_email = xstrdup("");
997 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
998 strbuf_addstr(&sb, author_date);
999 assert(!state->author_date);
1000 state->author_date = strbuf_detach(&sb, NULL);
1002 assert(!state->msg);
1003 msg = strstr(buffer, "\n\n");
1005 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1006 state->msg = xstrdup(msg + 2);
1007 state->msg_len = strlen(state->msg);
1011 * Writes `commit` as a patch to the state directory's "patch" file.
1013 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1015 struct rev_info rev_info;
1018 fp = xfopen(am_path(state, "patch"), "w");
1019 init_revisions(&rev_info, NULL);
1021 rev_info.abbrev = 0;
1022 rev_info.disable_stdin = 1;
1023 rev_info.show_root_diff = 1;
1024 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1025 rev_info.no_commit_id = 1;
1026 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1027 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1028 rev_info.diffopt.use_color = 0;
1029 rev_info.diffopt.file = fp;
1030 rev_info.diffopt.close_file = 1;
1031 add_pending_object(&rev_info, &commit->object, "");
1032 diff_setup_done(&rev_info.diffopt);
1033 log_tree_commit(&rev_info, commit);
1037 * Like parse_mail(), but parses the mail by looking up its commit ID
1038 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1041 * Will always return 0 as the patch should never be skipped.
1043 static int parse_mail_rebase(struct am_state *state, const char *mail)
1045 struct commit *commit;
1046 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1048 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1049 die(_("could not parse %s"), mail);
1051 commit = lookup_commit_or_die(commit_sha1, mail);
1053 get_commit_info(state, commit);
1055 write_commit_patch(state, commit);
1061 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1062 * `index_file` is not NULL, the patch will be applied to that index.
1064 static int run_apply(const struct am_state *state, const char *index_file)
1066 struct child_process cp = CHILD_PROCESS_INIT;
1071 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1074 * If we are allowed to fall back on 3-way merge, don't give false
1075 * errors during the initial attempt.
1077 if (state->threeway && !index_file) {
1082 argv_array_push(&cp.args, "apply");
1084 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1087 argv_array_push(&cp.args, "--cached");
1089 argv_array_push(&cp.args, "--index");
1091 argv_array_push(&cp.args, am_path(state, "patch"));
1093 if (run_command(&cp))
1096 /* Reload index as git-apply will have modified it. */
1098 read_cache_from(index_file ? index_file : get_index_file());
1104 * Builds an index that contains just the blobs needed for a 3way merge.
1106 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1108 struct child_process cp = CHILD_PROCESS_INIT;
1111 argv_array_push(&cp.args, "apply");
1112 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1113 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1114 argv_array_push(&cp.args, am_path(state, "patch"));
1116 if (run_command(&cp))
1123 * Attempt a threeway merge, using index_path as the temporary index.
1125 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1127 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1128 our_tree[GIT_SHA1_RAWSZ];
1129 const unsigned char *bases[1] = {orig_tree};
1130 struct merge_options o;
1131 struct commit *result;
1132 char *his_tree_name;
1134 if (get_sha1("HEAD", our_tree) < 0)
1135 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1137 if (build_fake_ancestor(state, index_path))
1138 return error("could not build fake ancestor");
1141 read_cache_from(index_path);
1143 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1144 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1146 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1148 if (!state->quiet) {
1150 * List paths that needed 3-way fallback, so that the user can
1151 * review them with extra care to spot mismerges.
1153 struct rev_info rev_info;
1154 const char *diff_filter_str = "--diff-filter=AM";
1156 init_revisions(&rev_info, NULL);
1157 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1158 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1159 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1160 diff_setup_done(&rev_info.diffopt);
1161 run_diff_index(&rev_info, 1);
1164 if (run_apply(state, index_path))
1165 return error(_("Did you hand edit your patch?\n"
1166 "It does not apply to blobs recorded in its index."));
1168 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1169 return error("could not write tree");
1171 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1177 * This is not so wrong. Depending on which base we picked, orig_tree
1178 * may be wildly different from ours, but his_tree has the same set of
1179 * wildly different changes in parts the patch did not touch, so
1180 * recursive ends up canceling them, saying that we reverted all those
1184 init_merge_options(&o);
1187 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1188 o.branch2 = his_tree_name;
1193 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1194 free(his_tree_name);
1195 return error(_("Failed to merge in the changes."));
1198 free(his_tree_name);
1203 * Commits the current index with state->msg as the commit message and
1204 * state->author_name, state->author_email and state->author_date as the author
1207 static void do_commit(const struct am_state *state)
1209 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1210 commit[GIT_SHA1_RAWSZ];
1212 struct commit_list *parents = NULL;
1213 const char *reflog_msg, *author;
1214 struct strbuf sb = STRBUF_INIT;
1216 if (write_cache_as_tree(tree, 0, NULL))
1217 die(_("git write-tree failed to write a tree"));
1219 if (!get_sha1_commit("HEAD", parent)) {
1221 commit_list_insert(lookup_commit(parent), &parents);
1224 say(state, stderr, _("applying to an empty history"));
1227 author = fmt_ident(state->author_name, state->author_email,
1228 state->ignore_date ? NULL : state->author_date,
1231 if (state->committer_date_is_author_date)
1232 setenv("GIT_COMMITTER_DATE",
1233 state->ignore_date ? "" : state->author_date, 1);
1235 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1236 author, state->sign_commit))
1237 die(_("failed to write commit object"));
1239 reflog_msg = getenv("GIT_REFLOG_ACTION");
1243 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1246 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1248 strbuf_release(&sb);
1252 * Validates the am_state for resuming -- the "msg" and authorship fields must
1255 static void validate_resume_state(const struct am_state *state)
1258 die(_("cannot resume: %s does not exist."),
1259 am_path(state, "final-commit"));
1261 if (!state->author_name || !state->author_email || !state->author_date)
1262 die(_("cannot resume: %s does not exist."),
1263 am_path(state, "author-script"));
1267 * Applies all queued mail.
1269 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1270 * well as the state directory's "patch" file is used as-is for applying the
1271 * patch and committing it.
1273 static void am_run(struct am_state *state, int resume)
1275 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1276 struct strbuf sb = STRBUF_INIT;
1278 unlink(am_path(state, "dirtyindex"));
1280 refresh_and_write_cache();
1282 if (index_has_changes(&sb)) {
1283 write_file(am_path(state, "dirtyindex"), 1, "t");
1284 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1287 strbuf_release(&sb);
1289 while (state->cur <= state->last) {
1290 const char *mail = am_path(state, msgnum(state));
1293 if (!file_exists(mail))
1297 validate_resume_state(state);
1302 if (state->rebasing)
1303 skip = parse_mail_rebase(state, mail);
1305 skip = parse_mail(state, mail);
1308 goto next; /* mail should be skipped */
1310 write_author_script(state);
1311 write_commit_msg(state);
1314 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1316 apply_status = run_apply(state, NULL);
1318 if (apply_status && state->threeway) {
1319 struct strbuf sb = STRBUF_INIT;
1321 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1322 apply_status = fall_back_threeway(state, sb.buf);
1323 strbuf_release(&sb);
1326 * Applying the patch to an earlier tree and merging
1327 * the result may have produced the same tree as ours.
1329 if (!apply_status && !index_has_changes(NULL)) {
1330 say(state, stdout, _("No changes -- Patch already applied."));
1336 int advice_amworkdir = 1;
1338 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1339 linelen(state->msg), state->msg);
1341 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1343 if (advice_amworkdir)
1344 printf_ln(_("The copy of the patch that failed is found in: %s"),
1345 am_path(state, "patch"));
1347 die_user_resolve(state);
1357 * In rebasing mode, it's up to the caller to take care of
1360 if (!state->rebasing) {
1362 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1367 * Resume the current am session after patch application failure. The user did
1368 * all the hard work, and we do not have to do any patch application. Just
1369 * trust and commit what the user has in the index and working tree.
1371 static void am_resolve(struct am_state *state)
1373 validate_resume_state(state);
1375 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1377 if (!index_has_changes(NULL)) {
1378 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1379 "If there is nothing left to stage, chances are that something else\n"
1380 "already introduced the same changes; you might want to skip this patch."));
1381 die_user_resolve(state);
1384 if (unmerged_cache()) {
1385 printf_ln(_("You still have unmerged paths in your index.\n"
1386 "Did you forget to use 'git add'?"));
1387 die_user_resolve(state);
1397 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1398 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1401 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1403 struct lock_file *lock_file;
1404 struct unpack_trees_options opts;
1405 struct tree_desc t[2];
1407 if (parse_tree(head) || parse_tree(remote))
1410 lock_file = xcalloc(1, sizeof(struct lock_file));
1411 hold_locked_index(lock_file, 1);
1413 refresh_cache(REFRESH_QUIET);
1415 memset(&opts, 0, sizeof(opts));
1417 opts.src_index = &the_index;
1418 opts.dst_index = &the_index;
1422 opts.fn = twoway_merge;
1423 init_tree_desc(&t[0], head->buffer, head->size);
1424 init_tree_desc(&t[1], remote->buffer, remote->size);
1426 if (unpack_trees(2, t, &opts)) {
1427 rollback_lock_file(lock_file);
1431 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1432 die(_("unable to write new index file"));
1438 * Clean the index without touching entries that are not modified between
1439 * `head` and `remote`.
1441 static int clean_index(const unsigned char *head, const unsigned char *remote)
1443 struct lock_file *lock_file;
1444 struct tree *head_tree, *remote_tree, *index_tree;
1445 unsigned char index[GIT_SHA1_RAWSZ];
1446 struct pathspec pathspec;
1448 head_tree = parse_tree_indirect(head);
1450 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1452 remote_tree = parse_tree_indirect(remote);
1454 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1456 read_cache_unmerged();
1458 if (fast_forward_to(head_tree, head_tree, 1))
1461 if (write_cache_as_tree(index, 0, NULL))
1464 index_tree = parse_tree_indirect(index);
1466 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1468 if (fast_forward_to(index_tree, remote_tree, 0))
1471 memset(&pathspec, 0, sizeof(pathspec));
1473 lock_file = xcalloc(1, sizeof(struct lock_file));
1474 hold_locked_index(lock_file, 1);
1476 if (read_tree(remote_tree, 0, &pathspec)) {
1477 rollback_lock_file(lock_file);
1481 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1482 die(_("unable to write new index file"));
1484 remove_branch_state();
1490 * Resume the current am session by skipping the current patch.
1492 static void am_skip(struct am_state *state)
1494 unsigned char head[GIT_SHA1_RAWSZ];
1496 if (get_sha1("HEAD", head))
1497 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1499 if (clean_index(head, head))
1500 die(_("failed to clean index"));
1507 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1509 * It is not safe to reset HEAD when:
1510 * 1. git-am previously failed because the index was dirty.
1511 * 2. HEAD has moved since git-am previously failed.
1513 static int safe_to_abort(const struct am_state *state)
1515 struct strbuf sb = STRBUF_INIT;
1516 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1518 if (file_exists(am_path(state, "dirtyindex")))
1521 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1522 if (get_sha1_hex(sb.buf, abort_safety))
1523 die(_("could not parse %s"), am_path(state, "abort_safety"));
1525 hashclr(abort_safety);
1527 if (get_sha1("HEAD", head))
1530 if (!hashcmp(head, abort_safety))
1533 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1534 "Not rewinding to ORIG_HEAD"));
1540 * Aborts the current am session if it is safe to do so.
1542 static void am_abort(struct am_state *state)
1544 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1545 int has_curr_head, has_orig_head;
1548 if (!safe_to_abort(state)) {
1553 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1554 has_curr_head = !is_null_sha1(curr_head);
1556 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1558 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1560 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1562 clean_index(curr_head, orig_head);
1565 update_ref("am --abort", "HEAD", orig_head,
1566 has_curr_head ? curr_head : NULL, 0,
1567 UPDATE_REFS_DIE_ON_ERR);
1568 else if (curr_branch)
1569 delete_ref(curr_branch, NULL, REF_NODEREF);
1576 * parse_options() callback that validates and sets opt->value to the
1577 * PATCH_FORMAT_* enum value corresponding to `arg`.
1579 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1581 int *opt_value = opt->value;
1583 if (!strcmp(arg, "mbox"))
1584 *opt_value = PATCH_FORMAT_MBOX;
1586 return error(_("Invalid value for --patch-format: %s"), arg);
1598 int cmd_am(int argc, const char **argv, const char *prefix)
1600 struct am_state state;
1602 int patch_format = PATCH_FORMAT_UNKNOWN;
1603 enum resume_mode resume = RESUME_FALSE;
1605 const char * const usage[] = {
1606 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1607 N_("git am [options] (--continue | --skip | --abort)"),
1611 struct option options[] = {
1612 OPT_BOOL('3', "3way", &state.threeway,
1613 N_("allow fall back on 3way merging if needed")),
1614 OPT__QUIET(&state.quiet, N_("be quiet")),
1615 OPT_BOOL('s', "signoff", &state.signoff,
1616 N_("add a Signed-off-by line to the commit message")),
1617 OPT_BOOL('u', "utf8", &state.utf8,
1618 N_("recode into utf8 (default)")),
1619 OPT_SET_INT('k', "keep", &state.keep,
1620 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1621 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1622 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1623 OPT_BOOL('m', "message-id", &state.message_id,
1624 N_("pass -m flag to git-mailinfo")),
1625 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1626 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1627 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1628 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1629 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1630 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
1631 OPT_BOOL('c', "scissors", &state.scissors,
1632 N_("strip everything before a scissors line")),
1633 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
1634 N_("pass it through git-apply"),
1636 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
1637 N_("pass it through git-apply"),
1639 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
1640 N_("pass it through git-apply"),
1642 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
1643 N_("pass it through git-apply"),
1645 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
1646 N_("pass it through git-apply"),
1648 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
1649 N_("pass it through git-apply"),
1651 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
1652 N_("pass it through git-apply"),
1654 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
1655 N_("pass it through git-apply"),
1657 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1658 N_("format the patch(es) are in"),
1659 parse_opt_patchformat),
1660 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
1661 N_("pass it through git-apply"),
1663 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1664 N_("override error message when patch failure occurs")),
1665 OPT_CMDMODE(0, "continue", &resume,
1666 N_("continue applying patches after resolving a conflict"),
1668 OPT_CMDMODE('r', "resolved", &resume,
1669 N_("synonyms for --continue"),
1671 OPT_CMDMODE(0, "skip", &resume,
1672 N_("skip the current patch"),
1674 OPT_CMDMODE(0, "abort", &resume,
1675 N_("restore the original branch and abort the patching operation."),
1677 OPT_BOOL(0, "committer-date-is-author-date",
1678 &state.committer_date_is_author_date,
1679 N_("lie about committer date")),
1680 OPT_BOOL(0, "ignore-date", &state.ignore_date,
1681 N_("use current timestamp for author date")),
1682 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
1683 N_("GPG-sign commits"),
1684 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1685 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1686 N_("(internal use for git-rebase)")),
1691 * NEEDSWORK: Once all the features of git-am.sh have been
1692 * re-implemented in builtin/am.c, this preamble can be removed.
1694 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1695 const char *path = mkpath("%s/git-am", git_exec_path());
1697 if (sane_execvp(path, (char **)argv) < 0)
1698 die_errno("could not exec %s", path);
1700 prefix = setup_git_directory();
1701 trace_repo_setup(prefix);
1705 git_config(git_default_config, NULL);
1707 am_state_init(&state, git_path("rebase-apply"));
1709 argc = parse_options(argc, argv, prefix, options, usage, 0);
1711 if (read_index_preload(&the_index, NULL) < 0)
1712 die(_("failed to read the index"));
1714 if (am_in_progress(&state)) {
1716 * Catch user error to feed us patches when there is a session
1719 * 1. mbox path(s) are provided on the command-line.
1720 * 2. stdin is not a tty: the user is trying to feed us a patch
1721 * from standard input. This is somewhat unreliable -- stdin
1722 * could be /dev/null for example and the caller did not
1723 * intend to feed us a patch but wanted to continue
1726 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1727 die(_("previous rebase directory %s still exists but mbox given."),
1730 if (resume == RESUME_FALSE)
1731 resume = RESUME_APPLY;
1735 struct argv_array paths = ARGV_ARRAY_INIT;
1739 * Handle stray state directory in the independent-run case. In
1740 * the --rebasing case, it is up to the caller to take care of
1741 * stray directories.
1743 if (file_exists(state.dir) && !state.rebasing) {
1744 if (resume == RESUME_ABORT) {
1746 am_state_release(&state);
1750 die(_("Stray %s directory found.\n"
1751 "Use \"git am --abort\" to remove it."),
1756 die(_("Resolve operation not in progress, we are not resuming."));
1758 for (i = 0; i < argc; i++) {
1759 if (is_absolute_path(argv[i]) || !prefix)
1760 argv_array_push(&paths, argv[i]);
1762 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1765 am_setup(&state, patch_format, paths.argv, keep_cr);
1767 argv_array_clear(&paths);
1777 case RESUME_RESOLVED:
1787 die("BUG: invalid resume value");
1790 am_state_release(&state);