gpg-interface: drop pointless config_error_nonbool() checks
[alt-git.git] / builtin / am.c
blob9f084d58bc705c74d6986541fe81161dcd37df8c
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
6 #define USE_THE_INDEX_VARIABLE
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 "exec-cmd.h"
14 #include "gettext.h"
15 #include "hex.h"
16 #include "parse-options.h"
17 #include "dir.h"
18 #include "run-command.h"
19 #include "hook.h"
20 #include "quote.h"
21 #include "tempfile.h"
22 #include "lockfile.h"
23 #include "cache-tree.h"
24 #include "refs.h"
25 #include "commit.h"
26 #include "diff.h"
27 #include "diffcore.h"
28 #include "unpack-trees.h"
29 #include "branch.h"
30 #include "object-name.h"
31 #include "preload-index.h"
32 #include "sequencer.h"
33 #include "revision.h"
34 #include "merge-recursive.h"
35 #include "log-tree.h"
36 #include "notes-utils.h"
37 #include "rerere.h"
38 #include "prompt.h"
39 #include "mailinfo.h"
40 #include "apply.h"
41 #include "string-list.h"
42 #include "packfile.h"
43 #include "pager.h"
44 #include "path.h"
45 #include "repository.h"
46 #include "pretty.h"
48 /**
49 * Returns the length of the first line of msg.
51 static int linelen(const char *msg)
53 return strchrnul(msg, '\n') - msg;
56 /**
57 * Returns true if `str` consists of only whitespace, false otherwise.
59 static int str_isspace(const char *str)
61 for (; *str; str++)
62 if (!isspace(*str))
63 return 0;
65 return 1;
68 enum patch_format {
69 PATCH_FORMAT_UNKNOWN = 0,
70 PATCH_FORMAT_MBOX,
71 PATCH_FORMAT_STGIT,
72 PATCH_FORMAT_STGIT_SERIES,
73 PATCH_FORMAT_HG,
74 PATCH_FORMAT_MBOXRD
77 enum keep_type {
78 KEEP_FALSE = 0,
79 KEEP_TRUE, /* pass -k flag to git-mailinfo */
80 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
83 enum scissors_type {
84 SCISSORS_UNSET = -1,
85 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
86 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
89 enum signoff_type {
90 SIGNOFF_FALSE = 0,
91 SIGNOFF_TRUE = 1,
92 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
95 enum resume_type {
96 RESUME_FALSE = 0,
97 RESUME_APPLY,
98 RESUME_RESOLVED,
99 RESUME_SKIP,
100 RESUME_ABORT,
101 RESUME_QUIT,
102 RESUME_SHOW_PATCH_RAW,
103 RESUME_SHOW_PATCH_DIFF,
104 RESUME_ALLOW_EMPTY,
107 enum empty_action {
108 STOP_ON_EMPTY_COMMIT = 0, /* output errors and stop in the middle of an am session */
109 DROP_EMPTY_COMMIT, /* skip with a notice message, unless "--quiet" has been passed */
110 KEEP_EMPTY_COMMIT, /* keep recording as empty commits */
113 struct am_state {
114 /* state directory path */
115 char *dir;
117 /* current and last patch numbers, 1-indexed */
118 int cur;
119 int last;
121 /* commit metadata and message */
122 char *author_name;
123 char *author_email;
124 char *author_date;
125 char *msg;
126 size_t msg_len;
128 /* when --rebasing, records the original commit the patch came from */
129 struct object_id orig_commit;
131 /* number of digits in patch filename */
132 int prec;
134 /* various operating modes and command line options */
135 int interactive;
136 int no_verify;
137 int threeway;
138 int quiet;
139 int signoff; /* enum signoff_type */
140 int utf8;
141 int keep; /* enum keep_type */
142 int message_id;
143 int scissors; /* enum scissors_type */
144 int quoted_cr; /* enum quoted_cr_action */
145 int empty_type; /* enum empty_action */
146 struct strvec git_apply_opts;
147 const char *resolvemsg;
148 int committer_date_is_author_date;
149 int ignore_date;
150 int allow_rerere_autoupdate;
151 const char *sign_commit;
152 int rebasing;
156 * Initializes am_state with the default values.
158 static void am_state_init(struct am_state *state)
160 int gpgsign;
162 memset(state, 0, sizeof(*state));
164 state->dir = git_pathdup("rebase-apply");
166 state->prec = 4;
168 git_config_get_bool("am.threeway", &state->threeway);
170 state->utf8 = 1;
172 git_config_get_bool("am.messageid", &state->message_id);
174 state->scissors = SCISSORS_UNSET;
175 state->quoted_cr = quoted_cr_unset;
177 strvec_init(&state->git_apply_opts);
179 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
180 state->sign_commit = gpgsign ? "" : NULL;
184 * Releases memory allocated by an am_state.
186 static void am_state_release(struct am_state *state)
188 free(state->dir);
189 free(state->author_name);
190 free(state->author_email);
191 free(state->author_date);
192 free(state->msg);
193 strvec_clear(&state->git_apply_opts);
196 static int am_option_parse_quoted_cr(const struct option *opt,
197 const char *arg, int unset)
199 BUG_ON_OPT_NEG(unset);
201 if (mailinfo_parse_quoted_cr_action(arg, opt->value) != 0)
202 return error(_("bad action '%s' for '%s'"), arg, "--quoted-cr");
203 return 0;
206 static int am_option_parse_empty(const struct option *opt,
207 const char *arg, int unset)
209 int *opt_value = opt->value;
211 BUG_ON_OPT_NEG(unset);
213 if (!strcmp(arg, "stop"))
214 *opt_value = STOP_ON_EMPTY_COMMIT;
215 else if (!strcmp(arg, "drop"))
216 *opt_value = DROP_EMPTY_COMMIT;
217 else if (!strcmp(arg, "keep"))
218 *opt_value = KEEP_EMPTY_COMMIT;
219 else
220 return error(_("invalid value for '%s': '%s'"), "--empty", arg);
222 return 0;
226 * Returns path relative to the am_state directory.
228 static inline const char *am_path(const struct am_state *state, const char *path)
230 return mkpath("%s/%s", state->dir, path);
234 * For convenience to call write_file()
236 static void write_state_text(const struct am_state *state,
237 const char *name, const char *string)
239 write_file(am_path(state, name), "%s", string);
242 static void write_state_count(const struct am_state *state,
243 const char *name, int value)
245 write_file(am_path(state, name), "%d", value);
248 static void write_state_bool(const struct am_state *state,
249 const char *name, int value)
251 write_state_text(state, name, value ? "t" : "f");
255 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
256 * at the end.
258 __attribute__((format (printf, 3, 4)))
259 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
261 va_list ap;
263 va_start(ap, fmt);
264 if (!state->quiet) {
265 vfprintf(fp, fmt, ap);
266 putc('\n', fp);
268 va_end(ap);
272 * Returns 1 if there is an am session in progress, 0 otherwise.
274 static int am_in_progress(const struct am_state *state)
276 struct stat st;
278 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
279 return 0;
280 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
281 return 0;
282 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
283 return 0;
284 return 1;
288 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
289 * number of bytes read on success, -1 if the file does not exist. If `trim` is
290 * set, trailing whitespace will be removed.
292 static int read_state_file(struct strbuf *sb, const struct am_state *state,
293 const char *file, int trim)
295 strbuf_reset(sb);
297 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
298 if (trim)
299 strbuf_trim(sb);
301 return sb->len;
304 if (errno == ENOENT)
305 return -1;
307 die_errno(_("could not read '%s'"), am_path(state, file));
311 * Reads and parses the state directory's "author-script" file, and sets
312 * state->author_name, state->author_email and state->author_date accordingly.
313 * Returns 0 on success, -1 if the file could not be parsed.
315 * The author script is of the format:
317 * GIT_AUTHOR_NAME='$author_name'
318 * GIT_AUTHOR_EMAIL='$author_email'
319 * GIT_AUTHOR_DATE='$author_date'
321 * where $author_name, $author_email and $author_date are quoted. We are strict
322 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
323 * script, and thus if the file differs from what this function expects, it is
324 * better to bail out than to do something that the user does not expect.
326 static int read_am_author_script(struct am_state *state)
328 const char *filename = am_path(state, "author-script");
330 assert(!state->author_name);
331 assert(!state->author_email);
332 assert(!state->author_date);
334 return read_author_script(filename, &state->author_name,
335 &state->author_email, &state->author_date, 1);
339 * Saves state->author_name, state->author_email and state->author_date in the
340 * state directory's "author-script" file.
342 static void write_author_script(const struct am_state *state)
344 struct strbuf sb = STRBUF_INIT;
346 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
347 sq_quote_buf(&sb, state->author_name);
348 strbuf_addch(&sb, '\n');
350 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
351 sq_quote_buf(&sb, state->author_email);
352 strbuf_addch(&sb, '\n');
354 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
355 sq_quote_buf(&sb, state->author_date);
356 strbuf_addch(&sb, '\n');
358 write_state_text(state, "author-script", sb.buf);
360 strbuf_release(&sb);
364 * Reads the commit message from the state directory's "final-commit" file,
365 * setting state->msg to its contents and state->msg_len to the length of its
366 * contents in bytes.
368 * Returns 0 on success, -1 if the file does not exist.
370 static int read_commit_msg(struct am_state *state)
372 struct strbuf sb = STRBUF_INIT;
374 assert(!state->msg);
376 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
377 strbuf_release(&sb);
378 return -1;
381 state->msg = strbuf_detach(&sb, &state->msg_len);
382 return 0;
386 * Saves state->msg in the state directory's "final-commit" file.
388 static void write_commit_msg(const struct am_state *state)
390 const char *filename = am_path(state, "final-commit");
391 write_file_buf(filename, state->msg, state->msg_len);
395 * Loads state from disk.
397 static void am_load(struct am_state *state)
399 struct strbuf sb = STRBUF_INIT;
401 if (read_state_file(&sb, state, "next", 1) < 0)
402 BUG("state file 'next' does not exist");
403 state->cur = strtol(sb.buf, NULL, 10);
405 if (read_state_file(&sb, state, "last", 1) < 0)
406 BUG("state file 'last' does not exist");
407 state->last = strtol(sb.buf, NULL, 10);
409 if (read_am_author_script(state) < 0)
410 die(_("could not parse author script"));
412 read_commit_msg(state);
414 if (read_state_file(&sb, state, "original-commit", 1) < 0)
415 oidclr(&state->orig_commit);
416 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
417 die(_("could not parse %s"), am_path(state, "original-commit"));
419 read_state_file(&sb, state, "threeway", 1);
420 state->threeway = !strcmp(sb.buf, "t");
422 read_state_file(&sb, state, "quiet", 1);
423 state->quiet = !strcmp(sb.buf, "t");
425 read_state_file(&sb, state, "sign", 1);
426 state->signoff = !strcmp(sb.buf, "t");
428 read_state_file(&sb, state, "utf8", 1);
429 state->utf8 = !strcmp(sb.buf, "t");
431 if (file_exists(am_path(state, "rerere-autoupdate"))) {
432 read_state_file(&sb, state, "rerere-autoupdate", 1);
433 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
434 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
435 } else {
436 state->allow_rerere_autoupdate = 0;
439 read_state_file(&sb, state, "keep", 1);
440 if (!strcmp(sb.buf, "t"))
441 state->keep = KEEP_TRUE;
442 else if (!strcmp(sb.buf, "b"))
443 state->keep = KEEP_NON_PATCH;
444 else
445 state->keep = KEEP_FALSE;
447 read_state_file(&sb, state, "messageid", 1);
448 state->message_id = !strcmp(sb.buf, "t");
450 read_state_file(&sb, state, "scissors", 1);
451 if (!strcmp(sb.buf, "t"))
452 state->scissors = SCISSORS_TRUE;
453 else if (!strcmp(sb.buf, "f"))
454 state->scissors = SCISSORS_FALSE;
455 else
456 state->scissors = SCISSORS_UNSET;
458 read_state_file(&sb, state, "quoted-cr", 1);
459 if (!*sb.buf)
460 state->quoted_cr = quoted_cr_unset;
461 else if (mailinfo_parse_quoted_cr_action(sb.buf, &state->quoted_cr) != 0)
462 die(_("could not parse %s"), am_path(state, "quoted-cr"));
464 read_state_file(&sb, state, "apply-opt", 1);
465 strvec_clear(&state->git_apply_opts);
466 if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
467 die(_("could not parse %s"), am_path(state, "apply-opt"));
469 state->rebasing = !!file_exists(am_path(state, "rebasing"));
471 strbuf_release(&sb);
475 * Removes the am_state directory, forcefully terminating the current am
476 * session.
478 static void am_destroy(const struct am_state *state)
480 struct strbuf sb = STRBUF_INIT;
482 strbuf_addstr(&sb, state->dir);
483 remove_dir_recursively(&sb, 0);
484 strbuf_release(&sb);
488 * Runs applypatch-msg hook. Returns its exit code.
490 static int run_applypatch_msg_hook(struct am_state *state)
492 int ret = 0;
494 assert(state->msg);
496 if (!state->no_verify)
497 ret = run_hooks_l("applypatch-msg", am_path(state, "final-commit"), NULL);
499 if (!ret) {
500 FREE_AND_NULL(state->msg);
501 if (read_commit_msg(state) < 0)
502 die(_("'%s' was deleted by the applypatch-msg hook"),
503 am_path(state, "final-commit"));
506 return ret;
510 * Runs post-rewrite hook. Returns it exit code.
512 static int run_post_rewrite_hook(const struct am_state *state)
514 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
516 strvec_push(&opt.args, "rebase");
517 opt.path_to_stdin = am_path(state, "rewritten");
519 return run_hooks_opt("post-rewrite", &opt);
523 * Reads the state directory's "rewritten" file, and copies notes from the old
524 * commits listed in the file to their rewritten commits.
526 * Returns 0 on success, -1 on failure.
528 static int copy_notes_for_rebase(const struct am_state *state)
530 struct notes_rewrite_cfg *c;
531 struct strbuf sb = STRBUF_INIT;
532 const char *invalid_line = _("Malformed input line: '%s'.");
533 const char *msg = "Notes added by 'git rebase'";
534 FILE *fp;
535 int ret = 0;
537 assert(state->rebasing);
539 c = init_copy_notes_for_rewrite("rebase");
540 if (!c)
541 return 0;
543 fp = xfopen(am_path(state, "rewritten"), "r");
545 while (!strbuf_getline_lf(&sb, fp)) {
546 struct object_id from_obj, to_obj;
547 const char *p;
549 if (sb.len != the_hash_algo->hexsz * 2 + 1) {
550 ret = error(invalid_line, sb.buf);
551 goto finish;
554 if (parse_oid_hex(sb.buf, &from_obj, &p)) {
555 ret = error(invalid_line, sb.buf);
556 goto finish;
559 if (*p != ' ') {
560 ret = error(invalid_line, sb.buf);
561 goto finish;
564 if (get_oid_hex(p + 1, &to_obj)) {
565 ret = error(invalid_line, sb.buf);
566 goto finish;
569 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
570 ret = error(_("Failed to copy notes from '%s' to '%s'"),
571 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
574 finish:
575 finish_copy_notes_for_rewrite(the_repository, c, msg);
576 fclose(fp);
577 strbuf_release(&sb);
578 return ret;
582 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
583 * non-indented lines and checking if they look like they begin with valid
584 * header field names.
586 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
588 static int is_mail(FILE *fp)
590 const char *header_regex = "^[!-9;-~]+:";
591 struct strbuf sb = STRBUF_INIT;
592 regex_t regex;
593 int ret = 1;
595 if (fseek(fp, 0L, SEEK_SET))
596 die_errno(_("fseek failed"));
598 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
599 die("invalid pattern: %s", header_regex);
601 while (!strbuf_getline(&sb, fp)) {
602 if (!sb.len)
603 break; /* End of header */
605 /* Ignore indented folded lines */
606 if (*sb.buf == '\t' || *sb.buf == ' ')
607 continue;
609 /* It's a header if it matches header_regex */
610 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
611 ret = 0;
612 goto done;
616 done:
617 regfree(&regex);
618 strbuf_release(&sb);
619 return ret;
623 * Attempts to detect the patch_format of the patches contained in `paths`,
624 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
625 * detection fails.
627 static int detect_patch_format(const char **paths)
629 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
630 struct strbuf l1 = STRBUF_INIT;
631 struct strbuf l2 = STRBUF_INIT;
632 struct strbuf l3 = STRBUF_INIT;
633 FILE *fp;
636 * We default to mbox format if input is from stdin and for directories
638 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
639 return PATCH_FORMAT_MBOX;
642 * Otherwise, check the first few lines of the first patch, starting
643 * from the first non-blank line, to try to detect its format.
646 fp = xfopen(*paths, "r");
648 while (!strbuf_getline(&l1, fp)) {
649 if (l1.len)
650 break;
653 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
654 ret = PATCH_FORMAT_MBOX;
655 goto done;
658 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
659 ret = PATCH_FORMAT_STGIT_SERIES;
660 goto done;
663 if (!strcmp(l1.buf, "# HG changeset patch")) {
664 ret = PATCH_FORMAT_HG;
665 goto done;
668 strbuf_getline(&l2, fp);
669 strbuf_getline(&l3, fp);
672 * If the second line is empty and the third is a From, Author or Date
673 * entry, this is likely an StGit patch.
675 if (l1.len && !l2.len &&
676 (starts_with(l3.buf, "From:") ||
677 starts_with(l3.buf, "Author:") ||
678 starts_with(l3.buf, "Date:"))) {
679 ret = PATCH_FORMAT_STGIT;
680 goto done;
683 if (l1.len && is_mail(fp)) {
684 ret = PATCH_FORMAT_MBOX;
685 goto done;
688 done:
689 fclose(fp);
690 strbuf_release(&l1);
691 strbuf_release(&l2);
692 strbuf_release(&l3);
693 return ret;
697 * Splits out individual email patches from `paths`, where each path is either
698 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
700 static int split_mail_mbox(struct am_state *state, const char **paths,
701 int keep_cr, int mboxrd)
703 struct child_process cp = CHILD_PROCESS_INIT;
704 struct strbuf last = STRBUF_INIT;
705 int ret;
707 cp.git_cmd = 1;
708 strvec_push(&cp.args, "mailsplit");
709 strvec_pushf(&cp.args, "-d%d", state->prec);
710 strvec_pushf(&cp.args, "-o%s", state->dir);
711 strvec_push(&cp.args, "-b");
712 if (keep_cr)
713 strvec_push(&cp.args, "--keep-cr");
714 if (mboxrd)
715 strvec_push(&cp.args, "--mboxrd");
716 strvec_push(&cp.args, "--");
717 strvec_pushv(&cp.args, paths);
719 ret = capture_command(&cp, &last, 8);
720 if (ret)
721 goto exit;
723 state->cur = 1;
724 state->last = strtol(last.buf, NULL, 10);
726 exit:
727 strbuf_release(&last);
728 return ret ? -1 : 0;
732 * Callback signature for split_mail_conv(). The foreign patch should be
733 * read from `in`, and the converted patch (in RFC2822 mail format) should be
734 * written to `out`. Return 0 on success, or -1 on failure.
736 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
739 * Calls `fn` for each file in `paths` to convert the foreign patch to the
740 * RFC2822 mail format suitable for parsing with git-mailinfo.
742 * Returns 0 on success, -1 on failure.
744 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
745 const char **paths, int keep_cr)
747 static const char *stdin_only[] = {"-", NULL};
748 int i;
750 if (!*paths)
751 paths = stdin_only;
753 for (i = 0; *paths; paths++, i++) {
754 FILE *in, *out;
755 const char *mail;
756 int ret;
758 if (!strcmp(*paths, "-"))
759 in = stdin;
760 else
761 in = fopen(*paths, "r");
763 if (!in)
764 return error_errno(_("could not open '%s' for reading"),
765 *paths);
767 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
769 out = fopen(mail, "w");
770 if (!out) {
771 if (in != stdin)
772 fclose(in);
773 return error_errno(_("could not open '%s' for writing"),
774 mail);
777 ret = fn(out, in, keep_cr);
779 fclose(out);
780 if (in != stdin)
781 fclose(in);
783 if (ret)
784 return error(_("could not parse patch '%s'"), *paths);
787 state->cur = 1;
788 state->last = i;
789 return 0;
793 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
794 * message suitable for parsing with git-mailinfo.
796 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
798 struct strbuf sb = STRBUF_INIT;
799 int subject_printed = 0;
801 while (!strbuf_getline_lf(&sb, in)) {
802 const char *str;
804 if (str_isspace(sb.buf))
805 continue;
806 else if (skip_prefix(sb.buf, "Author:", &str))
807 fprintf(out, "From:%s\n", str);
808 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
809 fprintf(out, "%s\n", sb.buf);
810 else if (!subject_printed) {
811 fprintf(out, "Subject: %s\n", sb.buf);
812 subject_printed = 1;
813 } else {
814 fprintf(out, "\n%s\n", sb.buf);
815 break;
819 strbuf_reset(&sb);
820 while (strbuf_fread(&sb, 8192, in) > 0) {
821 fwrite(sb.buf, 1, sb.len, out);
822 strbuf_reset(&sb);
825 strbuf_release(&sb);
826 return 0;
830 * This function only supports a single StGit series file in `paths`.
832 * Given an StGit series file, converts the StGit patches in the series into
833 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
834 * the state directory.
836 * Returns 0 on success, -1 on failure.
838 static int split_mail_stgit_series(struct am_state *state, const char **paths,
839 int keep_cr)
841 const char *series_dir;
842 char *series_dir_buf;
843 FILE *fp;
844 struct strvec patches = STRVEC_INIT;
845 struct strbuf sb = STRBUF_INIT;
846 int ret;
848 if (!paths[0] || paths[1])
849 return error(_("Only one StGIT patch series can be applied at once"));
851 series_dir_buf = xstrdup(*paths);
852 series_dir = dirname(series_dir_buf);
854 fp = fopen(*paths, "r");
855 if (!fp)
856 return error_errno(_("could not open '%s' for reading"), *paths);
858 while (!strbuf_getline_lf(&sb, fp)) {
859 if (*sb.buf == '#')
860 continue; /* skip comment lines */
862 strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
865 fclose(fp);
866 strbuf_release(&sb);
867 free(series_dir_buf);
869 ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
871 strvec_clear(&patches);
872 return ret;
876 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
877 * message suitable for parsing with git-mailinfo.
879 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
881 struct strbuf sb = STRBUF_INIT;
882 int rc = 0;
884 while (!strbuf_getline_lf(&sb, in)) {
885 const char *str;
887 if (skip_prefix(sb.buf, "# User ", &str))
888 fprintf(out, "From: %s\n", str);
889 else if (skip_prefix(sb.buf, "# Date ", &str)) {
890 timestamp_t timestamp;
891 long tz, tz2;
892 char *end;
894 errno = 0;
895 timestamp = parse_timestamp(str, &end, 10);
896 if (errno) {
897 rc = error(_("invalid timestamp"));
898 goto exit;
901 if (!skip_prefix(end, " ", &str)) {
902 rc = error(_("invalid Date line"));
903 goto exit;
906 errno = 0;
907 tz = strtol(str, &end, 10);
908 if (errno) {
909 rc = error(_("invalid timezone offset"));
910 goto exit;
913 if (*end) {
914 rc = error(_("invalid Date line"));
915 goto exit;
919 * mercurial's timezone is in seconds west of UTC,
920 * however git's timezone is in hours + minutes east of
921 * UTC. Convert it.
923 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
924 if (tz > 0)
925 tz2 = -tz2;
927 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
928 } else if (starts_with(sb.buf, "# ")) {
929 continue;
930 } else {
931 fprintf(out, "\n%s\n", sb.buf);
932 break;
936 strbuf_reset(&sb);
937 while (strbuf_fread(&sb, 8192, in) > 0) {
938 fwrite(sb.buf, 1, sb.len, out);
939 strbuf_reset(&sb);
941 exit:
942 strbuf_release(&sb);
943 return rc;
947 * Splits a list of files/directories into individual email patches. Each path
948 * in `paths` must be a file/directory that is formatted according to
949 * `patch_format`.
951 * Once split out, the individual email patches will be stored in the state
952 * directory, with each patch's filename being its index, padded to state->prec
953 * digits.
955 * state->cur will be set to the index of the first mail, and state->last will
956 * be set to the index of the last mail.
958 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
959 * to disable this behavior, -1 to use the default configured setting.
961 * Returns 0 on success, -1 on failure.
963 static int split_mail(struct am_state *state, enum patch_format patch_format,
964 const char **paths, int keep_cr)
966 if (keep_cr < 0) {
967 keep_cr = 0;
968 git_config_get_bool("am.keepcr", &keep_cr);
971 switch (patch_format) {
972 case PATCH_FORMAT_MBOX:
973 return split_mail_mbox(state, paths, keep_cr, 0);
974 case PATCH_FORMAT_STGIT:
975 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
976 case PATCH_FORMAT_STGIT_SERIES:
977 return split_mail_stgit_series(state, paths, keep_cr);
978 case PATCH_FORMAT_HG:
979 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
980 case PATCH_FORMAT_MBOXRD:
981 return split_mail_mbox(state, paths, keep_cr, 1);
982 default:
983 BUG("invalid patch_format");
985 return -1;
989 * Setup a new am session for applying patches
991 static void am_setup(struct am_state *state, enum patch_format patch_format,
992 const char **paths, int keep_cr)
994 struct object_id curr_head;
995 const char *str;
996 struct strbuf sb = STRBUF_INIT;
998 if (!patch_format)
999 patch_format = detect_patch_format(paths);
1001 if (!patch_format) {
1002 fprintf_ln(stderr, _("Patch format detection failed."));
1003 exit(128);
1006 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1007 die_errno(_("failed to create directory '%s'"), state->dir);
1008 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1010 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1011 am_destroy(state);
1012 die(_("Failed to split patches."));
1015 if (state->rebasing)
1016 state->threeway = 1;
1018 write_state_bool(state, "threeway", state->threeway);
1019 write_state_bool(state, "quiet", state->quiet);
1020 write_state_bool(state, "sign", state->signoff);
1021 write_state_bool(state, "utf8", state->utf8);
1023 if (state->allow_rerere_autoupdate)
1024 write_state_bool(state, "rerere-autoupdate",
1025 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1027 switch (state->keep) {
1028 case KEEP_FALSE:
1029 str = "f";
1030 break;
1031 case KEEP_TRUE:
1032 str = "t";
1033 break;
1034 case KEEP_NON_PATCH:
1035 str = "b";
1036 break;
1037 default:
1038 BUG("invalid value for state->keep");
1041 write_state_text(state, "keep", str);
1042 write_state_bool(state, "messageid", state->message_id);
1044 switch (state->scissors) {
1045 case SCISSORS_UNSET:
1046 str = "";
1047 break;
1048 case SCISSORS_FALSE:
1049 str = "f";
1050 break;
1051 case SCISSORS_TRUE:
1052 str = "t";
1053 break;
1054 default:
1055 BUG("invalid value for state->scissors");
1057 write_state_text(state, "scissors", str);
1059 switch (state->quoted_cr) {
1060 case quoted_cr_unset:
1061 str = "";
1062 break;
1063 case quoted_cr_nowarn:
1064 str = "nowarn";
1065 break;
1066 case quoted_cr_warn:
1067 str = "warn";
1068 break;
1069 case quoted_cr_strip:
1070 str = "strip";
1071 break;
1072 default:
1073 BUG("invalid value for state->quoted_cr");
1075 write_state_text(state, "quoted-cr", str);
1077 sq_quote_argv(&sb, state->git_apply_opts.v);
1078 write_state_text(state, "apply-opt", sb.buf);
1080 if (state->rebasing)
1081 write_state_text(state, "rebasing", "");
1082 else
1083 write_state_text(state, "applying", "");
1085 if (!repo_get_oid(the_repository, "HEAD", &curr_head)) {
1086 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1087 if (!state->rebasing)
1088 update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1089 UPDATE_REFS_DIE_ON_ERR);
1090 } else {
1091 write_state_text(state, "abort-safety", "");
1092 if (!state->rebasing)
1093 delete_ref(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);
1125 unlink(am_path(state, "original-commit"));
1126 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
1128 if (!repo_get_oid(the_repository, "HEAD", &head))
1129 write_state_text(state, "abort-safety", oid_to_hex(&head));
1130 else
1131 write_state_text(state, "abort-safety", "");
1133 state->cur++;
1134 write_state_count(state, "next", state->cur);
1138 * Returns the filename of the current patch email.
1140 static const char *msgnum(const struct am_state *state)
1142 static struct strbuf sb = STRBUF_INIT;
1144 strbuf_reset(&sb);
1145 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1147 return sb.buf;
1151 * Dies with a user-friendly message on how to proceed after resolving the
1152 * problem. This message can be overridden with state->resolvemsg.
1154 static void NORETURN die_user_resolve(const struct am_state *state)
1156 if (state->resolvemsg) {
1157 printf_ln("%s", state->resolvemsg);
1158 } else {
1159 const char *cmdline = state->interactive ? "git am -i" : "git am";
1161 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1162 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1164 if (advice_enabled(ADVICE_AM_WORK_DIR) &&
1165 is_empty_or_missing_file(am_path(state, "patch")) &&
1166 !repo_index_has_changes(the_repository, NULL, NULL))
1167 printf_ln(_("To record the empty patch as an empty commit, run \"%s --allow-empty\"."), cmdline);
1169 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1172 exit(128);
1176 * Appends signoff to the "msg" field of the am_state.
1178 static void am_append_signoff(struct am_state *state)
1180 struct strbuf sb = STRBUF_INIT;
1182 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1183 append_signoff(&sb, 0, 0);
1184 state->msg = strbuf_detach(&sb, &state->msg_len);
1188 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1189 * state->msg will be set to the patch message. state->author_name,
1190 * state->author_email and state->author_date will be set to the patch author's
1191 * name, email and date respectively. The patch body will be written to the
1192 * state directory's "patch" file.
1194 * Returns 1 if the patch should be skipped, 0 otherwise.
1196 static int parse_mail(struct am_state *state, const char *mail)
1198 FILE *fp;
1199 struct strbuf sb = STRBUF_INIT;
1200 struct strbuf msg = STRBUF_INIT;
1201 struct strbuf author_name = STRBUF_INIT;
1202 struct strbuf author_date = STRBUF_INIT;
1203 struct strbuf author_email = STRBUF_INIT;
1204 int ret = 0;
1205 struct mailinfo mi;
1207 setup_mailinfo(&mi);
1209 if (state->utf8)
1210 mi.metainfo_charset = get_commit_output_encoding();
1211 else
1212 mi.metainfo_charset = NULL;
1214 switch (state->keep) {
1215 case KEEP_FALSE:
1216 break;
1217 case KEEP_TRUE:
1218 mi.keep_subject = 1;
1219 break;
1220 case KEEP_NON_PATCH:
1221 mi.keep_non_patch_brackets_in_subject = 1;
1222 break;
1223 default:
1224 BUG("invalid value for state->keep");
1227 if (state->message_id)
1228 mi.add_message_id = 1;
1230 switch (state->scissors) {
1231 case SCISSORS_UNSET:
1232 break;
1233 case SCISSORS_FALSE:
1234 mi.use_scissors = 0;
1235 break;
1236 case SCISSORS_TRUE:
1237 mi.use_scissors = 1;
1238 break;
1239 default:
1240 BUG("invalid value for state->scissors");
1243 switch (state->quoted_cr) {
1244 case quoted_cr_unset:
1245 break;
1246 case quoted_cr_nowarn:
1247 case quoted_cr_warn:
1248 case quoted_cr_strip:
1249 mi.quoted_cr = state->quoted_cr;
1250 break;
1251 default:
1252 BUG("invalid value for state->quoted_cr");
1255 mi.input = xfopen(mail, "r");
1256 mi.output = xfopen(am_path(state, "info"), "w");
1257 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1258 die("could not parse patch");
1260 fclose(mi.input);
1261 fclose(mi.output);
1263 if (mi.format_flowed)
1264 warning(_("Patch sent with format=flowed; "
1265 "space at the end of lines might be lost."));
1267 /* Extract message and author information */
1268 fp = xfopen(am_path(state, "info"), "r");
1269 while (!strbuf_getline_lf(&sb, fp)) {
1270 const char *x;
1272 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1273 if (msg.len)
1274 strbuf_addch(&msg, '\n');
1275 strbuf_addstr(&msg, x);
1276 } else if (skip_prefix(sb.buf, "Author: ", &x))
1277 strbuf_addstr(&author_name, x);
1278 else if (skip_prefix(sb.buf, "Email: ", &x))
1279 strbuf_addstr(&author_email, x);
1280 else if (skip_prefix(sb.buf, "Date: ", &x))
1281 strbuf_addstr(&author_date, x);
1283 fclose(fp);
1285 /* Skip pine's internal folder data */
1286 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1287 ret = 1;
1288 goto finish;
1291 strbuf_addstr(&msg, "\n\n");
1292 strbuf_addbuf(&msg, &mi.log_message);
1293 strbuf_stripspace(&msg, '\0');
1295 assert(!state->author_name);
1296 state->author_name = strbuf_detach(&author_name, NULL);
1298 assert(!state->author_email);
1299 state->author_email = strbuf_detach(&author_email, NULL);
1301 assert(!state->author_date);
1302 state->author_date = strbuf_detach(&author_date, NULL);
1304 assert(!state->msg);
1305 state->msg = strbuf_detach(&msg, &state->msg_len);
1307 finish:
1308 strbuf_release(&msg);
1309 strbuf_release(&author_date);
1310 strbuf_release(&author_email);
1311 strbuf_release(&author_name);
1312 strbuf_release(&sb);
1313 clear_mailinfo(&mi);
1314 return ret;
1318 * Sets commit_id to the commit hash where the mail was generated from.
1319 * Returns 0 on success, -1 on failure.
1321 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1323 struct strbuf sb = STRBUF_INIT;
1324 FILE *fp = xfopen(mail, "r");
1325 const char *x;
1326 int ret = 0;
1328 if (strbuf_getline_lf(&sb, fp) ||
1329 !skip_prefix(sb.buf, "From ", &x) ||
1330 get_oid_hex(x, commit_id) < 0)
1331 ret = -1;
1333 strbuf_release(&sb);
1334 fclose(fp);
1335 return ret;
1339 * Sets state->msg, state->author_name, state->author_email, state->author_date
1340 * to the commit's respective info.
1342 static void get_commit_info(struct am_state *state, struct commit *commit)
1344 const char *buffer, *ident_line, *msg;
1345 size_t ident_len;
1346 struct ident_split id;
1348 buffer = repo_logmsg_reencode(the_repository, commit, NULL,
1349 get_commit_output_encoding());
1351 ident_line = find_commit_header(buffer, "author", &ident_len);
1352 if (!ident_line)
1353 die(_("missing author line in commit %s"),
1354 oid_to_hex(&commit->object.oid));
1355 if (split_ident_line(&id, ident_line, ident_len) < 0)
1356 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1358 assert(!state->author_name);
1359 if (id.name_begin)
1360 state->author_name =
1361 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1362 else
1363 state->author_name = xstrdup("");
1365 assert(!state->author_email);
1366 if (id.mail_begin)
1367 state->author_email =
1368 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1369 else
1370 state->author_email = xstrdup("");
1372 assert(!state->author_date);
1373 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1375 assert(!state->msg);
1376 msg = strstr(buffer, "\n\n");
1377 if (!msg)
1378 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1379 state->msg = xstrdup(msg + 2);
1380 state->msg_len = strlen(state->msg);
1381 repo_unuse_commit_buffer(the_repository, commit, buffer);
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 repo_init_revisions(the_repository, &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 rev_info.diffopt.flags.binary = 1;
1401 rev_info.diffopt.flags.full_index = 1;
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);
1408 release_revisions(&rev_info);
1412 * Writes the diff of the index against HEAD as a patch to the state
1413 * directory's "patch" file.
1415 static void write_index_patch(const struct am_state *state)
1417 struct tree *tree;
1418 struct object_id head;
1419 struct rev_info rev_info;
1420 FILE *fp;
1422 if (!repo_get_oid(the_repository, "HEAD", &head)) {
1423 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1424 tree = repo_get_commit_tree(the_repository, commit);
1425 } else
1426 tree = lookup_tree(the_repository,
1427 the_repository->hash_algo->empty_tree);
1429 fp = xfopen(am_path(state, "patch"), "w");
1430 repo_init_revisions(the_repository, &rev_info, NULL);
1431 rev_info.diff = 1;
1432 rev_info.disable_stdin = 1;
1433 rev_info.no_commit_id = 1;
1434 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1435 rev_info.diffopt.use_color = 0;
1436 rev_info.diffopt.file = fp;
1437 rev_info.diffopt.close_file = 1;
1438 add_pending_object(&rev_info, &tree->object, "");
1439 diff_setup_done(&rev_info.diffopt);
1440 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1441 release_revisions(&rev_info);
1445 * Like parse_mail(), but parses the mail by looking up its commit ID
1446 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1447 * of patches.
1449 * state->orig_commit will be set to the original commit ID.
1451 * Will always return 0 as the patch should never be skipped.
1453 static int parse_mail_rebase(struct am_state *state, const char *mail)
1455 struct commit *commit;
1456 struct object_id commit_oid;
1458 if (get_mail_commit_oid(&commit_oid, mail) < 0)
1459 die(_("could not parse %s"), mail);
1461 commit = lookup_commit_or_die(&commit_oid, mail);
1463 get_commit_info(state, commit);
1465 write_commit_patch(state, commit);
1467 oidcpy(&state->orig_commit, &commit_oid);
1468 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1469 update_ref("am", "REBASE_HEAD", &commit_oid,
1470 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1472 return 0;
1476 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1477 * `index_file` is not NULL, the patch will be applied to that index.
1479 static int run_apply(const struct am_state *state, const char *index_file)
1481 struct strvec apply_paths = STRVEC_INIT;
1482 struct strvec apply_opts = STRVEC_INIT;
1483 struct apply_state apply_state;
1484 int res, opts_left;
1485 int force_apply = 0;
1486 int options = 0;
1487 const char **apply_argv;
1489 if (init_apply_state(&apply_state, the_repository, NULL))
1490 BUG("init_apply_state() failed");
1492 strvec_push(&apply_opts, "apply");
1493 strvec_pushv(&apply_opts, state->git_apply_opts.v);
1496 * Build a copy that apply_parse_options() can rearrange.
1497 * apply_opts.v keeps referencing the allocated strings for
1498 * strvec_clear() to release.
1500 DUP_ARRAY(apply_argv, apply_opts.v, apply_opts.nr);
1502 opts_left = apply_parse_options(apply_opts.nr, apply_argv,
1503 &apply_state, &force_apply, &options,
1504 NULL);
1506 if (opts_left != 0)
1507 die("unknown option passed through to git apply");
1509 if (index_file) {
1510 apply_state.index_file = index_file;
1511 apply_state.cached = 1;
1512 } else
1513 apply_state.check_index = 1;
1516 * If we are allowed to fall back on 3-way merge, don't give false
1517 * errors during the initial attempt.
1519 if (state->threeway && !index_file)
1520 apply_state.apply_verbosity = verbosity_silent;
1522 if (check_apply_state(&apply_state, force_apply))
1523 BUG("check_apply_state() failed");
1525 strvec_push(&apply_paths, am_path(state, "patch"));
1527 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
1529 strvec_clear(&apply_paths);
1530 strvec_clear(&apply_opts);
1531 clear_apply_state(&apply_state);
1532 free(apply_argv);
1534 if (res)
1535 return res;
1537 if (index_file) {
1538 /* Reload index as apply_all_patches() will have modified it. */
1539 discard_index(&the_index);
1540 read_index_from(&the_index, index_file, get_git_dir());
1543 return 0;
1547 * Builds an index that contains just the blobs needed for a 3way merge.
1549 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1551 struct child_process cp = CHILD_PROCESS_INIT;
1553 cp.git_cmd = 1;
1554 strvec_push(&cp.args, "apply");
1555 strvec_pushv(&cp.args, state->git_apply_opts.v);
1556 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1557 strvec_push(&cp.args, am_path(state, "patch"));
1559 if (run_command(&cp))
1560 return -1;
1562 return 0;
1566 * Attempt a threeway merge, using index_path as the temporary index.
1568 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1570 struct object_id orig_tree, their_tree, our_tree;
1571 const struct object_id *bases[1] = { &orig_tree };
1572 struct merge_options o;
1573 struct commit *result;
1574 char *their_tree_name;
1576 if (repo_get_oid(the_repository, "HEAD", &our_tree) < 0)
1577 oidcpy(&our_tree, the_hash_algo->empty_tree);
1579 if (build_fake_ancestor(state, index_path))
1580 return error("could not build fake ancestor");
1582 discard_index(&the_index);
1583 read_index_from(&the_index, index_path, get_git_dir());
1585 if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
1586 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1588 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1590 if (!state->quiet) {
1592 * List paths that needed 3-way fallback, so that the user can
1593 * review them with extra care to spot mismerges.
1595 struct rev_info rev_info;
1597 repo_init_revisions(the_repository, &rev_info, NULL);
1598 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1599 rev_info.diffopt.filter |= diff_filter_bit('A');
1600 rev_info.diffopt.filter |= diff_filter_bit('M');
1601 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1602 diff_setup_done(&rev_info.diffopt);
1603 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1604 release_revisions(&rev_info);
1607 if (run_apply(state, index_path))
1608 return error(_("Did you hand edit your patch?\n"
1609 "It does not apply to blobs recorded in its index."));
1611 if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
1612 return error("could not write tree");
1614 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1616 discard_index(&the_index);
1617 repo_read_index(the_repository);
1620 * This is not so wrong. Depending on which base we picked, orig_tree
1621 * may be wildly different from ours, but their_tree has the same set of
1622 * wildly different changes in parts the patch did not touch, so
1623 * recursive ends up canceling them, saying that we reverted all those
1624 * changes.
1627 init_merge_options(&o, the_repository);
1629 o.branch1 = "HEAD";
1630 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1631 o.branch2 = their_tree_name;
1632 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
1634 if (state->quiet)
1635 o.verbosity = 0;
1637 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1638 repo_rerere(the_repository, state->allow_rerere_autoupdate);
1639 free(their_tree_name);
1640 return error(_("Failed to merge in the changes."));
1643 free(their_tree_name);
1644 return 0;
1648 * Commits the current index with state->msg as the commit message and
1649 * state->author_name, state->author_email and state->author_date as the author
1650 * information.
1652 static void do_commit(const struct am_state *state)
1654 struct object_id tree, parent, commit;
1655 const struct object_id *old_oid;
1656 struct commit_list *parents = NULL;
1657 const char *reflog_msg, *author, *committer = NULL;
1658 struct strbuf sb = STRBUF_INIT;
1660 if (!state->no_verify && run_hooks("pre-applypatch"))
1661 exit(1);
1663 if (write_index_as_tree(&tree, &the_index, get_index_file(), 0, NULL))
1664 die(_("git write-tree failed to write a tree"));
1666 if (!repo_get_oid_commit(the_repository, "HEAD", &parent)) {
1667 old_oid = &parent;
1668 commit_list_insert(lookup_commit(the_repository, &parent),
1669 &parents);
1670 } else {
1671 old_oid = NULL;
1672 say(state, stderr, _("applying to an empty history"));
1675 author = fmt_ident(state->author_name, state->author_email,
1676 WANT_AUTHOR_IDENT,
1677 state->ignore_date ? NULL : state->author_date,
1678 IDENT_STRICT);
1680 if (state->committer_date_is_author_date)
1681 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1682 getenv("GIT_COMMITTER_EMAIL"),
1683 WANT_COMMITTER_IDENT,
1684 state->ignore_date ? NULL
1685 : state->author_date,
1686 IDENT_STRICT);
1688 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1689 &commit, author, committer, state->sign_commit,
1690 NULL))
1691 die(_("failed to write commit object"));
1693 reflog_msg = getenv("GIT_REFLOG_ACTION");
1694 if (!reflog_msg)
1695 reflog_msg = "am";
1697 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1698 state->msg);
1700 update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1701 UPDATE_REFS_DIE_ON_ERR);
1703 if (state->rebasing) {
1704 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1706 assert(!is_null_oid(&state->orig_commit));
1707 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1708 fprintf(fp, "%s\n", oid_to_hex(&commit));
1709 fclose(fp);
1712 run_hooks("post-applypatch");
1714 strbuf_release(&sb);
1718 * Validates the am_state for resuming -- the "msg" and authorship fields must
1719 * be filled up.
1721 static void validate_resume_state(const struct am_state *state)
1723 if (!state->msg)
1724 die(_("cannot resume: %s does not exist."),
1725 am_path(state, "final-commit"));
1727 if (!state->author_name || !state->author_email || !state->author_date)
1728 die(_("cannot resume: %s does not exist."),
1729 am_path(state, "author-script"));
1733 * Interactively prompt the user on whether the current patch should be
1734 * applied.
1736 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1737 * skip it.
1739 static int do_interactive(struct am_state *state)
1741 assert(state->msg);
1743 for (;;) {
1744 char reply[64];
1746 puts(_("Commit Body is:"));
1747 puts("--------------------------");
1748 printf("%s", state->msg);
1749 puts("--------------------------");
1752 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1753 * in your translation. The program will only accept English
1754 * input at this point.
1756 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1757 if (!fgets(reply, sizeof(reply), stdin))
1758 die("unable to read from stdin; aborting");
1760 if (*reply == 'y' || *reply == 'Y') {
1761 return 0;
1762 } else if (*reply == 'a' || *reply == 'A') {
1763 state->interactive = 0;
1764 return 0;
1765 } else if (*reply == 'n' || *reply == 'N') {
1766 return 1;
1767 } else if (*reply == 'e' || *reply == 'E') {
1768 struct strbuf msg = STRBUF_INIT;
1770 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1771 free(state->msg);
1772 state->msg = strbuf_detach(&msg, &state->msg_len);
1774 strbuf_release(&msg);
1775 } else if (*reply == 'v' || *reply == 'V') {
1776 const char *pager = git_pager(1);
1777 struct child_process cp = CHILD_PROCESS_INIT;
1779 if (!pager)
1780 pager = "cat";
1781 prepare_pager_args(&cp, pager);
1782 strvec_push(&cp.args, am_path(state, "patch"));
1783 run_command(&cp);
1789 * Applies all queued mail.
1791 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1792 * well as the state directory's "patch" file is used as-is for applying the
1793 * patch and committing it.
1795 static void am_run(struct am_state *state, int resume)
1797 struct strbuf sb = STRBUF_INIT;
1799 unlink(am_path(state, "dirtyindex"));
1801 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1802 NULL, NULL, NULL) < 0)
1803 die(_("unable to write index file"));
1805 if (repo_index_has_changes(the_repository, NULL, &sb)) {
1806 write_state_bool(state, "dirtyindex", 1);
1807 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1810 strbuf_release(&sb);
1812 while (state->cur <= state->last) {
1813 const char *mail = am_path(state, msgnum(state));
1814 int apply_status;
1815 int to_keep;
1817 reset_ident_date();
1819 if (!file_exists(mail))
1820 goto next;
1822 if (resume) {
1823 validate_resume_state(state);
1824 } else {
1825 int skip;
1827 if (state->rebasing)
1828 skip = parse_mail_rebase(state, mail);
1829 else
1830 skip = parse_mail(state, mail);
1832 if (skip)
1833 goto next; /* mail should be skipped */
1835 if (state->signoff)
1836 am_append_signoff(state);
1838 write_author_script(state);
1839 write_commit_msg(state);
1842 if (state->interactive && do_interactive(state))
1843 goto next;
1845 to_keep = 0;
1846 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1847 switch (state->empty_type) {
1848 case DROP_EMPTY_COMMIT:
1849 say(state, stdout, _("Skipping: %.*s"), linelen(state->msg), state->msg);
1850 goto next;
1851 break;
1852 case KEEP_EMPTY_COMMIT:
1853 to_keep = 1;
1854 say(state, stdout, _("Creating an empty commit: %.*s"),
1855 linelen(state->msg), state->msg);
1856 break;
1857 case STOP_ON_EMPTY_COMMIT:
1858 printf_ln(_("Patch is empty."));
1859 die_user_resolve(state);
1860 break;
1864 if (run_applypatch_msg_hook(state))
1865 exit(1);
1866 if (to_keep)
1867 goto commit;
1869 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1871 apply_status = run_apply(state, NULL);
1873 if (apply_status && state->threeway) {
1874 struct strbuf sb = STRBUF_INIT;
1876 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1877 apply_status = fall_back_threeway(state, sb.buf);
1878 strbuf_release(&sb);
1881 * Applying the patch to an earlier tree and merging
1882 * the result may have produced the same tree as ours.
1884 if (!apply_status &&
1885 !repo_index_has_changes(the_repository, NULL, NULL)) {
1886 say(state, stdout, _("No changes -- Patch already applied."));
1887 goto next;
1891 if (apply_status) {
1892 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1893 linelen(state->msg), state->msg);
1895 if (advice_enabled(ADVICE_AM_WORK_DIR))
1896 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1898 die_user_resolve(state);
1901 commit:
1902 do_commit(state);
1904 next:
1905 am_next(state);
1907 if (resume)
1908 am_load(state);
1909 resume = 0;
1912 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1913 assert(state->rebasing);
1914 copy_notes_for_rebase(state);
1915 run_post_rewrite_hook(state);
1919 * In rebasing mode, it's up to the caller to take care of
1920 * housekeeping.
1922 if (!state->rebasing) {
1923 am_destroy(state);
1924 run_auto_maintenance(state->quiet);
1929 * Resume the current am session after patch application failure. The user did
1930 * all the hard work, and we do not have to do any patch application. Just
1931 * trust and commit what the user has in the index and working tree. If `allow_empty`
1932 * is true, commit as an empty commit when index has not changed and lacking a patch.
1934 static void am_resolve(struct am_state *state, int allow_empty)
1936 validate_resume_state(state);
1938 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1940 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
1941 if (allow_empty && is_empty_or_missing_file(am_path(state, "patch"))) {
1942 printf_ln(_("No changes - recorded it as an empty commit."));
1943 } else {
1944 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1945 "If there is nothing left to stage, chances are that something else\n"
1946 "already introduced the same changes; you might want to skip this patch."));
1947 die_user_resolve(state);
1951 if (unmerged_index(&the_index)) {
1952 printf_ln(_("You still have unmerged paths in your index.\n"
1953 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1954 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1955 die_user_resolve(state);
1958 if (state->interactive) {
1959 write_index_patch(state);
1960 if (do_interactive(state))
1961 goto next;
1964 repo_rerere(the_repository, 0);
1966 do_commit(state);
1968 next:
1969 am_next(state);
1970 am_load(state);
1971 am_run(state, 0);
1975 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1976 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1977 * failure.
1979 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1981 struct lock_file lock_file = LOCK_INIT;
1982 struct unpack_trees_options opts;
1983 struct tree_desc t[2];
1985 if (parse_tree(head) || parse_tree(remote))
1986 return -1;
1988 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
1990 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
1992 memset(&opts, 0, sizeof(opts));
1993 opts.head_idx = 1;
1994 opts.src_index = &the_index;
1995 opts.dst_index = &the_index;
1996 opts.update = 1;
1997 opts.merge = 1;
1998 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
1999 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
2000 opts.fn = twoway_merge;
2001 init_tree_desc(&t[0], head->buffer, head->size);
2002 init_tree_desc(&t[1], remote->buffer, remote->size);
2004 if (unpack_trees(2, t, &opts)) {
2005 rollback_lock_file(&lock_file);
2006 return -1;
2009 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
2010 die(_("unable to write new index file"));
2012 return 0;
2016 * Merges a tree into the index. The index's stat info will take precedence
2017 * over the merged tree's. Returns 0 on success, -1 on failure.
2019 static int merge_tree(struct tree *tree)
2021 struct lock_file lock_file = LOCK_INIT;
2022 struct unpack_trees_options opts;
2023 struct tree_desc t[1];
2025 if (parse_tree(tree))
2026 return -1;
2028 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
2030 memset(&opts, 0, sizeof(opts));
2031 opts.head_idx = 1;
2032 opts.src_index = &the_index;
2033 opts.dst_index = &the_index;
2034 opts.merge = 1;
2035 opts.fn = oneway_merge;
2036 init_tree_desc(&t[0], tree->buffer, tree->size);
2038 if (unpack_trees(1, t, &opts)) {
2039 rollback_lock_file(&lock_file);
2040 return -1;
2043 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
2044 die(_("unable to write new index file"));
2046 return 0;
2050 * Clean the index without touching entries that are not modified between
2051 * `head` and `remote`.
2053 static int clean_index(const struct object_id *head, const struct object_id *remote)
2055 struct tree *head_tree, *remote_tree, *index_tree;
2056 struct object_id index;
2058 head_tree = parse_tree_indirect(head);
2059 if (!head_tree)
2060 return error(_("Could not parse object '%s'."), oid_to_hex(head));
2062 remote_tree = parse_tree_indirect(remote);
2063 if (!remote_tree)
2064 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
2066 repo_read_index_unmerged(the_repository);
2068 if (fast_forward_to(head_tree, head_tree, 1))
2069 return -1;
2071 if (write_index_as_tree(&index, &the_index, get_index_file(), 0, NULL))
2072 return -1;
2074 index_tree = parse_tree_indirect(&index);
2075 if (!index_tree)
2076 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
2078 if (fast_forward_to(index_tree, remote_tree, 0))
2079 return -1;
2081 if (merge_tree(remote_tree))
2082 return -1;
2084 remove_branch_state(the_repository, 0);
2086 return 0;
2090 * Resets rerere's merge resolution metadata.
2092 static void am_rerere_clear(void)
2094 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2095 rerere_clear(the_repository, &merge_rr);
2096 string_list_clear(&merge_rr, 1);
2100 * Resume the current am session by skipping the current patch.
2102 static void am_skip(struct am_state *state)
2104 struct object_id head;
2106 am_rerere_clear();
2108 if (repo_get_oid(the_repository, "HEAD", &head))
2109 oidcpy(&head, the_hash_algo->empty_tree);
2111 if (clean_index(&head, &head))
2112 die(_("failed to clean index"));
2114 if (state->rebasing) {
2115 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2117 assert(!is_null_oid(&state->orig_commit));
2118 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2119 fprintf(fp, "%s\n", oid_to_hex(&head));
2120 fclose(fp);
2123 am_next(state);
2124 am_load(state);
2125 am_run(state, 0);
2129 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2131 * It is not safe to reset HEAD when:
2132 * 1. git-am previously failed because the index was dirty.
2133 * 2. HEAD has moved since git-am previously failed.
2135 static int safe_to_abort(const struct am_state *state)
2137 struct strbuf sb = STRBUF_INIT;
2138 struct object_id abort_safety, head;
2140 if (file_exists(am_path(state, "dirtyindex")))
2141 return 0;
2143 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2144 if (get_oid_hex(sb.buf, &abort_safety))
2145 die(_("could not parse %s"), am_path(state, "abort-safety"));
2146 } else
2147 oidclr(&abort_safety);
2148 strbuf_release(&sb);
2150 if (repo_get_oid(the_repository, "HEAD", &head))
2151 oidclr(&head);
2153 if (oideq(&head, &abort_safety))
2154 return 1;
2156 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2157 "Not rewinding to ORIG_HEAD"));
2159 return 0;
2163 * Aborts the current am session if it is safe to do so.
2165 static void am_abort(struct am_state *state)
2167 struct object_id curr_head, orig_head;
2168 int has_curr_head, has_orig_head;
2169 char *curr_branch;
2171 if (!safe_to_abort(state)) {
2172 am_destroy(state);
2173 return;
2176 am_rerere_clear();
2178 curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2179 has_curr_head = curr_branch && !is_null_oid(&curr_head);
2180 if (!has_curr_head)
2181 oidcpy(&curr_head, the_hash_algo->empty_tree);
2183 has_orig_head = !repo_get_oid(the_repository, "ORIG_HEAD", &orig_head);
2184 if (!has_orig_head)
2185 oidcpy(&orig_head, the_hash_algo->empty_tree);
2187 if (clean_index(&curr_head, &orig_head))
2188 die(_("failed to clean index"));
2190 if (has_orig_head)
2191 update_ref("am --abort", "HEAD", &orig_head,
2192 has_curr_head ? &curr_head : NULL, 0,
2193 UPDATE_REFS_DIE_ON_ERR);
2194 else if (curr_branch)
2195 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
2197 free(curr_branch);
2198 am_destroy(state);
2201 static int show_patch(struct am_state *state, enum resume_type resume_mode)
2203 struct strbuf sb = STRBUF_INIT;
2204 const char *patch_path;
2205 int len;
2207 if (!is_null_oid(&state->orig_commit)) {
2208 struct child_process cmd = CHILD_PROCESS_INIT;
2210 strvec_pushl(&cmd.args, "show", oid_to_hex(&state->orig_commit),
2211 "--", NULL);
2212 cmd.git_cmd = 1;
2213 return run_command(&cmd);
2216 switch (resume_mode) {
2217 case RESUME_SHOW_PATCH_RAW:
2218 patch_path = am_path(state, msgnum(state));
2219 break;
2220 case RESUME_SHOW_PATCH_DIFF:
2221 patch_path = am_path(state, "patch");
2222 break;
2223 default:
2224 BUG("invalid mode for --show-current-patch");
2227 len = strbuf_read_file(&sb, patch_path, 0);
2228 if (len < 0)
2229 die_errno(_("failed to read '%s'"), patch_path);
2231 setup_pager();
2232 write_in_full(1, sb.buf, sb.len);
2233 strbuf_release(&sb);
2234 return 0;
2238 * parse_options() callback that validates and sets opt->value to the
2239 * PATCH_FORMAT_* enum value corresponding to `arg`.
2241 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2243 int *opt_value = opt->value;
2245 if (unset)
2246 *opt_value = PATCH_FORMAT_UNKNOWN;
2247 else if (!strcmp(arg, "mbox"))
2248 *opt_value = PATCH_FORMAT_MBOX;
2249 else if (!strcmp(arg, "stgit"))
2250 *opt_value = PATCH_FORMAT_STGIT;
2251 else if (!strcmp(arg, "stgit-series"))
2252 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2253 else if (!strcmp(arg, "hg"))
2254 *opt_value = PATCH_FORMAT_HG;
2255 else if (!strcmp(arg, "mboxrd"))
2256 *opt_value = PATCH_FORMAT_MBOXRD;
2258 * Please update $__git_patchformat in git-completion.bash
2259 * when you add new options
2261 else
2262 return error(_("invalid value for '%s': '%s'"),
2263 "--patch-format", arg);
2264 return 0;
2267 static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2269 int *opt_value = opt->value;
2271 BUG_ON_OPT_NEG(unset);
2273 if (!arg)
2274 *opt_value = opt->defval;
2275 else if (!strcmp(arg, "raw"))
2276 *opt_value = RESUME_SHOW_PATCH_RAW;
2277 else if (!strcmp(arg, "diff"))
2278 *opt_value = RESUME_SHOW_PATCH_DIFF;
2280 * Please update $__git_showcurrentpatch in git-completion.bash
2281 * when you add new options
2283 else
2284 return error(_("invalid value for '%s': '%s'"),
2285 "--show-current-patch", arg);
2286 return 0;
2289 int cmd_am(int argc, const char **argv, const char *prefix)
2291 struct am_state state;
2292 int binary = -1;
2293 int keep_cr = -1;
2294 int patch_format = PATCH_FORMAT_UNKNOWN;
2295 enum resume_type resume_mode = RESUME_FALSE;
2296 int in_progress;
2297 int ret = 0;
2299 const char * const usage[] = {
2300 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2301 N_("git am [<options>] (--continue | --skip | --abort)"),
2302 NULL
2305 struct option options[] = {
2306 OPT_BOOL('i', "interactive", &state.interactive,
2307 N_("run interactively")),
2308 OPT_BOOL('n', "no-verify", &state.no_verify,
2309 N_("bypass pre-applypatch and applypatch-msg hooks")),
2310 OPT_HIDDEN_BOOL('b', "binary", &binary,
2311 N_("historical option -- no-op")),
2312 OPT_BOOL('3', "3way", &state.threeway,
2313 N_("allow fall back on 3way merging if needed")),
2314 OPT__QUIET(&state.quiet, N_("be quiet")),
2315 OPT_SET_INT('s', "signoff", &state.signoff,
2316 N_("add a Signed-off-by trailer to the commit message"),
2317 SIGNOFF_EXPLICIT),
2318 OPT_BOOL('u', "utf8", &state.utf8,
2319 N_("recode into utf8 (default)")),
2320 OPT_SET_INT('k', "keep", &state.keep,
2321 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2322 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2323 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2324 OPT_BOOL('m', "message-id", &state.message_id,
2325 N_("pass -m flag to git-mailinfo")),
2326 OPT_SET_INT(0, "keep-cr", &keep_cr,
2327 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2329 OPT_BOOL('c', "scissors", &state.scissors,
2330 N_("strip everything before a scissors line")),
2331 OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2332 N_("pass it through git-mailinfo"),
2333 PARSE_OPT_NONEG, am_option_parse_quoted_cr),
2334 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2335 N_("pass it through git-apply"),
2337 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2338 N_("pass it through git-apply"),
2339 PARSE_OPT_NOARG),
2340 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2341 N_("pass it through git-apply"),
2342 PARSE_OPT_NOARG),
2343 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2344 N_("pass it through git-apply"),
2346 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2347 N_("pass it through git-apply"),
2349 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2350 N_("pass it through git-apply"),
2352 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2353 N_("pass it through git-apply"),
2355 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2356 N_("pass it through git-apply"),
2358 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2359 N_("format the patch(es) are in"),
2360 parse_opt_patchformat),
2361 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2362 N_("pass it through git-apply"),
2363 PARSE_OPT_NOARG),
2364 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2365 N_("override error message when patch failure occurs")),
2366 OPT_CMDMODE(0, "continue", &resume_mode,
2367 N_("continue applying patches after resolving a conflict"),
2368 RESUME_RESOLVED),
2369 OPT_CMDMODE('r', "resolved", &resume_mode,
2370 N_("synonyms for --continue"),
2371 RESUME_RESOLVED),
2372 OPT_CMDMODE(0, "skip", &resume_mode,
2373 N_("skip the current patch"),
2374 RESUME_SKIP),
2375 OPT_CMDMODE(0, "abort", &resume_mode,
2376 N_("restore the original branch and abort the patching operation"),
2377 RESUME_ABORT),
2378 OPT_CMDMODE(0, "quit", &resume_mode,
2379 N_("abort the patching operation but keep HEAD where it is"),
2380 RESUME_QUIT),
2381 { OPTION_CALLBACK, 0, "show-current-patch", &resume_mode,
2382 "(diff|raw)",
2383 N_("show the patch being applied"),
2384 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2385 parse_opt_show_current_patch, RESUME_SHOW_PATCH_RAW },
2386 OPT_CMDMODE(0, "allow-empty", &resume_mode,
2387 N_("record the empty patch as an empty commit"),
2388 RESUME_ALLOW_EMPTY),
2389 OPT_BOOL(0, "committer-date-is-author-date",
2390 &state.committer_date_is_author_date,
2391 N_("lie about committer date")),
2392 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2393 N_("use current timestamp for author date")),
2394 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2395 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2396 N_("GPG-sign commits"),
2397 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2398 OPT_CALLBACK_F(0, "empty", &state.empty_type, "(stop|drop|keep)",
2399 N_("how to handle empty patches"),
2400 PARSE_OPT_NONEG, am_option_parse_empty),
2401 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2402 N_("(internal use for git-rebase)")),
2403 OPT_END()
2406 if (argc == 2 && !strcmp(argv[1], "-h"))
2407 usage_with_options(usage, options);
2409 git_config(git_default_config, NULL);
2411 am_state_init(&state);
2413 in_progress = am_in_progress(&state);
2414 if (in_progress)
2415 am_load(&state);
2417 argc = parse_options(argc, argv, prefix, options, usage, 0);
2419 if (binary >= 0)
2420 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2421 "it will be removed. Please do not use it anymore."));
2423 /* Ensure a valid committer ident can be constructed */
2424 git_committer_info(IDENT_STRICT);
2426 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
2427 die(_("failed to read the index"));
2429 if (in_progress) {
2431 * Catch user error to feed us patches when there is a session
2432 * in progress:
2434 * 1. mbox path(s) are provided on the command-line.
2435 * 2. stdin is not a tty: the user is trying to feed us a patch
2436 * from standard input. This is somewhat unreliable -- stdin
2437 * could be /dev/null for example and the caller did not
2438 * intend to feed us a patch but wanted to continue
2439 * unattended.
2441 if (argc || (resume_mode == RESUME_FALSE && !isatty(0)))
2442 die(_("previous rebase directory %s still exists but mbox given."),
2443 state.dir);
2445 if (resume_mode == RESUME_FALSE)
2446 resume_mode = RESUME_APPLY;
2448 if (state.signoff == SIGNOFF_EXPLICIT)
2449 am_append_signoff(&state);
2450 } else {
2451 struct strvec paths = STRVEC_INIT;
2452 int i;
2455 * Handle stray state directory in the independent-run case. In
2456 * the --rebasing case, it is up to the caller to take care of
2457 * stray directories.
2459 if (file_exists(state.dir) && !state.rebasing) {
2460 if (resume_mode == RESUME_ABORT || resume_mode == RESUME_QUIT) {
2461 am_destroy(&state);
2462 am_state_release(&state);
2463 return 0;
2466 die(_("Stray %s directory found.\n"
2467 "Use \"git am --abort\" to remove it."),
2468 state.dir);
2471 if (resume_mode)
2472 die(_("Resolve operation not in progress, we are not resuming."));
2474 for (i = 0; i < argc; i++) {
2475 if (is_absolute_path(argv[i]) || !prefix)
2476 strvec_push(&paths, argv[i]);
2477 else
2478 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2481 if (state.interactive && !paths.nr)
2482 die(_("interactive mode requires patches on the command line"));
2484 am_setup(&state, patch_format, paths.v, keep_cr);
2486 strvec_clear(&paths);
2489 switch (resume_mode) {
2490 case RESUME_FALSE:
2491 am_run(&state, 0);
2492 break;
2493 case RESUME_APPLY:
2494 am_run(&state, 1);
2495 break;
2496 case RESUME_RESOLVED:
2497 case RESUME_ALLOW_EMPTY:
2498 am_resolve(&state, resume_mode == RESUME_ALLOW_EMPTY ? 1 : 0);
2499 break;
2500 case RESUME_SKIP:
2501 am_skip(&state);
2502 break;
2503 case RESUME_ABORT:
2504 am_abort(&state);
2505 break;
2506 case RESUME_QUIT:
2507 am_rerere_clear();
2508 am_destroy(&state);
2509 break;
2510 case RESUME_SHOW_PATCH_RAW:
2511 case RESUME_SHOW_PATCH_DIFF:
2512 ret = show_patch(&state, resume_mode);
2513 break;
2514 default:
2515 BUG("invalid resume value");
2518 am_state_release(&state);
2520 return ret;