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