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