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