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