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