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