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