Merge branch 'pw/rebase-i-squash-number-fix'
[git/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"
043a4492
RR
33
34#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 35
5ed75e2a 36const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 37static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 38
66618a50
PW
39GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
40
8a2a0f53
JS
41GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
42
43static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
44static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
45static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 46static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 47
84583957
JS
48static GIT_PATH_FUNC(rebase_path, "rebase-merge")
49/*
50 * The file containing rebase commands, comments, and empty lines.
51 * This file is created by "git rebase -i" then edited by the user. As
52 * the lines are processed, they are removed from the front of this
53 * file and written to the tail of 'done'.
54 */
55static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
1df6df0c
JS
56/*
57 * The rebase command lines that have already been processed. A line
58 * is moved here when it is first handled, before any associated user
59 * actions.
60 */
61static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
62/*
63 * The file to keep track of how many commands were already processed (e.g.
64 * for the prompt).
65 */
9ad36356 66static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
67/*
68 * The file to keep track of how many commands are to be processed in total
69 * (e.g. for the prompt).
70 */
9ad36356 71static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
72/*
73 * The commit message that is planned to be used for any changes that
74 * need to be committed following a user interaction.
75 */
76static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
77/*
78 * The file into which is accumulated the suggested commit message for
79 * squash/fixup commands. When the first of a series of squash/fixups
80 * is seen, the file is created and the commit message from the
81 * previous commit and from the first squash/fixup commit are written
82 * to it. The commit message for each subsequent squash/fixup commit
83 * is appended to the file as it is processed.
6e98de72
JS
84 */
85static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
86/*
87 * If the current series of squash/fixups has not yet included a squash
88 * command, then this file exists and holds the commit message of the
89 * original "pick" commit. (If the series ends without a "squash"
90 * command, then this can be used as the commit message of the combined
91 * commit without opening the editor.)
92 */
93static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
94/*
95 * This file contains the list fixup/squash commands that have been
96 * accumulated into message-fixup or message-squash so far.
97 */
98static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
99/*
100 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
101 * GIT_AUTHOR_DATE that will be used for the commit that is currently
102 * being rebased.
103 */
104static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
105/*
106 * When an "edit" rebase command is being processed, the SHA1 of the
107 * commit to be edited is recorded in this file. When "git rebase
108 * --continue" is executed, if there are any staged changes then they
109 * will be amended to the HEAD commit, but only provided the HEAD
110 * commit is still the commit to be edited. When any other rebase
111 * command is processed, this file is deleted.
112 */
113static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
114/*
115 * When we stop at a given patch via the "edit" command, this file contains
116 * the abbreviated commit name of the corresponding patch.
117 */
118static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
119/*
120 * For the post-rewrite hook, we make a list of rewritten commits and
121 * their new sha1s. The rewritten-pending list keeps the sha1s of
122 * commits that have been processed, but not committed yet,
123 * e.g. because they are waiting for a 'squash' command.
124 */
125static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
126static GIT_PATH_FUNC(rebase_path_rewritten_pending,
127 "rebase-merge/rewritten-pending")
9055e401 128
d87d48b2
JS
129/*
130 * The path of the file containig the OID of the "squash onto" commit, i.e.
131 * the dummy commit used for `reset [new root]`.
132 */
133static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
134
9055e401
JS
135/*
136 * The path of the file listing refs that need to be deleted after the rebase
137 * finishes. This is used by the `label` command to record the need for cleanup.
138 */
139static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
140
a1c75762
JS
141/*
142 * The following files are written by git-rebase just after parsing the
143 * command-line (and are only consumed, not modified, by the sequencer).
144 */
145static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
556907f1
JS
146static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
147static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
a852ec7f 148static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
149static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
150static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 151static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
152static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
153static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 154static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
b5a67045 155
28d6daed
PW
156static int git_sequencer_config(const char *k, const char *v, void *cb)
157{
158 struct replay_opts *opts = cb;
159 int status;
160
161 if (!strcmp(k, "commit.cleanup")) {
162 const char *s;
163
164 status = git_config_string(&s, k, v);
165 if (status)
166 return status;
167
168 if (!strcmp(s, "verbatim"))
169 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
170 else if (!strcmp(s, "whitespace"))
171 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
172 else if (!strcmp(s, "strip"))
173 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
174 else if (!strcmp(s, "scissors"))
175 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
176 else
177 warning(_("invalid commit message cleanup mode '%s'"),
178 s);
179
f40f3c16 180 free((char *)s);
28d6daed
PW
181 return status;
182 }
183
184 if (!strcmp(k, "commit.gpgsign")) {
ed1e5282 185 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
186 return 0;
187 }
188
189 status = git_gpg_config(k, v, NULL);
190 if (status)
191 return status;
192
193 return git_diff_basic_config(k, v, NULL);
194}
195
196void sequencer_init_config(struct replay_opts *opts)
197{
198 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
199 git_config(git_sequencer_config, opts);
200}
201
b5a67045
JS
202static inline int is_rebase_i(const struct replay_opts *opts)
203{
84583957 204 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
205}
206
285abf56
JS
207static const char *get_dir(const struct replay_opts *opts)
208{
84583957
JS
209 if (is_rebase_i(opts))
210 return rebase_path();
285abf56
JS
211 return git_path_seq_dir();
212}
213
c0246501
JS
214static const char *get_todo_path(const struct replay_opts *opts)
215{
84583957
JS
216 if (is_rebase_i(opts))
217 return rebase_path_todo();
c0246501
JS
218 return git_path_todo_file();
219}
220
bab4d109
BC
221/*
222 * Returns 0 for non-conforming footer
223 * Returns 1 for conforming footer
224 * Returns 2 when sob exists within conforming footer
225 * Returns 3 when sob exists within conforming footer as last entry
226 */
227static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
228 int ignore_footer)
b971e04f 229{
967dfd4d
JT
230 struct trailer_info info;
231 int i;
232 int found_sob = 0, found_sob_last = 0;
b971e04f 233
967dfd4d 234 trailer_info_get(&info, sb->buf);
b971e04f 235
967dfd4d 236 if (info.trailer_start == info.trailer_end)
b971e04f
BC
237 return 0;
238
967dfd4d
JT
239 for (i = 0; i < info.trailer_nr; i++)
240 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
241 found_sob = 1;
242 if (i == info.trailer_nr - 1)
243 found_sob_last = 1;
244 }
b971e04f 245
967dfd4d 246 trailer_info_release(&info);
bab4d109 247
967dfd4d 248 if (found_sob_last)
bab4d109
BC
249 return 3;
250 if (found_sob)
251 return 2;
b971e04f
BC
252 return 1;
253}
5ed75e2a 254
a1c75762
JS
255static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
256{
257 static struct strbuf buf = STRBUF_INIT;
258
259 strbuf_reset(&buf);
260 if (opts->gpg_sign)
261 sq_quotef(&buf, "-S%s", opts->gpg_sign);
262 return buf.buf;
263}
264
2863584f 265int sequencer_remove_state(struct replay_opts *opts)
26ae337b 266{
9055e401 267 struct strbuf buf = STRBUF_INIT;
03a4e260
JS
268 int i;
269
9055e401
JS
270 if (is_rebase_i(opts) &&
271 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
272 char *p = buf.buf;
273 while (*p) {
274 char *eol = strchr(p, '\n');
275 if (eol)
276 *eol = '\0';
277 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
278 warning(_("could not delete '%s'"), p);
279 if (!eol)
280 break;
281 p = eol + 1;
282 }
283 }
284
03a4e260
JS
285 free(opts->gpg_sign);
286 free(opts->strategy);
287 for (i = 0; i < opts->xopts_nr; i++)
288 free(opts->xopts[i]);
289 free(opts->xopts);
e12a7ef5 290 strbuf_release(&opts->current_fixups);
26ae337b 291
9055e401
JS
292 strbuf_reset(&buf);
293 strbuf_addstr(&buf, get_dir(opts));
294 remove_dir_recursively(&buf, 0);
295 strbuf_release(&buf);
2863584f
JS
296
297 return 0;
26ae337b 298}
043a4492
RR
299
300static const char *action_name(const struct replay_opts *opts)
301{
84583957
JS
302 switch (opts->action) {
303 case REPLAY_REVERT:
304 return N_("revert");
305 case REPLAY_PICK:
306 return N_("cherry-pick");
307 case REPLAY_INTERACTIVE_REBASE:
308 return N_("rebase -i");
309 }
1a07e59c 310 die(_("unknown action: %d"), opts->action);
043a4492
RR
311}
312
043a4492
RR
313struct commit_message {
314 char *parent_label;
7b35eaf8
JK
315 char *label;
316 char *subject;
043a4492
RR
317 const char *message;
318};
319
39755964
JS
320static const char *short_commit_name(struct commit *commit)
321{
aab9583f 322 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
39755964
JS
323}
324
043a4492
RR
325static int get_message(struct commit *commit, struct commit_message *out)
326{
043a4492 327 const char *abbrev, *subject;
7b35eaf8 328 int subject_len;
043a4492 329
7b35eaf8 330 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 331 abbrev = short_commit_name(commit);
043a4492
RR
332
333 subject_len = find_commit_subject(out->message, &subject);
334
7b35eaf8
JK
335 out->subject = xmemdupz(subject, subject_len);
336 out->label = xstrfmt("%s... %s", abbrev, out->subject);
337 out->parent_label = xstrfmt("parent of %s", out->label);
338
043a4492
RR
339 return 0;
340}
341
d74a4e57 342static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
343{
344 free(msg->parent_label);
7b35eaf8
JK
345 free(msg->label);
346 free(msg->subject);
b66103c3 347 unuse_commit_buffer(commit, msg->message);
043a4492
RR
348}
349
ed727b19 350static void print_advice(int show_hint, struct replay_opts *opts)
043a4492
RR
351{
352 char *msg = getenv("GIT_CHERRY_PICK_HELP");
353
354 if (msg) {
355 fprintf(stderr, "%s\n", msg);
356 /*
41ccfdd9 357 * A conflict has occurred but the porcelain
043a4492
RR
358 * (typically rebase --interactive) wants to take care
359 * of the commit itself so remove CHERRY_PICK_HEAD
360 */
102de880 361 unlink(git_path_cherry_pick_head(the_repository));
043a4492
RR
362 return;
363 }
364
ed727b19
PH
365 if (show_hint) {
366 if (opts->no_commit)
367 advise(_("after resolving the conflicts, mark the corrected paths\n"
368 "with 'git add <paths>' or 'git rm <paths>'"));
369 else
370 advise(_("after resolving the conflicts, mark the corrected paths\n"
371 "with 'git add <paths>' or 'git rm <paths>'\n"
372 "and commit the result with 'git commit'"));
373 }
043a4492
RR
374}
375
f56fffef
JS
376static int write_message(const void *buf, size_t len, const char *filename,
377 int append_eol)
043a4492 378{
14bca6c6 379 struct lock_file msg_file = LOCK_INIT;
043a4492 380
4ef3d8f0
JS
381 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
382 if (msg_fd < 0)
93b3df6f 383 return error_errno(_("could not lock '%s'"), filename);
75871495 384 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 385 error_errno(_("could not write to '%s'"), filename);
4f66c837 386 rollback_lock_file(&msg_file);
bf5c0571 387 return -1;
4f66c837 388 }
f56fffef 389 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 390 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 391 rollback_lock_file(&msg_file);
bf5c0571 392 return -1;
f56fffef 393 }
350292a1
394 if (commit_lock_file(&msg_file) < 0)
395 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
396
397 return 0;
043a4492
RR
398}
399
1dfc84e9
JS
400/*
401 * Reads a file that was presumably written by a shell script, i.e. with an
402 * end-of-line marker that needs to be stripped.
403 *
404 * Note that only the last end-of-line marker is stripped, consistent with the
405 * behavior of "$(cat path)" in a shell script.
406 *
407 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
408 */
409static int read_oneliner(struct strbuf *buf,
410 const char *path, int skip_if_empty)
411{
412 int orig_len = buf->len;
413
414 if (!file_exists(path))
415 return 0;
416
417 if (strbuf_read_file(buf, path, 0) < 0) {
418 warning_errno(_("could not read '%s'"), path);
419 return 0;
420 }
421
422 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
423 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
424 --buf->len;
425 buf->buf[buf->len] = '\0';
426 }
427
428 if (skip_if_empty && buf->len == orig_len)
429 return 0;
430
431 return 1;
432}
433
043a4492
RR
434static struct tree *empty_tree(void)
435{
f86bcc7b 436 return lookup_tree(the_repository, the_repository->hash_algo->empty_tree);
043a4492
RR
437}
438
439static int error_dirty_index(struct replay_opts *opts)
440{
441 if (read_cache_unmerged())
c28cbc5e 442 return error_resolve_conflict(_(action_name(opts)));
043a4492 443
93b3df6f 444 error(_("your local changes would be overwritten by %s."),
c28cbc5e 445 _(action_name(opts)));
043a4492
RR
446
447 if (advice_commit_before_merge)
93b3df6f 448 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
449 return -1;
450}
451
1e41229d
SB
452static void update_abort_safety_file(void)
453{
454 struct object_id head;
455
456 /* Do nothing on a single-pick */
457 if (!file_exists(git_path_seq_dir()))
458 return;
459
460 if (!get_oid("HEAD", &head))
461 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
462 else
463 write_file(git_path_abort_safety_file(), "%s", "");
464}
465
ace976b2 466static int fast_forward_to(const struct object_id *to, const struct object_id *from,
eb4be1cb 467 int unborn, struct replay_opts *opts)
043a4492 468{
d668d16c 469 struct ref_transaction *transaction;
eb4be1cb 470 struct strbuf sb = STRBUF_INIT;
d668d16c 471 struct strbuf err = STRBUF_INIT;
043a4492
RR
472
473 read_cache();
db699a8a 474 if (checkout_fast_forward(from, to, 1))
0e408fc3 475 return -1; /* the callee should have complained already */
651ab9f5 476
c28cbc5e 477 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
478
479 transaction = ref_transaction_begin(&err);
480 if (!transaction ||
481 ref_transaction_update(transaction, "HEAD",
d87d48b2
JS
482 to, unborn && !is_rebase_i(opts) ?
483 &null_oid : from,
1d147bdf 484 0, sb.buf, &err) ||
db7516ab 485 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
486 ref_transaction_free(transaction);
487 error("%s", err.buf);
488 strbuf_release(&sb);
489 strbuf_release(&err);
490 return -1;
491 }
651ab9f5 492
eb4be1cb 493 strbuf_release(&sb);
d668d16c
RS
494 strbuf_release(&err);
495 ref_transaction_free(transaction);
1e41229d 496 update_abort_safety_file();
d668d16c 497 return 0;
043a4492
RR
498}
499
75c961b7
JH
500void append_conflicts_hint(struct strbuf *msgbuf)
501{
502 int i;
503
261f315b
JH
504 strbuf_addch(msgbuf, '\n');
505 strbuf_commented_addf(msgbuf, "Conflicts:\n");
75c961b7
JH
506 for (i = 0; i < active_nr;) {
507 const struct cache_entry *ce = active_cache[i++];
508 if (ce_stage(ce)) {
261f315b 509 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
75c961b7
JH
510 while (i < active_nr && !strcmp(ce->name,
511 active_cache[i]->name))
512 i++;
513 }
514 }
515}
516
043a4492
RR
517static int do_recursive_merge(struct commit *base, struct commit *next,
518 const char *base_label, const char *next_label,
48be4c62 519 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
520 struct replay_opts *opts)
521{
522 struct merge_options o;
523 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 524 int clean;
03a4e260 525 char **xopt;
14bca6c6 526 struct lock_file index_lock = LOCK_INIT;
043a4492 527
bd588867
PW
528 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
529 return -1;
043a4492
RR
530
531 read_cache();
532
533 init_merge_options(&o);
534 o.ancestor = base ? base_label : "(empty tree)";
535 o.branch1 = "HEAD";
536 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
537 if (is_rebase_i(opts))
538 o.buffer_output = 2;
9268cf4a 539 o.show_rename_progress = 1;
043a4492
RR
540
541 head_tree = parse_tree_indirect(head);
2e27bd77
DS
542 next_tree = next ? get_commit_tree(next) : empty_tree();
543 base_tree = base ? get_commit_tree(base) : empty_tree();
043a4492
RR
544
545 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
546 parse_merge_opt(&o, *xopt);
547
548 clean = merge_trees(&o,
549 head_tree,
550 next_tree, base_tree, &result);
62fdb652
JS
551 if (is_rebase_i(opts) && clean <= 0)
552 fputs(o.obuf.buf, stdout);
548009c0 553 strbuf_release(&o.obuf);
b520abf1 554 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
64816524
555 if (clean < 0) {
556 rollback_lock_file(&index_lock);
f241ff0d 557 return clean;
64816524 558 }
043a4492 559
61000814
560 if (write_locked_index(&the_index, &index_lock,
561 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
562 /*
563 * TRANSLATORS: %s will be "revert", "cherry-pick" or
84583957
JS
564 * "rebase -i".
565 */
c527b55e 566 return error(_("%s: Unable to write new index file"),
c28cbc5e 567 _(action_name(opts)));
043a4492 568
75c961b7
JH
569 if (!clean)
570 append_conflicts_hint(msgbuf);
043a4492
RR
571
572 return !clean;
573}
574
ba97aea1
JS
575static struct object_id *get_cache_tree_oid(void)
576{
577 if (!active_cache_tree)
578 active_cache_tree = cache_tree();
579
580 if (!cache_tree_fully_valid(active_cache_tree))
581 if (cache_tree_update(&the_index, 0)) {
582 error(_("unable to update cache tree"));
583 return NULL;
584 }
585
586 return &active_cache_tree->oid;
587}
588
b27cfb0d
NH
589static int is_index_unchanged(void)
590{
ba97aea1 591 struct object_id head_oid, *cache_tree_oid;
b27cfb0d
NH
592 struct commit *head_commit;
593
49e61479 594 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 595 return error(_("could not resolve HEAD commit"));
b27cfb0d 596
c1f5eb49 597 head_commit = lookup_commit(the_repository, &head_oid);
4b580061
NH
598
599 /*
600 * If head_commit is NULL, check_commit, called from
601 * lookup_commit, would have indicated that head_commit is not
602 * a commit object already. parse_commit() will return failure
603 * without further complaints in such a case. Otherwise, if
604 * the commit is invalid, parse_commit() will complain. So
605 * there is nothing for us to say here. Just return failure.
606 */
607 if (parse_commit(head_commit))
608 return -1;
b27cfb0d 609
ba97aea1
JS
610 if (!(cache_tree_oid = get_cache_tree_oid()))
611 return -1;
b27cfb0d 612
c5aa4bcc 613 return !oidcmp(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
614}
615
0473f28a
JS
616static int write_author_script(const char *message)
617{
618 struct strbuf buf = STRBUF_INIT;
619 const char *eol;
620 int res;
621
622 for (;;)
623 if (!*message || starts_with(message, "\n")) {
624missing_author:
625 /* Missing 'author' line? */
626 unlink(rebase_path_author_script());
627 return 0;
628 } else if (skip_prefix(message, "author ", &message))
629 break;
630 else if ((eol = strchr(message, '\n')))
631 message = eol + 1;
632 else
633 goto missing_author;
634
635 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
636 while (*message && *message != '\n' && *message != '\r')
637 if (skip_prefix(message, " <", &message))
638 break;
639 else if (*message != '\'')
640 strbuf_addch(&buf, *(message++));
641 else
642 strbuf_addf(&buf, "'\\\\%c'", *(message++));
643 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
644 while (*message && *message != '\n' && *message != '\r')
645 if (skip_prefix(message, "> ", &message))
646 break;
647 else if (*message != '\'')
648 strbuf_addch(&buf, *(message++));
649 else
650 strbuf_addf(&buf, "'\\\\%c'", *(message++));
651 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
652 while (*message && *message != '\n' && *message != '\r')
653 if (*message != '\'')
654 strbuf_addch(&buf, *(message++));
655 else
656 strbuf_addf(&buf, "'\\\\%c'", *(message++));
0f16c09a 657 strbuf_addch(&buf, '\'');
0473f28a
JS
658 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
659 strbuf_release(&buf);
660 return res;
661}
662
b5a67045 663/*
a2a20b0d
JS
664 * Read a list of environment variable assignments (such as the author-script
665 * file) into an environment block. Returns -1 on error, 0 otherwise.
b5a67045 666 */
a2a20b0d 667static int read_env_script(struct argv_array *env)
b5a67045
JS
668{
669 struct strbuf script = STRBUF_INIT;
670 int i, count = 0;
a2a20b0d 671 char *p, *p2;
b5a67045
JS
672
673 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
a2a20b0d 674 return -1;
b5a67045
JS
675
676 for (p = script.buf; *p; p++)
677 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
678 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
679 else if (*p == '\'')
680 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
681 else if (*p == '\n') {
682 *p = '\0';
683 count++;
684 }
685
a2a20b0d
JS
686 for (i = 0, p = script.buf; i < count; i++) {
687 argv_array_push(env, p);
b5a67045
JS
688 p += strlen(p) + 1;
689 }
b5a67045 690
a2a20b0d 691 return 0;
b5a67045
JS
692}
693
356ee465
PW
694static char *get_author(const char *message)
695{
696 size_t len;
697 const char *a;
698
699 a = find_commit_header(message, "author", &len);
700 if (a)
701 return xmemdupz(a, len);
702
703 return NULL;
704}
705
d87d48b2
JS
706/* Read author-script and return an ident line (author <email> timestamp) */
707static const char *read_author_ident(struct strbuf *buf)
708{
709 const char *keys[] = {
710 "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
711 };
67f16e3d
ES
712 struct strbuf out = STRBUF_INIT;
713 char *in, *eol;
714 const char *val[3];
715 int i = 0;
d87d48b2
JS
716
717 if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
718 return NULL;
719
720 /* dequote values and construct ident line in-place */
67f16e3d 721 for (in = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
d87d48b2 722 if (!skip_prefix(in, keys[i], (const char **)&in)) {
02127c63 723 warning(_("could not parse '%s' (looking for '%s'"),
d87d48b2
JS
724 rebase_path_author_script(), keys[i]);
725 return NULL;
726 }
727
728 eol = strchrnul(in, '\n');
729 *eol = '\0';
0f16c09a
ES
730 if (!sq_dequote(in)) {
731 warning(_("bad quoting on %s value in '%s'"),
732 keys[i], rebase_path_author_script());
733 return NULL;
734 }
67f16e3d 735 val[i] = in;
d87d48b2
JS
736 in = eol + 1;
737 }
738
739 if (i < 3) {
02127c63 740 warning(_("could not parse '%s' (looking for '%s')"),
d87d48b2
JS
741 rebase_path_author_script(), keys[i]);
742 return NULL;
743 }
744
5522bbac
ES
745 /* validate date since fmt_ident() will die() on bad value */
746 if (parse_date(val[2], &out)){
747 warning(_("invalid date format '%s' in '%s'"),
748 val[2], rebase_path_author_script());
749 strbuf_release(&out);
750 return NULL;
751 }
752
753 strbuf_reset(&out);
67f16e3d
ES
754 strbuf_addstr(&out, fmt_ident(val[0], val[1], val[2], 0));
755 strbuf_swap(buf, &out);
756 strbuf_release(&out);
d87d48b2
JS
757 return buf->buf;
758}
759
791eb870
JS
760static const char staged_changes_advice[] =
761N_("you have staged changes in your working tree\n"
762"If these changes are meant to be squashed into the previous commit, run:\n"
763"\n"
764" git commit --amend %s\n"
765"\n"
766"If they are meant to go into a new commit, run:\n"
767"\n"
768" git commit %s\n"
769"\n"
770"In both cases, once you're done, continue with:\n"
771"\n"
772" git rebase --continue\n");
773
789b3eff
JS
774#define ALLOW_EMPTY (1<<0)
775#define EDIT_MSG (1<<1)
776#define AMEND_MSG (1<<2)
777#define CLEANUP_MSG (1<<3)
b92ff6e8 778#define VERIFY_MSG (1<<4)
d87d48b2 779#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 780
043a4492
RR
781/*
782 * If we are cherry-pick, and if the merge did not result in
783 * hand-editing, we will hit this commit and inherit the original
784 * author date and name.
b5a67045 785 *
043a4492
RR
786 * If we are revert, or if our cherry-pick results in a hand merge,
787 * we had better say that the current user is responsible for that.
b5a67045
JS
788 *
789 * An exception is when run_git_commit() is called during an
790 * interactive rebase: in that case, we will want to retain the
791 * author metadata.
043a4492 792 */
ac2b0e8f 793static int run_git_commit(const char *defmsg, struct replay_opts *opts,
789b3eff 794 unsigned int flags)
043a4492 795{
07d968ef 796 struct child_process cmd = CHILD_PROCESS_INIT;
17d65f03 797 const char *value;
b27cfb0d 798
76fda6eb 799 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
d87d48b2
JS
800 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
801 const char *author = is_rebase_i(opts) ?
802 read_author_ident(&script) : NULL;
803 struct object_id root_commit, *cache_tree_oid;
804 int res = 0;
805
806 if (!defmsg)
807 BUG("root commit without message");
808
809 if (!(cache_tree_oid = get_cache_tree_oid()))
810 res = -1;
811
812 if (!res)
813 res = strbuf_read_file(&msg, defmsg, 0);
814
815 if (res <= 0)
816 res = error_errno(_("could not read '%s'"), defmsg);
817 else
818 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
819 NULL, &root_commit, author,
820 opts->gpg_sign);
821
822 strbuf_release(&msg);
823 strbuf_release(&script);
824 if (!res) {
825 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
826 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
827 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
828 UPDATE_REFS_MSG_ON_ERR);
829 }
830 return res < 0 ? error(_("writing root commit")) : 0;
831 }
832
07d968ef
JS
833 cmd.git_cmd = 1;
834
b5a67045 835 if (is_rebase_i(opts)) {
789b3eff 836 if (!(flags & EDIT_MSG)) {
9a757c49
JS
837 cmd.stdout_to_stderr = 1;
838 cmd.err = -1;
839 }
840
07d968ef 841 if (read_env_script(&cmd.env_array)) {
a1c75762
JS
842 const char *gpg_opt = gpg_sign_opt_quoted(opts);
843
791eb870
JS
844 return error(_(staged_changes_advice),
845 gpg_opt, gpg_opt);
a1c75762 846 }
b5a67045
JS
847 }
848
07d968ef 849 argv_array_push(&cmd.args, "commit");
043a4492 850
b92ff6e8
JS
851 if (!(flags & VERIFY_MSG))
852 argv_array_push(&cmd.args, "-n");
789b3eff 853 if ((flags & AMEND_MSG))
07d968ef 854 argv_array_push(&cmd.args, "--amend");
3bdd5522 855 if (opts->gpg_sign)
07d968ef 856 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 857 if (defmsg)
07d968ef 858 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
859 else if (!(flags & EDIT_MSG))
860 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 861 if ((flags & CLEANUP_MSG))
07d968ef 862 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 863 if ((flags & EDIT_MSG))
07d968ef 864 argv_array_push(&cmd.args, "-e");
789b3eff 865 else if (!(flags & CLEANUP_MSG) &&
0009426d 866 !opts->signoff && !opts->record_origin &&
b5a67045 867 git_config_get_value("commit.cleanup", &value))
07d968ef 868 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 869
789b3eff 870 if ((flags & ALLOW_EMPTY))
07d968ef 871 argv_array_push(&cmd.args, "--allow-empty");
df478b74 872
4bee9584 873 if (opts->allow_empty_message)
07d968ef 874 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 875
9a757c49
JS
876 if (cmd.err == -1) {
877 /* hide stderr on success */
878 struct strbuf buf = STRBUF_INIT;
879 int rc = pipe_command(&cmd,
880 NULL, 0,
881 /* stdout is already redirected */
882 NULL, 0,
883 &buf, 0);
884 if (rc)
885 fputs(buf.buf, stderr);
886 strbuf_release(&buf);
887 return rc;
888 }
b5a67045 889
07d968ef 890 return run_command(&cmd);
b27cfb0d
NH
891}
892
d0aaa46f
PW
893static int rest_is_empty(const struct strbuf *sb, int start)
894{
895 int i, eol;
896 const char *nl;
897
898 /* Check if the rest is just whitespace and Signed-off-by's. */
899 for (i = start; i < sb->len; i++) {
900 nl = memchr(sb->buf + i, '\n', sb->len - i);
901 if (nl)
902 eol = nl - sb->buf;
903 else
904 eol = sb->len;
905
906 if (strlen(sign_off_header) <= eol - i &&
907 starts_with(sb->buf + i, sign_off_header)) {
908 i = eol;
909 continue;
910 }
911 while (i < eol)
912 if (!isspace(sb->buf[i++]))
913 return 0;
914 }
915
916 return 1;
917}
918
919/*
920 * Find out if the message in the strbuf contains only whitespace and
921 * Signed-off-by lines.
922 */
923int message_is_empty(const struct strbuf *sb,
924 enum commit_msg_cleanup_mode cleanup_mode)
925{
926 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
927 return 0;
928 return rest_is_empty(sb, 0);
929}
930
931/*
932 * See if the user edited the message in the editor or left what
933 * was in the template intact
934 */
935int template_untouched(const struct strbuf *sb, const char *template_file,
936 enum commit_msg_cleanup_mode cleanup_mode)
937{
938 struct strbuf tmpl = STRBUF_INIT;
939 const char *start;
940
941 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
942 return 0;
943
944 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
945 return 0;
946
947 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
948 if (!skip_prefix(sb->buf, tmpl.buf, &start))
949 start = sb->buf;
950 strbuf_release(&tmpl);
951 return rest_is_empty(sb, start - sb->buf);
952}
953
0505d604
PW
954int update_head_with_reflog(const struct commit *old_head,
955 const struct object_id *new_head,
956 const char *action, const struct strbuf *msg,
957 struct strbuf *err)
958{
959 struct ref_transaction *transaction;
960 struct strbuf sb = STRBUF_INIT;
961 const char *nl;
962 int ret = 0;
963
964 if (action) {
965 strbuf_addstr(&sb, action);
966 strbuf_addstr(&sb, ": ");
967 }
968
969 nl = strchr(msg->buf, '\n');
970 if (nl) {
971 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
972 } else {
973 strbuf_addbuf(&sb, msg);
974 strbuf_addch(&sb, '\n');
975 }
976
977 transaction = ref_transaction_begin(err);
978 if (!transaction ||
979 ref_transaction_update(transaction, "HEAD", new_head,
980 old_head ? &old_head->object.oid : &null_oid,
981 0, sb.buf, err) ||
982 ref_transaction_commit(transaction, err)) {
983 ret = -1;
984 }
985 ref_transaction_free(transaction);
986 strbuf_release(&sb);
987
988 return ret;
989}
990
a87a6f3c
PW
991static int run_rewrite_hook(const struct object_id *oldoid,
992 const struct object_id *newoid)
993{
994 struct child_process proc = CHILD_PROCESS_INIT;
995 const char *argv[3];
996 int code;
997 struct strbuf sb = STRBUF_INIT;
998
999 argv[0] = find_hook("post-rewrite");
1000 if (!argv[0])
1001 return 0;
1002
1003 argv[1] = "amend";
1004 argv[2] = NULL;
1005
1006 proc.argv = argv;
1007 proc.in = -1;
1008 proc.stdout_to_stderr = 1;
1009
1010 code = start_command(&proc);
1011 if (code)
1012 return code;
1013 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1014 sigchain_push(SIGPIPE, SIG_IGN);
1015 write_in_full(proc.in, sb.buf, sb.len);
1016 close(proc.in);
1017 strbuf_release(&sb);
1018 sigchain_pop(SIGPIPE);
1019 return finish_command(&proc);
1020}
1021
1022void commit_post_rewrite(const struct commit *old_head,
1023 const struct object_id *new_head)
1024{
1025 struct notes_rewrite_cfg *cfg;
1026
1027 cfg = init_copy_notes_for_rewrite("amend");
1028 if (cfg) {
1029 /* we are amending, so old_head is not NULL */
1030 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1031 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1032 }
1033 run_rewrite_hook(&old_head->object.oid, new_head);
1034}
1035
66618a50
PW
1036static int run_prepare_commit_msg_hook(struct strbuf *msg, const char *commit)
1037{
1038 struct argv_array hook_env = ARGV_ARRAY_INIT;
1039 int ret;
1040 const char *name;
1041
1042 name = git_path_commit_editmsg();
1043 if (write_message(msg->buf, msg->len, name, 0))
1044 return -1;
1045
1046 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", get_index_file());
1047 argv_array_push(&hook_env, "GIT_EDITOR=:");
1048 if (commit)
1049 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1050 "commit", commit, NULL);
1051 else
1052 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1053 "message", NULL);
1054 if (ret)
1055 ret = error(_("'prepare-commit-msg' hook failed"));
1056 argv_array_clear(&hook_env);
1057
1058 return ret;
1059}
1060
e47c6caf
PW
1061static const char implicit_ident_advice_noconfig[] =
1062N_("Your name and email address were configured automatically based\n"
1063"on your username and hostname. Please check that they are accurate.\n"
1064"You can suppress this message by setting them explicitly. Run the\n"
1065"following command and follow the instructions in your editor to edit\n"
1066"your configuration file:\n"
1067"\n"
1068" git config --global --edit\n"
1069"\n"
1070"After doing this, you may fix the identity used for this commit with:\n"
1071"\n"
1072" git commit --amend --reset-author\n");
1073
1074static const char implicit_ident_advice_config[] =
1075N_("Your name and email address were configured automatically based\n"
1076"on your username and hostname. Please check that they are accurate.\n"
1077"You can suppress this message by setting them explicitly:\n"
1078"\n"
1079" git config --global user.name \"Your Name\"\n"
1080" git config --global user.email you@example.com\n"
1081"\n"
1082"After doing this, you may fix the identity used for this commit with:\n"
1083"\n"
1084" git commit --amend --reset-author\n");
1085
1086static const char *implicit_ident_advice(void)
1087{
1088 char *user_config = expand_user_path("~/.gitconfig", 0);
1089 char *xdg_config = xdg_config_home("config");
1090 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1091
1092 free(user_config);
1093 free(xdg_config);
1094
1095 if (config_exists)
1096 return _(implicit_ident_advice_config);
1097 else
1098 return _(implicit_ident_advice_noconfig);
1099
1100}
1101
1102void print_commit_summary(const char *prefix, const struct object_id *oid,
1103 unsigned int flags)
1104{
1105 struct rev_info rev;
1106 struct commit *commit;
1107 struct strbuf format = STRBUF_INIT;
1108 const char *head;
1109 struct pretty_print_context pctx = {0};
1110 struct strbuf author_ident = STRBUF_INIT;
1111 struct strbuf committer_ident = STRBUF_INIT;
1112
c1f5eb49 1113 commit = lookup_commit(the_repository, oid);
e47c6caf
PW
1114 if (!commit)
1115 die(_("couldn't look up newly created commit"));
1116 if (parse_commit(commit))
1117 die(_("could not parse newly created commit"));
1118
1119 strbuf_addstr(&format, "format:%h] %s");
1120
1121 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1122 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1123 if (strbuf_cmp(&author_ident, &committer_ident)) {
1124 strbuf_addstr(&format, "\n Author: ");
1125 strbuf_addbuf_percentquote(&format, &author_ident);
1126 }
1127 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1128 struct strbuf date = STRBUF_INIT;
1129
1130 format_commit_message(commit, "%ad", &date, &pctx);
1131 strbuf_addstr(&format, "\n Date: ");
1132 strbuf_addbuf_percentquote(&format, &date);
1133 strbuf_release(&date);
1134 }
1135 if (!committer_ident_sufficiently_given()) {
1136 strbuf_addstr(&format, "\n Committer: ");
1137 strbuf_addbuf_percentquote(&format, &committer_ident);
1138 if (advice_implicit_identity) {
1139 strbuf_addch(&format, '\n');
1140 strbuf_addstr(&format, implicit_ident_advice());
1141 }
1142 }
1143 strbuf_release(&author_ident);
1144 strbuf_release(&committer_ident);
1145
1146 init_revisions(&rev, prefix);
1147 setup_revisions(0, NULL, &rev, NULL);
1148
1149 rev.diff = 1;
1150 rev.diffopt.output_format =
1151 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1152
1153 rev.verbose_header = 1;
1154 rev.show_root_diff = 1;
1155 get_commit_format(format.buf, &rev);
1156 rev.always_show_header = 0;
0f57f731 1157 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1158 rev.diffopt.break_opt = 0;
1159 diff_setup_done(&rev.diffopt);
1160
1161 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1162 if (!head)
1163 die_errno(_("unable to resolve HEAD after creating commit"));
1164 if (!strcmp(head, "HEAD"))
1165 head = _("detached HEAD");
1166 else
1167 skip_prefix(head, "refs/heads/", &head);
1168 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1169 _(" (root-commit)") : "");
1170
1171 if (!log_tree_commit(&rev, commit)) {
1172 rev.always_show_header = 1;
1173 rev.use_terminator = 1;
1174 log_tree_commit(&rev, commit);
1175 }
1176
1177 strbuf_release(&format);
1178}
1179
356ee465
PW
1180static int parse_head(struct commit **head)
1181{
1182 struct commit *current_head;
1183 struct object_id oid;
1184
1185 if (get_oid("HEAD", &oid)) {
1186 current_head = NULL;
1187 } else {
2122f675 1188 current_head = lookup_commit_reference(the_repository, &oid);
356ee465
PW
1189 if (!current_head)
1190 return error(_("could not parse HEAD"));
1191 if (oidcmp(&oid, &current_head->object.oid)) {
1192 warning(_("HEAD %s is not a commit!"),
1193 oid_to_hex(&oid));
1194 }
1195 if (parse_commit(current_head))
1196 return error(_("could not parse HEAD commit"));
1197 }
1198 *head = current_head;
1199
1200 return 0;
1201}
1202
1203/*
1204 * Try to commit without forking 'git commit'. In some cases we need
1205 * to run 'git commit' to display an error message
1206 *
1207 * Returns:
1208 * -1 - error unable to commit
1209 * 0 - success
1210 * 1 - run 'git commit'
1211 */
1212static int try_to_commit(struct strbuf *msg, const char *author,
1213 struct replay_opts *opts, unsigned int flags,
1214 struct object_id *oid)
1215{
1216 struct object_id tree;
1217 struct commit *current_head;
1218 struct commit_list *parents = NULL;
1219 struct commit_extra_header *extra = NULL;
1220 struct strbuf err = STRBUF_INIT;
66618a50 1221 struct strbuf commit_msg = STRBUF_INIT;
356ee465 1222 char *amend_author = NULL;
66618a50 1223 const char *hook_commit = NULL;
356ee465
PW
1224 enum commit_msg_cleanup_mode cleanup;
1225 int res = 0;
1226
1227 if (parse_head(&current_head))
1228 return -1;
1229
1230 if (flags & AMEND_MSG) {
1231 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1232 const char *out_enc = get_commit_output_encoding();
1233 const char *message = logmsg_reencode(current_head, NULL,
1234 out_enc);
1235
1236 if (!msg) {
1237 const char *orig_message = NULL;
1238
1239 find_commit_subject(message, &orig_message);
66618a50 1240 msg = &commit_msg;
356ee465 1241 strbuf_addstr(msg, orig_message);
66618a50 1242 hook_commit = "HEAD";
356ee465
PW
1243 }
1244 author = amend_author = get_author(message);
1245 unuse_commit_buffer(current_head, message);
1246 if (!author) {
1247 res = error(_("unable to parse commit author"));
1248 goto out;
1249 }
1250 parents = copy_commit_list(current_head->parents);
1251 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1252 } else if (current_head) {
1253 commit_list_insert(current_head, &parents);
1254 }
1255
07096c96 1256 if (write_index_as_tree(&tree, &the_index, get_index_file(), 0, NULL)) {
356ee465
PW
1257 res = error(_("git write-tree failed to write a tree"));
1258 goto out;
1259 }
1260
1261 if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
2e27bd77 1262 get_commit_tree_oid(current_head) :
57911a31 1263 the_hash_algo->empty_tree, &tree)) {
356ee465
PW
1264 res = 1; /* run 'git commit' to display error message */
1265 goto out;
1266 }
1267
66618a50
PW
1268 if (find_hook("prepare-commit-msg")) {
1269 res = run_prepare_commit_msg_hook(msg, hook_commit);
1270 if (res)
1271 goto out;
1272 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1273 2048) < 0) {
1274 res = error_errno(_("unable to read commit message "
1275 "from '%s'"),
1276 git_path_commit_editmsg());
1277 goto out;
1278 }
1279 msg = &commit_msg;
1280 }
1281
1282 cleanup = (flags & CLEANUP_MSG) ? COMMIT_MSG_CLEANUP_ALL :
1283 opts->default_msg_cleanup;
1284
1285 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1286 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
1287 if (!opts->allow_empty_message && message_is_empty(msg, cleanup)) {
1288 res = 1; /* run 'git commit' to display error message */
1289 goto out;
1290 }
1291
12f7babd
JS
1292 reset_ident_date();
1293
8be8342b
JH
1294 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1295 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1296 res = error(_("failed to write commit object"));
1297 goto out;
1298 }
1299
1300 if (update_head_with_reflog(current_head, oid,
1301 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1302 res = error("%s", err.buf);
1303 goto out;
1304 }
1305
1306 if (flags & AMEND_MSG)
1307 commit_post_rewrite(current_head, oid);
1308
1309out:
1310 free_commit_extra_headers(extra);
1311 strbuf_release(&err);
66618a50 1312 strbuf_release(&commit_msg);
356ee465
PW
1313 free(amend_author);
1314
1315 return res;
1316}
1317
1318static int do_commit(const char *msg_file, const char *author,
1319 struct replay_opts *opts, unsigned int flags)
1320{
1321 int res = 1;
1322
d87d48b2
JS
1323 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1324 !(flags & CREATE_ROOT_COMMIT)) {
356ee465
PW
1325 struct object_id oid;
1326 struct strbuf sb = STRBUF_INIT;
1327
1328 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1329 return error_errno(_("unable to read commit message "
1330 "from '%s'"),
1331 msg_file);
1332
1333 res = try_to_commit(msg_file ? &sb : NULL, author, opts, flags,
1334 &oid);
1335 strbuf_release(&sb);
1336 if (!res) {
102de880
SB
1337 unlink(git_path_cherry_pick_head(the_repository));
1338 unlink(git_path_merge_msg(the_repository));
356ee465
PW
1339 if (!is_rebase_i(opts))
1340 print_commit_summary(NULL, &oid,
1341 SUMMARY_SHOW_AUTHOR_DATE);
1342 return res;
1343 }
1344 }
1345 if (res == 1)
1346 return run_git_commit(msg_file, opts, flags);
1347
1348 return res;
1349}
1350
b27cfb0d
NH
1351static int is_original_commit_empty(struct commit *commit)
1352{
092bbcdf 1353 const struct object_id *ptree_oid;
b27cfb0d
NH
1354
1355 if (parse_commit(commit))
aee42e1f 1356 return error(_("could not parse commit %s"),
f2fd0760 1357 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1358 if (commit->parents) {
1359 struct commit *parent = commit->parents->item;
1360 if (parse_commit(parent))
aee42e1f 1361 return error(_("could not parse parent commit %s"),
f2fd0760 1362 oid_to_hex(&parent->object.oid));
2e27bd77 1363 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1364 } else {
eb0ccfd7 1365 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1366 }
043a4492 1367
2e27bd77 1368 return !oidcmp(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1369}
1370
ac2b0e8f
JH
1371/*
1372 * Do we run "git commit" with "--allow-empty"?
1373 */
1374static int allow_empty(struct replay_opts *opts, struct commit *commit)
1375{
1376 int index_unchanged, empty_commit;
1377
1378 /*
1379 * Three cases:
1380 *
1381 * (1) we do not allow empty at all and error out.
1382 *
1383 * (2) we allow ones that were initially empty, but
1384 * forbid the ones that become empty;
1385 *
1386 * (3) we allow both.
1387 */
1388 if (!opts->allow_empty)
1389 return 0; /* let "git commit" barf as necessary */
1390
1391 index_unchanged = is_index_unchanged();
1392 if (index_unchanged < 0)
1393 return index_unchanged;
1394 if (!index_unchanged)
1395 return 0; /* we do not have to say --allow-empty */
1396
1397 if (opts->keep_redundant_commits)
1398 return 1;
1399
1400 empty_commit = is_original_commit_empty(commit);
1401 if (empty_commit < 0)
1402 return empty_commit;
1403 if (!empty_commit)
1404 return 0;
1405 else
1406 return 1;
1407}
1408
25c43667
JS
1409/*
1410 * Note that ordering matters in this enum. Not only must it match the mapping
1411 * below, it is also divided into several sections that matter. When adding
1412 * new commands, make sure you add it in the right section.
1413 */
004fefa7 1414enum todo_command {
25c43667 1415 /* commands that handle commits */
004fefa7 1416 TODO_PICK = 0,
25c43667 1417 TODO_REVERT,
56dc3ab0 1418 TODO_EDIT,
04efc8b5 1419 TODO_REWORD,
6e98de72
JS
1420 TODO_FIXUP,
1421 TODO_SQUASH,
311af526
JS
1422 /* commands that do something else than handling a single commit */
1423 TODO_EXEC,
9055e401
JS
1424 TODO_LABEL,
1425 TODO_RESET,
4c68e7dd 1426 TODO_MERGE,
25c43667 1427 /* commands that do nothing but are counted for reporting progress */
b3fdd581 1428 TODO_NOOP,
ac191470
JS
1429 TODO_DROP,
1430 /* comments (not counted for reporting progress) */
1431 TODO_COMMENT
004fefa7
JS
1432};
1433
414697a9
JS
1434static struct {
1435 char c;
1436 const char *str;
1437} todo_command_info[] = {
1438 { 'p', "pick" },
1439 { 0, "revert" },
1440 { 'e', "edit" },
04efc8b5 1441 { 'r', "reword" },
414697a9
JS
1442 { 'f', "fixup" },
1443 { 's', "squash" },
1444 { 'x', "exec" },
9055e401
JS
1445 { 'l', "label" },
1446 { 't', "reset" },
4c68e7dd 1447 { 'm', "merge" },
b3fdd581 1448 { 0, "noop" },
ac191470
JS
1449 { 'd', "drop" },
1450 { 0, NULL }
004fefa7
JS
1451};
1452
1453static const char *command_to_string(const enum todo_command command)
1454{
ac191470 1455 if (command < TODO_COMMENT)
414697a9 1456 return todo_command_info[command].str;
02127c63 1457 die(_("unknown command: %d"), command);
004fefa7
JS
1458}
1459
ee5462d6 1460static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1461{
1462 if (command < TODO_COMMENT && todo_command_info[command].c)
1463 return todo_command_info[command].c;
1464 return comment_line_char;
1465}
1466
25c43667
JS
1467static int is_noop(const enum todo_command command)
1468{
b3fdd581 1469 return TODO_NOOP <= command;
25c43667 1470}
004fefa7 1471
6e98de72
JS
1472static int is_fixup(enum todo_command command)
1473{
1474 return command == TODO_FIXUP || command == TODO_SQUASH;
1475}
1476
d87d48b2
JS
1477/* Does this command create a (non-merge) commit? */
1478static int is_pick_or_similar(enum todo_command command)
1479{
1480 switch (command) {
1481 case TODO_PICK:
1482 case TODO_REVERT:
1483 case TODO_EDIT:
1484 case TODO_REWORD:
1485 case TODO_FIXUP:
1486 case TODO_SQUASH:
1487 return 1;
1488 default:
1489 return 0;
1490 }
1491}
1492
6e98de72
JS
1493static int update_squash_messages(enum todo_command command,
1494 struct commit *commit, struct replay_opts *opts)
1495{
1496 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1497 int res;
6e98de72
JS
1498 const char *message, *body;
1499
e12a7ef5 1500 if (opts->current_fixup_count > 0) {
6e98de72 1501 struct strbuf header = STRBUF_INIT;
e12a7ef5 1502 char *eol;
6e98de72 1503
e12a7ef5 1504 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1505 return error(_("could not read '%s'"),
1506 rebase_path_squash_msg());
1507
e12a7ef5
JS
1508 eol = buf.buf[0] != comment_line_char ?
1509 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1510
1511 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1512 strbuf_addf(&header, _("This is a combination of %d commits."),
1513 opts->current_fixup_count + 2);
6e98de72
JS
1514 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1515 strbuf_release(&header);
1516 } else {
33d66df3 1517 struct object_id head;
6e98de72
JS
1518 struct commit *head_commit;
1519 const char *head_message, *body;
1520
33d66df3 1521 if (get_oid("HEAD", &head))
6e98de72 1522 return error(_("need a HEAD to fixup"));
2122f675 1523 if (!(head_commit = lookup_commit_reference(the_repository, &head)))
6e98de72
JS
1524 return error(_("could not read HEAD"));
1525 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1526 return error(_("could not read HEAD's commit message"));
1527
1528 find_commit_subject(head_message, &body);
1529 if (write_message(body, strlen(body),
1530 rebase_path_fixup_msg(), 0)) {
1531 unuse_commit_buffer(head_commit, head_message);
1532 return error(_("cannot write '%s'"),
1533 rebase_path_fixup_msg());
1534 }
1535
6e98de72 1536 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1537 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1538 strbuf_addf(&buf, "\n%c ", comment_line_char);
1539 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1540 strbuf_addstr(&buf, "\n\n");
1541 strbuf_addstr(&buf, body);
1542
1543 unuse_commit_buffer(head_commit, head_message);
1544 }
1545
1546 if (!(message = get_commit_buffer(commit, NULL)))
1547 return error(_("could not read commit message of %s"),
1548 oid_to_hex(&commit->object.oid));
1549 find_commit_subject(message, &body);
1550
1551 if (command == TODO_SQUASH) {
1552 unlink(rebase_path_fixup_msg());
1553 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1554 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1555 ++opts->current_fixup_count + 1);
6e98de72
JS
1556 strbuf_addstr(&buf, "\n\n");
1557 strbuf_addstr(&buf, body);
1558 } else if (command == TODO_FIXUP) {
1559 strbuf_addf(&buf, "\n%c ", comment_line_char);
1560 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1561 ++opts->current_fixup_count + 1);
6e98de72
JS
1562 strbuf_addstr(&buf, "\n\n");
1563 strbuf_add_commented_lines(&buf, body, strlen(body));
1564 } else
1565 return error(_("unknown command: %d"), command);
1566 unuse_commit_buffer(commit, message);
1567
1568 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1569 strbuf_release(&buf);
e12a7ef5
JS
1570
1571 if (!res) {
1572 strbuf_addf(&opts->current_fixups, "%s%s %s",
1573 opts->current_fixups.len ? "\n" : "",
1574 command_to_string(command),
1575 oid_to_hex(&commit->object.oid));
1576 res = write_message(opts->current_fixups.buf,
1577 opts->current_fixups.len,
1578 rebase_path_current_fixups(), 0);
1579 }
1580
6e98de72
JS
1581 return res;
1582}
1583
25cb8df9
JS
1584static void flush_rewritten_pending(void) {
1585 struct strbuf buf = STRBUF_INIT;
092bbcdf 1586 struct object_id newoid;
25cb8df9
JS
1587 FILE *out;
1588
092bbcdf 1589 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1590 !get_oid("HEAD", &newoid) &&
e9d983f1 1591 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1592 char *bol = buf.buf, *eol;
1593
1594 while (*bol) {
1595 eol = strchrnul(bol, '\n');
1596 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1597 bol, oid_to_hex(&newoid));
25cb8df9
JS
1598 if (!*eol)
1599 break;
1600 bol = eol + 1;
1601 }
1602 fclose(out);
1603 unlink(rebase_path_rewritten_pending());
1604 }
1605 strbuf_release(&buf);
1606}
1607
1608static void record_in_rewritten(struct object_id *oid,
1609 enum todo_command next_command) {
e9d983f1 1610 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1611
1612 if (!out)
1613 return;
1614
1615 fprintf(out, "%s\n", oid_to_hex(oid));
1616 fclose(out);
1617
1618 if (!is_fixup(next_command))
1619 flush_rewritten_pending();
1620}
1621
004fefa7 1622static int do_pick_commit(enum todo_command command, struct commit *commit,
6e98de72 1623 struct replay_opts *opts, int final_fixup)
043a4492 1624{
789b3eff 1625 unsigned int flags = opts->edit ? EDIT_MSG : 0;
102de880 1626 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(the_repository);
ace976b2 1627 struct object_id head;
043a4492
RR
1628 struct commit *base, *next, *parent;
1629 const char *base_label, *next_label;
356ee465 1630 char *author = NULL;
d74a4e57 1631 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1632 struct strbuf msgbuf = STRBUF_INIT;
789b3eff 1633 int res, unborn = 0, allow;
043a4492
RR
1634
1635 if (opts->no_commit) {
1636 /*
1637 * We do not intend to commit immediately. We just want to
1638 * merge the differences in, so let's compute the tree
1639 * that represents the "current" state for merge-recursive
1640 * to work on.
1641 */
07096c96 1642 if (write_index_as_tree(&head, &the_index, get_index_file(), 0, NULL))
93b3df6f 1643 return error(_("your index file is unmerged."));
043a4492 1644 } else {
ace976b2 1645 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1646 /* Do we want to generate a root commit? */
1647 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1648 !oidcmp(&head, &opts->squash_onto)) {
1649 if (is_fixup(command))
1650 return error(_("cannot fixup root commit"));
1651 flags |= CREATE_ROOT_COMMIT;
1652 unborn = 1;
1653 } else if (unborn)
eb0ccfd7 1654 oidcpy(&head, the_hash_algo->empty_tree);
7a915b4b 1655 if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1656 NULL, 0))
043a4492
RR
1657 return error_dirty_index(opts);
1658 }
1659 discard_cache();
1660
637666c8 1661 if (!commit->parents)
043a4492 1662 parent = NULL;
043a4492
RR
1663 else if (commit->parents->next) {
1664 /* Reverting or cherry-picking a merge commit */
1665 int cnt;
1666 struct commit_list *p;
1667
1668 if (!opts->mainline)
93b3df6f 1669 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1670 oid_to_hex(&commit->object.oid));
043a4492
RR
1671
1672 for (cnt = 1, p = commit->parents;
1673 cnt != opts->mainline && p;
1674 cnt++)
1675 p = p->next;
1676 if (cnt != opts->mainline || !p)
93b3df6f 1677 return error(_("commit %s does not have parent %d"),
f2fd0760 1678 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1679 parent = p->item;
1680 } else if (0 < opts->mainline)
93b3df6f 1681 return error(_("mainline was specified but commit %s is not a merge."),
f2fd0760 1682 oid_to_hex(&commit->object.oid));
043a4492
RR
1683 else
1684 parent = commit->parents->item;
1685
bcbb68be
JS
1686 if (get_message(commit, &msg) != 0)
1687 return error(_("cannot get commit message for %s"),
1688 oid_to_hex(&commit->object.oid));
1689
6e98de72 1690 if (opts->allow_ff && !is_fixup(command) &&
ace976b2 1691 ((parent && !oidcmp(&parent->object.oid, &head)) ||
bcbb68be
JS
1692 (!parent && unborn))) {
1693 if (is_rebase_i(opts))
1694 write_author_script(msg.message);
ace976b2 1695 res = fast_forward_to(&commit->object.oid, &head, unborn,
bcbb68be
JS
1696 opts);
1697 if (res || command != TODO_REWORD)
1698 goto leave;
5f8f9277 1699 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
bcbb68be
JS
1700 msg_file = NULL;
1701 goto fast_forward_edit;
1702 }
043a4492 1703 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1704 /* TRANSLATORS: The first %s will be a "todo" command like
1705 "revert" or "pick", the second %s a SHA1. */
043a4492 1706 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1707 command_to_string(command),
1708 oid_to_hex(&parent->object.oid));
043a4492 1709
043a4492
RR
1710 /*
1711 * "commit" is an existing commit. We would want to apply
1712 * the difference it introduces since its first parent "prev"
1713 * on top of the current HEAD if we are cherry-pick. Or the
1714 * reverse of it if we are revert.
1715 */
1716
004fefa7 1717 if (command == TODO_REVERT) {
043a4492
RR
1718 base = commit;
1719 base_label = msg.label;
1720 next = parent;
1721 next_label = msg.parent_label;
1722 strbuf_addstr(&msgbuf, "Revert \"");
1723 strbuf_addstr(&msgbuf, msg.subject);
1724 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1725 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1726
1727 if (commit->parents && commit->parents->next) {
1728 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1729 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1730 }
1731 strbuf_addstr(&msgbuf, ".\n");
1732 } else {
1733 const char *p;
1734
1735 base = parent;
1736 base_label = msg.parent_label;
1737 next = commit;
1738 next_label = msg.label;
1739
23aa5142
JS
1740 /* Append the commit log message to msgbuf. */
1741 if (find_commit_subject(msg.message, &p))
1742 strbuf_addstr(&msgbuf, p);
043a4492
RR
1743
1744 if (opts->record_origin) {
44dc738a 1745 strbuf_complete_line(&msgbuf);
bab4d109 1746 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1747 strbuf_addch(&msgbuf, '\n');
cd650a4e 1748 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1749 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1750 strbuf_addstr(&msgbuf, ")\n");
1751 }
356ee465
PW
1752 if (!is_fixup(command))
1753 author = get_author(msg.message);
043a4492
RR
1754 }
1755
04efc8b5 1756 if (command == TODO_REWORD)
b92ff6e8 1757 flags |= EDIT_MSG | VERIFY_MSG;
04efc8b5 1758 else if (is_fixup(command)) {
6e98de72
JS
1759 if (update_squash_messages(command, commit, opts))
1760 return -1;
789b3eff 1761 flags |= AMEND_MSG;
6e98de72
JS
1762 if (!final_fixup)
1763 msg_file = rebase_path_squash_msg();
1764 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1765 flags |= CLEANUP_MSG;
6e98de72
JS
1766 msg_file = rebase_path_fixup_msg();
1767 } else {
102de880 1768 const char *dest = git_path_squash_msg(the_repository);
6e98de72
JS
1769 unlink(dest);
1770 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1771 return error(_("could not rename '%s' to '%s'"),
1772 rebase_path_squash_msg(), dest);
102de880 1773 unlink(git_path_merge_msg(the_repository));
6e98de72 1774 msg_file = dest;
789b3eff 1775 flags |= EDIT_MSG;
6e98de72
JS
1776 }
1777 }
1778
a852ec7f 1779 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1780 append_signoff(&msgbuf, 0, 0);
1781
0473f28a
JS
1782 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1783 res = -1;
1784 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
043a4492 1785 res = do_recursive_merge(base, next, base_label, next_label,
48be4c62 1786 &head, &msgbuf, opts);
f241ff0d 1787 if (res < 0)
19517fb9
SB
1788 goto leave;
1789
75871495 1790 res |= write_message(msgbuf.buf, msgbuf.len,
102de880 1791 git_path_merge_msg(the_repository), 0);
043a4492
RR
1792 } else {
1793 struct commit_list *common = NULL;
1794 struct commit_list *remotes = NULL;
1795
75871495 1796 res = write_message(msgbuf.buf, msgbuf.len,
102de880 1797 git_path_merge_msg(the_repository), 0);
043a4492
RR
1798
1799 commit_list_insert(base, &common);
1800 commit_list_insert(next, &remotes);
03a4e260
JS
1801 res |= try_merge_command(opts->strategy,
1802 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1803 common, oid_to_hex(&head), remotes);
043a4492
RR
1804 free_commit_list(common);
1805 free_commit_list(remotes);
1806 }
452202c7 1807 strbuf_release(&msgbuf);
043a4492
RR
1808
1809 /*
1810 * If the merge was clean or if it failed due to conflict, we write
1811 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1812 * However, if the merge did not even start, then we don't want to
1813 * write it at all.
1814 */
004fefa7 1815 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1816 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 1817 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1818 res = -1;
004fefa7 1819 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 1820 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 1821 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1822 res = -1;
043a4492
RR
1823
1824 if (res) {
004fefa7 1825 error(command == TODO_REVERT
043a4492
RR
1826 ? _("could not revert %s... %s")
1827 : _("could not apply %s... %s"),
39755964 1828 short_commit_name(commit), msg.subject);
ed727b19 1829 print_advice(res == 1, opts);
043a4492 1830 rerere(opts->allow_rerere_auto);
c8d1351d 1831 goto leave;
043a4492
RR
1832 }
1833
c8d1351d 1834 allow = allow_empty(opts, commit);
706728a3
FC
1835 if (allow < 0) {
1836 res = allow;
1837 goto leave;
789b3eff
JS
1838 } else if (allow)
1839 flags |= ALLOW_EMPTY;
356ee465 1840 if (!opts->no_commit) {
bcbb68be 1841fast_forward_edit:
356ee465
PW
1842 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1843 res = do_commit(msg_file, author, opts, flags);
1844 else
1845 res = error(_("unable to parse commit author"));
1846 }
6e98de72
JS
1847
1848 if (!res && final_fixup) {
1849 unlink(rebase_path_fixup_msg());
1850 unlink(rebase_path_squash_msg());
e12a7ef5
JS
1851 unlink(rebase_path_current_fixups());
1852 strbuf_reset(&opts->current_fixups);
1853 opts->current_fixup_count = 0;
6e98de72 1854 }
c8d1351d
FC
1855
1856leave:
d74a4e57 1857 free_message(commit, &msg);
356ee465 1858 free(author);
1e41229d 1859 update_abort_safety_file();
043a4492
RR
1860
1861 return res;
1862}
1863
c3e8618c 1864static int prepare_revs(struct replay_opts *opts)
043a4492 1865{
a73e22e9
MZ
1866 /*
1867 * picking (but not reverting) ranges (but not individual revisions)
1868 * should be done in reverse
1869 */
1870 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
1871 opts->revs->reverse ^= 1;
1872
1873 if (prepare_revision_walk(opts->revs))
c3e8618c 1874 return error(_("revision walk setup failed"));
043a4492 1875
c3e8618c 1876 return 0;
043a4492
RR
1877}
1878
0d9c6dc9 1879static int read_and_refresh_cache(struct replay_opts *opts)
043a4492 1880{
14bca6c6 1881 struct lock_file index_lock = LOCK_INIT;
043a4492 1882 int index_fd = hold_locked_index(&index_lock, 0);
49fb937e
JS
1883 if (read_index_preload(&the_index, NULL) < 0) {
1884 rollback_lock_file(&index_lock);
0d9c6dc9 1885 return error(_("git %s: failed to read the index"),
c28cbc5e 1886 _(action_name(opts)));
49fb937e 1887 }
043a4492 1888 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814
1889 if (index_fd >= 0) {
1890 if (write_locked_index(&the_index, &index_lock,
1891 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 1892 return error(_("git %s: failed to refresh the index"),
c28cbc5e 1893 _(action_name(opts)));
49fb937e 1894 }
043a4492 1895 }
0d9c6dc9 1896 return 0;
043a4492
RR
1897}
1898
4c68e7dd
JS
1899enum todo_item_flags {
1900 TODO_EDIT_MERGE_MSG = 1
1901};
1902
004fefa7
JS
1903struct todo_item {
1904 enum todo_command command;
1905 struct commit *commit;
4c68e7dd 1906 unsigned int flags;
c22f7dfb
JS
1907 const char *arg;
1908 int arg_len;
004fefa7
JS
1909 size_t offset_in_buf;
1910};
1911
1912struct todo_list {
1913 struct strbuf buf;
1914 struct todo_item *items;
1915 int nr, alloc, current;
968492e4 1916 int done_nr, total_nr;
54fd3243 1917 struct stat_data stat;
004fefa7
JS
1918};
1919
1920#define TODO_LIST_INIT { STRBUF_INIT }
1921
1922static void todo_list_release(struct todo_list *todo_list)
043a4492 1923{
004fefa7 1924 strbuf_release(&todo_list->buf);
6a83d902 1925 FREE_AND_NULL(todo_list->items);
004fefa7
JS
1926 todo_list->nr = todo_list->alloc = 0;
1927}
043a4492 1928
004fefa7
JS
1929static struct todo_item *append_new_todo(struct todo_list *todo_list)
1930{
1931 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1932 return todo_list->items + todo_list->nr++;
043a4492
RR
1933}
1934
004fefa7 1935static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
043a4492 1936{
1e43ed98 1937 struct object_id commit_oid;
043a4492 1938 char *end_of_object_name;
004fefa7
JS
1939 int i, saved, status, padding;
1940
4c68e7dd
JS
1941 item->flags = 0;
1942
8f8550b3
JS
1943 /* left-trim */
1944 bol += strspn(bol, " \t");
1945
25c43667 1946 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 1947 item->command = TODO_COMMENT;
25c43667
JS
1948 item->commit = NULL;
1949 item->arg = bol;
1950 item->arg_len = eol - bol;
1951 return 0;
1952 }
1953
ac191470 1954 for (i = 0; i < TODO_COMMENT; i++)
414697a9
JS
1955 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1956 item->command = i;
1957 break;
1958 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1959 bol++;
004fefa7
JS
1960 item->command = i;
1961 break;
1962 }
ac191470 1963 if (i >= TODO_COMMENT)
004fefa7 1964 return -1;
043a4492 1965
66afa24f
JS
1966 /* Eat up extra spaces/ tabs before object name */
1967 padding = strspn(bol, " \t");
1968 bol += padding;
1969
25c43667 1970 if (item->command == TODO_NOOP) {
66afa24f
JS
1971 if (bol != eol)
1972 return error(_("%s does not accept arguments: '%s'"),
1973 command_to_string(item->command), bol);
25c43667
JS
1974 item->commit = NULL;
1975 item->arg = bol;
1976 item->arg_len = eol - bol;
1977 return 0;
1978 }
1979
043a4492 1980 if (!padding)
66afa24f
JS
1981 return error(_("missing arguments for %s"),
1982 command_to_string(item->command));
043a4492 1983
9055e401
JS
1984 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
1985 item->command == TODO_RESET) {
7dcbb3cb 1986 item->commit = NULL;
311af526
JS
1987 item->arg = bol;
1988 item->arg_len = (int)(eol - bol);
1989 return 0;
1990 }
1991
4c68e7dd
JS
1992 if (item->command == TODO_MERGE) {
1993 if (skip_prefix(bol, "-C", &bol))
1994 bol += strspn(bol, " \t");
1995 else if (skip_prefix(bol, "-c", &bol)) {
1996 bol += strspn(bol, " \t");
1997 item->flags |= TODO_EDIT_MERGE_MSG;
1998 } else {
1999 item->flags |= TODO_EDIT_MERGE_MSG;
2000 item->commit = NULL;
2001 item->arg = bol;
2002 item->arg_len = (int)(eol - bol);
2003 return 0;
2004 }
2005 }
2006
004fefa7 2007 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2008 saved = *end_of_object_name;
2009 *end_of_object_name = '\0';
1e43ed98 2010 status = get_oid(bol, &commit_oid);
043a4492
RR
2011 *end_of_object_name = saved;
2012
c22f7dfb
JS
2013 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2014 item->arg_len = (int)(eol - item->arg);
2015
043a4492 2016 if (status < 0)
004fefa7 2017 return -1;
043a4492 2018
2122f675 2019 item->commit = lookup_commit_reference(the_repository, &commit_oid);
004fefa7 2020 return !item->commit;
043a4492
RR
2021}
2022
004fefa7 2023static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
043a4492 2024{
004fefa7
JS
2025 struct todo_item *item;
2026 char *p = buf, *next_p;
6e98de72 2027 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2028
004fefa7 2029 for (i = 1; *p; i++, p = next_p) {
043a4492 2030 char *eol = strchrnul(p, '\n');
004fefa7
JS
2031
2032 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2033
6307041d
JS
2034 if (p != eol && eol[-1] == '\r')
2035 eol--; /* strip Carriage Return */
2036
004fefa7
JS
2037 item = append_new_todo(todo_list);
2038 item->offset_in_buf = p - todo_list->buf.buf;
2039 if (parse_insn_line(item, p, eol)) {
93b3df6f 2040 res = error(_("invalid line %d: %.*s"),
004fefa7 2041 i, (int)(eol - p), p);
6e98de72 2042 item->command = TODO_NOOP;
004fefa7 2043 }
6e98de72
JS
2044
2045 if (fixup_okay)
2046 ; /* do nothing */
2047 else if (is_fixup(item->command))
2048 return error(_("cannot '%s' without a previous commit"),
2049 command_to_string(item->command));
2050 else if (!is_noop(item->command))
2051 fixup_okay = 1;
043a4492 2052 }
52865279 2053
004fefa7 2054 return res;
043a4492
RR
2055}
2056
968492e4
JS
2057static int count_commands(struct todo_list *todo_list)
2058{
2059 int count = 0, i;
2060
2061 for (i = 0; i < todo_list->nr; i++)
2062 if (todo_list->items[i].command != TODO_COMMENT)
2063 count++;
2064
2065 return count;
2066}
2067
a01c2a5f
JS
2068static int get_item_line_offset(struct todo_list *todo_list, int index)
2069{
2070 return index < todo_list->nr ?
2071 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2072}
2073
2074static const char *get_item_line(struct todo_list *todo_list, int index)
2075{
2076 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2077}
2078
2079static int get_item_line_length(struct todo_list *todo_list, int index)
2080{
2081 return get_item_line_offset(todo_list, index + 1)
2082 - get_item_line_offset(todo_list, index);
2083}
2084
87805600
RS
2085static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2086{
2087 int fd;
2088 ssize_t len;
2089
2090 fd = open(path, O_RDONLY);
2091 if (fd < 0)
2092 return error_errno(_("could not open '%s'"), path);
2093 len = strbuf_read(sb, fd, 0);
2094 close(fd);
2095 if (len < 0)
2096 return error(_("could not read '%s'."), path);
2097 return len;
2098}
2099
004fefa7 2100static int read_populate_todo(struct todo_list *todo_list,
043a4492
RR
2101 struct replay_opts *opts)
2102{
54fd3243 2103 struct stat st;
c0246501 2104 const char *todo_file = get_todo_path(opts);
87805600 2105 int res;
043a4492 2106
004fefa7 2107 strbuf_reset(&todo_list->buf);
87805600
RS
2108 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2109 return -1;
043a4492 2110
54fd3243
SH
2111 res = stat(todo_file, &st);
2112 if (res)
2113 return error(_("could not stat '%s'"), todo_file);
2114 fill_stat_data(&todo_list->stat, &st);
2115
004fefa7 2116 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
27fdbb96
JS
2117 if (res) {
2118 if (is_rebase_i(opts))
2119 return error(_("please fix this using "
2120 "'git rebase --edit-todo'."));
93b3df6f 2121 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2122 }
2eeaf1b3 2123
52865279
JS
2124 if (!todo_list->nr &&
2125 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2126 return error(_("no commits parsed."));
2127
2eeaf1b3 2128 if (!is_rebase_i(opts)) {
004fefa7
JS
2129 enum todo_command valid =
2130 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2131 int i;
2132
2133 for (i = 0; i < todo_list->nr; i++)
2134 if (valid == todo_list->items[i].command)
2135 continue;
2136 else if (valid == TODO_PICK)
93b3df6f 2137 return error(_("cannot cherry-pick during a revert."));
004fefa7 2138 else
93b3df6f 2139 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2140 }
2141
968492e4
JS
2142 if (is_rebase_i(opts)) {
2143 struct todo_list done = TODO_LIST_INIT;
e9d983f1 2144 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
968492e4
JS
2145
2146 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2147 !parse_insn_buffer(done.buf.buf, &done))
2148 todo_list->done_nr = count_commands(&done);
2149 else
2150 todo_list->done_nr = 0;
2151
2152 todo_list->total_nr = todo_list->done_nr
2153 + count_commands(todo_list);
968492e4 2154 todo_list_release(&done);
ef80069a
JS
2155
2156 if (f) {
2157 fprintf(f, "%d\n", todo_list->total_nr);
2158 fclose(f);
2159 }
968492e4
JS
2160 }
2161
0ae42a03 2162 return 0;
043a4492
RR
2163}
2164
03a4e260
JS
2165static int git_config_string_dup(char **dest,
2166 const char *var, const char *value)
2167{
2168 if (!value)
2169 return config_error_nonbool(var);
2170 free(*dest);
2171 *dest = xstrdup(value);
2172 return 0;
2173}
2174
043a4492
RR
2175static int populate_opts_cb(const char *key, const char *value, void *data)
2176{
2177 struct replay_opts *opts = data;
2178 int error_flag = 1;
2179
2180 if (!value)
2181 error_flag = 0;
2182 else if (!strcmp(key, "options.no-commit"))
2183 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2184 else if (!strcmp(key, "options.edit"))
2185 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2186 else if (!strcmp(key, "options.signoff"))
2187 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2188 else if (!strcmp(key, "options.record-origin"))
2189 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2190 else if (!strcmp(key, "options.allow-ff"))
2191 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2192 else if (!strcmp(key, "options.mainline"))
2193 opts->mainline = git_config_int(key, value);
2194 else if (!strcmp(key, "options.strategy"))
03a4e260 2195 git_config_string_dup(&opts->strategy, key, value);
3253553e 2196 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2197 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2198 else if (!strcmp(key, "options.strategy-option")) {
2199 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2200 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2201 } else if (!strcmp(key, "options.allow-rerere-auto"))
2202 opts->allow_rerere_auto =
2203 git_config_bool_or_int(key, value, &error_flag) ?
2204 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2205 else
93b3df6f 2206 return error(_("invalid key: %s"), key);
043a4492
RR
2207
2208 if (!error_flag)
93b3df6f 2209 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2210
2211 return 0;
2212}
2213
ca6c6b45
JS
2214static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2215{
2216 int i;
0060041d 2217 char *strategy_opts_string;
ca6c6b45
JS
2218
2219 strbuf_reset(buf);
2220 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2221 return;
2222 opts->strategy = strbuf_detach(buf, NULL);
2223 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2224 return;
2225
0060041d
EN
2226 strategy_opts_string = buf->buf;
2227 if (*strategy_opts_string == ' ')
2228 strategy_opts_string++;
2229 opts->xopts_nr = split_cmdline(strategy_opts_string,
2230 (const char ***)&opts->xopts);
ca6c6b45
JS
2231 for (i = 0; i < opts->xopts_nr; i++) {
2232 const char *arg = opts->xopts[i];
2233
2234 skip_prefix(arg, "--", &arg);
2235 opts->xopts[i] = xstrdup(arg);
2236 }
2237}
2238
5adf9bdc 2239static int read_populate_opts(struct replay_opts *opts)
043a4492 2240{
a1c75762
JS
2241 if (is_rebase_i(opts)) {
2242 struct strbuf buf = STRBUF_INIT;
2243
2244 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2245 if (!starts_with(buf.buf, "-S"))
2246 strbuf_reset(&buf);
2247 else {
2248 free(opts->gpg_sign);
2249 opts->gpg_sign = xstrdup(buf.buf + 2);
2250 }
9b6d7a62
PW
2251 strbuf_reset(&buf);
2252 }
2253
2254 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2255 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2256 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2257 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2258 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2259 strbuf_reset(&buf);
a1c75762 2260 }
a1c75762 2261
556907f1
JS
2262 if (file_exists(rebase_path_verbose()))
2263 opts->verbose = 1;
2264
a852ec7f
PW
2265 if (file_exists(rebase_path_signoff())) {
2266 opts->allow_ff = 0;
2267 opts->signoff = 1;
2268 }
2269
ca6c6b45
JS
2270 read_strategy_opts(opts, &buf);
2271 strbuf_release(&buf);
2272
e12a7ef5
JS
2273 if (read_oneliner(&opts->current_fixups,
2274 rebase_path_current_fixups(), 1)) {
2275 const char *p = opts->current_fixups.buf;
2276 opts->current_fixup_count = 1;
2277 while ((p = strchr(p, '\n'))) {
2278 opts->current_fixup_count++;
2279 p++;
2280 }
2281 }
2282
d87d48b2
JS
2283 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2284 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2285 return error(_("unusable squash-onto"));
2286 opts->have_squash_onto = 1;
2287 }
2288
b5a67045 2289 return 0;
a1c75762 2290 }
b5a67045 2291
f932729c 2292 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2293 return 0;
2294 /*
2295 * The function git_parse_source(), called from git_config_from_file(),
2296 * may die() in case of a syntactically incorrect file. We do not care
2297 * about this case, though, because we wrote that file ourselves, so we
2298 * are pretty certain that it is syntactically correct.
2299 */
5adf9bdc 2300 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2301 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2302 git_path_opts_file());
2303 return 0;
043a4492
RR
2304}
2305
004fefa7 2306static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2307 struct replay_opts *opts)
2308{
004fefa7
JS
2309 enum todo_command command = opts->action == REPLAY_PICK ?
2310 TODO_PICK : TODO_REVERT;
414697a9 2311 const char *command_string = todo_command_info[command].str;
043a4492 2312 struct commit *commit;
043a4492 2313
34b0528b
JS
2314 if (prepare_revs(opts))
2315 return -1;
043a4492 2316
004fefa7
JS
2317 while ((commit = get_revision(opts->revs))) {
2318 struct todo_item *item = append_new_todo(todo_list);
2319 const char *commit_buffer = get_commit_buffer(commit, NULL);
2320 const char *subject;
2321 int subject_len;
2322
2323 item->command = command;
2324 item->commit = commit;
c22f7dfb
JS
2325 item->arg = NULL;
2326 item->arg_len = 0;
004fefa7
JS
2327 item->offset_in_buf = todo_list->buf.len;
2328 subject_len = find_commit_subject(commit_buffer, &subject);
2329 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2330 short_commit_name(commit), subject_len, subject);
2331 unuse_commit_buffer(commit, commit_buffer);
2332 }
8530c739
JK
2333
2334 if (!todo_list->nr)
2335 return error(_("empty commit set passed"));
2336
34b0528b 2337 return 0;
043a4492
RR
2338}
2339
2340static int create_seq_dir(void)
2341{
f932729c 2342 if (file_exists(git_path_seq_dir())) {
043a4492
RR
2343 error(_("a cherry-pick or revert is already in progress"));
2344 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2345 return -1;
a70d8f80 2346 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2347 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2348 git_path_seq_dir());
043a4492
RR
2349 return 0;
2350}
2351
311fd397 2352static int save_head(const char *head)
043a4492 2353{
14bca6c6 2354 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2355 struct strbuf buf = STRBUF_INIT;
2356 int fd;
ed3f9a12 2357 ssize_t written;
043a4492 2358
311fd397 2359 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2360 if (fd < 0)
93b3df6f 2361 return error_errno(_("could not lock HEAD"));
043a4492 2362 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2363 written = write_in_full(fd, buf.buf, buf.len);
2364 strbuf_release(&buf);
2365 if (written < 0) {
bf5c0571 2366 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2367 rollback_lock_file(&head_lock);
bf5c0571 2368 return -1;
311fd397 2369 }
350292a1
2370 if (commit_lock_file(&head_lock) < 0)
2371 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2372 return 0;
043a4492
RR
2373}
2374
1e41229d
SB
2375static int rollback_is_safe(void)
2376{
2377 struct strbuf sb = STRBUF_INIT;
2378 struct object_id expected_head, actual_head;
2379
2380 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2381 strbuf_trim(&sb);
2382 if (get_oid_hex(sb.buf, &expected_head)) {
2383 strbuf_release(&sb);
2384 die(_("could not parse %s"), git_path_abort_safety_file());
2385 }
2386 strbuf_release(&sb);
2387 }
2388 else if (errno == ENOENT)
2389 oidclr(&expected_head);
2390 else
2391 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2392
2393 if (get_oid("HEAD", &actual_head))
2394 oidclr(&actual_head);
2395
2396 return !oidcmp(&actual_head, &expected_head);
2397}
2398
092bbcdf 2399static int reset_for_rollback(const struct object_id *oid)
043a4492
RR
2400{
2401 const char *argv[4]; /* reset --merge <arg> + NULL */
1e41229d 2402
043a4492
RR
2403 argv[0] = "reset";
2404 argv[1] = "--merge";
092bbcdf 2405 argv[2] = oid_to_hex(oid);
043a4492
RR
2406 argv[3] = NULL;
2407 return run_command_v_opt(argv, RUN_GIT_CMD);
2408}
2409
2410static int rollback_single_pick(void)
2411{
092bbcdf 2412 struct object_id head_oid;
043a4492 2413
102de880
SB
2414 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
2415 !file_exists(git_path_revert_head(the_repository)))
043a4492 2416 return error(_("no cherry-pick or revert in progress"));
34c290a6 2417 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2418 return error(_("cannot resolve HEAD"));
092bbcdf 2419 if (is_null_oid(&head_oid))
043a4492 2420 return error(_("cannot abort from a branch yet to be born"));
092bbcdf 2421 return reset_for_rollback(&head_oid);
043a4492
RR
2422}
2423
2863584f 2424int sequencer_rollback(struct replay_opts *opts)
043a4492 2425{
043a4492 2426 FILE *f;
092bbcdf 2427 struct object_id oid;
043a4492 2428 struct strbuf buf = STRBUF_INIT;
092bbcdf 2429 const char *p;
043a4492 2430
f932729c 2431 f = fopen(git_path_head_file(), "r");
043a4492
RR
2432 if (!f && errno == ENOENT) {
2433 /*
2434 * There is no multiple-cherry-pick in progress.
2435 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2436 * a single-cherry-pick in progress, abort that.
2437 */
2438 return rollback_single_pick();
2439 }
2440 if (!f)
f7ed1953 2441 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2442 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2443 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2444 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2445 fclose(f);
2446 goto fail;
2447 }
2448 fclose(f);
092bbcdf 2449 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2450 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2451 git_path_head_file());
043a4492
RR
2452 goto fail;
2453 }
092bbcdf 2454 if (is_null_oid(&oid)) {
0f974e21
MG
2455 error(_("cannot abort from a branch yet to be born"));
2456 goto fail;
2457 }
1e41229d
SB
2458
2459 if (!rollback_is_safe()) {
2460 /* Do not error, just do not rollback */
2461 warning(_("You seem to have moved HEAD. "
2462 "Not rewinding, check your HEAD!"));
2463 } else
092bbcdf 2464 if (reset_for_rollback(&oid))
043a4492 2465 goto fail;
043a4492 2466 strbuf_release(&buf);
2863584f 2467 return sequencer_remove_state(opts);
043a4492
RR
2468fail:
2469 strbuf_release(&buf);
2470 return -1;
2471}
2472
004fefa7 2473static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2474{
14bca6c6 2475 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2476 const char *todo_path = get_todo_path(opts);
2477 int next = todo_list->current, offset, fd;
043a4492 2478
84583957
JS
2479 /*
2480 * rebase -i writes "git-rebase-todo" without the currently executing
2481 * command, appending it to "done" instead.
2482 */
2483 if (is_rebase_i(opts))
2484 next++;
2485
004fefa7 2486 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2487 if (fd < 0)
93b3df6f 2488 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2489 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2490 if (write_in_full(fd, todo_list->buf.buf + offset,
2491 todo_list->buf.len - offset) < 0)
93b3df6f 2492 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2493 if (commit_lock_file(&todo_lock) < 0)
350292a1 2494 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2495
a01c2a5f
JS
2496 if (is_rebase_i(opts) && next > 0) {
2497 const char *done = rebase_path_done();
2498 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2499 int ret = 0;
1df6df0c 2500
a01c2a5f
JS
2501 if (fd < 0)
2502 return 0;
2503 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2504 get_item_line_length(todo_list, next - 1))
2505 < 0)
2506 ret = error_errno(_("could not write to '%s'"), done);
2507 if (close(fd) < 0)
2508 ret = error_errno(_("failed to finalize '%s'"), done);
2509 return ret;
1df6df0c 2510 }
221675de 2511 return 0;
043a4492
RR
2512}
2513
88d5a271 2514static int save_opts(struct replay_opts *opts)
043a4492 2515{
f932729c 2516 const char *opts_file = git_path_opts_file();
88d5a271 2517 int res = 0;
043a4492
RR
2518
2519 if (opts->no_commit)
88d5a271 2520 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 2521 if (opts->edit)
88d5a271 2522 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 2523 if (opts->signoff)
88d5a271 2524 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 2525 if (opts->record_origin)
88d5a271 2526 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 2527 if (opts->allow_ff)
88d5a271 2528 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
2529 if (opts->mainline) {
2530 struct strbuf buf = STRBUF_INIT;
2531 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 2532 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
2533 strbuf_release(&buf);
2534 }
2535 if (opts->strategy)
88d5a271 2536 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 2537 if (opts->gpg_sign)
88d5a271 2538 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2539 if (opts->xopts) {
2540 int i;
2541 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2542 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
2543 "options.strategy-option",
2544 opts->xopts[i], "^$", 0);
2545 }
8d8cb4b0
PW
2546 if (opts->allow_rerere_auto)
2547 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2548 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2549 "true" : "false");
88d5a271 2550 return res;
043a4492
RR
2551}
2552
56dc3ab0
JS
2553static int make_patch(struct commit *commit, struct replay_opts *opts)
2554{
2555 struct strbuf buf = STRBUF_INIT;
2556 struct rev_info log_tree_opt;
2557 const char *subject, *p;
2558 int res = 0;
2559
2560 p = short_commit_name(commit);
2561 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2562 return -1;
fbd7a232
NTND
2563 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2564 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2565 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
2566
2567 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2568 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2569 init_revisions(&log_tree_opt, NULL);
2570 log_tree_opt.abbrev = 0;
2571 log_tree_opt.diff = 1;
2572 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2573 log_tree_opt.disable_stdin = 1;
2574 log_tree_opt.no_commit_id = 1;
2575 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2576 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2577 if (!log_tree_opt.diffopt.file)
2578 res |= error_errno(_("could not open '%s'"), buf.buf);
2579 else {
2580 res |= log_tree_commit(&log_tree_opt, commit);
2581 fclose(log_tree_opt.diffopt.file);
2582 }
2583 strbuf_reset(&buf);
2584
2585 strbuf_addf(&buf, "%s/message", get_dir(opts));
2586 if (!file_exists(buf.buf)) {
2587 const char *commit_buffer = get_commit_buffer(commit, NULL);
2588 find_commit_subject(commit_buffer, &subject);
2589 res |= write_message(subject, strlen(subject), buf.buf, 1);
2590 unuse_commit_buffer(commit, commit_buffer);
2591 }
2592 strbuf_release(&buf);
2593
2594 return res;
2595}
2596
2597static int intend_to_amend(void)
2598{
092bbcdf 2599 struct object_id head;
56dc3ab0
JS
2600 char *p;
2601
092bbcdf 2602 if (get_oid("HEAD", &head))
56dc3ab0
JS
2603 return error(_("cannot read HEAD"));
2604
092bbcdf 2605 p = oid_to_hex(&head);
56dc3ab0
JS
2606 return write_message(p, strlen(p), rebase_path_amend(), 1);
2607}
2608
2609static int error_with_patch(struct commit *commit,
2610 const char *subject, int subject_len,
2611 struct replay_opts *opts, int exit_code, int to_amend)
2612{
2613 if (make_patch(commit, opts))
2614 return -1;
2615
2616 if (to_amend) {
2617 if (intend_to_amend())
2618 return -1;
2619
02127c63
NTND
2620 fprintf(stderr,
2621 _("You can amend the commit now, with\n"
2622 "\n"
2623 " git commit --amend %s\n"
2624 "\n"
2625 "Once you are satisfied with your changes, run\n"
2626 "\n"
2627 " git rebase --continue\n"),
2628 gpg_sign_opt_quoted(opts));
56dc3ab0 2629 } else if (exit_code)
02127c63 2630 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
56dc3ab0
JS
2631 short_commit_name(commit), subject_len, subject);
2632
2633 return exit_code;
2634}
2635
6e98de72
JS
2636static int error_failed_squash(struct commit *commit,
2637 struct replay_opts *opts, int subject_len, const char *subject)
2638{
e12a7ef5
JS
2639 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2640 return error(_("could not copy '%s' to '%s'"),
6e98de72 2641 rebase_path_squash_msg(), rebase_path_message());
102de880
SB
2642 unlink(git_path_merge_msg(the_repository));
2643 if (copy_file(git_path_merge_msg(the_repository), rebase_path_message(), 0666))
6e98de72 2644 return error(_("could not copy '%s' to '%s'"),
102de880
SB
2645 rebase_path_message(),
2646 git_path_merge_msg(the_repository));
6e98de72
JS
2647 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2648}
2649
311af526
JS
2650static int do_exec(const char *command_line)
2651{
09d7b6c6 2652 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
2653 const char *child_argv[] = { NULL, NULL };
2654 int dirty, status;
2655
2656 fprintf(stderr, "Executing: %s\n", command_line);
2657 child_argv[0] = command_line;
09d7b6c6 2658 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 2659 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2660 absolute_path(get_git_work_tree()));
09d7b6c6
JK
2661 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2662 child_env.argv);
311af526
JS
2663
2664 /* force re-reading of the cache */
2665 if (discard_cache() < 0 || read_cache() < 0)
2666 return error(_("could not read index"));
2667
2668 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2669
2670 if (status) {
2671 warning(_("execution failed: %s\n%s"
2672 "You can fix the problem, and then run\n"
2673 "\n"
2674 " git rebase --continue\n"
2675 "\n"),
2676 command_line,
2677 dirty ? N_("and made changes to the index and/or the "
2678 "working tree\n") : "");
2679 if (status == 127)
2680 /* command not found */
2681 status = 1;
2682 } else if (dirty) {
2683 warning(_("execution succeeded: %s\nbut "
2684 "left changes to the index and/or the working tree\n"
2685 "Commit or stash your changes, and then run\n"
2686 "\n"
2687 " git rebase --continue\n"
2688 "\n"), command_line);
2689 status = 1;
2690 }
2691
09d7b6c6
JK
2692 argv_array_clear(&child_env);
2693
311af526
JS
2694 return status;
2695}
2696
9055e401
JS
2697static int safe_append(const char *filename, const char *fmt, ...)
2698{
2699 va_list ap;
2700 struct lock_file lock = LOCK_INIT;
2701 int fd = hold_lock_file_for_update(&lock, filename,
2702 LOCK_REPORT_ON_ERROR);
2703 struct strbuf buf = STRBUF_INIT;
2704
2705 if (fd < 0)
2706 return -1;
2707
2708 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2709 error_errno(_("could not read '%s'"), filename);
2710 rollback_lock_file(&lock);
2711 return -1;
2712 }
2713 strbuf_complete(&buf, '\n');
2714 va_start(ap, fmt);
2715 strbuf_vaddf(&buf, fmt, ap);
2716 va_end(ap);
2717
2718 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2719 error_errno(_("could not write to '%s'"), filename);
2720 strbuf_release(&buf);
2721 rollback_lock_file(&lock);
2722 return -1;
2723 }
2724 if (commit_lock_file(&lock) < 0) {
2725 strbuf_release(&buf);
2726 rollback_lock_file(&lock);
2727 return error(_("failed to finalize '%s'"), filename);
2728 }
2729
2730 strbuf_release(&buf);
2731 return 0;
2732}
2733
2734static int do_label(const char *name, int len)
2735{
2c18e6ae 2736 struct ref_store *refs = get_main_ref_store(the_repository);
9055e401
JS
2737 struct ref_transaction *transaction;
2738 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2739 struct strbuf msg = STRBUF_INIT;
2740 int ret = 0;
2741 struct object_id head_oid;
2742
2743 if (len == 1 && *name == '#')
02127c63 2744 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
2745
2746 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2747 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2748
2749 transaction = ref_store_transaction_begin(refs, &err);
2750 if (!transaction) {
2751 error("%s", err.buf);
2752 ret = -1;
2753 } else if (get_oid("HEAD", &head_oid)) {
2754 error(_("could not read HEAD"));
2755 ret = -1;
2756 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2757 NULL, 0, msg.buf, &err) < 0 ||
2758 ref_transaction_commit(transaction, &err)) {
2759 error("%s", err.buf);
2760 ret = -1;
2761 }
2762 ref_transaction_free(transaction);
2763 strbuf_release(&err);
2764 strbuf_release(&msg);
2765
2766 if (!ret)
2767 ret = safe_append(rebase_path_refs_to_delete(),
2768 "%s\n", ref_name.buf);
2769 strbuf_release(&ref_name);
2770
2771 return ret;
2772}
2773
2774static const char *reflog_message(struct replay_opts *opts,
2775 const char *sub_action, const char *fmt, ...);
2776
2777static int do_reset(const char *name, int len, struct replay_opts *opts)
2778{
2779 struct strbuf ref_name = STRBUF_INIT;
2780 struct object_id oid;
2781 struct lock_file lock = LOCK_INIT;
2782 struct tree_desc desc;
2783 struct tree *tree;
2784 struct unpack_trees_options unpack_tree_opts;
2785 int ret = 0, i;
2786
2787 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2788 return -1;
2789
ebddf393
JS
2790 if (len == 10 && !strncmp("[new root]", name, len)) {
2791 if (!opts->have_squash_onto) {
2792 const char *hex;
2793 if (commit_tree("", 0, the_hash_algo->empty_tree,
2794 NULL, &opts->squash_onto,
2795 NULL, NULL))
2796 return error(_("writing fake root commit"));
2797 opts->have_squash_onto = 1;
2798 hex = oid_to_hex(&opts->squash_onto);
2799 if (write_message(hex, strlen(hex),
2800 rebase_path_squash_onto(), 0))
2801 return error(_("writing squash-onto"));
2802 }
2803 oidcpy(&oid, &opts->squash_onto);
2804 } else {
2805 /* Determine the length of the label */
2806 for (i = 0; i < len; i++)
2807 if (isspace(name[i]))
2808 len = i;
2809
2810 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2811 if (get_oid(ref_name.buf, &oid) &&
2812 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2813 error(_("could not read '%s'"), ref_name.buf);
2814 rollback_lock_file(&lock);
2815 strbuf_release(&ref_name);
2816 return -1;
2817 }
9055e401
JS
2818 }
2819
2820 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2821 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2822 unpack_tree_opts.head_idx = 1;
2823 unpack_tree_opts.src_index = &the_index;
2824 unpack_tree_opts.dst_index = &the_index;
2825 unpack_tree_opts.fn = oneway_merge;
2826 unpack_tree_opts.merge = 1;
2827 unpack_tree_opts.update = 1;
2828
2829 if (read_cache_unmerged()) {
2830 rollback_lock_file(&lock);
2831 strbuf_release(&ref_name);
2832 return error_resolve_conflict(_(action_name(opts)));
2833 }
2834
2835 if (!fill_tree_descriptor(&desc, &oid)) {
2836 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2837 rollback_lock_file(&lock);
2838 free((void *)desc.buffer);
2839 strbuf_release(&ref_name);
2840 return -1;
2841 }
2842
2843 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
2844 rollback_lock_file(&lock);
2845 free((void *)desc.buffer);
2846 strbuf_release(&ref_name);
2847 return -1;
2848 }
2849
2850 tree = parse_tree_indirect(&oid);
2851 prime_cache_tree(&the_index, tree);
2852
2853 if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
2854 ret = error(_("could not write index"));
2855 free((void *)desc.buffer);
2856
2857 if (!ret)
2858 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
2859 len, name), "HEAD", &oid,
2860 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
2861
2862 strbuf_release(&ref_name);
2863 return ret;
2864}
2865
2b6ad0f4
JS
2866static struct commit *lookup_label(const char *label, int len,
2867 struct strbuf *buf)
2868{
2869 struct commit *commit;
2870
2871 strbuf_reset(buf);
2872 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
2873 commit = lookup_commit_reference_by_name(buf->buf);
2874 if (!commit) {
2875 /* fall back to non-rewritten ref or commit */
2876 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
2877 commit = lookup_commit_reference_by_name(buf->buf);
2878 }
2879
2880 if (!commit)
2881 error(_("could not resolve '%s'"), buf->buf);
2882
2883 return commit;
2884}
2885
4c68e7dd
JS
2886static int do_merge(struct commit *commit, const char *arg, int arg_len,
2887 int flags, struct replay_opts *opts)
2888{
2889 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
2890 EDIT_MSG | VERIFY_MSG : 0;
2891 struct strbuf ref_name = STRBUF_INIT;
2892 struct commit *head_commit, *merge_commit, *i;
2893 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 2894 struct commit_list *to_merge = NULL, **tail = &to_merge;
4c68e7dd 2895 struct merge_options o;
2b6ad0f4 2896 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
2897 static struct lock_file lock;
2898 const char *p;
2899
2900 if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
2901 ret = -1;
2902 goto leave_merge;
2903 }
2904
2905 head_commit = lookup_commit_reference_by_name("HEAD");
2906 if (!head_commit) {
2907 ret = error(_("cannot merge without a current revision"));
2908 goto leave_merge;
2909 }
2910
2b6ad0f4
JS
2911 /*
2912 * For octopus merges, the arg starts with the list of revisions to be
2913 * merged. The list is optionally followed by '#' and the oneline.
2914 */
2915 merge_arg_len = oneline_offset = arg_len;
2916 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
2917 if (!*p)
2918 break;
2919 if (*p == '#' && (!p[1] || isspace(p[1]))) {
2920 p += 1 + strspn(p + 1, " \t\n");
2921 oneline_offset = p - arg;
2922 break;
2923 }
2924 k = strcspn(p, " \t\n");
2925 if (!k)
2926 continue;
2927 merge_commit = lookup_label(p, k, &ref_name);
2928 if (!merge_commit) {
2929 ret = error(_("unable to parse '%.*s'"), k, p);
2930 goto leave_merge;
2931 }
2932 tail = &commit_list_insert(merge_commit, tail)->next;
2933 p += k;
2934 merge_arg_len = p - arg;
4c68e7dd
JS
2935 }
2936
2b6ad0f4
JS
2937 if (!to_merge) {
2938 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
2939 goto leave_merge;
2940 }
2941
9c85a1c2
JS
2942 if (opts->have_squash_onto &&
2943 !oidcmp(&head_commit->object.oid, &opts->squash_onto)) {
2944 /*
2945 * When the user tells us to "merge" something into a
2946 * "[new root]", let's simply fast-forward to the merge head.
2947 */
2948 rollback_lock_file(&lock);
2b6ad0f4
JS
2949 if (to_merge->next)
2950 ret = error(_("octopus merge cannot be executed on "
2951 "top of a [new root]"));
2952 else
2953 ret = fast_forward_to(&to_merge->item->object.oid,
2954 &head_commit->object.oid, 0,
2955 opts);
9c85a1c2
JS
2956 goto leave_merge;
2957 }
2958
4c68e7dd
JS
2959 if (commit) {
2960 const char *message = get_commit_buffer(commit, NULL);
2961 const char *body;
2962 int len;
2963
2964 if (!message) {
2965 ret = error(_("could not get commit message of '%s'"),
2966 oid_to_hex(&commit->object.oid));
2967 goto leave_merge;
2968 }
2969 write_author_script(message);
2970 find_commit_subject(message, &body);
2971 len = strlen(body);
00624d60 2972 ret = write_message(body, len, git_path_merge_msg(the_repository), 0);
4c68e7dd
JS
2973 unuse_commit_buffer(commit, message);
2974 if (ret) {
2975 error_errno(_("could not write '%s'"),
00624d60 2976 git_path_merge_msg(the_repository));
4c68e7dd
JS
2977 goto leave_merge;
2978 }
2979 } else {
2980 struct strbuf buf = STRBUF_INIT;
2981 int len;
2982
2983 strbuf_addf(&buf, "author %s", git_author_info(0));
2984 write_author_script(buf.buf);
2985 strbuf_reset(&buf);
2986
2987 if (oneline_offset < arg_len) {
2988 p = arg + oneline_offset;
2989 len = arg_len - oneline_offset;
2990 } else {
2b6ad0f4
JS
2991 strbuf_addf(&buf, "Merge %s '%.*s'",
2992 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
2993 merge_arg_len, arg);
2994 p = buf.buf;
2995 len = buf.len;
2996 }
2997
00624d60 2998 ret = write_message(p, len, git_path_merge_msg(the_repository), 0);
4c68e7dd
JS
2999 strbuf_release(&buf);
3000 if (ret) {
3001 error_errno(_("could not write '%s'"),
00624d60 3002 git_path_merge_msg(the_repository));
4c68e7dd
JS
3003 goto leave_merge;
3004 }
3005 }
3006
d1e8b011
JS
3007 /*
3008 * If HEAD is not identical to the first parent of the original merge
3009 * commit, we cannot fast-forward.
3010 */
3011 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3012 !oidcmp(&commit->parents->item->object.oid,
3013 &head_commit->object.oid);
3014
3015 /*
2b6ad0f4 3016 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3017 * fast-forward.
3018 */
3019 if (can_fast_forward) {
2b6ad0f4 3020 struct commit_list *p = commit->parents->next;
d1e8b011 3021
2b6ad0f4
JS
3022 for (j = to_merge; j && p; j = j->next, p = p->next)
3023 if (oidcmp(&j->item->object.oid,
3024 &p->item->object.oid)) {
3025 can_fast_forward = 0;
3026 break;
3027 }
3028 /*
3029 * If the number of merge heads differs from the original merge
3030 * commit, we cannot fast-forward.
3031 */
3032 if (j || p)
d1e8b011
JS
3033 can_fast_forward = 0;
3034 }
3035
2b6ad0f4 3036 if (can_fast_forward) {
d1e8b011
JS
3037 rollback_lock_file(&lock);
3038 ret = fast_forward_to(&commit->object.oid,
3039 &head_commit->object.oid, 0, opts);
3040 goto leave_merge;
3041 }
3042
2b6ad0f4
JS
3043 if (to_merge->next) {
3044 /* Octopus merge */
3045 struct child_process cmd = CHILD_PROCESS_INIT;
3046
3047 if (read_env_script(&cmd.env_array)) {
3048 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3049
3050 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3051 goto leave_merge;
3052 }
3053
3054 cmd.git_cmd = 1;
3055 argv_array_push(&cmd.args, "merge");
3056 argv_array_push(&cmd.args, "-s");
3057 argv_array_push(&cmd.args, "octopus");
3058 argv_array_push(&cmd.args, "--no-edit");
3059 argv_array_push(&cmd.args, "--no-ff");
3060 argv_array_push(&cmd.args, "--no-log");
3061 argv_array_push(&cmd.args, "--no-stat");
3062 argv_array_push(&cmd.args, "-F");
2b9afea3 3063 argv_array_push(&cmd.args, git_path_merge_msg(the_repository));
2b6ad0f4
JS
3064 if (opts->gpg_sign)
3065 argv_array_push(&cmd.args, opts->gpg_sign);
3066
3067 /* Add the tips to be merged */
3068 for (j = to_merge; j; j = j->next)
3069 argv_array_push(&cmd.args,
3070 oid_to_hex(&j->item->object.oid));
3071
3072 strbuf_release(&ref_name);
2b9afea3 3073 unlink(git_path_cherry_pick_head(the_repository));
2b6ad0f4
JS
3074 rollback_lock_file(&lock);
3075
3076 rollback_lock_file(&lock);
3077 ret = run_command(&cmd);
3078
3079 /* force re-reading of the cache */
3080 if (!ret && (discard_cache() < 0 || read_cache() < 0))
3081 ret = error(_("could not read index"));
3082 goto leave_merge;
3083 }
3084
3085 merge_commit = to_merge->item;
4c68e7dd 3086 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
00624d60
JH
3087 git_path_merge_head(the_repository), 0);
3088 write_message("no-ff", 5, git_path_merge_mode(the_repository), 0);
4c68e7dd
JS
3089
3090 bases = get_merge_bases(head_commit, merge_commit);
7ccdf65b
JS
3091 if (bases && !oidcmp(&merge_commit->object.oid,
3092 &bases->item->object.oid)) {
3093 ret = 0;
3094 /* skip merging an ancestor of HEAD */
3095 goto leave_merge;
3096 }
3097
4c68e7dd
JS
3098 for (j = bases; j; j = j->next)
3099 commit_list_insert(j->item, &reversed);
3100 free_commit_list(bases);
3101
3102 read_cache();
3103 init_merge_options(&o);
3104 o.branch1 = "HEAD";
3105 o.branch2 = ref_name.buf;
3106 o.buffer_output = 2;
3107
3108 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3109 if (ret <= 0)
3110 fputs(o.obuf.buf, stdout);
3111 strbuf_release(&o.obuf);
3112 if (ret < 0) {
3113 error(_("could not even attempt to merge '%.*s'"),
3114 merge_arg_len, arg);
3115 goto leave_merge;
3116 }
3117 /*
3118 * The return value of merge_recursive() is 1 on clean, and 0 on
3119 * unclean merge.
3120 *
3121 * Let's reverse that, so that do_merge() returns 0 upon success and
3122 * 1 upon failed merge (keeping the return value -1 for the cases where
3123 * we will want to reschedule the `merge` command).
3124 */
3125 ret = !ret;
3126
3127 if (active_cache_changed &&
3128 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3129 ret = error(_("merge: Unable to write new index file"));
3130 goto leave_merge;
3131 }
3132
3133 rollback_lock_file(&lock);
3134 if (ret)
3135 rerere(opts->allow_rerere_auto);
3136 else
3137 /*
3138 * In case of problems, we now want to return a positive
3139 * value (a negative one would indicate that the `merge`
3140 * command needs to be rescheduled).
3141 */
00624d60 3142 ret = !!run_git_commit(git_path_merge_msg(the_repository), opts,
4c68e7dd
JS
3143 run_commit_flags);
3144
3145leave_merge:
3146 strbuf_release(&ref_name);
3147 rollback_lock_file(&lock);
2b6ad0f4 3148 free_commit_list(to_merge);
4c68e7dd
JS
3149 return ret;
3150}
3151
6e98de72
JS
3152static int is_final_fixup(struct todo_list *todo_list)
3153{
3154 int i = todo_list->current;
3155
3156 if (!is_fixup(todo_list->items[i].command))
3157 return 0;
3158
3159 while (++i < todo_list->nr)
3160 if (is_fixup(todo_list->items[i].command))
3161 return 0;
3162 else if (!is_noop(todo_list->items[i].command))
3163 break;
3164 return 1;
3165}
3166
25cb8df9
JS
3167static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3168{
3169 int i;
3170
3171 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3172 if (!is_noop(todo_list->items[i].command))
3173 return todo_list->items[i].command;
3174
3175 return -1;
3176}
3177
796c7972
JS
3178static int apply_autostash(struct replay_opts *opts)
3179{
3180 struct strbuf stash_sha1 = STRBUF_INIT;
3181 struct child_process child = CHILD_PROCESS_INIT;
3182 int ret = 0;
3183
3184 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3185 strbuf_release(&stash_sha1);
3186 return 0;
3187 }
3188 strbuf_trim(&stash_sha1);
3189
3190 child.git_cmd = 1;
79a62269
PW
3191 child.no_stdout = 1;
3192 child.no_stderr = 1;
796c7972
JS
3193 argv_array_push(&child.args, "stash");
3194 argv_array_push(&child.args, "apply");
3195 argv_array_push(&child.args, stash_sha1.buf);
3196 if (!run_command(&child))
cdb866b3 3197 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3198 else {
3199 struct child_process store = CHILD_PROCESS_INIT;
3200
3201 store.git_cmd = 1;
3202 argv_array_push(&store.args, "stash");
3203 argv_array_push(&store.args, "store");
3204 argv_array_push(&store.args, "-m");
3205 argv_array_push(&store.args, "autostash");
3206 argv_array_push(&store.args, "-q");
3207 argv_array_push(&store.args, stash_sha1.buf);
3208 if (run_command(&store))
3209 ret = error(_("cannot store %s"), stash_sha1.buf);
3210 else
cdb866b3
JS
3211 fprintf(stderr,
3212 _("Applying autostash resulted in conflicts.\n"
3213 "Your changes are safe in the stash.\n"
3214 "You can run \"git stash pop\" or"
3215 " \"git stash drop\" at any time.\n"));
796c7972
JS
3216 }
3217
3218 strbuf_release(&stash_sha1);
3219 return ret;
3220}
3221
96e832a5
JS
3222static const char *reflog_message(struct replay_opts *opts,
3223 const char *sub_action, const char *fmt, ...)
3224{
3225 va_list ap;
3226 static struct strbuf buf = STRBUF_INIT;
3227
3228 va_start(ap, fmt);
3229 strbuf_reset(&buf);
3230 strbuf_addstr(&buf, action_name(opts));
3231 if (sub_action)
3232 strbuf_addf(&buf, " (%s)", sub_action);
3233 if (fmt) {
3234 strbuf_addstr(&buf, ": ");
3235 strbuf_vaddf(&buf, fmt, ap);
3236 }
3237 va_end(ap);
3238
3239 return buf.buf;
3240}
3241
cb5206ea
JS
3242static const char rescheduled_advice[] =
3243N_("Could not execute the todo command\n"
3244"\n"
3245" %.*s"
3246"\n"
3247"It has been rescheduled; To edit the command before continuing, please\n"
3248"edit the todo list first:\n"
3249"\n"
3250" git rebase --edit-todo\n"
3251" git rebase --continue\n");
3252
004fefa7 3253static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 3254{
9055e401 3255 int res = 0, reschedule = 0;
043a4492
RR
3256
3257 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3258 if (opts->allow_ff)
3259 assert(!(opts->signoff || opts->no_commit ||
3260 opts->record_origin || opts->edit));
0d9c6dc9
JS
3261 if (read_and_refresh_cache(opts))
3262 return -1;
043a4492 3263
004fefa7
JS
3264 while (todo_list->current < todo_list->nr) {
3265 struct todo_item *item = todo_list->items + todo_list->current;
3266 if (save_todo(todo_list, opts))
221675de 3267 return -1;
6e98de72 3268 if (is_rebase_i(opts)) {
ef80069a
JS
3269 if (item->command != TODO_COMMENT) {
3270 FILE *f = fopen(rebase_path_msgnum(), "w");
3271
3272 todo_list->done_nr++;
3273
3274 if (f) {
3275 fprintf(f, "%d\n", todo_list->done_nr);
3276 fclose(f);
3277 }
968492e4 3278 fprintf(stderr, "Rebasing (%d/%d)%s",
ef80069a 3279 todo_list->done_nr,
968492e4
JS
3280 todo_list->total_nr,
3281 opts->verbose ? "\n" : "\r");
ef80069a 3282 }
6e98de72
JS
3283 unlink(rebase_path_message());
3284 unlink(rebase_path_author_script());
3285 unlink(rebase_path_stopped_sha());
3286 unlink(rebase_path_amend());
fbd7a232 3287 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
6e98de72
JS
3288 }
3289 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3290 if (is_rebase_i(opts))
3291 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3292 command_to_string(item->command), NULL),
3293 1);
25c43667 3294 res = do_pick_commit(item->command, item->commit,
6e98de72 3295 opts, is_final_fixup(todo_list));
9d7bf3cf
JS
3296 if (is_rebase_i(opts) && res < 0) {
3297 /* Reschedule */
cb5206ea
JS
3298 advise(_(rescheduled_advice),
3299 get_item_line_length(todo_list,
3300 todo_list->current),
3301 get_item_line(todo_list,
3302 todo_list->current));
9d7bf3cf
JS
3303 todo_list->current--;
3304 if (save_todo(todo_list, opts))
3305 return -1;
3306 }
56dc3ab0
JS
3307 if (item->command == TODO_EDIT) {
3308 struct commit *commit = item->commit;
3309 if (!res)
99429213 3310 fprintf(stderr,
a42e1b41 3311 _("Stopped at %s... %.*s\n"),
56dc3ab0
JS
3312 short_commit_name(commit),
3313 item->arg_len, item->arg);
3314 return error_with_patch(commit,
3315 item->arg, item->arg_len, opts, res,
3316 !res);
3317 }
25cb8df9
JS
3318 if (is_rebase_i(opts) && !res)
3319 record_in_rewritten(&item->commit->object.oid,
3320 peek_command(todo_list, 1));
6e98de72
JS
3321 if (res && is_fixup(item->command)) {
3322 if (res == 1)
3323 intend_to_amend();
3324 return error_failed_squash(item->commit, opts,
3325 item->arg_len, item->arg);
a9279c67
PW
3326 } else if (res && is_rebase_i(opts) && item->commit) {
3327 int to_amend = 0;
3328 struct object_id oid;
3329
3330 /*
3331 * If we are rewording and have either
3332 * fast-forwarded already, or are about to
3333 * create a new root commit, we want to amend,
3334 * otherwise we do not.
3335 */
3336 if (item->command == TODO_REWORD &&
3337 !get_oid("HEAD", &oid) &&
3338 (!oidcmp(&item->commit->object.oid, &oid) ||
3339 (opts->have_squash_onto &&
3340 !oidcmp(&opts->squash_onto, &oid))))
3341 to_amend = 1;
3342
4a5146f9 3343 return res | error_with_patch(item->commit,
a9279c67
PW
3344 item->arg, item->arg_len, opts,
3345 res, to_amend);
3346 }
311af526
JS
3347 } else if (item->command == TODO_EXEC) {
3348 char *end_of_arg = (char *)(item->arg + item->arg_len);
3349 int saved = *end_of_arg;
54fd3243 3350 struct stat st;
311af526
JS
3351
3352 *end_of_arg = '\0';
3353 res = do_exec(item->arg);
3354 *end_of_arg = saved;
54fd3243
SH
3355
3356 /* Reread the todo file if it has changed. */
3357 if (res)
3358 ; /* fall through */
3359 else if (stat(get_todo_path(opts), &st))
3360 res = error_errno(_("could not stat '%s'"),
3361 get_todo_path(opts));
3362 else if (match_stat_data(&todo_list->stat, &st)) {
3363 todo_list_release(todo_list);
3364 if (read_populate_todo(todo_list, opts))
3365 res = -1; /* message was printed */
3366 /* `current` will be incremented below */
3367 todo_list->current = -1;
3368 }
9055e401
JS
3369 } else if (item->command == TODO_LABEL) {
3370 if ((res = do_label(item->arg, item->arg_len)))
3371 reschedule = 1;
3372 } else if (item->command == TODO_RESET) {
3373 if ((res = do_reset(item->arg, item->arg_len, opts)))
3374 reschedule = 1;
4c68e7dd
JS
3375 } else if (item->command == TODO_MERGE) {
3376 if ((res = do_merge(item->commit,
3377 item->arg, item->arg_len,
3378 item->flags, opts)) < 0)
3379 reschedule = 1;
537e7d61
JS
3380 else if (item->commit)
3381 record_in_rewritten(&item->commit->object.oid,
3382 peek_command(todo_list, 1));
3383 if (res > 0)
4c68e7dd
JS
3384 /* failed with merge conflicts */
3385 return error_with_patch(item->commit,
3386 item->arg,
3387 item->arg_len, opts,
3388 res, 0);
56dc3ab0 3389 } else if (!is_noop(item->command))
25c43667
JS
3390 return error(_("unknown command %d"), item->command);
3391
9055e401
JS
3392 if (reschedule) {
3393 advise(_(rescheduled_advice),
3394 get_item_line_length(todo_list,
3395 todo_list->current),
3396 get_item_line(todo_list, todo_list->current));
3397 todo_list->current--;
3398 if (save_todo(todo_list, opts))
3399 return -1;
4c68e7dd
JS
3400 if (item->commit)
3401 return error_with_patch(item->commit,
3402 item->arg,
3403 item->arg_len, opts,
3404 res, 0);
9055e401
JS
3405 }
3406
004fefa7 3407 todo_list->current++;
043a4492
RR
3408 if (res)
3409 return res;
3410 }
3411
56dc3ab0 3412 if (is_rebase_i(opts)) {
4b83ce9f 3413 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3414 struct stat st;
556907f1 3415
56dc3ab0
JS
3416 /* Stopped in the middle, as planned? */
3417 if (todo_list->current < todo_list->nr)
3418 return 0;
556907f1 3419
4b83ce9f
JS
3420 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3421 starts_with(head_ref.buf, "refs/")) {
96e832a5 3422 const char *msg;
092bbcdf 3423 struct object_id head, orig;
4b83ce9f
JS
3424 int res;
3425
092bbcdf 3426 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
3427 res = error(_("cannot read HEAD"));
3428cleanup_head_ref:
3429 strbuf_release(&head_ref);
3430 strbuf_release(&buf);
3431 return res;
3432 }
3433 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 3434 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
3435 res = error(_("could not read orig-head"));
3436 goto cleanup_head_ref;
3437 }
4ab867b8 3438 strbuf_reset(&buf);
4b83ce9f
JS
3439 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3440 res = error(_("could not read 'onto'"));
3441 goto cleanup_head_ref;
3442 }
96e832a5
JS
3443 msg = reflog_message(opts, "finish", "%s onto %s",
3444 head_ref.buf, buf.buf);
ae077771 3445 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 3446 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
3447 res = error(_("could not update %s"),
3448 head_ref.buf);
3449 goto cleanup_head_ref;
3450 }
96e832a5 3451 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 3452 head_ref.buf);
96e832a5 3453 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
3454 res = error(_("could not update HEAD to %s"),
3455 head_ref.buf);
3456 goto cleanup_head_ref;
3457 }
3458 strbuf_reset(&buf);
3459 }
3460
556907f1
JS
3461 if (opts->verbose) {
3462 struct rev_info log_tree_opt;
3463 struct object_id orig, head;
3464
3465 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3466 init_revisions(&log_tree_opt, NULL);
3467 log_tree_opt.diff = 1;
3468 log_tree_opt.diffopt.output_format =
3469 DIFF_FORMAT_DIFFSTAT;
3470 log_tree_opt.disable_stdin = 1;
3471
3472 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 3473 !get_oid(buf.buf, &orig) &&
3474 !get_oid("HEAD", &head)) {
66f414f8
BW
3475 diff_tree_oid(&orig, &head, "",
3476 &log_tree_opt.diffopt);
556907f1
JS
3477 log_tree_diff_flush(&log_tree_opt);
3478 }
3479 }
25cb8df9
JS
3480 flush_rewritten_pending();
3481 if (!stat(rebase_path_rewritten_list(), &st) &&
3482 st.st_size > 0) {
3483 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
3484 const char *post_rewrite_hook =
3485 find_hook("post-rewrite");
25cb8df9
JS
3486
3487 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3488 child.git_cmd = 1;
3489 argv_array_push(&child.args, "notes");
3490 argv_array_push(&child.args, "copy");
3491 argv_array_push(&child.args, "--for-rewrite=rebase");
3492 /* we don't care if this copying failed */
3493 run_command(&child);
79516045
JS
3494
3495 if (post_rewrite_hook) {
3496 struct child_process hook = CHILD_PROCESS_INIT;
3497
3498 hook.in = open(rebase_path_rewritten_list(),
3499 O_RDONLY);
3500 hook.stdout_to_stderr = 1;
3501 argv_array_push(&hook.args, post_rewrite_hook);
3502 argv_array_push(&hook.args, "rebase");
3503 /* we don't care if this hook failed */
3504 run_command(&hook);
3505 }
25cb8df9 3506 }
796c7972 3507 apply_autostash(opts);
25cb8df9 3508
5da4966f
JS
3509 fprintf(stderr, "Successfully rebased and updated %s.\n",
3510 head_ref.buf);
3511
556907f1 3512 strbuf_release(&buf);
4b83ce9f 3513 strbuf_release(&head_ref);
56dc3ab0
JS
3514 }
3515
043a4492
RR
3516 /*
3517 * Sequence of picks finished successfully; cleanup by
3518 * removing the .git/sequencer directory
3519 */
2863584f 3520 return sequencer_remove_state(opts);
043a4492
RR
3521}
3522
3523static int continue_single_pick(void)
3524{
3525 const char *argv[] = { "commit", NULL };
3526
102de880
SB
3527 if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
3528 !file_exists(git_path_revert_head(the_repository)))
043a4492
RR
3529 return error(_("no cherry-pick or revert in progress"));
3530 return run_command_v_opt(argv, RUN_GIT_CMD);
3531}
3532
15ef6931
JS
3533static int commit_staged_changes(struct replay_opts *opts,
3534 struct todo_list *todo_list)
9d93ccd1 3535{
789b3eff 3536 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 3537 unsigned int final_fixup = 0, is_clean;
9d93ccd1
JS
3538
3539 if (has_unstaged_changes(1))
3540 return error(_("cannot rebase: You have unstaged changes."));
52632209 3541
15ef6931 3542 is_clean = !has_uncommitted_changes(0);
9d93ccd1
JS
3543
3544 if (file_exists(rebase_path_amend())) {
3545 struct strbuf rev = STRBUF_INIT;
092bbcdf 3546 struct object_id head, to_amend;
9d93ccd1 3547
092bbcdf 3548 if (get_oid("HEAD", &head))
9d93ccd1
JS
3549 return error(_("cannot amend non-existing commit"));
3550 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3551 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 3552 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
3553 return error(_("invalid contents: '%s'"),
3554 rebase_path_amend());
15ef6931 3555 if (!is_clean && oidcmp(&head, &to_amend))
9d93ccd1
JS
3556 return error(_("\nYou have uncommitted changes in your "
3557 "working tree. Please, commit them\n"
3558 "first and then run 'git rebase "
3559 "--continue' again."));
15ef6931
JS
3560 /*
3561 * When skipping a failed fixup/squash, we need to edit the
3562 * commit message, the current fixup list and count, and if it
3563 * was the last fixup/squash in the chain, we need to clean up
3564 * the commit message and if there was a squash, let the user
3565 * edit it.
3566 */
3567 if (is_clean && !oidcmp(&head, &to_amend) &&
3568 opts->current_fixup_count > 0 &&
3569 file_exists(rebase_path_stopped_sha())) {
3570 const char *p = opts->current_fixups.buf;
3571 int len = opts->current_fixups.len;
3572
3573 opts->current_fixup_count--;
3574 if (!len)
3575 BUG("Incorrect current_fixups:\n%s", p);
3576 while (len && p[len - 1] != '\n')
3577 len--;
3578 strbuf_setlen(&opts->current_fixups, len);
3579 if (write_message(p, len, rebase_path_current_fixups(),
3580 0) < 0)
3581 return error(_("could not write file: '%s'"),
3582 rebase_path_current_fixups());
3583
3584 /*
3585 * If a fixup/squash in a fixup/squash chain failed, the
3586 * commit message is already correct, no need to commit
3587 * it again.
3588 *
3589 * Only if it is the final command in the fixup/squash
3590 * chain, and only if the chain is longer than a single
3591 * fixup/squash command (which was just skipped), do we
3592 * actually need to re-commit with a cleaned up commit
3593 * message.
3594 */
3595 if (opts->current_fixup_count > 0 &&
3596 !is_fixup(peek_command(todo_list, 0))) {
3597 final_fixup = 1;
3598 /*
3599 * If there was not a single "squash" in the
3600 * chain, we only need to clean up the commit
3601 * message, no need to bother the user with
3602 * opening the commit message in the editor.
3603 */
3604 if (!starts_with(p, "squash ") &&
3605 !strstr(p, "\nsquash "))
3606 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3607 } else if (is_fixup(peek_command(todo_list, 0))) {
3608 /*
3609 * We need to update the squash message to skip
3610 * the latest commit message.
3611 */
3612 struct commit *commit;
3613 const char *path = rebase_path_squash_msg();
3614
3615 if (parse_head(&commit) ||
3616 !(p = get_commit_buffer(commit, NULL)) ||
3617 write_message(p, strlen(p), path, 0)) {
3618 unuse_commit_buffer(commit, p);
3619 return error(_("could not write file: "
3620 "'%s'"), path);
3621 }
3622 unuse_commit_buffer(commit, p);
3623 }
3624 }
9d93ccd1
JS
3625
3626 strbuf_release(&rev);
789b3eff 3627 flags |= AMEND_MSG;
9d93ccd1
JS
3628 }
3629
15ef6931 3630 if (is_clean) {
00624d60 3631 const char *cherry_pick_head = git_path_cherry_pick_head(the_repository);
15ef6931
JS
3632
3633 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3634 return error(_("could not remove CHERRY_PICK_HEAD"));
3635 if (!final_fixup)
3636 return 0;
3637 }
3638
3639 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3640 opts, flags))
9d93ccd1
JS
3641 return error(_("could not commit staged changes."));
3642 unlink(rebase_path_amend());
15ef6931
JS
3643 if (final_fixup) {
3644 unlink(rebase_path_fixup_msg());
3645 unlink(rebase_path_squash_msg());
3646 }
3647 if (opts->current_fixup_count > 0) {
3648 /*
3649 * Whether final fixup or not, we just cleaned up the commit
3650 * message...
3651 */
3652 unlink(rebase_path_current_fixups());
3653 strbuf_reset(&opts->current_fixups);
3654 opts->current_fixup_count = 0;
3655 }
9d93ccd1
JS
3656 return 0;
3657}
3658
2863584f 3659int sequencer_continue(struct replay_opts *opts)
043a4492 3660{
004fefa7
JS
3661 struct todo_list todo_list = TODO_LIST_INIT;
3662 int res;
043a4492 3663
2863584f
JS
3664 if (read_and_refresh_cache(opts))
3665 return -1;
3666
15ef6931
JS
3667 if (read_populate_opts(opts))
3668 return -1;
9d93ccd1 3669 if (is_rebase_i(opts)) {
15ef6931
JS
3670 if ((res = read_populate_todo(&todo_list, opts)))
3671 goto release_todo_list;
3672 if (commit_staged_changes(opts, &todo_list))
9d93ccd1 3673 return -1;
4258a6da 3674 } else if (!file_exists(get_todo_path(opts)))
043a4492 3675 return continue_single_pick();