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