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