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