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