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