]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/am.c
Merge branch 'jk/clone-allow-bare-and-o-together'
[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 */
f8adbec9 6#define USE_THE_INDEX_COMPATIBILITY_MACROS
73c2779f 7#include "cache.h"
b2141fc1 8#include "config.h"
73c2779f 9#include "builtin.h"
d807c4a0 10#include "exec-cmd.h"
8c3bd9e2
PT
11#include "parse-options.h"
12#include "dir.h"
11c2177f 13#include "run-command.h"
5e3aba33 14#include "hook.h"
3e20dcf3 15#include "quote.h"
db86e61c 16#include "tempfile.h"
38a824fe 17#include "lockfile.h"
c9e8d960
PT
18#include "cache-tree.h"
19#include "refs.h"
20#include "commit.h"
32a5fcbf
PT
21#include "diff.h"
22#include "diffcore.h"
9990080c
PT
23#include "unpack-trees.h"
24#include "branch.h"
eb898b83 25#include "sequencer.h"
84f3de28
PT
26#include "revision.h"
27#include "merge-recursive.h"
df2760a5 28#include "log-tree.h"
88b291fe 29#include "notes-utils.h"
f1cb96d6 30#include "rerere.h"
7ff26832 31#include "prompt.h"
4b98bae2 32#include "mailinfo.h"
edfac5eb 33#include "apply.h"
a77598ef 34#include "string-list.h"
3836d88a 35#include "packfile.h"
f86bcc7b 36#include "repository.h"
88c7b4c3 37#include "pretty.h"
3e20dcf3 38
38a824fe
PT
39/**
40 * Returns the length of the first line of msg.
41 */
42static int linelen(const char *msg)
43{
44 return strchrnul(msg, '\n') - msg;
45}
46
5ae41c79
PT
47/**
48 * Returns true if `str` consists of only whitespace, false otherwise.
49 */
50static int str_isspace(const char *str)
51{
52 for (; *str; str++)
53 if (!isspace(*str))
54 return 0;
55
56 return 1;
57}
58
11c2177f
PT
59enum patch_format {
60 PATCH_FORMAT_UNKNOWN = 0,
5ae41c79 61 PATCH_FORMAT_MBOX,
336108c1 62 PATCH_FORMAT_STGIT,
94cd175c 63 PATCH_FORMAT_STGIT_SERIES,
d9925d1a
EW
64 PATCH_FORMAT_HG,
65 PATCH_FORMAT_MBOXRD
11c2177f 66};
8c3bd9e2 67
4f1b6961
PT
68enum keep_type {
69 KEEP_FALSE = 0,
70 KEEP_TRUE, /* pass -k flag to git-mailinfo */
71 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
72};
73
9b646617
PT
74enum scissors_type {
75 SCISSORS_UNSET = -1,
76 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
77 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
78};
79
b5e82359
PT
80enum signoff_type {
81 SIGNOFF_FALSE = 0,
82 SIGNOFF_TRUE = 1,
83 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
84};
85
f3b48228
PB
86enum show_patch_type {
87 SHOW_PATCH_RAW = 0,
aa416b22 88 SHOW_PATCH_DIFF = 1,
f3b48228
PB
89};
90
7c096b8d
A
91enum empty_action {
92 STOP_ON_EMPTY_COMMIT = 0, /* output errors and stop in the middle of an am session */
93 DROP_EMPTY_COMMIT, /* skip with a notice message, unless "--quiet" has been passed */
94 KEEP_EMPTY_COMMIT, /* keep recording as empty commits */
95};
96
8c3bd9e2
PT
97struct am_state {
98 /* state directory path */
99 char *dir;
100
101 /* current and last patch numbers, 1-indexed */
102 int cur;
103 int last;
11c2177f 104
3e20dcf3
PT
105 /* commit metadata and message */
106 char *author_name;
107 char *author_email;
108 char *author_date;
109 char *msg;
110 size_t msg_len;
111
13b97ea5 112 /* when --rebasing, records the original commit the patch came from */
8c88769b 113 struct object_id orig_commit;
13b97ea5 114
11c2177f
PT
115 /* number of digits in patch filename */
116 int prec;
5d28cf78
PT
117
118 /* various operating modes and command line options */
7ff26832 119 int interactive;
84f3de28 120 int threeway;
5d28cf78 121 int quiet;
b5e82359 122 int signoff; /* enum signoff_type */
ef7ee16d 123 int utf8;
4f1b6961 124 int keep; /* enum keep_type */
702cbaad 125 int message_id;
9b646617 126 int scissors; /* enum scissors_type */
59b519ab 127 int quoted_cr; /* enum quoted_cr_action */
7c096b8d 128 int empty_type; /* enum empty_action */
22f9b7f3 129 struct strvec git_apply_opts;
2d83109a 130 const char *resolvemsg;
0cd4bcba 131 int committer_date_is_author_date;
f07adb62 132 int ignore_date;
f1cb96d6 133 int allow_rerere_autoupdate;
7e35dacb 134 const char *sign_commit;
35bdcc59 135 int rebasing;
8c3bd9e2
PT
136};
137
138/**
16d2676c 139 * Initializes am_state with the default values.
8c3bd9e2 140 */
16d2676c 141static void am_state_init(struct am_state *state)
8c3bd9e2 142{
7e35dacb
PT
143 int gpgsign;
144
8c3bd9e2
PT
145 memset(state, 0, sizeof(*state));
146
16d2676c 147 state->dir = git_pathdup("rebase-apply");
11c2177f
PT
148
149 state->prec = 4;
ef7ee16d 150
e97a5e76
RL
151 git_config_get_bool("am.threeway", &state->threeway);
152
ef7ee16d 153 state->utf8 = 1;
702cbaad
PT
154
155 git_config_get_bool("am.messageid", &state->message_id);
9b646617
PT
156
157 state->scissors = SCISSORS_UNSET;
59b519ab 158 state->quoted_cr = quoted_cr_unset;
257e8cec 159
22f9b7f3 160 strvec_init(&state->git_apply_opts);
7e35dacb
PT
161
162 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
163 state->sign_commit = gpgsign ? "" : NULL;
8c3bd9e2
PT
164}
165
166/**
167 * Releases memory allocated by an am_state.
168 */
169static void am_state_release(struct am_state *state)
170{
171 free(state->dir);
3e20dcf3
PT
172 free(state->author_name);
173 free(state->author_email);
174 free(state->author_date);
175 free(state->msg);
22f9b7f3 176 strvec_clear(&state->git_apply_opts);
8c3bd9e2
PT
177}
178
59b519ab
ĐTCD
179static int am_option_parse_quoted_cr(const struct option *opt,
180 const char *arg, int unset)
181{
182 BUG_ON_OPT_NEG(unset);
183
184 if (mailinfo_parse_quoted_cr_action(arg, opt->value) != 0)
185 return error(_("bad action '%s' for '%s'"), arg, "--quoted-cr");
186 return 0;
187}
188
7c096b8d
A
189static int am_option_parse_empty(const struct option *opt,
190 const char *arg, int unset)
191{
192 int *opt_value = opt->value;
193
194 BUG_ON_OPT_NEG(unset);
195
196 if (!strcmp(arg, "stop"))
197 *opt_value = STOP_ON_EMPTY_COMMIT;
198 else if (!strcmp(arg, "drop"))
199 *opt_value = DROP_EMPTY_COMMIT;
200 else if (!strcmp(arg, "keep"))
201 *opt_value = KEEP_EMPTY_COMMIT;
202 else
1a8aea85 203 return error(_("invalid value for '%s': '%s'"), "--empty", arg);
7c096b8d
A
204
205 return 0;
206}
207
8c3bd9e2
PT
208/**
209 * Returns path relative to the am_state directory.
210 */
211static inline const char *am_path(const struct am_state *state, const char *path)
212{
213 return mkpath("%s/%s", state->dir, path);
214}
215
25b763ba
JH
216/**
217 * For convenience to call write_file()
218 */
1dad879a
RS
219static void write_state_text(const struct am_state *state,
220 const char *name, const char *string)
25b763ba 221{
1dad879a 222 write_file(am_path(state, name), "%s", string);
25b763ba
JH
223}
224
1dad879a
RS
225static void write_state_count(const struct am_state *state,
226 const char *name, int value)
25b763ba 227{
1dad879a 228 write_file(am_path(state, name), "%d", value);
25b763ba
JH
229}
230
1dad879a
RS
231static void write_state_bool(const struct am_state *state,
232 const char *name, int value)
25b763ba 233{
1dad879a 234 write_state_text(state, name, value ? "t" : "f");
25b763ba
JH
235}
236
5d28cf78
PT
237/**
238 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
239 * at the end.
240 */
48ca53ca 241__attribute__((format (printf, 3, 4)))
5d28cf78
PT
242static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
243{
244 va_list ap;
245
246 va_start(ap, fmt);
247 if (!state->quiet) {
248 vfprintf(fp, fmt, ap);
249 putc('\n', fp);
250 }
251 va_end(ap);
252}
253
8c3bd9e2
PT
254/**
255 * Returns 1 if there is an am session in progress, 0 otherwise.
256 */
257static int am_in_progress(const struct am_state *state)
258{
259 struct stat st;
260
261 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
262 return 0;
263 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
264 return 0;
265 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
266 return 0;
267 return 1;
268}
269
270/**
271 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
272 * number of bytes read on success, -1 if the file does not exist. If `trim` is
273 * set, trailing whitespace will be removed.
274 */
275static int read_state_file(struct strbuf *sb, const struct am_state *state,
276 const char *file, int trim)
277{
278 strbuf_reset(sb);
279
280 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
281 if (trim)
282 strbuf_trim(sb);
283
284 return sb->len;
285 }
286
287 if (errno == ENOENT)
288 return -1;
289
290 die_errno(_("could not read '%s'"), am_path(state, file));
291}
292
3e20dcf3
PT
293/**
294 * Reads and parses the state directory's "author-script" file, and sets
295 * state->author_name, state->author_email and state->author_date accordingly.
296 * Returns 0 on success, -1 if the file could not be parsed.
297 *
298 * The author script is of the format:
299 *
300 * GIT_AUTHOR_NAME='$author_name'
301 * GIT_AUTHOR_EMAIL='$author_email'
302 * GIT_AUTHOR_DATE='$author_date'
303 *
304 * where $author_name, $author_email and $author_date are quoted. We are strict
305 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
306 * script, and thus if the file differs from what this function expects, it is
307 * better to bail out than to do something that the user does not expect.
308 */
a75d3513 309static int read_am_author_script(struct am_state *state)
3e20dcf3
PT
310{
311 const char *filename = am_path(state, "author-script");
3e20dcf3
PT
312
313 assert(!state->author_name);
314 assert(!state->author_email);
315 assert(!state->author_date);
316
bcd33ec2
PW
317 return read_author_script(filename, &state->author_name,
318 &state->author_email, &state->author_date, 1);
3e20dcf3
PT
319}
320
321/**
322 * Saves state->author_name, state->author_email and state->author_date in the
323 * state directory's "author-script" file.
324 */
325static void write_author_script(const struct am_state *state)
326{
327 struct strbuf sb = STRBUF_INIT;
328
329 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
330 sq_quote_buf(&sb, state->author_name);
331 strbuf_addch(&sb, '\n');
332
333 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
334 sq_quote_buf(&sb, state->author_email);
335 strbuf_addch(&sb, '\n');
336
337 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
338 sq_quote_buf(&sb, state->author_date);
339 strbuf_addch(&sb, '\n');
340
25b763ba 341 write_state_text(state, "author-script", sb.buf);
3e20dcf3
PT
342
343 strbuf_release(&sb);
344}
345
346/**
347 * Reads the commit message from the state directory's "final-commit" file,
348 * setting state->msg to its contents and state->msg_len to the length of its
349 * contents in bytes.
350 *
351 * Returns 0 on success, -1 if the file does not exist.
352 */
353static int read_commit_msg(struct am_state *state)
354{
355 struct strbuf sb = STRBUF_INIT;
356
357 assert(!state->msg);
358
359 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
360 strbuf_release(&sb);
361 return -1;
362 }
363
364 state->msg = strbuf_detach(&sb, &state->msg_len);
365 return 0;
366}
367
368/**
369 * Saves state->msg in the state directory's "final-commit" file.
370 */
371static void write_commit_msg(const struct am_state *state)
372{
3e20dcf3 373 const char *filename = am_path(state, "final-commit");
e78d5d49 374 write_file_buf(filename, state->msg, state->msg_len);
3e20dcf3
PT
375}
376
8c3bd9e2
PT
377/**
378 * Loads state from disk.
379 */
380static void am_load(struct am_state *state)
381{
382 struct strbuf sb = STRBUF_INIT;
383
384 if (read_state_file(&sb, state, "next", 1) < 0)
033abf97 385 BUG("state file 'next' does not exist");
8c3bd9e2
PT
386 state->cur = strtol(sb.buf, NULL, 10);
387
388 if (read_state_file(&sb, state, "last", 1) < 0)
033abf97 389 BUG("state file 'last' does not exist");
8c3bd9e2
PT
390 state->last = strtol(sb.buf, NULL, 10);
391
a75d3513 392 if (read_am_author_script(state) < 0)
3e20dcf3
PT
393 die(_("could not parse author script"));
394
395 read_commit_msg(state);
396
13b97ea5 397 if (read_state_file(&sb, state, "original-commit", 1) < 0)
8c88769b 398 oidclr(&state->orig_commit);
399 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
13b97ea5
PT
400 die(_("could not parse %s"), am_path(state, "original-commit"));
401
84f3de28
PT
402 read_state_file(&sb, state, "threeway", 1);
403 state->threeway = !strcmp(sb.buf, "t");
404
5d28cf78
PT
405 read_state_file(&sb, state, "quiet", 1);
406 state->quiet = !strcmp(sb.buf, "t");
407
eb898b83
PT
408 read_state_file(&sb, state, "sign", 1);
409 state->signoff = !strcmp(sb.buf, "t");
410
ef7ee16d
PT
411 read_state_file(&sb, state, "utf8", 1);
412 state->utf8 = !strcmp(sb.buf, "t");
413
fd4a3f48
PW
414 if (file_exists(am_path(state, "rerere-autoupdate"))) {
415 read_state_file(&sb, state, "rerere-autoupdate", 1);
416 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
417 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
418 } else {
419 state->allow_rerere_autoupdate = 0;
420 }
421
4f1b6961
PT
422 read_state_file(&sb, state, "keep", 1);
423 if (!strcmp(sb.buf, "t"))
424 state->keep = KEEP_TRUE;
425 else if (!strcmp(sb.buf, "b"))
426 state->keep = KEEP_NON_PATCH;
427 else
428 state->keep = KEEP_FALSE;
429
702cbaad
PT
430 read_state_file(&sb, state, "messageid", 1);
431 state->message_id = !strcmp(sb.buf, "t");
432
9b646617
PT
433 read_state_file(&sb, state, "scissors", 1);
434 if (!strcmp(sb.buf, "t"))
435 state->scissors = SCISSORS_TRUE;
436 else if (!strcmp(sb.buf, "f"))
437 state->scissors = SCISSORS_FALSE;
438 else
439 state->scissors = SCISSORS_UNSET;
440
59b519ab
ĐTCD
441 read_state_file(&sb, state, "quoted-cr", 1);
442 if (!*sb.buf)
443 state->quoted_cr = quoted_cr_unset;
444 else if (mailinfo_parse_quoted_cr_action(sb.buf, &state->quoted_cr) != 0)
445 die(_("could not parse %s"), am_path(state, "quoted-cr"));
446
257e8cec 447 read_state_file(&sb, state, "apply-opt", 1);
22f9b7f3 448 strvec_clear(&state->git_apply_opts);
2745b6b4 449 if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
257e8cec
PT
450 die(_("could not parse %s"), am_path(state, "apply-opt"));
451
35bdcc59
PT
452 state->rebasing = !!file_exists(am_path(state, "rebasing"));
453
8c3bd9e2
PT
454 strbuf_release(&sb);
455}
456
457/**
458 * Removes the am_state directory, forcefully terminating the current am
459 * session.
460 */
461static void am_destroy(const struct am_state *state)
462{
463 struct strbuf sb = STRBUF_INIT;
464
465 strbuf_addstr(&sb, state->dir);
466 remove_dir_recursively(&sb, 0);
467 strbuf_release(&sb);
468}
469
b8803d8f
PT
470/**
471 * Runs applypatch-msg hook. Returns its exit code.
472 */
473static int run_applypatch_msg_hook(struct am_state *state)
474{
475 int ret;
476
477 assert(state->msg);
432a50be 478 ret = run_hooks_l("applypatch-msg", am_path(state, "final-commit"), NULL);
b8803d8f
PT
479
480 if (!ret) {
6a83d902 481 FREE_AND_NULL(state->msg);
b8803d8f
PT
482 if (read_commit_msg(state) < 0)
483 die(_("'%s' was deleted by the applypatch-msg hook"),
484 am_path(state, "final-commit"));
485 }
486
487 return ret;
488}
489
13b97ea5
PT
490/**
491 * Runs post-rewrite hook. Returns it exit code.
492 */
493static int run_post_rewrite_hook(const struct am_state *state)
494{
495 struct child_process cp = CHILD_PROCESS_INIT;
496 const char *hook = find_hook("post-rewrite");
497 int ret;
498
499 if (!hook)
500 return 0;
501
22f9b7f3
JK
502 strvec_push(&cp.args, hook);
503 strvec_push(&cp.args, "rebase");
13b97ea5
PT
504
505 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
506 cp.stdout_to_stderr = 1;
6206286e 507 cp.trace2_hook_name = "post-rewrite";
13b97ea5
PT
508
509 ret = run_command(&cp);
510
511 close(cp.in);
512 return ret;
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 */
789static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
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 */
872static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
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
8c88769b 1078 if (!get_oid("HEAD", &curr_head)) {
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
8c88769b 1121 if (!get_oid("HEAD", &head))
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);
63af4a84 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
PT
1340
1341 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1342
1343 ident_line = find_commit_header(buffer, "author", &ident_len);
0dfed92d
JK
1344 if (!ident_line)
1345 die(_("missing author line in commit %s"),
1346 oid_to_hex(&commit->object.oid));
721f5f1e 1347 if (split_ident_line(&id, ident_line, ident_len) < 0)
2e2bbb96 1348 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
df2760a5
PT
1349
1350 assert(!state->author_name);
721f5f1e 1351 if (id.name_begin)
2e2bbb96 1352 state->author_name =
721f5f1e
JK
1353 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1354 else
df2760a5
PT
1355 state->author_name = xstrdup("");
1356
1357 assert(!state->author_email);
721f5f1e 1358 if (id.mail_begin)
2e2bbb96 1359 state->author_email =
721f5f1e
JK
1360 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1361 else
df2760a5
PT
1362 state->author_email = xstrdup("");
1363
df2760a5 1364 assert(!state->author_date);
721f5f1e 1365 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
df2760a5
PT
1366
1367 assert(!state->msg);
1368 msg = strstr(buffer, "\n\n");
1369 if (!msg)
f2fd0760 1370 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
df2760a5
PT
1371 state->msg = xstrdup(msg + 2);
1372 state->msg_len = strlen(state->msg);
f131db9e 1373 unuse_commit_buffer(commit, buffer);
df2760a5
PT
1374}
1375
1376/**
1377 * Writes `commit` as a patch to the state directory's "patch" file.
1378 */
1379static void write_commit_patch(const struct am_state *state, struct commit *commit)
1380{
1381 struct rev_info rev_info;
1382 FILE *fp;
1383
1384 fp = xfopen(am_path(state, "patch"), "w");
2abf3503 1385 repo_init_revisions(the_repository, &rev_info, NULL);
df2760a5
PT
1386 rev_info.diff = 1;
1387 rev_info.abbrev = 0;
1388 rev_info.disable_stdin = 1;
1389 rev_info.show_root_diff = 1;
1390 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1391 rev_info.no_commit_id = 1;
0d1e0e78
BW
1392 rev_info.diffopt.flags.binary = 1;
1393 rev_info.diffopt.flags.full_index = 1;
df2760a5
PT
1394 rev_info.diffopt.use_color = 0;
1395 rev_info.diffopt.file = fp;
1396 rev_info.diffopt.close_file = 1;
1397 add_pending_object(&rev_info, &commit->object, "");
1398 diff_setup_done(&rev_info.diffopt);
1399 log_tree_commit(&rev_info, commit);
2108fe4a 1400 release_revisions(&rev_info);
df2760a5
PT
1401}
1402
7ff26832
PT
1403/**
1404 * Writes the diff of the index against HEAD as a patch to the state
1405 * directory's "patch" file.
1406 */
1407static void write_index_patch(const struct am_state *state)
1408{
1409 struct tree *tree;
8c88769b 1410 struct object_id head;
7ff26832
PT
1411 struct rev_info rev_info;
1412 FILE *fp;
1413
7663e438
JK
1414 if (!get_oid("HEAD", &head)) {
1415 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1416 tree = get_commit_tree(commit);
1417 } else
f86bcc7b
SB
1418 tree = lookup_tree(the_repository,
1419 the_repository->hash_algo->empty_tree);
7ff26832
PT
1420
1421 fp = xfopen(am_path(state, "patch"), "w");
2abf3503 1422 repo_init_revisions(the_repository, &rev_info, NULL);
7ff26832
PT
1423 rev_info.diff = 1;
1424 rev_info.disable_stdin = 1;
1425 rev_info.no_commit_id = 1;
1426 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1427 rev_info.diffopt.use_color = 0;
1428 rev_info.diffopt.file = fp;
1429 rev_info.diffopt.close_file = 1;
1430 add_pending_object(&rev_info, &tree->object, "");
1431 diff_setup_done(&rev_info.diffopt);
1432 run_diff_index(&rev_info, 1);
2108fe4a 1433 release_revisions(&rev_info);
7ff26832
PT
1434}
1435
df2760a5
PT
1436/**
1437 * Like parse_mail(), but parses the mail by looking up its commit ID
1438 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1439 * of patches.
1440 *
13b97ea5
PT
1441 * state->orig_commit will be set to the original commit ID.
1442 *
df2760a5
PT
1443 * Will always return 0 as the patch should never be skipped.
1444 */
1445static int parse_mail_rebase(struct am_state *state, const char *mail)
1446{
1447 struct commit *commit;
8c88769b 1448 struct object_id commit_oid;
df2760a5 1449
8c88769b 1450 if (get_mail_commit_oid(&commit_oid, mail) < 0)
df2760a5
PT
1451 die(_("could not parse %s"), mail);
1452
bc83266a 1453 commit = lookup_commit_or_die(&commit_oid, mail);
df2760a5
PT
1454
1455 get_commit_info(state, commit);
1456
1457 write_commit_patch(state, commit);
1458
8c88769b 1459 oidcpy(&state->orig_commit, &commit_oid);
1460 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
fbd7a232
NTND
1461 update_ref("am", "REBASE_HEAD", &commit_oid,
1462 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
13b97ea5 1463
df2760a5
PT
1464 return 0;
1465}
1466
38a824fe 1467/**
84f3de28
PT
1468 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1469 * `index_file` is not NULL, the patch will be applied to that index.
38a824fe 1470 */
84f3de28 1471static int run_apply(const struct am_state *state, const char *index_file)
38a824fe 1472{
22f9b7f3
JK
1473 struct strvec apply_paths = STRVEC_INIT;
1474 struct strvec apply_opts = STRVEC_INIT;
edfac5eb
CC
1475 struct apply_state apply_state;
1476 int res, opts_left;
edfac5eb
CC
1477 int force_apply = 0;
1478 int options = 0;
1479
82ea77ec 1480 if (init_apply_state(&apply_state, the_repository, NULL))
033abf97 1481 BUG("init_apply_state() failed");
edfac5eb 1482
22f9b7f3 1483 strvec_push(&apply_opts, "apply");
d70a9eb6 1484 strvec_pushv(&apply_opts, state->git_apply_opts.v);
edfac5eb 1485
d70a9eb6 1486 opts_left = apply_parse_options(apply_opts.nr, apply_opts.v,
edfac5eb
CC
1487 &apply_state, &force_apply, &options,
1488 NULL);
1489
1490 if (opts_left != 0)
1491 die("unknown option passed through to git apply");
1492
1493 if (index_file) {
1494 apply_state.index_file = index_file;
1495 apply_state.cached = 1;
1496 } else
1497 apply_state.check_index = 1;
84f3de28
PT
1498
1499 /*
1500 * If we are allowed to fall back on 3-way merge, don't give false
1501 * errors during the initial attempt.
1502 */
edfac5eb
CC
1503 if (state->threeway && !index_file)
1504 apply_state.apply_verbosity = verbosity_silent;
84f3de28 1505
edfac5eb 1506 if (check_apply_state(&apply_state, force_apply))
033abf97 1507 BUG("check_apply_state() failed");
84f3de28 1508
22f9b7f3 1509 strvec_push(&apply_paths, am_path(state, "patch"));
257e8cec 1510
d70a9eb6 1511 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
84f3de28 1512
22f9b7f3
JK
1513 strvec_clear(&apply_paths);
1514 strvec_clear(&apply_opts);
edfac5eb 1515 clear_apply_state(&apply_state);
38a824fe 1516
edfac5eb
CC
1517 if (res)
1518 return res;
38a824fe 1519
edfac5eb
CC
1520 if (index_file) {
1521 /* Reload index as apply_all_patches() will have modified it. */
1522 discard_cache();
1523 read_cache_from(index_file);
1524 }
84f3de28
PT
1525
1526 return 0;
1527}
1528
1529/**
1530 * Builds an index that contains just the blobs needed for a 3way merge.
1531 */
1532static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1533{
1534 struct child_process cp = CHILD_PROCESS_INIT;
1535
1536 cp.git_cmd = 1;
22f9b7f3 1537 strvec_push(&cp.args, "apply");
d70a9eb6 1538 strvec_pushv(&cp.args, state->git_apply_opts.v);
22f9b7f3
JK
1539 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1540 strvec_push(&cp.args, am_path(state, "patch"));
84f3de28
PT
1541
1542 if (run_command(&cp))
1543 return -1;
1544
1545 return 0;
1546}
1547
1548/**
1549 * Attempt a threeway merge, using index_path as the temporary index.
1550 */
1551static int fall_back_threeway(const struct am_state *state, const char *index_path)
1552{
3f338f43
JS
1553 struct object_id orig_tree, their_tree, our_tree;
1554 const struct object_id *bases[1] = { &orig_tree };
1555 struct merge_options o;
1556 struct commit *result;
1557 char *their_tree_name;
84f3de28 1558
3f338f43 1559 if (get_oid("HEAD", &our_tree) < 0)
d41836a0 1560 oidcpy(&our_tree, the_hash_algo->empty_tree);
84f3de28
PT
1561
1562 if (build_fake_ancestor(state, index_path))
1563 return error("could not build fake ancestor");
1564
1565 discard_cache();
1566 read_cache_from(index_path);
1567
fc5cb99f 1568 if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
84f3de28
PT
1569 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1570
1571 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1572
1573 if (!state->quiet) {
1574 /*
1575 * List paths that needed 3-way fallback, so that the user can
1576 * review them with extra care to spot mismerges.
1577 */
1578 struct rev_info rev_info;
84f3de28 1579
2abf3503 1580 repo_init_revisions(the_repository, &rev_info, NULL);
84f3de28 1581 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
cdb5330a
NTND
1582 rev_info.diffopt.filter |= diff_filter_bit('A');
1583 rev_info.diffopt.filter |= diff_filter_bit('M');
a58a1b01 1584 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
84f3de28
PT
1585 diff_setup_done(&rev_info.diffopt);
1586 run_diff_index(&rev_info, 1);
2108fe4a 1587 release_revisions(&rev_info);
84f3de28
PT
1588 }
1589
1590 if (run_apply(state, index_path))
1591 return error(_("Did you hand edit your patch?\n"
1592 "It does not apply to blobs recorded in its index."));
1593
fc5cb99f 1594 if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
84f3de28
PT
1595 return error("could not write tree");
1596
1597 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1598
38a824fe
PT
1599 discard_cache();
1600 read_cache();
1601
84f3de28
PT
1602 /*
1603 * This is not so wrong. Depending on which base we picked, orig_tree
715a51bc 1604 * may be wildly different from ours, but their_tree has the same set of
84f3de28
PT
1605 * wildly different changes in parts the patch did not touch, so
1606 * recursive ends up canceling them, saying that we reverted all those
1607 * changes.
1608 */
1609
0d6caa2d 1610 init_merge_options(&o, the_repository);
3f338f43
JS
1611
1612 o.branch1 = "HEAD";
1613 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1614 o.branch2 = their_tree_name;
8e012516 1615 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
3f338f43
JS
1616
1617 if (state->quiet)
1618 o.verbosity = 0;
1619
1620 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
35843b11 1621 repo_rerere(the_repository, state->allow_rerere_autoupdate);
3f338f43 1622 free(their_tree_name);
84f3de28
PT
1623 return error(_("Failed to merge in the changes."));
1624 }
1625
3f338f43 1626 free(their_tree_name);
38a824fe
PT
1627 return 0;
1628}
1629
c9e8d960
PT
1630/**
1631 * Commits the current index with state->msg as the commit message and
1632 * state->author_name, state->author_email and state->author_date as the author
1633 * information.
1634 */
1635static void do_commit(const struct am_state *state)
1636{
8c88769b 1637 struct object_id tree, parent, commit;
1638 const struct object_id *old_oid;
c9e8d960 1639 struct commit_list *parents = NULL;
e8cbe211 1640 const char *reflog_msg, *author, *committer = NULL;
c9e8d960
PT
1641 struct strbuf sb = STRBUF_INIT;
1642
593ffdd8 1643 if (run_hooks("pre-applypatch"))
6c24c5c0
PT
1644 exit(1);
1645
fc5cb99f 1646 if (write_cache_as_tree(&tree, 0, NULL))
c9e8d960
PT
1647 die(_("git write-tree failed to write a tree"));
1648
e82caf38 1649 if (!get_oid_commit("HEAD", &parent)) {
8c88769b 1650 old_oid = &parent;
c1f5eb49
SB
1651 commit_list_insert(lookup_commit(the_repository, &parent),
1652 &parents);
c9e8d960 1653 } else {
8c88769b 1654 old_oid = NULL;
5d28cf78 1655 say(state, stderr, _("applying to an empty history"));
c9e8d960
PT
1656 }
1657
1658 author = fmt_ident(state->author_name, state->author_email,
39ab4d09 1659 WANT_AUTHOR_IDENT,
f07adb62
PT
1660 state->ignore_date ? NULL : state->author_date,
1661 IDENT_STRICT);
c9e8d960 1662
0cd4bcba 1663 if (state->committer_date_is_author_date)
2020451c
JK
1664 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1665 getenv("GIT_COMMITTER_EMAIL"),
1666 WANT_COMMITTER_IDENT,
e8cbe211
PW
1667 state->ignore_date ? NULL
1668 : state->author_date,
1669 IDENT_STRICT);
1670
1671 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1672 &commit, author, committer, state->sign_commit,
1673 NULL))
c9e8d960
PT
1674 die(_("failed to write commit object"));
1675
1676 reflog_msg = getenv("GIT_REFLOG_ACTION");
1677 if (!reflog_msg)
1678 reflog_msg = "am";
1679
1680 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1681 state->msg);
1682
ae077771 1683 update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1684 UPDATE_REFS_DIE_ON_ERR);
c9e8d960 1685
13b97ea5
PT
1686 if (state->rebasing) {
1687 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1688
8c88769b 1689 assert(!is_null_oid(&state->orig_commit));
1690 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1691 fprintf(fp, "%s\n", oid_to_hex(&commit));
13b97ea5
PT
1692 fclose(fp);
1693 }
1694
593ffdd8 1695 run_hooks("post-applypatch");
7088f807 1696
c9e8d960
PT
1697 strbuf_release(&sb);
1698}
1699
240bfd2d
PT
1700/**
1701 * Validates the am_state for resuming -- the "msg" and authorship fields must
1702 * be filled up.
1703 */
1704static void validate_resume_state(const struct am_state *state)
1705{
1706 if (!state->msg)
1707 die(_("cannot resume: %s does not exist."),
1708 am_path(state, "final-commit"));
1709
1710 if (!state->author_name || !state->author_email || !state->author_date)
1711 die(_("cannot resume: %s does not exist."),
1712 am_path(state, "author-script"));
1713}
1714
7ff26832
PT
1715/**
1716 * Interactively prompt the user on whether the current patch should be
1717 * applied.
1718 *
1719 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1720 * skip it.
1721 */
1722static int do_interactive(struct am_state *state)
1723{
1724 assert(state->msg);
1725
7ff26832 1726 for (;;) {
97387c8b 1727 char reply[64];
7ff26832
PT
1728
1729 puts(_("Commit Body is:"));
1730 puts("--------------------------");
1731 printf("%s", state->msg);
1732 puts("--------------------------");
1733
1734 /*
1735 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1736 * in your translation. The program will only accept English
1737 * input at this point.
1738 */
97387c8b
JK
1739 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1740 if (!fgets(reply, sizeof(reply), stdin))
1741 die("unable to read from stdin; aborting");
7ff26832 1742
1db65f32 1743 if (*reply == 'y' || *reply == 'Y') {
7ff26832
PT
1744 return 0;
1745 } else if (*reply == 'a' || *reply == 'A') {
1746 state->interactive = 0;
1747 return 0;
1748 } else if (*reply == 'n' || *reply == 'N') {
1749 return 1;
1750 } else if (*reply == 'e' || *reply == 'E') {
1751 struct strbuf msg = STRBUF_INIT;
1752
1753 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1754 free(state->msg);
1755 state->msg = strbuf_detach(&msg, &state->msg_len);
1756 }
1757 strbuf_release(&msg);
1758 } else if (*reply == 'v' || *reply == 'V') {
1759 const char *pager = git_pager(1);
1760 struct child_process cp = CHILD_PROCESS_INIT;
1761
1762 if (!pager)
1763 pager = "cat";
708b8cc9 1764 prepare_pager_args(&cp, pager);
22f9b7f3 1765 strvec_push(&cp.args, am_path(state, "patch"));
7ff26832
PT
1766 run_command(&cp);
1767 }
1768 }
1769}
1770
8c3bd9e2
PT
1771/**
1772 * Applies all queued mail.
8c7b1563
PT
1773 *
1774 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1775 * well as the state directory's "patch" file is used as-is for applying the
1776 * patch and committing it.
8c3bd9e2 1777 */
8c7b1563 1778static void am_run(struct am_state *state, int resume)
8c3bd9e2 1779{
32a5fcbf 1780 struct strbuf sb = STRBUF_INIT;
c9e8d960 1781
33388a71
PT
1782 unlink(am_path(state, "dirtyindex"));
1783
22184497
TG
1784 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0)
1785 die(_("unable to write index file"));
38a824fe 1786
150fe065 1787 if (repo_index_has_changes(the_repository, NULL, &sb)) {
25b763ba 1788 write_state_bool(state, "dirtyindex", 1);
32a5fcbf 1789 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
33388a71 1790 }
32a5fcbf
PT
1791
1792 strbuf_release(&sb);
1793
8c3bd9e2 1794 while (state->cur <= state->last) {
3e20dcf3 1795 const char *mail = am_path(state, msgnum(state));
84f3de28 1796 int apply_status;
7c096b8d 1797 int to_keep;
3e20dcf3 1798
4d9c7e6f
JK
1799 reset_ident_date();
1800
3e20dcf3
PT
1801 if (!file_exists(mail))
1802 goto next;
1803
8c7b1563
PT
1804 if (resume) {
1805 validate_resume_state(state);
8c7b1563 1806 } else {
df2760a5
PT
1807 int skip;
1808
1809 if (state->rebasing)
1810 skip = parse_mail_rebase(state, mail);
1811 else
1812 skip = parse_mail(state, mail);
1813
1814 if (skip)
8c7b1563 1815 goto next; /* mail should be skipped */
3e20dcf3 1816
b7cc7051
GB
1817 if (state->signoff)
1818 am_append_signoff(state);
1819
8c7b1563
PT
1820 write_author_script(state);
1821 write_commit_msg(state);
1822 }
8c3bd9e2 1823
7ff26832
PT
1824 if (state->interactive && do_interactive(state))
1825 goto next;
1826
7c096b8d
A
1827 to_keep = 0;
1828 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1829 switch (state->empty_type) {
1830 case DROP_EMPTY_COMMIT:
1831 say(state, stdout, _("Skipping: %.*s"), linelen(state->msg), state->msg);
1832 goto next;
1833 break;
1834 case KEEP_EMPTY_COMMIT:
1835 to_keep = 1;
1836 say(state, stdout, _("Creating an empty commit: %.*s"),
1837 linelen(state->msg), state->msg);
1838 break;
1839 case STOP_ON_EMPTY_COMMIT:
1840 printf_ln(_("Patch is empty."));
1841 die_user_resolve(state);
1842 break;
1843 }
1844 }
1845
b8803d8f
PT
1846 if (run_applypatch_msg_hook(state))
1847 exit(1);
7c096b8d
A
1848 if (to_keep)
1849 goto commit;
b8803d8f 1850
5d28cf78 1851 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
38a824fe 1852
84f3de28
PT
1853 apply_status = run_apply(state, NULL);
1854
1855 if (apply_status && state->threeway) {
1856 struct strbuf sb = STRBUF_INIT;
1857
1858 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1859 apply_status = fall_back_threeway(state, sb.buf);
1860 strbuf_release(&sb);
1861
1862 /*
1863 * Applying the patch to an earlier tree and merging
1864 * the result may have produced the same tree as ours.
1865 */
e1f8694f 1866 if (!apply_status &&
150fe065 1867 !repo_index_has_changes(the_repository, NULL, NULL)) {
84f3de28
PT
1868 say(state, stdout, _("No changes -- Patch already applied."));
1869 goto next;
1870 }
1871 }
1872
1873 if (apply_status) {
38a824fe
PT
1874 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1875 linelen(state->msg), state->msg);
1876
ed9bff08 1877 if (advice_enabled(ADVICE_AM_WORK_DIR))
aa416b22 1878 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
38a824fe 1879
2d83109a 1880 die_user_resolve(state);
38a824fe
PT
1881 }
1882
7c096b8d 1883commit:
c9e8d960 1884 do_commit(state);
8c3bd9e2 1885
3e20dcf3 1886next:
8c3bd9e2 1887 am_next(state);
852a1710
PT
1888
1889 if (resume)
1890 am_load(state);
1891 resume = 0;
8c3bd9e2
PT
1892 }
1893
e3b1e3bd 1894 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
13b97ea5 1895 assert(state->rebasing);
88b291fe 1896 copy_notes_for_rebase(state);
13b97ea5
PT
1897 run_post_rewrite_hook(state);
1898 }
1899
35bdcc59
PT
1900 /*
1901 * In rebasing mode, it's up to the caller to take care of
1902 * housekeeping.
1903 */
1904 if (!state->rebasing) {
1905 am_destroy(state);
a95ce124 1906 run_auto_maintenance(state->quiet);
35bdcc59 1907 }
8c3bd9e2 1908}
73c2779f 1909
240bfd2d
PT
1910/**
1911 * Resume the current am session after patch application failure. The user did
1912 * all the hard work, and we do not have to do any patch application. Just
9e7e41bf
A
1913 * trust and commit what the user has in the index and working tree. If `allow_empty`
1914 * is true, commit as an empty commit when index has not changed and lacking a patch.
240bfd2d 1915 */
9e7e41bf 1916static void am_resolve(struct am_state *state, int allow_empty)
240bfd2d
PT
1917{
1918 validate_resume_state(state);
1919
5d28cf78 1920 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
240bfd2d 1921
150fe065 1922 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
9e7e41bf
A
1923 if (allow_empty && is_empty_or_missing_file(am_path(state, "patch"))) {
1924 printf_ln(_("No changes - recorded it as an empty commit."));
1925 } else {
1926 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1927 "If there is nothing left to stage, chances are that something else\n"
1928 "already introduced the same changes; you might want to skip this patch."));
1929 die_user_resolve(state);
1930 }
240bfd2d
PT
1931 }
1932
1933 if (unmerged_cache()) {
1934 printf_ln(_("You still have unmerged paths in your index.\n"
6c486862
JNA
1935 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1936 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
2d83109a 1937 die_user_resolve(state);
240bfd2d
PT
1938 }
1939
7ff26832
PT
1940 if (state->interactive) {
1941 write_index_patch(state);
1942 if (do_interactive(state))
1943 goto next;
1944 }
1945
35843b11 1946 repo_rerere(the_repository, 0);
f1cb96d6 1947
240bfd2d
PT
1948 do_commit(state);
1949
7ff26832 1950next:
240bfd2d 1951 am_next(state);
852a1710 1952 am_load(state);
8c7b1563 1953 am_run(state, 0);
240bfd2d
PT
1954}
1955
9990080c
PT
1956/**
1957 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1958 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1959 * failure.
1960 */
1961static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1962{
837e34eb 1963 struct lock_file lock_file = LOCK_INIT;
9990080c
PT
1964 struct unpack_trees_options opts;
1965 struct tree_desc t[2];
1966
1967 if (parse_tree(head) || parse_tree(remote))
1968 return -1;
1969
837e34eb 1970 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
9990080c
PT
1971
1972 refresh_cache(REFRESH_QUIET);
1973
1974 memset(&opts, 0, sizeof(opts));
1975 opts.head_idx = 1;
1976 opts.src_index = &the_index;
1977 opts.dst_index = &the_index;
1978 opts.update = 1;
1979 opts.merge = 1;
480d3d6b
EN
1980 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
1981 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
9990080c
PT
1982 opts.fn = twoway_merge;
1983 init_tree_desc(&t[0], head->buffer, head->size);
1984 init_tree_desc(&t[1], remote->buffer, remote->size);
1985
1986 if (unpack_trees(2, t, &opts)) {
837e34eb 1987 rollback_lock_file(&lock_file);
9990080c
PT
1988 return -1;
1989 }
1990
837e34eb 1991 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
9990080c
PT
1992 die(_("unable to write new index file"));
1993
1994 return 0;
1995}
1996
3ecc7040
PT
1997/**
1998 * Merges a tree into the index. The index's stat info will take precedence
1999 * over the merged tree's. Returns 0 on success, -1 on failure.
2000 */
2001static int merge_tree(struct tree *tree)
2002{
837e34eb 2003 struct lock_file lock_file = LOCK_INIT;
3ecc7040
PT
2004 struct unpack_trees_options opts;
2005 struct tree_desc t[1];
2006
2007 if (parse_tree(tree))
2008 return -1;
2009
837e34eb 2010 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
3ecc7040
PT
2011
2012 memset(&opts, 0, sizeof(opts));
2013 opts.head_idx = 1;
2014 opts.src_index = &the_index;
2015 opts.dst_index = &the_index;
2016 opts.merge = 1;
2017 opts.fn = oneway_merge;
2018 init_tree_desc(&t[0], tree->buffer, tree->size);
2019
2020 if (unpack_trees(1, t, &opts)) {
837e34eb 2021 rollback_lock_file(&lock_file);
3ecc7040
PT
2022 return -1;
2023 }
2024
837e34eb 2025 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
3ecc7040
PT
2026 die(_("unable to write new index file"));
2027
2028 return 0;
2029}
2030
9990080c
PT
2031/**
2032 * Clean the index without touching entries that are not modified between
2033 * `head` and `remote`.
2034 */
8c88769b 2035static int clean_index(const struct object_id *head, const struct object_id *remote)
9990080c 2036{
9990080c 2037 struct tree *head_tree, *remote_tree, *index_tree;
8c88769b 2038 struct object_id index;
9990080c 2039
a9dbc179 2040 head_tree = parse_tree_indirect(head);
9990080c 2041 if (!head_tree)
8c88769b 2042 return error(_("Could not parse object '%s'."), oid_to_hex(head));
9990080c 2043
a9dbc179 2044 remote_tree = parse_tree_indirect(remote);
9990080c 2045 if (!remote_tree)
8c88769b 2046 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
9990080c
PT
2047
2048 read_cache_unmerged();
2049
2050 if (fast_forward_to(head_tree, head_tree, 1))
2051 return -1;
2052
fc5cb99f 2053 if (write_cache_as_tree(&index, 0, NULL))
9990080c
PT
2054 return -1;
2055
a9dbc179 2056 index_tree = parse_tree_indirect(&index);
9990080c 2057 if (!index_tree)
8c88769b 2058 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
9990080c
PT
2059
2060 if (fast_forward_to(index_tree, remote_tree, 0))
2061 return -1;
2062
3ecc7040 2063 if (merge_tree(remote_tree))
9990080c 2064 return -1;
9990080c 2065
f4a4b9ac 2066 remove_branch_state(the_repository, 0);
9990080c
PT
2067
2068 return 0;
2069}
2070
f1cb96d6
PT
2071/**
2072 * Resets rerere's merge resolution metadata.
2073 */
2074static void am_rerere_clear(void)
2075{
2076 struct string_list merge_rr = STRING_LIST_INIT_DUP;
55e6b354 2077 rerere_clear(the_repository, &merge_rr);
f1cb96d6
PT
2078 string_list_clear(&merge_rr, 1);
2079}
2080
9990080c
PT
2081/**
2082 * Resume the current am session by skipping the current patch.
2083 */
2084static void am_skip(struct am_state *state)
2085{
8c88769b 2086 struct object_id head;
9990080c 2087
f1cb96d6
PT
2088 am_rerere_clear();
2089
8c88769b 2090 if (get_oid("HEAD", &head))
d41836a0 2091 oidcpy(&head, the_hash_algo->empty_tree);
9990080c 2092
8c88769b 2093 if (clean_index(&head, &head))
9990080c
PT
2094 die(_("failed to clean index"));
2095
45339f74
EN
2096 if (state->rebasing) {
2097 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2098
2099 assert(!is_null_oid(&state->orig_commit));
2100 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2101 fprintf(fp, "%s\n", oid_to_hex(&head));
2102 fclose(fp);
2103 }
2104
9990080c 2105 am_next(state);
852a1710 2106 am_load(state);
9990080c
PT
2107 am_run(state, 0);
2108}
2109
33388a71
PT
2110/**
2111 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2112 *
2113 * It is not safe to reset HEAD when:
2114 * 1. git-am previously failed because the index was dirty.
2115 * 2. HEAD has moved since git-am previously failed.
2116 */
2117static int safe_to_abort(const struct am_state *state)
2118{
2119 struct strbuf sb = STRBUF_INIT;
8c88769b 2120 struct object_id abort_safety, head;
33388a71
PT
2121
2122 if (file_exists(am_path(state, "dirtyindex")))
2123 return 0;
2124
2125 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
8c88769b 2126 if (get_oid_hex(sb.buf, &abort_safety))
ccd71b2f 2127 die(_("could not parse %s"), am_path(state, "abort-safety"));
33388a71 2128 } else
8c88769b 2129 oidclr(&abort_safety);
28ac7aa7 2130 strbuf_release(&sb);
33388a71 2131
8c88769b 2132 if (get_oid("HEAD", &head))
2133 oidclr(&head);
33388a71 2134
4a7e27e9 2135 if (oideq(&head, &abort_safety))
33388a71
PT
2136 return 1;
2137
1868331f 2138 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
33388a71
PT
2139 "Not rewinding to ORIG_HEAD"));
2140
2141 return 0;
2142}
2143
2144/**
2145 * Aborts the current am session if it is safe to do so.
2146 */
2147static void am_abort(struct am_state *state)
2148{
8c88769b 2149 struct object_id curr_head, orig_head;
33388a71
PT
2150 int has_curr_head, has_orig_head;
2151 char *curr_branch;
2152
2153 if (!safe_to_abort(state)) {
2154 am_destroy(state);
2155 return;
2156 }
2157
f1cb96d6
PT
2158 am_rerere_clear();
2159
0f2dc722 2160 curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
57e0ef0e 2161 has_curr_head = curr_branch && !is_null_oid(&curr_head);
33388a71 2162 if (!has_curr_head)
d41836a0 2163 oidcpy(&curr_head, the_hash_algo->empty_tree);
33388a71 2164
8c88769b 2165 has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
33388a71 2166 if (!has_orig_head)
d41836a0 2167 oidcpy(&orig_head, the_hash_algo->empty_tree);
33388a71 2168
c5ead19e
EN
2169 if (clean_index(&curr_head, &orig_head))
2170 die(_("failed to clean index"));
33388a71
PT
2171
2172 if (has_orig_head)
ae077771 2173 update_ref("am --abort", "HEAD", &orig_head,
2174 has_curr_head ? &curr_head : NULL, 0,
2175 UPDATE_REFS_DIE_ON_ERR);
33388a71 2176 else if (curr_branch)
91774afc 2177 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
33388a71
PT
2178
2179 free(curr_branch);
2180 am_destroy(state);
2181}
2182
f3b48228 2183static int show_patch(struct am_state *state, enum show_patch_type sub_mode)
984913a2
NTND
2184{
2185 struct strbuf sb = STRBUF_INIT;
2186 const char *patch_path;
2187 int len;
2188
66335298
NTND
2189 if (!is_null_oid(&state->orig_commit)) {
2190 const char *av[4] = { "show", NULL, "--", NULL };
2191 char *new_oid_str;
2192 int ret;
2193
2194 av[1] = new_oid_str = xstrdup(oid_to_hex(&state->orig_commit));
2195 ret = run_command_v_opt(av, RUN_GIT_CMD);
2196 free(new_oid_str);
2197 return ret;
2198 }
2199
f3b48228
PB
2200 switch (sub_mode) {
2201 case SHOW_PATCH_RAW:
2202 patch_path = am_path(state, msgnum(state));
2203 break;
aa416b22
PB
2204 case SHOW_PATCH_DIFF:
2205 patch_path = am_path(state, "patch");
2206 break;
f3b48228
PB
2207 default:
2208 BUG("invalid mode for --show-current-patch");
2209 }
2210
984913a2
NTND
2211 len = strbuf_read_file(&sb, patch_path, 0);
2212 if (len < 0)
2213 die_errno(_("failed to read '%s'"), patch_path);
2214
2215 setup_pager();
2216 write_in_full(1, sb.buf, sb.len);
2217 strbuf_release(&sb);
2218 return 0;
2219}
2220
11c2177f
PT
2221/**
2222 * parse_options() callback that validates and sets opt->value to the
2223 * PATCH_FORMAT_* enum value corresponding to `arg`.
2224 */
2225static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2226{
2227 int *opt_value = opt->value;
2228
fce56648
JK
2229 if (unset)
2230 *opt_value = PATCH_FORMAT_UNKNOWN;
2231 else if (!strcmp(arg, "mbox"))
11c2177f 2232 *opt_value = PATCH_FORMAT_MBOX;
5ae41c79
PT
2233 else if (!strcmp(arg, "stgit"))
2234 *opt_value = PATCH_FORMAT_STGIT;
336108c1
PT
2235 else if (!strcmp(arg, "stgit-series"))
2236 *opt_value = PATCH_FORMAT_STGIT_SERIES;
94cd175c
PT
2237 else if (!strcmp(arg, "hg"))
2238 *opt_value = PATCH_FORMAT_HG;
d9925d1a
EW
2239 else if (!strcmp(arg, "mboxrd"))
2240 *opt_value = PATCH_FORMAT_MBOXRD;
5a59a230
NTND
2241 /*
2242 * Please update $__git_patchformat in git-completion.bash
2243 * when you add new options
2244 */
11c2177f 2245 else
1a8aea85
JNA
2246 return error(_("invalid value for '%s': '%s'"),
2247 "--patch-format", arg);
11c2177f
PT
2248 return 0;
2249}
2250
e8ef1e8d 2251enum resume_type {
240bfd2d 2252 RESUME_FALSE = 0,
8c7b1563 2253 RESUME_APPLY,
9990080c 2254 RESUME_RESOLVED,
33388a71 2255 RESUME_SKIP,
65ed8ff3 2256 RESUME_ABORT,
9ca488c0 2257 RESUME_QUIT,
9e7e41bf
A
2258 RESUME_SHOW_PATCH,
2259 RESUME_ALLOW_EMPTY,
240bfd2d
PT
2260};
2261
e8ef1e8d
PB
2262struct resume_mode {
2263 enum resume_type mode;
f3b48228 2264 enum show_patch_type sub_mode;
e8ef1e8d
PB
2265};
2266
f3b48228
PB
2267static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2268{
2269 int *opt_value = opt->value;
2270 struct resume_mode *resume = container_of(opt_value, struct resume_mode, mode);
2271
2272 /*
2273 * Please update $__git_showcurrentpatch in git-completion.bash
2274 * when you add new options
2275 */
2276 const char *valid_modes[] = {
aa416b22 2277 [SHOW_PATCH_DIFF] = "diff",
f3b48228
PB
2278 [SHOW_PATCH_RAW] = "raw"
2279 };
2280 int new_value = SHOW_PATCH_RAW;
2281
8d2aa8df
JK
2282 BUG_ON_OPT_NEG(unset);
2283
f3b48228
PB
2284 if (arg) {
2285 for (new_value = 0; new_value < ARRAY_SIZE(valid_modes); new_value++) {
2286 if (!strcmp(arg, valid_modes[new_value]))
2287 break;
2288 }
2289 if (new_value >= ARRAY_SIZE(valid_modes))
1a8aea85
JNA
2290 return error(_("invalid value for '%s': '%s'"),
2291 "--show-current-patch", arg);
f3b48228
PB
2292 }
2293
2294 if (resume->mode == RESUME_SHOW_PATCH && new_value != resume->sub_mode)
246cac85
JNA
2295 return error(_("options '%s=%s' and '%s=%s' "
2296 "cannot be used together"),
2297 "--show-current-patch", "--show-current-patch", arg, valid_modes[resume->sub_mode]);
f3b48228
PB
2298
2299 resume->mode = RESUME_SHOW_PATCH;
2300 resume->sub_mode = new_value;
2301 return 0;
2302}
2303
5cf88fd8 2304static int git_am_config(const char *k, const char *v, void *cb UNUSED)
434c64df
RMM
2305{
2306 int status;
2307
2308 status = git_gpg_config(k, v, NULL);
2309 if (status)
2310 return status;
2311
2312 return git_default_config(k, v, NULL);
2313}
2314
73c2779f
PT
2315int cmd_am(int argc, const char **argv, const char *prefix)
2316{
8c3bd9e2 2317 struct am_state state;
c2676cde 2318 int binary = -1;
5d123a40 2319 int keep_cr = -1;
11c2177f 2320 int patch_format = PATCH_FORMAT_UNKNOWN;
e8ef1e8d 2321 struct resume_mode resume = { .mode = RESUME_FALSE };
852a1710 2322 int in_progress;
984913a2 2323 int ret = 0;
8c3bd9e2
PT
2324
2325 const char * const usage[] = {
d65fdc9c 2326 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
d96a0313 2327 N_("git am [<options>] (--continue | --skip | --abort)"),
8c3bd9e2
PT
2328 NULL
2329 };
2330
2331 struct option options[] = {
7ff26832
PT
2332 OPT_BOOL('i', "interactive", &state.interactive,
2333 N_("run interactively")),
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")),
3e4a67b4
NTND
2350 OPT_SET_INT_F(0, "keep-cr", &keep_cr,
2351 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2352 1, PARSE_OPT_NONEG),
2353 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr,
2354 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2355 0, PARSE_OPT_NONEG),
9b646617
PT
2356 OPT_BOOL('c', "scissors", &state.scissors,
2357 N_("strip everything before a scissors line")),
59b519ab
ĐTCD
2358 OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2359 N_("pass it through git-mailinfo"),
2360 PARSE_OPT_NONEG, am_option_parse_quoted_cr),
257e8cec
PT
2361 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2362 N_("pass it through git-apply"),
2363 0),
2364 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2365 N_("pass it through git-apply"),
2366 PARSE_OPT_NOARG),
2367 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2368 N_("pass it through git-apply"),
2369 PARSE_OPT_NOARG),
2370 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2371 N_("pass it through git-apply"),
2372 0),
2373 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2374 N_("pass it through git-apply"),
2375 0),
2376 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2377 N_("pass it through git-apply"),
2378 0),
2379 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2380 N_("pass it through git-apply"),
2381 0),
2382 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2383 N_("pass it through git-apply"),
2384 0),
11c2177f
PT
2385 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2386 N_("format the patch(es) are in"),
2387 parse_opt_patchformat),
257e8cec
PT
2388 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2389 N_("pass it through git-apply"),
2390 PARSE_OPT_NOARG),
2d83109a
PT
2391 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2392 N_("override error message when patch failure occurs")),
e8ef1e8d 2393 OPT_CMDMODE(0, "continue", &resume.mode,
240bfd2d
PT
2394 N_("continue applying patches after resolving a conflict"),
2395 RESUME_RESOLVED),
e8ef1e8d 2396 OPT_CMDMODE('r', "resolved", &resume.mode,
240bfd2d
PT
2397 N_("synonyms for --continue"),
2398 RESUME_RESOLVED),
e8ef1e8d 2399 OPT_CMDMODE(0, "skip", &resume.mode,
9990080c
PT
2400 N_("skip the current patch"),
2401 RESUME_SKIP),
e8ef1e8d 2402 OPT_CMDMODE(0, "abort", &resume.mode,
e73fe3dd 2403 N_("restore the original branch and abort the patching operation"),
33388a71 2404 RESUME_ABORT),
e8ef1e8d 2405 OPT_CMDMODE(0, "quit", &resume.mode,
e73fe3dd 2406 N_("abort the patching operation but keep HEAD where it is"),
65ed8ff3 2407 RESUME_QUIT),
f3b48228 2408 { OPTION_CALLBACK, 0, "show-current-patch", &resume.mode,
aa416b22 2409 "(diff|raw)",
f3b48228
PB
2410 N_("show the patch being applied"),
2411 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2412 parse_opt_show_current_patch, RESUME_SHOW_PATCH },
9e7e41bf
A
2413 OPT_CMDMODE(0, "allow-empty", &resume.mode,
2414 N_("record the empty patch as an empty commit"),
2415 RESUME_ALLOW_EMPTY),
0cd4bcba
PT
2416 OPT_BOOL(0, "committer-date-is-author-date",
2417 &state.committer_date_is_author_date,
2418 N_("lie about committer date")),
f07adb62
PT
2419 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2420 N_("use current timestamp for author date")),
f1cb96d6 2421 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
7e35dacb
PT
2422 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2423 N_("GPG-sign commits"),
2424 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
7c096b8d
A
2425 OPT_CALLBACK_F(STOP_ON_EMPTY_COMMIT, "empty", &state.empty_type, "{stop,drop,keep}",
2426 N_("how to handle empty patches"),
2427 PARSE_OPT_NONEG, am_option_parse_empty),
35bdcc59
PT
2428 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2429 N_("(internal use for git-rebase)")),
8c3bd9e2
PT
2430 OPT_END()
2431 };
73c2779f 2432
f3a2fffe
JK
2433 if (argc == 2 && !strcmp(argv[1], "-h"))
2434 usage_with_options(usage, options);
2435
434c64df 2436 git_config(git_am_config, NULL);
8c3bd9e2 2437
16d2676c 2438 am_state_init(&state);
8c3bd9e2 2439
852a1710
PT
2440 in_progress = am_in_progress(&state);
2441 if (in_progress)
2442 am_load(&state);
2443
8c3bd9e2
PT
2444 argc = parse_options(argc, argv, prefix, options, usage, 0);
2445
c2676cde
PT
2446 if (binary >= 0)
2447 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2448 "it will be removed. Please do not use it anymore."));
2449
5e4f9cff
PT
2450 /* Ensure a valid committer ident can be constructed */
2451 git_committer_info(IDENT_STRICT);
2452
e1ff0a32 2453 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
38a824fe
PT
2454 die(_("failed to read the index"));
2455
852a1710 2456 if (in_progress) {
8d185503
PT
2457 /*
2458 * Catch user error to feed us patches when there is a session
2459 * in progress:
2460 *
2461 * 1. mbox path(s) are provided on the command-line.
2462 * 2. stdin is not a tty: the user is trying to feed us a patch
2463 * from standard input. This is somewhat unreliable -- stdin
2464 * could be /dev/null for example and the caller did not
2465 * intend to feed us a patch but wanted to continue
2466 * unattended.
2467 */
e8ef1e8d 2468 if (argc || (resume.mode == RESUME_FALSE && !isatty(0)))
8d185503
PT
2469 die(_("previous rebase directory %s still exists but mbox given."),
2470 state.dir);
2471
e8ef1e8d
PB
2472 if (resume.mode == RESUME_FALSE)
2473 resume.mode = RESUME_APPLY;
b5e82359
PT
2474
2475 if (state.signoff == SIGNOFF_EXPLICIT)
2476 am_append_signoff(&state);
8c7b1563 2477 } else {
22f9b7f3 2478 struct strvec paths = STRVEC_INIT;
11c2177f
PT
2479 int i;
2480
6d42ac29
PT
2481 /*
2482 * Handle stray state directory in the independent-run case. In
2483 * the --rebasing case, it is up to the caller to take care of
2484 * stray directories.
2485 */
2486 if (file_exists(state.dir) && !state.rebasing) {
e8ef1e8d 2487 if (resume.mode == RESUME_ABORT || resume.mode == RESUME_QUIT) {
6d42ac29
PT
2488 am_destroy(&state);
2489 am_state_release(&state);
2490 return 0;
2491 }
2492
2493 die(_("Stray %s directory found.\n"
2494 "Use \"git am --abort\" to remove it."),
2495 state.dir);
2496 }
2497
e8ef1e8d 2498 if (resume.mode)
240bfd2d
PT
2499 die(_("Resolve operation not in progress, we are not resuming."));
2500
11c2177f
PT
2501 for (i = 0; i < argc; i++) {
2502 if (is_absolute_path(argv[i]) || !prefix)
22f9b7f3 2503 strvec_push(&paths, argv[i]);
11c2177f 2504 else
22f9b7f3 2505 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
11c2177f
PT
2506 }
2507
d70a9eb6 2508 if (state.interactive && !paths.nr)
6e7baf24
JK
2509 die(_("interactive mode requires patches on the command line"));
2510
d70a9eb6 2511 am_setup(&state, patch_format, paths.v, keep_cr);
11c2177f 2512
22f9b7f3 2513 strvec_clear(&paths);
11c2177f 2514 }
8c3bd9e2 2515
e8ef1e8d 2516 switch (resume.mode) {
240bfd2d 2517 case RESUME_FALSE:
8c7b1563
PT
2518 am_run(&state, 0);
2519 break;
2520 case RESUME_APPLY:
2521 am_run(&state, 1);
240bfd2d
PT
2522 break;
2523 case RESUME_RESOLVED:
9e7e41bf
A
2524 case RESUME_ALLOW_EMPTY:
2525 am_resolve(&state, resume.mode == RESUME_ALLOW_EMPTY ? 1 : 0);
240bfd2d 2526 break;
9990080c
PT
2527 case RESUME_SKIP:
2528 am_skip(&state);
2529 break;
33388a71
PT
2530 case RESUME_ABORT:
2531 am_abort(&state);
2532 break;
65ed8ff3
NTND
2533 case RESUME_QUIT:
2534 am_rerere_clear();
2535 am_destroy(&state);
2536 break;
984913a2 2537 case RESUME_SHOW_PATCH:
f3b48228 2538 ret = show_patch(&state, resume.sub_mode);
984913a2 2539 break;
240bfd2d 2540 default:
033abf97 2541 BUG("invalid resume value");
240bfd2d 2542 }
8c3bd9e2
PT
2543
2544 am_state_release(&state);
2545
984913a2 2546 return ret;
73c2779f 2547}