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