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