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