builtin-am: implement legacy -b/--binary option
[git.git] / builtin / am.c
blob3c503920138c567bb756f093d9c684eae8f66834
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"
27 #include "rerere.h"
28 #include "prompt.h"
30 /**
31 * Returns 1 if the file is empty or does not exist, 0 otherwise.
33 static int is_empty_file(const char *filename)
35 struct stat st;
37 if (stat(filename, &st) < 0) {
38 if (errno == ENOENT)
39 return 1;
40 die_errno(_("could not stat %s"), filename);
43 return !st.st_size;
46 /**
47 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
49 static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
51 if (strbuf_getwholeline(sb, fp, '\n'))
52 return EOF;
53 if (sb->buf[sb->len - 1] == '\n') {
54 strbuf_setlen(sb, sb->len - 1);
55 if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
56 strbuf_setlen(sb, sb->len - 1);
58 return 0;
61 /**
62 * Returns the length of the first line of msg.
64 static int linelen(const char *msg)
66 return strchrnul(msg, '\n') - msg;
69 /**
70 * Returns true if `str` consists of only whitespace, false otherwise.
72 static int str_isspace(const char *str)
74 for (; *str; str++)
75 if (!isspace(*str))
76 return 0;
78 return 1;
81 enum patch_format {
82 PATCH_FORMAT_UNKNOWN = 0,
83 PATCH_FORMAT_MBOX,
84 PATCH_FORMAT_STGIT,
85 PATCH_FORMAT_STGIT_SERIES,
86 PATCH_FORMAT_HG
89 enum keep_type {
90 KEEP_FALSE = 0,
91 KEEP_TRUE, /* pass -k flag to git-mailinfo */
92 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
95 enum scissors_type {
96 SCISSORS_UNSET = -1,
97 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
98 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
101 struct am_state {
102 /* state directory path */
103 char *dir;
105 /* current and last patch numbers, 1-indexed */
106 int cur;
107 int last;
109 /* commit metadata and message */
110 char *author_name;
111 char *author_email;
112 char *author_date;
113 char *msg;
114 size_t msg_len;
116 /* when --rebasing, records the original commit the patch came from */
117 unsigned char orig_commit[GIT_SHA1_RAWSZ];
119 /* number of digits in patch filename */
120 int prec;
122 /* various operating modes and command line options */
123 int interactive;
124 int threeway;
125 int quiet;
126 int signoff;
127 int utf8;
128 int keep; /* enum keep_type */
129 int message_id;
130 int scissors; /* enum scissors_type */
131 struct argv_array git_apply_opts;
132 const char *resolvemsg;
133 int committer_date_is_author_date;
134 int ignore_date;
135 int allow_rerere_autoupdate;
136 const char *sign_commit;
137 int rebasing;
141 * Initializes am_state with the default values. The state directory is set to
142 * dir.
144 static void am_state_init(struct am_state *state, const char *dir)
146 int gpgsign;
148 memset(state, 0, sizeof(*state));
150 assert(dir);
151 state->dir = xstrdup(dir);
153 state->prec = 4;
155 state->utf8 = 1;
157 git_config_get_bool("am.messageid", &state->message_id);
159 state->scissors = SCISSORS_UNSET;
161 argv_array_init(&state->git_apply_opts);
163 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
164 state->sign_commit = gpgsign ? "" : NULL;
168 * Releases memory allocated by an am_state.
170 static void am_state_release(struct am_state *state)
172 free(state->dir);
173 free(state->author_name);
174 free(state->author_email);
175 free(state->author_date);
176 free(state->msg);
177 argv_array_clear(&state->git_apply_opts);
181 * Returns path relative to the am_state directory.
183 static inline const char *am_path(const struct am_state *state, const char *path)
185 return mkpath("%s/%s", state->dir, path);
189 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
190 * at the end.
192 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
194 va_list ap;
196 va_start(ap, fmt);
197 if (!state->quiet) {
198 vfprintf(fp, fmt, ap);
199 putc('\n', fp);
201 va_end(ap);
205 * Returns 1 if there is an am session in progress, 0 otherwise.
207 static int am_in_progress(const struct am_state *state)
209 struct stat st;
211 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
212 return 0;
213 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
214 return 0;
215 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
216 return 0;
217 return 1;
221 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
222 * number of bytes read on success, -1 if the file does not exist. If `trim` is
223 * set, trailing whitespace will be removed.
225 static int read_state_file(struct strbuf *sb, const struct am_state *state,
226 const char *file, int trim)
228 strbuf_reset(sb);
230 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
231 if (trim)
232 strbuf_trim(sb);
234 return sb->len;
237 if (errno == ENOENT)
238 return -1;
240 die_errno(_("could not read '%s'"), am_path(state, file));
244 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
245 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
246 * match `key`. Returns NULL on failure.
248 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
249 * the author-script.
251 static char *read_shell_var(FILE *fp, const char *key)
253 struct strbuf sb = STRBUF_INIT;
254 const char *str;
256 if (strbuf_getline(&sb, fp, '\n'))
257 goto fail;
259 if (!skip_prefix(sb.buf, key, &str))
260 goto fail;
262 if (!skip_prefix(str, "=", &str))
263 goto fail;
265 strbuf_remove(&sb, 0, str - sb.buf);
267 str = sq_dequote(sb.buf);
268 if (!str)
269 goto fail;
271 return strbuf_detach(&sb, NULL);
273 fail:
274 strbuf_release(&sb);
275 return NULL;
279 * Reads and parses the state directory's "author-script" file, and sets
280 * state->author_name, state->author_email and state->author_date accordingly.
281 * Returns 0 on success, -1 if the file could not be parsed.
283 * The author script is of the format:
285 * GIT_AUTHOR_NAME='$author_name'
286 * GIT_AUTHOR_EMAIL='$author_email'
287 * GIT_AUTHOR_DATE='$author_date'
289 * where $author_name, $author_email and $author_date are quoted. We are strict
290 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
291 * script, and thus if the file differs from what this function expects, it is
292 * better to bail out than to do something that the user does not expect.
294 static int read_author_script(struct am_state *state)
296 const char *filename = am_path(state, "author-script");
297 FILE *fp;
299 assert(!state->author_name);
300 assert(!state->author_email);
301 assert(!state->author_date);
303 fp = fopen(filename, "r");
304 if (!fp) {
305 if (errno == ENOENT)
306 return 0;
307 die_errno(_("could not open '%s' for reading"), filename);
310 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
311 if (!state->author_name) {
312 fclose(fp);
313 return -1;
316 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
317 if (!state->author_email) {
318 fclose(fp);
319 return -1;
322 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
323 if (!state->author_date) {
324 fclose(fp);
325 return -1;
328 if (fgetc(fp) != EOF) {
329 fclose(fp);
330 return -1;
333 fclose(fp);
334 return 0;
338 * Saves state->author_name, state->author_email and state->author_date in the
339 * state directory's "author-script" file.
341 static void write_author_script(const struct am_state *state)
343 struct strbuf sb = STRBUF_INIT;
345 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
346 sq_quote_buf(&sb, state->author_name);
347 strbuf_addch(&sb, '\n');
349 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
350 sq_quote_buf(&sb, state->author_email);
351 strbuf_addch(&sb, '\n');
353 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
354 sq_quote_buf(&sb, state->author_date);
355 strbuf_addch(&sb, '\n');
357 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
359 strbuf_release(&sb);
363 * Reads the commit message from the state directory's "final-commit" file,
364 * setting state->msg to its contents and state->msg_len to the length of its
365 * contents in bytes.
367 * Returns 0 on success, -1 if the file does not exist.
369 static int read_commit_msg(struct am_state *state)
371 struct strbuf sb = STRBUF_INIT;
373 assert(!state->msg);
375 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
376 strbuf_release(&sb);
377 return -1;
380 state->msg = strbuf_detach(&sb, &state->msg_len);
381 return 0;
385 * Saves state->msg in the state directory's "final-commit" file.
387 static void write_commit_msg(const struct am_state *state)
389 int fd;
390 const char *filename = am_path(state, "final-commit");
392 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
393 if (write_in_full(fd, state->msg, state->msg_len) < 0)
394 die_errno(_("could not write to %s"), filename);
395 close(fd);
399 * Loads state from disk.
401 static void am_load(struct am_state *state)
403 struct strbuf sb = STRBUF_INIT;
405 if (read_state_file(&sb, state, "next", 1) < 0)
406 die("BUG: state file 'next' does not exist");
407 state->cur = strtol(sb.buf, NULL, 10);
409 if (read_state_file(&sb, state, "last", 1) < 0)
410 die("BUG: state file 'last' does not exist");
411 state->last = strtol(sb.buf, NULL, 10);
413 if (read_author_script(state) < 0)
414 die(_("could not parse author script"));
416 read_commit_msg(state);
418 if (read_state_file(&sb, state, "original-commit", 1) < 0)
419 hashclr(state->orig_commit);
420 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
421 die(_("could not parse %s"), am_path(state, "original-commit"));
423 read_state_file(&sb, state, "threeway", 1);
424 state->threeway = !strcmp(sb.buf, "t");
426 read_state_file(&sb, state, "quiet", 1);
427 state->quiet = !strcmp(sb.buf, "t");
429 read_state_file(&sb, state, "sign", 1);
430 state->signoff = !strcmp(sb.buf, "t");
432 read_state_file(&sb, state, "utf8", 1);
433 state->utf8 = !strcmp(sb.buf, "t");
435 read_state_file(&sb, state, "keep", 1);
436 if (!strcmp(sb.buf, "t"))
437 state->keep = KEEP_TRUE;
438 else if (!strcmp(sb.buf, "b"))
439 state->keep = KEEP_NON_PATCH;
440 else
441 state->keep = KEEP_FALSE;
443 read_state_file(&sb, state, "messageid", 1);
444 state->message_id = !strcmp(sb.buf, "t");
446 read_state_file(&sb, state, "scissors", 1);
447 if (!strcmp(sb.buf, "t"))
448 state->scissors = SCISSORS_TRUE;
449 else if (!strcmp(sb.buf, "f"))
450 state->scissors = SCISSORS_FALSE;
451 else
452 state->scissors = SCISSORS_UNSET;
454 read_state_file(&sb, state, "apply-opt", 1);
455 argv_array_clear(&state->git_apply_opts);
456 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
457 die(_("could not parse %s"), am_path(state, "apply-opt"));
459 state->rebasing = !!file_exists(am_path(state, "rebasing"));
461 strbuf_release(&sb);
465 * Removes the am_state directory, forcefully terminating the current am
466 * session.
468 static void am_destroy(const struct am_state *state)
470 struct strbuf sb = STRBUF_INIT;
472 strbuf_addstr(&sb, state->dir);
473 remove_dir_recursively(&sb, 0);
474 strbuf_release(&sb);
478 * Runs applypatch-msg hook. Returns its exit code.
480 static int run_applypatch_msg_hook(struct am_state *state)
482 int ret;
484 assert(state->msg);
485 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
487 if (!ret) {
488 free(state->msg);
489 state->msg = NULL;
490 if (read_commit_msg(state) < 0)
491 die(_("'%s' was deleted by the applypatch-msg hook"),
492 am_path(state, "final-commit"));
495 return ret;
499 * Runs post-rewrite hook. Returns it exit code.
501 static int run_post_rewrite_hook(const struct am_state *state)
503 struct child_process cp = CHILD_PROCESS_INIT;
504 const char *hook = find_hook("post-rewrite");
505 int ret;
507 if (!hook)
508 return 0;
510 argv_array_push(&cp.args, hook);
511 argv_array_push(&cp.args, "rebase");
513 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
514 cp.stdout_to_stderr = 1;
516 ret = run_command(&cp);
518 close(cp.in);
519 return ret;
523 * Reads the state directory's "rewritten" file, and copies notes from the old
524 * commits listed in the file to their rewritten commits.
526 * Returns 0 on success, -1 on failure.
528 static int copy_notes_for_rebase(const struct am_state *state)
530 struct notes_rewrite_cfg *c;
531 struct strbuf sb = STRBUF_INIT;
532 const char *invalid_line = _("Malformed input line: '%s'.");
533 const char *msg = "Notes added by 'git rebase'";
534 FILE *fp;
535 int ret = 0;
537 assert(state->rebasing);
539 c = init_copy_notes_for_rewrite("rebase");
540 if (!c)
541 return 0;
543 fp = xfopen(am_path(state, "rewritten"), "r");
545 while (!strbuf_getline(&sb, fp, '\n')) {
546 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
548 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
549 ret = error(invalid_line, sb.buf);
550 goto finish;
553 if (get_sha1_hex(sb.buf, from_obj)) {
554 ret = error(invalid_line, sb.buf);
555 goto finish;
558 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
559 ret = error(invalid_line, sb.buf);
560 goto finish;
563 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
564 ret = error(invalid_line, sb.buf);
565 goto finish;
568 if (copy_note_for_rewrite(c, from_obj, to_obj))
569 ret = error(_("Failed to copy notes from '%s' to '%s'"),
570 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
573 finish:
574 finish_copy_notes_for_rewrite(c, msg);
575 fclose(fp);
576 strbuf_release(&sb);
577 return ret;
581 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
582 * non-indented lines and checking if they look like they begin with valid
583 * header field names.
585 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
587 static int is_mail(FILE *fp)
589 const char *header_regex = "^[!-9;-~]+:";
590 struct strbuf sb = STRBUF_INIT;
591 regex_t regex;
592 int ret = 1;
594 if (fseek(fp, 0L, SEEK_SET))
595 die_errno(_("fseek failed"));
597 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
598 die("invalid pattern: %s", header_regex);
600 while (!strbuf_getline_crlf(&sb, fp)) {
601 if (!sb.len)
602 break; /* End of header */
604 /* Ignore indented folded lines */
605 if (*sb.buf == '\t' || *sb.buf == ' ')
606 continue;
608 /* It's a header if it matches header_regex */
609 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
610 ret = 0;
611 goto done;
615 done:
616 regfree(&regex);
617 strbuf_release(&sb);
618 return ret;
622 * Attempts to detect the patch_format of the patches contained in `paths`,
623 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
624 * detection fails.
626 static int detect_patch_format(const char **paths)
628 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
629 struct strbuf l1 = STRBUF_INIT;
630 struct strbuf l2 = STRBUF_INIT;
631 struct strbuf l3 = STRBUF_INIT;
632 FILE *fp;
635 * We default to mbox format if input is from stdin and for directories
637 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
638 return PATCH_FORMAT_MBOX;
641 * Otherwise, check the first few lines of the first patch, starting
642 * from the first non-blank line, to try to detect its format.
645 fp = xfopen(*paths, "r");
647 while (!strbuf_getline_crlf(&l1, fp)) {
648 if (l1.len)
649 break;
652 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
653 ret = PATCH_FORMAT_MBOX;
654 goto done;
657 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
658 ret = PATCH_FORMAT_STGIT_SERIES;
659 goto done;
662 if (!strcmp(l1.buf, "# HG changeset patch")) {
663 ret = PATCH_FORMAT_HG;
664 goto done;
667 strbuf_reset(&l2);
668 strbuf_getline_crlf(&l2, fp);
669 strbuf_reset(&l3);
670 strbuf_getline_crlf(&l3, fp);
673 * If the second line is empty and the third is a From, Author or Date
674 * entry, this is likely an StGit patch.
676 if (l1.len && !l2.len &&
677 (starts_with(l3.buf, "From:") ||
678 starts_with(l3.buf, "Author:") ||
679 starts_with(l3.buf, "Date:"))) {
680 ret = PATCH_FORMAT_STGIT;
681 goto done;
684 if (l1.len && is_mail(fp)) {
685 ret = PATCH_FORMAT_MBOX;
686 goto done;
689 done:
690 fclose(fp);
691 strbuf_release(&l1);
692 return ret;
696 * Splits out individual email patches from `paths`, where each path is either
697 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
699 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
701 struct child_process cp = CHILD_PROCESS_INIT;
702 struct strbuf last = STRBUF_INIT;
704 cp.git_cmd = 1;
705 argv_array_push(&cp.args, "mailsplit");
706 argv_array_pushf(&cp.args, "-d%d", state->prec);
707 argv_array_pushf(&cp.args, "-o%s", state->dir);
708 argv_array_push(&cp.args, "-b");
709 if (keep_cr)
710 argv_array_push(&cp.args, "--keep-cr");
711 argv_array_push(&cp.args, "--");
712 argv_array_pushv(&cp.args, paths);
714 if (capture_command(&cp, &last, 8))
715 return -1;
717 state->cur = 1;
718 state->last = strtol(last.buf, NULL, 10);
720 return 0;
724 * Callback signature for split_mail_conv(). The foreign patch should be
725 * read from `in`, and the converted patch (in RFC2822 mail format) should be
726 * written to `out`. Return 0 on success, or -1 on failure.
728 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
731 * Calls `fn` for each file in `paths` to convert the foreign patch to the
732 * RFC2822 mail format suitable for parsing with git-mailinfo.
734 * Returns 0 on success, -1 on failure.
736 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
737 const char **paths, int keep_cr)
739 static const char *stdin_only[] = {"-", NULL};
740 int i;
742 if (!*paths)
743 paths = stdin_only;
745 for (i = 0; *paths; paths++, i++) {
746 FILE *in, *out;
747 const char *mail;
748 int ret;
750 if (!strcmp(*paths, "-"))
751 in = stdin;
752 else
753 in = fopen(*paths, "r");
755 if (!in)
756 return error(_("could not open '%s' for reading: %s"),
757 *paths, strerror(errno));
759 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
761 out = fopen(mail, "w");
762 if (!out)
763 return error(_("could not open '%s' for writing: %s"),
764 mail, strerror(errno));
766 ret = fn(out, in, keep_cr);
768 fclose(out);
769 fclose(in);
771 if (ret)
772 return error(_("could not parse patch '%s'"), *paths);
775 state->cur = 1;
776 state->last = i;
777 return 0;
781 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
782 * message suitable for parsing with git-mailinfo.
784 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
786 struct strbuf sb = STRBUF_INIT;
787 int subject_printed = 0;
789 while (!strbuf_getline(&sb, in, '\n')) {
790 const char *str;
792 if (str_isspace(sb.buf))
793 continue;
794 else if (skip_prefix(sb.buf, "Author:", &str))
795 fprintf(out, "From:%s\n", str);
796 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
797 fprintf(out, "%s\n", sb.buf);
798 else if (!subject_printed) {
799 fprintf(out, "Subject: %s\n", sb.buf);
800 subject_printed = 1;
801 } else {
802 fprintf(out, "\n%s\n", sb.buf);
803 break;
807 strbuf_reset(&sb);
808 while (strbuf_fread(&sb, 8192, in) > 0) {
809 fwrite(sb.buf, 1, sb.len, out);
810 strbuf_reset(&sb);
813 strbuf_release(&sb);
814 return 0;
818 * This function only supports a single StGit series file in `paths`.
820 * Given an StGit series file, converts the StGit patches in the series into
821 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
822 * the state directory.
824 * Returns 0 on success, -1 on failure.
826 static int split_mail_stgit_series(struct am_state *state, const char **paths,
827 int keep_cr)
829 const char *series_dir;
830 char *series_dir_buf;
831 FILE *fp;
832 struct argv_array patches = ARGV_ARRAY_INIT;
833 struct strbuf sb = STRBUF_INIT;
834 int ret;
836 if (!paths[0] || paths[1])
837 return error(_("Only one StGIT patch series can be applied at once"));
839 series_dir_buf = xstrdup(*paths);
840 series_dir = dirname(series_dir_buf);
842 fp = fopen(*paths, "r");
843 if (!fp)
844 return error(_("could not open '%s' for reading: %s"), *paths,
845 strerror(errno));
847 while (!strbuf_getline(&sb, fp, '\n')) {
848 if (*sb.buf == '#')
849 continue; /* skip comment lines */
851 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
854 fclose(fp);
855 strbuf_release(&sb);
856 free(series_dir_buf);
858 ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
860 argv_array_clear(&patches);
861 return ret;
865 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
866 * message suitable for parsing with git-mailinfo.
868 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
870 struct strbuf sb = STRBUF_INIT;
872 while (!strbuf_getline(&sb, in, '\n')) {
873 const char *str;
875 if (skip_prefix(sb.buf, "# User ", &str))
876 fprintf(out, "From: %s\n", str);
877 else if (skip_prefix(sb.buf, "# Date ", &str)) {
878 unsigned long timestamp;
879 long tz, tz2;
880 char *end;
882 errno = 0;
883 timestamp = strtoul(str, &end, 10);
884 if (errno)
885 return error(_("invalid timestamp"));
887 if (!skip_prefix(end, " ", &str))
888 return error(_("invalid Date line"));
890 errno = 0;
891 tz = strtol(str, &end, 10);
892 if (errno)
893 return error(_("invalid timezone offset"));
895 if (*end)
896 return error(_("invalid Date line"));
899 * mercurial's timezone is in seconds west of UTC,
900 * however git's timezone is in hours + minutes east of
901 * UTC. Convert it.
903 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
904 if (tz > 0)
905 tz2 = -tz2;
907 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
908 } else if (starts_with(sb.buf, "# ")) {
909 continue;
910 } else {
911 fprintf(out, "\n%s\n", sb.buf);
912 break;
916 strbuf_reset(&sb);
917 while (strbuf_fread(&sb, 8192, in) > 0) {
918 fwrite(sb.buf, 1, sb.len, out);
919 strbuf_reset(&sb);
922 strbuf_release(&sb);
923 return 0;
927 * Splits a list of files/directories into individual email patches. Each path
928 * in `paths` must be a file/directory that is formatted according to
929 * `patch_format`.
931 * Once split out, the individual email patches will be stored in the state
932 * directory, with each patch's filename being its index, padded to state->prec
933 * digits.
935 * state->cur will be set to the index of the first mail, and state->last will
936 * be set to the index of the last mail.
938 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
939 * to disable this behavior, -1 to use the default configured setting.
941 * Returns 0 on success, -1 on failure.
943 static int split_mail(struct am_state *state, enum patch_format patch_format,
944 const char **paths, int keep_cr)
946 if (keep_cr < 0) {
947 keep_cr = 0;
948 git_config_get_bool("am.keepcr", &keep_cr);
951 switch (patch_format) {
952 case PATCH_FORMAT_MBOX:
953 return split_mail_mbox(state, paths, keep_cr);
954 case PATCH_FORMAT_STGIT:
955 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
956 case PATCH_FORMAT_STGIT_SERIES:
957 return split_mail_stgit_series(state, paths, keep_cr);
958 case PATCH_FORMAT_HG:
959 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
960 default:
961 die("BUG: invalid patch_format");
963 return -1;
967 * Setup a new am session for applying patches
969 static void am_setup(struct am_state *state, enum patch_format patch_format,
970 const char **paths, int keep_cr)
972 unsigned char curr_head[GIT_SHA1_RAWSZ];
973 const char *str;
974 struct strbuf sb = STRBUF_INIT;
976 if (!patch_format)
977 patch_format = detect_patch_format(paths);
979 if (!patch_format) {
980 fprintf_ln(stderr, _("Patch format detection failed."));
981 exit(128);
984 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
985 die_errno(_("failed to create directory '%s'"), state->dir);
987 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
988 am_destroy(state);
989 die(_("Failed to split patches."));
992 if (state->rebasing)
993 state->threeway = 1;
995 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
997 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
999 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
1001 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
1003 switch (state->keep) {
1004 case KEEP_FALSE:
1005 str = "f";
1006 break;
1007 case KEEP_TRUE:
1008 str = "t";
1009 break;
1010 case KEEP_NON_PATCH:
1011 str = "b";
1012 break;
1013 default:
1014 die("BUG: invalid value for state->keep");
1017 write_file(am_path(state, "keep"), 1, "%s", str);
1019 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
1021 switch (state->scissors) {
1022 case SCISSORS_UNSET:
1023 str = "";
1024 break;
1025 case SCISSORS_FALSE:
1026 str = "f";
1027 break;
1028 case SCISSORS_TRUE:
1029 str = "t";
1030 break;
1031 default:
1032 die("BUG: invalid value for state->scissors");
1035 write_file(am_path(state, "scissors"), 1, "%s", str);
1037 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1038 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
1040 if (state->rebasing)
1041 write_file(am_path(state, "rebasing"), 1, "%s", "");
1042 else
1043 write_file(am_path(state, "applying"), 1, "%s", "");
1045 if (!get_sha1("HEAD", curr_head)) {
1046 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
1047 if (!state->rebasing)
1048 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
1049 UPDATE_REFS_DIE_ON_ERR);
1050 } else {
1051 write_file(am_path(state, "abort-safety"), 1, "%s", "");
1052 if (!state->rebasing)
1053 delete_ref("ORIG_HEAD", NULL, 0);
1057 * NOTE: Since the "next" and "last" files determine if an am_state
1058 * session is in progress, they should be written last.
1061 write_file(am_path(state, "next"), 1, "%d", state->cur);
1063 write_file(am_path(state, "last"), 1, "%d", state->last);
1065 strbuf_release(&sb);
1069 * Increments the patch pointer, and cleans am_state for the application of the
1070 * next patch.
1072 static void am_next(struct am_state *state)
1074 unsigned char head[GIT_SHA1_RAWSZ];
1076 free(state->author_name);
1077 state->author_name = NULL;
1079 free(state->author_email);
1080 state->author_email = NULL;
1082 free(state->author_date);
1083 state->author_date = NULL;
1085 free(state->msg);
1086 state->msg = NULL;
1087 state->msg_len = 0;
1089 unlink(am_path(state, "author-script"));
1090 unlink(am_path(state, "final-commit"));
1092 hashclr(state->orig_commit);
1093 unlink(am_path(state, "original-commit"));
1095 if (!get_sha1("HEAD", head))
1096 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
1097 else
1098 write_file(am_path(state, "abort-safety"), 1, "%s", "");
1100 state->cur++;
1101 write_file(am_path(state, "next"), 1, "%d", state->cur);
1105 * Returns the filename of the current patch email.
1107 static const char *msgnum(const struct am_state *state)
1109 static struct strbuf sb = STRBUF_INIT;
1111 strbuf_reset(&sb);
1112 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1114 return sb.buf;
1118 * Refresh and write index.
1120 static void refresh_and_write_cache(void)
1122 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1124 hold_locked_index(lock_file, 1);
1125 refresh_cache(REFRESH_QUIET);
1126 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1127 die(_("unable to write index file"));
1131 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1132 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1133 * strbuf is provided, the space-separated list of files that differ will be
1134 * appended to it.
1136 static int index_has_changes(struct strbuf *sb)
1138 unsigned char head[GIT_SHA1_RAWSZ];
1139 int i;
1141 if (!get_sha1_tree("HEAD", head)) {
1142 struct diff_options opt;
1144 diff_setup(&opt);
1145 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
1146 if (!sb)
1147 DIFF_OPT_SET(&opt, QUICK);
1148 do_diff_cache(head, &opt);
1149 diffcore_std(&opt);
1150 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1151 if (i)
1152 strbuf_addch(sb, ' ');
1153 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1155 diff_flush(&opt);
1156 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
1157 } else {
1158 for (i = 0; sb && i < active_nr; i++) {
1159 if (i)
1160 strbuf_addch(sb, ' ');
1161 strbuf_addstr(sb, active_cache[i]->name);
1163 return !!active_nr;
1168 * Dies with a user-friendly message on how to proceed after resolving the
1169 * problem. This message can be overridden with state->resolvemsg.
1171 static void NORETURN die_user_resolve(const struct am_state *state)
1173 if (state->resolvemsg) {
1174 printf_ln("%s", state->resolvemsg);
1175 } else {
1176 const char *cmdline = state->interactive ? "git am -i" : "git am";
1178 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1179 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1180 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1183 exit(128);
1187 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1188 * state->msg will be set to the patch message. state->author_name,
1189 * state->author_email and state->author_date will be set to the patch author's
1190 * name, email and date respectively. The patch body will be written to the
1191 * state directory's "patch" file.
1193 * Returns 1 if the patch should be skipped, 0 otherwise.
1195 static int parse_mail(struct am_state *state, const char *mail)
1197 FILE *fp;
1198 struct child_process cp = CHILD_PROCESS_INIT;
1199 struct strbuf sb = STRBUF_INIT;
1200 struct strbuf msg = STRBUF_INIT;
1201 struct strbuf author_name = STRBUF_INIT;
1202 struct strbuf author_date = STRBUF_INIT;
1203 struct strbuf author_email = STRBUF_INIT;
1204 int ret = 0;
1206 cp.git_cmd = 1;
1207 cp.in = xopen(mail, O_RDONLY, 0);
1208 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
1210 argv_array_push(&cp.args, "mailinfo");
1211 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
1213 switch (state->keep) {
1214 case KEEP_FALSE:
1215 break;
1216 case KEEP_TRUE:
1217 argv_array_push(&cp.args, "-k");
1218 break;
1219 case KEEP_NON_PATCH:
1220 argv_array_push(&cp.args, "-b");
1221 break;
1222 default:
1223 die("BUG: invalid value for state->keep");
1226 if (state->message_id)
1227 argv_array_push(&cp.args, "-m");
1229 switch (state->scissors) {
1230 case SCISSORS_UNSET:
1231 break;
1232 case SCISSORS_FALSE:
1233 argv_array_push(&cp.args, "--no-scissors");
1234 break;
1235 case SCISSORS_TRUE:
1236 argv_array_push(&cp.args, "--scissors");
1237 break;
1238 default:
1239 die("BUG: invalid value for state->scissors");
1242 argv_array_push(&cp.args, am_path(state, "msg"));
1243 argv_array_push(&cp.args, am_path(state, "patch"));
1245 if (run_command(&cp) < 0)
1246 die("could not parse patch");
1248 close(cp.in);
1249 close(cp.out);
1251 /* Extract message and author information */
1252 fp = xfopen(am_path(state, "info"), "r");
1253 while (!strbuf_getline(&sb, fp, '\n')) {
1254 const char *x;
1256 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1257 if (msg.len)
1258 strbuf_addch(&msg, '\n');
1259 strbuf_addstr(&msg, x);
1260 } else if (skip_prefix(sb.buf, "Author: ", &x))
1261 strbuf_addstr(&author_name, x);
1262 else if (skip_prefix(sb.buf, "Email: ", &x))
1263 strbuf_addstr(&author_email, x);
1264 else if (skip_prefix(sb.buf, "Date: ", &x))
1265 strbuf_addstr(&author_date, x);
1267 fclose(fp);
1269 /* Skip pine's internal folder data */
1270 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1271 ret = 1;
1272 goto finish;
1275 if (is_empty_file(am_path(state, "patch"))) {
1276 printf_ln(_("Patch is empty. Was it split wrong?"));
1277 die_user_resolve(state);
1280 strbuf_addstr(&msg, "\n\n");
1281 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
1282 die_errno(_("could not read '%s'"), am_path(state, "msg"));
1283 stripspace(&msg, 0);
1285 if (state->signoff)
1286 append_signoff(&msg, 0, 0);
1288 assert(!state->author_name);
1289 state->author_name = strbuf_detach(&author_name, NULL);
1291 assert(!state->author_email);
1292 state->author_email = strbuf_detach(&author_email, NULL);
1294 assert(!state->author_date);
1295 state->author_date = strbuf_detach(&author_date, NULL);
1297 assert(!state->msg);
1298 state->msg = strbuf_detach(&msg, &state->msg_len);
1300 finish:
1301 strbuf_release(&msg);
1302 strbuf_release(&author_date);
1303 strbuf_release(&author_email);
1304 strbuf_release(&author_name);
1305 strbuf_release(&sb);
1306 return ret;
1310 * Sets commit_id to the commit hash where the mail was generated from.
1311 * Returns 0 on success, -1 on failure.
1313 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1315 struct strbuf sb = STRBUF_INIT;
1316 FILE *fp = xfopen(mail, "r");
1317 const char *x;
1319 if (strbuf_getline(&sb, fp, '\n'))
1320 return -1;
1322 if (!skip_prefix(sb.buf, "From ", &x))
1323 return -1;
1325 if (get_sha1_hex(x, commit_id) < 0)
1326 return -1;
1328 strbuf_release(&sb);
1329 fclose(fp);
1330 return 0;
1334 * Sets state->msg, state->author_name, state->author_email, state->author_date
1335 * to the commit's respective info.
1337 static void get_commit_info(struct am_state *state, struct commit *commit)
1339 const char *buffer, *ident_line, *author_date, *msg;
1340 size_t ident_len;
1341 struct ident_split ident_split;
1342 struct strbuf sb = STRBUF_INIT;
1344 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1346 ident_line = find_commit_header(buffer, "author", &ident_len);
1348 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1349 strbuf_add(&sb, ident_line, ident_len);
1350 die(_("invalid ident line: %s"), sb.buf);
1353 assert(!state->author_name);
1354 if (ident_split.name_begin) {
1355 strbuf_add(&sb, ident_split.name_begin,
1356 ident_split.name_end - ident_split.name_begin);
1357 state->author_name = strbuf_detach(&sb, NULL);
1358 } else
1359 state->author_name = xstrdup("");
1361 assert(!state->author_email);
1362 if (ident_split.mail_begin) {
1363 strbuf_add(&sb, ident_split.mail_begin,
1364 ident_split.mail_end - ident_split.mail_begin);
1365 state->author_email = strbuf_detach(&sb, NULL);
1366 } else
1367 state->author_email = xstrdup("");
1369 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1370 strbuf_addstr(&sb, author_date);
1371 assert(!state->author_date);
1372 state->author_date = strbuf_detach(&sb, NULL);
1374 assert(!state->msg);
1375 msg = strstr(buffer, "\n\n");
1376 if (!msg)
1377 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1378 state->msg = xstrdup(msg + 2);
1379 state->msg_len = strlen(state->msg);
1383 * Writes `commit` as a patch to the state directory's "patch" file.
1385 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1387 struct rev_info rev_info;
1388 FILE *fp;
1390 fp = xfopen(am_path(state, "patch"), "w");
1391 init_revisions(&rev_info, NULL);
1392 rev_info.diff = 1;
1393 rev_info.abbrev = 0;
1394 rev_info.disable_stdin = 1;
1395 rev_info.show_root_diff = 1;
1396 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1397 rev_info.no_commit_id = 1;
1398 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1399 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1400 rev_info.diffopt.use_color = 0;
1401 rev_info.diffopt.file = fp;
1402 rev_info.diffopt.close_file = 1;
1403 add_pending_object(&rev_info, &commit->object, "");
1404 diff_setup_done(&rev_info.diffopt);
1405 log_tree_commit(&rev_info, commit);
1409 * Writes the diff of the index against HEAD as a patch to the state
1410 * directory's "patch" file.
1412 static void write_index_patch(const struct am_state *state)
1414 struct tree *tree;
1415 unsigned char head[GIT_SHA1_RAWSZ];
1416 struct rev_info rev_info;
1417 FILE *fp;
1419 if (!get_sha1_tree("HEAD", head))
1420 tree = lookup_tree(head);
1421 else
1422 tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
1424 fp = xfopen(am_path(state, "patch"), "w");
1425 init_revisions(&rev_info, NULL);
1426 rev_info.diff = 1;
1427 rev_info.disable_stdin = 1;
1428 rev_info.no_commit_id = 1;
1429 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1430 rev_info.diffopt.use_color = 0;
1431 rev_info.diffopt.file = fp;
1432 rev_info.diffopt.close_file = 1;
1433 add_pending_object(&rev_info, &tree->object, "");
1434 diff_setup_done(&rev_info.diffopt);
1435 run_diff_index(&rev_info, 1);
1439 * Like parse_mail(), but parses the mail by looking up its commit ID
1440 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1441 * of patches.
1443 * state->orig_commit will be set to the original commit ID.
1445 * Will always return 0 as the patch should never be skipped.
1447 static int parse_mail_rebase(struct am_state *state, const char *mail)
1449 struct commit *commit;
1450 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1452 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1453 die(_("could not parse %s"), mail);
1455 commit = lookup_commit_or_die(commit_sha1, mail);
1457 get_commit_info(state, commit);
1459 write_commit_patch(state, commit);
1461 hashcpy(state->orig_commit, commit_sha1);
1462 write_file(am_path(state, "original-commit"), 1, "%s",
1463 sha1_to_hex(commit_sha1));
1465 return 0;
1469 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1470 * `index_file` is not NULL, the patch will be applied to that index.
1472 static int run_apply(const struct am_state *state, const char *index_file)
1474 struct child_process cp = CHILD_PROCESS_INIT;
1476 cp.git_cmd = 1;
1478 if (index_file)
1479 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1482 * If we are allowed to fall back on 3-way merge, don't give false
1483 * errors during the initial attempt.
1485 if (state->threeway && !index_file) {
1486 cp.no_stdout = 1;
1487 cp.no_stderr = 1;
1490 argv_array_push(&cp.args, "apply");
1492 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1494 if (index_file)
1495 argv_array_push(&cp.args, "--cached");
1496 else
1497 argv_array_push(&cp.args, "--index");
1499 argv_array_push(&cp.args, am_path(state, "patch"));
1501 if (run_command(&cp))
1502 return -1;
1504 /* Reload index as git-apply will have modified it. */
1505 discard_cache();
1506 read_cache_from(index_file ? index_file : get_index_file());
1508 return 0;
1512 * Builds an index that contains just the blobs needed for a 3way merge.
1514 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1516 struct child_process cp = CHILD_PROCESS_INIT;
1518 cp.git_cmd = 1;
1519 argv_array_push(&cp.args, "apply");
1520 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1521 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1522 argv_array_push(&cp.args, am_path(state, "patch"));
1524 if (run_command(&cp))
1525 return -1;
1527 return 0;
1531 * Attempt a threeway merge, using index_path as the temporary index.
1533 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1535 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1536 our_tree[GIT_SHA1_RAWSZ];
1537 const unsigned char *bases[1] = {orig_tree};
1538 struct merge_options o;
1539 struct commit *result;
1540 char *his_tree_name;
1542 if (get_sha1("HEAD", our_tree) < 0)
1543 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1545 if (build_fake_ancestor(state, index_path))
1546 return error("could not build fake ancestor");
1548 discard_cache();
1549 read_cache_from(index_path);
1551 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1552 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1554 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1556 if (!state->quiet) {
1558 * List paths that needed 3-way fallback, so that the user can
1559 * review them with extra care to spot mismerges.
1561 struct rev_info rev_info;
1562 const char *diff_filter_str = "--diff-filter=AM";
1564 init_revisions(&rev_info, NULL);
1565 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1566 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1567 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1568 diff_setup_done(&rev_info.diffopt);
1569 run_diff_index(&rev_info, 1);
1572 if (run_apply(state, index_path))
1573 return error(_("Did you hand edit your patch?\n"
1574 "It does not apply to blobs recorded in its index."));
1576 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1577 return error("could not write tree");
1579 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1581 discard_cache();
1582 read_cache();
1585 * This is not so wrong. Depending on which base we picked, orig_tree
1586 * may be wildly different from ours, but his_tree has the same set of
1587 * wildly different changes in parts the patch did not touch, so
1588 * recursive ends up canceling them, saying that we reverted all those
1589 * changes.
1592 init_merge_options(&o);
1594 o.branch1 = "HEAD";
1595 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1596 o.branch2 = his_tree_name;
1598 if (state->quiet)
1599 o.verbosity = 0;
1601 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1602 rerere(state->allow_rerere_autoupdate);
1603 free(his_tree_name);
1604 return error(_("Failed to merge in the changes."));
1607 free(his_tree_name);
1608 return 0;
1612 * Commits the current index with state->msg as the commit message and
1613 * state->author_name, state->author_email and state->author_date as the author
1614 * information.
1616 static void do_commit(const struct am_state *state)
1618 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1619 commit[GIT_SHA1_RAWSZ];
1620 unsigned char *ptr;
1621 struct commit_list *parents = NULL;
1622 const char *reflog_msg, *author;
1623 struct strbuf sb = STRBUF_INIT;
1625 if (run_hook_le(NULL, "pre-applypatch", NULL))
1626 exit(1);
1628 if (write_cache_as_tree(tree, 0, NULL))
1629 die(_("git write-tree failed to write a tree"));
1631 if (!get_sha1_commit("HEAD", parent)) {
1632 ptr = parent;
1633 commit_list_insert(lookup_commit(parent), &parents);
1634 } else {
1635 ptr = NULL;
1636 say(state, stderr, _("applying to an empty history"));
1639 author = fmt_ident(state->author_name, state->author_email,
1640 state->ignore_date ? NULL : state->author_date,
1641 IDENT_STRICT);
1643 if (state->committer_date_is_author_date)
1644 setenv("GIT_COMMITTER_DATE",
1645 state->ignore_date ? "" : state->author_date, 1);
1647 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1648 author, state->sign_commit))
1649 die(_("failed to write commit object"));
1651 reflog_msg = getenv("GIT_REFLOG_ACTION");
1652 if (!reflog_msg)
1653 reflog_msg = "am";
1655 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1656 state->msg);
1658 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1660 if (state->rebasing) {
1661 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1663 assert(!is_null_sha1(state->orig_commit));
1664 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1665 fprintf(fp, "%s\n", sha1_to_hex(commit));
1666 fclose(fp);
1669 run_hook_le(NULL, "post-applypatch", NULL);
1671 strbuf_release(&sb);
1675 * Validates the am_state for resuming -- the "msg" and authorship fields must
1676 * be filled up.
1678 static void validate_resume_state(const struct am_state *state)
1680 if (!state->msg)
1681 die(_("cannot resume: %s does not exist."),
1682 am_path(state, "final-commit"));
1684 if (!state->author_name || !state->author_email || !state->author_date)
1685 die(_("cannot resume: %s does not exist."),
1686 am_path(state, "author-script"));
1690 * Interactively prompt the user on whether the current patch should be
1691 * applied.
1693 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1694 * skip it.
1696 static int do_interactive(struct am_state *state)
1698 assert(state->msg);
1700 if (!isatty(0))
1701 die(_("cannot be interactive without stdin connected to a terminal."));
1703 for (;;) {
1704 const char *reply;
1706 puts(_("Commit Body is:"));
1707 puts("--------------------------");
1708 printf("%s", state->msg);
1709 puts("--------------------------");
1712 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1713 * in your translation. The program will only accept English
1714 * input at this point.
1716 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1718 if (!reply) {
1719 continue;
1720 } else if (*reply == 'y' || *reply == 'Y') {
1721 return 0;
1722 } else if (*reply == 'a' || *reply == 'A') {
1723 state->interactive = 0;
1724 return 0;
1725 } else if (*reply == 'n' || *reply == 'N') {
1726 return 1;
1727 } else if (*reply == 'e' || *reply == 'E') {
1728 struct strbuf msg = STRBUF_INIT;
1730 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1731 free(state->msg);
1732 state->msg = strbuf_detach(&msg, &state->msg_len);
1734 strbuf_release(&msg);
1735 } else if (*reply == 'v' || *reply == 'V') {
1736 const char *pager = git_pager(1);
1737 struct child_process cp = CHILD_PROCESS_INIT;
1739 if (!pager)
1740 pager = "cat";
1741 argv_array_push(&cp.args, pager);
1742 argv_array_push(&cp.args, am_path(state, "patch"));
1743 run_command(&cp);
1749 * Applies all queued mail.
1751 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1752 * well as the state directory's "patch" file is used as-is for applying the
1753 * patch and committing it.
1755 static void am_run(struct am_state *state, int resume)
1757 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1758 struct strbuf sb = STRBUF_INIT;
1760 unlink(am_path(state, "dirtyindex"));
1762 refresh_and_write_cache();
1764 if (index_has_changes(&sb)) {
1765 write_file(am_path(state, "dirtyindex"), 1, "t");
1766 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1769 strbuf_release(&sb);
1771 while (state->cur <= state->last) {
1772 const char *mail = am_path(state, msgnum(state));
1773 int apply_status;
1775 if (!file_exists(mail))
1776 goto next;
1778 if (resume) {
1779 validate_resume_state(state);
1780 resume = 0;
1781 } else {
1782 int skip;
1784 if (state->rebasing)
1785 skip = parse_mail_rebase(state, mail);
1786 else
1787 skip = parse_mail(state, mail);
1789 if (skip)
1790 goto next; /* mail should be skipped */
1792 write_author_script(state);
1793 write_commit_msg(state);
1796 if (state->interactive && do_interactive(state))
1797 goto next;
1799 if (run_applypatch_msg_hook(state))
1800 exit(1);
1802 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1804 apply_status = run_apply(state, NULL);
1806 if (apply_status && state->threeway) {
1807 struct strbuf sb = STRBUF_INIT;
1809 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1810 apply_status = fall_back_threeway(state, sb.buf);
1811 strbuf_release(&sb);
1814 * Applying the patch to an earlier tree and merging
1815 * the result may have produced the same tree as ours.
1817 if (!apply_status && !index_has_changes(NULL)) {
1818 say(state, stdout, _("No changes -- Patch already applied."));
1819 goto next;
1823 if (apply_status) {
1824 int advice_amworkdir = 1;
1826 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1827 linelen(state->msg), state->msg);
1829 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1831 if (advice_amworkdir)
1832 printf_ln(_("The copy of the patch that failed is found in: %s"),
1833 am_path(state, "patch"));
1835 die_user_resolve(state);
1838 do_commit(state);
1840 next:
1841 am_next(state);
1844 if (!is_empty_file(am_path(state, "rewritten"))) {
1845 assert(state->rebasing);
1846 copy_notes_for_rebase(state);
1847 run_post_rewrite_hook(state);
1851 * In rebasing mode, it's up to the caller to take care of
1852 * housekeeping.
1854 if (!state->rebasing) {
1855 am_destroy(state);
1856 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1861 * Resume the current am session after patch application failure. The user did
1862 * all the hard work, and we do not have to do any patch application. Just
1863 * trust and commit what the user has in the index and working tree.
1865 static void am_resolve(struct am_state *state)
1867 validate_resume_state(state);
1869 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1871 if (!index_has_changes(NULL)) {
1872 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1873 "If there is nothing left to stage, chances are that something else\n"
1874 "already introduced the same changes; you might want to skip this patch."));
1875 die_user_resolve(state);
1878 if (unmerged_cache()) {
1879 printf_ln(_("You still have unmerged paths in your index.\n"
1880 "Did you forget to use 'git add'?"));
1881 die_user_resolve(state);
1884 if (state->interactive) {
1885 write_index_patch(state);
1886 if (do_interactive(state))
1887 goto next;
1890 rerere(0);
1892 do_commit(state);
1894 next:
1895 am_next(state);
1896 am_run(state, 0);
1900 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1901 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1902 * failure.
1904 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1906 struct lock_file *lock_file;
1907 struct unpack_trees_options opts;
1908 struct tree_desc t[2];
1910 if (parse_tree(head) || parse_tree(remote))
1911 return -1;
1913 lock_file = xcalloc(1, sizeof(struct lock_file));
1914 hold_locked_index(lock_file, 1);
1916 refresh_cache(REFRESH_QUIET);
1918 memset(&opts, 0, sizeof(opts));
1919 opts.head_idx = 1;
1920 opts.src_index = &the_index;
1921 opts.dst_index = &the_index;
1922 opts.update = 1;
1923 opts.merge = 1;
1924 opts.reset = reset;
1925 opts.fn = twoway_merge;
1926 init_tree_desc(&t[0], head->buffer, head->size);
1927 init_tree_desc(&t[1], remote->buffer, remote->size);
1929 if (unpack_trees(2, t, &opts)) {
1930 rollback_lock_file(lock_file);
1931 return -1;
1934 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1935 die(_("unable to write new index file"));
1937 return 0;
1941 * Clean the index without touching entries that are not modified between
1942 * `head` and `remote`.
1944 static int clean_index(const unsigned char *head, const unsigned char *remote)
1946 struct lock_file *lock_file;
1947 struct tree *head_tree, *remote_tree, *index_tree;
1948 unsigned char index[GIT_SHA1_RAWSZ];
1949 struct pathspec pathspec;
1951 head_tree = parse_tree_indirect(head);
1952 if (!head_tree)
1953 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1955 remote_tree = parse_tree_indirect(remote);
1956 if (!remote_tree)
1957 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1959 read_cache_unmerged();
1961 if (fast_forward_to(head_tree, head_tree, 1))
1962 return -1;
1964 if (write_cache_as_tree(index, 0, NULL))
1965 return -1;
1967 index_tree = parse_tree_indirect(index);
1968 if (!index_tree)
1969 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1971 if (fast_forward_to(index_tree, remote_tree, 0))
1972 return -1;
1974 memset(&pathspec, 0, sizeof(pathspec));
1976 lock_file = xcalloc(1, sizeof(struct lock_file));
1977 hold_locked_index(lock_file, 1);
1979 if (read_tree(remote_tree, 0, &pathspec)) {
1980 rollback_lock_file(lock_file);
1981 return -1;
1984 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1985 die(_("unable to write new index file"));
1987 remove_branch_state();
1989 return 0;
1993 * Resets rerere's merge resolution metadata.
1995 static void am_rerere_clear(void)
1997 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1998 int fd = setup_rerere(&merge_rr, 0);
2000 if (fd < 0)
2001 return;
2003 rerere_clear(&merge_rr);
2004 string_list_clear(&merge_rr, 1);
2008 * Resume the current am session by skipping the current patch.
2010 static void am_skip(struct am_state *state)
2012 unsigned char head[GIT_SHA1_RAWSZ];
2014 am_rerere_clear();
2016 if (get_sha1("HEAD", head))
2017 hashcpy(head, EMPTY_TREE_SHA1_BIN);
2019 if (clean_index(head, head))
2020 die(_("failed to clean index"));
2022 am_next(state);
2023 am_run(state, 0);
2027 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2029 * It is not safe to reset HEAD when:
2030 * 1. git-am previously failed because the index was dirty.
2031 * 2. HEAD has moved since git-am previously failed.
2033 static int safe_to_abort(const struct am_state *state)
2035 struct strbuf sb = STRBUF_INIT;
2036 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
2038 if (file_exists(am_path(state, "dirtyindex")))
2039 return 0;
2041 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2042 if (get_sha1_hex(sb.buf, abort_safety))
2043 die(_("could not parse %s"), am_path(state, "abort_safety"));
2044 } else
2045 hashclr(abort_safety);
2047 if (get_sha1("HEAD", head))
2048 hashclr(head);
2050 if (!hashcmp(head, abort_safety))
2051 return 1;
2053 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2054 "Not rewinding to ORIG_HEAD"));
2056 return 0;
2060 * Aborts the current am session if it is safe to do so.
2062 static void am_abort(struct am_state *state)
2064 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
2065 int has_curr_head, has_orig_head;
2066 char *curr_branch;
2068 if (!safe_to_abort(state)) {
2069 am_destroy(state);
2070 return;
2073 am_rerere_clear();
2075 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
2076 has_curr_head = !is_null_sha1(curr_head);
2077 if (!has_curr_head)
2078 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
2080 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
2081 if (!has_orig_head)
2082 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
2084 clean_index(curr_head, orig_head);
2086 if (has_orig_head)
2087 update_ref("am --abort", "HEAD", orig_head,
2088 has_curr_head ? curr_head : NULL, 0,
2089 UPDATE_REFS_DIE_ON_ERR);
2090 else if (curr_branch)
2091 delete_ref(curr_branch, NULL, REF_NODEREF);
2093 free(curr_branch);
2094 am_destroy(state);
2098 * parse_options() callback that validates and sets opt->value to the
2099 * PATCH_FORMAT_* enum value corresponding to `arg`.
2101 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2103 int *opt_value = opt->value;
2105 if (!strcmp(arg, "mbox"))
2106 *opt_value = PATCH_FORMAT_MBOX;
2107 else if (!strcmp(arg, "stgit"))
2108 *opt_value = PATCH_FORMAT_STGIT;
2109 else if (!strcmp(arg, "stgit-series"))
2110 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2111 else if (!strcmp(arg, "hg"))
2112 *opt_value = PATCH_FORMAT_HG;
2113 else
2114 return error(_("Invalid value for --patch-format: %s"), arg);
2115 return 0;
2118 enum resume_mode {
2119 RESUME_FALSE = 0,
2120 RESUME_APPLY,
2121 RESUME_RESOLVED,
2122 RESUME_SKIP,
2123 RESUME_ABORT
2126 int cmd_am(int argc, const char **argv, const char *prefix)
2128 struct am_state state;
2129 int binary = -1;
2130 int keep_cr = -1;
2131 int patch_format = PATCH_FORMAT_UNKNOWN;
2132 enum resume_mode resume = RESUME_FALSE;
2134 const char * const usage[] = {
2135 N_("git am [options] [(<mbox>|<Maildir>)...]"),
2136 N_("git am [options] (--continue | --skip | --abort)"),
2137 NULL
2140 struct option options[] = {
2141 OPT_BOOL('i', "interactive", &state.interactive,
2142 N_("run interactively")),
2143 OPT_HIDDEN_BOOL('b', "binary", &binary,
2144 N_("(historical option -- no-op")),
2145 OPT_BOOL('3', "3way", &state.threeway,
2146 N_("allow fall back on 3way merging if needed")),
2147 OPT__QUIET(&state.quiet, N_("be quiet")),
2148 OPT_BOOL('s', "signoff", &state.signoff,
2149 N_("add a Signed-off-by line to the commit message")),
2150 OPT_BOOL('u', "utf8", &state.utf8,
2151 N_("recode into utf8 (default)")),
2152 OPT_SET_INT('k', "keep", &state.keep,
2153 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2154 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2155 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2156 OPT_BOOL('m', "message-id", &state.message_id,
2157 N_("pass -m flag to git-mailinfo")),
2158 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2159 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2160 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2161 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2162 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2163 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2164 OPT_BOOL('c', "scissors", &state.scissors,
2165 N_("strip everything before a scissors line")),
2166 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2167 N_("pass it through git-apply"),
2169 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2170 N_("pass it through git-apply"),
2171 PARSE_OPT_NOARG),
2172 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2173 N_("pass it through git-apply"),
2174 PARSE_OPT_NOARG),
2175 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2176 N_("pass it through git-apply"),
2178 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2179 N_("pass it through git-apply"),
2181 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2182 N_("pass it through git-apply"),
2184 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2185 N_("pass it through git-apply"),
2187 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2188 N_("pass it through git-apply"),
2190 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2191 N_("format the patch(es) are in"),
2192 parse_opt_patchformat),
2193 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2194 N_("pass it through git-apply"),
2195 PARSE_OPT_NOARG),
2196 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2197 N_("override error message when patch failure occurs")),
2198 OPT_CMDMODE(0, "continue", &resume,
2199 N_("continue applying patches after resolving a conflict"),
2200 RESUME_RESOLVED),
2201 OPT_CMDMODE('r', "resolved", &resume,
2202 N_("synonyms for --continue"),
2203 RESUME_RESOLVED),
2204 OPT_CMDMODE(0, "skip", &resume,
2205 N_("skip the current patch"),
2206 RESUME_SKIP),
2207 OPT_CMDMODE(0, "abort", &resume,
2208 N_("restore the original branch and abort the patching operation."),
2209 RESUME_ABORT),
2210 OPT_BOOL(0, "committer-date-is-author-date",
2211 &state.committer_date_is_author_date,
2212 N_("lie about committer date")),
2213 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2214 N_("use current timestamp for author date")),
2215 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2216 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2217 N_("GPG-sign commits"),
2218 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2219 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2220 N_("(internal use for git-rebase)")),
2221 OPT_END()
2225 * NEEDSWORK: Once all the features of git-am.sh have been
2226 * re-implemented in builtin/am.c, this preamble can be removed.
2228 if (!getenv("_GIT_USE_BUILTIN_AM")) {
2229 const char *path = mkpath("%s/git-am", git_exec_path());
2231 if (sane_execvp(path, (char **)argv) < 0)
2232 die_errno("could not exec %s", path);
2233 } else {
2234 prefix = setup_git_directory();
2235 trace_repo_setup(prefix);
2236 setup_work_tree();
2239 git_config(git_default_config, NULL);
2241 am_state_init(&state, git_path("rebase-apply"));
2243 argc = parse_options(argc, argv, prefix, options, usage, 0);
2245 if (binary >= 0)
2246 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2247 "it will be removed. Please do not use it anymore."));
2249 if (read_index_preload(&the_index, NULL) < 0)
2250 die(_("failed to read the index"));
2252 if (am_in_progress(&state)) {
2254 * Catch user error to feed us patches when there is a session
2255 * in progress:
2257 * 1. mbox path(s) are provided on the command-line.
2258 * 2. stdin is not a tty: the user is trying to feed us a patch
2259 * from standard input. This is somewhat unreliable -- stdin
2260 * could be /dev/null for example and the caller did not
2261 * intend to feed us a patch but wanted to continue
2262 * unattended.
2264 if (argc || (resume == RESUME_FALSE && !isatty(0)))
2265 die(_("previous rebase directory %s still exists but mbox given."),
2266 state.dir);
2268 if (resume == RESUME_FALSE)
2269 resume = RESUME_APPLY;
2271 am_load(&state);
2272 } else {
2273 struct argv_array paths = ARGV_ARRAY_INIT;
2274 int i;
2277 * Handle stray state directory in the independent-run case. In
2278 * the --rebasing case, it is up to the caller to take care of
2279 * stray directories.
2281 if (file_exists(state.dir) && !state.rebasing) {
2282 if (resume == RESUME_ABORT) {
2283 am_destroy(&state);
2284 am_state_release(&state);
2285 return 0;
2288 die(_("Stray %s directory found.\n"
2289 "Use \"git am --abort\" to remove it."),
2290 state.dir);
2293 if (resume)
2294 die(_("Resolve operation not in progress, we are not resuming."));
2296 for (i = 0; i < argc; i++) {
2297 if (is_absolute_path(argv[i]) || !prefix)
2298 argv_array_push(&paths, argv[i]);
2299 else
2300 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2303 am_setup(&state, patch_format, paths.argv, keep_cr);
2305 argv_array_clear(&paths);
2308 switch (resume) {
2309 case RESUME_FALSE:
2310 am_run(&state, 0);
2311 break;
2312 case RESUME_APPLY:
2313 am_run(&state, 1);
2314 break;
2315 case RESUME_RESOLVED:
2316 am_resolve(&state);
2317 break;
2318 case RESUME_SKIP:
2319 am_skip(&state);
2320 break;
2321 case RESUME_ABORT:
2322 am_abort(&state);
2323 break;
2324 default:
2325 die("BUG: invalid resume value");
2328 am_state_release(&state);
2330 return 0;