]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
The sixth batch
[thirdparty/git.git] / sequencer.c
CommitLineData
e7da9385 1#define USE_THE_REPOSITORY_VARIABLE
41f43b82 2#define DISABLE_SIGN_COMPARE_WARNINGS
e7da9385 3
bc5c5ec0 4#include "git-compat-util.h"
0b027f6c 5#include "abspath.h"
6c6ddf92 6#include "advice.h"
b2141fc1 7#include "config.h"
d5fff46f 8#include "copy.h"
7ee24e18 9#include "environment.h"
f394e093 10#include "gettext.h"
41771fa4 11#include "hex.h"
697cc8ef 12#include "lockfile.h"
26ae337b 13#include "dir.h"
87bed179 14#include "object-file.h"
dabab1d6 15#include "object-name.h"
68cd492a 16#include "object-store.h"
043a4492 17#include "object.h"
ca4eed70 18#include "pager.h"
043a4492 19#include "commit.h"
0505d604 20#include "sequencer.h"
043a4492 21#include "run-command.h"
5e3aba33 22#include "hook.h"
043a4492
RR
23#include "utf8.h"
24#include "cache-tree.h"
25#include "diff.h"
c339932b 26#include "path.h"
043a4492
RR
27#include "revision.h"
28#include "rerere.h"
750324dd 29#include "merge.h"
14c4586c
EN
30#include "merge-ort.h"
31#include "merge-ort-wrappers.h"
043a4492 32#include "refs.h"
baf889c2 33#include "sparse-index.h"
dbbcd44f 34#include "strvec.h"
a1c75762 35#include "quote.h"
967dfd4d 36#include "trailer.h"
56dc3ab0 37#include "log-tree.h"
311af526 38#include "wt-status.h"
c44a4c65 39#include "hashmap.h"
a87a6f3c
PW
40#include "notes-utils.h"
41#include "sigchain.h"
9055e401 42#include "unpack-trees.h"
1644c73c
JS
43#include "oidmap.h"
44#include "oidset.h"
8315bd20 45#include "commit-slab.h"
65b5f948 46#include "alias.h"
64043556 47#include "commit-reach.h"
b97e1873 48#include "rebase-interactive.h"
0816f1df 49#include "reset.h"
900b50c2 50#include "branch.h"
043a4492
RR
51
52#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 53
7481d2bf
MRP
54/*
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
58 * are too long.
59 * Add some margin to stay clear from reaching `NAME_MAX`.
60 */
61#define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
62
5fe81438 63static const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 64static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 65
66618a50
PW
66GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
67
901ba7b1 68static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
8a2a0f53
JS
69
70static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
71static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
72static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 73static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 74
84583957
JS
75static GIT_PATH_FUNC(rebase_path, "rebase-merge")
76/*
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
81 */
44b776c3 82GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
a930eb03 83GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
b97e1873 84
5a5445d8
AG
85GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
86
1df6df0c
JS
87/*
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
90 * actions.
91 */
92static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
93/*
94 * The file to keep track of how many commands were already processed (e.g.
95 * for the prompt).
96 */
9ad36356 97static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
98/*
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
101 */
9ad36356 102static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
103/*
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
106 */
107static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
108/*
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
6e98de72
JS
115 */
116static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
117/*
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
123 */
124static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
125/*
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
128 */
129static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
130/*
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
133 * being rebased.
134 */
135static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
136/*
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
143 */
144static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
145/*
146 * When we stop at a given patch via the "edit" command, this file contains
0512eabd 147 * the commit object name of the corresponding patch.
56dc3ab0
JS
148 */
149static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
206a78d7
PW
150/*
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
153 */
154static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
25cb8df9
JS
155/*
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
160 */
161static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
162static GIT_PATH_FUNC(rebase_path_rewritten_pending,
163 "rebase-merge/rewritten-pending")
9055e401 164
d87d48b2 165/*
15beaaa3 166 * The path of the file containing the OID of the "squash onto" commit, i.e.
d87d48b2
JS
167 * the dummy commit used for `reset [new root]`.
168 */
169static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
170
9055e401
JS
171/*
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
174 */
175static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
176
aa7f2fd1
DS
177/*
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
182 *
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
185 */
186static char *rebase_path_update_refs(const char *wt_git_dir)
187{
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189}
190
a1c75762
JS
191/*
192 * The following files are written by git-rebase just after parsing the
65850686 193 * command-line.
a1c75762
JS
194 */
195static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
7573cec5 196static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
a3894aad 197static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
556907f1
JS
198static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
199static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
899b49c4 200static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
a852ec7f 201static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
202static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
203static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 204static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
205static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
206static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 207static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
d421afa0 208static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
e5b32bff 209static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
e98c4269
EN
210static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
211static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
b5a67045 212
a3152edc
PW
213/*
214 * A 'struct replay_ctx' represents the private state of the sequencer.
215 */
216struct replay_ctx {
53f67466
PW
217 /*
218 * The commit message that will be used except at the end of a
219 * chain of fixup and squash commands.
220 */
221 struct strbuf message;
497a01a2
PW
222 /*
223 * The list of completed fixup and squash commands in the
224 * current chain.
225 */
226 struct strbuf current_fixups;
497a01a2
PW
227 /*
228 * The number of completed fixup and squash commands in the
229 * current chain.
230 */
231 int current_fixup_count;
53f67466
PW
232 /*
233 * Whether message contains a commit message.
234 */
235 unsigned have_message :1;
a3152edc
PW
236};
237
238struct replay_ctx* replay_ctx_new(void)
239{
240 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
241
497a01a2 242 strbuf_init(&ctx->current_fixups, 0);
53f67466 243 strbuf_init(&ctx->message, 0);
497a01a2 244
a3152edc
PW
245 return ctx;
246}
247
aa7f2fd1
DS
248/**
249 * A 'struct update_refs_record' represents a value in the update-refs
250 * list. We use a string_list to map refs to these (before, after) pairs.
251 */
252struct update_ref_record {
253 struct object_id before;
254 struct object_id after;
255};
256
89fc0b53
DS
257static struct update_ref_record *init_update_ref_record(const char *ref)
258{
259 struct update_ref_record *rec;
260
261 CALLOC_ARRAY(rec, 1);
262
7d70b29c
PS
263 oidcpy(&rec->before, null_oid(the_hash_algo));
264 oidcpy(&rec->after, null_oid(the_hash_algo));
89fc0b53
DS
265
266 /* This may fail, but that's fine, we will keep the null OID. */
2e5c4758 267 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
89fc0b53
DS
268
269 return rec;
270}
271
a4e7e317
GC
272static int git_sequencer_config(const char *k, const char *v,
273 const struct config_context *ctx, void *cb)
28d6daed
PW
274{
275 struct replay_opts *opts = cb;
28d6daed
PW
276
277 if (!strcmp(k, "commit.cleanup")) {
ea8f9494
JK
278 if (!v)
279 return config_error_nonbool(k);
28d6daed 280
ea8f9494 281 if (!strcmp(v, "verbatim")) {
28d6daed 282 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58 283 opts->explicit_cleanup = 1;
ea8f9494 284 } else if (!strcmp(v, "whitespace")) {
28d6daed 285 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58 286 opts->explicit_cleanup = 1;
ea8f9494 287 } else if (!strcmp(v, "strip")) {
28d6daed 288 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
d74f3e58 289 opts->explicit_cleanup = 1;
ea8f9494 290 } else if (!strcmp(v, "scissors")) {
1a2b985f 291 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
d74f3e58
PW
292 opts->explicit_cleanup = 1;
293 } else {
28d6daed 294 warning(_("invalid commit message cleanup mode '%s'"),
ea8f9494 295 v);
d74f3e58 296 }
28d6daed 297
ea8f9494 298 return 0;
28d6daed
PW
299 }
300
301 if (!strcmp(k, "commit.gpgsign")) {
1ca57bea 302 free(opts->gpg_sign);
ed1e5282 303 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
304 return 0;
305 }
306
14c4586c 307 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
1b261c20 308 int ret = git_config_string(&opts->default_strategy, k, v);
14c4586c
EN
309 if (ret == 0) {
310 /*
311 * pull.twohead is allowed to be multi-valued; we only
312 * care about the first value.
313 */
314 char *tmp = strchr(opts->default_strategy, ' ');
315 if (tmp)
316 *tmp = '\0';
317 }
318 return ret;
319 }
320
191faaf7 321 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
43966ab3
JH
322 opts->commit_use_reference = git_config_bool(k, v);
323
a4e7e317 324 return git_diff_basic_config(k, v, ctx, NULL);
28d6daed
PW
325}
326
327void sequencer_init_config(struct replay_opts *opts)
328{
329 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
330 git_config(git_sequencer_config, opts);
331}
332
b5a67045
JS
333static inline int is_rebase_i(const struct replay_opts *opts)
334{
84583957 335 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
336}
337
285abf56
JS
338static const char *get_dir(const struct replay_opts *opts)
339{
84583957
JS
340 if (is_rebase_i(opts))
341 return rebase_path();
285abf56
JS
342 return git_path_seq_dir();
343}
344
c0246501
JS
345static const char *get_todo_path(const struct replay_opts *opts)
346{
84583957
JS
347 if (is_rebase_i(opts))
348 return rebase_path_todo();
c0246501
JS
349 return git_path_todo_file();
350}
351
bab4d109
BC
352/*
353 * Returns 0 for non-conforming footer
354 * Returns 1 for conforming footer
355 * Returns 2 when sob exists within conforming footer
356 * Returns 3 when sob exists within conforming footer as last entry
357 */
358static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
66e83d9b 359 size_t ignore_footer)
b971e04f 360{
2ade0543
LA
361 struct trailer_iterator iter;
362 size_t i = 0;
967dfd4d 363 int found_sob = 0, found_sob_last = 0;
9dad073d 364 char saved_char;
b971e04f 365
9dad073d
JK
366 if (ignore_footer) {
367 saved_char = sb->buf[sb->len - ignore_footer];
368 sb->buf[sb->len - ignore_footer] = '\0';
369 }
370
2ade0543 371 trailer_iterator_init(&iter, sb->buf);
b971e04f 372
9dad073d
JK
373 if (ignore_footer)
374 sb->buf[sb->len - ignore_footer] = saved_char;
375
2ade0543
LA
376 while (trailer_iterator_advance(&iter)) {
377 i++;
378 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
379 found_sob = i;
380 }
381 trailer_iterator_release(&iter);
b971e04f 382
2ade0543
LA
383 if (!i)
384 return 0;
b971e04f 385
2ade0543 386 found_sob_last = (int)i == found_sob;
bab4d109 387
967dfd4d 388 if (found_sob_last)
bab4d109
BC
389 return 3;
390 if (found_sob)
391 return 2;
b971e04f
BC
392 return 1;
393}
5ed75e2a 394
a1c75762
JS
395static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
396{
397 static struct strbuf buf = STRBUF_INIT;
398
399 strbuf_reset(&buf);
400 if (opts->gpg_sign)
401 sq_quotef(&buf, "-S%s", opts->gpg_sign);
402 return buf.buf;
403}
404
497a01a2
PW
405static void replay_ctx_release(struct replay_ctx *ctx)
406{
407 strbuf_release(&ctx->current_fixups);
53f67466 408 strbuf_release(&ctx->message);
497a01a2
PW
409}
410
9ff2f060 411void replay_opts_release(struct replay_opts *opts)
6a09c3a9 412{
497a01a2
PW
413 struct replay_ctx *ctx = opts->ctx;
414
6a09c3a9
ÆAB
415 free(opts->gpg_sign);
416 free(opts->reflog_action);
417 free(opts->default_strategy);
418 free(opts->strategy);
fb60b9f3 419 strvec_clear (&opts->xopts);
a6a700a4
ÆAB
420 if (opts->revs)
421 release_revisions(opts->revs);
422 free(opts->revs);
497a01a2 423 replay_ctx_release(ctx);
a3152edc 424 free(opts->ctx);
6a09c3a9
ÆAB
425}
426
2863584f 427int sequencer_remove_state(struct replay_opts *opts)
26ae337b 428{
9055e401 429 struct strbuf buf = STRBUF_INIT;
6a09c3a9 430 int ret = 0;
03a4e260 431
9055e401
JS
432 if (is_rebase_i(opts) &&
433 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
434 char *p = buf.buf;
435 while (*p) {
436 char *eol = strchr(p, '\n');
437 if (eol)
438 *eol = '\0';
2e5c4758 439 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
9055e401 440 warning(_("could not delete '%s'"), p);
37e9ee5c
PW
441 ret = -1;
442 }
9055e401
JS
443 if (!eol)
444 break;
445 p = eol + 1;
446 }
447 }
448
9055e401
JS
449 strbuf_reset(&buf);
450 strbuf_addstr(&buf, get_dir(opts));
37e9ee5c
PW
451 if (remove_dir_recursively(&buf, 0))
452 ret = error(_("could not remove '%s'"), buf.buf);
9055e401 453 strbuf_release(&buf);
2863584f 454
37e9ee5c 455 return ret;
26ae337b 456}
043a4492
RR
457
458static const char *action_name(const struct replay_opts *opts)
459{
84583957
JS
460 switch (opts->action) {
461 case REPLAY_REVERT:
462 return N_("revert");
463 case REPLAY_PICK:
464 return N_("cherry-pick");
465 case REPLAY_INTERACTIVE_REBASE:
c2417d3a 466 return N_("rebase");
84583957 467 }
1a07e59c 468 die(_("unknown action: %d"), opts->action);
043a4492
RR
469}
470
043a4492
RR
471struct commit_message {
472 char *parent_label;
7b35eaf8
JK
473 char *label;
474 char *subject;
043a4492
RR
475 const char *message;
476};
477
cb646ffb 478static const char *short_commit_name(struct repository *r, struct commit *commit)
39755964 479{
cb646ffb 480 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
39755964
JS
481}
482
043a4492
RR
483static int get_message(struct commit *commit, struct commit_message *out)
484{
043a4492 485 const char *abbrev, *subject;
7b35eaf8 486 int subject_len;
043a4492 487
ecb5091f
ÆAB
488 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
489 get_commit_output_encoding());
cb646ffb 490 abbrev = short_commit_name(the_repository, commit);
043a4492
RR
491
492 subject_len = find_commit_subject(out->message, &subject);
493
7b35eaf8 494 out->subject = xmemdupz(subject, subject_len);
7d056dea 495 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
7b35eaf8
JK
496 out->parent_label = xstrfmt("parent of %s", out->label);
497
043a4492
RR
498 return 0;
499}
500
d74a4e57 501static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
502{
503 free(msg->parent_label);
7b35eaf8
JK
504 free(msg->label);
505 free(msg->subject);
ecb5091f 506 repo_unuse_commit_buffer(the_repository, commit, msg->message);
043a4492
RR
507}
508
72a8d3f0
PW
509const char *rebase_resolvemsg =
510N_("Resolve all conflicts manually, mark them as resolved with\n"
511"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
512"You can instead skip this commit: run \"git rebase --skip\".\n"
513"To abort and get back to the state before \"git rebase\", run "
514"\"git rebase --abort\".");
515
005af339
NTND
516static void print_advice(struct repository *r, int show_hint,
517 struct replay_opts *opts)
043a4492 518{
72a8d3f0
PW
519 const char *msg;
520
521 if (is_rebase_i(opts))
522 msg = rebase_resolvemsg;
523 else
524 msg = getenv("GIT_CHERRY_PICK_HELP");
043a4492
RR
525
526 if (msg) {
ec030091 527 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
043a4492 528 /*
41ccfdd9 529 * A conflict has occurred but the porcelain
043a4492
RR
530 * (typically rebase --interactive) wants to take care
531 * of the commit itself so remove CHERRY_PICK_HEAD
532 */
c8e4159e 533 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
821f6632 534 NULL, REF_NO_DEREF);
043a4492
RR
535 return;
536 }
537
ed727b19
PH
538 if (show_hint) {
539 if (opts->no_commit)
ec030091
PB
540 advise_if_enabled(ADVICE_MERGE_CONFLICT,
541 _("after resolving the conflicts, mark the corrected paths\n"
542 "with 'git add <paths>' or 'git rm <paths>'"));
f172556b 543 else if (opts->action == REPLAY_PICK)
ec030091
PB
544 advise_if_enabled(ADVICE_MERGE_CONFLICT,
545 _("After resolving the conflicts, mark them with\n"
546 "\"git add/rm <pathspec>\", then run\n"
547 "\"git cherry-pick --continue\".\n"
548 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
549 "To abort and get back to the state before \"git cherry-pick\",\n"
550 "run \"git cherry-pick --abort\"."));
f172556b 551 else if (opts->action == REPLAY_REVERT)
ec030091
PB
552 advise_if_enabled(ADVICE_MERGE_CONFLICT,
553 _("After resolving the conflicts, mark them with\n"
554 "\"git add/rm <pathspec>\", then run\n"
555 "\"git revert --continue\".\n"
556 "You can instead skip this commit with \"git revert --skip\".\n"
557 "To abort and get back to the state before \"git revert\",\n"
558 "run \"git revert --abort\"."));
ed727b19 559 else
f172556b 560 BUG("unexpected pick action in print_advice()");
ed727b19 561 }
043a4492
RR
562}
563
ddb81e50
AG
564static int write_message(const void *buf, size_t len, const char *filename,
565 int append_eol)
043a4492 566{
14bca6c6 567 struct lock_file msg_file = LOCK_INIT;
043a4492 568
4ef3d8f0
JS
569 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
570 if (msg_fd < 0)
93b3df6f 571 return error_errno(_("could not lock '%s'"), filename);
75871495 572 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 573 error_errno(_("could not write to '%s'"), filename);
4f66c837 574 rollback_lock_file(&msg_file);
bf5c0571 575 return -1;
4f66c837 576 }
f56fffef 577 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 578 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 579 rollback_lock_file(&msg_file);
bf5c0571 580 return -1;
f56fffef 581 }
350292a1
582 if (commit_lock_file(&msg_file) < 0)
583 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
584
585 return 0;
043a4492
RR
586}
587
c20de8be 588int read_oneliner(struct strbuf *buf,
3442c3d1 589 const char *path, unsigned flags)
1dfc84e9
JS
590{
591 int orig_len = buf->len;
592
1dfc84e9 593 if (strbuf_read_file(buf, path, 0) < 0) {
bfa50c2c
DL
594 if ((flags & READ_ONELINER_WARN_MISSING) ||
595 (errno != ENOENT && errno != ENOTDIR))
5b2f6d9c 596 warning_errno(_("could not read '%s'"), path);
1dfc84e9
JS
597 return 0;
598 }
599
600 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
601 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
602 --buf->len;
603 buf->buf[buf->len] = '\0';
604 }
605
3442c3d1 606 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
1dfc84e9
JS
607 return 0;
608
609 return 1;
610}
611
005af339 612static struct tree *empty_tree(struct repository *r)
043a4492 613{
005af339 614 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
615}
616
e1ff0a32 617static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 618{
e1ff0a32 619 if (repo_read_index_unmerged(repo))
1c8dfc36 620 return error_resolve_conflict(action_name(opts));
043a4492 621
93b3df6f 622 error(_("your local changes would be overwritten by %s."),
c28cbc5e 623 _(action_name(opts)));
043a4492 624
ed9bff08 625 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
93b3df6f 626 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
627 return -1;
628}
629
1e41229d
SB
630static void update_abort_safety_file(void)
631{
632 struct object_id head;
633
634 /* Do nothing on a single-pick */
635 if (!file_exists(git_path_seq_dir()))
636 return;
637
d850b7a5 638 if (!repo_get_oid(the_repository, "HEAD", &head))
1e41229d
SB
639 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
640 else
641 write_file(git_path_abort_safety_file(), "%s", "");
642}
643
f11c9580
NTND
644static int fast_forward_to(struct repository *r,
645 const struct object_id *to,
646 const struct object_id *from,
647 int unborn,
648 struct replay_opts *opts)
043a4492 649{
d668d16c 650 struct ref_transaction *transaction;
eb4be1cb 651 struct strbuf sb = STRBUF_INIT;
d668d16c 652 struct strbuf err = STRBUF_INIT;
043a4492 653
e1ff0a32 654 repo_read_index(r);
f11c9580 655 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 656 return -1; /* the callee should have complained already */
651ab9f5 657
5670e0ec 658 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
d668d16c 659
2e5c4758 660 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
a0efef14 661 0, &err);
d668d16c
RS
662 if (!transaction ||
663 ref_transaction_update(transaction, "HEAD",
d87d48b2 664 to, unborn && !is_rebase_i(opts) ?
7d70b29c 665 null_oid(the_hash_algo) : from, NULL, NULL,
1d147bdf 666 0, sb.buf, &err) ||
db7516ab 667 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
668 ref_transaction_free(transaction);
669 error("%s", err.buf);
670 strbuf_release(&sb);
671 strbuf_release(&err);
672 return -1;
673 }
651ab9f5 674
eb4be1cb 675 strbuf_release(&sb);
d668d16c
RS
676 strbuf_release(&err);
677 ref_transaction_free(transaction);
1e41229d 678 update_abort_safety_file();
d668d16c 679 return 0;
043a4492
RR
680}
681
f29cd862
DL
682enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
683 int use_editor)
684{
685 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
686 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
687 COMMIT_MSG_CLEANUP_SPACE;
688 else if (!strcmp(cleanup_arg, "verbatim"))
689 return COMMIT_MSG_CLEANUP_NONE;
690 else if (!strcmp(cleanup_arg, "whitespace"))
691 return COMMIT_MSG_CLEANUP_SPACE;
692 else if (!strcmp(cleanup_arg, "strip"))
693 return COMMIT_MSG_CLEANUP_ALL;
694 else if (!strcmp(cleanup_arg, "scissors"))
695 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
696 COMMIT_MSG_CLEANUP_SPACE;
697 else
698 die(_("Invalid cleanup mode %s"), cleanup_arg);
699}
700
dc42e9a8
PW
701/*
702 * NB using int rather than enum cleanup_mode to stop clang's
703 * -Wtautological-constant-out-of-range-compare complaining that the comparison
704 * is always true.
705 */
706static const char *describe_cleanup_mode(int cleanup_mode)
707{
708 static const char *modes[] = { "whitespace",
709 "verbatim",
710 "scissors",
711 "strip" };
712
713 if (cleanup_mode < ARRAY_SIZE(modes))
714 return modes[cleanup_mode];
715
716 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
717}
718
f11c9580 719void append_conflicts_hint(struct index_state *istate,
1a2b985f 720 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
75c961b7
JH
721{
722 int i;
723
1a2b985f
DL
724 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
725 strbuf_addch(msgbuf, '\n');
726 wt_status_append_cut_line(msgbuf);
f99e1d94 727 strbuf_addstr(msgbuf, comment_line_str);
1a2b985f
DL
728 }
729
261f315b 730 strbuf_addch(msgbuf, '\n');
3a35d962 731 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
f11c9580
NTND
732 for (i = 0; i < istate->cache_nr;) {
733 const struct cache_entry *ce = istate->cache[i++];
75c961b7 734 if (ce_stage(ce)) {
3a35d962 735 strbuf_commented_addf(msgbuf, comment_line_str,
787cb8a4 736 "\t%s\n", ce->name);
f11c9580
NTND
737 while (i < istate->cache_nr &&
738 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
739 i++;
740 }
741 }
742}
743
f11c9580
NTND
744static int do_recursive_merge(struct repository *r,
745 struct commit *base, struct commit *next,
043a4492 746 const char *base_label, const char *next_label,
48be4c62 747 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
748 struct replay_opts *opts)
749{
750 struct merge_options o;
14c4586c 751 struct merge_result result;
b4db8a2b 752 struct tree *next_tree, *base_tree, *head_tree;
14c4586c 753 int clean, show_output;
d20bc01a 754 int i;
14bca6c6 755 struct lock_file index_lock = LOCK_INIT;
043a4492 756
3a95f31d 757 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 758 return -1;
043a4492 759
e1ff0a32 760 repo_read_index(r);
043a4492 761
9c93ba4d 762 init_ui_merge_options(&o, r);
043a4492
RR
763 o.ancestor = base ? base_label : "(empty tree)";
764 o.branch1 = "HEAD";
765 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
766 if (is_rebase_i(opts))
767 o.buffer_output = 2;
9268cf4a 768 o.show_rename_progress = 1;
043a4492
RR
769
770 head_tree = parse_tree_indirect(head);
aa9f6189
JS
771 if (!head_tree)
772 return error(_("unable to read tree (%s)"), oid_to_hex(head));
4a93b899
ÆAB
773 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
774 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
043a4492 775
fb60b9f3
PW
776 for (i = 0; i < opts->xopts.nr; i++)
777 parse_merge_opt(&o, opts->xopts.v[i]);
043a4492 778
f7ca9bbe
EN
779 memset(&result, 0, sizeof(result));
780 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree, &result);
781 show_output = !is_rebase_i(opts) || !result.clean;
782 /*
783 * TODO: merge_switch_to_result will update index/working tree;
784 * we only really want to do that if !result.clean || this is
785 * the final patch to be picked. But determining this is the
786 * final patch would take some work, and "head_tree" would need
787 * to be replace with the tree the index matched before we
788 * started doing any picks.
789 */
790 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
791 clean = result.clean;
64816524
792 if (clean < 0) {
793 rollback_lock_file(&index_lock);
f241ff0d 794 return clean;
64816524 795 }
043a4492 796
f11c9580 797 if (write_locked_index(r->index, &index_lock,
61000814 798 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
799 /*
800 * TRANSLATORS: %s will be "revert", "cherry-pick" or
c2417d3a 801 * "rebase".
84583957 802 */
c527b55e 803 return error(_("%s: Unable to write new index file"),
c28cbc5e 804 _(action_name(opts)));
043a4492 805
75c961b7 806 if (!clean)
1a2b985f
DL
807 append_conflicts_hint(r->index, msgbuf,
808 opts->default_msg_cleanup);
043a4492
RR
809
810 return !clean;
811}
812
f11c9580 813static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 814{
f11c9580
NTND
815 if (!cache_tree_fully_valid(istate->cache_tree))
816 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
817 error(_("unable to update cache tree"));
818 return NULL;
819 }
820
f11c9580 821 return &istate->cache_tree->oid;
ba97aea1
JS
822}
823
005af339 824static int is_index_unchanged(struct repository *r)
b27cfb0d 825{
ba97aea1 826 struct object_id head_oid, *cache_tree_oid;
1b90588d 827 const struct object_id *head_tree_oid;
b27cfb0d 828 struct commit *head_commit;
005af339 829 struct index_state *istate = r->index;
1b90588d
BL
830 const char *head_name;
831
2e5c4758 832 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
1b90588d 833 /* Check to see if this is an unborn branch */
2e5c4758
PS
834 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
835 "HEAD",
836 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
837 &head_oid, NULL);
1b90588d
BL
838 if (!head_name ||
839 !starts_with(head_name, "refs/heads/") ||
840 !is_null_oid(&head_oid))
841 return error(_("could not resolve HEAD commit"));
842 head_tree_oid = the_hash_algo->empty_tree;
843 } else {
844 head_commit = lookup_commit(r, &head_oid);
b27cfb0d 845
1b90588d
BL
846 /*
847 * If head_commit is NULL, check_commit, called from
848 * lookup_commit, would have indicated that head_commit is not
849 * a commit object already. repo_parse_commit() will return failure
850 * without further complaints in such a case. Otherwise, if
851 * the commit is invalid, repo_parse_commit() will complain. So
852 * there is nothing for us to say here. Just return failure.
853 */
854 if (repo_parse_commit(r, head_commit))
855 return -1;
4b580061 856
1b90588d
BL
857 head_tree_oid = get_commit_tree_oid(head_commit);
858 }
b27cfb0d 859
f11c9580 860 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 861 return -1;
b27cfb0d 862
1b90588d 863 return oideq(cache_tree_oid, head_tree_oid);
b27cfb0d
NH
864}
865
0473f28a
JS
866static int write_author_script(const char *message)
867{
868 struct strbuf buf = STRBUF_INIT;
869 const char *eol;
870 int res;
871
872 for (;;)
873 if (!*message || starts_with(message, "\n")) {
874missing_author:
875 /* Missing 'author' line? */
876 unlink(rebase_path_author_script());
877 return 0;
878 } else if (skip_prefix(message, "author ", &message))
879 break;
880 else if ((eol = strchr(message, '\n')))
881 message = eol + 1;
882 else
883 goto missing_author;
884
885 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
886 while (*message && *message != '\n' && *message != '\r')
887 if (skip_prefix(message, " <", &message))
888 break;
889 else if (*message != '\'')
890 strbuf_addch(&buf, *(message++));
891 else
4aa5ff94 892 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
893 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
894 while (*message && *message != '\n' && *message != '\r')
895 if (skip_prefix(message, "> ", &message))
896 break;
897 else if (*message != '\'')
898 strbuf_addch(&buf, *(message++));
899 else
4aa5ff94 900 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
901 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
902 while (*message && *message != '\n' && *message != '\r')
903 if (*message != '\'')
904 strbuf_addch(&buf, *(message++));
905 else
4aa5ff94 906 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 907 strbuf_addch(&buf, '\'');
0473f28a
JS
908 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
909 strbuf_release(&buf);
910 return res;
911}
912
bcd33ec2
PW
913/**
914 * Take a series of KEY='VALUE' lines where VALUE part is
915 * sq-quoted, and append <KEY, VALUE> at the end of the string list
916 */
917static int parse_key_value_squoted(char *buf, struct string_list *list)
918{
919 while (*buf) {
920 struct string_list_item *item;
921 char *np;
922 char *cp = strchr(buf, '=');
923 if (!cp) {
924 np = strchrnul(buf, '\n');
925 return error(_("no key present in '%.*s'"),
926 (int) (np - buf), buf);
927 }
928 np = strchrnul(cp, '\n');
929 *cp++ = '\0';
930 item = string_list_append(list, buf);
931
932 buf = np + (*np == '\n');
933 *np = '\0';
934 cp = sq_dequote(cp);
935 if (!cp)
936 return error(_("unable to dequote value of '%s'"),
937 item->string);
938 item->util = xstrdup(cp);
939 }
940 return 0;
941}
4aa5ff94 942
bcd33ec2
PW
943/**
944 * Reads and parses the state directory's "author-script" file, and sets name,
945 * email and date accordingly.
946 * Returns 0 on success, -1 if the file could not be parsed.
947 *
948 * The author script is of the format:
949 *
950 * GIT_AUTHOR_NAME='$author_name'
951 * GIT_AUTHOR_EMAIL='$author_email'
952 * GIT_AUTHOR_DATE='$author_date'
953 *
954 * where $author_name, $author_email and $author_date are quoted. We are strict
c3c003e7 955 * with our parsing, as the file was meant to be eval'd in the now-removed
bcd33ec2
PW
956 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
957 * from what this function expects, it is better to bail out than to do
958 * something that the user does not expect.
4aa5ff94 959 */
bcd33ec2
PW
960int read_author_script(const char *path, char **name, char **email, char **date,
961 int allow_missing)
4aa5ff94 962{
bcd33ec2
PW
963 struct strbuf buf = STRBUF_INIT;
964 struct string_list kv = STRING_LIST_INIT_DUP;
965 int retval = -1; /* assume failure */
966 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 967
bcd33ec2
PW
968 if (strbuf_read_file(&buf, path, 256) <= 0) {
969 strbuf_release(&buf);
970 if (errno == ENOENT && allow_missing)
971 return 0;
972 else
973 return error_errno(_("could not open '%s' for reading"),
974 path);
975 }
976
977 if (parse_key_value_squoted(buf.buf, &kv))
978 goto finish;
979
980 for (i = 0; i < kv.nr; i++) {
981 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
982 if (name_i != -2)
983 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
984 else
985 name_i = i;
986 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
987 if (email_i != -2)
988 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
989 else
990 email_i = i;
991 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
992 if (date_i != -2)
993 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
994 else
995 date_i = i;
996 } else {
997 err = error(_("unknown variable '%s'"),
998 kv.items[i].string);
999 }
1000 }
1001 if (name_i == -2)
1002 error(_("missing 'GIT_AUTHOR_NAME'"));
1003 if (email_i == -2)
1004 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1005 if (date_i == -2)
1006 error(_("missing 'GIT_AUTHOR_DATE'"));
45350aeb 1007 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
bcd33ec2 1008 goto finish;
4d924528
JH
1009 *name = kv.items[name_i].util;
1010 *email = kv.items[email_i].util;
1011 *date = kv.items[date_i].util;
bcd33ec2
PW
1012 retval = 0;
1013finish:
1014 string_list_clear(&kv, !!retval);
1015 strbuf_release(&buf);
1016 return retval;
4aa5ff94
PW
1017}
1018
b5a67045 1019/*
4d010a75 1020 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
c972bf4c 1021 * file with shell quoting into struct strvec. Returns -1 on
4d010a75 1022 * error, 0 otherwise.
b5a67045 1023 */
c972bf4c 1024static int read_env_script(struct strvec *env)
b5a67045 1025{
4d010a75 1026 char *name, *email, *date;
b5a67045 1027
4d010a75
PW
1028 if (read_author_script(rebase_path_author_script(),
1029 &name, &email, &date, 0))
a2a20b0d 1030 return -1;
b5a67045 1031
c972bf4c
JK
1032 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1033 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1034 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
4d010a75
PW
1035 free(name);
1036 free(email);
1037 free(date);
b5a67045 1038
a2a20b0d 1039 return 0;
b5a67045
JS
1040}
1041
356ee465
PW
1042static char *get_author(const char *message)
1043{
1044 size_t len;
1045 const char *a;
1046
1047 a = find_commit_header(message, "author", &len);
1048 if (a)
1049 return xmemdupz(a, len);
1050
1051 return NULL;
1052}
1053
b3193252 1054static const char *author_date_from_env(const struct strvec *env)
7573cec5
PW
1055{
1056 int i;
1057 const char *date;
1058
9c31b19d
JH
1059 for (i = 0; i < env->nr; i++)
1060 if (skip_prefix(env->v[i],
7573cec5
PW
1061 "GIT_AUTHOR_DATE=", &date))
1062 return date;
1063 /*
1064 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1065 * reading the script
1066 */
1067 BUG("GIT_AUTHOR_DATE missing from author script");
1068}
1069
791eb870
JS
1070static const char staged_changes_advice[] =
1071N_("you have staged changes in your working tree\n"
1072"If these changes are meant to be squashed into the previous commit, run:\n"
1073"\n"
1074" git commit --amend %s\n"
1075"\n"
1076"If they are meant to go into a new commit, run:\n"
1077"\n"
1078" git commit %s\n"
1079"\n"
1080"In both cases, once you're done, continue with:\n"
1081"\n"
1082" git rebase --continue\n");
1083
789b3eff
JS
1084#define ALLOW_EMPTY (1<<0)
1085#define EDIT_MSG (1<<1)
1086#define AMEND_MSG (1<<2)
1087#define CLEANUP_MSG (1<<3)
b92ff6e8 1088#define VERIFY_MSG (1<<4)
d87d48b2 1089#define CREATE_ROOT_COMMIT (1<<5)
f7d42cee 1090#define VERBATIM_MSG (1<<6)
789b3eff 1091
34bec2c4
AG
1092static int run_command_silent_on_success(struct child_process *cmd)
1093{
1094 struct strbuf buf = STRBUF_INIT;
1095 int rc;
1096
1097 cmd->stdout_to_stderr = 1;
1098 rc = pipe_command(cmd,
1099 NULL, 0,
1100 NULL, 0,
1101 &buf, 0);
1102
1103 if (rc)
1104 fputs(buf.buf, stderr);
1105 strbuf_release(&buf);
1106 return rc;
1107}
1108
043a4492
RR
1109/*
1110 * If we are cherry-pick, and if the merge did not result in
1111 * hand-editing, we will hit this commit and inherit the original
1112 * author date and name.
b5a67045 1113 *
043a4492
RR
1114 * If we are revert, or if our cherry-pick results in a hand merge,
1115 * we had better say that the current user is responsible for that.
b5a67045
JS
1116 *
1117 * An exception is when run_git_commit() is called during an
1118 * interactive rebase: in that case, we will want to retain the
1119 * author metadata.
043a4492 1120 */
20f4b044 1121static int run_git_commit(const char *defmsg,
5dbaec62 1122 const char *reflog_action,
f11c9580 1123 struct replay_opts *opts,
789b3eff 1124 unsigned int flags)
043a4492 1125{
07d968ef 1126 struct child_process cmd = CHILD_PROCESS_INIT;
b27cfb0d 1127
f7d42cee
JS
1128 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1129 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1130
07d968ef
JS
1131 cmd.git_cmd = 1;
1132
9d6b9df1
PW
1133 if (is_rebase_i(opts) &&
1134 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1135 !(!defmsg && (flags & AMEND_MSG))) &&
29fda24d 1136 read_env_script(&cmd.env)) {
34bec2c4 1137 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 1138
34bec2c4
AG
1139 return error(_(staged_changes_advice),
1140 gpg_opt, gpg_opt);
b5a67045
JS
1141 }
1142
5dbaec62 1143 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", reflog_action);
d188a60d 1144
7573cec5 1145 if (opts->committer_date_is_author_date)
29fda24d 1146 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
9c31b19d
JH
1147 opts->ignore_date ?
1148 "" :
b3193252 1149 author_date_from_env(&cmd.env));
a3894aad 1150 if (opts->ignore_date)
29fda24d 1151 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
7573cec5 1152
c972bf4c 1153 strvec_push(&cmd.args, "commit");
043a4492 1154
b92ff6e8 1155 if (!(flags & VERIFY_MSG))
c972bf4c 1156 strvec_push(&cmd.args, "-n");
789b3eff 1157 if ((flags & AMEND_MSG))
c972bf4c 1158 strvec_push(&cmd.args, "--amend");
3bdd5522 1159 if (opts->gpg_sign)
c972bf4c 1160 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
cf0ad4d1 1161 else
c972bf4c 1162 strvec_push(&cmd.args, "--no-gpg-sign");
b5a67045 1163 if (defmsg)
c972bf4c 1164 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3 1165 else if (!(flags & EDIT_MSG))
c972bf4c 1166 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 1167 if ((flags & CLEANUP_MSG))
c972bf4c 1168 strvec_push(&cmd.args, "--cleanup=strip");
f7d42cee
JS
1169 if ((flags & VERBATIM_MSG))
1170 strvec_push(&cmd.args, "--cleanup=verbatim");
789b3eff 1171 if ((flags & EDIT_MSG))
c972bf4c 1172 strvec_push(&cmd.args, "-e");
789b3eff 1173 else if (!(flags & CLEANUP_MSG) &&
0009426d 1174 !opts->signoff && !opts->record_origin &&
1a2b985f 1175 !opts->explicit_cleanup)
c972bf4c 1176 strvec_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 1177
789b3eff 1178 if ((flags & ALLOW_EMPTY))
c972bf4c 1179 strvec_push(&cmd.args, "--allow-empty");
df478b74 1180
a3ec9eaf 1181 if (!(flags & EDIT_MSG))
c972bf4c 1182 strvec_push(&cmd.args, "--allow-empty-message");
4bee9584 1183
34bec2c4
AG
1184 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1185 return run_command_silent_on_success(&cmd);
1186 else
1187 return run_command(&cmd);
b27cfb0d
NH
1188}
1189
d0aaa46f
PW
1190static int rest_is_empty(const struct strbuf *sb, int start)
1191{
1192 int i, eol;
1193 const char *nl;
1194
1195 /* Check if the rest is just whitespace and Signed-off-by's. */
1196 for (i = start; i < sb->len; i++) {
1197 nl = memchr(sb->buf + i, '\n', sb->len - i);
1198 if (nl)
1199 eol = nl - sb->buf;
1200 else
1201 eol = sb->len;
1202
1203 if (strlen(sign_off_header) <= eol - i &&
1204 starts_with(sb->buf + i, sign_off_header)) {
1205 i = eol;
1206 continue;
1207 }
1208 while (i < eol)
1209 if (!isspace(sb->buf[i++]))
1210 return 0;
1211 }
1212
1213 return 1;
1214}
1215
f29cd862
DL
1216void cleanup_message(struct strbuf *msgbuf,
1217 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1218{
1219 if (verbose || /* Truncate the message just before the diff, if any. */
1220 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1221 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1222 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
787cb8a4 1223 strbuf_stripspace(msgbuf,
2982b656 1224 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
f29cd862
DL
1225}
1226
d0aaa46f
PW
1227/*
1228 * Find out if the message in the strbuf contains only whitespace and
1229 * Signed-off-by lines.
1230 */
1231int message_is_empty(const struct strbuf *sb,
1232 enum commit_msg_cleanup_mode cleanup_mode)
1233{
1234 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1235 return 0;
1236 return rest_is_empty(sb, 0);
1237}
1238
1239/*
1240 * See if the user edited the message in the editor or left what
1241 * was in the template intact
1242 */
1243int template_untouched(const struct strbuf *sb, const char *template_file,
1244 enum commit_msg_cleanup_mode cleanup_mode)
1245{
1246 struct strbuf tmpl = STRBUF_INIT;
1247 const char *start;
1248
1249 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1250 return 0;
1251
1252 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1253 return 0;
1254
787cb8a4 1255 strbuf_stripspace(&tmpl,
2982b656 1256 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
d0aaa46f
PW
1257 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1258 start = sb->buf;
1259 strbuf_release(&tmpl);
1260 return rest_is_empty(sb, start - sb->buf);
1261}
1262
0505d604
PW
1263int update_head_with_reflog(const struct commit *old_head,
1264 const struct object_id *new_head,
1265 const char *action, const struct strbuf *msg,
1266 struct strbuf *err)
1267{
1268 struct ref_transaction *transaction;
1269 struct strbuf sb = STRBUF_INIT;
1270 const char *nl;
1271 int ret = 0;
1272
1273 if (action) {
1274 strbuf_addstr(&sb, action);
1275 strbuf_addstr(&sb, ": ");
1276 }
1277
1278 nl = strchr(msg->buf, '\n');
1279 if (nl) {
1280 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1281 } else {
1282 strbuf_addbuf(&sb, msg);
1283 strbuf_addch(&sb, '\n');
1284 }
1285
2e5c4758 1286 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
a0efef14 1287 0, err);
0505d604
PW
1288 if (!transaction ||
1289 ref_transaction_update(transaction, "HEAD", new_head,
7d70b29c 1290 old_head ? &old_head->object.oid : null_oid(the_hash_algo),
1bc4cc3f 1291 NULL, NULL, 0, sb.buf, err) ||
0505d604
PW
1292 ref_transaction_commit(transaction, err)) {
1293 ret = -1;
1294 }
1295 ref_transaction_free(transaction);
1296 strbuf_release(&sb);
1297
1298 return ret;
1299}
1300
a87a6f3c
PW
1301static int run_rewrite_hook(const struct object_id *oldoid,
1302 const struct object_id *newoid)
1303{
1304 struct child_process proc = CHILD_PROCESS_INIT;
a87a6f3c
PW
1305 int code;
1306 struct strbuf sb = STRBUF_INIT;
169c9797 1307 const char *hook_path = find_hook(the_repository, "post-rewrite");
a87a6f3c 1308
2b709893 1309 if (!hook_path)
a87a6f3c
PW
1310 return 0;
1311
2b709893 1312 strvec_pushl(&proc.args, hook_path, "amend", NULL);
a87a6f3c
PW
1313 proc.in = -1;
1314 proc.stdout_to_stderr = 1;
6206286e 1315 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1316
1317 code = start_command(&proc);
1318 if (code)
1319 return code;
1320 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1321 sigchain_push(SIGPIPE, SIG_IGN);
1322 write_in_full(proc.in, sb.buf, sb.len);
1323 close(proc.in);
1324 strbuf_release(&sb);
1325 sigchain_pop(SIGPIPE);
1326 return finish_command(&proc);
1327}
1328
1d18d758
NTND
1329void commit_post_rewrite(struct repository *r,
1330 const struct commit *old_head,
a87a6f3c
PW
1331 const struct object_id *new_head)
1332{
1333 struct notes_rewrite_cfg *cfg;
1334
1335 cfg = init_copy_notes_for_rewrite("amend");
1336 if (cfg) {
1337 /* we are amending, so old_head is not NULL */
1338 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1339 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1340 }
1341 run_rewrite_hook(&old_head->object.oid, new_head);
1342}
1343
f11c9580
NTND
1344static int run_prepare_commit_msg_hook(struct repository *r,
1345 struct strbuf *msg,
1346 const char *commit)
66618a50 1347{
49697cb7
PW
1348 int ret = 0;
1349 const char *name, *arg1 = NULL, *arg2 = NULL;
66618a50
PW
1350
1351 name = git_path_commit_editmsg();
1352 if (write_message(msg->buf, msg->len, name, 0))
1353 return -1;
1354
49697cb7
PW
1355 if (commit) {
1356 arg1 = "commit";
1357 arg2 = commit;
1358 } else {
1359 arg1 = "message";
1360 }
a8cc5943 1361 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
49697cb7 1362 arg1, arg2, NULL))
66618a50 1363 ret = error(_("'prepare-commit-msg' hook failed"));
66618a50
PW
1364
1365 return ret;
1366}
1367
e47c6caf
PW
1368static const char implicit_ident_advice_noconfig[] =
1369N_("Your name and email address were configured automatically based\n"
1370"on your username and hostname. Please check that they are accurate.\n"
1371"You can suppress this message by setting them explicitly. Run the\n"
1372"following command and follow the instructions in your editor to edit\n"
1373"your configuration file:\n"
1374"\n"
1375" git config --global --edit\n"
1376"\n"
1377"After doing this, you may fix the identity used for this commit with:\n"
1378"\n"
1379" git commit --amend --reset-author\n");
1380
1381static const char implicit_ident_advice_config[] =
1382N_("Your name and email address were configured automatically based\n"
1383"on your username and hostname. Please check that they are accurate.\n"
1384"You can suppress this message by setting them explicitly:\n"
1385"\n"
1386" git config --global user.name \"Your Name\"\n"
1387" git config --global user.email you@example.com\n"
1388"\n"
1389"After doing this, you may fix the identity used for this commit with:\n"
1390"\n"
1391" git commit --amend --reset-author\n");
1392
1393static const char *implicit_ident_advice(void)
1394{
a03b097d 1395 char *user_config = interpolate_path("~/.gitconfig", 0);
e47c6caf
PW
1396 char *xdg_config = xdg_config_home("config");
1397 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1398
1399 free(user_config);
1400 free(xdg_config);
1401
1402 if (config_exists)
1403 return _(implicit_ident_advice_config);
1404 else
1405 return _(implicit_ident_advice_noconfig);
1406
1407}
1408
f11c9580
NTND
1409void print_commit_summary(struct repository *r,
1410 const char *prefix,
1411 const struct object_id *oid,
e47c6caf
PW
1412 unsigned int flags)
1413{
1414 struct rev_info rev;
1415 struct commit *commit;
1416 struct strbuf format = STRBUF_INIT;
1417 const char *head;
1418 struct pretty_print_context pctx = {0};
1419 struct strbuf author_ident = STRBUF_INIT;
1420 struct strbuf committer_ident = STRBUF_INIT;
ed90f041 1421 struct ref_store *refs;
e47c6caf 1422
f11c9580 1423 commit = lookup_commit(r, oid);
e47c6caf
PW
1424 if (!commit)
1425 die(_("couldn't look up newly created commit"));
4a93b899 1426 if (repo_parse_commit(r, commit))
e47c6caf
PW
1427 die(_("could not parse newly created commit"));
1428
1429 strbuf_addstr(&format, "format:%h] %s");
1430
4a93b899
ÆAB
1431 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1432 &pctx);
1433 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1434 &pctx);
e47c6caf
PW
1435 if (strbuf_cmp(&author_ident, &committer_ident)) {
1436 strbuf_addstr(&format, "\n Author: ");
1437 strbuf_addbuf_percentquote(&format, &author_ident);
1438 }
1439 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1440 struct strbuf date = STRBUF_INIT;
1441
4a93b899 1442 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
e47c6caf
PW
1443 strbuf_addstr(&format, "\n Date: ");
1444 strbuf_addbuf_percentquote(&format, &date);
1445 strbuf_release(&date);
1446 }
1447 if (!committer_ident_sufficiently_given()) {
1448 strbuf_addstr(&format, "\n Committer: ");
1449 strbuf_addbuf_percentquote(&format, &committer_ident);
ed9bff08 1450 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
e47c6caf
PW
1451 strbuf_addch(&format, '\n');
1452 strbuf_addstr(&format, implicit_ident_advice());
1453 }
1454 }
1455 strbuf_release(&author_ident);
1456 strbuf_release(&committer_ident);
1457
f11c9580 1458 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1459 setup_revisions(0, NULL, &rev, NULL);
1460
1461 rev.diff = 1;
1462 rev.diffopt.output_format =
1463 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1464
1465 rev.verbose_header = 1;
1466 rev.show_root_diff = 1;
1467 get_commit_format(format.buf, &rev);
1468 rev.always_show_header = 0;
0f57f731 1469 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1470 diff_setup_done(&rev.diffopt);
1471
4a93b899 1472 refs = get_main_ref_store(r);
ce14de03 1473 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
09444e74
ÆAB
1474 if (!head)
1475 die(_("unable to resolve HEAD after creating commit"));
e47c6caf
PW
1476 if (!strcmp(head, "HEAD"))
1477 head = _("detached HEAD");
1478 else
1479 skip_prefix(head, "refs/heads/", &head);
1480 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1481 _(" (root-commit)") : "");
1482
1483 if (!log_tree_commit(&rev, commit)) {
1484 rev.always_show_header = 1;
1485 rev.use_terminator = 1;
1486 log_tree_commit(&rev, commit);
1487 }
1488
2108fe4a 1489 release_revisions(&rev);
e47c6caf
PW
1490 strbuf_release(&format);
1491}
1492
005af339 1493static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1494{
1495 struct commit *current_head;
1496 struct object_id oid;
1497
4a93b899 1498 if (repo_get_oid(r, "HEAD", &oid)) {
356ee465
PW
1499 current_head = NULL;
1500 } else {
005af339 1501 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1502 if (!current_head)
1503 return error(_("could not parse HEAD"));
9001dc2a 1504 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1505 warning(_("HEAD %s is not a commit!"),
1506 oid_to_hex(&oid));
1507 }
4a93b899 1508 if (repo_parse_commit(r, current_head))
356ee465
PW
1509 return error(_("could not parse HEAD commit"));
1510 }
1511 *head = current_head;
1512
1513 return 0;
1514}
1515
1516/*
1517 * Try to commit without forking 'git commit'. In some cases we need
1518 * to run 'git commit' to display an error message
1519 *
1520 * Returns:
1521 * -1 - error unable to commit
1522 * 0 - success
1523 * 1 - run 'git commit'
1524 */
f11c9580
NTND
1525static int try_to_commit(struct repository *r,
1526 struct strbuf *msg, const char *author,
5dbaec62 1527 const char *reflog_action,
356ee465
PW
1528 struct replay_opts *opts, unsigned int flags,
1529 struct object_id *oid)
1530{
1531 struct object_id tree;
b0a31861 1532 struct commit *current_head = NULL;
356ee465
PW
1533 struct commit_list *parents = NULL;
1534 struct commit_extra_header *extra = NULL;
1535 struct strbuf err = STRBUF_INIT;
66618a50 1536 struct strbuf commit_msg = STRBUF_INIT;
4d924528 1537 char *amend_author = NULL;
7573cec5 1538 const char *committer = NULL;
66618a50 1539 const char *hook_commit = NULL;
356ee465
PW
1540 enum commit_msg_cleanup_mode cleanup;
1541 int res = 0;
1542
f7d42cee
JS
1543 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1544 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1545
005af339 1546 if (parse_head(r, &current_head))
356ee465 1547 return -1;
4d924528 1548
356ee465 1549 if (flags & AMEND_MSG) {
42d4e1d1 1550 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
356ee465 1551 const char *out_enc = get_commit_output_encoding();
4a93b899
ÆAB
1552 const char *message = repo_logmsg_reencode(r, current_head,
1553 NULL, out_enc);
356ee465
PW
1554
1555 if (!msg) {
1556 const char *orig_message = NULL;
1557
1558 find_commit_subject(message, &orig_message);
66618a50 1559 msg = &commit_msg;
356ee465 1560 strbuf_addstr(msg, orig_message);
66618a50 1561 hook_commit = "HEAD";
356ee465 1562 }
4d924528 1563 author = amend_author = get_author(message);
4a93b899 1564 repo_unuse_commit_buffer(r, current_head,
ecb5091f 1565 message);
356ee465
PW
1566 if (!author) {
1567 res = error(_("unable to parse commit author"));
1568 goto out;
1569 }
1570 parents = copy_commit_list(current_head->parents);
1571 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
b0a31861
PW
1572 } else if (current_head &&
1573 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
356ee465
PW
1574 commit_list_insert(current_head, &parents);
1575 }
1576
f11c9580 1577 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1578 res = error(_("git write-tree failed to write a tree"));
1579 goto out;
1580 }
1581
2d05ef27
PW
1582 if (!(flags & ALLOW_EMPTY)) {
1583 struct commit *first_parent = current_head;
1584
1585 if (flags & AMEND_MSG) {
1586 if (current_head->parents) {
1587 first_parent = current_head->parents->item;
1588 if (repo_parse_commit(r, first_parent)) {
1589 res = error(_("could not parse HEAD commit"));
1590 goto out;
1591 }
1592 } else {
1593 first_parent = NULL;
1594 }
1595 }
1596 if (oideq(first_parent
1597 ? get_commit_tree_oid(first_parent)
1598 : the_hash_algo->empty_tree,
1599 &tree)) {
1600 res = 1; /* run 'git commit' to display error message */
1601 goto out;
1602 }
356ee465
PW
1603 }
1604
169c9797 1605 if (hook_exists(r, "prepare-commit-msg")) {
f11c9580 1606 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1607 if (res)
1608 goto out;
1609 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1610 2048) < 0) {
1611 res = error_errno(_("unable to read commit message "
1612 "from '%s'"),
1613 git_path_commit_editmsg());
1614 goto out;
1615 }
1616 msg = &commit_msg;
1617 }
1618
d74f3e58
PW
1619 if (flags & CLEANUP_MSG)
1620 cleanup = COMMIT_MSG_CLEANUP_ALL;
f7d42cee
JS
1621 else if (flags & VERBATIM_MSG)
1622 cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
1623 else if ((opts->signoff || opts->record_origin) &&
1624 !opts->explicit_cleanup)
1625 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1626 else
1627 cleanup = opts->default_msg_cleanup;
66618a50
PW
1628
1629 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
787cb8a4 1630 strbuf_stripspace(msg,
2982b656 1631 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
a3ec9eaf 1632 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1633 res = 1; /* run 'git commit' to display error message */
1634 goto out;
1635 }
1636
7573cec5
PW
1637 if (opts->committer_date_is_author_date) {
1638 struct ident_split id;
1639 struct strbuf date = STRBUF_INIT;
1640
a3894aad
PW
1641 if (!opts->ignore_date) {
1642 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1643 res = error(_("invalid author identity '%s'"),
1644 author);
1645 goto out;
1646 }
1647 if (!id.date_begin) {
1648 res = error(_(
1649 "corrupt author: missing date information"));
1650 goto out;
1651 }
1652 strbuf_addf(&date, "@%.*s %.*s",
1653 (int)(id.date_end - id.date_begin),
1654 id.date_begin,
1655 (int)(id.tz_end - id.tz_begin),
1656 id.tz_begin);
1657 } else {
1658 reset_ident_date();
7573cec5 1659 }
2020451c
JK
1660 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1661 getenv("GIT_COMMITTER_EMAIL"),
a3894aad
PW
1662 WANT_COMMITTER_IDENT,
1663 opts->ignore_date ? NULL : date.buf,
7573cec5
PW
1664 IDENT_STRICT);
1665 strbuf_release(&date);
1666 } else {
1667 reset_ident_date();
1668 }
12f7babd 1669
a3894aad
PW
1670 if (opts->ignore_date) {
1671 struct ident_split id;
1672 char *name, *email;
12f7babd 1673
a3894aad
PW
1674 if (split_ident_line(&id, author, strlen(author)) < 0) {
1675 error(_("invalid author identity '%s'"), author);
1676 goto out;
1677 }
1678 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1679 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1680 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1681 IDENT_STRICT);
1682 free(name);
1683 free(email);
1684 }
1685
e8cbe211 1686 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
7573cec5 1687 author, committer, opts->gpg_sign, extra)) {
356ee465
PW
1688 res = error(_("failed to write commit object"));
1689 goto out;
1690 }
1691
5dbaec62 1692 if (update_head_with_reflog(current_head, oid, reflog_action,
d188a60d 1693 msg, &err)) {
356ee465
PW
1694 res = error("%s", err.buf);
1695 goto out;
1696 }
1697
a8cc5943 1698 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
356ee465 1699 if (flags & AMEND_MSG)
1d18d758 1700 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1701
1702out:
1703 free_commit_extra_headers(extra);
63c9bd37 1704 free_commit_list(parents);
356ee465 1705 strbuf_release(&err);
66618a50 1706 strbuf_release(&commit_msg);
4d924528 1707 free(amend_author);
356ee465
PW
1708
1709 return res;
1710}
1711
430b75f7
PW
1712static int write_rebase_head(struct object_id *oid)
1713{
2e5c4758
PS
1714 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1715 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
430b75f7
PW
1716 return error(_("could not update %s"), "REBASE_HEAD");
1717
1718 return 0;
1719}
1720
f11c9580
NTND
1721static int do_commit(struct repository *r,
1722 const char *msg_file, const char *author,
5dbaec62 1723 const char *reflog_action,
430b75f7
PW
1724 struct replay_opts *opts, unsigned int flags,
1725 struct object_id *oid)
356ee465
PW
1726{
1727 int res = 1;
1728
b0a31861 1729 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
356ee465
PW
1730 struct object_id oid;
1731 struct strbuf sb = STRBUF_INIT;
1732
1733 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1734 return error_errno(_("unable to read commit message "
1735 "from '%s'"),
1736 msg_file);
1737
f11c9580 1738 res = try_to_commit(r, msg_file ? &sb : NULL,
5dbaec62 1739 author, reflog_action, opts, flags, &oid);
356ee465
PW
1740 strbuf_release(&sb);
1741 if (!res) {
c8e4159e 1742 refs_delete_ref(get_main_ref_store(r), "",
821f6632 1743 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
f11c9580 1744 unlink(git_path_merge_msg(r));
356ee465 1745 if (!is_rebase_i(opts))
f11c9580 1746 print_commit_summary(r, NULL, &oid,
356ee465
PW
1747 SUMMARY_SHOW_AUTHOR_DATE);
1748 return res;
1749 }
1750 }
430b75f7
PW
1751 if (res == 1) {
1752 if (is_rebase_i(opts) && oid)
1753 if (write_rebase_head(oid))
1754 return -1;
5dbaec62 1755 return run_git_commit(msg_file, reflog_action, opts, flags);
430b75f7 1756 }
356ee465
PW
1757
1758 return res;
1759}
1760
b27cfb0d
NH
1761static int is_original_commit_empty(struct commit *commit)
1762{
092bbcdf 1763 const struct object_id *ptree_oid;
b27cfb0d 1764
ecb5091f 1765 if (repo_parse_commit(the_repository, commit))
aee42e1f 1766 return error(_("could not parse commit %s"),
f2fd0760 1767 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1768 if (commit->parents) {
1769 struct commit *parent = commit->parents->item;
ecb5091f 1770 if (repo_parse_commit(the_repository, parent))
aee42e1f 1771 return error(_("could not parse parent commit %s"),
f2fd0760 1772 oid_to_hex(&parent->object.oid));
2e27bd77 1773 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1774 } else {
eb0ccfd7 1775 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1776 }
043a4492 1777
4a7e27e9 1778 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1779}
1780
ac2b0e8f 1781/*
e98c4269
EN
1782 * Should empty commits be allowed? Return status:
1783 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1784 * 0: Halt on empty commit
1785 * 1: Allow empty commit
1786 * 2: Drop empty commit
ac2b0e8f 1787 */
f11c9580
NTND
1788static int allow_empty(struct repository *r,
1789 struct replay_opts *opts,
1790 struct commit *commit)
ac2b0e8f 1791{
d48e5e21 1792 int index_unchanged, originally_empty;
ac2b0e8f
JH
1793
1794 /*
661b671a
BL
1795 * For a commit that is initially empty, allow_empty determines if it
1796 * should be kept or not
ac2b0e8f 1797 *
661b671a
BL
1798 * For a commit that becomes empty, keep_redundant_commits and
1799 * drop_redundant_commits determine whether the commit should be kept or
1800 * dropped. If neither is specified, halt.
ac2b0e8f 1801 */
005af339 1802 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1803 if (index_unchanged < 0)
1804 return index_unchanged;
1805 if (!index_unchanged)
1806 return 0; /* we do not have to say --allow-empty */
1807
d48e5e21
EN
1808 originally_empty = is_original_commit_empty(commit);
1809 if (originally_empty < 0)
1810 return originally_empty;
e98c4269 1811 if (originally_empty)
661b671a
BL
1812 return opts->allow_empty;
1813 else if (opts->keep_redundant_commits)
ac2b0e8f 1814 return 1;
e98c4269
EN
1815 else if (opts->drop_redundant_commits)
1816 return 2;
1817 else
1818 return 0;
ac2b0e8f
JH
1819}
1820
414697a9
JS
1821static struct {
1822 char c;
1823 const char *str;
1824} todo_command_info[] = {
d7ce9a22
DS
1825 [TODO_PICK] = { 'p', "pick" },
1826 [TODO_REVERT] = { 0, "revert" },
1827 [TODO_EDIT] = { 'e', "edit" },
1828 [TODO_REWORD] = { 'r', "reword" },
1829 [TODO_FIXUP] = { 'f', "fixup" },
1830 [TODO_SQUASH] = { 's', "squash" },
1831 [TODO_EXEC] = { 'x', "exec" },
1832 [TODO_BREAK] = { 'b', "break" },
1833 [TODO_LABEL] = { 'l', "label" },
1834 [TODO_RESET] = { 't', "reset" },
1835 [TODO_MERGE] = { 'm', "merge" },
a97d7916 1836 [TODO_UPDATE_REF] = { 'u', "update-ref" },
d7ce9a22
DS
1837 [TODO_NOOP] = { 0, "noop" },
1838 [TODO_DROP] = { 'd', "drop" },
1839 [TODO_COMMENT] = { 0, NULL },
004fefa7
JS
1840};
1841
1842static const char *command_to_string(const enum todo_command command)
1843{
ac191470 1844 if (command < TODO_COMMENT)
414697a9 1845 return todo_command_info[command].str;
7eb35e07
JK
1846 if (command == TODO_COMMENT)
1847 return comment_line_str;
02127c63 1848 die(_("unknown command: %d"), command);
004fefa7
JS
1849}
1850
ee5462d6 1851static char command_to_char(const enum todo_command command)
d8ae6c84 1852{
68e7090f 1853 if (command < TODO_COMMENT)
d8ae6c84 1854 return todo_command_info[command].c;
7eb35e07 1855 return 0;
d8ae6c84
LB
1856}
1857
25c43667
JS
1858static int is_noop(const enum todo_command command)
1859{
b3fdd581 1860 return TODO_NOOP <= command;
25c43667 1861}
004fefa7 1862
6e98de72
JS
1863static int is_fixup(enum todo_command command)
1864{
1865 return command == TODO_FIXUP || command == TODO_SQUASH;
1866}
1867
d87d48b2
JS
1868/* Does this command create a (non-merge) commit? */
1869static int is_pick_or_similar(enum todo_command command)
1870{
1871 switch (command) {
1872 case TODO_PICK:
1873 case TODO_REVERT:
1874 case TODO_EDIT:
1875 case TODO_REWORD:
1876 case TODO_FIXUP:
1877 case TODO_SQUASH:
1878 return 1;
1879 default:
1880 return 0;
1881 }
1882}
1883
9e3cebd9
CM
1884enum todo_item_flags {
1885 TODO_EDIT_MERGE_MSG = (1 << 0),
1886 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1887 TODO_EDIT_FIXUP_MSG = (1 << 2),
1888};
1889
71ee81cd
CM
1890static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1891static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
9e3cebd9 1892static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
71ee81cd
CM
1893static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1894static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1895
1f969601 1896static int is_fixup_flag(enum todo_command command, unsigned flag)
498bb5b8 1897{
9e3cebd9
CM
1898 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1899 (flag & TODO_EDIT_FIXUP_MSG));
1900}
7cdb9682 1901
9e3cebd9
CM
1902/*
1903 * Wrapper around strbuf_add_commented_lines() which avoids double
1904 * commenting commit subjects.
1905 */
1906static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1907{
1908 const char *s = str;
2ec225d3 1909 while (starts_with_mem(s, len, comment_line_str)) {
9e3cebd9
CM
1910 size_t count;
1911 const char *n = memchr(s, '\n', len);
1912 if (!n)
1913 count = len;
1914 else
1915 count = n - s + 1;
1916 strbuf_add(buf, s, count);
1917 s += count;
1918 len -= count;
1919 }
a1bb146a 1920 strbuf_add_commented_lines(buf, s, len, comment_line_str);
9e3cebd9
CM
1921}
1922
1923/* Does the current fixup chain contain a squash command? */
497a01a2 1924static int seen_squash(struct replay_ctx *ctx)
9e3cebd9 1925{
497a01a2
PW
1926 return starts_with(ctx->current_fixups.buf, "squash") ||
1927 strstr(ctx->current_fixups.buf, "\nsquash");
9e3cebd9
CM
1928}
1929
1930static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1931{
7e2f377b 1932 strbuf_setlen(buf1, strlen(comment_line_str) + 1);
9e3cebd9
CM
1933 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1934 strbuf_addch(buf1, '\n');
7e2f377b 1935 strbuf_setlen(buf2, strlen(comment_line_str) + 1);
9e3cebd9
CM
1936 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1937 strbuf_addch(buf2, '\n');
1938}
1939
1940/*
1941 * Comment out any un-commented commit messages, updating the message comments
1942 * to say they will be skipped but do not comment out the empty lines that
1943 * surround commit messages and their comments.
1944 */
1945static void update_squash_message_for_fixup(struct strbuf *msg)
1946{
1947 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1948 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1949 const char *s, *start;
1950 char *orig_msg;
1951 size_t orig_msg_len;
1952 int i = 1;
1953
7e2f377b
KH
1954 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str),
1955 strlen(_(first_commit_msg_str)),
1956 comment_line_str);
1957 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str),
1958 strlen(_(skip_first_commit_msg_str)),
1959 comment_line_str);
9e3cebd9
CM
1960 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1961 while (s) {
1962 const char *next;
1963 size_t off;
1964 if (skip_prefix(s, buf1.buf, &next)) {
1965 /*
1966 * Copy the last message, preserving the blank line
1967 * preceding the current line
1968 */
1969 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1970 copy_lines(msg, start, s - start - off);
1971 if (off)
1972 strbuf_addch(msg, '\n');
1973 /*
1974 * The next message needs to be commented out but the
1975 * message header is already commented out so just copy
1976 * it and the blank line that follows it.
1977 */
1978 strbuf_addbuf(msg, &buf2);
1979 if (*next == '\n')
1980 strbuf_addch(msg, *next++);
1981 start = s = next;
1982 copy_lines = add_commented_lines;
1983 update_comment_bufs(&buf1, &buf2, ++i);
1984 } else if (skip_prefix(s, buf2.buf, &next)) {
1985 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1986 copy_lines(msg, start, s - start - off);
1987 start = s - off;
1988 s = next;
1989 copy_lines = strbuf_add;
1990 update_comment_bufs(&buf1, &buf2, ++i);
1991 } else {
1992 s = strchr(s, '\n');
1993 if (s)
1994 s++;
1995 }
1996 }
1997 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1998 free(orig_msg);
1999 strbuf_release(&buf1);
2000 strbuf_release(&buf2);
2001}
2002
2003static int append_squash_message(struct strbuf *buf, const char *body,
2004 enum todo_command command, struct replay_opts *opts,
a25314c1 2005 unsigned flag)
9e3cebd9 2006{
497a01a2 2007 struct replay_ctx *ctx = opts->ctx;
9e3cebd9
CM
2008 const char *fixup_msg;
2009 size_t commented_len = 0, fixup_off;
2010 /*
2011 * amend is non-interactive and not normally used with fixup!
2012 * or squash! commits, so only comment out those subjects when
2013 * squashing commit messages.
2014 */
2015 if (starts_with(body, "amend!") ||
497a01a2 2016 ((command == TODO_SQUASH || seen_squash(ctx)) &&
9e3cebd9 2017 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
6e0e2887 2018 commented_len = commit_subject_length(body);
9e3cebd9 2019
f99e1d94 2020 strbuf_addf(buf, "\n%s ", comment_line_str);
71ee81cd 2021 strbuf_addf(buf, _(nth_commit_msg_fmt),
497a01a2 2022 ++ctx->current_fixup_count + 1);
498bb5b8 2023 strbuf_addstr(buf, "\n\n");
a1bb146a 2024 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
9e3cebd9
CM
2025 /* buf->buf may be reallocated so store an offset into the buffer */
2026 fixup_off = buf->len;
7cdb9682 2027 strbuf_addstr(buf, body + commented_len);
9e3cebd9
CM
2028
2029 /* fixup -C after squash behaves like squash */
497a01a2 2030 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
9e3cebd9
CM
2031 /*
2032 * We're replacing the commit message so we need to
2033 * append the Signed-off-by: trailer if the user
2034 * requested '--signoff'.
2035 */
2036 if (opts->signoff)
2037 append_signoff(buf, 0, 0);
2038
2039 if ((command == TODO_FIXUP) &&
2040 (flag & TODO_REPLACE_FIXUP_MSG) &&
2041 (file_exists(rebase_path_fixup_msg()) ||
2042 !file_exists(rebase_path_squash_msg()))) {
2043 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2044 if (write_message(fixup_msg, strlen(fixup_msg),
2045 rebase_path_fixup_msg(), 0) < 0)
2046 return error(_("cannot write '%s'"),
2047 rebase_path_fixup_msg());
2048 } else {
2049 unlink(rebase_path_fixup_msg());
2050 }
2051 } else {
2052 unlink(rebase_path_fixup_msg());
2053 }
2054
2055 return 0;
498bb5b8
PW
2056}
2057
005af339
NTND
2058static int update_squash_messages(struct repository *r,
2059 enum todo_command command,
2060 struct commit *commit,
9e3cebd9 2061 struct replay_opts *opts,
a25314c1 2062 unsigned flag)
6e98de72 2063{
497a01a2 2064 struct replay_ctx *ctx = opts->ctx;
6e98de72 2065 struct strbuf buf = STRBUF_INIT;
9e3cebd9 2066 int res = 0;
6e98de72 2067 const char *message, *body;
b3757442 2068 const char *encoding = get_commit_output_encoding();
6e98de72 2069
8b34b6a2
LY
2070 if (!is_fixup(command))
2071 BUG("not a FIXUP or SQUASH %d", command);
2072
497a01a2 2073 if (ctx->current_fixup_count > 0) {
6e98de72 2074 struct strbuf header = STRBUF_INIT;
e12a7ef5 2075 char *eol;
6e98de72 2076
e12a7ef5 2077 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
2078 return error(_("could not read '%s'"),
2079 rebase_path_squash_msg());
2080
600559b7 2081 eol = !starts_with(buf.buf, comment_line_str) ?
e12a7ef5 2082 buf.buf : strchrnul(buf.buf, '\n');
6e98de72 2083
f99e1d94 2084 strbuf_addf(&header, "%s ", comment_line_str);
71ee81cd 2085 strbuf_addf(&header, _(combined_commit_msg_fmt),
497a01a2 2086 ctx->current_fixup_count + 2);
6e98de72
JS
2087 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2088 strbuf_release(&header);
497a01a2 2089 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
9e3cebd9 2090 update_squash_message_for_fixup(&buf);
6e98de72 2091 } else {
33d66df3 2092 struct object_id head;
6e98de72
JS
2093 struct commit *head_commit;
2094 const char *head_message, *body;
2095
4a93b899 2096 if (repo_get_oid(r, "HEAD", &head))
6e98de72 2097 return error(_("need a HEAD to fixup"));
005af339 2098 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72 2099 return error(_("could not read HEAD"));
4a93b899
ÆAB
2100 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2101 encoding)))
6e98de72
JS
2102 return error(_("could not read HEAD's commit message"));
2103
2104 find_commit_subject(head_message, &body);
9e3cebd9 2105 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
eab0df0e 2106 rebase_path_fixup_msg(), 0) < 0) {
4a93b899 2107 repo_unuse_commit_buffer(r, head_commit, head_message);
eab0df0e 2108 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
6e98de72 2109 }
f99e1d94 2110 strbuf_addf(&buf, "%s ", comment_line_str);
71ee81cd 2111 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
f99e1d94 2112 strbuf_addf(&buf, "\n%s ", comment_line_str);
1f969601 2113 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
9e3cebd9
CM
2114 _(skip_first_commit_msg_str) :
2115 _(first_commit_msg_str));
6e98de72 2116 strbuf_addstr(&buf, "\n\n");
1f969601 2117 if (is_fixup_flag(command, flag))
787cb8a4 2118 strbuf_add_commented_lines(&buf, body, strlen(body),
a1bb146a 2119 comment_line_str);
9e3cebd9
CM
2120 else
2121 strbuf_addstr(&buf, body);
6e98de72 2122
4a93b899 2123 repo_unuse_commit_buffer(r, head_commit, head_message);
6e98de72
JS
2124 }
2125
4a93b899 2126 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
6e98de72
JS
2127 return error(_("could not read commit message of %s"),
2128 oid_to_hex(&commit->object.oid));
2129 find_commit_subject(message, &body);
2130
1f969601 2131 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
9e3cebd9 2132 res = append_squash_message(&buf, body, command, opts, flag);
6e98de72 2133 } else if (command == TODO_FIXUP) {
f99e1d94 2134 strbuf_addf(&buf, "\n%s ", comment_line_str);
71ee81cd 2135 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
497a01a2 2136 ++ctx->current_fixup_count + 1);
6e98de72 2137 strbuf_addstr(&buf, "\n\n");
787cb8a4 2138 strbuf_add_commented_lines(&buf, body, strlen(body),
a1bb146a 2139 comment_line_str);
8b34b6a2 2140 }
4a93b899 2141 repo_unuse_commit_buffer(r, commit, message);
6e98de72 2142
9e3cebd9
CM
2143 if (!res)
2144 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2145 0);
6e98de72 2146 strbuf_release(&buf);
e12a7ef5
JS
2147
2148 if (!res) {
497a01a2
PW
2149 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2150 ctx->current_fixups.len ? "\n" : "",
e12a7ef5
JS
2151 command_to_string(command),
2152 oid_to_hex(&commit->object.oid));
497a01a2
PW
2153 res = write_message(ctx->current_fixups.buf,
2154 ctx->current_fixups.len,
e12a7ef5
JS
2155 rebase_path_current_fixups(), 0);
2156 }
2157
6e98de72
JS
2158 return res;
2159}
2160
3b335762
NTND
2161static void flush_rewritten_pending(void)
2162{
25cb8df9 2163 struct strbuf buf = STRBUF_INIT;
092bbcdf 2164 struct object_id newoid;
25cb8df9
JS
2165 FILE *out;
2166
092bbcdf 2167 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
d850b7a5 2168 !repo_get_oid(the_repository, "HEAD", &newoid) &&
e9d983f1 2169 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
2170 char *bol = buf.buf, *eol;
2171
2172 while (*bol) {
2173 eol = strchrnul(bol, '\n');
2174 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 2175 bol, oid_to_hex(&newoid));
25cb8df9
JS
2176 if (!*eol)
2177 break;
2178 bol = eol + 1;
2179 }
2180 fclose(out);
2181 unlink(rebase_path_rewritten_pending());
2182 }
2183 strbuf_release(&buf);
2184}
2185
2186static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
2187 enum todo_command next_command)
2188{
e9d983f1 2189 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
2190
2191 if (!out)
2192 return;
2193
2194 fprintf(out, "%s\n", oid_to_hex(oid));
2195 fclose(out);
2196
2197 if (!is_fixup(next_command))
2198 flush_rewritten_pending();
2199}
2200
39edfd5c
EN
2201static int should_edit(struct replay_opts *opts) {
2202 if (opts->edit < 0)
2203 /*
2204 * Note that we only handle the case of non-conflicted
2205 * commits; continue_single_pick() handles the conflicted
2206 * commits itself instead of calling this function.
2207 */
2208 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2209 return opts->edit;
2210}
2211
43966ab3
JH
2212static void refer_to_commit(struct replay_opts *opts,
2213 struct strbuf *msgbuf, struct commit *commit)
2214{
2215 if (opts->commit_use_reference) {
2216 struct pretty_print_context ctx = {
2217 .abbrev = DEFAULT_ABBREV,
2218 .date_mode.type = DATE_SHORT,
2219 };
bab82164
ÆAB
2220 repo_format_commit_message(the_repository, commit,
2221 "%h (%s, %ad)", msgbuf, &ctx);
43966ab3
JH
2222 } else {
2223 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2224 }
2225}
2226
74727214
PW
2227static const char *sequencer_reflog_action(struct replay_opts *opts)
2228{
2229 if (!opts->reflog_action) {
2230 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
2231 opts->reflog_action =
2232 xstrdup(opts->reflog_action ? opts->reflog_action
2233 : action_name(opts));
2234 }
2235
2236 return opts->reflog_action;
2237}
2238
2239__attribute__((format (printf, 3, 4)))
2240static const char *reflog_message(struct replay_opts *opts,
2241 const char *sub_action, const char *fmt, ...)
2242{
2243 va_list ap;
2244 static struct strbuf buf = STRBUF_INIT;
2245
2246 va_start(ap, fmt);
2247 strbuf_reset(&buf);
2248 strbuf_addstr(&buf, sequencer_reflog_action(opts));
2249 if (sub_action)
2250 strbuf_addf(&buf, " (%s)", sub_action);
2251 if (fmt) {
2252 strbuf_addstr(&buf, ": ");
2253 strbuf_vaddf(&buf, fmt, ap);
2254 }
2255 va_end(ap);
2256
2257 return buf.buf;
2258}
2259
f11c9580 2260static int do_pick_commit(struct repository *r,
ae70e34f 2261 struct todo_item *item,
f11c9580 2262 struct replay_opts *opts,
a47ba3c7 2263 int final_fixup, int *check_todo)
043a4492 2264{
497a01a2 2265 struct replay_ctx *ctx = opts->ctx;
39edfd5c
EN
2266 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2267 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
ace976b2 2268 struct object_id head;
043a4492 2269 struct commit *base, *next, *parent;
5dbaec62 2270 const char *base_label, *next_label, *reflog_action;
356ee465 2271 char *author = NULL;
d74a4e57 2272 struct commit_message msg = { NULL, NULL, NULL, NULL };
e98c4269 2273 int res, unborn = 0, reword = 0, allow, drop_commit;
ae70e34f
CM
2274 enum todo_command command = item->command;
2275 struct commit *commit = item->commit;
043a4492 2276
5dbaec62
PW
2277 if (is_rebase_i(opts))
2278 reflog_action = reflog_message(
2279 opts, command_to_string(item->command), NULL);
2280 else
2281 reflog_action = sequencer_reflog_action(opts);
2282
043a4492
RR
2283 if (opts->no_commit) {
2284 /*
2285 * We do not intend to commit immediately. We just want to
2286 * merge the differences in, so let's compute the tree
81483fe6 2287 * that represents the "current" state for the merge machinery
043a4492
RR
2288 * to work on.
2289 */
f11c9580 2290 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 2291 return error(_("your index file is unmerged."));
043a4492 2292 } else {
4a93b899 2293 unborn = repo_get_oid(r, "HEAD", &head);
d87d48b2
JS
2294 /* Do we want to generate a root commit? */
2295 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 2296 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
2297 if (is_fixup(command))
2298 return error(_("cannot fixup root commit"));
2299 flags |= CREATE_ROOT_COMMIT;
2300 unborn = 1;
2301 } else if (unborn)
eb0ccfd7 2302 oidcpy(&head, the_hash_algo->empty_tree);
7abbca0e 2303 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
02f2f56b 2304 NULL, 0))
e1ff0a32 2305 return error_dirty_index(r, opts);
043a4492 2306 }
f11c9580 2307 discard_index(r->index);
043a4492 2308
637666c8 2309 if (!commit->parents)
043a4492 2310 parent = NULL;
043a4492
RR
2311 else if (commit->parents->next) {
2312 /* Reverting or cherry-picking a merge commit */
2313 int cnt;
2314 struct commit_list *p;
2315
2316 if (!opts->mainline)
93b3df6f 2317 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 2318 oid_to_hex(&commit->object.oid));
043a4492
RR
2319
2320 for (cnt = 1, p = commit->parents;
2321 cnt != opts->mainline && p;
2322 cnt++)
2323 p = p->next;
2324 if (cnt != opts->mainline || !p)
93b3df6f 2325 return error(_("commit %s does not have parent %d"),
f2fd0760 2326 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 2327 parent = p->item;
37897bfc
SO
2328 } else if (1 < opts->mainline)
2329 /*
2330 * Non-first parent explicitly specified as mainline for
2331 * non-merge commit
2332 */
2333 return error(_("commit %s does not have parent %d"),
2334 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
2335 else
2336 parent = commit->parents->item;
2337
bcbb68be
JS
2338 if (get_message(commit, &msg) != 0)
2339 return error(_("cannot get commit message for %s"),
2340 oid_to_hex(&commit->object.oid));
2341
6e98de72 2342 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 2343 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
2344 (!parent && unborn))) {
2345 if (is_rebase_i(opts))
2346 write_author_script(msg.message);
f11c9580 2347 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
2348 opts);
2349 if (res || command != TODO_REWORD)
2350 goto leave;
450efe2d 2351 reword = 1;
bcbb68be
JS
2352 msg_file = NULL;
2353 goto fast_forward_edit;
2354 }
4a93b899 2355 if (parent && repo_parse_commit(r, parent) < 0)
004fefa7
JS
2356 /* TRANSLATORS: The first %s will be a "todo" command like
2357 "revert" or "pick", the second %s a SHA1. */
043a4492 2358 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
2359 command_to_string(command),
2360 oid_to_hex(&parent->object.oid));
043a4492 2361
043a4492
RR
2362 /*
2363 * "commit" is an existing commit. We would want to apply
2364 * the difference it introduces since its first parent "prev"
2365 * on top of the current HEAD if we are cherry-pick. Or the
2366 * reverse of it if we are revert.
2367 */
2368
004fefa7 2369 if (command == TODO_REVERT) {
883cb1b8
OB
2370 const char *orig_subject;
2371
043a4492
RR
2372 base = commit;
2373 base_label = msg.label;
2374 next = parent;
2375 next_label = msg.parent_label;
43966ab3 2376 if (opts->commit_use_reference) {
515d034f
KH
2377 strbuf_commented_addf(&ctx->message, comment_line_str,
2378 "*** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
883cb1b8
OB
2379 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2380 /*
2381 * We don't touch pre-existing repeated reverts, because
2382 * theoretically these can be nested arbitrarily deeply,
2383 * thus requiring excessive complexity to deal with.
2384 */
2385 !starts_with(orig_subject, "Revert \"")) {
53f67466
PW
2386 strbuf_addstr(&ctx->message, "Reapply \"");
2387 strbuf_addstr(&ctx->message, orig_subject);
515d034f 2388 strbuf_addstr(&ctx->message, "\n");
43966ab3 2389 } else {
53f67466
PW
2390 strbuf_addstr(&ctx->message, "Revert \"");
2391 strbuf_addstr(&ctx->message, msg.subject);
515d034f 2392 strbuf_addstr(&ctx->message, "\"\n");
43966ab3 2393 }
515d034f 2394 strbuf_addstr(&ctx->message, "\nThis reverts commit ");
53f67466 2395 refer_to_commit(opts, &ctx->message, commit);
043a4492
RR
2396
2397 if (commit->parents && commit->parents->next) {
53f67466
PW
2398 strbuf_addstr(&ctx->message, ", reversing\nchanges made to ");
2399 refer_to_commit(opts, &ctx->message, parent);
043a4492 2400 }
53f67466 2401 strbuf_addstr(&ctx->message, ".\n");
043a4492
RR
2402 } else {
2403 const char *p;
2404
2405 base = parent;
2406 base_label = msg.parent_label;
2407 next = commit;
2408 next_label = msg.label;
2409
53f67466 2410 /* Append the commit log message to ctx->message. */
23aa5142 2411 if (find_commit_subject(msg.message, &p))
53f67466 2412 strbuf_addstr(&ctx->message, p);
043a4492
RR
2413
2414 if (opts->record_origin) {
53f67466
PW
2415 strbuf_complete_line(&ctx->message);
2416 if (!has_conforming_footer(&ctx->message, NULL, 0))
2417 strbuf_addch(&ctx->message, '\n');
2418 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2419 strbuf_addstr(&ctx->message, oid_to_hex(&commit->object.oid));
2420 strbuf_addstr(&ctx->message, ")\n");
043a4492 2421 }
356ee465
PW
2422 if (!is_fixup(command))
2423 author = get_author(msg.message);
043a4492 2424 }
53f67466 2425 ctx->have_message = 1;
043a4492 2426
04efc8b5 2427 if (command == TODO_REWORD)
450efe2d 2428 reword = 1;
04efc8b5 2429 else if (is_fixup(command)) {
9e3cebd9 2430 if (update_squash_messages(r, command, commit,
a5792e9d
ÆAB
2431 opts, item->flags)) {
2432 res = -1;
2433 goto leave;
2434 }
789b3eff 2435 flags |= AMEND_MSG;
6e98de72
JS
2436 if (!final_fixup)
2437 msg_file = rebase_path_squash_msg();
2438 else if (file_exists(rebase_path_fixup_msg())) {
f7d42cee 2439 flags |= VERBATIM_MSG;
6e98de72
JS
2440 msg_file = rebase_path_fixup_msg();
2441 } else {
f11c9580 2442 const char *dest = git_path_squash_msg(r);
6e98de72 2443 unlink(dest);
a5792e9d 2444 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
82af2c63 2445 res = error(_("could not copy '%s' to '%s'"),
a5792e9d
ÆAB
2446 rebase_path_squash_msg(), dest);
2447 goto leave;
2448 }
f11c9580 2449 unlink(git_path_merge_msg(r));
6e98de72 2450 msg_file = dest;
789b3eff 2451 flags |= EDIT_MSG;
6e98de72
JS
2452 }
2453 }
2454
a852ec7f 2455 if (opts->signoff && !is_fixup(command))
53f67466 2456 append_signoff(&ctx->message, 0, 0);
b34eeea3 2457
0473f28a
JS
2458 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2459 res = -1;
14c4586c
EN
2460 else if (!opts->strategy ||
2461 !strcmp(opts->strategy, "recursive") ||
2462 !strcmp(opts->strategy, "ort") ||
2463 command == TODO_REVERT) {
f11c9580 2464 res = do_recursive_merge(r, base, next, base_label, next_label,
53f67466 2465 &head, &ctx->message, opts);
f241ff0d 2466 if (res < 0)
19517fb9
SB
2467 goto leave;
2468
53f67466 2469 res |= write_message(ctx->message.buf, ctx->message.len,
f11c9580 2470 git_path_merge_msg(r), 0);
043a4492
RR
2471 } else {
2472 struct commit_list *common = NULL;
2473 struct commit_list *remotes = NULL;
2474
53f67466 2475 res = write_message(ctx->message.buf, ctx->message.len,
f11c9580 2476 git_path_merge_msg(r), 0);
043a4492
RR
2477
2478 commit_list_insert(base, &common);
2479 commit_list_insert(next, &remotes);
f11c9580 2480 res |= try_merge_command(r, opts->strategy,
fb60b9f3 2481 opts->xopts.nr, opts->xopts.v,
ace976b2 2482 common, oid_to_hex(&head), remotes);
043a4492
RR
2483 free_commit_list(common);
2484 free_commit_list(remotes);
2485 }
2486
2487 /*
2488 * If the merge was clean or if it failed due to conflict, we write
2489 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2490 * However, if the merge did not even start, then we don't want to
2491 * write it at all.
2492 */
21b11c6d
PW
2493 if ((command == TODO_PICK || command == TODO_REWORD ||
2494 command == TODO_EDIT) && !opts->no_commit &&
2495 (res == 0 || res == 1) &&
2e5c4758
PS
2496 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2497 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2498 res = -1;
004fefa7 2499 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2e5c4758
PS
2500 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2501 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2502 res = -1;
043a4492
RR
2503
2504 if (res) {
004fefa7 2505 error(command == TODO_REVERT
043a4492
RR
2506 ? _("could not revert %s... %s")
2507 : _("could not apply %s... %s"),
cb646ffb 2508 short_commit_name(r, commit), msg.subject);
005af339 2509 print_advice(r, res == 1, opts);
f11c9580 2510 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 2511 goto leave;
043a4492
RR
2512 }
2513
e98c4269 2514 drop_commit = 0;
f11c9580 2515 allow = allow_empty(r, opts, commit);
706728a3
FC
2516 if (allow < 0) {
2517 res = allow;
2518 goto leave;
e98c4269 2519 } else if (allow == 1) {
789b3eff 2520 flags |= ALLOW_EMPTY;
e98c4269
EN
2521 } else if (allow == 2) {
2522 drop_commit = 1;
c8e4159e 2523 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
821f6632 2524 NULL, REF_NO_DEREF);
9a1b7474 2525 unlink(git_path_merge_msg(r));
fd7c6ffa
PS
2526 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2527 NULL, REF_NO_DEREF);
e98c4269
EN
2528 fprintf(stderr,
2529 _("dropping %s %s -- patch contents already upstream\n"),
2530 oid_to_hex(&commit->object.oid), msg.subject);
2531 } /* else allow == 0 and there's nothing special to do */
2532 if (!opts->no_commit && !drop_commit) {
356ee465 2533 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
5dbaec62
PW
2534 res = do_commit(r, msg_file, author, reflog_action,
2535 opts, flags,
430b75f7 2536 commit? &commit->object.oid : NULL);
356ee465
PW
2537 else
2538 res = error(_("unable to parse commit author"));
a47ba3c7
PW
2539 *check_todo = !!(flags & EDIT_MSG);
2540 if (!res && reword) {
450efe2d 2541fast_forward_edit:
af8fc7be
PW
2542 /*
2543 * To reword we amend the commit we just
2544 * picked or fast-forwarded. As the commit has
2545 * already been picked we want to use the same
2546 * set of commit flags regardless of how we
2547 * got here.
2548 */
2549 flags = EDIT_MSG | VERIFY_MSG | AMEND_MSG | ALLOW_EMPTY;
0b8d22fd 2550 res = run_git_commit(NULL, reflog_action, opts, flags);
a47ba3c7
PW
2551 *check_todo = 1;
2552 }
356ee465 2553 }
6e98de72 2554
450efe2d 2555
6e98de72
JS
2556 if (!res && final_fixup) {
2557 unlink(rebase_path_fixup_msg());
2558 unlink(rebase_path_squash_msg());
e12a7ef5 2559 unlink(rebase_path_current_fixups());
497a01a2
PW
2560 strbuf_reset(&ctx->current_fixups);
2561 ctx->current_fixup_count = 0;
6e98de72 2562 }
c8d1351d
FC
2563
2564leave:
d74a4e57 2565 free_message(commit, &msg);
356ee465 2566 free(author);
1e41229d 2567 update_abort_safety_file();
043a4492
RR
2568
2569 return res;
2570}
2571
c3e8618c 2572static int prepare_revs(struct replay_opts *opts)
043a4492 2573{
a73e22e9
MZ
2574 /*
2575 * picking (but not reverting) ranges (but not individual revisions)
2576 * should be done in reverse
2577 */
2578 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2579 opts->revs->reverse ^= 1;
2580
2581 if (prepare_revision_walk(opts->revs))
c3e8618c 2582 return error(_("revision walk setup failed"));
043a4492 2583
c3e8618c 2584 return 0;
043a4492
RR
2585}
2586
f11c9580
NTND
2587static int read_and_refresh_cache(struct repository *r,
2588 struct replay_opts *opts)
043a4492 2589{
14bca6c6 2590 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2591 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2592 if (repo_read_index(r) < 0) {
49fb937e 2593 rollback_lock_file(&index_lock);
0d9c6dc9 2594 return error(_("git %s: failed to read the index"),
629444ad 2595 action_name(opts));
49fb937e 2596 }
f11c9580 2597 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
5d9c9349 2598
61000814 2599 if (index_fd >= 0) {
f11c9580 2600 if (write_locked_index(r->index, &index_lock,
61000814 2601 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2602 return error(_("git %s: failed to refresh the index"),
629444ad 2603 action_name(opts));
49fb937e 2604 }
043a4492 2605 }
5d9c9349
DS
2606
2607 /*
2608 * If we are resolving merges in any way other than "ort", then
2609 * expand the sparse index.
2610 */
2611 if (opts->strategy && strcmp(opts->strategy, "ort"))
2612 ensure_full_index(r->index);
0d9c6dc9 2613 return 0;
043a4492
RR
2614}
2615
5d94d545 2616void todo_list_release(struct todo_list *todo_list)
043a4492 2617{
004fefa7 2618 strbuf_release(&todo_list->buf);
6a83d902 2619 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2620 todo_list->nr = todo_list->alloc = 0;
2621}
043a4492 2622
004fefa7
JS
2623static struct todo_item *append_new_todo(struct todo_list *todo_list)
2624{
2625 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2626 return todo_list->items + todo_list->nr++;
043a4492
RR
2627}
2628
6ad656db
AG
2629const char *todo_item_get_arg(struct todo_list *todo_list,
2630 struct todo_item *item)
2631{
2632 return todo_list->buf.buf + item->arg_offset;
2633}
2634
3e81bccd
PW
2635static int is_command(enum todo_command command, const char **bol)
2636{
2637 const char *str = todo_command_info[command].str;
2638 const char nick = todo_command_info[command].c;
7aed2c05 2639 const char *p = *bol;
3e81bccd 2640
22488332
JS
2641 if ((skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2642 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p)) {
2643 *bol = p;
2644 return 1;
2645 }
2646 return 0;
3e81bccd
PW
2647}
2648
16b3880d
PW
2649static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2650{
2651 switch (command) {
2652 case TODO_LABEL:
2653 /*
2654 * '#' is not a valid label as the merge command uses it to
2655 * separate merge parents from the commit subject.
2656 */
2657 if (!strcmp(arg, "#") ||
2658 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2659 return error(_("'%s' is not a valid label"), arg);
2660 break;
2661
2662 case TODO_UPDATE_REF:
2663 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2664 return error(_("'%s' is not a valid refname"), arg);
2665 if (check_refname_format(arg, 0))
2666 return error(_("update-ref requires a fully qualified "
2667 "refname e.g. refs/heads/%s"), arg);
2668 break;
2669
2670 default:
2671 BUG("unexpected todo_command");
2672 }
2673
2674 return 0;
2675}
2676
4c063c82
PW
2677static int check_merge_commit_insn(enum todo_command command)
2678{
2679 switch(command) {
2680 case TODO_PICK:
2681 error(_("'%s' does not accept merge commits"),
2682 todo_command_info[command].str);
2683 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2684 /*
2685 * TRANSLATORS: 'pick' and 'merge -C' should not be
2686 * translated.
2687 */
2688 "'pick' does not take a merge commit. If you wanted to\n"
2689 "replay the merge, use 'merge -C' on the commit."));
2690 return -1;
2691
2692 case TODO_REWORD:
2693 error(_("'%s' does not accept merge commits"),
2694 todo_command_info[command].str);
2695 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2696 /*
2697 * TRANSLATORS: 'reword' and 'merge -c' should not be
2698 * translated.
2699 */
2700 "'reword' does not take a merge commit. If you wanted to\n"
2701 "replay the merge and reword the commit message, use\n"
2702 "'merge -c' on the commit"));
2703 return -1;
2704
2705 case TODO_EDIT:
2706 error(_("'%s' does not accept merge commits"),
2707 todo_command_info[command].str);
2708 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2709 /*
2710 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2711 * not be translated.
2712 */
2713 "'edit' does not take a merge commit. If you wanted to\n"
2714 "replay the merge, use 'merge -C' on the commit, and then\n"
2715 "'break' to give the control back to you so that you can\n"
2716 "do 'git commit --amend && git rebase --continue'."));
2717 return -1;
2718
2719 case TODO_FIXUP:
2720 case TODO_SQUASH:
2721 return error(_("cannot squash merge commit into another commit"));
2722
2723 case TODO_MERGE:
2724 return 0;
2725
2726 default:
2727 BUG("unexpected todo_command");
2728 }
2729}
2730
2731static int parse_insn_line(struct repository *r, struct replay_opts *opts,
0c26738a
PW
2732 struct todo_item *item, const char *buf,
2733 const char *bol, char *eol)
043a4492 2734{
1e43ed98 2735 struct object_id commit_oid;
043a4492 2736 char *end_of_object_name;
004fefa7
JS
2737 int i, saved, status, padding;
2738
4c68e7dd
JS
2739 item->flags = 0;
2740
8f8550b3
JS
2741 /* left-trim */
2742 bol += strspn(bol, " \t");
2743
2ec225d3 2744 if (bol == eol || *bol == '\r' || starts_with_mem(bol, eol - bol, comment_line_str)) {
ac191470 2745 item->command = TODO_COMMENT;
25c43667 2746 item->commit = NULL;
6ad656db 2747 item->arg_offset = bol - buf;
25c43667
JS
2748 item->arg_len = eol - bol;
2749 return 0;
2750 }
2751
ac191470 2752 for (i = 0; i < TODO_COMMENT; i++)
3e81bccd 2753 if (is_command(i, &bol)) {
004fefa7
JS
2754 item->command = i;
2755 break;
2756 }
ac191470 2757 if (i >= TODO_COMMENT)
7aed2c05
PW
2758 return error(_("invalid command '%.*s'"),
2759 (int)strcspn(bol, " \t\r\n"), bol);
043a4492 2760
66afa24f
JS
2761 /* Eat up extra spaces/ tabs before object name */
2762 padding = strspn(bol, " \t");
2763 bol += padding;
2764
71f82465 2765 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2766 if (bol != eol)
2767 return error(_("%s does not accept arguments: '%s'"),
2768 command_to_string(item->command), bol);
25c43667 2769 item->commit = NULL;
6ad656db 2770 item->arg_offset = bol - buf;
25c43667
JS
2771 item->arg_len = eol - bol;
2772 return 0;
2773 }
2774
043a4492 2775 if (!padding)
66afa24f
JS
2776 return error(_("missing arguments for %s"),
2777 command_to_string(item->command));
043a4492 2778
9055e401 2779 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
a97d7916 2780 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
16b3880d
PW
2781 int ret = 0;
2782
7dcbb3cb 2783 item->commit = NULL;
6ad656db 2784 item->arg_offset = bol - buf;
311af526 2785 item->arg_len = (int)(eol - bol);
16b3880d
PW
2786 if (item->command == TODO_LABEL ||
2787 item->command == TODO_UPDATE_REF) {
2788 saved = *eol;
2789 *eol = '\0';
2790 ret = check_label_or_ref_arg(item->command, bol);
2791 *eol = saved;
2792 }
2793 return ret;
311af526
JS
2794 }
2795
9e3cebd9 2796 if (item->command == TODO_FIXUP) {
666b6e11 2797 if (skip_prefix(bol, "-C", &bol)) {
9e3cebd9
CM
2798 bol += strspn(bol, " \t");
2799 item->flags |= TODO_REPLACE_FIXUP_MSG;
666b6e11 2800 } else if (skip_prefix(bol, "-c", &bol)) {
9e3cebd9
CM
2801 bol += strspn(bol, " \t");
2802 item->flags |= TODO_EDIT_FIXUP_MSG;
2803 }
2804 }
2805
4c68e7dd
JS
2806 if (item->command == TODO_MERGE) {
2807 if (skip_prefix(bol, "-C", &bol))
2808 bol += strspn(bol, " \t");
2809 else if (skip_prefix(bol, "-c", &bol)) {
2810 bol += strspn(bol, " \t");
2811 item->flags |= TODO_EDIT_MERGE_MSG;
2812 } else {
2813 item->flags |= TODO_EDIT_MERGE_MSG;
2814 item->commit = NULL;
6ad656db 2815 item->arg_offset = bol - buf;
4c68e7dd
JS
2816 item->arg_len = (int)(eol - bol);
2817 return 0;
2818 }
2819 }
2820
004fefa7 2821 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2822 saved = *end_of_object_name;
2823 *end_of_object_name = '\0';
4a93b899 2824 status = repo_get_oid(r, bol, &commit_oid);
d859dcad
JS
2825 if (status < 0)
2826 error(_("could not parse '%s'"), bol); /* return later */
043a4492
RR
2827 *end_of_object_name = saved;
2828
6ad656db
AG
2829 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2830 item->arg_offset = bol - buf;
2831 item->arg_len = (int)(eol - bol);
c22f7dfb 2832
043a4492 2833 if (status < 0)
d859dcad 2834 return status;
043a4492 2835
005af339 2836 item->commit = lookup_commit_reference(r, &commit_oid);
4c063c82
PW
2837 if (!item->commit)
2838 return -1;
2839 if (is_rebase_i(opts) &&
2840 item->commit->parents && item->commit->parents->next)
2841 return check_merge_commit_insn(item->command);
2842 return 0;
043a4492
RR
2843}
2844
c9f7b1e8 2845int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
4a72486d 2846{
ed5b1ca1 2847 const char *todo_file, *bol;
4a72486d 2848 struct strbuf buf = STRBUF_INIT;
ed5b1ca1 2849 int ret = 0;
4a72486d
PW
2850
2851 todo_file = git_path_todo_file();
2852 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
ed5b1ca1 2853 if (errno == ENOENT || errno == ENOTDIR)
4a72486d
PW
2854 return -1;
2855 else
2856 return error_errno("unable to open '%s'", todo_file);
2857 }
ed5b1ca1
PW
2858 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2859 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
4a72486d 2860 *action = REPLAY_PICK;
ed5b1ca1
PW
2861 else if (is_command(TODO_REVERT, &bol) &&
2862 (*bol == ' ' || *bol == '\t'))
4a72486d
PW
2863 *action = REPLAY_REVERT;
2864 else
ed5b1ca1 2865 ret = -1;
4a72486d 2866
4a72486d
PW
2867 strbuf_release(&buf);
2868
2869 return ret;
2870}
2871
0c26738a
PW
2872int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2873 char *buf, struct todo_list *todo_list)
043a4492 2874{
004fefa7
JS
2875 struct todo_item *item;
2876 char *p = buf, *next_p;
6e98de72 2877 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2878
170eea97 2879 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2b71595d 2880
004fefa7 2881 for (i = 1; *p; i++, p = next_p) {
043a4492 2882 char *eol = strchrnul(p, '\n');
004fefa7
JS
2883
2884 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2885
6307041d
JS
2886 if (p != eol && eol[-1] == '\r')
2887 eol--; /* strip Carriage Return */
2888
004fefa7
JS
2889 item = append_new_todo(todo_list);
2890 item->offset_in_buf = p - todo_list->buf.buf;
0c26738a 2891 if (parse_insn_line(r, opts, item, buf, p, eol)) {
93b3df6f 2892 res = error(_("invalid line %d: %.*s"),
004fefa7 2893 i, (int)(eol - p), p);
2b71595d 2894 item->command = TODO_COMMENT + 1;
6ad656db 2895 item->arg_offset = p - buf;
2b71595d
AG
2896 item->arg_len = (int)(eol - p);
2897 item->commit = NULL;
004fefa7 2898 }
6e98de72 2899
170eea97
JS
2900 if (item->command != TODO_COMMENT)
2901 todo_list->total_nr++;
2902
6e98de72
JS
2903 if (fixup_okay)
2904 ; /* do nothing */
2905 else if (is_fixup(item->command))
9645a087 2906 res = error(_("cannot '%s' without a previous commit"),
6e98de72
JS
2907 command_to_string(item->command));
2908 else if (!is_noop(item->command))
2909 fixup_okay = 1;
043a4492 2910 }
52865279 2911
004fefa7 2912 return res;
043a4492
RR
2913}
2914
968492e4
JS
2915static int count_commands(struct todo_list *todo_list)
2916{
2917 int count = 0, i;
2918
2919 for (i = 0; i < todo_list->nr; i++)
2920 if (todo_list->items[i].command != TODO_COMMENT)
2921 count++;
2922
2923 return count;
2924}
2925
a01c2a5f
JS
2926static int get_item_line_offset(struct todo_list *todo_list, int index)
2927{
2928 return index < todo_list->nr ?
2929 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2930}
2931
2932static const char *get_item_line(struct todo_list *todo_list, int index)
2933{
2934 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2935}
2936
2937static int get_item_line_length(struct todo_list *todo_list, int index)
2938{
2939 return get_item_line_offset(todo_list, index + 1)
2940 - get_item_line_offset(todo_list, index);
2941}
2942
87805600
RS
2943static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2944{
2945 int fd;
2946 ssize_t len;
2947
2948 fd = open(path, O_RDONLY);
2949 if (fd < 0)
2950 return error_errno(_("could not open '%s'"), path);
2951 len = strbuf_read(sb, fd, 0);
2952 close(fd);
2953 if (len < 0)
2954 return error(_("could not read '%s'."), path);
2955 return len;
2956}
2957
b07d9bfd
PW
2958static int have_finished_the_last_pick(void)
2959{
2960 struct strbuf buf = STRBUF_INIT;
2961 const char *eol;
2962 const char *todo_path = git_path_todo_file();
2963 int ret = 0;
2964
2965 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2966 if (errno == ENOENT) {
2967 return 0;
2968 } else {
2969 error_errno("unable to open '%s'", todo_path);
2970 return 0;
2971 }
2972 }
2973 /* If there is only one line then we are done */
2974 eol = strchr(buf.buf, '\n');
2975 if (!eol || !eol[1])
2976 ret = 1;
2977
2978 strbuf_release(&buf);
2979
2980 return ret;
2981}
2982
f496b064 2983void sequencer_post_commit_cleanup(struct repository *r, int verbose)
b07d9bfd
PW
2984{
2985 struct replay_opts opts = REPLAY_OPTS_INIT;
2986 int need_cleanup = 0;
2987
c8e4159e
HWN
2988 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2989 if (!refs_delete_ref(get_main_ref_store(r), "",
821f6632 2990 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
c8e4159e 2991 verbose)
f496b064 2992 warning(_("cancelling a cherry picking in progress"));
b07d9bfd
PW
2993 opts.action = REPLAY_PICK;
2994 need_cleanup = 1;
2995 }
2996
b8825ef2
HWN
2997 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2998 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
821f6632 2999 NULL, REF_NO_DEREF) &&
b8825ef2 3000 verbose)
f496b064 3001 warning(_("cancelling a revert in progress"));
b07d9bfd
PW
3002 opts.action = REPLAY_REVERT;
3003 need_cleanup = 1;
3004 }
3005
fd7c6ffa
PS
3006 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
3007 NULL, REF_NO_DEREF);
5291828d 3008
b07d9bfd 3009 if (!need_cleanup)
42aae6a4 3010 goto out;
b07d9bfd
PW
3011
3012 if (!have_finished_the_last_pick())
42aae6a4 3013 goto out;
b07d9bfd
PW
3014
3015 sequencer_remove_state(&opts);
42aae6a4
PW
3016out:
3017 replay_opts_release(&opts);
b07d9bfd
PW
3018}
3019
3f34f2d8
AG
3020static void todo_list_write_total_nr(struct todo_list *todo_list)
3021{
3022 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
3023
3024 if (f) {
3025 fprintf(f, "%d\n", todo_list->total_nr);
3026 fclose(f);
3027 }
3028}
3029
005af339
NTND
3030static int read_populate_todo(struct repository *r,
3031 struct todo_list *todo_list,
3032 struct replay_opts *opts)
043a4492 3033{
c0246501 3034 const char *todo_file = get_todo_path(opts);
87805600 3035 int res;
043a4492 3036
004fefa7 3037 strbuf_reset(&todo_list->buf);
87805600
RS
3038 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
3039 return -1;
043a4492 3040
0c26738a 3041 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
27fdbb96
JS
3042 if (res) {
3043 if (is_rebase_i(opts))
3044 return error(_("please fix this using "
3045 "'git rebase --edit-todo'."));
93b3df6f 3046 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 3047 }
2eeaf1b3 3048
52865279
JS
3049 if (!todo_list->nr &&
3050 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3051 return error(_("no commits parsed."));
3052
2eeaf1b3 3053 if (!is_rebase_i(opts)) {
004fefa7
JS
3054 enum todo_command valid =
3055 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3056 int i;
3057
3058 for (i = 0; i < todo_list->nr; i++)
3059 if (valid == todo_list->items[i].command)
3060 continue;
3061 else if (valid == TODO_PICK)
93b3df6f 3062 return error(_("cannot cherry-pick during a revert."));
004fefa7 3063 else
93b3df6f 3064 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
3065 }
3066
968492e4
JS
3067 if (is_rebase_i(opts)) {
3068 struct todo_list done = TODO_LIST_INIT;
3069
3070 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
0c26738a 3071 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
968492e4
JS
3072 todo_list->done_nr = count_commands(&done);
3073 else
3074 todo_list->done_nr = 0;
3075
3076 todo_list->total_nr = todo_list->done_nr
3077 + count_commands(todo_list);
968492e4 3078 todo_list_release(&done);
ef80069a 3079
3f34f2d8 3080 todo_list_write_total_nr(todo_list);
968492e4
JS
3081 }
3082
0ae42a03 3083 return 0;
043a4492
RR
3084}
3085
03a4e260
JS
3086static int git_config_string_dup(char **dest,
3087 const char *var, const char *value)
3088{
3089 if (!value)
3090 return config_error_nonbool(var);
3091 free(*dest);
3092 *dest = xstrdup(value);
3093 return 0;
3094}
3095
a4e7e317 3096static int populate_opts_cb(const char *key, const char *value,
8868b1eb 3097 const struct config_context *ctx,
a4e7e317 3098 void *data)
043a4492
RR
3099{
3100 struct replay_opts *opts = data;
3101 int error_flag = 1;
3102
3103 if (!value)
3104 error_flag = 0;
3105 else if (!strcmp(key, "options.no-commit"))
8868b1eb 3106 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 3107 else if (!strcmp(key, "options.edit"))
8868b1eb 3108 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
3109 else if (!strcmp(key, "options.allow-empty"))
3110 opts->allow_empty =
8868b1eb 3111 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
3112 else if (!strcmp(key, "options.allow-empty-message"))
3113 opts->allow_empty_message =
8868b1eb 3114 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
ec79d763
BL
3115 else if (!strcmp(key, "options.drop-redundant-commits"))
3116 opts->drop_redundant_commits =
3117 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
3118 else if (!strcmp(key, "options.keep-redundant-commits"))
3119 opts->keep_redundant_commits =
8868b1eb 3120 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 3121 else if (!strcmp(key, "options.signoff"))
8868b1eb 3122 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 3123 else if (!strcmp(key, "options.record-origin"))
8868b1eb 3124 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 3125 else if (!strcmp(key, "options.allow-ff"))
8868b1eb 3126 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 3127 else if (!strcmp(key, "options.mainline"))
8868b1eb 3128 opts->mainline = git_config_int(key, value, ctx->kvi);
043a4492 3129 else if (!strcmp(key, "options.strategy"))
03a4e260 3130 git_config_string_dup(&opts->strategy, key, value);
3253553e 3131 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 3132 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492 3133 else if (!strcmp(key, "options.strategy-option")) {
fb60b9f3 3134 strvec_push(&opts->xopts, value);
8d8cb4b0
PW
3135 } else if (!strcmp(key, "options.allow-rerere-auto"))
3136 opts->allow_rerere_auto =
8868b1eb 3137 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
8d8cb4b0 3138 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
3139 else if (!strcmp(key, "options.default-msg-cleanup")) {
3140 opts->explicit_cleanup = 1;
3141 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3142 } else
93b3df6f 3143 return error(_("invalid key: %s"), key);
043a4492
RR
3144
3145 if (!error_flag)
1a8aea85 3146 return error(_("invalid value for '%s': '%s'"), key, value);
043a4492
RR
3147
3148 return 0;
3149}
3150
4a8bc986 3151static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
3152{
3153 int i;
15a4cc91 3154 int count;
fb60b9f3 3155 const char **argv;
65850686 3156 char *strategy_opts_string = raw_opts;
ca6c6b45 3157
0060041d
EN
3158 if (*strategy_opts_string == ' ')
3159 strategy_opts_string++;
65850686 3160
fb60b9f3 3161 count = split_cmdline(strategy_opts_string, &argv);
15a4cc91 3162 if (count < 0)
4960e5c7 3163 BUG("could not split '%s': %s", strategy_opts_string,
15a4cc91 3164 split_cmdline_strerror(count));
fb60b9f3
PW
3165 for (i = 0; i < count; i++) {
3166 const char *arg = argv[i];
ca6c6b45
JS
3167
3168 skip_prefix(arg, "--", &arg);
fb60b9f3 3169 strvec_push(&opts->xopts, arg);
ca6c6b45 3170 }
fb60b9f3 3171 free(argv);
ca6c6b45
JS
3172}
3173
65850686
AG
3174static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3175{
3176 strbuf_reset(buf);
3177 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3178 return;
3179 opts->strategy = strbuf_detach(buf, NULL);
3180 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3181 return;
3182
3183 parse_strategy_opts(opts, buf->buf);
3184}
3185
5adf9bdc 3186static int read_populate_opts(struct replay_opts *opts)
043a4492 3187{
497a01a2
PW
3188 struct replay_ctx *ctx = opts->ctx;
3189
a1c75762
JS
3190 if (is_rebase_i(opts)) {
3191 struct strbuf buf = STRBUF_INIT;
65c425a2 3192 int ret = 0;
a1c75762 3193
3442c3d1
DL
3194 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3195 READ_ONELINER_SKIP_IF_EMPTY)) {
a1c75762
JS
3196 if (!starts_with(buf.buf, "-S"))
3197 strbuf_reset(&buf);
3198 else {
3199 free(opts->gpg_sign);
3200 opts->gpg_sign = xstrdup(buf.buf + 2);
3201 }
9b6d7a62
PW
3202 strbuf_reset(&buf);
3203 }
3204
3442c3d1
DL
3205 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3206 READ_ONELINER_SKIP_IF_EMPTY)) {
9b6d7a62
PW
3207 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3208 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3209 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3210 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3211 strbuf_reset(&buf);
a1c75762 3212 }
a1c75762 3213
556907f1
JS
3214 if (file_exists(rebase_path_verbose()))
3215 opts->verbose = 1;
3216
899b49c4
EN
3217 if (file_exists(rebase_path_quiet()))
3218 opts->quiet = 1;
3219
a852ec7f
PW
3220 if (file_exists(rebase_path_signoff())) {
3221 opts->allow_ff = 0;
3222 opts->signoff = 1;
3223 }
3224
7573cec5
PW
3225 if (file_exists(rebase_path_cdate_is_adate())) {
3226 opts->allow_ff = 0;
3227 opts->committer_date_is_author_date = 1;
3228 }
3229
a3894aad
PW
3230 if (file_exists(rebase_path_ignore_date())) {
3231 opts->allow_ff = 0;
3232 opts->ignore_date = 1;
3233 }
3234
d421afa0
JS
3235 if (file_exists(rebase_path_reschedule_failed_exec()))
3236 opts->reschedule_failed_exec = 1;
e5b32bff
ÆAB
3237 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3238 opts->reschedule_failed_exec = 0;
d421afa0 3239
e98c4269
EN
3240 if (file_exists(rebase_path_drop_redundant_commits()))
3241 opts->drop_redundant_commits = 1;
3242
3243 if (file_exists(rebase_path_keep_redundant_commits()))
3244 opts->keep_redundant_commits = 1;
3245
ca6c6b45 3246 read_strategy_opts(opts, &buf);
65c425a2 3247 strbuf_reset(&buf);
ca6c6b45 3248
497a01a2 3249 if (read_oneliner(&ctx->current_fixups,
3442c3d1
DL
3250 rebase_path_current_fixups(),
3251 READ_ONELINER_SKIP_IF_EMPTY)) {
497a01a2
PW
3252 const char *p = ctx->current_fixups.buf;
3253 ctx->current_fixup_count = 1;
e12a7ef5 3254 while ((p = strchr(p, '\n'))) {
497a01a2 3255 ctx->current_fixup_count++;
e12a7ef5
JS
3256 p++;
3257 }
3258 }
3259
d87d48b2 3260 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
d850b7a5 3261 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
65c425a2
DL
3262 ret = error(_("unusable squash-onto"));
3263 goto done_rebase_i;
3264 }
d87d48b2
JS
3265 opts->have_squash_onto = 1;
3266 }
3267
65c425a2
DL
3268done_rebase_i:
3269 strbuf_release(&buf);
3270 return ret;
a1c75762 3271 }
b5a67045 3272
f932729c 3273 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
3274 return 0;
3275 /*
3276 * The function git_parse_source(), called from git_config_from_file(),
3277 * may die() in case of a syntactically incorrect file. We do not care
3278 * about this case, though, because we wrote that file ourselves, so we
3279 * are pretty certain that it is syntactically correct.
3280 */
5adf9bdc 3281 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 3282 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
3283 git_path_opts_file());
3284 return 0;
043a4492
RR
3285}
3286
65850686
AG
3287static void write_strategy_opts(struct replay_opts *opts)
3288{
65850686
AG
3289 struct strbuf buf = STRBUF_INIT;
3290
4960e5c7
PW
3291 /*
3292 * Quote strategy options so that they can be read correctly
3293 * by split_cmdline().
3294 */
3295 quote_cmdline(&buf, opts->xopts.v);
65850686
AG
3296 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3297 strbuf_release(&buf);
3298}
3299
3300int write_basic_state(struct replay_opts *opts, const char *head_name,
a2bb10d0 3301 struct commit *onto, const struct object_id *orig_head)
65850686 3302{
65850686
AG
3303 if (head_name)
3304 write_file(rebase_path_head_name(), "%s\n", head_name);
3305 if (onto)
7d3488eb
PW
3306 write_file(rebase_path_onto(), "%s\n",
3307 oid_to_hex(&onto->object.oid));
65850686 3308 if (orig_head)
a2bb10d0
PW
3309 write_file(rebase_path_orig_head(), "%s\n",
3310 oid_to_hex(orig_head));
65850686 3311
8a997ed1
EN
3312 if (opts->quiet)
3313 write_file(rebase_path_quiet(), "%s", "");
65850686 3314 if (opts->verbose)
4af51741 3315 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
3316 if (opts->strategy)
3317 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
fb60b9f3 3318 if (opts->xopts.nr > 0)
65850686
AG
3319 write_strategy_opts(opts);
3320
3321 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3322 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3323 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3324 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3325
3326 if (opts->gpg_sign)
3327 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3328 if (opts->signoff)
3329 write_file(rebase_path_signoff(), "--signoff\n");
e98c4269
EN
3330 if (opts->drop_redundant_commits)
3331 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3332 if (opts->keep_redundant_commits)
3333 write_file(rebase_path_keep_redundant_commits(), "%s", "");
7573cec5
PW
3334 if (opts->committer_date_is_author_date)
3335 write_file(rebase_path_cdate_is_adate(), "%s", "");
a3894aad
PW
3336 if (opts->ignore_date)
3337 write_file(rebase_path_ignore_date(), "%s", "");
d421afa0
JS
3338 if (opts->reschedule_failed_exec)
3339 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
e5b32bff
ÆAB
3340 else
3341 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
65850686
AG
3342
3343 return 0;
3344}
3345
004fefa7 3346static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
3347 struct replay_opts *opts)
3348{
004fefa7
JS
3349 enum todo_command command = opts->action == REPLAY_PICK ?
3350 TODO_PICK : TODO_REVERT;
414697a9 3351 const char *command_string = todo_command_info[command].str;
019a9d83 3352 const char *encoding;
043a4492 3353 struct commit *commit;
043a4492 3354
34b0528b
JS
3355 if (prepare_revs(opts))
3356 return -1;
043a4492 3357
019a9d83
ĐTCD
3358 encoding = get_log_output_encoding();
3359
004fefa7
JS
3360 while ((commit = get_revision(opts->revs))) {
3361 struct todo_item *item = append_new_todo(todo_list);
ecb5091f
ÆAB
3362 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3363 commit, NULL,
3364 encoding);
004fefa7
JS
3365 const char *subject;
3366 int subject_len;
3367
3368 item->command = command;
3369 item->commit = commit;
6ad656db 3370 item->arg_offset = 0;
c22f7dfb 3371 item->arg_len = 0;
004fefa7
JS
3372 item->offset_in_buf = todo_list->buf.len;
3373 subject_len = find_commit_subject(commit_buffer, &subject);
3374 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
cb646ffb
JK
3375 short_commit_name(the_repository, commit),
3376 subject_len, subject);
ecb5091f
ÆAB
3377 repo_unuse_commit_buffer(the_repository, commit,
3378 commit_buffer);
004fefa7 3379 }
8530c739
JK
3380
3381 if (!todo_list->nr)
3382 return error(_("empty commit set passed"));
3383
34b0528b 3384 return 0;
043a4492
RR
3385}
3386
6a1f9046 3387static int create_seq_dir(struct repository *r)
043a4492 3388{
6a1f9046
RA
3389 enum replay_action action;
3390 const char *in_progress_error = NULL;
3391 const char *in_progress_advice = NULL;
c8e4159e 3392 unsigned int advise_skip =
b8825ef2 3393 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
c8e4159e 3394 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
6a1f9046
RA
3395
3396 if (!sequencer_get_last_command(r, &action)) {
3397 switch (action) {
3398 case REPLAY_REVERT:
3399 in_progress_error = _("revert is already in progress");
3400 in_progress_advice =
dcb500dc 3401 _("try \"git revert (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3402 break;
3403 case REPLAY_PICK:
3404 in_progress_error = _("cherry-pick is already in progress");
3405 in_progress_advice =
dcb500dc 3406 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3407 break;
3408 default:
3409 BUG("unexpected action in create_seq_dir");
3410 }
3411 }
3412 if (in_progress_error) {
3413 error("%s", in_progress_error);
ed9bff08 3414 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
dcb500dc
RA
3415 advise(in_progress_advice,
3416 advise_skip ? "--skip | " : "");
043a4492 3417 return -1;
6a1f9046
RA
3418 }
3419 if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 3420 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 3421 git_path_seq_dir());
6a1f9046 3422
043a4492
RR
3423 return 0;
3424}
3425
311fd397 3426static int save_head(const char *head)
043a4492 3427{
54dbd093 3428 return write_message(head, strlen(head), git_path_head_file(), 1);
043a4492
RR
3429}
3430
1e41229d
SB
3431static int rollback_is_safe(void)
3432{
3433 struct strbuf sb = STRBUF_INIT;
3434 struct object_id expected_head, actual_head;
3435
3436 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3437 strbuf_trim(&sb);
3438 if (get_oid_hex(sb.buf, &expected_head)) {
3439 strbuf_release(&sb);
3440 die(_("could not parse %s"), git_path_abort_safety_file());
3441 }
3442 strbuf_release(&sb);
3443 }
3444 else if (errno == ENOENT)
9da95bda 3445 oidclr(&expected_head, the_repository->hash_algo);
1e41229d
SB
3446 else
3447 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3448
d850b7a5 3449 if (repo_get_oid(the_repository, "HEAD", &actual_head))
9da95bda 3450 oidclr(&actual_head, the_repository->hash_algo);
1e41229d 3451
4a7e27e9 3452 return oideq(&actual_head, &expected_head);
1e41229d
SB
3453}
3454
918d1e6e 3455static int reset_merge(const struct object_id *oid)
043a4492 3456{
0e906739 3457 struct child_process cmd = CHILD_PROCESS_INIT;
1e41229d 3458
0e906739
RS
3459 cmd.git_cmd = 1;
3460 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
265ab48f
RA
3461
3462 if (!is_null_oid(oid))
0e906739 3463 strvec_push(&cmd.args, oid_to_hex(oid));
265ab48f 3464
0e906739 3465 return run_command(&cmd);
043a4492
RR
3466}
3467
005af339 3468static int rollback_single_pick(struct repository *r)
043a4492 3469{
092bbcdf 3470 struct object_id head_oid;
043a4492 3471
c8e4159e 3472 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 3473 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 3474 return error(_("no cherry-pick or revert in progress"));
2e5c4758 3475 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
043a4492 3476 return error(_("cannot resolve HEAD"));
092bbcdf 3477 if (is_null_oid(&head_oid))
043a4492 3478 return error(_("cannot abort from a branch yet to be born"));
918d1e6e 3479 return reset_merge(&head_oid);
043a4492
RR
3480}
3481
de81ca3f
RA
3482static int skip_single_pick(void)
3483{
3484 struct object_id head;
3485
2e5c4758 3486 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
de81ca3f
RA
3487 return error(_("cannot resolve HEAD"));
3488 return reset_merge(&head);
043a4492
RR
3489}
3490
005af339 3491int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 3492{
043a4492 3493 FILE *f;
092bbcdf 3494 struct object_id oid;
043a4492 3495 struct strbuf buf = STRBUF_INIT;
092bbcdf 3496 const char *p;
043a4492 3497
f932729c 3498 f = fopen(git_path_head_file(), "r");
043a4492
RR
3499 if (!f && errno == ENOENT) {
3500 /*
3501 * There is no multiple-cherry-pick in progress.
3502 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3503 * a single-cherry-pick in progress, abort that.
3504 */
005af339 3505 return rollback_single_pick(r);
043a4492
RR
3506 }
3507 if (!f)
f7ed1953 3508 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 3509 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 3510 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 3511 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
3512 fclose(f);
3513 goto fail;
3514 }
3515 fclose(f);
092bbcdf 3516 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 3517 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 3518 git_path_head_file());
043a4492
RR
3519 goto fail;
3520 }
092bbcdf 3521 if (is_null_oid(&oid)) {
0f974e21
MG
3522 error(_("cannot abort from a branch yet to be born"));
3523 goto fail;
3524 }
1e41229d
SB
3525
3526 if (!rollback_is_safe()) {
3527 /* Do not error, just do not rollback */
3528 warning(_("You seem to have moved HEAD. "
3529 "Not rewinding, check your HEAD!"));
3530 } else
918d1e6e 3531 if (reset_merge(&oid))
043a4492 3532 goto fail;
043a4492 3533 strbuf_release(&buf);
2863584f 3534 return sequencer_remove_state(opts);
043a4492
RR
3535fail:
3536 strbuf_release(&buf);
3537 return -1;
3538}
3539
de81ca3f
RA
3540int sequencer_skip(struct repository *r, struct replay_opts *opts)
3541{
3542 enum replay_action action = -1;
3543 sequencer_get_last_command(r, &action);
3544
3545 /*
3546 * Check whether the subcommand requested to skip the commit is actually
3547 * in progress and that it's safe to skip the commit.
3548 *
3549 * opts->action tells us which subcommand requested to skip the commit.
3550 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3551 * action is in progress and we can skip the commit.
3552 *
3553 * Otherwise we check that the last instruction was related to the
3554 * particular subcommand we're trying to execute and barf if that's not
3555 * the case.
3556 *
3557 * Finally we check that the rollback is "safe", i.e., has the HEAD
3558 * moved? In this case, it doesn't make sense to "reset the merge" and
3559 * "skip the commit" as the user already handled this by committing. But
3560 * we'd not want to barf here, instead give advice on how to proceed. We
3561 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3562 * it gets removed when the user commits, so if it still exists we're
3563 * sure the user can't have committed before.
3564 */
3565 switch (opts->action) {
3566 case REPLAY_REVERT:
b8825ef2 3567 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
de81ca3f
RA
3568 if (action != REPLAY_REVERT)
3569 return error(_("no revert in progress"));
3570 if (!rollback_is_safe())
3571 goto give_advice;
3572 }
3573 break;
3574 case REPLAY_PICK:
c8e4159e
HWN
3575 if (!refs_ref_exists(get_main_ref_store(r),
3576 "CHERRY_PICK_HEAD")) {
de81ca3f
RA
3577 if (action != REPLAY_PICK)
3578 return error(_("no cherry-pick in progress"));
3579 if (!rollback_is_safe())
3580 goto give_advice;
3581 }
3582 break;
3583 default:
3584 BUG("unexpected action in sequencer_skip");
3585 }
3586
3587 if (skip_single_pick())
3588 return error(_("failed to skip the commit"));
3589 if (!is_directory(git_path_seq_dir()))
3590 return 0;
3591
3592 return sequencer_continue(r, opts);
3593
3594give_advice:
3595 error(_("there is nothing to skip"));
3596
ed9bff08 3597 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
de81ca3f
RA
3598 advise(_("have you committed already?\n"
3599 "try \"git %s --continue\""),
3600 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3601 }
3602 return -1;
3603}
3604
203573b0
PW
3605static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3606 int reschedule)
043a4492 3607{
14bca6c6 3608 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
3609 const char *todo_path = get_todo_path(opts);
3610 int next = todo_list->current, offset, fd;
043a4492 3611
84583957
JS
3612 /*
3613 * rebase -i writes "git-rebase-todo" without the currently executing
3614 * command, appending it to "done" instead.
3615 */
203573b0 3616 if (is_rebase_i(opts) && !reschedule)
84583957
JS
3617 next++;
3618
004fefa7 3619 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 3620 if (fd < 0)
93b3df6f 3621 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 3622 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
3623 if (write_in_full(fd, todo_list->buf.buf + offset,
3624 todo_list->buf.len - offset) < 0)
93b3df6f 3625 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 3626 if (commit_lock_file(&todo_lock) < 0)
350292a1 3627 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 3628
203573b0 3629 if (is_rebase_i(opts) && !reschedule && next > 0) {
a01c2a5f
JS
3630 const char *done = rebase_path_done();
3631 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3632 int ret = 0;
1df6df0c 3633
a01c2a5f
JS
3634 if (fd < 0)
3635 return 0;
3636 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3637 get_item_line_length(todo_list, next - 1))
3638 < 0)
3639 ret = error_errno(_("could not write to '%s'"), done);
3640 if (close(fd) < 0)
3641 ret = error_errno(_("failed to finalize '%s'"), done);
3642 return ret;
1df6df0c 3643 }
221675de 3644 return 0;
043a4492
RR
3645}
3646
88d5a271 3647static int save_opts(struct replay_opts *opts)
043a4492 3648{
f932729c 3649 const char *opts_file = git_path_opts_file();
88d5a271 3650 int res = 0;
043a4492
RR
3651
3652 if (opts->no_commit)
f59199d5 3653 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3654 "options.no-commit", NULL, "true");
39edfd5c 3655 if (opts->edit >= 0)
42d5c033 3656 res |= git_config_set_in_file_gently(opts_file, "options.edit", NULL,
39edfd5c 3657 opts->edit ? "true" : "false");
6860ce5d
PW
3658 if (opts->allow_empty)
3659 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3660 "options.allow-empty", NULL, "true");
6860ce5d
PW
3661 if (opts->allow_empty_message)
3662 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3663 "options.allow-empty-message", NULL, "true");
ec79d763
BL
3664 if (opts->drop_redundant_commits)
3665 res |= git_config_set_in_file_gently(opts_file,
3256584c 3666 "options.drop-redundant-commits", NULL, "true");
6860ce5d
PW
3667 if (opts->keep_redundant_commits)
3668 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3669 "options.keep-redundant-commits", NULL, "true");
043a4492 3670 if (opts->signoff)
f59199d5 3671 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3672 "options.signoff", NULL, "true");
043a4492 3673 if (opts->record_origin)
f59199d5 3674 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3675 "options.record-origin", NULL, "true");
043a4492 3676 if (opts->allow_ff)
f59199d5 3677 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3678 "options.allow-ff", NULL, "true");
043a4492
RR
3679 if (opts->mainline) {
3680 struct strbuf buf = STRBUF_INIT;
3681 strbuf_addf(&buf, "%d", opts->mainline);
f59199d5 3682 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3683 "options.mainline", NULL, buf.buf);
043a4492
RR
3684 strbuf_release(&buf);
3685 }
3686 if (opts->strategy)
f59199d5 3687 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3688 "options.strategy", NULL, opts->strategy);
3253553e 3689 if (opts->gpg_sign)
f59199d5 3690 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3691 "options.gpg-sign", NULL, opts->gpg_sign);
fb60b9f3
PW
3692 for (size_t i = 0; i < opts->xopts.nr; i++)
3693 res |= git_config_set_multivar_in_file_gently(opts_file,
3694 "options.strategy-option",
42d5c033 3695 opts->xopts.v[i], "^$", NULL, 0);
8d8cb4b0 3696 if (opts->allow_rerere_auto)
f59199d5 3697 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3698 "options.allow-rerere-auto", NULL,
f59199d5
PW
3699 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3700 "true" : "false");
dc42e9a8
PW
3701
3702 if (opts->explicit_cleanup)
3703 res |= git_config_set_in_file_gently(opts_file,
42d5c033 3704 "options.default-msg-cleanup", NULL,
dc42e9a8 3705 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 3706 return res;
043a4492
RR
3707}
3708
f11c9580
NTND
3709static int make_patch(struct repository *r,
3710 struct commit *commit,
3711 struct replay_opts *opts)
56dc3ab0 3712{
56dc3ab0 3713 struct rev_info log_tree_opt;
0512eabd
JH
3714 const char *subject;
3715 char hex[GIT_MAX_HEXSZ + 1];
56dc3ab0
JS
3716 int res = 0;
3717
206a78d7
PW
3718 if (!is_rebase_i(opts))
3719 BUG("make_patch should only be called when rebasing");
3720
0512eabd
JH
3721 oid_to_hex_r(hex, &commit->object.oid);
3722 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
56dc3ab0 3723 return -1;
430b75f7 3724 res |= write_rebase_head(&commit->object.oid);
56dc3ab0 3725
56dc3ab0 3726 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3727 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
3728 log_tree_opt.abbrev = 0;
3729 log_tree_opt.diff = 1;
3730 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3731 log_tree_opt.disable_stdin = 1;
3732 log_tree_opt.no_commit_id = 1;
206a78d7 3733 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
56dc3ab0
JS
3734 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3735 if (!log_tree_opt.diffopt.file)
206a78d7
PW
3736 res |= error_errno(_("could not open '%s'"),
3737 rebase_path_patch());
56dc3ab0
JS
3738 else {
3739 res |= log_tree_commit(&log_tree_opt, commit);
3740 fclose(log_tree_opt.diffopt.file);
3741 }
56dc3ab0 3742
9f67899b 3743 if (!file_exists(rebase_path_message())) {
52f52e5a 3744 const char *encoding = get_commit_output_encoding();
4a93b899 3745 const char *commit_buffer = repo_logmsg_reencode(r,
ecb5091f
ÆAB
3746 commit, NULL,
3747 encoding);
56dc3ab0 3748 find_commit_subject(commit_buffer, &subject);
9f67899b 3749 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
4a93b899 3750 repo_unuse_commit_buffer(r, commit,
ecb5091f 3751 commit_buffer);
56dc3ab0 3752 }
2108fe4a 3753 release_revisions(&log_tree_opt);
56dc3ab0
JS
3754
3755 return res;
3756}
3757
3758static int intend_to_amend(void)
3759{
092bbcdf 3760 struct object_id head;
56dc3ab0
JS
3761 char *p;
3762
d850b7a5 3763 if (repo_get_oid(the_repository, "HEAD", &head))
56dc3ab0
JS
3764 return error(_("cannot read HEAD"));
3765
092bbcdf 3766 p = oid_to_hex(&head);
56dc3ab0
JS
3767 return write_message(p, strlen(p), rebase_path_amend(), 1);
3768}
3769
f11c9580
NTND
3770static int error_with_patch(struct repository *r,
3771 struct commit *commit,
3772 const char *subject, int subject_len,
3773 struct replay_opts *opts,
3774 int exit_code, int to_amend)
56dc3ab0 3775{
a6c2654f
PW
3776 struct replay_ctx *ctx = opts->ctx;
3777
3778 /*
3779 * Write the commit message to be used by "git rebase
3780 * --continue". If a "fixup" or "squash" command has conflicts
3781 * then we will have already written rebase_path_message() in
3782 * error_failed_squash(). If an "edit" command was
3783 * fast-forwarded then we don't have a message in ctx->message
3784 * and rely on make_patch() to write rebase_path_message()
3785 * instead.
3786 */
3787 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3788 write_message(ctx->message.buf, ctx->message.len,
3789 rebase_path_message(), 0))
3790 return error(_("could not write commit message file"));
3791
3792 if (commit && make_patch(r, commit, opts))
bc9238bb 3793 return -1;
56dc3ab0
JS
3794
3795 if (to_amend) {
3796 if (intend_to_amend())
3797 return -1;
3798
02127c63
NTND
3799 fprintf(stderr,
3800 _("You can amend the commit now, with\n"
3801 "\n"
3802 " git commit --amend %s\n"
3803 "\n"
3804 "Once you are satisfied with your changes, run\n"
3805 "\n"
3806 " git rebase --continue\n"),
3807 gpg_sign_opt_quoted(opts));
bc9238bb
PW
3808 } else if (exit_code) {
3809 if (commit)
5a5c5e95 3810 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
cb646ffb 3811 short_commit_name(r, commit), subject_len, subject);
bc9238bb
PW
3812 else
3813 /*
3814 * We don't have the hash of the parent so
3815 * just print the line from the todo file.
3816 */
5a5c5e95
JH
3817 fprintf_ln(stderr, _("Could not merge %.*s"),
3818 subject_len, subject);
bc9238bb 3819 }
56dc3ab0
JS
3820
3821 return exit_code;
3822}
3823
f11c9580
NTND
3824static int error_failed_squash(struct repository *r,
3825 struct commit *commit,
3826 struct replay_opts *opts,
3827 int subject_len,
3828 const char *subject)
6e98de72 3829{
e12a7ef5
JS
3830 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3831 return error(_("could not copy '%s' to '%s'"),
6e98de72 3832 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
3833 unlink(git_path_merge_msg(r));
3834 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 3835 return error(_("could not copy '%s' to '%s'"),
102de880 3836 rebase_path_message(),
f11c9580
NTND
3837 git_path_merge_msg(r));
3838 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
3839}
3840
4bdd6b7b 3841static int do_exec(struct repository *r, const char *command_line, int quiet)
311af526 3842{
ddbb47fd 3843 struct child_process cmd = CHILD_PROCESS_INIT;
311af526
JS
3844 int dirty, status;
3845
4bdd6b7b
MT
3846 if (!quiet)
3847 fprintf(stderr, _("Executing: %s\n"), command_line);
ddbb47fd
RS
3848 cmd.use_shell = 1;
3849 strvec_push(&cmd.args, command_line);
e4301f73 3850 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
ddbb47fd 3851 status = run_command(&cmd);
311af526
JS
3852
3853 /* force re-reading of the cache */
9c5f3ee3
ÆAB
3854 discard_index(r->index);
3855 if (repo_read_index(r) < 0)
311af526
JS
3856 return error(_("could not read index"));
3857
f11c9580 3858 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
3859
3860 if (status) {
3861 warning(_("execution failed: %s\n%s"
3862 "You can fix the problem, and then run\n"
3863 "\n"
3864 " git rebase --continue\n"
3865 "\n"),
3866 command_line,
d45cbe3f 3867 dirty ? _("and made changes to the index and/or the "
b734fe49 3868 "working tree.\n") : "");
311af526
JS
3869 if (status == 127)
3870 /* command not found */
3871 status = 1;
3872 } else if (dirty) {
3873 warning(_("execution succeeded: %s\nbut "
b734fe49 3874 "left changes to the index and/or the working tree.\n"
311af526
JS
3875 "Commit or stash your changes, and then run\n"
3876 "\n"
3877 " git rebase --continue\n"
3878 "\n"), command_line);
3879 status = 1;
3880 }
3881
3882 return status;
3883}
3884
48ca53ca 3885__attribute__((format (printf, 2, 3)))
9055e401
JS
3886static int safe_append(const char *filename, const char *fmt, ...)
3887{
3888 va_list ap;
3889 struct lock_file lock = LOCK_INIT;
3890 int fd = hold_lock_file_for_update(&lock, filename,
3891 LOCK_REPORT_ON_ERROR);
3892 struct strbuf buf = STRBUF_INIT;
3893
3894 if (fd < 0)
3895 return -1;
3896
3897 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3898 error_errno(_("could not read '%s'"), filename);
3899 rollback_lock_file(&lock);
3900 return -1;
3901 }
3902 strbuf_complete(&buf, '\n');
3903 va_start(ap, fmt);
3904 strbuf_vaddf(&buf, fmt, ap);
3905 va_end(ap);
3906
3907 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3908 error_errno(_("could not write to '%s'"), filename);
3909 strbuf_release(&buf);
3910 rollback_lock_file(&lock);
3911 return -1;
3912 }
3913 if (commit_lock_file(&lock) < 0) {
3914 strbuf_release(&buf);
9055e401
JS
3915 return error(_("failed to finalize '%s'"), filename);
3916 }
3917
3918 strbuf_release(&buf);
3919 return 0;
3920}
3921
f11c9580 3922static int do_label(struct repository *r, const char *name, int len)
9055e401 3923{
f11c9580 3924 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3925 struct ref_transaction *transaction;
3926 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3927 struct strbuf msg = STRBUF_INIT;
3928 int ret = 0;
3929 struct object_id head_oid;
3930
3931 if (len == 1 && *name == '#')
02127c63 3932 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3933
3934 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3935 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401 3936
a0efef14 3937 transaction = ref_store_transaction_begin(refs, 0, &err);
9055e401
JS
3938 if (!transaction) {
3939 error("%s", err.buf);
3940 ret = -1;
4a93b899 3941 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
9055e401
JS
3942 error(_("could not read HEAD"));
3943 ret = -1;
1bc4cc3f
KN
3944 } else if (ref_transaction_update(transaction, ref_name.buf,
3945 &head_oid, NULL, NULL, NULL,
3946 0, msg.buf, &err) < 0 ||
9055e401
JS
3947 ref_transaction_commit(transaction, &err)) {
3948 error("%s", err.buf);
3949 ret = -1;
3950 }
3951 ref_transaction_free(transaction);
3952 strbuf_release(&err);
3953 strbuf_release(&msg);
3954
3955 if (!ret)
3956 ret = safe_append(rebase_path_refs_to_delete(),
3957 "%s\n", ref_name.buf);
3958 strbuf_release(&ref_name);
3959
3960 return ret;
3961}
3962
688d82f2
PW
3963static struct commit *lookup_label(struct repository *r, const char *label,
3964 int len, struct strbuf *buf)
82766b29
PW
3965{
3966 struct commit *commit;
688d82f2 3967 struct object_id oid;
82766b29
PW
3968
3969 strbuf_reset(buf);
3970 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
2e5c4758 3971 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
688d82f2
PW
3972 commit = lookup_commit_object(r, &oid);
3973 } else {
82766b29
PW
3974 /* fall back to non-rewritten ref or commit */
3975 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3976 commit = lookup_commit_reference_by_name(buf->buf);
3977 }
3978
3979 if (!commit)
3980 error(_("could not resolve '%s'"), buf->buf);
3981
3982 return commit;
3983}
3984
f11c9580
NTND
3985static int do_reset(struct repository *r,
3986 const char *name, int len,
3987 struct replay_opts *opts)
9055e401
JS
3988{
3989 struct strbuf ref_name = STRBUF_INIT;
3990 struct object_id oid;
3991 struct lock_file lock = LOCK_INIT;
0c52cf8e 3992 struct tree_desc desc = { 0 };
9055e401 3993 struct tree *tree;
6e658547 3994 struct unpack_trees_options unpack_tree_opts = { 0 };
71571cd7 3995 int ret = 0;
9055e401 3996
3a95f31d 3997 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3998 return -1;
3999
ebddf393
JS
4000 if (len == 10 && !strncmp("[new root]", name, len)) {
4001 if (!opts->have_squash_onto) {
4002 const char *hex;
4003 if (commit_tree("", 0, the_hash_algo->empty_tree,
4004 NULL, &opts->squash_onto,
4005 NULL, NULL))
4006 return error(_("writing fake root commit"));
4007 opts->have_squash_onto = 1;
4008 hex = oid_to_hex(&opts->squash_onto);
4009 if (write_message(hex, strlen(hex),
4010 rebase_path_squash_onto(), 0))
4011 return error(_("writing squash-onto"));
4012 }
4013 oidcpy(&oid, &opts->squash_onto);
4014 } else {
71571cd7 4015 int i;
82766b29 4016 struct commit *commit;
71571cd7 4017
ebddf393
JS
4018 /* Determine the length of the label */
4019 for (i = 0; i < len; i++)
4020 if (isspace(name[i]))
71571cd7
4021 break;
4022 len = i;
ebddf393 4023
688d82f2 4024 commit = lookup_label(r, name, len, &ref_name);
82766b29
PW
4025 if (!commit) {
4026 ret = -1;
0c52cf8e 4027 goto cleanup;
ebddf393 4028 }
82766b29 4029 oid = commit->object.oid;
9055e401
JS
4030 }
4031
9055e401
JS
4032 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4033 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
4034 unpack_tree_opts.src_index = r->index;
4035 unpack_tree_opts.dst_index = r->index;
9055e401
JS
4036 unpack_tree_opts.fn = oneway_merge;
4037 unpack_tree_opts.merge = 1;
4038 unpack_tree_opts.update = 1;
1b5f3733 4039 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
652bd021 4040 unpack_tree_opts.skip_cache_tree_update = 1;
3f267856 4041 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
9055e401 4042
e1ff0a32 4043 if (repo_read_index_unmerged(r)) {
1c8dfc36 4044 ret = error_resolve_conflict(action_name(opts));
0c52cf8e 4045 goto cleanup;
9055e401
JS
4046 }
4047
5e575807 4048 if (!fill_tree_descriptor(r, &desc, &oid)) {
0c52cf8e
ÆAB
4049 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4050 goto cleanup;
9055e401
JS
4051 }
4052
4053 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
0c52cf8e
ÆAB
4054 ret = -1;
4055 goto cleanup;
9055e401
JS
4056 }
4057
4058 tree = parse_tree_indirect(&oid);
aa9f6189
JS
4059 if (!tree)
4060 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
c207e9e1 4061 prime_cache_tree(r, r->index, tree);
9055e401 4062
f11c9580 4063 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401 4064 ret = error(_("could not write index"));
9055e401
JS
4065
4066 if (!ret)
2e5c4758
PS
4067 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4068 len, name),
4069 "HEAD", &oid,
4070 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
0c52cf8e
ÆAB
4071cleanup:
4072 free((void *)desc.buffer);
4073 if (ret < 0)
4074 rollback_lock_file(&lock);
9055e401 4075 strbuf_release(&ref_name);
6e658547 4076 clear_unpack_trees_porcelain(&unpack_tree_opts);
9055e401
JS
4077 return ret;
4078}
4079
f11c9580
NTND
4080static int do_merge(struct repository *r,
4081 struct commit *commit,
4082 const char *arg, int arg_len,
2be6b6f4 4083 int flags, int *check_todo, struct replay_opts *opts)
4c68e7dd 4084{
53f67466 4085 struct replay_ctx *ctx = opts->ctx;
2be6b6f4 4086 int run_commit_flags = 0;
4c68e7dd
JS
4087 struct strbuf ref_name = STRBUF_INIT;
4088 struct commit *head_commit, *merge_commit, *i;
76e2a099 4089 struct commit_list *bases = NULL, *j;
2b6ad0f4 4090 struct commit_list *to_merge = NULL, **tail = &to_merge;
fb60b9f3 4091 const char *strategy = !opts->xopts.nr &&
14c4586c
EN
4092 (!opts->strategy ||
4093 !strcmp(opts->strategy, "recursive") ||
4094 !strcmp(opts->strategy, "ort")) ?
e145d993 4095 NULL : opts->strategy;
4c68e7dd 4096 struct merge_options o;
2b6ad0f4 4097 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
4098 static struct lock_file lock;
4099 const char *p;
5dbaec62 4100 const char *reflog_action = reflog_message(opts, "merge", NULL);
4c68e7dd 4101
3a95f31d 4102 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
4103 ret = -1;
4104 goto leave_merge;
4105 }
4106
4107 head_commit = lookup_commit_reference_by_name("HEAD");
4108 if (!head_commit) {
4109 ret = error(_("cannot merge without a current revision"));
4110 goto leave_merge;
4111 }
4112
2b6ad0f4
JS
4113 /*
4114 * For octopus merges, the arg starts with the list of revisions to be
4115 * merged. The list is optionally followed by '#' and the oneline.
4116 */
4117 merge_arg_len = oneline_offset = arg_len;
4118 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4119 if (!*p)
4120 break;
4121 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4122 p += 1 + strspn(p + 1, " \t\n");
4123 oneline_offset = p - arg;
4124 break;
4125 }
4126 k = strcspn(p, " \t\n");
4127 if (!k)
4128 continue;
688d82f2 4129 merge_commit = lookup_label(r, p, k, &ref_name);
2b6ad0f4
JS
4130 if (!merge_commit) {
4131 ret = error(_("unable to parse '%.*s'"), k, p);
4132 goto leave_merge;
4133 }
4134 tail = &commit_list_insert(merge_commit, tail)->next;
4135 p += k;
4136 merge_arg_len = p - arg;
4c68e7dd
JS
4137 }
4138
2b6ad0f4
JS
4139 if (!to_merge) {
4140 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
4141 goto leave_merge;
4142 }
4143
9c85a1c2 4144 if (opts->have_squash_onto &&
4a7e27e9 4145 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
4146 /*
4147 * When the user tells us to "merge" something into a
4148 * "[new root]", let's simply fast-forward to the merge head.
4149 */
4150 rollback_lock_file(&lock);
2b6ad0f4
JS
4151 if (to_merge->next)
4152 ret = error(_("octopus merge cannot be executed on "
4153 "top of a [new root]"));
4154 else
f11c9580 4155 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
4156 &head_commit->object.oid, 0,
4157 opts);
9c85a1c2
JS
4158 goto leave_merge;
4159 }
4160
baf8ec8d
PW
4161 /*
4162 * If HEAD is not identical to the first parent of the original merge
4163 * commit, we cannot fast-forward.
4164 */
4165 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4166 oideq(&commit->parents->item->object.oid,
4167 &head_commit->object.oid);
4168
4169 /*
4170 * If any merge head is different from the original one, we cannot
4171 * fast-forward.
4172 */
4173 if (can_fast_forward) {
4174 struct commit_list *p = commit->parents->next;
4175
4176 for (j = to_merge; j && p; j = j->next, p = p->next)
4177 if (!oideq(&j->item->object.oid,
4178 &p->item->object.oid)) {
4179 can_fast_forward = 0;
4180 break;
4181 }
4182 /*
4183 * If the number of merge heads differs from the original merge
4184 * commit, we cannot fast-forward.
4185 */
4186 if (j || p)
4187 can_fast_forward = 0;
4188 }
4189
4190 if (can_fast_forward) {
4191 rollback_lock_file(&lock);
4192 ret = fast_forward_to(r, &commit->object.oid,
4193 &head_commit->object.oid, 0, opts);
4194 if (flags & TODO_EDIT_MERGE_MSG)
4195 goto fast_forward_edit;
4196
4197 goto leave_merge;
4198 }
4199
4c68e7dd 4200 if (commit) {
5772b0c7 4201 const char *encoding = get_commit_output_encoding();
4a93b899 4202 const char *message = repo_logmsg_reencode(r, commit, NULL,
ecb5091f 4203 encoding);
4c68e7dd
JS
4204 const char *body;
4205 int len;
4206
4207 if (!message) {
4208 ret = error(_("could not get commit message of '%s'"),
4209 oid_to_hex(&commit->object.oid));
4210 goto leave_merge;
4211 }
4212 write_author_script(message);
4213 find_commit_subject(message, &body);
4214 len = strlen(body);
53f67466 4215 strbuf_add(&ctx->message, body, len);
4a93b899 4216 repo_unuse_commit_buffer(r, commit, message);
4c68e7dd
JS
4217 } else {
4218 struct strbuf buf = STRBUF_INIT;
4c68e7dd
JS
4219
4220 strbuf_addf(&buf, "author %s", git_author_info(0));
4221 write_author_script(buf.buf);
53f67466 4222 strbuf_release(&buf);
4c68e7dd
JS
4223
4224 if (oneline_offset < arg_len) {
53f67466
PW
4225 strbuf_add(&ctx->message, arg + oneline_offset,
4226 arg_len - oneline_offset);
4c68e7dd 4227 } else {
53f67466 4228 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
2b6ad0f4 4229 to_merge->next ? "branches" : "branch",
4c68e7dd 4230 merge_arg_len, arg);
4c68e7dd
JS
4231 }
4232 }
53f67466
PW
4233 ctx->have_message = 1;
4234 if (write_message(ctx->message.buf, ctx->message.len,
4235 git_path_merge_msg(r), 0)) {
4236 ret = error_errno(_("could not write '%s'"),
4237 git_path_merge_msg(r));
4238 goto leave_merge;
4239 }
4c68e7dd 4240
e145d993 4241 if (strategy || to_merge->next) {
2b6ad0f4
JS
4242 /* Octopus merge */
4243 struct child_process cmd = CHILD_PROCESS_INIT;
4244
29fda24d 4245 if (read_env_script(&cmd.env)) {
2b6ad0f4
JS
4246 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4247
4248 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4249 goto leave_merge;
4250 }
4251
7573cec5 4252 if (opts->committer_date_is_author_date)
29fda24d 4253 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
9c31b19d
JH
4254 opts->ignore_date ?
4255 "" :
b3193252 4256 author_date_from_env(&cmd.env));
a3894aad 4257 if (opts->ignore_date)
29fda24d 4258 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
7573cec5 4259
2b6ad0f4 4260 cmd.git_cmd = 1;
c972bf4c
JK
4261 strvec_push(&cmd.args, "merge");
4262 strvec_push(&cmd.args, "-s");
e145d993 4263 if (!strategy)
c972bf4c 4264 strvec_push(&cmd.args, "octopus");
e145d993 4265 else {
c972bf4c 4266 strvec_push(&cmd.args, strategy);
fb60b9f3 4267 for (k = 0; k < opts->xopts.nr; k++)
c972bf4c 4268 strvec_pushf(&cmd.args,
fb60b9f3 4269 "-X%s", opts->xopts.v[k]);
e145d993 4270 }
f2563c9e
PW
4271 if (!(flags & TODO_EDIT_MERGE_MSG))
4272 strvec_push(&cmd.args, "--no-edit");
4273 else
4274 strvec_push(&cmd.args, "--edit");
c972bf4c
JK
4275 strvec_push(&cmd.args, "--no-ff");
4276 strvec_push(&cmd.args, "--no-log");
4277 strvec_push(&cmd.args, "--no-stat");
4278 strvec_push(&cmd.args, "-F");
4279 strvec_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4 4280 if (opts->gpg_sign)
ae03c97a 4281 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
19dad040
4282 else
4283 strvec_push(&cmd.args, "--no-gpg-sign");
2b6ad0f4
JS
4284
4285 /* Add the tips to be merged */
4286 for (j = to_merge; j; j = j->next)
c972bf4c 4287 strvec_push(&cmd.args,
f6d8942b 4288 oid_to_hex(&j->item->object.oid));
2b6ad0f4
JS
4289
4290 strbuf_release(&ref_name);
c8e4159e 4291 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
821f6632 4292 NULL, REF_NO_DEREF);
2b6ad0f4
JS
4293 rollback_lock_file(&lock);
4294
2b6ad0f4
JS
4295 ret = run_command(&cmd);
4296
4297 /* force re-reading of the cache */
9c5f3ee3
ÆAB
4298 if (!ret) {
4299 discard_index(r->index);
4300 if (repo_read_index(r) < 0)
4301 ret = error(_("could not read index"));
4302 }
2b6ad0f4
JS
4303 goto leave_merge;
4304 }
4305
4306 merge_commit = to_merge->item;
76e2a099
JS
4307 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4308 ret = -1;
4309 goto leave_merge;
4310 }
4311
4a7e27e9
JK
4312 if (bases && oideq(&merge_commit->object.oid,
4313 &bases->item->object.oid)) {
7ccdf65b
JS
4314 ret = 0;
4315 /* skip merging an ancestor of HEAD */
4316 goto leave_merge;
4317 }
4318
4439c7a3 4319 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
4320 git_path_merge_head(r), 0);
4321 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 4322
5327d898 4323 bases = reverse_commit_list(bases);
4c68e7dd 4324
e1ff0a32 4325 repo_read_index(r);
9c93ba4d 4326 init_ui_merge_options(&o, r);
4c68e7dd
JS
4327 o.branch1 = "HEAD";
4328 o.branch2 = ref_name.buf;
4329 o.buffer_output = 2;
4330
75cd9ae0
EN
4331 /*
4332 * TODO: Should use merge_incore_recursive() and
4333 * merge_switch_to_result(), skipping the call to
4334 * merge_switch_to_result() when we don't actually need to
4335 * update the index and working copy immediately.
4336 */
4337 ret = merge_ort_recursive(&o, head_commit, merge_commit, bases, &i);
4c68e7dd
JS
4338 if (ret <= 0)
4339 fputs(o.obuf.buf, stdout);
4340 strbuf_release(&o.obuf);
4341 if (ret < 0) {
4342 error(_("could not even attempt to merge '%.*s'"),
4343 merge_arg_len, arg);
e032abd5 4344 unlink(git_path_merge_msg(r));
4c68e7dd
JS
4345 goto leave_merge;
4346 }
4347 /*
75cd9ae0 4348 * The return value of merge_ort_recursive() is 1 on clean, and 0 on
4c68e7dd
JS
4349 * unclean merge.
4350 *
4351 * Let's reverse that, so that do_merge() returns 0 upon success and
4352 * 1 upon failed merge (keeping the return value -1 for the cases where
4353 * we will want to reschedule the `merge` command).
4354 */
4355 ret = !ret;
4356
f11c9580
NTND
4357 if (r->index->cache_changed &&
4358 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
4359 ret = error(_("merge: Unable to write new index file"));
4360 goto leave_merge;
4361 }
4362
4363 rollback_lock_file(&lock);
4364 if (ret)
f11c9580 4365 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
4366 else
4367 /*
4368 * In case of problems, we now want to return a positive
4369 * value (a negative one would indicate that the `merge`
4370 * command needs to be rescheduled).
4371 */
5dbaec62
PW
4372 ret = !!run_git_commit(git_path_merge_msg(r), reflog_action,
4373 opts, run_commit_flags);
4c68e7dd 4374
2be6b6f4
PW
4375 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4376 fast_forward_edit:
4377 *check_todo = 1;
4378 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
5dbaec62
PW
4379 ret = !!run_git_commit(NULL, reflog_action, opts,
4380 run_commit_flags);
2be6b6f4
PW
4381 }
4382
4383
4c68e7dd
JS
4384leave_merge:
4385 strbuf_release(&ref_name);
4386 rollback_lock_file(&lock);
2b6ad0f4 4387 free_commit_list(to_merge);
44ec7c57 4388 free_commit_list(bases);
4c68e7dd
JS
4389 return ret;
4390}
4391
89fc0b53
DS
4392static int write_update_refs_state(struct string_list *refs_to_oids)
4393{
4394 int result = 0;
4395 struct lock_file lock = LOCK_INIT;
4396 FILE *fp = NULL;
4397 struct string_list_item *item;
4398 char *path;
4399
89fc0b53
DS
4400 path = rebase_path_update_refs(the_repository->gitdir);
4401
44da9e08
VD
4402 if (!refs_to_oids->nr) {
4403 if (unlink(path) && errno != ENOENT)
4404 result = error_errno(_("could not unlink: %s"), path);
4405 goto cleanup;
4406 }
4407
1a99fe80 4408 if (safe_create_leading_directories(the_repository, path)) {
89fc0b53
DS
4409 result = error(_("unable to create leading directories of %s"),
4410 path);
4411 goto cleanup;
4412 }
4413
4414 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4415 result = error(_("another 'rebase' process appears to be running; "
4416 "'%s.lock' already exists"),
4417 path);
4418 goto cleanup;
4419 }
4420
4421 fp = fdopen_lock_file(&lock, "w");
4422 if (!fp) {
4423 result = error_errno(_("could not open '%s' for writing"), path);
4424 rollback_lock_file(&lock);
4425 goto cleanup;
4426 }
4427
4428 for_each_string_list_item(item, refs_to_oids) {
4429 struct update_ref_record *rec = item->util;
4430 fprintf(fp, "%s\n%s\n%s\n", item->string,
4431 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4432 }
4433
4434 result = commit_lock_file(&lock);
4435
4436cleanup:
4437 free(path);
4438 return result;
4439}
4440
b3b1a21d
DS
4441/*
4442 * Parse the update-refs file for the current rebase, then remove the
4443 * refs that do not appear in the todo_list (and have not had updated
4444 * values stored) and add refs that are in the todo_list but not
4445 * represented in the update-refs file.
4446 *
4447 * If there are changes to the update-refs list, then write the new state
4448 * to disk.
4449 */
4450void todo_list_filter_update_refs(struct repository *r,
4451 struct todo_list *todo_list)
4452{
4453 int i;
4454 int updated = 0;
4455 struct string_list update_refs = STRING_LIST_INIT_DUP;
4456
4457 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4458
4459 /*
4460 * For each item in the update_refs list, if it has no updated
4461 * value and does not appear in the todo_list, then remove it
4462 * from the update_refs list.
4463 */
4464 for (i = 0; i < update_refs.nr; i++) {
4465 int j;
4466 int found = 0;
4467 const char *ref = update_refs.items[i].string;
4468 size_t reflen = strlen(ref);
4469 struct update_ref_record *rec = update_refs.items[i].util;
4470
4471 /* OID already stored as updated. */
4472 if (!is_null_oid(&rec->after))
4473 continue;
4474
fa5103dd 4475 for (j = 0; !found && j < todo_list->nr; j++) {
b3b1a21d
DS
4476 struct todo_item *item = &todo_list->items[j];
4477 const char *arg = todo_list->buf.buf + item->arg_offset;
4478
4479 if (item->command != TODO_UPDATE_REF)
4480 continue;
4481
4482 if (item->arg_len != reflen ||
4483 strncmp(arg, ref, reflen))
4484 continue;
4485
4486 found = 1;
4487 }
4488
4489 if (!found) {
4490 free(update_refs.items[i].string);
4491 free(update_refs.items[i].util);
4492
4493 update_refs.nr--;
4494 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4495
4496 updated = 1;
4497 i--;
4498 }
4499 }
4500
4501 /*
4502 * For each todo_item, check if its ref is in the update_refs list.
4503 * If not, then add it as an un-updated ref.
4504 */
fa5103dd 4505 for (i = 0; i < todo_list->nr; i++) {
b3b1a21d
DS
4506 struct todo_item *item = &todo_list->items[i];
4507 const char *arg = todo_list->buf.buf + item->arg_offset;
4508 int j, found = 0;
4509
4510 if (item->command != TODO_UPDATE_REF)
4511 continue;
4512
4513 for (j = 0; !found && j < update_refs.nr; j++) {
4514 const char *ref = update_refs.items[j].string;
4515
4516 found = strlen(ref) == item->arg_len &&
4517 !strncmp(ref, arg, item->arg_len);
4518 }
4519
4520 if (!found) {
4521 struct string_list_item *inserted;
4522 struct strbuf argref = STRBUF_INIT;
4523
4524 strbuf_add(&argref, arg, item->arg_len);
4525 inserted = string_list_insert(&update_refs, argref.buf);
4526 inserted->util = init_update_ref_record(argref.buf);
4527 strbuf_release(&argref);
4528 updated = 1;
4529 }
4530 }
4531
4532 if (updated)
4533 write_update_refs_state(&update_refs);
4534 string_list_clear(&update_refs, 1);
4535}
4536
89fc0b53 4537static int do_update_ref(struct repository *r, const char *refname)
a97d7916 4538{
89fc0b53
DS
4539 struct string_list_item *item;
4540 struct string_list list = STRING_LIST_INIT_DUP;
4541
4542 if (sequencer_get_update_refs_state(r->gitdir, &list))
4543 return -1;
4544
4545 for_each_string_list_item(item, &list) {
4546 if (!strcmp(item->string, refname)) {
4547 struct update_ref_record *rec = item->util;
2e5c4758 4548 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
89fc0b53
DS
4549 return -1;
4550 break;
4551 }
4552 }
4553
4554 write_update_refs_state(&list);
4555 string_list_clear(&list, 1);
a97d7916
DS
4556 return 0;
4557}
4558
4611884e 4559static int do_update_refs(struct repository *r, int quiet)
89fc0b53
DS
4560{
4561 int res = 0;
4562 struct string_list_item *item;
4563 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4564 struct ref_store *refs = get_main_ref_store(r);
4611884e
DS
4565 struct strbuf update_msg = STRBUF_INIT;
4566 struct strbuf error_msg = STRBUF_INIT;
89fc0b53
DS
4567
4568 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4569 return res;
4570
4571 for_each_string_list_item(item, &refs_to_oids) {
4572 struct update_ref_record *rec = item->util;
4611884e 4573 int loop_res;
89fc0b53 4574
4611884e
DS
4575 loop_res = refs_update_ref(refs, "rewritten during rebase",
4576 item->string,
4577 &rec->after, &rec->before,
4578 0, UPDATE_REFS_MSG_ON_ERR);
4579 res |= loop_res;
4580
4581 if (quiet)
4582 continue;
4583
4584 if (loop_res)
4585 strbuf_addf(&error_msg, "\t%s\n", item->string);
4586 else
4587 strbuf_addf(&update_msg, "\t%s\n", item->string);
4588 }
4589
4590 if (!quiet &&
4591 (update_msg.len || error_msg.len)) {
4592 fprintf(stderr,
4593 _("Updated the following refs with %s:\n%s"),
4594 "--update-refs",
4595 update_msg.buf);
4596
4597 if (res)
4598 fprintf(stderr,
4599 _("Failed to update the following refs with %s:\n%s"),
4600 "--update-refs",
4601 error_msg.buf);
89fc0b53
DS
4602 }
4603
4604 string_list_clear(&refs_to_oids, 1);
4611884e
DS
4605 strbuf_release(&update_msg);
4606 strbuf_release(&error_msg);
89fc0b53
DS
4607 return res;
4608}
4609
6e98de72
JS
4610static int is_final_fixup(struct todo_list *todo_list)
4611{
4612 int i = todo_list->current;
4613
4614 if (!is_fixup(todo_list->items[i].command))
4615 return 0;
4616
4617 while (++i < todo_list->nr)
4618 if (is_fixup(todo_list->items[i].command))
4619 return 0;
4620 else if (!is_noop(todo_list->items[i].command))
4621 break;
4622 return 1;
4623}
4624
25cb8df9
JS
4625static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4626{
4627 int i;
4628
4629 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4630 if (!is_noop(todo_list->items[i].command))
4631 return todo_list->items[i].command;
4632
4633 return -1;
4634}
4635
35122dae
PS
4636static void create_autostash_internal(struct repository *r,
4637 const char *path,
4638 const char *refname)
0816f1df
DL
4639{
4640 struct strbuf buf = STRBUF_INIT;
4641 struct lock_file lock_file = LOCK_INIT;
4642 int fd;
4643
35122dae
PS
4644 if (path && refname)
4645 BUG("can only pass path or refname");
4646
0816f1df
DL
4647 fd = repo_hold_locked_index(r, &lock_file, 0);
4648 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4649 if (0 <= fd)
4650 repo_update_index_if_able(r, &lock_file);
4651 rollback_lock_file(&lock_file);
4652
4653 if (has_unstaged_changes(r, 1) ||
4654 has_uncommitted_changes(r, 1)) {
4655 struct child_process stash = CHILD_PROCESS_INIT;
6ae80861 4656 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
0816f1df
DL
4657 struct object_id oid;
4658
c972bf4c 4659 strvec_pushl(&stash.args,
f6d8942b 4660 "stash", "create", "autostash", NULL);
0816f1df
DL
4661 stash.git_cmd = 1;
4662 stash.no_stdin = 1;
4663 strbuf_reset(&buf);
4664 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4665 die(_("Cannot autostash"));
4666 strbuf_trim_trailing_newline(&buf);
4a93b899 4667 if (repo_get_oid(r, buf.buf, &oid))
0816f1df
DL
4668 die(_("Unexpected stash response: '%s'"),
4669 buf.buf);
4670 strbuf_reset(&buf);
4671 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4672
35122dae 4673 if (path) {
1a99fe80 4674 if (safe_create_leading_directories_const(the_repository, path))
35122dae
PS
4675 die(_("Could not create directory for '%s'"),
4676 path);
4677 write_file(path, "%s", oid_to_hex(&oid));
4678 } else {
4679 refs_update_ref(get_main_ref_store(r), "", refname,
7d70b29c 4680 &oid, null_oid(the_hash_algo), 0, UPDATE_REFS_DIE_ON_ERR);
35122dae
PS
4681 }
4682
0816f1df 4683 printf(_("Created autostash: %s\n"), buf.buf);
6ae80861 4684 if (reset_head(r, &ropts) < 0)
0816f1df 4685 die(_("could not reset --hard"));
9c5f3ee3
ÆAB
4686 discard_index(r->index);
4687 if (repo_read_index(r) < 0)
0816f1df
DL
4688 die(_("could not read index"));
4689 }
4690 strbuf_release(&buf);
4691}
4692
35122dae
PS
4693void create_autostash(struct repository *r, const char *path)
4694{
4695 create_autostash_internal(r, path, NULL);
4696}
4697
4698void create_autostash_ref(struct repository *r, const char *refname)
4699{
4700 create_autostash_internal(r, NULL, refname);
4701}
4702
804fe315 4703static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
796c7972 4704{
796c7972
JS
4705 struct child_process child = CHILD_PROCESS_INIT;
4706 int ret = 0;
4707
12b6e136
DL
4708 if (attempt_apply) {
4709 child.git_cmd = 1;
4710 child.no_stdout = 1;
4711 child.no_stderr = 1;
c972bf4c
JK
4712 strvec_push(&child.args, "stash");
4713 strvec_push(&child.args, "apply");
4714 strvec_push(&child.args, stash_oid);
12b6e136 4715 ret = run_command(&child);
796c7972 4716 }
796c7972 4717
12b6e136 4718 if (attempt_apply && !ret)
cdb866b3 4719 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
4720 else {
4721 struct child_process store = CHILD_PROCESS_INIT;
4722
4723 store.git_cmd = 1;
c972bf4c
JK
4724 strvec_push(&store.args, "stash");
4725 strvec_push(&store.args, "store");
4726 strvec_push(&store.args, "-m");
4727 strvec_push(&store.args, "autostash");
4728 strvec_push(&store.args, "-q");
4729 strvec_push(&store.args, stash_oid);
796c7972 4730 if (run_command(&store))
804fe315 4731 ret = error(_("cannot store %s"), stash_oid);
796c7972 4732 else
cdb866b3 4733 fprintf(stderr,
12b6e136 4734 _("%s\n"
cdb866b3
JS
4735 "Your changes are safe in the stash.\n"
4736 "You can run \"git stash pop\" or"
12b6e136
DL
4737 " \"git stash drop\" at any time.\n"),
4738 attempt_apply ?
4739 _("Applying autostash resulted in conflicts.") :
4740 _("Autostash exists; creating a new stash entry."));
796c7972
JS
4741 }
4742
796c7972
JS
4743 return ret;
4744}
4745
804fe315
DL
4746static int apply_save_autostash(const char *path, int attempt_apply)
4747{
4748 struct strbuf stash_oid = STRBUF_INIT;
4749 int ret = 0;
4750
4751 if (!read_oneliner(&stash_oid, path,
4752 READ_ONELINER_SKIP_IF_EMPTY)) {
4753 strbuf_release(&stash_oid);
4754 return 0;
4755 }
4756 strbuf_trim(&stash_oid);
4757
4758 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4759
0dd562e0 4760 unlink(path);
facca7f0 4761 strbuf_release(&stash_oid);
796c7972
JS
4762 return ret;
4763}
4764
12b6e136
DL
4765int save_autostash(const char *path)
4766{
4767 return apply_save_autostash(path, 0);
4768}
4769
4770int apply_autostash(const char *path)
4771{
4772 return apply_save_autostash(path, 1);
4773}
4774
804fe315
DL
4775int apply_autostash_oid(const char *stash_oid)
4776{
4777 return apply_save_autostash_oid(stash_oid, 1);
4778}
4779
35122dae
PS
4780static int apply_save_autostash_ref(struct repository *r, const char *refname,
4781 int attempt_apply)
4782{
4783 struct object_id stash_oid;
4784 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4785 int flag, ret;
4786
4787 if (!refs_ref_exists(get_main_ref_store(r), refname))
4788 return 0;
4789
4790 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4791 RESOLVE_REF_READING, &stash_oid, &flag))
4792 return -1;
4793 if (flag & REF_ISSYMREF)
4794 return error(_("autostash reference is a symref"));
4795
4796 oid_to_hex_r(stash_oid_hex, &stash_oid);
4797 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4798
4799 refs_delete_ref(get_main_ref_store(r), "", refname,
4800 &stash_oid, REF_NO_DEREF);
4801
4802 return ret;
4803}
4804
4805int save_autostash_ref(struct repository *r, const char *refname)
4806{
4807 return apply_save_autostash_ref(r, refname, 0);
4808}
4809
4810int apply_autostash_ref(struct repository *r, const char *refname)
4811{
4812 return apply_save_autostash_ref(r, refname, 1);
4813}
4814
fc4a6735 4815static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 4816 const char *onto_name, const struct object_id *onto,
f3e27a02 4817 const struct object_id *orig_head)
4df66c40 4818{
38c541ce
PW
4819 struct reset_head_opts ropts = {
4820 .oid = onto,
4821 .orig_head = orig_head,
4822 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4823 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4824 .head_msg = reflog_message(opts, "start", "checkout %s",
4825 onto_name),
d188a60d 4826 .default_reflog_action = sequencer_reflog_action(opts)
38c541ce
PW
4827 };
4828 if (reset_head(r, &ropts)) {
be1bb600 4829 apply_autostash(rebase_path_autostash());
4df66c40
AG
4830 sequencer_remove_state(opts);
4831 return error(_("could not detach HEAD"));
4832 }
4833
38c541ce 4834 return 0;
4df66c40
AG
4835}
4836
005af339 4837static int stopped_at_head(struct repository *r)
71f82465
JS
4838{
4839 struct object_id head;
4840 struct commit *commit;
4841 struct commit_message message;
4842
4a93b899 4843 if (repo_get_oid(r, "HEAD", &head) ||
005af339 4844 !(commit = lookup_commit(r, &head)) ||
4a93b899 4845 repo_parse_commit(r, commit) || get_message(commit, &message))
71f82465
JS
4846 fprintf(stderr, _("Stopped at HEAD\n"));
4847 else {
4848 fprintf(stderr, _("Stopped at %s\n"), message.label);
4849 free_message(commit, &message);
4850 }
4851 return 0;
4852
4853}
4854
dfa8bae5
PW
4855static int reread_todo_if_changed(struct repository *r,
4856 struct todo_list *todo_list,
4857 struct replay_opts *opts)
4858{
2b88fe06
PW
4859 int offset;
4860 struct strbuf buf = STRBUF_INIT;
dfa8bae5 4861
2b88fe06
PW
4862 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4863 return -1;
4864 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4865 if (buf.len != todo_list->buf.len - offset ||
4866 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
dfa8bae5
PW
4867 /* Reread the todo file if it has changed. */
4868 todo_list_release(todo_list);
4869 if (read_populate_todo(r, todo_list, opts))
4870 return -1; /* message was printed */
4871 /* `current` will be incremented on return */
4872 todo_list->current = -1;
4873 }
2b88fe06 4874 strbuf_release(&buf);
dfa8bae5
PW
4875
4876 return 0;
4877}
4878
cb5206ea
JS
4879static const char rescheduled_advice[] =
4880N_("Could not execute the todo command\n"
4881"\n"
4882" %.*s"
4883"\n"
4884"It has been rescheduled; To edit the command before continuing, please\n"
4885"edit the todo list first:\n"
4886"\n"
4887" git rebase --edit-todo\n"
4888" git rebase --continue\n");
4889
f2b5f41e
PW
4890static int pick_one_commit(struct repository *r,
4891 struct todo_list *todo_list,
4892 struct replay_opts *opts,
e032abd5 4893 int *check_todo, int* reschedule)
f2b5f41e
PW
4894{
4895 int res;
4896 struct todo_item *item = todo_list->items + todo_list->current;
4897 const char *arg = todo_item_get_arg(todo_list, item);
f2b5f41e
PW
4898
4899 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4900 check_todo);
4901 if (is_rebase_i(opts) && res < 0) {
4902 /* Reschedule */
e032abd5
PW
4903 *reschedule = 1;
4904 return -1;
f2b5f41e
PW
4905 }
4906 if (item->command == TODO_EDIT) {
4907 struct commit *commit = item->commit;
4908 if (!res) {
4909 if (!opts->verbose)
4910 term_clear_line();
4911 fprintf(stderr, _("Stopped at %s... %.*s\n"),
b995e781 4912 short_commit_name(r, commit), item->arg_len, arg);
f2b5f41e
PW
4913 }
4914 return error_with_patch(r, commit,
4915 arg, item->arg_len, opts, res, !res);
4916 }
4917 if (is_rebase_i(opts) && !res)
4918 record_in_rewritten(&item->commit->object.oid,
4919 peek_command(todo_list, 1));
4920 if (res && is_fixup(item->command)) {
4921 if (res == 1)
4922 intend_to_amend();
4923 return error_failed_squash(r, item->commit, opts,
4924 item->arg_len, arg);
4925 } else if (res && is_rebase_i(opts) && item->commit) {
4926 int to_amend = 0;
4927 struct object_id oid;
4928
4929 /*
4930 * If we are rewording and have either
4931 * fast-forwarded already, or are about to
4932 * create a new root commit, we want to amend,
4933 * otherwise we do not.
4934 */
4935 if (item->command == TODO_REWORD &&
4936 !repo_get_oid(r, "HEAD", &oid) &&
4937 (oideq(&item->commit->object.oid, &oid) ||
4938 (opts->have_squash_onto &&
4939 oideq(&opts->squash_onto, &oid))))
4940 to_amend = 1;
4941
4942 return res | error_with_patch(r, item->commit,
4943 arg, item->arg_len, opts,
4944 res, to_amend);
4945 }
4946 return res;
4947}
4948
f11c9580
NTND
4949static int pick_commits(struct repository *r,
4950 struct todo_list *todo_list,
4951 struct replay_opts *opts)
043a4492 4952{
a3152edc 4953 struct replay_ctx *ctx = opts->ctx;
9055e401 4954 int res = 0, reschedule = 0;
043a4492 4955
043a4492 4956 if (opts->allow_ff)
5633aa3a 4957 ASSERT(!(opts->signoff || opts->no_commit ||
39edfd5c 4958 opts->record_origin || should_edit(opts) ||
a3894aad
PW
4959 opts->committer_date_is_author_date ||
4960 opts->ignore_date));
f11c9580 4961 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4962 return -1;
043a4492 4963
36ac861a
PW
4964 unlink(rebase_path_message());
4965 unlink(rebase_path_stopped_sha());
4966 unlink(rebase_path_amend());
206a78d7 4967 unlink(rebase_path_patch());
36ac861a 4968
004fefa7
JS
4969 while (todo_list->current < todo_list->nr) {
4970 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 4971 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 4972 int check_todo = 0;
6ad656db 4973
203573b0 4974 if (save_todo(todo_list, opts, reschedule))
221675de 4975 return -1;
6e98de72 4976 if (is_rebase_i(opts)) {
ef80069a
JS
4977 if (item->command != TODO_COMMENT) {
4978 FILE *f = fopen(rebase_path_msgnum(), "w");
4979
4980 todo_list->done_nr++;
4981
4982 if (f) {
4983 fprintf(f, "%d\n", todo_list->done_nr);
4984 fclose(f);
4985 }
899b49c4 4986 if (!opts->quiet)
4d55d63b 4987 fprintf(stderr, _("Rebasing (%d/%d)%s"),
899b49c4
EN
4988 todo_list->done_nr,
4989 todo_list->total_nr,
4990 opts->verbose ? "\n" : "\r");
ef80069a 4991 }
6e98de72 4992 unlink(rebase_path_author_script());
34e7771b 4993 unlink(git_path_merge_head(r));
fd7c6ffa
PS
4994 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4995 NULL, REF_NO_DEREF);
bb02e95f
PS
4996 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4997 NULL, REF_NO_DEREF);
71f82465 4998
d7d90885
SG
4999 if (item->command == TODO_BREAK) {
5000 if (!opts->verbose)
5001 term_clear_line();
005af339 5002 return stopped_at_head(r);
d7d90885 5003 }
6e98de72 5004 }
53f67466
PW
5005 strbuf_reset(&ctx->message);
5006 ctx->have_message = 0;
6e98de72 5007 if (item->command <= TODO_SQUASH) {
e032abd5
PW
5008 res = pick_one_commit(r, todo_list, opts, &check_todo,
5009 &reschedule);
f2b5f41e
PW
5010 if (!res && item->command == TODO_EDIT)
5011 return 0;
311af526 5012 } else if (item->command == TODO_EXEC) {
6ad656db 5013 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
5014 int saved = *end_of_arg;
5015
d7d90885
SG
5016 if (!opts->verbose)
5017 term_clear_line();
311af526 5018 *end_of_arg = '\0';
4bdd6b7b 5019 res = do_exec(r, arg, opts->quiet);
311af526 5020 *end_of_arg = saved;
54fd3243 5021
d421afa0
JS
5022 if (res) {
5023 if (opts->reschedule_failed_exec)
5024 reschedule = 1;
54fd3243 5025 }
a47ba3c7 5026 check_todo = 1;
9055e401 5027 } else if (item->command == TODO_LABEL) {
6ad656db 5028 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
5029 reschedule = 1;
5030 } else if (item->command == TODO_RESET) {
6ad656db 5031 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 5032 reschedule = 1;
4c68e7dd 5033 } else if (item->command == TODO_MERGE) {
2be6b6f4
PW
5034 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5035 item->flags, &check_todo, opts)) < 0)
4c68e7dd 5036 reschedule = 1;
537e7d61
JS
5037 else if (item->commit)
5038 record_in_rewritten(&item->commit->object.oid,
5039 peek_command(todo_list, 1));
5040 if (res > 0)
4c68e7dd 5041 /* failed with merge conflicts */
f11c9580 5042 return error_with_patch(r, item->commit,
6ad656db
AG
5043 arg, item->arg_len,
5044 opts, res, 0);
a97d7916
DS
5045 } else if (item->command == TODO_UPDATE_REF) {
5046 struct strbuf ref = STRBUF_INIT;
5047 strbuf_add(&ref, arg, item->arg_len);
5048 if ((res = do_update_ref(r, ref.buf)))
5049 reschedule = 1;
5050 strbuf_release(&ref);
56dc3ab0 5051 } else if (!is_noop(item->command))
25c43667
JS
5052 return error(_("unknown command %d"), item->command);
5053
9055e401
JS
5054 if (reschedule) {
5055 advise(_(rescheduled_advice),
5056 get_item_line_length(todo_list,
5057 todo_list->current),
5058 get_item_line(todo_list, todo_list->current));
203573b0 5059 if (save_todo(todo_list, opts, reschedule))
9055e401 5060 return -1;
4c68e7dd 5061 if (item->commit)
e032abd5 5062 write_rebase_head(&item->commit->object.oid);
dfa8bae5
PW
5063 } else if (is_rebase_i(opts) && check_todo && !res &&
5064 reread_todo_if_changed(r, todo_list, opts)) {
5065 return -1;
9055e401
JS
5066 }
5067
043a4492
RR
5068 if (res)
5069 return res;
f2b5f41e
PW
5070
5071 todo_list->current++;
043a4492
RR
5072 }
5073
56dc3ab0 5074 if (is_rebase_i(opts)) {
4b83ce9f 5075 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 5076 struct stat st;
556907f1 5077
4b83ce9f
JS
5078 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5079 starts_with(head_ref.buf, "refs/")) {
96e832a5 5080 const char *msg;
092bbcdf 5081 struct object_id head, orig;
4b83ce9f
JS
5082 int res;
5083
4a93b899 5084 if (repo_get_oid(r, "HEAD", &head)) {
4b83ce9f
JS
5085 res = error(_("cannot read HEAD"));
5086cleanup_head_ref:
5087 strbuf_release(&head_ref);
5088 strbuf_release(&buf);
5089 return res;
5090 }
5091 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 5092 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
5093 res = error(_("could not read orig-head"));
5094 goto cleanup_head_ref;
5095 }
4ab867b8 5096 strbuf_reset(&buf);
4b83ce9f
JS
5097 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5098 res = error(_("could not read 'onto'"));
5099 goto cleanup_head_ref;
5100 }
96e832a5
JS
5101 msg = reflog_message(opts, "finish", "%s onto %s",
5102 head_ref.buf, buf.buf);
2e5c4758
PS
5103 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5104 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
5105 res = error(_("could not update %s"),
5106 head_ref.buf);
5107 goto cleanup_head_ref;
5108 }
96e832a5 5109 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 5110 head_ref.buf);
4beb7a3b 5111 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
5112 res = error(_("could not update HEAD to %s"),
5113 head_ref.buf);
5114 goto cleanup_head_ref;
5115 }
5116 strbuf_reset(&buf);
5117 }
5118
556907f1
JS
5119 if (opts->verbose) {
5120 struct rev_info log_tree_opt;
5121 struct object_id orig, head;
5122
5123 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 5124 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
5125 log_tree_opt.diff = 1;
5126 log_tree_opt.diffopt.output_format =
5127 DIFF_FORMAT_DIFFSTAT;
5128 log_tree_opt.disable_stdin = 1;
5129
5130 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4a93b899
ÆAB
5131 !repo_get_oid(r, buf.buf, &orig) &&
5132 !repo_get_oid(r, "HEAD", &head)) {
66f414f8
BW
5133 diff_tree_oid(&orig, &head, "",
5134 &log_tree_opt.diffopt);
556907f1
JS
5135 log_tree_diff_flush(&log_tree_opt);
5136 }
2108fe4a 5137 release_revisions(&log_tree_opt);
556907f1 5138 }
25cb8df9
JS
5139 flush_rewritten_pending();
5140 if (!stat(rebase_path_rewritten_list(), &st) &&
5141 st.st_size > 0) {
5142 struct child_process child = CHILD_PROCESS_INIT;
96af564d 5143 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
25cb8df9
JS
5144
5145 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5146 child.git_cmd = 1;
c972bf4c
JK
5147 strvec_push(&child.args, "notes");
5148 strvec_push(&child.args, "copy");
5149 strvec_push(&child.args, "--for-rewrite=rebase");
25cb8df9
JS
5150 /* we don't care if this copying failed */
5151 run_command(&child);
79516045 5152
96af564d
ES
5153 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5154 strvec_push(&hook_opt.args, "rebase");
169c9797 5155 run_hooks_opt(r, "post-rewrite", &hook_opt);
25cb8df9 5156 }
be1bb600 5157 apply_autostash(rebase_path_autostash());
25cb8df9 5158
d7d90885
SG
5159 if (!opts->quiet) {
5160 if (!opts->verbose)
5161 term_clear_line();
899b49c4 5162 fprintf(stderr,
4d55d63b 5163 _("Successfully rebased and updated %s.\n"),
899b49c4 5164 head_ref.buf);
d7d90885 5165 }
5da4966f 5166
556907f1 5167 strbuf_release(&buf);
4b83ce9f 5168 strbuf_release(&head_ref);
89fc0b53 5169
4611884e 5170 if (do_update_refs(r, opts->quiet))
89fc0b53 5171 return -1;
56dc3ab0
JS
5172 }
5173
043a4492
RR
5174 /*
5175 * Sequence of picks finished successfully; cleanup by
5176 * removing the .git/sequencer directory
5177 */
2863584f 5178 return sequencer_remove_state(opts);
043a4492
RR
5179}
5180
39edfd5c 5181static int continue_single_pick(struct repository *r, struct replay_opts *opts)
043a4492 5182{
0e906739 5183 struct child_process cmd = CHILD_PROCESS_INIT;
043a4492 5184
c8e4159e 5185 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 5186 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 5187 return error(_("no cherry-pick or revert in progress"));
39edfd5c 5188
0e906739
RS
5189 cmd.git_cmd = 1;
5190 strvec_push(&cmd.args, "commit");
39edfd5c
EN
5191
5192 /*
5193 * continue_single_pick() handles the case of recovering from a
5194 * conflict. should_edit() doesn't handle that case; for a conflict,
5195 * we want to edit if the user asked for it, or if they didn't specify
5196 * and stdin is a tty.
5197 */
5198 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5199 /*
5200 * Include --cleanup=strip as well because we don't want the
5201 * "# Conflicts:" messages.
5202 */
0e906739 5203 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
39edfd5c 5204
0e906739 5205 return run_command(&cmd);
043a4492
RR
5206}
5207
f11c9580
NTND
5208static int commit_staged_changes(struct repository *r,
5209 struct replay_opts *opts,
15ef6931 5210 struct todo_list *todo_list)
9d93ccd1 5211{
497a01a2 5212 struct replay_ctx *ctx = opts->ctx;
789b3eff 5213 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 5214 unsigned int final_fixup = 0, is_clean;
1e5c1601 5215 struct strbuf rev = STRBUF_INIT;
5dbaec62 5216 const char *reflog_action = reflog_message(opts, "continue", NULL);
1e5c1601 5217 int ret;
9d93ccd1 5218
1e5c1601
PS
5219 if (has_unstaged_changes(r, 1)) {
5220 ret = error(_("cannot rebase: You have unstaged changes."));
5221 goto out;
5222 }
52632209 5223
f11c9580 5224 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1 5225
405509cb
PW
5226 if (!is_clean && !file_exists(rebase_path_message())) {
5227 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1e5c1601
PS
5228 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
5229 goto out;
405509cb 5230 }
1e5c1601 5231
9d93ccd1 5232 if (file_exists(rebase_path_amend())) {
092bbcdf 5233 struct object_id head, to_amend;
9d93ccd1 5234
1e5c1601
PS
5235 if (repo_get_oid(r, "HEAD", &head)) {
5236 ret = error(_("cannot amend non-existing commit"));
5237 goto out;
5238 }
5239
5240 if (!read_oneliner(&rev, rebase_path_amend(), 0)) {
5241 ret = error(_("invalid file: '%s'"), rebase_path_amend());
5242 goto out;
5243 }
5244
5245 if (get_oid_hex(rev.buf, &to_amend)) {
5246 ret = error(_("invalid contents: '%s'"),
5247 rebase_path_amend());
5248 goto out;
5249 }
5250 if (!is_clean && !oideq(&head, &to_amend)) {
5251 ret = error(_("\nYou have uncommitted changes in your "
5252 "working tree. Please, commit them\n"
5253 "first and then run 'git rebase "
5254 "--continue' again."));
5255 goto out;
5256 }
15ef6931
JS
5257 /*
5258 * When skipping a failed fixup/squash, we need to edit the
5259 * commit message, the current fixup list and count, and if it
5260 * was the last fixup/squash in the chain, we need to clean up
5261 * the commit message and if there was a squash, let the user
5262 * edit it.
5263 */
497a01a2 5264 if (!is_clean || !ctx->current_fixup_count)
10d2f354 5265 ; /* this is not the final fixup */
87ae8a1a 5266 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
5267 !file_exists(rebase_path_stopped_sha())) {
5268 /* was a final fixup or squash done manually? */
5269 if (!is_fixup(peek_command(todo_list, 0))) {
5270 unlink(rebase_path_fixup_msg());
5271 unlink(rebase_path_squash_msg());
5272 unlink(rebase_path_current_fixups());
497a01a2
PW
5273 strbuf_reset(&ctx->current_fixups);
5274 ctx->current_fixup_count = 0;
10d2f354
JS
5275 }
5276 } else {
5277 /* we are in a fixup/squash chain */
497a01a2
PW
5278 const char *p = ctx->current_fixups.buf;
5279 int len = ctx->current_fixups.len;
15ef6931 5280
497a01a2 5281 ctx->current_fixup_count--;
15ef6931
JS
5282 if (!len)
5283 BUG("Incorrect current_fixups:\n%s", p);
5284 while (len && p[len - 1] != '\n')
5285 len--;
497a01a2 5286 strbuf_setlen(&ctx->current_fixups, len);
15ef6931 5287 if (write_message(p, len, rebase_path_current_fixups(),
1e5c1601
PS
5288 0) < 0) {
5289 ret = error(_("could not write file: '%s'"),
5290 rebase_path_current_fixups());
5291 goto out;
5292 }
15ef6931
JS
5293
5294 /*
5295 * If a fixup/squash in a fixup/squash chain failed, the
5296 * commit message is already correct, no need to commit
5297 * it again.
5298 *
5299 * Only if it is the final command in the fixup/squash
5300 * chain, and only if the chain is longer than a single
5301 * fixup/squash command (which was just skipped), do we
5302 * actually need to re-commit with a cleaned up commit
5303 * message.
5304 */
497a01a2 5305 if (ctx->current_fixup_count > 0 &&
15ef6931
JS
5306 !is_fixup(peek_command(todo_list, 0))) {
5307 final_fixup = 1;
5308 /*
5309 * If there was not a single "squash" in the
5310 * chain, we only need to clean up the commit
5311 * message, no need to bother the user with
5312 * opening the commit message in the editor.
5313 */
5314 if (!starts_with(p, "squash ") &&
5315 !strstr(p, "\nsquash "))
5316 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5317 } else if (is_fixup(peek_command(todo_list, 0))) {
5318 /*
5319 * We need to update the squash message to skip
5320 * the latest commit message.
5321 */
5322 struct commit *commit;
6ce7afe1 5323 const char *msg;
15ef6931 5324 const char *path = rebase_path_squash_msg();
b3757442 5325 const char *encoding = get_commit_output_encoding();
15ef6931 5326
1e5c1601
PS
5327 if (parse_head(r, &commit)) {
5328 ret = error(_("could not parse HEAD"));
5329 goto out;
5330 }
6ce7afe1
PW
5331
5332 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5333 if (!p) {
1e5c1601 5334 ret = error(_("could not parse commit %s"),
6ce7afe1
PW
5335 oid_to_hex(&commit->object.oid));
5336 goto unuse_commit_buffer;
5337 }
5338 find_commit_subject(p, &msg);
5339 if (write_message(msg, strlen(msg), path, 0)) {
1e5c1601 5340 ret = error(_("could not write file: "
15ef6931 5341 "'%s'"), path);
6ce7afe1 5342 goto unuse_commit_buffer;
15ef6931 5343 }
1e5c1601
PS
5344
5345 ret = 0;
5346
6ce7afe1
PW
5347 unuse_commit_buffer:
5348 repo_unuse_commit_buffer(r, commit, p);
1e5c1601
PS
5349 if (ret)
5350 goto out;
15ef6931
JS
5351 }
5352 }
9d93ccd1 5353
789b3eff 5354 flags |= AMEND_MSG;
9d93ccd1
JS
5355 }
5356
15ef6931 5357 if (is_clean) {
c8e4159e
HWN
5358 if (refs_ref_exists(get_main_ref_store(r),
5359 "CHERRY_PICK_HEAD") &&
5360 refs_delete_ref(get_main_ref_store(r), "",
1e5c1601
PS
5361 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF)) {
5362 ret = error(_("could not remove CHERRY_PICK_HEAD"));
5363 goto out;
5364 }
5365
5366 if (unlink(git_path_merge_msg(r)) && errno != ENOENT) {
5367 ret = error_errno(_("could not remove '%s'"),
5368 git_path_merge_msg(r));
5369 goto out;
5370 }
5371
5372 if (!final_fixup) {
5373 ret = 0;
5374 goto out;
5375 }
15ef6931
JS
5376 }
5377
20f4b044 5378 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5dbaec62 5379 reflog_action, opts, flags)) {
1e5c1601
PS
5380 ret = error(_("could not commit staged changes."));
5381 goto out;
5382 }
5383
9d93ccd1 5384 unlink(rebase_path_amend());
34e7771b 5385 unlink(git_path_merge_head(r));
fd7c6ffa
PS
5386 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5387 NULL, REF_NO_DEREF);
15ef6931
JS
5388 if (final_fixup) {
5389 unlink(rebase_path_fixup_msg());
5390 unlink(rebase_path_squash_msg());
5391 }
497a01a2 5392 if (ctx->current_fixup_count > 0) {
15ef6931
JS
5393 /*
5394 * Whether final fixup or not, we just cleaned up the commit
5395 * message...
5396 */
5397 unlink(rebase_path_current_fixups());
497a01a2
PW
5398 strbuf_reset(&ctx->current_fixups);
5399 ctx->current_fixup_count = 0;
15ef6931 5400 }
1e5c1601
PS
5401
5402 ret = 0;
5403
5404out:
5405 strbuf_release(&rev);
5406 return ret;
9d93ccd1
JS
5407}
5408
f11c9580 5409int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 5410{
004fefa7
JS
5411 struct todo_list todo_list = TODO_LIST_INIT;
5412 int res;
043a4492 5413
f11c9580 5414 if (read_and_refresh_cache(r, opts))
2863584f
JS
5415 return -1;
5416
15ef6931
JS
5417 if (read_populate_opts(opts))
5418 return -1;
9d93ccd1 5419 if (is_rebase_i(opts)) {
005af339 5420 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 5421 goto release_todo_list;
5a5445d8
AG
5422
5423 if (file_exists(rebase_path_dropped())) {
0c26738a
PW
5424 if ((res = todo_list_check_against_backup(r, opts,
5425 &todo_list)))
5a5445d8
AG
5426 goto release_todo_list;
5427
5428 unlink(rebase_path_dropped());
5429 }
5430
f6b9413b
AG
5431 if (commit_staged_changes(r, opts, &todo_list)) {
5432 res = -1;
5433 goto release_todo_list;
5434 }
4258a6da 5435 } else if (!file_exists(get_todo_path(opts)))
39edfd5c 5436 return continue_single_pick(r, opts);
005af339 5437 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 5438 goto release_todo_list;
043a4492 5439
4258a6da
JS
5440 if (!is_rebase_i(opts)) {
5441 /* Verify that the conflict has been resolved */
c8e4159e
HWN
5442 if (refs_ref_exists(get_main_ref_store(r),
5443 "CHERRY_PICK_HEAD") ||
b8825ef2 5444 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
39edfd5c 5445 res = continue_single_pick(r, opts);
4258a6da
JS
5446 if (res)
5447 goto release_todo_list;
5448 }
ffc00a48 5449 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 5450 res = error_dirty_index(r, opts);
004fefa7 5451 goto release_todo_list;
4258a6da
JS
5452 }
5453 todo_list.current++;
ca98c6d4
JS
5454 } else if (file_exists(rebase_path_stopped_sha())) {
5455 struct strbuf buf = STRBUF_INIT;
5456 struct object_id oid;
5457
3442c3d1
DL
5458 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5459 READ_ONELINER_SKIP_IF_EMPTY) &&
0512eabd 5460 !get_oid_hex(buf.buf, &oid))
ca98c6d4
JS
5461 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5462 strbuf_release(&buf);
043a4492 5463 }
4258a6da 5464
f11c9580 5465 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
5466release_todo_list:
5467 todo_list_release(&todo_list);
5468 return res;
043a4492
RR
5469}
5470
f11c9580
NTND
5471static int single_pick(struct repository *r,
5472 struct commit *cmit,
5473 struct replay_opts *opts)
043a4492 5474{
a47ba3c7 5475 int check_todo;
ae70e34f
CM
5476 struct todo_item item;
5477
5478 item.command = opts->action == REPLAY_PICK ?
5479 TODO_PICK : TODO_REVERT;
5480 item.commit = cmit;
a47ba3c7 5481
ae70e34f 5482 return do_pick_commit(r, &item, opts, 0, &check_todo);
043a4492
RR
5483}
5484
f11c9580
NTND
5485int sequencer_pick_revisions(struct repository *r,
5486 struct replay_opts *opts)
043a4492 5487{
004fefa7 5488 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 5489 struct object_id oid;
004fefa7 5490 int i, res;
043a4492 5491
2863584f 5492 assert(opts->revs);
2f07d228
PS
5493 if (read_and_refresh_cache(r, opts)) {
5494 res = -1;
5495 goto out;
5496 }
043a4492 5497
21246dbb 5498 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 5499 struct object_id oid;
21246dbb
MV
5500 const char *name = opts->revs->pending.objects[i].name;
5501
5502 /* This happens when using --stdin. */
5503 if (!strlen(name))
5504 continue;
5505
4a93b899 5506 if (!repo_get_oid(r, name, &oid)) {
f11c9580
NTND
5507 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5508 enum object_type type = oid_object_info(r,
0df8e965 5509 &oid,
abef9020 5510 NULL);
2f07d228
PS
5511 res = error(_("%s: can't cherry-pick a %s"),
5512 name, type_name(type));
5513 goto out;
7c0b0d8d 5514 }
2f07d228
PS
5515 } else {
5516 res = error(_("%s: bad revision"), name);
5517 goto out;
5518 }
21246dbb
MV
5519 }
5520
043a4492
RR
5521 /*
5522 * If we were called as "git cherry-pick <commit>", just
5523 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5524 * REVERT_HEAD, and don't touch the sequencer state.
5525 * This means it is possible to cherry-pick in the middle
5526 * of a cherry-pick sequence.
5527 */
5528 if (opts->revs->cmdline.nr == 1 &&
5529 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5530 opts->revs->no_walk &&
5531 !opts->revs->cmdline.rev->flags) {
5532 struct commit *cmit;
2f07d228
PS
5533
5534 if (prepare_revision_walk(opts->revs)) {
5535 res = error(_("revision walk setup failed"));
5536 goto out;
5537 }
5538
043a4492 5539 cmit = get_revision(opts->revs);
2f07d228
PS
5540 if (!cmit) {
5541 res = error(_("empty commit set passed"));
5542 goto out;
5543 }
5544
c5e358d0
JK
5545 if (get_revision(opts->revs))
5546 BUG("unexpected extra commit from walk");
2f07d228
PS
5547
5548 res = single_pick(r, cmit, opts);
5549 goto out;
043a4492
RR
5550 }
5551
5552 /*
5553 * Start a new cherry-pick/ revert sequence; but
5554 * first, make sure that an existing one isn't in
5555 * progress
5556 */
5557
34b0528b 5558 if (walk_revs_populate_todo(&todo_list, opts) ||
2f07d228
PS
5559 create_seq_dir(r) < 0) {
5560 res = -1;
5561 goto out;
5562 }
5563
5564 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT)) {
5565 res = error(_("can't revert as initial commit"));
5566 goto out;
5567 }
5568
5569 if (save_head(oid_to_hex(&oid))) {
5570 res = -1;
5571 goto out;
5572 }
5573
5574 if (save_opts(opts)) {
5575 res = -1;
5576 goto out;
5577 }
5578
1e41229d 5579 update_abort_safety_file();
f11c9580 5580 res = pick_commits(r, &todo_list, opts);
2f07d228
PS
5581
5582out:
004fefa7
JS
5583 todo_list_release(&todo_list);
5584 return res;
043a4492 5585}
5ed75e2a 5586
66e83d9b 5587void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 5588{
bab4d109 5589 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 5590 struct strbuf sob = STRBUF_INIT;
bab4d109 5591 int has_footer;
5ed75e2a
MV
5592
5593 strbuf_addstr(&sob, sign_off_header);
39ab4d09 5594 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 5595 strbuf_addch(&sob, '\n');
bab4d109 5596
44dc738a
JT
5597 if (!ignore_footer)
5598 strbuf_complete_line(msgbuf);
5599
bab4d109
BC
5600 /*
5601 * If the whole message buffer is equal to the sob, pretend that we
5602 * found a conforming footer with a matching sob
5603 */
5604 if (msgbuf->len - ignore_footer == sob.len &&
5605 !strncmp(msgbuf->buf, sob.buf, sob.len))
5606 has_footer = 3;
5607 else
5608 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5609
33f2f9ab
BC
5610 if (!has_footer) {
5611 const char *append_newlines = NULL;
5612 size_t len = msgbuf->len - ignore_footer;
5613
8c613fd5
BC
5614 if (!len) {
5615 /*
5616 * The buffer is completely empty. Leave foom for
5617 * the title and body to be filled in by the user.
5618 */
33f2f9ab 5619 append_newlines = "\n\n";
8c613fd5
BC
5620 } else if (len == 1) {
5621 /*
5622 * Buffer contains a single newline. Add another
5623 * so that we leave room for the title and body.
5624 */
5625 append_newlines = "\n";
5626 } else if (msgbuf->buf[len - 2] != '\n') {
5627 /*
5628 * Buffer ends with a single newline. Add another
5629 * so that there is an empty line between the message
5630 * body and the sob.
5631 */
33f2f9ab 5632 append_newlines = "\n";
8c613fd5 5633 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
5634
5635 if (append_newlines)
5636 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5637 append_newlines, strlen(append_newlines));
5ed75e2a 5638 }
bab4d109
BC
5639
5640 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5641 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5642 sob.buf, sob.len);
5643
5ed75e2a
MV
5644 strbuf_release(&sob);
5645}
62db5247 5646
1644c73c
JS
5647struct labels_entry {
5648 struct hashmap_entry entry;
5649 char label[FLEX_ARRAY];
5650};
5651
5cf88fd8 5652static int labels_cmp(const void *fndata UNUSED,
02c3c59e 5653 const struct hashmap_entry *eptr,
939af16e 5654 const struct hashmap_entry *entry_or_key, const void *key)
1644c73c 5655{
939af16e
EW
5656 const struct labels_entry *a, *b;
5657
5658 a = container_of(eptr, const struct labels_entry, entry);
5659 b = container_of(entry_or_key, const struct labels_entry, entry);
5660
1644c73c
JS
5661 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5662}
5663
5664struct string_entry {
5665 struct oidmap_entry entry;
5666 char string[FLEX_ARRAY];
5667};
5668
5669struct label_state {
5670 struct oidmap commit2label;
5671 struct hashmap labels;
5672 struct strbuf buf;
ac300bda 5673 int max_label_length;
1644c73c
JS
5674};
5675
5676static const char *label_oid(struct object_id *oid, const char *label,
5677 struct label_state *state)
5678{
5679 struct labels_entry *labels_entry;
5680 struct string_entry *string_entry;
5681 struct object_id dummy;
1644c73c
JS
5682 int i;
5683
5684 string_entry = oidmap_get(&state->commit2label, oid);
5685 if (string_entry)
5686 return string_entry->string;
5687
5688 /*
5689 * For "uninteresting" commits, i.e. commits that are not to be
5690 * rebased, and which can therefore not be labeled, we use a unique
5691 * abbreviation of the commit name. This is slightly more complicated
c7c33f50 5692 * than calling repo_find_unique_abbrev() because we also need to make
1644c73c
JS
5693 * sure that the abbreviation does not conflict with any other
5694 * label.
5695 *
5696 * We disallow "interesting" commits to be labeled by a string that
5697 * is a valid full-length hash, to ensure that we always can find an
5698 * abbreviation for any uninteresting commit's names that does not
5699 * clash with any other label.
5700 */
867bc1d2 5701 strbuf_reset(&state->buf);
1644c73c
JS
5702 if (!label) {
5703 char *p;
5704
4439c7a3 5705 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
1644c73c
JS
5706 label = p = state->buf.buf;
5707
d850b7a5
ÆAB
5708 repo_find_unique_abbrev_r(the_repository, p, oid,
5709 default_abbrev);
1644c73c
JS
5710
5711 /*
5712 * We may need to extend the abbreviated hash so that there is
5713 * no conflicting label.
5714 */
5715 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5716 size_t i = strlen(p) + 1;
5717
5718 oid_to_hex_r(p, oid);
4439c7a3 5719 for (; i < the_hash_algo->hexsz; i++) {
1644c73c
JS
5720 char save = p[i];
5721 p[i] = '\0';
5722 if (!hashmap_get_from_hash(&state->labels,
5723 strihash(p), p))
5724 break;
5725 p[i] = save;
5726 }
5727 }
867bc1d2 5728 } else {
1644c73c 5729 struct strbuf *buf = &state->buf;
7481d2bf 5730 int label_is_utf8 = 1; /* start with this assumption */
ac300bda 5731 size_t max_len = buf->len + state->max_label_length;
1644c73c 5732
1644c73c 5733 /*
cd552227
MR
5734 * Sanitize labels by replacing non-alpha-numeric characters
5735 * (including white-space ones) by dashes, as they might be
5736 * illegal in file names (and hence in ref names).
5737 *
5738 * Note that we retain non-ASCII UTF-8 characters (identified
5739 * via the most significant bit). They should be all acceptable
7481d2bf
MRP
5740 * in file names.
5741 *
5742 * As we will use the labels as names of (loose) refs, it is
5743 * vital that the name not be longer than the maximum component
5744 * size of the file system (`NAME_MAX`). We are careful to
5745 * truncate the label accordingly, allowing for the `.lock`
5746 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5747 * truncating in the middle of a character).
1644c73c 5748 */
7481d2bf
MRP
5749 for (; *label && buf->len + 1 < max_len; label++)
5750 if (isalnum(*label) ||
5751 (!label_is_utf8 && (*label & 0x80)))
cd552227 5752 strbuf_addch(buf, *label);
7481d2bf
MRP
5753 else if (*label & 0x80) {
5754 const char *p = label;
5755
5756 utf8_width(&p, NULL);
5757 if (p) {
5758 if (buf->len + (p - label) > max_len)
5759 break;
5760 strbuf_add(buf, label, p - label);
5761 label = p - 1;
5762 } else {
5763 label_is_utf8 = 0;
5764 strbuf_addch(buf, *label);
5765 }
cd552227 5766 /* avoid leading dash and double-dashes */
7481d2bf 5767 } else if (buf->len && buf->buf[buf->len - 1] != '-')
cd552227
MR
5768 strbuf_addch(buf, '-');
5769 if (!buf->len) {
5770 strbuf_addstr(buf, "rev-");
5771 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5772 }
867bc1d2 5773 label = buf->buf;
1644c73c 5774
867bc1d2
JS
5775 if ((buf->len == the_hash_algo->hexsz &&
5776 !get_oid_hex(label, &dummy)) ||
5777 (buf->len == 1 && *label == '#') ||
5778 hashmap_get_from_hash(&state->labels,
5779 strihash(label), label)) {
5780 /*
5781 * If the label already exists, or if the label is a
5782 * valid full OID, or the label is a '#' (which we use
5783 * as a separator between merge heads and oneline), we
5784 * append a dash and a number to make it unique.
5785 */
5786 size_t len = buf->len;
1644c73c 5787
867bc1d2
JS
5788 for (i = 2; ; i++) {
5789 strbuf_setlen(buf, len);
5790 strbuf_addf(buf, "-%d", i);
5791 if (!hashmap_get_from_hash(&state->labels,
5792 strihash(buf->buf),
5793 buf->buf))
5794 break;
5795 }
1644c73c 5796
867bc1d2
JS
5797 label = buf->buf;
5798 }
1644c73c
JS
5799 }
5800
5801 FLEX_ALLOC_STR(labels_entry, label, label);
d22245a2 5802 hashmap_entry_init(&labels_entry->entry, strihash(label));
b94e5c1d 5803 hashmap_add(&state->labels, &labels_entry->entry);
1644c73c
JS
5804
5805 FLEX_ALLOC_STR(string_entry, string, label);
5806 oidcpy(&string_entry->entry.oid, oid);
5807 oidmap_put(&state->commit2label, string_entry);
5808
5809 return string_entry->string;
5810}
5811
5812static int make_script_with_merges(struct pretty_print_context *pp,
d358fc28 5813 struct rev_info *revs, struct strbuf *out,
1644c73c
JS
5814 unsigned flags)
5815{
b9cbd295 5816 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 5817 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
e1fac531 5818 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
767a4ca6 5819 int skipped_commit = 0;
1644c73c 5820 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
43689212 5821 struct strbuf label_from_message = STRBUF_INIT;
1644c73c
JS
5822 struct commit_list *commits = NULL, **tail = &commits, *iter;
5823 struct commit_list *tips = NULL, **tips_tail = &tips;
5824 struct commit *commit;
5825 struct oidmap commit2todo = OIDMAP_INIT;
5826 struct string_entry *entry;
5827 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5828 shown = OIDSET_INIT;
ac300bda
JS
5829 struct label_state state =
5830 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
1644c73c
JS
5831
5832 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5833 const char *cmd_pick = abbr ? "p" : "pick",
5834 *cmd_label = abbr ? "l" : "label",
5835 *cmd_reset = abbr ? "t" : "reset",
5836 *cmd_merge = abbr ? "m" : "merge";
5837
ac300bda
JS
5838 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5839
1644c73c
JS
5840 oidmap_init(&commit2todo, 0);
5841 oidmap_init(&state.commit2label, 0);
939af16e 5842 hashmap_init(&state.labels, labels_cmp, NULL, 0);
1644c73c 5843 strbuf_init(&state.buf, 32);
43689212 5844 load_branch_decorations();
1644c73c
JS
5845
5846 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
e02058a7 5847 struct labels_entry *onto_label_entry;
1644c73c
JS
5848 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5849 FLEX_ALLOC_STR(entry, string, "onto");
5850 oidcpy(&entry->entry.oid, oid);
5851 oidmap_put(&state.commit2label, entry);
e02058a7
ĐTCD
5852
5853 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5854 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5855 hashmap_add(&state.labels, &onto_label_entry->entry);
1644c73c
JS
5856 }
5857
5858 /*
5859 * First phase:
5860 * - get onelines for all commits
5861 * - gather all branch tips (i.e. 2nd or later parents of merges)
5862 * - label all branch tips
5863 */
5864 while ((commit = get_revision(revs))) {
5865 struct commit_list *to_merge;
1644c73c
JS
5866 const char *p1, *p2;
5867 struct object_id *oid;
5868 int is_empty;
5869
5870 tail = &commit_list_insert(commit, tail)->next;
5871 oidset_insert(&interesting, &commit->object.oid);
5872
5873 is_empty = is_original_commit_empty(commit);
767a4ca6
JS
5874 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5875 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5876 warning(_("skipped previously applied commit %s"),
cb646ffb 5877 short_commit_name(the_repository, commit));
767a4ca6 5878 skipped_commit = 1;
1644c73c 5879 continue;
767a4ca6 5880 }
b9cbd295
EN
5881 if (is_empty && !keep_empty)
5882 continue;
1644c73c
JS
5883
5884 strbuf_reset(&oneline);
5885 pretty_print_commit(pp, commit, &oneline);
5886
5887 to_merge = commit->parents ? commit->parents->next : NULL;
5888 if (!to_merge) {
5889 /* non-merge commit: easy case */
5890 strbuf_reset(&buf);
1644c73c
JS
5891 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5892 oid_to_hex(&commit->object.oid),
5893 oneline.buf);
1b5735f7 5894 if (is_empty)
f99e1d94
JK
5895 strbuf_addf(&buf, " %s empty",
5896 comment_line_str);
1644c73c
JS
5897
5898 FLEX_ALLOC_STR(entry, string, buf.buf);
5899 oidcpy(&entry->entry.oid, &commit->object.oid);
5900 oidmap_put(&commit2todo, entry);
5901
5902 continue;
5903 }
5904
43689212
NG
5905 /* Create a label from the commit message */
5906 strbuf_reset(&label_from_message);
e4266724 5907 if (skip_prefix(oneline.buf, "# Merge ", &p1) &&
1644c73c
JS
5908 (p1 = strchr(p1, '\'')) &&
5909 (p2 = strchr(++p1, '\'')))
43689212 5910 strbuf_add(&label_from_message, p1, p2 - p1);
e4266724 5911 else if (skip_prefix(oneline.buf, "# Merge pull request ",
1644c73c
JS
5912 &p1) &&
5913 (p1 = strstr(p1, " from ")))
43689212 5914 strbuf_addstr(&label_from_message, p1 + strlen(" from "));
1644c73c 5915 else
43689212 5916 strbuf_addbuf(&label_from_message, &oneline);
1644c73c 5917
1644c73c
JS
5918 strbuf_reset(&buf);
5919 strbuf_addf(&buf, "%s -C %s",
5920 cmd_merge, oid_to_hex(&commit->object.oid));
5921
2b6ad0f4
JS
5922 /* label the tips of merged branches */
5923 for (; to_merge; to_merge = to_merge->next) {
43689212
NG
5924 const char *label = label_from_message.buf;
5925 const struct name_decoration *decoration =
5926 get_name_decoration(&to_merge->item->object);
5927
5928 if (decoration)
5929 skip_prefix(decoration->name, "refs/heads/",
5930 &label);
5931
2b6ad0f4
JS
5932 oid = &to_merge->item->object.oid;
5933 strbuf_addch(&buf, ' ');
5934
5935 if (!oidset_contains(&interesting, oid)) {
5936 strbuf_addstr(&buf, label_oid(oid, NULL,
5937 &state));
5938 continue;
5939 }
1644c73c 5940
1644c73c
JS
5941 tips_tail = &commit_list_insert(to_merge->item,
5942 tips_tail)->next;
5943
43689212 5944 strbuf_addstr(&buf, label_oid(oid, label, &state));
1644c73c 5945 }
e4266724 5946 strbuf_addf(&buf, " %s", oneline.buf);
1644c73c
JS
5947
5948 FLEX_ALLOC_STR(entry, string, buf.buf);
5949 oidcpy(&entry->entry.oid, &commit->object.oid);
5950 oidmap_put(&commit2todo, entry);
5951 }
767a4ca6
JS
5952 if (skipped_commit)
5953 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5954 _("use --reapply-cherry-picks to include skipped commits"));
1644c73c
JS
5955
5956 /*
5957 * Second phase:
5958 * - label branch points
5959 * - add HEAD to the branch tips
5960 */
5961 for (iter = commits; iter; iter = iter->next) {
5962 struct commit_list *parent = iter->item->parents;
5963 for (; parent; parent = parent->next) {
5964 struct object_id *oid = &parent->item->object.oid;
5965 if (!oidset_contains(&interesting, oid))
5966 continue;
6e8fc70f 5967 if (oidset_insert(&child_seen, oid))
1644c73c
JS
5968 label_oid(oid, "branch-point", &state);
5969 }
5970
15beaaa3 5971 /* Add HEAD as implicit "tip of branch" */
1644c73c
JS
5972 if (!iter->next)
5973 tips_tail = &commit_list_insert(iter->item,
5974 tips_tail)->next;
5975 }
5976
5977 /*
5978 * Third phase: output the todo list. This is a bit tricky, as we
5979 * want to avoid jumping back and forth between revisions. To
5980 * accomplish that goal, we walk backwards from the branch tips,
5981 * gathering commits not yet shown, reversing the list on the fly,
5982 * then outputting that list (labeling revisions as needed).
5983 */
d358fc28 5984 strbuf_addf(out, "%s onto\n", cmd_label);
1644c73c
JS
5985 for (iter = tips; iter; iter = iter->next) {
5986 struct commit_list *list = NULL, *iter2;
5987
5988 commit = iter->item;
5989 if (oidset_contains(&shown, &commit->object.oid))
5990 continue;
5991 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5992
5993 if (entry)
f99e1d94 5994 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
1644c73c 5995 else
d358fc28 5996 strbuf_addch(out, '\n');
1644c73c
JS
5997
5998 while (oidset_contains(&interesting, &commit->object.oid) &&
5999 !oidset_contains(&shown, &commit->object.oid)) {
6000 commit_list_insert(commit, &list);
6001 if (!commit->parents) {
6002 commit = NULL;
6003 break;
6004 }
6005 commit = commit->parents->item;
6006 }
6007
6008 if (!commit)
d358fc28 6009 strbuf_addf(out, "%s %s\n", cmd_reset,
e1fac531
JS
6010 rebase_cousins || root_with_onto ?
6011 "onto" : "[new root]");
1644c73c
JS
6012 else {
6013 const char *to = NULL;
6014
6015 entry = oidmap_get(&state.commit2label,
6016 &commit->object.oid);
6017 if (entry)
6018 to = entry->string;
7543f6f4
JS
6019 else if (!rebase_cousins)
6020 to = label_oid(&commit->object.oid, NULL,
6021 &state);
1644c73c
JS
6022
6023 if (!to || !strcmp(to, "onto"))
d358fc28 6024 strbuf_addf(out, "%s onto\n", cmd_reset);
1644c73c
JS
6025 else {
6026 strbuf_reset(&oneline);
6027 pretty_print_commit(pp, commit, &oneline);
e4266724 6028 strbuf_addf(out, "%s %s %s\n",
d358fc28 6029 cmd_reset, to, oneline.buf);
1644c73c
JS
6030 }
6031 }
6032
6033 for (iter2 = list; iter2; iter2 = iter2->next) {
6034 struct object_id *oid = &iter2->item->object.oid;
6035 entry = oidmap_get(&commit2todo, oid);
6036 /* only show if not already upstream */
6037 if (entry)
d358fc28 6038 strbuf_addf(out, "%s\n", entry->string);
1644c73c
JS
6039 entry = oidmap_get(&state.commit2label, oid);
6040 if (entry)
d358fc28
AG
6041 strbuf_addf(out, "%s %s\n",
6042 cmd_label, entry->string);
1644c73c
JS
6043 oidset_insert(&shown, oid);
6044 }
6045
6046 free_commit_list(list);
6047 }
6048
6049 free_commit_list(commits);
6050 free_commit_list(tips);
6051
43689212 6052 strbuf_release(&label_from_message);
1644c73c
JS
6053 strbuf_release(&oneline);
6054 strbuf_release(&buf);
6055
6e95f4ee
PS
6056 oidset_clear(&interesting);
6057 oidset_clear(&child_seen);
6058 oidset_clear(&shown);
27446468
JK
6059 oidmap_clear(&commit2todo, 1);
6060 oidmap_clear(&state.commit2label, 1);
6da1a258 6061 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
1644c73c
JS
6062 strbuf_release(&state.buf);
6063
6064 return 0;
6065}
6066
d358fc28
AG
6067int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
6068 const char **argv, unsigned flags)
62db5247
JS
6069{
6070 char *format = NULL;
6071 struct pretty_print_context pp = {0};
62db5247
JS
6072 struct rev_info revs;
6073 struct commit *commit;
b9cbd295 6074 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 6075 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 6076 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
0fcb4f6b 6077 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
767a4ca6 6078 int skipped_commit = 0;
0139c58a 6079 int ret = 0;
62db5247 6080
f11c9580 6081 repo_init_revisions(r, &revs, NULL);
62db5247 6082 revs.verbose_header = 1;
1644c73c
JS
6083 if (!rebase_merges)
6084 revs.max_parents = 1;
0fcb4f6b 6085 revs.cherry_mark = !reapply_cherry_picks;
62db5247
JS
6086 revs.limited = 1;
6087 revs.reverse = 1;
6088 revs.right_only = 1;
6089 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6090 revs.topo_order = 1;
6091
6092 revs.pretty_given = 1;
6093 git_config_get_string("rebase.instructionFormat", &format);
6094 if (!format || !*format) {
6095 free(format);
e4266724 6096 format = xstrdup("# %s");
62db5247 6097 }
e4266724
EN
6098 if (*format != '#') {
6099 char *temp = format;
6100 format = xstrfmt("# %s", temp);
6101 free(temp);
6102 }
6103
62db5247
JS
6104 get_commit_format(format, &revs);
6105 free(format);
6106 pp.fmt = revs.commit_format;
6107 pp.output_encoding = get_log_output_encoding();
6108
0139c58a
ÆAB
6109 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
6110 ret = error(_("make_script: unhandled options"));
6111 goto cleanup;
6112 }
62db5247 6113
0139c58a
ÆAB
6114 if (prepare_revision_walk(&revs) < 0) {
6115 ret = error(_("make_script: error preparing revisions"));
6116 goto cleanup;
6117 }
62db5247 6118
0139c58a
ÆAB
6119 if (rebase_merges) {
6120 ret = make_script_with_merges(&pp, &revs, out, flags);
6121 goto cleanup;
6122 }
1644c73c 6123
62db5247 6124 while ((commit = get_revision(&revs))) {
d48e5e21 6125 int is_empty = is_original_commit_empty(commit);
76ea2358 6126
767a4ca6
JS
6127 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6128 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6129 warning(_("skipped previously applied commit %s"),
cb646ffb 6130 short_commit_name(r, commit));
767a4ca6 6131 skipped_commit = 1;
76ea2358 6132 continue;
767a4ca6 6133 }
b9cbd295
EN
6134 if (is_empty && !keep_empty)
6135 continue;
d358fc28 6136 strbuf_addf(out, "%s %s ", insn,
d8ae6c84 6137 oid_to_hex(&commit->object.oid));
d358fc28 6138 pretty_print_commit(&pp, commit, out);
1b5735f7 6139 if (is_empty)
f99e1d94 6140 strbuf_addf(out, " %s empty", comment_line_str);
d358fc28 6141 strbuf_addch(out, '\n');
62db5247 6142 }
767a4ca6
JS
6143 if (skipped_commit)
6144 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6145 _("use --reapply-cherry-picks to include skipped commits"));
0139c58a
ÆAB
6146cleanup:
6147 release_revisions(&revs);
6148 return ret;
62db5247 6149}
3546c8d9 6150
0cce4a27
LB
6151/*
6152 * Add commands after pick and (series of) squash/fixup commands
6153 * in the todo list.
6154 */
17919c35
JS
6155static void todo_list_add_exec_commands(struct todo_list *todo_list,
6156 struct string_list *commands)
3546c8d9 6157{
683153a4
AG
6158 struct strbuf *buf = &todo_list->buf;
6159 size_t base_offset = buf->len;
6160 int i, insert, nr = 0, alloc = 0;
6161 struct todo_item *items = NULL, *base_items = NULL;
3546c8d9 6162
ca56dadb 6163 CALLOC_ARRAY(base_items, commands->nr);
683153a4
AG
6164 for (i = 0; i < commands->nr; i++) {
6165 size_t command_len = strlen(commands->items[i].string);
3546c8d9 6166
683153a4
AG
6167 strbuf_addstr(buf, commands->items[i].string);
6168 strbuf_addch(buf, '\n');
3546c8d9 6169
683153a4
AG
6170 base_items[i].command = TODO_EXEC;
6171 base_items[i].offset_in_buf = base_offset;
e57d2c59
PW
6172 base_items[i].arg_offset = base_offset;
6173 base_items[i].arg_len = command_len;
3546c8d9 6174
683153a4 6175 base_offset += command_len + 1;
3546c8d9
JS
6176 }
6177
1ace63bc
JS
6178 /*
6179 * Insert <commands> after every pick. Here, fixup/squash chains
6180 * are considered part of the pick, so we insert the commands *after*
6181 * those chains if there are any.
683153a4 6182 *
15beaaa3 6183 * As we insert the exec commands immediately after rearranging
683153a4
AG
6184 * any fixups and before the user edits the list, a fixup chain
6185 * can never contain comments (any comments are empty picks that
6186 * have been commented out because the user did not specify
6187 * --keep-empty). So, it is safe to insert an exec command
6188 * without looking at the command following a comment.
1ace63bc 6189 */
683153a4
AG
6190 insert = 0;
6191 for (i = 0; i < todo_list->nr; i++) {
6192 enum todo_command command = todo_list->items[i].command;
6193 if (insert && !is_fixup(command)) {
6194 ALLOC_GROW(items, nr + commands->nr, alloc);
6195 COPY_ARRAY(items + nr, base_items, commands->nr);
6196 nr += commands->nr;
6197
6198 insert = 0;
0cce4a27 6199 }
1ace63bc 6200
683153a4
AG
6201 ALLOC_GROW(items, nr + 1, alloc);
6202 items[nr++] = todo_list->items[i];
6203
1ace63bc 6204 if (command == TODO_PICK || command == TODO_MERGE)
683153a4 6205 insert = 1;
0cce4a27
LB
6206 }
6207
1ace63bc 6208 /* insert or append final <commands> */
cc9dcdee 6209 if (insert) {
683153a4
AG
6210 ALLOC_GROW(items, nr + commands->nr, alloc);
6211 COPY_ARRAY(items + nr, base_items, commands->nr);
6212 nr += commands->nr;
6213 }
0cce4a27 6214
683153a4
AG
6215 free(base_items);
6216 FREE_AND_NULL(todo_list->items);
6217 todo_list->items = items;
6218 todo_list->nr = nr;
6219 todo_list->alloc = alloc;
0cce4a27 6220}
3546c8d9 6221
cb646ffb
JK
6222static void todo_list_to_strbuf(struct repository *r,
6223 struct todo_list *todo_list,
616d7740 6224 struct strbuf *buf, int num, unsigned flags)
3546c8d9 6225{
8dccc7a6 6226 struct todo_item *item;
616d7740 6227 int i, max = todo_list->nr;
3546c8d9 6228
616d7740
AG
6229 if (num > 0 && num < max)
6230 max = num;
3546c8d9 6231
616d7740 6232 for (item = todo_list->items, i = 0; i < max; i++, item++) {
68e7090f
AG
6233 char cmd;
6234
8dccc7a6
LB
6235 /* if the item is not a command write it and continue */
6236 if (item->command >= TODO_COMMENT) {
616d7740 6237 strbuf_addf(buf, "%.*s\n", item->arg_len,
cbef27d6 6238 todo_item_get_arg(todo_list, item));
8dccc7a6 6239 continue;
3546c8d9 6240 }
8dccc7a6
LB
6241
6242 /* add command to the buffer */
68e7090f
AG
6243 cmd = command_to_char(item->command);
6244 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6245 strbuf_addch(buf, cmd);
d8ae6c84 6246 else
616d7740 6247 strbuf_addstr(buf, command_to_string(item->command));
8dccc7a6
LB
6248
6249 /* add commit id */
6250 if (item->commit) {
313a48ea 6251 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
cb646ffb 6252 short_commit_name(r, item->commit) :
8dccc7a6
LB
6253 oid_to_hex(&item->commit->object.oid);
6254
9e3cebd9
CM
6255 if (item->command == TODO_FIXUP) {
6256 if (item->flags & TODO_EDIT_FIXUP_MSG)
6257 strbuf_addstr(buf, " -c");
6258 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6259 strbuf_addstr(buf, " -C");
6260 }
6261 }
6262
4c68e7dd
JS
6263 if (item->command == TODO_MERGE) {
6264 if (item->flags & TODO_EDIT_MERGE_MSG)
616d7740 6265 strbuf_addstr(buf, " -c");
4c68e7dd 6266 else
616d7740 6267 strbuf_addstr(buf, " -C");
4c68e7dd
JS
6268 }
6269
616d7740 6270 strbuf_addf(buf, " %s", oid);
3546c8d9 6271 }
4c68e7dd 6272
8dccc7a6 6273 /* add all the rest */
c7b4d79c 6274 if (!item->arg_len)
616d7740 6275 strbuf_addch(buf, '\n');
c7b4d79c 6276 else
616d7740 6277 strbuf_addf(buf, " %.*s\n", item->arg_len,
cbef27d6 6278 todo_item_get_arg(todo_list, item));
3546c8d9 6279 }
3546c8d9 6280}
94399949 6281
616d7740
AG
6282int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6283 const char *file, const char *shortrevisions,
6284 const char *shortonto, int num, unsigned flags)
94399949 6285{
af1fc3ad 6286 int res;
616d7740 6287 struct strbuf buf = STRBUF_INIT;
94399949 6288
616d7740 6289 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
af1fc3ad 6290 if (flags & TODO_LIST_APPEND_TODO_HELP)
d48e5e21 6291 append_todo_help(count_commands(todo_list),
af1fc3ad 6292 shortrevisions, shortonto, &buf);
94399949 6293
616d7740 6294 res = write_message(buf.buf, buf.len, file, 0);
cbef27d6 6295 strbuf_release(&buf);
8315bd20 6296
616d7740 6297 return res;
cbef27d6 6298}
94399949 6299
cdac2b01 6300/* skip picking commits whose parents are unchanged */
6bfeb7f1
AG
6301static int skip_unnecessary_picks(struct repository *r,
6302 struct todo_list *todo_list,
6303 struct object_id *base_oid)
cdac2b01 6304{
d4ed5d77 6305 struct object_id *parent_oid;
6bfeb7f1 6306 int i;
cdac2b01 6307
6bfeb7f1
AG
6308 for (i = 0; i < todo_list->nr; i++) {
6309 struct todo_item *item = todo_list->items + i;
cdac2b01
JS
6310
6311 if (item->command >= TODO_NOOP)
6312 continue;
6313 if (item->command != TODO_PICK)
6314 break;
4a93b899 6315 if (repo_parse_commit(r, item->commit)) {
cdac2b01
JS
6316 return error(_("could not parse commit '%s'"),
6317 oid_to_hex(&item->commit->object.oid));
6318 }
6319 if (!item->commit->parents)
6320 break; /* root commit */
6321 if (item->commit->parents->next)
6322 break; /* merge commit */
6323 parent_oid = &item->commit->parents->item->object.oid;
6bfeb7f1 6324 if (!oideq(parent_oid, base_oid))
cdac2b01 6325 break;
6bfeb7f1 6326 oidcpy(base_oid, &item->commit->object.oid);
cdac2b01
JS
6327 }
6328 if (i > 0) {
cdac2b01
JS
6329 const char *done_path = rebase_path_done();
6330
6bfeb7f1 6331 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
cdac2b01 6332 error_errno(_("could not write to '%s'"), done_path);
cdac2b01
JS
6333 return -1;
6334 }
cdac2b01 6335
6bfeb7f1
AG
6336 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6337 todo_list->nr -= i;
6338 todo_list->current = 0;
34065541 6339 todo_list->done_nr += i;
cdac2b01 6340
6bfeb7f1
AG
6341 if (is_fixup(peek_command(todo_list, 0)))
6342 record_in_rewritten(base_oid, peek_command(todo_list, 0));
cdac2b01
JS
6343 }
6344
cdac2b01
JS
6345 return 0;
6346}
c44a4c65 6347
900b50c2
DS
6348struct todo_add_branch_context {
6349 struct todo_item *items;
6350 size_t items_nr;
6351 size_t items_alloc;
6352 struct strbuf *buf;
6353 struct commit *commit;
6354 struct string_list refs_to_oids;
6355};
6356
6357static int add_decorations_to_list(const struct commit *commit,
6358 struct todo_add_branch_context *ctx)
6359{
6360 const struct name_decoration *decoration = get_name_decoration(&commit->object);
2e5c4758
PS
6361 const char *head_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
6362 "HEAD",
6363 RESOLVE_REF_READING,
6364 NULL,
6365 NULL);
900b50c2
DS
6366
6367 while (decoration) {
6368 struct todo_item *item;
6369 const char *path;
6370 size_t base_offset = ctx->buf->len;
6371
aa37f3e1
DS
6372 /*
6373 * If the branch is the current HEAD, then it will be
6374 * updated by the default rebase behavior.
6375 */
6376 if (head_ref && !strcmp(head_ref, decoration->name)) {
6377 decoration = decoration->next;
6378 continue;
6379 }
6380
900b50c2
DS
6381 ALLOC_GROW(ctx->items,
6382 ctx->items_nr + 1,
6383 ctx->items_alloc);
6384 item = &ctx->items[ctx->items_nr];
6385 memset(item, 0, sizeof(*item));
6386
6387 /* If the branch is checked out, then leave a comment instead. */
6388 if ((path = branch_checked_out(decoration->name))) {
6389 item->command = TODO_COMMENT;
94304b9f
KH
6390 strbuf_commented_addf(ctx->buf, comment_line_str,
6391 "Ref %s checked out at '%s'\n",
6392 decoration->name, path);
900b50c2
DS
6393 } else {
6394 struct string_list_item *sti;
6395 item->command = TODO_UPDATE_REF;
6396 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6397
6398 sti = string_list_insert(&ctx->refs_to_oids,
6399 decoration->name);
89fc0b53 6400 sti->util = init_update_ref_record(decoration->name);
900b50c2
DS
6401 }
6402
6403 item->offset_in_buf = base_offset;
6404 item->arg_offset = base_offset;
6405 item->arg_len = ctx->buf->len - base_offset;
6406 ctx->items_nr++;
6407
6408 decoration = decoration->next;
6409 }
6410
6411 return 0;
6412}
6413
6414/*
6415 * For each 'pick' command, find out if the commit has a decoration in
6416 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6417 */
6418static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6419{
89fc0b53 6420 int i, res;
900b50c2
DS
6421 struct todo_add_branch_context ctx = {
6422 .buf = &todo_list->buf,
6423 .refs_to_oids = STRING_LIST_INIT_DUP,
6424 };
6425
6426 ctx.items_alloc = 2 * todo_list->nr + 1;
6427 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6428
68c9fcb0 6429 load_branch_decorations();
900b50c2
DS
6430
6431 for (i = 0; i < todo_list->nr; ) {
6432 struct todo_item *item = &todo_list->items[i];
6433
6434 /* insert ith item into new list */
6435 ALLOC_GROW(ctx.items,
6436 ctx.items_nr + 1,
6437 ctx.items_alloc);
6438
6439 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6440
6441 if (item->commit) {
6442 ctx.commit = item->commit;
6443 add_decorations_to_list(item->commit, &ctx);
6444 }
6445 }
6446
89fc0b53
DS
6447 res = write_update_refs_state(&ctx.refs_to_oids);
6448
900b50c2 6449 string_list_clear(&ctx.refs_to_oids, 1);
89fc0b53
DS
6450
6451 if (res) {
6452 /* we failed, so clean up the new list. */
6453 free(ctx.items);
6454 return res;
6455 }
6456
900b50c2
DS
6457 free(todo_list->items);
6458 todo_list->items = ctx.items;
6459 todo_list->nr = ctx.items_nr;
6460 todo_list->alloc = ctx.items_alloc;
6461
6462 return 0;
6463}
6464
005af339 6465int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873 6466 const char *shortrevisions, const char *onto_name,
f3e27a02 6467 struct commit *onto, const struct object_id *orig_head,
7d3488eb 6468 struct string_list *commands, unsigned autosquash,
900b50c2 6469 unsigned update_refs,
7d3488eb 6470 struct todo_list *todo_list)
b97e1873 6471{
5da69c0d
AK
6472 char shortonto[GIT_MAX_HEXSZ + 1];
6473 const char *todo_file = rebase_path_todo();
94bcad79 6474 struct todo_list new_todo = TODO_LIST_INIT;
b6992261 6475 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
7d3488eb 6476 struct object_id oid = onto->object.oid;
1451d0f6 6477 int res;
b97e1873 6478
4a93b899 6479 repo_find_unique_abbrev_r(r, shortonto, &oid,
d850b7a5 6480 DEFAULT_ABBREV);
b97e1873 6481
94bcad79
AG
6482 if (buf->len == 0) {
6483 struct todo_item *item = append_new_todo(todo_list);
6484 item->command = TODO_NOOP;
6485 item->commit = NULL;
6486 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6487 }
b97e1873 6488
900b50c2
DS
6489 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6490 return -1;
6491
94bcad79 6492 if (autosquash && todo_list_rearrange_squash(todo_list))
b97e1873
AG
6493 return -1;
6494
683153a4 6495 if (commands->nr)
94bcad79 6496 todo_list_add_exec_commands(todo_list, commands);
b97e1873 6497
94bcad79 6498 if (count_commands(todo_list) == 0) {
be1bb600 6499 apply_autostash(rebase_path_autostash());
b97e1873 6500 sequencer_remove_state(opts);
b97e1873
AG
6501
6502 return error(_("nothing to do"));
6503 }
6504
0c26738a 6505 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
1451d0f6
AG
6506 shortonto, flags);
6507 if (res == -1)
b97e1873 6508 return -1;
1451d0f6 6509 else if (res == -2) {
be1bb600 6510 apply_autostash(rebase_path_autostash());
b97e1873 6511 sequencer_remove_state(opts);
b97e1873
AG
6512
6513 return -1;
1451d0f6 6514 } else if (res == -3) {
be1bb600 6515 apply_autostash(rebase_path_autostash());
b97e1873 6516 sequencer_remove_state(opts);
94bcad79 6517 todo_list_release(&new_todo);
b97e1873
AG
6518
6519 return error(_("nothing to do"));
5a5445d8 6520 } else if (res == -4) {
7d3488eb 6521 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
94bcad79
AG
6522 todo_list_release(&new_todo);
6523
b97e1873
AG
6524 return -1;
6525 }
6526
b6992261
JS
6527 /* Expand the commit IDs */
6528 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6529 strbuf_swap(&new_todo.buf, &buf2);
6530 strbuf_release(&buf2);
170eea97
JS
6531 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6532 new_todo.total_nr = 0;
0c26738a 6533 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
b6992261
JS
6534 BUG("invalid todo list after expanding IDs:\n%s",
6535 new_todo.buf.buf);
6536
6bfeb7f1
AG
6537 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6538 todo_list_release(&new_todo);
b97e1873 6539 return error(_("could not skip unnecessary pick commands"));
6bfeb7f1
AG
6540 }
6541
94bcad79
AG
6542 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6543 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6544 todo_list_release(&new_todo);
6545 return error_errno(_("could not write '%s'"), todo_file);
6546 }
6547
393adf7a 6548 res = -1;
b97e1873 6549
7d3488eb 6550 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
393adf7a 6551 goto cleanup;
29d51e21 6552
a9b5955e 6553 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
393adf7a 6554 goto cleanup;
b97e1873 6555
393adf7a
AG
6556 todo_list_write_total_nr(&new_todo);
6557 res = pick_commits(r, &new_todo, opts);
6558
6559cleanup:
6560 todo_list_release(&new_todo);
6561
6562 return res;
b97e1873
AG
6563}
6564
c44a4c65
JS
6565struct subject2item_entry {
6566 struct hashmap_entry entry;
6567 int i;
6568 char subject[FLEX_ARRAY];
6569};
6570
5cf88fd8 6571static int subject2item_cmp(const void *fndata UNUSED,
939af16e
EW
6572 const struct hashmap_entry *eptr,
6573 const struct hashmap_entry *entry_or_key,
6574 const void *key)
c44a4c65 6575{
939af16e
EW
6576 const struct subject2item_entry *a, *b;
6577
6578 a = container_of(eptr, const struct subject2item_entry, entry);
6579 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6580
c44a4c65
JS
6581 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6582}
6583
3cc0287b
NTND
6584define_commit_slab(commit_todo_item, struct todo_item *);
6585
1f969601 6586static int skip_fixupish(const char *subject, const char **p) {
bae5b4ae
CM
6587 return skip_prefix(subject, "fixup! ", p) ||
6588 skip_prefix(subject, "amend! ", p) ||
6589 skip_prefix(subject, "squash! ", p);
6590}
6591
c44a4c65
JS
6592/*
6593 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6594 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6595 * after the former, and change "pick" to "fixup"/"squash".
6596 *
6597 * Note that if the config has specified a custom instruction format, each log
6598 * message will have to be retrieved from the commit (as the oneline in the
6599 * script cannot be trusted) in order to normalize the autosquash arrangement.
6600 */
79d7e883 6601int todo_list_rearrange_squash(struct todo_list *todo_list)
c44a4c65 6602{
c44a4c65 6603 struct hashmap subject2item;
82dc42cb 6604 int rearranged = 0, *next, *tail, i, nr = 0;
c44a4c65 6605 char **subjects;
3cc0287b 6606 struct commit_todo_item commit_todo;
f2a04904 6607 struct todo_item *items = NULL;
044511f8 6608 int ret = 0;
c44a4c65 6609
3cc0287b 6610 init_commit_todo_item(&commit_todo);
c44a4c65
JS
6611 /*
6612 * The hashmap maps onelines to the respective todo list index.
6613 *
6614 * If any items need to be rearranged, the next[i] value will indicate
6615 * which item was moved directly after the i'th.
6616 *
6617 * In that case, last[i] will indicate the index of the latest item to
6618 * be moved to appear after the i'th.
6619 */
939af16e 6620 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
f2a04904
AG
6621 ALLOC_ARRAY(next, todo_list->nr);
6622 ALLOC_ARRAY(tail, todo_list->nr);
6623 ALLOC_ARRAY(subjects, todo_list->nr);
6624 for (i = 0; i < todo_list->nr; i++) {
c44a4c65 6625 struct strbuf buf = STRBUF_INIT;
f2a04904 6626 struct todo_item *item = todo_list->items + i;
c44a4c65
JS
6627 const char *commit_buffer, *subject, *p;
6628 size_t subject_len;
6629 int i2 = -1;
6630 struct subject2item_entry *entry;
6631
6632 next[i] = tail[i] = -1;
2f6b1d13 6633 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
6634 subjects[i] = NULL;
6635 continue;
6636 }
6637
6638 if (is_fixup(item->command)) {
044511f8
LY
6639 ret = error(_("the script was already rearranged."));
6640 goto cleanup;
c44a4c65
JS
6641 }
6642
ecb5091f
ÆAB
6643 repo_parse_commit(the_repository, item->commit);
6644 commit_buffer = repo_logmsg_reencode(the_repository,
6645 item->commit, NULL,
6646 "UTF-8");
c44a4c65
JS
6647 find_commit_subject(commit_buffer, &subject);
6648 format_subject(&buf, subject, " ");
6649 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
ecb5091f
ÆAB
6650 repo_unuse_commit_buffer(the_repository, item->commit,
6651 commit_buffer);
1f969601 6652 if (skip_fixupish(subject, &p)) {
c44a4c65
JS
6653 struct commit *commit2;
6654
6655 for (;;) {
6656 while (isspace(*p))
6657 p++;
1f969601 6658 if (!skip_fixupish(p, &p))
c44a4c65
JS
6659 break;
6660 }
6661
f23a4651
EW
6662 entry = hashmap_get_entry_from_hash(&subject2item,
6663 strhash(p), p,
6664 struct subject2item_entry,
6665 entry);
6666 if (entry)
c44a4c65
JS
6667 /* found by title */
6668 i2 = entry->i;
6669 else if (!strchr(p, ' ') &&
6670 (commit2 =
6671 lookup_commit_reference_by_name(p)) &&
3cc0287b 6672 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 6673 /* found by commit name */
3cc0287b 6674 i2 = *commit_todo_item_at(&commit_todo, commit2)
f2a04904 6675 - todo_list->items;
c44a4c65
JS
6676 else {
6677 /* copy can be a prefix of the commit subject */
6678 for (i2 = 0; i2 < i; i2++)
6679 if (subjects[i2] &&
6680 starts_with(subjects[i2], p))
6681 break;
6682 if (i2 == i)
6683 i2 = -1;
6684 }
6685 }
6686 if (i2 >= 0) {
6687 rearranged = 1;
bae5b4ae
CM
6688 if (starts_with(subject, "fixup!")) {
6689 todo_list->items[i].command = TODO_FIXUP;
6690 } else if (starts_with(subject, "amend!")) {
6691 todo_list->items[i].command = TODO_FIXUP;
6692 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6693 } else {
6694 todo_list->items[i].command = TODO_SQUASH;
6695 }
02471e7e
JS
6696 if (tail[i2] < 0) {
6697 next[i] = next[i2];
c44a4c65 6698 next[i2] = i;
02471e7e
JS
6699 } else {
6700 next[i] = next[tail[i2]];
c44a4c65 6701 next[tail[i2]] = i;
02471e7e 6702 }
c44a4c65
JS
6703 tail[i2] = i;
6704 } else if (!hashmap_get_from_hash(&subject2item,
6705 strhash(subject), subject)) {
6706 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6707 entry->i = i;
d22245a2
EW
6708 hashmap_entry_init(&entry->entry,
6709 strhash(entry->subject));
26b455f2 6710 hashmap_put(&subject2item, &entry->entry);
c44a4c65 6711 }
3e367a5f
JA
6712
6713 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
6714 }
6715
6716 if (rearranged) {
82dc42cb
OB
6717 ALLOC_ARRAY(items, todo_list->nr);
6718
f2a04904
AG
6719 for (i = 0; i < todo_list->nr; i++) {
6720 enum todo_command command = todo_list->items[i].command;
c44a4c65
JS
6721 int cur = i;
6722
6723 /*
6724 * Initially, all commands are 'pick's. If it is a
6725 * fixup or a squash now, we have rearranged it.
6726 */
6727 if (is_fixup(command))
6728 continue;
6729
6730 while (cur >= 0) {
f2a04904 6731 items[nr++] = todo_list->items[cur];
c44a4c65
JS
6732 cur = next[cur];
6733 }
6734 }
6735
82dc42cb
OB
6736 assert(nr == todo_list->nr);
6737 todo_list->alloc = nr;
f2a04904
AG
6738 FREE_AND_NULL(todo_list->items);
6739 todo_list->items = items;
c44a4c65
JS
6740 }
6741
044511f8 6742cleanup:
c44a4c65
JS
6743 free(next);
6744 free(tail);
f2a04904 6745 for (i = 0; i < todo_list->nr; i++)
c44a4c65
JS
6746 free(subjects[i]);
6747 free(subjects);
6da1a258 6748 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
c44a4c65 6749
3cc0287b 6750 clear_commit_todo_item(&commit_todo);
f2a04904 6751
044511f8 6752 return ret;
c44a4c65 6753}
901ba7b1
PW
6754
6755int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6756{
c8e4159e 6757 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
430b75f7
PW
6758 struct object_id cherry_pick_head, rebase_head;
6759
6760 if (file_exists(git_path_seq_dir()))
6761 *whence = FROM_CHERRY_PICK_MULTI;
6762 if (file_exists(rebase_path()) &&
4a93b899
ÆAB
6763 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6764 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
430b75f7
PW
6765 oideq(&rebase_head, &cherry_pick_head))
6766 *whence = FROM_REBASE_PICK;
6767 else
6768 *whence = FROM_CHERRY_PICK_SINGLE;
6769
901ba7b1
PW
6770 return 1;
6771 }
6772
6773 return 0;
6774}
aa7f2fd1
DS
6775
6776int sequencer_get_update_refs_state(const char *wt_dir,
6777 struct string_list *refs)
6778{
6779 int result = 0;
6780 FILE *fp = NULL;
6781 struct strbuf ref = STRBUF_INIT;
6782 struct strbuf hash = STRBUF_INIT;
6783 struct update_ref_record *rec = NULL;
6784
6785 char *path = rebase_path_update_refs(wt_dir);
6786
6787 fp = fopen(path, "r");
6788 if (!fp)
6789 goto cleanup;
6790
6791 while (strbuf_getline(&ref, fp) != EOF) {
6792 struct string_list_item *item;
6793
6794 CALLOC_ARRAY(rec, 1);
6795
6796 if (strbuf_getline(&hash, fp) == EOF ||
6797 get_oid_hex(hash.buf, &rec->before)) {
6798 warning(_("update-refs file at '%s' is invalid"),
6799 path);
6800 result = -1;
6801 goto cleanup;
6802 }
6803
6804 if (strbuf_getline(&hash, fp) == EOF ||
6805 get_oid_hex(hash.buf, &rec->after)) {
6806 warning(_("update-refs file at '%s' is invalid"),
6807 path);
6808 result = -1;
6809 goto cleanup;
6810 }
6811
6812 item = string_list_insert(refs, ref.buf);
6813 item->util = rec;
6814 rec = NULL;
6815 }
6816
6817cleanup:
6818 if (fp)
6819 fclose(fp);
6820 free(path);
6821 free(rec);
6822 strbuf_release(&ref);
6823 strbuf_release(&hash);
6824 return result;
6825}