builtin-am: implement --committer-date-is-author-date
[git.git] / builtin / am.c
blob1561580de490de6d7af68d7b931b4bbc0c5e2e56
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 committer_date_is_author_date;
112 int ignore_date;
113 int rebasing;
117 * Initializes am_state with the default values. The state directory is set to
118 * dir.
120 static void am_state_init(struct am_state *state, const char *dir)
122 memset(state, 0, sizeof(*state));
124 assert(dir);
125 state->dir = xstrdup(dir);
127 state->prec = 4;
129 state->utf8 = 1;
131 git_config_get_bool("am.messageid", &state->message_id);
133 state->scissors = SCISSORS_UNSET;
135 argv_array_init(&state->git_apply_opts);
139 * Releases memory allocated by an am_state.
141 static void am_state_release(struct am_state *state)
143 free(state->dir);
144 free(state->author_name);
145 free(state->author_email);
146 free(state->author_date);
147 free(state->msg);
148 argv_array_clear(&state->git_apply_opts);
152 * Returns path relative to the am_state directory.
154 static inline const char *am_path(const struct am_state *state, const char *path)
156 return mkpath("%s/%s", state->dir, path);
160 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
161 * at the end.
163 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
165 va_list ap;
167 va_start(ap, fmt);
168 if (!state->quiet) {
169 vfprintf(fp, fmt, ap);
170 putc('\n', fp);
172 va_end(ap);
176 * Returns 1 if there is an am session in progress, 0 otherwise.
178 static int am_in_progress(const struct am_state *state)
180 struct stat st;
182 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
183 return 0;
184 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
185 return 0;
186 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
187 return 0;
188 return 1;
192 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
193 * number of bytes read on success, -1 if the file does not exist. If `trim` is
194 * set, trailing whitespace will be removed.
196 static int read_state_file(struct strbuf *sb, const struct am_state *state,
197 const char *file, int trim)
199 strbuf_reset(sb);
201 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
202 if (trim)
203 strbuf_trim(sb);
205 return sb->len;
208 if (errno == ENOENT)
209 return -1;
211 die_errno(_("could not read '%s'"), am_path(state, file));
215 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
216 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
217 * match `key`. Returns NULL on failure.
219 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
220 * the author-script.
222 static char *read_shell_var(FILE *fp, const char *key)
224 struct strbuf sb = STRBUF_INIT;
225 const char *str;
227 if (strbuf_getline(&sb, fp, '\n'))
228 goto fail;
230 if (!skip_prefix(sb.buf, key, &str))
231 goto fail;
233 if (!skip_prefix(str, "=", &str))
234 goto fail;
236 strbuf_remove(&sb, 0, str - sb.buf);
238 str = sq_dequote(sb.buf);
239 if (!str)
240 goto fail;
242 return strbuf_detach(&sb, NULL);
244 fail:
245 strbuf_release(&sb);
246 return NULL;
250 * Reads and parses the state directory's "author-script" file, and sets
251 * state->author_name, state->author_email and state->author_date accordingly.
252 * Returns 0 on success, -1 if the file could not be parsed.
254 * The author script is of the format:
256 * GIT_AUTHOR_NAME='$author_name'
257 * GIT_AUTHOR_EMAIL='$author_email'
258 * GIT_AUTHOR_DATE='$author_date'
260 * where $author_name, $author_email and $author_date are quoted. We are strict
261 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
262 * script, and thus if the file differs from what this function expects, it is
263 * better to bail out than to do something that the user does not expect.
265 static int read_author_script(struct am_state *state)
267 const char *filename = am_path(state, "author-script");
268 FILE *fp;
270 assert(!state->author_name);
271 assert(!state->author_email);
272 assert(!state->author_date);
274 fp = fopen(filename, "r");
275 if (!fp) {
276 if (errno == ENOENT)
277 return 0;
278 die_errno(_("could not open '%s' for reading"), filename);
281 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
282 if (!state->author_name) {
283 fclose(fp);
284 return -1;
287 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
288 if (!state->author_email) {
289 fclose(fp);
290 return -1;
293 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
294 if (!state->author_date) {
295 fclose(fp);
296 return -1;
299 if (fgetc(fp) != EOF) {
300 fclose(fp);
301 return -1;
304 fclose(fp);
305 return 0;
309 * Saves state->author_name, state->author_email and state->author_date in the
310 * state directory's "author-script" file.
312 static void write_author_script(const struct am_state *state)
314 struct strbuf sb = STRBUF_INIT;
316 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
317 sq_quote_buf(&sb, state->author_name);
318 strbuf_addch(&sb, '\n');
320 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
321 sq_quote_buf(&sb, state->author_email);
322 strbuf_addch(&sb, '\n');
324 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
325 sq_quote_buf(&sb, state->author_date);
326 strbuf_addch(&sb, '\n');
328 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
330 strbuf_release(&sb);
334 * Reads the commit message from the state directory's "final-commit" file,
335 * setting state->msg to its contents and state->msg_len to the length of its
336 * contents in bytes.
338 * Returns 0 on success, -1 if the file does not exist.
340 static int read_commit_msg(struct am_state *state)
342 struct strbuf sb = STRBUF_INIT;
344 assert(!state->msg);
346 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
347 strbuf_release(&sb);
348 return -1;
351 state->msg = strbuf_detach(&sb, &state->msg_len);
352 return 0;
356 * Saves state->msg in the state directory's "final-commit" file.
358 static void write_commit_msg(const struct am_state *state)
360 int fd;
361 const char *filename = am_path(state, "final-commit");
363 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
364 if (write_in_full(fd, state->msg, state->msg_len) < 0)
365 die_errno(_("could not write to %s"), filename);
366 close(fd);
370 * Loads state from disk.
372 static void am_load(struct am_state *state)
374 struct strbuf sb = STRBUF_INIT;
376 if (read_state_file(&sb, state, "next", 1) < 0)
377 die("BUG: state file 'next' does not exist");
378 state->cur = strtol(sb.buf, NULL, 10);
380 if (read_state_file(&sb, state, "last", 1) < 0)
381 die("BUG: state file 'last' does not exist");
382 state->last = strtol(sb.buf, NULL, 10);
384 if (read_author_script(state) < 0)
385 die(_("could not parse author script"));
387 read_commit_msg(state);
389 read_state_file(&sb, state, "threeway", 1);
390 state->threeway = !strcmp(sb.buf, "t");
392 read_state_file(&sb, state, "quiet", 1);
393 state->quiet = !strcmp(sb.buf, "t");
395 read_state_file(&sb, state, "sign", 1);
396 state->signoff = !strcmp(sb.buf, "t");
398 read_state_file(&sb, state, "utf8", 1);
399 state->utf8 = !strcmp(sb.buf, "t");
401 read_state_file(&sb, state, "keep", 1);
402 if (!strcmp(sb.buf, "t"))
403 state->keep = KEEP_TRUE;
404 else if (!strcmp(sb.buf, "b"))
405 state->keep = KEEP_NON_PATCH;
406 else
407 state->keep = KEEP_FALSE;
409 read_state_file(&sb, state, "messageid", 1);
410 state->message_id = !strcmp(sb.buf, "t");
412 read_state_file(&sb, state, "scissors", 1);
413 if (!strcmp(sb.buf, "t"))
414 state->scissors = SCISSORS_TRUE;
415 else if (!strcmp(sb.buf, "f"))
416 state->scissors = SCISSORS_FALSE;
417 else
418 state->scissors = SCISSORS_UNSET;
420 read_state_file(&sb, state, "apply-opt", 1);
421 argv_array_clear(&state->git_apply_opts);
422 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
423 die(_("could not parse %s"), am_path(state, "apply-opt"));
425 state->rebasing = !!file_exists(am_path(state, "rebasing"));
427 strbuf_release(&sb);
431 * Removes the am_state directory, forcefully terminating the current am
432 * session.
434 static void am_destroy(const struct am_state *state)
436 struct strbuf sb = STRBUF_INIT;
438 strbuf_addstr(&sb, state->dir);
439 remove_dir_recursively(&sb, 0);
440 strbuf_release(&sb);
444 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
445 * non-indented lines and checking if they look like they begin with valid
446 * header field names.
448 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
450 static int is_mail(FILE *fp)
452 const char *header_regex = "^[!-9;-~]+:";
453 struct strbuf sb = STRBUF_INIT;
454 regex_t regex;
455 int ret = 1;
457 if (fseek(fp, 0L, SEEK_SET))
458 die_errno(_("fseek failed"));
460 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
461 die("invalid pattern: %s", header_regex);
463 while (!strbuf_getline_crlf(&sb, fp)) {
464 if (!sb.len)
465 break; /* End of header */
467 /* Ignore indented folded lines */
468 if (*sb.buf == '\t' || *sb.buf == ' ')
469 continue;
471 /* It's a header if it matches header_regex */
472 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
473 ret = 0;
474 goto done;
478 done:
479 regfree(&regex);
480 strbuf_release(&sb);
481 return ret;
485 * Attempts to detect the patch_format of the patches contained in `paths`,
486 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
487 * detection fails.
489 static int detect_patch_format(const char **paths)
491 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
492 struct strbuf l1 = STRBUF_INIT;
493 FILE *fp;
496 * We default to mbox format if input is from stdin and for directories
498 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
499 return PATCH_FORMAT_MBOX;
502 * Otherwise, check the first few lines of the first patch, starting
503 * from the first non-blank line, to try to detect its format.
506 fp = xfopen(*paths, "r");
508 while (!strbuf_getline_crlf(&l1, fp)) {
509 if (l1.len)
510 break;
513 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
514 ret = PATCH_FORMAT_MBOX;
515 goto done;
518 if (l1.len && is_mail(fp)) {
519 ret = PATCH_FORMAT_MBOX;
520 goto done;
523 done:
524 fclose(fp);
525 strbuf_release(&l1);
526 return ret;
530 * Splits out individual email patches from `paths`, where each path is either
531 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
533 static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
535 struct child_process cp = CHILD_PROCESS_INIT;
536 struct strbuf last = STRBUF_INIT;
538 cp.git_cmd = 1;
539 argv_array_push(&cp.args, "mailsplit");
540 argv_array_pushf(&cp.args, "-d%d", state->prec);
541 argv_array_pushf(&cp.args, "-o%s", state->dir);
542 argv_array_push(&cp.args, "-b");
543 if (keep_cr)
544 argv_array_push(&cp.args, "--keep-cr");
545 argv_array_push(&cp.args, "--");
546 argv_array_pushv(&cp.args, paths);
548 if (capture_command(&cp, &last, 8))
549 return -1;
551 state->cur = 1;
552 state->last = strtol(last.buf, NULL, 10);
554 return 0;
558 * Splits a list of files/directories into individual email patches. Each path
559 * in `paths` must be a file/directory that is formatted according to
560 * `patch_format`.
562 * Once split out, the individual email patches will be stored in the state
563 * directory, with each patch's filename being its index, padded to state->prec
564 * digits.
566 * state->cur will be set to the index of the first mail, and state->last will
567 * be set to the index of the last mail.
569 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
570 * to disable this behavior, -1 to use the default configured setting.
572 * Returns 0 on success, -1 on failure.
574 static int split_mail(struct am_state *state, enum patch_format patch_format,
575 const char **paths, int keep_cr)
577 if (keep_cr < 0) {
578 keep_cr = 0;
579 git_config_get_bool("am.keepcr", &keep_cr);
582 switch (patch_format) {
583 case PATCH_FORMAT_MBOX:
584 return split_mail_mbox(state, paths, keep_cr);
585 default:
586 die("BUG: invalid patch_format");
588 return -1;
592 * Setup a new am session for applying patches
594 static void am_setup(struct am_state *state, enum patch_format patch_format,
595 const char **paths, int keep_cr)
597 unsigned char curr_head[GIT_SHA1_RAWSZ];
598 const char *str;
599 struct strbuf sb = STRBUF_INIT;
601 if (!patch_format)
602 patch_format = detect_patch_format(paths);
604 if (!patch_format) {
605 fprintf_ln(stderr, _("Patch format detection failed."));
606 exit(128);
609 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
610 die_errno(_("failed to create directory '%s'"), state->dir);
612 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
613 am_destroy(state);
614 die(_("Failed to split patches."));
617 if (state->rebasing)
618 state->threeway = 1;
620 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
622 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
624 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
626 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
628 switch (state->keep) {
629 case KEEP_FALSE:
630 str = "f";
631 break;
632 case KEEP_TRUE:
633 str = "t";
634 break;
635 case KEEP_NON_PATCH:
636 str = "b";
637 break;
638 default:
639 die("BUG: invalid value for state->keep");
642 write_file(am_path(state, "keep"), 1, "%s", str);
644 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
646 switch (state->scissors) {
647 case SCISSORS_UNSET:
648 str = "";
649 break;
650 case SCISSORS_FALSE:
651 str = "f";
652 break;
653 case SCISSORS_TRUE:
654 str = "t";
655 break;
656 default:
657 die("BUG: invalid value for state->scissors");
660 write_file(am_path(state, "scissors"), 1, "%s", str);
662 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
663 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
665 if (state->rebasing)
666 write_file(am_path(state, "rebasing"), 1, "%s", "");
667 else
668 write_file(am_path(state, "applying"), 1, "%s", "");
670 if (!get_sha1("HEAD", curr_head)) {
671 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
672 if (!state->rebasing)
673 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
674 UPDATE_REFS_DIE_ON_ERR);
675 } else {
676 write_file(am_path(state, "abort-safety"), 1, "%s", "");
677 if (!state->rebasing)
678 delete_ref("ORIG_HEAD", NULL, 0);
682 * NOTE: Since the "next" and "last" files determine if an am_state
683 * session is in progress, they should be written last.
686 write_file(am_path(state, "next"), 1, "%d", state->cur);
688 write_file(am_path(state, "last"), 1, "%d", state->last);
690 strbuf_release(&sb);
694 * Increments the patch pointer, and cleans am_state for the application of the
695 * next patch.
697 static void am_next(struct am_state *state)
699 unsigned char head[GIT_SHA1_RAWSZ];
701 free(state->author_name);
702 state->author_name = NULL;
704 free(state->author_email);
705 state->author_email = NULL;
707 free(state->author_date);
708 state->author_date = NULL;
710 free(state->msg);
711 state->msg = NULL;
712 state->msg_len = 0;
714 unlink(am_path(state, "author-script"));
715 unlink(am_path(state, "final-commit"));
717 if (!get_sha1("HEAD", head))
718 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
719 else
720 write_file(am_path(state, "abort-safety"), 1, "%s", "");
722 state->cur++;
723 write_file(am_path(state, "next"), 1, "%d", state->cur);
727 * Returns the filename of the current patch email.
729 static const char *msgnum(const struct am_state *state)
731 static struct strbuf sb = STRBUF_INIT;
733 strbuf_reset(&sb);
734 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
736 return sb.buf;
740 * Refresh and write index.
742 static void refresh_and_write_cache(void)
744 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
746 hold_locked_index(lock_file, 1);
747 refresh_cache(REFRESH_QUIET);
748 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
749 die(_("unable to write index file"));
753 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
754 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
755 * strbuf is provided, the space-separated list of files that differ will be
756 * appended to it.
758 static int index_has_changes(struct strbuf *sb)
760 unsigned char head[GIT_SHA1_RAWSZ];
761 int i;
763 if (!get_sha1_tree("HEAD", head)) {
764 struct diff_options opt;
766 diff_setup(&opt);
767 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
768 if (!sb)
769 DIFF_OPT_SET(&opt, QUICK);
770 do_diff_cache(head, &opt);
771 diffcore_std(&opt);
772 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
773 if (i)
774 strbuf_addch(sb, ' ');
775 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
777 diff_flush(&opt);
778 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
779 } else {
780 for (i = 0; sb && i < active_nr; i++) {
781 if (i)
782 strbuf_addch(sb, ' ');
783 strbuf_addstr(sb, active_cache[i]->name);
785 return !!active_nr;
790 * Dies with a user-friendly message on how to proceed after resolving the
791 * problem. This message can be overridden with state->resolvemsg.
793 static void NORETURN die_user_resolve(const struct am_state *state)
795 if (state->resolvemsg) {
796 printf_ln("%s", state->resolvemsg);
797 } else {
798 const char *cmdline = "git am";
800 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
801 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
802 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
805 exit(128);
809 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
810 * state->msg will be set to the patch message. state->author_name,
811 * state->author_email and state->author_date will be set to the patch author's
812 * name, email and date respectively. The patch body will be written to the
813 * state directory's "patch" file.
815 * Returns 1 if the patch should be skipped, 0 otherwise.
817 static int parse_mail(struct am_state *state, const char *mail)
819 FILE *fp;
820 struct child_process cp = CHILD_PROCESS_INIT;
821 struct strbuf sb = STRBUF_INIT;
822 struct strbuf msg = STRBUF_INIT;
823 struct strbuf author_name = STRBUF_INIT;
824 struct strbuf author_date = STRBUF_INIT;
825 struct strbuf author_email = STRBUF_INIT;
826 int ret = 0;
828 cp.git_cmd = 1;
829 cp.in = xopen(mail, O_RDONLY, 0);
830 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
832 argv_array_push(&cp.args, "mailinfo");
833 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
835 switch (state->keep) {
836 case KEEP_FALSE:
837 break;
838 case KEEP_TRUE:
839 argv_array_push(&cp.args, "-k");
840 break;
841 case KEEP_NON_PATCH:
842 argv_array_push(&cp.args, "-b");
843 break;
844 default:
845 die("BUG: invalid value for state->keep");
848 if (state->message_id)
849 argv_array_push(&cp.args, "-m");
851 switch (state->scissors) {
852 case SCISSORS_UNSET:
853 break;
854 case SCISSORS_FALSE:
855 argv_array_push(&cp.args, "--no-scissors");
856 break;
857 case SCISSORS_TRUE:
858 argv_array_push(&cp.args, "--scissors");
859 break;
860 default:
861 die("BUG: invalid value for state->scissors");
864 argv_array_push(&cp.args, am_path(state, "msg"));
865 argv_array_push(&cp.args, am_path(state, "patch"));
867 if (run_command(&cp) < 0)
868 die("could not parse patch");
870 close(cp.in);
871 close(cp.out);
873 /* Extract message and author information */
874 fp = xfopen(am_path(state, "info"), "r");
875 while (!strbuf_getline(&sb, fp, '\n')) {
876 const char *x;
878 if (skip_prefix(sb.buf, "Subject: ", &x)) {
879 if (msg.len)
880 strbuf_addch(&msg, '\n');
881 strbuf_addstr(&msg, x);
882 } else if (skip_prefix(sb.buf, "Author: ", &x))
883 strbuf_addstr(&author_name, x);
884 else if (skip_prefix(sb.buf, "Email: ", &x))
885 strbuf_addstr(&author_email, x);
886 else if (skip_prefix(sb.buf, "Date: ", &x))
887 strbuf_addstr(&author_date, x);
889 fclose(fp);
891 /* Skip pine's internal folder data */
892 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
893 ret = 1;
894 goto finish;
897 if (is_empty_file(am_path(state, "patch"))) {
898 printf_ln(_("Patch is empty. Was it split wrong?"));
899 die_user_resolve(state);
902 strbuf_addstr(&msg, "\n\n");
903 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
904 die_errno(_("could not read '%s'"), am_path(state, "msg"));
905 stripspace(&msg, 0);
907 if (state->signoff)
908 append_signoff(&msg, 0, 0);
910 assert(!state->author_name);
911 state->author_name = strbuf_detach(&author_name, NULL);
913 assert(!state->author_email);
914 state->author_email = strbuf_detach(&author_email, NULL);
916 assert(!state->author_date);
917 state->author_date = strbuf_detach(&author_date, NULL);
919 assert(!state->msg);
920 state->msg = strbuf_detach(&msg, &state->msg_len);
922 finish:
923 strbuf_release(&msg);
924 strbuf_release(&author_date);
925 strbuf_release(&author_email);
926 strbuf_release(&author_name);
927 strbuf_release(&sb);
928 return ret;
932 * Sets commit_id to the commit hash where the mail was generated from.
933 * Returns 0 on success, -1 on failure.
935 static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
937 struct strbuf sb = STRBUF_INIT;
938 FILE *fp = xfopen(mail, "r");
939 const char *x;
941 if (strbuf_getline(&sb, fp, '\n'))
942 return -1;
944 if (!skip_prefix(sb.buf, "From ", &x))
945 return -1;
947 if (get_sha1_hex(x, commit_id) < 0)
948 return -1;
950 strbuf_release(&sb);
951 fclose(fp);
952 return 0;
956 * Sets state->msg, state->author_name, state->author_email, state->author_date
957 * to the commit's respective info.
959 static void get_commit_info(struct am_state *state, struct commit *commit)
961 const char *buffer, *ident_line, *author_date, *msg;
962 size_t ident_len;
963 struct ident_split ident_split;
964 struct strbuf sb = STRBUF_INIT;
966 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
968 ident_line = find_commit_header(buffer, "author", &ident_len);
970 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
971 strbuf_add(&sb, ident_line, ident_len);
972 die(_("invalid ident line: %s"), sb.buf);
975 assert(!state->author_name);
976 if (ident_split.name_begin) {
977 strbuf_add(&sb, ident_split.name_begin,
978 ident_split.name_end - ident_split.name_begin);
979 state->author_name = strbuf_detach(&sb, NULL);
980 } else
981 state->author_name = xstrdup("");
983 assert(!state->author_email);
984 if (ident_split.mail_begin) {
985 strbuf_add(&sb, ident_split.mail_begin,
986 ident_split.mail_end - ident_split.mail_begin);
987 state->author_email = strbuf_detach(&sb, NULL);
988 } else
989 state->author_email = xstrdup("");
991 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
992 strbuf_addstr(&sb, author_date);
993 assert(!state->author_date);
994 state->author_date = strbuf_detach(&sb, NULL);
996 assert(!state->msg);
997 msg = strstr(buffer, "\n\n");
998 if (!msg)
999 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1000 state->msg = xstrdup(msg + 2);
1001 state->msg_len = strlen(state->msg);
1005 * Writes `commit` as a patch to the state directory's "patch" file.
1007 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1009 struct rev_info rev_info;
1010 FILE *fp;
1012 fp = xfopen(am_path(state, "patch"), "w");
1013 init_revisions(&rev_info, NULL);
1014 rev_info.diff = 1;
1015 rev_info.abbrev = 0;
1016 rev_info.disable_stdin = 1;
1017 rev_info.show_root_diff = 1;
1018 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1019 rev_info.no_commit_id = 1;
1020 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1021 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1022 rev_info.diffopt.use_color = 0;
1023 rev_info.diffopt.file = fp;
1024 rev_info.diffopt.close_file = 1;
1025 add_pending_object(&rev_info, &commit->object, "");
1026 diff_setup_done(&rev_info.diffopt);
1027 log_tree_commit(&rev_info, commit);
1031 * Like parse_mail(), but parses the mail by looking up its commit ID
1032 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1033 * of patches.
1035 * Will always return 0 as the patch should never be skipped.
1037 static int parse_mail_rebase(struct am_state *state, const char *mail)
1039 struct commit *commit;
1040 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1042 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1043 die(_("could not parse %s"), mail);
1045 commit = lookup_commit_or_die(commit_sha1, mail);
1047 get_commit_info(state, commit);
1049 write_commit_patch(state, commit);
1051 return 0;
1055 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1056 * `index_file` is not NULL, the patch will be applied to that index.
1058 static int run_apply(const struct am_state *state, const char *index_file)
1060 struct child_process cp = CHILD_PROCESS_INIT;
1062 cp.git_cmd = 1;
1064 if (index_file)
1065 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1068 * If we are allowed to fall back on 3-way merge, don't give false
1069 * errors during the initial attempt.
1071 if (state->threeway && !index_file) {
1072 cp.no_stdout = 1;
1073 cp.no_stderr = 1;
1076 argv_array_push(&cp.args, "apply");
1078 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1080 if (index_file)
1081 argv_array_push(&cp.args, "--cached");
1082 else
1083 argv_array_push(&cp.args, "--index");
1085 argv_array_push(&cp.args, am_path(state, "patch"));
1087 if (run_command(&cp))
1088 return -1;
1090 /* Reload index as git-apply will have modified it. */
1091 discard_cache();
1092 read_cache_from(index_file ? index_file : get_index_file());
1094 return 0;
1098 * Builds an index that contains just the blobs needed for a 3way merge.
1100 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1102 struct child_process cp = CHILD_PROCESS_INIT;
1104 cp.git_cmd = 1;
1105 argv_array_push(&cp.args, "apply");
1106 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1107 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1108 argv_array_push(&cp.args, am_path(state, "patch"));
1110 if (run_command(&cp))
1111 return -1;
1113 return 0;
1117 * Attempt a threeway merge, using index_path as the temporary index.
1119 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1121 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1122 our_tree[GIT_SHA1_RAWSZ];
1123 const unsigned char *bases[1] = {orig_tree};
1124 struct merge_options o;
1125 struct commit *result;
1126 char *his_tree_name;
1128 if (get_sha1("HEAD", our_tree) < 0)
1129 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1131 if (build_fake_ancestor(state, index_path))
1132 return error("could not build fake ancestor");
1134 discard_cache();
1135 read_cache_from(index_path);
1137 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1138 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1140 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1142 if (!state->quiet) {
1144 * List paths that needed 3-way fallback, so that the user can
1145 * review them with extra care to spot mismerges.
1147 struct rev_info rev_info;
1148 const char *diff_filter_str = "--diff-filter=AM";
1150 init_revisions(&rev_info, NULL);
1151 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1152 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1153 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1154 diff_setup_done(&rev_info.diffopt);
1155 run_diff_index(&rev_info, 1);
1158 if (run_apply(state, index_path))
1159 return error(_("Did you hand edit your patch?\n"
1160 "It does not apply to blobs recorded in its index."));
1162 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1163 return error("could not write tree");
1165 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1167 discard_cache();
1168 read_cache();
1171 * This is not so wrong. Depending on which base we picked, orig_tree
1172 * may be wildly different from ours, but his_tree has the same set of
1173 * wildly different changes in parts the patch did not touch, so
1174 * recursive ends up canceling them, saying that we reverted all those
1175 * changes.
1178 init_merge_options(&o);
1180 o.branch1 = "HEAD";
1181 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1182 o.branch2 = his_tree_name;
1184 if (state->quiet)
1185 o.verbosity = 0;
1187 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
1188 free(his_tree_name);
1189 return error(_("Failed to merge in the changes."));
1192 free(his_tree_name);
1193 return 0;
1197 * Commits the current index with state->msg as the commit message and
1198 * state->author_name, state->author_email and state->author_date as the author
1199 * information.
1201 static void do_commit(const struct am_state *state)
1203 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1204 commit[GIT_SHA1_RAWSZ];
1205 unsigned char *ptr;
1206 struct commit_list *parents = NULL;
1207 const char *reflog_msg, *author;
1208 struct strbuf sb = STRBUF_INIT;
1210 if (write_cache_as_tree(tree, 0, NULL))
1211 die(_("git write-tree failed to write a tree"));
1213 if (!get_sha1_commit("HEAD", parent)) {
1214 ptr = parent;
1215 commit_list_insert(lookup_commit(parent), &parents);
1216 } else {
1217 ptr = NULL;
1218 say(state, stderr, _("applying to an empty history"));
1221 author = fmt_ident(state->author_name, state->author_email,
1222 state->ignore_date ? NULL : state->author_date,
1223 IDENT_STRICT);
1225 if (state->committer_date_is_author_date)
1226 setenv("GIT_COMMITTER_DATE",
1227 state->ignore_date ? "" : state->author_date, 1);
1229 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
1230 author, NULL))
1231 die(_("failed to write commit object"));
1233 reflog_msg = getenv("GIT_REFLOG_ACTION");
1234 if (!reflog_msg)
1235 reflog_msg = "am";
1237 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1238 state->msg);
1240 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1242 strbuf_release(&sb);
1246 * Validates the am_state for resuming -- the "msg" and authorship fields must
1247 * be filled up.
1249 static void validate_resume_state(const struct am_state *state)
1251 if (!state->msg)
1252 die(_("cannot resume: %s does not exist."),
1253 am_path(state, "final-commit"));
1255 if (!state->author_name || !state->author_email || !state->author_date)
1256 die(_("cannot resume: %s does not exist."),
1257 am_path(state, "author-script"));
1261 * Applies all queued mail.
1263 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1264 * well as the state directory's "patch" file is used as-is for applying the
1265 * patch and committing it.
1267 static void am_run(struct am_state *state, int resume)
1269 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1270 struct strbuf sb = STRBUF_INIT;
1272 unlink(am_path(state, "dirtyindex"));
1274 refresh_and_write_cache();
1276 if (index_has_changes(&sb)) {
1277 write_file(am_path(state, "dirtyindex"), 1, "t");
1278 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1281 strbuf_release(&sb);
1283 while (state->cur <= state->last) {
1284 const char *mail = am_path(state, msgnum(state));
1285 int apply_status;
1287 if (!file_exists(mail))
1288 goto next;
1290 if (resume) {
1291 validate_resume_state(state);
1292 resume = 0;
1293 } else {
1294 int skip;
1296 if (state->rebasing)
1297 skip = parse_mail_rebase(state, mail);
1298 else
1299 skip = parse_mail(state, mail);
1301 if (skip)
1302 goto next; /* mail should be skipped */
1304 write_author_script(state);
1305 write_commit_msg(state);
1308 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1310 apply_status = run_apply(state, NULL);
1312 if (apply_status && state->threeway) {
1313 struct strbuf sb = STRBUF_INIT;
1315 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1316 apply_status = fall_back_threeway(state, sb.buf);
1317 strbuf_release(&sb);
1320 * Applying the patch to an earlier tree and merging
1321 * the result may have produced the same tree as ours.
1323 if (!apply_status && !index_has_changes(NULL)) {
1324 say(state, stdout, _("No changes -- Patch already applied."));
1325 goto next;
1329 if (apply_status) {
1330 int advice_amworkdir = 1;
1332 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1333 linelen(state->msg), state->msg);
1335 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1337 if (advice_amworkdir)
1338 printf_ln(_("The copy of the patch that failed is found in: %s"),
1339 am_path(state, "patch"));
1341 die_user_resolve(state);
1344 do_commit(state);
1346 next:
1347 am_next(state);
1351 * In rebasing mode, it's up to the caller to take care of
1352 * housekeeping.
1354 if (!state->rebasing) {
1355 am_destroy(state);
1356 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1361 * Resume the current am session after patch application failure. The user did
1362 * all the hard work, and we do not have to do any patch application. Just
1363 * trust and commit what the user has in the index and working tree.
1365 static void am_resolve(struct am_state *state)
1367 validate_resume_state(state);
1369 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1371 if (!index_has_changes(NULL)) {
1372 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1373 "If there is nothing left to stage, chances are that something else\n"
1374 "already introduced the same changes; you might want to skip this patch."));
1375 die_user_resolve(state);
1378 if (unmerged_cache()) {
1379 printf_ln(_("You still have unmerged paths in your index.\n"
1380 "Did you forget to use 'git add'?"));
1381 die_user_resolve(state);
1384 do_commit(state);
1386 am_next(state);
1387 am_run(state, 0);
1391 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1392 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1393 * failure.
1395 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1397 struct lock_file *lock_file;
1398 struct unpack_trees_options opts;
1399 struct tree_desc t[2];
1401 if (parse_tree(head) || parse_tree(remote))
1402 return -1;
1404 lock_file = xcalloc(1, sizeof(struct lock_file));
1405 hold_locked_index(lock_file, 1);
1407 refresh_cache(REFRESH_QUIET);
1409 memset(&opts, 0, sizeof(opts));
1410 opts.head_idx = 1;
1411 opts.src_index = &the_index;
1412 opts.dst_index = &the_index;
1413 opts.update = 1;
1414 opts.merge = 1;
1415 opts.reset = reset;
1416 opts.fn = twoway_merge;
1417 init_tree_desc(&t[0], head->buffer, head->size);
1418 init_tree_desc(&t[1], remote->buffer, remote->size);
1420 if (unpack_trees(2, t, &opts)) {
1421 rollback_lock_file(lock_file);
1422 return -1;
1425 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1426 die(_("unable to write new index file"));
1428 return 0;
1432 * Clean the index without touching entries that are not modified between
1433 * `head` and `remote`.
1435 static int clean_index(const unsigned char *head, const unsigned char *remote)
1437 struct lock_file *lock_file;
1438 struct tree *head_tree, *remote_tree, *index_tree;
1439 unsigned char index[GIT_SHA1_RAWSZ];
1440 struct pathspec pathspec;
1442 head_tree = parse_tree_indirect(head);
1443 if (!head_tree)
1444 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1446 remote_tree = parse_tree_indirect(remote);
1447 if (!remote_tree)
1448 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1450 read_cache_unmerged();
1452 if (fast_forward_to(head_tree, head_tree, 1))
1453 return -1;
1455 if (write_cache_as_tree(index, 0, NULL))
1456 return -1;
1458 index_tree = parse_tree_indirect(index);
1459 if (!index_tree)
1460 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1462 if (fast_forward_to(index_tree, remote_tree, 0))
1463 return -1;
1465 memset(&pathspec, 0, sizeof(pathspec));
1467 lock_file = xcalloc(1, sizeof(struct lock_file));
1468 hold_locked_index(lock_file, 1);
1470 if (read_tree(remote_tree, 0, &pathspec)) {
1471 rollback_lock_file(lock_file);
1472 return -1;
1475 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1476 die(_("unable to write new index file"));
1478 remove_branch_state();
1480 return 0;
1484 * Resume the current am session by skipping the current patch.
1486 static void am_skip(struct am_state *state)
1488 unsigned char head[GIT_SHA1_RAWSZ];
1490 if (get_sha1("HEAD", head))
1491 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1493 if (clean_index(head, head))
1494 die(_("failed to clean index"));
1496 am_next(state);
1497 am_run(state, 0);
1501 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1503 * It is not safe to reset HEAD when:
1504 * 1. git-am previously failed because the index was dirty.
1505 * 2. HEAD has moved since git-am previously failed.
1507 static int safe_to_abort(const struct am_state *state)
1509 struct strbuf sb = STRBUF_INIT;
1510 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1512 if (file_exists(am_path(state, "dirtyindex")))
1513 return 0;
1515 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1516 if (get_sha1_hex(sb.buf, abort_safety))
1517 die(_("could not parse %s"), am_path(state, "abort_safety"));
1518 } else
1519 hashclr(abort_safety);
1521 if (get_sha1("HEAD", head))
1522 hashclr(head);
1524 if (!hashcmp(head, abort_safety))
1525 return 1;
1527 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1528 "Not rewinding to ORIG_HEAD"));
1530 return 0;
1534 * Aborts the current am session if it is safe to do so.
1536 static void am_abort(struct am_state *state)
1538 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1539 int has_curr_head, has_orig_head;
1540 char *curr_branch;
1542 if (!safe_to_abort(state)) {
1543 am_destroy(state);
1544 return;
1547 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1548 has_curr_head = !is_null_sha1(curr_head);
1549 if (!has_curr_head)
1550 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1552 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1553 if (!has_orig_head)
1554 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1556 clean_index(curr_head, orig_head);
1558 if (has_orig_head)
1559 update_ref("am --abort", "HEAD", orig_head,
1560 has_curr_head ? curr_head : NULL, 0,
1561 UPDATE_REFS_DIE_ON_ERR);
1562 else if (curr_branch)
1563 delete_ref(curr_branch, NULL, REF_NODEREF);
1565 free(curr_branch);
1566 am_destroy(state);
1570 * parse_options() callback that validates and sets opt->value to the
1571 * PATCH_FORMAT_* enum value corresponding to `arg`.
1573 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1575 int *opt_value = opt->value;
1577 if (!strcmp(arg, "mbox"))
1578 *opt_value = PATCH_FORMAT_MBOX;
1579 else
1580 return error(_("Invalid value for --patch-format: %s"), arg);
1581 return 0;
1584 enum resume_mode {
1585 RESUME_FALSE = 0,
1586 RESUME_APPLY,
1587 RESUME_RESOLVED,
1588 RESUME_SKIP,
1589 RESUME_ABORT
1592 int cmd_am(int argc, const char **argv, const char *prefix)
1594 struct am_state state;
1595 int keep_cr = -1;
1596 int patch_format = PATCH_FORMAT_UNKNOWN;
1597 enum resume_mode resume = RESUME_FALSE;
1599 const char * const usage[] = {
1600 N_("git am [options] [(<mbox>|<Maildir>)...]"),
1601 N_("git am [options] (--continue | --skip | --abort)"),
1602 NULL
1605 struct option options[] = {
1606 OPT_BOOL('3', "3way", &state.threeway,
1607 N_("allow fall back on 3way merging if needed")),
1608 OPT__QUIET(&state.quiet, N_("be quiet")),
1609 OPT_BOOL('s', "signoff", &state.signoff,
1610 N_("add a Signed-off-by line to the commit message")),
1611 OPT_BOOL('u', "utf8", &state.utf8,
1612 N_("recode into utf8 (default)")),
1613 OPT_SET_INT('k', "keep", &state.keep,
1614 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1615 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1616 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
1617 OPT_BOOL('m', "message-id", &state.message_id,
1618 N_("pass -m flag to git-mailinfo")),
1619 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1620 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1621 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1622 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1623 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1624 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
1625 OPT_BOOL('c', "scissors", &state.scissors,
1626 N_("strip everything before a scissors line")),
1627 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
1628 N_("pass it through git-apply"),
1630 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
1631 N_("pass it through git-apply"),
1632 PARSE_OPT_NOARG),
1633 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
1634 N_("pass it through git-apply"),
1635 PARSE_OPT_NOARG),
1636 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
1637 N_("pass it through git-apply"),
1639 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
1640 N_("pass it through git-apply"),
1642 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
1643 N_("pass it through git-apply"),
1645 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
1646 N_("pass it through git-apply"),
1648 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
1649 N_("pass it through git-apply"),
1651 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1652 N_("format the patch(es) are in"),
1653 parse_opt_patchformat),
1654 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
1655 N_("pass it through git-apply"),
1656 PARSE_OPT_NOARG),
1657 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1658 N_("override error message when patch failure occurs")),
1659 OPT_CMDMODE(0, "continue", &resume,
1660 N_("continue applying patches after resolving a conflict"),
1661 RESUME_RESOLVED),
1662 OPT_CMDMODE('r', "resolved", &resume,
1663 N_("synonyms for --continue"),
1664 RESUME_RESOLVED),
1665 OPT_CMDMODE(0, "skip", &resume,
1666 N_("skip the current patch"),
1667 RESUME_SKIP),
1668 OPT_CMDMODE(0, "abort", &resume,
1669 N_("restore the original branch and abort the patching operation."),
1670 RESUME_ABORT),
1671 OPT_BOOL(0, "committer-date-is-author-date",
1672 &state.committer_date_is_author_date,
1673 N_("lie about committer date")),
1674 OPT_BOOL(0, "ignore-date", &state.ignore_date,
1675 N_("use current timestamp for author date")),
1676 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1677 N_("(internal use for git-rebase)")),
1678 OPT_END()
1682 * NEEDSWORK: Once all the features of git-am.sh have been
1683 * re-implemented in builtin/am.c, this preamble can be removed.
1685 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1686 const char *path = mkpath("%s/git-am", git_exec_path());
1688 if (sane_execvp(path, (char **)argv) < 0)
1689 die_errno("could not exec %s", path);
1690 } else {
1691 prefix = setup_git_directory();
1692 trace_repo_setup(prefix);
1693 setup_work_tree();
1696 git_config(git_default_config, NULL);
1698 am_state_init(&state, git_path("rebase-apply"));
1700 argc = parse_options(argc, argv, prefix, options, usage, 0);
1702 if (read_index_preload(&the_index, NULL) < 0)
1703 die(_("failed to read the index"));
1705 if (am_in_progress(&state)) {
1707 * Catch user error to feed us patches when there is a session
1708 * in progress:
1710 * 1. mbox path(s) are provided on the command-line.
1711 * 2. stdin is not a tty: the user is trying to feed us a patch
1712 * from standard input. This is somewhat unreliable -- stdin
1713 * could be /dev/null for example and the caller did not
1714 * intend to feed us a patch but wanted to continue
1715 * unattended.
1717 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1718 die(_("previous rebase directory %s still exists but mbox given."),
1719 state.dir);
1721 if (resume == RESUME_FALSE)
1722 resume = RESUME_APPLY;
1724 am_load(&state);
1725 } else {
1726 struct argv_array paths = ARGV_ARRAY_INIT;
1727 int i;
1730 * Handle stray state directory in the independent-run case. In
1731 * the --rebasing case, it is up to the caller to take care of
1732 * stray directories.
1734 if (file_exists(state.dir) && !state.rebasing) {
1735 if (resume == RESUME_ABORT) {
1736 am_destroy(&state);
1737 am_state_release(&state);
1738 return 0;
1741 die(_("Stray %s directory found.\n"
1742 "Use \"git am --abort\" to remove it."),
1743 state.dir);
1746 if (resume)
1747 die(_("Resolve operation not in progress, we are not resuming."));
1749 for (i = 0; i < argc; i++) {
1750 if (is_absolute_path(argv[i]) || !prefix)
1751 argv_array_push(&paths, argv[i]);
1752 else
1753 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1756 am_setup(&state, patch_format, paths.argv, keep_cr);
1758 argv_array_clear(&paths);
1761 switch (resume) {
1762 case RESUME_FALSE:
1763 am_run(&state, 0);
1764 break;
1765 case RESUME_APPLY:
1766 am_run(&state, 1);
1767 break;
1768 case RESUME_RESOLVED:
1769 am_resolve(&state);
1770 break;
1771 case RESUME_SKIP:
1772 am_skip(&state);
1773 break;
1774 case RESUME_ABORT:
1775 am_abort(&state);
1776 break;
1777 default:
1778 die("BUG: invalid resume value");
1781 am_state_release(&state);
1783 return 0;