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