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