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