builtin-am: implement --rebasing mode
[git/mingw.git] / builtin / am.c
blob440a65361a3d2f26d9dff3355610fda712a56164
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
6 #include "cache.h"
7 #include "builtin.h"
8 #include "exec_cmd.h"
9 #include "parse-options.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "quote.h"
13 #include "lockfile.h"
14 #include "cache-tree.h"
15 #include "refs.h"
16 #include "commit.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "unpack-trees.h"
20 #include "branch.h"
21 #include "sequencer.h"
22 #include "revision.h"
23 #include "merge-recursive.h"
25 /**
26 * Returns 1 if the file is empty or does not exist, 0 otherwise.
28 static int is_empty_file(const char *filename)
30 struct stat st;
32 if (stat(filename, &st) < 0) {
33 if (errno == ENOENT)
34 return 1;
35 die_errno(_("could not stat %s"), filename);
38 return !st.st_size;
41 /**
42 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
44 static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
46 if (strbuf_getwholeline(sb, fp, '\n'))
47 return EOF;
48 if (sb->buf[sb->len - 1] == '\n') {
49 strbuf_setlen(sb, sb->len - 1);
50 if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
51 strbuf_setlen(sb, sb->len - 1);
53 return 0;
56 /**
57 * Returns the length of the first line of msg.
59 static int linelen(const char *msg)
61 return strchrnul(msg, '\n') - msg;
64 enum patch_format {
65 PATCH_FORMAT_UNKNOWN = 0,
66 PATCH_FORMAT_MBOX
69 struct am_state {
70 /* state directory path */
71 char *dir;
73 /* current and last patch numbers, 1-indexed */
74 int cur;
75 int last;
77 /* commit metadata and message */
78 char *author_name;
79 char *author_email;
80 char *author_date;
81 char *msg;
82 size_t msg_len;
84 /* number of digits in patch filename */
85 int prec;
87 /* various operating modes and command line options */
88 int threeway;
89 int quiet;
90 int signoff;
91 const char *resolvemsg;
92 int rebasing;
95 /**
96 * Initializes am_state with the default values. The state directory is set to
97 * dir.
99 static void am_state_init(struct am_state *state, const char *dir)
101 memset(state, 0, sizeof(*state));
103 assert(dir);
104 state->dir = xstrdup(dir);
106 state->prec = 4;
110 * Releases memory allocated by an am_state.
112 static void am_state_release(struct am_state *state)
114 free(state->dir);
115 free(state->author_name);
116 free(state->author_email);
117 free(state->author_date);
118 free(state->msg);
122 * Returns path relative to the am_state directory.
124 static inline const char *am_path(const struct am_state *state, const char *path)
126 return mkpath("%s/%s", state->dir, path);
130 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
131 * at the end.
133 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
135 va_list ap;
137 va_start(ap, fmt);
138 if (!state->quiet) {
139 vfprintf(fp, fmt, ap);
140 putc('\n', fp);
142 va_end(ap);
146 * Returns 1 if there is an am session in progress, 0 otherwise.
148 static int am_in_progress(const struct am_state *state)
150 struct stat st;
152 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
153 return 0;
154 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
155 return 0;
156 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
157 return 0;
158 return 1;
162 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
163 * number of bytes read on success, -1 if the file does not exist. If `trim` is
164 * set, trailing whitespace will be removed.
166 static int read_state_file(struct strbuf *sb, const struct am_state *state,
167 const char *file, int trim)
169 strbuf_reset(sb);
171 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
172 if (trim)
173 strbuf_trim(sb);
175 return sb->len;
178 if (errno == ENOENT)
179 return -1;
181 die_errno(_("could not read '%s'"), am_path(state, file));
185 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
186 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
187 * match `key`. Returns NULL on failure.
189 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
190 * the author-script.
192 static char *read_shell_var(FILE *fp, const char *key)
194 struct strbuf sb = STRBUF_INIT;
195 const char *str;
197 if (strbuf_getline(&sb, fp, '\n'))
198 goto fail;
200 if (!skip_prefix(sb.buf, key, &str))
201 goto fail;
203 if (!skip_prefix(str, "=", &str))
204 goto fail;
206 strbuf_remove(&sb, 0, str - sb.buf);
208 str = sq_dequote(sb.buf);
209 if (!str)
210 goto fail;
212 return strbuf_detach(&sb, NULL);
214 fail:
215 strbuf_release(&sb);
216 return NULL;
220 * Reads and parses the state directory's "author-script" file, and sets
221 * state->author_name, state->author_email and state->author_date accordingly.
222 * Returns 0 on success, -1 if the file could not be parsed.
224 * The author script is of the format:
226 * GIT_AUTHOR_NAME='$author_name'
227 * GIT_AUTHOR_EMAIL='$author_email'
228 * GIT_AUTHOR_DATE='$author_date'
230 * where $author_name, $author_email and $author_date are quoted. We are strict
231 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
232 * script, and thus if the file differs from what this function expects, it is
233 * better to bail out than to do something that the user does not expect.
235 static int read_author_script(struct am_state *state)
237 const char *filename = am_path(state, "author-script");
238 FILE *fp;
240 assert(!state->author_name);
241 assert(!state->author_email);
242 assert(!state->author_date);
244 fp = fopen(filename, "r");
245 if (!fp) {
246 if (errno == ENOENT)
247 return 0;
248 die_errno(_("could not open '%s' for reading"), filename);
251 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
252 if (!state->author_name) {
253 fclose(fp);
254 return -1;
257 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
258 if (!state->author_email) {
259 fclose(fp);
260 return -1;
263 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
264 if (!state->author_date) {
265 fclose(fp);
266 return -1;
269 if (fgetc(fp) != EOF) {
270 fclose(fp);
271 return -1;
274 fclose(fp);
275 return 0;
279 * Saves state->author_name, state->author_email and state->author_date in the
280 * state directory's "author-script" file.
282 static void write_author_script(const struct am_state *state)
284 struct strbuf sb = STRBUF_INIT;
286 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
287 sq_quote_buf(&sb, state->author_name);
288 strbuf_addch(&sb, '\n');
290 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
291 sq_quote_buf(&sb, state->author_email);
292 strbuf_addch(&sb, '\n');
294 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
295 sq_quote_buf(&sb, state->author_date);
296 strbuf_addch(&sb, '\n');
298 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
300 strbuf_release(&sb);
304 * Reads the commit message from the state directory's "final-commit" file,
305 * setting state->msg to its contents and state->msg_len to the length of its
306 * contents in bytes.
308 * Returns 0 on success, -1 if the file does not exist.
310 static int read_commit_msg(struct am_state *state)
312 struct strbuf sb = STRBUF_INIT;
314 assert(!state->msg);
316 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
317 strbuf_release(&sb);
318 return -1;
321 state->msg = strbuf_detach(&sb, &state->msg_len);
322 return 0;
326 * Saves state->msg in the state directory's "final-commit" file.
328 static void write_commit_msg(const struct am_state *state)
330 int fd;
331 const char *filename = am_path(state, "final-commit");
333 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
334 if (write_in_full(fd, state->msg, state->msg_len) < 0)
335 die_errno(_("could not write to %s"), filename);
336 close(fd);
340 * Loads state from disk.
342 static void am_load(struct am_state *state)
344 struct strbuf sb = STRBUF_INIT;
346 if (read_state_file(&sb, state, "next", 1) < 0)
347 die("BUG: state file 'next' does not exist");
348 state->cur = strtol(sb.buf, NULL, 10);
350 if (read_state_file(&sb, state, "last", 1) < 0)
351 die("BUG: state file 'last' does not exist");
352 state->last = strtol(sb.buf, NULL, 10);
354 if (read_author_script(state) < 0)
355 die(_("could not parse author script"));
357 read_commit_msg(state);
359 read_state_file(&sb, state, "threeway", 1);
360 state->threeway = !strcmp(sb.buf, "t");
362 read_state_file(&sb, state, "quiet", 1);
363 state->quiet = !strcmp(sb.buf, "t");
365 read_state_file(&sb, state, "sign", 1);
366 state->signoff = !strcmp(sb.buf, "t");
368 state->rebasing = !!file_exists(am_path(state, "rebasing"));
370 strbuf_release(&sb);
374 * Removes the am_state directory, forcefully terminating the current am
375 * session.
377 static void am_destroy(const struct am_state *state)
379 struct strbuf sb = STRBUF_INIT;
381 strbuf_addstr(&sb, state->dir);
382 remove_dir_recursively(&sb, 0);
383 strbuf_release(&sb);
387 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
388 * non-indented lines and checking if they look like they begin with valid
389 * header field names.
391 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
393 static int is_mail(FILE *fp)
395 const char *header_regex = "^[!-9;-~]+:";
396 struct strbuf sb = STRBUF_INIT;
397 regex_t regex;
398 int ret = 1;
400 if (fseek(fp, 0L, SEEK_SET))
401 die_errno(_("fseek failed"));
403 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
404 die("invalid pattern: %s", header_regex);
406 while (!strbuf_getline_crlf(&sb, fp)) {
407 if (!sb.len)
408 break; /* End of header */
410 /* Ignore indented folded lines */
411 if (*sb.buf == '\t' || *sb.buf == ' ')
412 continue;
414 /* It's a header if it matches header_regex */
415 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
416 ret = 0;
417 goto done;
421 done:
422 regfree(&regex);
423 strbuf_release(&sb);
424 return ret;
428 * Attempts to detect the patch_format of the patches contained in `paths`,
429 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
430 * detection fails.
432 static int detect_patch_format(const char **paths)
434 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
435 struct strbuf l1 = STRBUF_INIT;
436 FILE *fp;
439 * We default to mbox format if input is from stdin and for directories
441 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
442 return PATCH_FORMAT_MBOX;
445 * Otherwise, check the first few lines of the first patch, starting
446 * from the first non-blank line, to try to detect its format.
449 fp = xfopen(*paths, "r");
451 while (!strbuf_getline_crlf(&l1, fp)) {
452 if (l1.len)
453 break;
456 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
457 ret = PATCH_FORMAT_MBOX;
458 goto done;
461 if (l1.len && is_mail(fp)) {
462 ret = PATCH_FORMAT_MBOX;
463 goto done;
466 done:
467 fclose(fp);
468 strbuf_release(&l1);
469 return ret;
473 * Splits out individual email patches from `paths`, where each path is either
474 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
476 static int split_mail_mbox(struct am_state *state, const char **paths)
478 struct child_process cp = CHILD_PROCESS_INIT;
479 struct strbuf last = STRBUF_INIT;
481 cp.git_cmd = 1;
482 argv_array_push(&cp.args, "mailsplit");
483 argv_array_pushf(&cp.args, "-d%d", state->prec);
484 argv_array_pushf(&cp.args, "-o%s", state->dir);
485 argv_array_push(&cp.args, "-b");
486 argv_array_push(&cp.args, "--");
487 argv_array_pushv(&cp.args, paths);
489 if (capture_command(&cp, &last, 8))
490 return -1;
492 state->cur = 1;
493 state->last = strtol(last.buf, NULL, 10);
495 return 0;
499 * Splits a list of files/directories into individual email patches. Each path
500 * in `paths` must be a file/directory that is formatted according to
501 * `patch_format`.
503 * Once split out, the individual email patches will be stored in the state
504 * directory, with each patch's filename being its index, padded to state->prec
505 * digits.
507 * state->cur will be set to the index of the first mail, and state->last will
508 * be set to the index of the last mail.
510 * Returns 0 on success, -1 on failure.
512 static int split_mail(struct am_state *state, enum patch_format patch_format,
513 const char **paths)
515 switch (patch_format) {
516 case PATCH_FORMAT_MBOX:
517 return split_mail_mbox(state, paths);
518 default:
519 die("BUG: invalid patch_format");
521 return -1;
525 * Setup a new am session for applying patches
527 static void am_setup(struct am_state *state, enum patch_format patch_format,
528 const char **paths)
530 unsigned char curr_head[GIT_SHA1_RAWSZ];
532 if (!patch_format)
533 patch_format = detect_patch_format(paths);
535 if (!patch_format) {
536 fprintf_ln(stderr, _("Patch format detection failed."));
537 exit(128);
540 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
541 die_errno(_("failed to create directory '%s'"), state->dir);
543 if (split_mail(state, patch_format, paths) < 0) {
544 am_destroy(state);
545 die(_("Failed to split patches."));
548 if (state->rebasing)
549 state->threeway = 1;
551 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
553 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
555 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
557 if (state->rebasing)
558 write_file(am_path(state, "rebasing"), 1, "%s", "");
559 else
560 write_file(am_path(state, "applying"), 1, "%s", "");
562 if (!get_sha1("HEAD", curr_head)) {
563 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
564 if (!state->rebasing)
565 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
566 UPDATE_REFS_DIE_ON_ERR);
567 } else {
568 write_file(am_path(state, "abort-safety"), 1, "%s", "");
569 if (!state->rebasing)
570 delete_ref("ORIG_HEAD", NULL, 0);
574 * NOTE: Since the "next" and "last" files determine if an am_state
575 * session is in progress, they should be written last.
578 write_file(am_path(state, "next"), 1, "%d", state->cur);
580 write_file(am_path(state, "last"), 1, "%d", state->last);
584 * Increments the patch pointer, and cleans am_state for the application of the
585 * next patch.
587 static void am_next(struct am_state *state)
589 unsigned char head[GIT_SHA1_RAWSZ];
591 free(state->author_name);
592 state->author_name = NULL;
594 free(state->author_email);
595 state->author_email = NULL;
597 free(state->author_date);
598 state->author_date = NULL;
600 free(state->msg);
601 state->msg = NULL;
602 state->msg_len = 0;
604 unlink(am_path(state, "author-script"));
605 unlink(am_path(state, "final-commit"));
607 if (!get_sha1("HEAD", head))
608 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
609 else
610 write_file(am_path(state, "abort-safety"), 1, "%s", "");
612 state->cur++;
613 write_file(am_path(state, "next"), 1, "%d", state->cur);
617 * Returns the filename of the current patch email.
619 static const char *msgnum(const struct am_state *state)
621 static struct strbuf sb = STRBUF_INIT;
623 strbuf_reset(&sb);
624 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
626 return sb.buf;
630 * Refresh and write index.
632 static void refresh_and_write_cache(void)
634 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
636 hold_locked_index(lock_file, 1);
637 refresh_cache(REFRESH_QUIET);
638 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
639 die(_("unable to write index file"));
643 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
644 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
645 * strbuf is provided, the space-separated list of files that differ will be
646 * appended to it.
648 static int index_has_changes(struct strbuf *sb)
650 unsigned char head[GIT_SHA1_RAWSZ];
651 int i;
653 if (!get_sha1_tree("HEAD", head)) {
654 struct diff_options opt;
656 diff_setup(&opt);
657 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
658 if (!sb)
659 DIFF_OPT_SET(&opt, QUICK);
660 do_diff_cache(head, &opt);
661 diffcore_std(&opt);
662 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
663 if (i)
664 strbuf_addch(sb, ' ');
665 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
667 diff_flush(&opt);
668 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
669 } else {
670 for (i = 0; sb && i < active_nr; i++) {
671 if (i)
672 strbuf_addch(sb, ' ');
673 strbuf_addstr(sb, active_cache[i]->name);
675 return !!active_nr;
680 * Dies with a user-friendly message on how to proceed after resolving the
681 * problem. This message can be overridden with state->resolvemsg.
683 static void NORETURN die_user_resolve(const struct am_state *state)
685 if (state->resolvemsg) {
686 printf_ln("%s", state->resolvemsg);
687 } else {
688 const char *cmdline = "git am";
690 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
691 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
692 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
695 exit(128);
699 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
700 * state->msg will be set to the patch message. state->author_name,
701 * state->author_email and state->author_date will be set to the patch author's
702 * name, email and date respectively. The patch body will be written to the
703 * state directory's "patch" file.
705 * Returns 1 if the patch should be skipped, 0 otherwise.
707 static int parse_mail(struct am_state *state, const char *mail)
709 FILE *fp;
710 struct child_process cp = CHILD_PROCESS_INIT;
711 struct strbuf sb = STRBUF_INIT;
712 struct strbuf msg = STRBUF_INIT;
713 struct strbuf author_name = STRBUF_INIT;
714 struct strbuf author_date = STRBUF_INIT;
715 struct strbuf author_email = STRBUF_INIT;
716 int ret = 0;
718 cp.git_cmd = 1;
719 cp.in = xopen(mail, O_RDONLY, 0);
720 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
722 argv_array_push(&cp.args, "mailinfo");
723 argv_array_push(&cp.args, am_path(state, "msg"));
724 argv_array_push(&cp.args, am_path(state, "patch"));
726 if (run_command(&cp) < 0)
727 die("could not parse patch");
729 close(cp.in);
730 close(cp.out);
732 /* Extract message and author information */
733 fp = xfopen(am_path(state, "info"), "r");
734 while (!strbuf_getline(&sb, fp, '\n')) {
735 const char *x;
737 if (skip_prefix(sb.buf, "Subject: ", &x)) {
738 if (msg.len)
739 strbuf_addch(&msg, '\n');
740 strbuf_addstr(&msg, x);
741 } else if (skip_prefix(sb.buf, "Author: ", &x))
742 strbuf_addstr(&author_name, x);
743 else if (skip_prefix(sb.buf, "Email: ", &x))
744 strbuf_addstr(&author_email, x);
745 else if (skip_prefix(sb.buf, "Date: ", &x))
746 strbuf_addstr(&author_date, x);
748 fclose(fp);
750 /* Skip pine's internal folder data */
751 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
752 ret = 1;
753 goto finish;
756 if (is_empty_file(am_path(state, "patch"))) {
757 printf_ln(_("Patch is empty. Was it split wrong?"));
758 die_user_resolve(state);
761 strbuf_addstr(&msg, "\n\n");
762 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
763 die_errno(_("could not read '%s'"), am_path(state, "msg"));
764 stripspace(&msg, 0);
766 if (state->signoff)
767 append_signoff(&msg, 0, 0);
769 assert(!state->author_name);
770 state->author_name = strbuf_detach(&author_name, NULL);
772 assert(!state->author_email);
773 state->author_email = strbuf_detach(&author_email, NULL);
775 assert(!state->author_date);
776 state->author_date = strbuf_detach(&author_date, NULL);
778 assert(!state->msg);
779 state->msg = strbuf_detach(&msg, &state->msg_len);
781 finish:
782 strbuf_release(&msg);
783 strbuf_release(&author_date);
784 strbuf_release(&author_email);
785 strbuf_release(&author_name);
786 strbuf_release(&sb);
787 return ret;
791 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
792 * `index_file` is not NULL, the patch will be applied to that index.
794 static int run_apply(const struct am_state *state, const char *index_file)
796 struct child_process cp = CHILD_PROCESS_INIT;
798 cp.git_cmd = 1;
800 if (index_file)
801 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
804 * If we are allowed to fall back on 3-way merge, don't give false
805 * errors during the initial attempt.
807 if (state->threeway && !index_file) {
808 cp.no_stdout = 1;
809 cp.no_stderr = 1;
812 argv_array_push(&cp.args, "apply");
814 if (index_file)
815 argv_array_push(&cp.args, "--cached");
816 else
817 argv_array_push(&cp.args, "--index");
819 argv_array_push(&cp.args, am_path(state, "patch"));
821 if (run_command(&cp))
822 return -1;
824 /* Reload index as git-apply will have modified it. */
825 discard_cache();
826 read_cache_from(index_file ? index_file : get_index_file());
828 return 0;
832 * Builds an index that contains just the blobs needed for a 3way merge.
834 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
836 struct child_process cp = CHILD_PROCESS_INIT;
838 cp.git_cmd = 1;
839 argv_array_push(&cp.args, "apply");
840 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
841 argv_array_push(&cp.args, am_path(state, "patch"));
843 if (run_command(&cp))
844 return -1;
846 return 0;
850 * Attempt a threeway merge, using index_path as the temporary index.
852 static int fall_back_threeway(const struct am_state *state, const char *index_path)
854 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
855 our_tree[GIT_SHA1_RAWSZ];
856 const unsigned char *bases[1] = {orig_tree};
857 struct merge_options o;
858 struct commit *result;
859 char *his_tree_name;
861 if (get_sha1("HEAD", our_tree) < 0)
862 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
864 if (build_fake_ancestor(state, index_path))
865 return error("could not build fake ancestor");
867 discard_cache();
868 read_cache_from(index_path);
870 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
871 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
873 say(state, stdout, _("Using index info to reconstruct a base tree..."));
875 if (!state->quiet) {
877 * List paths that needed 3-way fallback, so that the user can
878 * review them with extra care to spot mismerges.
880 struct rev_info rev_info;
881 const char *diff_filter_str = "--diff-filter=AM";
883 init_revisions(&rev_info, NULL);
884 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
885 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
886 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
887 diff_setup_done(&rev_info.diffopt);
888 run_diff_index(&rev_info, 1);
891 if (run_apply(state, index_path))
892 return error(_("Did you hand edit your patch?\n"
893 "It does not apply to blobs recorded in its index."));
895 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
896 return error("could not write tree");
898 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
900 discard_cache();
901 read_cache();
904 * This is not so wrong. Depending on which base we picked, orig_tree
905 * may be wildly different from ours, but his_tree has the same set of
906 * wildly different changes in parts the patch did not touch, so
907 * recursive ends up canceling them, saying that we reverted all those
908 * changes.
911 init_merge_options(&o);
913 o.branch1 = "HEAD";
914 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
915 o.branch2 = his_tree_name;
917 if (state->quiet)
918 o.verbosity = 0;
920 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
921 free(his_tree_name);
922 return error(_("Failed to merge in the changes."));
925 free(his_tree_name);
926 return 0;
930 * Commits the current index with state->msg as the commit message and
931 * state->author_name, state->author_email and state->author_date as the author
932 * information.
934 static void do_commit(const struct am_state *state)
936 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
937 commit[GIT_SHA1_RAWSZ];
938 unsigned char *ptr;
939 struct commit_list *parents = NULL;
940 const char *reflog_msg, *author;
941 struct strbuf sb = STRBUF_INIT;
943 if (write_cache_as_tree(tree, 0, NULL))
944 die(_("git write-tree failed to write a tree"));
946 if (!get_sha1_commit("HEAD", parent)) {
947 ptr = parent;
948 commit_list_insert(lookup_commit(parent), &parents);
949 } else {
950 ptr = NULL;
951 say(state, stderr, _("applying to an empty history"));
954 author = fmt_ident(state->author_name, state->author_email,
955 state->author_date, IDENT_STRICT);
957 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
958 author, NULL))
959 die(_("failed to write commit object"));
961 reflog_msg = getenv("GIT_REFLOG_ACTION");
962 if (!reflog_msg)
963 reflog_msg = "am";
965 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
966 state->msg);
968 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
970 strbuf_release(&sb);
974 * Validates the am_state for resuming -- the "msg" and authorship fields must
975 * be filled up.
977 static void validate_resume_state(const struct am_state *state)
979 if (!state->msg)
980 die(_("cannot resume: %s does not exist."),
981 am_path(state, "final-commit"));
983 if (!state->author_name || !state->author_email || !state->author_date)
984 die(_("cannot resume: %s does not exist."),
985 am_path(state, "author-script"));
989 * Applies all queued mail.
991 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
992 * well as the state directory's "patch" file is used as-is for applying the
993 * patch and committing it.
995 static void am_run(struct am_state *state, int resume)
997 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
998 struct strbuf sb = STRBUF_INIT;
1000 unlink(am_path(state, "dirtyindex"));
1002 refresh_and_write_cache();
1004 if (index_has_changes(&sb)) {
1005 write_file(am_path(state, "dirtyindex"), 1, "t");
1006 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1009 strbuf_release(&sb);
1011 while (state->cur <= state->last) {
1012 const char *mail = am_path(state, msgnum(state));
1013 int apply_status;
1015 if (!file_exists(mail))
1016 goto next;
1018 if (resume) {
1019 validate_resume_state(state);
1020 resume = 0;
1021 } else {
1022 if (parse_mail(state, mail))
1023 goto next; /* mail should be skipped */
1025 write_author_script(state);
1026 write_commit_msg(state);
1029 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1031 apply_status = run_apply(state, NULL);
1033 if (apply_status && state->threeway) {
1034 struct strbuf sb = STRBUF_INIT;
1036 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1037 apply_status = fall_back_threeway(state, sb.buf);
1038 strbuf_release(&sb);
1041 * Applying the patch to an earlier tree and merging
1042 * the result may have produced the same tree as ours.
1044 if (!apply_status && !index_has_changes(NULL)) {
1045 say(state, stdout, _("No changes -- Patch already applied."));
1046 goto next;
1050 if (apply_status) {
1051 int advice_amworkdir = 1;
1053 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1054 linelen(state->msg), state->msg);
1056 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1058 if (advice_amworkdir)
1059 printf_ln(_("The copy of the patch that failed is found in: %s"),
1060 am_path(state, "patch"));
1062 die_user_resolve(state);
1065 do_commit(state);
1067 next:
1068 am_next(state);
1072 * In rebasing mode, it's up to the caller to take care of
1073 * housekeeping.
1075 if (!state->rebasing) {
1076 am_destroy(state);
1077 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1082 * Resume the current am session after patch application failure. The user did
1083 * all the hard work, and we do not have to do any patch application. Just
1084 * trust and commit what the user has in the index and working tree.
1086 static void am_resolve(struct am_state *state)
1088 validate_resume_state(state);
1090 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1092 if (!index_has_changes(NULL)) {
1093 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1094 "If there is nothing left to stage, chances are that something else\n"
1095 "already introduced the same changes; you might want to skip this patch."));
1096 die_user_resolve(state);
1099 if (unmerged_cache()) {
1100 printf_ln(_("You still have unmerged paths in your index.\n"
1101 "Did you forget to use 'git add'?"));
1102 die_user_resolve(state);
1105 do_commit(state);
1107 am_next(state);
1108 am_run(state, 0);
1112 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1113 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1114 * failure.
1116 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1118 struct lock_file *lock_file;
1119 struct unpack_trees_options opts;
1120 struct tree_desc t[2];
1122 if (parse_tree(head) || parse_tree(remote))
1123 return -1;
1125 lock_file = xcalloc(1, sizeof(struct lock_file));
1126 hold_locked_index(lock_file, 1);
1128 refresh_cache(REFRESH_QUIET);
1130 memset(&opts, 0, sizeof(opts));
1131 opts.head_idx = 1;
1132 opts.src_index = &the_index;
1133 opts.dst_index = &the_index;
1134 opts.update = 1;
1135 opts.merge = 1;
1136 opts.reset = reset;
1137 opts.fn = twoway_merge;
1138 init_tree_desc(&t[0], head->buffer, head->size);
1139 init_tree_desc(&t[1], remote->buffer, remote->size);
1141 if (unpack_trees(2, t, &opts)) {
1142 rollback_lock_file(lock_file);
1143 return -1;
1146 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1147 die(_("unable to write new index file"));
1149 return 0;
1153 * Clean the index without touching entries that are not modified between
1154 * `head` and `remote`.
1156 static int clean_index(const unsigned char *head, const unsigned char *remote)
1158 struct lock_file *lock_file;
1159 struct tree *head_tree, *remote_tree, *index_tree;
1160 unsigned char index[GIT_SHA1_RAWSZ];
1161 struct pathspec pathspec;
1163 head_tree = parse_tree_indirect(head);
1164 if (!head_tree)
1165 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1167 remote_tree = parse_tree_indirect(remote);
1168 if (!remote_tree)
1169 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1171 read_cache_unmerged();
1173 if (fast_forward_to(head_tree, head_tree, 1))
1174 return -1;
1176 if (write_cache_as_tree(index, 0, NULL))
1177 return -1;
1179 index_tree = parse_tree_indirect(index);
1180 if (!index_tree)
1181 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1183 if (fast_forward_to(index_tree, remote_tree, 0))
1184 return -1;
1186 memset(&pathspec, 0, sizeof(pathspec));
1188 lock_file = xcalloc(1, sizeof(struct lock_file));
1189 hold_locked_index(lock_file, 1);
1191 if (read_tree(remote_tree, 0, &pathspec)) {
1192 rollback_lock_file(lock_file);
1193 return -1;
1196 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1197 die(_("unable to write new index file"));
1199 remove_branch_state();
1201 return 0;
1205 * Resume the current am session by skipping the current patch.
1207 static void am_skip(struct am_state *state)
1209 unsigned char head[GIT_SHA1_RAWSZ];
1211 if (get_sha1("HEAD", head))
1212 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1214 if (clean_index(head, head))
1215 die(_("failed to clean index"));
1217 am_next(state);
1218 am_run(state, 0);
1222 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1224 * It is not safe to reset HEAD when:
1225 * 1. git-am previously failed because the index was dirty.
1226 * 2. HEAD has moved since git-am previously failed.
1228 static int safe_to_abort(const struct am_state *state)
1230 struct strbuf sb = STRBUF_INIT;
1231 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1233 if (file_exists(am_path(state, "dirtyindex")))
1234 return 0;
1236 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1237 if (get_sha1_hex(sb.buf, abort_safety))
1238 die(_("could not parse %s"), am_path(state, "abort_safety"));
1239 } else
1240 hashclr(abort_safety);
1242 if (get_sha1("HEAD", head))
1243 hashclr(head);
1245 if (!hashcmp(head, abort_safety))
1246 return 1;
1248 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1249 "Not rewinding to ORIG_HEAD"));
1251 return 0;
1255 * Aborts the current am session if it is safe to do so.
1257 static void am_abort(struct am_state *state)
1259 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1260 int has_curr_head, has_orig_head;
1261 char *curr_branch;
1263 if (!safe_to_abort(state)) {
1264 am_destroy(state);
1265 return;
1268 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1269 has_curr_head = !is_null_sha1(curr_head);
1270 if (!has_curr_head)
1271 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1273 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1274 if (!has_orig_head)
1275 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1277 clean_index(curr_head, orig_head);
1279 if (has_orig_head)
1280 update_ref("am --abort", "HEAD", orig_head,
1281 has_curr_head ? curr_head : NULL, 0,
1282 UPDATE_REFS_DIE_ON_ERR);
1283 else if (curr_branch)
1284 delete_ref(curr_branch, NULL, REF_NODEREF);
1286 free(curr_branch);
1287 am_destroy(state);
1291 * parse_options() callback that validates and sets opt->value to the
1292 * PATCH_FORMAT_* enum value corresponding to `arg`.
1294 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1296 int *opt_value = opt->value;
1298 if (!strcmp(arg, "mbox"))
1299 *opt_value = PATCH_FORMAT_MBOX;
1300 else
1301 return error(_("Invalid value for --patch-format: %s"), arg);
1302 return 0;
1305 enum resume_mode {
1306 RESUME_FALSE = 0,
1307 RESUME_APPLY,
1308 RESUME_RESOLVED,
1309 RESUME_SKIP,
1310 RESUME_ABORT
1313 int cmd_am(int argc, const char **argv, const char *prefix)
1315 struct am_state state;
1316 int patch_format = PATCH_FORMAT_UNKNOWN;
1317 enum resume_mode resume = RESUME_FALSE;
1319 const char * const usage[] = {
1320 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1321 N_("git am [options] (--continue | --skip | --abort)"),
1322 NULL
1325 struct option options[] = {
1326 OPT_BOOL('3', "3way", &state.threeway,
1327 N_("allow fall back on 3way merging if needed")),
1328 OPT__QUIET(&state.quiet, N_("be quiet")),
1329 OPT_BOOL('s', "signoff", &state.signoff,
1330 N_("add a Signed-off-by line to the commit message")),
1331 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1332 N_("format the patch(es) are in"),
1333 parse_opt_patchformat),
1334 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1335 N_("override error message when patch failure occurs")),
1336 OPT_CMDMODE(0, "continue", &resume,
1337 N_("continue applying patches after resolving a conflict"),
1338 RESUME_RESOLVED),
1339 OPT_CMDMODE('r', "resolved", &resume,
1340 N_("synonyms for --continue"),
1341 RESUME_RESOLVED),
1342 OPT_CMDMODE(0, "skip", &resume,
1343 N_("skip the current patch"),
1344 RESUME_SKIP),
1345 OPT_CMDMODE(0, "abort", &resume,
1346 N_("restore the original branch and abort the patching operation."),
1347 RESUME_ABORT),
1348 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1349 N_("(internal use for git-rebase)")),
1350 OPT_END()
1354 * NEEDSWORK: Once all the features of git-am.sh have been
1355 * re-implemented in builtin/am.c, this preamble can be removed.
1357 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1358 const char *path = mkpath("%s/git-am", git_exec_path());
1360 if (sane_execvp(path, (char **)argv) < 0)
1361 die_errno("could not exec %s", path);
1362 } else {
1363 prefix = setup_git_directory();
1364 trace_repo_setup(prefix);
1365 setup_work_tree();
1368 git_config(git_default_config, NULL);
1370 am_state_init(&state, git_path("rebase-apply"));
1372 argc = parse_options(argc, argv, prefix, options, usage, 0);
1374 if (read_index_preload(&the_index, NULL) < 0)
1375 die(_("failed to read the index"));
1377 if (am_in_progress(&state)) {
1379 * Catch user error to feed us patches when there is a session
1380 * in progress:
1382 * 1. mbox path(s) are provided on the command-line.
1383 * 2. stdin is not a tty: the user is trying to feed us a patch
1384 * from standard input. This is somewhat unreliable -- stdin
1385 * could be /dev/null for example and the caller did not
1386 * intend to feed us a patch but wanted to continue
1387 * unattended.
1389 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1390 die(_("previous rebase directory %s still exists but mbox given."),
1391 state.dir);
1393 if (resume == RESUME_FALSE)
1394 resume = RESUME_APPLY;
1396 am_load(&state);
1397 } else {
1398 struct argv_array paths = ARGV_ARRAY_INIT;
1399 int i;
1401 if (resume)
1402 die(_("Resolve operation not in progress, we are not resuming."));
1404 for (i = 0; i < argc; i++) {
1405 if (is_absolute_path(argv[i]) || !prefix)
1406 argv_array_push(&paths, argv[i]);
1407 else
1408 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1411 am_setup(&state, patch_format, paths.argv);
1413 argv_array_clear(&paths);
1416 switch (resume) {
1417 case RESUME_FALSE:
1418 am_run(&state, 0);
1419 break;
1420 case RESUME_APPLY:
1421 am_run(&state, 1);
1422 break;
1423 case RESUME_RESOLVED:
1424 am_resolve(&state);
1425 break;
1426 case RESUME_SKIP:
1427 am_skip(&state);
1428 break;
1429 case RESUME_ABORT:
1430 am_abort(&state);
1431 break;
1432 default:
1433 die("BUG: invalid resume value");
1436 am_state_release(&state);
1438 return 0;