builtin-am: handle stray state directory
[git/mingw.git] / builtin / am.c
blob47dd4c7ddfac5e3ac5a0e3f671bb4c59c6be9c3f
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"
24 #include "revision.h"
25 #include "log-tree.h"
27 /**
28 * Returns 1 if the file is empty or does not exist, 0 otherwise.
30 static int is_empty_file(const char *filename)
32 struct stat st;
34 if (stat(filename, &st) < 0) {
35 if (errno == ENOENT)
36 return 1;
37 die_errno(_("could not stat %s"), filename);
40 return !st.st_size;
43 /**
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'))
49 return EOF;
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);
55 return 0;
58 /**
59 * Returns the length of the first line of msg.
61 static int linelen(const char *msg)
63 return strchrnul(msg, '\n') - msg;
66 enum patch_format {
67 PATCH_FORMAT_UNKNOWN = 0,
68 PATCH_FORMAT_MBOX
71 struct am_state {
72 /* state directory path */
73 char *dir;
75 /* current and last patch numbers, 1-indexed */
76 int cur;
77 int last;
79 /* commit metadata and message */
80 char *author_name;
81 char *author_email;
82 char *author_date;
83 char *msg;
84 size_t msg_len;
86 /* number of digits in patch filename */
87 int prec;
89 /* various operating modes and command line options */
90 int threeway;
91 int quiet;
92 int signoff;
93 const char *resolvemsg;
94 int rebasing;
97 /**
98 * Initializes am_state with the default values. The state directory is set to
99 * dir.
101 static void am_state_init(struct am_state *state, const char *dir)
103 memset(state, 0, sizeof(*state));
105 assert(dir);
106 state->dir = xstrdup(dir);
108 state->prec = 4;
112 * Releases memory allocated by an am_state.
114 static void am_state_release(struct am_state *state)
116 free(state->dir);
117 free(state->author_name);
118 free(state->author_email);
119 free(state->author_date);
120 free(state->msg);
124 * Returns path relative to the am_state directory.
126 static inline const char *am_path(const struct am_state *state, const char *path)
128 return mkpath("%s/%s", state->dir, path);
132 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
133 * at the end.
135 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
137 va_list ap;
139 va_start(ap, fmt);
140 if (!state->quiet) {
141 vfprintf(fp, fmt, ap);
142 putc('\n', fp);
144 va_end(ap);
148 * Returns 1 if there is an am session in progress, 0 otherwise.
150 static int am_in_progress(const struct am_state *state)
152 struct stat st;
154 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
155 return 0;
156 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
157 return 0;
158 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
159 return 0;
160 return 1;
164 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
165 * number of bytes read on success, -1 if the file does not exist. If `trim` is
166 * set, trailing whitespace will be removed.
168 static int read_state_file(struct strbuf *sb, const struct am_state *state,
169 const char *file, int trim)
171 strbuf_reset(sb);
173 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
174 if (trim)
175 strbuf_trim(sb);
177 return sb->len;
180 if (errno == ENOENT)
181 return -1;
183 die_errno(_("could not read '%s'"), am_path(state, file));
187 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
188 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
189 * match `key`. Returns NULL on failure.
191 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
192 * the author-script.
194 static char *read_shell_var(FILE *fp, const char *key)
196 struct strbuf sb = STRBUF_INIT;
197 const char *str;
199 if (strbuf_getline(&sb, fp, '\n'))
200 goto fail;
202 if (!skip_prefix(sb.buf, key, &str))
203 goto fail;
205 if (!skip_prefix(str, "=", &str))
206 goto fail;
208 strbuf_remove(&sb, 0, str - sb.buf);
210 str = sq_dequote(sb.buf);
211 if (!str)
212 goto fail;
214 return strbuf_detach(&sb, NULL);
216 fail:
217 strbuf_release(&sb);
218 return NULL;
222 * Reads and parses the state directory's "author-script" file, and sets
223 * state->author_name, state->author_email and state->author_date accordingly.
224 * Returns 0 on success, -1 if the file could not be parsed.
226 * The author script is of the format:
228 * GIT_AUTHOR_NAME='$author_name'
229 * GIT_AUTHOR_EMAIL='$author_email'
230 * GIT_AUTHOR_DATE='$author_date'
232 * where $author_name, $author_email and $author_date are quoted. We are strict
233 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
234 * script, and thus if the file differs from what this function expects, it is
235 * better to bail out than to do something that the user does not expect.
237 static int read_author_script(struct am_state *state)
239 const char *filename = am_path(state, "author-script");
240 FILE *fp;
242 assert(!state->author_name);
243 assert(!state->author_email);
244 assert(!state->author_date);
246 fp = fopen(filename, "r");
247 if (!fp) {
248 if (errno == ENOENT)
249 return 0;
250 die_errno(_("could not open '%s' for reading"), filename);
253 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
254 if (!state->author_name) {
255 fclose(fp);
256 return -1;
259 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
260 if (!state->author_email) {
261 fclose(fp);
262 return -1;
265 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
266 if (!state->author_date) {
267 fclose(fp);
268 return -1;
271 if (fgetc(fp) != EOF) {
272 fclose(fp);
273 return -1;
276 fclose(fp);
277 return 0;
281 * Saves state->author_name, state->author_email and state->author_date in the
282 * state directory's "author-script" file.
284 static void write_author_script(const struct am_state *state)
286 struct strbuf sb = STRBUF_INIT;
288 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
289 sq_quote_buf(&sb, state->author_name);
290 strbuf_addch(&sb, '\n');
292 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
293 sq_quote_buf(&sb, state->author_email);
294 strbuf_addch(&sb, '\n');
296 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
297 sq_quote_buf(&sb, state->author_date);
298 strbuf_addch(&sb, '\n');
300 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
302 strbuf_release(&sb);
306 * Reads the commit message from the state directory's "final-commit" file,
307 * setting state->msg to its contents and state->msg_len to the length of its
308 * contents in bytes.
310 * Returns 0 on success, -1 if the file does not exist.
312 static int read_commit_msg(struct am_state *state)
314 struct strbuf sb = STRBUF_INIT;
316 assert(!state->msg);
318 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
319 strbuf_release(&sb);
320 return -1;
323 state->msg = strbuf_detach(&sb, &state->msg_len);
324 return 0;
328 * Saves state->msg in the state directory's "final-commit" file.
330 static void write_commit_msg(const struct am_state *state)
332 int fd;
333 const char *filename = am_path(state, "final-commit");
335 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
336 if (write_in_full(fd, state->msg, state->msg_len) < 0)
337 die_errno(_("could not write to %s"), filename);
338 close(fd);
342 * Loads state from disk.
344 static void am_load(struct am_state *state)
346 struct strbuf sb = STRBUF_INIT;
348 if (read_state_file(&sb, state, "next", 1) < 0)
349 die("BUG: state file 'next' does not exist");
350 state->cur = strtol(sb.buf, NULL, 10);
352 if (read_state_file(&sb, state, "last", 1) < 0)
353 die("BUG: state file 'last' does not exist");
354 state->last = strtol(sb.buf, NULL, 10);
356 if (read_author_script(state) < 0)
357 die(_("could not parse author script"));
359 read_commit_msg(state);
361 read_state_file(&sb, state, "threeway", 1);
362 state->threeway = !strcmp(sb.buf, "t");
364 read_state_file(&sb, state, "quiet", 1);
365 state->quiet = !strcmp(sb.buf, "t");
367 read_state_file(&sb, state, "sign", 1);
368 state->signoff = !strcmp(sb.buf, "t");
370 state->rebasing = !!file_exists(am_path(state, "rebasing"));
372 strbuf_release(&sb);
376 * Removes the am_state directory, forcefully terminating the current am
377 * session.
379 static void am_destroy(const struct am_state *state)
381 struct strbuf sb = STRBUF_INIT;
383 strbuf_addstr(&sb, state->dir);
384 remove_dir_recursively(&sb, 0);
385 strbuf_release(&sb);
389 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
390 * non-indented lines and checking if they look like they begin with valid
391 * header field names.
393 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
395 static int is_mail(FILE *fp)
397 const char *header_regex = "^[!-9;-~]+:";
398 struct strbuf sb = STRBUF_INIT;
399 regex_t regex;
400 int ret = 1;
402 if (fseek(fp, 0L, SEEK_SET))
403 die_errno(_("fseek failed"));
405 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
406 die("invalid pattern: %s", header_regex);
408 while (!strbuf_getline_crlf(&sb, fp)) {
409 if (!sb.len)
410 break; /* End of header */
412 /* Ignore indented folded lines */
413 if (*sb.buf == '\t' || *sb.buf == ' ')
414 continue;
416 /* It's a header if it matches header_regex */
417 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
418 ret = 0;
419 goto done;
423 done:
424 regfree(&regex);
425 strbuf_release(&sb);
426 return ret;
430 * Attempts to detect the patch_format of the patches contained in `paths`,
431 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
432 * detection fails.
434 static int detect_patch_format(const char **paths)
436 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
437 struct strbuf l1 = STRBUF_INIT;
438 FILE *fp;
441 * We default to mbox format if input is from stdin and for directories
443 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
444 return PATCH_FORMAT_MBOX;
447 * Otherwise, check the first few lines of the first patch, starting
448 * from the first non-blank line, to try to detect its format.
451 fp = xfopen(*paths, "r");
453 while (!strbuf_getline_crlf(&l1, fp)) {
454 if (l1.len)
455 break;
458 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
459 ret = PATCH_FORMAT_MBOX;
460 goto done;
463 if (l1.len && is_mail(fp)) {
464 ret = PATCH_FORMAT_MBOX;
465 goto done;
468 done:
469 fclose(fp);
470 strbuf_release(&l1);
471 return ret;
475 * Splits out individual email patches from `paths`, where each path is either
476 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
478 static int split_mail_mbox(struct am_state *state, const char **paths)
480 struct child_process cp = CHILD_PROCESS_INIT;
481 struct strbuf last = STRBUF_INIT;
483 cp.git_cmd = 1;
484 argv_array_push(&cp.args, "mailsplit");
485 argv_array_pushf(&cp.args, "-d%d", state->prec);
486 argv_array_pushf(&cp.args, "-o%s", state->dir);
487 argv_array_push(&cp.args, "-b");
488 argv_array_push(&cp.args, "--");
489 argv_array_pushv(&cp.args, paths);
491 if (capture_command(&cp, &last, 8))
492 return -1;
494 state->cur = 1;
495 state->last = strtol(last.buf, NULL, 10);
497 return 0;
501 * Splits a list of files/directories into individual email patches. Each path
502 * in `paths` must be a file/directory that is formatted according to
503 * `patch_format`.
505 * Once split out, the individual email patches will be stored in the state
506 * directory, with each patch's filename being its index, padded to state->prec
507 * digits.
509 * state->cur will be set to the index of the first mail, and state->last will
510 * be set to the index of the last mail.
512 * Returns 0 on success, -1 on failure.
514 static int split_mail(struct am_state *state, enum patch_format patch_format,
515 const char **paths)
517 switch (patch_format) {
518 case PATCH_FORMAT_MBOX:
519 return split_mail_mbox(state, paths);
520 default:
521 die("BUG: invalid patch_format");
523 return -1;
527 * Setup a new am session for applying patches
529 static void am_setup(struct am_state *state, enum patch_format patch_format,
530 const char **paths)
532 unsigned char curr_head[GIT_SHA1_RAWSZ];
534 if (!patch_format)
535 patch_format = detect_patch_format(paths);
537 if (!patch_format) {
538 fprintf_ln(stderr, _("Patch format detection failed."));
539 exit(128);
542 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
543 die_errno(_("failed to create directory '%s'"), state->dir);
545 if (split_mail(state, patch_format, paths) < 0) {
546 am_destroy(state);
547 die(_("Failed to split patches."));
550 if (state->rebasing)
551 state->threeway = 1;
553 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
555 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
557 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
559 if (state->rebasing)
560 write_file(am_path(state, "rebasing"), 1, "%s", "");
561 else
562 write_file(am_path(state, "applying"), 1, "%s", "");
564 if (!get_sha1("HEAD", curr_head)) {
565 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
566 if (!state->rebasing)
567 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
568 UPDATE_REFS_DIE_ON_ERR);
569 } else {
570 write_file(am_path(state, "abort-safety"), 1, "%s", "");
571 if (!state->rebasing)
572 delete_ref("ORIG_HEAD", NULL, 0);
576 * NOTE: Since the "next" and "last" files determine if an am_state
577 * session is in progress, they should be written last.
580 write_file(am_path(state, "next"), 1, "%d", state->cur);
582 write_file(am_path(state, "last"), 1, "%d", state->last);
586 * Increments the patch pointer, and cleans am_state for the application of the
587 * next patch.
589 static void am_next(struct am_state *state)
591 unsigned char head[GIT_SHA1_RAWSZ];
593 free(state->author_name);
594 state->author_name = NULL;
596 free(state->author_email);
597 state->author_email = NULL;
599 free(state->author_date);
600 state->author_date = NULL;
602 free(state->msg);
603 state->msg = NULL;
604 state->msg_len = 0;
606 unlink(am_path(state, "author-script"));
607 unlink(am_path(state, "final-commit"));
609 if (!get_sha1("HEAD", head))
610 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
611 else
612 write_file(am_path(state, "abort-safety"), 1, "%s", "");
614 state->cur++;
615 write_file(am_path(state, "next"), 1, "%d", state->cur);
619 * Returns the filename of the current patch email.
621 static const char *msgnum(const struct am_state *state)
623 static struct strbuf sb = STRBUF_INIT;
625 strbuf_reset(&sb);
626 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
628 return sb.buf;
632 * Refresh and write index.
634 static void refresh_and_write_cache(void)
636 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
638 hold_locked_index(lock_file, 1);
639 refresh_cache(REFRESH_QUIET);
640 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
641 die(_("unable to write index file"));
645 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
646 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
647 * strbuf is provided, the space-separated list of files that differ will be
648 * appended to it.
650 static int index_has_changes(struct strbuf *sb)
652 unsigned char head[GIT_SHA1_RAWSZ];
653 int i;
655 if (!get_sha1_tree("HEAD", head)) {
656 struct diff_options opt;
658 diff_setup(&opt);
659 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
660 if (!sb)
661 DIFF_OPT_SET(&opt, QUICK);
662 do_diff_cache(head, &opt);
663 diffcore_std(&opt);
664 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
665 if (i)
666 strbuf_addch(sb, ' ');
667 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
669 diff_flush(&opt);
670 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
671 } else {
672 for (i = 0; sb && i < active_nr; i++) {
673 if (i)
674 strbuf_addch(sb, ' ');
675 strbuf_addstr(sb, active_cache[i]->name);
677 return !!active_nr;
682 * Dies with a user-friendly message on how to proceed after resolving the
683 * problem. This message can be overridden with state->resolvemsg.
685 static void NORETURN die_user_resolve(const struct am_state *state)
687 if (state->resolvemsg) {
688 printf_ln("%s", state->resolvemsg);
689 } else {
690 const char *cmdline = "git am";
692 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
693 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
694 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
697 exit(128);
701 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
702 * state->msg will be set to the patch message. state->author_name,
703 * state->author_email and state->author_date will be set to the patch author's
704 * name, email and date respectively. The patch body will be written to the
705 * state directory's "patch" file.
707 * Returns 1 if the patch should be skipped, 0 otherwise.
709 static int parse_mail(struct am_state *state, const char *mail)
711 FILE *fp;
712 struct child_process cp = CHILD_PROCESS_INIT;
713 struct strbuf sb = STRBUF_INIT;
714 struct strbuf msg = STRBUF_INIT;
715 struct strbuf author_name = STRBUF_INIT;
716 struct strbuf author_date = STRBUF_INIT;
717 struct strbuf author_email = STRBUF_INIT;
718 int ret = 0;
720 cp.git_cmd = 1;
721 cp.in = xopen(mail, O_RDONLY, 0);
722 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
724 argv_array_push(&cp.args, "mailinfo");
725 argv_array_push(&cp.args, am_path(state, "msg"));
726 argv_array_push(&cp.args, am_path(state, "patch"));
728 if (run_command(&cp) < 0)
729 die("could not parse patch");
731 close(cp.in);
732 close(cp.out);
734 /* Extract message and author information */
735 fp = xfopen(am_path(state, "info"), "r");
736 while (!strbuf_getline(&sb, fp, '\n')) {
737 const char *x;
739 if (skip_prefix(sb.buf, "Subject: ", &x)) {
740 if (msg.len)
741 strbuf_addch(&msg, '\n');
742 strbuf_addstr(&msg, x);
743 } else if (skip_prefix(sb.buf, "Author: ", &x))
744 strbuf_addstr(&author_name, x);
745 else if (skip_prefix(sb.buf, "Email: ", &x))
746 strbuf_addstr(&author_email, x);
747 else if (skip_prefix(sb.buf, "Date: ", &x))
748 strbuf_addstr(&author_date, x);
750 fclose(fp);
752 /* Skip pine's internal folder data */
753 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
754 ret = 1;
755 goto finish;
758 if (is_empty_file(am_path(state, "patch"))) {
759 printf_ln(_("Patch is empty. Was it split wrong?"));
760 die_user_resolve(state);
763 strbuf_addstr(&msg, "\n\n");
764 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
765 die_errno(_("could not read '%s'"), am_path(state, "msg"));
766 stripspace(&msg, 0);
768 if (state->signoff)
769 append_signoff(&msg, 0, 0);
771 assert(!state->author_name);
772 state->author_name = strbuf_detach(&author_name, NULL);
774 assert(!state->author_email);
775 state->author_email = strbuf_detach(&author_email, NULL);
777 assert(!state->author_date);
778 state->author_date = strbuf_detach(&author_date, NULL);
780 assert(!state->msg);
781 state->msg = strbuf_detach(&msg, &state->msg_len);
783 finish:
784 strbuf_release(&msg);
785 strbuf_release(&author_date);
786 strbuf_release(&author_email);
787 strbuf_release(&author_name);
788 strbuf_release(&sb);
789 return ret;
793 * Sets commit_id to the commit hash where the mail was generated from.
794 * Returns 0 on success, -1 on failure.
796 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
798 struct strbuf sb = STRBUF_INIT;
799 FILE *fp = xfopen(mail, "r");
800 const char *x;
802 if (strbuf_getline(&sb, fp, '\n'))
803 return -1;
805 if (!skip_prefix(sb.buf, "From ", &x))
806 return -1;
808 if (get_sha1_hex(x, commit_id) < 0)
809 return -1;
811 strbuf_release(&sb);
812 fclose(fp);
813 return 0;
817 * Sets state->msg, state->author_name, state->author_email, state->author_date
818 * to the commit's respective info.
820 static void get_commit_info(struct am_state *state, struct commit *commit)
822 const char *buffer, *ident_line, *author_date, *msg;
823 size_t ident_len;
824 struct ident_split ident_split;
825 struct strbuf sb = STRBUF_INIT;
827 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
829 ident_line = find_commit_header(buffer, "author", &ident_len);
831 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
832 strbuf_add(&sb, ident_line, ident_len);
833 die(_("invalid ident line: %s"), sb.buf);
836 assert(!state->author_name);
837 if (ident_split.name_begin) {
838 strbuf_add(&sb, ident_split.name_begin,
839 ident_split.name_end - ident_split.name_begin);
840 state->author_name = strbuf_detach(&sb, NULL);
841 } else
842 state->author_name = xstrdup("");
844 assert(!state->author_email);
845 if (ident_split.mail_begin) {
846 strbuf_add(&sb, ident_split.mail_begin,
847 ident_split.mail_end - ident_split.mail_begin);
848 state->author_email = strbuf_detach(&sb, NULL);
849 } else
850 state->author_email = xstrdup("");
852 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
853 strbuf_addstr(&sb, author_date);
854 assert(!state->author_date);
855 state->author_date = strbuf_detach(&sb, NULL);
857 assert(!state->msg);
858 msg = strstr(buffer, "\n\n");
859 if (!msg)
860 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
861 state->msg = xstrdup(msg + 2);
862 state->msg_len = strlen(state->msg);
866 * Writes `commit` as a patch to the state directory's "patch" file.
868 static void write_commit_patch(const struct am_state *state, struct commit *commit)
870 struct rev_info rev_info;
871 FILE *fp;
873 fp = xfopen(am_path(state, "patch"), "w");
874 init_revisions(&rev_info, NULL);
875 rev_info.diff = 1;
876 rev_info.abbrev = 0;
877 rev_info.disable_stdin = 1;
878 rev_info.show_root_diff = 1;
879 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
880 rev_info.no_commit_id = 1;
881 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
882 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
883 rev_info.diffopt.use_color = 0;
884 rev_info.diffopt.file = fp;
885 rev_info.diffopt.close_file = 1;
886 add_pending_object(&rev_info, &commit->object, "");
887 diff_setup_done(&rev_info.diffopt);
888 log_tree_commit(&rev_info, commit);
892 * Like parse_mail(), but parses the mail by looking up its commit ID
893 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
894 * of patches.
896 * Will always return 0 as the patch should never be skipped.
898 static int parse_mail_rebase(struct am_state *state, const char *mail)
900 struct commit *commit;
901 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
903 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
904 die(_("could not parse %s"), mail);
906 commit = lookup_commit_or_die(commit_sha1, mail);
908 get_commit_info(state, commit);
910 write_commit_patch(state, commit);
912 return 0;
916 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
917 * `index_file` is not NULL, the patch will be applied to that index.
919 static int run_apply(const struct am_state *state, const char *index_file)
921 struct child_process cp = CHILD_PROCESS_INIT;
923 cp.git_cmd = 1;
925 if (index_file)
926 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
929 * If we are allowed to fall back on 3-way merge, don't give false
930 * errors during the initial attempt.
932 if (state->threeway && !index_file) {
933 cp.no_stdout = 1;
934 cp.no_stderr = 1;
937 argv_array_push(&cp.args, "apply");
939 if (index_file)
940 argv_array_push(&cp.args, "--cached");
941 else
942 argv_array_push(&cp.args, "--index");
944 argv_array_push(&cp.args, am_path(state, "patch"));
946 if (run_command(&cp))
947 return -1;
949 /* Reload index as git-apply will have modified it. */
950 discard_cache();
951 read_cache_from(index_file ? index_file : get_index_file());
953 return 0;
957 * Builds an index that contains just the blobs needed for a 3way merge.
959 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
961 struct child_process cp = CHILD_PROCESS_INIT;
963 cp.git_cmd = 1;
964 argv_array_push(&cp.args, "apply");
965 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
966 argv_array_push(&cp.args, am_path(state, "patch"));
968 if (run_command(&cp))
969 return -1;
971 return 0;
975 * Attempt a threeway merge, using index_path as the temporary index.
977 static int fall_back_threeway(const struct am_state *state, const char *index_path)
979 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
980 our_tree[GIT_SHA1_RAWSZ];
981 const unsigned char *bases[1] = {orig_tree};
982 struct merge_options o;
983 struct commit *result;
984 char *his_tree_name;
986 if (get_sha1("HEAD", our_tree) < 0)
987 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
989 if (build_fake_ancestor(state, index_path))
990 return error("could not build fake ancestor");
992 discard_cache();
993 read_cache_from(index_path);
995 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
996 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
998 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1000 if (!state->quiet) {
1002 * List paths that needed 3-way fallback, so that the user can
1003 * review them with extra care to spot mismerges.
1005 struct rev_info rev_info;
1006 const char *diff_filter_str = "--diff-filter=AM";
1008 init_revisions(&rev_info, NULL);
1009 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1010 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1011 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1012 diff_setup_done(&rev_info.diffopt);
1013 run_diff_index(&rev_info, 1);
1016 if (run_apply(state, index_path))
1017 return error(_("Did you hand edit your patch?\n"
1018 "It does not apply to blobs recorded in its index."));
1020 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1021 return error("could not write tree");
1023 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1025 discard_cache();
1026 read_cache();
1029 * This is not so wrong. Depending on which base we picked, orig_tree
1030 * may be wildly different from ours, but his_tree has the same set of
1031 * wildly different changes in parts the patch did not touch, so
1032 * recursive ends up canceling them, saying that we reverted all those
1033 * changes.
1036 init_merge_options(&o);
1038 o.branch1 = "HEAD";
1039 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1040 o.branch2 = his_tree_name;
1042 if (state->quiet)
1043 o.verbosity = 0;
1045 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1046 free(his_tree_name);
1047 return error(_("Failed to merge in the changes."));
1050 free(his_tree_name);
1051 return 0;
1055 * Commits the current index with state->msg as the commit message and
1056 * state->author_name, state->author_email and state->author_date as the author
1057 * information.
1059 static void do_commit(const struct am_state *state)
1061 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1062 commit[GIT_SHA1_RAWSZ];
1063 unsigned char *ptr;
1064 struct commit_list *parents = NULL;
1065 const char *reflog_msg, *author;
1066 struct strbuf sb = STRBUF_INIT;
1068 if (write_cache_as_tree(tree, 0, NULL))
1069 die(_("git write-tree failed to write a tree"));
1071 if (!get_sha1_commit("HEAD", parent)) {
1072 ptr = parent;
1073 commit_list_insert(lookup_commit(parent), &parents);
1074 } else {
1075 ptr = NULL;
1076 say(state, stderr, _("applying to an empty history"));
1079 author = fmt_ident(state->author_name, state->author_email,
1080 state->author_date, IDENT_STRICT);
1082 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1083 author, NULL))
1084 die(_("failed to write commit object"));
1086 reflog_msg = getenv("GIT_REFLOG_ACTION");
1087 if (!reflog_msg)
1088 reflog_msg = "am";
1090 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1091 state->msg);
1093 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1095 strbuf_release(&sb);
1099 * Validates the am_state for resuming -- the "msg" and authorship fields must
1100 * be filled up.
1102 static void validate_resume_state(const struct am_state *state)
1104 if (!state->msg)
1105 die(_("cannot resume: %s does not exist."),
1106 am_path(state, "final-commit"));
1108 if (!state->author_name || !state->author_email || !state->author_date)
1109 die(_("cannot resume: %s does not exist."),
1110 am_path(state, "author-script"));
1114 * Applies all queued mail.
1116 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1117 * well as the state directory's "patch" file is used as-is for applying the
1118 * patch and committing it.
1120 static void am_run(struct am_state *state, int resume)
1122 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1123 struct strbuf sb = STRBUF_INIT;
1125 unlink(am_path(state, "dirtyindex"));
1127 refresh_and_write_cache();
1129 if (index_has_changes(&sb)) {
1130 write_file(am_path(state, "dirtyindex"), 1, "t");
1131 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1134 strbuf_release(&sb);
1136 while (state->cur <= state->last) {
1137 const char *mail = am_path(state, msgnum(state));
1138 int apply_status;
1140 if (!file_exists(mail))
1141 goto next;
1143 if (resume) {
1144 validate_resume_state(state);
1145 resume = 0;
1146 } else {
1147 int skip;
1149 if (state->rebasing)
1150 skip = parse_mail_rebase(state, mail);
1151 else
1152 skip = parse_mail(state, mail);
1154 if (skip)
1155 goto next; /* mail should be skipped */
1157 write_author_script(state);
1158 write_commit_msg(state);
1161 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1163 apply_status = run_apply(state, NULL);
1165 if (apply_status && state->threeway) {
1166 struct strbuf sb = STRBUF_INIT;
1168 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1169 apply_status = fall_back_threeway(state, sb.buf);
1170 strbuf_release(&sb);
1173 * Applying the patch to an earlier tree and merging
1174 * the result may have produced the same tree as ours.
1176 if (!apply_status && !index_has_changes(NULL)) {
1177 say(state, stdout, _("No changes -- Patch already applied."));
1178 goto next;
1182 if (apply_status) {
1183 int advice_amworkdir = 1;
1185 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1186 linelen(state->msg), state->msg);
1188 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1190 if (advice_amworkdir)
1191 printf_ln(_("The copy of the patch that failed is found in: %s"),
1192 am_path(state, "patch"));
1194 die_user_resolve(state);
1197 do_commit(state);
1199 next:
1200 am_next(state);
1204 * In rebasing mode, it's up to the caller to take care of
1205 * housekeeping.
1207 if (!state->rebasing) {
1208 am_destroy(state);
1209 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1214 * Resume the current am session after patch application failure. The user did
1215 * all the hard work, and we do not have to do any patch application. Just
1216 * trust and commit what the user has in the index and working tree.
1218 static void am_resolve(struct am_state *state)
1220 validate_resume_state(state);
1222 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1224 if (!index_has_changes(NULL)) {
1225 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1226 "If there is nothing left to stage, chances are that something else\n"
1227 "already introduced the same changes; you might want to skip this patch."));
1228 die_user_resolve(state);
1231 if (unmerged_cache()) {
1232 printf_ln(_("You still have unmerged paths in your index.\n"
1233 "Did you forget to use 'git add'?"));
1234 die_user_resolve(state);
1237 do_commit(state);
1239 am_next(state);
1240 am_run(state, 0);
1244 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1245 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1246 * failure.
1248 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1250 struct lock_file *lock_file;
1251 struct unpack_trees_options opts;
1252 struct tree_desc t[2];
1254 if (parse_tree(head) || parse_tree(remote))
1255 return -1;
1257 lock_file = xcalloc(1, sizeof(struct lock_file));
1258 hold_locked_index(lock_file, 1);
1260 refresh_cache(REFRESH_QUIET);
1262 memset(&opts, 0, sizeof(opts));
1263 opts.head_idx = 1;
1264 opts.src_index = &the_index;
1265 opts.dst_index = &the_index;
1266 opts.update = 1;
1267 opts.merge = 1;
1268 opts.reset = reset;
1269 opts.fn = twoway_merge;
1270 init_tree_desc(&t[0], head->buffer, head->size);
1271 init_tree_desc(&t[1], remote->buffer, remote->size);
1273 if (unpack_trees(2, t, &opts)) {
1274 rollback_lock_file(lock_file);
1275 return -1;
1278 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1279 die(_("unable to write new index file"));
1281 return 0;
1285 * Clean the index without touching entries that are not modified between
1286 * `head` and `remote`.
1288 static int clean_index(const unsigned char *head, const unsigned char *remote)
1290 struct lock_file *lock_file;
1291 struct tree *head_tree, *remote_tree, *index_tree;
1292 unsigned char index[GIT_SHA1_RAWSZ];
1293 struct pathspec pathspec;
1295 head_tree = parse_tree_indirect(head);
1296 if (!head_tree)
1297 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1299 remote_tree = parse_tree_indirect(remote);
1300 if (!remote_tree)
1301 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1303 read_cache_unmerged();
1305 if (fast_forward_to(head_tree, head_tree, 1))
1306 return -1;
1308 if (write_cache_as_tree(index, 0, NULL))
1309 return -1;
1311 index_tree = parse_tree_indirect(index);
1312 if (!index_tree)
1313 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1315 if (fast_forward_to(index_tree, remote_tree, 0))
1316 return -1;
1318 memset(&pathspec, 0, sizeof(pathspec));
1320 lock_file = xcalloc(1, sizeof(struct lock_file));
1321 hold_locked_index(lock_file, 1);
1323 if (read_tree(remote_tree, 0, &pathspec)) {
1324 rollback_lock_file(lock_file);
1325 return -1;
1328 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1329 die(_("unable to write new index file"));
1331 remove_branch_state();
1333 return 0;
1337 * Resume the current am session by skipping the current patch.
1339 static void am_skip(struct am_state *state)
1341 unsigned char head[GIT_SHA1_RAWSZ];
1343 if (get_sha1("HEAD", head))
1344 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1346 if (clean_index(head, head))
1347 die(_("failed to clean index"));
1349 am_next(state);
1350 am_run(state, 0);
1354 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1356 * It is not safe to reset HEAD when:
1357 * 1. git-am previously failed because the index was dirty.
1358 * 2. HEAD has moved since git-am previously failed.
1360 static int safe_to_abort(const struct am_state *state)
1362 struct strbuf sb = STRBUF_INIT;
1363 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1365 if (file_exists(am_path(state, "dirtyindex")))
1366 return 0;
1368 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1369 if (get_sha1_hex(sb.buf, abort_safety))
1370 die(_("could not parse %s"), am_path(state, "abort_safety"));
1371 } else
1372 hashclr(abort_safety);
1374 if (get_sha1("HEAD", head))
1375 hashclr(head);
1377 if (!hashcmp(head, abort_safety))
1378 return 1;
1380 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1381 "Not rewinding to ORIG_HEAD"));
1383 return 0;
1387 * Aborts the current am session if it is safe to do so.
1389 static void am_abort(struct am_state *state)
1391 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1392 int has_curr_head, has_orig_head;
1393 char *curr_branch;
1395 if (!safe_to_abort(state)) {
1396 am_destroy(state);
1397 return;
1400 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1401 has_curr_head = !is_null_sha1(curr_head);
1402 if (!has_curr_head)
1403 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1405 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1406 if (!has_orig_head)
1407 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1409 clean_index(curr_head, orig_head);
1411 if (has_orig_head)
1412 update_ref("am --abort", "HEAD", orig_head,
1413 has_curr_head ? curr_head : NULL, 0,
1414 UPDATE_REFS_DIE_ON_ERR);
1415 else if (curr_branch)
1416 delete_ref(curr_branch, NULL, REF_NODEREF);
1418 free(curr_branch);
1419 am_destroy(state);
1423 * parse_options() callback that validates and sets opt->value to the
1424 * PATCH_FORMAT_* enum value corresponding to `arg`.
1426 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1428 int *opt_value = opt->value;
1430 if (!strcmp(arg, "mbox"))
1431 *opt_value = PATCH_FORMAT_MBOX;
1432 else
1433 return error(_("Invalid value for --patch-format: %s"), arg);
1434 return 0;
1437 enum resume_mode {
1438 RESUME_FALSE = 0,
1439 RESUME_APPLY,
1440 RESUME_RESOLVED,
1441 RESUME_SKIP,
1442 RESUME_ABORT
1445 int cmd_am(int argc, const char **argv, const char *prefix)
1447 struct am_state state;
1448 int patch_format = PATCH_FORMAT_UNKNOWN;
1449 enum resume_mode resume = RESUME_FALSE;
1451 const char * const usage[] = {
1452 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1453 N_("git am [options] (--continue | --skip | --abort)"),
1454 NULL
1457 struct option options[] = {
1458 OPT_BOOL('3', "3way", &state.threeway,
1459 N_("allow fall back on 3way merging if needed")),
1460 OPT__QUIET(&state.quiet, N_("be quiet")),
1461 OPT_BOOL('s', "signoff", &state.signoff,
1462 N_("add a Signed-off-by line to the commit message")),
1463 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1464 N_("format the patch(es) are in"),
1465 parse_opt_patchformat),
1466 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1467 N_("override error message when patch failure occurs")),
1468 OPT_CMDMODE(0, "continue", &resume,
1469 N_("continue applying patches after resolving a conflict"),
1470 RESUME_RESOLVED),
1471 OPT_CMDMODE('r', "resolved", &resume,
1472 N_("synonyms for --continue"),
1473 RESUME_RESOLVED),
1474 OPT_CMDMODE(0, "skip", &resume,
1475 N_("skip the current patch"),
1476 RESUME_SKIP),
1477 OPT_CMDMODE(0, "abort", &resume,
1478 N_("restore the original branch and abort the patching operation."),
1479 RESUME_ABORT),
1480 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1481 N_("(internal use for git-rebase)")),
1482 OPT_END()
1486 * NEEDSWORK: Once all the features of git-am.sh have been
1487 * re-implemented in builtin/am.c, this preamble can be removed.
1489 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1490 const char *path = mkpath("%s/git-am", git_exec_path());
1492 if (sane_execvp(path, (char **)argv) < 0)
1493 die_errno("could not exec %s", path);
1494 } else {
1495 prefix = setup_git_directory();
1496 trace_repo_setup(prefix);
1497 setup_work_tree();
1500 git_config(git_default_config, NULL);
1502 am_state_init(&state, git_path("rebase-apply"));
1504 argc = parse_options(argc, argv, prefix, options, usage, 0);
1506 if (read_index_preload(&the_index, NULL) < 0)
1507 die(_("failed to read the index"));
1509 if (am_in_progress(&state)) {
1511 * Catch user error to feed us patches when there is a session
1512 * in progress:
1514 * 1. mbox path(s) are provided on the command-line.
1515 * 2. stdin is not a tty: the user is trying to feed us a patch
1516 * from standard input. This is somewhat unreliable -- stdin
1517 * could be /dev/null for example and the caller did not
1518 * intend to feed us a patch but wanted to continue
1519 * unattended.
1521 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1522 die(_("previous rebase directory %s still exists but mbox given."),
1523 state.dir);
1525 if (resume == RESUME_FALSE)
1526 resume = RESUME_APPLY;
1528 am_load(&state);
1529 } else {
1530 struct argv_array paths = ARGV_ARRAY_INIT;
1531 int i;
1534 * Handle stray state directory in the independent-run case. In
1535 * the --rebasing case, it is up to the caller to take care of
1536 * stray directories.
1538 if (file_exists(state.dir) && !state.rebasing) {
1539 if (resume == RESUME_ABORT) {
1540 am_destroy(&state);
1541 am_state_release(&state);
1542 return 0;
1545 die(_("Stray %s directory found.\n"
1546 "Use \"git am --abort\" to remove it."),
1547 state.dir);
1550 if (resume)
1551 die(_("Resolve operation not in progress, we are not resuming."));
1553 for (i = 0; i < argc; i++) {
1554 if (is_absolute_path(argv[i]) || !prefix)
1555 argv_array_push(&paths, argv[i]);
1556 else
1557 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1560 am_setup(&state, patch_format, paths.argv);
1562 argv_array_clear(&paths);
1565 switch (resume) {
1566 case RESUME_FALSE:
1567 am_run(&state, 0);
1568 break;
1569 case RESUME_APPLY:
1570 am_run(&state, 1);
1571 break;
1572 case RESUME_RESOLVED:
1573 am_resolve(&state);
1574 break;
1575 case RESUME_SKIP:
1576 am_skip(&state);
1577 break;
1578 case RESUME_ABORT:
1579 am_abort(&state);
1580 break;
1581 default:
1582 die("BUG: invalid resume value");
1585 am_state_release(&state);
1587 return 0;