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