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