builtin-am: implement --[no-]scissors
[alt-git.git] / builtin / am.c
blob727cfb8f96d8aff02130747f1075a7c54a892e29
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 const char *resolvemsg;
110 int rebasing;
114 * Initializes am_state with the default values. The state directory is set to
115 * dir.
117 static void am_state_init(struct am_state *state, const char *dir)
119 memset(state, 0, sizeof(*state));
121 assert(dir);
122 state->dir = xstrdup(dir);
124 state->prec = 4;
126 state->utf8 = 1;
128 git_config_get_bool("am.messageid", &state->message_id);
130 state->scissors = SCISSORS_UNSET;
134 * Releases memory allocated by an am_state.
136 static void am_state_release(struct am_state *state)
138 free(state->dir);
139 free(state->author_name);
140 free(state->author_email);
141 free(state->author_date);
142 free(state->msg);
146 * Returns path relative to the am_state directory.
148 static inline const char *am_path(const struct am_state *state, const char *path)
150 return mkpath("%s/%s", state->dir, path);
154 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
155 * at the end.
157 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
159 va_list ap;
161 va_start(ap, fmt);
162 if (!state->quiet) {
163 vfprintf(fp, fmt, ap);
164 putc('\n', fp);
166 va_end(ap);
170 * Returns 1 if there is an am session in progress, 0 otherwise.
172 static int am_in_progress(const struct am_state *state)
174 struct stat st;
176 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
177 return 0;
178 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
179 return 0;
180 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
181 return 0;
182 return 1;
186 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
187 * number of bytes read on success, -1 if the file does not exist. If `trim` is
188 * set, trailing whitespace will be removed.
190 static int read_state_file(struct strbuf *sb, const struct am_state *state,
191 const char *file, int trim)
193 strbuf_reset(sb);
195 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
196 if (trim)
197 strbuf_trim(sb);
199 return sb->len;
202 if (errno == ENOENT)
203 return -1;
205 die_errno(_("could not read '%s'"), am_path(state, file));
209 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
210 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
211 * match `key`. Returns NULL on failure.
213 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
214 * the author-script.
216 static char *read_shell_var(FILE *fp, const char *key)
218 struct strbuf sb = STRBUF_INIT;
219 const char *str;
221 if (strbuf_getline(&sb, fp, '\n'))
222 goto fail;
224 if (!skip_prefix(sb.buf, key, &str))
225 goto fail;
227 if (!skip_prefix(str, "=", &str))
228 goto fail;
230 strbuf_remove(&sb, 0, str - sb.buf);
232 str = sq_dequote(sb.buf);
233 if (!str)
234 goto fail;
236 return strbuf_detach(&sb, NULL);
238 fail:
239 strbuf_release(&sb);
240 return NULL;
244 * Reads and parses the state directory's "author-script" file, and sets
245 * state->author_name, state->author_email and state->author_date accordingly.
246 * Returns 0 on success, -1 if the file could not be parsed.
248 * The author script is of the format:
250 * GIT_AUTHOR_NAME='$author_name'
251 * GIT_AUTHOR_EMAIL='$author_email'
252 * GIT_AUTHOR_DATE='$author_date'
254 * where $author_name, $author_email and $author_date are quoted. We are strict
255 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
256 * script, and thus if the file differs from what this function expects, it is
257 * better to bail out than to do something that the user does not expect.
259 static int read_author_script(struct am_state *state)
261 const char *filename = am_path(state, "author-script");
262 FILE *fp;
264 assert(!state->author_name);
265 assert(!state->author_email);
266 assert(!state->author_date);
268 fp = fopen(filename, "r");
269 if (!fp) {
270 if (errno == ENOENT)
271 return 0;
272 die_errno(_("could not open '%s' for reading"), filename);
275 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
276 if (!state->author_name) {
277 fclose(fp);
278 return -1;
281 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
282 if (!state->author_email) {
283 fclose(fp);
284 return -1;
287 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
288 if (!state->author_date) {
289 fclose(fp);
290 return -1;
293 if (fgetc(fp) != EOF) {
294 fclose(fp);
295 return -1;
298 fclose(fp);
299 return 0;
303 * Saves state->author_name, state->author_email and state->author_date in the
304 * state directory's "author-script" file.
306 static void write_author_script(const struct am_state *state)
308 struct strbuf sb = STRBUF_INIT;
310 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
311 sq_quote_buf(&sb, state->author_name);
312 strbuf_addch(&sb, '\n');
314 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
315 sq_quote_buf(&sb, state->author_email);
316 strbuf_addch(&sb, '\n');
318 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
319 sq_quote_buf(&sb, state->author_date);
320 strbuf_addch(&sb, '\n');
322 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
324 strbuf_release(&sb);
328 * Reads the commit message from the state directory's "final-commit" file,
329 * setting state->msg to its contents and state->msg_len to the length of its
330 * contents in bytes.
332 * Returns 0 on success, -1 if the file does not exist.
334 static int read_commit_msg(struct am_state *state)
336 struct strbuf sb = STRBUF_INIT;
338 assert(!state->msg);
340 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
341 strbuf_release(&sb);
342 return -1;
345 state->msg = strbuf_detach(&sb, &state->msg_len);
346 return 0;
350 * Saves state->msg in the state directory's "final-commit" file.
352 static void write_commit_msg(const struct am_state *state)
354 int fd;
355 const char *filename = am_path(state, "final-commit");
357 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
358 if (write_in_full(fd, state->msg, state->msg_len) < 0)
359 die_errno(_("could not write to %s"), filename);
360 close(fd);
364 * Loads state from disk.
366 static void am_load(struct am_state *state)
368 struct strbuf sb = STRBUF_INIT;
370 if (read_state_file(&sb, state, "next", 1) < 0)
371 die("BUG: state file 'next' does not exist");
372 state->cur = strtol(sb.buf, NULL, 10);
374 if (read_state_file(&sb, state, "last", 1) < 0)
375 die("BUG: state file 'last' does not exist");
376 state->last = strtol(sb.buf, NULL, 10);
378 if (read_author_script(state) < 0)
379 die(_("could not parse author script"));
381 read_commit_msg(state);
383 read_state_file(&sb, state, "threeway", 1);
384 state->threeway = !strcmp(sb.buf, "t");
386 read_state_file(&sb, state, "quiet", 1);
387 state->quiet = !strcmp(sb.buf, "t");
389 read_state_file(&sb, state, "sign", 1);
390 state->signoff = !strcmp(sb.buf, "t");
392 read_state_file(&sb, state, "utf8", 1);
393 state->utf8 = !strcmp(sb.buf, "t");
395 read_state_file(&sb, state, "keep", 1);
396 if (!strcmp(sb.buf, "t"))
397 state->keep = KEEP_TRUE;
398 else if (!strcmp(sb.buf, "b"))
399 state->keep = KEEP_NON_PATCH;
400 else
401 state->keep = KEEP_FALSE;
403 read_state_file(&sb, state, "messageid", 1);
404 state->message_id = !strcmp(sb.buf, "t");
406 read_state_file(&sb, state, "scissors", 1);
407 if (!strcmp(sb.buf, "t"))
408 state->scissors = SCISSORS_TRUE;
409 else if (!strcmp(sb.buf, "f"))
410 state->scissors = SCISSORS_FALSE;
411 else
412 state->scissors = SCISSORS_UNSET;
414 state->rebasing = !!file_exists(am_path(state, "rebasing"));
416 strbuf_release(&sb);
420 * Removes the am_state directory, forcefully terminating the current am
421 * session.
423 static void am_destroy(const struct am_state *state)
425 struct strbuf sb = STRBUF_INIT;
427 strbuf_addstr(&sb, state->dir);
428 remove_dir_recursively(&sb, 0);
429 strbuf_release(&sb);
433 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
434 * non-indented lines and checking if they look like they begin with valid
435 * header field names.
437 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
439 static int is_mail(FILE *fp)
441 const char *header_regex = "^[!-9;-~]+:";
442 struct strbuf sb = STRBUF_INIT;
443 regex_t regex;
444 int ret = 1;
446 if (fseek(fp, 0L, SEEK_SET))
447 die_errno(_("fseek failed"));
449 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
450 die("invalid pattern: %s", header_regex);
452 while (!strbuf_getline_crlf(&sb, fp)) {
453 if (!sb.len)
454 break; /* End of header */
456 /* Ignore indented folded lines */
457 if (*sb.buf == '\t' || *sb.buf == ' ')
458 continue;
460 /* It's a header if it matches header_regex */
461 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
462 ret = 0;
463 goto done;
467 done:
468 regfree(&regex);
469 strbuf_release(&sb);
470 return ret;
474 * Attempts to detect the patch_format of the patches contained in `paths`,
475 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
476 * detection fails.
478 static int detect_patch_format(const char **paths)
480 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
481 struct strbuf l1 = STRBUF_INIT;
482 FILE *fp;
485 * We default to mbox format if input is from stdin and for directories
487 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
488 return PATCH_FORMAT_MBOX;
491 * Otherwise, check the first few lines of the first patch, starting
492 * from the first non-blank line, to try to detect its format.
495 fp = xfopen(*paths, "r");
497 while (!strbuf_getline_crlf(&l1, fp)) {
498 if (l1.len)
499 break;
502 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
503 ret = PATCH_FORMAT_MBOX;
504 goto done;
507 if (l1.len && is_mail(fp)) {
508 ret = PATCH_FORMAT_MBOX;
509 goto done;
512 done:
513 fclose(fp);
514 strbuf_release(&l1);
515 return ret;
519 * Splits out individual email patches from `paths`, where each path is either
520 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
522 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
524 struct child_process cp = CHILD_PROCESS_INIT;
525 struct strbuf last = STRBUF_INIT;
527 cp.git_cmd = 1;
528 argv_array_push(&cp.args, "mailsplit");
529 argv_array_pushf(&cp.args, "-d%d", state->prec);
530 argv_array_pushf(&cp.args, "-o%s", state->dir);
531 argv_array_push(&cp.args, "-b");
532 if (keep_cr)
533 argv_array_push(&cp.args, "--keep-cr");
534 argv_array_push(&cp.args, "--");
535 argv_array_pushv(&cp.args, paths);
537 if (capture_command(&cp, &last, 8))
538 return -1;
540 state->cur = 1;
541 state->last = strtol(last.buf, NULL, 10);
543 return 0;
547 * Splits a list of files/directories into individual email patches. Each path
548 * in `paths` must be a file/directory that is formatted according to
549 * `patch_format`.
551 * Once split out, the individual email patches will be stored in the state
552 * directory, with each patch's filename being its index, padded to state->prec
553 * digits.
555 * state->cur will be set to the index of the first mail, and state->last will
556 * be set to the index of the last mail.
558 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
559 * to disable this behavior, -1 to use the default configured setting.
561 * Returns 0 on success, -1 on failure.
563 static int split_mail(struct am_state *state, enum patch_format patch_format,
564 const char **paths, int keep_cr)
566 if (keep_cr < 0) {
567 keep_cr = 0;
568 git_config_get_bool("am.keepcr", &keep_cr);
571 switch (patch_format) {
572 case PATCH_FORMAT_MBOX:
573 return split_mail_mbox(state, paths, keep_cr);
574 default:
575 die("BUG: invalid patch_format");
577 return -1;
581 * Setup a new am session for applying patches
583 static void am_setup(struct am_state *state, enum patch_format patch_format,
584 const char **paths, int keep_cr)
586 unsigned char curr_head[GIT_SHA1_RAWSZ];
587 const char *str;
589 if (!patch_format)
590 patch_format = detect_patch_format(paths);
592 if (!patch_format) {
593 fprintf_ln(stderr, _("Patch format detection failed."));
594 exit(128);
597 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
598 die_errno(_("failed to create directory '%s'"), state->dir);
600 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
601 am_destroy(state);
602 die(_("Failed to split patches."));
605 if (state->rebasing)
606 state->threeway = 1;
608 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
610 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
612 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
614 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
616 switch (state->keep) {
617 case KEEP_FALSE:
618 str = "f";
619 break;
620 case KEEP_TRUE:
621 str = "t";
622 break;
623 case KEEP_NON_PATCH:
624 str = "b";
625 break;
626 default:
627 die("BUG: invalid value for state->keep");
630 write_file(am_path(state, "keep"), 1, "%s", str);
632 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
634 switch (state->scissors) {
635 case SCISSORS_UNSET:
636 str = "";
637 break;
638 case SCISSORS_FALSE:
639 str = "f";
640 break;
641 case SCISSORS_TRUE:
642 str = "t";
643 break;
644 default:
645 die("BUG: invalid value for state->scissors");
648 write_file(am_path(state, "scissors"), 1, "%s", str);
650 if (state->rebasing)
651 write_file(am_path(state, "rebasing"), 1, "%s", "");
652 else
653 write_file(am_path(state, "applying"), 1, "%s", "");
655 if (!get_sha1("HEAD", curr_head)) {
656 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
657 if (!state->rebasing)
658 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
659 UPDATE_REFS_DIE_ON_ERR);
660 } else {
661 write_file(am_path(state, "abort-safety"), 1, "%s", "");
662 if (!state->rebasing)
663 delete_ref("ORIG_HEAD", NULL, 0);
667 * NOTE: Since the "next" and "last" files determine if an am_state
668 * session is in progress, they should be written last.
671 write_file(am_path(state, "next"), 1, "%d", state->cur);
673 write_file(am_path(state, "last"), 1, "%d", state->last);
677 * Increments the patch pointer, and cleans am_state for the application of the
678 * next patch.
680 static void am_next(struct am_state *state)
682 unsigned char head[GIT_SHA1_RAWSZ];
684 free(state->author_name);
685 state->author_name = NULL;
687 free(state->author_email);
688 state->author_email = NULL;
690 free(state->author_date);
691 state->author_date = NULL;
693 free(state->msg);
694 state->msg = NULL;
695 state->msg_len = 0;
697 unlink(am_path(state, "author-script"));
698 unlink(am_path(state, "final-commit"));
700 if (!get_sha1("HEAD", head))
701 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
702 else
703 write_file(am_path(state, "abort-safety"), 1, "%s", "");
705 state->cur++;
706 write_file(am_path(state, "next"), 1, "%d", state->cur);
710 * Returns the filename of the current patch email.
712 static const char *msgnum(const struct am_state *state)
714 static struct strbuf sb = STRBUF_INIT;
716 strbuf_reset(&sb);
717 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
719 return sb.buf;
723 * Refresh and write index.
725 static void refresh_and_write_cache(void)
727 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
729 hold_locked_index(lock_file, 1);
730 refresh_cache(REFRESH_QUIET);
731 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
732 die(_("unable to write index file"));
736 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
737 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
738 * strbuf is provided, the space-separated list of files that differ will be
739 * appended to it.
741 static int index_has_changes(struct strbuf *sb)
743 unsigned char head[GIT_SHA1_RAWSZ];
744 int i;
746 if (!get_sha1_tree("HEAD", head)) {
747 struct diff_options opt;
749 diff_setup(&opt);
750 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
751 if (!sb)
752 DIFF_OPT_SET(&opt, QUICK);
753 do_diff_cache(head, &opt);
754 diffcore_std(&opt);
755 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
756 if (i)
757 strbuf_addch(sb, ' ');
758 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
760 diff_flush(&opt);
761 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
762 } else {
763 for (i = 0; sb && i < active_nr; i++) {
764 if (i)
765 strbuf_addch(sb, ' ');
766 strbuf_addstr(sb, active_cache[i]->name);
768 return !!active_nr;
773 * Dies with a user-friendly message on how to proceed after resolving the
774 * problem. This message can be overridden with state->resolvemsg.
776 static void NORETURN die_user_resolve(const struct am_state *state)
778 if (state->resolvemsg) {
779 printf_ln("%s", state->resolvemsg);
780 } else {
781 const char *cmdline = "git am";
783 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
784 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
785 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
788 exit(128);
792 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
793 * state->msg will be set to the patch message. state->author_name,
794 * state->author_email and state->author_date will be set to the patch author's
795 * name, email and date respectively. The patch body will be written to the
796 * state directory's "patch" file.
798 * Returns 1 if the patch should be skipped, 0 otherwise.
800 static int parse_mail(struct am_state *state, const char *mail)
802 FILE *fp;
803 struct child_process cp = CHILD_PROCESS_INIT;
804 struct strbuf sb = STRBUF_INIT;
805 struct strbuf msg = STRBUF_INIT;
806 struct strbuf author_name = STRBUF_INIT;
807 struct strbuf author_date = STRBUF_INIT;
808 struct strbuf author_email = STRBUF_INIT;
809 int ret = 0;
811 cp.git_cmd = 1;
812 cp.in = xopen(mail, O_RDONLY, 0);
813 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
815 argv_array_push(&cp.args, "mailinfo");
816 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
818 switch (state->keep) {
819 case KEEP_FALSE:
820 break;
821 case KEEP_TRUE:
822 argv_array_push(&cp.args, "-k");
823 break;
824 case KEEP_NON_PATCH:
825 argv_array_push(&cp.args, "-b");
826 break;
827 default:
828 die("BUG: invalid value for state->keep");
831 if (state->message_id)
832 argv_array_push(&cp.args, "-m");
834 switch (state->scissors) {
835 case SCISSORS_UNSET:
836 break;
837 case SCISSORS_FALSE:
838 argv_array_push(&cp.args, "--no-scissors");
839 break;
840 case SCISSORS_TRUE:
841 argv_array_push(&cp.args, "--scissors");
842 break;
843 default:
844 die("BUG: invalid value for state->scissors");
847 argv_array_push(&cp.args, am_path(state, "msg"));
848 argv_array_push(&cp.args, am_path(state, "patch"));
850 if (run_command(&cp) < 0)
851 die("could not parse patch");
853 close(cp.in);
854 close(cp.out);
856 /* Extract message and author information */
857 fp = xfopen(am_path(state, "info"), "r");
858 while (!strbuf_getline(&sb, fp, '\n')) {
859 const char *x;
861 if (skip_prefix(sb.buf, "Subject: ", &x)) {
862 if (msg.len)
863 strbuf_addch(&msg, '\n');
864 strbuf_addstr(&msg, x);
865 } else if (skip_prefix(sb.buf, "Author: ", &x))
866 strbuf_addstr(&author_name, x);
867 else if (skip_prefix(sb.buf, "Email: ", &x))
868 strbuf_addstr(&author_email, x);
869 else if (skip_prefix(sb.buf, "Date: ", &x))
870 strbuf_addstr(&author_date, x);
872 fclose(fp);
874 /* Skip pine's internal folder data */
875 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
876 ret = 1;
877 goto finish;
880 if (is_empty_file(am_path(state, "patch"))) {
881 printf_ln(_("Patch is empty. Was it split wrong?"));
882 die_user_resolve(state);
885 strbuf_addstr(&msg, "\n\n");
886 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
887 die_errno(_("could not read '%s'"), am_path(state, "msg"));
888 stripspace(&msg, 0);
890 if (state->signoff)
891 append_signoff(&msg, 0, 0);
893 assert(!state->author_name);
894 state->author_name = strbuf_detach(&author_name, NULL);
896 assert(!state->author_email);
897 state->author_email = strbuf_detach(&author_email, NULL);
899 assert(!state->author_date);
900 state->author_date = strbuf_detach(&author_date, NULL);
902 assert(!state->msg);
903 state->msg = strbuf_detach(&msg, &state->msg_len);
905 finish:
906 strbuf_release(&msg);
907 strbuf_release(&author_date);
908 strbuf_release(&author_email);
909 strbuf_release(&author_name);
910 strbuf_release(&sb);
911 return ret;
915 * Sets commit_id to the commit hash where the mail was generated from.
916 * Returns 0 on success, -1 on failure.
918 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
920 struct strbuf sb = STRBUF_INIT;
921 FILE *fp = xfopen(mail, "r");
922 const char *x;
924 if (strbuf_getline(&sb, fp, '\n'))
925 return -1;
927 if (!skip_prefix(sb.buf, "From ", &x))
928 return -1;
930 if (get_sha1_hex(x, commit_id) < 0)
931 return -1;
933 strbuf_release(&sb);
934 fclose(fp);
935 return 0;
939 * Sets state->msg, state->author_name, state->author_email, state->author_date
940 * to the commit's respective info.
942 static void get_commit_info(struct am_state *state, struct commit *commit)
944 const char *buffer, *ident_line, *author_date, *msg;
945 size_t ident_len;
946 struct ident_split ident_split;
947 struct strbuf sb = STRBUF_INIT;
949 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
951 ident_line = find_commit_header(buffer, "author", &ident_len);
953 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
954 strbuf_add(&sb, ident_line, ident_len);
955 die(_("invalid ident line: %s"), sb.buf);
958 assert(!state->author_name);
959 if (ident_split.name_begin) {
960 strbuf_add(&sb, ident_split.name_begin,
961 ident_split.name_end - ident_split.name_begin);
962 state->author_name = strbuf_detach(&sb, NULL);
963 } else
964 state->author_name = xstrdup("");
966 assert(!state->author_email);
967 if (ident_split.mail_begin) {
968 strbuf_add(&sb, ident_split.mail_begin,
969 ident_split.mail_end - ident_split.mail_begin);
970 state->author_email = strbuf_detach(&sb, NULL);
971 } else
972 state->author_email = xstrdup("");
974 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
975 strbuf_addstr(&sb, author_date);
976 assert(!state->author_date);
977 state->author_date = strbuf_detach(&sb, NULL);
979 assert(!state->msg);
980 msg = strstr(buffer, "\n\n");
981 if (!msg)
982 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
983 state->msg = xstrdup(msg + 2);
984 state->msg_len = strlen(state->msg);
988 * Writes `commit` as a patch to the state directory's "patch" file.
990 static void write_commit_patch(const struct am_state *state, struct commit *commit)
992 struct rev_info rev_info;
993 FILE *fp;
995 fp = xfopen(am_path(state, "patch"), "w");
996 init_revisions(&rev_info, NULL);
997 rev_info.diff = 1;
998 rev_info.abbrev = 0;
999 rev_info.disable_stdin = 1;
1000 rev_info.show_root_diff = 1;
1001 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1002 rev_info.no_commit_id = 1;
1003 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1004 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1005 rev_info.diffopt.use_color = 0;
1006 rev_info.diffopt.file = fp;
1007 rev_info.diffopt.close_file = 1;
1008 add_pending_object(&rev_info, &commit->object, "");
1009 diff_setup_done(&rev_info.diffopt);
1010 log_tree_commit(&rev_info, commit);
1014 * Like parse_mail(), but parses the mail by looking up its commit ID
1015 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1016 * of patches.
1018 * Will always return 0 as the patch should never be skipped.
1020 static int parse_mail_rebase(struct am_state *state, const char *mail)
1022 struct commit *commit;
1023 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1025 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1026 die(_("could not parse %s"), mail);
1028 commit = lookup_commit_or_die(commit_sha1, mail);
1030 get_commit_info(state, commit);
1032 write_commit_patch(state, commit);
1034 return 0;
1038 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1039 * `index_file` is not NULL, the patch will be applied to that index.
1041 static int run_apply(const struct am_state *state, const char *index_file)
1043 struct child_process cp = CHILD_PROCESS_INIT;
1045 cp.git_cmd = 1;
1047 if (index_file)
1048 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1051 * If we are allowed to fall back on 3-way merge, don't give false
1052 * errors during the initial attempt.
1054 if (state->threeway && !index_file) {
1055 cp.no_stdout = 1;
1056 cp.no_stderr = 1;
1059 argv_array_push(&cp.args, "apply");
1061 if (index_file)
1062 argv_array_push(&cp.args, "--cached");
1063 else
1064 argv_array_push(&cp.args, "--index");
1066 argv_array_push(&cp.args, am_path(state, "patch"));
1068 if (run_command(&cp))
1069 return -1;
1071 /* Reload index as git-apply will have modified it. */
1072 discard_cache();
1073 read_cache_from(index_file ? index_file : get_index_file());
1075 return 0;
1079 * Builds an index that contains just the blobs needed for a 3way merge.
1081 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1083 struct child_process cp = CHILD_PROCESS_INIT;
1085 cp.git_cmd = 1;
1086 argv_array_push(&cp.args, "apply");
1087 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1088 argv_array_push(&cp.args, am_path(state, "patch"));
1090 if (run_command(&cp))
1091 return -1;
1093 return 0;
1097 * Attempt a threeway merge, using index_path as the temporary index.
1099 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1101 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1102 our_tree[GIT_SHA1_RAWSZ];
1103 const unsigned char *bases[1] = {orig_tree};
1104 struct merge_options o;
1105 struct commit *result;
1106 char *his_tree_name;
1108 if (get_sha1("HEAD", our_tree) < 0)
1109 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1111 if (build_fake_ancestor(state, index_path))
1112 return error("could not build fake ancestor");
1114 discard_cache();
1115 read_cache_from(index_path);
1117 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1118 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1120 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1122 if (!state->quiet) {
1124 * List paths that needed 3-way fallback, so that the user can
1125 * review them with extra care to spot mismerges.
1127 struct rev_info rev_info;
1128 const char *diff_filter_str = "--diff-filter=AM";
1130 init_revisions(&rev_info, NULL);
1131 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1132 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1133 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1134 diff_setup_done(&rev_info.diffopt);
1135 run_diff_index(&rev_info, 1);
1138 if (run_apply(state, index_path))
1139 return error(_("Did you hand edit your patch?\n"
1140 "It does not apply to blobs recorded in its index."));
1142 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1143 return error("could not write tree");
1145 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1147 discard_cache();
1148 read_cache();
1151 * This is not so wrong. Depending on which base we picked, orig_tree
1152 * may be wildly different from ours, but his_tree has the same set of
1153 * wildly different changes in parts the patch did not touch, so
1154 * recursive ends up canceling them, saying that we reverted all those
1155 * changes.
1158 init_merge_options(&o);
1160 o.branch1 = "HEAD";
1161 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1162 o.branch2 = his_tree_name;
1164 if (state->quiet)
1165 o.verbosity = 0;
1167 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1168 free(his_tree_name);
1169 return error(_("Failed to merge in the changes."));
1172 free(his_tree_name);
1173 return 0;
1177 * Commits the current index with state->msg as the commit message and
1178 * state->author_name, state->author_email and state->author_date as the author
1179 * information.
1181 static void do_commit(const struct am_state *state)
1183 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1184 commit[GIT_SHA1_RAWSZ];
1185 unsigned char *ptr;
1186 struct commit_list *parents = NULL;
1187 const char *reflog_msg, *author;
1188 struct strbuf sb = STRBUF_INIT;
1190 if (write_cache_as_tree(tree, 0, NULL))
1191 die(_("git write-tree failed to write a tree"));
1193 if (!get_sha1_commit("HEAD", parent)) {
1194 ptr = parent;
1195 commit_list_insert(lookup_commit(parent), &parents);
1196 } else {
1197 ptr = NULL;
1198 say(state, stderr, _("applying to an empty history"));
1201 author = fmt_ident(state->author_name, state->author_email,
1202 state->author_date, IDENT_STRICT);
1204 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1205 author, NULL))
1206 die(_("failed to write commit object"));
1208 reflog_msg = getenv("GIT_REFLOG_ACTION");
1209 if (!reflog_msg)
1210 reflog_msg = "am";
1212 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1213 state->msg);
1215 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1217 strbuf_release(&sb);
1221 * Validates the am_state for resuming -- the "msg" and authorship fields must
1222 * be filled up.
1224 static void validate_resume_state(const struct am_state *state)
1226 if (!state->msg)
1227 die(_("cannot resume: %s does not exist."),
1228 am_path(state, "final-commit"));
1230 if (!state->author_name || !state->author_email || !state->author_date)
1231 die(_("cannot resume: %s does not exist."),
1232 am_path(state, "author-script"));
1236 * Applies all queued mail.
1238 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1239 * well as the state directory's "patch" file is used as-is for applying the
1240 * patch and committing it.
1242 static void am_run(struct am_state *state, int resume)
1244 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1245 struct strbuf sb = STRBUF_INIT;
1247 unlink(am_path(state, "dirtyindex"));
1249 refresh_and_write_cache();
1251 if (index_has_changes(&sb)) {
1252 write_file(am_path(state, "dirtyindex"), 1, "t");
1253 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1256 strbuf_release(&sb);
1258 while (state->cur <= state->last) {
1259 const char *mail = am_path(state, msgnum(state));
1260 int apply_status;
1262 if (!file_exists(mail))
1263 goto next;
1265 if (resume) {
1266 validate_resume_state(state);
1267 resume = 0;
1268 } else {
1269 int skip;
1271 if (state->rebasing)
1272 skip = parse_mail_rebase(state, mail);
1273 else
1274 skip = parse_mail(state, mail);
1276 if (skip)
1277 goto next; /* mail should be skipped */
1279 write_author_script(state);
1280 write_commit_msg(state);
1283 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1285 apply_status = run_apply(state, NULL);
1287 if (apply_status && state->threeway) {
1288 struct strbuf sb = STRBUF_INIT;
1290 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1291 apply_status = fall_back_threeway(state, sb.buf);
1292 strbuf_release(&sb);
1295 * Applying the patch to an earlier tree and merging
1296 * the result may have produced the same tree as ours.
1298 if (!apply_status && !index_has_changes(NULL)) {
1299 say(state, stdout, _("No changes -- Patch already applied."));
1300 goto next;
1304 if (apply_status) {
1305 int advice_amworkdir = 1;
1307 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1308 linelen(state->msg), state->msg);
1310 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1312 if (advice_amworkdir)
1313 printf_ln(_("The copy of the patch that failed is found in: %s"),
1314 am_path(state, "patch"));
1316 die_user_resolve(state);
1319 do_commit(state);
1321 next:
1322 am_next(state);
1326 * In rebasing mode, it's up to the caller to take care of
1327 * housekeeping.
1329 if (!state->rebasing) {
1330 am_destroy(state);
1331 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1336 * Resume the current am session after patch application failure. The user did
1337 * all the hard work, and we do not have to do any patch application. Just
1338 * trust and commit what the user has in the index and working tree.
1340 static void am_resolve(struct am_state *state)
1342 validate_resume_state(state);
1344 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1346 if (!index_has_changes(NULL)) {
1347 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1348 "If there is nothing left to stage, chances are that something else\n"
1349 "already introduced the same changes; you might want to skip this patch."));
1350 die_user_resolve(state);
1353 if (unmerged_cache()) {
1354 printf_ln(_("You still have unmerged paths in your index.\n"
1355 "Did you forget to use 'git add'?"));
1356 die_user_resolve(state);
1359 do_commit(state);
1361 am_next(state);
1362 am_run(state, 0);
1366 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1367 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1368 * failure.
1370 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1372 struct lock_file *lock_file;
1373 struct unpack_trees_options opts;
1374 struct tree_desc t[2];
1376 if (parse_tree(head) || parse_tree(remote))
1377 return -1;
1379 lock_file = xcalloc(1, sizeof(struct lock_file));
1380 hold_locked_index(lock_file, 1);
1382 refresh_cache(REFRESH_QUIET);
1384 memset(&opts, 0, sizeof(opts));
1385 opts.head_idx = 1;
1386 opts.src_index = &the_index;
1387 opts.dst_index = &the_index;
1388 opts.update = 1;
1389 opts.merge = 1;
1390 opts.reset = reset;
1391 opts.fn = twoway_merge;
1392 init_tree_desc(&t[0], head->buffer, head->size);
1393 init_tree_desc(&t[1], remote->buffer, remote->size);
1395 if (unpack_trees(2, t, &opts)) {
1396 rollback_lock_file(lock_file);
1397 return -1;
1400 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1401 die(_("unable to write new index file"));
1403 return 0;
1407 * Clean the index without touching entries that are not modified between
1408 * `head` and `remote`.
1410 static int clean_index(const unsigned char *head, const unsigned char *remote)
1412 struct lock_file *lock_file;
1413 struct tree *head_tree, *remote_tree, *index_tree;
1414 unsigned char index[GIT_SHA1_RAWSZ];
1415 struct pathspec pathspec;
1417 head_tree = parse_tree_indirect(head);
1418 if (!head_tree)
1419 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1421 remote_tree = parse_tree_indirect(remote);
1422 if (!remote_tree)
1423 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1425 read_cache_unmerged();
1427 if (fast_forward_to(head_tree, head_tree, 1))
1428 return -1;
1430 if (write_cache_as_tree(index, 0, NULL))
1431 return -1;
1433 index_tree = parse_tree_indirect(index);
1434 if (!index_tree)
1435 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1437 if (fast_forward_to(index_tree, remote_tree, 0))
1438 return -1;
1440 memset(&pathspec, 0, sizeof(pathspec));
1442 lock_file = xcalloc(1, sizeof(struct lock_file));
1443 hold_locked_index(lock_file, 1);
1445 if (read_tree(remote_tree, 0, &pathspec)) {
1446 rollback_lock_file(lock_file);
1447 return -1;
1450 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1451 die(_("unable to write new index file"));
1453 remove_branch_state();
1455 return 0;
1459 * Resume the current am session by skipping the current patch.
1461 static void am_skip(struct am_state *state)
1463 unsigned char head[GIT_SHA1_RAWSZ];
1465 if (get_sha1("HEAD", head))
1466 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1468 if (clean_index(head, head))
1469 die(_("failed to clean index"));
1471 am_next(state);
1472 am_run(state, 0);
1476 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1478 * It is not safe to reset HEAD when:
1479 * 1. git-am previously failed because the index was dirty.
1480 * 2. HEAD has moved since git-am previously failed.
1482 static int safe_to_abort(const struct am_state *state)
1484 struct strbuf sb = STRBUF_INIT;
1485 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1487 if (file_exists(am_path(state, "dirtyindex")))
1488 return 0;
1490 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1491 if (get_sha1_hex(sb.buf, abort_safety))
1492 die(_("could not parse %s"), am_path(state, "abort_safety"));
1493 } else
1494 hashclr(abort_safety);
1496 if (get_sha1("HEAD", head))
1497 hashclr(head);
1499 if (!hashcmp(head, abort_safety))
1500 return 1;
1502 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1503 "Not rewinding to ORIG_HEAD"));
1505 return 0;
1509 * Aborts the current am session if it is safe to do so.
1511 static void am_abort(struct am_state *state)
1513 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1514 int has_curr_head, has_orig_head;
1515 char *curr_branch;
1517 if (!safe_to_abort(state)) {
1518 am_destroy(state);
1519 return;
1522 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1523 has_curr_head = !is_null_sha1(curr_head);
1524 if (!has_curr_head)
1525 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1527 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1528 if (!has_orig_head)
1529 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1531 clean_index(curr_head, orig_head);
1533 if (has_orig_head)
1534 update_ref("am --abort", "HEAD", orig_head,
1535 has_curr_head ? curr_head : NULL, 0,
1536 UPDATE_REFS_DIE_ON_ERR);
1537 else if (curr_branch)
1538 delete_ref(curr_branch, NULL, REF_NODEREF);
1540 free(curr_branch);
1541 am_destroy(state);
1545 * parse_options() callback that validates and sets opt->value to the
1546 * PATCH_FORMAT_* enum value corresponding to `arg`.
1548 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1550 int *opt_value = opt->value;
1552 if (!strcmp(arg, "mbox"))
1553 *opt_value = PATCH_FORMAT_MBOX;
1554 else
1555 return error(_("Invalid value for --patch-format: %s"), arg);
1556 return 0;
1559 enum resume_mode {
1560 RESUME_FALSE = 0,
1561 RESUME_APPLY,
1562 RESUME_RESOLVED,
1563 RESUME_SKIP,
1564 RESUME_ABORT
1567 int cmd_am(int argc, const char **argv, const char *prefix)
1569 struct am_state state;
1570 int keep_cr = -1;
1571 int patch_format = PATCH_FORMAT_UNKNOWN;
1572 enum resume_mode resume = RESUME_FALSE;
1574 const char * const usage[] = {
1575 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1576 N_("git am [options] (--continue | --skip | --abort)"),
1577 NULL
1580 struct option options[] = {
1581 OPT_BOOL('3', "3way", &state.threeway,
1582 N_("allow fall back on 3way merging if needed")),
1583 OPT__QUIET(&state.quiet, N_("be quiet")),
1584 OPT_BOOL('s', "signoff", &state.signoff,
1585 N_("add a Signed-off-by line to the commit message")),
1586 OPT_BOOL('u', "utf8", &state.utf8,
1587 N_("recode into utf8 (default)")),
1588 OPT_SET_INT('k', "keep", &state.keep,
1589 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1590 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1591 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1592 OPT_BOOL('m', "message-id", &state.message_id,
1593 N_("pass -m flag to git-mailinfo")),
1594 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1595 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1596 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1597 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1598 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1599 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
1600 OPT_BOOL('c', "scissors", &state.scissors,
1601 N_("strip everything before a scissors line")),
1602 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1603 N_("format the patch(es) are in"),
1604 parse_opt_patchformat),
1605 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1606 N_("override error message when patch failure occurs")),
1607 OPT_CMDMODE(0, "continue", &resume,
1608 N_("continue applying patches after resolving a conflict"),
1609 RESUME_RESOLVED),
1610 OPT_CMDMODE('r', "resolved", &resume,
1611 N_("synonyms for --continue"),
1612 RESUME_RESOLVED),
1613 OPT_CMDMODE(0, "skip", &resume,
1614 N_("skip the current patch"),
1615 RESUME_SKIP),
1616 OPT_CMDMODE(0, "abort", &resume,
1617 N_("restore the original branch and abort the patching operation."),
1618 RESUME_ABORT),
1619 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1620 N_("(internal use for git-rebase)")),
1621 OPT_END()
1625 * NEEDSWORK: Once all the features of git-am.sh have been
1626 * re-implemented in builtin/am.c, this preamble can be removed.
1628 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1629 const char *path = mkpath("%s/git-am", git_exec_path());
1631 if (sane_execvp(path, (char **)argv) < 0)
1632 die_errno("could not exec %s", path);
1633 } else {
1634 prefix = setup_git_directory();
1635 trace_repo_setup(prefix);
1636 setup_work_tree();
1639 git_config(git_default_config, NULL);
1641 am_state_init(&state, git_path("rebase-apply"));
1643 argc = parse_options(argc, argv, prefix, options, usage, 0);
1645 if (read_index_preload(&the_index, NULL) < 0)
1646 die(_("failed to read the index"));
1648 if (am_in_progress(&state)) {
1650 * Catch user error to feed us patches when there is a session
1651 * in progress:
1653 * 1. mbox path(s) are provided on the command-line.
1654 * 2. stdin is not a tty: the user is trying to feed us a patch
1655 * from standard input. This is somewhat unreliable -- stdin
1656 * could be /dev/null for example and the caller did not
1657 * intend to feed us a patch but wanted to continue
1658 * unattended.
1660 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1661 die(_("previous rebase directory %s still exists but mbox given."),
1662 state.dir);
1664 if (resume == RESUME_FALSE)
1665 resume = RESUME_APPLY;
1667 am_load(&state);
1668 } else {
1669 struct argv_array paths = ARGV_ARRAY_INIT;
1670 int i;
1673 * Handle stray state directory in the independent-run case. In
1674 * the --rebasing case, it is up to the caller to take care of
1675 * stray directories.
1677 if (file_exists(state.dir) && !state.rebasing) {
1678 if (resume == RESUME_ABORT) {
1679 am_destroy(&state);
1680 am_state_release(&state);
1681 return 0;
1684 die(_("Stray %s directory found.\n"
1685 "Use \"git am --abort\" to remove it."),
1686 state.dir);
1689 if (resume)
1690 die(_("Resolve operation not in progress, we are not resuming."));
1692 for (i = 0; i < argc; i++) {
1693 if (is_absolute_path(argv[i]) || !prefix)
1694 argv_array_push(&paths, argv[i]);
1695 else
1696 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1699 am_setup(&state, patch_format, paths.argv, keep_cr);
1701 argv_array_clear(&paths);
1704 switch (resume) {
1705 case RESUME_FALSE:
1706 am_run(&state, 0);
1707 break;
1708 case RESUME_APPLY:
1709 am_run(&state, 1);
1710 break;
1711 case RESUME_RESOLVED:
1712 am_resolve(&state);
1713 break;
1714 case RESUME_SKIP:
1715 am_skip(&state);
1716 break;
1717 case RESUME_ABORT:
1718 am_abort(&state);
1719 break;
1720 default:
1721 die("BUG: invalid resume value");
1724 am_state_release(&state);
1726 return 0;