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