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