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