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