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