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