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