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