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