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