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