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