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