blob: 82a41cbfc4e9ce2538644b9247dfc3a3bbe60888 [file] [log] [blame]
Paul Tan73c27792015-08-04 21:51:24 +08001/*
2 * Builtin "git am"
3 *
4 * Based on git-am.sh by Junio C Hamano.
5 */
Nguyễn Thái Ngọc Duyf8adbec2019-01-24 15:29:12 +07006#define USE_THE_INDEX_COMPATIBILITY_MACROS
Paul Tan73c27792015-08-04 21:51:24 +08007#include "cache.h"
Brandon Williamsb2141fc2017-06-14 11:07:36 -07008#include "config.h"
Paul Tan73c27792015-08-04 21:51:24 +08009#include "builtin.h"
Stefan Bellerd807c4a2018-04-10 14:26:18 -070010#include "exec-cmd.h"
Paul Tan8c3bd9e2015-08-04 21:51:25 +080011#include "parse-options.h"
12#include "dir.h"
Paul Tan11c21772015-08-04 21:51:26 +080013#include "run-command.h"
Ævar Arnfjörð Bjarmason5e3aba32021-09-26 21:03:26 +020014#include "hook.h"
Paul Tan3e20dcf2015-08-04 21:51:28 +080015#include "quote.h"
Junio C Hamanodb86e612015-08-25 14:57:09 -070016#include "tempfile.h"
Paul Tan38a824f2015-08-04 21:51:29 +080017#include "lockfile.h"
Paul Tanc9e8d962015-08-04 21:51:30 +080018#include "cache-tree.h"
19#include "refs.h"
20#include "commit.h"
Paul Tan32a5fcb2015-08-04 21:51:31 +080021#include "diff.h"
22#include "diffcore.h"
Paul Tan99900802015-08-04 21:51:34 +080023#include "unpack-trees.h"
24#include "branch.h"
Paul Taneb898b82015-08-04 21:51:39 +080025#include "sequencer.h"
Paul Tan84f3de22015-08-04 21:51:41 +080026#include "revision.h"
27#include "merge-recursive.h"
Paul Tandf2760a2015-08-04 21:51:43 +080028#include "log-tree.h"
Paul Tan88b291f2015-08-04 21:51:55 +080029#include "notes-utils.h"
Paul Tanf1cb96d2015-08-04 21:51:59 +080030#include "rerere.h"
Paul Tan7ff26832015-08-04 21:52:03 +080031#include "prompt.h"
Junio C Hamano4b98bae2015-10-14 17:45:43 -070032#include "mailinfo.h"
Christian Couderedfac5e2016-09-04 22:18:33 +020033#include "apply.h"
Junio C Hamanoa77598e2016-08-30 12:36:42 -070034#include "string-list.h"
Jonathan Tan3836d882017-08-18 15:20:21 -070035#include "packfile.h"
Stefan Bellerf86bcc72018-06-28 18:21:56 -070036#include "repository.h"
Ævar Arnfjörð Bjarmason88c7b4c2022-02-16 09:14:02 +010037#include "pretty.h"
Paul Tan3e20dcf2015-08-04 21:51:28 +080038
39/**
Paul Tan38a824f2015-08-04 21:51:29 +080040 * Returns the length of the first line of msg.
41 */
42static int linelen(const char *msg)
43{
44 return strchrnul(msg, '\n') - msg;
45}
46
Paul Tan5ae41c72015-08-04 21:52:00 +080047/**
48 * Returns true if `str` consists of only whitespace, false otherwise.
49 */
50static int str_isspace(const char *str)
51{
52 for (; *str; str++)
53 if (!isspace(*str))
54 return 0;
55
56 return 1;
57}
58
Paul Tan11c21772015-08-04 21:51:26 +080059enum patch_format {
60 PATCH_FORMAT_UNKNOWN = 0,
Paul Tan5ae41c72015-08-04 21:52:00 +080061 PATCH_FORMAT_MBOX,
Paul Tan336108c2015-08-04 21:52:01 +080062 PATCH_FORMAT_STGIT,
Paul Tan94cd1752015-08-04 21:52:02 +080063 PATCH_FORMAT_STGIT_SERIES,
Eric Wongd9925d12016-06-05 04:46:41 +000064 PATCH_FORMAT_HG,
65 PATCH_FORMAT_MBOXRD
Paul Tan11c21772015-08-04 21:51:26 +080066};
Paul Tan8c3bd9e2015-08-04 21:51:25 +080067
Paul Tan4f1b6962015-08-04 21:51:46 +080068enum keep_type {
69 KEEP_FALSE = 0,
70 KEEP_TRUE, /* pass -k flag to git-mailinfo */
71 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
72};
73
Paul Tan9b646612015-08-04 21:51:49 +080074enum scissors_type {
75 SCISSORS_UNSET = -1,
76 SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
77 SCISSORS_TRUE /* pass --scissors to git-mailinfo */
78};
79
Paul Tanb5e82352015-08-04 22:08:51 +080080enum signoff_type {
81 SIGNOFF_FALSE = 0,
82 SIGNOFF_TRUE = 1,
83 SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
84};
85
Paolo Bonzinif3b48222020-02-20 15:15:18 +010086enum show_patch_type {
87 SHOW_PATCH_RAW = 0,
Paolo Bonziniaa416b22020-02-20 15:15:19 +010088 SHOW_PATCH_DIFF = 1,
Paolo Bonzinif3b48222020-02-20 15:15:18 +010089};
90
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +000091enum empty_action {
92 STOP_ON_EMPTY_COMMIT = 0, /* output errors and stop in the middle of an am session */
93 DROP_EMPTY_COMMIT, /* skip with a notice message, unless "--quiet" has been passed */
94 KEEP_EMPTY_COMMIT, /* keep recording as empty commits */
95};
96
Paul Tan8c3bd9e2015-08-04 21:51:25 +080097struct am_state {
98 /* state directory path */
99 char *dir;
100
101 /* current and last patch numbers, 1-indexed */
102 int cur;
103 int last;
Paul Tan11c21772015-08-04 21:51:26 +0800104
Paul Tan3e20dcf2015-08-04 21:51:28 +0800105 /* commit metadata and message */
106 char *author_name;
107 char *author_email;
108 char *author_date;
109 char *msg;
110 size_t msg_len;
111
Paul Tan13b97ea2015-08-04 21:51:54 +0800112 /* when --rebasing, records the original commit the patch came from */
brian m. carlson8c887692016-09-05 20:08:09 +0000113 struct object_id orig_commit;
Paul Tan13b97ea2015-08-04 21:51:54 +0800114
Paul Tan11c21772015-08-04 21:51:26 +0800115 /* number of digits in patch filename */
116 int prec;
Paul Tan5d28cf72015-08-04 21:51:37 +0800117
118 /* various operating modes and command line options */
Paul Tan7ff26832015-08-04 21:52:03 +0800119 int interactive;
Thierry Reding566902f2022-11-30 18:28:33 +0100120 int no_verify;
Paul Tan84f3de22015-08-04 21:51:41 +0800121 int threeway;
Paul Tan5d28cf72015-08-04 21:51:37 +0800122 int quiet;
Paul Tanb5e82352015-08-04 22:08:51 +0800123 int signoff; /* enum signoff_type */
Paul Tanef7ee162015-08-04 21:51:45 +0800124 int utf8;
Paul Tan4f1b6962015-08-04 21:51:46 +0800125 int keep; /* enum keep_type */
Paul Tan702cbaa2015-08-04 21:51:47 +0800126 int message_id;
Paul Tan9b646612015-08-04 21:51:49 +0800127 int scissors; /* enum scissors_type */
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +0700128 int quoted_cr; /* enum quoted_cr_action */
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +0000129 int empty_type; /* enum empty_action */
Jeff King22f9b7f2020-07-28 16:24:27 -0400130 struct strvec git_apply_opts;
Paul Tan2d831092015-08-04 21:51:38 +0800131 const char *resolvemsg;
Paul Tan0cd4bcb2015-08-04 21:51:52 +0800132 int committer_date_is_author_date;
Paul Tanf07adb62015-08-04 21:51:51 +0800133 int ignore_date;
Paul Tanf1cb96d2015-08-04 21:51:59 +0800134 int allow_rerere_autoupdate;
Paul Tan7e35dac2015-08-04 21:51:53 +0800135 const char *sign_commit;
Paul Tan35bdcc52015-08-04 21:51:42 +0800136 int rebasing;
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800137};
138
139/**
Jeff King16d26762017-04-20 17:09:35 -0400140 * Initializes am_state with the default values.
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800141 */
Jeff King16d26762017-04-20 17:09:35 -0400142static void am_state_init(struct am_state *state)
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800143{
Paul Tan7e35dac2015-08-04 21:51:53 +0800144 int gpgsign;
145
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800146 memset(state, 0, sizeof(*state));
147
Jeff King16d26762017-04-20 17:09:35 -0400148 state->dir = git_pathdup("rebase-apply");
Paul Tan11c21772015-08-04 21:51:26 +0800149
150 state->prec = 4;
Paul Tanef7ee162015-08-04 21:51:45 +0800151
Remi Lespinete97a5e72015-08-04 22:19:26 +0800152 git_config_get_bool("am.threeway", &state->threeway);
153
Paul Tanef7ee162015-08-04 21:51:45 +0800154 state->utf8 = 1;
Paul Tan702cbaa2015-08-04 21:51:47 +0800155
156 git_config_get_bool("am.messageid", &state->message_id);
Paul Tan9b646612015-08-04 21:51:49 +0800157
158 state->scissors = SCISSORS_UNSET;
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +0700159 state->quoted_cr = quoted_cr_unset;
Paul Tan257e8ce2015-08-04 21:51:50 +0800160
Jeff King22f9b7f2020-07-28 16:24:27 -0400161 strvec_init(&state->git_apply_opts);
Paul Tan7e35dac2015-08-04 21:51:53 +0800162
163 if (!git_config_get_bool("commit.gpgsign", &gpgsign))
164 state->sign_commit = gpgsign ? "" : NULL;
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800165}
166
167/**
168 * Releases memory allocated by an am_state.
169 */
170static void am_state_release(struct am_state *state)
171{
172 free(state->dir);
Paul Tan3e20dcf2015-08-04 21:51:28 +0800173 free(state->author_name);
174 free(state->author_email);
175 free(state->author_date);
176 free(state->msg);
Jeff King22f9b7f2020-07-28 16:24:27 -0400177 strvec_clear(&state->git_apply_opts);
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800178}
179
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +0700180static int am_option_parse_quoted_cr(const struct option *opt,
181 const char *arg, int unset)
182{
183 BUG_ON_OPT_NEG(unset);
184
185 if (mailinfo_parse_quoted_cr_action(arg, opt->value) != 0)
186 return error(_("bad action '%s' for '%s'"), arg, "--quoted-cr");
187 return 0;
188}
189
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +0000190static int am_option_parse_empty(const struct option *opt,
191 const char *arg, int unset)
192{
193 int *opt_value = opt->value;
194
195 BUG_ON_OPT_NEG(unset);
196
197 if (!strcmp(arg, "stop"))
198 *opt_value = STOP_ON_EMPTY_COMMIT;
199 else if (!strcmp(arg, "drop"))
200 *opt_value = DROP_EMPTY_COMMIT;
201 else if (!strcmp(arg, "keep"))
202 *opt_value = KEEP_EMPTY_COMMIT;
203 else
Jean-Noël Avila1a8aea82022-01-31 22:07:47 +0000204 return error(_("invalid value for '%s': '%s'"), "--empty", arg);
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +0000205
206 return 0;
207}
208
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800209/**
210 * Returns path relative to the am_state directory.
211 */
212static inline const char *am_path(const struct am_state *state, const char *path)
213{
214 return mkpath("%s/%s", state->dir, path);
215}
216
217/**
Junio C Hamano25b763b2015-08-24 09:12:53 -0700218 * For convenience to call write_file()
219 */
René Scharfe1dad8792016-07-08 05:08:05 -0400220static void write_state_text(const struct am_state *state,
221 const char *name, const char *string)
Junio C Hamano25b763b2015-08-24 09:12:53 -0700222{
René Scharfe1dad8792016-07-08 05:08:05 -0400223 write_file(am_path(state, name), "%s", string);
Junio C Hamano25b763b2015-08-24 09:12:53 -0700224}
225
René Scharfe1dad8792016-07-08 05:08:05 -0400226static void write_state_count(const struct am_state *state,
227 const char *name, int value)
228{
229 write_file(am_path(state, name), "%d", value);
230}
231
232static void write_state_bool(const struct am_state *state,
Junio C Hamano25b763b2015-08-24 09:12:53 -0700233 const char *name, int value)
234{
René Scharfe1dad8792016-07-08 05:08:05 -0400235 write_state_text(state, name, value ? "t" : "f");
Junio C Hamano25b763b2015-08-24 09:12:53 -0700236}
237
238/**
Paul Tan5d28cf72015-08-04 21:51:37 +0800239 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
240 * at the end.
241 */
Ævar Arnfjörð Bjarmason48ca53c2021-07-13 10:05:18 +0200242__attribute__((format (printf, 3, 4)))
Paul Tan5d28cf72015-08-04 21:51:37 +0800243static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
244{
245 va_list ap;
246
247 va_start(ap, fmt);
248 if (!state->quiet) {
249 vfprintf(fp, fmt, ap);
250 putc('\n', fp);
251 }
252 va_end(ap);
253}
254
255/**
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800256 * Returns 1 if there is an am session in progress, 0 otherwise.
257 */
258static int am_in_progress(const struct am_state *state)
259{
260 struct stat st;
261
262 if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
263 return 0;
264 if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
265 return 0;
266 if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
267 return 0;
268 return 1;
269}
270
271/**
272 * Reads the contents of `file` in the `state` directory into `sb`. Returns the
273 * number of bytes read on success, -1 if the file does not exist. If `trim` is
274 * set, trailing whitespace will be removed.
275 */
276static int read_state_file(struct strbuf *sb, const struct am_state *state,
277 const char *file, int trim)
278{
279 strbuf_reset(sb);
280
281 if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
282 if (trim)
283 strbuf_trim(sb);
284
285 return sb->len;
286 }
287
288 if (errno == ENOENT)
289 return -1;
290
291 die_errno(_("could not read '%s'"), am_path(state, file));
292}
293
294/**
Paul Tan3e20dcf2015-08-04 21:51:28 +0800295 * Reads and parses the state directory's "author-script" file, and sets
296 * state->author_name, state->author_email and state->author_date accordingly.
297 * Returns 0 on success, -1 if the file could not be parsed.
298 *
299 * The author script is of the format:
300 *
301 * GIT_AUTHOR_NAME='$author_name'
302 * GIT_AUTHOR_EMAIL='$author_email'
303 * GIT_AUTHOR_DATE='$author_date'
304 *
305 * where $author_name, $author_email and $author_date are quoted. We are strict
306 * with our parsing, as the file was meant to be eval'd in the old git-am.sh
307 * script, and thus if the file differs from what this function expects, it is
308 * better to bail out than to do something that the user does not expect.
309 */
Phillip Wooda75d3512018-10-31 10:15:54 +0000310static int read_am_author_script(struct am_state *state)
Paul Tan3e20dcf2015-08-04 21:51:28 +0800311{
312 const char *filename = am_path(state, "author-script");
Paul Tan3e20dcf2015-08-04 21:51:28 +0800313
314 assert(!state->author_name);
315 assert(!state->author_email);
316 assert(!state->author_date);
317
Phillip Woodbcd33ec2018-10-31 10:15:55 +0000318 return read_author_script(filename, &state->author_name,
319 &state->author_email, &state->author_date, 1);
Paul Tan3e20dcf2015-08-04 21:51:28 +0800320}
321
322/**
323 * Saves state->author_name, state->author_email and state->author_date in the
324 * state directory's "author-script" file.
325 */
326static void write_author_script(const struct am_state *state)
327{
328 struct strbuf sb = STRBUF_INIT;
329
330 strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
331 sq_quote_buf(&sb, state->author_name);
332 strbuf_addch(&sb, '\n');
333
334 strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
335 sq_quote_buf(&sb, state->author_email);
336 strbuf_addch(&sb, '\n');
337
338 strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
339 sq_quote_buf(&sb, state->author_date);
340 strbuf_addch(&sb, '\n');
341
Junio C Hamano25b763b2015-08-24 09:12:53 -0700342 write_state_text(state, "author-script", sb.buf);
Paul Tan3e20dcf2015-08-04 21:51:28 +0800343
344 strbuf_release(&sb);
345}
346
347/**
348 * Reads the commit message from the state directory's "final-commit" file,
349 * setting state->msg to its contents and state->msg_len to the length of its
350 * contents in bytes.
351 *
352 * Returns 0 on success, -1 if the file does not exist.
353 */
354static int read_commit_msg(struct am_state *state)
355{
356 struct strbuf sb = STRBUF_INIT;
357
358 assert(!state->msg);
359
360 if (read_state_file(&sb, state, "final-commit", 0) < 0) {
361 strbuf_release(&sb);
362 return -1;
363 }
364
365 state->msg = strbuf_detach(&sb, &state->msg_len);
366 return 0;
367}
368
369/**
370 * Saves state->msg in the state directory's "final-commit" file.
371 */
372static void write_commit_msg(const struct am_state *state)
373{
Paul Tan3e20dcf2015-08-04 21:51:28 +0800374 const char *filename = am_path(state, "final-commit");
Jeff Kinge78d5d42016-07-08 05:12:55 -0400375 write_file_buf(filename, state->msg, state->msg_len);
Paul Tan3e20dcf2015-08-04 21:51:28 +0800376}
377
378/**
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800379 * Loads state from disk.
380 */
381static void am_load(struct am_state *state)
382{
383 struct strbuf sb = STRBUF_INIT;
384
385 if (read_state_file(&sb, state, "next", 1) < 0)
Johannes Schindelin033abf92018-05-02 11:38:39 +0200386 BUG("state file 'next' does not exist");
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800387 state->cur = strtol(sb.buf, NULL, 10);
388
389 if (read_state_file(&sb, state, "last", 1) < 0)
Johannes Schindelin033abf92018-05-02 11:38:39 +0200390 BUG("state file 'last' does not exist");
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800391 state->last = strtol(sb.buf, NULL, 10);
392
Phillip Wooda75d3512018-10-31 10:15:54 +0000393 if (read_am_author_script(state) < 0)
Paul Tan3e20dcf2015-08-04 21:51:28 +0800394 die(_("could not parse author script"));
395
396 read_commit_msg(state);
397
Paul Tan13b97ea2015-08-04 21:51:54 +0800398 if (read_state_file(&sb, state, "original-commit", 1) < 0)
brian m. carlson8c887692016-09-05 20:08:09 +0000399 oidclr(&state->orig_commit);
400 else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
Paul Tan13b97ea2015-08-04 21:51:54 +0800401 die(_("could not parse %s"), am_path(state, "original-commit"));
402
Paul Tan84f3de22015-08-04 21:51:41 +0800403 read_state_file(&sb, state, "threeway", 1);
404 state->threeway = !strcmp(sb.buf, "t");
405
Paul Tan5d28cf72015-08-04 21:51:37 +0800406 read_state_file(&sb, state, "quiet", 1);
407 state->quiet = !strcmp(sb.buf, "t");
408
Paul Taneb898b82015-08-04 21:51:39 +0800409 read_state_file(&sb, state, "sign", 1);
410 state->signoff = !strcmp(sb.buf, "t");
411
Paul Tanef7ee162015-08-04 21:51:45 +0800412 read_state_file(&sb, state, "utf8", 1);
413 state->utf8 = !strcmp(sb.buf, "t");
414
Phillip Woodfd4a3f42017-08-02 11:44:15 +0100415 if (file_exists(am_path(state, "rerere-autoupdate"))) {
416 read_state_file(&sb, state, "rerere-autoupdate", 1);
417 state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
418 RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
419 } else {
420 state->allow_rerere_autoupdate = 0;
421 }
422
Paul Tan4f1b6962015-08-04 21:51:46 +0800423 read_state_file(&sb, state, "keep", 1);
424 if (!strcmp(sb.buf, "t"))
425 state->keep = KEEP_TRUE;
426 else if (!strcmp(sb.buf, "b"))
427 state->keep = KEEP_NON_PATCH;
428 else
429 state->keep = KEEP_FALSE;
430
Paul Tan702cbaa2015-08-04 21:51:47 +0800431 read_state_file(&sb, state, "messageid", 1);
432 state->message_id = !strcmp(sb.buf, "t");
433
Paul Tan9b646612015-08-04 21:51:49 +0800434 read_state_file(&sb, state, "scissors", 1);
435 if (!strcmp(sb.buf, "t"))
436 state->scissors = SCISSORS_TRUE;
437 else if (!strcmp(sb.buf, "f"))
438 state->scissors = SCISSORS_FALSE;
439 else
440 state->scissors = SCISSORS_UNSET;
441
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +0700442 read_state_file(&sb, state, "quoted-cr", 1);
443 if (!*sb.buf)
444 state->quoted_cr = quoted_cr_unset;
445 else if (mailinfo_parse_quoted_cr_action(sb.buf, &state->quoted_cr) != 0)
446 die(_("could not parse %s"), am_path(state, "quoted-cr"));
447
Paul Tan257e8ce2015-08-04 21:51:50 +0800448 read_state_file(&sb, state, "apply-opt", 1);
Jeff King22f9b7f2020-07-28 16:24:27 -0400449 strvec_clear(&state->git_apply_opts);
Jeff King2745b6b2020-07-28 16:24:02 -0400450 if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
Paul Tan257e8ce2015-08-04 21:51:50 +0800451 die(_("could not parse %s"), am_path(state, "apply-opt"));
452
Paul Tan35bdcc52015-08-04 21:51:42 +0800453 state->rebasing = !!file_exists(am_path(state, "rebasing"));
454
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800455 strbuf_release(&sb);
456}
457
458/**
459 * Removes the am_state directory, forcefully terminating the current am
460 * session.
461 */
462static void am_destroy(const struct am_state *state)
463{
464 struct strbuf sb = STRBUF_INIT;
465
466 strbuf_addstr(&sb, state->dir);
467 remove_dir_recursively(&sb, 0);
468 strbuf_release(&sb);
469}
470
471/**
Paul Tanb8803d82015-08-04 21:51:56 +0800472 * Runs applypatch-msg hook. Returns its exit code.
473 */
474static int run_applypatch_msg_hook(struct am_state *state)
475{
Thierry Reding566902f2022-11-30 18:28:33 +0100476 int ret = 0;
Paul Tanb8803d82015-08-04 21:51:56 +0800477
478 assert(state->msg);
Thierry Reding566902f2022-11-30 18:28:33 +0100479
480 if (!state->no_verify)
481 ret = run_hooks_l("applypatch-msg", am_path(state, "final-commit"), NULL);
Paul Tanb8803d82015-08-04 21:51:56 +0800482
483 if (!ret) {
Ævar Arnfjörð Bjarmason6a83d902017-06-15 23:15:46 +0000484 FREE_AND_NULL(state->msg);
Paul Tanb8803d82015-08-04 21:51:56 +0800485 if (read_commit_msg(state) < 0)
486 die(_("'%s' was deleted by the applypatch-msg hook"),
487 am_path(state, "final-commit"));
488 }
489
490 return ret;
491}
492
493/**
Paul Tan13b97ea2015-08-04 21:51:54 +0800494 * Runs post-rewrite hook. Returns it exit code.
495 */
496static int run_post_rewrite_hook(const struct am_state *state)
497{
498 struct child_process cp = CHILD_PROCESS_INIT;
499 const char *hook = find_hook("post-rewrite");
500 int ret;
501
502 if (!hook)
503 return 0;
504
Jeff King22f9b7f2020-07-28 16:24:27 -0400505 strvec_push(&cp.args, hook);
506 strvec_push(&cp.args, "rebase");
Paul Tan13b97ea2015-08-04 21:51:54 +0800507
508 cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
509 cp.stdout_to_stderr = 1;
Jeff Hostetler62062862019-02-22 14:25:06 -0800510 cp.trace2_hook_name = "post-rewrite";
Paul Tan13b97ea2015-08-04 21:51:54 +0800511
512 ret = run_command(&cp);
513
514 close(cp.in);
515 return ret;
516}
517
518/**
Paul Tan88b291f2015-08-04 21:51:55 +0800519 * Reads the state directory's "rewritten" file, and copies notes from the old
520 * commits listed in the file to their rewritten commits.
521 *
522 * Returns 0 on success, -1 on failure.
523 */
524static int copy_notes_for_rebase(const struct am_state *state)
525{
526 struct notes_rewrite_cfg *c;
527 struct strbuf sb = STRBUF_INIT;
528 const char *invalid_line = _("Malformed input line: '%s'.");
529 const char *msg = "Notes added by 'git rebase'";
530 FILE *fp;
531 int ret = 0;
532
533 assert(state->rebasing);
534
535 c = init_copy_notes_for_rewrite("rebase");
536 if (!c)
537 return 0;
538
539 fp = xfopen(am_path(state, "rewritten"), "r");
540
Junio C Hamano8f309ae2016-01-13 15:31:17 -0800541 while (!strbuf_getline_lf(&sb, fp)) {
brian m. carlson8c887692016-09-05 20:08:09 +0000542 struct object_id from_obj, to_obj;
brian m. carlson24dd3632019-02-19 00:05:07 +0000543 const char *p;
Paul Tan88b291f2015-08-04 21:51:55 +0800544
brian m. carlson24dd3632019-02-19 00:05:07 +0000545 if (sb.len != the_hash_algo->hexsz * 2 + 1) {
Paul Tan88b291f2015-08-04 21:51:55 +0800546 ret = error(invalid_line, sb.buf);
547 goto finish;
548 }
549
brian m. carlson24dd3632019-02-19 00:05:07 +0000550 if (parse_oid_hex(sb.buf, &from_obj, &p)) {
Paul Tan88b291f2015-08-04 21:51:55 +0800551 ret = error(invalid_line, sb.buf);
552 goto finish;
553 }
554
brian m. carlson24dd3632019-02-19 00:05:07 +0000555 if (*p != ' ') {
Paul Tan88b291f2015-08-04 21:51:55 +0800556 ret = error(invalid_line, sb.buf);
557 goto finish;
558 }
559
brian m. carlson24dd3632019-02-19 00:05:07 +0000560 if (get_oid_hex(p + 1, &to_obj)) {
Paul Tan88b291f2015-08-04 21:51:55 +0800561 ret = error(invalid_line, sb.buf);
562 goto finish;
563 }
564
brian m. carlsonbb7e4732017-05-30 10:30:42 -0700565 if (copy_note_for_rewrite(c, &from_obj, &to_obj))
Paul Tan88b291f2015-08-04 21:51:55 +0800566 ret = error(_("Failed to copy notes from '%s' to '%s'"),
brian m. carlson8c887692016-09-05 20:08:09 +0000567 oid_to_hex(&from_obj), oid_to_hex(&to_obj));
Paul Tan88b291f2015-08-04 21:51:55 +0800568 }
569
570finish:
Nguyễn Thái Ngọc Duy1d18d752019-01-12 09:13:23 +0700571 finish_copy_notes_for_rewrite(the_repository, c, msg);
Paul Tan88b291f2015-08-04 21:51:55 +0800572 fclose(fp);
573 strbuf_release(&sb);
574 return ret;
575}
576
577/**
Paul Tanc29807b2015-08-04 21:51:27 +0800578 * Determines if the file looks like a piece of RFC2822 mail by grabbing all
579 * non-indented lines and checking if they look like they begin with valid
580 * header field names.
581 *
582 * Returns 1 if the file looks like a piece of mail, 0 otherwise.
583 */
584static int is_mail(FILE *fp)
585{
586 const char *header_regex = "^[!-9;-~]+:";
587 struct strbuf sb = STRBUF_INIT;
588 regex_t regex;
589 int ret = 1;
590
591 if (fseek(fp, 0L, SEEK_SET))
592 die_errno(_("fseek failed"));
593
594 if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
595 die("invalid pattern: %s", header_regex);
596
Junio C Hamano1a0c8df2016-01-13 18:32:23 -0800597 while (!strbuf_getline(&sb, fp)) {
Paul Tanc29807b2015-08-04 21:51:27 +0800598 if (!sb.len)
599 break; /* End of header */
600
601 /* Ignore indented folded lines */
602 if (*sb.buf == '\t' || *sb.buf == ' ')
603 continue;
604
605 /* It's a header if it matches header_regex */
606 if (regexec(&regex, sb.buf, 0, NULL, 0)) {
607 ret = 0;
608 goto done;
609 }
610 }
611
612done:
613 regfree(&regex);
614 strbuf_release(&sb);
615 return ret;
616}
617
618/**
619 * Attempts to detect the patch_format of the patches contained in `paths`,
620 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
621 * detection fails.
622 */
623static int detect_patch_format(const char **paths)
624{
625 enum patch_format ret = PATCH_FORMAT_UNKNOWN;
626 struct strbuf l1 = STRBUF_INIT;
Paul Tan5ae41c72015-08-04 21:52:00 +0800627 struct strbuf l2 = STRBUF_INIT;
628 struct strbuf l3 = STRBUF_INIT;
Paul Tanc29807b2015-08-04 21:51:27 +0800629 FILE *fp;
630
631 /*
632 * We default to mbox format if input is from stdin and for directories
633 */
634 if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
635 return PATCH_FORMAT_MBOX;
636
637 /*
638 * Otherwise, check the first few lines of the first patch, starting
639 * from the first non-blank line, to try to detect its format.
640 */
641
642 fp = xfopen(*paths, "r");
643
Junio C Hamano1a0c8df2016-01-13 18:32:23 -0800644 while (!strbuf_getline(&l1, fp)) {
Paul Tanc29807b2015-08-04 21:51:27 +0800645 if (l1.len)
646 break;
647 }
648
649 if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
650 ret = PATCH_FORMAT_MBOX;
651 goto done;
652 }
653
Paul Tan336108c2015-08-04 21:52:01 +0800654 if (starts_with(l1.buf, "# This series applies on GIT commit")) {
655 ret = PATCH_FORMAT_STGIT_SERIES;
656 goto done;
657 }
658
Paul Tan94cd1752015-08-04 21:52:02 +0800659 if (!strcmp(l1.buf, "# HG changeset patch")) {
660 ret = PATCH_FORMAT_HG;
661 goto done;
662 }
663
Junio C Hamano1a0c8df2016-01-13 18:32:23 -0800664 strbuf_getline(&l2, fp);
Junio C Hamano1a0c8df2016-01-13 18:32:23 -0800665 strbuf_getline(&l3, fp);
Paul Tan5ae41c72015-08-04 21:52:00 +0800666
667 /*
668 * If the second line is empty and the third is a From, Author or Date
669 * entry, this is likely an StGit patch.
670 */
671 if (l1.len && !l2.len &&
672 (starts_with(l3.buf, "From:") ||
673 starts_with(l3.buf, "Author:") ||
674 starts_with(l3.buf, "Date:"))) {
675 ret = PATCH_FORMAT_STGIT;
676 goto done;
677 }
678
Paul Tanc29807b2015-08-04 21:51:27 +0800679 if (l1.len && is_mail(fp)) {
680 ret = PATCH_FORMAT_MBOX;
681 goto done;
682 }
683
684done:
685 fclose(fp);
686 strbuf_release(&l1);
Rene Scharfe542627a2017-08-30 19:49:32 +0200687 strbuf_release(&l2);
688 strbuf_release(&l3);
Paul Tanc29807b2015-08-04 21:51:27 +0800689 return ret;
690}
691
692/**
Paul Tan11c21772015-08-04 21:51:26 +0800693 * Splits out individual email patches from `paths`, where each path is either
694 * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
695 */
Eric Wongd9925d12016-06-05 04:46:41 +0000696static int split_mail_mbox(struct am_state *state, const char **paths,
697 int keep_cr, int mboxrd)
Paul Tan11c21772015-08-04 21:51:26 +0800698{
699 struct child_process cp = CHILD_PROCESS_INIT;
700 struct strbuf last = STRBUF_INIT;
René Scharfe1b090732017-12-07 21:20:19 +0100701 int ret;
Paul Tan11c21772015-08-04 21:51:26 +0800702
703 cp.git_cmd = 1;
Jeff King22f9b7f2020-07-28 16:24:27 -0400704 strvec_push(&cp.args, "mailsplit");
705 strvec_pushf(&cp.args, "-d%d", state->prec);
706 strvec_pushf(&cp.args, "-o%s", state->dir);
707 strvec_push(&cp.args, "-b");
Paul Tan5d123a42015-08-04 21:51:48 +0800708 if (keep_cr)
Jeff King22f9b7f2020-07-28 16:24:27 -0400709 strvec_push(&cp.args, "--keep-cr");
Eric Wongd9925d12016-06-05 04:46:41 +0000710 if (mboxrd)
Jeff King22f9b7f2020-07-28 16:24:27 -0400711 strvec_push(&cp.args, "--mboxrd");
712 strvec_push(&cp.args, "--");
713 strvec_pushv(&cp.args, paths);
Paul Tan11c21772015-08-04 21:51:26 +0800714
René Scharfe1b090732017-12-07 21:20:19 +0100715 ret = capture_command(&cp, &last, 8);
716 if (ret)
717 goto exit;
Paul Tan11c21772015-08-04 21:51:26 +0800718
719 state->cur = 1;
720 state->last = strtol(last.buf, NULL, 10);
721
René Scharfe1b090732017-12-07 21:20:19 +0100722exit:
723 strbuf_release(&last);
724 return ret ? -1 : 0;
Paul Tan11c21772015-08-04 21:51:26 +0800725}
726
727/**
Paul Tan5ae41c72015-08-04 21:52:00 +0800728 * Callback signature for split_mail_conv(). The foreign patch should be
729 * read from `in`, and the converted patch (in RFC2822 mail format) should be
730 * written to `out`. Return 0 on success, or -1 on failure.
731 */
732typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
733
734/**
735 * Calls `fn` for each file in `paths` to convert the foreign patch to the
736 * RFC2822 mail format suitable for parsing with git-mailinfo.
737 *
738 * Returns 0 on success, -1 on failure.
739 */
740static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
741 const char **paths, int keep_cr)
742{
743 static const char *stdin_only[] = {"-", NULL};
744 int i;
745
746 if (!*paths)
747 paths = stdin_only;
748
749 for (i = 0; *paths; paths++, i++) {
750 FILE *in, *out;
751 const char *mail;
752 int ret;
753
754 if (!strcmp(*paths, "-"))
755 in = stdin;
756 else
757 in = fopen(*paths, "r");
758
759 if (!in)
Nguyễn Thái Ngọc Duy6e59e9c2016-05-08 16:47:24 +0700760 return error_errno(_("could not open '%s' for reading"),
761 *paths);
Paul Tan5ae41c72015-08-04 21:52:00 +0800762
763 mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
764
765 out = fopen(mail, "w");
René Scharfeac8ce182017-04-16 18:55:30 +0200766 if (!out) {
767 if (in != stdin)
768 fclose(in);
Nguyễn Thái Ngọc Duy6e59e9c2016-05-08 16:47:24 +0700769 return error_errno(_("could not open '%s' for writing"),
770 mail);
René Scharfeac8ce182017-04-16 18:55:30 +0200771 }
Paul Tan5ae41c72015-08-04 21:52:00 +0800772
773 ret = fn(out, in, keep_cr);
774
775 fclose(out);
René Scharfeac8ce182017-04-16 18:55:30 +0200776 if (in != stdin)
777 fclose(in);
Paul Tan5ae41c72015-08-04 21:52:00 +0800778
779 if (ret)
780 return error(_("could not parse patch '%s'"), *paths);
781 }
782
783 state->cur = 1;
784 state->last = i;
785 return 0;
786}
787
788/**
789 * A split_mail_conv() callback that converts an StGit patch to an RFC2822
790 * message suitable for parsing with git-mailinfo.
791 */
792static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
793{
794 struct strbuf sb = STRBUF_INIT;
795 int subject_printed = 0;
796
Junio C Hamano8f309ae2016-01-13 15:31:17 -0800797 while (!strbuf_getline_lf(&sb, in)) {
Paul Tan5ae41c72015-08-04 21:52:00 +0800798 const char *str;
799
800 if (str_isspace(sb.buf))
801 continue;
802 else if (skip_prefix(sb.buf, "Author:", &str))
803 fprintf(out, "From:%s\n", str);
804 else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
805 fprintf(out, "%s\n", sb.buf);
806 else if (!subject_printed) {
807 fprintf(out, "Subject: %s\n", sb.buf);
808 subject_printed = 1;
809 } else {
810 fprintf(out, "\n%s\n", sb.buf);
811 break;
812 }
813 }
814
815 strbuf_reset(&sb);
816 while (strbuf_fread(&sb, 8192, in) > 0) {
817 fwrite(sb.buf, 1, sb.len, out);
818 strbuf_reset(&sb);
819 }
820
821 strbuf_release(&sb);
822 return 0;
823}
824
825/**
Paul Tan336108c2015-08-04 21:52:01 +0800826 * This function only supports a single StGit series file in `paths`.
827 *
828 * Given an StGit series file, converts the StGit patches in the series into
829 * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
830 * the state directory.
831 *
832 * Returns 0 on success, -1 on failure.
833 */
834static int split_mail_stgit_series(struct am_state *state, const char **paths,
835 int keep_cr)
836{
837 const char *series_dir;
838 char *series_dir_buf;
839 FILE *fp;
Jeff King22f9b7f2020-07-28 16:24:27 -0400840 struct strvec patches = STRVEC_INIT;
Paul Tan336108c2015-08-04 21:52:01 +0800841 struct strbuf sb = STRBUF_INIT;
842 int ret;
843
844 if (!paths[0] || paths[1])
845 return error(_("Only one StGIT patch series can be applied at once"));
846
847 series_dir_buf = xstrdup(*paths);
848 series_dir = dirname(series_dir_buf);
849
850 fp = fopen(*paths, "r");
851 if (!fp)
Nguyễn Thái Ngọc Duy6e59e9c2016-05-08 16:47:24 +0700852 return error_errno(_("could not open '%s' for reading"), *paths);
Paul Tan336108c2015-08-04 21:52:01 +0800853
Junio C Hamano8f309ae2016-01-13 15:31:17 -0800854 while (!strbuf_getline_lf(&sb, fp)) {
Paul Tan336108c2015-08-04 21:52:01 +0800855 if (*sb.buf == '#')
856 continue; /* skip comment lines */
857
Jeff King22f9b7f2020-07-28 16:24:27 -0400858 strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
Paul Tan336108c2015-08-04 21:52:01 +0800859 }
860
861 fclose(fp);
862 strbuf_release(&sb);
863 free(series_dir_buf);
864
Jeff Kingd70a9eb2020-07-28 20:37:20 -0400865 ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
Paul Tan336108c2015-08-04 21:52:01 +0800866
Jeff King22f9b7f2020-07-28 16:24:27 -0400867 strvec_clear(&patches);
Paul Tan336108c2015-08-04 21:52:01 +0800868 return ret;
869}
870
871/**
Paul Tan94cd1752015-08-04 21:52:02 +0800872 * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
873 * message suitable for parsing with git-mailinfo.
874 */
875static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
876{
877 struct strbuf sb = STRBUF_INIT;
Rene Scharfeb36474f2017-08-30 19:49:33 +0200878 int rc = 0;
Paul Tan94cd1752015-08-04 21:52:02 +0800879
Junio C Hamano8f309ae2016-01-13 15:31:17 -0800880 while (!strbuf_getline_lf(&sb, in)) {
Paul Tan94cd1752015-08-04 21:52:02 +0800881 const char *str;
882
883 if (skip_prefix(sb.buf, "# User ", &str))
884 fprintf(out, "From: %s\n", str);
885 else if (skip_prefix(sb.buf, "# Date ", &str)) {
Johannes Schindelindddbad72017-04-26 21:29:31 +0200886 timestamp_t timestamp;
Paul Tan94cd1752015-08-04 21:52:02 +0800887 long tz, tz2;
888 char *end;
889
890 errno = 0;
Johannes Schindelin1aeb7e72017-04-21 12:45:44 +0200891 timestamp = parse_timestamp(str, &end, 10);
Rene Scharfeb36474f2017-08-30 19:49:33 +0200892 if (errno) {
893 rc = error(_("invalid timestamp"));
894 goto exit;
895 }
Paul Tan94cd1752015-08-04 21:52:02 +0800896
Rene Scharfeb36474f2017-08-30 19:49:33 +0200897 if (!skip_prefix(end, " ", &str)) {
898 rc = error(_("invalid Date line"));
899 goto exit;
900 }
Paul Tan94cd1752015-08-04 21:52:02 +0800901
902 errno = 0;
903 tz = strtol(str, &end, 10);
Rene Scharfeb36474f2017-08-30 19:49:33 +0200904 if (errno) {
905 rc = error(_("invalid timezone offset"));
906 goto exit;
907 }
Paul Tan94cd1752015-08-04 21:52:02 +0800908
Rene Scharfeb36474f2017-08-30 19:49:33 +0200909 if (*end) {
910 rc = error(_("invalid Date line"));
911 goto exit;
912 }
Paul Tan94cd1752015-08-04 21:52:02 +0800913
914 /*
915 * mercurial's timezone is in seconds west of UTC,
916 * however git's timezone is in hours + minutes east of
917 * UTC. Convert it.
918 */
919 tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
920 if (tz > 0)
921 tz2 = -tz2;
922
923 fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
924 } else if (starts_with(sb.buf, "# ")) {
925 continue;
926 } else {
927 fprintf(out, "\n%s\n", sb.buf);
928 break;
929 }
930 }
931
932 strbuf_reset(&sb);
933 while (strbuf_fread(&sb, 8192, in) > 0) {
934 fwrite(sb.buf, 1, sb.len, out);
935 strbuf_reset(&sb);
936 }
Rene Scharfeb36474f2017-08-30 19:49:33 +0200937exit:
Paul Tan94cd1752015-08-04 21:52:02 +0800938 strbuf_release(&sb);
Rene Scharfeb36474f2017-08-30 19:49:33 +0200939 return rc;
Paul Tan94cd1752015-08-04 21:52:02 +0800940}
941
942/**
Paul Tan11c21772015-08-04 21:51:26 +0800943 * Splits a list of files/directories into individual email patches. Each path
944 * in `paths` must be a file/directory that is formatted according to
945 * `patch_format`.
946 *
947 * Once split out, the individual email patches will be stored in the state
948 * directory, with each patch's filename being its index, padded to state->prec
949 * digits.
950 *
951 * state->cur will be set to the index of the first mail, and state->last will
952 * be set to the index of the last mail.
953 *
Paul Tan5d123a42015-08-04 21:51:48 +0800954 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
955 * to disable this behavior, -1 to use the default configured setting.
956 *
Paul Tan11c21772015-08-04 21:51:26 +0800957 * Returns 0 on success, -1 on failure.
958 */
959static int split_mail(struct am_state *state, enum patch_format patch_format,
Paul Tan5d123a42015-08-04 21:51:48 +0800960 const char **paths, int keep_cr)
Paul Tan11c21772015-08-04 21:51:26 +0800961{
Paul Tan5d123a42015-08-04 21:51:48 +0800962 if (keep_cr < 0) {
963 keep_cr = 0;
964 git_config_get_bool("am.keepcr", &keep_cr);
965 }
966
Paul Tan11c21772015-08-04 21:51:26 +0800967 switch (patch_format) {
968 case PATCH_FORMAT_MBOX:
Eric Wongd9925d12016-06-05 04:46:41 +0000969 return split_mail_mbox(state, paths, keep_cr, 0);
Paul Tan5ae41c72015-08-04 21:52:00 +0800970 case PATCH_FORMAT_STGIT:
971 return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
Paul Tan336108c2015-08-04 21:52:01 +0800972 case PATCH_FORMAT_STGIT_SERIES:
973 return split_mail_stgit_series(state, paths, keep_cr);
Paul Tan94cd1752015-08-04 21:52:02 +0800974 case PATCH_FORMAT_HG:
975 return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
Eric Wongd9925d12016-06-05 04:46:41 +0000976 case PATCH_FORMAT_MBOXRD:
977 return split_mail_mbox(state, paths, keep_cr, 1);
Paul Tan11c21772015-08-04 21:51:26 +0800978 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +0200979 BUG("invalid patch_format");
Paul Tan11c21772015-08-04 21:51:26 +0800980 }
981 return -1;
982}
983
984/**
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800985 * Setup a new am session for applying patches
986 */
Paul Tan11c21772015-08-04 21:51:26 +0800987static void am_setup(struct am_state *state, enum patch_format patch_format,
Paul Tan5d123a42015-08-04 21:51:48 +0800988 const char **paths, int keep_cr)
Paul Tan8c3bd9e2015-08-04 21:51:25 +0800989{
brian m. carlson8c887692016-09-05 20:08:09 +0000990 struct object_id curr_head;
Paul Tan4f1b6962015-08-04 21:51:46 +0800991 const char *str;
Paul Tan257e8ce2015-08-04 21:51:50 +0800992 struct strbuf sb = STRBUF_INIT;
Paul Tan33388a72015-08-04 21:51:35 +0800993
Paul Tanc29807b2015-08-04 21:51:27 +0800994 if (!patch_format)
995 patch_format = detect_patch_format(paths);
996
997 if (!patch_format) {
998 fprintf_ln(stderr, _("Patch format detection failed."));
999 exit(128);
1000 }
1001
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001002 if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
1003 die_errno(_("failed to create directory '%s'"), state->dir);
Nguyễn Thái Ngọc Duyfbd7a232018-02-11 16:43:28 +07001004 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001005
Paul Tan5d123a42015-08-04 21:51:48 +08001006 if (split_mail(state, patch_format, paths, keep_cr) < 0) {
Paul Tan11c21772015-08-04 21:51:26 +08001007 am_destroy(state);
1008 die(_("Failed to split patches."));
1009 }
1010
Paul Tan35bdcc52015-08-04 21:51:42 +08001011 if (state->rebasing)
1012 state->threeway = 1;
1013
Junio C Hamano25b763b2015-08-24 09:12:53 -07001014 write_state_bool(state, "threeway", state->threeway);
1015 write_state_bool(state, "quiet", state->quiet);
1016 write_state_bool(state, "sign", state->signoff);
1017 write_state_bool(state, "utf8", state->utf8);
Paul Tanef7ee162015-08-04 21:51:45 +08001018
Phillip Woodfd4a3f42017-08-02 11:44:15 +01001019 if (state->allow_rerere_autoupdate)
1020 write_state_bool(state, "rerere-autoupdate",
1021 state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
1022
Paul Tan4f1b6962015-08-04 21:51:46 +08001023 switch (state->keep) {
1024 case KEEP_FALSE:
1025 str = "f";
1026 break;
1027 case KEEP_TRUE:
1028 str = "t";
1029 break;
1030 case KEEP_NON_PATCH:
1031 str = "b";
1032 break;
1033 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +02001034 BUG("invalid value for state->keep");
Paul Tan4f1b6962015-08-04 21:51:46 +08001035 }
1036
Junio C Hamano25b763b2015-08-24 09:12:53 -07001037 write_state_text(state, "keep", str);
1038 write_state_bool(state, "messageid", state->message_id);
Paul Tan702cbaa2015-08-04 21:51:47 +08001039
Paul Tan9b646612015-08-04 21:51:49 +08001040 switch (state->scissors) {
1041 case SCISSORS_UNSET:
1042 str = "";
1043 break;
1044 case SCISSORS_FALSE:
1045 str = "f";
1046 break;
1047 case SCISSORS_TRUE:
1048 str = "t";
1049 break;
1050 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +02001051 BUG("invalid value for state->scissors");
Paul Tan9b646612015-08-04 21:51:49 +08001052 }
Junio C Hamano25b763b2015-08-24 09:12:53 -07001053 write_state_text(state, "scissors", str);
Paul Tan9b646612015-08-04 21:51:49 +08001054
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +07001055 switch (state->quoted_cr) {
1056 case quoted_cr_unset:
1057 str = "";
1058 break;
1059 case quoted_cr_nowarn:
1060 str = "nowarn";
1061 break;
1062 case quoted_cr_warn:
1063 str = "warn";
1064 break;
1065 case quoted_cr_strip:
1066 str = "strip";
1067 break;
1068 default:
1069 BUG("invalid value for state->quoted_cr");
1070 }
1071 write_state_text(state, "quoted-cr", str);
1072
Jeff Kingd70a9eb2020-07-28 20:37:20 -04001073 sq_quote_argv(&sb, state->git_apply_opts.v);
Junio C Hamano25b763b2015-08-24 09:12:53 -07001074 write_state_text(state, "apply-opt", sb.buf);
Paul Tan257e8ce2015-08-04 21:51:50 +08001075
Paul Tan35bdcc52015-08-04 21:51:42 +08001076 if (state->rebasing)
Junio C Hamano25b763b2015-08-24 09:12:53 -07001077 write_state_text(state, "rebasing", "");
Paul Tan35bdcc52015-08-04 21:51:42 +08001078 else
Junio C Hamano25b763b2015-08-24 09:12:53 -07001079 write_state_text(state, "applying", "");
Paul Tan35bdcc52015-08-04 21:51:42 +08001080
brian m. carlson8c887692016-09-05 20:08:09 +00001081 if (!get_oid("HEAD", &curr_head)) {
1082 write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
Paul Tan35bdcc52015-08-04 21:51:42 +08001083 if (!state->rebasing)
brian m. carlsonae077772017-10-15 22:06:51 +00001084 update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
1085 UPDATE_REFS_DIE_ON_ERR);
Paul Tan33388a72015-08-04 21:51:35 +08001086 } else {
Junio C Hamano25b763b2015-08-24 09:12:53 -07001087 write_state_text(state, "abort-safety", "");
Paul Tan35bdcc52015-08-04 21:51:42 +08001088 if (!state->rebasing)
Kyle Meyer755b49a2017-02-20 20:10:32 -05001089 delete_ref(NULL, "ORIG_HEAD", NULL, 0);
Paul Tan33388a72015-08-04 21:51:35 +08001090 }
1091
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001092 /*
1093 * NOTE: Since the "next" and "last" files determine if an am_state
1094 * session is in progress, they should be written last.
1095 */
1096
Junio C Hamano25b763b2015-08-24 09:12:53 -07001097 write_state_count(state, "next", state->cur);
1098 write_state_count(state, "last", state->last);
Paul Tan257e8ce2015-08-04 21:51:50 +08001099
1100 strbuf_release(&sb);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001101}
1102
1103/**
1104 * Increments the patch pointer, and cleans am_state for the application of the
1105 * next patch.
1106 */
1107static void am_next(struct am_state *state)
1108{
brian m. carlson8c887692016-09-05 20:08:09 +00001109 struct object_id head;
Paul Tan33388a72015-08-04 21:51:35 +08001110
Ævar Arnfjörð Bjarmason88ce3ef2017-06-15 23:15:49 +00001111 FREE_AND_NULL(state->author_name);
1112 FREE_AND_NULL(state->author_email);
1113 FREE_AND_NULL(state->author_date);
1114 FREE_AND_NULL(state->msg);
Paul Tan3e20dcf2015-08-04 21:51:28 +08001115 state->msg_len = 0;
1116
1117 unlink(am_path(state, "author-script"));
1118 unlink(am_path(state, "final-commit"));
1119
brian m. carlson8c887692016-09-05 20:08:09 +00001120 oidclr(&state->orig_commit);
Paul Tan13b97ea2015-08-04 21:51:54 +08001121 unlink(am_path(state, "original-commit"));
Nguyễn Thái Ngọc Duyfbd7a232018-02-11 16:43:28 +07001122 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
Paul Tan13b97ea2015-08-04 21:51:54 +08001123
brian m. carlson8c887692016-09-05 20:08:09 +00001124 if (!get_oid("HEAD", &head))
1125 write_state_text(state, "abort-safety", oid_to_hex(&head));
Paul Tan33388a72015-08-04 21:51:35 +08001126 else
Junio C Hamano25b763b2015-08-24 09:12:53 -07001127 write_state_text(state, "abort-safety", "");
Paul Tan33388a72015-08-04 21:51:35 +08001128
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001129 state->cur++;
Junio C Hamano25b763b2015-08-24 09:12:53 -07001130 write_state_count(state, "next", state->cur);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001131}
1132
1133/**
Paul Tan3e20dcf2015-08-04 21:51:28 +08001134 * Returns the filename of the current patch email.
1135 */
1136static const char *msgnum(const struct am_state *state)
1137{
1138 static struct strbuf sb = STRBUF_INIT;
1139
1140 strbuf_reset(&sb);
1141 strbuf_addf(&sb, "%0*d", state->prec, state->cur);
1142
1143 return sb.buf;
1144}
1145
1146/**
Paul Tan2d831092015-08-04 21:51:38 +08001147 * Dies with a user-friendly message on how to proceed after resolving the
1148 * problem. This message can be overridden with state->resolvemsg.
1149 */
1150static void NORETURN die_user_resolve(const struct am_state *state)
1151{
1152 if (state->resolvemsg) {
1153 printf_ln("%s", state->resolvemsg);
1154 } else {
Paul Tan7ff26832015-08-04 21:52:03 +08001155 const char *cmdline = state->interactive ? "git am -i" : "git am";
Paul Tan2d831092015-08-04 21:51:38 +08001156
1157 printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
1158 printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00001159
1160 if (advice_enabled(ADVICE_AM_WORK_DIR) &&
1161 is_empty_or_missing_file(am_path(state, "patch")) &&
1162 !repo_index_has_changes(the_repository, NULL, NULL))
1163 printf_ln(_("To record the empty patch as an empty commit, run \"%s --allow-empty\"."), cmdline);
1164
Paul Tan2d831092015-08-04 21:51:38 +08001165 printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
1166 }
1167
1168 exit(128);
1169}
1170
1171/**
Paul Tanb5e82352015-08-04 22:08:51 +08001172 * Appends signoff to the "msg" field of the am_state.
1173 */
1174static void am_append_signoff(struct am_state *state)
1175{
1176 struct strbuf sb = STRBUF_INIT;
1177
1178 strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
Phillip Wood735285b2017-08-08 11:25:33 +01001179 append_signoff(&sb, 0, 0);
Paul Tanb5e82352015-08-04 22:08:51 +08001180 state->msg = strbuf_detach(&sb, &state->msg_len);
1181}
1182
1183/**
Paul Tan3e20dcf2015-08-04 21:51:28 +08001184 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
1185 * state->msg will be set to the patch message. state->author_name,
1186 * state->author_email and state->author_date will be set to the patch author's
1187 * name, email and date respectively. The patch body will be written to the
1188 * state directory's "patch" file.
1189 *
1190 * Returns 1 if the patch should be skipped, 0 otherwise.
1191 */
1192static int parse_mail(struct am_state *state, const char *mail)
1193{
1194 FILE *fp;
Paul Tan3e20dcf2015-08-04 21:51:28 +08001195 struct strbuf sb = STRBUF_INIT;
1196 struct strbuf msg = STRBUF_INIT;
1197 struct strbuf author_name = STRBUF_INIT;
1198 struct strbuf author_date = STRBUF_INIT;
1199 struct strbuf author_email = STRBUF_INIT;
1200 int ret = 0;
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001201 struct mailinfo mi;
Paul Tan3e20dcf2015-08-04 21:51:28 +08001202
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001203 setup_mailinfo(&mi);
Paul Tan3e20dcf2015-08-04 21:51:28 +08001204
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001205 if (state->utf8)
1206 mi.metainfo_charset = get_commit_output_encoding();
1207 else
1208 mi.metainfo_charset = NULL;
Paul Tan4f1b6962015-08-04 21:51:46 +08001209
1210 switch (state->keep) {
1211 case KEEP_FALSE:
1212 break;
1213 case KEEP_TRUE:
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001214 mi.keep_subject = 1;
Paul Tan4f1b6962015-08-04 21:51:46 +08001215 break;
1216 case KEEP_NON_PATCH:
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001217 mi.keep_non_patch_brackets_in_subject = 1;
Paul Tan4f1b6962015-08-04 21:51:46 +08001218 break;
1219 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +02001220 BUG("invalid value for state->keep");
Paul Tan4f1b6962015-08-04 21:51:46 +08001221 }
1222
Paul Tan702cbaa2015-08-04 21:51:47 +08001223 if (state->message_id)
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001224 mi.add_message_id = 1;
Paul Tan702cbaa2015-08-04 21:51:47 +08001225
Paul Tan9b646612015-08-04 21:51:49 +08001226 switch (state->scissors) {
1227 case SCISSORS_UNSET:
1228 break;
1229 case SCISSORS_FALSE:
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001230 mi.use_scissors = 0;
Paul Tan9b646612015-08-04 21:51:49 +08001231 break;
1232 case SCISSORS_TRUE:
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001233 mi.use_scissors = 1;
Paul Tan9b646612015-08-04 21:51:49 +08001234 break;
1235 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +02001236 BUG("invalid value for state->scissors");
Paul Tan9b646612015-08-04 21:51:49 +08001237 }
1238
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +07001239 switch (state->quoted_cr) {
1240 case quoted_cr_unset:
1241 break;
1242 case quoted_cr_nowarn:
1243 case quoted_cr_warn:
1244 case quoted_cr_strip:
1245 mi.quoted_cr = state->quoted_cr;
1246 break;
1247 default:
1248 BUG("invalid value for state->quoted_cr");
1249 }
1250
Nguyễn Thái Ngọc Duy23a9e072017-05-03 17:16:46 +07001251 mi.input = xfopen(mail, "r");
1252 mi.output = xfopen(am_path(state, "info"), "w");
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001253 if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
Paul Tan3e20dcf2015-08-04 21:51:28 +08001254 die("could not parse patch");
1255
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001256 fclose(mi.input);
1257 fclose(mi.output);
Paul Tan3e20dcf2015-08-04 21:51:28 +08001258
René Scharfe3aa4d812018-08-25 23:50:32 +02001259 if (mi.format_flowed)
1260 warning(_("Patch sent with format=flowed; "
1261 "space at the end of lines might be lost."));
1262
Paul Tan3e20dcf2015-08-04 21:51:28 +08001263 /* Extract message and author information */
1264 fp = xfopen(am_path(state, "info"), "r");
Junio C Hamano8f309ae2016-01-13 15:31:17 -08001265 while (!strbuf_getline_lf(&sb, fp)) {
Paul Tan3e20dcf2015-08-04 21:51:28 +08001266 const char *x;
1267
1268 if (skip_prefix(sb.buf, "Subject: ", &x)) {
1269 if (msg.len)
1270 strbuf_addch(&msg, '\n');
1271 strbuf_addstr(&msg, x);
1272 } else if (skip_prefix(sb.buf, "Author: ", &x))
1273 strbuf_addstr(&author_name, x);
1274 else if (skip_prefix(sb.buf, "Email: ", &x))
1275 strbuf_addstr(&author_email, x);
1276 else if (skip_prefix(sb.buf, "Date: ", &x))
1277 strbuf_addstr(&author_date, x);
1278 }
1279 fclose(fp);
1280
1281 /* Skip pine's internal folder data */
1282 if (!strcmp(author_name.buf, "Mail System Internal Data")) {
1283 ret = 1;
1284 goto finish;
1285 }
1286
Paul Tan3e20dcf2015-08-04 21:51:28 +08001287 strbuf_addstr(&msg, "\n\n");
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001288 strbuf_addbuf(&msg, &mi.log_message);
Tobias Klauser63af4a82015-10-16 17:16:42 +02001289 strbuf_stripspace(&msg, 0);
Paul Tan3e20dcf2015-08-04 21:51:28 +08001290
1291 assert(!state->author_name);
1292 state->author_name = strbuf_detach(&author_name, NULL);
1293
1294 assert(!state->author_email);
1295 state->author_email = strbuf_detach(&author_email, NULL);
1296
1297 assert(!state->author_date);
1298 state->author_date = strbuf_detach(&author_date, NULL);
1299
1300 assert(!state->msg);
1301 state->msg = strbuf_detach(&msg, &state->msg_len);
1302
1303finish:
1304 strbuf_release(&msg);
1305 strbuf_release(&author_date);
1306 strbuf_release(&author_email);
1307 strbuf_release(&author_name);
1308 strbuf_release(&sb);
Junio C Hamano4b98bae2015-10-14 17:45:43 -07001309 clear_mailinfo(&mi);
Paul Tan3e20dcf2015-08-04 21:51:28 +08001310 return ret;
1311}
1312
1313/**
Paul Tandf2760a2015-08-04 21:51:43 +08001314 * Sets commit_id to the commit hash where the mail was generated from.
1315 * Returns 0 on success, -1 on failure.
1316 */
brian m. carlson8c887692016-09-05 20:08:09 +00001317static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
Paul Tandf2760a2015-08-04 21:51:43 +08001318{
1319 struct strbuf sb = STRBUF_INIT;
1320 FILE *fp = xfopen(mail, "r");
1321 const char *x;
Johannes Schindelin5b34ba42017-05-04 15:55:45 +02001322 int ret = 0;
Paul Tandf2760a2015-08-04 21:51:43 +08001323
Johannes Schindelin5b34ba42017-05-04 15:55:45 +02001324 if (strbuf_getline_lf(&sb, fp) ||
1325 !skip_prefix(sb.buf, "From ", &x) ||
1326 get_oid_hex(x, commit_id) < 0)
1327 ret = -1;
Paul Tandf2760a2015-08-04 21:51:43 +08001328
1329 strbuf_release(&sb);
1330 fclose(fp);
Johannes Schindelin5b34ba42017-05-04 15:55:45 +02001331 return ret;
Paul Tandf2760a2015-08-04 21:51:43 +08001332}
1333
1334/**
1335 * Sets state->msg, state->author_name, state->author_email, state->author_date
1336 * to the commit's respective info.
1337 */
1338static void get_commit_info(struct am_state *state, struct commit *commit)
1339{
Jeff King2e2bbb92017-04-26 23:27:17 -04001340 const char *buffer, *ident_line, *msg;
Paul Tandf2760a2015-08-04 21:51:43 +08001341 size_t ident_len;
Jeff King721f5f12017-04-26 23:28:31 -04001342 struct ident_split id;
Paul Tandf2760a2015-08-04 21:51:43 +08001343
1344 buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
1345
1346 ident_line = find_commit_header(buffer, "author", &ident_len);
Jeff King0dfed922019-09-05 18:50:31 -04001347 if (!ident_line)
1348 die(_("missing author line in commit %s"),
1349 oid_to_hex(&commit->object.oid));
Jeff King721f5f12017-04-26 23:28:31 -04001350 if (split_ident_line(&id, ident_line, ident_len) < 0)
Jeff King2e2bbb92017-04-26 23:27:17 -04001351 die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
Paul Tandf2760a2015-08-04 21:51:43 +08001352
1353 assert(!state->author_name);
Jeff King721f5f12017-04-26 23:28:31 -04001354 if (id.name_begin)
Jeff King2e2bbb92017-04-26 23:27:17 -04001355 state->author_name =
Jeff King721f5f12017-04-26 23:28:31 -04001356 xmemdupz(id.name_begin, id.name_end - id.name_begin);
1357 else
Paul Tandf2760a2015-08-04 21:51:43 +08001358 state->author_name = xstrdup("");
1359
1360 assert(!state->author_email);
Jeff King721f5f12017-04-26 23:28:31 -04001361 if (id.mail_begin)
Jeff King2e2bbb92017-04-26 23:27:17 -04001362 state->author_email =
Jeff King721f5f12017-04-26 23:28:31 -04001363 xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1364 else
Paul Tandf2760a2015-08-04 21:51:43 +08001365 state->author_email = xstrdup("");
1366
Paul Tandf2760a2015-08-04 21:51:43 +08001367 assert(!state->author_date);
Jeff King721f5f12017-04-26 23:28:31 -04001368 state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
Paul Tandf2760a2015-08-04 21:51:43 +08001369
1370 assert(!state->msg);
1371 msg = strstr(buffer, "\n\n");
1372 if (!msg)
brian m. carlsonf2fd0762015-11-10 02:22:28 +00001373 die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
Paul Tandf2760a2015-08-04 21:51:43 +08001374 state->msg = xstrdup(msg + 2);
1375 state->msg_len = strlen(state->msg);
Jeff Kingf131db92017-04-26 23:25:55 -04001376 unuse_commit_buffer(commit, buffer);
Paul Tandf2760a2015-08-04 21:51:43 +08001377}
1378
1379/**
1380 * Writes `commit` as a patch to the state directory's "patch" file.
1381 */
1382static void write_commit_patch(const struct am_state *state, struct commit *commit)
1383{
1384 struct rev_info rev_info;
1385 FILE *fp;
1386
1387 fp = xfopen(am_path(state, "patch"), "w");
Nguyễn Thái Ngọc Duy2abf3502018-09-21 17:57:38 +02001388 repo_init_revisions(the_repository, &rev_info, NULL);
Paul Tandf2760a2015-08-04 21:51:43 +08001389 rev_info.diff = 1;
1390 rev_info.abbrev = 0;
1391 rev_info.disable_stdin = 1;
1392 rev_info.show_root_diff = 1;
1393 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1394 rev_info.no_commit_id = 1;
Brandon Williams0d1e0e72017-10-31 11:19:11 -07001395 rev_info.diffopt.flags.binary = 1;
1396 rev_info.diffopt.flags.full_index = 1;
Paul Tandf2760a2015-08-04 21:51:43 +08001397 rev_info.diffopt.use_color = 0;
1398 rev_info.diffopt.file = fp;
1399 rev_info.diffopt.close_file = 1;
1400 add_pending_object(&rev_info, &commit->object, "");
1401 diff_setup_done(&rev_info.diffopt);
1402 log_tree_commit(&rev_info, commit);
Ævar Arnfjörð Bjarmason2108fe42022-04-13 22:01:36 +02001403 release_revisions(&rev_info);
Paul Tandf2760a2015-08-04 21:51:43 +08001404}
1405
1406/**
Paul Tan7ff26832015-08-04 21:52:03 +08001407 * Writes the diff of the index against HEAD as a patch to the state
1408 * directory's "patch" file.
1409 */
1410static void write_index_patch(const struct am_state *state)
1411{
1412 struct tree *tree;
brian m. carlson8c887692016-09-05 20:08:09 +00001413 struct object_id head;
Paul Tan7ff26832015-08-04 21:52:03 +08001414 struct rev_info rev_info;
1415 FILE *fp;
1416
Jeff King7663e432019-05-24 02:46:27 -04001417 if (!get_oid("HEAD", &head)) {
1418 struct commit *commit = lookup_commit_or_die(&head, "HEAD");
1419 tree = get_commit_tree(commit);
1420 } else
Stefan Bellerf86bcc72018-06-28 18:21:56 -07001421 tree = lookup_tree(the_repository,
1422 the_repository->hash_algo->empty_tree);
Paul Tan7ff26832015-08-04 21:52:03 +08001423
1424 fp = xfopen(am_path(state, "patch"), "w");
Nguyễn Thái Ngọc Duy2abf3502018-09-21 17:57:38 +02001425 repo_init_revisions(the_repository, &rev_info, NULL);
Paul Tan7ff26832015-08-04 21:52:03 +08001426 rev_info.diff = 1;
1427 rev_info.disable_stdin = 1;
1428 rev_info.no_commit_id = 1;
1429 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
1430 rev_info.diffopt.use_color = 0;
1431 rev_info.diffopt.file = fp;
1432 rev_info.diffopt.close_file = 1;
1433 add_pending_object(&rev_info, &tree->object, "");
1434 diff_setup_done(&rev_info.diffopt);
1435 run_diff_index(&rev_info, 1);
Ævar Arnfjörð Bjarmason2108fe42022-04-13 22:01:36 +02001436 release_revisions(&rev_info);
Paul Tan7ff26832015-08-04 21:52:03 +08001437}
1438
1439/**
Paul Tandf2760a2015-08-04 21:51:43 +08001440 * Like parse_mail(), but parses the mail by looking up its commit ID
1441 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
1442 * of patches.
1443 *
Paul Tan13b97ea2015-08-04 21:51:54 +08001444 * state->orig_commit will be set to the original commit ID.
1445 *
Paul Tandf2760a2015-08-04 21:51:43 +08001446 * Will always return 0 as the patch should never be skipped.
1447 */
1448static int parse_mail_rebase(struct am_state *state, const char *mail)
1449{
1450 struct commit *commit;
brian m. carlson8c887692016-09-05 20:08:09 +00001451 struct object_id commit_oid;
Paul Tandf2760a2015-08-04 21:51:43 +08001452
brian m. carlson8c887692016-09-05 20:08:09 +00001453 if (get_mail_commit_oid(&commit_oid, mail) < 0)
Paul Tandf2760a2015-08-04 21:51:43 +08001454 die(_("could not parse %s"), mail);
1455
brian m. carlsonbc832662017-05-06 22:10:10 +00001456 commit = lookup_commit_or_die(&commit_oid, mail);
Paul Tandf2760a2015-08-04 21:51:43 +08001457
1458 get_commit_info(state, commit);
1459
1460 write_commit_patch(state, commit);
1461
brian m. carlson8c887692016-09-05 20:08:09 +00001462 oidcpy(&state->orig_commit, &commit_oid);
1463 write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
Nguyễn Thái Ngọc Duyfbd7a232018-02-11 16:43:28 +07001464 update_ref("am", "REBASE_HEAD", &commit_oid,
1465 NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
Paul Tan13b97ea2015-08-04 21:51:54 +08001466
Paul Tandf2760a2015-08-04 21:51:43 +08001467 return 0;
1468}
1469
1470/**
Paul Tan84f3de22015-08-04 21:51:41 +08001471 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
1472 * `index_file` is not NULL, the patch will be applied to that index.
Paul Tan38a824f2015-08-04 21:51:29 +08001473 */
Paul Tan84f3de22015-08-04 21:51:41 +08001474static int run_apply(const struct am_state *state, const char *index_file)
Paul Tan38a824f2015-08-04 21:51:29 +08001475{
Jeff King22f9b7f2020-07-28 16:24:27 -04001476 struct strvec apply_paths = STRVEC_INIT;
1477 struct strvec apply_opts = STRVEC_INIT;
Christian Couderedfac5e2016-09-04 22:18:33 +02001478 struct apply_state apply_state;
1479 int res, opts_left;
Christian Couderedfac5e2016-09-04 22:18:33 +02001480 int force_apply = 0;
1481 int options = 0;
René Scharfea658e882022-12-13 07:47:59 +01001482 const char **apply_argv;
Paul Tan38a824f2015-08-04 21:51:29 +08001483
Nguyễn Thái Ngọc Duy82ea77e2018-08-13 18:14:39 +02001484 if (init_apply_state(&apply_state, the_repository, NULL))
Johannes Schindelin033abf92018-05-02 11:38:39 +02001485 BUG("init_apply_state() failed");
Paul Tan38a824f2015-08-04 21:51:29 +08001486
Jeff King22f9b7f2020-07-28 16:24:27 -04001487 strvec_push(&apply_opts, "apply");
Jeff Kingd70a9eb2020-07-28 20:37:20 -04001488 strvec_pushv(&apply_opts, state->git_apply_opts.v);
Christian Couderedfac5e2016-09-04 22:18:33 +02001489
René Scharfea658e882022-12-13 07:47:59 +01001490 /*
1491 * Build a copy that apply_parse_options() can rearrange.
1492 * apply_opts.v keeps referencing the allocated strings for
1493 * strvec_clear() to release.
1494 */
René Scharfe6e578412023-01-01 22:16:48 +01001495 DUP_ARRAY(apply_argv, apply_opts.v, apply_opts.nr);
René Scharfea658e882022-12-13 07:47:59 +01001496
1497 opts_left = apply_parse_options(apply_opts.nr, apply_argv,
Christian Couderedfac5e2016-09-04 22:18:33 +02001498 &apply_state, &force_apply, &options,
1499 NULL);
1500
1501 if (opts_left != 0)
1502 die("unknown option passed through to git apply");
1503
1504 if (index_file) {
1505 apply_state.index_file = index_file;
1506 apply_state.cached = 1;
1507 } else
1508 apply_state.check_index = 1;
Paul Tan84f3de22015-08-04 21:51:41 +08001509
1510 /*
1511 * If we are allowed to fall back on 3-way merge, don't give false
1512 * errors during the initial attempt.
1513 */
Christian Couderedfac5e2016-09-04 22:18:33 +02001514 if (state->threeway && !index_file)
1515 apply_state.apply_verbosity = verbosity_silent;
1516
1517 if (check_apply_state(&apply_state, force_apply))
Johannes Schindelin033abf92018-05-02 11:38:39 +02001518 BUG("check_apply_state() failed");
Christian Couderedfac5e2016-09-04 22:18:33 +02001519
Jeff King22f9b7f2020-07-28 16:24:27 -04001520 strvec_push(&apply_paths, am_path(state, "patch"));
Christian Couderedfac5e2016-09-04 22:18:33 +02001521
Jeff Kingd70a9eb2020-07-28 20:37:20 -04001522 res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
Christian Couderedfac5e2016-09-04 22:18:33 +02001523
Jeff King22f9b7f2020-07-28 16:24:27 -04001524 strvec_clear(&apply_paths);
1525 strvec_clear(&apply_opts);
Christian Couderedfac5e2016-09-04 22:18:33 +02001526 clear_apply_state(&apply_state);
René Scharfea658e882022-12-13 07:47:59 +01001527 free(apply_argv);
Christian Couderedfac5e2016-09-04 22:18:33 +02001528
1529 if (res)
1530 return res;
1531
1532 if (index_file) {
1533 /* Reload index as apply_all_patches() will have modified it. */
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001534 discard_index(&the_index);
1535 read_index_from(&the_index, index_file, get_git_dir());
Paul Tan84f3de22015-08-04 21:51:41 +08001536 }
1537
Paul Tan84f3de22015-08-04 21:51:41 +08001538 return 0;
1539}
1540
1541/**
1542 * Builds an index that contains just the blobs needed for a 3way merge.
1543 */
1544static int build_fake_ancestor(const struct am_state *state, const char *index_file)
1545{
1546 struct child_process cp = CHILD_PROCESS_INIT;
1547
1548 cp.git_cmd = 1;
Jeff King22f9b7f2020-07-28 16:24:27 -04001549 strvec_push(&cp.args, "apply");
Jeff Kingd70a9eb2020-07-28 20:37:20 -04001550 strvec_pushv(&cp.args, state->git_apply_opts.v);
Jeff King22f9b7f2020-07-28 16:24:27 -04001551 strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
1552 strvec_push(&cp.args, am_path(state, "patch"));
Paul Tan84f3de22015-08-04 21:51:41 +08001553
1554 if (run_command(&cp))
1555 return -1;
1556
1557 return 0;
1558}
1559
1560/**
1561 * Attempt a threeway merge, using index_path as the temporary index.
1562 */
1563static int fall_back_threeway(const struct am_state *state, const char *index_path)
1564{
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001565 struct object_id orig_tree, their_tree, our_tree;
1566 const struct object_id *bases[1] = { &orig_tree };
1567 struct merge_options o;
1568 struct commit *result;
1569 char *their_tree_name;
Paul Tan84f3de22015-08-04 21:51:41 +08001570
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001571 if (get_oid("HEAD", &our_tree) < 0)
brian m. carlsond41836a2018-05-02 00:25:55 +00001572 oidcpy(&our_tree, the_hash_algo->empty_tree);
Paul Tan84f3de22015-08-04 21:51:41 +08001573
1574 if (build_fake_ancestor(state, index_path))
1575 return error("could not build fake ancestor");
1576
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001577 discard_index(&the_index);
1578 read_index_from(&the_index, index_path, get_git_dir());
Paul Tan84f3de22015-08-04 21:51:41 +08001579
brian m. carlsonfc5cb992018-03-12 02:27:23 +00001580 if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
Paul Tan84f3de22015-08-04 21:51:41 +08001581 return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
1582
1583 say(state, stdout, _("Using index info to reconstruct a base tree..."));
1584
1585 if (!state->quiet) {
1586 /*
1587 * List paths that needed 3-way fallback, so that the user can
1588 * review them with extra care to spot mismerges.
1589 */
1590 struct rev_info rev_info;
Paul Tan84f3de22015-08-04 21:51:41 +08001591
Nguyễn Thái Ngọc Duy2abf3502018-09-21 17:57:38 +02001592 repo_init_revisions(the_repository, &rev_info, NULL);
Paul Tan84f3de22015-08-04 21:51:41 +08001593 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
Nguyễn Thái Ngọc Duycdb53302019-03-24 15:20:14 +07001594 rev_info.diffopt.filter |= diff_filter_bit('A');
1595 rev_info.diffopt.filter |= diff_filter_bit('M');
brian m. carlsona58a1b02017-05-06 22:10:26 +00001596 add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
Paul Tan84f3de22015-08-04 21:51:41 +08001597 diff_setup_done(&rev_info.diffopt);
1598 run_diff_index(&rev_info, 1);
Ævar Arnfjörð Bjarmason2108fe42022-04-13 22:01:36 +02001599 release_revisions(&rev_info);
Paul Tan84f3de22015-08-04 21:51:41 +08001600 }
1601
1602 if (run_apply(state, index_path))
1603 return error(_("Did you hand edit your patch?\n"
1604 "It does not apply to blobs recorded in its index."));
1605
brian m. carlsonfc5cb992018-03-12 02:27:23 +00001606 if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
Paul Tan84f3de22015-08-04 21:51:41 +08001607 return error("could not write tree");
1608
1609 say(state, stdout, _("Falling back to patching base and 3-way merge..."));
1610
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001611 discard_index(&the_index);
1612 repo_read_index(the_repository);
Paul Tan38a824f2015-08-04 21:51:29 +08001613
Paul Tan84f3de22015-08-04 21:51:41 +08001614 /*
1615 * This is not so wrong. Depending on which base we picked, orig_tree
Johannes Schindelin715a51b2016-07-08 09:17:34 +02001616 * may be wildly different from ours, but their_tree has the same set of
Paul Tan84f3de22015-08-04 21:51:41 +08001617 * wildly different changes in parts the patch did not touch, so
1618 * recursive ends up canceling them, saying that we reverted all those
1619 * changes.
1620 */
1621
Nguyễn Thái Ngọc Duy0d6caa22019-01-12 09:13:29 +07001622 init_merge_options(&o, the_repository);
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001623
1624 o.branch1 = "HEAD";
1625 their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
1626 o.branch2 = their_tree_name;
Derrick Stolee8e012512019-08-17 11:41:25 -07001627 o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001628
1629 if (state->quiet)
1630 o.verbosity = 0;
1631
1632 if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
Nguyễn Thái Ngọc Duy35843b12018-09-21 17:57:32 +02001633 repo_rerere(the_repository, state->allow_rerere_autoupdate);
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001634 free(their_tree_name);
Paul Tan84f3de22015-08-04 21:51:41 +08001635 return error(_("Failed to merge in the changes."));
1636 }
1637
Johannes Schindelin3f338f42016-07-26 18:06:30 +02001638 free(their_tree_name);
Paul Tan38a824f2015-08-04 21:51:29 +08001639 return 0;
1640}
1641
1642/**
Paul Tanc9e8d962015-08-04 21:51:30 +08001643 * Commits the current index with state->msg as the commit message and
1644 * state->author_name, state->author_email and state->author_date as the author
1645 * information.
1646 */
1647static void do_commit(const struct am_state *state)
1648{
brian m. carlson8c887692016-09-05 20:08:09 +00001649 struct object_id tree, parent, commit;
1650 const struct object_id *old_oid;
Paul Tanc9e8d962015-08-04 21:51:30 +08001651 struct commit_list *parents = NULL;
Phillip Woode8cbe212020-08-17 18:40:01 +01001652 const char *reflog_msg, *author, *committer = NULL;
Paul Tanc9e8d962015-08-04 21:51:30 +08001653 struct strbuf sb = STRBUF_INIT;
1654
Thierry Reding566902f2022-11-30 18:28:33 +01001655 if (!state->no_verify && run_hooks("pre-applypatch"))
Paul Tan6c24c5c2015-08-04 21:51:57 +08001656 exit(1);
1657
brian m. carlsonfc5cb992018-03-12 02:27:23 +00001658 if (write_cache_as_tree(&tree, 0, NULL))
Paul Tanc9e8d962015-08-04 21:51:30 +08001659 die(_("git write-tree failed to write a tree"));
1660
brian m. carlsone82caf32017-07-13 23:49:28 +00001661 if (!get_oid_commit("HEAD", &parent)) {
brian m. carlson8c887692016-09-05 20:08:09 +00001662 old_oid = &parent;
Stefan Bellerc1f5eb42018-06-28 18:21:59 -07001663 commit_list_insert(lookup_commit(the_repository, &parent),
1664 &parents);
Paul Tanc9e8d962015-08-04 21:51:30 +08001665 } else {
brian m. carlson8c887692016-09-05 20:08:09 +00001666 old_oid = NULL;
Paul Tan5d28cf72015-08-04 21:51:37 +08001667 say(state, stderr, _("applying to an empty history"));
Paul Tanc9e8d962015-08-04 21:51:30 +08001668 }
1669
1670 author = fmt_ident(state->author_name, state->author_email,
William Hubbs39ab4d02019-02-04 12:48:50 -06001671 WANT_AUTHOR_IDENT,
Paul Tanf07adb62015-08-04 21:51:51 +08001672 state->ignore_date ? NULL : state->author_date,
1673 IDENT_STRICT);
Paul Tanc9e8d962015-08-04 21:51:30 +08001674
Paul Tan0cd4bcb2015-08-04 21:51:52 +08001675 if (state->committer_date_is_author_date)
Jeff King20204512020-10-23 03:26:30 -04001676 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1677 getenv("GIT_COMMITTER_EMAIL"),
1678 WANT_COMMITTER_IDENT,
Phillip Woode8cbe212020-08-17 18:40:01 +01001679 state->ignore_date ? NULL
1680 : state->author_date,
1681 IDENT_STRICT);
Paul Tan0cd4bcb2015-08-04 21:51:52 +08001682
Phillip Woode8cbe212020-08-17 18:40:01 +01001683 if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
1684 &commit, author, committer, state->sign_commit,
1685 NULL))
Paul Tanc9e8d962015-08-04 21:51:30 +08001686 die(_("failed to write commit object"));
1687
1688 reflog_msg = getenv("GIT_REFLOG_ACTION");
1689 if (!reflog_msg)
1690 reflog_msg = "am";
1691
1692 strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
1693 state->msg);
1694
brian m. carlsonae077772017-10-15 22:06:51 +00001695 update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
1696 UPDATE_REFS_DIE_ON_ERR);
Paul Tanc9e8d962015-08-04 21:51:30 +08001697
Paul Tan13b97ea2015-08-04 21:51:54 +08001698 if (state->rebasing) {
1699 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
1700
brian m. carlson8c887692016-09-05 20:08:09 +00001701 assert(!is_null_oid(&state->orig_commit));
1702 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
1703 fprintf(fp, "%s\n", oid_to_hex(&commit));
Paul Tan13b97ea2015-08-04 21:51:54 +08001704 fclose(fp);
1705 }
1706
Emily Shaffer593ffdd2021-12-22 04:59:30 +01001707 run_hooks("post-applypatch");
Paul Tan7088f802015-08-04 21:51:58 +08001708
Paul Tanc9e8d962015-08-04 21:51:30 +08001709 strbuf_release(&sb);
1710}
1711
1712/**
Paul Tan240bfd22015-08-04 21:51:32 +08001713 * Validates the am_state for resuming -- the "msg" and authorship fields must
1714 * be filled up.
1715 */
1716static void validate_resume_state(const struct am_state *state)
1717{
1718 if (!state->msg)
1719 die(_("cannot resume: %s does not exist."),
1720 am_path(state, "final-commit"));
1721
1722 if (!state->author_name || !state->author_email || !state->author_date)
1723 die(_("cannot resume: %s does not exist."),
1724 am_path(state, "author-script"));
1725}
1726
1727/**
Paul Tan7ff26832015-08-04 21:52:03 +08001728 * Interactively prompt the user on whether the current patch should be
1729 * applied.
1730 *
1731 * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
1732 * skip it.
1733 */
1734static int do_interactive(struct am_state *state)
1735{
1736 assert(state->msg);
1737
Paul Tan7ff26832015-08-04 21:52:03 +08001738 for (;;) {
Jeff King97387c82019-05-20 08:09:26 -04001739 char reply[64];
Paul Tan7ff26832015-08-04 21:52:03 +08001740
1741 puts(_("Commit Body is:"));
1742 puts("--------------------------");
1743 printf("%s", state->msg);
1744 puts("--------------------------");
1745
1746 /*
1747 * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
1748 * in your translation. The program will only accept English
1749 * input at this point.
1750 */
Jeff King97387c82019-05-20 08:09:26 -04001751 printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
1752 if (!fgets(reply, sizeof(reply), stdin))
1753 die("unable to read from stdin; aborting");
Paul Tan7ff26832015-08-04 21:52:03 +08001754
Jeff King1db65f32019-05-20 08:07:15 -04001755 if (*reply == 'y' || *reply == 'Y') {
Paul Tan7ff26832015-08-04 21:52:03 +08001756 return 0;
1757 } else if (*reply == 'a' || *reply == 'A') {
1758 state->interactive = 0;
1759 return 0;
1760 } else if (*reply == 'n' || *reply == 'N') {
1761 return 1;
1762 } else if (*reply == 'e' || *reply == 'E') {
1763 struct strbuf msg = STRBUF_INIT;
1764
1765 if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
1766 free(state->msg);
1767 state->msg = strbuf_detach(&msg, &state->msg_len);
1768 }
1769 strbuf_release(&msg);
1770 } else if (*reply == 'v' || *reply == 'V') {
1771 const char *pager = git_pager(1);
1772 struct child_process cp = CHILD_PROCESS_INIT;
1773
1774 if (!pager)
1775 pager = "cat";
Junio C Hamano708b8cc2016-02-16 14:46:39 -08001776 prepare_pager_args(&cp, pager);
Jeff King22f9b7f2020-07-28 16:24:27 -04001777 strvec_push(&cp.args, am_path(state, "patch"));
Paul Tan7ff26832015-08-04 21:52:03 +08001778 run_command(&cp);
1779 }
1780 }
1781}
1782
1783/**
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001784 * Applies all queued mail.
Paul Tan8c7b1562015-08-04 21:51:33 +08001785 *
1786 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
1787 * well as the state directory's "patch" file is used as-is for applying the
1788 * patch and committing it.
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001789 */
Paul Tan8c7b1562015-08-04 21:51:33 +08001790static void am_run(struct am_state *state, int resume)
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001791{
Paul Tan32a5fcb2015-08-04 21:51:31 +08001792 struct strbuf sb = STRBUF_INIT;
Paul Tanc9e8d962015-08-04 21:51:30 +08001793
Paul Tan33388a72015-08-04 21:51:35 +08001794 unlink(am_path(state, "dirtyindex"));
1795
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001796 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1797 NULL, NULL, NULL) < 0)
Thomas Gummerer22184492019-09-11 19:20:25 +01001798 die(_("unable to write index file"));
Paul Tan38a824f2015-08-04 21:51:29 +08001799
Nguyễn Thái Ngọc Duy150fe062019-01-12 09:13:31 +07001800 if (repo_index_has_changes(the_repository, NULL, &sb)) {
Junio C Hamano25b763b2015-08-24 09:12:53 -07001801 write_state_bool(state, "dirtyindex", 1);
Paul Tan32a5fcb2015-08-04 21:51:31 +08001802 die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
Paul Tan33388a72015-08-04 21:51:35 +08001803 }
Paul Tan32a5fcb2015-08-04 21:51:31 +08001804
1805 strbuf_release(&sb);
1806
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001807 while (state->cur <= state->last) {
Paul Tan3e20dcf2015-08-04 21:51:28 +08001808 const char *mail = am_path(state, msgnum(state));
Paul Tan84f3de22015-08-04 21:51:41 +08001809 int apply_status;
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +00001810 int to_keep;
Paul Tan3e20dcf2015-08-04 21:51:28 +08001811
Jeff King4d9c7e62016-08-01 15:37:00 -04001812 reset_ident_date();
1813
Paul Tan3e20dcf2015-08-04 21:51:28 +08001814 if (!file_exists(mail))
1815 goto next;
1816
Paul Tan8c7b1562015-08-04 21:51:33 +08001817 if (resume) {
1818 validate_resume_state(state);
Paul Tan8c7b1562015-08-04 21:51:33 +08001819 } else {
Paul Tandf2760a2015-08-04 21:51:43 +08001820 int skip;
1821
1822 if (state->rebasing)
1823 skip = parse_mail_rebase(state, mail);
1824 else
1825 skip = parse_mail(state, mail);
1826
1827 if (skip)
Paul Tan8c7b1562015-08-04 21:51:33 +08001828 goto next; /* mail should be skipped */
Paul Tan3e20dcf2015-08-04 21:51:28 +08001829
Giuseppe Bilottab7cc7052017-04-15 16:41:01 +02001830 if (state->signoff)
1831 am_append_signoff(state);
1832
Paul Tan8c7b1562015-08-04 21:51:33 +08001833 write_author_script(state);
1834 write_commit_msg(state);
1835 }
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001836
Paul Tan7ff26832015-08-04 21:52:03 +08001837 if (state->interactive && do_interactive(state))
1838 goto next;
1839
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +00001840 to_keep = 0;
1841 if (is_empty_or_missing_file(am_path(state, "patch"))) {
1842 switch (state->empty_type) {
1843 case DROP_EMPTY_COMMIT:
1844 say(state, stdout, _("Skipping: %.*s"), linelen(state->msg), state->msg);
1845 goto next;
1846 break;
1847 case KEEP_EMPTY_COMMIT:
1848 to_keep = 1;
1849 say(state, stdout, _("Creating an empty commit: %.*s"),
1850 linelen(state->msg), state->msg);
1851 break;
1852 case STOP_ON_EMPTY_COMMIT:
1853 printf_ln(_("Patch is empty."));
1854 die_user_resolve(state);
1855 break;
1856 }
1857 }
1858
Paul Tanb8803d82015-08-04 21:51:56 +08001859 if (run_applypatch_msg_hook(state))
1860 exit(1);
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +00001861 if (to_keep)
1862 goto commit;
Paul Tanb8803d82015-08-04 21:51:56 +08001863
Paul Tan5d28cf72015-08-04 21:51:37 +08001864 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
Paul Tan38a824f2015-08-04 21:51:29 +08001865
Paul Tan84f3de22015-08-04 21:51:41 +08001866 apply_status = run_apply(state, NULL);
1867
1868 if (apply_status && state->threeway) {
1869 struct strbuf sb = STRBUF_INIT;
1870
1871 strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
1872 apply_status = fall_back_threeway(state, sb.buf);
1873 strbuf_release(&sb);
1874
1875 /*
1876 * Applying the patch to an earlier tree and merging
1877 * the result may have produced the same tree as ours.
1878 */
Elijah Newrene1f86942018-06-30 18:25:00 -07001879 if (!apply_status &&
Nguyễn Thái Ngọc Duy150fe062019-01-12 09:13:31 +07001880 !repo_index_has_changes(the_repository, NULL, NULL)) {
Paul Tan84f3de22015-08-04 21:51:41 +08001881 say(state, stdout, _("No changes -- Patch already applied."));
1882 goto next;
1883 }
1884 }
1885
1886 if (apply_status) {
Paul Tan38a824f2015-08-04 21:51:29 +08001887 printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
1888 linelen(state->msg), state->msg);
1889
Ben Boeckeled9bff02021-08-23 12:44:00 +02001890 if (advice_enabled(ADVICE_AM_WORK_DIR))
Paolo Bonziniaa416b22020-02-20 15:15:19 +01001891 advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
Paul Tan38a824f2015-08-04 21:51:29 +08001892
Paul Tan2d831092015-08-04 21:51:38 +08001893 die_user_resolve(state);
Paul Tan38a824f2015-08-04 21:51:29 +08001894 }
1895
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +00001896commit:
Paul Tanc9e8d962015-08-04 21:51:30 +08001897 do_commit(state);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001898
Paul Tan3e20dcf2015-08-04 21:51:28 +08001899next:
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001900 am_next(state);
Paul Tan852a1712015-08-04 22:08:50 +08001901
1902 if (resume)
1903 am_load(state);
1904 resume = 0;
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001905 }
1906
Pranit Bauvae3b1e3b2019-01-02 07:38:32 -08001907 if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
Paul Tan13b97ea2015-08-04 21:51:54 +08001908 assert(state->rebasing);
Paul Tan88b291f2015-08-04 21:51:55 +08001909 copy_notes_for_rebase(state);
Paul Tan13b97ea2015-08-04 21:51:54 +08001910 run_post_rewrite_hook(state);
1911 }
1912
Paul Tan35bdcc52015-08-04 21:51:42 +08001913 /*
1914 * In rebasing mode, it's up to the caller to take care of
1915 * housekeeping.
1916 */
1917 if (!state->rebasing) {
1918 am_destroy(state);
Derrick Stoleea95ce122020-09-17 18:11:44 +00001919 run_auto_maintenance(state->quiet);
Paul Tan35bdcc52015-08-04 21:51:42 +08001920 }
Paul Tan8c3bd9e2015-08-04 21:51:25 +08001921}
Paul Tan73c27792015-08-04 21:51:24 +08001922
Paul Tan11c21772015-08-04 21:51:26 +08001923/**
Paul Tan240bfd22015-08-04 21:51:32 +08001924 * Resume the current am session after patch application failure. The user did
1925 * all the hard work, and we do not have to do any patch application. Just
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00001926 * trust and commit what the user has in the index and working tree. If `allow_empty`
1927 * is true, commit as an empty commit when index has not changed and lacking a patch.
Paul Tan240bfd22015-08-04 21:51:32 +08001928 */
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00001929static void am_resolve(struct am_state *state, int allow_empty)
Paul Tan240bfd22015-08-04 21:51:32 +08001930{
1931 validate_resume_state(state);
1932
Paul Tan5d28cf72015-08-04 21:51:37 +08001933 say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
Paul Tan240bfd22015-08-04 21:51:32 +08001934
Nguyễn Thái Ngọc Duy150fe062019-01-12 09:13:31 +07001935 if (!repo_index_has_changes(the_repository, NULL, NULL)) {
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00001936 if (allow_empty && is_empty_or_missing_file(am_path(state, "patch"))) {
1937 printf_ln(_("No changes - recorded it as an empty commit."));
1938 } else {
1939 printf_ln(_("No changes - did you forget to use 'git add'?\n"
1940 "If there is nothing left to stage, chances are that something else\n"
1941 "already introduced the same changes; you might want to skip this patch."));
1942 die_user_resolve(state);
1943 }
Paul Tan240bfd22015-08-04 21:51:32 +08001944 }
1945
Ævar Arnfjörð Bjarmasonfbc1ed62022-11-19 14:07:30 +01001946 if (unmerged_index(&the_index)) {
Paul Tan240bfd22015-08-04 21:51:32 +08001947 printf_ln(_("You still have unmerged paths in your index.\n"
Jean-Noel Avila6c486862017-05-11 14:06:32 +02001948 "You should 'git add' each file with resolved conflicts to mark them as such.\n"
1949 "You might run `git rm` on a file to accept \"deleted by them\" for it."));
Paul Tan2d831092015-08-04 21:51:38 +08001950 die_user_resolve(state);
Paul Tan240bfd22015-08-04 21:51:32 +08001951 }
1952
Paul Tan7ff26832015-08-04 21:52:03 +08001953 if (state->interactive) {
1954 write_index_patch(state);
1955 if (do_interactive(state))
1956 goto next;
1957 }
1958
Nguyễn Thái Ngọc Duy35843b12018-09-21 17:57:32 +02001959 repo_rerere(the_repository, 0);
Paul Tanf1cb96d2015-08-04 21:51:59 +08001960
Paul Tan240bfd22015-08-04 21:51:32 +08001961 do_commit(state);
1962
Paul Tan7ff26832015-08-04 21:52:03 +08001963next:
Paul Tan240bfd22015-08-04 21:51:32 +08001964 am_next(state);
Paul Tan852a1712015-08-04 22:08:50 +08001965 am_load(state);
Paul Tan8c7b1562015-08-04 21:51:33 +08001966 am_run(state, 0);
Paul Tan240bfd22015-08-04 21:51:32 +08001967}
1968
1969/**
Paul Tan99900802015-08-04 21:51:34 +08001970 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
1971 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
1972 * failure.
1973 */
1974static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
1975{
Martin Ågren837e34e2017-10-05 22:32:04 +02001976 struct lock_file lock_file = LOCK_INIT;
Paul Tan99900802015-08-04 21:51:34 +08001977 struct unpack_trees_options opts;
1978 struct tree_desc t[2];
1979
1980 if (parse_tree(head) || parse_tree(remote))
1981 return -1;
1982
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001983 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
Paul Tan99900802015-08-04 21:51:34 +08001984
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01001985 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
Paul Tan99900802015-08-04 21:51:34 +08001986
1987 memset(&opts, 0, sizeof(opts));
1988 opts.head_idx = 1;
1989 opts.src_index = &the_index;
1990 opts.dst_index = &the_index;
1991 opts.update = 1;
1992 opts.merge = 1;
Elijah Newren480d3d62021-09-27 16:33:44 +00001993 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
1994 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
Paul Tan99900802015-08-04 21:51:34 +08001995 opts.fn = twoway_merge;
1996 init_tree_desc(&t[0], head->buffer, head->size);
1997 init_tree_desc(&t[1], remote->buffer, remote->size);
1998
1999 if (unpack_trees(2, t, &opts)) {
Martin Ågren837e34e2017-10-05 22:32:04 +02002000 rollback_lock_file(&lock_file);
Paul Tan99900802015-08-04 21:51:34 +08002001 return -1;
2002 }
2003
Martin Ågren837e34e2017-10-05 22:32:04 +02002004 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
Paul Tan99900802015-08-04 21:51:34 +08002005 die(_("unable to write new index file"));
2006
2007 return 0;
2008}
2009
2010/**
Paul Tan3ecc7042015-08-19 16:22:22 +08002011 * Merges a tree into the index. The index's stat info will take precedence
2012 * over the merged tree's. Returns 0 on success, -1 on failure.
2013 */
2014static int merge_tree(struct tree *tree)
2015{
Martin Ågren837e34e2017-10-05 22:32:04 +02002016 struct lock_file lock_file = LOCK_INIT;
Paul Tan3ecc7042015-08-19 16:22:22 +08002017 struct unpack_trees_options opts;
2018 struct tree_desc t[1];
2019
2020 if (parse_tree(tree))
2021 return -1;
2022
Ævar Arnfjörð Bjarmason07047d62022-11-19 14:07:38 +01002023 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
Paul Tan3ecc7042015-08-19 16:22:22 +08002024
2025 memset(&opts, 0, sizeof(opts));
2026 opts.head_idx = 1;
2027 opts.src_index = &the_index;
2028 opts.dst_index = &the_index;
2029 opts.merge = 1;
2030 opts.fn = oneway_merge;
2031 init_tree_desc(&t[0], tree->buffer, tree->size);
2032
2033 if (unpack_trees(1, t, &opts)) {
Martin Ågren837e34e2017-10-05 22:32:04 +02002034 rollback_lock_file(&lock_file);
Paul Tan3ecc7042015-08-19 16:22:22 +08002035 return -1;
2036 }
2037
Martin Ågren837e34e2017-10-05 22:32:04 +02002038 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
Paul Tan3ecc7042015-08-19 16:22:22 +08002039 die(_("unable to write new index file"));
2040
2041 return 0;
2042}
2043
2044/**
Paul Tan99900802015-08-04 21:51:34 +08002045 * Clean the index without touching entries that are not modified between
2046 * `head` and `remote`.
2047 */
brian m. carlson8c887692016-09-05 20:08:09 +00002048static int clean_index(const struct object_id *head, const struct object_id *remote)
Paul Tan99900802015-08-04 21:51:34 +08002049{
Paul Tan99900802015-08-04 21:51:34 +08002050 struct tree *head_tree, *remote_tree, *index_tree;
brian m. carlson8c887692016-09-05 20:08:09 +00002051 struct object_id index;
Paul Tan99900802015-08-04 21:51:34 +08002052
brian m. carlsona9dbc172017-05-06 22:10:37 +00002053 head_tree = parse_tree_indirect(head);
Paul Tan99900802015-08-04 21:51:34 +08002054 if (!head_tree)
brian m. carlson8c887692016-09-05 20:08:09 +00002055 return error(_("Could not parse object '%s'."), oid_to_hex(head));
Paul Tan99900802015-08-04 21:51:34 +08002056
brian m. carlsona9dbc172017-05-06 22:10:37 +00002057 remote_tree = parse_tree_indirect(remote);
Paul Tan99900802015-08-04 21:51:34 +08002058 if (!remote_tree)
brian m. carlson8c887692016-09-05 20:08:09 +00002059 return error(_("Could not parse object '%s'."), oid_to_hex(remote));
Paul Tan99900802015-08-04 21:51:34 +08002060
Ævar Arnfjörð Bjarmasonfbc1ed62022-11-19 14:07:30 +01002061 repo_read_index_unmerged(the_repository);
Paul Tan99900802015-08-04 21:51:34 +08002062
2063 if (fast_forward_to(head_tree, head_tree, 1))
2064 return -1;
2065
brian m. carlsonfc5cb992018-03-12 02:27:23 +00002066 if (write_cache_as_tree(&index, 0, NULL))
Paul Tan99900802015-08-04 21:51:34 +08002067 return -1;
2068
brian m. carlsona9dbc172017-05-06 22:10:37 +00002069 index_tree = parse_tree_indirect(&index);
Paul Tan99900802015-08-04 21:51:34 +08002070 if (!index_tree)
brian m. carlson8c887692016-09-05 20:08:09 +00002071 return error(_("Could not parse object '%s'."), oid_to_hex(&index));
Paul Tan99900802015-08-04 21:51:34 +08002072
2073 if (fast_forward_to(index_tree, remote_tree, 0))
2074 return -1;
2075
Paul Tan3ecc7042015-08-19 16:22:22 +08002076 if (merge_tree(remote_tree))
Paul Tan99900802015-08-04 21:51:34 +08002077 return -1;
Paul Tan99900802015-08-04 21:51:34 +08002078
Nguyễn Thái Ngọc Duyf4a4b9a2019-03-29 17:38:59 +07002079 remove_branch_state(the_repository, 0);
Paul Tan99900802015-08-04 21:51:34 +08002080
2081 return 0;
2082}
2083
2084/**
Paul Tanf1cb96d2015-08-04 21:51:59 +08002085 * Resets rerere's merge resolution metadata.
2086 */
2087static void am_rerere_clear(void)
2088{
2089 struct string_list merge_rr = STRING_LIST_INIT_DUP;
Nguyễn Thái Ngọc Duy55e6b352018-11-10 06:49:09 +01002090 rerere_clear(the_repository, &merge_rr);
Paul Tanf1cb96d2015-08-04 21:51:59 +08002091 string_list_clear(&merge_rr, 1);
2092}
2093
2094/**
Paul Tan99900802015-08-04 21:51:34 +08002095 * Resume the current am session by skipping the current patch.
2096 */
2097static void am_skip(struct am_state *state)
2098{
brian m. carlson8c887692016-09-05 20:08:09 +00002099 struct object_id head;
Paul Tan99900802015-08-04 21:51:34 +08002100
Paul Tanf1cb96d2015-08-04 21:51:59 +08002101 am_rerere_clear();
2102
brian m. carlson8c887692016-09-05 20:08:09 +00002103 if (get_oid("HEAD", &head))
brian m. carlsond41836a2018-05-02 00:25:55 +00002104 oidcpy(&head, the_hash_algo->empty_tree);
Paul Tan99900802015-08-04 21:51:34 +08002105
brian m. carlson8c887692016-09-05 20:08:09 +00002106 if (clean_index(&head, &head))
Paul Tan99900802015-08-04 21:51:34 +08002107 die(_("failed to clean index"));
2108
Elijah Newren45339f72018-12-11 08:11:35 -08002109 if (state->rebasing) {
2110 FILE *fp = xfopen(am_path(state, "rewritten"), "a");
2111
2112 assert(!is_null_oid(&state->orig_commit));
2113 fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
2114 fprintf(fp, "%s\n", oid_to_hex(&head));
2115 fclose(fp);
2116 }
2117
Paul Tan99900802015-08-04 21:51:34 +08002118 am_next(state);
Paul Tan852a1712015-08-04 22:08:50 +08002119 am_load(state);
Paul Tan99900802015-08-04 21:51:34 +08002120 am_run(state, 0);
2121}
2122
2123/**
Paul Tan33388a72015-08-04 21:51:35 +08002124 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
2125 *
2126 * It is not safe to reset HEAD when:
2127 * 1. git-am previously failed because the index was dirty.
2128 * 2. HEAD has moved since git-am previously failed.
2129 */
2130static int safe_to_abort(const struct am_state *state)
2131{
2132 struct strbuf sb = STRBUF_INIT;
brian m. carlson8c887692016-09-05 20:08:09 +00002133 struct object_id abort_safety, head;
Paul Tan33388a72015-08-04 21:51:35 +08002134
2135 if (file_exists(am_path(state, "dirtyindex")))
2136 return 0;
2137
2138 if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
brian m. carlson8c887692016-09-05 20:08:09 +00002139 if (get_oid_hex(sb.buf, &abort_safety))
Stephan Beyerccd71b22016-12-07 22:51:29 +01002140 die(_("could not parse %s"), am_path(state, "abort-safety"));
Paul Tan33388a72015-08-04 21:51:35 +08002141 } else
brian m. carlson8c887692016-09-05 20:08:09 +00002142 oidclr(&abort_safety);
Rene Scharfe28ac7aa2017-08-30 19:49:34 +02002143 strbuf_release(&sb);
Paul Tan33388a72015-08-04 21:51:35 +08002144
brian m. carlson8c887692016-09-05 20:08:09 +00002145 if (get_oid("HEAD", &head))
2146 oidclr(&head);
Paul Tan33388a72015-08-04 21:51:35 +08002147
Jeff King4a7e27e2018-08-28 17:22:40 -04002148 if (oideq(&head, &abort_safety))
Paul Tan33388a72015-08-04 21:51:35 +08002149 return 1;
2150
Stephan Beyer18683312016-12-07 22:51:30 +01002151 warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
Paul Tan33388a72015-08-04 21:51:35 +08002152 "Not rewinding to ORIG_HEAD"));
2153
2154 return 0;
2155}
2156
2157/**
2158 * Aborts the current am session if it is safe to do so.
2159 */
2160static void am_abort(struct am_state *state)
2161{
brian m. carlson8c887692016-09-05 20:08:09 +00002162 struct object_id curr_head, orig_head;
Paul Tan33388a72015-08-04 21:51:35 +08002163 int has_curr_head, has_orig_head;
2164 char *curr_branch;
2165
2166 if (!safe_to_abort(state)) {
2167 am_destroy(state);
2168 return;
2169 }
2170
Paul Tanf1cb96d2015-08-04 21:51:59 +08002171 am_rerere_clear();
2172
brian m. carlson0f2dc722017-10-15 22:06:55 +00002173 curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
René Scharfe57e0ef02017-05-06 19:13:56 +02002174 has_curr_head = curr_branch && !is_null_oid(&curr_head);
Paul Tan33388a72015-08-04 21:51:35 +08002175 if (!has_curr_head)
brian m. carlsond41836a2018-05-02 00:25:55 +00002176 oidcpy(&curr_head, the_hash_algo->empty_tree);
Paul Tan33388a72015-08-04 21:51:35 +08002177
brian m. carlson8c887692016-09-05 20:08:09 +00002178 has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
Paul Tan33388a72015-08-04 21:51:35 +08002179 if (!has_orig_head)
brian m. carlsond41836a2018-05-02 00:25:55 +00002180 oidcpy(&orig_head, the_hash_algo->empty_tree);
Paul Tan33388a72015-08-04 21:51:35 +08002181
Elijah Newrenc5ead192021-09-10 10:31:16 +00002182 if (clean_index(&curr_head, &orig_head))
2183 die(_("failed to clean index"));
Paul Tan33388a72015-08-04 21:51:35 +08002184
2185 if (has_orig_head)
brian m. carlsonae077772017-10-15 22:06:51 +00002186 update_ref("am --abort", "HEAD", &orig_head,
2187 has_curr_head ? &curr_head : NULL, 0,
2188 UPDATE_REFS_DIE_ON_ERR);
Paul Tan33388a72015-08-04 21:51:35 +08002189 else if (curr_branch)
Michael Haggerty91774af2017-11-05 09:42:06 +01002190 delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
Paul Tan33388a72015-08-04 21:51:35 +08002191
2192 free(curr_branch);
2193 am_destroy(state);
2194}
2195
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002196static int show_patch(struct am_state *state, enum show_patch_type sub_mode)
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002197{
2198 struct strbuf sb = STRBUF_INIT;
2199 const char *patch_path;
2200 int len;
2201
Nguyễn Thái Ngọc Duy66335292018-02-11 16:43:27 +07002202 if (!is_null_oid(&state->orig_commit)) {
René Scharfeddbb47f2022-10-30 12:55:06 +01002203 struct child_process cmd = CHILD_PROCESS_INIT;
Nguyễn Thái Ngọc Duy66335292018-02-11 16:43:27 +07002204
René Scharfeddbb47f2022-10-30 12:55:06 +01002205 strvec_pushl(&cmd.args, "show", oid_to_hex(&state->orig_commit),
2206 "--", NULL);
2207 cmd.git_cmd = 1;
2208 return run_command(&cmd);
Nguyễn Thái Ngọc Duy66335292018-02-11 16:43:27 +07002209 }
2210
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002211 switch (sub_mode) {
2212 case SHOW_PATCH_RAW:
2213 patch_path = am_path(state, msgnum(state));
2214 break;
Paolo Bonziniaa416b22020-02-20 15:15:19 +01002215 case SHOW_PATCH_DIFF:
2216 patch_path = am_path(state, "patch");
2217 break;
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002218 default:
2219 BUG("invalid mode for --show-current-patch");
2220 }
2221
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002222 len = strbuf_read_file(&sb, patch_path, 0);
2223 if (len < 0)
2224 die_errno(_("failed to read '%s'"), patch_path);
2225
2226 setup_pager();
2227 write_in_full(1, sb.buf, sb.len);
2228 strbuf_release(&sb);
2229 return 0;
2230}
2231
Paul Tan33388a72015-08-04 21:51:35 +08002232/**
Paul Tan11c21772015-08-04 21:51:26 +08002233 * parse_options() callback that validates and sets opt->value to the
2234 * PATCH_FORMAT_* enum value corresponding to `arg`.
2235 */
2236static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
2237{
2238 int *opt_value = opt->value;
2239
Jeff Kingfce56642018-11-05 01:38:39 -05002240 if (unset)
2241 *opt_value = PATCH_FORMAT_UNKNOWN;
2242 else if (!strcmp(arg, "mbox"))
Paul Tan11c21772015-08-04 21:51:26 +08002243 *opt_value = PATCH_FORMAT_MBOX;
Paul Tan5ae41c72015-08-04 21:52:00 +08002244 else if (!strcmp(arg, "stgit"))
2245 *opt_value = PATCH_FORMAT_STGIT;
Paul Tan336108c2015-08-04 21:52:01 +08002246 else if (!strcmp(arg, "stgit-series"))
2247 *opt_value = PATCH_FORMAT_STGIT_SERIES;
Paul Tan94cd1752015-08-04 21:52:02 +08002248 else if (!strcmp(arg, "hg"))
2249 *opt_value = PATCH_FORMAT_HG;
Eric Wongd9925d12016-06-05 04:46:41 +00002250 else if (!strcmp(arg, "mboxrd"))
2251 *opt_value = PATCH_FORMAT_MBOXRD;
Nguyễn Thái Ngọc Duy5a59a232019-02-16 18:24:41 +07002252 /*
2253 * Please update $__git_patchformat in git-completion.bash
2254 * when you add new options
2255 */
Paul Tan11c21772015-08-04 21:51:26 +08002256 else
Jean-Noël Avila1a8aea82022-01-31 22:07:47 +00002257 return error(_("invalid value for '%s': '%s'"),
2258 "--patch-format", arg);
Paul Tan11c21772015-08-04 21:51:26 +08002259 return 0;
2260}
2261
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002262enum resume_type {
Paul Tan240bfd22015-08-04 21:51:32 +08002263 RESUME_FALSE = 0,
Paul Tan8c7b1562015-08-04 21:51:33 +08002264 RESUME_APPLY,
Paul Tan99900802015-08-04 21:51:34 +08002265 RESUME_RESOLVED,
Paul Tan33388a72015-08-04 21:51:35 +08002266 RESUME_SKIP,
Nguyễn Thái Ngọc Duy65ed8ff2018-02-14 18:16:06 +07002267 RESUME_ABORT,
Junio C Hamano9ca488c2018-03-06 14:54:02 -08002268 RESUME_QUIT,
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00002269 RESUME_SHOW_PATCH,
2270 RESUME_ALLOW_EMPTY,
Paul Tan240bfd22015-08-04 21:51:32 +08002271};
2272
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002273struct resume_mode {
2274 enum resume_type mode;
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002275 enum show_patch_type sub_mode;
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002276};
2277
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002278static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
2279{
2280 int *opt_value = opt->value;
2281 struct resume_mode *resume = container_of(opt_value, struct resume_mode, mode);
2282
2283 /*
2284 * Please update $__git_showcurrentpatch in git-completion.bash
2285 * when you add new options
2286 */
2287 const char *valid_modes[] = {
Paolo Bonziniaa416b22020-02-20 15:15:19 +01002288 [SHOW_PATCH_DIFF] = "diff",
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002289 [SHOW_PATCH_RAW] = "raw"
2290 };
2291 int new_value = SHOW_PATCH_RAW;
2292
Jeff King8d2aa8d2020-09-30 08:29:02 -04002293 BUG_ON_OPT_NEG(unset);
2294
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002295 if (arg) {
2296 for (new_value = 0; new_value < ARRAY_SIZE(valid_modes); new_value++) {
2297 if (!strcmp(arg, valid_modes[new_value]))
2298 break;
2299 }
2300 if (new_value >= ARRAY_SIZE(valid_modes))
Jean-Noël Avila1a8aea82022-01-31 22:07:47 +00002301 return error(_("invalid value for '%s': '%s'"),
2302 "--show-current-patch", arg);
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002303 }
2304
2305 if (resume->mode == RESUME_SHOW_PATCH && new_value != resume->sub_mode)
Jean-Noël Avila246cac82022-01-05 20:02:24 +00002306 return error(_("options '%s=%s' and '%s=%s' "
2307 "cannot be used together"),
2308 "--show-current-patch", "--show-current-patch", arg, valid_modes[resume->sub_mode]);
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002309
2310 resume->mode = RESUME_SHOW_PATCH;
2311 resume->sub_mode = new_value;
2312 return 0;
2313}
2314
Ævar Arnfjörð Bjarmason5cf88fd2022-08-25 19:09:48 +02002315static int git_am_config(const char *k, const char *v, void *cb UNUSED)
Renee Margaret McConahy434c64d2015-09-30 13:49:44 -04002316{
2317 int status;
2318
2319 status = git_gpg_config(k, v, NULL);
2320 if (status)
2321 return status;
2322
2323 return git_default_config(k, v, NULL);
2324}
2325
Paul Tan73c27792015-08-04 21:51:24 +08002326int cmd_am(int argc, const char **argv, const char *prefix)
2327{
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002328 struct am_state state;
Paul Tanc2676cd2015-08-04 21:52:04 +08002329 int binary = -1;
Paul Tan5d123a42015-08-04 21:51:48 +08002330 int keep_cr = -1;
Paul Tan11c21772015-08-04 21:51:26 +08002331 int patch_format = PATCH_FORMAT_UNKNOWN;
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002332 struct resume_mode resume = { .mode = RESUME_FALSE };
Paul Tan852a1712015-08-04 22:08:50 +08002333 int in_progress;
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002334 int ret = 0;
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002335
2336 const char * const usage[] = {
Alex Henried65fdc92016-09-07 22:33:08 -06002337 N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
Ralf Thielowd96a0312015-10-16 19:09:57 +02002338 N_("git am [<options>] (--continue | --skip | --abort)"),
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002339 NULL
2340 };
2341
2342 struct option options[] = {
Paul Tan7ff26832015-08-04 21:52:03 +08002343 OPT_BOOL('i', "interactive", &state.interactive,
2344 N_("run interactively")),
Thierry Reding566902f2022-11-30 18:28:33 +01002345 OPT_BOOL('n', "no-verify", &state.no_verify,
2346 N_("bypass pre-applypatch and applypatch-msg hooks")),
Paul Tanc2676cd2015-08-04 21:52:04 +08002347 OPT_HIDDEN_BOOL('b', "binary", &binary,
Jiang Xin1fb5a0e2015-08-26 23:51:19 +08002348 N_("historical option -- no-op")),
Paul Tan84f3de22015-08-04 21:51:41 +08002349 OPT_BOOL('3', "3way", &state.threeway,
2350 N_("allow fall back on 3way merging if needed")),
Paul Tan5d28cf72015-08-04 21:51:37 +08002351 OPT__QUIET(&state.quiet, N_("be quiet")),
Paul Tanb5e82352015-08-04 22:08:51 +08002352 OPT_SET_INT('s', "signoff", &state.signoff,
Bradley M. Kuhn3abd4a62020-10-19 18:03:55 -07002353 N_("add a Signed-off-by trailer to the commit message"),
Paul Tanb5e82352015-08-04 22:08:51 +08002354 SIGNOFF_EXPLICIT),
Paul Tanef7ee162015-08-04 21:51:45 +08002355 OPT_BOOL('u', "utf8", &state.utf8,
2356 N_("recode into utf8 (default)")),
Paul Tan4f1b6962015-08-04 21:51:46 +08002357 OPT_SET_INT('k', "keep", &state.keep,
2358 N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
2359 OPT_SET_INT(0, "keep-non-patch", &state.keep,
2360 N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
Paul Tan702cbaa2015-08-04 21:51:47 +08002361 OPT_BOOL('m', "message-id", &state.message_id,
2362 N_("pass -m flag to git-mailinfo")),
Nguyễn Thái Ngọc Duy3e4a67b2018-05-20 17:42:58 +02002363 OPT_SET_INT_F(0, "keep-cr", &keep_cr,
2364 N_("pass --keep-cr flag to git-mailsplit for mbox format"),
2365 1, PARSE_OPT_NONEG),
2366 OPT_SET_INT_F(0, "no-keep-cr", &keep_cr,
2367 N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
2368 0, PARSE_OPT_NONEG),
Paul Tan9b646612015-08-04 21:51:49 +08002369 OPT_BOOL('c', "scissors", &state.scissors,
2370 N_("strip everything before a scissors line")),
Đoàn Trần Công Danh59b519a2021-05-10 00:12:13 +07002371 OPT_CALLBACK_F(0, "quoted-cr", &state.quoted_cr, N_("action"),
2372 N_("pass it through git-mailinfo"),
2373 PARSE_OPT_NONEG, am_option_parse_quoted_cr),
Paul Tan257e8ce2015-08-04 21:51:50 +08002374 OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
2375 N_("pass it through git-apply"),
2376 0),
2377 OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
2378 N_("pass it through git-apply"),
2379 PARSE_OPT_NOARG),
2380 OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
2381 N_("pass it through git-apply"),
2382 PARSE_OPT_NOARG),
2383 OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
2384 N_("pass it through git-apply"),
2385 0),
2386 OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
2387 N_("pass it through git-apply"),
2388 0),
2389 OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
2390 N_("pass it through git-apply"),
2391 0),
2392 OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
2393 N_("pass it through git-apply"),
2394 0),
2395 OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
2396 N_("pass it through git-apply"),
2397 0),
Paul Tan11c21772015-08-04 21:51:26 +08002398 OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
2399 N_("format the patch(es) are in"),
2400 parse_opt_patchformat),
Paul Tan257e8ce2015-08-04 21:51:50 +08002401 OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
2402 N_("pass it through git-apply"),
2403 PARSE_OPT_NOARG),
Paul Tan2d831092015-08-04 21:51:38 +08002404 OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
2405 N_("override error message when patch failure occurs")),
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002406 OPT_CMDMODE(0, "continue", &resume.mode,
Paul Tan240bfd22015-08-04 21:51:32 +08002407 N_("continue applying patches after resolving a conflict"),
2408 RESUME_RESOLVED),
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002409 OPT_CMDMODE('r', "resolved", &resume.mode,
Paul Tan240bfd22015-08-04 21:51:32 +08002410 N_("synonyms for --continue"),
2411 RESUME_RESOLVED),
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002412 OPT_CMDMODE(0, "skip", &resume.mode,
Paul Tan99900802015-08-04 21:51:34 +08002413 N_("skip the current patch"),
2414 RESUME_SKIP),
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002415 OPT_CMDMODE(0, "abort", &resume.mode,
ZheNing Hue73fe3d2021-01-06 14:44:03 +00002416 N_("restore the original branch and abort the patching operation"),
Paul Tan33388a72015-08-04 21:51:35 +08002417 RESUME_ABORT),
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002418 OPT_CMDMODE(0, "quit", &resume.mode,
ZheNing Hue73fe3d2021-01-06 14:44:03 +00002419 N_("abort the patching operation but keep HEAD where it is"),
Nguyễn Thái Ngọc Duy65ed8ff2018-02-14 18:16:06 +07002420 RESUME_QUIT),
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002421 { OPTION_CALLBACK, 0, "show-current-patch", &resume.mode,
Paolo Bonziniaa416b22020-02-20 15:15:19 +01002422 "(diff|raw)",
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002423 N_("show the patch being applied"),
2424 PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
2425 parse_opt_show_current_patch, RESUME_SHOW_PATCH },
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00002426 OPT_CMDMODE(0, "allow-empty", &resume.mode,
2427 N_("record the empty patch as an empty commit"),
2428 RESUME_ALLOW_EMPTY),
Paul Tan0cd4bcb2015-08-04 21:51:52 +08002429 OPT_BOOL(0, "committer-date-is-author-date",
2430 &state.committer_date_is_author_date,
2431 N_("lie about committer date")),
Paul Tanf07adb62015-08-04 21:51:51 +08002432 OPT_BOOL(0, "ignore-date", &state.ignore_date,
2433 N_("use current timestamp for author date")),
Paul Tanf1cb96d2015-08-04 21:51:59 +08002434 OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
Paul Tan7e35dac2015-08-04 21:51:53 +08002435 { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
2436 N_("GPG-sign commits"),
2437 PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
徐沛文 (Aleen)7c096b82021-12-09 07:25:54 +00002438 OPT_CALLBACK_F(STOP_ON_EMPTY_COMMIT, "empty", &state.empty_type, "{stop,drop,keep}",
2439 N_("how to handle empty patches"),
2440 PARSE_OPT_NONEG, am_option_parse_empty),
Paul Tan35bdcc52015-08-04 21:51:42 +08002441 OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
2442 N_("(internal use for git-rebase)")),
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002443 OPT_END()
2444 };
Paul Tan73c27792015-08-04 21:51:24 +08002445
Jeff Kingf3a2fff2017-05-30 01:11:23 -04002446 if (argc == 2 && !strcmp(argv[1], "-h"))
2447 usage_with_options(usage, options);
2448
Renee Margaret McConahy434c64d2015-09-30 13:49:44 -04002449 git_config(git_am_config, NULL);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002450
Jeff King16d26762017-04-20 17:09:35 -04002451 am_state_init(&state);
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002452
Paul Tan852a1712015-08-04 22:08:50 +08002453 in_progress = am_in_progress(&state);
2454 if (in_progress)
2455 am_load(&state);
2456
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002457 argc = parse_options(argc, argv, prefix, options, usage, 0);
2458
Paul Tanc2676cd2015-08-04 21:52:04 +08002459 if (binary >= 0)
2460 fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
2461 "it will be removed. Please do not use it anymore."));
2462
Paul Tan5e4f9cf2015-08-04 21:52:05 +08002463 /* Ensure a valid committer ident can be constructed */
2464 git_committer_info(IDENT_STRICT);
2465
Nguyễn Thái Ngọc Duye1ff0a32019-01-12 09:13:26 +07002466 if (repo_read_index_preload(the_repository, NULL, 0) < 0)
Paul Tan38a824f2015-08-04 21:51:29 +08002467 die(_("failed to read the index"));
2468
Paul Tan852a1712015-08-04 22:08:50 +08002469 if (in_progress) {
Paul Tan8d185502015-08-04 21:51:36 +08002470 /*
2471 * Catch user error to feed us patches when there is a session
2472 * in progress:
2473 *
2474 * 1. mbox path(s) are provided on the command-line.
2475 * 2. stdin is not a tty: the user is trying to feed us a patch
2476 * from standard input. This is somewhat unreliable -- stdin
2477 * could be /dev/null for example and the caller did not
2478 * intend to feed us a patch but wanted to continue
2479 * unattended.
2480 */
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002481 if (argc || (resume.mode == RESUME_FALSE && !isatty(0)))
Paul Tan8d185502015-08-04 21:51:36 +08002482 die(_("previous rebase directory %s still exists but mbox given."),
2483 state.dir);
2484
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002485 if (resume.mode == RESUME_FALSE)
2486 resume.mode = RESUME_APPLY;
Paul Tanb5e82352015-08-04 22:08:51 +08002487
2488 if (state.signoff == SIGNOFF_EXPLICIT)
2489 am_append_signoff(&state);
Paul Tan8c7b1562015-08-04 21:51:33 +08002490 } else {
Jeff King22f9b7f2020-07-28 16:24:27 -04002491 struct strvec paths = STRVEC_INIT;
Paul Tan11c21772015-08-04 21:51:26 +08002492 int i;
2493
Paul Tan6d42ac22015-08-04 21:51:44 +08002494 /*
2495 * Handle stray state directory in the independent-run case. In
2496 * the --rebasing case, it is up to the caller to take care of
2497 * stray directories.
2498 */
2499 if (file_exists(state.dir) && !state.rebasing) {
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002500 if (resume.mode == RESUME_ABORT || resume.mode == RESUME_QUIT) {
Paul Tan6d42ac22015-08-04 21:51:44 +08002501 am_destroy(&state);
2502 am_state_release(&state);
2503 return 0;
2504 }
2505
2506 die(_("Stray %s directory found.\n"
2507 "Use \"git am --abort\" to remove it."),
2508 state.dir);
2509 }
2510
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002511 if (resume.mode)
Paul Tan240bfd22015-08-04 21:51:32 +08002512 die(_("Resolve operation not in progress, we are not resuming."));
2513
Paul Tan11c21772015-08-04 21:51:26 +08002514 for (i = 0; i < argc; i++) {
2515 if (is_absolute_path(argv[i]) || !prefix)
Jeff King22f9b7f2020-07-28 16:24:27 -04002516 strvec_push(&paths, argv[i]);
Paul Tan11c21772015-08-04 21:51:26 +08002517 else
Jeff King22f9b7f2020-07-28 16:24:27 -04002518 strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
Paul Tan11c21772015-08-04 21:51:26 +08002519 }
2520
Jeff Kingd70a9eb2020-07-28 20:37:20 -04002521 if (state.interactive && !paths.nr)
Jeff King6e7baf22019-05-20 08:11:13 -04002522 die(_("interactive mode requires patches on the command line"));
2523
Jeff Kingd70a9eb2020-07-28 20:37:20 -04002524 am_setup(&state, patch_format, paths.v, keep_cr);
Paul Tan11c21772015-08-04 21:51:26 +08002525
Jeff King22f9b7f2020-07-28 16:24:27 -04002526 strvec_clear(&paths);
Paul Tan11c21772015-08-04 21:51:26 +08002527 }
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002528
Paolo Bonzinie8ef1e82020-02-20 15:15:17 +01002529 switch (resume.mode) {
Paul Tan240bfd22015-08-04 21:51:32 +08002530 case RESUME_FALSE:
Paul Tan8c7b1562015-08-04 21:51:33 +08002531 am_run(&state, 0);
2532 break;
2533 case RESUME_APPLY:
2534 am_run(&state, 1);
Paul Tan240bfd22015-08-04 21:51:32 +08002535 break;
2536 case RESUME_RESOLVED:
徐沛文 (Aleen)9e7e41b2021-12-09 07:25:55 +00002537 case RESUME_ALLOW_EMPTY:
2538 am_resolve(&state, resume.mode == RESUME_ALLOW_EMPTY ? 1 : 0);
Paul Tan240bfd22015-08-04 21:51:32 +08002539 break;
Paul Tan99900802015-08-04 21:51:34 +08002540 case RESUME_SKIP:
2541 am_skip(&state);
2542 break;
Paul Tan33388a72015-08-04 21:51:35 +08002543 case RESUME_ABORT:
2544 am_abort(&state);
2545 break;
Nguyễn Thái Ngọc Duy65ed8ff2018-02-14 18:16:06 +07002546 case RESUME_QUIT:
2547 am_rerere_clear();
2548 am_destroy(&state);
2549 break;
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002550 case RESUME_SHOW_PATCH:
Paolo Bonzinif3b48222020-02-20 15:15:18 +01002551 ret = show_patch(&state, resume.sub_mode);
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002552 break;
Paul Tan240bfd22015-08-04 21:51:32 +08002553 default:
Johannes Schindelin033abf92018-05-02 11:38:39 +02002554 BUG("invalid resume value");
Paul Tan240bfd22015-08-04 21:51:32 +08002555 }
Paul Tan8c3bd9e2015-08-04 21:51:25 +08002556
2557 am_state_release(&state);
2558
Nguyễn Thái Ngọc Duy984913a2018-02-11 16:43:26 +07002559 return ret;
Paul Tan73c27792015-08-04 21:51:24 +08002560}