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