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