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