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