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