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