am: let command-line options override saved options
[git/git-svn.git] / builtin / am.c
blobf81b74dd0b91cbcf84d2df87414805ffbaa7e06e
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 git_config_get_bool("am.threeway", &state->threeway);
157 state->utf8 = 1;
159 git_config_get_bool("am.messageid", &state->message_id);
161 state->scissors = SCISSORS_UNSET;
163 argv_array_init(&state->git_apply_opts);
165 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
166 state->sign_commit = gpgsign ? "" : NULL;
170 * Releases memory allocated by an am_state.
172 static void am_state_release(struct am_state *state)
174 free(state->dir);
175 free(state->author_name);
176 free(state->author_email);
177 free(state->author_date);
178 free(state->msg);
179 argv_array_clear(&state->git_apply_opts);
183 * Returns path relative to the am_state directory.
185 static inline const char *am_path(const struct am_state *state, const char *path)
187 return mkpath("%s/%s", state->dir, path);
191 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
192 * at the end.
194 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
196 va_list ap;
198 va_start(ap, fmt);
199 if (!state->quiet) {
200 vfprintf(fp, fmt, ap);
201 putc('\n', fp);
203 va_end(ap);
207 * Returns 1 if there is an am session in progress, 0 otherwise.
209 static int am_in_progress(const struct am_state *state)
211 struct stat st;
213 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
214 return 0;
215 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
216 return 0;
217 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
218 return 0;
219 return 1;
223 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
224 * number of bytes read on success, -1 if the file does not exist. If `trim` is
225 * set, trailing whitespace will be removed.
227 static int read_state_file(struct strbuf *sb, const struct am_state *state,
228 const char *file, int trim)
230 strbuf_reset(sb);
232 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
233 if (trim)
234 strbuf_trim(sb);
236 return sb->len;
239 if (errno == ENOENT)
240 return -1;
242 die_errno(_("could not read '%s'"), am_path(state, file));
246 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
247 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
248 * match `key`. Returns NULL on failure.
250 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
251 * the author-script.
253 static char *read_shell_var(FILE *fp, const char *key)
255 struct strbuf sb = STRBUF_INIT;
256 const char *str;
258 if (strbuf_getline(&sb, fp, '\n'))
259 goto fail;
261 if (!skip_prefix(sb.buf, key, &str))
262 goto fail;
264 if (!skip_prefix(str, "=", &str))
265 goto fail;
267 strbuf_remove(&sb, 0, str - sb.buf);
269 str = sq_dequote(sb.buf);
270 if (!str)
271 goto fail;
273 return strbuf_detach(&sb, NULL);
275 fail:
276 strbuf_release(&sb);
277 return NULL;
281 * Reads and parses the state directory's "author-script" file, and sets
282 * state->author_name, state->author_email and state->author_date accordingly.
283 * Returns 0 on success, -1 if the file could not be parsed.
285 * The author script is of the format:
287 * GIT_AUTHOR_NAME='$author_name'
288 * GIT_AUTHOR_EMAIL='$author_email'
289 * GIT_AUTHOR_DATE='$author_date'
291 * where $author_name, $author_email and $author_date are quoted. We are strict
292 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
293 * script, and thus if the file differs from what this function expects, it is
294 * better to bail out than to do something that the user does not expect.
296 static int read_author_script(struct am_state *state)
298 const char *filename = am_path(state, "author-script");
299 FILE *fp;
301 assert(!state->author_name);
302 assert(!state->author_email);
303 assert(!state->author_date);
305 fp = fopen(filename, "r");
306 if (!fp) {
307 if (errno == ENOENT)
308 return 0;
309 die_errno(_("could not open '%s' for reading"), filename);
312 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
313 if (!state->author_name) {
314 fclose(fp);
315 return -1;
318 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
319 if (!state->author_email) {
320 fclose(fp);
321 return -1;
324 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
325 if (!state->author_date) {
326 fclose(fp);
327 return -1;
330 if (fgetc(fp) != EOF) {
331 fclose(fp);
332 return -1;
335 fclose(fp);
336 return 0;
340 * Saves state->author_name, state->author_email and state->author_date in the
341 * state directory's "author-script" file.
343 static void write_author_script(const struct am_state *state)
345 struct strbuf sb = STRBUF_INIT;
347 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
348 sq_quote_buf(&sb, state->author_name);
349 strbuf_addch(&sb, '\n');
351 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
352 sq_quote_buf(&sb, state->author_email);
353 strbuf_addch(&sb, '\n');
355 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
356 sq_quote_buf(&sb, state->author_date);
357 strbuf_addch(&sb, '\n');
359 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
361 strbuf_release(&sb);
365 * Reads the commit message from the state directory's "final-commit" file,
366 * setting state->msg to its contents and state->msg_len to the length of its
367 * contents in bytes.
369 * Returns 0 on success, -1 if the file does not exist.
371 static int read_commit_msg(struct am_state *state)
373 struct strbuf sb = STRBUF_INIT;
375 assert(!state->msg);
377 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
378 strbuf_release(&sb);
379 return -1;
382 state->msg = strbuf_detach(&sb, &state->msg_len);
383 return 0;
387 * Saves state->msg in the state directory's "final-commit" file.
389 static void write_commit_msg(const struct am_state *state)
391 int fd;
392 const char *filename = am_path(state, "final-commit");
394 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
395 if (write_in_full(fd, state->msg, state->msg_len) < 0)
396 die_errno(_("could not write to %s"), filename);
397 close(fd);
401 * Loads state from disk.
403 static void am_load(struct am_state *state)
405 struct strbuf sb = STRBUF_INIT;
407 if (read_state_file(&sb, state, "next", 1) < 0)
408 die("BUG: state file 'next' does not exist");
409 state->cur = strtol(sb.buf, NULL, 10);
411 if (read_state_file(&sb, state, "last", 1) < 0)
412 die("BUG: state file 'last' does not exist");
413 state->last = strtol(sb.buf, NULL, 10);
415 if (read_author_script(state) < 0)
416 die(_("could not parse author script"));
418 read_commit_msg(state);
420 if (read_state_file(&sb, state, "original-commit", 1) < 0)
421 hashclr(state->orig_commit);
422 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
423 die(_("could not parse %s"), am_path(state, "original-commit"));
425 read_state_file(&sb, state, "threeway", 1);
426 state->threeway = !strcmp(sb.buf, "t");
428 read_state_file(&sb, state, "quiet", 1);
429 state->quiet = !strcmp(sb.buf, "t");
431 read_state_file(&sb, state, "sign", 1);
432 state->signoff = !strcmp(sb.buf, "t");
434 read_state_file(&sb, state, "utf8", 1);
435 state->utf8 = !strcmp(sb.buf, "t");
437 read_state_file(&sb, state, "keep", 1);
438 if (!strcmp(sb.buf, "t"))
439 state->keep = KEEP_TRUE;
440 else if (!strcmp(sb.buf, "b"))
441 state->keep = KEEP_NON_PATCH;
442 else
443 state->keep = KEEP_FALSE;
445 read_state_file(&sb, state, "messageid", 1);
446 state->message_id = !strcmp(sb.buf, "t");
448 read_state_file(&sb, state, "scissors", 1);
449 if (!strcmp(sb.buf, "t"))
450 state->scissors = SCISSORS_TRUE;
451 else if (!strcmp(sb.buf, "f"))
452 state->scissors = SCISSORS_FALSE;
453 else
454 state->scissors = SCISSORS_UNSET;
456 read_state_file(&sb, state, "apply-opt", 1);
457 argv_array_clear(&state->git_apply_opts);
458 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
459 die(_("could not parse %s"), am_path(state, "apply-opt"));
461 state->rebasing = !!file_exists(am_path(state, "rebasing"));
463 strbuf_release(&sb);
467 * Removes the am_state directory, forcefully terminating the current am
468 * session.
470 static void am_destroy(const struct am_state *state)
472 struct strbuf sb = STRBUF_INIT;
474 strbuf_addstr(&sb, state->dir);
475 remove_dir_recursively(&sb, 0);
476 strbuf_release(&sb);
480 * Runs applypatch-msg hook. Returns its exit code.
482 static int run_applypatch_msg_hook(struct am_state *state)
484 int ret;
486 assert(state->msg);
487 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
489 if (!ret) {
490 free(state->msg);
491 state->msg = NULL;
492 if (read_commit_msg(state) < 0)
493 die(_("'%s' was deleted by the applypatch-msg hook"),
494 am_path(state, "final-commit"));
497 return ret;
501 * Runs post-rewrite hook. Returns it exit code.
503 static int run_post_rewrite_hook(const struct am_state *state)
505 struct child_process cp = CHILD_PROCESS_INIT;
506 const char *hook = find_hook("post-rewrite");
507 int ret;
509 if (!hook)
510 return 0;
512 argv_array_push(&cp.args, hook);
513 argv_array_push(&cp.args, "rebase");
515 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
516 cp.stdout_to_stderr = 1;
518 ret = run_command(&cp);
520 close(cp.in);
521 return ret;
525 * Reads the state directory's "rewritten" file, and copies notes from the old
526 * commits listed in the file to their rewritten commits.
528 * Returns 0 on success, -1 on failure.
530 static int copy_notes_for_rebase(const struct am_state *state)
532 struct notes_rewrite_cfg *c;
533 struct strbuf sb = STRBUF_INIT;
534 const char *invalid_line = _("Malformed input line: '%s'.");
535 const char *msg = "Notes added by 'git rebase'";
536 FILE *fp;
537 int ret = 0;
539 assert(state->rebasing);
541 c = init_copy_notes_for_rewrite("rebase");
542 if (!c)
543 return 0;
545 fp = xfopen(am_path(state, "rewritten"), "r");
547 while (!strbuf_getline(&sb, fp, '\n')) {
548 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
550 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
551 ret = error(invalid_line, sb.buf);
552 goto finish;
555 if (get_sha1_hex(sb.buf, from_obj)) {
556 ret = error(invalid_line, sb.buf);
557 goto finish;
560 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
561 ret = error(invalid_line, sb.buf);
562 goto finish;
565 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
566 ret = error(invalid_line, sb.buf);
567 goto finish;
570 if (copy_note_for_rewrite(c, from_obj, to_obj))
571 ret = error(_("Failed to copy notes from '%s' to '%s'"),
572 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
575 finish:
576 finish_copy_notes_for_rewrite(c, msg);
577 fclose(fp);
578 strbuf_release(&sb);
579 return ret;
583 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
584 * non-indented lines and checking if they look like they begin with valid
585 * header field names.
587 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
589 static int is_mail(FILE *fp)
591 const char *header_regex = "^[!-9;-~]+:";
592 struct strbuf sb = STRBUF_INIT;
593 regex_t regex;
594 int ret = 1;
596 if (fseek(fp, 0L, SEEK_SET))
597 die_errno(_("fseek failed"));
599 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
600 die("invalid pattern: %s", header_regex);
602 while (!strbuf_getline_crlf(&sb, fp)) {
603 if (!sb.len)
604 break; /* End of header */
606 /* Ignore indented folded lines */
607 if (*sb.buf == '\t' || *sb.buf == ' ')
608 continue;
610 /* It's a header if it matches header_regex */
611 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
612 ret = 0;
613 goto done;
617 done:
618 regfree(&regex);
619 strbuf_release(&sb);
620 return ret;
624 * Attempts to detect the patch_format of the patches contained in `paths`,
625 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
626 * detection fails.
628 static int detect_patch_format(const char **paths)
630 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
631 struct strbuf l1 = STRBUF_INIT;
632 struct strbuf l2 = STRBUF_INIT;
633 struct strbuf l3 = STRBUF_INIT;
634 FILE *fp;
637 * We default to mbox format if input is from stdin and for directories
639 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
640 return PATCH_FORMAT_MBOX;
643 * Otherwise, check the first few lines of the first patch, starting
644 * from the first non-blank line, to try to detect its format.
647 fp = xfopen(*paths, "r");
649 while (!strbuf_getline_crlf(&l1, fp)) {
650 if (l1.len)
651 break;
654 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
655 ret = PATCH_FORMAT_MBOX;
656 goto done;
659 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
660 ret = PATCH_FORMAT_STGIT_SERIES;
661 goto done;
664 if (!strcmp(l1.buf, "# HG changeset patch")) {
665 ret = PATCH_FORMAT_HG;
666 goto done;
669 strbuf_reset(&l2);
670 strbuf_getline_crlf(&l2, fp);
671 strbuf_reset(&l3);
672 strbuf_getline_crlf(&l3, fp);
675 * If the second line is empty and the third is a From, Author or Date
676 * entry, this is likely an StGit patch.
678 if (l1.len && !l2.len &&
679 (starts_with(l3.buf, "From:") ||
680 starts_with(l3.buf, "Author:") ||
681 starts_with(l3.buf, "Date:"))) {
682 ret = PATCH_FORMAT_STGIT;
683 goto done;
686 if (l1.len && is_mail(fp)) {
687 ret = PATCH_FORMAT_MBOX;
688 goto done;
691 done:
692 fclose(fp);
693 strbuf_release(&l1);
694 return ret;
698 * Splits out individual email patches from `paths`, where each path is either
699 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
701 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
703 struct child_process cp = CHILD_PROCESS_INIT;
704 struct strbuf last = STRBUF_INIT;
706 cp.git_cmd = 1;
707 argv_array_push(&cp.args, "mailsplit");
708 argv_array_pushf(&cp.args, "-d%d", state->prec);
709 argv_array_pushf(&cp.args, "-o%s", state->dir);
710 argv_array_push(&cp.args, "-b");
711 if (keep_cr)
712 argv_array_push(&cp.args, "--keep-cr");
713 argv_array_push(&cp.args, "--");
714 argv_array_pushv(&cp.args, paths);
716 if (capture_command(&cp, &last, 8))
717 return -1;
719 state->cur = 1;
720 state->last = strtol(last.buf, NULL, 10);
722 return 0;
726 * Callback signature for split_mail_conv(). The foreign patch should be
727 * read from `in`, and the converted patch (in RFC2822 mail format) should be
728 * written to `out`. Return 0 on success, or -1 on failure.
730 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
733 * Calls `fn` for each file in `paths` to convert the foreign patch to the
734 * RFC2822 mail format suitable for parsing with git-mailinfo.
736 * Returns 0 on success, -1 on failure.
738 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
739 const char **paths, int keep_cr)
741 static const char *stdin_only[] = {"-", NULL};
742 int i;
744 if (!*paths)
745 paths = stdin_only;
747 for (i = 0; *paths; paths++, i++) {
748 FILE *in, *out;
749 const char *mail;
750 int ret;
752 if (!strcmp(*paths, "-"))
753 in = stdin;
754 else
755 in = fopen(*paths, "r");
757 if (!in)
758 return error(_("could not open '%s' for reading: %s"),
759 *paths, strerror(errno));
761 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
763 out = fopen(mail, "w");
764 if (!out)
765 return error(_("could not open '%s' for writing: %s"),
766 mail, strerror(errno));
768 ret = fn(out, in, keep_cr);
770 fclose(out);
771 fclose(in);
773 if (ret)
774 return error(_("could not parse patch '%s'"), *paths);
777 state->cur = 1;
778 state->last = i;
779 return 0;
783 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
784 * message suitable for parsing with git-mailinfo.
786 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
788 struct strbuf sb = STRBUF_INIT;
789 int subject_printed = 0;
791 while (!strbuf_getline(&sb, in, '\n')) {
792 const char *str;
794 if (str_isspace(sb.buf))
795 continue;
796 else if (skip_prefix(sb.buf, "Author:", &str))
797 fprintf(out, "From:%s\n", str);
798 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
799 fprintf(out, "%s\n", sb.buf);
800 else if (!subject_printed) {
801 fprintf(out, "Subject: %s\n", sb.buf);
802 subject_printed = 1;
803 } else {
804 fprintf(out, "\n%s\n", sb.buf);
805 break;
809 strbuf_reset(&sb);
810 while (strbuf_fread(&sb, 8192, in) > 0) {
811 fwrite(sb.buf, 1, sb.len, out);
812 strbuf_reset(&sb);
815 strbuf_release(&sb);
816 return 0;
820 * This function only supports a single StGit series file in `paths`.
822 * Given an StGit series file, converts the StGit patches in the series into
823 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
824 * the state directory.
826 * Returns 0 on success, -1 on failure.
828 static int split_mail_stgit_series(struct am_state *state, const char **paths,
829 int keep_cr)
831 const char *series_dir;
832 char *series_dir_buf;
833 FILE *fp;
834 struct argv_array patches = ARGV_ARRAY_INIT;
835 struct strbuf sb = STRBUF_INIT;
836 int ret;
838 if (!paths[0] || paths[1])
839 return error(_("Only one StGIT patch series can be applied at once"));
841 series_dir_buf = xstrdup(*paths);
842 series_dir = dirname(series_dir_buf);
844 fp = fopen(*paths, "r");
845 if (!fp)
846 return error(_("could not open '%s' for reading: %s"), *paths,
847 strerror(errno));
849 while (!strbuf_getline(&sb, fp, '\n')) {
850 if (*sb.buf == '#')
851 continue; /* skip comment lines */
853 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
856 fclose(fp);
857 strbuf_release(&sb);
858 free(series_dir_buf);
860 ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
862 argv_array_clear(&patches);
863 return ret;
867 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
868 * message suitable for parsing with git-mailinfo.
870 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
872 struct strbuf sb = STRBUF_INIT;
874 while (!strbuf_getline(&sb, in, '\n')) {
875 const char *str;
877 if (skip_prefix(sb.buf, "# User ", &str))
878 fprintf(out, "From: %s\n", str);
879 else if (skip_prefix(sb.buf, "# Date ", &str)) {
880 unsigned long timestamp;
881 long tz, tz2;
882 char *end;
884 errno = 0;
885 timestamp = strtoul(str, &end, 10);
886 if (errno)
887 return error(_("invalid timestamp"));
889 if (!skip_prefix(end, " ", &str))
890 return error(_("invalid Date line"));
892 errno = 0;
893 tz = strtol(str, &end, 10);
894 if (errno)
895 return error(_("invalid timezone offset"));
897 if (*end)
898 return error(_("invalid Date line"));
901 * mercurial's timezone is in seconds west of UTC,
902 * however git's timezone is in hours + minutes east of
903 * UTC. Convert it.
905 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
906 if (tz > 0)
907 tz2 = -tz2;
909 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
910 } else if (starts_with(sb.buf, "# ")) {
911 continue;
912 } else {
913 fprintf(out, "\n%s\n", sb.buf);
914 break;
918 strbuf_reset(&sb);
919 while (strbuf_fread(&sb, 8192, in) > 0) {
920 fwrite(sb.buf, 1, sb.len, out);
921 strbuf_reset(&sb);
924 strbuf_release(&sb);
925 return 0;
929 * Splits a list of files/directories into individual email patches. Each path
930 * in `paths` must be a file/directory that is formatted according to
931 * `patch_format`.
933 * Once split out, the individual email patches will be stored in the state
934 * directory, with each patch's filename being its index, padded to state->prec
935 * digits.
937 * state->cur will be set to the index of the first mail, and state->last will
938 * be set to the index of the last mail.
940 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
941 * to disable this behavior, -1 to use the default configured setting.
943 * Returns 0 on success, -1 on failure.
945 static int split_mail(struct am_state *state, enum patch_format patch_format,
946 const char **paths, int keep_cr)
948 if (keep_cr < 0) {
949 keep_cr = 0;
950 git_config_get_bool("am.keepcr", &keep_cr);
953 switch (patch_format) {
954 case PATCH_FORMAT_MBOX:
955 return split_mail_mbox(state, paths, keep_cr);
956 case PATCH_FORMAT_STGIT:
957 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
958 case PATCH_FORMAT_STGIT_SERIES:
959 return split_mail_stgit_series(state, paths, keep_cr);
960 case PATCH_FORMAT_HG:
961 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
962 default:
963 die("BUG: invalid patch_format");
965 return -1;
969 * Setup a new am session for applying patches
971 static void am_setup(struct am_state *state, enum patch_format patch_format,
972 const char **paths, int keep_cr)
974 unsigned char curr_head[GIT_SHA1_RAWSZ];
975 const char *str;
976 struct strbuf sb = STRBUF_INIT;
978 if (!patch_format)
979 patch_format = detect_patch_format(paths);
981 if (!patch_format) {
982 fprintf_ln(stderr, _("Patch format detection failed."));
983 exit(128);
986 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
987 die_errno(_("failed to create directory '%s'"), state->dir);
989 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
990 am_destroy(state);
991 die(_("Failed to split patches."));
994 if (state->rebasing)
995 state->threeway = 1;
997 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
999 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
1001 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
1003 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
1005 switch (state->keep) {
1006 case KEEP_FALSE:
1007 str = "f";
1008 break;
1009 case KEEP_TRUE:
1010 str = "t";
1011 break;
1012 case KEEP_NON_PATCH:
1013 str = "b";
1014 break;
1015 default:
1016 die("BUG: invalid value for state->keep");
1019 write_file(am_path(state, "keep"), 1, "%s", str);
1021 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
1023 switch (state->scissors) {
1024 case SCISSORS_UNSET:
1025 str = "";
1026 break;
1027 case SCISSORS_FALSE:
1028 str = "f";
1029 break;
1030 case SCISSORS_TRUE:
1031 str = "t";
1032 break;
1033 default:
1034 die("BUG: invalid value for state->scissors");
1037 write_file(am_path(state, "scissors"), 1, "%s", str);
1039 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1040 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
1042 if (state->rebasing)
1043 write_file(am_path(state, "rebasing"), 1, "%s", "");
1044 else
1045 write_file(am_path(state, "applying"), 1, "%s", "");
1047 if (!get_sha1("HEAD", curr_head)) {
1048 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
1049 if (!state->rebasing)
1050 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
1051 UPDATE_REFS_DIE_ON_ERR);
1052 } else {
1053 write_file(am_path(state, "abort-safety"), 1, "%s", "");
1054 if (!state->rebasing)
1055 delete_ref("ORIG_HEAD", NULL, 0);
1059 * NOTE: Since the "next" and "last" files determine if an am_state
1060 * session is in progress, they should be written last.
1063 write_file(am_path(state, "next"), 1, "%d", state->cur);
1065 write_file(am_path(state, "last"), 1, "%d", state->last);
1067 strbuf_release(&sb);
1071 * Increments the patch pointer, and cleans am_state for the application of the
1072 * next patch.
1074 static void am_next(struct am_state *state)
1076 unsigned char head[GIT_SHA1_RAWSZ];
1078 free(state->author_name);
1079 state->author_name = NULL;
1081 free(state->author_email);
1082 state->author_email = NULL;
1084 free(state->author_date);
1085 state->author_date = NULL;
1087 free(state->msg);
1088 state->msg = NULL;
1089 state->msg_len = 0;
1091 unlink(am_path(state, "author-script"));
1092 unlink(am_path(state, "final-commit"));
1094 hashclr(state->orig_commit);
1095 unlink(am_path(state, "original-commit"));
1097 if (!get_sha1("HEAD", head))
1098 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
1099 else
1100 write_file(am_path(state, "abort-safety"), 1, "%s", "");
1102 state->cur++;
1103 write_file(am_path(state, "next"), 1, "%d", state->cur);
1107 * Returns the filename of the current patch email.
1109 static const char *msgnum(const struct am_state *state)
1111 static struct strbuf sb = STRBUF_INIT;
1113 strbuf_reset(&sb);
1114 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1116 return sb.buf;
1120 * Refresh and write index.
1122 static void refresh_and_write_cache(void)
1124 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1126 hold_locked_index(lock_file, 1);
1127 refresh_cache(REFRESH_QUIET);
1128 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1129 die(_("unable to write index file"));
1133 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1134 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1135 * strbuf is provided, the space-separated list of files that differ will be
1136 * appended to it.
1138 static int index_has_changes(struct strbuf *sb)
1140 unsigned char head[GIT_SHA1_RAWSZ];
1141 int i;
1143 if (!get_sha1_tree("HEAD", head)) {
1144 struct diff_options opt;
1146 diff_setup(&opt);
1147 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
1148 if (!sb)
1149 DIFF_OPT_SET(&opt, QUICK);
1150 do_diff_cache(head, &opt);
1151 diffcore_std(&opt);
1152 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1153 if (i)
1154 strbuf_addch(sb, ' ');
1155 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1157 diff_flush(&opt);
1158 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
1159 } else {
1160 for (i = 0; sb && i < active_nr; i++) {
1161 if (i)
1162 strbuf_addch(sb, ' ');
1163 strbuf_addstr(sb, active_cache[i]->name);
1165 return !!active_nr;
1170 * Dies with a user-friendly message on how to proceed after resolving the
1171 * problem. This message can be overridden with state->resolvemsg.
1173 static void NORETURN die_user_resolve(const struct am_state *state)
1175 if (state->resolvemsg) {
1176 printf_ln("%s", state->resolvemsg);
1177 } else {
1178 const char *cmdline = state->interactive ? "git am -i" : "git am";
1180 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1181 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1182 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1185 exit(128);
1189 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1190 * state->msg will be set to the patch message. state->author_name,
1191 * state->author_email and state->author_date will be set to the patch author's
1192 * name, email and date respectively. The patch body will be written to the
1193 * state directory's "patch" file.
1195 * Returns 1 if the patch should be skipped, 0 otherwise.
1197 static int parse_mail(struct am_state *state, const char *mail)
1199 FILE *fp;
1200 struct child_process cp = CHILD_PROCESS_INIT;
1201 struct strbuf sb = STRBUF_INIT;
1202 struct strbuf msg = STRBUF_INIT;
1203 struct strbuf author_name = STRBUF_INIT;
1204 struct strbuf author_date = STRBUF_INIT;
1205 struct strbuf author_email = STRBUF_INIT;
1206 int ret = 0;
1208 cp.git_cmd = 1;
1209 cp.in = xopen(mail, O_RDONLY, 0);
1210 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
1212 argv_array_push(&cp.args, "mailinfo");
1213 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
1215 switch (state->keep) {
1216 case KEEP_FALSE:
1217 break;
1218 case KEEP_TRUE:
1219 argv_array_push(&cp.args, "-k");
1220 break;
1221 case KEEP_NON_PATCH:
1222 argv_array_push(&cp.args, "-b");
1223 break;
1224 default:
1225 die("BUG: invalid value for state->keep");
1228 if (state->message_id)
1229 argv_array_push(&cp.args, "-m");
1231 switch (state->scissors) {
1232 case SCISSORS_UNSET:
1233 break;
1234 case SCISSORS_FALSE:
1235 argv_array_push(&cp.args, "--no-scissors");
1236 break;
1237 case SCISSORS_TRUE:
1238 argv_array_push(&cp.args, "--scissors");
1239 break;
1240 default:
1241 die("BUG: invalid value for state->scissors");
1244 argv_array_push(&cp.args, am_path(state, "msg"));
1245 argv_array_push(&cp.args, am_path(state, "patch"));
1247 if (run_command(&cp) < 0)
1248 die("could not parse patch");
1250 close(cp.in);
1251 close(cp.out);
1253 /* Extract message and author information */
1254 fp = xfopen(am_path(state, "info"), "r");
1255 while (!strbuf_getline(&sb, fp, '\n')) {
1256 const char *x;
1258 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1259 if (msg.len)
1260 strbuf_addch(&msg, '\n');
1261 strbuf_addstr(&msg, x);
1262 } else if (skip_prefix(sb.buf, "Author: ", &x))
1263 strbuf_addstr(&author_name, x);
1264 else if (skip_prefix(sb.buf, "Email: ", &x))
1265 strbuf_addstr(&author_email, x);
1266 else if (skip_prefix(sb.buf, "Date: ", &x))
1267 strbuf_addstr(&author_date, x);
1269 fclose(fp);
1271 /* Skip pine's internal folder data */
1272 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1273 ret = 1;
1274 goto finish;
1277 if (is_empty_file(am_path(state, "patch"))) {
1278 printf_ln(_("Patch is empty. Was it split wrong?"));
1279 die_user_resolve(state);
1282 strbuf_addstr(&msg, "\n\n");
1283 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
1284 die_errno(_("could not read '%s'"), am_path(state, "msg"));
1285 stripspace(&msg, 0);
1287 if (state->signoff)
1288 append_signoff(&msg, 0, 0);
1290 assert(!state->author_name);
1291 state->author_name = strbuf_detach(&author_name, NULL);
1293 assert(!state->author_email);
1294 state->author_email = strbuf_detach(&author_email, NULL);
1296 assert(!state->author_date);
1297 state->author_date = strbuf_detach(&author_date, NULL);
1299 assert(!state->msg);
1300 state->msg = strbuf_detach(&msg, &state->msg_len);
1302 finish:
1303 strbuf_release(&msg);
1304 strbuf_release(&author_date);
1305 strbuf_release(&author_email);
1306 strbuf_release(&author_name);
1307 strbuf_release(&sb);
1308 return ret;
1312 * Sets commit_id to the commit hash where the mail was generated from.
1313 * Returns 0 on success, -1 on failure.
1315 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1317 struct strbuf sb = STRBUF_INIT;
1318 FILE *fp = xfopen(mail, "r");
1319 const char *x;
1321 if (strbuf_getline(&sb, fp, '\n'))
1322 return -1;
1324 if (!skip_prefix(sb.buf, "From ", &x))
1325 return -1;
1327 if (get_sha1_hex(x, commit_id) < 0)
1328 return -1;
1330 strbuf_release(&sb);
1331 fclose(fp);
1332 return 0;
1336 * Sets state->msg, state->author_name, state->author_email, state->author_date
1337 * to the commit's respective info.
1339 static void get_commit_info(struct am_state *state, struct commit *commit)
1341 const char *buffer, *ident_line, *author_date, *msg;
1342 size_t ident_len;
1343 struct ident_split ident_split;
1344 struct strbuf sb = STRBUF_INIT;
1346 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1348 ident_line = find_commit_header(buffer, "author", &ident_len);
1350 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1351 strbuf_add(&sb, ident_line, ident_len);
1352 die(_("invalid ident line: %s"), sb.buf);
1355 assert(!state->author_name);
1356 if (ident_split.name_begin) {
1357 strbuf_add(&sb, ident_split.name_begin,
1358 ident_split.name_end - ident_split.name_begin);
1359 state->author_name = strbuf_detach(&sb, NULL);
1360 } else
1361 state->author_name = xstrdup("");
1363 assert(!state->author_email);
1364 if (ident_split.mail_begin) {
1365 strbuf_add(&sb, ident_split.mail_begin,
1366 ident_split.mail_end - ident_split.mail_begin);
1367 state->author_email = strbuf_detach(&sb, NULL);
1368 } else
1369 state->author_email = xstrdup("");
1371 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1372 strbuf_addstr(&sb, author_date);
1373 assert(!state->author_date);
1374 state->author_date = strbuf_detach(&sb, NULL);
1376 assert(!state->msg);
1377 msg = strstr(buffer, "\n\n");
1378 if (!msg)
1379 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1380 state->msg = xstrdup(msg + 2);
1381 state->msg_len = strlen(state->msg);
1385 * Writes `commit` as a patch to the state directory's "patch" file.
1387 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1389 struct rev_info rev_info;
1390 FILE *fp;
1392 fp = xfopen(am_path(state, "patch"), "w");
1393 init_revisions(&rev_info, NULL);
1394 rev_info.diff = 1;
1395 rev_info.abbrev = 0;
1396 rev_info.disable_stdin = 1;
1397 rev_info.show_root_diff = 1;
1398 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1399 rev_info.no_commit_id = 1;
1400 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1401 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1402 rev_info.diffopt.use_color = 0;
1403 rev_info.diffopt.file = fp;
1404 rev_info.diffopt.close_file = 1;
1405 add_pending_object(&rev_info, &commit->object, "");
1406 diff_setup_done(&rev_info.diffopt);
1407 log_tree_commit(&rev_info, commit);
1411 * Writes the diff of the index against HEAD as a patch to the state
1412 * directory's "patch" file.
1414 static void write_index_patch(const struct am_state *state)
1416 struct tree *tree;
1417 unsigned char head[GIT_SHA1_RAWSZ];
1418 struct rev_info rev_info;
1419 FILE *fp;
1421 if (!get_sha1_tree("HEAD", head))
1422 tree = lookup_tree(head);
1423 else
1424 tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
1426 fp = xfopen(am_path(state, "patch"), "w");
1427 init_revisions(&rev_info, NULL);
1428 rev_info.diff = 1;
1429 rev_info.disable_stdin = 1;
1430 rev_info.no_commit_id = 1;
1431 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1432 rev_info.diffopt.use_color = 0;
1433 rev_info.diffopt.file = fp;
1434 rev_info.diffopt.close_file = 1;
1435 add_pending_object(&rev_info, &tree->object, "");
1436 diff_setup_done(&rev_info.diffopt);
1437 run_diff_index(&rev_info, 1);
1441 * Like parse_mail(), but parses the mail by looking up its commit ID
1442 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1443 * of patches.
1445 * state->orig_commit will be set to the original commit ID.
1447 * Will always return 0 as the patch should never be skipped.
1449 static int parse_mail_rebase(struct am_state *state, const char *mail)
1451 struct commit *commit;
1452 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1454 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1455 die(_("could not parse %s"), mail);
1457 commit = lookup_commit_or_die(commit_sha1, mail);
1459 get_commit_info(state, commit);
1461 write_commit_patch(state, commit);
1463 hashcpy(state->orig_commit, commit_sha1);
1464 write_file(am_path(state, "original-commit"), 1, "%s",
1465 sha1_to_hex(commit_sha1));
1467 return 0;
1471 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1472 * `index_file` is not NULL, the patch will be applied to that index.
1474 static int run_apply(const struct am_state *state, const char *index_file)
1476 struct child_process cp = CHILD_PROCESS_INIT;
1478 cp.git_cmd = 1;
1480 if (index_file)
1481 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1484 * If we are allowed to fall back on 3-way merge, don't give false
1485 * errors during the initial attempt.
1487 if (state->threeway && !index_file) {
1488 cp.no_stdout = 1;
1489 cp.no_stderr = 1;
1492 argv_array_push(&cp.args, "apply");
1494 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1496 if (index_file)
1497 argv_array_push(&cp.args, "--cached");
1498 else
1499 argv_array_push(&cp.args, "--index");
1501 argv_array_push(&cp.args, am_path(state, "patch"));
1503 if (run_command(&cp))
1504 return -1;
1506 /* Reload index as git-apply will have modified it. */
1507 discard_cache();
1508 read_cache_from(index_file ? index_file : get_index_file());
1510 return 0;
1514 * Builds an index that contains just the blobs needed for a 3way merge.
1516 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1518 struct child_process cp = CHILD_PROCESS_INIT;
1520 cp.git_cmd = 1;
1521 argv_array_push(&cp.args, "apply");
1522 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1523 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1524 argv_array_push(&cp.args, am_path(state, "patch"));
1526 if (run_command(&cp))
1527 return -1;
1529 return 0;
1533 * Attempt a threeway merge, using index_path as the temporary index.
1535 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1537 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1538 our_tree[GIT_SHA1_RAWSZ];
1539 const unsigned char *bases[1] = {orig_tree};
1540 struct merge_options o;
1541 struct commit *result;
1542 char *his_tree_name;
1544 if (get_sha1("HEAD", our_tree) < 0)
1545 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1547 if (build_fake_ancestor(state, index_path))
1548 return error("could not build fake ancestor");
1550 discard_cache();
1551 read_cache_from(index_path);
1553 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1554 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1556 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1558 if (!state->quiet) {
1560 * List paths that needed 3-way fallback, so that the user can
1561 * review them with extra care to spot mismerges.
1563 struct rev_info rev_info;
1564 const char *diff_filter_str = "--diff-filter=AM";
1566 init_revisions(&rev_info, NULL);
1567 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1568 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1569 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1570 diff_setup_done(&rev_info.diffopt);
1571 run_diff_index(&rev_info, 1);
1574 if (run_apply(state, index_path))
1575 return error(_("Did you hand edit your patch?\n"
1576 "It does not apply to blobs recorded in its index."));
1578 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1579 return error("could not write tree");
1581 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1583 discard_cache();
1584 read_cache();
1587 * This is not so wrong. Depending on which base we picked, orig_tree
1588 * may be wildly different from ours, but his_tree has the same set of
1589 * wildly different changes in parts the patch did not touch, so
1590 * recursive ends up canceling them, saying that we reverted all those
1591 * changes.
1594 init_merge_options(&o);
1596 o.branch1 = "HEAD";
1597 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1598 o.branch2 = his_tree_name;
1600 if (state->quiet)
1601 o.verbosity = 0;
1603 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1604 rerere(state->allow_rerere_autoupdate);
1605 free(his_tree_name);
1606 return error(_("Failed to merge in the changes."));
1609 free(his_tree_name);
1610 return 0;
1614 * Commits the current index with state->msg as the commit message and
1615 * state->author_name, state->author_email and state->author_date as the author
1616 * information.
1618 static void do_commit(const struct am_state *state)
1620 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1621 commit[GIT_SHA1_RAWSZ];
1622 unsigned char *ptr;
1623 struct commit_list *parents = NULL;
1624 const char *reflog_msg, *author;
1625 struct strbuf sb = STRBUF_INIT;
1627 if (run_hook_le(NULL, "pre-applypatch", NULL))
1628 exit(1);
1630 if (write_cache_as_tree(tree, 0, NULL))
1631 die(_("git write-tree failed to write a tree"));
1633 if (!get_sha1_commit("HEAD", parent)) {
1634 ptr = parent;
1635 commit_list_insert(lookup_commit(parent), &parents);
1636 } else {
1637 ptr = NULL;
1638 say(state, stderr, _("applying to an empty history"));
1641 author = fmt_ident(state->author_name, state->author_email,
1642 state->ignore_date ? NULL : state->author_date,
1643 IDENT_STRICT);
1645 if (state->committer_date_is_author_date)
1646 setenv("GIT_COMMITTER_DATE",
1647 state->ignore_date ? "" : state->author_date, 1);
1649 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1650 author, state->sign_commit))
1651 die(_("failed to write commit object"));
1653 reflog_msg = getenv("GIT_REFLOG_ACTION");
1654 if (!reflog_msg)
1655 reflog_msg = "am";
1657 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1658 state->msg);
1660 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1662 if (state->rebasing) {
1663 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1665 assert(!is_null_sha1(state->orig_commit));
1666 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1667 fprintf(fp, "%s\n", sha1_to_hex(commit));
1668 fclose(fp);
1671 run_hook_le(NULL, "post-applypatch", NULL);
1673 strbuf_release(&sb);
1677 * Validates the am_state for resuming -- the "msg" and authorship fields must
1678 * be filled up.
1680 static void validate_resume_state(const struct am_state *state)
1682 if (!state->msg)
1683 die(_("cannot resume: %s does not exist."),
1684 am_path(state, "final-commit"));
1686 if (!state->author_name || !state->author_email || !state->author_date)
1687 die(_("cannot resume: %s does not exist."),
1688 am_path(state, "author-script"));
1692 * Interactively prompt the user on whether the current patch should be
1693 * applied.
1695 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1696 * skip it.
1698 static int do_interactive(struct am_state *state)
1700 assert(state->msg);
1702 if (!isatty(0))
1703 die(_("cannot be interactive without stdin connected to a terminal."));
1705 for (;;) {
1706 const char *reply;
1708 puts(_("Commit Body is:"));
1709 puts("--------------------------");
1710 printf("%s", state->msg);
1711 puts("--------------------------");
1714 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1715 * in your translation. The program will only accept English
1716 * input at this point.
1718 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1720 if (!reply) {
1721 continue;
1722 } else if (*reply == 'y' || *reply == 'Y') {
1723 return 0;
1724 } else if (*reply == 'a' || *reply == 'A') {
1725 state->interactive = 0;
1726 return 0;
1727 } else if (*reply == 'n' || *reply == 'N') {
1728 return 1;
1729 } else if (*reply == 'e' || *reply == 'E') {
1730 struct strbuf msg = STRBUF_INIT;
1732 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1733 free(state->msg);
1734 state->msg = strbuf_detach(&msg, &state->msg_len);
1736 strbuf_release(&msg);
1737 } else if (*reply == 'v' || *reply == 'V') {
1738 const char *pager = git_pager(1);
1739 struct child_process cp = CHILD_PROCESS_INIT;
1741 if (!pager)
1742 pager = "cat";
1743 argv_array_push(&cp.args, pager);
1744 argv_array_push(&cp.args, am_path(state, "patch"));
1745 run_command(&cp);
1751 * Applies all queued mail.
1753 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1754 * well as the state directory's "patch" file is used as-is for applying the
1755 * patch and committing it.
1757 static void am_run(struct am_state *state, int resume)
1759 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1760 struct strbuf sb = STRBUF_INIT;
1762 unlink(am_path(state, "dirtyindex"));
1764 refresh_and_write_cache();
1766 if (index_has_changes(&sb)) {
1767 write_file(am_path(state, "dirtyindex"), 1, "t");
1768 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1771 strbuf_release(&sb);
1773 while (state->cur <= state->last) {
1774 const char *mail = am_path(state, msgnum(state));
1775 int apply_status;
1777 if (!file_exists(mail))
1778 goto next;
1780 if (resume) {
1781 validate_resume_state(state);
1782 } else {
1783 int skip;
1785 if (state->rebasing)
1786 skip = parse_mail_rebase(state, mail);
1787 else
1788 skip = parse_mail(state, mail);
1790 if (skip)
1791 goto next; /* mail should be skipped */
1793 write_author_script(state);
1794 write_commit_msg(state);
1797 if (state->interactive && do_interactive(state))
1798 goto next;
1800 if (run_applypatch_msg_hook(state))
1801 exit(1);
1803 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1805 apply_status = run_apply(state, NULL);
1807 if (apply_status && state->threeway) {
1808 struct strbuf sb = STRBUF_INIT;
1810 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1811 apply_status = fall_back_threeway(state, sb.buf);
1812 strbuf_release(&sb);
1815 * Applying the patch to an earlier tree and merging
1816 * the result may have produced the same tree as ours.
1818 if (!apply_status && !index_has_changes(NULL)) {
1819 say(state, stdout, _("No changes -- Patch already applied."));
1820 goto next;
1824 if (apply_status) {
1825 int advice_amworkdir = 1;
1827 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1828 linelen(state->msg), state->msg);
1830 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1832 if (advice_amworkdir)
1833 printf_ln(_("The copy of the patch that failed is found in: %s"),
1834 am_path(state, "patch"));
1836 die_user_resolve(state);
1839 do_commit(state);
1841 next:
1842 am_next(state);
1844 if (resume)
1845 am_load(state);
1846 resume = 0;
1849 if (!is_empty_file(am_path(state, "rewritten"))) {
1850 assert(state->rebasing);
1851 copy_notes_for_rebase(state);
1852 run_post_rewrite_hook(state);
1856 * In rebasing mode, it's up to the caller to take care of
1857 * housekeeping.
1859 if (!state->rebasing) {
1860 am_destroy(state);
1861 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1866 * Resume the current am session after patch application failure. The user did
1867 * all the hard work, and we do not have to do any patch application. Just
1868 * trust and commit what the user has in the index and working tree.
1870 static void am_resolve(struct am_state *state)
1872 validate_resume_state(state);
1874 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1876 if (!index_has_changes(NULL)) {
1877 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1878 "If there is nothing left to stage, chances are that something else\n"
1879 "already introduced the same changes; you might want to skip this patch."));
1880 die_user_resolve(state);
1883 if (unmerged_cache()) {
1884 printf_ln(_("You still have unmerged paths in your index.\n"
1885 "Did you forget to use 'git add'?"));
1886 die_user_resolve(state);
1889 if (state->interactive) {
1890 write_index_patch(state);
1891 if (do_interactive(state))
1892 goto next;
1895 rerere(0);
1897 do_commit(state);
1899 next:
1900 am_next(state);
1901 am_load(state);
1902 am_run(state, 0);
1906 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1907 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1908 * failure.
1910 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1912 struct lock_file *lock_file;
1913 struct unpack_trees_options opts;
1914 struct tree_desc t[2];
1916 if (parse_tree(head) || parse_tree(remote))
1917 return -1;
1919 lock_file = xcalloc(1, sizeof(struct lock_file));
1920 hold_locked_index(lock_file, 1);
1922 refresh_cache(REFRESH_QUIET);
1924 memset(&opts, 0, sizeof(opts));
1925 opts.head_idx = 1;
1926 opts.src_index = &the_index;
1927 opts.dst_index = &the_index;
1928 opts.update = 1;
1929 opts.merge = 1;
1930 opts.reset = reset;
1931 opts.fn = twoway_merge;
1932 init_tree_desc(&t[0], head->buffer, head->size);
1933 init_tree_desc(&t[1], remote->buffer, remote->size);
1935 if (unpack_trees(2, t, &opts)) {
1936 rollback_lock_file(lock_file);
1937 return -1;
1940 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1941 die(_("unable to write new index file"));
1943 return 0;
1947 * Clean the index without touching entries that are not modified between
1948 * `head` and `remote`.
1950 static int clean_index(const unsigned char *head, const unsigned char *remote)
1952 struct lock_file *lock_file;
1953 struct tree *head_tree, *remote_tree, *index_tree;
1954 unsigned char index[GIT_SHA1_RAWSZ];
1955 struct pathspec pathspec;
1957 head_tree = parse_tree_indirect(head);
1958 if (!head_tree)
1959 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1961 remote_tree = parse_tree_indirect(remote);
1962 if (!remote_tree)
1963 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1965 read_cache_unmerged();
1967 if (fast_forward_to(head_tree, head_tree, 1))
1968 return -1;
1970 if (write_cache_as_tree(index, 0, NULL))
1971 return -1;
1973 index_tree = parse_tree_indirect(index);
1974 if (!index_tree)
1975 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1977 if (fast_forward_to(index_tree, remote_tree, 0))
1978 return -1;
1980 memset(&pathspec, 0, sizeof(pathspec));
1982 lock_file = xcalloc(1, sizeof(struct lock_file));
1983 hold_locked_index(lock_file, 1);
1985 if (read_tree(remote_tree, 0, &pathspec)) {
1986 rollback_lock_file(lock_file);
1987 return -1;
1990 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1991 die(_("unable to write new index file"));
1993 remove_branch_state();
1995 return 0;
1999 * Resets rerere's merge resolution metadata.
2001 static void am_rerere_clear(void)
2003 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2004 int fd = setup_rerere(&merge_rr, 0);
2006 if (fd < 0)
2007 return;
2009 rerere_clear(&merge_rr);
2010 string_list_clear(&merge_rr, 1);
2014 * Resume the current am session by skipping the current patch.
2016 static void am_skip(struct am_state *state)
2018 unsigned char head[GIT_SHA1_RAWSZ];
2020 am_rerere_clear();
2022 if (get_sha1("HEAD", head))
2023 hashcpy(head, EMPTY_TREE_SHA1_BIN);
2025 if (clean_index(head, head))
2026 die(_("failed to clean index"));
2028 am_next(state);
2029 am_load(state);
2030 am_run(state, 0);
2034 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2036 * It is not safe to reset HEAD when:
2037 * 1. git-am previously failed because the index was dirty.
2038 * 2. HEAD has moved since git-am previously failed.
2040 static int safe_to_abort(const struct am_state *state)
2042 struct strbuf sb = STRBUF_INIT;
2043 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
2045 if (file_exists(am_path(state, "dirtyindex")))
2046 return 0;
2048 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2049 if (get_sha1_hex(sb.buf, abort_safety))
2050 die(_("could not parse %s"), am_path(state, "abort_safety"));
2051 } else
2052 hashclr(abort_safety);
2054 if (get_sha1("HEAD", head))
2055 hashclr(head);
2057 if (!hashcmp(head, abort_safety))
2058 return 1;
2060 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
2061 "Not rewinding to ORIG_HEAD"));
2063 return 0;
2067 * Aborts the current am session if it is safe to do so.
2069 static void am_abort(struct am_state *state)
2071 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
2072 int has_curr_head, has_orig_head;
2073 char *curr_branch;
2075 if (!safe_to_abort(state)) {
2076 am_destroy(state);
2077 return;
2080 am_rerere_clear();
2082 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
2083 has_curr_head = !is_null_sha1(curr_head);
2084 if (!has_curr_head)
2085 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
2087 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
2088 if (!has_orig_head)
2089 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
2091 clean_index(curr_head, orig_head);
2093 if (has_orig_head)
2094 update_ref("am --abort", "HEAD", orig_head,
2095 has_curr_head ? curr_head : NULL, 0,
2096 UPDATE_REFS_DIE_ON_ERR);
2097 else if (curr_branch)
2098 delete_ref(curr_branch, NULL, REF_NODEREF);
2100 free(curr_branch);
2101 am_destroy(state);
2105 * parse_options() callback that validates and sets opt->value to the
2106 * PATCH_FORMAT_* enum value corresponding to `arg`.
2108 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2110 int *opt_value = opt->value;
2112 if (!strcmp(arg, "mbox"))
2113 *opt_value = PATCH_FORMAT_MBOX;
2114 else if (!strcmp(arg, "stgit"))
2115 *opt_value = PATCH_FORMAT_STGIT;
2116 else if (!strcmp(arg, "stgit-series"))
2117 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2118 else if (!strcmp(arg, "hg"))
2119 *opt_value = PATCH_FORMAT_HG;
2120 else
2121 return error(_("Invalid value for --patch-format: %s"), arg);
2122 return 0;
2125 enum resume_mode {
2126 RESUME_FALSE = 0,
2127 RESUME_APPLY,
2128 RESUME_RESOLVED,
2129 RESUME_SKIP,
2130 RESUME_ABORT
2133 int cmd_am(int argc, const char **argv, const char *prefix)
2135 struct am_state state;
2136 int binary = -1;
2137 int keep_cr = -1;
2138 int patch_format = PATCH_FORMAT_UNKNOWN;
2139 enum resume_mode resume = RESUME_FALSE;
2140 int in_progress;
2142 const char * const usage[] = {
2143 N_("git am [options] [(<mbox>|<Maildir>)...]"),
2144 N_("git am [options] (--continue | --skip | --abort)"),
2145 NULL
2148 struct option options[] = {
2149 OPT_BOOL('i', "interactive", &state.interactive,
2150 N_("run interactively")),
2151 OPT_HIDDEN_BOOL('b', "binary", &binary,
2152 N_("(historical option -- no-op")),
2153 OPT_BOOL('3', "3way", &state.threeway,
2154 N_("allow fall back on 3way merging if needed")),
2155 OPT__QUIET(&state.quiet, N_("be quiet")),
2156 OPT_BOOL('s', "signoff", &state.signoff,
2157 N_("add a Signed-off-by line to the commit message")),
2158 OPT_BOOL('u', "utf8", &state.utf8,
2159 N_("recode into utf8 (default)")),
2160 OPT_SET_INT('k', "keep", &state.keep,
2161 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2162 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2163 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2164 OPT_BOOL('m', "message-id", &state.message_id,
2165 N_("pass -m flag to git-mailinfo")),
2166 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2167 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2168 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2169 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2170 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2171 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2172 OPT_BOOL('c', "scissors", &state.scissors,
2173 N_("strip everything before a scissors line")),
2174 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2175 N_("pass it through git-apply"),
2177 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2178 N_("pass it through git-apply"),
2179 PARSE_OPT_NOARG),
2180 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2181 N_("pass it through git-apply"),
2182 PARSE_OPT_NOARG),
2183 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2184 N_("pass it through git-apply"),
2186 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2187 N_("pass it through git-apply"),
2189 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2190 N_("pass it through git-apply"),
2192 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2193 N_("pass it through git-apply"),
2195 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2196 N_("pass it through git-apply"),
2198 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2199 N_("format the patch(es) are in"),
2200 parse_opt_patchformat),
2201 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2202 N_("pass it through git-apply"),
2203 PARSE_OPT_NOARG),
2204 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2205 N_("override error message when patch failure occurs")),
2206 OPT_CMDMODE(0, "continue", &resume,
2207 N_("continue applying patches after resolving a conflict"),
2208 RESUME_RESOLVED),
2209 OPT_CMDMODE('r', "resolved", &resume,
2210 N_("synonyms for --continue"),
2211 RESUME_RESOLVED),
2212 OPT_CMDMODE(0, "skip", &resume,
2213 N_("skip the current patch"),
2214 RESUME_SKIP),
2215 OPT_CMDMODE(0, "abort", &resume,
2216 N_("restore the original branch and abort the patching operation."),
2217 RESUME_ABORT),
2218 OPT_BOOL(0, "committer-date-is-author-date",
2219 &state.committer_date_is_author_date,
2220 N_("lie about committer date")),
2221 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2222 N_("use current timestamp for author date")),
2223 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2224 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2225 N_("GPG-sign commits"),
2226 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2227 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2228 N_("(internal use for git-rebase)")),
2229 OPT_END()
2232 git_config(git_default_config, NULL);
2234 am_state_init(&state, git_path("rebase-apply"));
2236 in_progress = am_in_progress(&state);
2237 if (in_progress)
2238 am_load(&state);
2240 argc = parse_options(argc, argv, prefix, options, usage, 0);
2242 if (binary >= 0)
2243 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2244 "it will be removed. Please do not use it anymore."));
2246 /* Ensure a valid committer ident can be constructed */
2247 git_committer_info(IDENT_STRICT);
2249 if (read_index_preload(&the_index, NULL) < 0)
2250 die(_("failed to read the index"));
2252 if (in_progress) {
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;
2270 } else {
2271 struct argv_array paths = ARGV_ARRAY_INIT;
2272 int i;
2275 * Handle stray state directory in the independent-run case. In
2276 * the --rebasing case, it is up to the caller to take care of
2277 * stray directories.
2279 if (file_exists(state.dir) && !state.rebasing) {
2280 if (resume == RESUME_ABORT) {
2281 am_destroy(&state);
2282 am_state_release(&state);
2283 return 0;
2286 die(_("Stray %s directory found.\n"
2287 "Use \"git am --abort\" to remove it."),
2288 state.dir);
2291 if (resume)
2292 die(_("Resolve operation not in progress, we are not resuming."));
2294 for (i = 0; i < argc; i++) {
2295 if (is_absolute_path(argv[i]) || !prefix)
2296 argv_array_push(&paths, argv[i]);
2297 else
2298 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2301 am_setup(&state, patch_format, paths.argv, keep_cr);
2303 argv_array_clear(&paths);
2306 switch (resume) {
2307 case RESUME_FALSE:
2308 am_run(&state, 0);
2309 break;
2310 case RESUME_APPLY:
2311 am_run(&state, 1);
2312 break;
2313 case RESUME_RESOLVED:
2314 am_resolve(&state);
2315 break;
2316 case RESUME_SKIP:
2317 am_skip(&state);
2318 break;
2319 case RESUME_ABORT:
2320 am_abort(&state);
2321 break;
2322 default:
2323 die("BUG: invalid resume value");
2326 am_state_release(&state);
2328 return 0;