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