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