Merge branch 'tb/delimit-pretty-trailers-args-with-comma'
[git] / builtin / am.c
1 /*
2  * Builtin "git am"
3  *
4  * Based on git-am.sh by Junio C Hamano.
5  */
6 #include "cache.h"
7 #include "config.h"
8 #include "builtin.h"
9 #include "exec_cmd.h"
10 #include "parse-options.h"
11 #include "dir.h"
12 #include "run-command.h"
13 #include "quote.h"
14 #include "tempfile.h"
15 #include "lockfile.h"
16 #include "cache-tree.h"
17 #include "refs.h"
18 #include "commit.h"
19 #include "diff.h"
20 #include "diffcore.h"
21 #include "unpack-trees.h"
22 #include "branch.h"
23 #include "sequencer.h"
24 #include "revision.h"
25 #include "merge-recursive.h"
26 #include "revision.h"
27 #include "log-tree.h"
28 #include "notes-utils.h"
29 #include "rerere.h"
30 #include "prompt.h"
31 #include "mailinfo.h"
32 #include "apply.h"
33 #include "string-list.h"
34 #include "packfile.h"
35
36 /**
37  * Returns 1 if the file is empty or does not exist, 0 otherwise.
38  */
39 static int is_empty_file(const char *filename)
40 {
41         struct stat st;
42
43         if (stat(filename, &st) < 0) {
44                 if (errno == ENOENT)
45                         return 1;
46                 die_errno(_("could not stat %s"), filename);
47         }
48
49         return !st.st_size;
50 }
51
52 /**
53  * Returns the length of the first line of msg.
54  */
55 static int linelen(const char *msg)
56 {
57         return strchrnul(msg, '\n') - msg;
58 }
59
60 /**
61  * Returns true if `str` consists of only whitespace, false otherwise.
62  */
63 static int str_isspace(const char *str)
64 {
65         for (; *str; str++)
66                 if (!isspace(*str))
67                         return 0;
68
69         return 1;
70 }
71
72 enum patch_format {
73         PATCH_FORMAT_UNKNOWN = 0,
74         PATCH_FORMAT_MBOX,
75         PATCH_FORMAT_STGIT,
76         PATCH_FORMAT_STGIT_SERIES,
77         PATCH_FORMAT_HG,
78         PATCH_FORMAT_MBOXRD
79 };
80
81 enum keep_type {
82         KEEP_FALSE = 0,
83         KEEP_TRUE,      /* pass -k flag to git-mailinfo */
84         KEEP_NON_PATCH  /* pass -b flag to git-mailinfo */
85 };
86
87 enum scissors_type {
88         SCISSORS_UNSET = -1,
89         SCISSORS_FALSE = 0,  /* pass --no-scissors to git-mailinfo */
90         SCISSORS_TRUE        /* pass --scissors to git-mailinfo */
91 };
92
93 enum signoff_type {
94         SIGNOFF_FALSE = 0,
95         SIGNOFF_TRUE = 1,
96         SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
97 };
98
99 struct am_state {
100         /* state directory path */
101         char *dir;
102
103         /* current and last patch numbers, 1-indexed */
104         int cur;
105         int last;
106
107         /* commit metadata and message */
108         char *author_name;
109         char *author_email;
110         char *author_date;
111         char *msg;
112         size_t msg_len;
113
114         /* when --rebasing, records the original commit the patch came from */
115         struct object_id orig_commit;
116
117         /* number of digits in patch filename */
118         int prec;
119
120         /* various operating modes and command line options */
121         int interactive;
122         int threeway;
123         int quiet;
124         int signoff; /* enum signoff_type */
125         int utf8;
126         int keep; /* enum keep_type */
127         int message_id;
128         int scissors; /* enum scissors_type */
129         struct argv_array git_apply_opts;
130         const char *resolvemsg;
131         int committer_date_is_author_date;
132         int ignore_date;
133         int allow_rerere_autoupdate;
134         const char *sign_commit;
135         int rebasing;
136 };
137
138 /**
139  * Initializes am_state with the default values.
140  */
141 static void am_state_init(struct am_state *state)
142 {
143         int gpgsign;
144
145         memset(state, 0, sizeof(*state));
146
147         state->dir = git_pathdup("rebase-apply");
148
149         state->prec = 4;
150
151         git_config_get_bool("am.threeway", &state->threeway);
152
153         state->utf8 = 1;
154
155         git_config_get_bool("am.messageid", &state->message_id);
156
157         state->scissors = SCISSORS_UNSET;
158
159         argv_array_init(&state->git_apply_opts);
160
161         if (!git_config_get_bool("commit.gpgsign", &gpgsign))
162                 state->sign_commit = gpgsign ? "" : NULL;
163 }
164
165 /**
166  * Releases memory allocated by an am_state.
167  */
168 static void am_state_release(struct am_state *state)
169 {
170         free(state->dir);
171         free(state->author_name);
172         free(state->author_email);
173         free(state->author_date);
174         free(state->msg);
175         argv_array_clear(&state->git_apply_opts);
176 }
177
178 /**
179  * Returns path relative to the am_state directory.
180  */
181 static inline const char *am_path(const struct am_state *state, const char *path)
182 {
183         return mkpath("%s/%s", state->dir, path);
184 }
185
186 /**
187  * For convenience to call write_file()
188  */
189 static void write_state_text(const struct am_state *state,
190                              const char *name, const char *string)
191 {
192         write_file(am_path(state, name), "%s", string);
193 }
194
195 static void write_state_count(const struct am_state *state,
196                               const char *name, int value)
197 {
198         write_file(am_path(state, name), "%d", value);
199 }
200
201 static void write_state_bool(const struct am_state *state,
202                              const char *name, int value)
203 {
204         write_state_text(state, name, value ? "t" : "f");
205 }
206
207 /**
208  * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
209  * at the end.
210  */
211 static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
212 {
213         va_list ap;
214
215         va_start(ap, fmt);
216         if (!state->quiet) {
217                 vfprintf(fp, fmt, ap);
218                 putc('\n', fp);
219         }
220         va_end(ap);
221 }
222
223 /**
224  * Returns 1 if there is an am session in progress, 0 otherwise.
225  */
226 static int am_in_progress(const struct am_state *state)
227 {
228         struct stat st;
229
230         if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
231                 return 0;
232         if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
233                 return 0;
234         if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
235                 return 0;
236         return 1;
237 }
238
239 /**
240  * Reads the contents of `file` in the `state` directory into `sb`. Returns the
241  * number of bytes read on success, -1 if the file does not exist. If `trim` is
242  * set, trailing whitespace will be removed.
243  */
244 static int read_state_file(struct strbuf *sb, const struct am_state *state,
245                         const char *file, int trim)
246 {
247         strbuf_reset(sb);
248
249         if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
250                 if (trim)
251                         strbuf_trim(sb);
252
253                 return sb->len;
254         }
255
256         if (errno == ENOENT)
257                 return -1;
258
259         die_errno(_("could not read '%s'"), am_path(state, file));
260 }
261
262 /**
263  * Take a series of KEY='VALUE' lines where VALUE part is
264  * sq-quoted, and append <KEY, VALUE> at the end of the string list
265  */
266 static int parse_key_value_squoted(char *buf, struct string_list *list)
267 {
268         while (*buf) {
269                 struct string_list_item *item;
270                 char *np;
271                 char *cp = strchr(buf, '=');
272                 if (!cp)
273                         return -1;
274                 np = strchrnul(cp, '\n');
275                 *cp++ = '\0';
276                 item = string_list_append(list, buf);
277
278                 buf = np + (*np == '\n');
279                 *np = '\0';
280                 cp = sq_dequote(cp);
281                 if (!cp)
282                         return -1;
283                 item->util = xstrdup(cp);
284         }
285         return 0;
286 }
287
288 /**
289  * Reads and parses the state directory's "author-script" file, and sets
290  * state->author_name, state->author_email and state->author_date accordingly.
291  * Returns 0 on success, -1 if the file could not be parsed.
292  *
293  * The author script is of the format:
294  *
295  *      GIT_AUTHOR_NAME='$author_name'
296  *      GIT_AUTHOR_EMAIL='$author_email'
297  *      GIT_AUTHOR_DATE='$author_date'
298  *
299  * where $author_name, $author_email and $author_date are quoted. We are strict
300  * with our parsing, as the file was meant to be eval'd in the old git-am.sh
301  * script, and thus if the file differs from what this function expects, it is
302  * better to bail out than to do something that the user does not expect.
303  */
304 static int read_author_script(struct am_state *state)
305 {
306         const char *filename = am_path(state, "author-script");
307         struct strbuf buf = STRBUF_INIT;
308         struct string_list kv = STRING_LIST_INIT_DUP;
309         int retval = -1; /* assume failure */
310         int fd;
311
312         assert(!state->author_name);
313         assert(!state->author_email);
314         assert(!state->author_date);
315
316         fd = open(filename, O_RDONLY);
317         if (fd < 0) {
318                 if (errno == ENOENT)
319                         return 0;
320                 die_errno(_("could not open '%s' for reading"), filename);
321         }
322         strbuf_read(&buf, fd, 0);
323         close(fd);
324         if (parse_key_value_squoted(buf.buf, &kv))
325                 goto finish;
326
327         if (kv.nr != 3 ||
328             strcmp(kv.items[0].string, "GIT_AUTHOR_NAME") ||
329             strcmp(kv.items[1].string, "GIT_AUTHOR_EMAIL") ||
330             strcmp(kv.items[2].string, "GIT_AUTHOR_DATE"))
331                 goto finish;
332         state->author_name = kv.items[0].util;
333         state->author_email = kv.items[1].util;
334         state->author_date = kv.items[2].util;
335         retval = 0;
336 finish:
337         string_list_clear(&kv, !!retval);
338         strbuf_release(&buf);
339         return retval;
340 }
341
342 /**
343  * Saves state->author_name, state->author_email and state->author_date in the
344  * state directory's "author-script" file.
345  */
346 static void write_author_script(const struct am_state *state)
347 {
348         struct strbuf sb = STRBUF_INIT;
349
350         strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
351         sq_quote_buf(&sb, state->author_name);
352         strbuf_addch(&sb, '\n');
353
354         strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
355         sq_quote_buf(&sb, state->author_email);
356         strbuf_addch(&sb, '\n');
357
358         strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
359         sq_quote_buf(&sb, state->author_date);
360         strbuf_addch(&sb, '\n');
361
362         write_state_text(state, "author-script", sb.buf);
363
364         strbuf_release(&sb);
365 }
366
367 /**
368  * Reads the commit message from the state directory's "final-commit" file,
369  * setting state->msg to its contents and state->msg_len to the length of its
370  * contents in bytes.
371  *
372  * Returns 0 on success, -1 if the file does not exist.
373  */
374 static int read_commit_msg(struct am_state *state)
375 {
376         struct strbuf sb = STRBUF_INIT;
377
378         assert(!state->msg);
379
380         if (read_state_file(&sb, state, "final-commit", 0) < 0) {
381                 strbuf_release(&sb);
382                 return -1;
383         }
384
385         state->msg = strbuf_detach(&sb, &state->msg_len);
386         return 0;
387 }
388
389 /**
390  * Saves state->msg in the state directory's "final-commit" file.
391  */
392 static void write_commit_msg(const struct am_state *state)
393 {
394         const char *filename = am_path(state, "final-commit");
395         write_file_buf(filename, state->msg, state->msg_len);
396 }
397
398 /**
399  * Loads state from disk.
400  */
401 static void am_load(struct am_state *state)
402 {
403         struct strbuf sb = STRBUF_INIT;
404
405         if (read_state_file(&sb, state, "next", 1) < 0)
406                 die("BUG: state file 'next' does not exist");
407         state->cur = strtol(sb.buf, NULL, 10);
408
409         if (read_state_file(&sb, state, "last", 1) < 0)
410                 die("BUG: state file 'last' does not exist");
411         state->last = strtol(sb.buf, NULL, 10);
412
413         if (read_author_script(state) < 0)
414                 die(_("could not parse author script"));
415
416         read_commit_msg(state);
417
418         if (read_state_file(&sb, state, "original-commit", 1) < 0)
419                 oidclr(&state->orig_commit);
420         else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
421                 die(_("could not parse %s"), am_path(state, "original-commit"));
422
423         read_state_file(&sb, state, "threeway", 1);
424         state->threeway = !strcmp(sb.buf, "t");
425
426         read_state_file(&sb, state, "quiet", 1);
427         state->quiet = !strcmp(sb.buf, "t");
428
429         read_state_file(&sb, state, "sign", 1);
430         state->signoff = !strcmp(sb.buf, "t");
431
432         read_state_file(&sb, state, "utf8", 1);
433         state->utf8 = !strcmp(sb.buf, "t");
434
435         if (file_exists(am_path(state, "rerere-autoupdate"))) {
436                 read_state_file(&sb, state, "rerere-autoupdate", 1);
437                 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
438                         RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
439         } else {
440                 state->allow_rerere_autoupdate = 0;
441         }
442
443         read_state_file(&sb, state, "keep", 1);
444         if (!strcmp(sb.buf, "t"))
445                 state->keep = KEEP_TRUE;
446         else if (!strcmp(sb.buf, "b"))
447                 state->keep = KEEP_NON_PATCH;
448         else
449                 state->keep = KEEP_FALSE;
450
451         read_state_file(&sb, state, "messageid", 1);
452         state->message_id = !strcmp(sb.buf, "t");
453
454         read_state_file(&sb, state, "scissors", 1);
455         if (!strcmp(sb.buf, "t"))
456                 state->scissors = SCISSORS_TRUE;
457         else if (!strcmp(sb.buf, "f"))
458                 state->scissors = SCISSORS_FALSE;
459         else
460                 state->scissors = SCISSORS_UNSET;
461
462         read_state_file(&sb, state, "apply-opt", 1);
463         argv_array_clear(&state->git_apply_opts);
464         if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
465                 die(_("could not parse %s"), am_path(state, "apply-opt"));
466
467         state->rebasing = !!file_exists(am_path(state, "rebasing"));
468
469         strbuf_release(&sb);
470 }
471
472 /**
473  * Removes the am_state directory, forcefully terminating the current am
474  * session.
475  */
476 static void am_destroy(const struct am_state *state)
477 {
478         struct strbuf sb = STRBUF_INIT;
479
480         strbuf_addstr(&sb, state->dir);
481         remove_dir_recursively(&sb, 0);
482         strbuf_release(&sb);
483 }
484
485 /**
486  * Runs applypatch-msg hook. Returns its exit code.
487  */
488 static int run_applypatch_msg_hook(struct am_state *state)
489 {
490         int ret;
491
492         assert(state->msg);
493         ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
494
495         if (!ret) {
496                 FREE_AND_NULL(state->msg);
497                 if (read_commit_msg(state) < 0)
498                         die(_("'%s' was deleted by the applypatch-msg hook"),
499                                 am_path(state, "final-commit"));
500         }
501
502         return ret;
503 }
504
505 /**
506  * Runs post-rewrite hook. Returns it exit code.
507  */
508 static int run_post_rewrite_hook(const struct am_state *state)
509 {
510         struct child_process cp = CHILD_PROCESS_INIT;
511         const char *hook = find_hook("post-rewrite");
512         int ret;
513
514         if (!hook)
515                 return 0;
516
517         argv_array_push(&cp.args, hook);
518         argv_array_push(&cp.args, "rebase");
519
520         cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
521         cp.stdout_to_stderr = 1;
522
523         ret = run_command(&cp);
524
525         close(cp.in);
526         return ret;
527 }
528
529 /**
530  * Reads the state directory's "rewritten" file, and copies notes from the old
531  * commits listed in the file to their rewritten commits.
532  *
533  * Returns 0 on success, -1 on failure.
534  */
535 static int copy_notes_for_rebase(const struct am_state *state)
536 {
537         struct notes_rewrite_cfg *c;
538         struct strbuf sb = STRBUF_INIT;
539         const char *invalid_line = _("Malformed input line: '%s'.");
540         const char *msg = "Notes added by 'git rebase'";
541         FILE *fp;
542         int ret = 0;
543
544         assert(state->rebasing);
545
546         c = init_copy_notes_for_rewrite("rebase");
547         if (!c)
548                 return 0;
549
550         fp = xfopen(am_path(state, "rewritten"), "r");
551
552         while (!strbuf_getline_lf(&sb, fp)) {
553                 struct object_id from_obj, to_obj;
554
555                 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
556                         ret = error(invalid_line, sb.buf);
557                         goto finish;
558                 }
559
560                 if (get_oid_hex(sb.buf, &from_obj)) {
561                         ret = error(invalid_line, sb.buf);
562                         goto finish;
563                 }
564
565                 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
566                         ret = error(invalid_line, sb.buf);
567                         goto finish;
568                 }
569
570                 if (get_oid_hex(sb.buf + GIT_SHA1_HEXSZ + 1, &to_obj)) {
571                         ret = error(invalid_line, sb.buf);
572                         goto finish;
573                 }
574
575                 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
576                         ret = error(_("Failed to copy notes from '%s' to '%s'"),
577                                         oid_to_hex(&from_obj), oid_to_hex(&to_obj));
578         }
579
580 finish:
581         finish_copy_notes_for_rewrite(c, msg);
582         fclose(fp);
583         strbuf_release(&sb);
584         return ret;
585 }
586
587 /**
588  * Determines if the file looks like a piece of RFC2822 mail by grabbing all
589  * non-indented lines and checking if they look like they begin with valid
590  * header field names.
591  *
592  * Returns 1 if the file looks like a piece of mail, 0 otherwise.
593  */
594 static int is_mail(FILE *fp)
595 {
596         const char *header_regex = "^[!-9;-~]+:";
597         struct strbuf sb = STRBUF_INIT;
598         regex_t regex;
599         int ret = 1;
600
601         if (fseek(fp, 0L, SEEK_SET))
602                 die_errno(_("fseek failed"));
603
604         if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
605                 die("invalid pattern: %s", header_regex);
606
607         while (!strbuf_getline(&sb, fp)) {
608                 if (!sb.len)
609                         break; /* End of header */
610
611                 /* Ignore indented folded lines */
612                 if (*sb.buf == '\t' || *sb.buf == ' ')
613                         continue;
614
615                 /* It's a header if it matches header_regex */
616                 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
617                         ret = 0;
618                         goto done;
619                 }
620         }
621
622 done:
623         regfree(&regex);
624         strbuf_release(&sb);
625         return ret;
626 }
627
628 /**
629  * Attempts to detect the patch_format of the patches contained in `paths`,
630  * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
631  * detection fails.
632  */
633 static int detect_patch_format(const char **paths)
634 {
635         enum patch_format ret = PATCH_FORMAT_UNKNOWN;
636         struct strbuf l1 = STRBUF_INIT;
637         struct strbuf l2 = STRBUF_INIT;
638         struct strbuf l3 = STRBUF_INIT;
639         FILE *fp;
640
641         /*
642          * We default to mbox format if input is from stdin and for directories
643          */
644         if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
645                 return PATCH_FORMAT_MBOX;
646
647         /*
648          * Otherwise, check the first few lines of the first patch, starting
649          * from the first non-blank line, to try to detect its format.
650          */
651
652         fp = xfopen(*paths, "r");
653
654         while (!strbuf_getline(&l1, fp)) {
655                 if (l1.len)
656                         break;
657         }
658
659         if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
660                 ret = PATCH_FORMAT_MBOX;
661                 goto done;
662         }
663
664         if (starts_with(l1.buf, "# This series applies on GIT commit")) {
665                 ret = PATCH_FORMAT_STGIT_SERIES;
666                 goto done;
667         }
668
669         if (!strcmp(l1.buf, "# HG changeset patch")) {
670                 ret = PATCH_FORMAT_HG;
671                 goto done;
672         }
673
674         strbuf_getline(&l2, fp);
675         strbuf_getline(&l3, fp);
676
677         /*
678          * If the second line is empty and the third is a From, Author or Date
679          * entry, this is likely an StGit patch.
680          */
681         if (l1.len && !l2.len &&
682                 (starts_with(l3.buf, "From:") ||
683                  starts_with(l3.buf, "Author:") ||
684                  starts_with(l3.buf, "Date:"))) {
685                 ret = PATCH_FORMAT_STGIT;
686                 goto done;
687         }
688
689         if (l1.len && is_mail(fp)) {
690                 ret = PATCH_FORMAT_MBOX;
691                 goto done;
692         }
693
694 done:
695         fclose(fp);
696         strbuf_release(&l1);
697         strbuf_release(&l2);
698         strbuf_release(&l3);
699         return ret;
700 }
701
702 /**
703  * Splits out individual email patches from `paths`, where each path is either
704  * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
705  */
706 static int split_mail_mbox(struct am_state *state, const char **paths,
707                                 int keep_cr, int mboxrd)
708 {
709         struct child_process cp = CHILD_PROCESS_INIT;
710         struct strbuf last = STRBUF_INIT;
711         int ret;
712
713         cp.git_cmd = 1;
714         argv_array_push(&cp.args, "mailsplit");
715         argv_array_pushf(&cp.args, "-d%d", state->prec);
716         argv_array_pushf(&cp.args, "-o%s", state->dir);
717         argv_array_push(&cp.args, "-b");
718         if (keep_cr)
719                 argv_array_push(&cp.args, "--keep-cr");
720         if (mboxrd)
721                 argv_array_push(&cp.args, "--mboxrd");
722         argv_array_push(&cp.args, "--");
723         argv_array_pushv(&cp.args, paths);
724
725         ret = capture_command(&cp, &last, 8);
726         if (ret)
727                 goto exit;
728
729         state->cur = 1;
730         state->last = strtol(last.buf, NULL, 10);
731
732 exit:
733         strbuf_release(&last);
734         return ret ? -1 : 0;
735 }
736
737 /**
738  * Callback signature for split_mail_conv(). The foreign patch should be
739  * read from `in`, and the converted patch (in RFC2822 mail format) should be
740  * written to `out`. Return 0 on success, or -1 on failure.
741  */
742 typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
743
744 /**
745  * Calls `fn` for each file in `paths` to convert the foreign patch to the
746  * RFC2822 mail format suitable for parsing with git-mailinfo.
747  *
748  * Returns 0 on success, -1 on failure.
749  */
750 static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
751                         const char **paths, int keep_cr)
752 {
753         static const char *stdin_only[] = {"-", NULL};
754         int i;
755
756         if (!*paths)
757                 paths = stdin_only;
758
759         for (i = 0; *paths; paths++, i++) {
760                 FILE *in, *out;
761                 const char *mail;
762                 int ret;
763
764                 if (!strcmp(*paths, "-"))
765                         in = stdin;
766                 else
767                         in = fopen(*paths, "r");
768
769                 if (!in)
770                         return error_errno(_("could not open '%s' for reading"),
771                                            *paths);
772
773                 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
774
775                 out = fopen(mail, "w");
776                 if (!out) {
777                         if (in != stdin)
778                                 fclose(in);
779                         return error_errno(_("could not open '%s' for writing"),
780                                            mail);
781                 }
782
783                 ret = fn(out, in, keep_cr);
784
785                 fclose(out);
786                 if (in != stdin)
787                         fclose(in);
788
789                 if (ret)
790                         return error(_("could not parse patch '%s'"), *paths);
791         }
792
793         state->cur = 1;
794         state->last = i;
795         return 0;
796 }
797
798 /**
799  * A split_mail_conv() callback that converts an StGit patch to an RFC2822
800  * message suitable for parsing with git-mailinfo.
801  */
802 static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
803 {
804         struct strbuf sb = STRBUF_INIT;
805         int subject_printed = 0;
806
807         while (!strbuf_getline_lf(&sb, in)) {
808                 const char *str;
809
810                 if (str_isspace(sb.buf))
811                         continue;
812                 else if (skip_prefix(sb.buf, "Author:", &str))
813                         fprintf(out, "From:%s\n", str);
814                 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
815                         fprintf(out, "%s\n", sb.buf);
816                 else if (!subject_printed) {
817                         fprintf(out, "Subject: %s\n", sb.buf);
818                         subject_printed = 1;
819                 } else {
820                         fprintf(out, "\n%s\n", sb.buf);
821                         break;
822                 }
823         }
824
825         strbuf_reset(&sb);
826         while (strbuf_fread(&sb, 8192, in) > 0) {
827                 fwrite(sb.buf, 1, sb.len, out);
828                 strbuf_reset(&sb);
829         }
830
831         strbuf_release(&sb);
832         return 0;
833 }
834
835 /**
836  * This function only supports a single StGit series file in `paths`.
837  *
838  * Given an StGit series file, converts the StGit patches in the series into
839  * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
840  * the state directory.
841  *
842  * Returns 0 on success, -1 on failure.
843  */
844 static int split_mail_stgit_series(struct am_state *state, const char **paths,
845                                         int keep_cr)
846 {
847         const char *series_dir;
848         char *series_dir_buf;
849         FILE *fp;
850         struct argv_array patches = ARGV_ARRAY_INIT;
851         struct strbuf sb = STRBUF_INIT;
852         int ret;
853
854         if (!paths[0] || paths[1])
855                 return error(_("Only one StGIT patch series can be applied at once"));
856
857         series_dir_buf = xstrdup(*paths);
858         series_dir = dirname(series_dir_buf);
859
860         fp = fopen(*paths, "r");
861         if (!fp)
862                 return error_errno(_("could not open '%s' for reading"), *paths);
863
864         while (!strbuf_getline_lf(&sb, fp)) {
865                 if (*sb.buf == '#')
866                         continue; /* skip comment lines */
867
868                 argv_array_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
869         }
870
871         fclose(fp);
872         strbuf_release(&sb);
873         free(series_dir_buf);
874
875         ret = split_mail_conv(stgit_patch_to_mail, state, patches.argv, keep_cr);
876
877         argv_array_clear(&patches);
878         return ret;
879 }
880
881 /**
882  * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
883  * message suitable for parsing with git-mailinfo.
884  */
885 static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
886 {
887         struct strbuf sb = STRBUF_INIT;
888         int rc = 0;
889
890         while (!strbuf_getline_lf(&sb, in)) {
891                 const char *str;
892
893                 if (skip_prefix(sb.buf, "# User ", &str))
894                         fprintf(out, "From: %s\n", str);
895                 else if (skip_prefix(sb.buf, "# Date ", &str)) {
896                         timestamp_t timestamp;
897                         long tz, tz2;
898                         char *end;
899
900                         errno = 0;
901                         timestamp = parse_timestamp(str, &end, 10);
902                         if (errno) {
903                                 rc = error(_("invalid timestamp"));
904                                 goto exit;
905                         }
906
907                         if (!skip_prefix(end, " ", &str)) {
908                                 rc = error(_("invalid Date line"));
909                                 goto exit;
910                         }
911
912                         errno = 0;
913                         tz = strtol(str, &end, 10);
914                         if (errno) {
915                                 rc = error(_("invalid timezone offset"));
916                                 goto exit;
917                         }
918
919                         if (*end) {
920                                 rc = error(_("invalid Date line"));
921                                 goto exit;
922                         }
923
924                         /*
925                          * mercurial's timezone is in seconds west of UTC,
926                          * however git's timezone is in hours + minutes east of
927                          * UTC. Convert it.
928                          */
929                         tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
930                         if (tz > 0)
931                                 tz2 = -tz2;
932
933                         fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
934                 } else if (starts_with(sb.buf, "# ")) {
935                         continue;
936                 } else {
937                         fprintf(out, "\n%s\n", sb.buf);
938                         break;
939                 }
940         }
941
942         strbuf_reset(&sb);
943         while (strbuf_fread(&sb, 8192, in) > 0) {
944                 fwrite(sb.buf, 1, sb.len, out);
945                 strbuf_reset(&sb);
946         }
947 exit:
948         strbuf_release(&sb);
949         return rc;
950 }
951
952 /**
953  * Splits a list of files/directories into individual email patches. Each path
954  * in `paths` must be a file/directory that is formatted according to
955  * `patch_format`.
956  *
957  * Once split out, the individual email patches will be stored in the state
958  * directory, with each patch's filename being its index, padded to state->prec
959  * digits.
960  *
961  * state->cur will be set to the index of the first mail, and state->last will
962  * be set to the index of the last mail.
963  *
964  * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
965  * to disable this behavior, -1 to use the default configured setting.
966  *
967  * Returns 0 on success, -1 on failure.
968  */
969 static int split_mail(struct am_state *state, enum patch_format patch_format,
970                         const char **paths, int keep_cr)
971 {
972         if (keep_cr < 0) {
973                 keep_cr = 0;
974                 git_config_get_bool("am.keepcr", &keep_cr);
975         }
976
977         switch (patch_format) {
978         case PATCH_FORMAT_MBOX:
979                 return split_mail_mbox(state, paths, keep_cr, 0);
980         case PATCH_FORMAT_STGIT:
981                 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
982         case PATCH_FORMAT_STGIT_SERIES:
983                 return split_mail_stgit_series(state, paths, keep_cr);
984         case PATCH_FORMAT_HG:
985                 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
986         case PATCH_FORMAT_MBOXRD:
987                 return split_mail_mbox(state, paths, keep_cr, 1);
988         default:
989                 die("BUG: invalid patch_format");
990         }
991         return -1;
992 }
993
994 /**
995  * Setup a new am session for applying patches
996  */
997 static void am_setup(struct am_state *state, enum patch_format patch_format,
998                         const char **paths, int keep_cr)
999 {
1000         struct object_id curr_head;
1001         const char *str;
1002         struct strbuf sb = STRBUF_INIT;
1003
1004         if (!patch_format)
1005                 patch_format = detect_patch_format(paths);
1006
1007         if (!patch_format) {
1008                 fprintf_ln(stderr, _("Patch format detection failed."));
1009                 exit(128);
1010         }
1011
1012         if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1013                 die_errno(_("failed to create directory '%s'"), state->dir);
1014
1015         if (split_mail(state, patch_format, paths, keep_cr) < 0) {
1016                 am_destroy(state);
1017                 die(_("Failed to split patches."));
1018         }
1019
1020         if (state->rebasing)
1021                 state->threeway = 1;
1022
1023         write_state_bool(state, "threeway", state->threeway);
1024         write_state_bool(state, "quiet", state->quiet);
1025         write_state_bool(state, "sign", state->signoff);
1026         write_state_bool(state, "utf8", state->utf8);
1027
1028         if (state->allow_rerere_autoupdate)
1029                 write_state_bool(state, "rerere-autoupdate",
1030                          state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1031
1032         switch (state->keep) {
1033         case KEEP_FALSE:
1034                 str = "f";
1035                 break;
1036         case KEEP_TRUE:
1037                 str = "t";
1038                 break;
1039         case KEEP_NON_PATCH:
1040                 str = "b";
1041                 break;
1042         default:
1043                 die("BUG: invalid value for state->keep");
1044         }
1045
1046         write_state_text(state, "keep", str);
1047         write_state_bool(state, "messageid", state->message_id);
1048
1049         switch (state->scissors) {
1050         case SCISSORS_UNSET:
1051                 str = "";
1052                 break;
1053         case SCISSORS_FALSE:
1054                 str = "f";
1055                 break;
1056         case SCISSORS_TRUE:
1057                 str = "t";
1058                 break;
1059         default:
1060                 die("BUG: invalid value for state->scissors");
1061         }
1062         write_state_text(state, "scissors", str);
1063
1064         sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
1065         write_state_text(state, "apply-opt", sb.buf);
1066
1067         if (state->rebasing)
1068                 write_state_text(state, "rebasing", "");
1069         else
1070                 write_state_text(state, "applying", "");
1071
1072         if (!get_oid("HEAD", &curr_head)) {
1073                 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
1074                 if (!state->rebasing)
1075                         update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1076                                    UPDATE_REFS_DIE_ON_ERR);
1077         } else {
1078                 write_state_text(state, "abort-safety", "");
1079                 if (!state->rebasing)
1080                         delete_ref(NULL, "ORIG_HEAD", NULL, 0);
1081         }
1082
1083         /*
1084          * NOTE: Since the "next" and "last" files determine if an am_state
1085          * session is in progress, they should be written last.
1086          */
1087
1088         write_state_count(state, "next", state->cur);
1089         write_state_count(state, "last", state->last);
1090
1091         strbuf_release(&sb);
1092 }
1093
1094 /**
1095  * Increments the patch pointer, and cleans am_state for the application of the
1096  * next patch.
1097  */
1098 static void am_next(struct am_state *state)
1099 {
1100         struct object_id head;
1101
1102         FREE_AND_NULL(state->author_name);
1103         FREE_AND_NULL(state->author_email);
1104         FREE_AND_NULL(state->author_date);
1105         FREE_AND_NULL(state->msg);
1106         state->msg_len = 0;
1107
1108         unlink(am_path(state, "author-script"));
1109         unlink(am_path(state, "final-commit"));
1110
1111         oidclr(&state->orig_commit);
1112         unlink(am_path(state, "original-commit"));
1113
1114         if (!get_oid("HEAD", &head))
1115                 write_state_text(state, "abort-safety", oid_to_hex(&head));
1116         else
1117                 write_state_text(state, "abort-safety", "");
1118
1119         state->cur++;
1120         write_state_count(state, "next", state->cur);
1121 }
1122
1123 /**
1124  * Returns the filename of the current patch email.
1125  */
1126 static const char *msgnum(const struct am_state *state)
1127 {
1128         static struct strbuf sb = STRBUF_INIT;
1129
1130         strbuf_reset(&sb);
1131         strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1132
1133         return sb.buf;
1134 }
1135
1136 /**
1137  * Refresh and write index.
1138  */
1139 static void refresh_and_write_cache(void)
1140 {
1141         struct lock_file lock_file = LOCK_INIT;
1142
1143         hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1144         refresh_cache(REFRESH_QUIET);
1145         if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1146                 die(_("unable to write index file"));
1147 }
1148
1149 /**
1150  * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
1151  * branch, returns 1 if there are entries in the index, 0 otherwise. If an
1152  * strbuf is provided, the space-separated list of files that differ will be
1153  * appended to it.
1154  */
1155 static int index_has_changes(struct strbuf *sb)
1156 {
1157         struct object_id head;
1158         int i;
1159
1160         if (!get_oid_tree("HEAD", &head)) {
1161                 struct diff_options opt;
1162
1163                 diff_setup(&opt);
1164                 opt.flags.exit_with_status = 1;
1165                 if (!sb)
1166                         opt.flags.quick = 1;
1167                 do_diff_cache(&head, &opt);
1168                 diffcore_std(&opt);
1169                 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
1170                         if (i)
1171                                 strbuf_addch(sb, ' ');
1172                         strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
1173                 }
1174                 diff_flush(&opt);
1175                 return opt.flags.has_changes != 0;
1176         } else {
1177                 for (i = 0; sb && i < active_nr; i++) {
1178                         if (i)
1179                                 strbuf_addch(sb, ' ');
1180                         strbuf_addstr(sb, active_cache[i]->name);
1181                 }
1182                 return !!active_nr;
1183         }
1184 }
1185
1186 /**
1187  * Dies with a user-friendly message on how to proceed after resolving the
1188  * problem. This message can be overridden with state->resolvemsg.
1189  */
1190 static void NORETURN die_user_resolve(const struct am_state *state)
1191 {
1192         if (state->resolvemsg) {
1193                 printf_ln("%s", state->resolvemsg);
1194         } else {
1195                 const char *cmdline = state->interactive ? "git am -i" : "git am";
1196
1197                 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1198                 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
1199                 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1200         }
1201
1202         exit(128);
1203 }
1204
1205 /**
1206  * Appends signoff to the "msg" field of the am_state.
1207  */
1208 static void am_append_signoff(struct am_state *state)
1209 {
1210         struct strbuf sb = STRBUF_INIT;
1211
1212         strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
1213         append_signoff(&sb, 0, 0);
1214         state->msg = strbuf_detach(&sb, &state->msg_len);
1215 }
1216
1217 /**
1218  * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1219  * state->msg will be set to the patch message. state->author_name,
1220  * state->author_email and state->author_date will be set to the patch author's
1221  * name, email and date respectively. The patch body will be written to the
1222  * state directory's "patch" file.
1223  *
1224  * Returns 1 if the patch should be skipped, 0 otherwise.
1225  */
1226 static int parse_mail(struct am_state *state, const char *mail)
1227 {
1228         FILE *fp;
1229         struct strbuf sb = STRBUF_INIT;
1230         struct strbuf msg = STRBUF_INIT;
1231         struct strbuf author_name = STRBUF_INIT;
1232         struct strbuf author_date = STRBUF_INIT;
1233         struct strbuf author_email = STRBUF_INIT;
1234         int ret = 0;
1235         struct mailinfo mi;
1236
1237         setup_mailinfo(&mi);
1238
1239         if (state->utf8)
1240                 mi.metainfo_charset = get_commit_output_encoding();
1241         else
1242                 mi.metainfo_charset = NULL;
1243
1244         switch (state->keep) {
1245         case KEEP_FALSE:
1246                 break;
1247         case KEEP_TRUE:
1248                 mi.keep_subject = 1;
1249                 break;
1250         case KEEP_NON_PATCH:
1251                 mi.keep_non_patch_brackets_in_subject = 1;
1252                 break;
1253         default:
1254                 die("BUG: invalid value for state->keep");
1255         }
1256
1257         if (state->message_id)
1258                 mi.add_message_id = 1;
1259
1260         switch (state->scissors) {
1261         case SCISSORS_UNSET:
1262                 break;
1263         case SCISSORS_FALSE:
1264                 mi.use_scissors = 0;
1265                 break;
1266         case SCISSORS_TRUE:
1267                 mi.use_scissors = 1;
1268                 break;
1269         default:
1270                 die("BUG: invalid value for state->scissors");
1271         }
1272
1273         mi.input = xfopen(mail, "r");
1274         mi.output = xfopen(am_path(state, "info"), "w");
1275         if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
1276                 die("could not parse patch");
1277
1278         fclose(mi.input);
1279         fclose(mi.output);
1280
1281         /* Extract message and author information */
1282         fp = xfopen(am_path(state, "info"), "r");
1283         while (!strbuf_getline_lf(&sb, fp)) {
1284                 const char *x;
1285
1286                 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1287                         if (msg.len)
1288                                 strbuf_addch(&msg, '\n');
1289                         strbuf_addstr(&msg, x);
1290                 } else if (skip_prefix(sb.buf, "Author: ", &x))
1291                         strbuf_addstr(&author_name, x);
1292                 else if (skip_prefix(sb.buf, "Email: ", &x))
1293                         strbuf_addstr(&author_email, x);
1294                 else if (skip_prefix(sb.buf, "Date: ", &x))
1295                         strbuf_addstr(&author_date, x);
1296         }
1297         fclose(fp);
1298
1299         /* Skip pine's internal folder data */
1300         if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1301                 ret = 1;
1302                 goto finish;
1303         }
1304
1305         if (is_empty_file(am_path(state, "patch"))) {
1306                 printf_ln(_("Patch is empty."));
1307                 die_user_resolve(state);
1308         }
1309
1310         strbuf_addstr(&msg, "\n\n");
1311         strbuf_addbuf(&msg, &mi.log_message);
1312         strbuf_stripspace(&msg, 0);
1313
1314         assert(!state->author_name);
1315         state->author_name = strbuf_detach(&author_name, NULL);
1316
1317         assert(!state->author_email);
1318         state->author_email = strbuf_detach(&author_email, NULL);
1319
1320         assert(!state->author_date);
1321         state->author_date = strbuf_detach(&author_date, NULL);
1322
1323         assert(!state->msg);
1324         state->msg = strbuf_detach(&msg, &state->msg_len);
1325
1326 finish:
1327         strbuf_release(&msg);
1328         strbuf_release(&author_date);
1329         strbuf_release(&author_email);
1330         strbuf_release(&author_name);
1331         strbuf_release(&sb);
1332         clear_mailinfo(&mi);
1333         return ret;
1334 }
1335
1336 /**
1337  * Sets commit_id to the commit hash where the mail was generated from.
1338  * Returns 0 on success, -1 on failure.
1339  */
1340 static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
1341 {
1342         struct strbuf sb = STRBUF_INIT;
1343         FILE *fp = xfopen(mail, "r");
1344         const char *x;
1345         int ret = 0;
1346
1347         if (strbuf_getline_lf(&sb, fp) ||
1348             !skip_prefix(sb.buf, "From ", &x) ||
1349             get_oid_hex(x, commit_id) < 0)
1350                 ret = -1;
1351
1352         strbuf_release(&sb);
1353         fclose(fp);
1354         return ret;
1355 }
1356
1357 /**
1358  * Sets state->msg, state->author_name, state->author_email, state->author_date
1359  * to the commit's respective info.
1360  */
1361 static void get_commit_info(struct am_state *state, struct commit *commit)
1362 {
1363         const char *buffer, *ident_line, *msg;
1364         size_t ident_len;
1365         struct ident_split id;
1366
1367         buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1368
1369         ident_line = find_commit_header(buffer, "author", &ident_len);
1370
1371         if (split_ident_line(&id, ident_line, ident_len) < 0)
1372                 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
1373
1374         assert(!state->author_name);
1375         if (id.name_begin)
1376                 state->author_name =
1377                         xmemdupz(id.name_begin, id.name_end - id.name_begin);
1378         else
1379                 state->author_name = xstrdup("");
1380
1381         assert(!state->author_email);
1382         if (id.mail_begin)
1383                 state->author_email =
1384                         xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1385         else
1386                 state->author_email = xstrdup("");
1387
1388         assert(!state->author_date);
1389         state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
1390
1391         assert(!state->msg);
1392         msg = strstr(buffer, "\n\n");
1393         if (!msg)
1394                 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
1395         state->msg = xstrdup(msg + 2);
1396         state->msg_len = strlen(state->msg);
1397         unuse_commit_buffer(commit, buffer);
1398 }
1399
1400 /**
1401  * Writes `commit` as a patch to the state directory's "patch" file.
1402  */
1403 static void write_commit_patch(const struct am_state *state, struct commit *commit)
1404 {
1405         struct rev_info rev_info;
1406         FILE *fp;
1407
1408         fp = xfopen(am_path(state, "patch"), "w");
1409         init_revisions(&rev_info, NULL);
1410         rev_info.diff = 1;
1411         rev_info.abbrev = 0;
1412         rev_info.disable_stdin = 1;
1413         rev_info.show_root_diff = 1;
1414         rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1415         rev_info.no_commit_id = 1;
1416         rev_info.diffopt.flags.binary = 1;
1417         rev_info.diffopt.flags.full_index = 1;
1418         rev_info.diffopt.use_color = 0;
1419         rev_info.diffopt.file = fp;
1420         rev_info.diffopt.close_file = 1;
1421         add_pending_object(&rev_info, &commit->object, "");
1422         diff_setup_done(&rev_info.diffopt);
1423         log_tree_commit(&rev_info, commit);
1424 }
1425
1426 /**
1427  * Writes the diff of the index against HEAD as a patch to the state
1428  * directory's "patch" file.
1429  */
1430 static void write_index_patch(const struct am_state *state)
1431 {
1432         struct tree *tree;
1433         struct object_id head;
1434         struct rev_info rev_info;
1435         FILE *fp;
1436
1437         if (!get_oid_tree("HEAD", &head))
1438                 tree = lookup_tree(&head);
1439         else
1440                 tree = lookup_tree(the_hash_algo->empty_tree);
1441
1442         fp = xfopen(am_path(state, "patch"), "w");
1443         init_revisions(&rev_info, NULL);
1444         rev_info.diff = 1;
1445         rev_info.disable_stdin = 1;
1446         rev_info.no_commit_id = 1;
1447         rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1448         rev_info.diffopt.use_color = 0;
1449         rev_info.diffopt.file = fp;
1450         rev_info.diffopt.close_file = 1;
1451         add_pending_object(&rev_info, &tree->object, "");
1452         diff_setup_done(&rev_info.diffopt);
1453         run_diff_index(&rev_info, 1);
1454 }
1455
1456 /**
1457  * Like parse_mail(), but parses the mail by looking up its commit ID
1458  * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1459  * of patches.
1460  *
1461  * state->orig_commit will be set to the original commit ID.
1462  *
1463  * Will always return 0 as the patch should never be skipped.
1464  */
1465 static int parse_mail_rebase(struct am_state *state, const char *mail)
1466 {
1467         struct commit *commit;
1468         struct object_id commit_oid;
1469
1470         if (get_mail_commit_oid(&commit_oid, mail) < 0)
1471                 die(_("could not parse %s"), mail);
1472
1473         commit = lookup_commit_or_die(&commit_oid, mail);
1474
1475         get_commit_info(state, commit);
1476
1477         write_commit_patch(state, commit);
1478
1479         oidcpy(&state->orig_commit, &commit_oid);
1480         write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
1481
1482         return 0;
1483 }
1484
1485 /**
1486  * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1487  * `index_file` is not NULL, the patch will be applied to that index.
1488  */
1489 static int run_apply(const struct am_state *state, const char *index_file)
1490 {
1491         struct argv_array apply_paths = ARGV_ARRAY_INIT;
1492         struct argv_array apply_opts = ARGV_ARRAY_INIT;
1493         struct apply_state apply_state;
1494         int res, opts_left;
1495         int force_apply = 0;
1496         int options = 0;
1497
1498         if (init_apply_state(&apply_state, NULL))
1499                 die("BUG: init_apply_state() failed");
1500
1501         argv_array_push(&apply_opts, "apply");
1502         argv_array_pushv(&apply_opts, state->git_apply_opts.argv);
1503
1504         opts_left = apply_parse_options(apply_opts.argc, apply_opts.argv,
1505                                         &apply_state, &force_apply, &options,
1506                                         NULL);
1507
1508         if (opts_left != 0)
1509                 die("unknown option passed through to git apply");
1510
1511         if (index_file) {
1512                 apply_state.index_file = index_file;
1513                 apply_state.cached = 1;
1514         } else
1515                 apply_state.check_index = 1;
1516
1517         /*
1518          * If we are allowed to fall back on 3-way merge, don't give false
1519          * errors during the initial attempt.
1520          */
1521         if (state->threeway && !index_file)
1522                 apply_state.apply_verbosity = verbosity_silent;
1523
1524         if (check_apply_state(&apply_state, force_apply))
1525                 die("BUG: check_apply_state() failed");
1526
1527         argv_array_push(&apply_paths, am_path(state, "patch"));
1528
1529         res = apply_all_patches(&apply_state, apply_paths.argc, apply_paths.argv, options);
1530
1531         argv_array_clear(&apply_paths);
1532         argv_array_clear(&apply_opts);
1533         clear_apply_state(&apply_state);
1534
1535         if (res)
1536                 return res;
1537
1538         if (index_file) {
1539                 /* Reload index as apply_all_patches() will have modified it. */
1540                 discard_cache();
1541                 read_cache_from(index_file);
1542         }
1543
1544         return 0;
1545 }
1546
1547 /**
1548  * Builds an index that contains just the blobs needed for a 3way merge.
1549  */
1550 static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1551 {
1552         struct child_process cp = CHILD_PROCESS_INIT;
1553
1554         cp.git_cmd = 1;
1555         argv_array_push(&cp.args, "apply");
1556         argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1557         argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1558         argv_array_push(&cp.args, am_path(state, "patch"));
1559
1560         if (run_command(&cp))
1561                 return -1;
1562
1563         return 0;
1564 }
1565
1566 /**
1567  * Attempt a threeway merge, using index_path as the temporary index.
1568  */
1569 static int fall_back_threeway(const struct am_state *state, const char *index_path)
1570 {
1571         struct object_id orig_tree, their_tree, our_tree;
1572         const struct object_id *bases[1] = { &orig_tree };
1573         struct merge_options o;
1574         struct commit *result;
1575         char *their_tree_name;
1576
1577         if (get_oid("HEAD", &our_tree) < 0)
1578                 hashcpy(our_tree.hash, EMPTY_TREE_SHA1_BIN);
1579
1580         if (build_fake_ancestor(state, index_path))
1581                 return error("could not build fake ancestor");
1582
1583         discard_cache();
1584         read_cache_from(index_path);
1585
1586         if (write_index_as_tree(orig_tree.hash, &the_index, index_path, 0, NULL))
1587                 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1588
1589         say(state, stdout, _("Using index info to reconstruct a base tree..."));
1590
1591         if (!state->quiet) {
1592                 /*
1593                  * List paths that needed 3-way fallback, so that the user can
1594                  * review them with extra care to spot mismerges.
1595                  */
1596                 struct rev_info rev_info;
1597                 const char *diff_filter_str = "--diff-filter=AM";
1598
1599                 init_revisions(&rev_info, NULL);
1600                 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1601                 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1, rev_info.prefix);
1602                 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
1603                 diff_setup_done(&rev_info.diffopt);
1604                 run_diff_index(&rev_info, 1);
1605         }
1606
1607         if (run_apply(state, index_path))
1608                 return error(_("Did you hand edit your patch?\n"
1609                                 "It does not apply to blobs recorded in its index."));
1610
1611         if (write_index_as_tree(their_tree.hash, &the_index, index_path, 0, NULL))
1612                 return error("could not write tree");
1613
1614         say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1615
1616         discard_cache();
1617         read_cache();
1618
1619         /*
1620          * This is not so wrong. Depending on which base we picked, orig_tree
1621          * may be wildly different from ours, but their_tree has the same set of
1622          * wildly different changes in parts the patch did not touch, so
1623          * recursive ends up canceling them, saying that we reverted all those
1624          * changes.
1625          */
1626
1627         init_merge_options(&o);
1628
1629         o.branch1 = "HEAD";
1630         their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1631         o.branch2 = their_tree_name;
1632
1633         if (state->quiet)
1634                 o.verbosity = 0;
1635
1636         if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
1637                 rerere(state->allow_rerere_autoupdate);
1638                 free(their_tree_name);
1639                 return error(_("Failed to merge in the changes."));
1640         }
1641
1642         free(their_tree_name);
1643         return 0;
1644 }
1645
1646 /**
1647  * Commits the current index with state->msg as the commit message and
1648  * state->author_name, state->author_email and state->author_date as the author
1649  * information.
1650  */
1651 static void do_commit(const struct am_state *state)
1652 {
1653         struct object_id tree, parent, commit;
1654         const struct object_id *old_oid;
1655         struct commit_list *parents = NULL;
1656         const char *reflog_msg, *author;
1657         struct strbuf sb = STRBUF_INIT;
1658
1659         if (run_hook_le(NULL, "pre-applypatch", NULL))
1660                 exit(1);
1661
1662         if (write_cache_as_tree(tree.hash, 0, NULL))
1663                 die(_("git write-tree failed to write a tree"));
1664
1665         if (!get_oid_commit("HEAD", &parent)) {
1666                 old_oid = &parent;
1667                 commit_list_insert(lookup_commit(&parent), &parents);
1668         } else {
1669                 old_oid = NULL;
1670                 say(state, stderr, _("applying to an empty history"));
1671         }
1672
1673         author = fmt_ident(state->author_name, state->author_email,
1674                         state->ignore_date ? NULL : state->author_date,
1675                         IDENT_STRICT);
1676
1677         if (state->committer_date_is_author_date)
1678                 setenv("GIT_COMMITTER_DATE",
1679                         state->ignore_date ? "" : state->author_date, 1);
1680
1681         if (commit_tree(state->msg, state->msg_len, tree.hash, parents, commit.hash,
1682                                 author, state->sign_commit))
1683                 die(_("failed to write commit object"));
1684
1685         reflog_msg = getenv("GIT_REFLOG_ACTION");
1686         if (!reflog_msg)
1687                 reflog_msg = "am";
1688
1689         strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1690                         state->msg);
1691
1692         update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1693                    UPDATE_REFS_DIE_ON_ERR);
1694
1695         if (state->rebasing) {
1696                 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1697
1698                 assert(!is_null_oid(&state->orig_commit));
1699                 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1700                 fprintf(fp, "%s\n", oid_to_hex(&commit));
1701                 fclose(fp);
1702         }
1703
1704         run_hook_le(NULL, "post-applypatch", NULL);
1705
1706         strbuf_release(&sb);
1707 }
1708
1709 /**
1710  * Validates the am_state for resuming -- the "msg" and authorship fields must
1711  * be filled up.
1712  */
1713 static void validate_resume_state(const struct am_state *state)
1714 {
1715         if (!state->msg)
1716                 die(_("cannot resume: %s does not exist."),
1717                         am_path(state, "final-commit"));
1718
1719         if (!state->author_name || !state->author_email || !state->author_date)
1720                 die(_("cannot resume: %s does not exist."),
1721                         am_path(state, "author-script"));
1722 }
1723
1724 /**
1725  * Interactively prompt the user on whether the current patch should be
1726  * applied.
1727  *
1728  * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1729  * skip it.
1730  */
1731 static int do_interactive(struct am_state *state)
1732 {
1733         assert(state->msg);
1734
1735         if (!isatty(0))
1736                 die(_("cannot be interactive without stdin connected to a terminal."));
1737
1738         for (;;) {
1739                 const char *reply;
1740
1741                 puts(_("Commit Body is:"));
1742                 puts("--------------------------");
1743                 printf("%s", state->msg);
1744                 puts("--------------------------");
1745
1746                 /*
1747                  * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1748                  * in your translation. The program will only accept English
1749                  * input at this point.
1750                  */
1751                 reply = git_prompt(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "), PROMPT_ECHO);
1752
1753                 if (!reply) {
1754                         continue;
1755                 } else if (*reply == 'y' || *reply == 'Y') {
1756                         return 0;
1757                 } else if (*reply == 'a' || *reply == 'A') {
1758                         state->interactive = 0;
1759                         return 0;
1760                 } else if (*reply == 'n' || *reply == 'N') {
1761                         return 1;
1762                 } else if (*reply == 'e' || *reply == 'E') {
1763                         struct strbuf msg = STRBUF_INIT;
1764
1765                         if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1766                                 free(state->msg);
1767                                 state->msg = strbuf_detach(&msg, &state->msg_len);
1768                         }
1769                         strbuf_release(&msg);
1770                 } else if (*reply == 'v' || *reply == 'V') {
1771                         const char *pager = git_pager(1);
1772                         struct child_process cp = CHILD_PROCESS_INIT;
1773
1774                         if (!pager)
1775                                 pager = "cat";
1776                         prepare_pager_args(&cp, pager);
1777                         argv_array_push(&cp.args, am_path(state, "patch"));
1778                         run_command(&cp);
1779                 }
1780         }
1781 }
1782
1783 /**
1784  * Applies all queued mail.
1785  *
1786  * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1787  * well as the state directory's "patch" file is used as-is for applying the
1788  * patch and committing it.
1789  */
1790 static void am_run(struct am_state *state, int resume)
1791 {
1792         const char *argv_gc_auto[] = {"gc", "--auto", NULL};
1793         struct strbuf sb = STRBUF_INIT;
1794
1795         unlink(am_path(state, "dirtyindex"));
1796
1797         refresh_and_write_cache();
1798
1799         if (index_has_changes(&sb)) {
1800                 write_state_bool(state, "dirtyindex", 1);
1801                 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
1802         }
1803
1804         strbuf_release(&sb);
1805
1806         while (state->cur <= state->last) {
1807                 const char *mail = am_path(state, msgnum(state));
1808                 int apply_status;
1809
1810                 reset_ident_date();
1811
1812                 if (!file_exists(mail))
1813                         goto next;
1814
1815                 if (resume) {
1816                         validate_resume_state(state);
1817                 } else {
1818                         int skip;
1819
1820                         if (state->rebasing)
1821                                 skip = parse_mail_rebase(state, mail);
1822                         else
1823                                 skip = parse_mail(state, mail);
1824
1825                         if (skip)
1826                                 goto next; /* mail should be skipped */
1827
1828                         if (state->signoff)
1829                                 am_append_signoff(state);
1830
1831                         write_author_script(state);
1832                         write_commit_msg(state);
1833                 }
1834
1835                 if (state->interactive && do_interactive(state))
1836                         goto next;
1837
1838                 if (run_applypatch_msg_hook(state))
1839                         exit(1);
1840
1841                 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1842
1843                 apply_status = run_apply(state, NULL);
1844
1845                 if (apply_status && state->threeway) {
1846                         struct strbuf sb = STRBUF_INIT;
1847
1848                         strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1849                         apply_status = fall_back_threeway(state, sb.buf);
1850                         strbuf_release(&sb);
1851
1852                         /*
1853                          * Applying the patch to an earlier tree and merging
1854                          * the result may have produced the same tree as ours.
1855                          */
1856                         if (!apply_status && !index_has_changes(NULL)) {
1857                                 say(state, stdout, _("No changes -- Patch already applied."));
1858                                 goto next;
1859                         }
1860                 }
1861
1862                 if (apply_status) {
1863                         int advice_amworkdir = 1;
1864
1865                         printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1866                                 linelen(state->msg), state->msg);
1867
1868                         git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1869
1870                         if (advice_amworkdir)
1871                                 printf_ln(_("The copy of the patch that failed is found in: %s"),
1872                                                 am_path(state, "patch"));
1873
1874                         die_user_resolve(state);
1875                 }
1876
1877                 do_commit(state);
1878
1879 next:
1880                 am_next(state);
1881
1882                 if (resume)
1883                         am_load(state);
1884                 resume = 0;
1885         }
1886
1887         if (!is_empty_file(am_path(state, "rewritten"))) {
1888                 assert(state->rebasing);
1889                 copy_notes_for_rebase(state);
1890                 run_post_rewrite_hook(state);
1891         }
1892
1893         /*
1894          * In rebasing mode, it's up to the caller to take care of
1895          * housekeeping.
1896          */
1897         if (!state->rebasing) {
1898                 am_destroy(state);
1899                 close_all_packs();
1900                 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1901         }
1902 }
1903
1904 /**
1905  * Resume the current am session after patch application failure. The user did
1906  * all the hard work, and we do not have to do any patch application. Just
1907  * trust and commit what the user has in the index and working tree.
1908  */
1909 static void am_resolve(struct am_state *state)
1910 {
1911         validate_resume_state(state);
1912
1913         say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
1914
1915         if (!index_has_changes(NULL)) {
1916                 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1917                         "If there is nothing left to stage, chances are that something else\n"
1918                         "already introduced the same changes; you might want to skip this patch."));
1919                 die_user_resolve(state);
1920         }
1921
1922         if (unmerged_cache()) {
1923                 printf_ln(_("You still have unmerged paths in your index.\n"
1924                         "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1925                         "You might run `git rm` on a file to accept \"deleted by them\" for it."));
1926                 die_user_resolve(state);
1927         }
1928
1929         if (state->interactive) {
1930                 write_index_patch(state);
1931                 if (do_interactive(state))
1932                         goto next;
1933         }
1934
1935         rerere(0);
1936
1937         do_commit(state);
1938
1939 next:
1940         am_next(state);
1941         am_load(state);
1942         am_run(state, 0);
1943 }
1944
1945 /**
1946  * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1947  * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1948  * failure.
1949  */
1950 static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1951 {
1952         struct lock_file lock_file = LOCK_INIT;
1953         struct unpack_trees_options opts;
1954         struct tree_desc t[2];
1955
1956         if (parse_tree(head) || parse_tree(remote))
1957                 return -1;
1958
1959         hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1960
1961         refresh_cache(REFRESH_QUIET);
1962
1963         memset(&opts, 0, sizeof(opts));
1964         opts.head_idx = 1;
1965         opts.src_index = &the_index;
1966         opts.dst_index = &the_index;
1967         opts.update = 1;
1968         opts.merge = 1;
1969         opts.reset = reset;
1970         opts.fn = twoway_merge;
1971         init_tree_desc(&t[0], head->buffer, head->size);
1972         init_tree_desc(&t[1], remote->buffer, remote->size);
1973
1974         if (unpack_trees(2, t, &opts)) {
1975                 rollback_lock_file(&lock_file);
1976                 return -1;
1977         }
1978
1979         if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
1980                 die(_("unable to write new index file"));
1981
1982         return 0;
1983 }
1984
1985 /**
1986  * Merges a tree into the index. The index's stat info will take precedence
1987  * over the merged tree's. Returns 0 on success, -1 on failure.
1988  */
1989 static int merge_tree(struct tree *tree)
1990 {
1991         struct lock_file lock_file = LOCK_INIT;
1992         struct unpack_trees_options opts;
1993         struct tree_desc t[1];
1994
1995         if (parse_tree(tree))
1996                 return -1;
1997
1998         hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
1999
2000         memset(&opts, 0, sizeof(opts));
2001         opts.head_idx = 1;
2002         opts.src_index = &the_index;
2003         opts.dst_index = &the_index;
2004         opts.merge = 1;
2005         opts.fn = oneway_merge;
2006         init_tree_desc(&t[0], tree->buffer, tree->size);
2007
2008         if (unpack_trees(1, t, &opts)) {
2009                 rollback_lock_file(&lock_file);
2010                 return -1;
2011         }
2012
2013         if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
2014                 die(_("unable to write new index file"));
2015
2016         return 0;
2017 }
2018
2019 /**
2020  * Clean the index without touching entries that are not modified between
2021  * `head` and `remote`.
2022  */
2023 static int clean_index(const struct object_id *head, const struct object_id *remote)
2024 {
2025         struct tree *head_tree, *remote_tree, *index_tree;
2026         struct object_id index;
2027
2028         head_tree = parse_tree_indirect(head);
2029         if (!head_tree)
2030                 return error(_("Could not parse object '%s'."), oid_to_hex(head));
2031
2032         remote_tree = parse_tree_indirect(remote);
2033         if (!remote_tree)
2034                 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
2035
2036         read_cache_unmerged();
2037
2038         if (fast_forward_to(head_tree, head_tree, 1))
2039                 return -1;
2040
2041         if (write_cache_as_tree(index.hash, 0, NULL))
2042                 return -1;
2043
2044         index_tree = parse_tree_indirect(&index);
2045         if (!index_tree)
2046                 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
2047
2048         if (fast_forward_to(index_tree, remote_tree, 0))
2049                 return -1;
2050
2051         if (merge_tree(remote_tree))
2052                 return -1;
2053
2054         remove_branch_state();
2055
2056         return 0;
2057 }
2058
2059 /**
2060  * Resets rerere's merge resolution metadata.
2061  */
2062 static void am_rerere_clear(void)
2063 {
2064         struct string_list merge_rr = STRING_LIST_INIT_DUP;
2065         rerere_clear(&merge_rr);
2066         string_list_clear(&merge_rr, 1);
2067 }
2068
2069 /**
2070  * Resume the current am session by skipping the current patch.
2071  */
2072 static void am_skip(struct am_state *state)
2073 {
2074         struct object_id head;
2075
2076         am_rerere_clear();
2077
2078         if (get_oid("HEAD", &head))
2079                 hashcpy(head.hash, EMPTY_TREE_SHA1_BIN);
2080
2081         if (clean_index(&head, &head))
2082                 die(_("failed to clean index"));
2083
2084         am_next(state);
2085         am_load(state);
2086         am_run(state, 0);
2087 }
2088
2089 /**
2090  * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2091  *
2092  * It is not safe to reset HEAD when:
2093  * 1. git-am previously failed because the index was dirty.
2094  * 2. HEAD has moved since git-am previously failed.
2095  */
2096 static int safe_to_abort(const struct am_state *state)
2097 {
2098         struct strbuf sb = STRBUF_INIT;
2099         struct object_id abort_safety, head;
2100
2101         if (file_exists(am_path(state, "dirtyindex")))
2102                 return 0;
2103
2104         if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
2105                 if (get_oid_hex(sb.buf, &abort_safety))
2106                         die(_("could not parse %s"), am_path(state, "abort-safety"));
2107         } else
2108                 oidclr(&abort_safety);
2109         strbuf_release(&sb);
2110
2111         if (get_oid("HEAD", &head))
2112                 oidclr(&head);
2113
2114         if (!oidcmp(&head, &abort_safety))
2115                 return 1;
2116
2117         warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
2118                 "Not rewinding to ORIG_HEAD"));
2119
2120         return 0;
2121 }
2122
2123 /**
2124  * Aborts the current am session if it is safe to do so.
2125  */
2126 static void am_abort(struct am_state *state)
2127 {
2128         struct object_id curr_head, orig_head;
2129         int has_curr_head, has_orig_head;
2130         char *curr_branch;
2131
2132         if (!safe_to_abort(state)) {
2133                 am_destroy(state);
2134                 return;
2135         }
2136
2137         am_rerere_clear();
2138
2139         curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
2140         has_curr_head = curr_branch && !is_null_oid(&curr_head);
2141         if (!has_curr_head)
2142                 hashcpy(curr_head.hash, EMPTY_TREE_SHA1_BIN);
2143
2144         has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
2145         if (!has_orig_head)
2146                 hashcpy(orig_head.hash, EMPTY_TREE_SHA1_BIN);
2147
2148         clean_index(&curr_head, &orig_head);
2149
2150         if (has_orig_head)
2151                 update_ref("am --abort", "HEAD", &orig_head,
2152                            has_curr_head ? &curr_head : NULL, 0,
2153                            UPDATE_REFS_DIE_ON_ERR);
2154         else if (curr_branch)
2155                 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
2156
2157         free(curr_branch);
2158         am_destroy(state);
2159 }
2160
2161 /**
2162  * parse_options() callback that validates and sets opt->value to the
2163  * PATCH_FORMAT_* enum value corresponding to `arg`.
2164  */
2165 static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2166 {
2167         int *opt_value = opt->value;
2168
2169         if (!strcmp(arg, "mbox"))
2170                 *opt_value = PATCH_FORMAT_MBOX;
2171         else if (!strcmp(arg, "stgit"))
2172                 *opt_value = PATCH_FORMAT_STGIT;
2173         else if (!strcmp(arg, "stgit-series"))
2174                 *opt_value = PATCH_FORMAT_STGIT_SERIES;
2175         else if (!strcmp(arg, "hg"))
2176                 *opt_value = PATCH_FORMAT_HG;
2177         else if (!strcmp(arg, "mboxrd"))
2178                 *opt_value = PATCH_FORMAT_MBOXRD;
2179         else
2180                 return error(_("Invalid value for --patch-format: %s"), arg);
2181         return 0;
2182 }
2183
2184 enum resume_mode {
2185         RESUME_FALSE = 0,
2186         RESUME_APPLY,
2187         RESUME_RESOLVED,
2188         RESUME_SKIP,
2189         RESUME_ABORT
2190 };
2191
2192 static int git_am_config(const char *k, const char *v, void *cb)
2193 {
2194         int status;
2195
2196         status = git_gpg_config(k, v, NULL);
2197         if (status)
2198                 return status;
2199
2200         return git_default_config(k, v, NULL);
2201 }
2202
2203 int cmd_am(int argc, const char **argv, const char *prefix)
2204 {
2205         struct am_state state;
2206         int binary = -1;
2207         int keep_cr = -1;
2208         int patch_format = PATCH_FORMAT_UNKNOWN;
2209         enum resume_mode resume = RESUME_FALSE;
2210         int in_progress;
2211
2212         const char * const usage[] = {
2213                 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
2214                 N_("git am [<options>] (--continue | --skip | --abort)"),
2215                 NULL
2216         };
2217
2218         struct option options[] = {
2219                 OPT_BOOL('i', "interactive", &state.interactive,
2220                         N_("run interactively")),
2221                 OPT_HIDDEN_BOOL('b', "binary", &binary,
2222                         N_("historical option -- no-op")),
2223                 OPT_BOOL('3', "3way", &state.threeway,
2224                         N_("allow fall back on 3way merging if needed")),
2225                 OPT__QUIET(&state.quiet, N_("be quiet")),
2226                 OPT_SET_INT('s', "signoff", &state.signoff,
2227                         N_("add a Signed-off-by line to the commit message"),
2228                         SIGNOFF_EXPLICIT),
2229                 OPT_BOOL('u', "utf8", &state.utf8,
2230                         N_("recode into utf8 (default)")),
2231                 OPT_SET_INT('k', "keep", &state.keep,
2232                         N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2233                 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2234                         N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
2235                 OPT_BOOL('m', "message-id", &state.message_id,
2236                         N_("pass -m flag to git-mailinfo")),
2237                 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
2238                   N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2239                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
2240                 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
2241                   N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2242                   PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
2243                 OPT_BOOL('c', "scissors", &state.scissors,
2244                         N_("strip everything before a scissors line")),
2245                 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2246                         N_("pass it through git-apply"),
2247                         0),
2248                 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2249                         N_("pass it through git-apply"),
2250                         PARSE_OPT_NOARG),
2251                 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2252                         N_("pass it through git-apply"),
2253                         PARSE_OPT_NOARG),
2254                 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2255                         N_("pass it through git-apply"),
2256                         0),
2257                 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2258                         N_("pass it through git-apply"),
2259                         0),
2260                 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2261                         N_("pass it through git-apply"),
2262                         0),
2263                 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2264                         N_("pass it through git-apply"),
2265                         0),
2266                 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2267                         N_("pass it through git-apply"),
2268                         0),
2269                 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2270                         N_("format the patch(es) are in"),
2271                         parse_opt_patchformat),
2272                 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2273                         N_("pass it through git-apply"),
2274                         PARSE_OPT_NOARG),
2275                 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2276                         N_("override error message when patch failure occurs")),
2277                 OPT_CMDMODE(0, "continue", &resume,
2278                         N_("continue applying patches after resolving a conflict"),
2279                         RESUME_RESOLVED),
2280                 OPT_CMDMODE('r', "resolved", &resume,
2281                         N_("synonyms for --continue"),
2282                         RESUME_RESOLVED),
2283                 OPT_CMDMODE(0, "skip", &resume,
2284                         N_("skip the current patch"),
2285                         RESUME_SKIP),
2286                 OPT_CMDMODE(0, "abort", &resume,
2287                         N_("restore the original branch and abort the patching operation."),
2288                         RESUME_ABORT),
2289                 OPT_BOOL(0, "committer-date-is-author-date",
2290                         &state.committer_date_is_author_date,
2291                         N_("lie about committer date")),
2292                 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2293                         N_("use current timestamp for author date")),
2294                 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
2295                 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2296                   N_("GPG-sign commits"),
2297                   PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
2298                 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2299                         N_("(internal use for git-rebase)")),
2300                 OPT_END()
2301         };
2302
2303         if (argc == 2 && !strcmp(argv[1], "-h"))
2304                 usage_with_options(usage, options);
2305
2306         git_config(git_am_config, NULL);
2307
2308         am_state_init(&state);
2309
2310         in_progress = am_in_progress(&state);
2311         if (in_progress)
2312                 am_load(&state);
2313
2314         argc = parse_options(argc, argv, prefix, options, usage, 0);
2315
2316         if (binary >= 0)
2317                 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2318                                 "it will be removed. Please do not use it anymore."));
2319
2320         /* Ensure a valid committer ident can be constructed */
2321         git_committer_info(IDENT_STRICT);
2322
2323         if (read_index_preload(&the_index, NULL) < 0)
2324                 die(_("failed to read the index"));
2325
2326         if (in_progress) {
2327                 /*
2328                  * Catch user error to feed us patches when there is a session
2329                  * in progress:
2330                  *
2331                  * 1. mbox path(s) are provided on the command-line.
2332                  * 2. stdin is not a tty: the user is trying to feed us a patch
2333                  *    from standard input. This is somewhat unreliable -- stdin
2334                  *    could be /dev/null for example and the caller did not
2335                  *    intend to feed us a patch but wanted to continue
2336                  *    unattended.
2337                  */
2338                 if (argc || (resume == RESUME_FALSE && !isatty(0)))
2339                         die(_("previous rebase directory %s still exists but mbox given."),
2340                                 state.dir);
2341
2342                 if (resume == RESUME_FALSE)
2343                         resume = RESUME_APPLY;
2344
2345                 if (state.signoff == SIGNOFF_EXPLICIT)
2346                         am_append_signoff(&state);
2347         } else {
2348                 struct argv_array paths = ARGV_ARRAY_INIT;
2349                 int i;
2350
2351                 /*
2352                  * Handle stray state directory in the independent-run case. In
2353                  * the --rebasing case, it is up to the caller to take care of
2354                  * stray directories.
2355                  */
2356                 if (file_exists(state.dir) && !state.rebasing) {
2357                         if (resume == RESUME_ABORT) {
2358                                 am_destroy(&state);
2359                                 am_state_release(&state);
2360                                 return 0;
2361                         }
2362
2363                         die(_("Stray %s directory found.\n"
2364                                 "Use \"git am --abort\" to remove it."),
2365                                 state.dir);
2366                 }
2367
2368                 if (resume)
2369                         die(_("Resolve operation not in progress, we are not resuming."));
2370
2371                 for (i = 0; i < argc; i++) {
2372                         if (is_absolute_path(argv[i]) || !prefix)
2373                                 argv_array_push(&paths, argv[i]);
2374                         else
2375                                 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
2376                 }
2377
2378                 am_setup(&state, patch_format, paths.argv, keep_cr);
2379
2380                 argv_array_clear(&paths);
2381         }
2382
2383         switch (resume) {
2384         case RESUME_FALSE:
2385                 am_run(&state, 0);
2386                 break;
2387         case RESUME_APPLY:
2388                 am_run(&state, 1);
2389                 break;
2390         case RESUME_RESOLVED:
2391                 am_resolve(&state);
2392                 break;
2393         case RESUME_SKIP:
2394                 am_skip(&state);
2395                 break;
2396         case RESUME_ABORT:
2397                 am_abort(&state);
2398                 break;
2399         default:
2400                 die("BUG: invalid resume value");
2401         }
2402
2403         am_state_release(&state);
2404
2405         return 0;
2406 }