builtin-am: invoke applypatch-msg hook
[git/mingw/j6t.git] / builtin / am.c
blobf0e3aab9af55d2b4e2345cc2e26c8c5faae4bf9c
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"
26 #include "notes-utils.h"
28 /**
29 * Returns 1 if the file is empty or does not exist, 0 otherwise.
31 static int is_empty_file(const char *filename)
33 struct stat st;
35 if (stat(filename, &st) < 0) {
36 if (errno == ENOENT)
37 return 1;
38 die_errno(_("could not stat %s"), filename);
41 return !st.st_size;
44 /**
45 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
47 static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
49 if (strbuf_getwholeline(sb, fp, '\n'))
50 return EOF;
51 if (sb->buf[sb->len - 1] == '\n') {
52 strbuf_setlen(sb, sb->len - 1);
53 if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
54 strbuf_setlen(sb, sb->len - 1);
56 return 0;
59 /**
60 * Returns the length of the first line of msg.
62 static int linelen(const char *msg)
64 return strchrnul(msg, '\n') - msg;
67 enum patch_format {
68 PATCH_FORMAT_UNKNOWN = 0,
69 PATCH_FORMAT_MBOX
72 enum keep_type {
73 KEEP_FALSE = 0,
74 KEEP_TRUE, /* pass -k flag to git-mailinfo */
75 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
78 enum scissors_type {
79 SCISSORS_UNSET = -1,
80 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
81 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
84 struct am_state {
85 /* state directory path */
86 char *dir;
88 /* current and last patch numbers, 1-indexed */
89 int cur;
90 int last;
92 /* commit metadata and message */
93 char *author_name;
94 char *author_email;
95 char *author_date;
96 char *msg;
97 size_t msg_len;
99 /* when --rebasing, records the original commit the patch came from */
100 unsigned char orig_commit[GIT_SHA1_RAWSZ];
102 /* number of digits in patch filename */
103 int prec;
105 /* various operating modes and command line options */
106 int threeway;
107 int quiet;
108 int signoff;
109 int utf8;
110 int keep; /* enum keep_type */
111 int message_id;
112 int scissors; /* enum scissors_type */
113 struct argv_array git_apply_opts;
114 const char *resolvemsg;
115 int committer_date_is_author_date;
116 int ignore_date;
117 const char *sign_commit;
118 int rebasing;
122 * Initializes am_state with the default values. The state directory is set to
123 * dir.
125 static void am_state_init(struct am_state *state, const char *dir)
127 int gpgsign;
129 memset(state, 0, sizeof(*state));
131 assert(dir);
132 state->dir = xstrdup(dir);
134 state->prec = 4;
136 state->utf8 = 1;
138 git_config_get_bool("am.messageid", &state->message_id);
140 state->scissors = SCISSORS_UNSET;
142 argv_array_init(&state->git_apply_opts);
144 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
145 state->sign_commit = gpgsign ? "" : NULL;
149 * Releases memory allocated by an am_state.
151 static void am_state_release(struct am_state *state)
153 free(state->dir);
154 free(state->author_name);
155 free(state->author_email);
156 free(state->author_date);
157 free(state->msg);
158 argv_array_clear(&state->git_apply_opts);
162 * Returns path relative to the am_state directory.
164 static inline const char *am_path(const struct am_state *state, const char *path)
166 return mkpath("%s/%s", state->dir, path);
170 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
171 * at the end.
173 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
175 va_list ap;
177 va_start(ap, fmt);
178 if (!state->quiet) {
179 vfprintf(fp, fmt, ap);
180 putc('\n', fp);
182 va_end(ap);
186 * Returns 1 if there is an am session in progress, 0 otherwise.
188 static int am_in_progress(const struct am_state *state)
190 struct stat st;
192 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
193 return 0;
194 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
195 return 0;
196 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
197 return 0;
198 return 1;
202 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
203 * number of bytes read on success, -1 if the file does not exist. If `trim` is
204 * set, trailing whitespace will be removed.
206 static int read_state_file(struct strbuf *sb, const struct am_state *state,
207 const char *file, int trim)
209 strbuf_reset(sb);
211 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
212 if (trim)
213 strbuf_trim(sb);
215 return sb->len;
218 if (errno == ENOENT)
219 return -1;
221 die_errno(_("could not read '%s'"), am_path(state, file));
225 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
226 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
227 * match `key`. Returns NULL on failure.
229 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
230 * the author-script.
232 static char *read_shell_var(FILE *fp, const char *key)
234 struct strbuf sb = STRBUF_INIT;
235 const char *str;
237 if (strbuf_getline(&sb, fp, '\n'))
238 goto fail;
240 if (!skip_prefix(sb.buf, key, &str))
241 goto fail;
243 if (!skip_prefix(str, "=", &str))
244 goto fail;
246 strbuf_remove(&sb, 0, str - sb.buf);
248 str = sq_dequote(sb.buf);
249 if (!str)
250 goto fail;
252 return strbuf_detach(&sb, NULL);
254 fail:
255 strbuf_release(&sb);
256 return NULL;
260 * Reads and parses the state directory's "author-script" file, and sets
261 * state->author_name, state->author_email and state->author_date accordingly.
262 * Returns 0 on success, -1 if the file could not be parsed.
264 * The author script is of the format:
266 * GIT_AUTHOR_NAME='$author_name'
267 * GIT_AUTHOR_EMAIL='$author_email'
268 * GIT_AUTHOR_DATE='$author_date'
270 * where $author_name, $author_email and $author_date are quoted. We are strict
271 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
272 * script, and thus if the file differs from what this function expects, it is
273 * better to bail out than to do something that the user does not expect.
275 static int read_author_script(struct am_state *state)
277 const char *filename = am_path(state, "author-script");
278 FILE *fp;
280 assert(!state->author_name);
281 assert(!state->author_email);
282 assert(!state->author_date);
284 fp = fopen(filename, "r");
285 if (!fp) {
286 if (errno == ENOENT)
287 return 0;
288 die_errno(_("could not open '%s' for reading"), filename);
291 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
292 if (!state->author_name) {
293 fclose(fp);
294 return -1;
297 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
298 if (!state->author_email) {
299 fclose(fp);
300 return -1;
303 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
304 if (!state->author_date) {
305 fclose(fp);
306 return -1;
309 if (fgetc(fp) != EOF) {
310 fclose(fp);
311 return -1;
314 fclose(fp);
315 return 0;
319 * Saves state->author_name, state->author_email and state->author_date in the
320 * state directory's "author-script" file.
322 static void write_author_script(const struct am_state *state)
324 struct strbuf sb = STRBUF_INIT;
326 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
327 sq_quote_buf(&sb, state->author_name);
328 strbuf_addch(&sb, '\n');
330 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
331 sq_quote_buf(&sb, state->author_email);
332 strbuf_addch(&sb, '\n');
334 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
335 sq_quote_buf(&sb, state->author_date);
336 strbuf_addch(&sb, '\n');
338 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
340 strbuf_release(&sb);
344 * Reads the commit message from the state directory's "final-commit" file,
345 * setting state->msg to its contents and state->msg_len to the length of its
346 * contents in bytes.
348 * Returns 0 on success, -1 if the file does not exist.
350 static int read_commit_msg(struct am_state *state)
352 struct strbuf sb = STRBUF_INIT;
354 assert(!state->msg);
356 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
357 strbuf_release(&sb);
358 return -1;
361 state->msg = strbuf_detach(&sb, &state->msg_len);
362 return 0;
366 * Saves state->msg in the state directory's "final-commit" file.
368 static void write_commit_msg(const struct am_state *state)
370 int fd;
371 const char *filename = am_path(state, "final-commit");
373 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
374 if (write_in_full(fd, state->msg, state->msg_len) < 0)
375 die_errno(_("could not write to %s"), filename);
376 close(fd);
380 * Loads state from disk.
382 static void am_load(struct am_state *state)
384 struct strbuf sb = STRBUF_INIT;
386 if (read_state_file(&sb, state, "next", 1) < 0)
387 die("BUG: state file 'next' does not exist");
388 state->cur = strtol(sb.buf, NULL, 10);
390 if (read_state_file(&sb, state, "last", 1) < 0)
391 die("BUG: state file 'last' does not exist");
392 state->last = strtol(sb.buf, NULL, 10);
394 if (read_author_script(state) < 0)
395 die(_("could not parse author script"));
397 read_commit_msg(state);
399 if (read_state_file(&sb, state, "original-commit", 1) < 0)
400 hashclr(state->orig_commit);
401 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
402 die(_("could not parse %s"), am_path(state, "original-commit"));
404 read_state_file(&sb, state, "threeway", 1);
405 state->threeway = !strcmp(sb.buf, "t");
407 read_state_file(&sb, state, "quiet", 1);
408 state->quiet = !strcmp(sb.buf, "t");
410 read_state_file(&sb, state, "sign", 1);
411 state->signoff = !strcmp(sb.buf, "t");
413 read_state_file(&sb, state, "utf8", 1);
414 state->utf8 = !strcmp(sb.buf, "t");
416 read_state_file(&sb, state, "keep", 1);
417 if (!strcmp(sb.buf, "t"))
418 state->keep = KEEP_TRUE;
419 else if (!strcmp(sb.buf, "b"))
420 state->keep = KEEP_NON_PATCH;
421 else
422 state->keep = KEEP_FALSE;
424 read_state_file(&sb, state, "messageid", 1);
425 state->message_id = !strcmp(sb.buf, "t");
427 read_state_file(&sb, state, "scissors", 1);
428 if (!strcmp(sb.buf, "t"))
429 state->scissors = SCISSORS_TRUE;
430 else if (!strcmp(sb.buf, "f"))
431 state->scissors = SCISSORS_FALSE;
432 else
433 state->scissors = SCISSORS_UNSET;
435 read_state_file(&sb, state, "apply-opt", 1);
436 argv_array_clear(&state->git_apply_opts);
437 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
438 die(_("could not parse %s"), am_path(state, "apply-opt"));
440 state->rebasing = !!file_exists(am_path(state, "rebasing"));
442 strbuf_release(&sb);
446 * Removes the am_state directory, forcefully terminating the current am
447 * session.
449 static void am_destroy(const struct am_state *state)
451 struct strbuf sb = STRBUF_INIT;
453 strbuf_addstr(&sb, state->dir);
454 remove_dir_recursively(&sb, 0);
455 strbuf_release(&sb);
459 * Runs applypatch-msg hook. Returns its exit code.
461 static int run_applypatch_msg_hook(struct am_state *state)
463 int ret;
465 assert(state->msg);
466 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
468 if (!ret) {
469 free(state->msg);
470 state->msg = NULL;
471 if (read_commit_msg(state) < 0)
472 die(_("'%s' was deleted by the applypatch-msg hook"),
473 am_path(state, "final-commit"));
476 return ret;
480 * Runs post-rewrite hook. Returns it exit code.
482 static int run_post_rewrite_hook(const struct am_state *state)
484 struct child_process cp = CHILD_PROCESS_INIT;
485 const char *hook = find_hook("post-rewrite");
486 int ret;
488 if (!hook)
489 return 0;
491 argv_array_push(&cp.args, hook);
492 argv_array_push(&cp.args, "rebase");
494 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
495 cp.stdout_to_stderr = 1;
497 ret = run_command(&cp);
499 close(cp.in);
500 return ret;
504 * Reads the state directory's "rewritten" file, and copies notes from the old
505 * commits listed in the file to their rewritten commits.
507 * Returns 0 on success, -1 on failure.
509 static int copy_notes_for_rebase(const struct am_state *state)
511 struct notes_rewrite_cfg *c;
512 struct strbuf sb = STRBUF_INIT;
513 const char *invalid_line = _("Malformed input line: '%s'.");
514 const char *msg = "Notes added by 'git rebase'";
515 FILE *fp;
516 int ret = 0;
518 assert(state->rebasing);
520 c = init_copy_notes_for_rewrite("rebase");
521 if (!c)
522 return 0;
524 fp = xfopen(am_path(state, "rewritten"), "r");
526 while (!strbuf_getline(&sb, fp, '\n')) {
527 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
529 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
530 ret = error(invalid_line, sb.buf);
531 goto finish;
534 if (get_sha1_hex(sb.buf, from_obj)) {
535 ret = error(invalid_line, sb.buf);
536 goto finish;
539 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
540 ret = error(invalid_line, sb.buf);
541 goto finish;
544 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
545 ret = error(invalid_line, sb.buf);
546 goto finish;
549 if (copy_note_for_rewrite(c, from_obj, to_obj))
550 ret = error(_("Failed to copy notes from '%s' to '%s'"),
551 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
554 finish:
555 finish_copy_notes_for_rewrite(c, msg);
556 fclose(fp);
557 strbuf_release(&sb);
558 return ret;
562 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
563 * non-indented lines and checking if they look like they begin with valid
564 * header field names.
566 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
568 static int is_mail(FILE *fp)
570 const char *header_regex = "^[!-9;-~]+:";
571 struct strbuf sb = STRBUF_INIT;
572 regex_t regex;
573 int ret = 1;
575 if (fseek(fp, 0L, SEEK_SET))
576 die_errno(_("fseek failed"));
578 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
579 die("invalid pattern: %s", header_regex);
581 while (!strbuf_getline_crlf(&sb, fp)) {
582 if (!sb.len)
583 break; /* End of header */
585 /* Ignore indented folded lines */
586 if (*sb.buf == '\t' || *sb.buf == ' ')
587 continue;
589 /* It's a header if it matches header_regex */
590 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
591 ret = 0;
592 goto done;
596 done:
597 regfree(&regex);
598 strbuf_release(&sb);
599 return ret;
603 * Attempts to detect the patch_format of the patches contained in `paths`,
604 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
605 * detection fails.
607 static int detect_patch_format(const char **paths)
609 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
610 struct strbuf l1 = STRBUF_INIT;
611 FILE *fp;
614 * We default to mbox format if input is from stdin and for directories
616 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
617 return PATCH_FORMAT_MBOX;
620 * Otherwise, check the first few lines of the first patch, starting
621 * from the first non-blank line, to try to detect its format.
624 fp = xfopen(*paths, "r");
626 while (!strbuf_getline_crlf(&l1, fp)) {
627 if (l1.len)
628 break;
631 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
632 ret = PATCH_FORMAT_MBOX;
633 goto done;
636 if (l1.len && is_mail(fp)) {
637 ret = PATCH_FORMAT_MBOX;
638 goto done;
641 done:
642 fclose(fp);
643 strbuf_release(&l1);
644 return ret;
648 * Splits out individual email patches from `paths`, where each path is either
649 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
651 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
653 struct child_process cp = CHILD_PROCESS_INIT;
654 struct strbuf last = STRBUF_INIT;
656 cp.git_cmd = 1;
657 argv_array_push(&cp.args, "mailsplit");
658 argv_array_pushf(&cp.args, "-d%d", state->prec);
659 argv_array_pushf(&cp.args, "-o%s", state->dir);
660 argv_array_push(&cp.args, "-b");
661 if (keep_cr)
662 argv_array_push(&cp.args, "--keep-cr");
663 argv_array_push(&cp.args, "--");
664 argv_array_pushv(&cp.args, paths);
666 if (capture_command(&cp, &last, 8))
667 return -1;
669 state->cur = 1;
670 state->last = strtol(last.buf, NULL, 10);
672 return 0;
676 * Splits a list of files/directories into individual email patches. Each path
677 * in `paths` must be a file/directory that is formatted according to
678 * `patch_format`.
680 * Once split out, the individual email patches will be stored in the state
681 * directory, with each patch's filename being its index, padded to state->prec
682 * digits.
684 * state->cur will be set to the index of the first mail, and state->last will
685 * be set to the index of the last mail.
687 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
688 * to disable this behavior, -1 to use the default configured setting.
690 * Returns 0 on success, -1 on failure.
692 static int split_mail(struct am_state *state, enum patch_format patch_format,
693 const char **paths, int keep_cr)
695 if (keep_cr < 0) {
696 keep_cr = 0;
697 git_config_get_bool("am.keepcr", &keep_cr);
700 switch (patch_format) {
701 case PATCH_FORMAT_MBOX:
702 return split_mail_mbox(state, paths, keep_cr);
703 default:
704 die("BUG: invalid patch_format");
706 return -1;
710 * Setup a new am session for applying patches
712 static void am_setup(struct am_state *state, enum patch_format patch_format,
713 const char **paths, int keep_cr)
715 unsigned char curr_head[GIT_SHA1_RAWSZ];
716 const char *str;
717 struct strbuf sb = STRBUF_INIT;
719 if (!patch_format)
720 patch_format = detect_patch_format(paths);
722 if (!patch_format) {
723 fprintf_ln(stderr, _("Patch format detection failed."));
724 exit(128);
727 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
728 die_errno(_("failed to create directory '%s'"), state->dir);
730 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
731 am_destroy(state);
732 die(_("Failed to split patches."));
735 if (state->rebasing)
736 state->threeway = 1;
738 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
740 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
742 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
744 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
746 switch (state->keep) {
747 case KEEP_FALSE:
748 str = "f";
749 break;
750 case KEEP_TRUE:
751 str = "t";
752 break;
753 case KEEP_NON_PATCH:
754 str = "b";
755 break;
756 default:
757 die("BUG: invalid value for state->keep");
760 write_file(am_path(state, "keep"), 1, "%s", str);
762 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
764 switch (state->scissors) {
765 case SCISSORS_UNSET:
766 str = "";
767 break;
768 case SCISSORS_FALSE:
769 str = "f";
770 break;
771 case SCISSORS_TRUE:
772 str = "t";
773 break;
774 default:
775 die("BUG: invalid value for state->scissors");
778 write_file(am_path(state, "scissors"), 1, "%s", str);
780 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
781 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
783 if (state->rebasing)
784 write_file(am_path(state, "rebasing"), 1, "%s", "");
785 else
786 write_file(am_path(state, "applying"), 1, "%s", "");
788 if (!get_sha1("HEAD", curr_head)) {
789 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
790 if (!state->rebasing)
791 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
792 UPDATE_REFS_DIE_ON_ERR);
793 } else {
794 write_file(am_path(state, "abort-safety"), 1, "%s", "");
795 if (!state->rebasing)
796 delete_ref("ORIG_HEAD", NULL, 0);
800 * NOTE: Since the "next" and "last" files determine if an am_state
801 * session is in progress, they should be written last.
804 write_file(am_path(state, "next"), 1, "%d", state->cur);
806 write_file(am_path(state, "last"), 1, "%d", state->last);
808 strbuf_release(&sb);
812 * Increments the patch pointer, and cleans am_state for the application of the
813 * next patch.
815 static void am_next(struct am_state *state)
817 unsigned char head[GIT_SHA1_RAWSZ];
819 free(state->author_name);
820 state->author_name = NULL;
822 free(state->author_email);
823 state->author_email = NULL;
825 free(state->author_date);
826 state->author_date = NULL;
828 free(state->msg);
829 state->msg = NULL;
830 state->msg_len = 0;
832 unlink(am_path(state, "author-script"));
833 unlink(am_path(state, "final-commit"));
835 hashclr(state->orig_commit);
836 unlink(am_path(state, "original-commit"));
838 if (!get_sha1("HEAD", head))
839 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
840 else
841 write_file(am_path(state, "abort-safety"), 1, "%s", "");
843 state->cur++;
844 write_file(am_path(state, "next"), 1, "%d", state->cur);
848 * Returns the filename of the current patch email.
850 static const char *msgnum(const struct am_state *state)
852 static struct strbuf sb = STRBUF_INIT;
854 strbuf_reset(&sb);
855 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
857 return sb.buf;
861 * Refresh and write index.
863 static void refresh_and_write_cache(void)
865 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
867 hold_locked_index(lock_file, 1);
868 refresh_cache(REFRESH_QUIET);
869 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
870 die(_("unable to write index file"));
874 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
875 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
876 * strbuf is provided, the space-separated list of files that differ will be
877 * appended to it.
879 static int index_has_changes(struct strbuf *sb)
881 unsigned char head[GIT_SHA1_RAWSZ];
882 int i;
884 if (!get_sha1_tree("HEAD", head)) {
885 struct diff_options opt;
887 diff_setup(&opt);
888 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
889 if (!sb)
890 DIFF_OPT_SET(&opt, QUICK);
891 do_diff_cache(head, &opt);
892 diffcore_std(&opt);
893 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
894 if (i)
895 strbuf_addch(sb, ' ');
896 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
898 diff_flush(&opt);
899 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
900 } else {
901 for (i = 0; sb && i < active_nr; i++) {
902 if (i)
903 strbuf_addch(sb, ' ');
904 strbuf_addstr(sb, active_cache[i]->name);
906 return !!active_nr;
911 * Dies with a user-friendly message on how to proceed after resolving the
912 * problem. This message can be overridden with state->resolvemsg.
914 static void NORETURN die_user_resolve(const struct am_state *state)
916 if (state->resolvemsg) {
917 printf_ln("%s", state->resolvemsg);
918 } else {
919 const char *cmdline = "git am";
921 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
922 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
923 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
926 exit(128);
930 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
931 * state->msg will be set to the patch message. state->author_name,
932 * state->author_email and state->author_date will be set to the patch author's
933 * name, email and date respectively. The patch body will be written to the
934 * state directory's "patch" file.
936 * Returns 1 if the patch should be skipped, 0 otherwise.
938 static int parse_mail(struct am_state *state, const char *mail)
940 FILE *fp;
941 struct child_process cp = CHILD_PROCESS_INIT;
942 struct strbuf sb = STRBUF_INIT;
943 struct strbuf msg = STRBUF_INIT;
944 struct strbuf author_name = STRBUF_INIT;
945 struct strbuf author_date = STRBUF_INIT;
946 struct strbuf author_email = STRBUF_INIT;
947 int ret = 0;
949 cp.git_cmd = 1;
950 cp.in = xopen(mail, O_RDONLY, 0);
951 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
953 argv_array_push(&cp.args, "mailinfo");
954 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
956 switch (state->keep) {
957 case KEEP_FALSE:
958 break;
959 case KEEP_TRUE:
960 argv_array_push(&cp.args, "-k");
961 break;
962 case KEEP_NON_PATCH:
963 argv_array_push(&cp.args, "-b");
964 break;
965 default:
966 die("BUG: invalid value for state->keep");
969 if (state->message_id)
970 argv_array_push(&cp.args, "-m");
972 switch (state->scissors) {
973 case SCISSORS_UNSET:
974 break;
975 case SCISSORS_FALSE:
976 argv_array_push(&cp.args, "--no-scissors");
977 break;
978 case SCISSORS_TRUE:
979 argv_array_push(&cp.args, "--scissors");
980 break;
981 default:
982 die("BUG: invalid value for state->scissors");
985 argv_array_push(&cp.args, am_path(state, "msg"));
986 argv_array_push(&cp.args, am_path(state, "patch"));
988 if (run_command(&cp) < 0)
989 die("could not parse patch");
991 close(cp.in);
992 close(cp.out);
994 /* Extract message and author information */
995 fp = xfopen(am_path(state, "info"), "r");
996 while (!strbuf_getline(&sb, fp, '\n')) {
997 const char *x;
999 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1000 if (msg.len)
1001 strbuf_addch(&msg, '\n');
1002 strbuf_addstr(&msg, x);
1003 } else if (skip_prefix(sb.buf, "Author: ", &x))
1004 strbuf_addstr(&author_name, x);
1005 else if (skip_prefix(sb.buf, "Email: ", &x))
1006 strbuf_addstr(&author_email, x);
1007 else if (skip_prefix(sb.buf, "Date: ", &x))
1008 strbuf_addstr(&author_date, x);
1010 fclose(fp);
1012 /* Skip pine's internal folder data */
1013 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1014 ret = 1;
1015 goto finish;
1018 if (is_empty_file(am_path(state, "patch"))) {
1019 printf_ln(_("Patch is empty. Was it split wrong?"));
1020 die_user_resolve(state);
1023 strbuf_addstr(&msg, "\n\n");
1024 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
1025 die_errno(_("could not read '%s'"), am_path(state, "msg"));
1026 stripspace(&msg, 0);
1028 if (state->signoff)
1029 append_signoff(&msg, 0, 0);
1031 assert(!state->author_name);
1032 state->author_name = strbuf_detach(&author_name, NULL);
1034 assert(!state->author_email);
1035 state->author_email = strbuf_detach(&author_email, NULL);
1037 assert(!state->author_date);
1038 state->author_date = strbuf_detach(&author_date, NULL);
1040 assert(!state->msg);
1041 state->msg = strbuf_detach(&msg, &state->msg_len);
1043 finish:
1044 strbuf_release(&msg);
1045 strbuf_release(&author_date);
1046 strbuf_release(&author_email);
1047 strbuf_release(&author_name);
1048 strbuf_release(&sb);
1049 return ret;
1053 * Sets commit_id to the commit hash where the mail was generated from.
1054 * Returns 0 on success, -1 on failure.
1056 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1058 struct strbuf sb = STRBUF_INIT;
1059 FILE *fp = xfopen(mail, "r");
1060 const char *x;
1062 if (strbuf_getline(&sb, fp, '\n'))
1063 return -1;
1065 if (!skip_prefix(sb.buf, "From ", &x))
1066 return -1;
1068 if (get_sha1_hex(x, commit_id) < 0)
1069 return -1;
1071 strbuf_release(&sb);
1072 fclose(fp);
1073 return 0;
1077 * Sets state->msg, state->author_name, state->author_email, state->author_date
1078 * to the commit's respective info.
1080 static void get_commit_info(struct am_state *state, struct commit *commit)
1082 const char *buffer, *ident_line, *author_date, *msg;
1083 size_t ident_len;
1084 struct ident_split ident_split;
1085 struct strbuf sb = STRBUF_INIT;
1087 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1089 ident_line = find_commit_header(buffer, "author", &ident_len);
1091 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1092 strbuf_add(&sb, ident_line, ident_len);
1093 die(_("invalid ident line: %s"), sb.buf);
1096 assert(!state->author_name);
1097 if (ident_split.name_begin) {
1098 strbuf_add(&sb, ident_split.name_begin,
1099 ident_split.name_end - ident_split.name_begin);
1100 state->author_name = strbuf_detach(&sb, NULL);
1101 } else
1102 state->author_name = xstrdup("");
1104 assert(!state->author_email);
1105 if (ident_split.mail_begin) {
1106 strbuf_add(&sb, ident_split.mail_begin,
1107 ident_split.mail_end - ident_split.mail_begin);
1108 state->author_email = strbuf_detach(&sb, NULL);
1109 } else
1110 state->author_email = xstrdup("");
1112 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1113 strbuf_addstr(&sb, author_date);
1114 assert(!state->author_date);
1115 state->author_date = strbuf_detach(&sb, NULL);
1117 assert(!state->msg);
1118 msg = strstr(buffer, "\n\n");
1119 if (!msg)
1120 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1121 state->msg = xstrdup(msg + 2);
1122 state->msg_len = strlen(state->msg);
1126 * Writes `commit` as a patch to the state directory's "patch" file.
1128 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1130 struct rev_info rev_info;
1131 FILE *fp;
1133 fp = xfopen(am_path(state, "patch"), "w");
1134 init_revisions(&rev_info, NULL);
1135 rev_info.diff = 1;
1136 rev_info.abbrev = 0;
1137 rev_info.disable_stdin = 1;
1138 rev_info.show_root_diff = 1;
1139 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1140 rev_info.no_commit_id = 1;
1141 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1142 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1143 rev_info.diffopt.use_color = 0;
1144 rev_info.diffopt.file = fp;
1145 rev_info.diffopt.close_file = 1;
1146 add_pending_object(&rev_info, &commit->object, "");
1147 diff_setup_done(&rev_info.diffopt);
1148 log_tree_commit(&rev_info, commit);
1152 * Like parse_mail(), but parses the mail by looking up its commit ID
1153 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1154 * of patches.
1156 * state->orig_commit will be set to the original commit ID.
1158 * Will always return 0 as the patch should never be skipped.
1160 static int parse_mail_rebase(struct am_state *state, const char *mail)
1162 struct commit *commit;
1163 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1165 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1166 die(_("could not parse %s"), mail);
1168 commit = lookup_commit_or_die(commit_sha1, mail);
1170 get_commit_info(state, commit);
1172 write_commit_patch(state, commit);
1174 hashcpy(state->orig_commit, commit_sha1);
1175 write_file(am_path(state, "original-commit"), 1, "%s",
1176 sha1_to_hex(commit_sha1));
1178 return 0;
1182 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1183 * `index_file` is not NULL, the patch will be applied to that index.
1185 static int run_apply(const struct am_state *state, const char *index_file)
1187 struct child_process cp = CHILD_PROCESS_INIT;
1189 cp.git_cmd = 1;
1191 if (index_file)
1192 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1195 * If we are allowed to fall back on 3-way merge, don't give false
1196 * errors during the initial attempt.
1198 if (state->threeway && !index_file) {
1199 cp.no_stdout = 1;
1200 cp.no_stderr = 1;
1203 argv_array_push(&cp.args, "apply");
1205 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1207 if (index_file)
1208 argv_array_push(&cp.args, "--cached");
1209 else
1210 argv_array_push(&cp.args, "--index");
1212 argv_array_push(&cp.args, am_path(state, "patch"));
1214 if (run_command(&cp))
1215 return -1;
1217 /* Reload index as git-apply will have modified it. */
1218 discard_cache();
1219 read_cache_from(index_file ? index_file : get_index_file());
1221 return 0;
1225 * Builds an index that contains just the blobs needed for a 3way merge.
1227 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1229 struct child_process cp = CHILD_PROCESS_INIT;
1231 cp.git_cmd = 1;
1232 argv_array_push(&cp.args, "apply");
1233 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1234 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1235 argv_array_push(&cp.args, am_path(state, "patch"));
1237 if (run_command(&cp))
1238 return -1;
1240 return 0;
1244 * Attempt a threeway merge, using index_path as the temporary index.
1246 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1248 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1249 our_tree[GIT_SHA1_RAWSZ];
1250 const unsigned char *bases[1] = {orig_tree};
1251 struct merge_options o;
1252 struct commit *result;
1253 char *his_tree_name;
1255 if (get_sha1("HEAD", our_tree) < 0)
1256 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1258 if (build_fake_ancestor(state, index_path))
1259 return error("could not build fake ancestor");
1261 discard_cache();
1262 read_cache_from(index_path);
1264 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1265 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1267 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1269 if (!state->quiet) {
1271 * List paths that needed 3-way fallback, so that the user can
1272 * review them with extra care to spot mismerges.
1274 struct rev_info rev_info;
1275 const char *diff_filter_str = "--diff-filter=AM";
1277 init_revisions(&rev_info, NULL);
1278 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1279 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1280 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1281 diff_setup_done(&rev_info.diffopt);
1282 run_diff_index(&rev_info, 1);
1285 if (run_apply(state, index_path))
1286 return error(_("Did you hand edit your patch?\n"
1287 "It does not apply to blobs recorded in its index."));
1289 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1290 return error("could not write tree");
1292 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1294 discard_cache();
1295 read_cache();
1298 * This is not so wrong. Depending on which base we picked, orig_tree
1299 * may be wildly different from ours, but his_tree has the same set of
1300 * wildly different changes in parts the patch did not touch, so
1301 * recursive ends up canceling them, saying that we reverted all those
1302 * changes.
1305 init_merge_options(&o);
1307 o.branch1 = "HEAD";
1308 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1309 o.branch2 = his_tree_name;
1311 if (state->quiet)
1312 o.verbosity = 0;
1314 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1315 free(his_tree_name);
1316 return error(_("Failed to merge in the changes."));
1319 free(his_tree_name);
1320 return 0;
1324 * Commits the current index with state->msg as the commit message and
1325 * state->author_name, state->author_email and state->author_date as the author
1326 * information.
1328 static void do_commit(const struct am_state *state)
1330 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1331 commit[GIT_SHA1_RAWSZ];
1332 unsigned char *ptr;
1333 struct commit_list *parents = NULL;
1334 const char *reflog_msg, *author;
1335 struct strbuf sb = STRBUF_INIT;
1337 if (write_cache_as_tree(tree, 0, NULL))
1338 die(_("git write-tree failed to write a tree"));
1340 if (!get_sha1_commit("HEAD", parent)) {
1341 ptr = parent;
1342 commit_list_insert(lookup_commit(parent), &parents);
1343 } else {
1344 ptr = NULL;
1345 say(state, stderr, _("applying to an empty history"));
1348 author = fmt_ident(state->author_name, state->author_email,
1349 state->ignore_date ? NULL : state->author_date,
1350 IDENT_STRICT);
1352 if (state->committer_date_is_author_date)
1353 setenv("GIT_COMMITTER_DATE",
1354 state->ignore_date ? "" : state->author_date, 1);
1356 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1357 author, state->sign_commit))
1358 die(_("failed to write commit object"));
1360 reflog_msg = getenv("GIT_REFLOG_ACTION");
1361 if (!reflog_msg)
1362 reflog_msg = "am";
1364 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1365 state->msg);
1367 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1369 if (state->rebasing) {
1370 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1372 assert(!is_null_sha1(state->orig_commit));
1373 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1374 fprintf(fp, "%s\n", sha1_to_hex(commit));
1375 fclose(fp);
1378 strbuf_release(&sb);
1382 * Validates the am_state for resuming -- the "msg" and authorship fields must
1383 * be filled up.
1385 static void validate_resume_state(const struct am_state *state)
1387 if (!state->msg)
1388 die(_("cannot resume: %s does not exist."),
1389 am_path(state, "final-commit"));
1391 if (!state->author_name || !state->author_email || !state->author_date)
1392 die(_("cannot resume: %s does not exist."),
1393 am_path(state, "author-script"));
1397 * Applies all queued mail.
1399 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1400 * well as the state directory's "patch" file is used as-is for applying the
1401 * patch and committing it.
1403 static void am_run(struct am_state *state, int resume)
1405 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1406 struct strbuf sb = STRBUF_INIT;
1408 unlink(am_path(state, "dirtyindex"));
1410 refresh_and_write_cache();
1412 if (index_has_changes(&sb)) {
1413 write_file(am_path(state, "dirtyindex"), 1, "t");
1414 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1417 strbuf_release(&sb);
1419 while (state->cur <= state->last) {
1420 const char *mail = am_path(state, msgnum(state));
1421 int apply_status;
1423 if (!file_exists(mail))
1424 goto next;
1426 if (resume) {
1427 validate_resume_state(state);
1428 resume = 0;
1429 } else {
1430 int skip;
1432 if (state->rebasing)
1433 skip = parse_mail_rebase(state, mail);
1434 else
1435 skip = parse_mail(state, mail);
1437 if (skip)
1438 goto next; /* mail should be skipped */
1440 write_author_script(state);
1441 write_commit_msg(state);
1444 if (run_applypatch_msg_hook(state))
1445 exit(1);
1447 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1449 apply_status = run_apply(state, NULL);
1451 if (apply_status && state->threeway) {
1452 struct strbuf sb = STRBUF_INIT;
1454 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1455 apply_status = fall_back_threeway(state, sb.buf);
1456 strbuf_release(&sb);
1459 * Applying the patch to an earlier tree and merging
1460 * the result may have produced the same tree as ours.
1462 if (!apply_status && !index_has_changes(NULL)) {
1463 say(state, stdout, _("No changes -- Patch already applied."));
1464 goto next;
1468 if (apply_status) {
1469 int advice_amworkdir = 1;
1471 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1472 linelen(state->msg), state->msg);
1474 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1476 if (advice_amworkdir)
1477 printf_ln(_("The copy of the patch that failed is found in: %s"),
1478 am_path(state, "patch"));
1480 die_user_resolve(state);
1483 do_commit(state);
1485 next:
1486 am_next(state);
1489 if (!is_empty_file(am_path(state, "rewritten"))) {
1490 assert(state->rebasing);
1491 copy_notes_for_rebase(state);
1492 run_post_rewrite_hook(state);
1496 * In rebasing mode, it's up to the caller to take care of
1497 * housekeeping.
1499 if (!state->rebasing) {
1500 am_destroy(state);
1501 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1506 * Resume the current am session after patch application failure. The user did
1507 * all the hard work, and we do not have to do any patch application. Just
1508 * trust and commit what the user has in the index and working tree.
1510 static void am_resolve(struct am_state *state)
1512 validate_resume_state(state);
1514 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1516 if (!index_has_changes(NULL)) {
1517 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1518 "If there is nothing left to stage, chances are that something else\n"
1519 "already introduced the same changes; you might want to skip this patch."));
1520 die_user_resolve(state);
1523 if (unmerged_cache()) {
1524 printf_ln(_("You still have unmerged paths in your index.\n"
1525 "Did you forget to use 'git add'?"));
1526 die_user_resolve(state);
1529 do_commit(state);
1531 am_next(state);
1532 am_run(state, 0);
1536 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1537 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1538 * failure.
1540 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1542 struct lock_file *lock_file;
1543 struct unpack_trees_options opts;
1544 struct tree_desc t[2];
1546 if (parse_tree(head) || parse_tree(remote))
1547 return -1;
1549 lock_file = xcalloc(1, sizeof(struct lock_file));
1550 hold_locked_index(lock_file, 1);
1552 refresh_cache(REFRESH_QUIET);
1554 memset(&opts, 0, sizeof(opts));
1555 opts.head_idx = 1;
1556 opts.src_index = &the_index;
1557 opts.dst_index = &the_index;
1558 opts.update = 1;
1559 opts.merge = 1;
1560 opts.reset = reset;
1561 opts.fn = twoway_merge;
1562 init_tree_desc(&t[0], head->buffer, head->size);
1563 init_tree_desc(&t[1], remote->buffer, remote->size);
1565 if (unpack_trees(2, t, &opts)) {
1566 rollback_lock_file(lock_file);
1567 return -1;
1570 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1571 die(_("unable to write new index file"));
1573 return 0;
1577 * Clean the index without touching entries that are not modified between
1578 * `head` and `remote`.
1580 static int clean_index(const unsigned char *head, const unsigned char *remote)
1582 struct lock_file *lock_file;
1583 struct tree *head_tree, *remote_tree, *index_tree;
1584 unsigned char index[GIT_SHA1_RAWSZ];
1585 struct pathspec pathspec;
1587 head_tree = parse_tree_indirect(head);
1588 if (!head_tree)
1589 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1591 remote_tree = parse_tree_indirect(remote);
1592 if (!remote_tree)
1593 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1595 read_cache_unmerged();
1597 if (fast_forward_to(head_tree, head_tree, 1))
1598 return -1;
1600 if (write_cache_as_tree(index, 0, NULL))
1601 return -1;
1603 index_tree = parse_tree_indirect(index);
1604 if (!index_tree)
1605 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1607 if (fast_forward_to(index_tree, remote_tree, 0))
1608 return -1;
1610 memset(&pathspec, 0, sizeof(pathspec));
1612 lock_file = xcalloc(1, sizeof(struct lock_file));
1613 hold_locked_index(lock_file, 1);
1615 if (read_tree(remote_tree, 0, &pathspec)) {
1616 rollback_lock_file(lock_file);
1617 return -1;
1620 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1621 die(_("unable to write new index file"));
1623 remove_branch_state();
1625 return 0;
1629 * Resume the current am session by skipping the current patch.
1631 static void am_skip(struct am_state *state)
1633 unsigned char head[GIT_SHA1_RAWSZ];
1635 if (get_sha1("HEAD", head))
1636 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1638 if (clean_index(head, head))
1639 die(_("failed to clean index"));
1641 am_next(state);
1642 am_run(state, 0);
1646 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1648 * It is not safe to reset HEAD when:
1649 * 1. git-am previously failed because the index was dirty.
1650 * 2. HEAD has moved since git-am previously failed.
1652 static int safe_to_abort(const struct am_state *state)
1654 struct strbuf sb = STRBUF_INIT;
1655 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1657 if (file_exists(am_path(state, "dirtyindex")))
1658 return 0;
1660 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1661 if (get_sha1_hex(sb.buf, abort_safety))
1662 die(_("could not parse %s"), am_path(state, "abort_safety"));
1663 } else
1664 hashclr(abort_safety);
1666 if (get_sha1("HEAD", head))
1667 hashclr(head);
1669 if (!hashcmp(head, abort_safety))
1670 return 1;
1672 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1673 "Not rewinding to ORIG_HEAD"));
1675 return 0;
1679 * Aborts the current am session if it is safe to do so.
1681 static void am_abort(struct am_state *state)
1683 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1684 int has_curr_head, has_orig_head;
1685 char *curr_branch;
1687 if (!safe_to_abort(state)) {
1688 am_destroy(state);
1689 return;
1692 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1693 has_curr_head = !is_null_sha1(curr_head);
1694 if (!has_curr_head)
1695 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1697 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1698 if (!has_orig_head)
1699 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1701 clean_index(curr_head, orig_head);
1703 if (has_orig_head)
1704 update_ref("am --abort", "HEAD", orig_head,
1705 has_curr_head ? curr_head : NULL, 0,
1706 UPDATE_REFS_DIE_ON_ERR);
1707 else if (curr_branch)
1708 delete_ref(curr_branch, NULL, REF_NODEREF);
1710 free(curr_branch);
1711 am_destroy(state);
1715 * parse_options() callback that validates and sets opt->value to the
1716 * PATCH_FORMAT_* enum value corresponding to `arg`.
1718 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1720 int *opt_value = opt->value;
1722 if (!strcmp(arg, "mbox"))
1723 *opt_value = PATCH_FORMAT_MBOX;
1724 else
1725 return error(_("Invalid value for --patch-format: %s"), arg);
1726 return 0;
1729 enum resume_mode {
1730 RESUME_FALSE = 0,
1731 RESUME_APPLY,
1732 RESUME_RESOLVED,
1733 RESUME_SKIP,
1734 RESUME_ABORT
1737 int cmd_am(int argc, const char **argv, const char *prefix)
1739 struct am_state state;
1740 int keep_cr = -1;
1741 int patch_format = PATCH_FORMAT_UNKNOWN;
1742 enum resume_mode resume = RESUME_FALSE;
1744 const char * const usage[] = {
1745 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1746 N_("git am [options] (--continue | --skip | --abort)"),
1747 NULL
1750 struct option options[] = {
1751 OPT_BOOL('3', "3way", &state.threeway,
1752 N_("allow fall back on 3way merging if needed")),
1753 OPT__QUIET(&state.quiet, N_("be quiet")),
1754 OPT_BOOL('s', "signoff", &state.signoff,
1755 N_("add a Signed-off-by line to the commit message")),
1756 OPT_BOOL('u', "utf8", &state.utf8,
1757 N_("recode into utf8 (default)")),
1758 OPT_SET_INT('k', "keep", &state.keep,
1759 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1760 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1761 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1762 OPT_BOOL('m', "message-id", &state.message_id,
1763 N_("pass -m flag to git-mailinfo")),
1764 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1765 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1766 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1767 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1768 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1769 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
1770 OPT_BOOL('c', "scissors", &state.scissors,
1771 N_("strip everything before a scissors line")),
1772 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
1773 N_("pass it through git-apply"),
1775 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
1776 N_("pass it through git-apply"),
1777 PARSE_OPT_NOARG),
1778 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
1779 N_("pass it through git-apply"),
1780 PARSE_OPT_NOARG),
1781 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
1782 N_("pass it through git-apply"),
1784 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
1785 N_("pass it through git-apply"),
1787 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
1788 N_("pass it through git-apply"),
1790 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
1791 N_("pass it through git-apply"),
1793 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
1794 N_("pass it through git-apply"),
1796 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1797 N_("format the patch(es) are in"),
1798 parse_opt_patchformat),
1799 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
1800 N_("pass it through git-apply"),
1801 PARSE_OPT_NOARG),
1802 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1803 N_("override error message when patch failure occurs")),
1804 OPT_CMDMODE(0, "continue", &resume,
1805 N_("continue applying patches after resolving a conflict"),
1806 RESUME_RESOLVED),
1807 OPT_CMDMODE('r', "resolved", &resume,
1808 N_("synonyms for --continue"),
1809 RESUME_RESOLVED),
1810 OPT_CMDMODE(0, "skip", &resume,
1811 N_("skip the current patch"),
1812 RESUME_SKIP),
1813 OPT_CMDMODE(0, "abort", &resume,
1814 N_("restore the original branch and abort the patching operation."),
1815 RESUME_ABORT),
1816 OPT_BOOL(0, "committer-date-is-author-date",
1817 &state.committer_date_is_author_date,
1818 N_("lie about committer date")),
1819 OPT_BOOL(0, "ignore-date", &state.ignore_date,
1820 N_("use current timestamp for author date")),
1821 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
1822 N_("GPG-sign commits"),
1823 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1824 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1825 N_("(internal use for git-rebase)")),
1826 OPT_END()
1830 * NEEDSWORK: Once all the features of git-am.sh have been
1831 * re-implemented in builtin/am.c, this preamble can be removed.
1833 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1834 const char *path = mkpath("%s/git-am", git_exec_path());
1836 if (sane_execvp(path, (char **)argv) < 0)
1837 die_errno("could not exec %s", path);
1838 } else {
1839 prefix = setup_git_directory();
1840 trace_repo_setup(prefix);
1841 setup_work_tree();
1844 git_config(git_default_config, NULL);
1846 am_state_init(&state, git_path("rebase-apply"));
1848 argc = parse_options(argc, argv, prefix, options, usage, 0);
1850 if (read_index_preload(&the_index, NULL) < 0)
1851 die(_("failed to read the index"));
1853 if (am_in_progress(&state)) {
1855 * Catch user error to feed us patches when there is a session
1856 * in progress:
1858 * 1. mbox path(s) are provided on the command-line.
1859 * 2. stdin is not a tty: the user is trying to feed us a patch
1860 * from standard input. This is somewhat unreliable -- stdin
1861 * could be /dev/null for example and the caller did not
1862 * intend to feed us a patch but wanted to continue
1863 * unattended.
1865 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1866 die(_("previous rebase directory %s still exists but mbox given."),
1867 state.dir);
1869 if (resume == RESUME_FALSE)
1870 resume = RESUME_APPLY;
1872 am_load(&state);
1873 } else {
1874 struct argv_array paths = ARGV_ARRAY_INIT;
1875 int i;
1878 * Handle stray state directory in the independent-run case. In
1879 * the --rebasing case, it is up to the caller to take care of
1880 * stray directories.
1882 if (file_exists(state.dir) && !state.rebasing) {
1883 if (resume == RESUME_ABORT) {
1884 am_destroy(&state);
1885 am_state_release(&state);
1886 return 0;
1889 die(_("Stray %s directory found.\n"
1890 "Use \"git am --abort\" to remove it."),
1891 state.dir);
1894 if (resume)
1895 die(_("Resolve operation not in progress, we are not resuming."));
1897 for (i = 0; i < argc; i++) {
1898 if (is_absolute_path(argv[i]) || !prefix)
1899 argv_array_push(&paths, argv[i]);
1900 else
1901 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1904 am_setup(&state, patch_format, paths.argv, keep_cr);
1906 argv_array_clear(&paths);
1909 switch (resume) {
1910 case RESUME_FALSE:
1911 am_run(&state, 0);
1912 break;
1913 case RESUME_APPLY:
1914 am_run(&state, 1);
1915 break;
1916 case RESUME_RESOLVED:
1917 am_resolve(&state);
1918 break;
1919 case RESUME_SKIP:
1920 am_skip(&state);
1921 break;
1922 case RESUME_ABORT:
1923 am_abort(&state);
1924 break;
1925 default:
1926 die("BUG: invalid resume value");
1929 am_state_release(&state);
1931 return 0;