]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
advice: add enum variants for missing advice variables
[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
48ca53ca 3524__attribute__((format (printf, 2, 3)))
9055e401
JS
3525static int safe_append(const char *filename, const char *fmt, ...)
3526{
3527 va_list ap;
3528 struct lock_file lock = LOCK_INIT;
3529 int fd = hold_lock_file_for_update(&lock, filename,
3530 LOCK_REPORT_ON_ERROR);
3531 struct strbuf buf = STRBUF_INIT;
3532
3533 if (fd < 0)
3534 return -1;
3535
3536 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3537 error_errno(_("could not read '%s'"), filename);
3538 rollback_lock_file(&lock);
3539 return -1;
3540 }
3541 strbuf_complete(&buf, '\n');
3542 va_start(ap, fmt);
3543 strbuf_vaddf(&buf, fmt, ap);
3544 va_end(ap);
3545
3546 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3547 error_errno(_("could not write to '%s'"), filename);
3548 strbuf_release(&buf);
3549 rollback_lock_file(&lock);
3550 return -1;
3551 }
3552 if (commit_lock_file(&lock) < 0) {
3553 strbuf_release(&buf);
3554 rollback_lock_file(&lock);
3555 return error(_("failed to finalize '%s'"), filename);
3556 }
3557
3558 strbuf_release(&buf);
3559 return 0;
3560}
3561
f11c9580 3562static int do_label(struct repository *r, const char *name, int len)
9055e401 3563{
f11c9580 3564 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3565 struct ref_transaction *transaction;
3566 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3567 struct strbuf msg = STRBUF_INIT;
3568 int ret = 0;
3569 struct object_id head_oid;
3570
3571 if (len == 1 && *name == '#')
02127c63 3572 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3573
3574 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3575 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401
JS
3576
3577 transaction = ref_store_transaction_begin(refs, &err);
3578 if (!transaction) {
3579 error("%s", err.buf);
3580 ret = -1;
3581 } else if (get_oid("HEAD", &head_oid)) {
3582 error(_("could not read HEAD"));
3583 ret = -1;
3584 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3585 NULL, 0, msg.buf, &err) < 0 ||
3586 ref_transaction_commit(transaction, &err)) {
3587 error("%s", err.buf);
3588 ret = -1;
3589 }
3590 ref_transaction_free(transaction);
3591 strbuf_release(&err);
3592 strbuf_release(&msg);
3593
3594 if (!ret)
3595 ret = safe_append(rebase_path_refs_to_delete(),
3596 "%s\n", ref_name.buf);
3597 strbuf_release(&ref_name);
3598
3599 return ret;
3600}
3601
48ca53ca 3602__attribute__((format (printf, 3, 4)))
9055e401 3603static const char *reflog_message(struct replay_opts *opts,
d4ac3050
ÆAB
3604 const char *sub_action, const char *fmt, ...)
3605{
3606 va_list ap;
3607 static struct strbuf buf = STRBUF_INIT;
3608 char *reflog_action = getenv(GIT_REFLOG_ACTION);
3609
3610 va_start(ap, fmt);
3611 strbuf_reset(&buf);
3612 strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3613 if (sub_action)
3614 strbuf_addf(&buf, " (%s)", sub_action);
3615 if (fmt) {
3616 strbuf_addstr(&buf, ": ");
3617 strbuf_vaddf(&buf, fmt, ap);
3618 }
3619 va_end(ap);
3620
3621 return buf.buf;
3622}
9055e401 3623
f11c9580
NTND
3624static int do_reset(struct repository *r,
3625 const char *name, int len,
3626 struct replay_opts *opts)
9055e401
JS
3627{
3628 struct strbuf ref_name = STRBUF_INIT;
3629 struct object_id oid;
3630 struct lock_file lock = LOCK_INIT;
3631 struct tree_desc desc;
3632 struct tree *tree;
3633 struct unpack_trees_options unpack_tree_opts;
71571cd7 3634 int ret = 0;
9055e401 3635
3a95f31d 3636 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3637 return -1;
3638
ebddf393
JS
3639 if (len == 10 && !strncmp("[new root]", name, len)) {
3640 if (!opts->have_squash_onto) {
3641 const char *hex;
3642 if (commit_tree("", 0, the_hash_algo->empty_tree,
3643 NULL, &opts->squash_onto,
3644 NULL, NULL))
3645 return error(_("writing fake root commit"));
3646 opts->have_squash_onto = 1;
3647 hex = oid_to_hex(&opts->squash_onto);
3648 if (write_message(hex, strlen(hex),
3649 rebase_path_squash_onto(), 0))
3650 return error(_("writing squash-onto"));
3651 }
3652 oidcpy(&oid, &opts->squash_onto);
3653 } else {
71571cd7
3654 int i;
3655
ebddf393
JS
3656 /* Determine the length of the label */
3657 for (i = 0; i < len; i++)
3658 if (isspace(name[i]))
71571cd7
3659 break;
3660 len = i;
ebddf393
JS
3661
3662 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3663 if (get_oid(ref_name.buf, &oid) &&
3664 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3665 error(_("could not read '%s'"), ref_name.buf);
3666 rollback_lock_file(&lock);
3667 strbuf_release(&ref_name);
3668 return -1;
3669 }
9055e401
JS
3670 }
3671
3672 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3673 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3674 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3675 unpack_tree_opts.src_index = r->index;
3676 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3677 unpack_tree_opts.fn = oneway_merge;
3678 unpack_tree_opts.merge = 1;
3679 unpack_tree_opts.update = 1;
3f267856 3680 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
9055e401 3681
e1ff0a32 3682 if (repo_read_index_unmerged(r)) {
9055e401
JS
3683 rollback_lock_file(&lock);
3684 strbuf_release(&ref_name);
3685 return error_resolve_conflict(_(action_name(opts)));
3686 }
3687
5e575807 3688 if (!fill_tree_descriptor(r, &desc, &oid)) {
9055e401
JS
3689 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3690 rollback_lock_file(&lock);
3691 free((void *)desc.buffer);
3692 strbuf_release(&ref_name);
3693 return -1;
3694 }
3695
3696 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3697 rollback_lock_file(&lock);
3698 free((void *)desc.buffer);
3699 strbuf_release(&ref_name);
3700 return -1;
3701 }
3702
3703 tree = parse_tree_indirect(&oid);
c207e9e1 3704 prime_cache_tree(r, r->index, tree);
9055e401 3705
f11c9580 3706 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3707 ret = error(_("could not write index"));
3708 free((void *)desc.buffer);
3709
3710 if (!ret)
3711 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3712 len, name), "HEAD", &oid,
3713 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3714
3715 strbuf_release(&ref_name);
3716 return ret;
3717}
3718
2b6ad0f4
JS
3719static struct commit *lookup_label(const char *label, int len,
3720 struct strbuf *buf)
3721{
3722 struct commit *commit;
3723
3724 strbuf_reset(buf);
3725 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3726 commit = lookup_commit_reference_by_name(buf->buf);
3727 if (!commit) {
3728 /* fall back to non-rewritten ref or commit */
3729 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3730 commit = lookup_commit_reference_by_name(buf->buf);
3731 }
3732
3733 if (!commit)
3734 error(_("could not resolve '%s'"), buf->buf);
3735
3736 return commit;
3737}
3738
f11c9580
NTND
3739static int do_merge(struct repository *r,
3740 struct commit *commit,
3741 const char *arg, int arg_len,
4c68e7dd
JS
3742 int flags, struct replay_opts *opts)
3743{
3744 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3745 EDIT_MSG | VERIFY_MSG : 0;
3746 struct strbuf ref_name = STRBUF_INIT;
3747 struct commit *head_commit, *merge_commit, *i;
3748 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3749 struct commit_list *to_merge = NULL, **tail = &to_merge;
e145d993 3750 const char *strategy = !opts->xopts_nr &&
14c4586c
EN
3751 (!opts->strategy ||
3752 !strcmp(opts->strategy, "recursive") ||
3753 !strcmp(opts->strategy, "ort")) ?
e145d993 3754 NULL : opts->strategy;
4c68e7dd 3755 struct merge_options o;
2b6ad0f4 3756 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3757 static struct lock_file lock;
3758 const char *p;
3759
3a95f31d 3760 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3761 ret = -1;
3762 goto leave_merge;
3763 }
3764
3765 head_commit = lookup_commit_reference_by_name("HEAD");
3766 if (!head_commit) {
3767 ret = error(_("cannot merge without a current revision"));
3768 goto leave_merge;
3769 }
3770
2b6ad0f4
JS
3771 /*
3772 * For octopus merges, the arg starts with the list of revisions to be
3773 * merged. The list is optionally followed by '#' and the oneline.
3774 */
3775 merge_arg_len = oneline_offset = arg_len;
3776 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3777 if (!*p)
3778 break;
3779 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3780 p += 1 + strspn(p + 1, " \t\n");
3781 oneline_offset = p - arg;
3782 break;
3783 }
3784 k = strcspn(p, " \t\n");
3785 if (!k)
3786 continue;
3787 merge_commit = lookup_label(p, k, &ref_name);
3788 if (!merge_commit) {
3789 ret = error(_("unable to parse '%.*s'"), k, p);
3790 goto leave_merge;
3791 }
3792 tail = &commit_list_insert(merge_commit, tail)->next;
3793 p += k;
3794 merge_arg_len = p - arg;
4c68e7dd
JS
3795 }
3796
2b6ad0f4
JS
3797 if (!to_merge) {
3798 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3799 goto leave_merge;
3800 }
3801
9c85a1c2 3802 if (opts->have_squash_onto &&
4a7e27e9 3803 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3804 /*
3805 * When the user tells us to "merge" something into a
3806 * "[new root]", let's simply fast-forward to the merge head.
3807 */
3808 rollback_lock_file(&lock);
2b6ad0f4
JS
3809 if (to_merge->next)
3810 ret = error(_("octopus merge cannot be executed on "
3811 "top of a [new root]"));
3812 else
f11c9580 3813 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3814 &head_commit->object.oid, 0,
3815 opts);
9c85a1c2
JS
3816 goto leave_merge;
3817 }
3818
4c68e7dd 3819 if (commit) {
5772b0c7
ĐTCD
3820 const char *encoding = get_commit_output_encoding();
3821 const char *message = logmsg_reencode(commit, NULL, encoding);
4c68e7dd
JS
3822 const char *body;
3823 int len;
3824
3825 if (!message) {
3826 ret = error(_("could not get commit message of '%s'"),
3827 oid_to_hex(&commit->object.oid));
3828 goto leave_merge;
3829 }
3830 write_author_script(message);
3831 find_commit_subject(message, &body);
3832 len = strlen(body);
f11c9580 3833 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3834 unuse_commit_buffer(commit, message);
3835 if (ret) {
3836 error_errno(_("could not write '%s'"),
f11c9580 3837 git_path_merge_msg(r));
4c68e7dd
JS
3838 goto leave_merge;
3839 }
3840 } else {
3841 struct strbuf buf = STRBUF_INIT;
3842 int len;
3843
3844 strbuf_addf(&buf, "author %s", git_author_info(0));
3845 write_author_script(buf.buf);
3846 strbuf_reset(&buf);
3847
3848 if (oneline_offset < arg_len) {
3849 p = arg + oneline_offset;
3850 len = arg_len - oneline_offset;
3851 } else {
2b6ad0f4
JS
3852 strbuf_addf(&buf, "Merge %s '%.*s'",
3853 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3854 merge_arg_len, arg);
3855 p = buf.buf;
3856 len = buf.len;
3857 }
3858
f11c9580 3859 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3860 strbuf_release(&buf);
3861 if (ret) {
3862 error_errno(_("could not write '%s'"),
f11c9580 3863 git_path_merge_msg(r));
4c68e7dd
JS
3864 goto leave_merge;
3865 }
3866 }
3867
d1e8b011
JS
3868 /*
3869 * If HEAD is not identical to the first parent of the original merge
3870 * commit, we cannot fast-forward.
3871 */
3872 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3873 oideq(&commit->parents->item->object.oid,
3874 &head_commit->object.oid);
d1e8b011
JS
3875
3876 /*
2b6ad0f4 3877 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3878 * fast-forward.
3879 */
3880 if (can_fast_forward) {
2b6ad0f4 3881 struct commit_list *p = commit->parents->next;
d1e8b011 3882
2b6ad0f4 3883 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3884 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3885 &p->item->object.oid)) {
3886 can_fast_forward = 0;
3887 break;
3888 }
3889 /*
3890 * If the number of merge heads differs from the original merge
3891 * commit, we cannot fast-forward.
3892 */
3893 if (j || p)
d1e8b011
JS
3894 can_fast_forward = 0;
3895 }
3896
2b6ad0f4 3897 if (can_fast_forward) {
d1e8b011 3898 rollback_lock_file(&lock);
f11c9580 3899 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011 3900 &head_commit->object.oid, 0, opts);
6df8df08
PW
3901 if (flags & TODO_EDIT_MERGE_MSG) {
3902 run_commit_flags |= AMEND_MSG;
3903 goto fast_forward_edit;
3904 }
d1e8b011
JS
3905 goto leave_merge;
3906 }
3907
e145d993 3908 if (strategy || to_merge->next) {
2b6ad0f4
JS
3909 /* Octopus merge */
3910 struct child_process cmd = CHILD_PROCESS_INIT;
3911
3912 if (read_env_script(&cmd.env_array)) {
3913 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3914
3915 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3916 goto leave_merge;
3917 }
3918
7573cec5 3919 if (opts->committer_date_is_author_date)
9c31b19d
JH
3920 strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3921 opts->ignore_date ?
3922 "" :
3923 author_date_from_env_array(&cmd.env_array));
a3894aad 3924 if (opts->ignore_date)
9c31b19d 3925 strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
7573cec5 3926
2b6ad0f4 3927 cmd.git_cmd = 1;
c972bf4c
JK
3928 strvec_push(&cmd.args, "merge");
3929 strvec_push(&cmd.args, "-s");
e145d993 3930 if (!strategy)
c972bf4c 3931 strvec_push(&cmd.args, "octopus");
e145d993 3932 else {
c972bf4c 3933 strvec_push(&cmd.args, strategy);
e145d993 3934 for (k = 0; k < opts->xopts_nr; k++)
c972bf4c 3935 strvec_pushf(&cmd.args,
f6d8942b 3936 "-X%s", opts->xopts[k]);
e145d993 3937 }
c972bf4c
JK
3938 strvec_push(&cmd.args, "--no-edit");
3939 strvec_push(&cmd.args, "--no-ff");
3940 strvec_push(&cmd.args, "--no-log");
3941 strvec_push(&cmd.args, "--no-stat");
3942 strvec_push(&cmd.args, "-F");
3943 strvec_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4 3944 if (opts->gpg_sign)
ae03c97a 3945 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
19dad040
3946 else
3947 strvec_push(&cmd.args, "--no-gpg-sign");
2b6ad0f4
JS
3948
3949 /* Add the tips to be merged */
3950 for (j = to_merge; j; j = j->next)
c972bf4c 3951 strvec_push(&cmd.args,
f6d8942b 3952 oid_to_hex(&j->item->object.oid));
2b6ad0f4
JS
3953
3954 strbuf_release(&ref_name);
c8e4159e
HWN
3955 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3956 NULL, 0);
2b6ad0f4
JS
3957 rollback_lock_file(&lock);
3958
2b6ad0f4
JS
3959 ret = run_command(&cmd);
3960
3961 /* force re-reading of the cache */
f11c9580 3962 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3963 repo_read_index(r) < 0))
2b6ad0f4
JS
3964 ret = error(_("could not read index"));
3965 goto leave_merge;
3966 }
3967
3968 merge_commit = to_merge->item;
4c68e7dd 3969 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3970 if (bases && oideq(&merge_commit->object.oid,
3971 &bases->item->object.oid)) {
7ccdf65b
JS
3972 ret = 0;
3973 /* skip merging an ancestor of HEAD */
3974 goto leave_merge;
3975 }
3976
4439c7a3 3977 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
3978 git_path_merge_head(r), 0);
3979 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3980
4c68e7dd
JS
3981 for (j = bases; j; j = j->next)
3982 commit_list_insert(j->item, &reversed);
3983 free_commit_list(bases);
3984
e1ff0a32 3985 repo_read_index(r);
0d6caa2d 3986 init_merge_options(&o, r);
4c68e7dd
JS
3987 o.branch1 = "HEAD";
3988 o.branch2 = ref_name.buf;
3989 o.buffer_output = 2;
3990
14c4586c
EN
3991 if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3992 /*
3993 * TODO: Should use merge_incore_recursive() and
3994 * merge_switch_to_result(), skipping the call to
3995 * merge_switch_to_result() when we don't actually need to
3996 * update the index and working copy immediately.
3997 */
3998 ret = merge_ort_recursive(&o,
3999 head_commit, merge_commit, reversed,
4000 &i);
4001 } else {
4002 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
4003 &i);
4004 }
4c68e7dd
JS
4005 if (ret <= 0)
4006 fputs(o.obuf.buf, stdout);
4007 strbuf_release(&o.obuf);
4008 if (ret < 0) {
4009 error(_("could not even attempt to merge '%.*s'"),
4010 merge_arg_len, arg);
4011 goto leave_merge;
4012 }
4013 /*
4014 * The return value of merge_recursive() is 1 on clean, and 0 on
4015 * unclean merge.
4016 *
4017 * Let's reverse that, so that do_merge() returns 0 upon success and
4018 * 1 upon failed merge (keeping the return value -1 for the cases where
4019 * we will want to reschedule the `merge` command).
4020 */
4021 ret = !ret;
4022
f11c9580
NTND
4023 if (r->index->cache_changed &&
4024 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
4025 ret = error(_("merge: Unable to write new index file"));
4026 goto leave_merge;
4027 }
4028
4029 rollback_lock_file(&lock);
4030 if (ret)
f11c9580 4031 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
4032 else
4033 /*
4034 * In case of problems, we now want to return a positive
4035 * value (a negative one would indicate that the `merge`
4036 * command needs to be rescheduled).
4037 */
6df8df08 4038 fast_forward_edit:
20f4b044 4039 ret = !!run_git_commit(git_path_merge_msg(r), opts,
f11c9580 4040 run_commit_flags);
4c68e7dd
JS
4041
4042leave_merge:
4043 strbuf_release(&ref_name);
4044 rollback_lock_file(&lock);
2b6ad0f4 4045 free_commit_list(to_merge);
4c68e7dd
JS
4046 return ret;
4047}
4048
6e98de72
JS
4049static int is_final_fixup(struct todo_list *todo_list)
4050{
4051 int i = todo_list->current;
4052
4053 if (!is_fixup(todo_list->items[i].command))
4054 return 0;
4055
4056 while (++i < todo_list->nr)
4057 if (is_fixup(todo_list->items[i].command))
4058 return 0;
4059 else if (!is_noop(todo_list->items[i].command))
4060 break;
4061 return 1;
4062}
4063
25cb8df9
JS
4064static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4065{
4066 int i;
4067
4068 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4069 if (!is_noop(todo_list->items[i].command))
4070 return todo_list->items[i].command;
4071
4072 return -1;
4073}
4074
0816f1df
DL
4075void create_autostash(struct repository *r, const char *path,
4076 const char *default_reflog_action)
4077{
4078 struct strbuf buf = STRBUF_INIT;
4079 struct lock_file lock_file = LOCK_INIT;
4080 int fd;
4081
4082 fd = repo_hold_locked_index(r, &lock_file, 0);
4083 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4084 if (0 <= fd)
4085 repo_update_index_if_able(r, &lock_file);
4086 rollback_lock_file(&lock_file);
4087
4088 if (has_unstaged_changes(r, 1) ||
4089 has_uncommitted_changes(r, 1)) {
4090 struct child_process stash = CHILD_PROCESS_INIT;
4091 struct object_id oid;
4092
c972bf4c 4093 strvec_pushl(&stash.args,
f6d8942b 4094 "stash", "create", "autostash", NULL);
0816f1df
DL
4095 stash.git_cmd = 1;
4096 stash.no_stdin = 1;
4097 strbuf_reset(&buf);
4098 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4099 die(_("Cannot autostash"));
4100 strbuf_trim_trailing_newline(&buf);
4101 if (get_oid(buf.buf, &oid))
4102 die(_("Unexpected stash response: '%s'"),
4103 buf.buf);
4104 strbuf_reset(&buf);
4105 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4106
4107 if (safe_create_leading_directories_const(path))
4108 die(_("Could not create directory for '%s'"),
4109 path);
4110 write_file(path, "%s", oid_to_hex(&oid));
4111 printf(_("Created autostash: %s\n"), buf.buf);
4112 if (reset_head(r, NULL, "reset --hard",
4113 NULL, RESET_HEAD_HARD, NULL, NULL,
4114 default_reflog_action) < 0)
4115 die(_("could not reset --hard"));
4116
4117 if (discard_index(r->index) < 0 ||
4118 repo_read_index(r) < 0)
4119 die(_("could not read index"));
4120 }
4121 strbuf_release(&buf);
4122}
4123
804fe315 4124static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
796c7972 4125{
796c7972
JS
4126 struct child_process child = CHILD_PROCESS_INIT;
4127 int ret = 0;
4128
12b6e136
DL
4129 if (attempt_apply) {
4130 child.git_cmd = 1;
4131 child.no_stdout = 1;
4132 child.no_stderr = 1;
c972bf4c
JK
4133 strvec_push(&child.args, "stash");
4134 strvec_push(&child.args, "apply");
4135 strvec_push(&child.args, stash_oid);
12b6e136 4136 ret = run_command(&child);
796c7972 4137 }
796c7972 4138
12b6e136 4139 if (attempt_apply && !ret)
cdb866b3 4140 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
4141 else {
4142 struct child_process store = CHILD_PROCESS_INIT;
4143
4144 store.git_cmd = 1;
c972bf4c
JK
4145 strvec_push(&store.args, "stash");
4146 strvec_push(&store.args, "store");
4147 strvec_push(&store.args, "-m");
4148 strvec_push(&store.args, "autostash");
4149 strvec_push(&store.args, "-q");
4150 strvec_push(&store.args, stash_oid);
796c7972 4151 if (run_command(&store))
804fe315 4152 ret = error(_("cannot store %s"), stash_oid);
796c7972 4153 else
cdb866b3 4154 fprintf(stderr,
12b6e136 4155 _("%s\n"
cdb866b3
JS
4156 "Your changes are safe in the stash.\n"
4157 "You can run \"git stash pop\" or"
12b6e136
DL
4158 " \"git stash drop\" at any time.\n"),
4159 attempt_apply ?
4160 _("Applying autostash resulted in conflicts.") :
4161 _("Autostash exists; creating a new stash entry."));
796c7972
JS
4162 }
4163
796c7972
JS
4164 return ret;
4165}
4166
804fe315
DL
4167static int apply_save_autostash(const char *path, int attempt_apply)
4168{
4169 struct strbuf stash_oid = STRBUF_INIT;
4170 int ret = 0;
4171
4172 if (!read_oneliner(&stash_oid, path,
4173 READ_ONELINER_SKIP_IF_EMPTY)) {
4174 strbuf_release(&stash_oid);
4175 return 0;
4176 }
4177 strbuf_trim(&stash_oid);
4178
4179 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4180
0dd562e0 4181 unlink(path);
facca7f0 4182 strbuf_release(&stash_oid);
796c7972
JS
4183 return ret;
4184}
4185
12b6e136
DL
4186int save_autostash(const char *path)
4187{
4188 return apply_save_autostash(path, 0);
4189}
4190
4191int apply_autostash(const char *path)
4192{
4193 return apply_save_autostash(path, 1);
4194}
4195
804fe315
DL
4196int apply_autostash_oid(const char *stash_oid)
4197{
4198 return apply_save_autostash_oid(stash_oid, 1);
4199}
4200
fc4a6735
PW
4201static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4202 const char *commit, const char *action)
2c58483a
AG
4203{
4204 struct child_process cmd = CHILD_PROCESS_INIT;
fc4a6735 4205 int ret;
2c58483a
AG
4206
4207 cmd.git_cmd = 1;
4208
c972bf4c
JK
4209 strvec_push(&cmd.args, "checkout");
4210 strvec_push(&cmd.args, commit);
4211 strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
2c58483a
AG
4212
4213 if (opts->verbose)
fc4a6735 4214 ret = run_command(&cmd);
2c58483a 4215 else
fc4a6735
PW
4216 ret = run_command_silent_on_success(&cmd);
4217
4218 if (!ret)
4219 discard_index(r->index);
4220
4221 return ret;
2c58483a
AG
4222}
4223
fc4a6735 4224static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 4225 const char *onto_name, const struct object_id *onto,
f3e27a02 4226 const struct object_id *orig_head)
4df66c40 4227{
4df66c40
AG
4228 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4229
7d3488eb 4230 if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
be1bb600 4231 apply_autostash(rebase_path_autostash());
4df66c40
AG
4232 sequencer_remove_state(opts);
4233 return error(_("could not detach HEAD"));
4234 }
4235
f3e27a02 4236 return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4df66c40
AG
4237}
4238
005af339 4239static int stopped_at_head(struct repository *r)
71f82465
JS
4240{
4241 struct object_id head;
4242 struct commit *commit;
4243 struct commit_message message;
4244
789b1f70 4245 if (get_oid("HEAD", &head) ||
005af339 4246 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
4247 parse_commit(commit) || get_message(commit, &message))
4248 fprintf(stderr, _("Stopped at HEAD\n"));
4249 else {
4250 fprintf(stderr, _("Stopped at %s\n"), message.label);
4251 free_message(commit, &message);
4252 }
4253 return 0;
4254
4255}
4256
cb5206ea
JS
4257static const char rescheduled_advice[] =
4258N_("Could not execute the todo command\n"
4259"\n"
4260" %.*s"
4261"\n"
4262"It has been rescheduled; To edit the command before continuing, please\n"
4263"edit the todo list first:\n"
4264"\n"
4265" git rebase --edit-todo\n"
4266" git rebase --continue\n");
4267
f11c9580
NTND
4268static int pick_commits(struct repository *r,
4269 struct todo_list *todo_list,
4270 struct replay_opts *opts)
043a4492 4271{
9055e401 4272 int res = 0, reschedule = 0;
1f6965f9 4273 char *prev_reflog_action;
043a4492 4274
1f6965f9 4275 /* Note that 0 for 3rd parameter of setenv means set only if not set */
043a4492 4276 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
1f6965f9 4277 prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
043a4492
RR
4278 if (opts->allow_ff)
4279 assert(!(opts->signoff || opts->no_commit ||
39edfd5c 4280 opts->record_origin || should_edit(opts) ||
a3894aad
PW
4281 opts->committer_date_is_author_date ||
4282 opts->ignore_date));
f11c9580 4283 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4284 return -1;
043a4492 4285
004fefa7
JS
4286 while (todo_list->current < todo_list->nr) {
4287 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 4288 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 4289 int check_todo = 0;
6ad656db 4290
004fefa7 4291 if (save_todo(todo_list, opts))
221675de 4292 return -1;
6e98de72 4293 if (is_rebase_i(opts)) {
ef80069a
JS
4294 if (item->command != TODO_COMMENT) {
4295 FILE *f = fopen(rebase_path_msgnum(), "w");
4296
4297 todo_list->done_nr++;
4298
4299 if (f) {
4300 fprintf(f, "%d\n", todo_list->done_nr);
4301 fclose(f);
4302 }
899b49c4 4303 if (!opts->quiet)
4d55d63b 4304 fprintf(stderr, _("Rebasing (%d/%d)%s"),
899b49c4
EN
4305 todo_list->done_nr,
4306 todo_list->total_nr,
4307 opts->verbose ? "\n" : "\r");
ef80069a 4308 }
6e98de72
JS
4309 unlink(rebase_path_message());
4310 unlink(rebase_path_author_script());
4311 unlink(rebase_path_stopped_sha());
4312 unlink(rebase_path_amend());
34e7771b 4313 unlink(git_path_merge_head(r));
5291828d 4314 unlink(git_path_auto_merge(r));
fbd7a232 4315 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465 4316
d7d90885
SG
4317 if (item->command == TODO_BREAK) {
4318 if (!opts->verbose)
4319 term_clear_line();
005af339 4320 return stopped_at_head(r);
d7d90885 4321 }
6e98de72
JS
4322 }
4323 if (item->command <= TODO_SQUASH) {
8ab37ef2 4324 if (is_rebase_i(opts))
1f6965f9 4325 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
8ab37ef2
JS
4326 command_to_string(item->command), NULL),
4327 1);
ae70e34f
CM
4328 res = do_pick_commit(r, item, opts,
4329 is_final_fixup(todo_list),
a47ba3c7 4330 &check_todo);
1f6965f9
EN
4331 if (is_rebase_i(opts))
4332 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
9d7bf3cf
JS
4333 if (is_rebase_i(opts) && res < 0) {
4334 /* Reschedule */
cb5206ea
JS
4335 advise(_(rescheduled_advice),
4336 get_item_line_length(todo_list,
4337 todo_list->current),
4338 get_item_line(todo_list,
4339 todo_list->current));
9d7bf3cf
JS
4340 todo_list->current--;
4341 if (save_todo(todo_list, opts))
4342 return -1;
4343 }
56dc3ab0
JS
4344 if (item->command == TODO_EDIT) {
4345 struct commit *commit = item->commit;
d7d90885
SG
4346 if (!res) {
4347 if (!opts->verbose)
4348 term_clear_line();
99429213 4349 fprintf(stderr,
a42e1b41 4350 _("Stopped at %s... %.*s\n"),
56dc3ab0 4351 short_commit_name(commit),
6ad656db 4352 item->arg_len, arg);
d7d90885 4353 }
f11c9580 4354 return error_with_patch(r, commit,
6ad656db 4355 arg, item->arg_len, opts, res, !res);
56dc3ab0 4356 }
25cb8df9
JS
4357 if (is_rebase_i(opts) && !res)
4358 record_in_rewritten(&item->commit->object.oid,
4359 peek_command(todo_list, 1));
6e98de72
JS
4360 if (res && is_fixup(item->command)) {
4361 if (res == 1)
4362 intend_to_amend();
f11c9580 4363 return error_failed_squash(r, item->commit, opts,
6ad656db 4364 item->arg_len, arg);
a9279c67
PW
4365 } else if (res && is_rebase_i(opts) && item->commit) {
4366 int to_amend = 0;
4367 struct object_id oid;
4368
4369 /*
4370 * If we are rewording and have either
4371 * fast-forwarded already, or are about to
4372 * create a new root commit, we want to amend,
4373 * otherwise we do not.
4374 */
4375 if (item->command == TODO_REWORD &&
4376 !get_oid("HEAD", &oid) &&
4a7e27e9 4377 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 4378 (opts->have_squash_onto &&
4a7e27e9 4379 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
4380 to_amend = 1;
4381
f11c9580 4382 return res | error_with_patch(r, item->commit,
6ad656db 4383 arg, item->arg_len, opts,
a9279c67
PW
4384 res, to_amend);
4385 }
311af526 4386 } else if (item->command == TODO_EXEC) {
6ad656db 4387 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
4388 int saved = *end_of_arg;
4389
d7d90885
SG
4390 if (!opts->verbose)
4391 term_clear_line();
311af526 4392 *end_of_arg = '\0';
6ad656db 4393 res = do_exec(r, arg);
311af526 4394 *end_of_arg = saved;
54fd3243 4395
d421afa0
JS
4396 if (res) {
4397 if (opts->reschedule_failed_exec)
4398 reschedule = 1;
54fd3243 4399 }
a47ba3c7 4400 check_todo = 1;
9055e401 4401 } else if (item->command == TODO_LABEL) {
6ad656db 4402 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
4403 reschedule = 1;
4404 } else if (item->command == TODO_RESET) {
6ad656db 4405 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 4406 reschedule = 1;
4c68e7dd 4407 } else if (item->command == TODO_MERGE) {
f11c9580 4408 if ((res = do_merge(r, item->commit,
6ad656db 4409 arg, item->arg_len,
4c68e7dd
JS
4410 item->flags, opts)) < 0)
4411 reschedule = 1;
537e7d61
JS
4412 else if (item->commit)
4413 record_in_rewritten(&item->commit->object.oid,
4414 peek_command(todo_list, 1));
4415 if (res > 0)
4c68e7dd 4416 /* failed with merge conflicts */
f11c9580 4417 return error_with_patch(r, item->commit,
6ad656db
AG
4418 arg, item->arg_len,
4419 opts, res, 0);
56dc3ab0 4420 } else if (!is_noop(item->command))
25c43667
JS
4421 return error(_("unknown command %d"), item->command);
4422
9055e401
JS
4423 if (reschedule) {
4424 advise(_(rescheduled_advice),
4425 get_item_line_length(todo_list,
4426 todo_list->current),
4427 get_item_line(todo_list, todo_list->current));
4428 todo_list->current--;
4429 if (save_todo(todo_list, opts))
4430 return -1;
4c68e7dd 4431 if (item->commit)
f11c9580
NTND
4432 return error_with_patch(r,
4433 item->commit,
6ad656db
AG
4434 arg, item->arg_len,
4435 opts, res, 0);
befd4f6a 4436 } else if (is_rebase_i(opts) && check_todo && !res) {
a47ba3c7
PW
4437 struct stat st;
4438
4439 if (stat(get_todo_path(opts), &st)) {
4440 res = error_errno(_("could not stat '%s'"),
4441 get_todo_path(opts));
4442 } else if (match_stat_data(&todo_list->stat, &st)) {
4443 /* Reread the todo file if it has changed. */
4444 todo_list_release(todo_list);
4445 if (read_populate_todo(r, todo_list, opts))
4446 res = -1; /* message was printed */
4447 /* `current` will be incremented below */
4448 todo_list->current = -1;
4449 }
9055e401
JS
4450 }
4451
004fefa7 4452 todo_list->current++;
043a4492
RR
4453 if (res)
4454 return res;
4455 }
4456
56dc3ab0 4457 if (is_rebase_i(opts)) {
4b83ce9f 4458 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 4459 struct stat st;
556907f1 4460
56dc3ab0
JS
4461 /* Stopped in the middle, as planned? */
4462 if (todo_list->current < todo_list->nr)
4463 return 0;
556907f1 4464
4b83ce9f
JS
4465 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4466 starts_with(head_ref.buf, "refs/")) {
96e832a5 4467 const char *msg;
092bbcdf 4468 struct object_id head, orig;
4b83ce9f
JS
4469 int res;
4470
092bbcdf 4471 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
4472 res = error(_("cannot read HEAD"));
4473cleanup_head_ref:
4474 strbuf_release(&head_ref);
4475 strbuf_release(&buf);
4476 return res;
4477 }
4478 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 4479 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
4480 res = error(_("could not read orig-head"));
4481 goto cleanup_head_ref;
4482 }
4ab867b8 4483 strbuf_reset(&buf);
4b83ce9f
JS
4484 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4485 res = error(_("could not read 'onto'"));
4486 goto cleanup_head_ref;
4487 }
96e832a5
JS
4488 msg = reflog_message(opts, "finish", "%s onto %s",
4489 head_ref.buf, buf.buf);
ae077771 4490 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 4491 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
4492 res = error(_("could not update %s"),
4493 head_ref.buf);
4494 goto cleanup_head_ref;
4495 }
96e832a5 4496 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 4497 head_ref.buf);
96e832a5 4498 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
4499 res = error(_("could not update HEAD to %s"),
4500 head_ref.buf);
4501 goto cleanup_head_ref;
4502 }
4503 strbuf_reset(&buf);
4504 }
4505
556907f1
JS
4506 if (opts->verbose) {
4507 struct rev_info log_tree_opt;
4508 struct object_id orig, head;
4509
4510 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 4511 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
4512 log_tree_opt.diff = 1;
4513 log_tree_opt.diffopt.output_format =
4514 DIFF_FORMAT_DIFFSTAT;
4515 log_tree_opt.disable_stdin = 1;
4516
4517 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 4518 !get_oid(buf.buf, &orig) &&
4519 !get_oid("HEAD", &head)) {
66f414f8
BW
4520 diff_tree_oid(&orig, &head, "",
4521 &log_tree_opt.diffopt);
556907f1
JS
4522 log_tree_diff_flush(&log_tree_opt);
4523 }
4524 }
25cb8df9
JS
4525 flush_rewritten_pending();
4526 if (!stat(rebase_path_rewritten_list(), &st) &&
4527 st.st_size > 0) {
4528 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
4529 const char *post_rewrite_hook =
4530 find_hook("post-rewrite");
25cb8df9
JS
4531
4532 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4533 child.git_cmd = 1;
c972bf4c
JK
4534 strvec_push(&child.args, "notes");
4535 strvec_push(&child.args, "copy");
4536 strvec_push(&child.args, "--for-rewrite=rebase");
25cb8df9
JS
4537 /* we don't care if this copying failed */
4538 run_command(&child);
79516045
JS
4539
4540 if (post_rewrite_hook) {
4541 struct child_process hook = CHILD_PROCESS_INIT;
4542
4543 hook.in = open(rebase_path_rewritten_list(),
4544 O_RDONLY);
4545 hook.stdout_to_stderr = 1;
6206286e 4546 hook.trace2_hook_name = "post-rewrite";
c972bf4c
JK
4547 strvec_push(&hook.args, post_rewrite_hook);
4548 strvec_push(&hook.args, "rebase");
79516045
JS
4549 /* we don't care if this hook failed */
4550 run_command(&hook);
4551 }
25cb8df9 4552 }
be1bb600 4553 apply_autostash(rebase_path_autostash());
25cb8df9 4554
d7d90885
SG
4555 if (!opts->quiet) {
4556 if (!opts->verbose)
4557 term_clear_line();
899b49c4 4558 fprintf(stderr,
4d55d63b 4559 _("Successfully rebased and updated %s.\n"),
899b49c4 4560 head_ref.buf);
d7d90885 4561 }
5da4966f 4562
556907f1 4563 strbuf_release(&buf);
4b83ce9f 4564 strbuf_release(&head_ref);
56dc3ab0
JS
4565 }
4566
043a4492
RR
4567 /*
4568 * Sequence of picks finished successfully; cleanup by
4569 * removing the .git/sequencer directory
4570 */
2863584f 4571 return sequencer_remove_state(opts);
043a4492
RR
4572}
4573
39edfd5c 4574static int continue_single_pick(struct repository *r, struct replay_opts *opts)
043a4492 4575{
39edfd5c
EN
4576 struct strvec argv = STRVEC_INIT;
4577 int ret;
043a4492 4578
c8e4159e 4579 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 4580 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 4581 return error(_("no cherry-pick or revert in progress"));
39edfd5c
EN
4582
4583 strvec_push(&argv, "commit");
4584
4585 /*
4586 * continue_single_pick() handles the case of recovering from a
4587 * conflict. should_edit() doesn't handle that case; for a conflict,
4588 * we want to edit if the user asked for it, or if they didn't specify
4589 * and stdin is a tty.
4590 */
4591 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4592 /*
4593 * Include --cleanup=strip as well because we don't want the
4594 * "# Conflicts:" messages.
4595 */
4596 strvec_pushl(&argv, "--no-edit", "--cleanup=strip", NULL);
4597
4598 ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
4599 strvec_clear(&argv);
4600 return ret;
043a4492
RR
4601}
4602
f11c9580
NTND
4603static int commit_staged_changes(struct repository *r,
4604 struct replay_opts *opts,
15ef6931 4605 struct todo_list *todo_list)
9d93ccd1 4606{
789b3eff 4607 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 4608 unsigned int final_fixup = 0, is_clean;
9d93ccd1 4609
f11c9580 4610 if (has_unstaged_changes(r, 1))
9d93ccd1 4611 return error(_("cannot rebase: You have unstaged changes."));
52632209 4612
f11c9580 4613 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
4614
4615 if (file_exists(rebase_path_amend())) {
4616 struct strbuf rev = STRBUF_INIT;
092bbcdf 4617 struct object_id head, to_amend;
9d93ccd1 4618
092bbcdf 4619 if (get_oid("HEAD", &head))
9d93ccd1
JS
4620 return error(_("cannot amend non-existing commit"));
4621 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4622 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 4623 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
4624 return error(_("invalid contents: '%s'"),
4625 rebase_path_amend());
9001dc2a 4626 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
4627 return error(_("\nYou have uncommitted changes in your "
4628 "working tree. Please, commit them\n"
4629 "first and then run 'git rebase "
4630 "--continue' again."));
15ef6931
JS
4631 /*
4632 * When skipping a failed fixup/squash, we need to edit the
4633 * commit message, the current fixup list and count, and if it
4634 * was the last fixup/squash in the chain, we need to clean up
4635 * the commit message and if there was a squash, let the user
4636 * edit it.
4637 */
10d2f354
JS
4638 if (!is_clean || !opts->current_fixup_count)
4639 ; /* this is not the final fixup */
87ae8a1a 4640 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
4641 !file_exists(rebase_path_stopped_sha())) {
4642 /* was a final fixup or squash done manually? */
4643 if (!is_fixup(peek_command(todo_list, 0))) {
4644 unlink(rebase_path_fixup_msg());
4645 unlink(rebase_path_squash_msg());
4646 unlink(rebase_path_current_fixups());
4647 strbuf_reset(&opts->current_fixups);
4648 opts->current_fixup_count = 0;
4649 }
4650 } else {
4651 /* we are in a fixup/squash chain */
15ef6931
JS
4652 const char *p = opts->current_fixups.buf;
4653 int len = opts->current_fixups.len;
4654
4655 opts->current_fixup_count--;
4656 if (!len)
4657 BUG("Incorrect current_fixups:\n%s", p);
4658 while (len && p[len - 1] != '\n')
4659 len--;
4660 strbuf_setlen(&opts->current_fixups, len);
4661 if (write_message(p, len, rebase_path_current_fixups(),
4662 0) < 0)
4663 return error(_("could not write file: '%s'"),
4664 rebase_path_current_fixups());
4665
4666 /*
4667 * If a fixup/squash in a fixup/squash chain failed, the
4668 * commit message is already correct, no need to commit
4669 * it again.
4670 *
4671 * Only if it is the final command in the fixup/squash
4672 * chain, and only if the chain is longer than a single
4673 * fixup/squash command (which was just skipped), do we
4674 * actually need to re-commit with a cleaned up commit
4675 * message.
4676 */
4677 if (opts->current_fixup_count > 0 &&
4678 !is_fixup(peek_command(todo_list, 0))) {
4679 final_fixup = 1;
4680 /*
4681 * If there was not a single "squash" in the
4682 * chain, we only need to clean up the commit
4683 * message, no need to bother the user with
4684 * opening the commit message in the editor.
4685 */
4686 if (!starts_with(p, "squash ") &&
4687 !strstr(p, "\nsquash "))
4688 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4689 } else if (is_fixup(peek_command(todo_list, 0))) {
4690 /*
4691 * We need to update the squash message to skip
4692 * the latest commit message.
4693 */
4694 struct commit *commit;
4695 const char *path = rebase_path_squash_msg();
b3757442 4696 const char *encoding = get_commit_output_encoding();
15ef6931 4697
005af339 4698 if (parse_head(r, &commit) ||
b3757442 4699 !(p = logmsg_reencode(commit, NULL, encoding)) ||
15ef6931
JS
4700 write_message(p, strlen(p), path, 0)) {
4701 unuse_commit_buffer(commit, p);
4702 return error(_("could not write file: "
4703 "'%s'"), path);
4704 }
4705 unuse_commit_buffer(commit, p);
4706 }
4707 }
9d93ccd1
JS
4708
4709 strbuf_release(&rev);
789b3eff 4710 flags |= AMEND_MSG;
9d93ccd1
JS
4711 }
4712
15ef6931 4713 if (is_clean) {
c8e4159e
HWN
4714 if (refs_ref_exists(get_main_ref_store(r),
4715 "CHERRY_PICK_HEAD") &&
4716 refs_delete_ref(get_main_ref_store(r), "",
4717 "CHERRY_PICK_HEAD", NULL, 0))
15ef6931
JS
4718 return error(_("could not remove CHERRY_PICK_HEAD"));
4719 if (!final_fixup)
4720 return 0;
4721 }
4722
20f4b044 4723 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
15ef6931 4724 opts, flags))
9d93ccd1
JS
4725 return error(_("could not commit staged changes."));
4726 unlink(rebase_path_amend());
34e7771b 4727 unlink(git_path_merge_head(r));
5291828d 4728 unlink(git_path_auto_merge(r));
15ef6931
JS
4729 if (final_fixup) {
4730 unlink(rebase_path_fixup_msg());
4731 unlink(rebase_path_squash_msg());
4732 }
4733 if (opts->current_fixup_count > 0) {
4734 /*
4735 * Whether final fixup or not, we just cleaned up the commit
4736 * message...
4737 */
4738 unlink(rebase_path_current_fixups());
4739 strbuf_reset(&opts->current_fixups);
4740 opts->current_fixup_count = 0;
4741 }
9d93ccd1
JS
4742 return 0;
4743}
4744
f11c9580 4745int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 4746{
004fefa7
JS
4747 struct todo_list todo_list = TODO_LIST_INIT;
4748 int res;
043a4492 4749
f11c9580 4750 if (read_and_refresh_cache(r, opts))
2863584f
JS
4751 return -1;
4752
15ef6931
JS
4753 if (read_populate_opts(opts))
4754 return -1;
9d93ccd1 4755 if (is_rebase_i(opts)) {
005af339 4756 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 4757 goto release_todo_list;
5a5445d8
AG
4758
4759 if (file_exists(rebase_path_dropped())) {
4760 if ((res = todo_list_check_against_backup(r, &todo_list)))
4761 goto release_todo_list;
4762
4763 unlink(rebase_path_dropped());
4764 }
4765
f6b9413b
AG
4766 if (commit_staged_changes(r, opts, &todo_list)) {
4767 res = -1;
4768 goto release_todo_list;
4769 }
4258a6da 4770 } else if (!file_exists(get_todo_path(opts)))
39edfd5c 4771 return continue_single_pick(r, opts);
005af339 4772 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 4773 goto release_todo_list;
043a4492 4774
4258a6da
JS
4775 if (!is_rebase_i(opts)) {
4776 /* Verify that the conflict has been resolved */
c8e4159e
HWN
4777 if (refs_ref_exists(get_main_ref_store(r),
4778 "CHERRY_PICK_HEAD") ||
b8825ef2 4779 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
39edfd5c 4780 res = continue_single_pick(r, opts);
4258a6da
JS
4781 if (res)
4782 goto release_todo_list;
4783 }
ffc00a48 4784 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 4785 res = error_dirty_index(r, opts);
004fefa7 4786 goto release_todo_list;
4258a6da
JS
4787 }
4788 todo_list.current++;
ca98c6d4
JS
4789 } else if (file_exists(rebase_path_stopped_sha())) {
4790 struct strbuf buf = STRBUF_INIT;
4791 struct object_id oid;
4792
3442c3d1
DL
4793 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4794 READ_ONELINER_SKIP_IF_EMPTY) &&
0512eabd 4795 !get_oid_hex(buf.buf, &oid))
ca98c6d4
JS
4796 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4797 strbuf_release(&buf);
043a4492 4798 }
4258a6da 4799
f11c9580 4800 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4801release_todo_list:
4802 todo_list_release(&todo_list);
4803 return res;
043a4492
RR
4804}
4805
f11c9580
NTND
4806static int single_pick(struct repository *r,
4807 struct commit *cmit,
4808 struct replay_opts *opts)
043a4492 4809{
a47ba3c7 4810 int check_todo;
ae70e34f
CM
4811 struct todo_item item;
4812
4813 item.command = opts->action == REPLAY_PICK ?
4814 TODO_PICK : TODO_REVERT;
4815 item.commit = cmit;
a47ba3c7 4816
043a4492 4817 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
ae70e34f 4818 return do_pick_commit(r, &item, opts, 0, &check_todo);
043a4492
RR
4819}
4820
f11c9580
NTND
4821int sequencer_pick_revisions(struct repository *r,
4822 struct replay_opts *opts)
043a4492 4823{
004fefa7 4824 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 4825 struct object_id oid;
004fefa7 4826 int i, res;
043a4492 4827
2863584f 4828 assert(opts->revs);
f11c9580 4829 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4830 return -1;
043a4492 4831
21246dbb 4832 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 4833 struct object_id oid;
21246dbb
MV
4834 const char *name = opts->revs->pending.objects[i].name;
4835
4836 /* This happens when using --stdin. */
4837 if (!strlen(name))
4838 continue;
4839
1e43ed98 4840 if (!get_oid(name, &oid)) {
f11c9580
NTND
4841 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4842 enum object_type type = oid_object_info(r,
0df8e965 4843 &oid,
abef9020 4844 NULL);
b9b946d4 4845 return error(_("%s: can't cherry-pick a %s"),
debca9d2 4846 name, type_name(type));
7c0b0d8d 4847 }
21246dbb 4848 } else
b9b946d4 4849 return error(_("%s: bad revision"), name);
21246dbb
MV
4850 }
4851
043a4492
RR
4852 /*
4853 * If we were called as "git cherry-pick <commit>", just
4854 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4855 * REVERT_HEAD, and don't touch the sequencer state.
4856 * This means it is possible to cherry-pick in the middle
4857 * of a cherry-pick sequence.
4858 */
4859 if (opts->revs->cmdline.nr == 1 &&
4860 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4861 opts->revs->no_walk &&
4862 !opts->revs->cmdline.rev->flags) {
4863 struct commit *cmit;
4864 if (prepare_revision_walk(opts->revs))
b9b946d4 4865 return error(_("revision walk setup failed"));
043a4492 4866 cmit = get_revision(opts->revs);
c5e358d0
JK
4867 if (!cmit)
4868 return error(_("empty commit set passed"));
4869 if (get_revision(opts->revs))
4870 BUG("unexpected extra commit from walk");
f11c9580 4871 return single_pick(r, cmit, opts);
043a4492
RR
4872 }
4873
4874 /*
4875 * Start a new cherry-pick/ revert sequence; but
4876 * first, make sure that an existing one isn't in
4877 * progress
4878 */
4879
34b0528b 4880 if (walk_revs_populate_todo(&todo_list, opts) ||
6a1f9046 4881 create_seq_dir(r) < 0)
043a4492 4882 return -1;
1e43ed98 4883 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 4884 return error(_("can't revert as initial commit"));
1e43ed98 4885 if (save_head(oid_to_hex(&oid)))
311fd397 4886 return -1;
88d5a271
JS
4887 if (save_opts(opts))
4888 return -1;
1e41229d 4889 update_abort_safety_file();
f11c9580 4890 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4891 todo_list_release(&todo_list);
4892 return res;
043a4492 4893}
5ed75e2a 4894
66e83d9b 4895void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 4896{
bab4d109 4897 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 4898 struct strbuf sob = STRBUF_INIT;
bab4d109 4899 int has_footer;
5ed75e2a
MV
4900
4901 strbuf_addstr(&sob, sign_off_header);
39ab4d09 4902 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 4903 strbuf_addch(&sob, '\n');
bab4d109 4904
44dc738a
JT
4905 if (!ignore_footer)
4906 strbuf_complete_line(msgbuf);
4907
bab4d109
BC
4908 /*
4909 * If the whole message buffer is equal to the sob, pretend that we
4910 * found a conforming footer with a matching sob
4911 */
4912 if (msgbuf->len - ignore_footer == sob.len &&
4913 !strncmp(msgbuf->buf, sob.buf, sob.len))
4914 has_footer = 3;
4915 else
4916 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4917
33f2f9ab
BC
4918 if (!has_footer) {
4919 const char *append_newlines = NULL;
4920 size_t len = msgbuf->len - ignore_footer;
4921
8c613fd5
BC
4922 if (!len) {
4923 /*
4924 * The buffer is completely empty. Leave foom for
4925 * the title and body to be filled in by the user.
4926 */
33f2f9ab 4927 append_newlines = "\n\n";
8c613fd5
BC
4928 } else if (len == 1) {
4929 /*
4930 * Buffer contains a single newline. Add another
4931 * so that we leave room for the title and body.
4932 */
4933 append_newlines = "\n";
4934 } else if (msgbuf->buf[len - 2] != '\n') {
4935 /*
4936 * Buffer ends with a single newline. Add another
4937 * so that there is an empty line between the message
4938 * body and the sob.
4939 */
33f2f9ab 4940 append_newlines = "\n";
8c613fd5 4941 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
4942
4943 if (append_newlines)
4944 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4945 append_newlines, strlen(append_newlines));
5ed75e2a 4946 }
bab4d109
BC
4947
4948 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4949 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4950 sob.buf, sob.len);
4951
5ed75e2a
MV
4952 strbuf_release(&sob);
4953}
62db5247 4954
1644c73c
JS
4955struct labels_entry {
4956 struct hashmap_entry entry;
4957 char label[FLEX_ARRAY];
4958};
4959
939af16e
EW
4960static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4961 const struct hashmap_entry *entry_or_key, const void *key)
1644c73c 4962{
939af16e
EW
4963 const struct labels_entry *a, *b;
4964
4965 a = container_of(eptr, const struct labels_entry, entry);
4966 b = container_of(entry_or_key, const struct labels_entry, entry);
4967
1644c73c
JS
4968 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4969}
4970
4971struct string_entry {
4972 struct oidmap_entry entry;
4973 char string[FLEX_ARRAY];
4974};
4975
4976struct label_state {
4977 struct oidmap commit2label;
4978 struct hashmap labels;
4979 struct strbuf buf;
4980};
4981
4982static const char *label_oid(struct object_id *oid, const char *label,
4983 struct label_state *state)
4984{
4985 struct labels_entry *labels_entry;
4986 struct string_entry *string_entry;
4987 struct object_id dummy;
1644c73c
JS
4988 int i;
4989
4990 string_entry = oidmap_get(&state->commit2label, oid);
4991 if (string_entry)
4992 return string_entry->string;
4993
4994 /*
4995 * For "uninteresting" commits, i.e. commits that are not to be
4996 * rebased, and which can therefore not be labeled, we use a unique
4997 * abbreviation of the commit name. This is slightly more complicated
4998 * than calling find_unique_abbrev() because we also need to make
4999 * sure that the abbreviation does not conflict with any other
5000 * label.
5001 *
5002 * We disallow "interesting" commits to be labeled by a string that
5003 * is a valid full-length hash, to ensure that we always can find an
5004 * abbreviation for any uninteresting commit's names that does not
5005 * clash with any other label.
5006 */
867bc1d2 5007 strbuf_reset(&state->buf);
1644c73c
JS
5008 if (!label) {
5009 char *p;
5010
4439c7a3 5011 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
1644c73c
JS
5012 label = p = state->buf.buf;
5013
5014 find_unique_abbrev_r(p, oid, default_abbrev);
5015
5016 /*
5017 * We may need to extend the abbreviated hash so that there is
5018 * no conflicting label.
5019 */
5020 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5021 size_t i = strlen(p) + 1;
5022
5023 oid_to_hex_r(p, oid);
4439c7a3 5024 for (; i < the_hash_algo->hexsz; i++) {
1644c73c
JS
5025 char save = p[i];
5026 p[i] = '\0';
5027 if (!hashmap_get_from_hash(&state->labels,
5028 strihash(p), p))
5029 break;
5030 p[i] = save;
5031 }
5032 }
867bc1d2 5033 } else {
1644c73c
JS
5034 struct strbuf *buf = &state->buf;
5035
1644c73c 5036 /*
cd552227
MR
5037 * Sanitize labels by replacing non-alpha-numeric characters
5038 * (including white-space ones) by dashes, as they might be
5039 * illegal in file names (and hence in ref names).
5040 *
5041 * Note that we retain non-ASCII UTF-8 characters (identified
5042 * via the most significant bit). They should be all acceptable
5043 * in file names. We do not validate the UTF-8 here, that's not
5044 * the job of this function.
1644c73c 5045 */
867bc1d2 5046 for (; *label; label++)
cd552227
MR
5047 if ((*label & 0x80) || isalnum(*label))
5048 strbuf_addch(buf, *label);
5049 /* avoid leading dash and double-dashes */
5050 else if (buf->len && buf->buf[buf->len - 1] != '-')
5051 strbuf_addch(buf, '-');
5052 if (!buf->len) {
5053 strbuf_addstr(buf, "rev-");
5054 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5055 }
867bc1d2 5056 label = buf->buf;
1644c73c 5057
867bc1d2
JS
5058 if ((buf->len == the_hash_algo->hexsz &&
5059 !get_oid_hex(label, &dummy)) ||
5060 (buf->len == 1 && *label == '#') ||
5061 hashmap_get_from_hash(&state->labels,
5062 strihash(label), label)) {
5063 /*
5064 * If the label already exists, or if the label is a
5065 * valid full OID, or the label is a '#' (which we use
5066 * as a separator between merge heads and oneline), we
5067 * append a dash and a number to make it unique.
5068 */
5069 size_t len = buf->len;
1644c73c 5070
867bc1d2
JS
5071 for (i = 2; ; i++) {
5072 strbuf_setlen(buf, len);
5073 strbuf_addf(buf, "-%d", i);
5074 if (!hashmap_get_from_hash(&state->labels,
5075 strihash(buf->buf),
5076 buf->buf))
5077 break;
5078 }
1644c73c 5079
867bc1d2
JS
5080 label = buf->buf;
5081 }
1644c73c
JS
5082 }
5083
5084 FLEX_ALLOC_STR(labels_entry, label, label);
d22245a2 5085 hashmap_entry_init(&labels_entry->entry, strihash(label));
b94e5c1d 5086 hashmap_add(&state->labels, &labels_entry->entry);
1644c73c
JS
5087
5088 FLEX_ALLOC_STR(string_entry, string, label);
5089 oidcpy(&string_entry->entry.oid, oid);
5090 oidmap_put(&state->commit2label, string_entry);
5091
5092 return string_entry->string;
5093}
5094
5095static int make_script_with_merges(struct pretty_print_context *pp,
d358fc28 5096 struct rev_info *revs, struct strbuf *out,
1644c73c
JS
5097 unsigned flags)
5098{
b9cbd295 5099 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 5100 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
e1fac531 5101 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
1644c73c
JS
5102 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5103 struct strbuf label = STRBUF_INIT;
5104 struct commit_list *commits = NULL, **tail = &commits, *iter;
5105 struct commit_list *tips = NULL, **tips_tail = &tips;
5106 struct commit *commit;
5107 struct oidmap commit2todo = OIDMAP_INIT;
5108 struct string_entry *entry;
5109 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5110 shown = OIDSET_INIT;
5111 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5112
5113 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5114 const char *cmd_pick = abbr ? "p" : "pick",
5115 *cmd_label = abbr ? "l" : "label",
5116 *cmd_reset = abbr ? "t" : "reset",
5117 *cmd_merge = abbr ? "m" : "merge";
5118
5119 oidmap_init(&commit2todo, 0);
5120 oidmap_init(&state.commit2label, 0);
939af16e 5121 hashmap_init(&state.labels, labels_cmp, NULL, 0);
1644c73c
JS
5122 strbuf_init(&state.buf, 32);
5123
5124 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
e02058a7 5125 struct labels_entry *onto_label_entry;
1644c73c
JS
5126 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5127 FLEX_ALLOC_STR(entry, string, "onto");
5128 oidcpy(&entry->entry.oid, oid);
5129 oidmap_put(&state.commit2label, entry);
e02058a7
ĐTCD
5130
5131 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5132 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5133 hashmap_add(&state.labels, &onto_label_entry->entry);
1644c73c
JS
5134 }
5135
5136 /*
5137 * First phase:
5138 * - get onelines for all commits
5139 * - gather all branch tips (i.e. 2nd or later parents of merges)
5140 * - label all branch tips
5141 */
5142 while ((commit = get_revision(revs))) {
5143 struct commit_list *to_merge;
1644c73c
JS
5144 const char *p1, *p2;
5145 struct object_id *oid;
5146 int is_empty;
5147
5148 tail = &commit_list_insert(commit, tail)->next;
5149 oidset_insert(&interesting, &commit->object.oid);
5150
5151 is_empty = is_original_commit_empty(commit);
5152 if (!is_empty && (commit->object.flags & PATCHSAME))
5153 continue;
b9cbd295
EN
5154 if (is_empty && !keep_empty)
5155 continue;
1644c73c
JS
5156
5157 strbuf_reset(&oneline);
5158 pretty_print_commit(pp, commit, &oneline);
5159
5160 to_merge = commit->parents ? commit->parents->next : NULL;
5161 if (!to_merge) {
5162 /* non-merge commit: easy case */
5163 strbuf_reset(&buf);
1644c73c
JS
5164 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5165 oid_to_hex(&commit->object.oid),
5166 oneline.buf);
1b5735f7
EN
5167 if (is_empty)
5168 strbuf_addf(&buf, " %c empty",
5169 comment_line_char);
1644c73c
JS
5170
5171 FLEX_ALLOC_STR(entry, string, buf.buf);
5172 oidcpy(&entry->entry.oid, &commit->object.oid);
5173 oidmap_put(&commit2todo, entry);
5174
5175 continue;
5176 }
5177
1644c73c
JS
5178 /* Create a label */
5179 strbuf_reset(&label);
5180 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5181 (p1 = strchr(p1, '\'')) &&
5182 (p2 = strchr(++p1, '\'')))
5183 strbuf_add(&label, p1, p2 - p1);
5184 else if (skip_prefix(oneline.buf, "Merge pull request ",
5185 &p1) &&
5186 (p1 = strstr(p1, " from ")))
5187 strbuf_addstr(&label, p1 + strlen(" from "));
5188 else
5189 strbuf_addbuf(&label, &oneline);
5190
1644c73c
JS
5191 strbuf_reset(&buf);
5192 strbuf_addf(&buf, "%s -C %s",
5193 cmd_merge, oid_to_hex(&commit->object.oid));
5194
2b6ad0f4
JS
5195 /* label the tips of merged branches */
5196 for (; to_merge; to_merge = to_merge->next) {
5197 oid = &to_merge->item->object.oid;
5198 strbuf_addch(&buf, ' ');
5199
5200 if (!oidset_contains(&interesting, oid)) {
5201 strbuf_addstr(&buf, label_oid(oid, NULL,
5202 &state));
5203 continue;
5204 }
1644c73c 5205
1644c73c
JS
5206 tips_tail = &commit_list_insert(to_merge->item,
5207 tips_tail)->next;
5208
5209 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5210 }
5211 strbuf_addf(&buf, " # %s", oneline.buf);
5212
5213 FLEX_ALLOC_STR(entry, string, buf.buf);
5214 oidcpy(&entry->entry.oid, &commit->object.oid);
5215 oidmap_put(&commit2todo, entry);
5216 }
5217
5218 /*
5219 * Second phase:
5220 * - label branch points
5221 * - add HEAD to the branch tips
5222 */
5223 for (iter = commits; iter; iter = iter->next) {
5224 struct commit_list *parent = iter->item->parents;
5225 for (; parent; parent = parent->next) {
5226 struct object_id *oid = &parent->item->object.oid;
5227 if (!oidset_contains(&interesting, oid))
5228 continue;
6e8fc70f 5229 if (oidset_insert(&child_seen, oid))
1644c73c
JS
5230 label_oid(oid, "branch-point", &state);
5231 }
5232
15beaaa3 5233 /* Add HEAD as implicit "tip of branch" */
1644c73c
JS
5234 if (!iter->next)
5235 tips_tail = &commit_list_insert(iter->item,
5236 tips_tail)->next;
5237 }
5238
5239 /*
5240 * Third phase: output the todo list. This is a bit tricky, as we
5241 * want to avoid jumping back and forth between revisions. To
5242 * accomplish that goal, we walk backwards from the branch tips,
5243 * gathering commits not yet shown, reversing the list on the fly,
5244 * then outputting that list (labeling revisions as needed).
5245 */
d358fc28 5246 strbuf_addf(out, "%s onto\n", cmd_label);
1644c73c
JS
5247 for (iter = tips; iter; iter = iter->next) {
5248 struct commit_list *list = NULL, *iter2;
5249
5250 commit = iter->item;
5251 if (oidset_contains(&shown, &commit->object.oid))
5252 continue;
5253 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5254
5255 if (entry)
d358fc28 5256 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c 5257 else
d358fc28 5258 strbuf_addch(out, '\n');
1644c73c
JS
5259
5260 while (oidset_contains(&interesting, &commit->object.oid) &&
5261 !oidset_contains(&shown, &commit->object.oid)) {
5262 commit_list_insert(commit, &list);
5263 if (!commit->parents) {
5264 commit = NULL;
5265 break;
5266 }
5267 commit = commit->parents->item;
5268 }
5269
5270 if (!commit)
d358fc28 5271 strbuf_addf(out, "%s %s\n", cmd_reset,
e1fac531
JS
5272 rebase_cousins || root_with_onto ?
5273 "onto" : "[new root]");
1644c73c
JS
5274 else {
5275 const char *to = NULL;
5276
5277 entry = oidmap_get(&state.commit2label,
5278 &commit->object.oid);
5279 if (entry)
5280 to = entry->string;
7543f6f4
JS
5281 else if (!rebase_cousins)
5282 to = label_oid(&commit->object.oid, NULL,
5283 &state);
1644c73c
JS
5284
5285 if (!to || !strcmp(to, "onto"))
d358fc28 5286 strbuf_addf(out, "%s onto\n", cmd_reset);
1644c73c
JS
5287 else {
5288 strbuf_reset(&oneline);
5289 pretty_print_commit(pp, commit, &oneline);
d358fc28
AG
5290 strbuf_addf(out, "%s %s # %s\n",
5291 cmd_reset, to, oneline.buf);
1644c73c
JS
5292 }
5293 }
5294
5295 for (iter2 = list; iter2; iter2 = iter2->next) {
5296 struct object_id *oid = &iter2->item->object.oid;
5297 entry = oidmap_get(&commit2todo, oid);
5298 /* only show if not already upstream */
5299 if (entry)
d358fc28 5300 strbuf_addf(out, "%s\n", entry->string);
1644c73c
JS
5301 entry = oidmap_get(&state.commit2label, oid);
5302 if (entry)
d358fc28
AG
5303 strbuf_addf(out, "%s %s\n",
5304 cmd_label, entry->string);
1644c73c
JS
5305 oidset_insert(&shown, oid);
5306 }
5307
5308 free_commit_list(list);
5309 }
5310
5311 free_commit_list(commits);
5312 free_commit_list(tips);
5313
5314 strbuf_release(&label);
5315 strbuf_release(&oneline);
5316 strbuf_release(&buf);
5317
5318 oidmap_free(&commit2todo, 1);
5319 oidmap_free(&state.commit2label, 1);
6da1a258 5320 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
1644c73c
JS
5321 strbuf_release(&state.buf);
5322
5323 return 0;
5324}
5325
d358fc28
AG
5326int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5327 const char **argv, unsigned flags)
62db5247
JS
5328{
5329 char *format = NULL;
5330 struct pretty_print_context pp = {0};
62db5247
JS
5331 struct rev_info revs;
5332 struct commit *commit;
b9cbd295 5333 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 5334 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 5335 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
0fcb4f6b 5336 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
62db5247 5337
f11c9580 5338 repo_init_revisions(r, &revs, NULL);
62db5247 5339 revs.verbose_header = 1;
1644c73c
JS
5340 if (!rebase_merges)
5341 revs.max_parents = 1;
0fcb4f6b 5342 revs.cherry_mark = !reapply_cherry_picks;
62db5247
JS
5343 revs.limited = 1;
5344 revs.reverse = 1;
5345 revs.right_only = 1;
5346 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5347 revs.topo_order = 1;
5348
5349 revs.pretty_given = 1;
5350 git_config_get_string("rebase.instructionFormat", &format);
5351 if (!format || !*format) {
5352 free(format);
5353 format = xstrdup("%s");
5354 }
5355 get_commit_format(format, &revs);
5356 free(format);
5357 pp.fmt = revs.commit_format;
5358 pp.output_encoding = get_log_output_encoding();
5359
5360 if (setup_revisions(argc, argv, &revs, NULL) > 1)
5361 return error(_("make_script: unhandled options"));
5362
5363 if (prepare_revision_walk(&revs) < 0)
5364 return error(_("make_script: error preparing revisions"));
5365
1644c73c
JS
5366 if (rebase_merges)
5367 return make_script_with_merges(&pp, &revs, out, flags);
5368
62db5247 5369 while ((commit = get_revision(&revs))) {
d48e5e21 5370 int is_empty = is_original_commit_empty(commit);
76ea2358
PW
5371
5372 if (!is_empty && (commit->object.flags & PATCHSAME))
5373 continue;
b9cbd295
EN
5374 if (is_empty && !keep_empty)
5375 continue;
d358fc28 5376 strbuf_addf(out, "%s %s ", insn,
d8ae6c84 5377 oid_to_hex(&commit->object.oid));
d358fc28 5378 pretty_print_commit(&pp, commit, out);
1b5735f7
EN
5379 if (is_empty)
5380 strbuf_addf(out, " %c empty", comment_line_char);
d358fc28 5381 strbuf_addch(out, '\n');
62db5247 5382 }
62db5247
JS
5383 return 0;
5384}
3546c8d9 5385
0cce4a27
LB
5386/*
5387 * Add commands after pick and (series of) squash/fixup commands
5388 * in the todo list.
5389 */
1ba204de
AG
5390void todo_list_add_exec_commands(struct todo_list *todo_list,
5391 struct string_list *commands)
3546c8d9 5392{
683153a4
AG
5393 struct strbuf *buf = &todo_list->buf;
5394 size_t base_offset = buf->len;
5395 int i, insert, nr = 0, alloc = 0;
5396 struct todo_item *items = NULL, *base_items = NULL;
3546c8d9 5397
ca56dadb 5398 CALLOC_ARRAY(base_items, commands->nr);
683153a4
AG
5399 for (i = 0; i < commands->nr; i++) {
5400 size_t command_len = strlen(commands->items[i].string);
3546c8d9 5401
683153a4
AG
5402 strbuf_addstr(buf, commands->items[i].string);
5403 strbuf_addch(buf, '\n');
3546c8d9 5404
683153a4
AG
5405 base_items[i].command = TODO_EXEC;
5406 base_items[i].offset_in_buf = base_offset;
5407 base_items[i].arg_offset = base_offset + strlen("exec ");
5408 base_items[i].arg_len = command_len - strlen("exec ");
3546c8d9 5409
683153a4 5410 base_offset += command_len + 1;
3546c8d9
JS
5411 }
5412
1ace63bc
JS
5413 /*
5414 * Insert <commands> after every pick. Here, fixup/squash chains
5415 * are considered part of the pick, so we insert the commands *after*
5416 * those chains if there are any.
683153a4 5417 *
15beaaa3 5418 * As we insert the exec commands immediately after rearranging
683153a4
AG
5419 * any fixups and before the user edits the list, a fixup chain
5420 * can never contain comments (any comments are empty picks that
5421 * have been commented out because the user did not specify
5422 * --keep-empty). So, it is safe to insert an exec command
5423 * without looking at the command following a comment.
1ace63bc 5424 */
683153a4
AG
5425 insert = 0;
5426 for (i = 0; i < todo_list->nr; i++) {
5427 enum todo_command command = todo_list->items[i].command;
5428 if (insert && !is_fixup(command)) {
5429 ALLOC_GROW(items, nr + commands->nr, alloc);
5430 COPY_ARRAY(items + nr, base_items, commands->nr);
5431 nr += commands->nr;
5432
5433 insert = 0;
0cce4a27 5434 }
1ace63bc 5435
683153a4
AG
5436 ALLOC_GROW(items, nr + 1, alloc);
5437 items[nr++] = todo_list->items[i];
5438
1ace63bc 5439 if (command == TODO_PICK || command == TODO_MERGE)
683153a4 5440 insert = 1;
0cce4a27
LB
5441 }
5442
1ace63bc 5443 /* insert or append final <commands> */
683153a4
AG
5444 if (insert || nr == todo_list->nr) {
5445 ALLOC_GROW(items, nr + commands->nr, alloc);
5446 COPY_ARRAY(items + nr, base_items, commands->nr);
5447 nr += commands->nr;
5448 }
0cce4a27 5449
683153a4
AG
5450 free(base_items);
5451 FREE_AND_NULL(todo_list->items);
5452 todo_list->items = items;
5453 todo_list->nr = nr;
5454 todo_list->alloc = alloc;
0cce4a27 5455}
3546c8d9 5456
616d7740
AG
5457static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5458 struct strbuf *buf, int num, unsigned flags)
3546c8d9 5459{
8dccc7a6 5460 struct todo_item *item;
616d7740 5461 int i, max = todo_list->nr;
3546c8d9 5462
616d7740
AG
5463 if (num > 0 && num < max)
5464 max = num;
3546c8d9 5465
616d7740 5466 for (item = todo_list->items, i = 0; i < max; i++, item++) {
68e7090f
AG
5467 char cmd;
5468
8dccc7a6
LB
5469 /* if the item is not a command write it and continue */
5470 if (item->command >= TODO_COMMENT) {
616d7740 5471 strbuf_addf(buf, "%.*s\n", item->arg_len,
cbef27d6 5472 todo_item_get_arg(todo_list, item));
8dccc7a6 5473 continue;
3546c8d9 5474 }
8dccc7a6
LB
5475
5476 /* add command to the buffer */
68e7090f
AG
5477 cmd = command_to_char(item->command);
5478 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5479 strbuf_addch(buf, cmd);
d8ae6c84 5480 else
616d7740 5481 strbuf_addstr(buf, command_to_string(item->command));
8dccc7a6
LB
5482
5483 /* add commit id */
5484 if (item->commit) {
313a48ea 5485 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
5486 short_commit_name(item->commit) :
5487 oid_to_hex(&item->commit->object.oid);
5488
9e3cebd9
CM
5489 if (item->command == TODO_FIXUP) {
5490 if (item->flags & TODO_EDIT_FIXUP_MSG)
5491 strbuf_addstr(buf, " -c");
5492 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5493 strbuf_addstr(buf, " -C");
5494 }
5495 }
5496
4c68e7dd
JS
5497 if (item->command == TODO_MERGE) {
5498 if (item->flags & TODO_EDIT_MERGE_MSG)
616d7740 5499 strbuf_addstr(buf, " -c");
4c68e7dd 5500 else
616d7740 5501 strbuf_addstr(buf, " -C");
4c68e7dd
JS
5502 }
5503
616d7740 5504 strbuf_addf(buf, " %s", oid);
3546c8d9 5505 }
4c68e7dd 5506
8dccc7a6 5507 /* add all the rest */
c7b4d79c 5508 if (!item->arg_len)
616d7740 5509 strbuf_addch(buf, '\n');
c7b4d79c 5510 else
616d7740 5511 strbuf_addf(buf, " %.*s\n", item->arg_len,
cbef27d6 5512 todo_item_get_arg(todo_list, item));
3546c8d9 5513 }
3546c8d9 5514}
94399949 5515
616d7740
AG
5516int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5517 const char *file, const char *shortrevisions,
5518 const char *shortonto, int num, unsigned flags)
94399949 5519{
af1fc3ad 5520 int res;
616d7740 5521 struct strbuf buf = STRBUF_INIT;
94399949 5522
616d7740 5523 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
af1fc3ad 5524 if (flags & TODO_LIST_APPEND_TODO_HELP)
d48e5e21 5525 append_todo_help(count_commands(todo_list),
af1fc3ad 5526 shortrevisions, shortonto, &buf);
94399949 5527
616d7740 5528 res = write_message(buf.buf, buf.len, file, 0);
cbef27d6 5529 strbuf_release(&buf);
8315bd20 5530
616d7740 5531 return res;
cbef27d6 5532}
94399949 5533
cdac2b01 5534/* skip picking commits whose parents are unchanged */
6bfeb7f1
AG
5535static int skip_unnecessary_picks(struct repository *r,
5536 struct todo_list *todo_list,
5537 struct object_id *base_oid)
cdac2b01 5538{
d4ed5d77 5539 struct object_id *parent_oid;
6bfeb7f1 5540 int i;
cdac2b01 5541
6bfeb7f1
AG
5542 for (i = 0; i < todo_list->nr; i++) {
5543 struct todo_item *item = todo_list->items + i;
cdac2b01
JS
5544
5545 if (item->command >= TODO_NOOP)
5546 continue;
5547 if (item->command != TODO_PICK)
5548 break;
5549 if (parse_commit(item->commit)) {
cdac2b01
JS
5550 return error(_("could not parse commit '%s'"),
5551 oid_to_hex(&item->commit->object.oid));
5552 }
5553 if (!item->commit->parents)
5554 break; /* root commit */
5555 if (item->commit->parents->next)
5556 break; /* merge commit */
5557 parent_oid = &item->commit->parents->item->object.oid;
6bfeb7f1 5558 if (!oideq(parent_oid, base_oid))
cdac2b01 5559 break;
6bfeb7f1 5560 oidcpy(base_oid, &item->commit->object.oid);
cdac2b01
JS
5561 }
5562 if (i > 0) {
cdac2b01
JS
5563 const char *done_path = rebase_path_done();
5564
6bfeb7f1 5565 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
cdac2b01 5566 error_errno(_("could not write to '%s'"), done_path);
cdac2b01
JS
5567 return -1;
5568 }
cdac2b01 5569
6bfeb7f1
AG
5570 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5571 todo_list->nr -= i;
5572 todo_list->current = 0;
34065541 5573 todo_list->done_nr += i;
cdac2b01 5574
6bfeb7f1
AG
5575 if (is_fixup(peek_command(todo_list, 0)))
5576 record_in_rewritten(base_oid, peek_command(todo_list, 0));
cdac2b01
JS
5577 }
5578
cdac2b01
JS
5579 return 0;
5580}
c44a4c65 5581
005af339 5582int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873 5583 const char *shortrevisions, const char *onto_name,
f3e27a02 5584 struct commit *onto, const struct object_id *orig_head,
7d3488eb
PW
5585 struct string_list *commands, unsigned autosquash,
5586 struct todo_list *todo_list)
b97e1873 5587{
5da69c0d
AK
5588 char shortonto[GIT_MAX_HEXSZ + 1];
5589 const char *todo_file = rebase_path_todo();
94bcad79 5590 struct todo_list new_todo = TODO_LIST_INIT;
b6992261 5591 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
7d3488eb 5592 struct object_id oid = onto->object.oid;
1451d0f6 5593 int res;
b97e1873 5594
5da69c0d 5595 find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
b97e1873 5596
94bcad79
AG
5597 if (buf->len == 0) {
5598 struct todo_item *item = append_new_todo(todo_list);
5599 item->command = TODO_NOOP;
5600 item->commit = NULL;
5601 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5602 }
b97e1873 5603
94bcad79 5604 if (autosquash && todo_list_rearrange_squash(todo_list))
b97e1873
AG
5605 return -1;
5606
683153a4 5607 if (commands->nr)
94bcad79 5608 todo_list_add_exec_commands(todo_list, commands);
b97e1873 5609
94bcad79 5610 if (count_commands(todo_list) == 0) {
be1bb600 5611 apply_autostash(rebase_path_autostash());
b97e1873 5612 sequencer_remove_state(opts);
b97e1873
AG
5613
5614 return error(_("nothing to do"));
5615 }
5616
1451d0f6
AG
5617 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5618 shortonto, flags);
5619 if (res == -1)
b97e1873 5620 return -1;
1451d0f6 5621 else if (res == -2) {
be1bb600 5622 apply_autostash(rebase_path_autostash());
b97e1873 5623 sequencer_remove_state(opts);
b97e1873
AG
5624
5625 return -1;
1451d0f6 5626 } else if (res == -3) {
be1bb600 5627 apply_autostash(rebase_path_autostash());
b97e1873 5628 sequencer_remove_state(opts);
94bcad79 5629 todo_list_release(&new_todo);
b97e1873
AG
5630
5631 return error(_("nothing to do"));
5a5445d8 5632 } else if (res == -4) {
7d3488eb 5633 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
94bcad79
AG
5634 todo_list_release(&new_todo);
5635
b97e1873
AG
5636 return -1;
5637 }
5638
b6992261
JS
5639 /* Expand the commit IDs */
5640 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5641 strbuf_swap(&new_todo.buf, &buf2);
5642 strbuf_release(&buf2);
5643 new_todo.total_nr -= new_todo.nr;
5644 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5645 BUG("invalid todo list after expanding IDs:\n%s",
5646 new_todo.buf.buf);
5647
6bfeb7f1
AG
5648 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5649 todo_list_release(&new_todo);
b97e1873 5650 return error(_("could not skip unnecessary pick commands"));
6bfeb7f1
AG
5651 }
5652
94bcad79
AG
5653 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5654 flags & ~(TODO_LIST_SHORTEN_IDS))) {
5655 todo_list_release(&new_todo);
5656 return error_errno(_("could not write '%s'"), todo_file);
5657 }
5658
393adf7a 5659 res = -1;
b97e1873 5660
7d3488eb 5661 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
393adf7a 5662 goto cleanup;
29d51e21 5663
005af339 5664 if (require_clean_work_tree(r, "rebase", "", 1, 1))
393adf7a 5665 goto cleanup;
b97e1873 5666
393adf7a
AG
5667 todo_list_write_total_nr(&new_todo);
5668 res = pick_commits(r, &new_todo, opts);
5669
5670cleanup:
5671 todo_list_release(&new_todo);
5672
5673 return res;
b97e1873
AG
5674}
5675
c44a4c65
JS
5676struct subject2item_entry {
5677 struct hashmap_entry entry;
5678 int i;
5679 char subject[FLEX_ARRAY];
5680};
5681
5682static int subject2item_cmp(const void *fndata,
939af16e
EW
5683 const struct hashmap_entry *eptr,
5684 const struct hashmap_entry *entry_or_key,
5685 const void *key)
c44a4c65 5686{
939af16e
EW
5687 const struct subject2item_entry *a, *b;
5688
5689 a = container_of(eptr, const struct subject2item_entry, entry);
5690 b = container_of(entry_or_key, const struct subject2item_entry, entry);
5691
c44a4c65
JS
5692 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5693}
5694
3cc0287b
NTND
5695define_commit_slab(commit_todo_item, struct todo_item *);
5696
1f969601 5697static int skip_fixupish(const char *subject, const char **p) {
bae5b4ae
CM
5698 return skip_prefix(subject, "fixup! ", p) ||
5699 skip_prefix(subject, "amend! ", p) ||
5700 skip_prefix(subject, "squash! ", p);
5701}
5702
c44a4c65
JS
5703/*
5704 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5705 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5706 * after the former, and change "pick" to "fixup"/"squash".
5707 *
5708 * Note that if the config has specified a custom instruction format, each log
5709 * message will have to be retrieved from the commit (as the oneline in the
5710 * script cannot be trusted) in order to normalize the autosquash arrangement.
5711 */
79d7e883 5712int todo_list_rearrange_squash(struct todo_list *todo_list)
c44a4c65 5713{
c44a4c65 5714 struct hashmap subject2item;
f2a04904 5715 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
c44a4c65 5716 char **subjects;
3cc0287b 5717 struct commit_todo_item commit_todo;
f2a04904 5718 struct todo_item *items = NULL;
c44a4c65 5719
3cc0287b 5720 init_commit_todo_item(&commit_todo);
c44a4c65
JS
5721 /*
5722 * The hashmap maps onelines to the respective todo list index.
5723 *
5724 * If any items need to be rearranged, the next[i] value will indicate
5725 * which item was moved directly after the i'th.
5726 *
5727 * In that case, last[i] will indicate the index of the latest item to
5728 * be moved to appear after the i'th.
5729 */
939af16e 5730 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
f2a04904
AG
5731 ALLOC_ARRAY(next, todo_list->nr);
5732 ALLOC_ARRAY(tail, todo_list->nr);
5733 ALLOC_ARRAY(subjects, todo_list->nr);
5734 for (i = 0; i < todo_list->nr; i++) {
c44a4c65 5735 struct strbuf buf = STRBUF_INIT;
f2a04904 5736 struct todo_item *item = todo_list->items + i;
c44a4c65
JS
5737 const char *commit_buffer, *subject, *p;
5738 size_t subject_len;
5739 int i2 = -1;
5740 struct subject2item_entry *entry;
5741
5742 next[i] = tail[i] = -1;
2f6b1d13 5743 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
5744 subjects[i] = NULL;
5745 continue;
5746 }
5747
5748 if (is_fixup(item->command)) {
3cc0287b 5749 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5750 return error(_("the script was already rearranged."));
5751 }
5752
3cc0287b 5753 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
5754
5755 parse_commit(item->commit);
0798d16f 5756 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
c44a4c65
JS
5757 find_commit_subject(commit_buffer, &subject);
5758 format_subject(&buf, subject, " ");
5759 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5760 unuse_commit_buffer(item->commit, commit_buffer);
1f969601 5761 if (skip_fixupish(subject, &p)) {
c44a4c65
JS
5762 struct commit *commit2;
5763
5764 for (;;) {
5765 while (isspace(*p))
5766 p++;
1f969601 5767 if (!skip_fixupish(p, &p))
c44a4c65
JS
5768 break;
5769 }
5770
f23a4651
EW
5771 entry = hashmap_get_entry_from_hash(&subject2item,
5772 strhash(p), p,
5773 struct subject2item_entry,
5774 entry);
5775 if (entry)
c44a4c65
JS
5776 /* found by title */
5777 i2 = entry->i;
5778 else if (!strchr(p, ' ') &&
5779 (commit2 =
5780 lookup_commit_reference_by_name(p)) &&
3cc0287b 5781 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 5782 /* found by commit name */
3cc0287b 5783 i2 = *commit_todo_item_at(&commit_todo, commit2)
f2a04904 5784 - todo_list->items;
c44a4c65
JS
5785 else {
5786 /* copy can be a prefix of the commit subject */
5787 for (i2 = 0; i2 < i; i2++)
5788 if (subjects[i2] &&
5789 starts_with(subjects[i2], p))
5790 break;
5791 if (i2 == i)
5792 i2 = -1;
5793 }
5794 }
5795 if (i2 >= 0) {
5796 rearranged = 1;
bae5b4ae
CM
5797 if (starts_with(subject, "fixup!")) {
5798 todo_list->items[i].command = TODO_FIXUP;
5799 } else if (starts_with(subject, "amend!")) {
5800 todo_list->items[i].command = TODO_FIXUP;
5801 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5802 } else {
5803 todo_list->items[i].command = TODO_SQUASH;
5804 }
02471e7e
JS
5805 if (tail[i2] < 0) {
5806 next[i] = next[i2];
c44a4c65 5807 next[i2] = i;
02471e7e
JS
5808 } else {
5809 next[i] = next[tail[i2]];
c44a4c65 5810 next[tail[i2]] = i;
02471e7e 5811 }
c44a4c65
JS
5812 tail[i2] = i;
5813 } else if (!hashmap_get_from_hash(&subject2item,
5814 strhash(subject), subject)) {
5815 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5816 entry->i = i;
d22245a2
EW
5817 hashmap_entry_init(&entry->entry,
5818 strhash(entry->subject));
26b455f2 5819 hashmap_put(&subject2item, &entry->entry);
c44a4c65
JS
5820 }
5821 }
5822
5823 if (rearranged) {
f2a04904
AG
5824 for (i = 0; i < todo_list->nr; i++) {
5825 enum todo_command command = todo_list->items[i].command;
c44a4c65
JS
5826 int cur = i;
5827
5828 /*
5829 * Initially, all commands are 'pick's. If it is a
5830 * fixup or a squash now, we have rearranged it.
5831 */
5832 if (is_fixup(command))
5833 continue;
5834
5835 while (cur >= 0) {
f2a04904
AG
5836 ALLOC_GROW(items, nr + 1, alloc);
5837 items[nr++] = todo_list->items[cur];
c44a4c65
JS
5838 cur = next[cur];
5839 }
5840 }
5841
f2a04904
AG
5842 FREE_AND_NULL(todo_list->items);
5843 todo_list->items = items;
5844 todo_list->nr = nr;
5845 todo_list->alloc = alloc;
c44a4c65
JS
5846 }
5847
5848 free(next);
5849 free(tail);
f2a04904 5850 for (i = 0; i < todo_list->nr; i++)
c44a4c65
JS
5851 free(subjects[i]);
5852 free(subjects);
6da1a258 5853 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
c44a4c65 5854
3cc0287b 5855 clear_commit_todo_item(&commit_todo);
f2a04904
AG
5856
5857 return 0;
c44a4c65 5858}
901ba7b1
PW
5859
5860int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5861{
c8e4159e 5862 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
430b75f7
PW
5863 struct object_id cherry_pick_head, rebase_head;
5864
5865 if (file_exists(git_path_seq_dir()))
5866 *whence = FROM_CHERRY_PICK_MULTI;
5867 if (file_exists(rebase_path()) &&
5868 !get_oid("REBASE_HEAD", &rebase_head) &&
5869 !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5870 oideq(&rebase_head, &cherry_pick_head))
5871 *whence = FROM_REBASE_PICK;
5872 else
5873 *whence = FROM_CHERRY_PICK_SINGLE;
5874
901ba7b1
PW
5875 return 1;
5876 }
5877
5878 return 0;
5879}