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