gitlab-ci: introduce stages and dependencies
[git/gitster.git] / builtin / am.c
blobbfa95147cf403f9ce6b61afdd08077837fda2c48
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
7 #define USE_THE_REPOSITORY_VARIABLE
8 #include "builtin.h"
9 #include "abspath.h"
10 #include "advice.h"
11 #include "config.h"
12 #include "editor.h"
13 #include "environment.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 "unpack-trees.h"
28 #include "branch.h"
29 #include "object-name.h"
30 #include "preload-index.h"
31 #include "sequencer.h"
32 #include "revision.h"
33 #include "merge-recursive.h"
34 #include "log-tree.h"
35 #include "notes-utils.h"
36 #include "rerere.h"
37 #include "mailinfo.h"
38 #include "apply.h"
39 #include "string-list.h"
40 #include "pager.h"
41 #include "path.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(the_repository, "applypatch-msg",
494 am_path(state, "final-commit"), NULL);
496 if (!ret) {
497 FREE_AND_NULL(state->msg);
498 if (read_commit_msg(state) < 0)
499 die(_("'%s' was deleted by the applypatch-msg hook"),
500 am_path(state, "final-commit"));
503 return ret;
507 * Runs post-rewrite hook. Returns it exit code.
509 static int run_post_rewrite_hook(const struct am_state *state)
511 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
513 strvec_push(&opt.args, "rebase");
514 opt.path_to_stdin = am_path(state, "rewritten");
516 return run_hooks_opt(the_repository, "post-rewrite", &opt);
520 * Reads the state directory's "rewritten" file, and copies notes from the old
521 * commits listed in the file to their rewritten commits.
523 * Returns 0 on success, -1 on failure.
525 static int copy_notes_for_rebase(const struct am_state *state)
527 struct notes_rewrite_cfg *c;
528 struct strbuf sb = STRBUF_INIT;
529 const char *invalid_line = _("Malformed input line: '%s'.");
530 const char *msg = "Notes added by 'git rebase'";
531 FILE *fp;
532 int ret = 0;
534 assert(state->rebasing);
536 c = init_copy_notes_for_rewrite("rebase");
537 if (!c)
538 return 0;
540 fp = xfopen(am_path(state, "rewritten"), "r");
542 while (!strbuf_getline_lf(&sb, fp)) {
543 struct object_id from_obj, to_obj;
544 const char *p;
546 if (sb.len != the_hash_algo->hexsz * 2 + 1) {
547 ret = error(invalid_line, sb.buf);
548 goto finish;
551 if (parse_oid_hex(sb.buf, &from_obj, &p)) {
552 ret = error(invalid_line, sb.buf);
553 goto finish;
556 if (*p != ' ') {
557 ret = error(invalid_line, sb.buf);
558 goto finish;
561 if (get_oid_hex(p + 1, &to_obj)) {
562 ret = error(invalid_line, sb.buf);
563 goto finish;
566 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
567 ret = error(_("Failed to copy notes from '%s' to '%s'"),
568 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
571 finish:
572 finish_copy_notes_for_rewrite(the_repository, c, msg);
573 fclose(fp);
574 strbuf_release(&sb);
575 return ret;
579 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
580 * non-indented lines and checking if they look like they begin with valid
581 * header field names.
583 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
585 static int is_mail(FILE *fp)
587 const char *header_regex = "^[!-9;-~]+:";
588 struct strbuf sb = STRBUF_INIT;
589 regex_t regex;
590 int ret = 1;
592 if (fseek(fp, 0L, SEEK_SET))
593 die_errno(_("fseek failed"));
595 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
596 die("invalid pattern: %s", header_regex);
598 while (!strbuf_getline(&sb, fp)) {
599 if (!sb.len)
600 break; /* End of header */
602 /* Ignore indented folded lines */
603 if (*sb.buf == '\t' || *sb.buf == ' ')
604 continue;
606 /* It's a header if it matches header_regex */
607 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
608 ret = 0;
609 goto done;
613 done:
614 regfree(&regex);
615 strbuf_release(&sb);
616 return ret;
620 * Attempts to detect the patch_format of the patches contained in `paths`,
621 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
622 * detection fails.
624 static int detect_patch_format(const char **paths)
626 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
627 struct strbuf l1 = STRBUF_INIT;
628 struct strbuf l2 = STRBUF_INIT;
629 struct strbuf l3 = STRBUF_INIT;
630 FILE *fp;
633 * We default to mbox format if input is from stdin and for directories
635 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
636 return PATCH_FORMAT_MBOX;
639 * Otherwise, check the first few lines of the first patch, starting
640 * from the first non-blank line, to try to detect its format.
643 fp = xfopen(*paths, "r");
645 while (!strbuf_getline(&l1, fp)) {
646 if (l1.len)
647 break;
650 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
651 ret = PATCH_FORMAT_MBOX;
652 goto done;
655 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
656 ret = PATCH_FORMAT_STGIT_SERIES;
657 goto done;
660 if (!strcmp(l1.buf, "# HG changeset patch")) {
661 ret = PATCH_FORMAT_HG;
662 goto done;
665 strbuf_getline(&l2, fp);
666 strbuf_getline(&l3, fp);
669 * If the second line is empty and the third is a From, Author or Date
670 * entry, this is likely an StGit patch.
672 if (l1.len && !l2.len &&
673 (starts_with(l3.buf, "From:") ||
674 starts_with(l3.buf, "Author:") ||
675 starts_with(l3.buf, "Date:"))) {
676 ret = PATCH_FORMAT_STGIT;
677 goto done;
680 if (l1.len && is_mail(fp)) {
681 ret = PATCH_FORMAT_MBOX;
682 goto done;
685 done:
686 fclose(fp);
687 strbuf_release(&l1);
688 strbuf_release(&l2);
689 strbuf_release(&l3);
690 return ret;
694 * Splits out individual email patches from `paths`, where each path is either
695 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
697 static int split_mail_mbox(struct am_state *state, const char **paths,
698 int keep_cr, int mboxrd)
700 struct child_process cp = CHILD_PROCESS_INIT;
701 struct strbuf last = STRBUF_INIT;
702 int ret;
704 cp.git_cmd = 1;
705 strvec_push(&cp.args, "mailsplit");
706 strvec_pushf(&cp.args, "-d%d", state->prec);
707 strvec_pushf(&cp.args, "-o%s", state->dir);
708 strvec_push(&cp.args, "-b");
709 if (keep_cr)
710 strvec_push(&cp.args, "--keep-cr");
711 if (mboxrd)
712 strvec_push(&cp.args, "--mboxrd");
713 strvec_push(&cp.args, "--");
714 strvec_pushv(&cp.args, paths);
716 ret = capture_command(&cp, &last, 8);
717 if (ret)
718 goto exit;
720 state->cur = 1;
721 state->last = strtol(last.buf, NULL, 10);
723 exit:
724 strbuf_release(&last);
725 return ret ? -1 : 0;
729 * Callback signature for split_mail_conv(). The foreign patch should be
730 * read from `in`, and the converted patch (in RFC2822 mail format) should be
731 * written to `out`. Return 0 on success, or -1 on failure.
733 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
736 * Calls `fn` for each file in `paths` to convert the foreign patch to the
737 * RFC2822 mail format suitable for parsing with git-mailinfo.
739 * Returns 0 on success, -1 on failure.
741 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
742 const char **paths, int keep_cr)
744 static const char *stdin_only[] = {"-", NULL};
745 int i;
747 if (!*paths)
748 paths = stdin_only;
750 for (i = 0; *paths; paths++, i++) {
751 FILE *in, *out;
752 const char *mail;
753 int ret;
755 if (!strcmp(*paths, "-"))
756 in = stdin;
757 else
758 in = fopen(*paths, "r");
760 if (!in)
761 return error_errno(_("could not open '%s' for reading"),
762 *paths);
764 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
766 out = fopen(mail, "w");
767 if (!out) {
768 if (in != stdin)
769 fclose(in);
770 return error_errno(_("could not open '%s' for writing"),
771 mail);
774 ret = fn(out, in, keep_cr);
776 fclose(out);
777 if (in != stdin)
778 fclose(in);
780 if (ret)
781 return error(_("could not parse patch '%s'"), *paths);
784 state->cur = 1;
785 state->last = i;
786 return 0;
790 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
791 * message suitable for parsing with git-mailinfo.
793 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
795 struct strbuf sb = STRBUF_INIT;
796 int subject_printed = 0;
798 while (!strbuf_getline_lf(&sb, in)) {
799 const char *str;
801 if (str_isspace(sb.buf))
802 continue;
803 else if (skip_prefix(sb.buf, "Author:", &str))
804 fprintf(out, "From:%s\n", str);
805 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
806 fprintf(out, "%s\n", sb.buf);
807 else if (!subject_printed) {
808 fprintf(out, "Subject: %s\n", sb.buf);
809 subject_printed = 1;
810 } else {
811 fprintf(out, "\n%s\n", sb.buf);
812 break;
816 strbuf_reset(&sb);
817 while (strbuf_fread(&sb, 8192, in) > 0) {
818 fwrite(sb.buf, 1, sb.len, out);
819 strbuf_reset(&sb);
822 strbuf_release(&sb);
823 return 0;
827 * This function only supports a single StGit series file in `paths`.
829 * Given an StGit series file, converts the StGit patches in the series into
830 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
831 * the state directory.
833 * Returns 0 on success, -1 on failure.
835 static int split_mail_stgit_series(struct am_state *state, const char **paths,
836 int keep_cr)
838 const char *series_dir;
839 char *series_dir_buf;
840 FILE *fp;
841 struct strvec patches = STRVEC_INIT;
842 struct strbuf sb = STRBUF_INIT;
843 int ret;
845 if (!paths[0] || paths[1])
846 return error(_("Only one StGIT patch series can be applied at once"));
848 series_dir_buf = xstrdup(*paths);
849 series_dir = dirname(series_dir_buf);
851 fp = fopen(*paths, "r");
852 if (!fp)
853 return error_errno(_("could not open '%s' for reading"), *paths);
855 while (!strbuf_getline_lf(&sb, fp)) {
856 if (*sb.buf == '#')
857 continue; /* skip comment lines */
859 strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
862 fclose(fp);
863 strbuf_release(&sb);
864 free(series_dir_buf);
866 ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
868 strvec_clear(&patches);
869 return ret;
873 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
874 * message suitable for parsing with git-mailinfo.
876 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr UNUSED)
878 struct strbuf sb = STRBUF_INIT;
879 int rc = 0;
881 while (!strbuf_getline_lf(&sb, in)) {
882 const char *str;
884 if (skip_prefix(sb.buf, "# User ", &str))
885 fprintf(out, "From: %s\n", str);
886 else if (skip_prefix(sb.buf, "# Date ", &str)) {
887 timestamp_t timestamp;
888 long tz, tz2;
889 char *end;
891 errno = 0;
892 timestamp = parse_timestamp(str, &end, 10);
893 if (errno) {
894 rc = error(_("invalid timestamp"));
895 goto exit;
898 if (!skip_prefix(end, " ", &str)) {
899 rc = error(_("invalid Date line"));
900 goto exit;
903 errno = 0;
904 tz = strtol(str, &end, 10);
905 if (errno) {
906 rc = error(_("invalid timezone offset"));
907 goto exit;
910 if (*end) {
911 rc = error(_("invalid Date line"));
912 goto exit;
916 * mercurial's timezone is in seconds west of UTC,
917 * however git's timezone is in hours + minutes east of
918 * UTC. Convert it.
920 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
921 if (tz > 0)
922 tz2 = -tz2;
924 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
925 } else if (starts_with(sb.buf, "# ")) {
926 continue;
927 } else {
928 fprintf(out, "\n%s\n", sb.buf);
929 break;
933 strbuf_reset(&sb);
934 while (strbuf_fread(&sb, 8192, in) > 0) {
935 fwrite(sb.buf, 1, sb.len, out);
936 strbuf_reset(&sb);
938 exit:
939 strbuf_release(&sb);
940 return rc;
944 * Splits a list of files/directories into individual email patches. Each path
945 * in `paths` must be a file/directory that is formatted according to
946 * `patch_format`.
948 * Once split out, the individual email patches will be stored in the state
949 * directory, with each patch's filename being its index, padded to state->prec
950 * digits.
952 * state->cur will be set to the index of the first mail, and state->last will
953 * be set to the index of the last mail.
955 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
956 * to disable this behavior, -1 to use the default configured setting.
958 * Returns 0 on success, -1 on failure.
960 static int split_mail(struct am_state *state, enum patch_format patch_format,
961 const char **paths, int keep_cr)
963 if (keep_cr < 0) {
964 keep_cr = 0;
965 git_config_get_bool("am.keepcr", &keep_cr);
968 switch (patch_format) {
969 case PATCH_FORMAT_MBOX:
970 return split_mail_mbox(state, paths, keep_cr, 0);
971 case PATCH_FORMAT_STGIT:
972 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
973 case PATCH_FORMAT_STGIT_SERIES:
974 return split_mail_stgit_series(state, paths, keep_cr);
975 case PATCH_FORMAT_HG:
976 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
977 case PATCH_FORMAT_MBOXRD:
978 return split_mail_mbox(state, paths, keep_cr, 1);
979 default:
980 BUG("invalid patch_format");
982 return -1;
986 * Setup a new am session for applying patches
988 static void am_setup(struct am_state *state, enum patch_format patch_format,
989 const char **paths, int keep_cr)
991 struct object_id curr_head;
992 const char *str;
993 struct strbuf sb = STRBUF_INIT;
995 if (!patch_format)
996 patch_format = detect_patch_format(paths);
998 if (!patch_format) {
999 fprintf_ln(stderr, _("Patch format detection failed."));
1000 exit(128);
1003 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1004 die_errno(_("failed to create directory '%s'"), state->dir);
1005 refs_delete_ref(get_main_ref_store(the_repository), NULL,
1006 "REBASE_HEAD", NULL, REF_NO_DEREF);
1008 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1009 am_destroy(state);
1010 die(_("Failed to split patches."));
1013 if (state->rebasing)
1014 state->threeway = 1;
1016 write_state_bool(state, "threeway", state->threeway);
1017 write_state_bool(state, "quiet", state->quiet);
1018 write_state_bool(state, "sign", state->signoff);
1019 write_state_bool(state, "utf8", state->utf8);
1021 if (state->allow_rerere_autoupdate)
1022 write_state_bool(state, "rerere-autoupdate",
1023 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1025 switch (state->keep) {
1026 case KEEP_FALSE:
1027 str = "f";
1028 break;
1029 case KEEP_TRUE:
1030 str = "t";
1031 break;
1032 case KEEP_NON_PATCH:
1033 str = "b";
1034 break;
1035 default:
1036 BUG("invalid value for state->keep");
1039 write_state_text(state, "keep", str);
1040 write_state_bool(state, "messageid", state->message_id);
1042 switch (state->scissors) {
1043 case SCISSORS_UNSET:
1044 str = "";
1045 break;
1046 case SCISSORS_FALSE:
1047 str = "f";
1048 break;
1049 case SCISSORS_TRUE:
1050 str = "t";
1051 break;
1052 default:
1053 BUG("invalid value for state->scissors");
1055 write_state_text(state, "scissors", str);
1057 switch (state->quoted_cr) {
1058 case quoted_cr_unset:
1059 str = "";
1060 break;
1061 case quoted_cr_nowarn:
1062 str = "nowarn";
1063 break;
1064 case quoted_cr_warn:
1065 str = "warn";
1066 break;
1067 case quoted_cr_strip:
1068 str = "strip";
1069 break;
1070 default:
1071 BUG("invalid value for state->quoted_cr");
1073 write_state_text(state, "quoted-cr", str);
1075 sq_quote_argv(&sb, state->git_apply_opts.v);
1076 write_state_text(state, "apply-opt", sb.buf);
1078 if (state->rebasing)
1079 write_state_text(state, "rebasing", "");
1080 else
1081 write_state_text(state, "applying", "");
1083 if (!repo_get_oid(the_repository, "HEAD", &curr_head)) {
1084 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1085 if (!state->rebasing)
1086 refs_update_ref(get_main_ref_store(the_repository),
1087 "am", "ORIG_HEAD", &curr_head, NULL,
1089 UPDATE_REFS_DIE_ON_ERR);
1090 } else {
1091 write_state_text(state, "abort-safety", "");
1092 if (!state->rebasing)
1093 refs_delete_ref(get_main_ref_store(the_repository),
1094 NULL, "ORIG_HEAD", NULL, 0);
1098 * NOTE: Since the "next" and "last" files determine if an am_state
1099 * session is in progress, they should be written last.
1102 write_state_count(state, "next", state->cur);
1103 write_state_count(state, "last", state->last);
1105 strbuf_release(&sb);
1109 * Increments the patch pointer, and cleans am_state for the application of the
1110 * next patch.
1112 static void am_next(struct am_state *state)
1114 struct object_id head;
1116 FREE_AND_NULL(state->author_name);
1117 FREE_AND_NULL(state->author_email);
1118 FREE_AND_NULL(state->author_date);
1119 FREE_AND_NULL(state->msg);
1120 state->msg_len = 0;
1122 unlink(am_path(state, "author-script"));
1123 unlink(am_path(state, "final-commit"));
1125 oidclr(&state->orig_commit, the_repository->hash_algo);
1126 unlink(am_path(state, "original-commit"));
1127 refs_delete_ref(get_main_ref_store(the_repository), NULL,
1128 "REBASE_HEAD", NULL, REF_NO_DEREF);
1130 if (!repo_get_oid(the_repository, "HEAD", &head))
1131 write_state_text(state, "abort-safety", oid_to_hex(&head));
1132 else
1133 write_state_text(state, "abort-safety", "");
1135 state->cur++;
1136 write_state_count(state, "next", state->cur);
1140 * Returns the filename of the current patch email.
1142 static const char *msgnum(const struct am_state *state)
1144 static struct strbuf sb = STRBUF_INIT;
1146 strbuf_reset(&sb);
1147 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1149 return sb.buf;
1153 * Dies with a user-friendly message on how to proceed after resolving the
1154 * problem. This message can be overridden with state->resolvemsg.
1156 static void NORETURN die_user_resolve(const struct am_state *state)
1158 if (state->resolvemsg) {
1159 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", state->resolvemsg);
1160 } else {
1161 const char *cmdline = state->interactive ? "git am -i" : "git am";
1162 struct strbuf sb = STRBUF_INIT;
1164 strbuf_addf(&sb, _("When you have resolved this problem, run \"%s --continue\".\n"), cmdline);
1165 strbuf_addf(&sb, _("If you prefer to skip this patch, run \"%s --skip\" instead.\n"), cmdline);
1167 if (advice_enabled(ADVICE_AM_WORK_DIR) &&
1168 is_empty_or_missing_file(am_path(state, "patch")) &&
1169 !repo_index_has_changes(the_repository, NULL, NULL))
1170 strbuf_addf(&sb, _("To record the empty patch as an empty commit, run \"%s --allow-empty\".\n"), cmdline);
1172 strbuf_addf(&sb, _("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1174 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", sb.buf);
1175 strbuf_release(&sb);
1178 exit(128);
1182 * Appends signoff to the "msg" field of the am_state.
1184 static void am_append_signoff(struct am_state *state)
1186 struct strbuf sb = STRBUF_INIT;
1188 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1189 append_signoff(&sb, 0, 0);
1190 state->msg = strbuf_detach(&sb, &state->msg_len);
1194 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1195 * state->msg will be set to the patch message. state->author_name,
1196 * state->author_email and state->author_date will be set to the patch author's
1197 * name, email and date respectively. The patch body will be written to the
1198 * state directory's "patch" file.
1200 * Returns 1 if the patch should be skipped, 0 otherwise.
1202 static int parse_mail(struct am_state *state, const char *mail)
1204 FILE *fp;
1205 struct strbuf sb = STRBUF_INIT;
1206 struct strbuf msg = STRBUF_INIT;
1207 struct strbuf author_name = STRBUF_INIT;
1208 struct strbuf author_date = STRBUF_INIT;
1209 struct strbuf author_email = STRBUF_INIT;
1210 int ret = 0;
1211 struct mailinfo mi;
1213 setup_mailinfo(&mi);
1215 if (state->utf8)
1216 mi.metainfo_charset = get_commit_output_encoding();
1217 else
1218 mi.metainfo_charset = NULL;
1220 switch (state->keep) {
1221 case KEEP_FALSE:
1222 break;
1223 case KEEP_TRUE:
1224 mi.keep_subject = 1;
1225 break;
1226 case KEEP_NON_PATCH:
1227 mi.keep_non_patch_brackets_in_subject = 1;
1228 break;
1229 default:
1230 BUG("invalid value for state->keep");
1233 if (state->message_id)
1234 mi.add_message_id = 1;
1236 switch (state->scissors) {
1237 case SCISSORS_UNSET:
1238 break;
1239 case SCISSORS_FALSE:
1240 mi.use_scissors = 0;
1241 break;
1242 case SCISSORS_TRUE:
1243 mi.use_scissors = 1;
1244 break;
1245 default:
1246 BUG("invalid value for state->scissors");
1249 switch (state->quoted_cr) {
1250 case quoted_cr_unset:
1251 break;
1252 case quoted_cr_nowarn:
1253 case quoted_cr_warn:
1254 case quoted_cr_strip:
1255 mi.quoted_cr = state->quoted_cr;
1256 break;
1257 default:
1258 BUG("invalid value for state->quoted_cr");
1261 mi.input = xfopen(mail, "r");
1262 mi.output = xfopen(am_path(state, "info"), "w");
1263 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1264 die("could not parse patch");
1266 fclose(mi.input);
1267 fclose(mi.output);
1269 if (mi.format_flowed)
1270 warning(_("Patch sent with format=flowed; "
1271 "space at the end of lines might be lost."));
1273 /* Extract message and author information */
1274 fp = xfopen(am_path(state, "info"), "r");
1275 while (!strbuf_getline_lf(&sb, fp)) {
1276 const char *x;
1278 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1279 if (msg.len)
1280 strbuf_addch(&msg, '\n');
1281 strbuf_addstr(&msg, x);
1282 } else if (skip_prefix(sb.buf, "Author: ", &x))
1283 strbuf_addstr(&author_name, x);
1284 else if (skip_prefix(sb.buf, "Email: ", &x))
1285 strbuf_addstr(&author_email, x);
1286 else if (skip_prefix(sb.buf, "Date: ", &x))
1287 strbuf_addstr(&author_date, x);
1289 fclose(fp);
1291 /* Skip pine's internal folder data */
1292 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1293 ret = 1;
1294 goto finish;
1297 strbuf_addstr(&msg, "\n\n");
1298 strbuf_addbuf(&msg, &mi.log_message);
1299 strbuf_stripspace(&msg, NULL);
1301 assert(!state->author_name);
1302 state->author_name = strbuf_detach(&author_name, NULL);
1304 assert(!state->author_email);
1305 state->author_email = strbuf_detach(&author_email, NULL);
1307 assert(!state->author_date);
1308 state->author_date = strbuf_detach(&author_date, NULL);
1310 assert(!state->msg);
1311 state->msg = strbuf_detach(&msg, &state->msg_len);
1313 finish:
1314 strbuf_release(&msg);
1315 strbuf_release(&author_date);
1316 strbuf_release(&author_email);
1317 strbuf_release(&author_name);
1318 strbuf_release(&sb);
1319 clear_mailinfo(&mi);
1320 return ret;
1324 * Sets commit_id to the commit hash where the mail was generated from.
1325 * Returns 0 on success, -1 on failure.
1327 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1329 struct strbuf sb = STRBUF_INIT;
1330 FILE *fp = xfopen(mail, "r");
1331 const char *x;
1332 int ret = 0;
1334 if (strbuf_getline_lf(&sb, fp) ||
1335 !skip_prefix(sb.buf, "From ", &x) ||
1336 get_oid_hex(x, commit_id) < 0)
1337 ret = -1;
1339 strbuf_release(&sb);
1340 fclose(fp);
1341 return ret;
1345 * Sets state->msg, state->author_name, state->author_email, state->author_date
1346 * to the commit's respective info.
1348 static void get_commit_info(struct am_state *state, struct commit *commit)
1350 const char *buffer, *ident_line, *msg;
1351 size_t ident_len;
1352 struct ident_split id;
1354 buffer = repo_logmsg_reencode(the_repository, commit, NULL,
1355 get_commit_output_encoding());
1357 ident_line = find_commit_header(buffer, "author", &ident_len);
1358 if (!ident_line)
1359 die(_("missing author line in commit %s"),
1360 oid_to_hex(&commit->object.oid));
1361 if (split_ident_line(&id, ident_line, ident_len) < 0)
1362 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1364 assert(!state->author_name);
1365 if (id.name_begin)
1366 state->author_name =
1367 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1368 else
1369 state->author_name = xstrdup("");
1371 assert(!state->author_email);
1372 if (id.mail_begin)
1373 state->author_email =
1374 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1375 else
1376 state->author_email = xstrdup("");
1378 assert(!state->author_date);
1379 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1381 assert(!state->msg);
1382 msg = strstr(buffer, "\n\n");
1383 if (!msg)
1384 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1385 state->msg = xstrdup(msg + 2);
1386 state->msg_len = strlen(state->msg);
1387 repo_unuse_commit_buffer(the_repository, commit, buffer);
1391 * Writes `commit` as a patch to the state directory's "patch" file.
1393 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1395 struct rev_info rev_info;
1396 FILE *fp;
1398 fp = xfopen(am_path(state, "patch"), "w");
1399 repo_init_revisions(the_repository, &rev_info, NULL);
1400 rev_info.diff = 1;
1401 rev_info.abbrev = 0;
1402 rev_info.disable_stdin = 1;
1403 rev_info.show_root_diff = 1;
1404 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1405 rev_info.no_commit_id = 1;
1406 rev_info.diffopt.flags.binary = 1;
1407 rev_info.diffopt.flags.full_index = 1;
1408 rev_info.diffopt.use_color = 0;
1409 rev_info.diffopt.file = fp;
1410 rev_info.diffopt.close_file = 1;
1411 add_pending_object(&rev_info, &commit->object, "");
1412 diff_setup_done(&rev_info.diffopt);
1413 log_tree_commit(&rev_info, commit);
1414 release_revisions(&rev_info);
1418 * Writes the diff of the index against HEAD as a patch to the state
1419 * directory's "patch" file.
1421 static void write_index_patch(const struct am_state *state)
1423 struct tree *tree;
1424 struct object_id head;
1425 struct rev_info rev_info;
1426 FILE *fp;
1428 if (!repo_get_oid(the_repository, "HEAD", &head)) {
1429 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1430 tree = repo_get_commit_tree(the_repository, commit);
1431 } else
1432 tree = lookup_tree(the_repository,
1433 the_repository->hash_algo->empty_tree);
1435 fp = xfopen(am_path(state, "patch"), "w");
1436 repo_init_revisions(the_repository, &rev_info, NULL);
1437 rev_info.diff = 1;
1438 rev_info.disable_stdin = 1;
1439 rev_info.no_commit_id = 1;
1440 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1441 rev_info.diffopt.use_color = 0;
1442 rev_info.diffopt.file = fp;
1443 rev_info.diffopt.close_file = 1;
1444 add_pending_object(&rev_info, &tree->object, "");
1445 diff_setup_done(&rev_info.diffopt);
1446 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1447 release_revisions(&rev_info);
1451 * Like parse_mail(), but parses the mail by looking up its commit ID
1452 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1453 * of patches.
1455 * state->orig_commit will be set to the original commit ID.
1457 * Will always return 0 as the patch should never be skipped.
1459 static int parse_mail_rebase(struct am_state *state, const char *mail)
1461 struct commit *commit;
1462 struct object_id commit_oid;
1464 if (get_mail_commit_oid(&commit_oid, mail) < 0)
1465 die(_("could not parse %s"), mail);
1467 commit = lookup_commit_or_die(&commit_oid, mail);
1469 get_commit_info(state, commit);
1471 write_commit_patch(state, commit);
1473 oidcpy(&state->orig_commit, &commit_oid);
1474 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1475 refs_update_ref(get_main_ref_store(the_repository), "am",
1476 "REBASE_HEAD", &commit_oid,
1477 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
1479 return 0;
1483 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1484 * `index_file` is not NULL, the patch will be applied to that index.
1486 static int run_apply(const struct am_state *state, const char *index_file)
1488 struct strvec apply_paths = STRVEC_INIT;
1489 struct strvec apply_opts = STRVEC_INIT;
1490 struct apply_state apply_state;
1491 int res, opts_left;
1492 int force_apply = 0;
1493 int options = 0;
1494 const char **apply_argv;
1496 if (init_apply_state(&apply_state, the_repository, NULL))
1497 BUG("init_apply_state() failed");
1499 strvec_push(&apply_opts, "apply");
1500 strvec_pushv(&apply_opts, state->git_apply_opts.v);
1503 * Build a copy that apply_parse_options() can rearrange.
1504 * apply_opts.v keeps referencing the allocated strings for
1505 * strvec_clear() to release.
1507 DUP_ARRAY(apply_argv, apply_opts.v, apply_opts.nr);
1509 opts_left = apply_parse_options(apply_opts.nr, apply_argv,
1510 &apply_state, &force_apply, &options,
1511 NULL);
1513 if (opts_left != 0)
1514 die("unknown option passed through to git apply");
1516 if (index_file) {
1517 apply_state.index_file = index_file;
1518 apply_state.cached = 1;
1519 } else
1520 apply_state.check_index = 1;
1523 * If we are allowed to fall back on 3-way merge, don't give false
1524 * errors during the initial attempt.
1526 if (state->threeway && !index_file)
1527 apply_state.apply_verbosity = verbosity_silent;
1529 if (check_apply_state(&apply_state, force_apply))
1530 BUG("check_apply_state() failed");
1532 strvec_push(&apply_paths, am_path(state, "patch"));
1534 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
1536 strvec_clear(&apply_paths);
1537 strvec_clear(&apply_opts);
1538 clear_apply_state(&apply_state);
1539 free(apply_argv);
1541 if (res)
1542 return res;
1544 if (index_file) {
1545 /* Reload index as apply_all_patches() will have modified it. */
1546 discard_index(the_repository->index);
1547 read_index_from(the_repository->index, index_file,
1548 repo_get_git_dir(the_repository));
1551 return 0;
1555 * Builds an index that contains just the blobs needed for a 3way merge.
1557 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1559 struct child_process cp = CHILD_PROCESS_INIT;
1561 cp.git_cmd = 1;
1562 strvec_push(&cp.args, "apply");
1563 strvec_pushv(&cp.args, state->git_apply_opts.v);
1564 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1565 strvec_push(&cp.args, am_path(state, "patch"));
1567 if (run_command(&cp))
1568 return -1;
1570 return 0;
1574 * Attempt a threeway merge, using index_path as the temporary index.
1576 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1578 struct object_id their_tree, our_tree;
1579 struct object_id bases[1] = { 0 };
1580 struct merge_options o;
1581 struct commit *result;
1582 char *their_tree_name;
1584 if (repo_get_oid(the_repository, "HEAD", &our_tree) < 0)
1585 oidcpy(&our_tree, the_hash_algo->empty_tree);
1587 if (build_fake_ancestor(state, index_path))
1588 return error("could not build fake ancestor");
1590 discard_index(the_repository->index);
1591 read_index_from(the_repository->index, index_path, repo_get_git_dir(the_repository));
1593 if (write_index_as_tree(&bases[0], the_repository->index, index_path, 0, NULL))
1594 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1596 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1598 if (!state->quiet) {
1600 * List paths that needed 3-way fallback, so that the user can
1601 * review them with extra care to spot mismerges.
1603 struct rev_info rev_info;
1605 repo_init_revisions(the_repository, &rev_info, NULL);
1606 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1607 rev_info.diffopt.filter |= diff_filter_bit('A');
1608 rev_info.diffopt.filter |= diff_filter_bit('M');
1609 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1610 diff_setup_done(&rev_info.diffopt);
1611 run_diff_index(&rev_info, DIFF_INDEX_CACHED);
1612 release_revisions(&rev_info);
1615 if (run_apply(state, index_path))
1616 return error(_("Did you hand edit your patch?\n"
1617 "It does not apply to blobs recorded in its index."));
1619 if (write_index_as_tree(&their_tree, the_repository->index, index_path, 0, NULL))
1620 return error("could not write tree");
1622 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1624 discard_index(the_repository->index);
1625 repo_read_index(the_repository);
1628 * This is not so wrong. Depending on which base we picked, orig_tree
1629 * may be wildly different from ours, but their_tree has the same set of
1630 * wildly different changes in parts the patch did not touch, so
1631 * recursive ends up canceling them, saying that we reverted all those
1632 * changes.
1635 init_ui_merge_options(&o, the_repository);
1637 o.branch1 = "HEAD";
1638 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1639 o.branch2 = their_tree_name;
1640 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
1642 if (state->quiet)
1643 o.verbosity = 0;
1645 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1646 repo_rerere(the_repository, state->allow_rerere_autoupdate);
1647 free(their_tree_name);
1648 return error(_("Failed to merge in the changes."));
1651 free(their_tree_name);
1652 return 0;
1656 * Commits the current index with state->msg as the commit message and
1657 * state->author_name, state->author_email and state->author_date as the author
1658 * information.
1660 static void do_commit(const struct am_state *state)
1662 struct object_id tree, parent, commit;
1663 const struct object_id *old_oid;
1664 struct commit_list *parents = NULL;
1665 const char *reflog_msg, *author, *committer = NULL;
1666 struct strbuf sb = STRBUF_INIT;
1668 if (!state->no_verify && run_hooks(the_repository, "pre-applypatch"))
1669 exit(1);
1671 if (write_index_as_tree(&tree, the_repository->index,
1672 repo_get_index_file(the_repository),
1673 0, NULL))
1674 die(_("git write-tree failed to write a tree"));
1676 if (!repo_get_oid_commit(the_repository, "HEAD", &parent)) {
1677 old_oid = &parent;
1678 commit_list_insert(lookup_commit(the_repository, &parent),
1679 &parents);
1680 } else {
1681 old_oid = NULL;
1682 say(state, stderr, _("applying to an empty history"));
1685 author = fmt_ident(state->author_name, state->author_email,
1686 WANT_AUTHOR_IDENT,
1687 state->ignore_date ? NULL : state->author_date,
1688 IDENT_STRICT);
1690 if (state->committer_date_is_author_date)
1691 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1692 getenv("GIT_COMMITTER_EMAIL"),
1693 WANT_COMMITTER_IDENT,
1694 state->ignore_date ? NULL
1695 : state->author_date,
1696 IDENT_STRICT);
1698 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1699 &commit, author, committer, state->sign_commit,
1700 NULL))
1701 die(_("failed to write commit object"));
1703 reflog_msg = getenv("GIT_REFLOG_ACTION");
1704 if (!reflog_msg)
1705 reflog_msg = "am";
1707 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1708 state->msg);
1710 refs_update_ref(get_main_ref_store(the_repository), sb.buf, "HEAD",
1711 &commit, old_oid, 0,
1712 UPDATE_REFS_DIE_ON_ERR);
1714 if (state->rebasing) {
1715 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1717 assert(!is_null_oid(&state->orig_commit));
1718 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1719 fprintf(fp, "%s\n", oid_to_hex(&commit));
1720 fclose(fp);
1723 run_hooks(the_repository, "post-applypatch");
1725 free_commit_list(parents);
1726 strbuf_release(&sb);
1730 * Validates the am_state for resuming -- the "msg" and authorship fields must
1731 * be filled up.
1733 static void validate_resume_state(const struct am_state *state)
1735 if (!state->msg)
1736 die(_("cannot resume: %s does not exist."),
1737 am_path(state, "final-commit"));
1739 if (!state->author_name || !state->author_email || !state->author_date)
1740 die(_("cannot resume: %s does not exist."),
1741 am_path(state, "author-script"));
1745 * Interactively prompt the user on whether the current patch should be
1746 * applied.
1748 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1749 * skip it.
1751 static int do_interactive(struct am_state *state)
1753 assert(state->msg);
1755 for (;;) {
1756 char reply[64];
1758 puts(_("Commit Body is:"));
1759 puts("--------------------------");
1760 printf("%s", state->msg);
1761 puts("--------------------------");
1764 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1765 * in your translation. The program will only accept English
1766 * input at this point.
1768 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1769 if (!fgets(reply, sizeof(reply), stdin))
1770 die("unable to read from stdin; aborting");
1772 if (*reply == 'y' || *reply == 'Y') {
1773 return 0;
1774 } else if (*reply == 'a' || *reply == 'A') {
1775 state->interactive = 0;
1776 return 0;
1777 } else if (*reply == 'n' || *reply == 'N') {
1778 return 1;
1779 } else if (*reply == 'e' || *reply == 'E') {
1780 struct strbuf msg = STRBUF_INIT;
1782 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1783 free(state->msg);
1784 state->msg = strbuf_detach(&msg, &state->msg_len);
1786 strbuf_release(&msg);
1787 } else if (*reply == 'v' || *reply == 'V') {
1788 const char *pager = git_pager(1);
1789 struct child_process cp = CHILD_PROCESS_INIT;
1791 if (!pager)
1792 pager = "cat";
1793 prepare_pager_args(&cp, pager);
1794 strvec_push(&cp.args, am_path(state, "patch"));
1795 run_command(&cp);
1801 * Applies all queued mail.
1803 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1804 * well as the state directory's "patch" file is used as-is for applying the
1805 * patch and committing it.
1807 static void am_run(struct am_state *state, int resume)
1809 struct strbuf sb = STRBUF_INIT;
1811 unlink(am_path(state, "dirtyindex"));
1813 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1814 NULL, NULL, NULL) < 0)
1815 die(_("unable to write index file"));
1817 if (repo_index_has_changes(the_repository, NULL, &sb)) {
1818 write_state_bool(state, "dirtyindex", 1);
1819 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1822 strbuf_release(&sb);
1824 while (state->cur <= state->last) {
1825 const char *mail = am_path(state, msgnum(state));
1826 int apply_status;
1827 int to_keep;
1829 reset_ident_date();
1831 if (!file_exists(mail))
1832 goto next;
1834 if (resume) {
1835 validate_resume_state(state);
1836 } else {
1837 int skip;
1839 if (state->rebasing)
1840 skip = parse_mail_rebase(state, mail);
1841 else
1842 skip = parse_mail(state, mail);
1844 if (skip)
1845 goto next; /* mail should be skipped */
1847 if (state->signoff)
1848 am_append_signoff(state);
1850 write_author_script(state);
1851 write_commit_msg(state);
1854 if (state->interactive && do_interactive(state))
1855 goto next;
1857 to_keep = 0;
1858 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1859 switch (state->empty_type) {
1860 case DROP_EMPTY_COMMIT:
1861 say(state, stdout, _("Skipping: %.*s"), linelen(state->msg), state->msg);
1862 goto next;
1863 break;
1864 case KEEP_EMPTY_COMMIT:
1865 to_keep = 1;
1866 say(state, stdout, _("Creating an empty commit: %.*s"),
1867 linelen(state->msg), state->msg);
1868 break;
1869 case STOP_ON_EMPTY_COMMIT:
1870 printf_ln(_("Patch is empty."));
1871 die_user_resolve(state);
1872 break;
1876 if (run_applypatch_msg_hook(state))
1877 exit(1);
1878 if (to_keep)
1879 goto commit;
1881 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1883 apply_status = run_apply(state, NULL);
1885 if (apply_status && state->threeway) {
1886 struct strbuf sb = STRBUF_INIT;
1888 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1889 apply_status = fall_back_threeway(state, sb.buf);
1890 strbuf_release(&sb);
1893 * Applying the patch to an earlier tree and merging
1894 * the result may have produced the same tree as ours.
1896 if (!apply_status &&
1897 !repo_index_has_changes(the_repository, NULL, NULL)) {
1898 say(state, stdout, _("No changes -- Patch already applied."));
1899 goto next;
1903 if (apply_status) {
1904 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1905 linelen(state->msg), state->msg);
1907 if (advice_enabled(ADVICE_AM_WORK_DIR))
1908 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
1910 die_user_resolve(state);
1913 commit:
1914 do_commit(state);
1916 next:
1917 am_next(state);
1919 if (resume)
1920 am_load(state);
1921 resume = 0;
1924 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
1925 assert(state->rebasing);
1926 copy_notes_for_rebase(state);
1927 run_post_rewrite_hook(state);
1931 * In rebasing mode, it's up to the caller to take care of
1932 * housekeeping.
1934 if (!state->rebasing) {
1935 am_destroy(state);
1936 run_auto_maintenance(state->quiet);
1941 * Resume the current am session after patch application failure. The user did
1942 * all the hard work, and we do not have to do any patch application. Just
1943 * trust and commit what the user has in the index and working tree. If `allow_empty`
1944 * is true, commit as an empty commit when index has not changed and lacking a patch.
1946 static void am_resolve(struct am_state *state, int allow_empty)
1948 validate_resume_state(state);
1950 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1952 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
1953 if (allow_empty && is_empty_or_missing_file(am_path(state, "patch"))) {
1954 printf_ln(_("No changes - recorded it as an empty commit."));
1955 } else {
1956 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1957 "If there is nothing left to stage, chances are that something else\n"
1958 "already introduced the same changes; you might want to skip this patch."));
1959 die_user_resolve(state);
1963 if (unmerged_index(the_repository->index)) {
1964 printf_ln(_("You still have unmerged paths in your index.\n"
1965 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1966 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1967 die_user_resolve(state);
1970 if (state->interactive) {
1971 write_index_patch(state);
1972 if (do_interactive(state))
1973 goto next;
1976 repo_rerere(the_repository, 0);
1978 do_commit(state);
1980 next:
1981 am_next(state);
1982 am_load(state);
1983 am_run(state, 0);
1987 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1988 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1989 * failure.
1991 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1993 struct lock_file lock_file = LOCK_INIT;
1994 struct unpack_trees_options opts;
1995 struct tree_desc t[2];
1997 if (parse_tree(head) || parse_tree(remote))
1998 return -1;
2000 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
2002 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
2004 memset(&opts, 0, sizeof(opts));
2005 opts.head_idx = 1;
2006 opts.src_index = the_repository->index;
2007 opts.dst_index = the_repository->index;
2008 opts.update = 1;
2009 opts.merge = 1;
2010 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
2011 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
2012 opts.fn = twoway_merge;
2013 init_tree_desc(&t[0], &head->object.oid, head->buffer, head->size);
2014 init_tree_desc(&t[1], &remote->object.oid, remote->buffer, remote->size);
2016 if (unpack_trees(2, t, &opts)) {
2017 rollback_lock_file(&lock_file);
2018 return -1;
2021 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
2022 die(_("unable to write new index file"));
2024 return 0;
2028 * Merges a tree into the index. The index's stat info will take precedence
2029 * over the merged tree's. Returns 0 on success, -1 on failure.
2031 static int merge_tree(struct tree *tree)
2033 struct lock_file lock_file = LOCK_INIT;
2034 struct unpack_trees_options opts;
2035 struct tree_desc t[1];
2037 if (parse_tree(tree))
2038 return -1;
2040 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
2042 memset(&opts, 0, sizeof(opts));
2043 opts.head_idx = 1;
2044 opts.src_index = the_repository->index;
2045 opts.dst_index = the_repository->index;
2046 opts.merge = 1;
2047 opts.fn = oneway_merge;
2048 init_tree_desc(&t[0], &tree->object.oid, tree->buffer, tree->size);
2050 if (unpack_trees(1, t, &opts)) {
2051 rollback_lock_file(&lock_file);
2052 return -1;
2055 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
2056 die(_("unable to write new index file"));
2058 return 0;
2062 * Clean the index without touching entries that are not modified between
2063 * `head` and `remote`.
2065 static int clean_index(const struct object_id *head, const struct object_id *remote)
2067 struct tree *head_tree, *remote_tree, *index_tree;
2068 struct object_id index;
2070 head_tree = parse_tree_indirect(head);
2071 if (!head_tree)
2072 return error(_("Could not parse object '%s'."), oid_to_hex(head));
2074 remote_tree = parse_tree_indirect(remote);
2075 if (!remote_tree)
2076 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
2078 repo_read_index_unmerged(the_repository);
2080 if (fast_forward_to(head_tree, head_tree, 1))
2081 return -1;
2083 if (write_index_as_tree(&index, the_repository->index,
2084 repo_get_index_file(the_repository),
2085 0, NULL))
2086 return -1;
2088 index_tree = parse_tree_indirect(&index);
2089 if (!index_tree)
2090 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
2092 if (fast_forward_to(index_tree, remote_tree, 0))
2093 return -1;
2095 if (merge_tree(remote_tree))
2096 return -1;
2098 remove_branch_state(the_repository, 0);
2100 return 0;
2104 * Resets rerere's merge resolution metadata.
2106 static void am_rerere_clear(void)
2108 struct string_list merge_rr = STRING_LIST_INIT_DUP;
2109 rerere_clear(the_repository, &merge_rr);
2110 string_list_clear(&merge_rr, 1);
2114 * Resume the current am session by skipping the current patch.
2116 static void am_skip(struct am_state *state)
2118 struct object_id head;
2120 am_rerere_clear();
2122 if (repo_get_oid(the_repository, "HEAD", &head))
2123 oidcpy(&head, the_hash_algo->empty_tree);
2125 if (clean_index(&head, &head))
2126 die(_("failed to clean index"));
2128 if (state->rebasing) {
2129 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2131 assert(!is_null_oid(&state->orig_commit));
2132 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2133 fprintf(fp, "%s\n", oid_to_hex(&head));
2134 fclose(fp);
2137 am_next(state);
2138 am_load(state);
2139 am_run(state, 0);
2143 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2145 * It is not safe to reset HEAD when:
2146 * 1. git-am previously failed because the index was dirty.
2147 * 2. HEAD has moved since git-am previously failed.
2149 static int safe_to_abort(const struct am_state *state)
2151 struct strbuf sb = STRBUF_INIT;
2152 struct object_id abort_safety, head;
2154 if (file_exists(am_path(state, "dirtyindex")))
2155 return 0;
2157 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2158 if (get_oid_hex(sb.buf, &abort_safety))
2159 die(_("could not parse %s"), am_path(state, "abort-safety"));
2160 } else
2161 oidclr(&abort_safety, the_repository->hash_algo);
2162 strbuf_release(&sb);
2164 if (repo_get_oid(the_repository, "HEAD", &head))
2165 oidclr(&head, the_repository->hash_algo);
2167 if (oideq(&head, &abort_safety))
2168 return 1;
2170 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2171 "Not rewinding to ORIG_HEAD"));
2173 return 0;
2177 * Aborts the current am session if it is safe to do so.
2179 static void am_abort(struct am_state *state)
2181 struct object_id curr_head, orig_head;
2182 int has_curr_head, has_orig_head;
2183 char *curr_branch;
2185 if (!safe_to_abort(state)) {
2186 am_destroy(state);
2187 return;
2190 am_rerere_clear();
2192 curr_branch = refs_resolve_refdup(get_main_ref_store(the_repository),
2193 "HEAD", 0, &curr_head, NULL);
2194 has_curr_head = curr_branch && !is_null_oid(&curr_head);
2195 if (!has_curr_head)
2196 oidcpy(&curr_head, the_hash_algo->empty_tree);
2198 has_orig_head = !repo_get_oid(the_repository, "ORIG_HEAD", &orig_head);
2199 if (!has_orig_head)
2200 oidcpy(&orig_head, the_hash_algo->empty_tree);
2202 if (clean_index(&curr_head, &orig_head))
2203 die(_("failed to clean index"));
2205 if (has_orig_head)
2206 refs_update_ref(get_main_ref_store(the_repository),
2207 "am --abort", "HEAD", &orig_head,
2208 has_curr_head ? &curr_head : NULL, 0,
2209 UPDATE_REFS_DIE_ON_ERR);
2210 else if (curr_branch)
2211 refs_delete_ref(get_main_ref_store(the_repository), NULL,
2212 curr_branch, NULL, REF_NO_DEREF);
2214 free(curr_branch);
2215 am_destroy(state);
2218 static int show_patch(struct am_state *state, enum resume_type resume_mode)
2220 struct strbuf sb = STRBUF_INIT;
2221 const char *patch_path;
2222 int len;
2224 if (!is_null_oid(&state->orig_commit)) {
2225 struct child_process cmd = CHILD_PROCESS_INIT;
2227 strvec_pushl(&cmd.args, "show", oid_to_hex(&state->orig_commit),
2228 "--", NULL);
2229 cmd.git_cmd = 1;
2230 return run_command(&cmd);
2233 switch (resume_mode) {
2234 case RESUME_SHOW_PATCH_RAW:
2235 patch_path = am_path(state, msgnum(state));
2236 break;
2237 case RESUME_SHOW_PATCH_DIFF:
2238 patch_path = am_path(state, "patch");
2239 break;
2240 default:
2241 BUG("invalid mode for --show-current-patch");
2244 len = strbuf_read_file(&sb, patch_path, 0);
2245 if (len < 0)
2246 die_errno(_("failed to read '%s'"), patch_path);
2248 setup_pager();
2249 write_in_full(1, sb.buf, sb.len);
2250 strbuf_release(&sb);
2251 return 0;
2255 * parse_options() callback that validates and sets opt->value to the
2256 * PATCH_FORMAT_* enum value corresponding to `arg`.
2258 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2260 int *opt_value = opt->value;
2262 if (unset)
2263 *opt_value = PATCH_FORMAT_UNKNOWN;
2264 else if (!strcmp(arg, "mbox"))
2265 *opt_value = PATCH_FORMAT_MBOX;
2266 else if (!strcmp(arg, "stgit"))
2267 *opt_value = PATCH_FORMAT_STGIT;
2268 else if (!strcmp(arg, "stgit-series"))
2269 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2270 else if (!strcmp(arg, "hg"))
2271 *opt_value = PATCH_FORMAT_HG;
2272 else if (!strcmp(arg, "mboxrd"))
2273 *opt_value = PATCH_FORMAT_MBOXRD;
2275 * Please update $__git_patchformat in git-completion.bash
2276 * when you add new options
2278 else
2279 return error(_("invalid value for '%s': '%s'"),
2280 "--patch-format", arg);
2281 return 0;
2284 static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2286 int *opt_value = opt->value;
2288 BUG_ON_OPT_NEG(unset);
2290 if (!arg)
2291 *opt_value = opt->defval;
2292 else if (!strcmp(arg, "raw"))
2293 *opt_value = RESUME_SHOW_PATCH_RAW;
2294 else if (!strcmp(arg, "diff"))
2295 *opt_value = RESUME_SHOW_PATCH_DIFF;
2297 * Please update $__git_showcurrentpatch in git-completion.bash
2298 * when you add new options
2300 else
2301 return error(_("invalid value for '%s': '%s'"),
2302 "--show-current-patch", arg);
2303 return 0;
2306 int cmd_am(int argc,
2307 const char **argv,
2308 const char *prefix,
2309 struct repository *repo UNUSED)
2311 struct am_state state;
2312 int binary = -1;
2313 int keep_cr = -1;
2314 int patch_format = PATCH_FORMAT_UNKNOWN;
2315 enum resume_type resume_mode = RESUME_FALSE;
2316 int in_progress;
2317 int ret = 0;
2319 const char * const usage[] = {
2320 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2321 N_("git am [<options>] (--continue | --skip | --abort)"),
2322 NULL
2325 struct option options[] = {
2326 OPT_BOOL('i', "interactive", &state.interactive,
2327 N_("run interactively")),
2328 OPT_BOOL('n', "no-verify", &state.no_verify,
2329 N_("bypass pre-applypatch and applypatch-msg hooks")),
2330 OPT_HIDDEN_BOOL('b', "binary", &binary,
2331 N_("historical option -- no-op")),
2332 OPT_BOOL('3', "3way", &state.threeway,
2333 N_("allow fall back on 3way merging if needed")),
2334 OPT__QUIET(&state.quiet, N_("be quiet")),
2335 OPT_SET_INT('s', "signoff", &state.signoff,
2336 N_("add a Signed-off-by trailer to the commit message"),
2337 SIGNOFF_EXPLICIT),
2338 OPT_BOOL('u', "utf8", &state.utf8,
2339 N_("recode into utf8 (default)")),
2340 OPT_SET_INT('k', "keep", &state.keep,
2341 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2342 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2343 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2344 OPT_BOOL('m', "message-id", &state.message_id,
2345 N_("pass -m flag to git-mailinfo")),
2346 OPT_SET_INT(0, "keep-cr", &keep_cr,
2347 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2349 OPT_BOOL('c', "scissors", &state.scissors,
2350 N_("strip everything before a scissors line")),
2351 OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2352 N_("pass it through git-mailinfo"),
2353 PARSE_OPT_NONEG, am_option_parse_quoted_cr),
2354 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2355 N_("pass it through git-apply"),
2357 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2358 N_("pass it through git-apply"),
2359 PARSE_OPT_NOARG),
2360 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2361 N_("pass it through git-apply"),
2362 PARSE_OPT_NOARG),
2363 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2364 N_("pass it through git-apply"),
2366 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2367 N_("pass it through git-apply"),
2369 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2370 N_("pass it through git-apply"),
2372 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2373 N_("pass it through git-apply"),
2375 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2376 N_("pass it through git-apply"),
2378 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2379 N_("format the patch(es) are in"),
2380 parse_opt_patchformat),
2381 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2382 N_("pass it through git-apply"),
2383 PARSE_OPT_NOARG),
2384 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2385 N_("override error message when patch failure occurs")),
2386 OPT_CMDMODE(0, "continue", &resume_mode,
2387 N_("continue applying patches after resolving a conflict"),
2388 RESUME_RESOLVED),
2389 OPT_CMDMODE('r', "resolved", &resume_mode,
2390 N_("synonyms for --continue"),
2391 RESUME_RESOLVED),
2392 OPT_CMDMODE(0, "skip", &resume_mode,
2393 N_("skip the current patch"),
2394 RESUME_SKIP),
2395 OPT_CMDMODE(0, "abort", &resume_mode,
2396 N_("restore the original branch and abort the patching operation"),
2397 RESUME_ABORT),
2398 OPT_CMDMODE(0, "quit", &resume_mode,
2399 N_("abort the patching operation but keep HEAD where it is"),
2400 RESUME_QUIT),
2401 { OPTION_CALLBACK, 0, "show-current-patch", &resume_mode,
2402 "(diff|raw)",
2403 N_("show the patch being applied"),
2404 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2405 parse_opt_show_current_patch, RESUME_SHOW_PATCH_RAW },
2406 OPT_CMDMODE(0, "retry", &resume_mode,
2407 N_("try to apply current patch again"),
2408 RESUME_APPLY),
2409 OPT_CMDMODE(0, "allow-empty", &resume_mode,
2410 N_("record the empty patch as an empty commit"),
2411 RESUME_ALLOW_EMPTY),
2412 OPT_BOOL(0, "committer-date-is-author-date",
2413 &state.committer_date_is_author_date,
2414 N_("lie about committer date")),
2415 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2416 N_("use current timestamp for author date")),
2417 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2418 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2419 N_("GPG-sign commits"),
2420 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2421 OPT_CALLBACK_F(0, "empty", &state.empty_type, "(stop|drop|keep)",
2422 N_("how to handle empty patches"),
2423 PARSE_OPT_NONEG, am_option_parse_empty),
2424 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2425 N_("(internal use for git-rebase)")),
2426 OPT_END()
2429 if (argc == 2 && !strcmp(argv[1], "-h"))
2430 usage_with_options(usage, options);
2432 git_config(git_default_config, NULL);
2434 am_state_init(&state);
2436 in_progress = am_in_progress(&state);
2437 if (in_progress)
2438 am_load(&state);
2440 argc = parse_options(argc, argv, prefix, options, usage, 0);
2442 if (binary >= 0)
2443 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2444 "it will be removed. Please do not use it anymore."));
2446 /* Ensure a valid committer ident can be constructed */
2447 git_committer_info(IDENT_STRICT);
2449 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
2450 die(_("failed to read the index"));
2452 if (in_progress) {
2454 * Catch user error to feed us patches when there is a session
2455 * in progress:
2457 * 1. mbox path(s) are provided on the command-line.
2458 * 2. stdin is not a tty: the user is trying to feed us a patch
2459 * from standard input. This is somewhat unreliable -- stdin
2460 * could be /dev/null for example and the caller did not
2461 * intend to feed us a patch but wanted to continue
2462 * unattended.
2464 if (argc || (resume_mode == RESUME_FALSE && !isatty(0)))
2465 die(_("previous rebase directory %s still exists but mbox given."),
2466 state.dir);
2468 if (resume_mode == RESUME_FALSE)
2469 resume_mode = RESUME_APPLY;
2471 if (state.signoff == SIGNOFF_EXPLICIT)
2472 am_append_signoff(&state);
2473 } else {
2474 struct strvec paths = STRVEC_INIT;
2475 int i;
2478 * Handle stray state directory in the independent-run case. In
2479 * the --rebasing case, it is up to the caller to take care of
2480 * stray directories.
2482 if (file_exists(state.dir) && !state.rebasing) {
2483 if (resume_mode == RESUME_ABORT || resume_mode == RESUME_QUIT) {
2484 am_destroy(&state);
2485 am_state_release(&state);
2486 return 0;
2489 die(_("Stray %s directory found.\n"
2490 "Use \"git am --abort\" to remove it."),
2491 state.dir);
2494 if (resume_mode)
2495 die(_("Resolve operation not in progress, we are not resuming."));
2497 for (i = 0; i < argc; i++) {
2498 if (is_absolute_path(argv[i]) || !prefix)
2499 strvec_push(&paths, argv[i]);
2500 else
2501 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2504 if (state.interactive && !paths.nr)
2505 die(_("interactive mode requires patches on the command line"));
2507 am_setup(&state, patch_format, paths.v, keep_cr);
2509 strvec_clear(&paths);
2512 switch (resume_mode) {
2513 case RESUME_FALSE:
2514 am_run(&state, 0);
2515 break;
2516 case RESUME_APPLY:
2517 am_run(&state, 1);
2518 break;
2519 case RESUME_RESOLVED:
2520 case RESUME_ALLOW_EMPTY:
2521 am_resolve(&state, resume_mode == RESUME_ALLOW_EMPTY ? 1 : 0);
2522 break;
2523 case RESUME_SKIP:
2524 am_skip(&state);
2525 break;
2526 case RESUME_ABORT:
2527 am_abort(&state);
2528 break;
2529 case RESUME_QUIT:
2530 am_rerere_clear();
2531 am_destroy(&state);
2532 break;
2533 case RESUME_SHOW_PATCH_RAW:
2534 case RESUME_SHOW_PATCH_DIFF:
2535 ret = show_patch(&state, resume_mode);
2536 break;
2537 default:
2538 BUG("invalid resume value");
2541 am_state_release(&state);
2543 return ret;