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