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