]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
rebase: generify create_autostash()
[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
c20de8be 422int read_oneliner(struct strbuf *buf,
3442c3d1 423 const char *path, unsigned flags)
1dfc84e9
JS
424{
425 int orig_len = buf->len;
426
1dfc84e9 427 if (strbuf_read_file(buf, path, 0) < 0) {
bfa50c2c
DL
428 if ((flags & READ_ONELINER_WARN_MISSING) ||
429 (errno != ENOENT && errno != ENOTDIR))
5b2f6d9c 430 warning_errno(_("could not read '%s'"), path);
1dfc84e9
JS
431 return 0;
432 }
433
434 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
435 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
436 --buf->len;
437 buf->buf[buf->len] = '\0';
438 }
439
3442c3d1 440 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
1dfc84e9
JS
441 return 0;
442
443 return 1;
444}
445
005af339 446static struct tree *empty_tree(struct repository *r)
043a4492 447{
005af339 448 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
449}
450
e1ff0a32 451static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 452{
e1ff0a32 453 if (repo_read_index_unmerged(repo))
c28cbc5e 454 return error_resolve_conflict(_(action_name(opts)));
043a4492 455
93b3df6f 456 error(_("your local changes would be overwritten by %s."),
c28cbc5e 457 _(action_name(opts)));
043a4492
RR
458
459 if (advice_commit_before_merge)
93b3df6f 460 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
461 return -1;
462}
463
1e41229d
SB
464static void update_abort_safety_file(void)
465{
466 struct object_id head;
467
468 /* Do nothing on a single-pick */
469 if (!file_exists(git_path_seq_dir()))
470 return;
471
472 if (!get_oid("HEAD", &head))
473 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
474 else
475 write_file(git_path_abort_safety_file(), "%s", "");
476}
477
f11c9580
NTND
478static int fast_forward_to(struct repository *r,
479 const struct object_id *to,
480 const struct object_id *from,
481 int unborn,
482 struct replay_opts *opts)
043a4492 483{
d668d16c 484 struct ref_transaction *transaction;
eb4be1cb 485 struct strbuf sb = STRBUF_INIT;
d668d16c 486 struct strbuf err = STRBUF_INIT;
043a4492 487
e1ff0a32 488 repo_read_index(r);
f11c9580 489 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 490 return -1; /* the callee should have complained already */
651ab9f5 491
c28cbc5e 492 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
493
494 transaction = ref_transaction_begin(&err);
495 if (!transaction ||
496 ref_transaction_update(transaction, "HEAD",
d87d48b2
JS
497 to, unborn && !is_rebase_i(opts) ?
498 &null_oid : from,
1d147bdf 499 0, sb.buf, &err) ||
db7516ab 500 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
501 ref_transaction_free(transaction);
502 error("%s", err.buf);
503 strbuf_release(&sb);
504 strbuf_release(&err);
505 return -1;
506 }
651ab9f5 507
eb4be1cb 508 strbuf_release(&sb);
d668d16c
RS
509 strbuf_release(&err);
510 ref_transaction_free(transaction);
1e41229d 511 update_abort_safety_file();
d668d16c 512 return 0;
043a4492
RR
513}
514
f29cd862
DL
515enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
516 int use_editor)
517{
518 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
519 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
520 COMMIT_MSG_CLEANUP_SPACE;
521 else if (!strcmp(cleanup_arg, "verbatim"))
522 return COMMIT_MSG_CLEANUP_NONE;
523 else if (!strcmp(cleanup_arg, "whitespace"))
524 return COMMIT_MSG_CLEANUP_SPACE;
525 else if (!strcmp(cleanup_arg, "strip"))
526 return COMMIT_MSG_CLEANUP_ALL;
527 else if (!strcmp(cleanup_arg, "scissors"))
528 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
529 COMMIT_MSG_CLEANUP_SPACE;
530 else
531 die(_("Invalid cleanup mode %s"), cleanup_arg);
532}
533
dc42e9a8
PW
534/*
535 * NB using int rather than enum cleanup_mode to stop clang's
536 * -Wtautological-constant-out-of-range-compare complaining that the comparison
537 * is always true.
538 */
539static const char *describe_cleanup_mode(int cleanup_mode)
540{
541 static const char *modes[] = { "whitespace",
542 "verbatim",
543 "scissors",
544 "strip" };
545
546 if (cleanup_mode < ARRAY_SIZE(modes))
547 return modes[cleanup_mode];
548
549 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
550}
551
f11c9580 552void append_conflicts_hint(struct index_state *istate,
1a2b985f 553 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
75c961b7
JH
554{
555 int i;
556
1a2b985f
DL
557 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
558 strbuf_addch(msgbuf, '\n');
559 wt_status_append_cut_line(msgbuf);
560 strbuf_addch(msgbuf, comment_line_char);
561 }
562
261f315b
JH
563 strbuf_addch(msgbuf, '\n');
564 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
565 for (i = 0; i < istate->cache_nr;) {
566 const struct cache_entry *ce = istate->cache[i++];
75c961b7 567 if (ce_stage(ce)) {
261f315b 568 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
569 while (i < istate->cache_nr &&
570 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
571 i++;
572 }
573 }
574}
575
f11c9580
NTND
576static int do_recursive_merge(struct repository *r,
577 struct commit *base, struct commit *next,
043a4492 578 const char *base_label, const char *next_label,
48be4c62 579 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
580 struct replay_opts *opts)
581{
582 struct merge_options o;
b4db8a2b 583 struct tree *next_tree, *base_tree, *head_tree;
03b86647 584 int clean;
d20bc01a 585 int i;
14bca6c6 586 struct lock_file index_lock = LOCK_INIT;
043a4492 587
3a95f31d 588 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 589 return -1;
043a4492 590
e1ff0a32 591 repo_read_index(r);
043a4492 592
0d6caa2d 593 init_merge_options(&o, r);
043a4492
RR
594 o.ancestor = base ? base_label : "(empty tree)";
595 o.branch1 = "HEAD";
596 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
597 if (is_rebase_i(opts))
598 o.buffer_output = 2;
9268cf4a 599 o.show_rename_progress = 1;
043a4492
RR
600
601 head_tree = parse_tree_indirect(head);
005af339
NTND
602 next_tree = next ? get_commit_tree(next) : empty_tree(r);
603 base_tree = base ? get_commit_tree(base) : empty_tree(r);
043a4492 604
d20bc01a
JK
605 for (i = 0; i < opts->xopts_nr; i++)
606 parse_merge_opt(&o, opts->xopts[i]);
043a4492
RR
607
608 clean = merge_trees(&o,
609 head_tree,
b4db8a2b 610 next_tree, base_tree);
62fdb652
JS
611 if (is_rebase_i(opts) && clean <= 0)
612 fputs(o.obuf.buf, stdout);
548009c0 613 strbuf_release(&o.obuf);
64816524
614 if (clean < 0) {
615 rollback_lock_file(&index_lock);
f241ff0d 616 return clean;
64816524 617 }
043a4492 618
f11c9580 619 if (write_locked_index(r->index, &index_lock,
61000814 620 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
621 /*
622 * TRANSLATORS: %s will be "revert", "cherry-pick" or
c2417d3a 623 * "rebase".
84583957 624 */
c527b55e 625 return error(_("%s: Unable to write new index file"),
c28cbc5e 626 _(action_name(opts)));
043a4492 627
75c961b7 628 if (!clean)
1a2b985f
DL
629 append_conflicts_hint(r->index, msgbuf,
630 opts->default_msg_cleanup);
043a4492
RR
631
632 return !clean;
633}
634
f11c9580 635static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 636{
f11c9580
NTND
637 if (!istate->cache_tree)
638 istate->cache_tree = cache_tree();
ba97aea1 639
f11c9580
NTND
640 if (!cache_tree_fully_valid(istate->cache_tree))
641 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
642 error(_("unable to update cache tree"));
643 return NULL;
644 }
645
f11c9580 646 return &istate->cache_tree->oid;
ba97aea1
JS
647}
648
005af339 649static int is_index_unchanged(struct repository *r)
b27cfb0d 650{
ba97aea1 651 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 652 struct commit *head_commit;
005af339 653 struct index_state *istate = r->index;
b27cfb0d 654
49e61479 655 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 656 return error(_("could not resolve HEAD commit"));
b27cfb0d 657
005af339 658 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
659
660 /*
661 * If head_commit is NULL, check_commit, called from
662 * lookup_commit, would have indicated that head_commit is not
663 * a commit object already. parse_commit() will return failure
664 * without further complaints in such a case. Otherwise, if
665 * the commit is invalid, parse_commit() will complain. So
666 * there is nothing for us to say here. Just return failure.
667 */
668 if (parse_commit(head_commit))
669 return -1;
b27cfb0d 670
f11c9580 671 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 672 return -1;
b27cfb0d 673
4a7e27e9 674 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
675}
676
0473f28a
JS
677static int write_author_script(const char *message)
678{
679 struct strbuf buf = STRBUF_INIT;
680 const char *eol;
681 int res;
682
683 for (;;)
684 if (!*message || starts_with(message, "\n")) {
685missing_author:
686 /* Missing 'author' line? */
687 unlink(rebase_path_author_script());
688 return 0;
689 } else if (skip_prefix(message, "author ", &message))
690 break;
691 else if ((eol = strchr(message, '\n')))
692 message = eol + 1;
693 else
694 goto missing_author;
695
696 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
697 while (*message && *message != '\n' && *message != '\r')
698 if (skip_prefix(message, " <", &message))
699 break;
700 else if (*message != '\'')
701 strbuf_addch(&buf, *(message++));
702 else
4aa5ff94 703 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
704 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
705 while (*message && *message != '\n' && *message != '\r')
706 if (skip_prefix(message, "> ", &message))
707 break;
708 else if (*message != '\'')
709 strbuf_addch(&buf, *(message++));
710 else
4aa5ff94 711 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
712 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
713 while (*message && *message != '\n' && *message != '\r')
714 if (*message != '\'')
715 strbuf_addch(&buf, *(message++));
716 else
4aa5ff94 717 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 718 strbuf_addch(&buf, '\'');
0473f28a
JS
719 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
720 strbuf_release(&buf);
721 return res;
722}
723
bcd33ec2
PW
724/**
725 * Take a series of KEY='VALUE' lines where VALUE part is
726 * sq-quoted, and append <KEY, VALUE> at the end of the string list
727 */
728static int parse_key_value_squoted(char *buf, struct string_list *list)
729{
730 while (*buf) {
731 struct string_list_item *item;
732 char *np;
733 char *cp = strchr(buf, '=');
734 if (!cp) {
735 np = strchrnul(buf, '\n');
736 return error(_("no key present in '%.*s'"),
737 (int) (np - buf), buf);
738 }
739 np = strchrnul(cp, '\n');
740 *cp++ = '\0';
741 item = string_list_append(list, buf);
742
743 buf = np + (*np == '\n');
744 *np = '\0';
745 cp = sq_dequote(cp);
746 if (!cp)
747 return error(_("unable to dequote value of '%s'"),
748 item->string);
749 item->util = xstrdup(cp);
750 }
751 return 0;
752}
4aa5ff94 753
bcd33ec2
PW
754/**
755 * Reads and parses the state directory's "author-script" file, and sets name,
756 * email and date accordingly.
757 * Returns 0 on success, -1 if the file could not be parsed.
758 *
759 * The author script is of the format:
760 *
761 * GIT_AUTHOR_NAME='$author_name'
762 * GIT_AUTHOR_EMAIL='$author_email'
763 * GIT_AUTHOR_DATE='$author_date'
764 *
765 * where $author_name, $author_email and $author_date are quoted. We are strict
c3c003e7 766 * with our parsing, as the file was meant to be eval'd in the now-removed
bcd33ec2
PW
767 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
768 * from what this function expects, it is better to bail out than to do
769 * something that the user does not expect.
4aa5ff94 770 */
bcd33ec2
PW
771int read_author_script(const char *path, char **name, char **email, char **date,
772 int allow_missing)
4aa5ff94 773{
bcd33ec2
PW
774 struct strbuf buf = STRBUF_INIT;
775 struct string_list kv = STRING_LIST_INIT_DUP;
776 int retval = -1; /* assume failure */
777 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 778
bcd33ec2
PW
779 if (strbuf_read_file(&buf, path, 256) <= 0) {
780 strbuf_release(&buf);
781 if (errno == ENOENT && allow_missing)
782 return 0;
783 else
784 return error_errno(_("could not open '%s' for reading"),
785 path);
786 }
787
788 if (parse_key_value_squoted(buf.buf, &kv))
789 goto finish;
790
791 for (i = 0; i < kv.nr; i++) {
792 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
793 if (name_i != -2)
794 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
795 else
796 name_i = i;
797 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
798 if (email_i != -2)
799 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
800 else
801 email_i = i;
802 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
803 if (date_i != -2)
804 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
805 else
806 date_i = i;
807 } else {
808 err = error(_("unknown variable '%s'"),
809 kv.items[i].string);
810 }
811 }
812 if (name_i == -2)
813 error(_("missing 'GIT_AUTHOR_NAME'"));
814 if (email_i == -2)
815 error(_("missing 'GIT_AUTHOR_EMAIL'"));
816 if (date_i == -2)
817 error(_("missing 'GIT_AUTHOR_DATE'"));
818 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
819 goto finish;
4d924528
JH
820 *name = kv.items[name_i].util;
821 *email = kv.items[email_i].util;
822 *date = kv.items[date_i].util;
bcd33ec2
PW
823 retval = 0;
824finish:
825 string_list_clear(&kv, !!retval);
826 strbuf_release(&buf);
827 return retval;
4aa5ff94
PW
828}
829
b5a67045 830/*
4d010a75
PW
831 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
832 * file with shell quoting into struct argv_array. Returns -1 on
833 * error, 0 otherwise.
b5a67045 834 */
a2a20b0d 835static int read_env_script(struct argv_array *env)
b5a67045 836{
4d010a75 837 char *name, *email, *date;
b5a67045 838
4d010a75
PW
839 if (read_author_script(rebase_path_author_script(),
840 &name, &email, &date, 0))
a2a20b0d 841 return -1;
b5a67045 842
4d010a75
PW
843 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
844 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
845 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
846 free(name);
847 free(email);
848 free(date);
b5a67045 849
a2a20b0d 850 return 0;
b5a67045
JS
851}
852
356ee465
PW
853static char *get_author(const char *message)
854{
855 size_t len;
856 const char *a;
857
858 a = find_commit_header(message, "author", &len);
859 if (a)
860 return xmemdupz(a, len);
861
862 return NULL;
863}
864
791eb870
JS
865static const char staged_changes_advice[] =
866N_("you have staged changes in your working tree\n"
867"If these changes are meant to be squashed into the previous commit, run:\n"
868"\n"
869" git commit --amend %s\n"
870"\n"
871"If they are meant to go into a new commit, run:\n"
872"\n"
873" git commit %s\n"
874"\n"
875"In both cases, once you're done, continue with:\n"
876"\n"
877" git rebase --continue\n");
878
789b3eff
JS
879#define ALLOW_EMPTY (1<<0)
880#define EDIT_MSG (1<<1)
881#define AMEND_MSG (1<<2)
882#define CLEANUP_MSG (1<<3)
b92ff6e8 883#define VERIFY_MSG (1<<4)
d87d48b2 884#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 885
34bec2c4
AG
886static int run_command_silent_on_success(struct child_process *cmd)
887{
888 struct strbuf buf = STRBUF_INIT;
889 int rc;
890
891 cmd->stdout_to_stderr = 1;
892 rc = pipe_command(cmd,
893 NULL, 0,
894 NULL, 0,
895 &buf, 0);
896
897 if (rc)
898 fputs(buf.buf, stderr);
899 strbuf_release(&buf);
900 return rc;
901}
902
043a4492
RR
903/*
904 * If we are cherry-pick, and if the merge did not result in
905 * hand-editing, we will hit this commit and inherit the original
906 * author date and name.
b5a67045 907 *
043a4492
RR
908 * If we are revert, or if our cherry-pick results in a hand merge,
909 * we had better say that the current user is responsible for that.
b5a67045
JS
910 *
911 * An exception is when run_git_commit() is called during an
912 * interactive rebase: in that case, we will want to retain the
913 * author metadata.
043a4492 914 */
f11c9580
NTND
915static int run_git_commit(struct repository *r,
916 const char *defmsg,
917 struct replay_opts *opts,
789b3eff 918 unsigned int flags)
043a4492 919{
07d968ef 920 struct child_process cmd = CHILD_PROCESS_INIT;
b27cfb0d 921
07d968ef
JS
922 cmd.git_cmd = 1;
923
34bec2c4
AG
924 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
925 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 926
34bec2c4
AG
927 return error(_(staged_changes_advice),
928 gpg_opt, gpg_opt);
b5a67045
JS
929 }
930
07d968ef 931 argv_array_push(&cmd.args, "commit");
043a4492 932
b92ff6e8
JS
933 if (!(flags & VERIFY_MSG))
934 argv_array_push(&cmd.args, "-n");
789b3eff 935 if ((flags & AMEND_MSG))
07d968ef 936 argv_array_push(&cmd.args, "--amend");
3bdd5522 937 if (opts->gpg_sign)
07d968ef 938 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 939 if (defmsg)
07d968ef 940 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
941 else if (!(flags & EDIT_MSG))
942 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 943 if ((flags & CLEANUP_MSG))
07d968ef 944 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 945 if ((flags & EDIT_MSG))
07d968ef 946 argv_array_push(&cmd.args, "-e");
789b3eff 947 else if (!(flags & CLEANUP_MSG) &&
0009426d 948 !opts->signoff && !opts->record_origin &&
1a2b985f 949 !opts->explicit_cleanup)
07d968ef 950 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 951
789b3eff 952 if ((flags & ALLOW_EMPTY))
07d968ef 953 argv_array_push(&cmd.args, "--allow-empty");
df478b74 954
a3ec9eaf 955 if (!(flags & EDIT_MSG))
07d968ef 956 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 957
34bec2c4
AG
958 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
959 return run_command_silent_on_success(&cmd);
960 else
961 return run_command(&cmd);
b27cfb0d
NH
962}
963
d0aaa46f
PW
964static int rest_is_empty(const struct strbuf *sb, int start)
965{
966 int i, eol;
967 const char *nl;
968
969 /* Check if the rest is just whitespace and Signed-off-by's. */
970 for (i = start; i < sb->len; i++) {
971 nl = memchr(sb->buf + i, '\n', sb->len - i);
972 if (nl)
973 eol = nl - sb->buf;
974 else
975 eol = sb->len;
976
977 if (strlen(sign_off_header) <= eol - i &&
978 starts_with(sb->buf + i, sign_off_header)) {
979 i = eol;
980 continue;
981 }
982 while (i < eol)
983 if (!isspace(sb->buf[i++]))
984 return 0;
985 }
986
987 return 1;
988}
989
f29cd862
DL
990void cleanup_message(struct strbuf *msgbuf,
991 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
992{
993 if (verbose || /* Truncate the message just before the diff, if any. */
994 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
995 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
996 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
997 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
998}
999
d0aaa46f
PW
1000/*
1001 * Find out if the message in the strbuf contains only whitespace and
1002 * Signed-off-by lines.
1003 */
1004int message_is_empty(const struct strbuf *sb,
1005 enum commit_msg_cleanup_mode cleanup_mode)
1006{
1007 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1008 return 0;
1009 return rest_is_empty(sb, 0);
1010}
1011
1012/*
1013 * See if the user edited the message in the editor or left what
1014 * was in the template intact
1015 */
1016int template_untouched(const struct strbuf *sb, const char *template_file,
1017 enum commit_msg_cleanup_mode cleanup_mode)
1018{
1019 struct strbuf tmpl = STRBUF_INIT;
1020 const char *start;
1021
1022 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1023 return 0;
1024
1025 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1026 return 0;
1027
1028 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1029 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1030 start = sb->buf;
1031 strbuf_release(&tmpl);
1032 return rest_is_empty(sb, start - sb->buf);
1033}
1034
0505d604
PW
1035int update_head_with_reflog(const struct commit *old_head,
1036 const struct object_id *new_head,
1037 const char *action, const struct strbuf *msg,
1038 struct strbuf *err)
1039{
1040 struct ref_transaction *transaction;
1041 struct strbuf sb = STRBUF_INIT;
1042 const char *nl;
1043 int ret = 0;
1044
1045 if (action) {
1046 strbuf_addstr(&sb, action);
1047 strbuf_addstr(&sb, ": ");
1048 }
1049
1050 nl = strchr(msg->buf, '\n');
1051 if (nl) {
1052 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1053 } else {
1054 strbuf_addbuf(&sb, msg);
1055 strbuf_addch(&sb, '\n');
1056 }
1057
1058 transaction = ref_transaction_begin(err);
1059 if (!transaction ||
1060 ref_transaction_update(transaction, "HEAD", new_head,
1061 old_head ? &old_head->object.oid : &null_oid,
1062 0, sb.buf, err) ||
1063 ref_transaction_commit(transaction, err)) {
1064 ret = -1;
1065 }
1066 ref_transaction_free(transaction);
1067 strbuf_release(&sb);
1068
1069 return ret;
1070}
1071
a87a6f3c
PW
1072static int run_rewrite_hook(const struct object_id *oldoid,
1073 const struct object_id *newoid)
1074{
1075 struct child_process proc = CHILD_PROCESS_INIT;
1076 const char *argv[3];
1077 int code;
1078 struct strbuf sb = STRBUF_INIT;
1079
1080 argv[0] = find_hook("post-rewrite");
1081 if (!argv[0])
1082 return 0;
1083
1084 argv[1] = "amend";
1085 argv[2] = NULL;
1086
1087 proc.argv = argv;
1088 proc.in = -1;
1089 proc.stdout_to_stderr = 1;
6206286e 1090 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1091
1092 code = start_command(&proc);
1093 if (code)
1094 return code;
1095 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1096 sigchain_push(SIGPIPE, SIG_IGN);
1097 write_in_full(proc.in, sb.buf, sb.len);
1098 close(proc.in);
1099 strbuf_release(&sb);
1100 sigchain_pop(SIGPIPE);
1101 return finish_command(&proc);
1102}
1103
1d18d758
NTND
1104void commit_post_rewrite(struct repository *r,
1105 const struct commit *old_head,
a87a6f3c
PW
1106 const struct object_id *new_head)
1107{
1108 struct notes_rewrite_cfg *cfg;
1109
1110 cfg = init_copy_notes_for_rewrite("amend");
1111 if (cfg) {
1112 /* we are amending, so old_head is not NULL */
1113 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1114 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1115 }
1116 run_rewrite_hook(&old_head->object.oid, new_head);
1117}
1118
f11c9580
NTND
1119static int run_prepare_commit_msg_hook(struct repository *r,
1120 struct strbuf *msg,
1121 const char *commit)
66618a50 1122{
49697cb7
PW
1123 int ret = 0;
1124 const char *name, *arg1 = NULL, *arg2 = NULL;
66618a50
PW
1125
1126 name = git_path_commit_editmsg();
1127 if (write_message(msg->buf, msg->len, name, 0))
1128 return -1;
1129
49697cb7
PW
1130 if (commit) {
1131 arg1 = "commit";
1132 arg2 = commit;
1133 } else {
1134 arg1 = "message";
1135 }
1136 if (run_commit_hook(0, r->index_file, "prepare-commit-msg", name,
1137 arg1, arg2, NULL))
66618a50 1138 ret = error(_("'prepare-commit-msg' hook failed"));
66618a50
PW
1139
1140 return ret;
1141}
1142
e47c6caf
PW
1143static const char implicit_ident_advice_noconfig[] =
1144N_("Your name and email address were configured automatically based\n"
1145"on your username and hostname. Please check that they are accurate.\n"
1146"You can suppress this message by setting them explicitly. Run the\n"
1147"following command and follow the instructions in your editor to edit\n"
1148"your configuration file:\n"
1149"\n"
1150" git config --global --edit\n"
1151"\n"
1152"After doing this, you may fix the identity used for this commit with:\n"
1153"\n"
1154" git commit --amend --reset-author\n");
1155
1156static const char implicit_ident_advice_config[] =
1157N_("Your name and email address were configured automatically based\n"
1158"on your username and hostname. Please check that they are accurate.\n"
1159"You can suppress this message by setting them explicitly:\n"
1160"\n"
1161" git config --global user.name \"Your Name\"\n"
1162" git config --global user.email you@example.com\n"
1163"\n"
1164"After doing this, you may fix the identity used for this commit with:\n"
1165"\n"
1166" git commit --amend --reset-author\n");
1167
1168static const char *implicit_ident_advice(void)
1169{
1170 char *user_config = expand_user_path("~/.gitconfig", 0);
1171 char *xdg_config = xdg_config_home("config");
1172 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1173
1174 free(user_config);
1175 free(xdg_config);
1176
1177 if (config_exists)
1178 return _(implicit_ident_advice_config);
1179 else
1180 return _(implicit_ident_advice_noconfig);
1181
1182}
1183
f11c9580
NTND
1184void print_commit_summary(struct repository *r,
1185 const char *prefix,
1186 const struct object_id *oid,
e47c6caf
PW
1187 unsigned int flags)
1188{
1189 struct rev_info rev;
1190 struct commit *commit;
1191 struct strbuf format = STRBUF_INIT;
1192 const char *head;
1193 struct pretty_print_context pctx = {0};
1194 struct strbuf author_ident = STRBUF_INIT;
1195 struct strbuf committer_ident = STRBUF_INIT;
1196
f11c9580 1197 commit = lookup_commit(r, oid);
e47c6caf
PW
1198 if (!commit)
1199 die(_("couldn't look up newly created commit"));
1200 if (parse_commit(commit))
1201 die(_("could not parse newly created commit"));
1202
1203 strbuf_addstr(&format, "format:%h] %s");
1204
1205 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1206 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1207 if (strbuf_cmp(&author_ident, &committer_ident)) {
1208 strbuf_addstr(&format, "\n Author: ");
1209 strbuf_addbuf_percentquote(&format, &author_ident);
1210 }
1211 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1212 struct strbuf date = STRBUF_INIT;
1213
1214 format_commit_message(commit, "%ad", &date, &pctx);
1215 strbuf_addstr(&format, "\n Date: ");
1216 strbuf_addbuf_percentquote(&format, &date);
1217 strbuf_release(&date);
1218 }
1219 if (!committer_ident_sufficiently_given()) {
1220 strbuf_addstr(&format, "\n Committer: ");
1221 strbuf_addbuf_percentquote(&format, &committer_ident);
1222 if (advice_implicit_identity) {
1223 strbuf_addch(&format, '\n');
1224 strbuf_addstr(&format, implicit_ident_advice());
1225 }
1226 }
1227 strbuf_release(&author_ident);
1228 strbuf_release(&committer_ident);
1229
f11c9580 1230 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1231 setup_revisions(0, NULL, &rev, NULL);
1232
1233 rev.diff = 1;
1234 rev.diffopt.output_format =
1235 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1236
1237 rev.verbose_header = 1;
1238 rev.show_root_diff = 1;
1239 get_commit_format(format.buf, &rev);
1240 rev.always_show_header = 0;
0f57f731 1241 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1242 rev.diffopt.break_opt = 0;
1243 diff_setup_done(&rev.diffopt);
1244
1245 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1246 if (!head)
1247 die_errno(_("unable to resolve HEAD after creating commit"));
1248 if (!strcmp(head, "HEAD"))
1249 head = _("detached HEAD");
1250 else
1251 skip_prefix(head, "refs/heads/", &head);
1252 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1253 _(" (root-commit)") : "");
1254
1255 if (!log_tree_commit(&rev, commit)) {
1256 rev.always_show_header = 1;
1257 rev.use_terminator = 1;
1258 log_tree_commit(&rev, commit);
1259 }
1260
1261 strbuf_release(&format);
1262}
1263
005af339 1264static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1265{
1266 struct commit *current_head;
1267 struct object_id oid;
1268
1269 if (get_oid("HEAD", &oid)) {
1270 current_head = NULL;
1271 } else {
005af339 1272 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1273 if (!current_head)
1274 return error(_("could not parse HEAD"));
9001dc2a 1275 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1276 warning(_("HEAD %s is not a commit!"),
1277 oid_to_hex(&oid));
1278 }
1279 if (parse_commit(current_head))
1280 return error(_("could not parse HEAD commit"));
1281 }
1282 *head = current_head;
1283
1284 return 0;
1285}
1286
1287/*
1288 * Try to commit without forking 'git commit'. In some cases we need
1289 * to run 'git commit' to display an error message
1290 *
1291 * Returns:
1292 * -1 - error unable to commit
1293 * 0 - success
1294 * 1 - run 'git commit'
1295 */
f11c9580
NTND
1296static int try_to_commit(struct repository *r,
1297 struct strbuf *msg, const char *author,
356ee465
PW
1298 struct replay_opts *opts, unsigned int flags,
1299 struct object_id *oid)
1300{
1301 struct object_id tree;
b0a31861 1302 struct commit *current_head = NULL;
356ee465
PW
1303 struct commit_list *parents = NULL;
1304 struct commit_extra_header *extra = NULL;
1305 struct strbuf err = STRBUF_INIT;
66618a50 1306 struct strbuf commit_msg = STRBUF_INIT;
4d924528 1307 char *amend_author = NULL;
66618a50 1308 const char *hook_commit = NULL;
356ee465
PW
1309 enum commit_msg_cleanup_mode cleanup;
1310 int res = 0;
1311
005af339 1312 if (parse_head(r, &current_head))
356ee465 1313 return -1;
4d924528 1314
356ee465
PW
1315 if (flags & AMEND_MSG) {
1316 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1317 const char *out_enc = get_commit_output_encoding();
1318 const char *message = logmsg_reencode(current_head, NULL,
1319 out_enc);
1320
1321 if (!msg) {
1322 const char *orig_message = NULL;
1323
1324 find_commit_subject(message, &orig_message);
66618a50 1325 msg = &commit_msg;
356ee465 1326 strbuf_addstr(msg, orig_message);
66618a50 1327 hook_commit = "HEAD";
356ee465 1328 }
4d924528 1329 author = amend_author = get_author(message);
356ee465
PW
1330 unuse_commit_buffer(current_head, message);
1331 if (!author) {
1332 res = error(_("unable to parse commit author"));
1333 goto out;
1334 }
1335 parents = copy_commit_list(current_head->parents);
1336 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
b0a31861
PW
1337 } else if (current_head &&
1338 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
356ee465
PW
1339 commit_list_insert(current_head, &parents);
1340 }
1341
f11c9580 1342 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1343 res = error(_("git write-tree failed to write a tree"));
1344 goto out;
1345 }
1346
2d05ef27
PW
1347 if (!(flags & ALLOW_EMPTY)) {
1348 struct commit *first_parent = current_head;
1349
1350 if (flags & AMEND_MSG) {
1351 if (current_head->parents) {
1352 first_parent = current_head->parents->item;
1353 if (repo_parse_commit(r, first_parent)) {
1354 res = error(_("could not parse HEAD commit"));
1355 goto out;
1356 }
1357 } else {
1358 first_parent = NULL;
1359 }
1360 }
1361 if (oideq(first_parent
1362 ? get_commit_tree_oid(first_parent)
1363 : the_hash_algo->empty_tree,
1364 &tree)) {
1365 res = 1; /* run 'git commit' to display error message */
1366 goto out;
1367 }
356ee465
PW
1368 }
1369
66618a50 1370 if (find_hook("prepare-commit-msg")) {
f11c9580 1371 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1372 if (res)
1373 goto out;
1374 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1375 2048) < 0) {
1376 res = error_errno(_("unable to read commit message "
1377 "from '%s'"),
1378 git_path_commit_editmsg());
1379 goto out;
1380 }
1381 msg = &commit_msg;
1382 }
1383
d74f3e58
PW
1384 if (flags & CLEANUP_MSG)
1385 cleanup = COMMIT_MSG_CLEANUP_ALL;
1386 else if ((opts->signoff || opts->record_origin) &&
1387 !opts->explicit_cleanup)
1388 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1389 else
1390 cleanup = opts->default_msg_cleanup;
66618a50
PW
1391
1392 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1393 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1394 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1395 res = 1; /* run 'git commit' to display error message */
1396 goto out;
1397 }
1398
12f7babd
JS
1399 reset_ident_date();
1400
8be8342b
JH
1401 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1402 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1403 res = error(_("failed to write commit object"));
1404 goto out;
1405 }
1406
1407 if (update_head_with_reflog(current_head, oid,
1408 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1409 res = error("%s", err.buf);
1410 goto out;
1411 }
1412
4627bc77 1413 run_commit_hook(0, r->index_file, "post-commit", NULL);
356ee465 1414 if (flags & AMEND_MSG)
1d18d758 1415 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1416
1417out:
1418 free_commit_extra_headers(extra);
1419 strbuf_release(&err);
66618a50 1420 strbuf_release(&commit_msg);
4d924528 1421 free(amend_author);
356ee465
PW
1422
1423 return res;
1424}
1425
f11c9580
NTND
1426static int do_commit(struct repository *r,
1427 const char *msg_file, const char *author,
356ee465
PW
1428 struct replay_opts *opts, unsigned int flags)
1429{
1430 int res = 1;
1431
b0a31861 1432 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
356ee465
PW
1433 struct object_id oid;
1434 struct strbuf sb = STRBUF_INIT;
1435
1436 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1437 return error_errno(_("unable to read commit message "
1438 "from '%s'"),
1439 msg_file);
1440
f11c9580
NTND
1441 res = try_to_commit(r, msg_file ? &sb : NULL,
1442 author, opts, flags, &oid);
356ee465
PW
1443 strbuf_release(&sb);
1444 if (!res) {
f11c9580
NTND
1445 unlink(git_path_cherry_pick_head(r));
1446 unlink(git_path_merge_msg(r));
356ee465 1447 if (!is_rebase_i(opts))
f11c9580 1448 print_commit_summary(r, NULL, &oid,
356ee465
PW
1449 SUMMARY_SHOW_AUTHOR_DATE);
1450 return res;
1451 }
1452 }
1453 if (res == 1)
f11c9580 1454 return run_git_commit(r, msg_file, opts, flags);
356ee465
PW
1455
1456 return res;
1457}
1458
b27cfb0d
NH
1459static int is_original_commit_empty(struct commit *commit)
1460{
092bbcdf 1461 const struct object_id *ptree_oid;
b27cfb0d
NH
1462
1463 if (parse_commit(commit))
aee42e1f 1464 return error(_("could not parse commit %s"),
f2fd0760 1465 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1466 if (commit->parents) {
1467 struct commit *parent = commit->parents->item;
1468 if (parse_commit(parent))
aee42e1f 1469 return error(_("could not parse parent commit %s"),
f2fd0760 1470 oid_to_hex(&parent->object.oid));
2e27bd77 1471 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1472 } else {
eb0ccfd7 1473 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1474 }
043a4492 1475
4a7e27e9 1476 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1477}
1478
ac2b0e8f 1479/*
e98c4269
EN
1480 * Should empty commits be allowed? Return status:
1481 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1482 * 0: Halt on empty commit
1483 * 1: Allow empty commit
1484 * 2: Drop empty commit
ac2b0e8f 1485 */
f11c9580
NTND
1486static int allow_empty(struct repository *r,
1487 struct replay_opts *opts,
1488 struct commit *commit)
ac2b0e8f 1489{
d48e5e21 1490 int index_unchanged, originally_empty;
ac2b0e8f
JH
1491
1492 /*
e98c4269 1493 * Four cases:
ac2b0e8f
JH
1494 *
1495 * (1) we do not allow empty at all and error out.
1496 *
e98c4269
EN
1497 * (2) we allow ones that were initially empty, and
1498 * just drop the ones that become empty
ac2b0e8f 1499 *
e98c4269
EN
1500 * (3) we allow ones that were initially empty, but
1501 * halt for the ones that become empty;
1502 *
1503 * (4) we allow both.
ac2b0e8f
JH
1504 */
1505 if (!opts->allow_empty)
1506 return 0; /* let "git commit" barf as necessary */
1507
005af339 1508 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1509 if (index_unchanged < 0)
1510 return index_unchanged;
1511 if (!index_unchanged)
1512 return 0; /* we do not have to say --allow-empty */
1513
1514 if (opts->keep_redundant_commits)
1515 return 1;
1516
d48e5e21
EN
1517 originally_empty = is_original_commit_empty(commit);
1518 if (originally_empty < 0)
1519 return originally_empty;
e98c4269 1520 if (originally_empty)
ac2b0e8f 1521 return 1;
e98c4269
EN
1522 else if (opts->drop_redundant_commits)
1523 return 2;
1524 else
1525 return 0;
ac2b0e8f
JH
1526}
1527
414697a9
JS
1528static struct {
1529 char c;
1530 const char *str;
1531} todo_command_info[] = {
1532 { 'p', "pick" },
1533 { 0, "revert" },
1534 { 'e', "edit" },
04efc8b5 1535 { 'r', "reword" },
414697a9
JS
1536 { 'f', "fixup" },
1537 { 's', "squash" },
1538 { 'x', "exec" },
71f82465 1539 { 'b', "break" },
9055e401
JS
1540 { 'l', "label" },
1541 { 't', "reset" },
4c68e7dd 1542 { 'm', "merge" },
b3fdd581 1543 { 0, "noop" },
ac191470
JS
1544 { 'd', "drop" },
1545 { 0, NULL }
004fefa7
JS
1546};
1547
1548static const char *command_to_string(const enum todo_command command)
1549{
ac191470 1550 if (command < TODO_COMMENT)
414697a9 1551 return todo_command_info[command].str;
02127c63 1552 die(_("unknown command: %d"), command);
004fefa7
JS
1553}
1554
ee5462d6 1555static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1556{
1557 if (command < TODO_COMMENT && todo_command_info[command].c)
1558 return todo_command_info[command].c;
1559 return comment_line_char;
1560}
1561
25c43667
JS
1562static int is_noop(const enum todo_command command)
1563{
b3fdd581 1564 return TODO_NOOP <= command;
25c43667 1565}
004fefa7 1566
6e98de72
JS
1567static int is_fixup(enum todo_command command)
1568{
1569 return command == TODO_FIXUP || command == TODO_SQUASH;
1570}
1571
d87d48b2
JS
1572/* Does this command create a (non-merge) commit? */
1573static int is_pick_or_similar(enum todo_command command)
1574{
1575 switch (command) {
1576 case TODO_PICK:
1577 case TODO_REVERT:
1578 case TODO_EDIT:
1579 case TODO_REWORD:
1580 case TODO_FIXUP:
1581 case TODO_SQUASH:
1582 return 1;
1583 default:
1584 return 0;
1585 }
1586}
1587
005af339
NTND
1588static int update_squash_messages(struct repository *r,
1589 enum todo_command command,
1590 struct commit *commit,
1591 struct replay_opts *opts)
6e98de72
JS
1592{
1593 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1594 int res;
6e98de72 1595 const char *message, *body;
b3757442 1596 const char *encoding = get_commit_output_encoding();
6e98de72 1597
e12a7ef5 1598 if (opts->current_fixup_count > 0) {
6e98de72 1599 struct strbuf header = STRBUF_INIT;
e12a7ef5 1600 char *eol;
6e98de72 1601
e12a7ef5 1602 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1603 return error(_("could not read '%s'"),
1604 rebase_path_squash_msg());
1605
e12a7ef5
JS
1606 eol = buf.buf[0] != comment_line_char ?
1607 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1608
1609 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1610 strbuf_addf(&header, _("This is a combination of %d commits."),
1611 opts->current_fixup_count + 2);
6e98de72
JS
1612 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1613 strbuf_release(&header);
1614 } else {
33d66df3 1615 struct object_id head;
6e98de72
JS
1616 struct commit *head_commit;
1617 const char *head_message, *body;
1618
33d66df3 1619 if (get_oid("HEAD", &head))
6e98de72 1620 return error(_("need a HEAD to fixup"));
005af339 1621 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72 1622 return error(_("could not read HEAD"));
b3757442 1623 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
6e98de72
JS
1624 return error(_("could not read HEAD's commit message"));
1625
1626 find_commit_subject(head_message, &body);
1627 if (write_message(body, strlen(body),
1628 rebase_path_fixup_msg(), 0)) {
1629 unuse_commit_buffer(head_commit, head_message);
1630 return error(_("cannot write '%s'"),
1631 rebase_path_fixup_msg());
1632 }
1633
6e98de72 1634 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1635 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1636 strbuf_addf(&buf, "\n%c ", comment_line_char);
1637 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1638 strbuf_addstr(&buf, "\n\n");
1639 strbuf_addstr(&buf, body);
1640
1641 unuse_commit_buffer(head_commit, head_message);
1642 }
1643
b3757442 1644 if (!(message = logmsg_reencode(commit, NULL, encoding)))
6e98de72
JS
1645 return error(_("could not read commit message of %s"),
1646 oid_to_hex(&commit->object.oid));
1647 find_commit_subject(message, &body);
1648
1649 if (command == TODO_SQUASH) {
1650 unlink(rebase_path_fixup_msg());
1651 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1652 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1653 ++opts->current_fixup_count + 1);
6e98de72
JS
1654 strbuf_addstr(&buf, "\n\n");
1655 strbuf_addstr(&buf, body);
1656 } else if (command == TODO_FIXUP) {
1657 strbuf_addf(&buf, "\n%c ", comment_line_char);
1658 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1659 ++opts->current_fixup_count + 1);
6e98de72
JS
1660 strbuf_addstr(&buf, "\n\n");
1661 strbuf_add_commented_lines(&buf, body, strlen(body));
1662 } else
1663 return error(_("unknown command: %d"), command);
1664 unuse_commit_buffer(commit, message);
1665
1666 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1667 strbuf_release(&buf);
e12a7ef5
JS
1668
1669 if (!res) {
1670 strbuf_addf(&opts->current_fixups, "%s%s %s",
1671 opts->current_fixups.len ? "\n" : "",
1672 command_to_string(command),
1673 oid_to_hex(&commit->object.oid));
1674 res = write_message(opts->current_fixups.buf,
1675 opts->current_fixups.len,
1676 rebase_path_current_fixups(), 0);
1677 }
1678
6e98de72
JS
1679 return res;
1680}
1681
3b335762
NTND
1682static void flush_rewritten_pending(void)
1683{
25cb8df9 1684 struct strbuf buf = STRBUF_INIT;
092bbcdf 1685 struct object_id newoid;
25cb8df9
JS
1686 FILE *out;
1687
092bbcdf 1688 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1689 !get_oid("HEAD", &newoid) &&
e9d983f1 1690 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1691 char *bol = buf.buf, *eol;
1692
1693 while (*bol) {
1694 eol = strchrnul(bol, '\n');
1695 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1696 bol, oid_to_hex(&newoid));
25cb8df9
JS
1697 if (!*eol)
1698 break;
1699 bol = eol + 1;
1700 }
1701 fclose(out);
1702 unlink(rebase_path_rewritten_pending());
1703 }
1704 strbuf_release(&buf);
1705}
1706
1707static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
1708 enum todo_command next_command)
1709{
e9d983f1 1710 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1711
1712 if (!out)
1713 return;
1714
1715 fprintf(out, "%s\n", oid_to_hex(oid));
1716 fclose(out);
1717
1718 if (!is_fixup(next_command))
1719 flush_rewritten_pending();
1720}
1721
f11c9580
NTND
1722static int do_pick_commit(struct repository *r,
1723 enum todo_command command,
1724 struct commit *commit,
1725 struct replay_opts *opts,
a47ba3c7 1726 int final_fixup, int *check_todo)
043a4492 1727{
789b3eff 1728 unsigned int flags = opts->edit ? EDIT_MSG : 0;
f11c9580 1729 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
ace976b2 1730 struct object_id head;
043a4492
RR
1731 struct commit *base, *next, *parent;
1732 const char *base_label, *next_label;
356ee465 1733 char *author = NULL;
d74a4e57 1734 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1735 struct strbuf msgbuf = STRBUF_INIT;
e98c4269 1736 int res, unborn = 0, reword = 0, allow, drop_commit;
043a4492
RR
1737
1738 if (opts->no_commit) {
1739 /*
1740 * We do not intend to commit immediately. We just want to
1741 * merge the differences in, so let's compute the tree
1742 * that represents the "current" state for merge-recursive
1743 * to work on.
1744 */
f11c9580 1745 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 1746 return error(_("your index file is unmerged."));
043a4492 1747 } else {
ace976b2 1748 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1749 /* Do we want to generate a root commit? */
1750 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 1751 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
1752 if (is_fixup(command))
1753 return error(_("cannot fixup root commit"));
1754 flags |= CREATE_ROOT_COMMIT;
1755 unborn = 1;
1756 } else if (unborn)
eb0ccfd7 1757 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 1758 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1759 NULL, 0))
e1ff0a32 1760 return error_dirty_index(r, opts);
043a4492 1761 }
f11c9580 1762 discard_index(r->index);
043a4492 1763
637666c8 1764 if (!commit->parents)
043a4492 1765 parent = NULL;
043a4492
RR
1766 else if (commit->parents->next) {
1767 /* Reverting or cherry-picking a merge commit */
1768 int cnt;
1769 struct commit_list *p;
1770
1771 if (!opts->mainline)
93b3df6f 1772 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1773 oid_to_hex(&commit->object.oid));
043a4492
RR
1774
1775 for (cnt = 1, p = commit->parents;
1776 cnt != opts->mainline && p;
1777 cnt++)
1778 p = p->next;
1779 if (cnt != opts->mainline || !p)
93b3df6f 1780 return error(_("commit %s does not have parent %d"),
f2fd0760 1781 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 1782 parent = p->item;
37897bfc
SO
1783 } else if (1 < opts->mainline)
1784 /*
1785 * Non-first parent explicitly specified as mainline for
1786 * non-merge commit
1787 */
1788 return error(_("commit %s does not have parent %d"),
1789 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1790 else
1791 parent = commit->parents->item;
1792
bcbb68be
JS
1793 if (get_message(commit, &msg) != 0)
1794 return error(_("cannot get commit message for %s"),
1795 oid_to_hex(&commit->object.oid));
1796
6e98de72 1797 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 1798 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
1799 (!parent && unborn))) {
1800 if (is_rebase_i(opts))
1801 write_author_script(msg.message);
f11c9580 1802 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
1803 opts);
1804 if (res || command != TODO_REWORD)
1805 goto leave;
450efe2d 1806 reword = 1;
bcbb68be
JS
1807 msg_file = NULL;
1808 goto fast_forward_edit;
1809 }
043a4492 1810 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1811 /* TRANSLATORS: The first %s will be a "todo" command like
1812 "revert" or "pick", the second %s a SHA1. */
043a4492 1813 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1814 command_to_string(command),
1815 oid_to_hex(&parent->object.oid));
043a4492 1816
043a4492
RR
1817 /*
1818 * "commit" is an existing commit. We would want to apply
1819 * the difference it introduces since its first parent "prev"
1820 * on top of the current HEAD if we are cherry-pick. Or the
1821 * reverse of it if we are revert.
1822 */
1823
004fefa7 1824 if (command == TODO_REVERT) {
043a4492
RR
1825 base = commit;
1826 base_label = msg.label;
1827 next = parent;
1828 next_label = msg.parent_label;
1829 strbuf_addstr(&msgbuf, "Revert \"");
1830 strbuf_addstr(&msgbuf, msg.subject);
1831 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1832 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1833
1834 if (commit->parents && commit->parents->next) {
1835 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1836 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1837 }
1838 strbuf_addstr(&msgbuf, ".\n");
1839 } else {
1840 const char *p;
1841
1842 base = parent;
1843 base_label = msg.parent_label;
1844 next = commit;
1845 next_label = msg.label;
1846
23aa5142
JS
1847 /* Append the commit log message to msgbuf. */
1848 if (find_commit_subject(msg.message, &p))
1849 strbuf_addstr(&msgbuf, p);
043a4492
RR
1850
1851 if (opts->record_origin) {
44dc738a 1852 strbuf_complete_line(&msgbuf);
bab4d109 1853 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1854 strbuf_addch(&msgbuf, '\n');
cd650a4e 1855 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1856 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1857 strbuf_addstr(&msgbuf, ")\n");
1858 }
356ee465
PW
1859 if (!is_fixup(command))
1860 author = get_author(msg.message);
043a4492
RR
1861 }
1862
04efc8b5 1863 if (command == TODO_REWORD)
450efe2d 1864 reword = 1;
04efc8b5 1865 else if (is_fixup(command)) {
005af339 1866 if (update_squash_messages(r, command, commit, opts))
6e98de72 1867 return -1;
789b3eff 1868 flags |= AMEND_MSG;
6e98de72
JS
1869 if (!final_fixup)
1870 msg_file = rebase_path_squash_msg();
1871 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1872 flags |= CLEANUP_MSG;
6e98de72
JS
1873 msg_file = rebase_path_fixup_msg();
1874 } else {
f11c9580 1875 const char *dest = git_path_squash_msg(r);
6e98de72
JS
1876 unlink(dest);
1877 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1878 return error(_("could not rename '%s' to '%s'"),
1879 rebase_path_squash_msg(), dest);
f11c9580 1880 unlink(git_path_merge_msg(r));
6e98de72 1881 msg_file = dest;
789b3eff 1882 flags |= EDIT_MSG;
6e98de72
JS
1883 }
1884 }
1885
a852ec7f 1886 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1887 append_signoff(&msgbuf, 0, 0);
1888
0473f28a
JS
1889 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1890 res = -1;
1891 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
f11c9580 1892 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 1893 &head, &msgbuf, opts);
f241ff0d 1894 if (res < 0)
19517fb9
SB
1895 goto leave;
1896
75871495 1897 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 1898 git_path_merge_msg(r), 0);
043a4492
RR
1899 } else {
1900 struct commit_list *common = NULL;
1901 struct commit_list *remotes = NULL;
1902
75871495 1903 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 1904 git_path_merge_msg(r), 0);
043a4492
RR
1905
1906 commit_list_insert(base, &common);
1907 commit_list_insert(next, &remotes);
f11c9580 1908 res |= try_merge_command(r, opts->strategy,
03a4e260 1909 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1910 common, oid_to_hex(&head), remotes);
043a4492
RR
1911 free_commit_list(common);
1912 free_commit_list(remotes);
1913 }
452202c7 1914 strbuf_release(&msgbuf);
043a4492
RR
1915
1916 /*
1917 * If the merge was clean or if it failed due to conflict, we write
1918 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1919 * However, if the merge did not even start, then we don't want to
1920 * write it at all.
1921 */
004fefa7 1922 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1923 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 1924 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1925 res = -1;
004fefa7 1926 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 1927 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 1928 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1929 res = -1;
043a4492
RR
1930
1931 if (res) {
004fefa7 1932 error(command == TODO_REVERT
043a4492
RR
1933 ? _("could not revert %s... %s")
1934 : _("could not apply %s... %s"),
39755964 1935 short_commit_name(commit), msg.subject);
005af339 1936 print_advice(r, res == 1, opts);
f11c9580 1937 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 1938 goto leave;
043a4492
RR
1939 }
1940
e98c4269 1941 drop_commit = 0;
f11c9580 1942 allow = allow_empty(r, opts, commit);
706728a3
FC
1943 if (allow < 0) {
1944 res = allow;
1945 goto leave;
e98c4269 1946 } else if (allow == 1) {
789b3eff 1947 flags |= ALLOW_EMPTY;
e98c4269
EN
1948 } else if (allow == 2) {
1949 drop_commit = 1;
9a1b7474
EN
1950 unlink(git_path_cherry_pick_head(r));
1951 unlink(git_path_merge_msg(r));
e98c4269
EN
1952 fprintf(stderr,
1953 _("dropping %s %s -- patch contents already upstream\n"),
1954 oid_to_hex(&commit->object.oid), msg.subject);
1955 } /* else allow == 0 and there's nothing special to do */
1956 if (!opts->no_commit && !drop_commit) {
356ee465 1957 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
f11c9580 1958 res = do_commit(r, msg_file, author, opts, flags);
356ee465
PW
1959 else
1960 res = error(_("unable to parse commit author"));
a47ba3c7
PW
1961 *check_todo = !!(flags & EDIT_MSG);
1962 if (!res && reword) {
450efe2d
PW
1963fast_forward_edit:
1964 res = run_git_commit(r, NULL, opts, EDIT_MSG |
1965 VERIFY_MSG | AMEND_MSG |
1966 (flags & ALLOW_EMPTY));
a47ba3c7
PW
1967 *check_todo = 1;
1968 }
356ee465 1969 }
6e98de72 1970
450efe2d 1971
6e98de72
JS
1972 if (!res && final_fixup) {
1973 unlink(rebase_path_fixup_msg());
1974 unlink(rebase_path_squash_msg());
e12a7ef5
JS
1975 unlink(rebase_path_current_fixups());
1976 strbuf_reset(&opts->current_fixups);
1977 opts->current_fixup_count = 0;
6e98de72 1978 }
c8d1351d
FC
1979
1980leave:
d74a4e57 1981 free_message(commit, &msg);
356ee465 1982 free(author);
1e41229d 1983 update_abort_safety_file();
043a4492
RR
1984
1985 return res;
1986}
1987
c3e8618c 1988static int prepare_revs(struct replay_opts *opts)
043a4492 1989{
a73e22e9
MZ
1990 /*
1991 * picking (but not reverting) ranges (but not individual revisions)
1992 * should be done in reverse
1993 */
1994 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
1995 opts->revs->reverse ^= 1;
1996
1997 if (prepare_revision_walk(opts->revs))
c3e8618c 1998 return error(_("revision walk setup failed"));
043a4492 1999
c3e8618c 2000 return 0;
043a4492
RR
2001}
2002
f11c9580
NTND
2003static int read_and_refresh_cache(struct repository *r,
2004 struct replay_opts *opts)
043a4492 2005{
14bca6c6 2006 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2007 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2008 if (repo_read_index(r) < 0) {
49fb937e 2009 rollback_lock_file(&index_lock);
0d9c6dc9 2010 return error(_("git %s: failed to read the index"),
c28cbc5e 2011 _(action_name(opts)));
49fb937e 2012 }
f11c9580 2013 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814 2014 if (index_fd >= 0) {
f11c9580 2015 if (write_locked_index(r->index, &index_lock,
61000814 2016 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2017 return error(_("git %s: failed to refresh the index"),
c28cbc5e 2018 _(action_name(opts)));
49fb937e 2019 }
043a4492 2020 }
0d9c6dc9 2021 return 0;
043a4492
RR
2022}
2023
4c68e7dd
JS
2024enum todo_item_flags {
2025 TODO_EDIT_MERGE_MSG = 1
2026};
2027
5d94d545 2028void todo_list_release(struct todo_list *todo_list)
043a4492 2029{
004fefa7 2030 strbuf_release(&todo_list->buf);
6a83d902 2031 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2032 todo_list->nr = todo_list->alloc = 0;
2033}
043a4492 2034
004fefa7
JS
2035static struct todo_item *append_new_todo(struct todo_list *todo_list)
2036{
2037 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
8638114e 2038 todo_list->total_nr++;
004fefa7 2039 return todo_list->items + todo_list->nr++;
043a4492
RR
2040}
2041
6ad656db
AG
2042const char *todo_item_get_arg(struct todo_list *todo_list,
2043 struct todo_item *item)
2044{
2045 return todo_list->buf.buf + item->arg_offset;
2046}
2047
3e81bccd
PW
2048static int is_command(enum todo_command command, const char **bol)
2049{
2050 const char *str = todo_command_info[command].str;
2051 const char nick = todo_command_info[command].c;
2052 const char *p = *bol + 1;
2053
2054 return skip_prefix(*bol, str, bol) ||
2055 ((nick && **bol == nick) &&
2056 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2057 (*bol = p));
2058}
2059
005af339 2060static int parse_insn_line(struct repository *r, struct todo_item *item,
6ad656db 2061 const char *buf, const char *bol, char *eol)
043a4492 2062{
1e43ed98 2063 struct object_id commit_oid;
043a4492 2064 char *end_of_object_name;
004fefa7
JS
2065 int i, saved, status, padding;
2066
4c68e7dd
JS
2067 item->flags = 0;
2068
8f8550b3
JS
2069 /* left-trim */
2070 bol += strspn(bol, " \t");
2071
25c43667 2072 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2073 item->command = TODO_COMMENT;
25c43667 2074 item->commit = NULL;
6ad656db 2075 item->arg_offset = bol - buf;
25c43667
JS
2076 item->arg_len = eol - bol;
2077 return 0;
2078 }
2079
ac191470 2080 for (i = 0; i < TODO_COMMENT; i++)
3e81bccd 2081 if (is_command(i, &bol)) {
004fefa7
JS
2082 item->command = i;
2083 break;
2084 }
ac191470 2085 if (i >= TODO_COMMENT)
004fefa7 2086 return -1;
043a4492 2087
66afa24f
JS
2088 /* Eat up extra spaces/ tabs before object name */
2089 padding = strspn(bol, " \t");
2090 bol += padding;
2091
71f82465 2092 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2093 if (bol != eol)
2094 return error(_("%s does not accept arguments: '%s'"),
2095 command_to_string(item->command), bol);
25c43667 2096 item->commit = NULL;
6ad656db 2097 item->arg_offset = bol - buf;
25c43667
JS
2098 item->arg_len = eol - bol;
2099 return 0;
2100 }
2101
043a4492 2102 if (!padding)
66afa24f
JS
2103 return error(_("missing arguments for %s"),
2104 command_to_string(item->command));
043a4492 2105
9055e401
JS
2106 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2107 item->command == TODO_RESET) {
7dcbb3cb 2108 item->commit = NULL;
6ad656db 2109 item->arg_offset = bol - buf;
311af526
JS
2110 item->arg_len = (int)(eol - bol);
2111 return 0;
2112 }
2113
4c68e7dd
JS
2114 if (item->command == TODO_MERGE) {
2115 if (skip_prefix(bol, "-C", &bol))
2116 bol += strspn(bol, " \t");
2117 else if (skip_prefix(bol, "-c", &bol)) {
2118 bol += strspn(bol, " \t");
2119 item->flags |= TODO_EDIT_MERGE_MSG;
2120 } else {
2121 item->flags |= TODO_EDIT_MERGE_MSG;
2122 item->commit = NULL;
6ad656db 2123 item->arg_offset = bol - buf;
4c68e7dd
JS
2124 item->arg_len = (int)(eol - bol);
2125 return 0;
2126 }
2127 }
2128
004fefa7 2129 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2130 saved = *end_of_object_name;
2131 *end_of_object_name = '\0';
1e43ed98 2132 status = get_oid(bol, &commit_oid);
d859dcad
JS
2133 if (status < 0)
2134 error(_("could not parse '%s'"), bol); /* return later */
043a4492
RR
2135 *end_of_object_name = saved;
2136
6ad656db
AG
2137 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2138 item->arg_offset = bol - buf;
2139 item->arg_len = (int)(eol - bol);
c22f7dfb 2140
043a4492 2141 if (status < 0)
d859dcad 2142 return status;
043a4492 2143
005af339 2144 item->commit = lookup_commit_reference(r, &commit_oid);
d859dcad 2145 return item->commit ? 0 : -1;
043a4492
RR
2146}
2147
4a72486d
PW
2148int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2149{
ed5b1ca1 2150 const char *todo_file, *bol;
4a72486d 2151 struct strbuf buf = STRBUF_INIT;
ed5b1ca1 2152 int ret = 0;
4a72486d
PW
2153
2154 todo_file = git_path_todo_file();
2155 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
ed5b1ca1 2156 if (errno == ENOENT || errno == ENOTDIR)
4a72486d
PW
2157 return -1;
2158 else
2159 return error_errno("unable to open '%s'", todo_file);
2160 }
ed5b1ca1
PW
2161 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2162 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
4a72486d 2163 *action = REPLAY_PICK;
ed5b1ca1
PW
2164 else if (is_command(TODO_REVERT, &bol) &&
2165 (*bol == ' ' || *bol == '\t'))
4a72486d
PW
2166 *action = REPLAY_REVERT;
2167 else
ed5b1ca1 2168 ret = -1;
4a72486d 2169
4a72486d
PW
2170 strbuf_release(&buf);
2171
2172 return ret;
2173}
2174
5d94d545
AG
2175int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2176 struct todo_list *todo_list)
043a4492 2177{
004fefa7
JS
2178 struct todo_item *item;
2179 char *p = buf, *next_p;
6e98de72 2180 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2181
2b71595d
AG
2182 todo_list->current = todo_list->nr = 0;
2183
004fefa7 2184 for (i = 1; *p; i++, p = next_p) {
043a4492 2185 char *eol = strchrnul(p, '\n');
004fefa7
JS
2186
2187 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2188
6307041d
JS
2189 if (p != eol && eol[-1] == '\r')
2190 eol--; /* strip Carriage Return */
2191
004fefa7
JS
2192 item = append_new_todo(todo_list);
2193 item->offset_in_buf = p - todo_list->buf.buf;
6ad656db 2194 if (parse_insn_line(r, item, buf, p, eol)) {
93b3df6f 2195 res = error(_("invalid line %d: %.*s"),
004fefa7 2196 i, (int)(eol - p), p);
2b71595d 2197 item->command = TODO_COMMENT + 1;
6ad656db 2198 item->arg_offset = p - buf;
2b71595d
AG
2199 item->arg_len = (int)(eol - p);
2200 item->commit = NULL;
004fefa7 2201 }
6e98de72
JS
2202
2203 if (fixup_okay)
2204 ; /* do nothing */
2205 else if (is_fixup(item->command))
2206 return error(_("cannot '%s' without a previous commit"),
2207 command_to_string(item->command));
2208 else if (!is_noop(item->command))
2209 fixup_okay = 1;
043a4492 2210 }
52865279 2211
004fefa7 2212 return res;
043a4492
RR
2213}
2214
968492e4
JS
2215static int count_commands(struct todo_list *todo_list)
2216{
2217 int count = 0, i;
2218
2219 for (i = 0; i < todo_list->nr; i++)
2220 if (todo_list->items[i].command != TODO_COMMENT)
2221 count++;
2222
2223 return count;
2224}
2225
a01c2a5f
JS
2226static int get_item_line_offset(struct todo_list *todo_list, int index)
2227{
2228 return index < todo_list->nr ?
2229 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2230}
2231
2232static const char *get_item_line(struct todo_list *todo_list, int index)
2233{
2234 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2235}
2236
2237static int get_item_line_length(struct todo_list *todo_list, int index)
2238{
2239 return get_item_line_offset(todo_list, index + 1)
2240 - get_item_line_offset(todo_list, index);
2241}
2242
87805600
RS
2243static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2244{
2245 int fd;
2246 ssize_t len;
2247
2248 fd = open(path, O_RDONLY);
2249 if (fd < 0)
2250 return error_errno(_("could not open '%s'"), path);
2251 len = strbuf_read(sb, fd, 0);
2252 close(fd);
2253 if (len < 0)
2254 return error(_("could not read '%s'."), path);
2255 return len;
2256}
2257
b07d9bfd
PW
2258static int have_finished_the_last_pick(void)
2259{
2260 struct strbuf buf = STRBUF_INIT;
2261 const char *eol;
2262 const char *todo_path = git_path_todo_file();
2263 int ret = 0;
2264
2265 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2266 if (errno == ENOENT) {
2267 return 0;
2268 } else {
2269 error_errno("unable to open '%s'", todo_path);
2270 return 0;
2271 }
2272 }
2273 /* If there is only one line then we are done */
2274 eol = strchr(buf.buf, '\n');
2275 if (!eol || !eol[1])
2276 ret = 1;
2277
2278 strbuf_release(&buf);
2279
2280 return ret;
2281}
2282
f496b064 2283void sequencer_post_commit_cleanup(struct repository *r, int verbose)
b07d9bfd
PW
2284{
2285 struct replay_opts opts = REPLAY_OPTS_INIT;
2286 int need_cleanup = 0;
2287
2288 if (file_exists(git_path_cherry_pick_head(r))) {
f496b064
JH
2289 if (!unlink(git_path_cherry_pick_head(r)) && verbose)
2290 warning(_("cancelling a cherry picking in progress"));
b07d9bfd
PW
2291 opts.action = REPLAY_PICK;
2292 need_cleanup = 1;
2293 }
2294
2295 if (file_exists(git_path_revert_head(r))) {
f496b064
JH
2296 if (!unlink(git_path_revert_head(r)) && verbose)
2297 warning(_("cancelling a revert in progress"));
b07d9bfd
PW
2298 opts.action = REPLAY_REVERT;
2299 need_cleanup = 1;
2300 }
2301
2302 if (!need_cleanup)
2303 return;
2304
2305 if (!have_finished_the_last_pick())
2306 return;
2307
2308 sequencer_remove_state(&opts);
2309}
2310
3f34f2d8
AG
2311static void todo_list_write_total_nr(struct todo_list *todo_list)
2312{
2313 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2314
2315 if (f) {
2316 fprintf(f, "%d\n", todo_list->total_nr);
2317 fclose(f);
2318 }
2319}
2320
005af339
NTND
2321static int read_populate_todo(struct repository *r,
2322 struct todo_list *todo_list,
2323 struct replay_opts *opts)
043a4492 2324{
54fd3243 2325 struct stat st;
c0246501 2326 const char *todo_file = get_todo_path(opts);
87805600 2327 int res;
043a4492 2328
004fefa7 2329 strbuf_reset(&todo_list->buf);
87805600
RS
2330 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2331 return -1;
043a4492 2332
54fd3243
SH
2333 res = stat(todo_file, &st);
2334 if (res)
2335 return error(_("could not stat '%s'"), todo_file);
2336 fill_stat_data(&todo_list->stat, &st);
2337
5d94d545 2338 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2339 if (res) {
2340 if (is_rebase_i(opts))
2341 return error(_("please fix this using "
2342 "'git rebase --edit-todo'."));
93b3df6f 2343 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2344 }
2eeaf1b3 2345
52865279
JS
2346 if (!todo_list->nr &&
2347 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2348 return error(_("no commits parsed."));
2349
2eeaf1b3 2350 if (!is_rebase_i(opts)) {
004fefa7
JS
2351 enum todo_command valid =
2352 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2353 int i;
2354
2355 for (i = 0; i < todo_list->nr; i++)
2356 if (valid == todo_list->items[i].command)
2357 continue;
2358 else if (valid == TODO_PICK)
93b3df6f 2359 return error(_("cannot cherry-pick during a revert."));
004fefa7 2360 else
93b3df6f 2361 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2362 }
2363
968492e4
JS
2364 if (is_rebase_i(opts)) {
2365 struct todo_list done = TODO_LIST_INIT;
2366
2367 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
5d94d545 2368 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2369 todo_list->done_nr = count_commands(&done);
2370 else
2371 todo_list->done_nr = 0;
2372
2373 todo_list->total_nr = todo_list->done_nr
2374 + count_commands(todo_list);
968492e4 2375 todo_list_release(&done);
ef80069a 2376
3f34f2d8 2377 todo_list_write_total_nr(todo_list);
968492e4
JS
2378 }
2379
0ae42a03 2380 return 0;
043a4492
RR
2381}
2382
03a4e260
JS
2383static int git_config_string_dup(char **dest,
2384 const char *var, const char *value)
2385{
2386 if (!value)
2387 return config_error_nonbool(var);
2388 free(*dest);
2389 *dest = xstrdup(value);
2390 return 0;
2391}
2392
043a4492
RR
2393static int populate_opts_cb(const char *key, const char *value, void *data)
2394{
2395 struct replay_opts *opts = data;
2396 int error_flag = 1;
2397
2398 if (!value)
2399 error_flag = 0;
2400 else if (!strcmp(key, "options.no-commit"))
2401 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2402 else if (!strcmp(key, "options.edit"))
2403 opts->edit = git_config_bool_or_int(key, value, &error_flag);
6860ce5d
PW
2404 else if (!strcmp(key, "options.allow-empty"))
2405 opts->allow_empty =
2406 git_config_bool_or_int(key, value, &error_flag);
2407 else if (!strcmp(key, "options.allow-empty-message"))
2408 opts->allow_empty_message =
2409 git_config_bool_or_int(key, value, &error_flag);
2410 else if (!strcmp(key, "options.keep-redundant-commits"))
2411 opts->keep_redundant_commits =
2412 git_config_bool_or_int(key, value, &error_flag);
043a4492
RR
2413 else if (!strcmp(key, "options.signoff"))
2414 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2415 else if (!strcmp(key, "options.record-origin"))
2416 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2417 else if (!strcmp(key, "options.allow-ff"))
2418 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2419 else if (!strcmp(key, "options.mainline"))
2420 opts->mainline = git_config_int(key, value);
2421 else if (!strcmp(key, "options.strategy"))
03a4e260 2422 git_config_string_dup(&opts->strategy, key, value);
3253553e 2423 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2424 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2425 else if (!strcmp(key, "options.strategy-option")) {
2426 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2427 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2428 } else if (!strcmp(key, "options.allow-rerere-auto"))
2429 opts->allow_rerere_auto =
2430 git_config_bool_or_int(key, value, &error_flag) ?
2431 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2432 else if (!strcmp(key, "options.default-msg-cleanup")) {
2433 opts->explicit_cleanup = 1;
2434 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2435 } else
93b3df6f 2436 return error(_("invalid key: %s"), key);
043a4492
RR
2437
2438 if (!error_flag)
93b3df6f 2439 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2440
2441 return 0;
2442}
2443
65850686 2444void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2445{
2446 int i;
65850686 2447 char *strategy_opts_string = raw_opts;
ca6c6b45 2448
0060041d
EN
2449 if (*strategy_opts_string == ' ')
2450 strategy_opts_string++;
65850686 2451
0060041d
EN
2452 opts->xopts_nr = split_cmdline(strategy_opts_string,
2453 (const char ***)&opts->xopts);
ca6c6b45
JS
2454 for (i = 0; i < opts->xopts_nr; i++) {
2455 const char *arg = opts->xopts[i];
2456
2457 skip_prefix(arg, "--", &arg);
2458 opts->xopts[i] = xstrdup(arg);
2459 }
2460}
2461
65850686
AG
2462static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2463{
2464 strbuf_reset(buf);
2465 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2466 return;
2467 opts->strategy = strbuf_detach(buf, NULL);
2468 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2469 return;
2470
2471 parse_strategy_opts(opts, buf->buf);
2472}
2473
5adf9bdc 2474static int read_populate_opts(struct replay_opts *opts)
043a4492 2475{
a1c75762
JS
2476 if (is_rebase_i(opts)) {
2477 struct strbuf buf = STRBUF_INIT;
65c425a2 2478 int ret = 0;
a1c75762 2479
3442c3d1
DL
2480 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2481 READ_ONELINER_SKIP_IF_EMPTY)) {
a1c75762
JS
2482 if (!starts_with(buf.buf, "-S"))
2483 strbuf_reset(&buf);
2484 else {
2485 free(opts->gpg_sign);
2486 opts->gpg_sign = xstrdup(buf.buf + 2);
2487 }
9b6d7a62
PW
2488 strbuf_reset(&buf);
2489 }
2490
3442c3d1
DL
2491 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2492 READ_ONELINER_SKIP_IF_EMPTY)) {
9b6d7a62
PW
2493 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2494 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2495 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2496 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2497 strbuf_reset(&buf);
a1c75762 2498 }
a1c75762 2499
556907f1
JS
2500 if (file_exists(rebase_path_verbose()))
2501 opts->verbose = 1;
2502
899b49c4
EN
2503 if (file_exists(rebase_path_quiet()))
2504 opts->quiet = 1;
2505
a852ec7f
PW
2506 if (file_exists(rebase_path_signoff())) {
2507 opts->allow_ff = 0;
2508 opts->signoff = 1;
2509 }
2510
d421afa0
JS
2511 if (file_exists(rebase_path_reschedule_failed_exec()))
2512 opts->reschedule_failed_exec = 1;
2513
e98c4269
EN
2514 if (file_exists(rebase_path_drop_redundant_commits()))
2515 opts->drop_redundant_commits = 1;
2516
2517 if (file_exists(rebase_path_keep_redundant_commits()))
2518 opts->keep_redundant_commits = 1;
2519
ca6c6b45 2520 read_strategy_opts(opts, &buf);
65c425a2 2521 strbuf_reset(&buf);
ca6c6b45 2522
e12a7ef5 2523 if (read_oneliner(&opts->current_fixups,
3442c3d1
DL
2524 rebase_path_current_fixups(),
2525 READ_ONELINER_SKIP_IF_EMPTY)) {
e12a7ef5
JS
2526 const char *p = opts->current_fixups.buf;
2527 opts->current_fixup_count = 1;
2528 while ((p = strchr(p, '\n'))) {
2529 opts->current_fixup_count++;
2530 p++;
2531 }
2532 }
2533
d87d48b2 2534 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
65c425a2
DL
2535 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0) {
2536 ret = error(_("unusable squash-onto"));
2537 goto done_rebase_i;
2538 }
d87d48b2
JS
2539 opts->have_squash_onto = 1;
2540 }
2541
65c425a2
DL
2542done_rebase_i:
2543 strbuf_release(&buf);
2544 return ret;
a1c75762 2545 }
b5a67045 2546
f932729c 2547 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2548 return 0;
2549 /*
2550 * The function git_parse_source(), called from git_config_from_file(),
2551 * may die() in case of a syntactically incorrect file. We do not care
2552 * about this case, though, because we wrote that file ourselves, so we
2553 * are pretty certain that it is syntactically correct.
2554 */
5adf9bdc 2555 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2556 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2557 git_path_opts_file());
2558 return 0;
043a4492
RR
2559}
2560
65850686
AG
2561static void write_strategy_opts(struct replay_opts *opts)
2562{
2563 int i;
2564 struct strbuf buf = STRBUF_INIT;
2565
2566 for (i = 0; i < opts->xopts_nr; ++i)
2567 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2568
2569 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2570 strbuf_release(&buf);
2571}
2572
2573int write_basic_state(struct replay_opts *opts, const char *head_name,
7d3488eb 2574 struct commit *onto, const char *orig_head)
65850686 2575{
65850686
AG
2576 if (head_name)
2577 write_file(rebase_path_head_name(), "%s\n", head_name);
2578 if (onto)
7d3488eb
PW
2579 write_file(rebase_path_onto(), "%s\n",
2580 oid_to_hex(&onto->object.oid));
65850686
AG
2581 if (orig_head)
2582 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2583
8a997ed1
EN
2584 if (opts->quiet)
2585 write_file(rebase_path_quiet(), "%s", "");
65850686 2586 if (opts->verbose)
4af51741 2587 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
2588 if (opts->strategy)
2589 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2590 if (opts->xopts_nr > 0)
2591 write_strategy_opts(opts);
2592
2593 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2594 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2595 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2596 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2597
2598 if (opts->gpg_sign)
2599 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2600 if (opts->signoff)
2601 write_file(rebase_path_signoff(), "--signoff\n");
e98c4269
EN
2602 if (opts->drop_redundant_commits)
2603 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2604 if (opts->keep_redundant_commits)
2605 write_file(rebase_path_keep_redundant_commits(), "%s", "");
d421afa0
JS
2606 if (opts->reschedule_failed_exec)
2607 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
65850686
AG
2608
2609 return 0;
2610}
2611
004fefa7 2612static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2613 struct replay_opts *opts)
2614{
004fefa7
JS
2615 enum todo_command command = opts->action == REPLAY_PICK ?
2616 TODO_PICK : TODO_REVERT;
414697a9 2617 const char *command_string = todo_command_info[command].str;
019a9d83 2618 const char *encoding;
043a4492 2619 struct commit *commit;
043a4492 2620
34b0528b
JS
2621 if (prepare_revs(opts))
2622 return -1;
043a4492 2623
019a9d83
ĐTCD
2624 encoding = get_log_output_encoding();
2625
004fefa7
JS
2626 while ((commit = get_revision(opts->revs))) {
2627 struct todo_item *item = append_new_todo(todo_list);
019a9d83 2628 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
004fefa7
JS
2629 const char *subject;
2630 int subject_len;
2631
2632 item->command = command;
2633 item->commit = commit;
6ad656db 2634 item->arg_offset = 0;
c22f7dfb 2635 item->arg_len = 0;
004fefa7
JS
2636 item->offset_in_buf = todo_list->buf.len;
2637 subject_len = find_commit_subject(commit_buffer, &subject);
2638 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2639 short_commit_name(commit), subject_len, subject);
2640 unuse_commit_buffer(commit, commit_buffer);
2641 }
8530c739
JK
2642
2643 if (!todo_list->nr)
2644 return error(_("empty commit set passed"));
2645
34b0528b 2646 return 0;
043a4492
RR
2647}
2648
6a1f9046 2649static int create_seq_dir(struct repository *r)
043a4492 2650{
6a1f9046
RA
2651 enum replay_action action;
2652 const char *in_progress_error = NULL;
2653 const char *in_progress_advice = NULL;
dcb500dc
RA
2654 unsigned int advise_skip = file_exists(git_path_revert_head(r)) ||
2655 file_exists(git_path_cherry_pick_head(r));
6a1f9046
RA
2656
2657 if (!sequencer_get_last_command(r, &action)) {
2658 switch (action) {
2659 case REPLAY_REVERT:
2660 in_progress_error = _("revert is already in progress");
2661 in_progress_advice =
dcb500dc 2662 _("try \"git revert (--continue | %s--abort | --quit)\"");
6a1f9046
RA
2663 break;
2664 case REPLAY_PICK:
2665 in_progress_error = _("cherry-pick is already in progress");
2666 in_progress_advice =
dcb500dc 2667 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
6a1f9046
RA
2668 break;
2669 default:
2670 BUG("unexpected action in create_seq_dir");
2671 }
2672 }
2673 if (in_progress_error) {
2674 error("%s", in_progress_error);
2675 if (advice_sequencer_in_use)
dcb500dc
RA
2676 advise(in_progress_advice,
2677 advise_skip ? "--skip | " : "");
043a4492 2678 return -1;
6a1f9046
RA
2679 }
2680 if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2681 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2682 git_path_seq_dir());
6a1f9046 2683
043a4492
RR
2684 return 0;
2685}
2686
311fd397 2687static int save_head(const char *head)
043a4492 2688{
14bca6c6 2689 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2690 struct strbuf buf = STRBUF_INIT;
2691 int fd;
ed3f9a12 2692 ssize_t written;
043a4492 2693
311fd397 2694 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2695 if (fd < 0)
93b3df6f 2696 return error_errno(_("could not lock HEAD"));
043a4492 2697 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2698 written = write_in_full(fd, buf.buf, buf.len);
2699 strbuf_release(&buf);
2700 if (written < 0) {
bf5c0571 2701 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2702 rollback_lock_file(&head_lock);
bf5c0571 2703 return -1;
311fd397 2704 }
350292a1
2705 if (commit_lock_file(&head_lock) < 0)
2706 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2707 return 0;
043a4492
RR
2708}
2709
1e41229d
SB
2710static int rollback_is_safe(void)
2711{
2712 struct strbuf sb = STRBUF_INIT;
2713 struct object_id expected_head, actual_head;
2714
2715 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2716 strbuf_trim(&sb);
2717 if (get_oid_hex(sb.buf, &expected_head)) {
2718 strbuf_release(&sb);
2719 die(_("could not parse %s"), git_path_abort_safety_file());
2720 }
2721 strbuf_release(&sb);
2722 }
2723 else if (errno == ENOENT)
2724 oidclr(&expected_head);
2725 else
2726 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2727
2728 if (get_oid("HEAD", &actual_head))
2729 oidclr(&actual_head);
2730
4a7e27e9 2731 return oideq(&actual_head, &expected_head);
1e41229d
SB
2732}
2733
918d1e6e 2734static int reset_merge(const struct object_id *oid)
043a4492 2735{
265ab48f
RA
2736 int ret;
2737 struct argv_array argv = ARGV_ARRAY_INIT;
1e41229d 2738
265ab48f
RA
2739 argv_array_pushl(&argv, "reset", "--merge", NULL);
2740
2741 if (!is_null_oid(oid))
2742 argv_array_push(&argv, oid_to_hex(oid));
1e41229d 2743
265ab48f
RA
2744 ret = run_command_v_opt(argv.argv, RUN_GIT_CMD);
2745 argv_array_clear(&argv);
2746
2747 return ret;
043a4492
RR
2748}
2749
005af339 2750static int rollback_single_pick(struct repository *r)
043a4492 2751{
092bbcdf 2752 struct object_id head_oid;
043a4492 2753
005af339
NTND
2754 if (!file_exists(git_path_cherry_pick_head(r)) &&
2755 !file_exists(git_path_revert_head(r)))
043a4492 2756 return error(_("no cherry-pick or revert in progress"));
34c290a6 2757 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2758 return error(_("cannot resolve HEAD"));
092bbcdf 2759 if (is_null_oid(&head_oid))
043a4492 2760 return error(_("cannot abort from a branch yet to be born"));
918d1e6e 2761 return reset_merge(&head_oid);
043a4492
RR
2762}
2763
de81ca3f
RA
2764static int skip_single_pick(void)
2765{
2766 struct object_id head;
2767
2768 if (read_ref_full("HEAD", 0, &head, NULL))
2769 return error(_("cannot resolve HEAD"));
2770 return reset_merge(&head);
043a4492
RR
2771}
2772
005af339 2773int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 2774{
043a4492 2775 FILE *f;
092bbcdf 2776 struct object_id oid;
043a4492 2777 struct strbuf buf = STRBUF_INIT;
092bbcdf 2778 const char *p;
043a4492 2779
f932729c 2780 f = fopen(git_path_head_file(), "r");
043a4492
RR
2781 if (!f && errno == ENOENT) {
2782 /*
2783 * There is no multiple-cherry-pick in progress.
2784 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2785 * a single-cherry-pick in progress, abort that.
2786 */
005af339 2787 return rollback_single_pick(r);
043a4492
RR
2788 }
2789 if (!f)
f7ed1953 2790 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2791 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2792 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2793 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2794 fclose(f);
2795 goto fail;
2796 }
2797 fclose(f);
092bbcdf 2798 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2799 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2800 git_path_head_file());
043a4492
RR
2801 goto fail;
2802 }
092bbcdf 2803 if (is_null_oid(&oid)) {
0f974e21
MG
2804 error(_("cannot abort from a branch yet to be born"));
2805 goto fail;
2806 }
1e41229d
SB
2807
2808 if (!rollback_is_safe()) {
2809 /* Do not error, just do not rollback */
2810 warning(_("You seem to have moved HEAD. "
2811 "Not rewinding, check your HEAD!"));
2812 } else
918d1e6e 2813 if (reset_merge(&oid))
043a4492 2814 goto fail;
043a4492 2815 strbuf_release(&buf);
2863584f 2816 return sequencer_remove_state(opts);
043a4492
RR
2817fail:
2818 strbuf_release(&buf);
2819 return -1;
2820}
2821
de81ca3f
RA
2822int sequencer_skip(struct repository *r, struct replay_opts *opts)
2823{
2824 enum replay_action action = -1;
2825 sequencer_get_last_command(r, &action);
2826
2827 /*
2828 * Check whether the subcommand requested to skip the commit is actually
2829 * in progress and that it's safe to skip the commit.
2830 *
2831 * opts->action tells us which subcommand requested to skip the commit.
2832 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2833 * action is in progress and we can skip the commit.
2834 *
2835 * Otherwise we check that the last instruction was related to the
2836 * particular subcommand we're trying to execute and barf if that's not
2837 * the case.
2838 *
2839 * Finally we check that the rollback is "safe", i.e., has the HEAD
2840 * moved? In this case, it doesn't make sense to "reset the merge" and
2841 * "skip the commit" as the user already handled this by committing. But
2842 * we'd not want to barf here, instead give advice on how to proceed. We
2843 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2844 * it gets removed when the user commits, so if it still exists we're
2845 * sure the user can't have committed before.
2846 */
2847 switch (opts->action) {
2848 case REPLAY_REVERT:
2849 if (!file_exists(git_path_revert_head(r))) {
2850 if (action != REPLAY_REVERT)
2851 return error(_("no revert in progress"));
2852 if (!rollback_is_safe())
2853 goto give_advice;
2854 }
2855 break;
2856 case REPLAY_PICK:
2857 if (!file_exists(git_path_cherry_pick_head(r))) {
2858 if (action != REPLAY_PICK)
2859 return error(_("no cherry-pick in progress"));
2860 if (!rollback_is_safe())
2861 goto give_advice;
2862 }
2863 break;
2864 default:
2865 BUG("unexpected action in sequencer_skip");
2866 }
2867
2868 if (skip_single_pick())
2869 return error(_("failed to skip the commit"));
2870 if (!is_directory(git_path_seq_dir()))
2871 return 0;
2872
2873 return sequencer_continue(r, opts);
2874
2875give_advice:
2876 error(_("there is nothing to skip"));
2877
2878 if (advice_resolve_conflict) {
2879 advise(_("have you committed already?\n"
2880 "try \"git %s --continue\""),
2881 action == REPLAY_REVERT ? "revert" : "cherry-pick");
2882 }
2883 return -1;
2884}
2885
004fefa7 2886static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2887{
14bca6c6 2888 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2889 const char *todo_path = get_todo_path(opts);
2890 int next = todo_list->current, offset, fd;
043a4492 2891
84583957
JS
2892 /*
2893 * rebase -i writes "git-rebase-todo" without the currently executing
2894 * command, appending it to "done" instead.
2895 */
2896 if (is_rebase_i(opts))
2897 next++;
2898
004fefa7 2899 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2900 if (fd < 0)
93b3df6f 2901 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2902 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2903 if (write_in_full(fd, todo_list->buf.buf + offset,
2904 todo_list->buf.len - offset) < 0)
93b3df6f 2905 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2906 if (commit_lock_file(&todo_lock) < 0)
350292a1 2907 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2908
a01c2a5f
JS
2909 if (is_rebase_i(opts) && next > 0) {
2910 const char *done = rebase_path_done();
2911 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2912 int ret = 0;
1df6df0c 2913
a01c2a5f
JS
2914 if (fd < 0)
2915 return 0;
2916 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2917 get_item_line_length(todo_list, next - 1))
2918 < 0)
2919 ret = error_errno(_("could not write to '%s'"), done);
2920 if (close(fd) < 0)
2921 ret = error_errno(_("failed to finalize '%s'"), done);
2922 return ret;
1df6df0c 2923 }
221675de 2924 return 0;
043a4492
RR
2925}
2926
88d5a271 2927static int save_opts(struct replay_opts *opts)
043a4492 2928{
f932729c 2929 const char *opts_file = git_path_opts_file();
88d5a271 2930 int res = 0;
043a4492
RR
2931
2932 if (opts->no_commit)
f59199d5
PW
2933 res |= git_config_set_in_file_gently(opts_file,
2934 "options.no-commit", "true");
043a4492 2935 if (opts->edit)
f59199d5
PW
2936 res |= git_config_set_in_file_gently(opts_file,
2937 "options.edit", "true");
6860ce5d
PW
2938 if (opts->allow_empty)
2939 res |= git_config_set_in_file_gently(opts_file,
2940 "options.allow-empty", "true");
2941 if (opts->allow_empty_message)
2942 res |= git_config_set_in_file_gently(opts_file,
2943 "options.allow-empty-message", "true");
2944 if (opts->keep_redundant_commits)
2945 res |= git_config_set_in_file_gently(opts_file,
2946 "options.keep-redundant-commits", "true");
043a4492 2947 if (opts->signoff)
f59199d5
PW
2948 res |= git_config_set_in_file_gently(opts_file,
2949 "options.signoff", "true");
043a4492 2950 if (opts->record_origin)
f59199d5
PW
2951 res |= git_config_set_in_file_gently(opts_file,
2952 "options.record-origin", "true");
043a4492 2953 if (opts->allow_ff)
f59199d5
PW
2954 res |= git_config_set_in_file_gently(opts_file,
2955 "options.allow-ff", "true");
043a4492
RR
2956 if (opts->mainline) {
2957 struct strbuf buf = STRBUF_INIT;
2958 strbuf_addf(&buf, "%d", opts->mainline);
f59199d5
PW
2959 res |= git_config_set_in_file_gently(opts_file,
2960 "options.mainline", buf.buf);
043a4492
RR
2961 strbuf_release(&buf);
2962 }
2963 if (opts->strategy)
f59199d5
PW
2964 res |= git_config_set_in_file_gently(opts_file,
2965 "options.strategy", opts->strategy);
3253553e 2966 if (opts->gpg_sign)
f59199d5
PW
2967 res |= git_config_set_in_file_gently(opts_file,
2968 "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2969 if (opts->xopts) {
2970 int i;
2971 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2972 res |= git_config_set_multivar_in_file_gently(opts_file,
f59199d5
PW
2973 "options.strategy-option",
2974 opts->xopts[i], "^$", 0);
043a4492 2975 }
8d8cb4b0 2976 if (opts->allow_rerere_auto)
f59199d5
PW
2977 res |= git_config_set_in_file_gently(opts_file,
2978 "options.allow-rerere-auto",
2979 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2980 "true" : "false");
dc42e9a8
PW
2981
2982 if (opts->explicit_cleanup)
2983 res |= git_config_set_in_file_gently(opts_file,
2984 "options.default-msg-cleanup",
2985 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 2986 return res;
043a4492
RR
2987}
2988
f11c9580
NTND
2989static int make_patch(struct repository *r,
2990 struct commit *commit,
2991 struct replay_opts *opts)
56dc3ab0
JS
2992{
2993 struct strbuf buf = STRBUF_INIT;
2994 struct rev_info log_tree_opt;
2995 const char *subject, *p;
2996 int res = 0;
2997
2998 p = short_commit_name(commit);
2999 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3000 return -1;
fbd7a232
NTND
3001 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
3002 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
3003 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
3004
3005 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3006 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3007 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
3008 log_tree_opt.abbrev = 0;
3009 log_tree_opt.diff = 1;
3010 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3011 log_tree_opt.disable_stdin = 1;
3012 log_tree_opt.no_commit_id = 1;
3013 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3014 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3015 if (!log_tree_opt.diffopt.file)
3016 res |= error_errno(_("could not open '%s'"), buf.buf);
3017 else {
3018 res |= log_tree_commit(&log_tree_opt, commit);
3019 fclose(log_tree_opt.diffopt.file);
3020 }
3021 strbuf_reset(&buf);
3022
3023 strbuf_addf(&buf, "%s/message", get_dir(opts));
3024 if (!file_exists(buf.buf)) {
52f52e5a
ĐTCD
3025 const char *encoding = get_commit_output_encoding();
3026 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
56dc3ab0
JS
3027 find_commit_subject(commit_buffer, &subject);
3028 res |= write_message(subject, strlen(subject), buf.buf, 1);
3029 unuse_commit_buffer(commit, commit_buffer);
3030 }
3031 strbuf_release(&buf);
3032
3033 return res;
3034}
3035
3036static int intend_to_amend(void)
3037{
092bbcdf 3038 struct object_id head;
56dc3ab0
JS
3039 char *p;
3040
092bbcdf 3041 if (get_oid("HEAD", &head))
56dc3ab0
JS
3042 return error(_("cannot read HEAD"));
3043
092bbcdf 3044 p = oid_to_hex(&head);
56dc3ab0
JS
3045 return write_message(p, strlen(p), rebase_path_amend(), 1);
3046}
3047
f11c9580
NTND
3048static int error_with_patch(struct repository *r,
3049 struct commit *commit,
3050 const char *subject, int subject_len,
3051 struct replay_opts *opts,
3052 int exit_code, int to_amend)
56dc3ab0 3053{
bc9238bb 3054 if (commit) {
f11c9580 3055 if (make_patch(r, commit, opts))
bc9238bb 3056 return -1;
5a5c5e95 3057 } else if (copy_file(rebase_path_message(),
f11c9580 3058 git_path_merge_msg(r), 0666))
bc9238bb 3059 return error(_("unable to copy '%s' to '%s'"),
f11c9580 3060 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
3061
3062 if (to_amend) {
3063 if (intend_to_amend())
3064 return -1;
3065
02127c63
NTND
3066 fprintf(stderr,
3067 _("You can amend the commit now, with\n"
3068 "\n"
3069 " git commit --amend %s\n"
3070 "\n"
3071 "Once you are satisfied with your changes, run\n"
3072 "\n"
3073 " git rebase --continue\n"),
3074 gpg_sign_opt_quoted(opts));
bc9238bb
PW
3075 } else if (exit_code) {
3076 if (commit)
5a5c5e95
JH
3077 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3078 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
3079 else
3080 /*
3081 * We don't have the hash of the parent so
3082 * just print the line from the todo file.
3083 */
5a5c5e95
JH
3084 fprintf_ln(stderr, _("Could not merge %.*s"),
3085 subject_len, subject);
bc9238bb 3086 }
56dc3ab0
JS
3087
3088 return exit_code;
3089}
3090
f11c9580
NTND
3091static int error_failed_squash(struct repository *r,
3092 struct commit *commit,
3093 struct replay_opts *opts,
3094 int subject_len,
3095 const char *subject)
6e98de72 3096{
e12a7ef5
JS
3097 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3098 return error(_("could not copy '%s' to '%s'"),
6e98de72 3099 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
3100 unlink(git_path_merge_msg(r));
3101 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 3102 return error(_("could not copy '%s' to '%s'"),
102de880 3103 rebase_path_message(),
f11c9580
NTND
3104 git_path_merge_msg(r));
3105 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
3106}
3107
f11c9580 3108static int do_exec(struct repository *r, const char *command_line)
311af526 3109{
09d7b6c6 3110 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
3111 const char *child_argv[] = { NULL, NULL };
3112 int dirty, status;
3113
3114 fprintf(stderr, "Executing: %s\n", command_line);
3115 child_argv[0] = command_line;
09d7b6c6 3116 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 3117 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
3118 absolute_path(get_git_work_tree()));
09d7b6c6
JK
3119 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3120 child_env.argv);
311af526
JS
3121
3122 /* force re-reading of the cache */
e1ff0a32 3123 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
311af526
JS
3124 return error(_("could not read index"));
3125
f11c9580 3126 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
3127
3128 if (status) {
3129 warning(_("execution failed: %s\n%s"
3130 "You can fix the problem, and then run\n"
3131 "\n"
3132 " git rebase --continue\n"
3133 "\n"),
3134 command_line,
3135 dirty ? N_("and made changes to the index and/or the "
3136 "working tree\n") : "");
3137 if (status == 127)
3138 /* command not found */
3139 status = 1;
3140 } else if (dirty) {
3141 warning(_("execution succeeded: %s\nbut "
3142 "left changes to the index and/or the working tree\n"
3143 "Commit or stash your changes, and then run\n"
3144 "\n"
3145 " git rebase --continue\n"
3146 "\n"), command_line);
3147 status = 1;
3148 }
3149
09d7b6c6
JK
3150 argv_array_clear(&child_env);
3151
311af526
JS
3152 return status;
3153}
3154
9055e401
JS
3155static int safe_append(const char *filename, const char *fmt, ...)
3156{
3157 va_list ap;
3158 struct lock_file lock = LOCK_INIT;
3159 int fd = hold_lock_file_for_update(&lock, filename,
3160 LOCK_REPORT_ON_ERROR);
3161 struct strbuf buf = STRBUF_INIT;
3162
3163 if (fd < 0)
3164 return -1;
3165
3166 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3167 error_errno(_("could not read '%s'"), filename);
3168 rollback_lock_file(&lock);
3169 return -1;
3170 }
3171 strbuf_complete(&buf, '\n');
3172 va_start(ap, fmt);
3173 strbuf_vaddf(&buf, fmt, ap);
3174 va_end(ap);
3175
3176 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3177 error_errno(_("could not write to '%s'"), filename);
3178 strbuf_release(&buf);
3179 rollback_lock_file(&lock);
3180 return -1;
3181 }
3182 if (commit_lock_file(&lock) < 0) {
3183 strbuf_release(&buf);
3184 rollback_lock_file(&lock);
3185 return error(_("failed to finalize '%s'"), filename);
3186 }
3187
3188 strbuf_release(&buf);
3189 return 0;
3190}
3191
f11c9580 3192static int do_label(struct repository *r, const char *name, int len)
9055e401 3193{
f11c9580 3194 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3195 struct ref_transaction *transaction;
3196 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3197 struct strbuf msg = STRBUF_INIT;
3198 int ret = 0;
3199 struct object_id head_oid;
3200
3201 if (len == 1 && *name == '#')
02127c63 3202 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3203
3204 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3205 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401
JS
3206
3207 transaction = ref_store_transaction_begin(refs, &err);
3208 if (!transaction) {
3209 error("%s", err.buf);
3210 ret = -1;
3211 } else if (get_oid("HEAD", &head_oid)) {
3212 error(_("could not read HEAD"));
3213 ret = -1;
3214 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3215 NULL, 0, msg.buf, &err) < 0 ||
3216 ref_transaction_commit(transaction, &err)) {
3217 error("%s", err.buf);
3218 ret = -1;
3219 }
3220 ref_transaction_free(transaction);
3221 strbuf_release(&err);
3222 strbuf_release(&msg);
3223
3224 if (!ret)
3225 ret = safe_append(rebase_path_refs_to_delete(),
3226 "%s\n", ref_name.buf);
3227 strbuf_release(&ref_name);
3228
3229 return ret;
3230}
3231
3232static const char *reflog_message(struct replay_opts *opts,
3233 const char *sub_action, const char *fmt, ...);
3234
f11c9580
NTND
3235static int do_reset(struct repository *r,
3236 const char *name, int len,
3237 struct replay_opts *opts)
9055e401
JS
3238{
3239 struct strbuf ref_name = STRBUF_INIT;
3240 struct object_id oid;
3241 struct lock_file lock = LOCK_INIT;
3242 struct tree_desc desc;
3243 struct tree *tree;
3244 struct unpack_trees_options unpack_tree_opts;
71571cd7 3245 int ret = 0;
9055e401 3246
3a95f31d 3247 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3248 return -1;
3249
ebddf393
JS
3250 if (len == 10 && !strncmp("[new root]", name, len)) {
3251 if (!opts->have_squash_onto) {
3252 const char *hex;
3253 if (commit_tree("", 0, the_hash_algo->empty_tree,
3254 NULL, &opts->squash_onto,
3255 NULL, NULL))
3256 return error(_("writing fake root commit"));
3257 opts->have_squash_onto = 1;
3258 hex = oid_to_hex(&opts->squash_onto);
3259 if (write_message(hex, strlen(hex),
3260 rebase_path_squash_onto(), 0))
3261 return error(_("writing squash-onto"));
3262 }
3263 oidcpy(&oid, &opts->squash_onto);
3264 } else {
71571cd7
3265 int i;
3266
ebddf393
JS
3267 /* Determine the length of the label */
3268 for (i = 0; i < len; i++)
3269 if (isspace(name[i]))
71571cd7
3270 break;
3271 len = i;
ebddf393
JS
3272
3273 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3274 if (get_oid(ref_name.buf, &oid) &&
3275 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3276 error(_("could not read '%s'"), ref_name.buf);
3277 rollback_lock_file(&lock);
3278 strbuf_release(&ref_name);
3279 return -1;
3280 }
9055e401
JS
3281 }
3282
3283 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3284 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3285 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3286 unpack_tree_opts.src_index = r->index;
3287 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3288 unpack_tree_opts.fn = oneway_merge;
3289 unpack_tree_opts.merge = 1;
3290 unpack_tree_opts.update = 1;
3291
e1ff0a32 3292 if (repo_read_index_unmerged(r)) {
9055e401
JS
3293 rollback_lock_file(&lock);
3294 strbuf_release(&ref_name);
3295 return error_resolve_conflict(_(action_name(opts)));
3296 }
3297
5e575807 3298 if (!fill_tree_descriptor(r, &desc, &oid)) {
9055e401
JS
3299 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3300 rollback_lock_file(&lock);
3301 free((void *)desc.buffer);
3302 strbuf_release(&ref_name);
3303 return -1;
3304 }
3305
3306 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3307 rollback_lock_file(&lock);
3308 free((void *)desc.buffer);
3309 strbuf_release(&ref_name);
3310 return -1;
3311 }
3312
3313 tree = parse_tree_indirect(&oid);
c207e9e1 3314 prime_cache_tree(r, r->index, tree);
9055e401 3315
f11c9580 3316 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3317 ret = error(_("could not write index"));
3318 free((void *)desc.buffer);
3319
3320 if (!ret)
3321 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3322 len, name), "HEAD", &oid,
3323 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3324
3325 strbuf_release(&ref_name);
3326 return ret;
3327}
3328
2b6ad0f4
JS
3329static struct commit *lookup_label(const char *label, int len,
3330 struct strbuf *buf)
3331{
3332 struct commit *commit;
3333
3334 strbuf_reset(buf);
3335 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3336 commit = lookup_commit_reference_by_name(buf->buf);
3337 if (!commit) {
3338 /* fall back to non-rewritten ref or commit */
3339 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3340 commit = lookup_commit_reference_by_name(buf->buf);
3341 }
3342
3343 if (!commit)
3344 error(_("could not resolve '%s'"), buf->buf);
3345
3346 return commit;
3347}
3348
f11c9580
NTND
3349static int do_merge(struct repository *r,
3350 struct commit *commit,
3351 const char *arg, int arg_len,
4c68e7dd
JS
3352 int flags, struct replay_opts *opts)
3353{
3354 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3355 EDIT_MSG | VERIFY_MSG : 0;
3356 struct strbuf ref_name = STRBUF_INIT;
3357 struct commit *head_commit, *merge_commit, *i;
3358 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3359 struct commit_list *to_merge = NULL, **tail = &to_merge;
e145d993
JS
3360 const char *strategy = !opts->xopts_nr &&
3361 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3362 NULL : opts->strategy;
4c68e7dd 3363 struct merge_options o;
2b6ad0f4 3364 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3365 static struct lock_file lock;
3366 const char *p;
3367
3a95f31d 3368 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3369 ret = -1;
3370 goto leave_merge;
3371 }
3372
3373 head_commit = lookup_commit_reference_by_name("HEAD");
3374 if (!head_commit) {
3375 ret = error(_("cannot merge without a current revision"));
3376 goto leave_merge;
3377 }
3378
2b6ad0f4
JS
3379 /*
3380 * For octopus merges, the arg starts with the list of revisions to be
3381 * merged. The list is optionally followed by '#' and the oneline.
3382 */
3383 merge_arg_len = oneline_offset = arg_len;
3384 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3385 if (!*p)
3386 break;
3387 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3388 p += 1 + strspn(p + 1, " \t\n");
3389 oneline_offset = p - arg;
3390 break;
3391 }
3392 k = strcspn(p, " \t\n");
3393 if (!k)
3394 continue;
3395 merge_commit = lookup_label(p, k, &ref_name);
3396 if (!merge_commit) {
3397 ret = error(_("unable to parse '%.*s'"), k, p);
3398 goto leave_merge;
3399 }
3400 tail = &commit_list_insert(merge_commit, tail)->next;
3401 p += k;
3402 merge_arg_len = p - arg;
4c68e7dd
JS
3403 }
3404
2b6ad0f4
JS
3405 if (!to_merge) {
3406 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3407 goto leave_merge;
3408 }
3409
9c85a1c2 3410 if (opts->have_squash_onto &&
4a7e27e9 3411 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3412 /*
3413 * When the user tells us to "merge" something into a
3414 * "[new root]", let's simply fast-forward to the merge head.
3415 */
3416 rollback_lock_file(&lock);
2b6ad0f4
JS
3417 if (to_merge->next)
3418 ret = error(_("octopus merge cannot be executed on "
3419 "top of a [new root]"));
3420 else
f11c9580 3421 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3422 &head_commit->object.oid, 0,
3423 opts);
9c85a1c2
JS
3424 goto leave_merge;
3425 }
3426
4c68e7dd 3427 if (commit) {
5772b0c7
ĐTCD
3428 const char *encoding = get_commit_output_encoding();
3429 const char *message = logmsg_reencode(commit, NULL, encoding);
4c68e7dd
JS
3430 const char *body;
3431 int len;
3432
3433 if (!message) {
3434 ret = error(_("could not get commit message of '%s'"),
3435 oid_to_hex(&commit->object.oid));
3436 goto leave_merge;
3437 }
3438 write_author_script(message);
3439 find_commit_subject(message, &body);
3440 len = strlen(body);
f11c9580 3441 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3442 unuse_commit_buffer(commit, message);
3443 if (ret) {
3444 error_errno(_("could not write '%s'"),
f11c9580 3445 git_path_merge_msg(r));
4c68e7dd
JS
3446 goto leave_merge;
3447 }
3448 } else {
3449 struct strbuf buf = STRBUF_INIT;
3450 int len;
3451
3452 strbuf_addf(&buf, "author %s", git_author_info(0));
3453 write_author_script(buf.buf);
3454 strbuf_reset(&buf);
3455
3456 if (oneline_offset < arg_len) {
3457 p = arg + oneline_offset;
3458 len = arg_len - oneline_offset;
3459 } else {
2b6ad0f4
JS
3460 strbuf_addf(&buf, "Merge %s '%.*s'",
3461 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3462 merge_arg_len, arg);
3463 p = buf.buf;
3464 len = buf.len;
3465 }
3466
f11c9580 3467 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3468 strbuf_release(&buf);
3469 if (ret) {
3470 error_errno(_("could not write '%s'"),
f11c9580 3471 git_path_merge_msg(r));
4c68e7dd
JS
3472 goto leave_merge;
3473 }
3474 }
3475
d1e8b011
JS
3476 /*
3477 * If HEAD is not identical to the first parent of the original merge
3478 * commit, we cannot fast-forward.
3479 */
3480 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3481 oideq(&commit->parents->item->object.oid,
3482 &head_commit->object.oid);
d1e8b011
JS
3483
3484 /*
2b6ad0f4 3485 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3486 * fast-forward.
3487 */
3488 if (can_fast_forward) {
2b6ad0f4 3489 struct commit_list *p = commit->parents->next;
d1e8b011 3490
2b6ad0f4 3491 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3492 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3493 &p->item->object.oid)) {
3494 can_fast_forward = 0;
3495 break;
3496 }
3497 /*
3498 * If the number of merge heads differs from the original merge
3499 * commit, we cannot fast-forward.
3500 */
3501 if (j || p)
d1e8b011
JS
3502 can_fast_forward = 0;
3503 }
3504
2b6ad0f4 3505 if (can_fast_forward) {
d1e8b011 3506 rollback_lock_file(&lock);
f11c9580 3507 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011 3508 &head_commit->object.oid, 0, opts);
6df8df08
PW
3509 if (flags & TODO_EDIT_MERGE_MSG) {
3510 run_commit_flags |= AMEND_MSG;
3511 goto fast_forward_edit;
3512 }
d1e8b011
JS
3513 goto leave_merge;
3514 }
3515
e145d993 3516 if (strategy || to_merge->next) {
2b6ad0f4
JS
3517 /* Octopus merge */
3518 struct child_process cmd = CHILD_PROCESS_INIT;
3519
3520 if (read_env_script(&cmd.env_array)) {
3521 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3522
3523 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3524 goto leave_merge;
3525 }
3526
3527 cmd.git_cmd = 1;
3528 argv_array_push(&cmd.args, "merge");
3529 argv_array_push(&cmd.args, "-s");
e145d993
JS
3530 if (!strategy)
3531 argv_array_push(&cmd.args, "octopus");
3532 else {
3533 argv_array_push(&cmd.args, strategy);
3534 for (k = 0; k < opts->xopts_nr; k++)
3535 argv_array_pushf(&cmd.args,
3536 "-X%s", opts->xopts[k]);
3537 }
2b6ad0f4
JS
3538 argv_array_push(&cmd.args, "--no-edit");
3539 argv_array_push(&cmd.args, "--no-ff");
3540 argv_array_push(&cmd.args, "--no-log");
3541 argv_array_push(&cmd.args, "--no-stat");
3542 argv_array_push(&cmd.args, "-F");
f11c9580 3543 argv_array_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4
JS
3544 if (opts->gpg_sign)
3545 argv_array_push(&cmd.args, opts->gpg_sign);
3546
3547 /* Add the tips to be merged */
3548 for (j = to_merge; j; j = j->next)
3549 argv_array_push(&cmd.args,
3550 oid_to_hex(&j->item->object.oid));
3551
3552 strbuf_release(&ref_name);
f11c9580 3553 unlink(git_path_cherry_pick_head(r));
2b6ad0f4
JS
3554 rollback_lock_file(&lock);
3555
3556 rollback_lock_file(&lock);
3557 ret = run_command(&cmd);
3558
3559 /* force re-reading of the cache */
f11c9580 3560 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3561 repo_read_index(r) < 0))
2b6ad0f4
JS
3562 ret = error(_("could not read index"));
3563 goto leave_merge;
3564 }
3565
3566 merge_commit = to_merge->item;
4c68e7dd 3567 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3568 if (bases && oideq(&merge_commit->object.oid,
3569 &bases->item->object.oid)) {
7ccdf65b
JS
3570 ret = 0;
3571 /* skip merging an ancestor of HEAD */
3572 goto leave_merge;
3573 }
3574
4439c7a3 3575 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
3576 git_path_merge_head(r), 0);
3577 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3578
4c68e7dd
JS
3579 for (j = bases; j; j = j->next)
3580 commit_list_insert(j->item, &reversed);
3581 free_commit_list(bases);
3582
e1ff0a32 3583 repo_read_index(r);
0d6caa2d 3584 init_merge_options(&o, r);
4c68e7dd
JS
3585 o.branch1 = "HEAD";
3586 o.branch2 = ref_name.buf;
3587 o.buffer_output = 2;
3588
3589 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3590 if (ret <= 0)
3591 fputs(o.obuf.buf, stdout);
3592 strbuf_release(&o.obuf);
3593 if (ret < 0) {
3594 error(_("could not even attempt to merge '%.*s'"),
3595 merge_arg_len, arg);
3596 goto leave_merge;
3597 }
3598 /*
3599 * The return value of merge_recursive() is 1 on clean, and 0 on
3600 * unclean merge.
3601 *
3602 * Let's reverse that, so that do_merge() returns 0 upon success and
3603 * 1 upon failed merge (keeping the return value -1 for the cases where
3604 * we will want to reschedule the `merge` command).
3605 */
3606 ret = !ret;
3607
f11c9580
NTND
3608 if (r->index->cache_changed &&
3609 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
3610 ret = error(_("merge: Unable to write new index file"));
3611 goto leave_merge;
3612 }
3613
3614 rollback_lock_file(&lock);
3615 if (ret)
f11c9580 3616 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
3617 else
3618 /*
3619 * In case of problems, we now want to return a positive
3620 * value (a negative one would indicate that the `merge`
3621 * command needs to be rescheduled).
3622 */
6df8df08 3623 fast_forward_edit:
f11c9580
NTND
3624 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3625 run_commit_flags);
4c68e7dd
JS
3626
3627leave_merge:
3628 strbuf_release(&ref_name);
3629 rollback_lock_file(&lock);
2b6ad0f4 3630 free_commit_list(to_merge);
4c68e7dd
JS
3631 return ret;
3632}
3633
6e98de72
JS
3634static int is_final_fixup(struct todo_list *todo_list)
3635{
3636 int i = todo_list->current;
3637
3638 if (!is_fixup(todo_list->items[i].command))
3639 return 0;
3640
3641 while (++i < todo_list->nr)
3642 if (is_fixup(todo_list->items[i].command))
3643 return 0;
3644 else if (!is_noop(todo_list->items[i].command))
3645 break;
3646 return 1;
3647}
3648
25cb8df9
JS
3649static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3650{
3651 int i;
3652
3653 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3654 if (!is_noop(todo_list->items[i].command))
3655 return todo_list->items[i].command;
3656
3657 return -1;
3658}
3659
86ed00af 3660int apply_autostash(const char *path)
796c7972 3661{
facca7f0 3662 struct strbuf stash_oid = STRBUF_INIT;
796c7972
JS
3663 struct child_process child = CHILD_PROCESS_INIT;
3664 int ret = 0;
3665
facca7f0 3666 if (!read_oneliner(&stash_oid, path,
3442c3d1 3667 READ_ONELINER_SKIP_IF_EMPTY)) {
facca7f0 3668 strbuf_release(&stash_oid);
796c7972
JS
3669 return 0;
3670 }
facca7f0 3671 strbuf_trim(&stash_oid);
796c7972
JS
3672
3673 child.git_cmd = 1;
79a62269
PW
3674 child.no_stdout = 1;
3675 child.no_stderr = 1;
796c7972
JS
3676 argv_array_push(&child.args, "stash");
3677 argv_array_push(&child.args, "apply");
facca7f0 3678 argv_array_push(&child.args, stash_oid.buf);
796c7972 3679 if (!run_command(&child))
cdb866b3 3680 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3681 else {
3682 struct child_process store = CHILD_PROCESS_INIT;
3683
3684 store.git_cmd = 1;
3685 argv_array_push(&store.args, "stash");
3686 argv_array_push(&store.args, "store");
3687 argv_array_push(&store.args, "-m");
3688 argv_array_push(&store.args, "autostash");
3689 argv_array_push(&store.args, "-q");
facca7f0 3690 argv_array_push(&store.args, stash_oid.buf);
796c7972 3691 if (run_command(&store))
facca7f0 3692 ret = error(_("cannot store %s"), stash_oid.buf);
796c7972 3693 else
cdb866b3
JS
3694 fprintf(stderr,
3695 _("Applying autostash resulted in conflicts.\n"
3696 "Your changes are safe in the stash.\n"
3697 "You can run \"git stash pop\" or"
3698 " \"git stash drop\" at any time.\n"));
796c7972
JS
3699 }
3700
facca7f0 3701 strbuf_release(&stash_oid);
796c7972
JS
3702 return ret;
3703}
3704
96e832a5
JS
3705static const char *reflog_message(struct replay_opts *opts,
3706 const char *sub_action, const char *fmt, ...)
3707{
3708 va_list ap;
3709 static struct strbuf buf = STRBUF_INIT;
3710
3711 va_start(ap, fmt);
3712 strbuf_reset(&buf);
3713 strbuf_addstr(&buf, action_name(opts));
3714 if (sub_action)
3715 strbuf_addf(&buf, " (%s)", sub_action);
3716 if (fmt) {
3717 strbuf_addstr(&buf, ": ");
3718 strbuf_vaddf(&buf, fmt, ap);
3719 }
3720 va_end(ap);
3721
3722 return buf.buf;
3723}
3724
fc4a6735
PW
3725static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3726 const char *commit, const char *action)
2c58483a
AG
3727{
3728 struct child_process cmd = CHILD_PROCESS_INIT;
fc4a6735 3729 int ret;
2c58483a
AG
3730
3731 cmd.git_cmd = 1;
3732
3733 argv_array_push(&cmd.args, "checkout");
3734 argv_array_push(&cmd.args, commit);
3735 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3736
3737 if (opts->verbose)
fc4a6735 3738 ret = run_command(&cmd);
2c58483a 3739 else
fc4a6735
PW
3740 ret = run_command_silent_on_success(&cmd);
3741
3742 if (!ret)
3743 discard_index(r->index);
3744
3745 return ret;
2c58483a
AG
3746}
3747
fc4a6735 3748static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 3749 const char *onto_name, const struct object_id *onto,
91f0d95d 3750 const char *orig_head)
4df66c40
AG
3751{
3752 struct object_id oid;
3753 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3754
3755 if (get_oid(orig_head, &oid))
3756 return error(_("%s: not a valid OID"), orig_head);
3757
7d3488eb 3758 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
be1bb600 3759 apply_autostash(rebase_path_autostash());
4df66c40
AG
3760 sequencer_remove_state(opts);
3761 return error(_("could not detach HEAD"));
3762 }
3763
3764 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3765}
3766
005af339 3767static int stopped_at_head(struct repository *r)
71f82465
JS
3768{
3769 struct object_id head;
3770 struct commit *commit;
3771 struct commit_message message;
3772
789b1f70 3773 if (get_oid("HEAD", &head) ||
005af339 3774 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
3775 parse_commit(commit) || get_message(commit, &message))
3776 fprintf(stderr, _("Stopped at HEAD\n"));
3777 else {
3778 fprintf(stderr, _("Stopped at %s\n"), message.label);
3779 free_message(commit, &message);
3780 }
3781 return 0;
3782
3783}
3784
cb5206ea
JS
3785static const char rescheduled_advice[] =
3786N_("Could not execute the todo command\n"
3787"\n"
3788" %.*s"
3789"\n"
3790"It has been rescheduled; To edit the command before continuing, please\n"
3791"edit the todo list first:\n"
3792"\n"
3793" git rebase --edit-todo\n"
3794" git rebase --continue\n");
3795
f11c9580
NTND
3796static int pick_commits(struct repository *r,
3797 struct todo_list *todo_list,
3798 struct replay_opts *opts)
043a4492 3799{
9055e401 3800 int res = 0, reschedule = 0;
043a4492
RR
3801
3802 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3803 if (opts->allow_ff)
3804 assert(!(opts->signoff || opts->no_commit ||
4d924528 3805 opts->record_origin || opts->edit));
f11c9580 3806 if (read_and_refresh_cache(r, opts))
0d9c6dc9 3807 return -1;
043a4492 3808
004fefa7
JS
3809 while (todo_list->current < todo_list->nr) {
3810 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 3811 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 3812 int check_todo = 0;
6ad656db 3813
004fefa7 3814 if (save_todo(todo_list, opts))
221675de 3815 return -1;
6e98de72 3816 if (is_rebase_i(opts)) {
ef80069a
JS
3817 if (item->command != TODO_COMMENT) {
3818 FILE *f = fopen(rebase_path_msgnum(), "w");
3819
3820 todo_list->done_nr++;
3821
3822 if (f) {
3823 fprintf(f, "%d\n", todo_list->done_nr);
3824 fclose(f);
3825 }
899b49c4
EN
3826 if (!opts->quiet)
3827 fprintf(stderr, "Rebasing (%d/%d)%s",
3828 todo_list->done_nr,
3829 todo_list->total_nr,
3830 opts->verbose ? "\n" : "\r");
ef80069a 3831 }
6e98de72
JS
3832 unlink(rebase_path_message());
3833 unlink(rebase_path_author_script());
3834 unlink(rebase_path_stopped_sha());
3835 unlink(rebase_path_amend());
34e7771b 3836 unlink(git_path_merge_head(r));
fbd7a232 3837 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465 3838
d7d90885
SG
3839 if (item->command == TODO_BREAK) {
3840 if (!opts->verbose)
3841 term_clear_line();
005af339 3842 return stopped_at_head(r);
d7d90885 3843 }
6e98de72
JS
3844 }
3845 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3846 if (is_rebase_i(opts))
3847 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3848 command_to_string(item->command), NULL),
3849 1);
f11c9580 3850 res = do_pick_commit(r, item->command, item->commit,
a47ba3c7
PW
3851 opts, is_final_fixup(todo_list),
3852 &check_todo);
9d7bf3cf
JS
3853 if (is_rebase_i(opts) && res < 0) {
3854 /* Reschedule */
cb5206ea
JS
3855 advise(_(rescheduled_advice),
3856 get_item_line_length(todo_list,
3857 todo_list->current),
3858 get_item_line(todo_list,
3859 todo_list->current));
9d7bf3cf
JS
3860 todo_list->current--;
3861 if (save_todo(todo_list, opts))
3862 return -1;
3863 }
56dc3ab0
JS
3864 if (item->command == TODO_EDIT) {
3865 struct commit *commit = item->commit;
d7d90885
SG
3866 if (!res) {
3867 if (!opts->verbose)
3868 term_clear_line();
99429213 3869 fprintf(stderr,
a42e1b41 3870 _("Stopped at %s... %.*s\n"),
56dc3ab0 3871 short_commit_name(commit),
6ad656db 3872 item->arg_len, arg);
d7d90885 3873 }
f11c9580 3874 return error_with_patch(r, commit,
6ad656db 3875 arg, item->arg_len, opts, res, !res);
56dc3ab0 3876 }
25cb8df9
JS
3877 if (is_rebase_i(opts) && !res)
3878 record_in_rewritten(&item->commit->object.oid,
3879 peek_command(todo_list, 1));
6e98de72
JS
3880 if (res && is_fixup(item->command)) {
3881 if (res == 1)
3882 intend_to_amend();
f11c9580 3883 return error_failed_squash(r, item->commit, opts,
6ad656db 3884 item->arg_len, arg);
a9279c67
PW
3885 } else if (res && is_rebase_i(opts) && item->commit) {
3886 int to_amend = 0;
3887 struct object_id oid;
3888
3889 /*
3890 * If we are rewording and have either
3891 * fast-forwarded already, or are about to
3892 * create a new root commit, we want to amend,
3893 * otherwise we do not.
3894 */
3895 if (item->command == TODO_REWORD &&
3896 !get_oid("HEAD", &oid) &&
4a7e27e9 3897 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 3898 (opts->have_squash_onto &&
4a7e27e9 3899 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
3900 to_amend = 1;
3901
f11c9580 3902 return res | error_with_patch(r, item->commit,
6ad656db 3903 arg, item->arg_len, opts,
a9279c67
PW
3904 res, to_amend);
3905 }
311af526 3906 } else if (item->command == TODO_EXEC) {
6ad656db 3907 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
3908 int saved = *end_of_arg;
3909
d7d90885
SG
3910 if (!opts->verbose)
3911 term_clear_line();
311af526 3912 *end_of_arg = '\0';
6ad656db 3913 res = do_exec(r, arg);
311af526 3914 *end_of_arg = saved;
54fd3243 3915
d421afa0
JS
3916 if (res) {
3917 if (opts->reschedule_failed_exec)
3918 reschedule = 1;
54fd3243 3919 }
a47ba3c7 3920 check_todo = 1;
9055e401 3921 } else if (item->command == TODO_LABEL) {
6ad656db 3922 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
3923 reschedule = 1;
3924 } else if (item->command == TODO_RESET) {
6ad656db 3925 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 3926 reschedule = 1;
4c68e7dd 3927 } else if (item->command == TODO_MERGE) {
f11c9580 3928 if ((res = do_merge(r, item->commit,
6ad656db 3929 arg, item->arg_len,
4c68e7dd
JS
3930 item->flags, opts)) < 0)
3931 reschedule = 1;
537e7d61
JS
3932 else if (item->commit)
3933 record_in_rewritten(&item->commit->object.oid,
3934 peek_command(todo_list, 1));
3935 if (res > 0)
4c68e7dd 3936 /* failed with merge conflicts */
f11c9580 3937 return error_with_patch(r, item->commit,
6ad656db
AG
3938 arg, item->arg_len,
3939 opts, res, 0);
56dc3ab0 3940 } else if (!is_noop(item->command))
25c43667
JS
3941 return error(_("unknown command %d"), item->command);
3942
9055e401
JS
3943 if (reschedule) {
3944 advise(_(rescheduled_advice),
3945 get_item_line_length(todo_list,
3946 todo_list->current),
3947 get_item_line(todo_list, todo_list->current));
3948 todo_list->current--;
3949 if (save_todo(todo_list, opts))
3950 return -1;
4c68e7dd 3951 if (item->commit)
f11c9580
NTND
3952 return error_with_patch(r,
3953 item->commit,
6ad656db
AG
3954 arg, item->arg_len,
3955 opts, res, 0);
befd4f6a 3956 } else if (is_rebase_i(opts) && check_todo && !res) {
a47ba3c7
PW
3957 struct stat st;
3958
3959 if (stat(get_todo_path(opts), &st)) {
3960 res = error_errno(_("could not stat '%s'"),
3961 get_todo_path(opts));
3962 } else if (match_stat_data(&todo_list->stat, &st)) {
3963 /* Reread the todo file if it has changed. */
3964 todo_list_release(todo_list);
3965 if (read_populate_todo(r, todo_list, opts))
3966 res = -1; /* message was printed */
3967 /* `current` will be incremented below */
3968 todo_list->current = -1;
3969 }
9055e401
JS
3970 }
3971
004fefa7 3972 todo_list->current++;
043a4492
RR
3973 if (res)
3974 return res;
3975 }
3976
56dc3ab0 3977 if (is_rebase_i(opts)) {
4b83ce9f 3978 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3979 struct stat st;
556907f1 3980
56dc3ab0
JS
3981 /* Stopped in the middle, as planned? */
3982 if (todo_list->current < todo_list->nr)
3983 return 0;
556907f1 3984
4b83ce9f
JS
3985 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3986 starts_with(head_ref.buf, "refs/")) {
96e832a5 3987 const char *msg;
092bbcdf 3988 struct object_id head, orig;
4b83ce9f
JS
3989 int res;
3990
092bbcdf 3991 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
3992 res = error(_("cannot read HEAD"));
3993cleanup_head_ref:
3994 strbuf_release(&head_ref);
3995 strbuf_release(&buf);
3996 return res;
3997 }
3998 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 3999 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
4000 res = error(_("could not read orig-head"));
4001 goto cleanup_head_ref;
4002 }
4ab867b8 4003 strbuf_reset(&buf);
4b83ce9f
JS
4004 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4005 res = error(_("could not read 'onto'"));
4006 goto cleanup_head_ref;
4007 }
96e832a5
JS
4008 msg = reflog_message(opts, "finish", "%s onto %s",
4009 head_ref.buf, buf.buf);
ae077771 4010 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 4011 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
4012 res = error(_("could not update %s"),
4013 head_ref.buf);
4014 goto cleanup_head_ref;
4015 }
96e832a5 4016 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 4017 head_ref.buf);
96e832a5 4018 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
4019 res = error(_("could not update HEAD to %s"),
4020 head_ref.buf);
4021 goto cleanup_head_ref;
4022 }
4023 strbuf_reset(&buf);
4024 }
4025
556907f1
JS
4026 if (opts->verbose) {
4027 struct rev_info log_tree_opt;
4028 struct object_id orig, head;
4029
4030 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 4031 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
4032 log_tree_opt.diff = 1;
4033 log_tree_opt.diffopt.output_format =
4034 DIFF_FORMAT_DIFFSTAT;
4035 log_tree_opt.disable_stdin = 1;
4036
4037 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 4038 !get_oid(buf.buf, &orig) &&
4039 !get_oid("HEAD", &head)) {
66f414f8
BW
4040 diff_tree_oid(&orig, &head, "",
4041 &log_tree_opt.diffopt);
556907f1
JS
4042 log_tree_diff_flush(&log_tree_opt);
4043 }
4044 }
25cb8df9
JS
4045 flush_rewritten_pending();
4046 if (!stat(rebase_path_rewritten_list(), &st) &&
4047 st.st_size > 0) {
4048 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
4049 const char *post_rewrite_hook =
4050 find_hook("post-rewrite");
25cb8df9
JS
4051
4052 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4053 child.git_cmd = 1;
4054 argv_array_push(&child.args, "notes");
4055 argv_array_push(&child.args, "copy");
4056 argv_array_push(&child.args, "--for-rewrite=rebase");
4057 /* we don't care if this copying failed */
4058 run_command(&child);
79516045
JS
4059
4060 if (post_rewrite_hook) {
4061 struct child_process hook = CHILD_PROCESS_INIT;
4062
4063 hook.in = open(rebase_path_rewritten_list(),
4064 O_RDONLY);
4065 hook.stdout_to_stderr = 1;
6206286e 4066 hook.trace2_hook_name = "post-rewrite";
79516045
JS
4067 argv_array_push(&hook.args, post_rewrite_hook);
4068 argv_array_push(&hook.args, "rebase");
4069 /* we don't care if this hook failed */
4070 run_command(&hook);
4071 }
25cb8df9 4072 }
be1bb600 4073 apply_autostash(rebase_path_autostash());
25cb8df9 4074
d7d90885
SG
4075 if (!opts->quiet) {
4076 if (!opts->verbose)
4077 term_clear_line();
899b49c4
EN
4078 fprintf(stderr,
4079 "Successfully rebased and updated %s.\n",
4080 head_ref.buf);
d7d90885 4081 }
5da4966f 4082
556907f1 4083 strbuf_release(&buf);
4b83ce9f 4084 strbuf_release(&head_ref);
56dc3ab0
JS
4085 }
4086
043a4492
RR
4087 /*
4088 * Sequence of picks finished successfully; cleanup by
4089 * removing the .git/sequencer directory
4090 */
2863584f 4091 return sequencer_remove_state(opts);
043a4492
RR
4092}
4093
005af339 4094static int continue_single_pick(struct repository *r)
043a4492
RR
4095{
4096 const char *argv[] = { "commit", NULL };
4097
005af339
NTND
4098 if (!file_exists(git_path_cherry_pick_head(r)) &&
4099 !file_exists(git_path_revert_head(r)))
043a4492
RR
4100 return error(_("no cherry-pick or revert in progress"));
4101 return run_command_v_opt(argv, RUN_GIT_CMD);
4102}
4103
f11c9580
NTND
4104static int commit_staged_changes(struct repository *r,
4105 struct replay_opts *opts,
15ef6931 4106 struct todo_list *todo_list)
9d93ccd1 4107{
789b3eff 4108 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 4109 unsigned int final_fixup = 0, is_clean;
9d93ccd1 4110
f11c9580 4111 if (has_unstaged_changes(r, 1))
9d93ccd1 4112 return error(_("cannot rebase: You have unstaged changes."));
52632209 4113
f11c9580 4114 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
4115
4116 if (file_exists(rebase_path_amend())) {
4117 struct strbuf rev = STRBUF_INIT;
092bbcdf 4118 struct object_id head, to_amend;
9d93ccd1 4119
092bbcdf 4120 if (get_oid("HEAD", &head))
9d93ccd1
JS
4121 return error(_("cannot amend non-existing commit"));
4122 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4123 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 4124 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
4125 return error(_("invalid contents: '%s'"),
4126 rebase_path_amend());
9001dc2a 4127 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
4128 return error(_("\nYou have uncommitted changes in your "
4129 "working tree. Please, commit them\n"
4130 "first and then run 'git rebase "
4131 "--continue' again."));
15ef6931
JS
4132 /*
4133 * When skipping a failed fixup/squash, we need to edit the
4134 * commit message, the current fixup list and count, and if it
4135 * was the last fixup/squash in the chain, we need to clean up
4136 * the commit message and if there was a squash, let the user
4137 * edit it.
4138 */
10d2f354
JS
4139 if (!is_clean || !opts->current_fixup_count)
4140 ; /* this is not the final fixup */
87ae8a1a 4141 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
4142 !file_exists(rebase_path_stopped_sha())) {
4143 /* was a final fixup or squash done manually? */
4144 if (!is_fixup(peek_command(todo_list, 0))) {
4145 unlink(rebase_path_fixup_msg());
4146 unlink(rebase_path_squash_msg());
4147 unlink(rebase_path_current_fixups());
4148 strbuf_reset(&opts->current_fixups);
4149 opts->current_fixup_count = 0;
4150 }
4151 } else {
4152 /* we are in a fixup/squash chain */
15ef6931
JS
4153 const char *p = opts->current_fixups.buf;
4154 int len = opts->current_fixups.len;
4155
4156 opts->current_fixup_count--;
4157 if (!len)
4158 BUG("Incorrect current_fixups:\n%s", p);
4159 while (len && p[len - 1] != '\n')
4160 len--;
4161 strbuf_setlen(&opts->current_fixups, len);
4162 if (write_message(p, len, rebase_path_current_fixups(),
4163 0) < 0)
4164 return error(_("could not write file: '%s'"),
4165 rebase_path_current_fixups());
4166
4167 /*
4168 * If a fixup/squash in a fixup/squash chain failed, the
4169 * commit message is already correct, no need to commit
4170 * it again.
4171 *
4172 * Only if it is the final command in the fixup/squash
4173 * chain, and only if the chain is longer than a single
4174 * fixup/squash command (which was just skipped), do we
4175 * actually need to re-commit with a cleaned up commit
4176 * message.
4177 */
4178 if (opts->current_fixup_count > 0 &&
4179 !is_fixup(peek_command(todo_list, 0))) {
4180 final_fixup = 1;
4181 /*
4182 * If there was not a single "squash" in the
4183 * chain, we only need to clean up the commit
4184 * message, no need to bother the user with
4185 * opening the commit message in the editor.
4186 */
4187 if (!starts_with(p, "squash ") &&
4188 !strstr(p, "\nsquash "))
4189 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4190 } else if (is_fixup(peek_command(todo_list, 0))) {
4191 /*
4192 * We need to update the squash message to skip
4193 * the latest commit message.
4194 */
4195 struct commit *commit;
4196 const char *path = rebase_path_squash_msg();
b3757442 4197 const char *encoding = get_commit_output_encoding();
15ef6931 4198
005af339 4199 if (parse_head(r, &commit) ||
b3757442 4200 !(p = logmsg_reencode(commit, NULL, encoding)) ||
15ef6931
JS
4201 write_message(p, strlen(p), path, 0)) {
4202 unuse_commit_buffer(commit, p);
4203 return error(_("could not write file: "
4204 "'%s'"), path);
4205 }
4206 unuse_commit_buffer(commit, p);
4207 }
4208 }
9d93ccd1
JS
4209
4210 strbuf_release(&rev);
789b3eff 4211 flags |= AMEND_MSG;
9d93ccd1
JS
4212 }
4213
15ef6931 4214 if (is_clean) {
f11c9580 4215 const char *cherry_pick_head = git_path_cherry_pick_head(r);
15ef6931
JS
4216
4217 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4218 return error(_("could not remove CHERRY_PICK_HEAD"));
4219 if (!final_fixup)
4220 return 0;
4221 }
4222
f11c9580 4223 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
15ef6931 4224 opts, flags))
9d93ccd1
JS
4225 return error(_("could not commit staged changes."));
4226 unlink(rebase_path_amend());
34e7771b 4227 unlink(git_path_merge_head(r));
15ef6931
JS
4228 if (final_fixup) {
4229 unlink(rebase_path_fixup_msg());
4230 unlink(rebase_path_squash_msg());
4231 }
4232 if (opts->current_fixup_count > 0) {
4233 /*
4234 * Whether final fixup or not, we just cleaned up the commit
4235 * message...
4236 */
4237 unlink(rebase_path_current_fixups());
4238 strbuf_reset(&opts->current_fixups);
4239 opts->current_fixup_count = 0;
4240 }
9d93ccd1
JS
4241 return 0;
4242}
4243
f11c9580 4244int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 4245{
004fefa7
JS
4246 struct todo_list todo_list = TODO_LIST_INIT;
4247 int res;
043a4492 4248
f11c9580 4249 if (read_and_refresh_cache(r, opts))
2863584f
JS
4250 return -1;
4251
15ef6931
JS
4252 if (read_populate_opts(opts))
4253 return -1;
9d93ccd1 4254 if (is_rebase_i(opts)) {
005af339 4255 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 4256 goto release_todo_list;
5a5445d8
AG
4257
4258 if (file_exists(rebase_path_dropped())) {
4259 if ((res = todo_list_check_against_backup(r, &todo_list)))
4260 goto release_todo_list;
4261
4262 unlink(rebase_path_dropped());
4263 }
4264
f6b9413b
AG
4265 if (commit_staged_changes(r, opts, &todo_list)) {
4266 res = -1;
4267 goto release_todo_list;
4268 }
4258a6da 4269 } else if (!file_exists(get_todo_path(opts)))
005af339
NTND
4270 return continue_single_pick(r);
4271 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 4272 goto release_todo_list;
043a4492 4273
4258a6da
JS
4274 if (!is_rebase_i(opts)) {
4275 /* Verify that the conflict has been resolved */
f11c9580
NTND
4276 if (file_exists(git_path_cherry_pick_head(r)) ||
4277 file_exists(git_path_revert_head(r))) {
005af339 4278 res = continue_single_pick(r);
4258a6da
JS
4279 if (res)
4280 goto release_todo_list;
4281 }
ffc00a48 4282 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 4283 res = error_dirty_index(r, opts);
004fefa7 4284 goto release_todo_list;
4258a6da
JS
4285 }
4286 todo_list.current++;
ca98c6d4
JS
4287 } else if (file_exists(rebase_path_stopped_sha())) {
4288 struct strbuf buf = STRBUF_INIT;
4289 struct object_id oid;
4290
3442c3d1
DL
4291 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4292 READ_ONELINER_SKIP_IF_EMPTY) &&
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) {
be1bb600 5082 apply_autostash(rebase_path_autostash());
b97e1873 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) {
be1bb600 5093 apply_autostash(rebase_path_autostash());
b97e1873 5094 sequencer_remove_state(opts);
b97e1873
AG
5095
5096 return -1;
1451d0f6 5097 } else if (res == -3) {
be1bb600 5098 apply_autostash(rebase_path_autostash());
b97e1873 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}