builtin-am: pass git-apply's options to git-apply
[git/mingw/j6t.git] / builtin / am.c
blobf842f69d3650c30ff5bf07247bb4d0e4e7ae9b02
1 /*
2 * Builtin "git am"
4 * Based on git-am.sh by Junio C Hamano.
5 */
6 #include "cache.h"
7 #include "builtin.h"
8 #include "exec_cmd.h"
9 #include "parse-options.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "quote.h"
13 #include "lockfile.h"
14 #include "cache-tree.h"
15 #include "refs.h"
16 #include "commit.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "unpack-trees.h"
20 #include "branch.h"
21 #include "sequencer.h"
22 #include "revision.h"
23 #include "merge-recursive.h"
24 #include "revision.h"
25 #include "log-tree.h"
27 /**
28 * Returns 1 if the file is empty or does not exist, 0 otherwise.
30 static int is_empty_file(const char *filename)
32 struct stat st;
34 if (stat(filename, &st) < 0) {
35 if (errno == ENOENT)
36 return 1;
37 die_errno(_("could not stat %s"), filename);
40 return !st.st_size;
43 /**
44 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
46 static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
48 if (strbuf_getwholeline(sb, fp, '\n'))
49 return EOF;
50 if (sb->buf[sb->len - 1] == '\n') {
51 strbuf_setlen(sb, sb->len - 1);
52 if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
53 strbuf_setlen(sb, sb->len - 1);
55 return 0;
58 /**
59 * Returns the length of the first line of msg.
61 static int linelen(const char *msg)
63 return strchrnul(msg, '\n') - msg;
66 enum patch_format {
67 PATCH_FORMAT_UNKNOWN = 0,
68 PATCH_FORMAT_MBOX
71 enum keep_type {
72 KEEP_FALSE = 0,
73 KEEP_TRUE, /* pass -k flag to git-mailinfo */
74 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
77 enum scissors_type {
78 SCISSORS_UNSET = -1,
79 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
80 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
83 struct am_state {
84 /* state directory path */
85 char *dir;
87 /* current and last patch numbers, 1-indexed */
88 int cur;
89 int last;
91 /* commit metadata and message */
92 char *author_name;
93 char *author_email;
94 char *author_date;
95 char *msg;
96 size_t msg_len;
98 /* number of digits in patch filename */
99 int prec;
101 /* various operating modes and command line options */
102 int threeway;
103 int quiet;
104 int signoff;
105 int utf8;
106 int keep; /* enum keep_type */
107 int message_id;
108 int scissors; /* enum scissors_type */
109 struct argv_array git_apply_opts;
110 const char *resolvemsg;
111 int rebasing;
115 * Initializes am_state with the default values. The state directory is set to
116 * dir.
118 static void am_state_init(struct am_state *state, const char *dir)
120 memset(state, 0, sizeof(*state));
122 assert(dir);
123 state->dir = xstrdup(dir);
125 state->prec = 4;
127 state->utf8 = 1;
129 git_config_get_bool("am.messageid", &state->message_id);
131 state->scissors = SCISSORS_UNSET;
133 argv_array_init(&state->git_apply_opts);
137 * Releases memory allocated by an am_state.
139 static void am_state_release(struct am_state *state)
141 free(state->dir);
142 free(state->author_name);
143 free(state->author_email);
144 free(state->author_date);
145 free(state->msg);
146 argv_array_clear(&state->git_apply_opts);
150 * Returns path relative to the am_state directory.
152 static inline const char *am_path(const struct am_state *state, const char *path)
154 return mkpath("%s/%s", state->dir, path);
158 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
159 * at the end.
161 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
163 va_list ap;
165 va_start(ap, fmt);
166 if (!state->quiet) {
167 vfprintf(fp, fmt, ap);
168 putc('\n', fp);
170 va_end(ap);
174 * Returns 1 if there is an am session in progress, 0 otherwise.
176 static int am_in_progress(const struct am_state *state)
178 struct stat st;
180 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
181 return 0;
182 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
183 return 0;
184 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
185 return 0;
186 return 1;
190 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
191 * number of bytes read on success, -1 if the file does not exist. If `trim` is
192 * set, trailing whitespace will be removed.
194 static int read_state_file(struct strbuf *sb, const struct am_state *state,
195 const char *file, int trim)
197 strbuf_reset(sb);
199 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
200 if (trim)
201 strbuf_trim(sb);
203 return sb->len;
206 if (errno == ENOENT)
207 return -1;
209 die_errno(_("could not read '%s'"), am_path(state, file));
213 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
214 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
215 * match `key`. Returns NULL on failure.
217 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
218 * the author-script.
220 static char *read_shell_var(FILE *fp, const char *key)
222 struct strbuf sb = STRBUF_INIT;
223 const char *str;
225 if (strbuf_getline(&sb, fp, '\n'))
226 goto fail;
228 if (!skip_prefix(sb.buf, key, &str))
229 goto fail;
231 if (!skip_prefix(str, "=", &str))
232 goto fail;
234 strbuf_remove(&sb, 0, str - sb.buf);
236 str = sq_dequote(sb.buf);
237 if (!str)
238 goto fail;
240 return strbuf_detach(&sb, NULL);
242 fail:
243 strbuf_release(&sb);
244 return NULL;
248 * Reads and parses the state directory's "author-script" file, and sets
249 * state->author_name, state->author_email and state->author_date accordingly.
250 * Returns 0 on success, -1 if the file could not be parsed.
252 * The author script is of the format:
254 * GIT_AUTHOR_NAME='$author_name'
255 * GIT_AUTHOR_EMAIL='$author_email'
256 * GIT_AUTHOR_DATE='$author_date'
258 * where $author_name, $author_email and $author_date are quoted. We are strict
259 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
260 * script, and thus if the file differs from what this function expects, it is
261 * better to bail out than to do something that the user does not expect.
263 static int read_author_script(struct am_state *state)
265 const char *filename = am_path(state, "author-script");
266 FILE *fp;
268 assert(!state->author_name);
269 assert(!state->author_email);
270 assert(!state->author_date);
272 fp = fopen(filename, "r");
273 if (!fp) {
274 if (errno == ENOENT)
275 return 0;
276 die_errno(_("could not open '%s' for reading"), filename);
279 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
280 if (!state->author_name) {
281 fclose(fp);
282 return -1;
285 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
286 if (!state->author_email) {
287 fclose(fp);
288 return -1;
291 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
292 if (!state->author_date) {
293 fclose(fp);
294 return -1;
297 if (fgetc(fp) != EOF) {
298 fclose(fp);
299 return -1;
302 fclose(fp);
303 return 0;
307 * Saves state->author_name, state->author_email and state->author_date in the
308 * state directory's "author-script" file.
310 static void write_author_script(const struct am_state *state)
312 struct strbuf sb = STRBUF_INIT;
314 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
315 sq_quote_buf(&sb, state->author_name);
316 strbuf_addch(&sb, '\n');
318 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
319 sq_quote_buf(&sb, state->author_email);
320 strbuf_addch(&sb, '\n');
322 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
323 sq_quote_buf(&sb, state->author_date);
324 strbuf_addch(&sb, '\n');
326 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
328 strbuf_release(&sb);
332 * Reads the commit message from the state directory's "final-commit" file,
333 * setting state->msg to its contents and state->msg_len to the length of its
334 * contents in bytes.
336 * Returns 0 on success, -1 if the file does not exist.
338 static int read_commit_msg(struct am_state *state)
340 struct strbuf sb = STRBUF_INIT;
342 assert(!state->msg);
344 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
345 strbuf_release(&sb);
346 return -1;
349 state->msg = strbuf_detach(&sb, &state->msg_len);
350 return 0;
354 * Saves state->msg in the state directory's "final-commit" file.
356 static void write_commit_msg(const struct am_state *state)
358 int fd;
359 const char *filename = am_path(state, "final-commit");
361 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
362 if (write_in_full(fd, state->msg, state->msg_len) < 0)
363 die_errno(_("could not write to %s"), filename);
364 close(fd);
368 * Loads state from disk.
370 static void am_load(struct am_state *state)
372 struct strbuf sb = STRBUF_INIT;
374 if (read_state_file(&sb, state, "next", 1) < 0)
375 die("BUG: state file 'next' does not exist");
376 state->cur = strtol(sb.buf, NULL, 10);
378 if (read_state_file(&sb, state, "last", 1) < 0)
379 die("BUG: state file 'last' does not exist");
380 state->last = strtol(sb.buf, NULL, 10);
382 if (read_author_script(state) < 0)
383 die(_("could not parse author script"));
385 read_commit_msg(state);
387 read_state_file(&sb, state, "threeway", 1);
388 state->threeway = !strcmp(sb.buf, "t");
390 read_state_file(&sb, state, "quiet", 1);
391 state->quiet = !strcmp(sb.buf, "t");
393 read_state_file(&sb, state, "sign", 1);
394 state->signoff = !strcmp(sb.buf, "t");
396 read_state_file(&sb, state, "utf8", 1);
397 state->utf8 = !strcmp(sb.buf, "t");
399 read_state_file(&sb, state, "keep", 1);
400 if (!strcmp(sb.buf, "t"))
401 state->keep = KEEP_TRUE;
402 else if (!strcmp(sb.buf, "b"))
403 state->keep = KEEP_NON_PATCH;
404 else
405 state->keep = KEEP_FALSE;
407 read_state_file(&sb, state, "messageid", 1);
408 state->message_id = !strcmp(sb.buf, "t");
410 read_state_file(&sb, state, "scissors", 1);
411 if (!strcmp(sb.buf, "t"))
412 state->scissors = SCISSORS_TRUE;
413 else if (!strcmp(sb.buf, "f"))
414 state->scissors = SCISSORS_FALSE;
415 else
416 state->scissors = SCISSORS_UNSET;
418 read_state_file(&sb, state, "apply-opt", 1);
419 argv_array_clear(&state->git_apply_opts);
420 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
421 die(_("could not parse %s"), am_path(state, "apply-opt"));
423 state->rebasing = !!file_exists(am_path(state, "rebasing"));
425 strbuf_release(&sb);
429 * Removes the am_state directory, forcefully terminating the current am
430 * session.
432 static void am_destroy(const struct am_state *state)
434 struct strbuf sb = STRBUF_INIT;
436 strbuf_addstr(&sb, state->dir);
437 remove_dir_recursively(&sb, 0);
438 strbuf_release(&sb);
442 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
443 * non-indented lines and checking if they look like they begin with valid
444 * header field names.
446 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
448 static int is_mail(FILE *fp)
450 const char *header_regex = "^[!-9;-~]+:";
451 struct strbuf sb = STRBUF_INIT;
452 regex_t regex;
453 int ret = 1;
455 if (fseek(fp, 0L, SEEK_SET))
456 die_errno(_("fseek failed"));
458 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
459 die("invalid pattern: %s", header_regex);
461 while (!strbuf_getline_crlf(&sb, fp)) {
462 if (!sb.len)
463 break; /* End of header */
465 /* Ignore indented folded lines */
466 if (*sb.buf == '\t' || *sb.buf == ' ')
467 continue;
469 /* It's a header if it matches header_regex */
470 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
471 ret = 0;
472 goto done;
476 done:
477 regfree(&regex);
478 strbuf_release(&sb);
479 return ret;
483 * Attempts to detect the patch_format of the patches contained in `paths`,
484 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
485 * detection fails.
487 static int detect_patch_format(const char **paths)
489 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
490 struct strbuf l1 = STRBUF_INIT;
491 FILE *fp;
494 * We default to mbox format if input is from stdin and for directories
496 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
497 return PATCH_FORMAT_MBOX;
500 * Otherwise, check the first few lines of the first patch, starting
501 * from the first non-blank line, to try to detect its format.
504 fp = xfopen(*paths, "r");
506 while (!strbuf_getline_crlf(&l1, fp)) {
507 if (l1.len)
508 break;
511 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
512 ret = PATCH_FORMAT_MBOX;
513 goto done;
516 if (l1.len && is_mail(fp)) {
517 ret = PATCH_FORMAT_MBOX;
518 goto done;
521 done:
522 fclose(fp);
523 strbuf_release(&l1);
524 return ret;
528 * Splits out individual email patches from `paths`, where each path is either
529 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
531 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
533 struct child_process cp = CHILD_PROCESS_INIT;
534 struct strbuf last = STRBUF_INIT;
536 cp.git_cmd = 1;
537 argv_array_push(&cp.args, "mailsplit");
538 argv_array_pushf(&cp.args, "-d%d", state->prec);
539 argv_array_pushf(&cp.args, "-o%s", state->dir);
540 argv_array_push(&cp.args, "-b");
541 if (keep_cr)
542 argv_array_push(&cp.args, "--keep-cr");
543 argv_array_push(&cp.args, "--");
544 argv_array_pushv(&cp.args, paths);
546 if (capture_command(&cp, &last, 8))
547 return -1;
549 state->cur = 1;
550 state->last = strtol(last.buf, NULL, 10);
552 return 0;
556 * Splits a list of files/directories into individual email patches. Each path
557 * in `paths` must be a file/directory that is formatted according to
558 * `patch_format`.
560 * Once split out, the individual email patches will be stored in the state
561 * directory, with each patch's filename being its index, padded to state->prec
562 * digits.
564 * state->cur will be set to the index of the first mail, and state->last will
565 * be set to the index of the last mail.
567 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
568 * to disable this behavior, -1 to use the default configured setting.
570 * Returns 0 on success, -1 on failure.
572 static int split_mail(struct am_state *state, enum patch_format patch_format,
573 const char **paths, int keep_cr)
575 if (keep_cr < 0) {
576 keep_cr = 0;
577 git_config_get_bool("am.keepcr", &keep_cr);
580 switch (patch_format) {
581 case PATCH_FORMAT_MBOX:
582 return split_mail_mbox(state, paths, keep_cr);
583 default:
584 die("BUG: invalid patch_format");
586 return -1;
590 * Setup a new am session for applying patches
592 static void am_setup(struct am_state *state, enum patch_format patch_format,
593 const char **paths, int keep_cr)
595 unsigned char curr_head[GIT_SHA1_RAWSZ];
596 const char *str;
597 struct strbuf sb = STRBUF_INIT;
599 if (!patch_format)
600 patch_format = detect_patch_format(paths);
602 if (!patch_format) {
603 fprintf_ln(stderr, _("Patch format detection failed."));
604 exit(128);
607 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
608 die_errno(_("failed to create directory '%s'"), state->dir);
610 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
611 am_destroy(state);
612 die(_("Failed to split patches."));
615 if (state->rebasing)
616 state->threeway = 1;
618 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
620 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
622 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
624 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
626 switch (state->keep) {
627 case KEEP_FALSE:
628 str = "f";
629 break;
630 case KEEP_TRUE:
631 str = "t";
632 break;
633 case KEEP_NON_PATCH:
634 str = "b";
635 break;
636 default:
637 die("BUG: invalid value for state->keep");
640 write_file(am_path(state, "keep"), 1, "%s", str);
642 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
644 switch (state->scissors) {
645 case SCISSORS_UNSET:
646 str = "";
647 break;
648 case SCISSORS_FALSE:
649 str = "f";
650 break;
651 case SCISSORS_TRUE:
652 str = "t";
653 break;
654 default:
655 die("BUG: invalid value for state->scissors");
658 write_file(am_path(state, "scissors"), 1, "%s", str);
660 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
661 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
663 if (state->rebasing)
664 write_file(am_path(state, "rebasing"), 1, "%s", "");
665 else
666 write_file(am_path(state, "applying"), 1, "%s", "");
668 if (!get_sha1("HEAD", curr_head)) {
669 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
670 if (!state->rebasing)
671 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
672 UPDATE_REFS_DIE_ON_ERR);
673 } else {
674 write_file(am_path(state, "abort-safety"), 1, "%s", "");
675 if (!state->rebasing)
676 delete_ref("ORIG_HEAD", NULL, 0);
680 * NOTE: Since the "next" and "last" files determine if an am_state
681 * session is in progress, they should be written last.
684 write_file(am_path(state, "next"), 1, "%d", state->cur);
686 write_file(am_path(state, "last"), 1, "%d", state->last);
688 strbuf_release(&sb);
692 * Increments the patch pointer, and cleans am_state for the application of the
693 * next patch.
695 static void am_next(struct am_state *state)
697 unsigned char head[GIT_SHA1_RAWSZ];
699 free(state->author_name);
700 state->author_name = NULL;
702 free(state->author_email);
703 state->author_email = NULL;
705 free(state->author_date);
706 state->author_date = NULL;
708 free(state->msg);
709 state->msg = NULL;
710 state->msg_len = 0;
712 unlink(am_path(state, "author-script"));
713 unlink(am_path(state, "final-commit"));
715 if (!get_sha1("HEAD", head))
716 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
717 else
718 write_file(am_path(state, "abort-safety"), 1, "%s", "");
720 state->cur++;
721 write_file(am_path(state, "next"), 1, "%d", state->cur);
725 * Returns the filename of the current patch email.
727 static const char *msgnum(const struct am_state *state)
729 static struct strbuf sb = STRBUF_INIT;
731 strbuf_reset(&sb);
732 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
734 return sb.buf;
738 * Refresh and write index.
740 static void refresh_and_write_cache(void)
742 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
744 hold_locked_index(lock_file, 1);
745 refresh_cache(REFRESH_QUIET);
746 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
747 die(_("unable to write index file"));
751 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
752 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
753 * strbuf is provided, the space-separated list of files that differ will be
754 * appended to it.
756 static int index_has_changes(struct strbuf *sb)
758 unsigned char head[GIT_SHA1_RAWSZ];
759 int i;
761 if (!get_sha1_tree("HEAD", head)) {
762 struct diff_options opt;
764 diff_setup(&opt);
765 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
766 if (!sb)
767 DIFF_OPT_SET(&opt, QUICK);
768 do_diff_cache(head, &opt);
769 diffcore_std(&opt);
770 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
771 if (i)
772 strbuf_addch(sb, ' ');
773 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
775 diff_flush(&opt);
776 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
777 } else {
778 for (i = 0; sb && i < active_nr; i++) {
779 if (i)
780 strbuf_addch(sb, ' ');
781 strbuf_addstr(sb, active_cache[i]->name);
783 return !!active_nr;
788 * Dies with a user-friendly message on how to proceed after resolving the
789 * problem. This message can be overridden with state->resolvemsg.
791 static void NORETURN die_user_resolve(const struct am_state *state)
793 if (state->resolvemsg) {
794 printf_ln("%s", state->resolvemsg);
795 } else {
796 const char *cmdline = "git am";
798 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
799 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
800 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
803 exit(128);
807 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
808 * state->msg will be set to the patch message. state->author_name,
809 * state->author_email and state->author_date will be set to the patch author's
810 * name, email and date respectively. The patch body will be written to the
811 * state directory's "patch" file.
813 * Returns 1 if the patch should be skipped, 0 otherwise.
815 static int parse_mail(struct am_state *state, const char *mail)
817 FILE *fp;
818 struct child_process cp = CHILD_PROCESS_INIT;
819 struct strbuf sb = STRBUF_INIT;
820 struct strbuf msg = STRBUF_INIT;
821 struct strbuf author_name = STRBUF_INIT;
822 struct strbuf author_date = STRBUF_INIT;
823 struct strbuf author_email = STRBUF_INIT;
824 int ret = 0;
826 cp.git_cmd = 1;
827 cp.in = xopen(mail, O_RDONLY, 0);
828 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
830 argv_array_push(&cp.args, "mailinfo");
831 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
833 switch (state->keep) {
834 case KEEP_FALSE:
835 break;
836 case KEEP_TRUE:
837 argv_array_push(&cp.args, "-k");
838 break;
839 case KEEP_NON_PATCH:
840 argv_array_push(&cp.args, "-b");
841 break;
842 default:
843 die("BUG: invalid value for state->keep");
846 if (state->message_id)
847 argv_array_push(&cp.args, "-m");
849 switch (state->scissors) {
850 case SCISSORS_UNSET:
851 break;
852 case SCISSORS_FALSE:
853 argv_array_push(&cp.args, "--no-scissors");
854 break;
855 case SCISSORS_TRUE:
856 argv_array_push(&cp.args, "--scissors");
857 break;
858 default:
859 die("BUG: invalid value for state->scissors");
862 argv_array_push(&cp.args, am_path(state, "msg"));
863 argv_array_push(&cp.args, am_path(state, "patch"));
865 if (run_command(&cp) < 0)
866 die("could not parse patch");
868 close(cp.in);
869 close(cp.out);
871 /* Extract message and author information */
872 fp = xfopen(am_path(state, "info"), "r");
873 while (!strbuf_getline(&sb, fp, '\n')) {
874 const char *x;
876 if (skip_prefix(sb.buf, "Subject: ", &x)) {
877 if (msg.len)
878 strbuf_addch(&msg, '\n');
879 strbuf_addstr(&msg, x);
880 } else if (skip_prefix(sb.buf, "Author: ", &x))
881 strbuf_addstr(&author_name, x);
882 else if (skip_prefix(sb.buf, "Email: ", &x))
883 strbuf_addstr(&author_email, x);
884 else if (skip_prefix(sb.buf, "Date: ", &x))
885 strbuf_addstr(&author_date, x);
887 fclose(fp);
889 /* Skip pine's internal folder data */
890 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
891 ret = 1;
892 goto finish;
895 if (is_empty_file(am_path(state, "patch"))) {
896 printf_ln(_("Patch is empty. Was it split wrong?"));
897 die_user_resolve(state);
900 strbuf_addstr(&msg, "\n\n");
901 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
902 die_errno(_("could not read '%s'"), am_path(state, "msg"));
903 stripspace(&msg, 0);
905 if (state->signoff)
906 append_signoff(&msg, 0, 0);
908 assert(!state->author_name);
909 state->author_name = strbuf_detach(&author_name, NULL);
911 assert(!state->author_email);
912 state->author_email = strbuf_detach(&author_email, NULL);
914 assert(!state->author_date);
915 state->author_date = strbuf_detach(&author_date, NULL);
917 assert(!state->msg);
918 state->msg = strbuf_detach(&msg, &state->msg_len);
920 finish:
921 strbuf_release(&msg);
922 strbuf_release(&author_date);
923 strbuf_release(&author_email);
924 strbuf_release(&author_name);
925 strbuf_release(&sb);
926 return ret;
930 * Sets commit_id to the commit hash where the mail was generated from.
931 * Returns 0 on success, -1 on failure.
933 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
935 struct strbuf sb = STRBUF_INIT;
936 FILE *fp = xfopen(mail, "r");
937 const char *x;
939 if (strbuf_getline(&sb, fp, '\n'))
940 return -1;
942 if (!skip_prefix(sb.buf, "From ", &x))
943 return -1;
945 if (get_sha1_hex(x, commit_id) < 0)
946 return -1;
948 strbuf_release(&sb);
949 fclose(fp);
950 return 0;
954 * Sets state->msg, state->author_name, state->author_email, state->author_date
955 * to the commit's respective info.
957 static void get_commit_info(struct am_state *state, struct commit *commit)
959 const char *buffer, *ident_line, *author_date, *msg;
960 size_t ident_len;
961 struct ident_split ident_split;
962 struct strbuf sb = STRBUF_INIT;
964 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
966 ident_line = find_commit_header(buffer, "author", &ident_len);
968 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
969 strbuf_add(&sb, ident_line, ident_len);
970 die(_("invalid ident line: %s"), sb.buf);
973 assert(!state->author_name);
974 if (ident_split.name_begin) {
975 strbuf_add(&sb, ident_split.name_begin,
976 ident_split.name_end - ident_split.name_begin);
977 state->author_name = strbuf_detach(&sb, NULL);
978 } else
979 state->author_name = xstrdup("");
981 assert(!state->author_email);
982 if (ident_split.mail_begin) {
983 strbuf_add(&sb, ident_split.mail_begin,
984 ident_split.mail_end - ident_split.mail_begin);
985 state->author_email = strbuf_detach(&sb, NULL);
986 } else
987 state->author_email = xstrdup("");
989 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
990 strbuf_addstr(&sb, author_date);
991 assert(!state->author_date);
992 state->author_date = strbuf_detach(&sb, NULL);
994 assert(!state->msg);
995 msg = strstr(buffer, "\n\n");
996 if (!msg)
997 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
998 state->msg = xstrdup(msg + 2);
999 state->msg_len = strlen(state->msg);
1003 * Writes `commit` as a patch to the state directory's "patch" file.
1005 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1007 struct rev_info rev_info;
1008 FILE *fp;
1010 fp = xfopen(am_path(state, "patch"), "w");
1011 init_revisions(&rev_info, NULL);
1012 rev_info.diff = 1;
1013 rev_info.abbrev = 0;
1014 rev_info.disable_stdin = 1;
1015 rev_info.show_root_diff = 1;
1016 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1017 rev_info.no_commit_id = 1;
1018 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1019 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1020 rev_info.diffopt.use_color = 0;
1021 rev_info.diffopt.file = fp;
1022 rev_info.diffopt.close_file = 1;
1023 add_pending_object(&rev_info, &commit->object, "");
1024 diff_setup_done(&rev_info.diffopt);
1025 log_tree_commit(&rev_info, commit);
1029 * Like parse_mail(), but parses the mail by looking up its commit ID
1030 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1031 * of patches.
1033 * Will always return 0 as the patch should never be skipped.
1035 static int parse_mail_rebase(struct am_state *state, const char *mail)
1037 struct commit *commit;
1038 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1040 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1041 die(_("could not parse %s"), mail);
1043 commit = lookup_commit_or_die(commit_sha1, mail);
1045 get_commit_info(state, commit);
1047 write_commit_patch(state, commit);
1049 return 0;
1053 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1054 * `index_file` is not NULL, the patch will be applied to that index.
1056 static int run_apply(const struct am_state *state, const char *index_file)
1058 struct child_process cp = CHILD_PROCESS_INIT;
1060 cp.git_cmd = 1;
1062 if (index_file)
1063 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1066 * If we are allowed to fall back on 3-way merge, don't give false
1067 * errors during the initial attempt.
1069 if (state->threeway && !index_file) {
1070 cp.no_stdout = 1;
1071 cp.no_stderr = 1;
1074 argv_array_push(&cp.args, "apply");
1076 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1078 if (index_file)
1079 argv_array_push(&cp.args, "--cached");
1080 else
1081 argv_array_push(&cp.args, "--index");
1083 argv_array_push(&cp.args, am_path(state, "patch"));
1085 if (run_command(&cp))
1086 return -1;
1088 /* Reload index as git-apply will have modified it. */
1089 discard_cache();
1090 read_cache_from(index_file ? index_file : get_index_file());
1092 return 0;
1096 * Builds an index that contains just the blobs needed for a 3way merge.
1098 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1100 struct child_process cp = CHILD_PROCESS_INIT;
1102 cp.git_cmd = 1;
1103 argv_array_push(&cp.args, "apply");
1104 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1105 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1106 argv_array_push(&cp.args, am_path(state, "patch"));
1108 if (run_command(&cp))
1109 return -1;
1111 return 0;
1115 * Attempt a threeway merge, using index_path as the temporary index.
1117 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1119 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1120 our_tree[GIT_SHA1_RAWSZ];
1121 const unsigned char *bases[1] = {orig_tree};
1122 struct merge_options o;
1123 struct commit *result;
1124 char *his_tree_name;
1126 if (get_sha1("HEAD", our_tree) < 0)
1127 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1129 if (build_fake_ancestor(state, index_path))
1130 return error("could not build fake ancestor");
1132 discard_cache();
1133 read_cache_from(index_path);
1135 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1136 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1138 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1140 if (!state->quiet) {
1142 * List paths that needed 3-way fallback, so that the user can
1143 * review them with extra care to spot mismerges.
1145 struct rev_info rev_info;
1146 const char *diff_filter_str = "--diff-filter=AM";
1148 init_revisions(&rev_info, NULL);
1149 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1150 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1151 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1152 diff_setup_done(&rev_info.diffopt);
1153 run_diff_index(&rev_info, 1);
1156 if (run_apply(state, index_path))
1157 return error(_("Did you hand edit your patch?\n"
1158 "It does not apply to blobs recorded in its index."));
1160 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1161 return error("could not write tree");
1163 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1165 discard_cache();
1166 read_cache();
1169 * This is not so wrong. Depending on which base we picked, orig_tree
1170 * may be wildly different from ours, but his_tree has the same set of
1171 * wildly different changes in parts the patch did not touch, so
1172 * recursive ends up canceling them, saying that we reverted all those
1173 * changes.
1176 init_merge_options(&o);
1178 o.branch1 = "HEAD";
1179 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1180 o.branch2 = his_tree_name;
1182 if (state->quiet)
1183 o.verbosity = 0;
1185 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1186 free(his_tree_name);
1187 return error(_("Failed to merge in the changes."));
1190 free(his_tree_name);
1191 return 0;
1195 * Commits the current index with state->msg as the commit message and
1196 * state->author_name, state->author_email and state->author_date as the author
1197 * information.
1199 static void do_commit(const struct am_state *state)
1201 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1202 commit[GIT_SHA1_RAWSZ];
1203 unsigned char *ptr;
1204 struct commit_list *parents = NULL;
1205 const char *reflog_msg, *author;
1206 struct strbuf sb = STRBUF_INIT;
1208 if (write_cache_as_tree(tree, 0, NULL))
1209 die(_("git write-tree failed to write a tree"));
1211 if (!get_sha1_commit("HEAD", parent)) {
1212 ptr = parent;
1213 commit_list_insert(lookup_commit(parent), &parents);
1214 } else {
1215 ptr = NULL;
1216 say(state, stderr, _("applying to an empty history"));
1219 author = fmt_ident(state->author_name, state->author_email,
1220 state->author_date, IDENT_STRICT);
1222 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1223 author, NULL))
1224 die(_("failed to write commit object"));
1226 reflog_msg = getenv("GIT_REFLOG_ACTION");
1227 if (!reflog_msg)
1228 reflog_msg = "am";
1230 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1231 state->msg);
1233 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1235 strbuf_release(&sb);
1239 * Validates the am_state for resuming -- the "msg" and authorship fields must
1240 * be filled up.
1242 static void validate_resume_state(const struct am_state *state)
1244 if (!state->msg)
1245 die(_("cannot resume: %s does not exist."),
1246 am_path(state, "final-commit"));
1248 if (!state->author_name || !state->author_email || !state->author_date)
1249 die(_("cannot resume: %s does not exist."),
1250 am_path(state, "author-script"));
1254 * Applies all queued mail.
1256 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1257 * well as the state directory's "patch" file is used as-is for applying the
1258 * patch and committing it.
1260 static void am_run(struct am_state *state, int resume)
1262 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1263 struct strbuf sb = STRBUF_INIT;
1265 unlink(am_path(state, "dirtyindex"));
1267 refresh_and_write_cache();
1269 if (index_has_changes(&sb)) {
1270 write_file(am_path(state, "dirtyindex"), 1, "t");
1271 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1274 strbuf_release(&sb);
1276 while (state->cur <= state->last) {
1277 const char *mail = am_path(state, msgnum(state));
1278 int apply_status;
1280 if (!file_exists(mail))
1281 goto next;
1283 if (resume) {
1284 validate_resume_state(state);
1285 resume = 0;
1286 } else {
1287 int skip;
1289 if (state->rebasing)
1290 skip = parse_mail_rebase(state, mail);
1291 else
1292 skip = parse_mail(state, mail);
1294 if (skip)
1295 goto next; /* mail should be skipped */
1297 write_author_script(state);
1298 write_commit_msg(state);
1301 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1303 apply_status = run_apply(state, NULL);
1305 if (apply_status && state->threeway) {
1306 struct strbuf sb = STRBUF_INIT;
1308 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1309 apply_status = fall_back_threeway(state, sb.buf);
1310 strbuf_release(&sb);
1313 * Applying the patch to an earlier tree and merging
1314 * the result may have produced the same tree as ours.
1316 if (!apply_status && !index_has_changes(NULL)) {
1317 say(state, stdout, _("No changes -- Patch already applied."));
1318 goto next;
1322 if (apply_status) {
1323 int advice_amworkdir = 1;
1325 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1326 linelen(state->msg), state->msg);
1328 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1330 if (advice_amworkdir)
1331 printf_ln(_("The copy of the patch that failed is found in: %s"),
1332 am_path(state, "patch"));
1334 die_user_resolve(state);
1337 do_commit(state);
1339 next:
1340 am_next(state);
1344 * In rebasing mode, it's up to the caller to take care of
1345 * housekeeping.
1347 if (!state->rebasing) {
1348 am_destroy(state);
1349 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1354 * Resume the current am session after patch application failure. The user did
1355 * all the hard work, and we do not have to do any patch application. Just
1356 * trust and commit what the user has in the index and working tree.
1358 static void am_resolve(struct am_state *state)
1360 validate_resume_state(state);
1362 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1364 if (!index_has_changes(NULL)) {
1365 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1366 "If there is nothing left to stage, chances are that something else\n"
1367 "already introduced the same changes; you might want to skip this patch."));
1368 die_user_resolve(state);
1371 if (unmerged_cache()) {
1372 printf_ln(_("You still have unmerged paths in your index.\n"
1373 "Did you forget to use 'git add'?"));
1374 die_user_resolve(state);
1377 do_commit(state);
1379 am_next(state);
1380 am_run(state, 0);
1384 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1385 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1386 * failure.
1388 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1390 struct lock_file *lock_file;
1391 struct unpack_trees_options opts;
1392 struct tree_desc t[2];
1394 if (parse_tree(head) || parse_tree(remote))
1395 return -1;
1397 lock_file = xcalloc(1, sizeof(struct lock_file));
1398 hold_locked_index(lock_file, 1);
1400 refresh_cache(REFRESH_QUIET);
1402 memset(&opts, 0, sizeof(opts));
1403 opts.head_idx = 1;
1404 opts.src_index = &the_index;
1405 opts.dst_index = &the_index;
1406 opts.update = 1;
1407 opts.merge = 1;
1408 opts.reset = reset;
1409 opts.fn = twoway_merge;
1410 init_tree_desc(&t[0], head->buffer, head->size);
1411 init_tree_desc(&t[1], remote->buffer, remote->size);
1413 if (unpack_trees(2, t, &opts)) {
1414 rollback_lock_file(lock_file);
1415 return -1;
1418 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1419 die(_("unable to write new index file"));
1421 return 0;
1425 * Clean the index without touching entries that are not modified between
1426 * `head` and `remote`.
1428 static int clean_index(const unsigned char *head, const unsigned char *remote)
1430 struct lock_file *lock_file;
1431 struct tree *head_tree, *remote_tree, *index_tree;
1432 unsigned char index[GIT_SHA1_RAWSZ];
1433 struct pathspec pathspec;
1435 head_tree = parse_tree_indirect(head);
1436 if (!head_tree)
1437 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1439 remote_tree = parse_tree_indirect(remote);
1440 if (!remote_tree)
1441 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1443 read_cache_unmerged();
1445 if (fast_forward_to(head_tree, head_tree, 1))
1446 return -1;
1448 if (write_cache_as_tree(index, 0, NULL))
1449 return -1;
1451 index_tree = parse_tree_indirect(index);
1452 if (!index_tree)
1453 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1455 if (fast_forward_to(index_tree, remote_tree, 0))
1456 return -1;
1458 memset(&pathspec, 0, sizeof(pathspec));
1460 lock_file = xcalloc(1, sizeof(struct lock_file));
1461 hold_locked_index(lock_file, 1);
1463 if (read_tree(remote_tree, 0, &pathspec)) {
1464 rollback_lock_file(lock_file);
1465 return -1;
1468 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1469 die(_("unable to write new index file"));
1471 remove_branch_state();
1473 return 0;
1477 * Resume the current am session by skipping the current patch.
1479 static void am_skip(struct am_state *state)
1481 unsigned char head[GIT_SHA1_RAWSZ];
1483 if (get_sha1("HEAD", head))
1484 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1486 if (clean_index(head, head))
1487 die(_("failed to clean index"));
1489 am_next(state);
1490 am_run(state, 0);
1494 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1496 * It is not safe to reset HEAD when:
1497 * 1. git-am previously failed because the index was dirty.
1498 * 2. HEAD has moved since git-am previously failed.
1500 static int safe_to_abort(const struct am_state *state)
1502 struct strbuf sb = STRBUF_INIT;
1503 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1505 if (file_exists(am_path(state, "dirtyindex")))
1506 return 0;
1508 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1509 if (get_sha1_hex(sb.buf, abort_safety))
1510 die(_("could not parse %s"), am_path(state, "abort_safety"));
1511 } else
1512 hashclr(abort_safety);
1514 if (get_sha1("HEAD", head))
1515 hashclr(head);
1517 if (!hashcmp(head, abort_safety))
1518 return 1;
1520 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1521 "Not rewinding to ORIG_HEAD"));
1523 return 0;
1527 * Aborts the current am session if it is safe to do so.
1529 static void am_abort(struct am_state *state)
1531 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1532 int has_curr_head, has_orig_head;
1533 char *curr_branch;
1535 if (!safe_to_abort(state)) {
1536 am_destroy(state);
1537 return;
1540 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1541 has_curr_head = !is_null_sha1(curr_head);
1542 if (!has_curr_head)
1543 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1545 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1546 if (!has_orig_head)
1547 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1549 clean_index(curr_head, orig_head);
1551 if (has_orig_head)
1552 update_ref("am --abort", "HEAD", orig_head,
1553 has_curr_head ? curr_head : NULL, 0,
1554 UPDATE_REFS_DIE_ON_ERR);
1555 else if (curr_branch)
1556 delete_ref(curr_branch, NULL, REF_NODEREF);
1558 free(curr_branch);
1559 am_destroy(state);
1563 * parse_options() callback that validates and sets opt->value to the
1564 * PATCH_FORMAT_* enum value corresponding to `arg`.
1566 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1568 int *opt_value = opt->value;
1570 if (!strcmp(arg, "mbox"))
1571 *opt_value = PATCH_FORMAT_MBOX;
1572 else
1573 return error(_("Invalid value for --patch-format: %s"), arg);
1574 return 0;
1577 enum resume_mode {
1578 RESUME_FALSE = 0,
1579 RESUME_APPLY,
1580 RESUME_RESOLVED,
1581 RESUME_SKIP,
1582 RESUME_ABORT
1585 int cmd_am(int argc, const char **argv, const char *prefix)
1587 struct am_state state;
1588 int keep_cr = -1;
1589 int patch_format = PATCH_FORMAT_UNKNOWN;
1590 enum resume_mode resume = RESUME_FALSE;
1592 const char * const usage[] = {
1593 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1594 N_("git am [options] (--continue | --skip | --abort)"),
1595 NULL
1598 struct option options[] = {
1599 OPT_BOOL('3', "3way", &state.threeway,
1600 N_("allow fall back on 3way merging if needed")),
1601 OPT__QUIET(&state.quiet, N_("be quiet")),
1602 OPT_BOOL('s', "signoff", &state.signoff,
1603 N_("add a Signed-off-by line to the commit message")),
1604 OPT_BOOL('u', "utf8", &state.utf8,
1605 N_("recode into utf8 (default)")),
1606 OPT_SET_INT('k', "keep", &state.keep,
1607 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1608 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1609 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1610 OPT_BOOL('m', "message-id", &state.message_id,
1611 N_("pass -m flag to git-mailinfo")),
1612 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1613 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1614 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1615 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1616 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1617 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
1618 OPT_BOOL('c', "scissors", &state.scissors,
1619 N_("strip everything before a scissors line")),
1620 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
1621 N_("pass it through git-apply"),
1623 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
1624 N_("pass it through git-apply"),
1625 PARSE_OPT_NOARG),
1626 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
1627 N_("pass it through git-apply"),
1628 PARSE_OPT_NOARG),
1629 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
1630 N_("pass it through git-apply"),
1632 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
1633 N_("pass it through git-apply"),
1635 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
1636 N_("pass it through git-apply"),
1638 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
1639 N_("pass it through git-apply"),
1641 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
1642 N_("pass it through git-apply"),
1644 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1645 N_("format the patch(es) are in"),
1646 parse_opt_patchformat),
1647 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
1648 N_("pass it through git-apply"),
1649 PARSE_OPT_NOARG),
1650 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1651 N_("override error message when patch failure occurs")),
1652 OPT_CMDMODE(0, "continue", &resume,
1653 N_("continue applying patches after resolving a conflict"),
1654 RESUME_RESOLVED),
1655 OPT_CMDMODE('r', "resolved", &resume,
1656 N_("synonyms for --continue"),
1657 RESUME_RESOLVED),
1658 OPT_CMDMODE(0, "skip", &resume,
1659 N_("skip the current patch"),
1660 RESUME_SKIP),
1661 OPT_CMDMODE(0, "abort", &resume,
1662 N_("restore the original branch and abort the patching operation."),
1663 RESUME_ABORT),
1664 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1665 N_("(internal use for git-rebase)")),
1666 OPT_END()
1670 * NEEDSWORK: Once all the features of git-am.sh have been
1671 * re-implemented in builtin/am.c, this preamble can be removed.
1673 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1674 const char *path = mkpath("%s/git-am", git_exec_path());
1676 if (sane_execvp(path, (char **)argv) < 0)
1677 die_errno("could not exec %s", path);
1678 } else {
1679 prefix = setup_git_directory();
1680 trace_repo_setup(prefix);
1681 setup_work_tree();
1684 git_config(git_default_config, NULL);
1686 am_state_init(&state, git_path("rebase-apply"));
1688 argc = parse_options(argc, argv, prefix, options, usage, 0);
1690 if (read_index_preload(&the_index, NULL) < 0)
1691 die(_("failed to read the index"));
1693 if (am_in_progress(&state)) {
1695 * Catch user error to feed us patches when there is a session
1696 * in progress:
1698 * 1. mbox path(s) are provided on the command-line.
1699 * 2. stdin is not a tty: the user is trying to feed us a patch
1700 * from standard input. This is somewhat unreliable -- stdin
1701 * could be /dev/null for example and the caller did not
1702 * intend to feed us a patch but wanted to continue
1703 * unattended.
1705 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1706 die(_("previous rebase directory %s still exists but mbox given."),
1707 state.dir);
1709 if (resume == RESUME_FALSE)
1710 resume = RESUME_APPLY;
1712 am_load(&state);
1713 } else {
1714 struct argv_array paths = ARGV_ARRAY_INIT;
1715 int i;
1718 * Handle stray state directory in the independent-run case. In
1719 * the --rebasing case, it is up to the caller to take care of
1720 * stray directories.
1722 if (file_exists(state.dir) && !state.rebasing) {
1723 if (resume == RESUME_ABORT) {
1724 am_destroy(&state);
1725 am_state_release(&state);
1726 return 0;
1729 die(_("Stray %s directory found.\n"
1730 "Use \"git am --abort\" to remove it."),
1731 state.dir);
1734 if (resume)
1735 die(_("Resolve operation not in progress, we are not resuming."));
1737 for (i = 0; i < argc; i++) {
1738 if (is_absolute_path(argv[i]) || !prefix)
1739 argv_array_push(&paths, argv[i]);
1740 else
1741 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1744 am_setup(&state, patch_format, paths.argv, keep_cr);
1746 argv_array_clear(&paths);
1749 switch (resume) {
1750 case RESUME_FALSE:
1751 am_run(&state, 0);
1752 break;
1753 case RESUME_APPLY:
1754 am_run(&state, 1);
1755 break;
1756 case RESUME_RESOLVED:
1757 am_resolve(&state);
1758 break;
1759 case RESUME_SKIP:
1760 am_skip(&state);
1761 break;
1762 case RESUME_ABORT:
1763 am_abort(&state);
1764 break;
1765 default:
1766 die("BUG: invalid resume value");
1769 am_state_release(&state);
1771 return 0;