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