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