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