builtin-am: rerere support
[git/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 */
6#include "cache.h"
7#include "builtin.h"
8#include "exec_cmd.h"
8c3bd9e2
PT
9#include "parse-options.h"
10#include "dir.h"
11c2177f 11#include "run-command.h"
3e20dcf3 12#include "quote.h"
38a824fe 13#include "lockfile.h"
c9e8d960
PT
14#include "cache-tree.h"
15#include "refs.h"
16#include "commit.h"
32a5fcbf
PT
17#include "diff.h"
18#include "diffcore.h"
9990080c
PT
19#include "unpack-trees.h"
20#include "branch.h"
eb898b83 21#include "sequencer.h"
84f3de28
PT
22#include "revision.h"
23#include "merge-recursive.h"
df2760a5
PT
24#include "revision.h"
25#include "log-tree.h"
88b291fe 26#include "notes-utils.h"
f1cb96d6 27#include "rerere.h"
3e20dcf3
PT
28
29/**
30 * Returns 1 if the file is empty or does not exist, 0 otherwise.
31 */
32static int is_empty_file(const char *filename)
33{
34 struct stat st;
35
36 if (stat(filename, &st) < 0) {
37 if (errno == ENOENT)
38 return 1;
39 die_errno(_("could not stat %s"), filename);
40 }
41
42 return !st.st_size;
43}
11c2177f 44
c29807b2
PT
45/**
46 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators.
47 */
48static int strbuf_getline_crlf(struct strbuf *sb, FILE *fp)
49{
50 if (strbuf_getwholeline(sb, fp, '\n'))
51 return EOF;
52 if (sb->buf[sb->len - 1] == '\n') {
53 strbuf_setlen(sb, sb->len - 1);
54 if (sb->len > 0 && sb->buf[sb->len - 1] == '\r')
55 strbuf_setlen(sb, sb->len - 1);
56 }
57 return 0;
58}
59
38a824fe
PT
60/**
61 * Returns the length of the first line of msg.
62 */
63static int linelen(const char *msg)
64{
65 return strchrnul(msg, '\n') - msg;
66}
67
11c2177f
PT
68enum patch_format {
69 PATCH_FORMAT_UNKNOWN = 0,
70 PATCH_FORMAT_MBOX
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
8c3bd9e2
PT
85struct am_state {
86 /* state directory path */
87 char *dir;
88
89 /* current and last patch numbers, 1-indexed */
90 int cur;
91 int last;
11c2177f 92
3e20dcf3
PT
93 /* commit metadata and message */
94 char *author_name;
95 char *author_email;
96 char *author_date;
97 char *msg;
98 size_t msg_len;
99
13b97ea5
PT
100 /* when --rebasing, records the original commit the patch came from */
101 unsigned char orig_commit[GIT_SHA1_RAWSZ];
102
11c2177f
PT
103 /* number of digits in patch filename */
104 int prec;
5d28cf78
PT
105
106 /* various operating modes and command line options */
84f3de28 107 int threeway;
5d28cf78 108 int quiet;
eb898b83 109 int signoff;
ef7ee16d 110 int utf8;
4f1b6961 111 int keep; /* enum keep_type */
702cbaad 112 int message_id;
9b646617 113 int scissors; /* enum scissors_type */
257e8cec 114 struct argv_array git_apply_opts;
2d83109a 115 const char *resolvemsg;
0cd4bcba 116 int committer_date_is_author_date;
f07adb62 117 int ignore_date;
f1cb96d6 118 int allow_rerere_autoupdate;
7e35dacb 119 const char *sign_commit;
35bdcc59 120 int rebasing;
8c3bd9e2
PT
121};
122
123/**
124 * Initializes am_state with the default values. The state directory is set to
125 * dir.
126 */
127static void am_state_init(struct am_state *state, const char *dir)
128{
7e35dacb
PT
129 int gpgsign;
130
8c3bd9e2
PT
131 memset(state, 0, sizeof(*state));
132
133 assert(dir);
134 state->dir = xstrdup(dir);
11c2177f
PT
135
136 state->prec = 4;
ef7ee16d
PT
137
138 state->utf8 = 1;
702cbaad
PT
139
140 git_config_get_bool("am.messageid", &state->message_id);
9b646617
PT
141
142 state->scissors = SCISSORS_UNSET;
257e8cec
PT
143
144 argv_array_init(&state->git_apply_opts);
7e35dacb
PT
145
146 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
147 state->sign_commit = gpgsign ? "" : NULL;
8c3bd9e2
PT
148}
149
150/**
151 * Releases memory allocated by an am_state.
152 */
153static void am_state_release(struct am_state *state)
154{
155 free(state->dir);
3e20dcf3
PT
156 free(state->author_name);
157 free(state->author_email);
158 free(state->author_date);
159 free(state->msg);
257e8cec 160 argv_array_clear(&state->git_apply_opts);
8c3bd9e2
PT
161}
162
163/**
164 * Returns path relative to the am_state directory.
165 */
166static inline const char *am_path(const struct am_state *state, const char *path)
167{
168 return mkpath("%s/%s", state->dir, path);
169}
170
5d28cf78
PT
171/**
172 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
173 * at the end.
174 */
175static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
176{
177 va_list ap;
178
179 va_start(ap, fmt);
180 if (!state->quiet) {
181 vfprintf(fp, fmt, ap);
182 putc('\n', fp);
183 }
184 va_end(ap);
185}
186
8c3bd9e2
PT
187/**
188 * Returns 1 if there is an am session in progress, 0 otherwise.
189 */
190static int am_in_progress(const struct am_state *state)
191{
192 struct stat st;
193
194 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
195 return 0;
196 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
197 return 0;
198 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
199 return 0;
200 return 1;
201}
202
203/**
204 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
205 * number of bytes read on success, -1 if the file does not exist. If `trim` is
206 * set, trailing whitespace will be removed.
207 */
208static int read_state_file(struct strbuf *sb, const struct am_state *state,
209 const char *file, int trim)
210{
211 strbuf_reset(sb);
212
213 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
214 if (trim)
215 strbuf_trim(sb);
216
217 return sb->len;
218 }
219
220 if (errno == ENOENT)
221 return -1;
222
223 die_errno(_("could not read '%s'"), am_path(state, file));
224}
225
3e20dcf3
PT
226/**
227 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE
228 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must
229 * match `key`. Returns NULL on failure.
230 *
231 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from
232 * the author-script.
233 */
234static char *read_shell_var(FILE *fp, const char *key)
235{
236 struct strbuf sb = STRBUF_INIT;
237 const char *str;
238
239 if (strbuf_getline(&sb, fp, '\n'))
240 goto fail;
241
242 if (!skip_prefix(sb.buf, key, &str))
243 goto fail;
244
245 if (!skip_prefix(str, "=", &str))
246 goto fail;
247
248 strbuf_remove(&sb, 0, str - sb.buf);
249
250 str = sq_dequote(sb.buf);
251 if (!str)
252 goto fail;
253
254 return strbuf_detach(&sb, NULL);
255
256fail:
257 strbuf_release(&sb);
258 return NULL;
259}
260
261/**
262 * Reads and parses the state directory's "author-script" file, and sets
263 * state->author_name, state->author_email and state->author_date accordingly.
264 * Returns 0 on success, -1 if the file could not be parsed.
265 *
266 * The author script is of the format:
267 *
268 * GIT_AUTHOR_NAME='$author_name'
269 * GIT_AUTHOR_EMAIL='$author_email'
270 * GIT_AUTHOR_DATE='$author_date'
271 *
272 * where $author_name, $author_email and $author_date are quoted. We are strict
273 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
274 * script, and thus if the file differs from what this function expects, it is
275 * better to bail out than to do something that the user does not expect.
276 */
277static int read_author_script(struct am_state *state)
278{
279 const char *filename = am_path(state, "author-script");
280 FILE *fp;
281
282 assert(!state->author_name);
283 assert(!state->author_email);
284 assert(!state->author_date);
285
286 fp = fopen(filename, "r");
287 if (!fp) {
288 if (errno == ENOENT)
289 return 0;
290 die_errno(_("could not open '%s' for reading"), filename);
291 }
292
293 state->author_name = read_shell_var(fp, "GIT_AUTHOR_NAME");
294 if (!state->author_name) {
295 fclose(fp);
296 return -1;
297 }
298
299 state->author_email = read_shell_var(fp, "GIT_AUTHOR_EMAIL");
300 if (!state->author_email) {
301 fclose(fp);
302 return -1;
303 }
304
305 state->author_date = read_shell_var(fp, "GIT_AUTHOR_DATE");
306 if (!state->author_date) {
307 fclose(fp);
308 return -1;
309 }
310
311 if (fgetc(fp) != EOF) {
312 fclose(fp);
313 return -1;
314 }
315
316 fclose(fp);
317 return 0;
318}
319
320/**
321 * Saves state->author_name, state->author_email and state->author_date in the
322 * state directory's "author-script" file.
323 */
324static void write_author_script(const struct am_state *state)
325{
326 struct strbuf sb = STRBUF_INIT;
327
328 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
329 sq_quote_buf(&sb, state->author_name);
330 strbuf_addch(&sb, '\n');
331
332 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
333 sq_quote_buf(&sb, state->author_email);
334 strbuf_addch(&sb, '\n');
335
336 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
337 sq_quote_buf(&sb, state->author_date);
338 strbuf_addch(&sb, '\n');
339
340 write_file(am_path(state, "author-script"), 1, "%s", sb.buf);
341
342 strbuf_release(&sb);
343}
344
345/**
346 * Reads the commit message from the state directory's "final-commit" file,
347 * setting state->msg to its contents and state->msg_len to the length of its
348 * contents in bytes.
349 *
350 * Returns 0 on success, -1 if the file does not exist.
351 */
352static int read_commit_msg(struct am_state *state)
353{
354 struct strbuf sb = STRBUF_INIT;
355
356 assert(!state->msg);
357
358 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
359 strbuf_release(&sb);
360 return -1;
361 }
362
363 state->msg = strbuf_detach(&sb, &state->msg_len);
364 return 0;
365}
366
367/**
368 * Saves state->msg in the state directory's "final-commit" file.
369 */
370static void write_commit_msg(const struct am_state *state)
371{
372 int fd;
373 const char *filename = am_path(state, "final-commit");
374
375 fd = xopen(filename, O_WRONLY | O_CREAT, 0666);
376 if (write_in_full(fd, state->msg, state->msg_len) < 0)
377 die_errno(_("could not write to %s"), filename);
378 close(fd);
379}
380
8c3bd9e2
PT
381/**
382 * Loads state from disk.
383 */
384static void am_load(struct am_state *state)
385{
386 struct strbuf sb = STRBUF_INIT;
387
388 if (read_state_file(&sb, state, "next", 1) < 0)
389 die("BUG: state file 'next' does not exist");
390 state->cur = strtol(sb.buf, NULL, 10);
391
392 if (read_state_file(&sb, state, "last", 1) < 0)
393 die("BUG: state file 'last' does not exist");
394 state->last = strtol(sb.buf, NULL, 10);
395
3e20dcf3
PT
396 if (read_author_script(state) < 0)
397 die(_("could not parse author script"));
398
399 read_commit_msg(state);
400
13b97ea5
PT
401 if (read_state_file(&sb, state, "original-commit", 1) < 0)
402 hashclr(state->orig_commit);
403 else if (get_sha1_hex(sb.buf, state->orig_commit) < 0)
404 die(_("could not parse %s"), am_path(state, "original-commit"));
405
84f3de28
PT
406 read_state_file(&sb, state, "threeway", 1);
407 state->threeway = !strcmp(sb.buf, "t");
408
5d28cf78
PT
409 read_state_file(&sb, state, "quiet", 1);
410 state->quiet = !strcmp(sb.buf, "t");
411
eb898b83
PT
412 read_state_file(&sb, state, "sign", 1);
413 state->signoff = !strcmp(sb.buf, "t");
414
ef7ee16d
PT
415 read_state_file(&sb, state, "utf8", 1);
416 state->utf8 = !strcmp(sb.buf, "t");
417
4f1b6961
PT
418 read_state_file(&sb, state, "keep", 1);
419 if (!strcmp(sb.buf, "t"))
420 state->keep = KEEP_TRUE;
421 else if (!strcmp(sb.buf, "b"))
422 state->keep = KEEP_NON_PATCH;
423 else
424 state->keep = KEEP_FALSE;
425
702cbaad
PT
426 read_state_file(&sb, state, "messageid", 1);
427 state->message_id = !strcmp(sb.buf, "t");
428
9b646617
PT
429 read_state_file(&sb, state, "scissors", 1);
430 if (!strcmp(sb.buf, "t"))
431 state->scissors = SCISSORS_TRUE;
432 else if (!strcmp(sb.buf, "f"))
433 state->scissors = SCISSORS_FALSE;
434 else
435 state->scissors = SCISSORS_UNSET;
436
257e8cec
PT
437 read_state_file(&sb, state, "apply-opt", 1);
438 argv_array_clear(&state->git_apply_opts);
439 if (sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) < 0)
440 die(_("could not parse %s"), am_path(state, "apply-opt"));
441
35bdcc59
PT
442 state->rebasing = !!file_exists(am_path(state, "rebasing"));
443
8c3bd9e2
PT
444 strbuf_release(&sb);
445}
446
447/**
448 * Removes the am_state directory, forcefully terminating the current am
449 * session.
450 */
451static void am_destroy(const struct am_state *state)
452{
453 struct strbuf sb = STRBUF_INIT;
454
455 strbuf_addstr(&sb, state->dir);
456 remove_dir_recursively(&sb, 0);
457 strbuf_release(&sb);
458}
459
b8803d8f
PT
460/**
461 * Runs applypatch-msg hook. Returns its exit code.
462 */
463static int run_applypatch_msg_hook(struct am_state *state)
464{
465 int ret;
466
467 assert(state->msg);
468 ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
469
470 if (!ret) {
471 free(state->msg);
472 state->msg = NULL;
473 if (read_commit_msg(state) < 0)
474 die(_("'%s' was deleted by the applypatch-msg hook"),
475 am_path(state, "final-commit"));
476 }
477
478 return ret;
479}
480
13b97ea5
PT
481/**
482 * Runs post-rewrite hook. Returns it exit code.
483 */
484static int run_post_rewrite_hook(const struct am_state *state)
485{
486 struct child_process cp = CHILD_PROCESS_INIT;
487 const char *hook = find_hook("post-rewrite");
488 int ret;
489
490 if (!hook)
491 return 0;
492
493 argv_array_push(&cp.args, hook);
494 argv_array_push(&cp.args, "rebase");
495
496 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
497 cp.stdout_to_stderr = 1;
498
499 ret = run_command(&cp);
500
501 close(cp.in);
502 return ret;
503}
504
88b291fe
PT
505/**
506 * Reads the state directory's "rewritten" file, and copies notes from the old
507 * commits listed in the file to their rewritten commits.
508 *
509 * Returns 0 on success, -1 on failure.
510 */
511static int copy_notes_for_rebase(const struct am_state *state)
512{
513 struct notes_rewrite_cfg *c;
514 struct strbuf sb = STRBUF_INIT;
515 const char *invalid_line = _("Malformed input line: '%s'.");
516 const char *msg = "Notes added by 'git rebase'";
517 FILE *fp;
518 int ret = 0;
519
520 assert(state->rebasing);
521
522 c = init_copy_notes_for_rewrite("rebase");
523 if (!c)
524 return 0;
525
526 fp = xfopen(am_path(state, "rewritten"), "r");
527
528 while (!strbuf_getline(&sb, fp, '\n')) {
529 unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ];
530
531 if (sb.len != GIT_SHA1_HEXSZ * 2 + 1) {
532 ret = error(invalid_line, sb.buf);
533 goto finish;
534 }
535
536 if (get_sha1_hex(sb.buf, from_obj)) {
537 ret = error(invalid_line, sb.buf);
538 goto finish;
539 }
540
541 if (sb.buf[GIT_SHA1_HEXSZ] != ' ') {
542 ret = error(invalid_line, sb.buf);
543 goto finish;
544 }
545
546 if (get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ + 1, to_obj)) {
547 ret = error(invalid_line, sb.buf);
548 goto finish;
549 }
550
551 if (copy_note_for_rewrite(c, from_obj, to_obj))
552 ret = error(_("Failed to copy notes from '%s' to '%s'"),
553 sha1_to_hex(from_obj), sha1_to_hex(to_obj));
554 }
555
556finish:
557 finish_copy_notes_for_rewrite(c, msg);
558 fclose(fp);
559 strbuf_release(&sb);
560 return ret;
561}
562
c29807b2
PT
563/**
564 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
565 * non-indented lines and checking if they look like they begin with valid
566 * header field names.
567 *
568 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
569 */
570static int is_mail(FILE *fp)
571{
572 const char *header_regex = "^[!-9;-~]+:";
573 struct strbuf sb = STRBUF_INIT;
574 regex_t regex;
575 int ret = 1;
576
577 if (fseek(fp, 0L, SEEK_SET))
578 die_errno(_("fseek failed"));
579
580 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
581 die("invalid pattern: %s", header_regex);
582
583 while (!strbuf_getline_crlf(&sb, fp)) {
584 if (!sb.len)
585 break; /* End of header */
586
587 /* Ignore indented folded lines */
588 if (*sb.buf == '\t' || *sb.buf == ' ')
589 continue;
590
591 /* It's a header if it matches header_regex */
592 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
593 ret = 0;
594 goto done;
595 }
596 }
597
598done:
599 regfree(&regex);
600 strbuf_release(&sb);
601 return ret;
602}
603
604/**
605 * Attempts to detect the patch_format of the patches contained in `paths`,
606 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
607 * detection fails.
608 */
609static int detect_patch_format(const char **paths)
610{
611 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
612 struct strbuf l1 = STRBUF_INIT;
613 FILE *fp;
614
615 /*
616 * We default to mbox format if input is from stdin and for directories
617 */
618 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
619 return PATCH_FORMAT_MBOX;
620
621 /*
622 * Otherwise, check the first few lines of the first patch, starting
623 * from the first non-blank line, to try to detect its format.
624 */
625
626 fp = xfopen(*paths, "r");
627
628 while (!strbuf_getline_crlf(&l1, fp)) {
629 if (l1.len)
630 break;
631 }
632
633 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
634 ret = PATCH_FORMAT_MBOX;
635 goto done;
636 }
637
638 if (l1.len && is_mail(fp)) {
639 ret = PATCH_FORMAT_MBOX;
640 goto done;
641 }
642
643done:
644 fclose(fp);
645 strbuf_release(&l1);
646 return ret;
647}
648
11c2177f
PT
649/**
650 * Splits out individual email patches from `paths`, where each path is either
651 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
652 */
5d123a40 653static int split_mail_mbox(struct am_state *state, const char **paths, int keep_cr)
11c2177f
PT
654{
655 struct child_process cp = CHILD_PROCESS_INIT;
656 struct strbuf last = STRBUF_INIT;
657
658 cp.git_cmd = 1;
659 argv_array_push(&cp.args, "mailsplit");
660 argv_array_pushf(&cp.args, "-d%d", state->prec);
661 argv_array_pushf(&cp.args, "-o%s", state->dir);
662 argv_array_push(&cp.args, "-b");
5d123a40
PT
663 if (keep_cr)
664 argv_array_push(&cp.args, "--keep-cr");
11c2177f
PT
665 argv_array_push(&cp.args, "--");
666 argv_array_pushv(&cp.args, paths);
667
668 if (capture_command(&cp, &last, 8))
669 return -1;
670
671 state->cur = 1;
672 state->last = strtol(last.buf, NULL, 10);
673
674 return 0;
675}
676
677/**
678 * Splits a list of files/directories into individual email patches. Each path
679 * in `paths` must be a file/directory that is formatted according to
680 * `patch_format`.
681 *
682 * Once split out, the individual email patches will be stored in the state
683 * directory, with each patch's filename being its index, padded to state->prec
684 * digits.
685 *
686 * state->cur will be set to the index of the first mail, and state->last will
687 * be set to the index of the last mail.
688 *
5d123a40
PT
689 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
690 * to disable this behavior, -1 to use the default configured setting.
691 *
11c2177f
PT
692 * Returns 0 on success, -1 on failure.
693 */
694static int split_mail(struct am_state *state, enum patch_format patch_format,
5d123a40 695 const char **paths, int keep_cr)
11c2177f 696{
5d123a40
PT
697 if (keep_cr < 0) {
698 keep_cr = 0;
699 git_config_get_bool("am.keepcr", &keep_cr);
700 }
701
11c2177f
PT
702 switch (patch_format) {
703 case PATCH_FORMAT_MBOX:
5d123a40 704 return split_mail_mbox(state, paths, keep_cr);
11c2177f
PT
705 default:
706 die("BUG: invalid patch_format");
707 }
708 return -1;
709}
710
8c3bd9e2
PT
711/**
712 * Setup a new am session for applying patches
713 */
11c2177f 714static void am_setup(struct am_state *state, enum patch_format patch_format,
5d123a40 715 const char **paths, int keep_cr)
8c3bd9e2 716{
33388a71 717 unsigned char curr_head[GIT_SHA1_RAWSZ];
4f1b6961 718 const char *str;
257e8cec 719 struct strbuf sb = STRBUF_INIT;
33388a71 720
c29807b2
PT
721 if (!patch_format)
722 patch_format = detect_patch_format(paths);
723
724 if (!patch_format) {
725 fprintf_ln(stderr, _("Patch format detection failed."));
726 exit(128);
727 }
728
8c3bd9e2
PT
729 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
730 die_errno(_("failed to create directory '%s'"), state->dir);
731
5d123a40 732 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
11c2177f
PT
733 am_destroy(state);
734 die(_("Failed to split patches."));
735 }
736
35bdcc59
PT
737 if (state->rebasing)
738 state->threeway = 1;
739
84f3de28
PT
740 write_file(am_path(state, "threeway"), 1, state->threeway ? "t" : "f");
741
5d28cf78
PT
742 write_file(am_path(state, "quiet"), 1, state->quiet ? "t" : "f");
743
eb898b83
PT
744 write_file(am_path(state, "sign"), 1, state->signoff ? "t" : "f");
745
ef7ee16d
PT
746 write_file(am_path(state, "utf8"), 1, state->utf8 ? "t" : "f");
747
4f1b6961
PT
748 switch (state->keep) {
749 case KEEP_FALSE:
750 str = "f";
751 break;
752 case KEEP_TRUE:
753 str = "t";
754 break;
755 case KEEP_NON_PATCH:
756 str = "b";
757 break;
758 default:
759 die("BUG: invalid value for state->keep");
760 }
761
762 write_file(am_path(state, "keep"), 1, "%s", str);
763
702cbaad
PT
764 write_file(am_path(state, "messageid"), 1, state->message_id ? "t" : "f");
765
9b646617
PT
766 switch (state->scissors) {
767 case SCISSORS_UNSET:
768 str = "";
769 break;
770 case SCISSORS_FALSE:
771 str = "f";
772 break;
773 case SCISSORS_TRUE:
774 str = "t";
775 break;
776 default:
777 die("BUG: invalid value for state->scissors");
778 }
779
780 write_file(am_path(state, "scissors"), 1, "%s", str);
781
257e8cec
PT
782 sq_quote_argv(&sb, state->git_apply_opts.argv, 0);
783 write_file(am_path(state, "apply-opt"), 1, "%s", sb.buf);
784
35bdcc59
PT
785 if (state->rebasing)
786 write_file(am_path(state, "rebasing"), 1, "%s", "");
787 else
788 write_file(am_path(state, "applying"), 1, "%s", "");
789
33388a71
PT
790 if (!get_sha1("HEAD", curr_head)) {
791 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(curr_head));
35bdcc59
PT
792 if (!state->rebasing)
793 update_ref("am", "ORIG_HEAD", curr_head, NULL, 0,
794 UPDATE_REFS_DIE_ON_ERR);
33388a71
PT
795 } else {
796 write_file(am_path(state, "abort-safety"), 1, "%s", "");
35bdcc59
PT
797 if (!state->rebasing)
798 delete_ref("ORIG_HEAD", NULL, 0);
33388a71
PT
799 }
800
8c3bd9e2
PT
801 /*
802 * NOTE: Since the "next" and "last" files determine if an am_state
803 * session is in progress, they should be written last.
804 */
805
806 write_file(am_path(state, "next"), 1, "%d", state->cur);
807
808 write_file(am_path(state, "last"), 1, "%d", state->last);
257e8cec
PT
809
810 strbuf_release(&sb);
8c3bd9e2
PT
811}
812
813/**
814 * Increments the patch pointer, and cleans am_state for the application of the
815 * next patch.
816 */
817static void am_next(struct am_state *state)
818{
33388a71
PT
819 unsigned char head[GIT_SHA1_RAWSZ];
820
3e20dcf3
PT
821 free(state->author_name);
822 state->author_name = NULL;
823
824 free(state->author_email);
825 state->author_email = NULL;
826
827 free(state->author_date);
828 state->author_date = NULL;
829
830 free(state->msg);
831 state->msg = NULL;
832 state->msg_len = 0;
833
834 unlink(am_path(state, "author-script"));
835 unlink(am_path(state, "final-commit"));
836
13b97ea5
PT
837 hashclr(state->orig_commit);
838 unlink(am_path(state, "original-commit"));
839
33388a71
PT
840 if (!get_sha1("HEAD", head))
841 write_file(am_path(state, "abort-safety"), 1, "%s", sha1_to_hex(head));
842 else
843 write_file(am_path(state, "abort-safety"), 1, "%s", "");
844
8c3bd9e2
PT
845 state->cur++;
846 write_file(am_path(state, "next"), 1, "%d", state->cur);
847}
848
3e20dcf3
PT
849/**
850 * Returns the filename of the current patch email.
851 */
852static const char *msgnum(const struct am_state *state)
853{
854 static struct strbuf sb = STRBUF_INIT;
855
856 strbuf_reset(&sb);
857 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
858
859 return sb.buf;
860}
861
38a824fe
PT
862/**
863 * Refresh and write index.
864 */
865static void refresh_and_write_cache(void)
866{
867 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
868
869 hold_locked_index(lock_file, 1);
870 refresh_cache(REFRESH_QUIET);
871 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
872 die(_("unable to write index file"));
873}
874
32a5fcbf
PT
875/**
876 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn
877 * branch, returns 1 if there are entries in the index, 0 otherwise. If an
878 * strbuf is provided, the space-separated list of files that differ will be
879 * appended to it.
880 */
881static int index_has_changes(struct strbuf *sb)
882{
883 unsigned char head[GIT_SHA1_RAWSZ];
884 int i;
885
886 if (!get_sha1_tree("HEAD", head)) {
887 struct diff_options opt;
888
889 diff_setup(&opt);
890 DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);
891 if (!sb)
892 DIFF_OPT_SET(&opt, QUICK);
893 do_diff_cache(head, &opt);
894 diffcore_std(&opt);
895 for (i = 0; sb && i < diff_queued_diff.nr; i++) {
896 if (i)
897 strbuf_addch(sb, ' ');
898 strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);
899 }
900 diff_flush(&opt);
901 return DIFF_OPT_TST(&opt, HAS_CHANGES) != 0;
902 } else {
903 for (i = 0; sb && i < active_nr; i++) {
904 if (i)
905 strbuf_addch(sb, ' ');
906 strbuf_addstr(sb, active_cache[i]->name);
907 }
908 return !!active_nr;
909 }
910}
911
2d83109a
PT
912/**
913 * Dies with a user-friendly message on how to proceed after resolving the
914 * problem. This message can be overridden with state->resolvemsg.
915 */
916static void NORETURN die_user_resolve(const struct am_state *state)
917{
918 if (state->resolvemsg) {
919 printf_ln("%s", state->resolvemsg);
920 } else {
921 const char *cmdline = "git am";
922
923 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
924 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
925 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
926 }
927
928 exit(128);
929}
930
3e20dcf3
PT
931/**
932 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
933 * state->msg will be set to the patch message. state->author_name,
934 * state->author_email and state->author_date will be set to the patch author's
935 * name, email and date respectively. The patch body will be written to the
936 * state directory's "patch" file.
937 *
938 * Returns 1 if the patch should be skipped, 0 otherwise.
939 */
940static int parse_mail(struct am_state *state, const char *mail)
941{
942 FILE *fp;
943 struct child_process cp = CHILD_PROCESS_INIT;
944 struct strbuf sb = STRBUF_INIT;
945 struct strbuf msg = STRBUF_INIT;
946 struct strbuf author_name = STRBUF_INIT;
947 struct strbuf author_date = STRBUF_INIT;
948 struct strbuf author_email = STRBUF_INIT;
949 int ret = 0;
950
951 cp.git_cmd = 1;
952 cp.in = xopen(mail, O_RDONLY, 0);
953 cp.out = xopen(am_path(state, "info"), O_WRONLY | O_CREAT, 0777);
954
955 argv_array_push(&cp.args, "mailinfo");
ef7ee16d 956 argv_array_push(&cp.args, state->utf8 ? "-u" : "-n");
4f1b6961
PT
957
958 switch (state->keep) {
959 case KEEP_FALSE:
960 break;
961 case KEEP_TRUE:
962 argv_array_push(&cp.args, "-k");
963 break;
964 case KEEP_NON_PATCH:
965 argv_array_push(&cp.args, "-b");
966 break;
967 default:
968 die("BUG: invalid value for state->keep");
969 }
970
702cbaad
PT
971 if (state->message_id)
972 argv_array_push(&cp.args, "-m");
973
9b646617
PT
974 switch (state->scissors) {
975 case SCISSORS_UNSET:
976 break;
977 case SCISSORS_FALSE:
978 argv_array_push(&cp.args, "--no-scissors");
979 break;
980 case SCISSORS_TRUE:
981 argv_array_push(&cp.args, "--scissors");
982 break;
983 default:
984 die("BUG: invalid value for state->scissors");
985 }
986
3e20dcf3
PT
987 argv_array_push(&cp.args, am_path(state, "msg"));
988 argv_array_push(&cp.args, am_path(state, "patch"));
989
990 if (run_command(&cp) < 0)
991 die("could not parse patch");
992
993 close(cp.in);
994 close(cp.out);
995
996 /* Extract message and author information */
997 fp = xfopen(am_path(state, "info"), "r");
998 while (!strbuf_getline(&sb, fp, '\n')) {
999 const char *x;
1000
1001 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1002 if (msg.len)
1003 strbuf_addch(&msg, '\n');
1004 strbuf_addstr(&msg, x);
1005 } else if (skip_prefix(sb.buf, "Author: ", &x))
1006 strbuf_addstr(&author_name, x);
1007 else if (skip_prefix(sb.buf, "Email: ", &x))
1008 strbuf_addstr(&author_email, x);
1009 else if (skip_prefix(sb.buf, "Date: ", &x))
1010 strbuf_addstr(&author_date, x);
1011 }
1012 fclose(fp);
1013
1014 /* Skip pine's internal folder data */
1015 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1016 ret = 1;
1017 goto finish;
1018 }
1019
1020 if (is_empty_file(am_path(state, "patch"))) {
1021 printf_ln(_("Patch is empty. Was it split wrong?"));
2d83109a 1022 die_user_resolve(state);
3e20dcf3
PT
1023 }
1024
1025 strbuf_addstr(&msg, "\n\n");
1026 if (strbuf_read_file(&msg, am_path(state, "msg"), 0) < 0)
1027 die_errno(_("could not read '%s'"), am_path(state, "msg"));
1028 stripspace(&msg, 0);
1029
eb898b83
PT
1030 if (state->signoff)
1031 append_signoff(&msg, 0, 0);
1032
3e20dcf3
PT
1033 assert(!state->author_name);
1034 state->author_name = strbuf_detach(&author_name, NULL);
1035
1036 assert(!state->author_email);
1037 state->author_email = strbuf_detach(&author_email, NULL);
1038
1039 assert(!state->author_date);
1040 state->author_date = strbuf_detach(&author_date, NULL);
1041
1042 assert(!state->msg);
1043 state->msg = strbuf_detach(&msg, &state->msg_len);
1044
1045finish:
1046 strbuf_release(&msg);
1047 strbuf_release(&author_date);
1048 strbuf_release(&author_email);
1049 strbuf_release(&author_name);
1050 strbuf_release(&sb);
1051 return ret;
1052}
1053
df2760a5
PT
1054/**
1055 * Sets commit_id to the commit hash where the mail was generated from.
1056 * Returns 0 on success, -1 on failure.
1057 */
1058static int get_mail_commit_sha1(unsigned char *commit_id, const char *mail)
1059{
1060 struct strbuf sb = STRBUF_INIT;
1061 FILE *fp = xfopen(mail, "r");
1062 const char *x;
1063
1064 if (strbuf_getline(&sb, fp, '\n'))
1065 return -1;
1066
1067 if (!skip_prefix(sb.buf, "From ", &x))
1068 return -1;
1069
1070 if (get_sha1_hex(x, commit_id) < 0)
1071 return -1;
1072
1073 strbuf_release(&sb);
1074 fclose(fp);
1075 return 0;
1076}
1077
1078/**
1079 * Sets state->msg, state->author_name, state->author_email, state->author_date
1080 * to the commit's respective info.
1081 */
1082static void get_commit_info(struct am_state *state, struct commit *commit)
1083{
1084 const char *buffer, *ident_line, *author_date, *msg;
1085 size_t ident_len;
1086 struct ident_split ident_split;
1087 struct strbuf sb = STRBUF_INIT;
1088
1089 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1090
1091 ident_line = find_commit_header(buffer, "author", &ident_len);
1092
1093 if (split_ident_line(&ident_split, ident_line, ident_len) < 0) {
1094 strbuf_add(&sb, ident_line, ident_len);
1095 die(_("invalid ident line: %s"), sb.buf);
1096 }
1097
1098 assert(!state->author_name);
1099 if (ident_split.name_begin) {
1100 strbuf_add(&sb, ident_split.name_begin,
1101 ident_split.name_end - ident_split.name_begin);
1102 state->author_name = strbuf_detach(&sb, NULL);
1103 } else
1104 state->author_name = xstrdup("");
1105
1106 assert(!state->author_email);
1107 if (ident_split.mail_begin) {
1108 strbuf_add(&sb, ident_split.mail_begin,
1109 ident_split.mail_end - ident_split.mail_begin);
1110 state->author_email = strbuf_detach(&sb, NULL);
1111 } else
1112 state->author_email = xstrdup("");
1113
1114 author_date = show_ident_date(&ident_split, DATE_MODE(NORMAL));
1115 strbuf_addstr(&sb, author_date);
1116 assert(!state->author_date);
1117 state->author_date = strbuf_detach(&sb, NULL);
1118
1119 assert(!state->msg);
1120 msg = strstr(buffer, "\n\n");
1121 if (!msg)
1122 die(_("unable to parse commit %s"), sha1_to_hex(commit->object.sha1));
1123 state->msg = xstrdup(msg + 2);
1124 state->msg_len = strlen(state->msg);
1125}
1126
1127/**
1128 * Writes `commit` as a patch to the state directory's "patch" file.
1129 */
1130static void write_commit_patch(const struct am_state *state, struct commit *commit)
1131{
1132 struct rev_info rev_info;
1133 FILE *fp;
1134
1135 fp = xfopen(am_path(state, "patch"), "w");
1136 init_revisions(&rev_info, NULL);
1137 rev_info.diff = 1;
1138 rev_info.abbrev = 0;
1139 rev_info.disable_stdin = 1;
1140 rev_info.show_root_diff = 1;
1141 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1142 rev_info.no_commit_id = 1;
1143 DIFF_OPT_SET(&rev_info.diffopt, BINARY);
1144 DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);
1145 rev_info.diffopt.use_color = 0;
1146 rev_info.diffopt.file = fp;
1147 rev_info.diffopt.close_file = 1;
1148 add_pending_object(&rev_info, &commit->object, "");
1149 diff_setup_done(&rev_info.diffopt);
1150 log_tree_commit(&rev_info, commit);
1151}
1152
1153/**
1154 * Like parse_mail(), but parses the mail by looking up its commit ID
1155 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1156 * of patches.
1157 *
13b97ea5
PT
1158 * state->orig_commit will be set to the original commit ID.
1159 *
df2760a5
PT
1160 * Will always return 0 as the patch should never be skipped.
1161 */
1162static int parse_mail_rebase(struct am_state *state, const char *mail)
1163{
1164 struct commit *commit;
1165 unsigned char commit_sha1[GIT_SHA1_RAWSZ];
1166
1167 if (get_mail_commit_sha1(commit_sha1, mail) < 0)
1168 die(_("could not parse %s"), mail);
1169
1170 commit = lookup_commit_or_die(commit_sha1, mail);
1171
1172 get_commit_info(state, commit);
1173
1174 write_commit_patch(state, commit);
1175
13b97ea5
PT
1176 hashcpy(state->orig_commit, commit_sha1);
1177 write_file(am_path(state, "original-commit"), 1, "%s",
1178 sha1_to_hex(commit_sha1));
1179
df2760a5
PT
1180 return 0;
1181}
1182
38a824fe 1183/**
84f3de28
PT
1184 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1185 * `index_file` is not NULL, the patch will be applied to that index.
38a824fe 1186 */
84f3de28 1187static int run_apply(const struct am_state *state, const char *index_file)
38a824fe
PT
1188{
1189 struct child_process cp = CHILD_PROCESS_INIT;
1190
1191 cp.git_cmd = 1;
1192
84f3de28
PT
1193 if (index_file)
1194 argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s", index_file);
1195
1196 /*
1197 * If we are allowed to fall back on 3-way merge, don't give false
1198 * errors during the initial attempt.
1199 */
1200 if (state->threeway && !index_file) {
1201 cp.no_stdout = 1;
1202 cp.no_stderr = 1;
1203 }
1204
38a824fe 1205 argv_array_push(&cp.args, "apply");
84f3de28 1206
257e8cec
PT
1207 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
1208
84f3de28
PT
1209 if (index_file)
1210 argv_array_push(&cp.args, "--cached");
1211 else
1212 argv_array_push(&cp.args, "--index");
1213
38a824fe
PT
1214 argv_array_push(&cp.args, am_path(state, "patch"));
1215
1216 if (run_command(&cp))
1217 return -1;
1218
1219 /* Reload index as git-apply will have modified it. */
84f3de28
PT
1220 discard_cache();
1221 read_cache_from(index_file ? index_file : get_index_file());
1222
1223 return 0;
1224}
1225
1226/**
1227 * Builds an index that contains just the blobs needed for a 3way merge.
1228 */
1229static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1230{
1231 struct child_process cp = CHILD_PROCESS_INIT;
1232
1233 cp.git_cmd = 1;
1234 argv_array_push(&cp.args, "apply");
257e8cec 1235 argv_array_pushv(&cp.args, state->git_apply_opts.argv);
84f3de28
PT
1236 argv_array_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1237 argv_array_push(&cp.args, am_path(state, "patch"));
1238
1239 if (run_command(&cp))
1240 return -1;
1241
1242 return 0;
1243}
1244
1245/**
1246 * Attempt a threeway merge, using index_path as the temporary index.
1247 */
1248static int fall_back_threeway(const struct am_state *state, const char *index_path)
1249{
1250 unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],
1251 our_tree[GIT_SHA1_RAWSZ];
1252 const unsigned char *bases[1] = {orig_tree};
1253 struct merge_options o;
1254 struct commit *result;
1255 char *his_tree_name;
1256
1257 if (get_sha1("HEAD", our_tree) < 0)
1258 hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);
1259
1260 if (build_fake_ancestor(state, index_path))
1261 return error("could not build fake ancestor");
1262
1263 discard_cache();
1264 read_cache_from(index_path);
1265
1266 if (write_index_as_tree(orig_tree, &the_index, index_path, 0, NULL))
1267 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1268
1269 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1270
1271 if (!state->quiet) {
1272 /*
1273 * List paths that needed 3-way fallback, so that the user can
1274 * review them with extra care to spot mismerges.
1275 */
1276 struct rev_info rev_info;
1277 const char *diff_filter_str = "--diff-filter=AM";
1278
1279 init_revisions(&rev_info, NULL);
1280 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
1281 diff_opt_parse(&rev_info.diffopt, &diff_filter_str, 1);
1282 add_pending_sha1(&rev_info, "HEAD", our_tree, 0);
1283 diff_setup_done(&rev_info.diffopt);
1284 run_diff_index(&rev_info, 1);
1285 }
1286
1287 if (run_apply(state, index_path))
1288 return error(_("Did you hand edit your patch?\n"
1289 "It does not apply to blobs recorded in its index."));
1290
1291 if (write_index_as_tree(his_tree, &the_index, index_path, 0, NULL))
1292 return error("could not write tree");
1293
1294 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1295
38a824fe
PT
1296 discard_cache();
1297 read_cache();
1298
84f3de28
PT
1299 /*
1300 * This is not so wrong. Depending on which base we picked, orig_tree
1301 * may be wildly different from ours, but his_tree has the same set of
1302 * wildly different changes in parts the patch did not touch, so
1303 * recursive ends up canceling them, saying that we reverted all those
1304 * changes.
1305 */
1306
1307 init_merge_options(&o);
1308
1309 o.branch1 = "HEAD";
1310 his_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1311 o.branch2 = his_tree_name;
1312
1313 if (state->quiet)
1314 o.verbosity = 0;
1315
1316 if (merge_recursive_generic(&o, our_tree, his_tree, 1, bases, &result)) {
f1cb96d6 1317 rerere(state->allow_rerere_autoupdate);
84f3de28
PT
1318 free(his_tree_name);
1319 return error(_("Failed to merge in the changes."));
1320 }
1321
1322 free(his_tree_name);
38a824fe
PT
1323 return 0;
1324}
1325
c9e8d960
PT
1326/**
1327 * Commits the current index with state->msg as the commit message and
1328 * state->author_name, state->author_email and state->author_date as the author
1329 * information.
1330 */
1331static void do_commit(const struct am_state *state)
1332{
1333 unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],
1334 commit[GIT_SHA1_RAWSZ];
1335 unsigned char *ptr;
1336 struct commit_list *parents = NULL;
1337 const char *reflog_msg, *author;
1338 struct strbuf sb = STRBUF_INIT;
1339
6c24c5c0
PT
1340 if (run_hook_le(NULL, "pre-applypatch", NULL))
1341 exit(1);
1342
c9e8d960
PT
1343 if (write_cache_as_tree(tree, 0, NULL))
1344 die(_("git write-tree failed to write a tree"));
1345
1346 if (!get_sha1_commit("HEAD", parent)) {
1347 ptr = parent;
1348 commit_list_insert(lookup_commit(parent), &parents);
1349 } else {
1350 ptr = NULL;
5d28cf78 1351 say(state, stderr, _("applying to an empty history"));
c9e8d960
PT
1352 }
1353
1354 author = fmt_ident(state->author_name, state->author_email,
f07adb62
PT
1355 state->ignore_date ? NULL : state->author_date,
1356 IDENT_STRICT);
c9e8d960 1357
0cd4bcba
PT
1358 if (state->committer_date_is_author_date)
1359 setenv("GIT_COMMITTER_DATE",
1360 state->ignore_date ? "" : state->author_date, 1);
1361
c9e8d960 1362 if (commit_tree(state->msg, state->msg_len, tree, parents, commit,
7e35dacb 1363 author, state->sign_commit))
c9e8d960
PT
1364 die(_("failed to write commit object"));
1365
1366 reflog_msg = getenv("GIT_REFLOG_ACTION");
1367 if (!reflog_msg)
1368 reflog_msg = "am";
1369
1370 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1371 state->msg);
1372
1373 update_ref(sb.buf, "HEAD", commit, ptr, 0, UPDATE_REFS_DIE_ON_ERR);
1374
13b97ea5
PT
1375 if (state->rebasing) {
1376 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1377
1378 assert(!is_null_sha1(state->orig_commit));
1379 fprintf(fp, "%s ", sha1_to_hex(state->orig_commit));
1380 fprintf(fp, "%s\n", sha1_to_hex(commit));
1381 fclose(fp);
1382 }
1383
7088f807
PT
1384 run_hook_le(NULL, "post-applypatch", NULL);
1385
c9e8d960
PT
1386 strbuf_release(&sb);
1387}
1388
240bfd2d
PT
1389/**
1390 * Validates the am_state for resuming -- the "msg" and authorship fields must
1391 * be filled up.
1392 */
1393static void validate_resume_state(const struct am_state *state)
1394{
1395 if (!state->msg)
1396 die(_("cannot resume: %s does not exist."),
1397 am_path(state, "final-commit"));
1398
1399 if (!state->author_name || !state->author_email || !state->author_date)
1400 die(_("cannot resume: %s does not exist."),
1401 am_path(state, "author-script"));
1402}
1403
8c3bd9e2
PT
1404/**
1405 * Applies all queued mail.
8c7b1563
PT
1406 *
1407 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1408 * well as the state directory's "patch" file is used as-is for applying the
1409 * patch and committing it.
8c3bd9e2 1410 */
8c7b1563 1411static void am_run(struct am_state *state, int resume)
8c3bd9e2 1412{
c9e8d960 1413 const char *argv_gc_auto[] = {"gc", "--auto", NULL};
32a5fcbf 1414 struct strbuf sb = STRBUF_INIT;
c9e8d960 1415
33388a71
PT
1416 unlink(am_path(state, "dirtyindex"));
1417
38a824fe
PT
1418 refresh_and_write_cache();
1419
33388a71
PT
1420 if (index_has_changes(&sb)) {
1421 write_file(am_path(state, "dirtyindex"), 1, "t");
32a5fcbf 1422 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
33388a71 1423 }
32a5fcbf
PT
1424
1425 strbuf_release(&sb);
1426
8c3bd9e2 1427 while (state->cur <= state->last) {
3e20dcf3 1428 const char *mail = am_path(state, msgnum(state));
84f3de28 1429 int apply_status;
3e20dcf3
PT
1430
1431 if (!file_exists(mail))
1432 goto next;
1433
8c7b1563
PT
1434 if (resume) {
1435 validate_resume_state(state);
1436 resume = 0;
1437 } else {
df2760a5
PT
1438 int skip;
1439
1440 if (state->rebasing)
1441 skip = parse_mail_rebase(state, mail);
1442 else
1443 skip = parse_mail(state, mail);
1444
1445 if (skip)
8c7b1563 1446 goto next; /* mail should be skipped */
3e20dcf3 1447
8c7b1563
PT
1448 write_author_script(state);
1449 write_commit_msg(state);
1450 }
8c3bd9e2 1451
b8803d8f
PT
1452 if (run_applypatch_msg_hook(state))
1453 exit(1);
1454
5d28cf78 1455 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
38a824fe 1456
84f3de28
PT
1457 apply_status = run_apply(state, NULL);
1458
1459 if (apply_status && state->threeway) {
1460 struct strbuf sb = STRBUF_INIT;
1461
1462 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1463 apply_status = fall_back_threeway(state, sb.buf);
1464 strbuf_release(&sb);
1465
1466 /*
1467 * Applying the patch to an earlier tree and merging
1468 * the result may have produced the same tree as ours.
1469 */
1470 if (!apply_status && !index_has_changes(NULL)) {
1471 say(state, stdout, _("No changes -- Patch already applied."));
1472 goto next;
1473 }
1474 }
1475
1476 if (apply_status) {
38a824fe
PT
1477 int advice_amworkdir = 1;
1478
1479 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1480 linelen(state->msg), state->msg);
1481
1482 git_config_get_bool("advice.amworkdir", &advice_amworkdir);
1483
1484 if (advice_amworkdir)
1485 printf_ln(_("The copy of the patch that failed is found in: %s"),
1486 am_path(state, "patch"));
1487
2d83109a 1488 die_user_resolve(state);
38a824fe
PT
1489 }
1490
c9e8d960 1491 do_commit(state);
8c3bd9e2 1492
3e20dcf3 1493next:
8c3bd9e2
PT
1494 am_next(state);
1495 }
1496
13b97ea5
PT
1497 if (!is_empty_file(am_path(state, "rewritten"))) {
1498 assert(state->rebasing);
88b291fe 1499 copy_notes_for_rebase(state);
13b97ea5
PT
1500 run_post_rewrite_hook(state);
1501 }
1502
35bdcc59
PT
1503 /*
1504 * In rebasing mode, it's up to the caller to take care of
1505 * housekeeping.
1506 */
1507 if (!state->rebasing) {
1508 am_destroy(state);
1509 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1510 }
8c3bd9e2 1511}
73c2779f 1512
240bfd2d
PT
1513/**
1514 * Resume the current am session after patch application failure. The user did
1515 * all the hard work, and we do not have to do any patch application. Just
1516 * trust and commit what the user has in the index and working tree.
1517 */
1518static void am_resolve(struct am_state *state)
1519{
1520 validate_resume_state(state);
1521
5d28cf78 1522 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
240bfd2d
PT
1523
1524 if (!index_has_changes(NULL)) {
1525 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1526 "If there is nothing left to stage, chances are that something else\n"
1527 "already introduced the same changes; you might want to skip this patch."));
2d83109a 1528 die_user_resolve(state);
240bfd2d
PT
1529 }
1530
1531 if (unmerged_cache()) {
1532 printf_ln(_("You still have unmerged paths in your index.\n"
1533 "Did you forget to use 'git add'?"));
2d83109a 1534 die_user_resolve(state);
240bfd2d
PT
1535 }
1536
f1cb96d6
PT
1537 rerere(0);
1538
240bfd2d
PT
1539 do_commit(state);
1540
1541 am_next(state);
8c7b1563 1542 am_run(state, 0);
240bfd2d
PT
1543}
1544
9990080c
PT
1545/**
1546 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1547 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1548 * failure.
1549 */
1550static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1551{
1552 struct lock_file *lock_file;
1553 struct unpack_trees_options opts;
1554 struct tree_desc t[2];
1555
1556 if (parse_tree(head) || parse_tree(remote))
1557 return -1;
1558
1559 lock_file = xcalloc(1, sizeof(struct lock_file));
1560 hold_locked_index(lock_file, 1);
1561
1562 refresh_cache(REFRESH_QUIET);
1563
1564 memset(&opts, 0, sizeof(opts));
1565 opts.head_idx = 1;
1566 opts.src_index = &the_index;
1567 opts.dst_index = &the_index;
1568 opts.update = 1;
1569 opts.merge = 1;
1570 opts.reset = reset;
1571 opts.fn = twoway_merge;
1572 init_tree_desc(&t[0], head->buffer, head->size);
1573 init_tree_desc(&t[1], remote->buffer, remote->size);
1574
1575 if (unpack_trees(2, t, &opts)) {
1576 rollback_lock_file(lock_file);
1577 return -1;
1578 }
1579
1580 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1581 die(_("unable to write new index file"));
1582
1583 return 0;
1584}
1585
1586/**
1587 * Clean the index without touching entries that are not modified between
1588 * `head` and `remote`.
1589 */
1590static int clean_index(const unsigned char *head, const unsigned char *remote)
1591{
1592 struct lock_file *lock_file;
1593 struct tree *head_tree, *remote_tree, *index_tree;
1594 unsigned char index[GIT_SHA1_RAWSZ];
1595 struct pathspec pathspec;
1596
1597 head_tree = parse_tree_indirect(head);
1598 if (!head_tree)
1599 return error(_("Could not parse object '%s'."), sha1_to_hex(head));
1600
1601 remote_tree = parse_tree_indirect(remote);
1602 if (!remote_tree)
1603 return error(_("Could not parse object '%s'."), sha1_to_hex(remote));
1604
1605 read_cache_unmerged();
1606
1607 if (fast_forward_to(head_tree, head_tree, 1))
1608 return -1;
1609
1610 if (write_cache_as_tree(index, 0, NULL))
1611 return -1;
1612
1613 index_tree = parse_tree_indirect(index);
1614 if (!index_tree)
1615 return error(_("Could not parse object '%s'."), sha1_to_hex(index));
1616
1617 if (fast_forward_to(index_tree, remote_tree, 0))
1618 return -1;
1619
1620 memset(&pathspec, 0, sizeof(pathspec));
1621
1622 lock_file = xcalloc(1, sizeof(struct lock_file));
1623 hold_locked_index(lock_file, 1);
1624
1625 if (read_tree(remote_tree, 0, &pathspec)) {
1626 rollback_lock_file(lock_file);
1627 return -1;
1628 }
1629
1630 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
1631 die(_("unable to write new index file"));
1632
1633 remove_branch_state();
1634
1635 return 0;
1636}
1637
f1cb96d6
PT
1638/**
1639 * Resets rerere's merge resolution metadata.
1640 */
1641static void am_rerere_clear(void)
1642{
1643 struct string_list merge_rr = STRING_LIST_INIT_DUP;
1644 int fd = setup_rerere(&merge_rr, 0);
1645
1646 if (fd < 0)
1647 return;
1648
1649 rerere_clear(&merge_rr);
1650 string_list_clear(&merge_rr, 1);
1651}
1652
9990080c
PT
1653/**
1654 * Resume the current am session by skipping the current patch.
1655 */
1656static void am_skip(struct am_state *state)
1657{
1658 unsigned char head[GIT_SHA1_RAWSZ];
1659
f1cb96d6
PT
1660 am_rerere_clear();
1661
9990080c
PT
1662 if (get_sha1("HEAD", head))
1663 hashcpy(head, EMPTY_TREE_SHA1_BIN);
1664
1665 if (clean_index(head, head))
1666 die(_("failed to clean index"));
1667
1668 am_next(state);
1669 am_run(state, 0);
1670}
1671
33388a71
PT
1672/**
1673 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
1674 *
1675 * It is not safe to reset HEAD when:
1676 * 1. git-am previously failed because the index was dirty.
1677 * 2. HEAD has moved since git-am previously failed.
1678 */
1679static int safe_to_abort(const struct am_state *state)
1680{
1681 struct strbuf sb = STRBUF_INIT;
1682 unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];
1683
1684 if (file_exists(am_path(state, "dirtyindex")))
1685 return 0;
1686
1687 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
1688 if (get_sha1_hex(sb.buf, abort_safety))
1689 die(_("could not parse %s"), am_path(state, "abort_safety"));
1690 } else
1691 hashclr(abort_safety);
1692
1693 if (get_sha1("HEAD", head))
1694 hashclr(head);
1695
1696 if (!hashcmp(head, abort_safety))
1697 return 1;
1698
1699 error(_("You seem to have moved HEAD since the last 'am' failure.\n"
1700 "Not rewinding to ORIG_HEAD"));
1701
1702 return 0;
1703}
1704
1705/**
1706 * Aborts the current am session if it is safe to do so.
1707 */
1708static void am_abort(struct am_state *state)
1709{
1710 unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];
1711 int has_curr_head, has_orig_head;
1712 char *curr_branch;
1713
1714 if (!safe_to_abort(state)) {
1715 am_destroy(state);
1716 return;
1717 }
1718
f1cb96d6
PT
1719 am_rerere_clear();
1720
33388a71
PT
1721 curr_branch = resolve_refdup("HEAD", 0, curr_head, NULL);
1722 has_curr_head = !is_null_sha1(curr_head);
1723 if (!has_curr_head)
1724 hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);
1725
1726 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);
1727 if (!has_orig_head)
1728 hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);
1729
1730 clean_index(curr_head, orig_head);
1731
1732 if (has_orig_head)
1733 update_ref("am --abort", "HEAD", orig_head,
1734 has_curr_head ? curr_head : NULL, 0,
1735 UPDATE_REFS_DIE_ON_ERR);
1736 else if (curr_branch)
1737 delete_ref(curr_branch, NULL, REF_NODEREF);
1738
1739 free(curr_branch);
1740 am_destroy(state);
1741}
1742
11c2177f
PT
1743/**
1744 * parse_options() callback that validates and sets opt->value to the
1745 * PATCH_FORMAT_* enum value corresponding to `arg`.
1746 */
1747static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
1748{
1749 int *opt_value = opt->value;
1750
1751 if (!strcmp(arg, "mbox"))
1752 *opt_value = PATCH_FORMAT_MBOX;
1753 else
1754 return error(_("Invalid value for --patch-format: %s"), arg);
1755 return 0;
1756}
1757
240bfd2d
PT
1758enum resume_mode {
1759 RESUME_FALSE = 0,
8c7b1563 1760 RESUME_APPLY,
9990080c 1761 RESUME_RESOLVED,
33388a71
PT
1762 RESUME_SKIP,
1763 RESUME_ABORT
240bfd2d
PT
1764};
1765
73c2779f
PT
1766int cmd_am(int argc, const char **argv, const char *prefix)
1767{
8c3bd9e2 1768 struct am_state state;
5d123a40 1769 int keep_cr = -1;
11c2177f 1770 int patch_format = PATCH_FORMAT_UNKNOWN;
240bfd2d 1771 enum resume_mode resume = RESUME_FALSE;
8c3bd9e2
PT
1772
1773 const char * const usage[] = {
1774 N_("git am [options] [(<mbox>|<Maildir>)...]"),
33388a71 1775 N_("git am [options] (--continue | --skip | --abort)"),
8c3bd9e2
PT
1776 NULL
1777 };
1778
1779 struct option options[] = {
84f3de28
PT
1780 OPT_BOOL('3', "3way", &state.threeway,
1781 N_("allow fall back on 3way merging if needed")),
5d28cf78 1782 OPT__QUIET(&state.quiet, N_("be quiet")),
eb898b83
PT
1783 OPT_BOOL('s', "signoff", &state.signoff,
1784 N_("add a Signed-off-by line to the commit message")),
ef7ee16d
PT
1785 OPT_BOOL('u', "utf8", &state.utf8,
1786 N_("recode into utf8 (default)")),
4f1b6961
PT
1787 OPT_SET_INT('k', "keep", &state.keep,
1788 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
1789 OPT_SET_INT(0, "keep-non-patch", &state.keep,
1790 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
702cbaad
PT
1791 OPT_BOOL('m', "message-id", &state.message_id,
1792 N_("pass -m flag to git-mailinfo")),
5d123a40
PT
1793 { OPTION_SET_INT, 0, "keep-cr", &keep_cr, NULL,
1794 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
1795 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1},
1796 { OPTION_SET_INT, 0, "no-keep-cr", &keep_cr, NULL,
1797 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
1798 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 0},
9b646617
PT
1799 OPT_BOOL('c', "scissors", &state.scissors,
1800 N_("strip everything before a scissors line")),
257e8cec
PT
1801 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
1802 N_("pass it through git-apply"),
1803 0),
1804 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
1805 N_("pass it through git-apply"),
1806 PARSE_OPT_NOARG),
1807 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
1808 N_("pass it through git-apply"),
1809 PARSE_OPT_NOARG),
1810 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
1811 N_("pass it through git-apply"),
1812 0),
1813 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
1814 N_("pass it through git-apply"),
1815 0),
1816 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
1817 N_("pass it through git-apply"),
1818 0),
1819 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
1820 N_("pass it through git-apply"),
1821 0),
1822 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
1823 N_("pass it through git-apply"),
1824 0),
11c2177f
PT
1825 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
1826 N_("format the patch(es) are in"),
1827 parse_opt_patchformat),
257e8cec
PT
1828 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
1829 N_("pass it through git-apply"),
1830 PARSE_OPT_NOARG),
2d83109a
PT
1831 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
1832 N_("override error message when patch failure occurs")),
240bfd2d
PT
1833 OPT_CMDMODE(0, "continue", &resume,
1834 N_("continue applying patches after resolving a conflict"),
1835 RESUME_RESOLVED),
1836 OPT_CMDMODE('r', "resolved", &resume,
1837 N_("synonyms for --continue"),
1838 RESUME_RESOLVED),
9990080c
PT
1839 OPT_CMDMODE(0, "skip", &resume,
1840 N_("skip the current patch"),
1841 RESUME_SKIP),
33388a71
PT
1842 OPT_CMDMODE(0, "abort", &resume,
1843 N_("restore the original branch and abort the patching operation."),
1844 RESUME_ABORT),
0cd4bcba
PT
1845 OPT_BOOL(0, "committer-date-is-author-date",
1846 &state.committer_date_is_author_date,
1847 N_("lie about committer date")),
f07adb62
PT
1848 OPT_BOOL(0, "ignore-date", &state.ignore_date,
1849 N_("use current timestamp for author date")),
f1cb96d6 1850 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
7e35dacb
PT
1851 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
1852 N_("GPG-sign commits"),
1853 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
35bdcc59
PT
1854 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
1855 N_("(internal use for git-rebase)")),
8c3bd9e2
PT
1856 OPT_END()
1857 };
73c2779f
PT
1858
1859 /*
1860 * NEEDSWORK: Once all the features of git-am.sh have been
1861 * re-implemented in builtin/am.c, this preamble can be removed.
1862 */
1863 if (!getenv("_GIT_USE_BUILTIN_AM")) {
1864 const char *path = mkpath("%s/git-am", git_exec_path());
1865
1866 if (sane_execvp(path, (char **)argv) < 0)
1867 die_errno("could not exec %s", path);
1868 } else {
1869 prefix = setup_git_directory();
1870 trace_repo_setup(prefix);
1871 setup_work_tree();
1872 }
1873
8c3bd9e2
PT
1874 git_config(git_default_config, NULL);
1875
1876 am_state_init(&state, git_path("rebase-apply"));
1877
1878 argc = parse_options(argc, argv, prefix, options, usage, 0);
1879
38a824fe
PT
1880 if (read_index_preload(&the_index, NULL) < 0)
1881 die(_("failed to read the index"));
1882
8c7b1563 1883 if (am_in_progress(&state)) {
8d185503
PT
1884 /*
1885 * Catch user error to feed us patches when there is a session
1886 * in progress:
1887 *
1888 * 1. mbox path(s) are provided on the command-line.
1889 * 2. stdin is not a tty: the user is trying to feed us a patch
1890 * from standard input. This is somewhat unreliable -- stdin
1891 * could be /dev/null for example and the caller did not
1892 * intend to feed us a patch but wanted to continue
1893 * unattended.
1894 */
1895 if (argc || (resume == RESUME_FALSE && !isatty(0)))
1896 die(_("previous rebase directory %s still exists but mbox given."),
1897 state.dir);
1898
8c7b1563
PT
1899 if (resume == RESUME_FALSE)
1900 resume = RESUME_APPLY;
1901
8c3bd9e2 1902 am_load(&state);
8c7b1563 1903 } else {
11c2177f
PT
1904 struct argv_array paths = ARGV_ARRAY_INIT;
1905 int i;
1906
6d42ac29
PT
1907 /*
1908 * Handle stray state directory in the independent-run case. In
1909 * the --rebasing case, it is up to the caller to take care of
1910 * stray directories.
1911 */
1912 if (file_exists(state.dir) && !state.rebasing) {
1913 if (resume == RESUME_ABORT) {
1914 am_destroy(&state);
1915 am_state_release(&state);
1916 return 0;
1917 }
1918
1919 die(_("Stray %s directory found.\n"
1920 "Use \"git am --abort\" to remove it."),
1921 state.dir);
1922 }
1923
240bfd2d
PT
1924 if (resume)
1925 die(_("Resolve operation not in progress, we are not resuming."));
1926
11c2177f
PT
1927 for (i = 0; i < argc; i++) {
1928 if (is_absolute_path(argv[i]) || !prefix)
1929 argv_array_push(&paths, argv[i]);
1930 else
1931 argv_array_push(&paths, mkpath("%s/%s", prefix, argv[i]));
1932 }
1933
5d123a40 1934 am_setup(&state, patch_format, paths.argv, keep_cr);
11c2177f
PT
1935
1936 argv_array_clear(&paths);
1937 }
8c3bd9e2 1938
240bfd2d
PT
1939 switch (resume) {
1940 case RESUME_FALSE:
8c7b1563
PT
1941 am_run(&state, 0);
1942 break;
1943 case RESUME_APPLY:
1944 am_run(&state, 1);
240bfd2d
PT
1945 break;
1946 case RESUME_RESOLVED:
1947 am_resolve(&state);
1948 break;
9990080c
PT
1949 case RESUME_SKIP:
1950 am_skip(&state);
1951 break;
33388a71
PT
1952 case RESUME_ABORT:
1953 am_abort(&state);
1954 break;
240bfd2d
PT
1955 default:
1956 die("BUG: invalid resume value");
1957 }
8c3bd9e2
PT
1958
1959 am_state_release(&state);
1960
73c2779f
PT
1961 return 0;
1962}