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