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