builtin/show: do not prune by pathspec
[git/mjg.git] / builtin / am.c
blob370f5593f23ae53ba573cac342a02b9044d2328b
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
7 #include "builtin.h"
8 #include "abspath.h"
9 #include "advice.h"
10 #include "config.h"
11 #include "editor.h"
12 #include "environment.h"
13 #include "gettext.h"
14 #include "hex.h"
15 #include "parse-options.h"
16 #include "dir.h"
17 #include "run-command.h"
18 #include "hook.h"
19 #include "quote.h"
20 #include "tempfile.h"
21 #include "lockfile.h"
22 #include "cache-tree.h"
23 #include "refs.h"
24 #include "commit.h"
25 #include "diff.h"
26 #include "unpack-trees.h"
27 #include "branch.h"
28 #include "object-name.h"
29 #include "preload-index.h"
30 #include "sequencer.h"
31 #include "revision.h"
32 #include "merge-recursive.h"
33 #include "log-tree.h"
34 #include "notes-utils.h"
35 #include "rerere.h"
36 #include "mailinfo.h"
37 #include "apply.h"
38 #include "string-list.h"
39 #include "pager.h"
40 #include "path.h"
41 #include "repository.h"
42 #include "pretty.h"
44 /**
45 * Returns the length of the first line of msg.
47 static int linelen(const char *msg)
49 return strchrnul(msg, '\n') - msg;
52 /**
53 * Returns true if `str` consists of only whitespace, false otherwise.
55 static int str_isspace(const char *str)
57 for (; *str; str++)
58 if (!isspace(*str))
59 return 0;
61 return 1;
64 enum patch_format {
65 PATCH_FORMAT_UNKNOWN = 0,
66 PATCH_FORMAT_MBOX,
67 PATCH_FORMAT_STGIT,
68 PATCH_FORMAT_STGIT_SERIES,
69 PATCH_FORMAT_HG,
70 PATCH_FORMAT_MBOXRD
73 enum keep_type {
74 KEEP_FALSE = 0,
75 KEEP_TRUE, /* pass -k flag to git-mailinfo */
76 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
79 enum scissors_type {
80 SCISSORS_UNSET = -1,
81 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
82 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
85 enum signoff_type {
86 SIGNOFF_FALSE = 0,
87 SIGNOFF_TRUE = 1,
88 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
91 enum resume_type {
92 RESUME_FALSE = 0,
93 RESUME_APPLY,
94 RESUME_RESOLVED,
95 RESUME_SKIP,
96 RESUME_ABORT,
97 RESUME_QUIT,
98 RESUME_SHOW_PATCH_RAW,
99 RESUME_SHOW_PATCH_DIFF,
100 RESUME_ALLOW_EMPTY,
103 enum empty_action {
104 STOP_ON_EMPTY_COMMIT = 0, /* output errors and stop in the middle of an am session */
105 DROP_EMPTY_COMMIT, /* skip with a notice message, unless "--quiet" has been passed */
106 KEEP_EMPTY_COMMIT, /* keep recording as empty commits */
109 struct am_state {
110 /* state directory path */
111 char *dir;
113 /* current and last patch numbers, 1-indexed */
114 int cur;
115 int last;
117 /* commit metadata and message */
118 char *author_name;
119 char *author_email;
120 char *author_date;
121 char *msg;
122 size_t msg_len;
124 /* when --rebasing, records the original commit the patch came from */
125 struct object_id orig_commit;
127 /* number of digits in patch filename */
128 int prec;
130 /* various operating modes and command line options */
131 int interactive;
132 int no_verify;
133 int threeway;
134 int quiet;
135 int signoff; /* enum signoff_type */
136 int utf8;
137 int keep; /* enum keep_type */
138 int message_id;
139 int scissors; /* enum scissors_type */
140 int quoted_cr; /* enum quoted_cr_action */
141 int empty_type; /* enum empty_action */
142 struct strvec git_apply_opts;
143 const char *resolvemsg;
144 int committer_date_is_author_date;
145 int ignore_date;
146 int allow_rerere_autoupdate;
147 const char *sign_commit;
148 int rebasing;
152 * Initializes am_state with the default values.
154 static void am_state_init(struct am_state *state)
156 int gpgsign;
158 memset(state, 0, sizeof(*state));
160 state->dir = git_pathdup("rebase-apply");
162 state->prec = 4;
164 git_config_get_bool("am.threeway", &state->threeway);
166 state->utf8 = 1;
168 git_config_get_bool("am.messageid", &state->message_id);
170 state->scissors = SCISSORS_UNSET;
171 state->quoted_cr = quoted_cr_unset;
173 strvec_init(&state->git_apply_opts);
175 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
176 state->sign_commit = gpgsign ? "" : NULL;
180 * Releases memory allocated by an am_state.
182 static void am_state_release(struct am_state *state)
184 free(state->dir);
185 free(state->author_name);
186 free(state->author_email);
187 free(state->author_date);
188 free(state->msg);
189 strvec_clear(&state->git_apply_opts);
192 static int am_option_parse_quoted_cr(const struct option *opt,
193 const char *arg, int unset)
195 BUG_ON_OPT_NEG(unset);
197 if (mailinfo_parse_quoted_cr_action(arg, opt->value) != 0)
198 return error(_("bad action '%s' for '%s'"), arg, "--quoted-cr");
199 return 0;
202 static int am_option_parse_empty(const struct option *opt,
203 const char *arg, int unset)
205 int *opt_value = opt->value;
207 BUG_ON_OPT_NEG(unset);
209 if (!strcmp(arg, "stop"))
210 *opt_value = STOP_ON_EMPTY_COMMIT;
211 else if (!strcmp(arg, "drop"))
212 *opt_value = DROP_EMPTY_COMMIT;
213 else if (!strcmp(arg, "keep"))
214 *opt_value = KEEP_EMPTY_COMMIT;
215 else
216 return error(_("invalid value for '%s': '%s'"), "--empty", arg);
218 return 0;
222 * Returns path relative to the am_state directory.
224 static inline const char *am_path(const struct am_state *state, const char *path)
226 return mkpath("%s/%s", state->dir, path);
230 * For convenience to call write_file()
232 static void write_state_text(const struct am_state *state,
233 const char *name, const char *string)
235 write_file(am_path(state, name), "%s", string);
238 static void write_state_count(const struct am_state *state,
239 const char *name, int value)
241 write_file(am_path(state, name), "%d", value);
244 static void write_state_bool(const struct am_state *state,
245 const char *name, int value)
247 write_state_text(state, name, value ? "t" : "f");
251 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
252 * at the end.
254 __attribute__((format (printf, 3, 4)))
255 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
257 va_list ap;
259 va_start(ap, fmt);
260 if (!state->quiet) {
261 vfprintf(fp, fmt, ap);
262 putc('\n', fp);
264 va_end(ap);
268 * Returns 1 if there is an am session in progress, 0 otherwise.
270 static int am_in_progress(const struct am_state *state)
272 struct stat st;
274 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
275 return 0;
276 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
277 return 0;
278 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
279 return 0;
280 return 1;
284 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
285 * number of bytes read on success, -1 if the file does not exist. If `trim` is
286 * set, trailing whitespace will be removed.
288 static int read_state_file(struct strbuf *sb, const struct am_state *state,
289 const char *file, int trim)
291 strbuf_reset(sb);
293 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
294 if (trim)
295 strbuf_trim(sb);
297 return sb->len;
300 if (errno == ENOENT)
301 return -1;
303 die_errno(_("could not read '%s'"), am_path(state, file));
307 * Reads and parses the state directory's "author-script" file, and sets
308 * state->author_name, state->author_email and state->author_date accordingly.
309 * Returns 0 on success, -1 if the file could not be parsed.
311 * The author script is of the format:
313 * GIT_AUTHOR_NAME='$author_name'
314 * GIT_AUTHOR_EMAIL='$author_email'
315 * GIT_AUTHOR_DATE='$author_date'
317 * where $author_name, $author_email and $author_date are quoted. We are strict
318 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
319 * script, and thus if the file differs from what this function expects, it is
320 * better to bail out than to do something that the user does not expect.
322 static int read_am_author_script(struct am_state *state)
324 const char *filename = am_path(state, "author-script");
326 assert(!state->author_name);
327 assert(!state->author_email);
328 assert(!state->author_date);
330 return read_author_script(filename, &state->author_name,
331 &state->author_email, &state->author_date, 1);
335 * Saves state->author_name, state->author_email and state->author_date in the
336 * state directory's "author-script" file.
338 static void write_author_script(const struct am_state *state)
340 struct strbuf sb = STRBUF_INIT;
342 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
343 sq_quote_buf(&sb, state->author_name);
344 strbuf_addch(&sb, '\n');
346 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
347 sq_quote_buf(&sb, state->author_email);
348 strbuf_addch(&sb, '\n');
350 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
351 sq_quote_buf(&sb, state->author_date);
352 strbuf_addch(&sb, '\n');
354 write_state_text(state, "author-script", sb.buf);
356 strbuf_release(&sb);
360 * Reads the commit message from the state directory's "final-commit" file,
361 * setting state->msg to its contents and state->msg_len to the length of its
362 * contents in bytes.
364 * Returns 0 on success, -1 if the file does not exist.
366 static int read_commit_msg(struct am_state *state)
368 struct strbuf sb = STRBUF_INIT;
370 assert(!state->msg);
372 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
373 strbuf_release(&sb);
374 return -1;
377 state->msg = strbuf_detach(&sb, &state->msg_len);
378 return 0;
382 * Saves state->msg in the state directory's "final-commit" file.
384 static void write_commit_msg(const struct am_state *state)
386 const char *filename = am_path(state, "final-commit");
387 write_file_buf(filename, state->msg, state->msg_len);
391 * Loads state from disk.
393 static void am_load(struct am_state *state)
395 struct strbuf sb = STRBUF_INIT;
397 if (read_state_file(&sb, state, "next", 1) < 0)
398 BUG("state file 'next' does not exist");
399 state->cur = strtol(sb.buf, NULL, 10);
401 if (read_state_file(&sb, state, "last", 1) < 0)
402 BUG("state file 'last' does not exist");
403 state->last = strtol(sb.buf, NULL, 10);
405 if (read_am_author_script(state) < 0)
406 die(_("could not parse author script"));
408 read_commit_msg(state);
410 if (read_state_file(&sb, state, "original-commit", 1) < 0)
411 oidclr(&state->orig_commit, the_repository->hash_algo);
412 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
413 die(_("could not parse %s"), am_path(state, "original-commit"));
415 read_state_file(&sb, state, "threeway", 1);
416 state->threeway = !strcmp(sb.buf, "t");
418 read_state_file(&sb, state, "quiet", 1);
419 state->quiet = !strcmp(sb.buf, "t");
421 read_state_file(&sb, state, "sign", 1);
422 state->signoff = !strcmp(sb.buf, "t");
424 read_state_file(&sb, state, "utf8", 1);
425 state->utf8 = !strcmp(sb.buf, "t");
427 if (file_exists(am_path(state, "rerere-autoupdate"))) {
428 read_state_file(&sb, state, "rerere-autoupdate", 1);
429 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
430 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
431 } else {
432 state->allow_rerere_autoupdate = 0;
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, "quoted-cr", 1);
455 if (!*sb.buf)
456 state->quoted_cr = quoted_cr_unset;
457 else if (mailinfo_parse_quoted_cr_action(sb.buf, &state->quoted_cr) != 0)
458 die(_("could not parse %s"), am_path(state, "quoted-cr"));
460 read_state_file(&sb, state, "apply-opt", 1);
461 strvec_clear(&state->git_apply_opts);
462 if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
463 die(_("could not parse %s"), am_path(state, "apply-opt"));
465 state->rebasing = !!file_exists(am_path(state, "rebasing"));
467 strbuf_release(&sb);
471 * Removes the am_state directory, forcefully terminating the current am
472 * session.
474 static void am_destroy(const struct am_state *state)
476 struct strbuf sb = STRBUF_INIT;
478 strbuf_addstr(&sb, state->dir);
479 remove_dir_recursively(&sb, 0);
480 strbuf_release(&sb);
484 * Runs applypatch-msg hook. Returns its exit code.
486 static int run_applypatch_msg_hook(struct am_state *state)
488 int ret = 0;
490 assert(state->msg);
492 if (!state->no_verify)
493 ret = run_hooks_l("applypatch-msg", am_path(state, "final-commit"), NULL);
495 if (!ret) {
496 FREE_AND_NULL(state->msg);
497 if (read_commit_msg(state) < 0)
498 die(_("'%s' was deleted by the applypatch-msg hook"),
499 am_path(state, "final-commit"));
502 return ret;
506 * Runs post-rewrite hook. Returns it exit code.
508 static int run_post_rewrite_hook(const struct am_state *state)
510 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
512 strvec_push(&opt.args, "rebase");
513 opt.path_to_stdin = am_path(state, "rewritten");
515 return run_hooks_opt("post-rewrite", &opt);
519 * Reads the state directory's "rewritten" file, and copies notes from the old
520 * commits listed in the file to their rewritten commits.
522 * Returns 0 on success, -1 on failure.
524 static int copy_notes_for_rebase(const struct am_state *state)
526 struct notes_rewrite_cfg *c;
527 struct strbuf sb = STRBUF_INIT;
528 const char *invalid_line = _("Malformed input line: '%s'.");
529 const char *msg = "Notes added by 'git rebase'";
530 FILE *fp;
531 int ret = 0;
533 assert(state->rebasing);
535 c = init_copy_notes_for_rewrite("rebase");
536 if (!c)
537 return 0;
539 fp = xfopen(am_path(state, "rewritten"), "r");
541 while (!strbuf_getline_lf(&sb, fp)) {
542 struct object_id from_obj, to_obj;
543 const char *p;
545 if (sb.len != the_hash_algo->hexsz * 2 + 1) {
546 ret = error(invalid_line, sb.buf);
547 goto finish;
550 if (parse_oid_hex(sb.buf, &from_obj, &p)) {
551 ret = error(invalid_line, sb.buf);
552 goto finish;
555 if (*p != ' ') {
556 ret = error(invalid_line, sb.buf);
557 goto finish;
560 if (get_oid_hex(p + 1, &to_obj)) {
561 ret = error(invalid_line, sb.buf);
562 goto finish;
565 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
566 ret = error(_("Failed to copy notes from '%s' to '%s'"),
567 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
570 finish:
571 finish_copy_notes_for_rewrite(the_repository, c, msg);
572 fclose(fp);
573 strbuf_release(&sb);
574 return ret;
578 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
579 * non-indented lines and checking if they look like they begin with valid
580 * header field names.
582 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
584 static int is_mail(FILE *fp)
586 const char *header_regex = "^[!-9;-~]+:";
587 struct strbuf sb = STRBUF_INIT;
588 regex_t regex;
589 int ret = 1;
591 if (fseek(fp, 0L, SEEK_SET))
592 die_errno(_("fseek failed"));
594 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
595 die("invalid pattern: %s", header_regex);
597 while (!strbuf_getline(&sb, fp)) {
598 if (!sb.len)
599 break; /* End of header */
601 /* Ignore indented folded lines */
602 if (*sb.buf == '\t' || *sb.buf == ' ')
603 continue;
605 /* It's a header if it matches header_regex */
606 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
607 ret = 0;
608 goto done;
612 done:
613 regfree(&regex);
614 strbuf_release(&sb);
615 return ret;
619 * Attempts to detect the patch_format of the patches contained in `paths`,
620 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
621 * detection fails.
623 static int detect_patch_format(const char **paths)
625 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
626 struct strbuf l1 = STRBUF_INIT;
627 struct strbuf l2 = STRBUF_INIT;
628 struct strbuf l3 = STRBUF_INIT;
629 FILE *fp;
632 * We default to mbox format if input is from stdin and for directories
634 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
635 return PATCH_FORMAT_MBOX;
638 * Otherwise, check the first few lines of the first patch, starting
639 * from the first non-blank line, to try to detect its format.
642 fp = xfopen(*paths, "r");
644 while (!strbuf_getline(&l1, fp)) {
645 if (l1.len)
646 break;
649 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
650 ret = PATCH_FORMAT_MBOX;
651 goto done;
654 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
655 ret = PATCH_FORMAT_STGIT_SERIES;
656 goto done;
659 if (!strcmp(l1.buf, "# HG changeset patch")) {
660 ret = PATCH_FORMAT_HG;
661 goto done;
664 strbuf_getline(&l2, fp);
665 strbuf_getline(&l3, fp);
668 * If the second line is empty and the third is a From, Author or Date
669 * entry, this is likely an StGit patch.
671 if (l1.len && !l2.len &&
672 (starts_with(l3.buf, "From:") ||
673 starts_with(l3.buf, "Author:") ||
674 starts_with(l3.buf, "Date:"))) {
675 ret = PATCH_FORMAT_STGIT;
676 goto done;
679 if (l1.len && is_mail(fp)) {
680 ret = PATCH_FORMAT_MBOX;
681 goto done;
684 done:
685 fclose(fp);
686 strbuf_release(&l1);
687 strbuf_release(&l2);
688 strbuf_release(&l3);
689 return ret;
693 * Splits out individual email patches from `paths`, where each path is either
694 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
696 static int split_mail_mbox(struct am_state *state, const char **paths,
697 int keep_cr, int mboxrd)
699 struct child_process cp = CHILD_PROCESS_INIT;
700 struct strbuf last = STRBUF_INIT;
701 int ret;
703 cp.git_cmd = 1;
704 strvec_push(&cp.args, "mailsplit");
705 strvec_pushf(&cp.args, "-d%d", state->prec);
706 strvec_pushf(&cp.args, "-o%s", state->dir);
707 strvec_push(&cp.args, "-b");
708 if (keep_cr)
709 strvec_push(&cp.args, "--keep-cr");
710 if (mboxrd)
711 strvec_push(&cp.args, "--mboxrd");
712 strvec_push(&cp.args, "--");
713 strvec_pushv(&cp.args, paths);
715 ret = capture_command(&cp, &last, 8);
716 if (ret)
717 goto exit;
719 state->cur = 1;
720 state->last = strtol(last.buf, NULL, 10);
722 exit:
723 strbuf_release(&last);
724 return ret ? -1 : 0;
728 * Callback signature for split_mail_conv(). The foreign patch should be
729 * read from `in`, and the converted patch (in RFC2822 mail format) should be
730 * written to `out`. Return 0 on success, or -1 on failure.
732 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
735 * Calls `fn` for each file in `paths` to convert the foreign patch to the
736 * RFC2822 mail format suitable for parsing with git-mailinfo.
738 * Returns 0 on success, -1 on failure.
740 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
741 const char **paths, int keep_cr)
743 static const char *stdin_only[] = {"-", NULL};
744 int i;
746 if (!*paths)
747 paths = stdin_only;
749 for (i = 0; *paths; paths++, i++) {
750 FILE *in, *out;
751 const char *mail;
752 int ret;
754 if (!strcmp(*paths, "-"))
755 in = stdin;
756 else
757 in = fopen(*paths, "r");
759 if (!in)
760 return error_errno(_("could not open '%s' for reading"),
761 *paths);
763 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
765 out = fopen(mail, "w");
766 if (!out) {
767 if (in != stdin)
768 fclose(in);
769 return error_errno(_("could not open '%s' for writing"),
770 mail);
773 ret = fn(out, in, keep_cr);
775 fclose(out);
776 if (in != stdin)
777 fclose(in);
779 if (ret)
780 return error(_("could not parse patch '%s'"), *paths);
783 state->cur = 1;
784 state->last = i;
785 return 0;
789 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
790 * message suitable for parsing with git-mailinfo.
792 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
794 struct strbuf sb = STRBUF_INIT;
795 int subject_printed = 0;
797 while (!strbuf_getline_lf(&sb, in)) {
798 const char *str;
800 if (str_isspace(sb.buf))
801 continue;
802 else if (skip_prefix(sb.buf, "Author:", &str))
803 fprintf(out, "From:%s\n", str);
804 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
805 fprintf(out, "%s\n", sb.buf);
806 else if (!subject_printed) {
807 fprintf(out, "Subject: %s\n", sb.buf);
808 subject_printed = 1;
809 } else {
810 fprintf(out, "\n%s\n", sb.buf);
811 break;
815 strbuf_reset(&sb);
816 while (strbuf_fread(&sb, 8192, in) > 0) {
817 fwrite(sb.buf, 1, sb.len, out);
818 strbuf_reset(&sb);
821 strbuf_release(&sb);
822 return 0;
826 * This function only supports a single StGit series file in `paths`.
828 * Given an StGit series file, converts the StGit patches in the series into
829 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
830 * the state directory.
832 * Returns 0 on success, -1 on failure.
834 static int split_mail_stgit_series(struct am_state *state, const char **paths,
835 int keep_cr)
837 const char *series_dir;
838 char *series_dir_buf;
839 FILE *fp;
840 struct strvec patches = STRVEC_INIT;
841 struct strbuf sb = STRBUF_INIT;
842 int ret;
844 if (!paths[0] || paths[1])
845 return error(_("Only one StGIT patch series can be applied at once"));
847 series_dir_buf = xstrdup(*paths);
848 series_dir = dirname(series_dir_buf);
850 fp = fopen(*paths, "r");
851 if (!fp)
852 return error_errno(_("could not open '%s' for reading"), *paths);
854 while (!strbuf_getline_lf(&sb, fp)) {
855 if (*sb.buf == '#')
856 continue; /* skip comment lines */
858 strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
861 fclose(fp);
862 strbuf_release(&sb);
863 free(series_dir_buf);
865 ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
867 strvec_clear(&patches);
868 return ret;
872 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
873 * message suitable for parsing with git-mailinfo.
875 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
877 struct strbuf sb = STRBUF_INIT;
878 int rc = 0;
880 while (!strbuf_getline_lf(&sb, in)) {
881 const char *str;
883 if (skip_prefix(sb.buf, "# User ", &str))
884 fprintf(out, "From: %s\n", str);
885 else if (skip_prefix(sb.buf, "# Date ", &str)) {
886 timestamp_t timestamp;
887 long tz, tz2;
888 char *end;
890 errno = 0;
891 timestamp = parse_timestamp(str, &end, 10);
892 if (errno) {
893 rc = error(_("invalid timestamp"));
894 goto exit;
897 if (!skip_prefix(end, " ", &str)) {
898 rc = error(_("invalid Date line"));
899 goto exit;
902 errno = 0;
903 tz = strtol(str, &end, 10);
904 if (errno) {
905 rc = error(_("invalid timezone offset"));
906 goto exit;
909 if (*end) {
910 rc = error(_("invalid Date line"));
911 goto exit;
915 * mercurial's timezone is in seconds west of UTC,
916 * however git's timezone is in hours + minutes east of
917 * UTC. Convert it.
919 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
920 if (tz > 0)
921 tz2 = -tz2;
923 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
924 } else if (starts_with(sb.buf, "# ")) {
925 continue;
926 } else {
927 fprintf(out, "\n%s\n", sb.buf);
928 break;
932 strbuf_reset(&sb);
933 while (strbuf_fread(&sb, 8192, in) > 0) {
934 fwrite(sb.buf, 1, sb.len, out);
935 strbuf_reset(&sb);
937 exit:
938 strbuf_release(&sb);
939 return rc;
943 * Splits a list of files/directories into individual email patches. Each path
944 * in `paths` must be a file/directory that is formatted according to
945 * `patch_format`.
947 * Once split out, the individual email patches will be stored in the state
948 * directory, with each patch's filename being its index, padded to state->prec
949 * digits.
951 * state->cur will be set to the index of the first mail, and state->last will
952 * be set to the index of the last mail.
954 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
955 * to disable this behavior, -1 to use the default configured setting.
957 * Returns 0 on success, -1 on failure.
959 static int split_mail(struct am_state *state, enum patch_format patch_format,
960 const char **paths, int keep_cr)
962 if (keep_cr < 0) {
963 keep_cr = 0;
964 git_config_get_bool("am.keepcr", &keep_cr);
967 switch (patch_format) {
968 case PATCH_FORMAT_MBOX:
969 return split_mail_mbox(state, paths, keep_cr, 0);
970 case PATCH_FORMAT_STGIT:
971 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
972 case PATCH_FORMAT_STGIT_SERIES:
973 return split_mail_stgit_series(state, paths, keep_cr);
974 case PATCH_FORMAT_HG:
975 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
976 case PATCH_FORMAT_MBOXRD:
977 return split_mail_mbox(state, paths, keep_cr, 1);
978 default:
979 BUG("invalid patch_format");
981 return -1;
985 * Setup a new am session for applying patches
987 static void am_setup(struct am_state *state, enum patch_format patch_format,
988 const char **paths, int keep_cr)
990 struct object_id curr_head;
991 const char *str;
992 struct strbuf sb = STRBUF_INIT;
994 if (!patch_format)
995 patch_format = detect_patch_format(paths);
997 if (!patch_format) {
998 fprintf_ln(stderr, _("Patch format detection failed."));
999 exit(128);
1002 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1003 die_errno(_("failed to create directory '%s'"), state->dir);
1004 refs_delete_ref(get_main_ref_store(the_repository), NULL,
1005 "REBASE_HEAD", NULL, REF_NO_DEREF);
1007 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1008 am_destroy(state);
1009 die(_("Failed to split patches."));
1012 if (state->rebasing)
1013 state->threeway = 1;
1015 write_state_bool(state, "threeway", state->threeway);
1016 write_state_bool(state, "quiet", state->quiet);
1017 write_state_bool(state, "sign", state->signoff);
1018 write_state_bool(state, "utf8", state->utf8);
1020 if (state->allow_rerere_autoupdate)
1021 write_state_bool(state, "rerere-autoupdate",
1022 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1024 switch (state->keep) {
1025 case KEEP_FALSE:
1026 str = "f";
1027 break;
1028 case KEEP_TRUE:
1029 str = "t";
1030 break;
1031 case KEEP_NON_PATCH:
1032 str = "b";
1033 break;
1034 default:
1035 BUG("invalid value for state->keep");
1038 write_state_text(state, "keep", str);
1039 write_state_bool(state, "messageid", state->message_id);
1041 switch (state->scissors) {
1042 case SCISSORS_UNSET:
1043 str = "";
1044 break;
1045 case SCISSORS_FALSE:
1046 str = "f";
1047 break;
1048 case SCISSORS_TRUE:
1049 str = "t";
1050 break;
1051 default:
1052 BUG("invalid value for state->scissors");
1054 write_state_text(state, "scissors", str);
1056 switch (state->quoted_cr) {
1057 case quoted_cr_unset:
1058 str = "";
1059 break;
1060 case quoted_cr_nowarn:
1061 str = "nowarn";
1062 break;
1063 case quoted_cr_warn:
1064 str = "warn";
1065 break;
1066 case quoted_cr_strip:
1067 str = "strip";
1068 break;
1069 default:
1070 BUG("invalid value for state->quoted_cr");
1072 write_state_text(state, "quoted-cr", str);
1074 sq_quote_argv(&sb, state->git_apply_opts.v);
1075 write_state_text(state, "apply-opt", sb.buf);
1077 if (state->rebasing)
1078 write_state_text(state, "rebasing", "");
1079 else
1080 write_state_text(state, "applying", "");
1082 if (!repo_get_oid(the_repository, "HEAD", &curr_head)) {
1083 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1084 if (!state->rebasing)
1085 refs_update_ref(get_main_ref_store(the_repository),
1086 "am", "ORIG_HEAD", &curr_head, NULL,
1088 UPDATE_REFS_DIE_ON_ERR);
1089 } else {
1090 write_state_text(state, "abort-safety", "");
1091 if (!state->rebasing)
1092 refs_delete_ref(get_main_ref_store(the_repository),
1093 NULL, "ORIG_HEAD", NULL, 0);
1097 * NOTE: Since the "next" and "last" files determine if an am_state
1098 * session is in progress, they should be written last.
1101 write_state_count(state, "next", state->cur);
1102 write_state_count(state, "last", state->last);
1104 strbuf_release(&sb);
1108 * Increments the patch pointer, and cleans am_state for the application of the
1109 * next patch.
1111 static void am_next(struct am_state *state)
1113 struct object_id head;
1115 FREE_AND_NULL(state->author_name);
1116 FREE_AND_NULL(state->author_email);
1117 FREE_AND_NULL(state->author_date);
1118 FREE_AND_NULL(state->msg);
1119 state->msg_len = 0;
1121 unlink(am_path(state, "author-script"));
1122 unlink(am_path(state, "final-commit"));
1124 oidclr(&state->orig_commit, the_repository->hash_algo);
1125 unlink(am_path(state, "original-commit"));
1126 refs_delete_ref(get_main_ref_store(the_repository), NULL,
1127 "REBASE_HEAD", NULL, REF_NO_DEREF);
1129 if (!repo_get_oid(the_repository, "HEAD", &head))
1130 write_state_text(state, "abort-safety", oid_to_hex(&head));
1131 else
1132 write_state_text(state, "abort-safety", "");
1134 state->cur++;
1135 write_state_count(state, "next", state->cur);
1139 * Returns the filename of the current patch email.
1141 static const char *msgnum(const struct am_state *state)
1143 static struct strbuf sb = STRBUF_INIT;
1145 strbuf_reset(&sb);
1146 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1148 return sb.buf;
1152 * Dies with a user-friendly message on how to proceed after resolving the
1153 * problem. This message can be overridden with state->resolvemsg.
1155 static void NORETURN die_user_resolve(const struct am_state *state)
1157 if (state->resolvemsg) {
1158 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", state->resolvemsg);
1159 } else {
1160 const char *cmdline = state->interactive ? "git am -i" : "git am";
1161 struct strbuf sb = STRBUF_INIT;
1163 strbuf_addf(&sb, _("When you have resolved this problem, run \"%s --continue\".\n"), cmdline);
1164 strbuf_addf(&sb, _("If you prefer to skip this patch, run \"%s --skip\" instead.\n"), cmdline);
1166 if (advice_enabled(ADVICE_AM_WORK_DIR) &&
1167 is_empty_or_missing_file(am_path(state, "patch")) &&
1168 !repo_index_has_changes(the_repository, NULL, NULL))
1169 strbuf_addf(&sb, _("To record the empty patch as an empty commit, run \"%s --allow-empty\".\n"), cmdline);
1171 strbuf_addf(&sb, _("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1173 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", sb.buf);
1174 strbuf_release(&sb);
1177 exit(128);
1181 * Appends signoff to the "msg" field of the am_state.
1183 static void am_append_signoff(struct am_state *state)
1185 struct strbuf sb = STRBUF_INIT;
1187 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1188 append_signoff(&sb, 0, 0);
1189 state->msg = strbuf_detach(&sb, &state->msg_len);
1193 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1194 * state->msg will be set to the patch message. state->author_name,
1195 * state->author_email and state->author_date will be set to the patch author's
1196 * name, email and date respectively. The patch body will be written to the
1197 * state directory's "patch" file.
1199 * Returns 1 if the patch should be skipped, 0 otherwise.
1201 static int parse_mail(struct am_state *state, const char *mail)
1203 FILE *fp;
1204 struct strbuf sb = STRBUF_INIT;
1205 struct strbuf msg = STRBUF_INIT;
1206 struct strbuf author_name = STRBUF_INIT;
1207 struct strbuf author_date = STRBUF_INIT;
1208 struct strbuf author_email = STRBUF_INIT;
1209 int ret = 0;
1210 struct mailinfo mi;
1212 setup_mailinfo(&mi);
1214 if (state->utf8)
1215 mi.metainfo_charset = get_commit_output_encoding();
1216 else
1217 mi.metainfo_charset = NULL;
1219 switch (state->keep) {
1220 case KEEP_FALSE:
1221 break;
1222 case KEEP_TRUE:
1223 mi.keep_subject = 1;
1224 break;
1225 case KEEP_NON_PATCH:
1226 mi.keep_non_patch_brackets_in_subject = 1;
1227 break;
1228 default:
1229 BUG("invalid value for state->keep");
1232 if (state->message_id)
1233 mi.add_message_id = 1;
1235 switch (state->scissors) {
1236 case SCISSORS_UNSET:
1237 break;
1238 case SCISSORS_FALSE:
1239 mi.use_scissors = 0;
1240 break;
1241 case SCISSORS_TRUE:
1242 mi.use_scissors = 1;
1243 break;
1244 default:
1245 BUG("invalid value for state->scissors");
1248 switch (state->quoted_cr) {
1249 case quoted_cr_unset:
1250 break;
1251 case quoted_cr_nowarn:
1252 case quoted_cr_warn:
1253 case quoted_cr_strip:
1254 mi.quoted_cr = state->quoted_cr;
1255 break;
1256 default:
1257 BUG("invalid value for state->quoted_cr");
1260 mi.input = xfopen(mail, "r");
1261 mi.output = xfopen(am_path(state, "info"), "w");
1262 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1263 die("could not parse patch");
1265 fclose(mi.input);
1266 fclose(mi.output);
1268 if (mi.format_flowed)
1269 warning(_("Patch sent with format=flowed; "
1270 "space at the end of lines might be lost."));
1272 /* Extract message and author information */
1273 fp = xfopen(am_path(state, "info"), "r");
1274 while (!strbuf_getline_lf(&sb, fp)) {
1275 const char *x;
1277 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1278 if (msg.len)
1279 strbuf_addch(&msg, '\n');
1280 strbuf_addstr(&msg, x);
1281 } else if (skip_prefix(sb.buf, "Author: ", &x))
1282 strbuf_addstr(&author_name, x);
1283 else if (skip_prefix(sb.buf, "Email: ", &x))
1284 strbuf_addstr(&author_email, x);
1285 else if (skip_prefix(sb.buf, "Date: ", &x))
1286 strbuf_addstr(&author_date, x);
1288 fclose(fp);
1290 /* Skip pine's internal folder data */
1291 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1292 ret = 1;
1293 goto finish;
1296 strbuf_addstr(&msg, "\n\n");
1297 strbuf_addbuf(&msg, &mi.log_message);
1298 strbuf_stripspace(&msg, NULL);
1300 assert(!state->author_name);
1301 state->author_name = strbuf_detach(&author_name, NULL);
1303 assert(!state->author_email);
1304 state->author_email = strbuf_detach(&author_email, NULL);
1306 assert(!state->author_date);
1307 state->author_date = strbuf_detach(&author_date, NULL);
1309 assert(!state->msg);
1310 state->msg = strbuf_detach(&msg, &state->msg_len);
1312 finish:
1313 strbuf_release(&msg);
1314 strbuf_release(&author_date);
1315 strbuf_release(&author_email);
1316 strbuf_release(&author_name);
1317 strbuf_release(&sb);
1318 clear_mailinfo(&mi);
1319 return ret;
1323 * Sets commit_id to the commit hash where the mail was generated from.
1324 * Returns 0 on success, -1 on failure.
1326 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1328 struct strbuf sb = STRBUF_INIT;
1329 FILE *fp = xfopen(mail, "r");
1330 const char *x;
1331 int ret = 0;
1333 if (strbuf_getline_lf(&sb, fp) ||
1334 !skip_prefix(sb.buf, "From ", &x) ||
1335 get_oid_hex(x, commit_id) < 0)
1336 ret = -1;
1338 strbuf_release(&sb);
1339 fclose(fp);
1340 return ret;
1344 * Sets state->msg, state->author_name, state->author_email, state->author_date
1345 * to the commit's respective info.
1347 static void get_commit_info(struct am_state *state, struct commit *commit)
1349 const char *buffer, *ident_line, *msg;
1350 size_t ident_len;
1351 struct ident_split id;
1353 buffer = repo_logmsg_reencode(the_repository, commit, NULL,
1354 get_commit_output_encoding());
1356 ident_line = find_commit_header(buffer, "author", &ident_len);
1357 if (!ident_line)
1358 die(_("missing author line in commit %s"),
1359 oid_to_hex(&commit->object.oid));
1360 if (split_ident_line(&id, ident_line, ident_len) < 0)
1361 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1363 assert(!state->author_name);
1364 if (id.name_begin)
1365 state->author_name =
1366 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1367 else
1368 state->author_name = xstrdup("");
1370 assert(!state->author_email);
1371 if (id.mail_begin)
1372 state->author_email =
1373 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1374 else
1375 state->author_email = xstrdup("");
1377 assert(!state->author_date);
1378 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1380 assert(!state->msg);
1381 msg = strstr(buffer, "\n\n");
1382 if (!msg)
1383 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1384 state->msg = xstrdup(msg + 2);
1385 state->msg_len = strlen(state->msg);
1386 repo_unuse_commit_buffer(the_repository, commit, buffer);
1390 * Writes `commit` as a patch to the state directory's "patch" file.
1392 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1394 struct rev_info rev_info;
1395 FILE *fp;
1397 fp = xfopen(am_path(state, "patch"), "w");
1398 repo_init_revisions(the_repository, &rev_info, NULL);
1399 rev_info.diff = 1;
1400 rev_info.abbrev = 0;
1401 rev_info.disable_stdin = 1;
1402 rev_info.show_root_diff = 1;
1403 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1404 rev_info.no_commit_id = 1;
1405 rev_info.diffopt.flags.binary = 1;
1406 rev_info.diffopt.flags.full_index = 1;
1407 rev_info.diffopt.use_color = 0;
1408 rev_info.diffopt.file = fp;
1409 rev_info.diffopt.close_file = 1;
1410 add_pending_object(&rev_info, &commit->object, "");
1411 diff_setup_done(&rev_info.diffopt);
1412 log_tree_commit(&rev_info, commit);
1413 release_revisions(&rev_info);
1417 * Writes the diff of the index against HEAD as a patch to the state
1418 * directory's "patch" file.
1420 static void write_index_patch(const struct am_state *state)
1422 struct tree *tree;
1423 struct object_id head;
1424 struct rev_info rev_info;
1425 FILE *fp;
1427 if (!repo_get_oid(the_repository, "HEAD", &head)) {
1428 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1429 tree = repo_get_commit_tree(the_repository, commit);
1430 } else
1431 tree = lookup_tree(the_repository,
1432 the_repository->hash_algo->empty_tree);
1434 fp = xfopen(am_path(state, "patch"), "w");
1435 repo_init_revisions(the_repository, &rev_info, NULL);
1436 rev_info.diff = 1;
1437 rev_info.disable_stdin = 1;
1438 rev_info.no_commit_id = 1;
1439 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1440 rev_info.diffopt.use_color = 0;
1441 rev_info.diffopt.file = fp;
1442 rev_info.diffopt.close_file = 1;
1443 add_pending_object(&rev_info, &tree->object, "");
1444 diff_setup_done(&rev_info.diffopt);
1445 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1446 release_revisions(&rev_info);
1450 * Like parse_mail(), but parses the mail by looking up its commit ID
1451 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1452 * of patches.
1454 * state->orig_commit will be set to the original commit ID.
1456 * Will always return 0 as the patch should never be skipped.
1458 static int parse_mail_rebase(struct am_state *state, const char *mail)
1460 struct commit *commit;
1461 struct object_id commit_oid;
1463 if (get_mail_commit_oid(&commit_oid, mail) < 0)
1464 die(_("could not parse %s"), mail);
1466 commit = lookup_commit_or_die(&commit_oid, mail);
1468 get_commit_info(state, commit);
1470 write_commit_patch(state, commit);
1472 oidcpy(&state->orig_commit, &commit_oid);
1473 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1474 refs_update_ref(get_main_ref_store(the_repository), "am",
1475 "REBASE_HEAD", &commit_oid,
1476 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1478 return 0;
1482 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1483 * `index_file` is not NULL, the patch will be applied to that index.
1485 static int run_apply(const struct am_state *state, const char *index_file)
1487 struct strvec apply_paths = STRVEC_INIT;
1488 struct strvec apply_opts = STRVEC_INIT;
1489 struct apply_state apply_state;
1490 int res, opts_left;
1491 int force_apply = 0;
1492 int options = 0;
1493 const char **apply_argv;
1495 if (init_apply_state(&apply_state, the_repository, NULL))
1496 BUG("init_apply_state() failed");
1498 strvec_push(&apply_opts, "apply");
1499 strvec_pushv(&apply_opts, state->git_apply_opts.v);
1502 * Build a copy that apply_parse_options() can rearrange.
1503 * apply_opts.v keeps referencing the allocated strings for
1504 * strvec_clear() to release.
1506 DUP_ARRAY(apply_argv, apply_opts.v, apply_opts.nr);
1508 opts_left = apply_parse_options(apply_opts.nr, apply_argv,
1509 &apply_state, &force_apply, &options,
1510 NULL);
1512 if (opts_left != 0)
1513 die("unknown option passed through to git apply");
1515 if (index_file) {
1516 apply_state.index_file = index_file;
1517 apply_state.cached = 1;
1518 } else
1519 apply_state.check_index = 1;
1522 * If we are allowed to fall back on 3-way merge, don't give false
1523 * errors during the initial attempt.
1525 if (state->threeway && !index_file)
1526 apply_state.apply_verbosity = verbosity_silent;
1528 if (check_apply_state(&apply_state, force_apply))
1529 BUG("check_apply_state() failed");
1531 strvec_push(&apply_paths, am_path(state, "patch"));
1533 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
1535 strvec_clear(&apply_paths);
1536 strvec_clear(&apply_opts);
1537 clear_apply_state(&apply_state);
1538 free(apply_argv);
1540 if (res)
1541 return res;
1543 if (index_file) {
1544 /* Reload index as apply_all_patches() will have modified it. */
1545 discard_index(the_repository->index);
1546 read_index_from(the_repository->index, index_file, get_git_dir());
1549 return 0;
1553 * Builds an index that contains just the blobs needed for a 3way merge.
1555 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1557 struct child_process cp = CHILD_PROCESS_INIT;
1559 cp.git_cmd = 1;
1560 strvec_push(&cp.args, "apply");
1561 strvec_pushv(&cp.args, state->git_apply_opts.v);
1562 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1563 strvec_push(&cp.args, am_path(state, "patch"));
1565 if (run_command(&cp))
1566 return -1;
1568 return 0;
1572 * Attempt a threeway merge, using index_path as the temporary index.
1574 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1576 struct object_id their_tree, our_tree;
1577 struct object_id bases[1] = { 0 };
1578 struct merge_options o;
1579 struct commit *result;
1580 char *their_tree_name;
1582 if (repo_get_oid(the_repository, "HEAD", &our_tree) < 0)
1583 oidcpy(&our_tree, the_hash_algo->empty_tree);
1585 if (build_fake_ancestor(state, index_path))
1586 return error("could not build fake ancestor");
1588 discard_index(the_repository->index);
1589 read_index_from(the_repository->index, index_path, get_git_dir());
1591 if (write_index_as_tree(&bases[0], the_repository->index, index_path, 0, NULL))
1592 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1594 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1596 if (!state->quiet) {
1598 * List paths that needed 3-way fallback, so that the user can
1599 * review them with extra care to spot mismerges.
1601 struct rev_info rev_info;
1603 repo_init_revisions(the_repository, &rev_info, NULL);
1604 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1605 rev_info.diffopt.filter |= diff_filter_bit('A');
1606 rev_info.diffopt.filter |= diff_filter_bit('M');
1607 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1608 diff_setup_done(&rev_info.diffopt);
1609 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1610 release_revisions(&rev_info);
1613 if (run_apply(state, index_path))
1614 return error(_("Did you hand edit your patch?\n"
1615 "It does not apply to blobs recorded in its index."));
1617 if (write_index_as_tree(&their_tree, the_repository->index, index_path, 0, NULL))
1618 return error("could not write tree");
1620 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1622 discard_index(the_repository->index);
1623 repo_read_index(the_repository);
1626 * This is not so wrong. Depending on which base we picked, orig_tree
1627 * may be wildly different from ours, but their_tree has the same set of
1628 * wildly different changes in parts the patch did not touch, so
1629 * recursive ends up canceling them, saying that we reverted all those
1630 * changes.
1633 init_merge_options(&o, the_repository);
1635 o.branch1 = "HEAD";
1636 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1637 o.branch2 = their_tree_name;
1638 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
1640 if (state->quiet)
1641 o.verbosity = 0;
1643 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1644 repo_rerere(the_repository, state->allow_rerere_autoupdate);
1645 free(their_tree_name);
1646 return error(_("Failed to merge in the changes."));
1649 free(their_tree_name);
1650 return 0;
1654 * Commits the current index with state->msg as the commit message and
1655 * state->author_name, state->author_email and state->author_date as the author
1656 * information.
1658 static void do_commit(const struct am_state *state)
1660 struct object_id tree, parent, commit;
1661 const struct object_id *old_oid;
1662 struct commit_list *parents = NULL;
1663 const char *reflog_msg, *author, *committer = NULL;
1664 struct strbuf sb = STRBUF_INIT;
1666 if (!state->no_verify && run_hooks("pre-applypatch"))
1667 exit(1);
1669 if (write_index_as_tree(&tree, the_repository->index, get_index_file(), 0, NULL))
1670 die(_("git write-tree failed to write a tree"));
1672 if (!repo_get_oid_commit(the_repository, "HEAD", &parent)) {
1673 old_oid = &parent;
1674 commit_list_insert(lookup_commit(the_repository, &parent),
1675 &parents);
1676 } else {
1677 old_oid = NULL;
1678 say(state, stderr, _("applying to an empty history"));
1681 author = fmt_ident(state->author_name, state->author_email,
1682 WANT_AUTHOR_IDENT,
1683 state->ignore_date ? NULL : state->author_date,
1684 IDENT_STRICT);
1686 if (state->committer_date_is_author_date)
1687 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1688 getenv("GIT_COMMITTER_EMAIL"),
1689 WANT_COMMITTER_IDENT,
1690 state->ignore_date ? NULL
1691 : state->author_date,
1692 IDENT_STRICT);
1694 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1695 &commit, author, committer, state->sign_commit,
1696 NULL))
1697 die(_("failed to write commit object"));
1699 reflog_msg = getenv("GIT_REFLOG_ACTION");
1700 if (!reflog_msg)
1701 reflog_msg = "am";
1703 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1704 state->msg);
1706 refs_update_ref(get_main_ref_store(the_repository), sb.buf, "HEAD",
1707 &commit, old_oid, 0,
1708 UPDATE_REFS_DIE_ON_ERR);
1710 if (state->rebasing) {
1711 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1713 assert(!is_null_oid(&state->orig_commit));
1714 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1715 fprintf(fp, "%s\n", oid_to_hex(&commit));
1716 fclose(fp);
1719 run_hooks("post-applypatch");
1721 free_commit_list(parents);
1722 strbuf_release(&sb);
1726 * Validates the am_state for resuming -- the "msg" and authorship fields must
1727 * be filled up.
1729 static void validate_resume_state(const struct am_state *state)
1731 if (!state->msg)
1732 die(_("cannot resume: %s does not exist."),
1733 am_path(state, "final-commit"));
1735 if (!state->author_name || !state->author_email || !state->author_date)
1736 die(_("cannot resume: %s does not exist."),
1737 am_path(state, "author-script"));
1741 * Interactively prompt the user on whether the current patch should be
1742 * applied.
1744 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1745 * skip it.
1747 static int do_interactive(struct am_state *state)
1749 assert(state->msg);
1751 for (;;) {
1752 char reply[64];
1754 puts(_("Commit Body is:"));
1755 puts("--------------------------");
1756 printf("%s", state->msg);
1757 puts("--------------------------");
1760 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1761 * in your translation. The program will only accept English
1762 * input at this point.
1764 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1765 if (!fgets(reply, sizeof(reply), stdin))
1766 die("unable to read from stdin; aborting");
1768 if (*reply == 'y' || *reply == 'Y') {
1769 return 0;
1770 } else if (*reply == 'a' || *reply == 'A') {
1771 state->interactive = 0;
1772 return 0;
1773 } else if (*reply == 'n' || *reply == 'N') {
1774 return 1;
1775 } else if (*reply == 'e' || *reply == 'E') {
1776 struct strbuf msg = STRBUF_INIT;
1778 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1779 free(state->msg);
1780 state->msg = strbuf_detach(&msg, &state->msg_len);
1782 strbuf_release(&msg);
1783 } else if (*reply == 'v' || *reply == 'V') {
1784 const char *pager = git_pager(1);
1785 struct child_process cp = CHILD_PROCESS_INIT;
1787 if (!pager)
1788 pager = "cat";
1789 prepare_pager_args(&cp, pager);
1790 strvec_push(&cp.args, am_path(state, "patch"));
1791 run_command(&cp);
1797 * Applies all queued mail.
1799 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1800 * well as the state directory's "patch" file is used as-is for applying the
1801 * patch and committing it.
1803 static void am_run(struct am_state *state, int resume)
1805 struct strbuf sb = STRBUF_INIT;
1807 unlink(am_path(state, "dirtyindex"));
1809 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1810 NULL, NULL, NULL) < 0)
1811 die(_("unable to write index file"));
1813 if (repo_index_has_changes(the_repository, NULL, &sb)) {
1814 write_state_bool(state, "dirtyindex", 1);
1815 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1818 strbuf_release(&sb);
1820 while (state->cur <= state->last) {
1821 const char *mail = am_path(state, msgnum(state));
1822 int apply_status;
1823 int to_keep;
1825 reset_ident_date();
1827 if (!file_exists(mail))
1828 goto next;
1830 if (resume) {
1831 validate_resume_state(state);
1832 } else {
1833 int skip;
1835 if (state->rebasing)
1836 skip = parse_mail_rebase(state, mail);
1837 else
1838 skip = parse_mail(state, mail);
1840 if (skip)
1841 goto next; /* mail should be skipped */
1843 if (state->signoff)
1844 am_append_signoff(state);
1846 write_author_script(state);
1847 write_commit_msg(state);
1850 if (state->interactive && do_interactive(state))
1851 goto next;
1853 to_keep = 0;
1854 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1855 switch (state->empty_type) {
1856 case DROP_EMPTY_COMMIT:
1857 say(state, stdout, _("Skipping: %.*s"), linelen(state->msg), state->msg);
1858 goto next;
1859 break;
1860 case KEEP_EMPTY_COMMIT:
1861 to_keep = 1;
1862 say(state, stdout, _("Creating an empty commit: %.*s"),
1863 linelen(state->msg), state->msg);
1864 break;
1865 case STOP_ON_EMPTY_COMMIT:
1866 printf_ln(_("Patch is empty."));
1867 die_user_resolve(state);
1868 break;
1872 if (run_applypatch_msg_hook(state))
1873 exit(1);
1874 if (to_keep)
1875 goto commit;
1877 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1879 apply_status = run_apply(state, NULL);
1881 if (apply_status && state->threeway) {
1882 struct strbuf sb = STRBUF_INIT;
1884 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1885 apply_status = fall_back_threeway(state, sb.buf);
1886 strbuf_release(&sb);
1889 * Applying the patch to an earlier tree and merging
1890 * the result may have produced the same tree as ours.
1892 if (!apply_status &&
1893 !repo_index_has_changes(the_repository, NULL, NULL)) {
1894 say(state, stdout, _("No changes -- Patch already applied."));
1895 goto next;
1899 if (apply_status) {
1900 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1901 linelen(state->msg), state->msg);
1903 if (advice_enabled(ADVICE_AM_WORK_DIR))
1904 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1906 die_user_resolve(state);
1909 commit:
1910 do_commit(state);
1912 next:
1913 am_next(state);
1915 if (resume)
1916 am_load(state);
1917 resume = 0;
1920 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1921 assert(state->rebasing);
1922 copy_notes_for_rebase(state);
1923 run_post_rewrite_hook(state);
1927 * In rebasing mode, it's up to the caller to take care of
1928 * housekeeping.
1930 if (!state->rebasing) {
1931 am_destroy(state);
1932 run_auto_maintenance(state->quiet);
1937 * Resume the current am session after patch application failure. The user did
1938 * all the hard work, and we do not have to do any patch application. Just
1939 * trust and commit what the user has in the index and working tree. If `allow_empty`
1940 * is true, commit as an empty commit when index has not changed and lacking a patch.
1942 static void am_resolve(struct am_state *state, int allow_empty)
1944 validate_resume_state(state);
1946 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1948 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
1949 if (allow_empty && is_empty_or_missing_file(am_path(state, "patch"))) {
1950 printf_ln(_("No changes - recorded it as an empty commit."));
1951 } else {
1952 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1953 "If there is nothing left to stage, chances are that something else\n"
1954 "already introduced the same changes; you might want to skip this patch."));
1955 die_user_resolve(state);
1959 if (unmerged_index(the_repository->index)) {
1960 printf_ln(_("You still have unmerged paths in your index.\n"
1961 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1962 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1963 die_user_resolve(state);
1966 if (state->interactive) {
1967 write_index_patch(state);
1968 if (do_interactive(state))
1969 goto next;
1972 repo_rerere(the_repository, 0);
1974 do_commit(state);
1976 next:
1977 am_next(state);
1978 am_load(state);
1979 am_run(state, 0);
1983 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1984 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1985 * failure.
1987 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1989 struct lock_file lock_file = LOCK_INIT;
1990 struct unpack_trees_options opts;
1991 struct tree_desc t[2];
1993 if (parse_tree(head) || parse_tree(remote))
1994 return -1;
1996 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
1998 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
2000 memset(&opts, 0, sizeof(opts));
2001 opts.head_idx = 1;
2002 opts.src_index = the_repository->index;
2003 opts.dst_index = the_repository->index;
2004 opts.update = 1;
2005 opts.merge = 1;
2006 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
2007 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
2008 opts.fn = twoway_merge;
2009 init_tree_desc(&t[0], &head->object.oid, head->buffer, head->size);
2010 init_tree_desc(&t[1], &remote->object.oid, remote->buffer, remote->size);
2012 if (unpack_trees(2, t, &opts)) {
2013 rollback_lock_file(&lock_file);
2014 return -1;
2017 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
2018 die(_("unable to write new index file"));
2020 return 0;
2024 * Merges a tree into the index. The index's stat info will take precedence
2025 * over the merged tree's. Returns 0 on success, -1 on failure.
2027 static int merge_tree(struct tree *tree)
2029 struct lock_file lock_file = LOCK_INIT;
2030 struct unpack_trees_options opts;
2031 struct tree_desc t[1];
2033 if (parse_tree(tree))
2034 return -1;
2036 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
2038 memset(&opts, 0, sizeof(opts));
2039 opts.head_idx = 1;
2040 opts.src_index = the_repository->index;
2041 opts.dst_index = the_repository->index;
2042 opts.merge = 1;
2043 opts.fn = oneway_merge;
2044 init_tree_desc(&t[0], &tree->object.oid, tree->buffer, tree->size);
2046 if (unpack_trees(1, t, &opts)) {
2047 rollback_lock_file(&lock_file);
2048 return -1;
2051 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
2052 die(_("unable to write new index file"));
2054 return 0;
2058 * Clean the index without touching entries that are not modified between
2059 * `head` and `remote`.
2061 static int clean_index(const struct object_id *head, const struct object_id *remote)
2063 struct tree *head_tree, *remote_tree, *index_tree;
2064 struct object_id index;
2066 head_tree = parse_tree_indirect(head);
2067 if (!head_tree)
2068 return error(_("Could not parse object '%s'."), oid_to_hex(head));
2070 remote_tree = parse_tree_indirect(remote);
2071 if (!remote_tree)
2072 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
2074 repo_read_index_unmerged(the_repository);
2076 if (fast_forward_to(head_tree, head_tree, 1))
2077 return -1;
2079 if (write_index_as_tree(&index, the_repository->index, get_index_file(), 0, NULL))
2080 return -1;
2082 index_tree = parse_tree_indirect(&index);
2083 if (!index_tree)
2084 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
2086 if (fast_forward_to(index_tree, remote_tree, 0))
2087 return -1;
2089 if (merge_tree(remote_tree))
2090 return -1;
2092 remove_branch_state(the_repository, 0);
2094 return 0;
2098 * Resets rerere's merge resolution metadata.
2100 static void am_rerere_clear(void)
2102 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2103 rerere_clear(the_repository, &merge_rr);
2104 string_list_clear(&merge_rr, 1);
2108 * Resume the current am session by skipping the current patch.
2110 static void am_skip(struct am_state *state)
2112 struct object_id head;
2114 am_rerere_clear();
2116 if (repo_get_oid(the_repository, "HEAD", &head))
2117 oidcpy(&head, the_hash_algo->empty_tree);
2119 if (clean_index(&head, &head))
2120 die(_("failed to clean index"));
2122 if (state->rebasing) {
2123 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2125 assert(!is_null_oid(&state->orig_commit));
2126 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2127 fprintf(fp, "%s\n", oid_to_hex(&head));
2128 fclose(fp);
2131 am_next(state);
2132 am_load(state);
2133 am_run(state, 0);
2137 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2139 * It is not safe to reset HEAD when:
2140 * 1. git-am previously failed because the index was dirty.
2141 * 2. HEAD has moved since git-am previously failed.
2143 static int safe_to_abort(const struct am_state *state)
2145 struct strbuf sb = STRBUF_INIT;
2146 struct object_id abort_safety, head;
2148 if (file_exists(am_path(state, "dirtyindex")))
2149 return 0;
2151 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2152 if (get_oid_hex(sb.buf, &abort_safety))
2153 die(_("could not parse %s"), am_path(state, "abort-safety"));
2154 } else
2155 oidclr(&abort_safety, the_repository->hash_algo);
2156 strbuf_release(&sb);
2158 if (repo_get_oid(the_repository, "HEAD", &head))
2159 oidclr(&head, the_repository->hash_algo);
2161 if (oideq(&head, &abort_safety))
2162 return 1;
2164 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2165 "Not rewinding to ORIG_HEAD"));
2167 return 0;
2171 * Aborts the current am session if it is safe to do so.
2173 static void am_abort(struct am_state *state)
2175 struct object_id curr_head, orig_head;
2176 int has_curr_head, has_orig_head;
2177 char *curr_branch;
2179 if (!safe_to_abort(state)) {
2180 am_destroy(state);
2181 return;
2184 am_rerere_clear();
2186 curr_branch = refs_resolve_refdup(get_main_ref_store(the_repository),
2187 "HEAD", 0, &curr_head, NULL);
2188 has_curr_head = curr_branch && !is_null_oid(&curr_head);
2189 if (!has_curr_head)
2190 oidcpy(&curr_head, the_hash_algo->empty_tree);
2192 has_orig_head = !repo_get_oid(the_repository, "ORIG_HEAD", &orig_head);
2193 if (!has_orig_head)
2194 oidcpy(&orig_head, the_hash_algo->empty_tree);
2196 if (clean_index(&curr_head, &orig_head))
2197 die(_("failed to clean index"));
2199 if (has_orig_head)
2200 refs_update_ref(get_main_ref_store(the_repository),
2201 "am --abort", "HEAD", &orig_head,
2202 has_curr_head ? &curr_head : NULL, 0,
2203 UPDATE_REFS_DIE_ON_ERR);
2204 else if (curr_branch)
2205 refs_delete_ref(get_main_ref_store(the_repository), NULL,
2206 curr_branch, NULL, REF_NO_DEREF);
2208 free(curr_branch);
2209 am_destroy(state);
2212 static int show_patch(struct am_state *state, enum resume_type resume_mode)
2214 struct strbuf sb = STRBUF_INIT;
2215 const char *patch_path;
2216 int len;
2218 if (!is_null_oid(&state->orig_commit)) {
2219 struct child_process cmd = CHILD_PROCESS_INIT;
2221 strvec_pushl(&cmd.args, "show", oid_to_hex(&state->orig_commit),
2222 "--", NULL);
2223 cmd.git_cmd = 1;
2224 return run_command(&cmd);
2227 switch (resume_mode) {
2228 case RESUME_SHOW_PATCH_RAW:
2229 patch_path = am_path(state, msgnum(state));
2230 break;
2231 case RESUME_SHOW_PATCH_DIFF:
2232 patch_path = am_path(state, "patch");
2233 break;
2234 default:
2235 BUG("invalid mode for --show-current-patch");
2238 len = strbuf_read_file(&sb, patch_path, 0);
2239 if (len < 0)
2240 die_errno(_("failed to read '%s'"), patch_path);
2242 setup_pager();
2243 write_in_full(1, sb.buf, sb.len);
2244 strbuf_release(&sb);
2245 return 0;
2249 * parse_options() callback that validates and sets opt->value to the
2250 * PATCH_FORMAT_* enum value corresponding to `arg`.
2252 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2254 int *opt_value = opt->value;
2256 if (unset)
2257 *opt_value = PATCH_FORMAT_UNKNOWN;
2258 else if (!strcmp(arg, "mbox"))
2259 *opt_value = PATCH_FORMAT_MBOX;
2260 else if (!strcmp(arg, "stgit"))
2261 *opt_value = PATCH_FORMAT_STGIT;
2262 else if (!strcmp(arg, "stgit-series"))
2263 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2264 else if (!strcmp(arg, "hg"))
2265 *opt_value = PATCH_FORMAT_HG;
2266 else if (!strcmp(arg, "mboxrd"))
2267 *opt_value = PATCH_FORMAT_MBOXRD;
2269 * Please update $__git_patchformat in git-completion.bash
2270 * when you add new options
2272 else
2273 return error(_("invalid value for '%s': '%s'"),
2274 "--patch-format", arg);
2275 return 0;
2278 static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2280 int *opt_value = opt->value;
2282 BUG_ON_OPT_NEG(unset);
2284 if (!arg)
2285 *opt_value = opt->defval;
2286 else if (!strcmp(arg, "raw"))
2287 *opt_value = RESUME_SHOW_PATCH_RAW;
2288 else if (!strcmp(arg, "diff"))
2289 *opt_value = RESUME_SHOW_PATCH_DIFF;
2291 * Please update $__git_showcurrentpatch in git-completion.bash
2292 * when you add new options
2294 else
2295 return error(_("invalid value for '%s': '%s'"),
2296 "--show-current-patch", arg);
2297 return 0;
2300 int cmd_am(int argc, const char **argv, const char *prefix)
2302 struct am_state state;
2303 int binary = -1;
2304 int keep_cr = -1;
2305 int patch_format = PATCH_FORMAT_UNKNOWN;
2306 enum resume_type resume_mode = RESUME_FALSE;
2307 int in_progress;
2308 int ret = 0;
2310 const char * const usage[] = {
2311 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2312 N_("git am [<options>] (--continue | --skip | --abort)"),
2313 NULL
2316 struct option options[] = {
2317 OPT_BOOL('i', "interactive", &state.interactive,
2318 N_("run interactively")),
2319 OPT_BOOL('n', "no-verify", &state.no_verify,
2320 N_("bypass pre-applypatch and applypatch-msg hooks")),
2321 OPT_HIDDEN_BOOL('b', "binary", &binary,
2322 N_("historical option -- no-op")),
2323 OPT_BOOL('3', "3way", &state.threeway,
2324 N_("allow fall back on 3way merging if needed")),
2325 OPT__QUIET(&state.quiet, N_("be quiet")),
2326 OPT_SET_INT('s', "signoff", &state.signoff,
2327 N_("add a Signed-off-by trailer to the commit message"),
2328 SIGNOFF_EXPLICIT),
2329 OPT_BOOL('u', "utf8", &state.utf8,
2330 N_("recode into utf8 (default)")),
2331 OPT_SET_INT('k', "keep", &state.keep,
2332 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2333 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2334 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2335 OPT_BOOL('m', "message-id", &state.message_id,
2336 N_("pass -m flag to git-mailinfo")),
2337 OPT_SET_INT(0, "keep-cr", &keep_cr,
2338 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2340 OPT_BOOL('c', "scissors", &state.scissors,
2341 N_("strip everything before a scissors line")),
2342 OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2343 N_("pass it through git-mailinfo"),
2344 PARSE_OPT_NONEG, am_option_parse_quoted_cr),
2345 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2346 N_("pass it through git-apply"),
2348 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2349 N_("pass it through git-apply"),
2350 PARSE_OPT_NOARG),
2351 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2352 N_("pass it through git-apply"),
2353 PARSE_OPT_NOARG),
2354 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2355 N_("pass it through git-apply"),
2357 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2358 N_("pass it through git-apply"),
2360 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2361 N_("pass it through git-apply"),
2363 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2364 N_("pass it through git-apply"),
2366 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2367 N_("pass it through git-apply"),
2369 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2370 N_("format the patch(es) are in"),
2371 parse_opt_patchformat),
2372 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2373 N_("pass it through git-apply"),
2374 PARSE_OPT_NOARG),
2375 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2376 N_("override error message when patch failure occurs")),
2377 OPT_CMDMODE(0, "continue", &resume_mode,
2378 N_("continue applying patches after resolving a conflict"),
2379 RESUME_RESOLVED),
2380 OPT_CMDMODE('r', "resolved", &resume_mode,
2381 N_("synonyms for --continue"),
2382 RESUME_RESOLVED),
2383 OPT_CMDMODE(0, "skip", &resume_mode,
2384 N_("skip the current patch"),
2385 RESUME_SKIP),
2386 OPT_CMDMODE(0, "abort", &resume_mode,
2387 N_("restore the original branch and abort the patching operation"),
2388 RESUME_ABORT),
2389 OPT_CMDMODE(0, "quit", &resume_mode,
2390 N_("abort the patching operation but keep HEAD where it is"),
2391 RESUME_QUIT),
2392 { OPTION_CALLBACK, 0, "show-current-patch", &resume_mode,
2393 "(diff|raw)",
2394 N_("show the patch being applied"),
2395 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2396 parse_opt_show_current_patch, RESUME_SHOW_PATCH_RAW },
2397 OPT_CMDMODE(0, "retry", &resume_mode,
2398 N_("try to apply current patch again"),
2399 RESUME_APPLY),
2400 OPT_CMDMODE(0, "allow-empty", &resume_mode,
2401 N_("record the empty patch as an empty commit"),
2402 RESUME_ALLOW_EMPTY),
2403 OPT_BOOL(0, "committer-date-is-author-date",
2404 &state.committer_date_is_author_date,
2405 N_("lie about committer date")),
2406 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2407 N_("use current timestamp for author date")),
2408 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2409 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2410 N_("GPG-sign commits"),
2411 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2412 OPT_CALLBACK_F(0, "empty", &state.empty_type, "(stop|drop|keep)",
2413 N_("how to handle empty patches"),
2414 PARSE_OPT_NONEG, am_option_parse_empty),
2415 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2416 N_("(internal use for git-rebase)")),
2417 OPT_END()
2420 if (argc == 2 && !strcmp(argv[1], "-h"))
2421 usage_with_options(usage, options);
2423 git_config(git_default_config, NULL);
2425 am_state_init(&state);
2427 in_progress = am_in_progress(&state);
2428 if (in_progress)
2429 am_load(&state);
2431 argc = parse_options(argc, argv, prefix, options, usage, 0);
2433 if (binary >= 0)
2434 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2435 "it will be removed. Please do not use it anymore."));
2437 /* Ensure a valid committer ident can be constructed */
2438 git_committer_info(IDENT_STRICT);
2440 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
2441 die(_("failed to read the index"));
2443 if (in_progress) {
2445 * Catch user error to feed us patches when there is a session
2446 * in progress:
2448 * 1. mbox path(s) are provided on the command-line.
2449 * 2. stdin is not a tty: the user is trying to feed us a patch
2450 * from standard input. This is somewhat unreliable -- stdin
2451 * could be /dev/null for example and the caller did not
2452 * intend to feed us a patch but wanted to continue
2453 * unattended.
2455 if (argc || (resume_mode == RESUME_FALSE && !isatty(0)))
2456 die(_("previous rebase directory %s still exists but mbox given."),
2457 state.dir);
2459 if (resume_mode == RESUME_FALSE)
2460 resume_mode = RESUME_APPLY;
2462 if (state.signoff == SIGNOFF_EXPLICIT)
2463 am_append_signoff(&state);
2464 } else {
2465 struct strvec paths = STRVEC_INIT;
2466 int i;
2469 * Handle stray state directory in the independent-run case. In
2470 * the --rebasing case, it is up to the caller to take care of
2471 * stray directories.
2473 if (file_exists(state.dir) && !state.rebasing) {
2474 if (resume_mode == RESUME_ABORT || resume_mode == RESUME_QUIT) {
2475 am_destroy(&state);
2476 am_state_release(&state);
2477 return 0;
2480 die(_("Stray %s directory found.\n"
2481 "Use \"git am --abort\" to remove it."),
2482 state.dir);
2485 if (resume_mode)
2486 die(_("Resolve operation not in progress, we are not resuming."));
2488 for (i = 0; i < argc; i++) {
2489 if (is_absolute_path(argv[i]) || !prefix)
2490 strvec_push(&paths, argv[i]);
2491 else
2492 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2495 if (state.interactive && !paths.nr)
2496 die(_("interactive mode requires patches on the command line"));
2498 am_setup(&state, patch_format, paths.v, keep_cr);
2500 strvec_clear(&paths);
2503 switch (resume_mode) {
2504 case RESUME_FALSE:
2505 am_run(&state, 0);
2506 break;
2507 case RESUME_APPLY:
2508 am_run(&state, 1);
2509 break;
2510 case RESUME_RESOLVED:
2511 case RESUME_ALLOW_EMPTY:
2512 am_resolve(&state, resume_mode == RESUME_ALLOW_EMPTY ? 1 : 0);
2513 break;
2514 case RESUME_SKIP:
2515 am_skip(&state);
2516 break;
2517 case RESUME_ABORT:
2518 am_abort(&state);
2519 break;
2520 case RESUME_QUIT:
2521 am_rerere_clear();
2522 am_destroy(&state);
2523 break;
2524 case RESUME_SHOW_PATCH_RAW:
2525 case RESUME_SHOW_PATCH_DIFF:
2526 ret = show_patch(&state, resume_mode);
2527 break;
2528 default:
2529 BUG("invalid resume value");
2532 am_state_release(&state);
2534 return ret;