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