]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
sequencer.c: save and restore cleanup mode
[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"
cbd53a21 5#include "object-store.h"
043a4492
RR
6#include "object.h"
7#include "commit.h"
0505d604 8#include "sequencer.h"
043a4492
RR
9#include "tag.h"
10#include "run-command.h"
d807c4a0 11#include "exec-cmd.h"
043a4492
RR
12#include "utf8.h"
13#include "cache-tree.h"
14#include "diff.h"
15#include "revision.h"
16#include "rerere.h"
17#include "merge-recursive.h"
18#include "refs.h"
b27cfb0d 19#include "argv-array.h"
a1c75762 20#include "quote.h"
967dfd4d 21#include "trailer.h"
56dc3ab0 22#include "log-tree.h"
311af526 23#include "wt-status.h"
c44a4c65 24#include "hashmap.h"
a87a6f3c
PW
25#include "notes-utils.h"
26#include "sigchain.h"
9055e401
JS
27#include "unpack-trees.h"
28#include "worktree.h"
1644c73c
JS
29#include "oidmap.h"
30#include "oidset.h"
8315bd20 31#include "commit-slab.h"
65b5f948 32#include "alias.h"
64043556 33#include "commit-reach.h"
b97e1873 34#include "rebase-interactive.h"
043a4492
RR
35
36#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 37
5fe81438 38static const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 39static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 40
66618a50
PW
41GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
42
8a2a0f53
JS
43GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
44
45static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
46static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
47static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 48static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 49
84583957
JS
50static GIT_PATH_FUNC(rebase_path, "rebase-merge")
51/*
52 * The file containing rebase commands, comments, and empty lines.
53 * This file is created by "git rebase -i" then edited by the user. As
54 * the lines are processed, they are removed from the front of this
55 * file and written to the tail of 'done'.
56 */
44b776c3 57GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
b97e1873
AG
58static GIT_PATH_FUNC(rebase_path_todo_backup,
59 "rebase-merge/git-rebase-todo.backup")
60
1df6df0c
JS
61/*
62 * The rebase command lines that have already been processed. A line
63 * is moved here when it is first handled, before any associated user
64 * actions.
65 */
66static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
67/*
68 * The file to keep track of how many commands were already processed (e.g.
69 * for the prompt).
70 */
9ad36356 71static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
72/*
73 * The file to keep track of how many commands are to be processed in total
74 * (e.g. for the prompt).
75 */
9ad36356 76static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
77/*
78 * The commit message that is planned to be used for any changes that
79 * need to be committed following a user interaction.
80 */
81static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
82/*
83 * The file into which is accumulated the suggested commit message for
84 * squash/fixup commands. When the first of a series of squash/fixups
85 * is seen, the file is created and the commit message from the
86 * previous commit and from the first squash/fixup commit are written
87 * to it. The commit message for each subsequent squash/fixup commit
88 * is appended to the file as it is processed.
6e98de72
JS
89 */
90static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
91/*
92 * If the current series of squash/fixups has not yet included a squash
93 * command, then this file exists and holds the commit message of the
94 * original "pick" commit. (If the series ends without a "squash"
95 * command, then this can be used as the commit message of the combined
96 * commit without opening the editor.)
97 */
98static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
99/*
100 * This file contains the list fixup/squash commands that have been
101 * accumulated into message-fixup or message-squash so far.
102 */
103static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
104/*
105 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
106 * GIT_AUTHOR_DATE that will be used for the commit that is currently
107 * being rebased.
108 */
109static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
110/*
111 * When an "edit" rebase command is being processed, the SHA1 of the
112 * commit to be edited is recorded in this file. When "git rebase
113 * --continue" is executed, if there are any staged changes then they
114 * will be amended to the HEAD commit, but only provided the HEAD
115 * commit is still the commit to be edited. When any other rebase
116 * command is processed, this file is deleted.
117 */
118static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
119/*
120 * When we stop at a given patch via the "edit" command, this file contains
121 * the abbreviated commit name of the corresponding patch.
122 */
123static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
124/*
125 * For the post-rewrite hook, we make a list of rewritten commits and
126 * their new sha1s. The rewritten-pending list keeps the sha1s of
127 * commits that have been processed, but not committed yet,
128 * e.g. because they are waiting for a 'squash' command.
129 */
130static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
131static GIT_PATH_FUNC(rebase_path_rewritten_pending,
132 "rebase-merge/rewritten-pending")
9055e401 133
d87d48b2
JS
134/*
135 * The path of the file containig the OID of the "squash onto" commit, i.e.
136 * the dummy commit used for `reset [new root]`.
137 */
138static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
139
9055e401
JS
140/*
141 * The path of the file listing refs that need to be deleted after the rebase
142 * finishes. This is used by the `label` command to record the need for cleanup.
143 */
144static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
145
a1c75762
JS
146/*
147 * The following files are written by git-rebase just after parsing the
65850686 148 * command-line.
a1c75762
JS
149 */
150static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
556907f1
JS
151static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
152static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
899b49c4 153static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
a852ec7f 154static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
155static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
156static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 157static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
158static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
159static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 160static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
d421afa0 161static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
b5a67045 162
28d6daed
PW
163static int git_sequencer_config(const char *k, const char *v, void *cb)
164{
165 struct replay_opts *opts = cb;
166 int status;
167
168 if (!strcmp(k, "commit.cleanup")) {
169 const char *s;
170
171 status = git_config_string(&s, k, v);
172 if (status)
173 return status;
174
d74f3e58 175 if (!strcmp(s, "verbatim")) {
28d6daed 176 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
177 opts->explicit_cleanup = 1;
178 } else if (!strcmp(s, "whitespace")) {
28d6daed 179 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
180 opts->explicit_cleanup = 1;
181 } else if (!strcmp(s, "strip")) {
28d6daed 182 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
d74f3e58
PW
183 opts->explicit_cleanup = 1;
184 } else if (!strcmp(s, "scissors")) {
28d6daed 185 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
186 opts->explicit_cleanup = 1;
187 } else {
28d6daed
PW
188 warning(_("invalid commit message cleanup mode '%s'"),
189 s);
d74f3e58 190 }
28d6daed 191
f40f3c16 192 free((char *)s);
28d6daed
PW
193 return status;
194 }
195
196 if (!strcmp(k, "commit.gpgsign")) {
ed1e5282 197 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
198 return 0;
199 }
200
201 status = git_gpg_config(k, v, NULL);
202 if (status)
203 return status;
204
205 return git_diff_basic_config(k, v, NULL);
206}
207
208void sequencer_init_config(struct replay_opts *opts)
209{
210 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
211 git_config(git_sequencer_config, opts);
212}
213
b5a67045
JS
214static inline int is_rebase_i(const struct replay_opts *opts)
215{
84583957 216 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
217}
218
285abf56
JS
219static const char *get_dir(const struct replay_opts *opts)
220{
84583957
JS
221 if (is_rebase_i(opts))
222 return rebase_path();
285abf56
JS
223 return git_path_seq_dir();
224}
225
c0246501
JS
226static const char *get_todo_path(const struct replay_opts *opts)
227{
84583957
JS
228 if (is_rebase_i(opts))
229 return rebase_path_todo();
c0246501
JS
230 return git_path_todo_file();
231}
232
bab4d109
BC
233/*
234 * Returns 0 for non-conforming footer
235 * Returns 1 for conforming footer
236 * Returns 2 when sob exists within conforming footer
237 * Returns 3 when sob exists within conforming footer as last entry
238 */
239static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
66e83d9b 240 size_t ignore_footer)
b971e04f 241{
00a21f5c 242 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
967dfd4d 243 struct trailer_info info;
a3b636e2 244 size_t i;
967dfd4d 245 int found_sob = 0, found_sob_last = 0;
b971e04f 246
ffce7f59
JK
247 opts.no_divider = 1;
248
00a21f5c 249 trailer_info_get(&info, sb->buf, &opts);
b971e04f 250
967dfd4d 251 if (info.trailer_start == info.trailer_end)
b971e04f
BC
252 return 0;
253
967dfd4d
JT
254 for (i = 0; i < info.trailer_nr; i++)
255 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
256 found_sob = 1;
257 if (i == info.trailer_nr - 1)
258 found_sob_last = 1;
259 }
b971e04f 260
967dfd4d 261 trailer_info_release(&info);
bab4d109 262
967dfd4d 263 if (found_sob_last)
bab4d109
BC
264 return 3;
265 if (found_sob)
266 return 2;
b971e04f
BC
267 return 1;
268}
5ed75e2a 269
a1c75762
JS
270static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
271{
272 static struct strbuf buf = STRBUF_INIT;
273
274 strbuf_reset(&buf);
275 if (opts->gpg_sign)
276 sq_quotef(&buf, "-S%s", opts->gpg_sign);
277 return buf.buf;
278}
279
2863584f 280int sequencer_remove_state(struct replay_opts *opts)
26ae337b 281{
9055e401 282 struct strbuf buf = STRBUF_INIT;
03a4e260
JS
283 int i;
284
9055e401
JS
285 if (is_rebase_i(opts) &&
286 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
287 char *p = buf.buf;
288 while (*p) {
289 char *eol = strchr(p, '\n');
290 if (eol)
291 *eol = '\0';
292 if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
293 warning(_("could not delete '%s'"), p);
294 if (!eol)
295 break;
296 p = eol + 1;
297 }
298 }
299
03a4e260
JS
300 free(opts->gpg_sign);
301 free(opts->strategy);
302 for (i = 0; i < opts->xopts_nr; i++)
303 free(opts->xopts[i]);
304 free(opts->xopts);
e12a7ef5 305 strbuf_release(&opts->current_fixups);
26ae337b 306
9055e401
JS
307 strbuf_reset(&buf);
308 strbuf_addstr(&buf, get_dir(opts));
309 remove_dir_recursively(&buf, 0);
310 strbuf_release(&buf);
2863584f
JS
311
312 return 0;
26ae337b 313}
043a4492
RR
314
315static const char *action_name(const struct replay_opts *opts)
316{
84583957
JS
317 switch (opts->action) {
318 case REPLAY_REVERT:
319 return N_("revert");
320 case REPLAY_PICK:
321 return N_("cherry-pick");
322 case REPLAY_INTERACTIVE_REBASE:
323 return N_("rebase -i");
324 }
1a07e59c 325 die(_("unknown action: %d"), opts->action);
043a4492
RR
326}
327
043a4492
RR
328struct commit_message {
329 char *parent_label;
7b35eaf8
JK
330 char *label;
331 char *subject;
043a4492
RR
332 const char *message;
333};
334
39755964
JS
335static const char *short_commit_name(struct commit *commit)
336{
aab9583f 337 return find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV);
39755964
JS
338}
339
043a4492
RR
340static int get_message(struct commit *commit, struct commit_message *out)
341{
043a4492 342 const char *abbrev, *subject;
7b35eaf8 343 int subject_len;
043a4492 344
7b35eaf8 345 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
39755964 346 abbrev = short_commit_name(commit);
043a4492
RR
347
348 subject_len = find_commit_subject(out->message, &subject);
349
7b35eaf8
JK
350 out->subject = xmemdupz(subject, subject_len);
351 out->label = xstrfmt("%s... %s", abbrev, out->subject);
352 out->parent_label = xstrfmt("parent of %s", out->label);
353
043a4492
RR
354 return 0;
355}
356
d74a4e57 357static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
358{
359 free(msg->parent_label);
7b35eaf8
JK
360 free(msg->label);
361 free(msg->subject);
b66103c3 362 unuse_commit_buffer(commit, msg->message);
043a4492
RR
363}
364
005af339
NTND
365static void print_advice(struct repository *r, int show_hint,
366 struct replay_opts *opts)
043a4492
RR
367{
368 char *msg = getenv("GIT_CHERRY_PICK_HELP");
369
370 if (msg) {
371 fprintf(stderr, "%s\n", msg);
372 /*
41ccfdd9 373 * A conflict has occurred but the porcelain
043a4492
RR
374 * (typically rebase --interactive) wants to take care
375 * of the commit itself so remove CHERRY_PICK_HEAD
376 */
005af339 377 unlink(git_path_cherry_pick_head(r));
043a4492
RR
378 return;
379 }
380
ed727b19
PH
381 if (show_hint) {
382 if (opts->no_commit)
383 advise(_("after resolving the conflicts, mark the corrected paths\n"
384 "with 'git add <paths>' or 'git rm <paths>'"));
385 else
386 advise(_("after resolving the conflicts, mark the corrected paths\n"
387 "with 'git add <paths>' or 'git rm <paths>'\n"
388 "and commit the result with 'git commit'"));
389 }
043a4492
RR
390}
391
44b776c3
AG
392int write_message(const void *buf, size_t len, const char *filename,
393 int append_eol)
043a4492 394{
14bca6c6 395 struct lock_file msg_file = LOCK_INIT;
043a4492 396
4ef3d8f0
JS
397 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
398 if (msg_fd < 0)
93b3df6f 399 return error_errno(_("could not lock '%s'"), filename);
75871495 400 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 401 error_errno(_("could not write to '%s'"), filename);
4f66c837 402 rollback_lock_file(&msg_file);
bf5c0571 403 return -1;
4f66c837 404 }
f56fffef 405 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 406 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 407 rollback_lock_file(&msg_file);
bf5c0571 408 return -1;
f56fffef 409 }
350292a1
410 if (commit_lock_file(&msg_file) < 0)
411 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
412
413 return 0;
043a4492
RR
414}
415
1dfc84e9
JS
416/*
417 * Reads a file that was presumably written by a shell script, i.e. with an
418 * end-of-line marker that needs to be stripped.
419 *
420 * Note that only the last end-of-line marker is stripped, consistent with the
421 * behavior of "$(cat path)" in a shell script.
422 *
423 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
424 */
425static int read_oneliner(struct strbuf *buf,
426 const char *path, int skip_if_empty)
427{
428 int orig_len = buf->len;
429
430 if (!file_exists(path))
431 return 0;
432
433 if (strbuf_read_file(buf, path, 0) < 0) {
434 warning_errno(_("could not read '%s'"), path);
435 return 0;
436 }
437
438 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
439 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
440 --buf->len;
441 buf->buf[buf->len] = '\0';
442 }
443
444 if (skip_if_empty && buf->len == orig_len)
445 return 0;
446
447 return 1;
448}
449
005af339 450static struct tree *empty_tree(struct repository *r)
043a4492 451{
005af339 452 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
453}
454
e1ff0a32 455static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 456{
e1ff0a32 457 if (repo_read_index_unmerged(repo))
c28cbc5e 458 return error_resolve_conflict(_(action_name(opts)));
043a4492 459
93b3df6f 460 error(_("your local changes would be overwritten by %s."),
c28cbc5e 461 _(action_name(opts)));
043a4492
RR
462
463 if (advice_commit_before_merge)
93b3df6f 464 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
465 return -1;
466}
467
1e41229d
SB
468static void update_abort_safety_file(void)
469{
470 struct object_id head;
471
472 /* Do nothing on a single-pick */
473 if (!file_exists(git_path_seq_dir()))
474 return;
475
476 if (!get_oid("HEAD", &head))
477 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
478 else
479 write_file(git_path_abort_safety_file(), "%s", "");
480}
481
f11c9580
NTND
482static int fast_forward_to(struct repository *r,
483 const struct object_id *to,
484 const struct object_id *from,
485 int unborn,
486 struct replay_opts *opts)
043a4492 487{
d668d16c 488 struct ref_transaction *transaction;
eb4be1cb 489 struct strbuf sb = STRBUF_INIT;
d668d16c 490 struct strbuf err = STRBUF_INIT;
043a4492 491
e1ff0a32 492 repo_read_index(r);
f11c9580 493 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 494 return -1; /* the callee should have complained already */
651ab9f5 495
c28cbc5e 496 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
d668d16c
RS
497
498 transaction = ref_transaction_begin(&err);
499 if (!transaction ||
500 ref_transaction_update(transaction, "HEAD",
d87d48b2
JS
501 to, unborn && !is_rebase_i(opts) ?
502 &null_oid : from,
1d147bdf 503 0, sb.buf, &err) ||
db7516ab 504 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
505 ref_transaction_free(transaction);
506 error("%s", err.buf);
507 strbuf_release(&sb);
508 strbuf_release(&err);
509 return -1;
510 }
651ab9f5 511
eb4be1cb 512 strbuf_release(&sb);
d668d16c
RS
513 strbuf_release(&err);
514 ref_transaction_free(transaction);
1e41229d 515 update_abort_safety_file();
d668d16c 516 return 0;
043a4492
RR
517}
518
f29cd862
DL
519enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
520 int use_editor)
521{
522 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
523 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
524 COMMIT_MSG_CLEANUP_SPACE;
525 else if (!strcmp(cleanup_arg, "verbatim"))
526 return COMMIT_MSG_CLEANUP_NONE;
527 else if (!strcmp(cleanup_arg, "whitespace"))
528 return COMMIT_MSG_CLEANUP_SPACE;
529 else if (!strcmp(cleanup_arg, "strip"))
530 return COMMIT_MSG_CLEANUP_ALL;
531 else if (!strcmp(cleanup_arg, "scissors"))
532 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
533 COMMIT_MSG_CLEANUP_SPACE;
534 else
535 die(_("Invalid cleanup mode %s"), cleanup_arg);
536}
537
dc42e9a8
PW
538/*
539 * NB using int rather than enum cleanup_mode to stop clang's
540 * -Wtautological-constant-out-of-range-compare complaining that the comparison
541 * is always true.
542 */
543static const char *describe_cleanup_mode(int cleanup_mode)
544{
545 static const char *modes[] = { "whitespace",
546 "verbatim",
547 "scissors",
548 "strip" };
549
550 if (cleanup_mode < ARRAY_SIZE(modes))
551 return modes[cleanup_mode];
552
553 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
554}
555
f11c9580
NTND
556void append_conflicts_hint(struct index_state *istate,
557 struct strbuf *msgbuf)
75c961b7
JH
558{
559 int i;
560
261f315b
JH
561 strbuf_addch(msgbuf, '\n');
562 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
563 for (i = 0; i < istate->cache_nr;) {
564 const struct cache_entry *ce = istate->cache[i++];
75c961b7 565 if (ce_stage(ce)) {
261f315b 566 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
567 while (i < istate->cache_nr &&
568 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
569 i++;
570 }
571 }
572}
573
f11c9580
NTND
574static int do_recursive_merge(struct repository *r,
575 struct commit *base, struct commit *next,
043a4492 576 const char *base_label, const char *next_label,
48be4c62 577 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
578 struct replay_opts *opts)
579{
580 struct merge_options o;
581 struct tree *result, *next_tree, *base_tree, *head_tree;
03b86647 582 int clean;
03a4e260 583 char **xopt;
14bca6c6 584 struct lock_file index_lock = LOCK_INIT;
043a4492 585
3a95f31d 586 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 587 return -1;
043a4492 588
e1ff0a32 589 repo_read_index(r);
043a4492 590
0d6caa2d 591 init_merge_options(&o, r);
043a4492
RR
592 o.ancestor = base ? base_label : "(empty tree)";
593 o.branch1 = "HEAD";
594 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
595 if (is_rebase_i(opts))
596 o.buffer_output = 2;
9268cf4a 597 o.show_rename_progress = 1;
043a4492
RR
598
599 head_tree = parse_tree_indirect(head);
005af339
NTND
600 next_tree = next ? get_commit_tree(next) : empty_tree(r);
601 base_tree = base ? get_commit_tree(base) : empty_tree(r);
043a4492
RR
602
603 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
604 parse_merge_opt(&o, *xopt);
605
606 clean = merge_trees(&o,
607 head_tree,
608 next_tree, base_tree, &result);
62fdb652
JS
609 if (is_rebase_i(opts) && clean <= 0)
610 fputs(o.obuf.buf, stdout);
548009c0 611 strbuf_release(&o.obuf);
b520abf1 612 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
64816524
613 if (clean < 0) {
614 rollback_lock_file(&index_lock);
f241ff0d 615 return clean;
64816524 616 }
043a4492 617
f11c9580 618 if (write_locked_index(r->index, &index_lock,
61000814 619 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
620 /*
621 * TRANSLATORS: %s will be "revert", "cherry-pick" or
84583957
JS
622 * "rebase -i".
623 */
c527b55e 624 return error(_("%s: Unable to write new index file"),
c28cbc5e 625 _(action_name(opts)));
043a4492 626
75c961b7 627 if (!clean)
f11c9580 628 append_conflicts_hint(r->index, msgbuf);
043a4492
RR
629
630 return !clean;
631}
632
f11c9580 633static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 634{
f11c9580
NTND
635 if (!istate->cache_tree)
636 istate->cache_tree = cache_tree();
ba97aea1 637
f11c9580
NTND
638 if (!cache_tree_fully_valid(istate->cache_tree))
639 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
640 error(_("unable to update cache tree"));
641 return NULL;
642 }
643
f11c9580 644 return &istate->cache_tree->oid;
ba97aea1
JS
645}
646
005af339 647static int is_index_unchanged(struct repository *r)
b27cfb0d 648{
ba97aea1 649 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 650 struct commit *head_commit;
005af339 651 struct index_state *istate = r->index;
b27cfb0d 652
49e61479 653 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 654 return error(_("could not resolve HEAD commit"));
b27cfb0d 655
005af339 656 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
657
658 /*
659 * If head_commit is NULL, check_commit, called from
660 * lookup_commit, would have indicated that head_commit is not
661 * a commit object already. parse_commit() will return failure
662 * without further complaints in such a case. Otherwise, if
663 * the commit is invalid, parse_commit() will complain. So
664 * there is nothing for us to say here. Just return failure.
665 */
666 if (parse_commit(head_commit))
667 return -1;
b27cfb0d 668
f11c9580 669 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 670 return -1;
b27cfb0d 671
4a7e27e9 672 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
673}
674
0473f28a
JS
675static int write_author_script(const char *message)
676{
677 struct strbuf buf = STRBUF_INIT;
678 const char *eol;
679 int res;
680
681 for (;;)
682 if (!*message || starts_with(message, "\n")) {
683missing_author:
684 /* Missing 'author' line? */
685 unlink(rebase_path_author_script());
686 return 0;
687 } else if (skip_prefix(message, "author ", &message))
688 break;
689 else if ((eol = strchr(message, '\n')))
690 message = eol + 1;
691 else
692 goto missing_author;
693
694 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
695 while (*message && *message != '\n' && *message != '\r')
696 if (skip_prefix(message, " <", &message))
697 break;
698 else if (*message != '\'')
699 strbuf_addch(&buf, *(message++));
700 else
4aa5ff94 701 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
702 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
703 while (*message && *message != '\n' && *message != '\r')
704 if (skip_prefix(message, "> ", &message))
705 break;
706 else if (*message != '\'')
707 strbuf_addch(&buf, *(message++));
708 else
4aa5ff94 709 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
710 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
711 while (*message && *message != '\n' && *message != '\r')
712 if (*message != '\'')
713 strbuf_addch(&buf, *(message++));
714 else
4aa5ff94 715 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 716 strbuf_addch(&buf, '\'');
0473f28a
JS
717 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
718 strbuf_release(&buf);
719 return res;
720}
721
bcd33ec2
PW
722/**
723 * Take a series of KEY='VALUE' lines where VALUE part is
724 * sq-quoted, and append <KEY, VALUE> at the end of the string list
725 */
726static int parse_key_value_squoted(char *buf, struct string_list *list)
727{
728 while (*buf) {
729 struct string_list_item *item;
730 char *np;
731 char *cp = strchr(buf, '=');
732 if (!cp) {
733 np = strchrnul(buf, '\n');
734 return error(_("no key present in '%.*s'"),
735 (int) (np - buf), buf);
736 }
737 np = strchrnul(cp, '\n');
738 *cp++ = '\0';
739 item = string_list_append(list, buf);
740
741 buf = np + (*np == '\n');
742 *np = '\0';
743 cp = sq_dequote(cp);
744 if (!cp)
745 return error(_("unable to dequote value of '%s'"),
746 item->string);
747 item->util = xstrdup(cp);
748 }
749 return 0;
750}
4aa5ff94 751
bcd33ec2
PW
752/**
753 * Reads and parses the state directory's "author-script" file, and sets name,
754 * email and date accordingly.
755 * Returns 0 on success, -1 if the file could not be parsed.
756 *
757 * The author script is of the format:
758 *
759 * GIT_AUTHOR_NAME='$author_name'
760 * GIT_AUTHOR_EMAIL='$author_email'
761 * GIT_AUTHOR_DATE='$author_date'
762 *
763 * where $author_name, $author_email and $author_date are quoted. We are strict
764 * with our parsing, as the file was meant to be eval'd in the old
765 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
766 * from what this function expects, it is better to bail out than to do
767 * something that the user does not expect.
4aa5ff94 768 */
bcd33ec2
PW
769int read_author_script(const char *path, char **name, char **email, char **date,
770 int allow_missing)
4aa5ff94 771{
bcd33ec2
PW
772 struct strbuf buf = STRBUF_INIT;
773 struct string_list kv = STRING_LIST_INIT_DUP;
774 int retval = -1; /* assume failure */
775 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 776
bcd33ec2
PW
777 if (strbuf_read_file(&buf, path, 256) <= 0) {
778 strbuf_release(&buf);
779 if (errno == ENOENT && allow_missing)
780 return 0;
781 else
782 return error_errno(_("could not open '%s' for reading"),
783 path);
784 }
785
786 if (parse_key_value_squoted(buf.buf, &kv))
787 goto finish;
788
789 for (i = 0; i < kv.nr; i++) {
790 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
791 if (name_i != -2)
792 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
793 else
794 name_i = i;
795 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
796 if (email_i != -2)
797 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
798 else
799 email_i = i;
800 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
801 if (date_i != -2)
802 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
803 else
804 date_i = i;
805 } else {
806 err = error(_("unknown variable '%s'"),
807 kv.items[i].string);
808 }
809 }
810 if (name_i == -2)
811 error(_("missing 'GIT_AUTHOR_NAME'"));
812 if (email_i == -2)
813 error(_("missing 'GIT_AUTHOR_EMAIL'"));
814 if (date_i == -2)
815 error(_("missing 'GIT_AUTHOR_DATE'"));
816 if (date_i < 0 || email_i < 0 || date_i < 0 || err)
817 goto finish;
818 *name = kv.items[name_i].util;
819 *email = kv.items[email_i].util;
820 *date = kv.items[date_i].util;
821 retval = 0;
822finish:
823 string_list_clear(&kv, !!retval);
824 strbuf_release(&buf);
825 return retval;
4aa5ff94
PW
826}
827
b5a67045 828/*
4d010a75
PW
829 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
830 * file with shell quoting into struct argv_array. Returns -1 on
831 * error, 0 otherwise.
b5a67045 832 */
a2a20b0d 833static int read_env_script(struct argv_array *env)
b5a67045 834{
4d010a75 835 char *name, *email, *date;
b5a67045 836
4d010a75
PW
837 if (read_author_script(rebase_path_author_script(),
838 &name, &email, &date, 0))
a2a20b0d 839 return -1;
b5a67045 840
4d010a75
PW
841 argv_array_pushf(env, "GIT_AUTHOR_NAME=%s", name);
842 argv_array_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
843 argv_array_pushf(env, "GIT_AUTHOR_DATE=%s", date);
844 free(name);
845 free(email);
846 free(date);
b5a67045 847
a2a20b0d 848 return 0;
b5a67045
JS
849}
850
356ee465
PW
851static char *get_author(const char *message)
852{
853 size_t len;
854 const char *a;
855
856 a = find_commit_header(message, "author", &len);
857 if (a)
858 return xmemdupz(a, len);
859
860 return NULL;
861}
862
d87d48b2
JS
863/* Read author-script and return an ident line (author <email> timestamp) */
864static const char *read_author_ident(struct strbuf *buf)
865{
67f16e3d 866 struct strbuf out = STRBUF_INIT;
4d010a75 867 char *name, *email, *date;
d87d48b2 868
4d010a75
PW
869 if (read_author_script(rebase_path_author_script(),
870 &name, &email, &date, 0))
d87d48b2
JS
871 return NULL;
872
5522bbac 873 /* validate date since fmt_ident() will die() on bad value */
4d010a75 874 if (parse_date(date, &out)){
5522bbac 875 warning(_("invalid date format '%s' in '%s'"),
4d010a75 876 date, rebase_path_author_script());
5522bbac
ES
877 strbuf_release(&out);
878 return NULL;
879 }
880
881 strbuf_reset(&out);
39ab4d09 882 strbuf_addstr(&out, fmt_ident(name, email, WANT_AUTHOR_IDENT, date, 0));
67f16e3d
ES
883 strbuf_swap(buf, &out);
884 strbuf_release(&out);
4d010a75
PW
885 free(name);
886 free(email);
887 free(date);
d87d48b2
JS
888 return buf->buf;
889}
890
791eb870
JS
891static const char staged_changes_advice[] =
892N_("you have staged changes in your working tree\n"
893"If these changes are meant to be squashed into the previous commit, run:\n"
894"\n"
895" git commit --amend %s\n"
896"\n"
897"If they are meant to go into a new commit, run:\n"
898"\n"
899" git commit %s\n"
900"\n"
901"In both cases, once you're done, continue with:\n"
902"\n"
903" git rebase --continue\n");
904
789b3eff
JS
905#define ALLOW_EMPTY (1<<0)
906#define EDIT_MSG (1<<1)
907#define AMEND_MSG (1<<2)
908#define CLEANUP_MSG (1<<3)
b92ff6e8 909#define VERIFY_MSG (1<<4)
d87d48b2 910#define CREATE_ROOT_COMMIT (1<<5)
789b3eff 911
34bec2c4
AG
912static int run_command_silent_on_success(struct child_process *cmd)
913{
914 struct strbuf buf = STRBUF_INIT;
915 int rc;
916
917 cmd->stdout_to_stderr = 1;
918 rc = pipe_command(cmd,
919 NULL, 0,
920 NULL, 0,
921 &buf, 0);
922
923 if (rc)
924 fputs(buf.buf, stderr);
925 strbuf_release(&buf);
926 return rc;
927}
928
043a4492
RR
929/*
930 * If we are cherry-pick, and if the merge did not result in
931 * hand-editing, we will hit this commit and inherit the original
932 * author date and name.
b5a67045 933 *
043a4492
RR
934 * If we are revert, or if our cherry-pick results in a hand merge,
935 * we had better say that the current user is responsible for that.
b5a67045
JS
936 *
937 * An exception is when run_git_commit() is called during an
938 * interactive rebase: in that case, we will want to retain the
939 * author metadata.
043a4492 940 */
f11c9580
NTND
941static int run_git_commit(struct repository *r,
942 const char *defmsg,
943 struct replay_opts *opts,
789b3eff 944 unsigned int flags)
043a4492 945{
07d968ef 946 struct child_process cmd = CHILD_PROCESS_INIT;
17d65f03 947 const char *value;
b27cfb0d 948
76fda6eb 949 if ((flags & CREATE_ROOT_COMMIT) && !(flags & AMEND_MSG)) {
d87d48b2 950 struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
5dfcfe1e 951 const char *author = NULL;
d87d48b2
JS
952 struct object_id root_commit, *cache_tree_oid;
953 int res = 0;
954
5dfcfe1e
PW
955 if (is_rebase_i(opts)) {
956 author = read_author_ident(&script);
957 if (!author) {
958 strbuf_release(&script);
959 return -1;
960 }
961 }
962
d87d48b2
JS
963 if (!defmsg)
964 BUG("root commit without message");
965
f11c9580 966 if (!(cache_tree_oid = get_cache_tree_oid(r->index)))
d87d48b2
JS
967 res = -1;
968
969 if (!res)
970 res = strbuf_read_file(&msg, defmsg, 0);
971
972 if (res <= 0)
973 res = error_errno(_("could not read '%s'"), defmsg);
974 else
975 res = commit_tree(msg.buf, msg.len, cache_tree_oid,
976 NULL, &root_commit, author,
977 opts->gpg_sign);
978
979 strbuf_release(&msg);
980 strbuf_release(&script);
981 if (!res) {
982 update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
983 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
984 res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
985 UPDATE_REFS_MSG_ON_ERR);
986 }
987 return res < 0 ? error(_("writing root commit")) : 0;
988 }
989
07d968ef
JS
990 cmd.git_cmd = 1;
991
34bec2c4
AG
992 if (is_rebase_i(opts) && read_env_script(&cmd.env_array)) {
993 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 994
34bec2c4
AG
995 return error(_(staged_changes_advice),
996 gpg_opt, gpg_opt);
b5a67045
JS
997 }
998
07d968ef 999 argv_array_push(&cmd.args, "commit");
043a4492 1000
b92ff6e8
JS
1001 if (!(flags & VERIFY_MSG))
1002 argv_array_push(&cmd.args, "-n");
789b3eff 1003 if ((flags & AMEND_MSG))
07d968ef 1004 argv_array_push(&cmd.args, "--amend");
3bdd5522 1005 if (opts->gpg_sign)
07d968ef 1006 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
b5a67045 1007 if (defmsg)
07d968ef 1008 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3
JS
1009 else if (!(flags & EDIT_MSG))
1010 argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 1011 if ((flags & CLEANUP_MSG))
07d968ef 1012 argv_array_push(&cmd.args, "--cleanup=strip");
789b3eff 1013 if ((flags & EDIT_MSG))
07d968ef 1014 argv_array_push(&cmd.args, "-e");
789b3eff 1015 else if (!(flags & CLEANUP_MSG) &&
0009426d 1016 !opts->signoff && !opts->record_origin &&
b5a67045 1017 git_config_get_value("commit.cleanup", &value))
07d968ef 1018 argv_array_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 1019
789b3eff 1020 if ((flags & ALLOW_EMPTY))
07d968ef 1021 argv_array_push(&cmd.args, "--allow-empty");
df478b74 1022
a3ec9eaf 1023 if (!(flags & EDIT_MSG))
07d968ef 1024 argv_array_push(&cmd.args, "--allow-empty-message");
4bee9584 1025
34bec2c4
AG
1026 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1027 return run_command_silent_on_success(&cmd);
1028 else
1029 return run_command(&cmd);
b27cfb0d
NH
1030}
1031
d0aaa46f
PW
1032static int rest_is_empty(const struct strbuf *sb, int start)
1033{
1034 int i, eol;
1035 const char *nl;
1036
1037 /* Check if the rest is just whitespace and Signed-off-by's. */
1038 for (i = start; i < sb->len; i++) {
1039 nl = memchr(sb->buf + i, '\n', sb->len - i);
1040 if (nl)
1041 eol = nl - sb->buf;
1042 else
1043 eol = sb->len;
1044
1045 if (strlen(sign_off_header) <= eol - i &&
1046 starts_with(sb->buf + i, sign_off_header)) {
1047 i = eol;
1048 continue;
1049 }
1050 while (i < eol)
1051 if (!isspace(sb->buf[i++]))
1052 return 0;
1053 }
1054
1055 return 1;
1056}
1057
f29cd862
DL
1058void cleanup_message(struct strbuf *msgbuf,
1059 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1060{
1061 if (verbose || /* Truncate the message just before the diff, if any. */
1062 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1063 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1064 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1065 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1066}
1067
d0aaa46f
PW
1068/*
1069 * Find out if the message in the strbuf contains only whitespace and
1070 * Signed-off-by lines.
1071 */
1072int message_is_empty(const struct strbuf *sb,
1073 enum commit_msg_cleanup_mode cleanup_mode)
1074{
1075 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1076 return 0;
1077 return rest_is_empty(sb, 0);
1078}
1079
1080/*
1081 * See if the user edited the message in the editor or left what
1082 * was in the template intact
1083 */
1084int template_untouched(const struct strbuf *sb, const char *template_file,
1085 enum commit_msg_cleanup_mode cleanup_mode)
1086{
1087 struct strbuf tmpl = STRBUF_INIT;
1088 const char *start;
1089
1090 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1091 return 0;
1092
1093 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1094 return 0;
1095
1096 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1097 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1098 start = sb->buf;
1099 strbuf_release(&tmpl);
1100 return rest_is_empty(sb, start - sb->buf);
1101}
1102
0505d604
PW
1103int update_head_with_reflog(const struct commit *old_head,
1104 const struct object_id *new_head,
1105 const char *action, const struct strbuf *msg,
1106 struct strbuf *err)
1107{
1108 struct ref_transaction *transaction;
1109 struct strbuf sb = STRBUF_INIT;
1110 const char *nl;
1111 int ret = 0;
1112
1113 if (action) {
1114 strbuf_addstr(&sb, action);
1115 strbuf_addstr(&sb, ": ");
1116 }
1117
1118 nl = strchr(msg->buf, '\n');
1119 if (nl) {
1120 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1121 } else {
1122 strbuf_addbuf(&sb, msg);
1123 strbuf_addch(&sb, '\n');
1124 }
1125
1126 transaction = ref_transaction_begin(err);
1127 if (!transaction ||
1128 ref_transaction_update(transaction, "HEAD", new_head,
1129 old_head ? &old_head->object.oid : &null_oid,
1130 0, sb.buf, err) ||
1131 ref_transaction_commit(transaction, err)) {
1132 ret = -1;
1133 }
1134 ref_transaction_free(transaction);
1135 strbuf_release(&sb);
1136
1137 return ret;
1138}
1139
a87a6f3c
PW
1140static int run_rewrite_hook(const struct object_id *oldoid,
1141 const struct object_id *newoid)
1142{
1143 struct child_process proc = CHILD_PROCESS_INIT;
1144 const char *argv[3];
1145 int code;
1146 struct strbuf sb = STRBUF_INIT;
1147
1148 argv[0] = find_hook("post-rewrite");
1149 if (!argv[0])
1150 return 0;
1151
1152 argv[1] = "amend";
1153 argv[2] = NULL;
1154
1155 proc.argv = argv;
1156 proc.in = -1;
1157 proc.stdout_to_stderr = 1;
6206286e 1158 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1159
1160 code = start_command(&proc);
1161 if (code)
1162 return code;
1163 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1164 sigchain_push(SIGPIPE, SIG_IGN);
1165 write_in_full(proc.in, sb.buf, sb.len);
1166 close(proc.in);
1167 strbuf_release(&sb);
1168 sigchain_pop(SIGPIPE);
1169 return finish_command(&proc);
1170}
1171
1d18d758
NTND
1172void commit_post_rewrite(struct repository *r,
1173 const struct commit *old_head,
a87a6f3c
PW
1174 const struct object_id *new_head)
1175{
1176 struct notes_rewrite_cfg *cfg;
1177
1178 cfg = init_copy_notes_for_rewrite("amend");
1179 if (cfg) {
1180 /* we are amending, so old_head is not NULL */
1181 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1182 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1183 }
1184 run_rewrite_hook(&old_head->object.oid, new_head);
1185}
1186
f11c9580
NTND
1187static int run_prepare_commit_msg_hook(struct repository *r,
1188 struct strbuf *msg,
1189 const char *commit)
66618a50
PW
1190{
1191 struct argv_array hook_env = ARGV_ARRAY_INIT;
1192 int ret;
1193 const char *name;
1194
1195 name = git_path_commit_editmsg();
1196 if (write_message(msg->buf, msg->len, name, 0))
1197 return -1;
1198
f11c9580 1199 argv_array_pushf(&hook_env, "GIT_INDEX_FILE=%s", r->index_file);
66618a50
PW
1200 argv_array_push(&hook_env, "GIT_EDITOR=:");
1201 if (commit)
1202 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1203 "commit", commit, NULL);
1204 else
1205 ret = run_hook_le(hook_env.argv, "prepare-commit-msg", name,
1206 "message", NULL);
1207 if (ret)
1208 ret = error(_("'prepare-commit-msg' hook failed"));
1209 argv_array_clear(&hook_env);
1210
1211 return ret;
1212}
1213
e47c6caf
PW
1214static const char implicit_ident_advice_noconfig[] =
1215N_("Your name and email address were configured automatically based\n"
1216"on your username and hostname. Please check that they are accurate.\n"
1217"You can suppress this message by setting them explicitly. Run the\n"
1218"following command and follow the instructions in your editor to edit\n"
1219"your configuration file:\n"
1220"\n"
1221" git config --global --edit\n"
1222"\n"
1223"After doing this, you may fix the identity used for this commit with:\n"
1224"\n"
1225" git commit --amend --reset-author\n");
1226
1227static const char implicit_ident_advice_config[] =
1228N_("Your name and email address were configured automatically based\n"
1229"on your username and hostname. Please check that they are accurate.\n"
1230"You can suppress this message by setting them explicitly:\n"
1231"\n"
1232" git config --global user.name \"Your Name\"\n"
1233" git config --global user.email you@example.com\n"
1234"\n"
1235"After doing this, you may fix the identity used for this commit with:\n"
1236"\n"
1237" git commit --amend --reset-author\n");
1238
1239static const char *implicit_ident_advice(void)
1240{
1241 char *user_config = expand_user_path("~/.gitconfig", 0);
1242 char *xdg_config = xdg_config_home("config");
1243 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1244
1245 free(user_config);
1246 free(xdg_config);
1247
1248 if (config_exists)
1249 return _(implicit_ident_advice_config);
1250 else
1251 return _(implicit_ident_advice_noconfig);
1252
1253}
1254
f11c9580
NTND
1255void print_commit_summary(struct repository *r,
1256 const char *prefix,
1257 const struct object_id *oid,
e47c6caf
PW
1258 unsigned int flags)
1259{
1260 struct rev_info rev;
1261 struct commit *commit;
1262 struct strbuf format = STRBUF_INIT;
1263 const char *head;
1264 struct pretty_print_context pctx = {0};
1265 struct strbuf author_ident = STRBUF_INIT;
1266 struct strbuf committer_ident = STRBUF_INIT;
1267
f11c9580 1268 commit = lookup_commit(r, oid);
e47c6caf
PW
1269 if (!commit)
1270 die(_("couldn't look up newly created commit"));
1271 if (parse_commit(commit))
1272 die(_("could not parse newly created commit"));
1273
1274 strbuf_addstr(&format, "format:%h] %s");
1275
1276 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1277 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1278 if (strbuf_cmp(&author_ident, &committer_ident)) {
1279 strbuf_addstr(&format, "\n Author: ");
1280 strbuf_addbuf_percentquote(&format, &author_ident);
1281 }
1282 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1283 struct strbuf date = STRBUF_INIT;
1284
1285 format_commit_message(commit, "%ad", &date, &pctx);
1286 strbuf_addstr(&format, "\n Date: ");
1287 strbuf_addbuf_percentquote(&format, &date);
1288 strbuf_release(&date);
1289 }
1290 if (!committer_ident_sufficiently_given()) {
1291 strbuf_addstr(&format, "\n Committer: ");
1292 strbuf_addbuf_percentquote(&format, &committer_ident);
1293 if (advice_implicit_identity) {
1294 strbuf_addch(&format, '\n');
1295 strbuf_addstr(&format, implicit_ident_advice());
1296 }
1297 }
1298 strbuf_release(&author_ident);
1299 strbuf_release(&committer_ident);
1300
f11c9580 1301 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1302 setup_revisions(0, NULL, &rev, NULL);
1303
1304 rev.diff = 1;
1305 rev.diffopt.output_format =
1306 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1307
1308 rev.verbose_header = 1;
1309 rev.show_root_diff = 1;
1310 get_commit_format(format.buf, &rev);
1311 rev.always_show_header = 0;
0f57f731 1312 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1313 rev.diffopt.break_opt = 0;
1314 diff_setup_done(&rev.diffopt);
1315
1316 head = resolve_ref_unsafe("HEAD", 0, NULL, NULL);
1317 if (!head)
1318 die_errno(_("unable to resolve HEAD after creating commit"));
1319 if (!strcmp(head, "HEAD"))
1320 head = _("detached HEAD");
1321 else
1322 skip_prefix(head, "refs/heads/", &head);
1323 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1324 _(" (root-commit)") : "");
1325
1326 if (!log_tree_commit(&rev, commit)) {
1327 rev.always_show_header = 1;
1328 rev.use_terminator = 1;
1329 log_tree_commit(&rev, commit);
1330 }
1331
1332 strbuf_release(&format);
1333}
1334
005af339 1335static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1336{
1337 struct commit *current_head;
1338 struct object_id oid;
1339
1340 if (get_oid("HEAD", &oid)) {
1341 current_head = NULL;
1342 } else {
005af339 1343 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1344 if (!current_head)
1345 return error(_("could not parse HEAD"));
9001dc2a 1346 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1347 warning(_("HEAD %s is not a commit!"),
1348 oid_to_hex(&oid));
1349 }
1350 if (parse_commit(current_head))
1351 return error(_("could not parse HEAD commit"));
1352 }
1353 *head = current_head;
1354
1355 return 0;
1356}
1357
1358/*
1359 * Try to commit without forking 'git commit'. In some cases we need
1360 * to run 'git commit' to display an error message
1361 *
1362 * Returns:
1363 * -1 - error unable to commit
1364 * 0 - success
1365 * 1 - run 'git commit'
1366 */
f11c9580
NTND
1367static int try_to_commit(struct repository *r,
1368 struct strbuf *msg, const char *author,
356ee465
PW
1369 struct replay_opts *opts, unsigned int flags,
1370 struct object_id *oid)
1371{
1372 struct object_id tree;
1373 struct commit *current_head;
1374 struct commit_list *parents = NULL;
1375 struct commit_extra_header *extra = NULL;
1376 struct strbuf err = STRBUF_INIT;
66618a50 1377 struct strbuf commit_msg = STRBUF_INIT;
356ee465 1378 char *amend_author = NULL;
66618a50 1379 const char *hook_commit = NULL;
356ee465
PW
1380 enum commit_msg_cleanup_mode cleanup;
1381 int res = 0;
1382
005af339 1383 if (parse_head(r, &current_head))
356ee465
PW
1384 return -1;
1385
1386 if (flags & AMEND_MSG) {
1387 const char *exclude_gpgsig[] = { "gpgsig", NULL };
1388 const char *out_enc = get_commit_output_encoding();
1389 const char *message = logmsg_reencode(current_head, NULL,
1390 out_enc);
1391
1392 if (!msg) {
1393 const char *orig_message = NULL;
1394
1395 find_commit_subject(message, &orig_message);
66618a50 1396 msg = &commit_msg;
356ee465 1397 strbuf_addstr(msg, orig_message);
66618a50 1398 hook_commit = "HEAD";
356ee465
PW
1399 }
1400 author = amend_author = get_author(message);
1401 unuse_commit_buffer(current_head, message);
1402 if (!author) {
1403 res = error(_("unable to parse commit author"));
1404 goto out;
1405 }
1406 parents = copy_commit_list(current_head->parents);
1407 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1408 } else if (current_head) {
1409 commit_list_insert(current_head, &parents);
1410 }
1411
f11c9580 1412 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1413 res = error(_("git write-tree failed to write a tree"));
1414 goto out;
1415 }
1416
4a7e27e9
JK
1417 if (!(flags & ALLOW_EMPTY) && oideq(current_head ?
1418 get_commit_tree_oid(current_head) :
1419 the_hash_algo->empty_tree, &tree)) {
356ee465
PW
1420 res = 1; /* run 'git commit' to display error message */
1421 goto out;
1422 }
1423
66618a50 1424 if (find_hook("prepare-commit-msg")) {
f11c9580 1425 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1426 if (res)
1427 goto out;
1428 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1429 2048) < 0) {
1430 res = error_errno(_("unable to read commit message "
1431 "from '%s'"),
1432 git_path_commit_editmsg());
1433 goto out;
1434 }
1435 msg = &commit_msg;
1436 }
1437
d74f3e58
PW
1438 if (flags & CLEANUP_MSG)
1439 cleanup = COMMIT_MSG_CLEANUP_ALL;
1440 else if ((opts->signoff || opts->record_origin) &&
1441 !opts->explicit_cleanup)
1442 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1443 else
1444 cleanup = opts->default_msg_cleanup;
66618a50
PW
1445
1446 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1447 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1448 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1449 res = 1; /* run 'git commit' to display error message */
1450 goto out;
1451 }
1452
12f7babd
JS
1453 reset_ident_date();
1454
8be8342b
JH
1455 if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
1456 oid, author, opts->gpg_sign, extra)) {
356ee465
PW
1457 res = error(_("failed to write commit object"));
1458 goto out;
1459 }
1460
1461 if (update_head_with_reflog(current_head, oid,
1462 getenv("GIT_REFLOG_ACTION"), msg, &err)) {
1463 res = error("%s", err.buf);
1464 goto out;
1465 }
1466
1467 if (flags & AMEND_MSG)
1d18d758 1468 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1469
1470out:
1471 free_commit_extra_headers(extra);
1472 strbuf_release(&err);
66618a50 1473 strbuf_release(&commit_msg);
356ee465
PW
1474 free(amend_author);
1475
1476 return res;
1477}
1478
f11c9580
NTND
1479static int do_commit(struct repository *r,
1480 const char *msg_file, const char *author,
356ee465
PW
1481 struct replay_opts *opts, unsigned int flags)
1482{
1483 int res = 1;
1484
d87d48b2
JS
1485 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
1486 !(flags & CREATE_ROOT_COMMIT)) {
356ee465
PW
1487 struct object_id oid;
1488 struct strbuf sb = STRBUF_INIT;
1489
1490 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1491 return error_errno(_("unable to read commit message "
1492 "from '%s'"),
1493 msg_file);
1494
f11c9580
NTND
1495 res = try_to_commit(r, msg_file ? &sb : NULL,
1496 author, opts, flags, &oid);
356ee465
PW
1497 strbuf_release(&sb);
1498 if (!res) {
f11c9580
NTND
1499 unlink(git_path_cherry_pick_head(r));
1500 unlink(git_path_merge_msg(r));
356ee465 1501 if (!is_rebase_i(opts))
f11c9580 1502 print_commit_summary(r, NULL, &oid,
356ee465
PW
1503 SUMMARY_SHOW_AUTHOR_DATE);
1504 return res;
1505 }
1506 }
1507 if (res == 1)
f11c9580 1508 return run_git_commit(r, msg_file, opts, flags);
356ee465
PW
1509
1510 return res;
1511}
1512
b27cfb0d
NH
1513static int is_original_commit_empty(struct commit *commit)
1514{
092bbcdf 1515 const struct object_id *ptree_oid;
b27cfb0d
NH
1516
1517 if (parse_commit(commit))
aee42e1f 1518 return error(_("could not parse commit %s"),
f2fd0760 1519 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1520 if (commit->parents) {
1521 struct commit *parent = commit->parents->item;
1522 if (parse_commit(parent))
aee42e1f 1523 return error(_("could not parse parent commit %s"),
f2fd0760 1524 oid_to_hex(&parent->object.oid));
2e27bd77 1525 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1526 } else {
eb0ccfd7 1527 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1528 }
043a4492 1529
4a7e27e9 1530 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1531}
1532
ac2b0e8f
JH
1533/*
1534 * Do we run "git commit" with "--allow-empty"?
1535 */
f11c9580
NTND
1536static int allow_empty(struct repository *r,
1537 struct replay_opts *opts,
1538 struct commit *commit)
ac2b0e8f
JH
1539{
1540 int index_unchanged, empty_commit;
1541
1542 /*
1543 * Three cases:
1544 *
1545 * (1) we do not allow empty at all and error out.
1546 *
1547 * (2) we allow ones that were initially empty, but
1548 * forbid the ones that become empty;
1549 *
1550 * (3) we allow both.
1551 */
1552 if (!opts->allow_empty)
1553 return 0; /* let "git commit" barf as necessary */
1554
005af339 1555 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1556 if (index_unchanged < 0)
1557 return index_unchanged;
1558 if (!index_unchanged)
1559 return 0; /* we do not have to say --allow-empty */
1560
1561 if (opts->keep_redundant_commits)
1562 return 1;
1563
1564 empty_commit = is_original_commit_empty(commit);
1565 if (empty_commit < 0)
1566 return empty_commit;
1567 if (!empty_commit)
1568 return 0;
1569 else
1570 return 1;
1571}
1572
25c43667
JS
1573/*
1574 * Note that ordering matters in this enum. Not only must it match the mapping
1575 * below, it is also divided into several sections that matter. When adding
1576 * new commands, make sure you add it in the right section.
1577 */
004fefa7 1578enum todo_command {
25c43667 1579 /* commands that handle commits */
004fefa7 1580 TODO_PICK = 0,
25c43667 1581 TODO_REVERT,
56dc3ab0 1582 TODO_EDIT,
04efc8b5 1583 TODO_REWORD,
6e98de72
JS
1584 TODO_FIXUP,
1585 TODO_SQUASH,
311af526
JS
1586 /* commands that do something else than handling a single commit */
1587 TODO_EXEC,
71f82465 1588 TODO_BREAK,
9055e401
JS
1589 TODO_LABEL,
1590 TODO_RESET,
4c68e7dd 1591 TODO_MERGE,
25c43667 1592 /* commands that do nothing but are counted for reporting progress */
b3fdd581 1593 TODO_NOOP,
ac191470
JS
1594 TODO_DROP,
1595 /* comments (not counted for reporting progress) */
1596 TODO_COMMENT
004fefa7
JS
1597};
1598
414697a9
JS
1599static struct {
1600 char c;
1601 const char *str;
1602} todo_command_info[] = {
1603 { 'p', "pick" },
1604 { 0, "revert" },
1605 { 'e', "edit" },
04efc8b5 1606 { 'r', "reword" },
414697a9
JS
1607 { 'f', "fixup" },
1608 { 's', "squash" },
1609 { 'x', "exec" },
71f82465 1610 { 'b', "break" },
9055e401
JS
1611 { 'l', "label" },
1612 { 't', "reset" },
4c68e7dd 1613 { 'm', "merge" },
b3fdd581 1614 { 0, "noop" },
ac191470
JS
1615 { 'd', "drop" },
1616 { 0, NULL }
004fefa7
JS
1617};
1618
1619static const char *command_to_string(const enum todo_command command)
1620{
ac191470 1621 if (command < TODO_COMMENT)
414697a9 1622 return todo_command_info[command].str;
02127c63 1623 die(_("unknown command: %d"), command);
004fefa7
JS
1624}
1625
ee5462d6 1626static char command_to_char(const enum todo_command command)
d8ae6c84
LB
1627{
1628 if (command < TODO_COMMENT && todo_command_info[command].c)
1629 return todo_command_info[command].c;
1630 return comment_line_char;
1631}
1632
25c43667
JS
1633static int is_noop(const enum todo_command command)
1634{
b3fdd581 1635 return TODO_NOOP <= command;
25c43667 1636}
004fefa7 1637
6e98de72
JS
1638static int is_fixup(enum todo_command command)
1639{
1640 return command == TODO_FIXUP || command == TODO_SQUASH;
1641}
1642
d87d48b2
JS
1643/* Does this command create a (non-merge) commit? */
1644static int is_pick_or_similar(enum todo_command command)
1645{
1646 switch (command) {
1647 case TODO_PICK:
1648 case TODO_REVERT:
1649 case TODO_EDIT:
1650 case TODO_REWORD:
1651 case TODO_FIXUP:
1652 case TODO_SQUASH:
1653 return 1;
1654 default:
1655 return 0;
1656 }
1657}
1658
005af339
NTND
1659static int update_squash_messages(struct repository *r,
1660 enum todo_command command,
1661 struct commit *commit,
1662 struct replay_opts *opts)
6e98de72
JS
1663{
1664 struct strbuf buf = STRBUF_INIT;
e12a7ef5 1665 int res;
6e98de72
JS
1666 const char *message, *body;
1667
e12a7ef5 1668 if (opts->current_fixup_count > 0) {
6e98de72 1669 struct strbuf header = STRBUF_INIT;
e12a7ef5 1670 char *eol;
6e98de72 1671
e12a7ef5 1672 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1673 return error(_("could not read '%s'"),
1674 rebase_path_squash_msg());
1675
e12a7ef5
JS
1676 eol = buf.buf[0] != comment_line_char ?
1677 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1678
1679 strbuf_addf(&header, "%c ", comment_line_char);
e12a7ef5
JS
1680 strbuf_addf(&header, _("This is a combination of %d commits."),
1681 opts->current_fixup_count + 2);
6e98de72
JS
1682 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1683 strbuf_release(&header);
1684 } else {
33d66df3 1685 struct object_id head;
6e98de72
JS
1686 struct commit *head_commit;
1687 const char *head_message, *body;
1688
33d66df3 1689 if (get_oid("HEAD", &head))
6e98de72 1690 return error(_("need a HEAD to fixup"));
005af339 1691 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72
JS
1692 return error(_("could not read HEAD"));
1693 if (!(head_message = get_commit_buffer(head_commit, NULL)))
1694 return error(_("could not read HEAD's commit message"));
1695
1696 find_commit_subject(head_message, &body);
1697 if (write_message(body, strlen(body),
1698 rebase_path_fixup_msg(), 0)) {
1699 unuse_commit_buffer(head_commit, head_message);
1700 return error(_("cannot write '%s'"),
1701 rebase_path_fixup_msg());
1702 }
1703
6e98de72 1704 strbuf_addf(&buf, "%c ", comment_line_char);
e12a7ef5 1705 strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
6e98de72
JS
1706 strbuf_addf(&buf, "\n%c ", comment_line_char);
1707 strbuf_addstr(&buf, _("This is the 1st commit message:"));
1708 strbuf_addstr(&buf, "\n\n");
1709 strbuf_addstr(&buf, body);
1710
1711 unuse_commit_buffer(head_commit, head_message);
1712 }
1713
1714 if (!(message = get_commit_buffer(commit, NULL)))
1715 return error(_("could not read commit message of %s"),
1716 oid_to_hex(&commit->object.oid));
1717 find_commit_subject(message, &body);
1718
1719 if (command == TODO_SQUASH) {
1720 unlink(rebase_path_fixup_msg());
1721 strbuf_addf(&buf, "\n%c ", comment_line_char);
e12a7ef5 1722 strbuf_addf(&buf, _("This is the commit message #%d:"),
dd2e36eb 1723 ++opts->current_fixup_count + 1);
6e98de72
JS
1724 strbuf_addstr(&buf, "\n\n");
1725 strbuf_addstr(&buf, body);
1726 } else if (command == TODO_FIXUP) {
1727 strbuf_addf(&buf, "\n%c ", comment_line_char);
1728 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
dd2e36eb 1729 ++opts->current_fixup_count + 1);
6e98de72
JS
1730 strbuf_addstr(&buf, "\n\n");
1731 strbuf_add_commented_lines(&buf, body, strlen(body));
1732 } else
1733 return error(_("unknown command: %d"), command);
1734 unuse_commit_buffer(commit, message);
1735
1736 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
1737 strbuf_release(&buf);
e12a7ef5
JS
1738
1739 if (!res) {
1740 strbuf_addf(&opts->current_fixups, "%s%s %s",
1741 opts->current_fixups.len ? "\n" : "",
1742 command_to_string(command),
1743 oid_to_hex(&commit->object.oid));
1744 res = write_message(opts->current_fixups.buf,
1745 opts->current_fixups.len,
1746 rebase_path_current_fixups(), 0);
1747 }
1748
6e98de72
JS
1749 return res;
1750}
1751
3b335762
NTND
1752static void flush_rewritten_pending(void)
1753{
25cb8df9 1754 struct strbuf buf = STRBUF_INIT;
092bbcdf 1755 struct object_id newoid;
25cb8df9
JS
1756 FILE *out;
1757
092bbcdf 1758 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1759 !get_oid("HEAD", &newoid) &&
e9d983f1 1760 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
1761 char *bol = buf.buf, *eol;
1762
1763 while (*bol) {
1764 eol = strchrnul(bol, '\n');
1765 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 1766 bol, oid_to_hex(&newoid));
25cb8df9
JS
1767 if (!*eol)
1768 break;
1769 bol = eol + 1;
1770 }
1771 fclose(out);
1772 unlink(rebase_path_rewritten_pending());
1773 }
1774 strbuf_release(&buf);
1775}
1776
1777static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
1778 enum todo_command next_command)
1779{
e9d983f1 1780 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
1781
1782 if (!out)
1783 return;
1784
1785 fprintf(out, "%s\n", oid_to_hex(oid));
1786 fclose(out);
1787
1788 if (!is_fixup(next_command))
1789 flush_rewritten_pending();
1790}
1791
f11c9580
NTND
1792static int do_pick_commit(struct repository *r,
1793 enum todo_command command,
1794 struct commit *commit,
1795 struct replay_opts *opts,
1796 int final_fixup)
043a4492 1797{
789b3eff 1798 unsigned int flags = opts->edit ? EDIT_MSG : 0;
f11c9580 1799 const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
ace976b2 1800 struct object_id head;
043a4492
RR
1801 struct commit *base, *next, *parent;
1802 const char *base_label, *next_label;
356ee465 1803 char *author = NULL;
d74a4e57 1804 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 1805 struct strbuf msgbuf = STRBUF_INIT;
789b3eff 1806 int res, unborn = 0, allow;
043a4492
RR
1807
1808 if (opts->no_commit) {
1809 /*
1810 * We do not intend to commit immediately. We just want to
1811 * merge the differences in, so let's compute the tree
1812 * that represents the "current" state for merge-recursive
1813 * to work on.
1814 */
f11c9580 1815 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 1816 return error(_("your index file is unmerged."));
043a4492 1817 } else {
ace976b2 1818 unborn = get_oid("HEAD", &head);
d87d48b2
JS
1819 /* Do we want to generate a root commit? */
1820 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 1821 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
1822 if (is_fixup(command))
1823 return error(_("cannot fixup root commit"));
1824 flags |= CREATE_ROOT_COMMIT;
1825 unborn = 1;
1826 } else if (unborn)
eb0ccfd7 1827 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 1828 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 1829 NULL, 0))
e1ff0a32 1830 return error_dirty_index(r, opts);
043a4492 1831 }
f11c9580 1832 discard_index(r->index);
043a4492 1833
637666c8 1834 if (!commit->parents)
043a4492 1835 parent = NULL;
043a4492
RR
1836 else if (commit->parents->next) {
1837 /* Reverting or cherry-picking a merge commit */
1838 int cnt;
1839 struct commit_list *p;
1840
1841 if (!opts->mainline)
93b3df6f 1842 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 1843 oid_to_hex(&commit->object.oid));
043a4492
RR
1844
1845 for (cnt = 1, p = commit->parents;
1846 cnt != opts->mainline && p;
1847 cnt++)
1848 p = p->next;
1849 if (cnt != opts->mainline || !p)
93b3df6f 1850 return error(_("commit %s does not have parent %d"),
f2fd0760 1851 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 1852 parent = p->item;
37897bfc
SO
1853 } else if (1 < opts->mainline)
1854 /*
1855 * Non-first parent explicitly specified as mainline for
1856 * non-merge commit
1857 */
1858 return error(_("commit %s does not have parent %d"),
1859 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
1860 else
1861 parent = commit->parents->item;
1862
bcbb68be
JS
1863 if (get_message(commit, &msg) != 0)
1864 return error(_("cannot get commit message for %s"),
1865 oid_to_hex(&commit->object.oid));
1866
6e98de72 1867 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 1868 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
1869 (!parent && unborn))) {
1870 if (is_rebase_i(opts))
1871 write_author_script(msg.message);
f11c9580 1872 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
1873 opts);
1874 if (res || command != TODO_REWORD)
1875 goto leave;
5f8f9277 1876 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
bcbb68be
JS
1877 msg_file = NULL;
1878 goto fast_forward_edit;
1879 }
043a4492 1880 if (parent && parse_commit(parent) < 0)
004fefa7
JS
1881 /* TRANSLATORS: The first %s will be a "todo" command like
1882 "revert" or "pick", the second %s a SHA1. */
043a4492 1883 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
1884 command_to_string(command),
1885 oid_to_hex(&parent->object.oid));
043a4492 1886
043a4492
RR
1887 /*
1888 * "commit" is an existing commit. We would want to apply
1889 * the difference it introduces since its first parent "prev"
1890 * on top of the current HEAD if we are cherry-pick. Or the
1891 * reverse of it if we are revert.
1892 */
1893
004fefa7 1894 if (command == TODO_REVERT) {
043a4492
RR
1895 base = commit;
1896 base_label = msg.label;
1897 next = parent;
1898 next_label = msg.parent_label;
1899 strbuf_addstr(&msgbuf, "Revert \"");
1900 strbuf_addstr(&msgbuf, msg.subject);
1901 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
f2fd0760 1902 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1903
1904 if (commit->parents && commit->parents->next) {
1905 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
f2fd0760 1906 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
043a4492
RR
1907 }
1908 strbuf_addstr(&msgbuf, ".\n");
1909 } else {
1910 const char *p;
1911
1912 base = parent;
1913 base_label = msg.parent_label;
1914 next = commit;
1915 next_label = msg.label;
1916
23aa5142
JS
1917 /* Append the commit log message to msgbuf. */
1918 if (find_commit_subject(msg.message, &p))
1919 strbuf_addstr(&msgbuf, p);
043a4492
RR
1920
1921 if (opts->record_origin) {
44dc738a 1922 strbuf_complete_line(&msgbuf);
bab4d109 1923 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 1924 strbuf_addch(&msgbuf, '\n');
cd650a4e 1925 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 1926 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
1927 strbuf_addstr(&msgbuf, ")\n");
1928 }
356ee465
PW
1929 if (!is_fixup(command))
1930 author = get_author(msg.message);
043a4492
RR
1931 }
1932
04efc8b5 1933 if (command == TODO_REWORD)
b92ff6e8 1934 flags |= EDIT_MSG | VERIFY_MSG;
04efc8b5 1935 else if (is_fixup(command)) {
005af339 1936 if (update_squash_messages(r, command, commit, opts))
6e98de72 1937 return -1;
789b3eff 1938 flags |= AMEND_MSG;
6e98de72
JS
1939 if (!final_fixup)
1940 msg_file = rebase_path_squash_msg();
1941 else if (file_exists(rebase_path_fixup_msg())) {
789b3eff 1942 flags |= CLEANUP_MSG;
6e98de72
JS
1943 msg_file = rebase_path_fixup_msg();
1944 } else {
f11c9580 1945 const char *dest = git_path_squash_msg(r);
6e98de72
JS
1946 unlink(dest);
1947 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1948 return error(_("could not rename '%s' to '%s'"),
1949 rebase_path_squash_msg(), dest);
f11c9580 1950 unlink(git_path_merge_msg(r));
6e98de72 1951 msg_file = dest;
789b3eff 1952 flags |= EDIT_MSG;
6e98de72
JS
1953 }
1954 }
1955
a852ec7f 1956 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
1957 append_signoff(&msgbuf, 0, 0);
1958
0473f28a
JS
1959 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1960 res = -1;
1961 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
f11c9580 1962 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 1963 &head, &msgbuf, opts);
f241ff0d 1964 if (res < 0)
19517fb9
SB
1965 goto leave;
1966
75871495 1967 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 1968 git_path_merge_msg(r), 0);
043a4492
RR
1969 } else {
1970 struct commit_list *common = NULL;
1971 struct commit_list *remotes = NULL;
1972
75871495 1973 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 1974 git_path_merge_msg(r), 0);
043a4492
RR
1975
1976 commit_list_insert(base, &common);
1977 commit_list_insert(next, &remotes);
f11c9580 1978 res |= try_merge_command(r, opts->strategy,
03a4e260 1979 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 1980 common, oid_to_hex(&head), remotes);
043a4492
RR
1981 free_commit_list(common);
1982 free_commit_list(remotes);
1983 }
452202c7 1984 strbuf_release(&msgbuf);
043a4492
RR
1985
1986 /*
1987 * If the merge was clean or if it failed due to conflict, we write
1988 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1989 * However, if the merge did not even start, then we don't want to
1990 * write it at all.
1991 */
004fefa7 1992 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
ae077771 1993 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 1994 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1995 res = -1;
004fefa7 1996 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 1997 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 1998 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 1999 res = -1;
043a4492
RR
2000
2001 if (res) {
004fefa7 2002 error(command == TODO_REVERT
043a4492
RR
2003 ? _("could not revert %s... %s")
2004 : _("could not apply %s... %s"),
39755964 2005 short_commit_name(commit), msg.subject);
005af339 2006 print_advice(r, res == 1, opts);
f11c9580 2007 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 2008 goto leave;
043a4492
RR
2009 }
2010
f11c9580 2011 allow = allow_empty(r, opts, commit);
706728a3
FC
2012 if (allow < 0) {
2013 res = allow;
2014 goto leave;
789b3eff
JS
2015 } else if (allow)
2016 flags |= ALLOW_EMPTY;
356ee465 2017 if (!opts->no_commit) {
bcbb68be 2018fast_forward_edit:
356ee465 2019 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
f11c9580 2020 res = do_commit(r, msg_file, author, opts, flags);
356ee465
PW
2021 else
2022 res = error(_("unable to parse commit author"));
2023 }
6e98de72
JS
2024
2025 if (!res && final_fixup) {
2026 unlink(rebase_path_fixup_msg());
2027 unlink(rebase_path_squash_msg());
e12a7ef5
JS
2028 unlink(rebase_path_current_fixups());
2029 strbuf_reset(&opts->current_fixups);
2030 opts->current_fixup_count = 0;
6e98de72 2031 }
c8d1351d
FC
2032
2033leave:
d74a4e57 2034 free_message(commit, &msg);
356ee465 2035 free(author);
1e41229d 2036 update_abort_safety_file();
043a4492
RR
2037
2038 return res;
2039}
2040
c3e8618c 2041static int prepare_revs(struct replay_opts *opts)
043a4492 2042{
a73e22e9
MZ
2043 /*
2044 * picking (but not reverting) ranges (but not individual revisions)
2045 * should be done in reverse
2046 */
2047 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2048 opts->revs->reverse ^= 1;
2049
2050 if (prepare_revision_walk(opts->revs))
c3e8618c 2051 return error(_("revision walk setup failed"));
043a4492 2052
c3e8618c 2053 return 0;
043a4492
RR
2054}
2055
f11c9580
NTND
2056static int read_and_refresh_cache(struct repository *r,
2057 struct replay_opts *opts)
043a4492 2058{
14bca6c6 2059 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2060 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2061 if (repo_read_index(r) < 0) {
49fb937e 2062 rollback_lock_file(&index_lock);
0d9c6dc9 2063 return error(_("git %s: failed to read the index"),
c28cbc5e 2064 _(action_name(opts)));
49fb937e 2065 }
f11c9580 2066 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
61000814 2067 if (index_fd >= 0) {
f11c9580 2068 if (write_locked_index(r->index, &index_lock,
61000814 2069 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2070 return error(_("git %s: failed to refresh the index"),
c28cbc5e 2071 _(action_name(opts)));
49fb937e 2072 }
043a4492 2073 }
0d9c6dc9 2074 return 0;
043a4492
RR
2075}
2076
4c68e7dd
JS
2077enum todo_item_flags {
2078 TODO_EDIT_MERGE_MSG = 1
2079};
2080
004fefa7
JS
2081struct todo_item {
2082 enum todo_command command;
2083 struct commit *commit;
4c68e7dd 2084 unsigned int flags;
c22f7dfb
JS
2085 const char *arg;
2086 int arg_len;
004fefa7
JS
2087 size_t offset_in_buf;
2088};
2089
2090struct todo_list {
2091 struct strbuf buf;
2092 struct todo_item *items;
2093 int nr, alloc, current;
968492e4 2094 int done_nr, total_nr;
54fd3243 2095 struct stat_data stat;
004fefa7
JS
2096};
2097
2098#define TODO_LIST_INIT { STRBUF_INIT }
2099
2100static void todo_list_release(struct todo_list *todo_list)
043a4492 2101{
004fefa7 2102 strbuf_release(&todo_list->buf);
6a83d902 2103 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2104 todo_list->nr = todo_list->alloc = 0;
2105}
043a4492 2106
004fefa7
JS
2107static struct todo_item *append_new_todo(struct todo_list *todo_list)
2108{
2109 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2110 return todo_list->items + todo_list->nr++;
043a4492
RR
2111}
2112
005af339
NTND
2113static int parse_insn_line(struct repository *r, struct todo_item *item,
2114 const char *bol, char *eol)
043a4492 2115{
1e43ed98 2116 struct object_id commit_oid;
043a4492 2117 char *end_of_object_name;
004fefa7
JS
2118 int i, saved, status, padding;
2119
4c68e7dd
JS
2120 item->flags = 0;
2121
8f8550b3
JS
2122 /* left-trim */
2123 bol += strspn(bol, " \t");
2124
25c43667 2125 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2126 item->command = TODO_COMMENT;
25c43667
JS
2127 item->commit = NULL;
2128 item->arg = bol;
2129 item->arg_len = eol - bol;
2130 return 0;
2131 }
2132
ac191470 2133 for (i = 0; i < TODO_COMMENT; i++)
414697a9
JS
2134 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2135 item->command = i;
2136 break;
3a4a4cab
JS
2137 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2138 *bol == todo_command_info[i].c) {
414697a9 2139 bol++;
004fefa7
JS
2140 item->command = i;
2141 break;
2142 }
ac191470 2143 if (i >= TODO_COMMENT)
004fefa7 2144 return -1;
043a4492 2145
66afa24f
JS
2146 /* Eat up extra spaces/ tabs before object name */
2147 padding = strspn(bol, " \t");
2148 bol += padding;
2149
71f82465 2150 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2151 if (bol != eol)
2152 return error(_("%s does not accept arguments: '%s'"),
2153 command_to_string(item->command), bol);
25c43667
JS
2154 item->commit = NULL;
2155 item->arg = bol;
2156 item->arg_len = eol - bol;
2157 return 0;
2158 }
2159
043a4492 2160 if (!padding)
66afa24f
JS
2161 return error(_("missing arguments for %s"),
2162 command_to_string(item->command));
043a4492 2163
9055e401
JS
2164 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2165 item->command == TODO_RESET) {
7dcbb3cb 2166 item->commit = NULL;
311af526
JS
2167 item->arg = bol;
2168 item->arg_len = (int)(eol - bol);
2169 return 0;
2170 }
2171
4c68e7dd
JS
2172 if (item->command == TODO_MERGE) {
2173 if (skip_prefix(bol, "-C", &bol))
2174 bol += strspn(bol, " \t");
2175 else if (skip_prefix(bol, "-c", &bol)) {
2176 bol += strspn(bol, " \t");
2177 item->flags |= TODO_EDIT_MERGE_MSG;
2178 } else {
2179 item->flags |= TODO_EDIT_MERGE_MSG;
2180 item->commit = NULL;
2181 item->arg = bol;
2182 item->arg_len = (int)(eol - bol);
2183 return 0;
2184 }
2185 }
2186
004fefa7 2187 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2188 saved = *end_of_object_name;
2189 *end_of_object_name = '\0';
1e43ed98 2190 status = get_oid(bol, &commit_oid);
043a4492
RR
2191 *end_of_object_name = saved;
2192
c22f7dfb
JS
2193 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2194 item->arg_len = (int)(eol - item->arg);
2195
043a4492 2196 if (status < 0)
8b637cda
JS
2197 return error(_("could not parse '%.*s'"),
2198 (int)(end_of_object_name - bol), bol);
043a4492 2199
005af339 2200 item->commit = lookup_commit_reference(r, &commit_oid);
004fefa7 2201 return !item->commit;
043a4492
RR
2202}
2203
005af339
NTND
2204static int parse_insn_buffer(struct repository *r, char *buf,
2205 struct todo_list *todo_list)
043a4492 2206{
004fefa7
JS
2207 struct todo_item *item;
2208 char *p = buf, *next_p;
6e98de72 2209 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2210
004fefa7 2211 for (i = 1; *p; i++, p = next_p) {
043a4492 2212 char *eol = strchrnul(p, '\n');
004fefa7
JS
2213
2214 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2215
6307041d
JS
2216 if (p != eol && eol[-1] == '\r')
2217 eol--; /* strip Carriage Return */
2218
004fefa7
JS
2219 item = append_new_todo(todo_list);
2220 item->offset_in_buf = p - todo_list->buf.buf;
005af339 2221 if (parse_insn_line(r, item, p, eol)) {
93b3df6f 2222 res = error(_("invalid line %d: %.*s"),
004fefa7 2223 i, (int)(eol - p), p);
6e98de72 2224 item->command = TODO_NOOP;
004fefa7 2225 }
6e98de72
JS
2226
2227 if (fixup_okay)
2228 ; /* do nothing */
2229 else if (is_fixup(item->command))
2230 return error(_("cannot '%s' without a previous commit"),
2231 command_to_string(item->command));
2232 else if (!is_noop(item->command))
2233 fixup_okay = 1;
043a4492 2234 }
52865279 2235
004fefa7 2236 return res;
043a4492
RR
2237}
2238
968492e4
JS
2239static int count_commands(struct todo_list *todo_list)
2240{
2241 int count = 0, i;
2242
2243 for (i = 0; i < todo_list->nr; i++)
2244 if (todo_list->items[i].command != TODO_COMMENT)
2245 count++;
2246
2247 return count;
2248}
2249
a01c2a5f
JS
2250static int get_item_line_offset(struct todo_list *todo_list, int index)
2251{
2252 return index < todo_list->nr ?
2253 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2254}
2255
2256static const char *get_item_line(struct todo_list *todo_list, int index)
2257{
2258 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2259}
2260
2261static int get_item_line_length(struct todo_list *todo_list, int index)
2262{
2263 return get_item_line_offset(todo_list, index + 1)
2264 - get_item_line_offset(todo_list, index);
2265}
2266
87805600
RS
2267static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2268{
2269 int fd;
2270 ssize_t len;
2271
2272 fd = open(path, O_RDONLY);
2273 if (fd < 0)
2274 return error_errno(_("could not open '%s'"), path);
2275 len = strbuf_read(sb, fd, 0);
2276 close(fd);
2277 if (len < 0)
2278 return error(_("could not read '%s'."), path);
2279 return len;
2280}
2281
005af339
NTND
2282static int read_populate_todo(struct repository *r,
2283 struct todo_list *todo_list,
2284 struct replay_opts *opts)
043a4492 2285{
54fd3243 2286 struct stat st;
c0246501 2287 const char *todo_file = get_todo_path(opts);
87805600 2288 int res;
043a4492 2289
004fefa7 2290 strbuf_reset(&todo_list->buf);
87805600
RS
2291 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2292 return -1;
043a4492 2293
54fd3243
SH
2294 res = stat(todo_file, &st);
2295 if (res)
2296 return error(_("could not stat '%s'"), todo_file);
2297 fill_stat_data(&todo_list->stat, &st);
2298
005af339 2299 res = parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2300 if (res) {
2301 if (is_rebase_i(opts))
2302 return error(_("please fix this using "
2303 "'git rebase --edit-todo'."));
93b3df6f 2304 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2305 }
2eeaf1b3 2306
52865279
JS
2307 if (!todo_list->nr &&
2308 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2309 return error(_("no commits parsed."));
2310
2eeaf1b3 2311 if (!is_rebase_i(opts)) {
004fefa7
JS
2312 enum todo_command valid =
2313 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2314 int i;
2315
2316 for (i = 0; i < todo_list->nr; i++)
2317 if (valid == todo_list->items[i].command)
2318 continue;
2319 else if (valid == TODO_PICK)
93b3df6f 2320 return error(_("cannot cherry-pick during a revert."));
004fefa7 2321 else
93b3df6f 2322 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2323 }
2324
968492e4
JS
2325 if (is_rebase_i(opts)) {
2326 struct todo_list done = TODO_LIST_INIT;
e9d983f1 2327 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
968492e4
JS
2328
2329 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
005af339 2330 !parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2331 todo_list->done_nr = count_commands(&done);
2332 else
2333 todo_list->done_nr = 0;
2334
2335 todo_list->total_nr = todo_list->done_nr
2336 + count_commands(todo_list);
968492e4 2337 todo_list_release(&done);
ef80069a
JS
2338
2339 if (f) {
2340 fprintf(f, "%d\n", todo_list->total_nr);
2341 fclose(f);
2342 }
968492e4
JS
2343 }
2344
0ae42a03 2345 return 0;
043a4492
RR
2346}
2347
03a4e260
JS
2348static int git_config_string_dup(char **dest,
2349 const char *var, const char *value)
2350{
2351 if (!value)
2352 return config_error_nonbool(var);
2353 free(*dest);
2354 *dest = xstrdup(value);
2355 return 0;
2356}
2357
043a4492
RR
2358static int populate_opts_cb(const char *key, const char *value, void *data)
2359{
2360 struct replay_opts *opts = data;
2361 int error_flag = 1;
2362
2363 if (!value)
2364 error_flag = 0;
2365 else if (!strcmp(key, "options.no-commit"))
2366 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2367 else if (!strcmp(key, "options.edit"))
2368 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2369 else if (!strcmp(key, "options.signoff"))
2370 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2371 else if (!strcmp(key, "options.record-origin"))
2372 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2373 else if (!strcmp(key, "options.allow-ff"))
2374 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2375 else if (!strcmp(key, "options.mainline"))
2376 opts->mainline = git_config_int(key, value);
2377 else if (!strcmp(key, "options.strategy"))
03a4e260 2378 git_config_string_dup(&opts->strategy, key, value);
3253553e 2379 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2380 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2381 else if (!strcmp(key, "options.strategy-option")) {
2382 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2383 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2384 } else if (!strcmp(key, "options.allow-rerere-auto"))
2385 opts->allow_rerere_auto =
2386 git_config_bool_or_int(key, value, &error_flag) ?
2387 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2388 else if (!strcmp(key, "options.default-msg-cleanup")) {
2389 opts->explicit_cleanup = 1;
2390 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2391 } else
93b3df6f 2392 return error(_("invalid key: %s"), key);
043a4492
RR
2393
2394 if (!error_flag)
93b3df6f 2395 return error(_("invalid value for %s: %s"), key, value);
043a4492
RR
2396
2397 return 0;
2398}
2399
65850686 2400void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2401{
2402 int i;
65850686 2403 char *strategy_opts_string = raw_opts;
ca6c6b45 2404
0060041d
EN
2405 if (*strategy_opts_string == ' ')
2406 strategy_opts_string++;
65850686 2407
0060041d
EN
2408 opts->xopts_nr = split_cmdline(strategy_opts_string,
2409 (const char ***)&opts->xopts);
ca6c6b45
JS
2410 for (i = 0; i < opts->xopts_nr; i++) {
2411 const char *arg = opts->xopts[i];
2412
2413 skip_prefix(arg, "--", &arg);
2414 opts->xopts[i] = xstrdup(arg);
2415 }
2416}
2417
65850686
AG
2418static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2419{
2420 strbuf_reset(buf);
2421 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2422 return;
2423 opts->strategy = strbuf_detach(buf, NULL);
2424 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2425 return;
2426
2427 parse_strategy_opts(opts, buf->buf);
2428}
2429
5adf9bdc 2430static int read_populate_opts(struct replay_opts *opts)
043a4492 2431{
a1c75762
JS
2432 if (is_rebase_i(opts)) {
2433 struct strbuf buf = STRBUF_INIT;
2434
2435 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2436 if (!starts_with(buf.buf, "-S"))
2437 strbuf_reset(&buf);
2438 else {
2439 free(opts->gpg_sign);
2440 opts->gpg_sign = xstrdup(buf.buf + 2);
2441 }
9b6d7a62
PW
2442 strbuf_reset(&buf);
2443 }
2444
2445 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2446 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2447 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2448 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2449 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2450 strbuf_reset(&buf);
a1c75762 2451 }
a1c75762 2452
556907f1
JS
2453 if (file_exists(rebase_path_verbose()))
2454 opts->verbose = 1;
2455
899b49c4
EN
2456 if (file_exists(rebase_path_quiet()))
2457 opts->quiet = 1;
2458
a852ec7f
PW
2459 if (file_exists(rebase_path_signoff())) {
2460 opts->allow_ff = 0;
2461 opts->signoff = 1;
2462 }
2463
d421afa0
JS
2464 if (file_exists(rebase_path_reschedule_failed_exec()))
2465 opts->reschedule_failed_exec = 1;
2466
ca6c6b45
JS
2467 read_strategy_opts(opts, &buf);
2468 strbuf_release(&buf);
2469
e12a7ef5
JS
2470 if (read_oneliner(&opts->current_fixups,
2471 rebase_path_current_fixups(), 1)) {
2472 const char *p = opts->current_fixups.buf;
2473 opts->current_fixup_count = 1;
2474 while ((p = strchr(p, '\n'))) {
2475 opts->current_fixup_count++;
2476 p++;
2477 }
2478 }
2479
d87d48b2
JS
2480 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2481 if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2482 return error(_("unusable squash-onto"));
2483 opts->have_squash_onto = 1;
2484 }
2485
b5a67045 2486 return 0;
a1c75762 2487 }
b5a67045 2488
f932729c 2489 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
2490 return 0;
2491 /*
2492 * The function git_parse_source(), called from git_config_from_file(),
2493 * may die() in case of a syntactically incorrect file. We do not care
2494 * about this case, though, because we wrote that file ourselves, so we
2495 * are pretty certain that it is syntactically correct.
2496 */
5adf9bdc 2497 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 2498 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
2499 git_path_opts_file());
2500 return 0;
043a4492
RR
2501}
2502
65850686
AG
2503static void write_strategy_opts(struct replay_opts *opts)
2504{
2505 int i;
2506 struct strbuf buf = STRBUF_INIT;
2507
2508 for (i = 0; i < opts->xopts_nr; ++i)
2509 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2510
2511 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2512 strbuf_release(&buf);
2513}
2514
2515int write_basic_state(struct replay_opts *opts, const char *head_name,
2516 const char *onto, const char *orig_head)
2517{
2518 const char *quiet = getenv("GIT_QUIET");
2519
2520 if (head_name)
2521 write_file(rebase_path_head_name(), "%s\n", head_name);
2522 if (onto)
2523 write_file(rebase_path_onto(), "%s\n", onto);
2524 if (orig_head)
2525 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2526
2527 if (quiet)
2528 write_file(rebase_path_quiet(), "%s\n", quiet);
65850686 2529 if (opts->verbose)
4af51741 2530 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
2531 if (opts->strategy)
2532 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2533 if (opts->xopts_nr > 0)
2534 write_strategy_opts(opts);
2535
2536 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2537 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2538 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2539 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2540
2541 if (opts->gpg_sign)
2542 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2543 if (opts->signoff)
2544 write_file(rebase_path_signoff(), "--signoff\n");
d421afa0
JS
2545 if (opts->reschedule_failed_exec)
2546 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
65850686
AG
2547
2548 return 0;
2549}
2550
004fefa7 2551static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
2552 struct replay_opts *opts)
2553{
004fefa7
JS
2554 enum todo_command command = opts->action == REPLAY_PICK ?
2555 TODO_PICK : TODO_REVERT;
414697a9 2556 const char *command_string = todo_command_info[command].str;
043a4492 2557 struct commit *commit;
043a4492 2558
34b0528b
JS
2559 if (prepare_revs(opts))
2560 return -1;
043a4492 2561
004fefa7
JS
2562 while ((commit = get_revision(opts->revs))) {
2563 struct todo_item *item = append_new_todo(todo_list);
2564 const char *commit_buffer = get_commit_buffer(commit, NULL);
2565 const char *subject;
2566 int subject_len;
2567
2568 item->command = command;
2569 item->commit = commit;
c22f7dfb
JS
2570 item->arg = NULL;
2571 item->arg_len = 0;
004fefa7
JS
2572 item->offset_in_buf = todo_list->buf.len;
2573 subject_len = find_commit_subject(commit_buffer, &subject);
2574 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2575 short_commit_name(commit), subject_len, subject);
2576 unuse_commit_buffer(commit, commit_buffer);
2577 }
8530c739
JK
2578
2579 if (!todo_list->nr)
2580 return error(_("empty commit set passed"));
2581
34b0528b 2582 return 0;
043a4492
RR
2583}
2584
2585static int create_seq_dir(void)
2586{
f932729c 2587 if (file_exists(git_path_seq_dir())) {
043a4492
RR
2588 error(_("a cherry-pick or revert is already in progress"));
2589 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2590 return -1;
a70d8f80 2591 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 2592 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 2593 git_path_seq_dir());
043a4492
RR
2594 return 0;
2595}
2596
311fd397 2597static int save_head(const char *head)
043a4492 2598{
14bca6c6 2599 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
2600 struct strbuf buf = STRBUF_INIT;
2601 int fd;
ed3f9a12 2602 ssize_t written;
043a4492 2603
311fd397 2604 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 2605 if (fd < 0)
93b3df6f 2606 return error_errno(_("could not lock HEAD"));
043a4492 2607 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
2608 written = write_in_full(fd, buf.buf, buf.len);
2609 strbuf_release(&buf);
2610 if (written < 0) {
bf5c0571 2611 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 2612 rollback_lock_file(&head_lock);
bf5c0571 2613 return -1;
311fd397 2614 }
350292a1
2615 if (commit_lock_file(&head_lock) < 0)
2616 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 2617 return 0;
043a4492
RR
2618}
2619
1e41229d
SB
2620static int rollback_is_safe(void)
2621{
2622 struct strbuf sb = STRBUF_INIT;
2623 struct object_id expected_head, actual_head;
2624
2625 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2626 strbuf_trim(&sb);
2627 if (get_oid_hex(sb.buf, &expected_head)) {
2628 strbuf_release(&sb);
2629 die(_("could not parse %s"), git_path_abort_safety_file());
2630 }
2631 strbuf_release(&sb);
2632 }
2633 else if (errno == ENOENT)
2634 oidclr(&expected_head);
2635 else
2636 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2637
2638 if (get_oid("HEAD", &actual_head))
2639 oidclr(&actual_head);
2640
4a7e27e9 2641 return oideq(&actual_head, &expected_head);
1e41229d
SB
2642}
2643
092bbcdf 2644static int reset_for_rollback(const struct object_id *oid)
043a4492
RR
2645{
2646 const char *argv[4]; /* reset --merge <arg> + NULL */
1e41229d 2647
043a4492
RR
2648 argv[0] = "reset";
2649 argv[1] = "--merge";
092bbcdf 2650 argv[2] = oid_to_hex(oid);
043a4492
RR
2651 argv[3] = NULL;
2652 return run_command_v_opt(argv, RUN_GIT_CMD);
2653}
2654
005af339 2655static int rollback_single_pick(struct repository *r)
043a4492 2656{
092bbcdf 2657 struct object_id head_oid;
043a4492 2658
005af339
NTND
2659 if (!file_exists(git_path_cherry_pick_head(r)) &&
2660 !file_exists(git_path_revert_head(r)))
043a4492 2661 return error(_("no cherry-pick or revert in progress"));
34c290a6 2662 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 2663 return error(_("cannot resolve HEAD"));
092bbcdf 2664 if (is_null_oid(&head_oid))
043a4492 2665 return error(_("cannot abort from a branch yet to be born"));
092bbcdf 2666 return reset_for_rollback(&head_oid);
043a4492
RR
2667}
2668
005af339 2669int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 2670{
043a4492 2671 FILE *f;
092bbcdf 2672 struct object_id oid;
043a4492 2673 struct strbuf buf = STRBUF_INIT;
092bbcdf 2674 const char *p;
043a4492 2675
f932729c 2676 f = fopen(git_path_head_file(), "r");
043a4492
RR
2677 if (!f && errno == ENOENT) {
2678 /*
2679 * There is no multiple-cherry-pick in progress.
2680 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2681 * a single-cherry-pick in progress, abort that.
2682 */
005af339 2683 return rollback_single_pick(r);
043a4492
RR
2684 }
2685 if (!f)
f7ed1953 2686 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 2687 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 2688 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 2689 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
2690 fclose(f);
2691 goto fail;
2692 }
2693 fclose(f);
092bbcdf 2694 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 2695 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 2696 git_path_head_file());
043a4492
RR
2697 goto fail;
2698 }
092bbcdf 2699 if (is_null_oid(&oid)) {
0f974e21
MG
2700 error(_("cannot abort from a branch yet to be born"));
2701 goto fail;
2702 }
1e41229d
SB
2703
2704 if (!rollback_is_safe()) {
2705 /* Do not error, just do not rollback */
2706 warning(_("You seem to have moved HEAD. "
2707 "Not rewinding, check your HEAD!"));
2708 } else
092bbcdf 2709 if (reset_for_rollback(&oid))
043a4492 2710 goto fail;
043a4492 2711 strbuf_release(&buf);
2863584f 2712 return sequencer_remove_state(opts);
043a4492
RR
2713fail:
2714 strbuf_release(&buf);
2715 return -1;
2716}
2717
004fefa7 2718static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2719{
14bca6c6 2720 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
2721 const char *todo_path = get_todo_path(opts);
2722 int next = todo_list->current, offset, fd;
043a4492 2723
84583957
JS
2724 /*
2725 * rebase -i writes "git-rebase-todo" without the currently executing
2726 * command, appending it to "done" instead.
2727 */
2728 if (is_rebase_i(opts))
2729 next++;
2730
004fefa7 2731 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 2732 if (fd < 0)
93b3df6f 2733 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 2734 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
2735 if (write_in_full(fd, todo_list->buf.buf + offset,
2736 todo_list->buf.len - offset) < 0)
93b3df6f 2737 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 2738 if (commit_lock_file(&todo_lock) < 0)
350292a1 2739 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 2740
a01c2a5f
JS
2741 if (is_rebase_i(opts) && next > 0) {
2742 const char *done = rebase_path_done();
2743 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2744 int ret = 0;
1df6df0c 2745
a01c2a5f
JS
2746 if (fd < 0)
2747 return 0;
2748 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2749 get_item_line_length(todo_list, next - 1))
2750 < 0)
2751 ret = error_errno(_("could not write to '%s'"), done);
2752 if (close(fd) < 0)
2753 ret = error_errno(_("failed to finalize '%s'"), done);
2754 return ret;
1df6df0c 2755 }
221675de 2756 return 0;
043a4492
RR
2757}
2758
88d5a271 2759static int save_opts(struct replay_opts *opts)
043a4492 2760{
f932729c 2761 const char *opts_file = git_path_opts_file();
88d5a271 2762 int res = 0;
043a4492
RR
2763
2764 if (opts->no_commit)
88d5a271 2765 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
043a4492 2766 if (opts->edit)
88d5a271 2767 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
043a4492 2768 if (opts->signoff)
88d5a271 2769 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
043a4492 2770 if (opts->record_origin)
88d5a271 2771 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
043a4492 2772 if (opts->allow_ff)
88d5a271 2773 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
043a4492
RR
2774 if (opts->mainline) {
2775 struct strbuf buf = STRBUF_INIT;
2776 strbuf_addf(&buf, "%d", opts->mainline);
88d5a271 2777 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
043a4492
RR
2778 strbuf_release(&buf);
2779 }
2780 if (opts->strategy)
88d5a271 2781 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
3253553e 2782 if (opts->gpg_sign)
88d5a271 2783 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
043a4492
RR
2784 if (opts->xopts) {
2785 int i;
2786 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 2787 res |= git_config_set_multivar_in_file_gently(opts_file,
043a4492
RR
2788 "options.strategy-option",
2789 opts->xopts[i], "^$", 0);
2790 }
8d8cb4b0
PW
2791 if (opts->allow_rerere_auto)
2792 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2793 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2794 "true" : "false");
dc42e9a8
PW
2795
2796 if (opts->explicit_cleanup)
2797 res |= git_config_set_in_file_gently(opts_file,
2798 "options.default-msg-cleanup",
2799 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 2800 return res;
043a4492
RR
2801}
2802
f11c9580
NTND
2803static int make_patch(struct repository *r,
2804 struct commit *commit,
2805 struct replay_opts *opts)
56dc3ab0
JS
2806{
2807 struct strbuf buf = STRBUF_INIT;
2808 struct rev_info log_tree_opt;
2809 const char *subject, *p;
2810 int res = 0;
2811
2812 p = short_commit_name(commit);
2813 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2814 return -1;
fbd7a232
NTND
2815 if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2816 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2817 res |= error(_("could not update %s"), "REBASE_HEAD");
56dc3ab0
JS
2818
2819 strbuf_addf(&buf, "%s/patch", get_dir(opts));
2820 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 2821 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
2822 log_tree_opt.abbrev = 0;
2823 log_tree_opt.diff = 1;
2824 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2825 log_tree_opt.disable_stdin = 1;
2826 log_tree_opt.no_commit_id = 1;
2827 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2828 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2829 if (!log_tree_opt.diffopt.file)
2830 res |= error_errno(_("could not open '%s'"), buf.buf);
2831 else {
2832 res |= log_tree_commit(&log_tree_opt, commit);
2833 fclose(log_tree_opt.diffopt.file);
2834 }
2835 strbuf_reset(&buf);
2836
2837 strbuf_addf(&buf, "%s/message", get_dir(opts));
2838 if (!file_exists(buf.buf)) {
2839 const char *commit_buffer = get_commit_buffer(commit, NULL);
2840 find_commit_subject(commit_buffer, &subject);
2841 res |= write_message(subject, strlen(subject), buf.buf, 1);
2842 unuse_commit_buffer(commit, commit_buffer);
2843 }
2844 strbuf_release(&buf);
2845
2846 return res;
2847}
2848
2849static int intend_to_amend(void)
2850{
092bbcdf 2851 struct object_id head;
56dc3ab0
JS
2852 char *p;
2853
092bbcdf 2854 if (get_oid("HEAD", &head))
56dc3ab0
JS
2855 return error(_("cannot read HEAD"));
2856
092bbcdf 2857 p = oid_to_hex(&head);
56dc3ab0
JS
2858 return write_message(p, strlen(p), rebase_path_amend(), 1);
2859}
2860
f11c9580
NTND
2861static int error_with_patch(struct repository *r,
2862 struct commit *commit,
2863 const char *subject, int subject_len,
2864 struct replay_opts *opts,
2865 int exit_code, int to_amend)
56dc3ab0 2866{
bc9238bb 2867 if (commit) {
f11c9580 2868 if (make_patch(r, commit, opts))
bc9238bb 2869 return -1;
5a5c5e95 2870 } else if (copy_file(rebase_path_message(),
f11c9580 2871 git_path_merge_msg(r), 0666))
bc9238bb 2872 return error(_("unable to copy '%s' to '%s'"),
f11c9580 2873 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
2874
2875 if (to_amend) {
2876 if (intend_to_amend())
2877 return -1;
2878
02127c63
NTND
2879 fprintf(stderr,
2880 _("You can amend the commit now, with\n"
2881 "\n"
2882 " git commit --amend %s\n"
2883 "\n"
2884 "Once you are satisfied with your changes, run\n"
2885 "\n"
2886 " git rebase --continue\n"),
2887 gpg_sign_opt_quoted(opts));
bc9238bb
PW
2888 } else if (exit_code) {
2889 if (commit)
5a5c5e95
JH
2890 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2891 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
2892 else
2893 /*
2894 * We don't have the hash of the parent so
2895 * just print the line from the todo file.
2896 */
5a5c5e95
JH
2897 fprintf_ln(stderr, _("Could not merge %.*s"),
2898 subject_len, subject);
bc9238bb 2899 }
56dc3ab0
JS
2900
2901 return exit_code;
2902}
2903
f11c9580
NTND
2904static int error_failed_squash(struct repository *r,
2905 struct commit *commit,
2906 struct replay_opts *opts,
2907 int subject_len,
2908 const char *subject)
6e98de72 2909{
e12a7ef5
JS
2910 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2911 return error(_("could not copy '%s' to '%s'"),
6e98de72 2912 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
2913 unlink(git_path_merge_msg(r));
2914 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 2915 return error(_("could not copy '%s' to '%s'"),
102de880 2916 rebase_path_message(),
f11c9580
NTND
2917 git_path_merge_msg(r));
2918 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
2919}
2920
f11c9580 2921static int do_exec(struct repository *r, const char *command_line)
311af526 2922{
09d7b6c6 2923 struct argv_array child_env = ARGV_ARRAY_INIT;
311af526
JS
2924 const char *child_argv[] = { NULL, NULL };
2925 int dirty, status;
2926
2927 fprintf(stderr, "Executing: %s\n", command_line);
2928 child_argv[0] = command_line;
09d7b6c6 2929 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
ab5e67d7 2930 argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2931 absolute_path(get_git_work_tree()));
09d7b6c6
JK
2932 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2933 child_env.argv);
311af526
JS
2934
2935 /* force re-reading of the cache */
e1ff0a32 2936 if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
311af526
JS
2937 return error(_("could not read index"));
2938
f11c9580 2939 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
2940
2941 if (status) {
2942 warning(_("execution failed: %s\n%s"
2943 "You can fix the problem, and then run\n"
2944 "\n"
2945 " git rebase --continue\n"
2946 "\n"),
2947 command_line,
2948 dirty ? N_("and made changes to the index and/or the "
2949 "working tree\n") : "");
2950 if (status == 127)
2951 /* command not found */
2952 status = 1;
2953 } else if (dirty) {
2954 warning(_("execution succeeded: %s\nbut "
2955 "left changes to the index and/or the working tree\n"
2956 "Commit or stash your changes, and then run\n"
2957 "\n"
2958 " git rebase --continue\n"
2959 "\n"), command_line);
2960 status = 1;
2961 }
2962
09d7b6c6
JK
2963 argv_array_clear(&child_env);
2964
311af526
JS
2965 return status;
2966}
2967
9055e401
JS
2968static int safe_append(const char *filename, const char *fmt, ...)
2969{
2970 va_list ap;
2971 struct lock_file lock = LOCK_INIT;
2972 int fd = hold_lock_file_for_update(&lock, filename,
2973 LOCK_REPORT_ON_ERROR);
2974 struct strbuf buf = STRBUF_INIT;
2975
2976 if (fd < 0)
2977 return -1;
2978
2979 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2980 error_errno(_("could not read '%s'"), filename);
2981 rollback_lock_file(&lock);
2982 return -1;
2983 }
2984 strbuf_complete(&buf, '\n');
2985 va_start(ap, fmt);
2986 strbuf_vaddf(&buf, fmt, ap);
2987 va_end(ap);
2988
2989 if (write_in_full(fd, buf.buf, buf.len) < 0) {
2990 error_errno(_("could not write to '%s'"), filename);
2991 strbuf_release(&buf);
2992 rollback_lock_file(&lock);
2993 return -1;
2994 }
2995 if (commit_lock_file(&lock) < 0) {
2996 strbuf_release(&buf);
2997 rollback_lock_file(&lock);
2998 return error(_("failed to finalize '%s'"), filename);
2999 }
3000
3001 strbuf_release(&buf);
3002 return 0;
3003}
3004
f11c9580 3005static int do_label(struct repository *r, const char *name, int len)
9055e401 3006{
f11c9580 3007 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3008 struct ref_transaction *transaction;
3009 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3010 struct strbuf msg = STRBUF_INIT;
3011 int ret = 0;
3012 struct object_id head_oid;
3013
3014 if (len == 1 && *name == '#')
02127c63 3015 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3016
3017 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3018 strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
3019
3020 transaction = ref_store_transaction_begin(refs, &err);
3021 if (!transaction) {
3022 error("%s", err.buf);
3023 ret = -1;
3024 } else if (get_oid("HEAD", &head_oid)) {
3025 error(_("could not read HEAD"));
3026 ret = -1;
3027 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3028 NULL, 0, msg.buf, &err) < 0 ||
3029 ref_transaction_commit(transaction, &err)) {
3030 error("%s", err.buf);
3031 ret = -1;
3032 }
3033 ref_transaction_free(transaction);
3034 strbuf_release(&err);
3035 strbuf_release(&msg);
3036
3037 if (!ret)
3038 ret = safe_append(rebase_path_refs_to_delete(),
3039 "%s\n", ref_name.buf);
3040 strbuf_release(&ref_name);
3041
3042 return ret;
3043}
3044
3045static const char *reflog_message(struct replay_opts *opts,
3046 const char *sub_action, const char *fmt, ...);
3047
f11c9580
NTND
3048static int do_reset(struct repository *r,
3049 const char *name, int len,
3050 struct replay_opts *opts)
9055e401
JS
3051{
3052 struct strbuf ref_name = STRBUF_INIT;
3053 struct object_id oid;
3054 struct lock_file lock = LOCK_INIT;
3055 struct tree_desc desc;
3056 struct tree *tree;
3057 struct unpack_trees_options unpack_tree_opts;
71571cd7 3058 int ret = 0;
9055e401 3059
3a95f31d 3060 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3061 return -1;
3062
ebddf393
JS
3063 if (len == 10 && !strncmp("[new root]", name, len)) {
3064 if (!opts->have_squash_onto) {
3065 const char *hex;
3066 if (commit_tree("", 0, the_hash_algo->empty_tree,
3067 NULL, &opts->squash_onto,
3068 NULL, NULL))
3069 return error(_("writing fake root commit"));
3070 opts->have_squash_onto = 1;
3071 hex = oid_to_hex(&opts->squash_onto);
3072 if (write_message(hex, strlen(hex),
3073 rebase_path_squash_onto(), 0))
3074 return error(_("writing squash-onto"));
3075 }
3076 oidcpy(&oid, &opts->squash_onto);
3077 } else {
71571cd7
3078 int i;
3079
ebddf393
JS
3080 /* Determine the length of the label */
3081 for (i = 0; i < len; i++)
3082 if (isspace(name[i]))
71571cd7
3083 break;
3084 len = i;
ebddf393
JS
3085
3086 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3087 if (get_oid(ref_name.buf, &oid) &&
3088 get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3089 error(_("could not read '%s'"), ref_name.buf);
3090 rollback_lock_file(&lock);
3091 strbuf_release(&ref_name);
3092 return -1;
3093 }
9055e401
JS
3094 }
3095
3096 memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3097 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3098 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3099 unpack_tree_opts.src_index = r->index;
3100 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3101 unpack_tree_opts.fn = oneway_merge;
3102 unpack_tree_opts.merge = 1;
3103 unpack_tree_opts.update = 1;
3104
e1ff0a32 3105 if (repo_read_index_unmerged(r)) {
9055e401
JS
3106 rollback_lock_file(&lock);
3107 strbuf_release(&ref_name);
3108 return error_resolve_conflict(_(action_name(opts)));
3109 }
3110
3111 if (!fill_tree_descriptor(&desc, &oid)) {
3112 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3113 rollback_lock_file(&lock);
3114 free((void *)desc.buffer);
3115 strbuf_release(&ref_name);
3116 return -1;
3117 }
3118
3119 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3120 rollback_lock_file(&lock);
3121 free((void *)desc.buffer);
3122 strbuf_release(&ref_name);
3123 return -1;
3124 }
3125
3126 tree = parse_tree_indirect(&oid);
c207e9e1 3127 prime_cache_tree(r, r->index, tree);
9055e401 3128
f11c9580 3129 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401
JS
3130 ret = error(_("could not write index"));
3131 free((void *)desc.buffer);
3132
3133 if (!ret)
3134 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3135 len, name), "HEAD", &oid,
3136 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3137
3138 strbuf_release(&ref_name);
3139 return ret;
3140}
3141
2b6ad0f4
JS
3142static struct commit *lookup_label(const char *label, int len,
3143 struct strbuf *buf)
3144{
3145 struct commit *commit;
3146
3147 strbuf_reset(buf);
3148 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3149 commit = lookup_commit_reference_by_name(buf->buf);
3150 if (!commit) {
3151 /* fall back to non-rewritten ref or commit */
3152 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3153 commit = lookup_commit_reference_by_name(buf->buf);
3154 }
3155
3156 if (!commit)
3157 error(_("could not resolve '%s'"), buf->buf);
3158
3159 return commit;
3160}
3161
f11c9580
NTND
3162static int do_merge(struct repository *r,
3163 struct commit *commit,
3164 const char *arg, int arg_len,
4c68e7dd
JS
3165 int flags, struct replay_opts *opts)
3166{
3167 int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3168 EDIT_MSG | VERIFY_MSG : 0;
3169 struct strbuf ref_name = STRBUF_INIT;
3170 struct commit *head_commit, *merge_commit, *i;
3171 struct commit_list *bases, *j, *reversed = NULL;
2b6ad0f4 3172 struct commit_list *to_merge = NULL, **tail = &to_merge;
4c68e7dd 3173 struct merge_options o;
2b6ad0f4 3174 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3175 static struct lock_file lock;
3176 const char *p;
3177
3a95f31d 3178 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3179 ret = -1;
3180 goto leave_merge;
3181 }
3182
3183 head_commit = lookup_commit_reference_by_name("HEAD");
3184 if (!head_commit) {
3185 ret = error(_("cannot merge without a current revision"));
3186 goto leave_merge;
3187 }
3188
2b6ad0f4
JS
3189 /*
3190 * For octopus merges, the arg starts with the list of revisions to be
3191 * merged. The list is optionally followed by '#' and the oneline.
3192 */
3193 merge_arg_len = oneline_offset = arg_len;
3194 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3195 if (!*p)
3196 break;
3197 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3198 p += 1 + strspn(p + 1, " \t\n");
3199 oneline_offset = p - arg;
3200 break;
3201 }
3202 k = strcspn(p, " \t\n");
3203 if (!k)
3204 continue;
3205 merge_commit = lookup_label(p, k, &ref_name);
3206 if (!merge_commit) {
3207 ret = error(_("unable to parse '%.*s'"), k, p);
3208 goto leave_merge;
3209 }
3210 tail = &commit_list_insert(merge_commit, tail)->next;
3211 p += k;
3212 merge_arg_len = p - arg;
4c68e7dd
JS
3213 }
3214
2b6ad0f4
JS
3215 if (!to_merge) {
3216 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3217 goto leave_merge;
3218 }
3219
9c85a1c2 3220 if (opts->have_squash_onto &&
4a7e27e9 3221 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3222 /*
3223 * When the user tells us to "merge" something into a
3224 * "[new root]", let's simply fast-forward to the merge head.
3225 */
3226 rollback_lock_file(&lock);
2b6ad0f4
JS
3227 if (to_merge->next)
3228 ret = error(_("octopus merge cannot be executed on "
3229 "top of a [new root]"));
3230 else
f11c9580 3231 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3232 &head_commit->object.oid, 0,
3233 opts);
9c85a1c2
JS
3234 goto leave_merge;
3235 }
3236
4c68e7dd
JS
3237 if (commit) {
3238 const char *message = get_commit_buffer(commit, NULL);
3239 const char *body;
3240 int len;
3241
3242 if (!message) {
3243 ret = error(_("could not get commit message of '%s'"),
3244 oid_to_hex(&commit->object.oid));
3245 goto leave_merge;
3246 }
3247 write_author_script(message);
3248 find_commit_subject(message, &body);
3249 len = strlen(body);
f11c9580 3250 ret = write_message(body, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3251 unuse_commit_buffer(commit, message);
3252 if (ret) {
3253 error_errno(_("could not write '%s'"),
f11c9580 3254 git_path_merge_msg(r));
4c68e7dd
JS
3255 goto leave_merge;
3256 }
3257 } else {
3258 struct strbuf buf = STRBUF_INIT;
3259 int len;
3260
3261 strbuf_addf(&buf, "author %s", git_author_info(0));
3262 write_author_script(buf.buf);
3263 strbuf_reset(&buf);
3264
3265 if (oneline_offset < arg_len) {
3266 p = arg + oneline_offset;
3267 len = arg_len - oneline_offset;
3268 } else {
2b6ad0f4
JS
3269 strbuf_addf(&buf, "Merge %s '%.*s'",
3270 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
3271 merge_arg_len, arg);
3272 p = buf.buf;
3273 len = buf.len;
3274 }
3275
f11c9580 3276 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
3277 strbuf_release(&buf);
3278 if (ret) {
3279 error_errno(_("could not write '%s'"),
f11c9580 3280 git_path_merge_msg(r));
4c68e7dd
JS
3281 goto leave_merge;
3282 }
3283 }
3284
d1e8b011
JS
3285 /*
3286 * If HEAD is not identical to the first parent of the original merge
3287 * commit, we cannot fast-forward.
3288 */
3289 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4a7e27e9
JK
3290 oideq(&commit->parents->item->object.oid,
3291 &head_commit->object.oid);
d1e8b011
JS
3292
3293 /*
2b6ad0f4 3294 * If any merge head is different from the original one, we cannot
d1e8b011
JS
3295 * fast-forward.
3296 */
3297 if (can_fast_forward) {
2b6ad0f4 3298 struct commit_list *p = commit->parents->next;
d1e8b011 3299
2b6ad0f4 3300 for (j = to_merge; j && p; j = j->next, p = p->next)
9001dc2a 3301 if (!oideq(&j->item->object.oid,
2b6ad0f4
JS
3302 &p->item->object.oid)) {
3303 can_fast_forward = 0;
3304 break;
3305 }
3306 /*
3307 * If the number of merge heads differs from the original merge
3308 * commit, we cannot fast-forward.
3309 */
3310 if (j || p)
d1e8b011
JS
3311 can_fast_forward = 0;
3312 }
3313
2b6ad0f4 3314 if (can_fast_forward) {
d1e8b011 3315 rollback_lock_file(&lock);
f11c9580 3316 ret = fast_forward_to(r, &commit->object.oid,
d1e8b011
JS
3317 &head_commit->object.oid, 0, opts);
3318 goto leave_merge;
3319 }
3320
2b6ad0f4
JS
3321 if (to_merge->next) {
3322 /* Octopus merge */
3323 struct child_process cmd = CHILD_PROCESS_INIT;
3324
3325 if (read_env_script(&cmd.env_array)) {
3326 const char *gpg_opt = gpg_sign_opt_quoted(opts);
3327
3328 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3329 goto leave_merge;
3330 }
3331
3332 cmd.git_cmd = 1;
3333 argv_array_push(&cmd.args, "merge");
3334 argv_array_push(&cmd.args, "-s");
3335 argv_array_push(&cmd.args, "octopus");
3336 argv_array_push(&cmd.args, "--no-edit");
3337 argv_array_push(&cmd.args, "--no-ff");
3338 argv_array_push(&cmd.args, "--no-log");
3339 argv_array_push(&cmd.args, "--no-stat");
3340 argv_array_push(&cmd.args, "-F");
f11c9580 3341 argv_array_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4
JS
3342 if (opts->gpg_sign)
3343 argv_array_push(&cmd.args, opts->gpg_sign);
3344
3345 /* Add the tips to be merged */
3346 for (j = to_merge; j; j = j->next)
3347 argv_array_push(&cmd.args,
3348 oid_to_hex(&j->item->object.oid));
3349
3350 strbuf_release(&ref_name);
f11c9580 3351 unlink(git_path_cherry_pick_head(r));
2b6ad0f4
JS
3352 rollback_lock_file(&lock);
3353
3354 rollback_lock_file(&lock);
3355 ret = run_command(&cmd);
3356
3357 /* force re-reading of the cache */
f11c9580 3358 if (!ret && (discard_index(r->index) < 0 ||
e1ff0a32 3359 repo_read_index(r) < 0))
2b6ad0f4
JS
3360 ret = error(_("could not read index"));
3361 goto leave_merge;
3362 }
3363
3364 merge_commit = to_merge->item;
4c68e7dd 3365 bases = get_merge_bases(head_commit, merge_commit);
4a7e27e9
JK
3366 if (bases && oideq(&merge_commit->object.oid,
3367 &bases->item->object.oid)) {
7ccdf65b
JS
3368 ret = 0;
3369 /* skip merging an ancestor of HEAD */
3370 goto leave_merge;
3371 }
3372
85f8d9da 3373 write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
cde55548
JH
3374 git_path_merge_head(r), 0);
3375 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 3376
4c68e7dd
JS
3377 for (j = bases; j; j = j->next)
3378 commit_list_insert(j->item, &reversed);
3379 free_commit_list(bases);
3380
e1ff0a32 3381 repo_read_index(r);
0d6caa2d 3382 init_merge_options(&o, r);
4c68e7dd
JS
3383 o.branch1 = "HEAD";
3384 o.branch2 = ref_name.buf;
3385 o.buffer_output = 2;
3386
3387 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3388 if (ret <= 0)
3389 fputs(o.obuf.buf, stdout);
3390 strbuf_release(&o.obuf);
3391 if (ret < 0) {
3392 error(_("could not even attempt to merge '%.*s'"),
3393 merge_arg_len, arg);
3394 goto leave_merge;
3395 }
3396 /*
3397 * The return value of merge_recursive() is 1 on clean, and 0 on
3398 * unclean merge.
3399 *
3400 * Let's reverse that, so that do_merge() returns 0 upon success and
3401 * 1 upon failed merge (keeping the return value -1 for the cases where
3402 * we will want to reschedule the `merge` command).
3403 */
3404 ret = !ret;
3405
f11c9580
NTND
3406 if (r->index->cache_changed &&
3407 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
3408 ret = error(_("merge: Unable to write new index file"));
3409 goto leave_merge;
3410 }
3411
3412 rollback_lock_file(&lock);
3413 if (ret)
f11c9580 3414 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
3415 else
3416 /*
3417 * In case of problems, we now want to return a positive
3418 * value (a negative one would indicate that the `merge`
3419 * command needs to be rescheduled).
3420 */
f11c9580
NTND
3421 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3422 run_commit_flags);
4c68e7dd
JS
3423
3424leave_merge:
3425 strbuf_release(&ref_name);
3426 rollback_lock_file(&lock);
2b6ad0f4 3427 free_commit_list(to_merge);
4c68e7dd
JS
3428 return ret;
3429}
3430
6e98de72
JS
3431static int is_final_fixup(struct todo_list *todo_list)
3432{
3433 int i = todo_list->current;
3434
3435 if (!is_fixup(todo_list->items[i].command))
3436 return 0;
3437
3438 while (++i < todo_list->nr)
3439 if (is_fixup(todo_list->items[i].command))
3440 return 0;
3441 else if (!is_noop(todo_list->items[i].command))
3442 break;
3443 return 1;
3444}
3445
25cb8df9
JS
3446static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3447{
3448 int i;
3449
3450 for (i = todo_list->current + offset; i < todo_list->nr; i++)
3451 if (!is_noop(todo_list->items[i].command))
3452 return todo_list->items[i].command;
3453
3454 return -1;
3455}
3456
796c7972
JS
3457static int apply_autostash(struct replay_opts *opts)
3458{
3459 struct strbuf stash_sha1 = STRBUF_INIT;
3460 struct child_process child = CHILD_PROCESS_INIT;
3461 int ret = 0;
3462
3463 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3464 strbuf_release(&stash_sha1);
3465 return 0;
3466 }
3467 strbuf_trim(&stash_sha1);
3468
3469 child.git_cmd = 1;
79a62269
PW
3470 child.no_stdout = 1;
3471 child.no_stderr = 1;
796c7972
JS
3472 argv_array_push(&child.args, "stash");
3473 argv_array_push(&child.args, "apply");
3474 argv_array_push(&child.args, stash_sha1.buf);
3475 if (!run_command(&child))
cdb866b3 3476 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
3477 else {
3478 struct child_process store = CHILD_PROCESS_INIT;
3479
3480 store.git_cmd = 1;
3481 argv_array_push(&store.args, "stash");
3482 argv_array_push(&store.args, "store");
3483 argv_array_push(&store.args, "-m");
3484 argv_array_push(&store.args, "autostash");
3485 argv_array_push(&store.args, "-q");
3486 argv_array_push(&store.args, stash_sha1.buf);
3487 if (run_command(&store))
3488 ret = error(_("cannot store %s"), stash_sha1.buf);
3489 else
cdb866b3
JS
3490 fprintf(stderr,
3491 _("Applying autostash resulted in conflicts.\n"
3492 "Your changes are safe in the stash.\n"
3493 "You can run \"git stash pop\" or"
3494 " \"git stash drop\" at any time.\n"));
796c7972
JS
3495 }
3496
3497 strbuf_release(&stash_sha1);
3498 return ret;
3499}
3500
96e832a5
JS
3501static const char *reflog_message(struct replay_opts *opts,
3502 const char *sub_action, const char *fmt, ...)
3503{
3504 va_list ap;
3505 static struct strbuf buf = STRBUF_INIT;
3506
3507 va_start(ap, fmt);
3508 strbuf_reset(&buf);
3509 strbuf_addstr(&buf, action_name(opts));
3510 if (sub_action)
3511 strbuf_addf(&buf, " (%s)", sub_action);
3512 if (fmt) {
3513 strbuf_addstr(&buf, ": ");
3514 strbuf_vaddf(&buf, fmt, ap);
3515 }
3516 va_end(ap);
3517
3518 return buf.buf;
3519}
3520
2c58483a
AG
3521static int run_git_checkout(struct replay_opts *opts, const char *commit,
3522 const char *action)
3523{
3524 struct child_process cmd = CHILD_PROCESS_INIT;
3525
3526 cmd.git_cmd = 1;
3527
3528 argv_array_push(&cmd.args, "checkout");
3529 argv_array_push(&cmd.args, commit);
3530 argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3531
3532 if (opts->verbose)
3533 return run_command(&cmd);
3534 else
3535 return run_command_silent_on_success(&cmd);
3536}
3537
3538int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3539{
3540 const char *action;
3541
3542 if (commit && *commit) {
3543 action = reflog_message(opts, "start", "checkout %s", commit);
3544 if (run_git_checkout(opts, commit, action))
3545 return error(_("could not checkout %s"), commit);
3546 }
3547
3548 return 0;
3549}
3550
91f0d95d
AG
3551static int checkout_onto(struct replay_opts *opts,
3552 const char *onto_name, const char *onto,
3553 const char *orig_head)
4df66c40
AG
3554{
3555 struct object_id oid;
3556 const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3557
3558 if (get_oid(orig_head, &oid))
3559 return error(_("%s: not a valid OID"), orig_head);
3560
3561 if (run_git_checkout(opts, onto, action)) {
3562 apply_autostash(opts);
3563 sequencer_remove_state(opts);
3564 return error(_("could not detach HEAD"));
3565 }
3566
3567 return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3568}
3569
005af339 3570static int stopped_at_head(struct repository *r)
71f82465
JS
3571{
3572 struct object_id head;
3573 struct commit *commit;
3574 struct commit_message message;
3575
789b1f70 3576 if (get_oid("HEAD", &head) ||
005af339 3577 !(commit = lookup_commit(r, &head)) ||
71f82465
JS
3578 parse_commit(commit) || get_message(commit, &message))
3579 fprintf(stderr, _("Stopped at HEAD\n"));
3580 else {
3581 fprintf(stderr, _("Stopped at %s\n"), message.label);
3582 free_message(commit, &message);
3583 }
3584 return 0;
3585
3586}
3587
cb5206ea
JS
3588static const char rescheduled_advice[] =
3589N_("Could not execute the todo command\n"
3590"\n"
3591" %.*s"
3592"\n"
3593"It has been rescheduled; To edit the command before continuing, please\n"
3594"edit the todo list first:\n"
3595"\n"
3596" git rebase --edit-todo\n"
3597" git rebase --continue\n");
3598
f11c9580
NTND
3599static int pick_commits(struct repository *r,
3600 struct todo_list *todo_list,
3601 struct replay_opts *opts)
043a4492 3602{
9055e401 3603 int res = 0, reschedule = 0;
043a4492
RR
3604
3605 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3606 if (opts->allow_ff)
3607 assert(!(opts->signoff || opts->no_commit ||
3608 opts->record_origin || opts->edit));
f11c9580 3609 if (read_and_refresh_cache(r, opts))
0d9c6dc9 3610 return -1;
043a4492 3611
004fefa7
JS
3612 while (todo_list->current < todo_list->nr) {
3613 struct todo_item *item = todo_list->items + todo_list->current;
3614 if (save_todo(todo_list, opts))
221675de 3615 return -1;
6e98de72 3616 if (is_rebase_i(opts)) {
ef80069a
JS
3617 if (item->command != TODO_COMMENT) {
3618 FILE *f = fopen(rebase_path_msgnum(), "w");
3619
3620 todo_list->done_nr++;
3621
3622 if (f) {
3623 fprintf(f, "%d\n", todo_list->done_nr);
3624 fclose(f);
3625 }
899b49c4
EN
3626 if (!opts->quiet)
3627 fprintf(stderr, "Rebasing (%d/%d)%s",
3628 todo_list->done_nr,
3629 todo_list->total_nr,
3630 opts->verbose ? "\n" : "\r");
ef80069a 3631 }
6e98de72
JS
3632 unlink(rebase_path_message());
3633 unlink(rebase_path_author_script());
3634 unlink(rebase_path_stopped_sha());
3635 unlink(rebase_path_amend());
69c92209 3636 unlink(git_path_merge_head(the_repository));
fbd7a232 3637 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465
JS
3638
3639 if (item->command == TODO_BREAK)
005af339 3640 return stopped_at_head(r);
6e98de72
JS
3641 }
3642 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3643 if (is_rebase_i(opts))
3644 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3645 command_to_string(item->command), NULL),
3646 1);
f11c9580 3647 res = do_pick_commit(r, item->command, item->commit,
6e98de72 3648 opts, is_final_fixup(todo_list));
9d7bf3cf
JS
3649 if (is_rebase_i(opts) && res < 0) {
3650 /* Reschedule */
cb5206ea
JS
3651 advise(_(rescheduled_advice),
3652 get_item_line_length(todo_list,
3653 todo_list->current),
3654 get_item_line(todo_list,
3655 todo_list->current));
9d7bf3cf
JS
3656 todo_list->current--;
3657 if (save_todo(todo_list, opts))
3658 return -1;
3659 }
56dc3ab0
JS
3660 if (item->command == TODO_EDIT) {
3661 struct commit *commit = item->commit;
3662 if (!res)
99429213 3663 fprintf(stderr,
a42e1b41 3664 _("Stopped at %s... %.*s\n"),
56dc3ab0
JS
3665 short_commit_name(commit),
3666 item->arg_len, item->arg);
f11c9580 3667 return error_with_patch(r, commit,
56dc3ab0
JS
3668 item->arg, item->arg_len, opts, res,
3669 !res);
3670 }
25cb8df9
JS
3671 if (is_rebase_i(opts) && !res)
3672 record_in_rewritten(&item->commit->object.oid,
3673 peek_command(todo_list, 1));
6e98de72
JS
3674 if (res && is_fixup(item->command)) {
3675 if (res == 1)
3676 intend_to_amend();
f11c9580 3677 return error_failed_squash(r, item->commit, opts,
6e98de72 3678 item->arg_len, item->arg);
a9279c67
PW
3679 } else if (res && is_rebase_i(opts) && item->commit) {
3680 int to_amend = 0;
3681 struct object_id oid;
3682
3683 /*
3684 * If we are rewording and have either
3685 * fast-forwarded already, or are about to
3686 * create a new root commit, we want to amend,
3687 * otherwise we do not.
3688 */
3689 if (item->command == TODO_REWORD &&
3690 !get_oid("HEAD", &oid) &&
4a7e27e9 3691 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 3692 (opts->have_squash_onto &&
4a7e27e9 3693 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
3694 to_amend = 1;
3695
f11c9580 3696 return res | error_with_patch(r, item->commit,
a9279c67
PW
3697 item->arg, item->arg_len, opts,
3698 res, to_amend);
3699 }
311af526
JS
3700 } else if (item->command == TODO_EXEC) {
3701 char *end_of_arg = (char *)(item->arg + item->arg_len);
3702 int saved = *end_of_arg;
54fd3243 3703 struct stat st;
311af526
JS
3704
3705 *end_of_arg = '\0';
f11c9580 3706 res = do_exec(r, item->arg);
311af526 3707 *end_of_arg = saved;
54fd3243 3708
d421afa0
JS
3709 if (res) {
3710 if (opts->reschedule_failed_exec)
3711 reschedule = 1;
3712 } else if (stat(get_todo_path(opts), &st))
54fd3243
SH
3713 res = error_errno(_("could not stat '%s'"),
3714 get_todo_path(opts));
3715 else if (match_stat_data(&todo_list->stat, &st)) {
01710d0a 3716 /* Reread the todo file if it has changed. */
54fd3243 3717 todo_list_release(todo_list);
005af339 3718 if (read_populate_todo(r, todo_list, opts))
54fd3243
SH
3719 res = -1; /* message was printed */
3720 /* `current` will be incremented below */
3721 todo_list->current = -1;
3722 }
9055e401 3723 } else if (item->command == TODO_LABEL) {
f11c9580 3724 if ((res = do_label(r, item->arg, item->arg_len)))
9055e401
JS
3725 reschedule = 1;
3726 } else if (item->command == TODO_RESET) {
f11c9580 3727 if ((res = do_reset(r, item->arg, item->arg_len, opts)))
9055e401 3728 reschedule = 1;
4c68e7dd 3729 } else if (item->command == TODO_MERGE) {
f11c9580 3730 if ((res = do_merge(r, item->commit,
4c68e7dd
JS
3731 item->arg, item->arg_len,
3732 item->flags, opts)) < 0)
3733 reschedule = 1;
537e7d61
JS
3734 else if (item->commit)
3735 record_in_rewritten(&item->commit->object.oid,
3736 peek_command(todo_list, 1));
3737 if (res > 0)
4c68e7dd 3738 /* failed with merge conflicts */
f11c9580 3739 return error_with_patch(r, item->commit,
4c68e7dd
JS
3740 item->arg,
3741 item->arg_len, opts,
3742 res, 0);
56dc3ab0 3743 } else if (!is_noop(item->command))
25c43667
JS
3744 return error(_("unknown command %d"), item->command);
3745
9055e401
JS
3746 if (reschedule) {
3747 advise(_(rescheduled_advice),
3748 get_item_line_length(todo_list,
3749 todo_list->current),
3750 get_item_line(todo_list, todo_list->current));
3751 todo_list->current--;
3752 if (save_todo(todo_list, opts))
3753 return -1;
4c68e7dd 3754 if (item->commit)
f11c9580
NTND
3755 return error_with_patch(r,
3756 item->commit,
4c68e7dd
JS
3757 item->arg,
3758 item->arg_len, opts,
3759 res, 0);
9055e401
JS
3760 }
3761
004fefa7 3762 todo_list->current++;
043a4492
RR
3763 if (res)
3764 return res;
3765 }
3766
56dc3ab0 3767 if (is_rebase_i(opts)) {
4b83ce9f 3768 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3769 struct stat st;
556907f1 3770
56dc3ab0
JS
3771 /* Stopped in the middle, as planned? */
3772 if (todo_list->current < todo_list->nr)
3773 return 0;
556907f1 3774
4b83ce9f
JS
3775 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3776 starts_with(head_ref.buf, "refs/")) {
96e832a5 3777 const char *msg;
092bbcdf 3778 struct object_id head, orig;
4b83ce9f
JS
3779 int res;
3780
092bbcdf 3781 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
3782 res = error(_("cannot read HEAD"));
3783cleanup_head_ref:
3784 strbuf_release(&head_ref);
3785 strbuf_release(&buf);
3786 return res;
3787 }
3788 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 3789 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
3790 res = error(_("could not read orig-head"));
3791 goto cleanup_head_ref;
3792 }
4ab867b8 3793 strbuf_reset(&buf);
4b83ce9f
JS
3794 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3795 res = error(_("could not read 'onto'"));
3796 goto cleanup_head_ref;
3797 }
96e832a5
JS
3798 msg = reflog_message(opts, "finish", "%s onto %s",
3799 head_ref.buf, buf.buf);
ae077771 3800 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 3801 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
3802 res = error(_("could not update %s"),
3803 head_ref.buf);
3804 goto cleanup_head_ref;
3805 }
96e832a5 3806 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 3807 head_ref.buf);
96e832a5 3808 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
3809 res = error(_("could not update HEAD to %s"),
3810 head_ref.buf);
3811 goto cleanup_head_ref;
3812 }
3813 strbuf_reset(&buf);
3814 }
3815
556907f1
JS
3816 if (opts->verbose) {
3817 struct rev_info log_tree_opt;
3818 struct object_id orig, head;
3819
3820 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3821 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
3822 log_tree_opt.diff = 1;
3823 log_tree_opt.diffopt.output_format =
3824 DIFF_FORMAT_DIFFSTAT;
3825 log_tree_opt.disable_stdin = 1;
3826
3827 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 3828 !get_oid(buf.buf, &orig) &&
3829 !get_oid("HEAD", &head)) {
66f414f8
BW
3830 diff_tree_oid(&orig, &head, "",
3831 &log_tree_opt.diffopt);
556907f1
JS
3832 log_tree_diff_flush(&log_tree_opt);
3833 }
3834 }
25cb8df9
JS
3835 flush_rewritten_pending();
3836 if (!stat(rebase_path_rewritten_list(), &st) &&
3837 st.st_size > 0) {
3838 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
3839 const char *post_rewrite_hook =
3840 find_hook("post-rewrite");
25cb8df9
JS
3841
3842 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3843 child.git_cmd = 1;
3844 argv_array_push(&child.args, "notes");
3845 argv_array_push(&child.args, "copy");
3846 argv_array_push(&child.args, "--for-rewrite=rebase");
3847 /* we don't care if this copying failed */
3848 run_command(&child);
79516045
JS
3849
3850 if (post_rewrite_hook) {
3851 struct child_process hook = CHILD_PROCESS_INIT;
3852
3853 hook.in = open(rebase_path_rewritten_list(),
3854 O_RDONLY);
3855 hook.stdout_to_stderr = 1;
6206286e 3856 hook.trace2_hook_name = "post-rewrite";
79516045
JS
3857 argv_array_push(&hook.args, post_rewrite_hook);
3858 argv_array_push(&hook.args, "rebase");
3859 /* we don't care if this hook failed */
3860 run_command(&hook);
3861 }
25cb8df9 3862 }
796c7972 3863 apply_autostash(opts);
25cb8df9 3864
899b49c4
EN
3865 if (!opts->quiet)
3866 fprintf(stderr,
3867 "Successfully rebased and updated %s.\n",
3868 head_ref.buf);
5da4966f 3869
556907f1 3870 strbuf_release(&buf);
4b83ce9f 3871 strbuf_release(&head_ref);
56dc3ab0
JS
3872 }
3873
043a4492
RR
3874 /*
3875 * Sequence of picks finished successfully; cleanup by
3876 * removing the .git/sequencer directory
3877 */
2863584f 3878 return sequencer_remove_state(opts);
043a4492
RR
3879}
3880
005af339 3881static int continue_single_pick(struct repository *r)
043a4492
RR
3882{
3883 const char *argv[] = { "commit", NULL };
3884
005af339
NTND
3885 if (!file_exists(git_path_cherry_pick_head(r)) &&
3886 !file_exists(git_path_revert_head(r)))
043a4492
RR
3887 return error(_("no cherry-pick or revert in progress"));
3888 return run_command_v_opt(argv, RUN_GIT_CMD);
3889}
3890
f11c9580
NTND
3891static int commit_staged_changes(struct repository *r,
3892 struct replay_opts *opts,
15ef6931 3893 struct todo_list *todo_list)
9d93ccd1 3894{
789b3eff 3895 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 3896 unsigned int final_fixup = 0, is_clean;
9d93ccd1 3897
f11c9580 3898 if (has_unstaged_changes(r, 1))
9d93ccd1 3899 return error(_("cannot rebase: You have unstaged changes."));
52632209 3900
f11c9580 3901 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
3902
3903 if (file_exists(rebase_path_amend())) {
3904 struct strbuf rev = STRBUF_INIT;
092bbcdf 3905 struct object_id head, to_amend;
9d93ccd1 3906
092bbcdf 3907 if (get_oid("HEAD", &head))
9d93ccd1
JS
3908 return error(_("cannot amend non-existing commit"));
3909 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3910 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 3911 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
3912 return error(_("invalid contents: '%s'"),
3913 rebase_path_amend());
9001dc2a 3914 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
3915 return error(_("\nYou have uncommitted changes in your "
3916 "working tree. Please, commit them\n"
3917 "first and then run 'git rebase "
3918 "--continue' again."));
15ef6931
JS
3919 /*
3920 * When skipping a failed fixup/squash, we need to edit the
3921 * commit message, the current fixup list and count, and if it
3922 * was the last fixup/squash in the chain, we need to clean up
3923 * the commit message and if there was a squash, let the user
3924 * edit it.
3925 */
10d2f354
JS
3926 if (!is_clean || !opts->current_fixup_count)
3927 ; /* this is not the final fixup */
87ae8a1a 3928 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
3929 !file_exists(rebase_path_stopped_sha())) {
3930 /* was a final fixup or squash done manually? */
3931 if (!is_fixup(peek_command(todo_list, 0))) {
3932 unlink(rebase_path_fixup_msg());
3933 unlink(rebase_path_squash_msg());
3934 unlink(rebase_path_current_fixups());
3935 strbuf_reset(&opts->current_fixups);
3936 opts->current_fixup_count = 0;
3937 }
3938 } else {
3939 /* we are in a fixup/squash chain */
15ef6931
JS
3940 const char *p = opts->current_fixups.buf;
3941 int len = opts->current_fixups.len;
3942
3943 opts->current_fixup_count--;
3944 if (!len)
3945 BUG("Incorrect current_fixups:\n%s", p);
3946 while (len && p[len - 1] != '\n')
3947 len--;
3948 strbuf_setlen(&opts->current_fixups, len);
3949 if (write_message(p, len, rebase_path_current_fixups(),
3950 0) < 0)
3951 return error(_("could not write file: '%s'"),
3952 rebase_path_current_fixups());
3953
3954 /*
3955 * If a fixup/squash in a fixup/squash chain failed, the
3956 * commit message is already correct, no need to commit
3957 * it again.
3958 *
3959 * Only if it is the final command in the fixup/squash
3960 * chain, and only if the chain is longer than a single
3961 * fixup/squash command (which was just skipped), do we
3962 * actually need to re-commit with a cleaned up commit
3963 * message.
3964 */
3965 if (opts->current_fixup_count > 0 &&
3966 !is_fixup(peek_command(todo_list, 0))) {
3967 final_fixup = 1;
3968 /*
3969 * If there was not a single "squash" in the
3970 * chain, we only need to clean up the commit
3971 * message, no need to bother the user with
3972 * opening the commit message in the editor.
3973 */
3974 if (!starts_with(p, "squash ") &&
3975 !strstr(p, "\nsquash "))
3976 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3977 } else if (is_fixup(peek_command(todo_list, 0))) {
3978 /*
3979 * We need to update the squash message to skip
3980 * the latest commit message.
3981 */
3982 struct commit *commit;
3983 const char *path = rebase_path_squash_msg();
3984
005af339 3985 if (parse_head(r, &commit) ||
15ef6931
JS
3986 !(p = get_commit_buffer(commit, NULL)) ||
3987 write_message(p, strlen(p), path, 0)) {
3988 unuse_commit_buffer(commit, p);
3989 return error(_("could not write file: "
3990 "'%s'"), path);
3991 }
3992 unuse_commit_buffer(commit, p);
3993 }
3994 }
9d93ccd1
JS
3995
3996 strbuf_release(&rev);
789b3eff 3997 flags |= AMEND_MSG;
9d93ccd1
JS
3998 }
3999
15ef6931 4000 if (is_clean) {
f11c9580 4001 const char *cherry_pick_head = git_path_cherry_pick_head(r);
15ef6931
JS
4002
4003 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4004 return error(_("could not remove CHERRY_PICK_HEAD"));
4005 if (!final_fixup)
4006 return 0;
4007 }
4008
f11c9580 4009 if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
15ef6931 4010 opts, flags))
9d93ccd1
JS
4011 return error(_("could not commit staged changes."));
4012 unlink(rebase_path_amend());
69c92209 4013 unlink(git_path_merge_head(the_repository));
15ef6931
JS
4014 if (final_fixup) {
4015 unlink(rebase_path_fixup_msg());
4016 unlink(rebase_path_squash_msg());
4017 }
4018 if (opts->current_fixup_count > 0) {
4019 /*
4020 * Whether final fixup or not, we just cleaned up the commit
4021 * message...
4022 */
4023 unlink(rebase_path_current_fixups());
4024 strbuf_reset(&opts->current_fixups);
4025 opts->current_fixup_count = 0;
4026 }
9d93ccd1
JS
4027 return 0;
4028}
4029
f11c9580 4030int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 4031{
004fefa7
JS
4032 struct todo_list todo_list = TODO_LIST_INIT;
4033 int res;
043a4492 4034
f11c9580 4035 if (read_and_refresh_cache(r, opts))
2863584f
JS
4036 return -1;
4037
15ef6931
JS
4038 if (read_populate_opts(opts))
4039 return -1;
9d93ccd1 4040 if (is_rebase_i(opts)) {
005af339 4041 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 4042 goto release_todo_list;
f11c9580 4043 if (commit_staged_changes(r, opts, &todo_list))
9d93ccd1 4044 return -1;
4258a6da 4045 } else if (!file_exists(get_todo_path(opts)))
005af339
NTND
4046 return continue_single_pick(r);
4047 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 4048 goto release_todo_list;
043a4492 4049
4258a6da
JS
4050 if (!is_rebase_i(opts)) {
4051 /* Verify that the conflict has been resolved */
f11c9580
NTND
4052 if (file_exists(git_path_cherry_pick_head(r)) ||
4053 file_exists(git_path_revert_head(r))) {
005af339 4054 res = continue_single_pick(r);
4258a6da
JS
4055 if (res)
4056 goto release_todo_list;
4057 }
ffc00a48 4058 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 4059 res = error_dirty_index(r, opts);
004fefa7 4060 goto release_todo_list;
4258a6da
JS
4061 }
4062 todo_list.current++;
ca98c6d4
JS
4063 } else if (file_exists(rebase_path_stopped_sha())) {
4064 struct strbuf buf = STRBUF_INIT;
4065 struct object_id oid;
4066
4067 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
e82caf38 4068 !get_oid_committish(buf.buf, &oid))
ca98c6d4
JS
4069 record_in_rewritten(&oid, peek_command(&todo_list, 0));
4070 strbuf_release(&buf);
043a4492 4071 }
4258a6da 4072
f11c9580 4073 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4074release_todo_list:
4075 todo_list_release(&todo_list);
4076 return res;
043a4492
RR
4077}
4078
f11c9580
NTND
4079static int single_pick(struct repository *r,
4080 struct commit *cmit,
4081 struct replay_opts *opts)
043a4492
RR
4082{
4083 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
f11c9580 4084 return do_pick_commit(r, opts->action == REPLAY_PICK ?
6e98de72 4085 TODO_PICK : TODO_REVERT, cmit, opts, 0);
043a4492
RR
4086}
4087
f11c9580
NTND
4088int sequencer_pick_revisions(struct repository *r,
4089 struct replay_opts *opts)
043a4492 4090{
004fefa7 4091 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 4092 struct object_id oid;
004fefa7 4093 int i, res;
043a4492 4094
2863584f 4095 assert(opts->revs);
f11c9580 4096 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4097 return -1;
043a4492 4098
21246dbb 4099 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 4100 struct object_id oid;
21246dbb
MV
4101 const char *name = opts->revs->pending.objects[i].name;
4102
4103 /* This happens when using --stdin. */
4104 if (!strlen(name))
4105 continue;
4106
1e43ed98 4107 if (!get_oid(name, &oid)) {
f11c9580
NTND
4108 if (!lookup_commit_reference_gently(r, &oid, 1)) {
4109 enum object_type type = oid_object_info(r,
0df8e965 4110 &oid,
abef9020 4111 NULL);
b9b946d4 4112 return error(_("%s: can't cherry-pick a %s"),
debca9d2 4113 name, type_name(type));
7c0b0d8d 4114 }
21246dbb 4115 } else
b9b946d4 4116 return error(_("%s: bad revision"), name);
21246dbb
MV
4117 }
4118
043a4492
RR
4119 /*
4120 * If we were called as "git cherry-pick <commit>", just
4121 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4122 * REVERT_HEAD, and don't touch the sequencer state.
4123 * This means it is possible to cherry-pick in the middle
4124 * of a cherry-pick sequence.
4125 */
4126 if (opts->revs->cmdline.nr == 1 &&
4127 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4128 opts->revs->no_walk &&
4129 !opts->revs->cmdline.rev->flags) {
4130 struct commit *cmit;
4131 if (prepare_revision_walk(opts->revs))
b9b946d4 4132 return error(_("revision walk setup failed"));
043a4492 4133 cmit = get_revision(opts->revs);
c5e358d0
JK
4134 if (!cmit)
4135 return error(_("empty commit set passed"));
4136 if (get_revision(opts->revs))
4137 BUG("unexpected extra commit from walk");
f11c9580 4138 return single_pick(r, cmit, opts);
043a4492
RR
4139 }
4140
4141 /*
4142 * Start a new cherry-pick/ revert sequence; but
4143 * first, make sure that an existing one isn't in
4144 * progress
4145 */
4146
34b0528b
JS
4147 if (walk_revs_populate_todo(&todo_list, opts) ||
4148 create_seq_dir() < 0)
043a4492 4149 return -1;
1e43ed98 4150 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 4151 return error(_("can't revert as initial commit"));
1e43ed98 4152 if (save_head(oid_to_hex(&oid)))
311fd397 4153 return -1;
88d5a271
JS
4154 if (save_opts(opts))
4155 return -1;
1e41229d 4156 update_abort_safety_file();
f11c9580 4157 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
4158 todo_list_release(&todo_list);
4159 return res;
043a4492 4160}
5ed75e2a 4161
66e83d9b 4162void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 4163{
bab4d109 4164 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 4165 struct strbuf sob = STRBUF_INIT;
bab4d109 4166 int has_footer;
5ed75e2a
MV
4167
4168 strbuf_addstr(&sob, sign_off_header);
39ab4d09 4169 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 4170 strbuf_addch(&sob, '\n');
bab4d109 4171
44dc738a
JT
4172 if (!ignore_footer)
4173 strbuf_complete_line(msgbuf);
4174
bab4d109
BC
4175 /*
4176 * If the whole message buffer is equal to the sob, pretend that we
4177 * found a conforming footer with a matching sob
4178 */
4179 if (msgbuf->len - ignore_footer == sob.len &&
4180 !strncmp(msgbuf->buf, sob.buf, sob.len))
4181 has_footer = 3;
4182 else
4183 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4184
33f2f9ab
BC
4185 if (!has_footer) {
4186 const char *append_newlines = NULL;
4187 size_t len = msgbuf->len - ignore_footer;
4188
8c613fd5
BC
4189 if (!len) {
4190 /*
4191 * The buffer is completely empty. Leave foom for
4192 * the title and body to be filled in by the user.
4193 */
33f2f9ab 4194 append_newlines = "\n\n";
8c613fd5
BC
4195 } else if (len == 1) {
4196 /*
4197 * Buffer contains a single newline. Add another
4198 * so that we leave room for the title and body.
4199 */
4200 append_newlines = "\n";
4201 } else if (msgbuf->buf[len - 2] != '\n') {
4202 /*
4203 * Buffer ends with a single newline. Add another
4204 * so that there is an empty line between the message
4205 * body and the sob.
4206 */
33f2f9ab 4207 append_newlines = "\n";
8c613fd5 4208 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
4209
4210 if (append_newlines)
4211 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4212 append_newlines, strlen(append_newlines));
5ed75e2a 4213 }
bab4d109
BC
4214
4215 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4216 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4217 sob.buf, sob.len);
4218
5ed75e2a
MV
4219 strbuf_release(&sob);
4220}
62db5247 4221
1644c73c
JS
4222struct labels_entry {
4223 struct hashmap_entry entry;
4224 char label[FLEX_ARRAY];
4225};
4226
4227static int labels_cmp(const void *fndata, const struct labels_entry *a,
4228 const struct labels_entry *b, const void *key)
4229{
4230 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4231}
4232
4233struct string_entry {
4234 struct oidmap_entry entry;
4235 char string[FLEX_ARRAY];
4236};
4237
4238struct label_state {
4239 struct oidmap commit2label;
4240 struct hashmap labels;
4241 struct strbuf buf;
4242};
4243
4244static const char *label_oid(struct object_id *oid, const char *label,
4245 struct label_state *state)
4246{
4247 struct labels_entry *labels_entry;
4248 struct string_entry *string_entry;
4249 struct object_id dummy;
4250 size_t len;
4251 int i;
4252
4253 string_entry = oidmap_get(&state->commit2label, oid);
4254 if (string_entry)
4255 return string_entry->string;
4256
4257 /*
4258 * For "uninteresting" commits, i.e. commits that are not to be
4259 * rebased, and which can therefore not be labeled, we use a unique
4260 * abbreviation of the commit name. This is slightly more complicated
4261 * than calling find_unique_abbrev() because we also need to make
4262 * sure that the abbreviation does not conflict with any other
4263 * label.
4264 *
4265 * We disallow "interesting" commits to be labeled by a string that
4266 * is a valid full-length hash, to ensure that we always can find an
4267 * abbreviation for any uninteresting commit's names that does not
4268 * clash with any other label.
4269 */
4270 if (!label) {
4271 char *p;
4272
4273 strbuf_reset(&state->buf);
4274 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4275 label = p = state->buf.buf;
4276
4277 find_unique_abbrev_r(p, oid, default_abbrev);
4278
4279 /*
4280 * We may need to extend the abbreviated hash so that there is
4281 * no conflicting label.
4282 */
4283 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4284 size_t i = strlen(p) + 1;
4285
4286 oid_to_hex_r(p, oid);
4287 for (; i < GIT_SHA1_HEXSZ; i++) {
4288 char save = p[i];
4289 p[i] = '\0';
4290 if (!hashmap_get_from_hash(&state->labels,
4291 strihash(p), p))
4292 break;
4293 p[i] = save;
4294 }
4295 }
5971b083 4296 } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
1644c73c
JS
4297 !get_oid_hex(label, &dummy)) ||
4298 (len == 1 && *label == '#') ||
4299 hashmap_get_from_hash(&state->labels,
4300 strihash(label), label)) {
4301 /*
4302 * If the label already exists, or if the label is a valid full
4303 * OID, or the label is a '#' (which we use as a separator
4304 * between merge heads and oneline), we append a dash and a
4305 * number to make it unique.
4306 */
4307 struct strbuf *buf = &state->buf;
4308
4309 strbuf_reset(buf);
4310 strbuf_add(buf, label, len);
4311
4312 for (i = 2; ; i++) {
4313 strbuf_setlen(buf, len);
4314 strbuf_addf(buf, "-%d", i);
4315 if (!hashmap_get_from_hash(&state->labels,
4316 strihash(buf->buf),
4317 buf->buf))
4318 break;
4319 }
4320
4321 label = buf->buf;
4322 }
4323
4324 FLEX_ALLOC_STR(labels_entry, label, label);
4325 hashmap_entry_init(labels_entry, strihash(label));
4326 hashmap_add(&state->labels, labels_entry);
4327
4328 FLEX_ALLOC_STR(string_entry, string, label);
4329 oidcpy(&string_entry->entry.oid, oid);
4330 oidmap_put(&state->commit2label, string_entry);
4331
4332 return string_entry->string;
4333}
4334
4335static int make_script_with_merges(struct pretty_print_context *pp,
4336 struct rev_info *revs, FILE *out,
4337 unsigned flags)
4338{
4339 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 4340 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
1644c73c
JS
4341 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4342 struct strbuf label = STRBUF_INIT;
4343 struct commit_list *commits = NULL, **tail = &commits, *iter;
4344 struct commit_list *tips = NULL, **tips_tail = &tips;
4345 struct commit *commit;
4346 struct oidmap commit2todo = OIDMAP_INIT;
4347 struct string_entry *entry;
4348 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4349 shown = OIDSET_INIT;
4350 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4351
4352 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4353 const char *cmd_pick = abbr ? "p" : "pick",
4354 *cmd_label = abbr ? "l" : "label",
4355 *cmd_reset = abbr ? "t" : "reset",
4356 *cmd_merge = abbr ? "m" : "merge";
4357
4358 oidmap_init(&commit2todo, 0);
4359 oidmap_init(&state.commit2label, 0);
4360 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4361 strbuf_init(&state.buf, 32);
4362
4363 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4364 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4365 FLEX_ALLOC_STR(entry, string, "onto");
4366 oidcpy(&entry->entry.oid, oid);
4367 oidmap_put(&state.commit2label, entry);
4368 }
4369
4370 /*
4371 * First phase:
4372 * - get onelines for all commits
4373 * - gather all branch tips (i.e. 2nd or later parents of merges)
4374 * - label all branch tips
4375 */
4376 while ((commit = get_revision(revs))) {
4377 struct commit_list *to_merge;
1644c73c
JS
4378 const char *p1, *p2;
4379 struct object_id *oid;
4380 int is_empty;
4381
4382 tail = &commit_list_insert(commit, tail)->next;
4383 oidset_insert(&interesting, &commit->object.oid);
4384
4385 is_empty = is_original_commit_empty(commit);
4386 if (!is_empty && (commit->object.flags & PATCHSAME))
4387 continue;
4388
4389 strbuf_reset(&oneline);
4390 pretty_print_commit(pp, commit, &oneline);
4391
4392 to_merge = commit->parents ? commit->parents->next : NULL;
4393 if (!to_merge) {
4394 /* non-merge commit: easy case */
4395 strbuf_reset(&buf);
4396 if (!keep_empty && is_empty)
4397 strbuf_addf(&buf, "%c ", comment_line_char);
4398 strbuf_addf(&buf, "%s %s %s", cmd_pick,
4399 oid_to_hex(&commit->object.oid),
4400 oneline.buf);
4401
4402 FLEX_ALLOC_STR(entry, string, buf.buf);
4403 oidcpy(&entry->entry.oid, &commit->object.oid);
4404 oidmap_put(&commit2todo, entry);
4405
4406 continue;
4407 }
4408
1644c73c
JS
4409 /* Create a label */
4410 strbuf_reset(&label);
4411 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4412 (p1 = strchr(p1, '\'')) &&
4413 (p2 = strchr(++p1, '\'')))
4414 strbuf_add(&label, p1, p2 - p1);
4415 else if (skip_prefix(oneline.buf, "Merge pull request ",
4416 &p1) &&
4417 (p1 = strstr(p1, " from ")))
4418 strbuf_addstr(&label, p1 + strlen(" from "));
4419 else
4420 strbuf_addbuf(&label, &oneline);
4421
4422 for (p1 = label.buf; *p1; p1++)
4423 if (isspace(*p1))
4424 *(char *)p1 = '-';
4425
4426 strbuf_reset(&buf);
4427 strbuf_addf(&buf, "%s -C %s",
4428 cmd_merge, oid_to_hex(&commit->object.oid));
4429
2b6ad0f4
JS
4430 /* label the tips of merged branches */
4431 for (; to_merge; to_merge = to_merge->next) {
4432 oid = &to_merge->item->object.oid;
4433 strbuf_addch(&buf, ' ');
4434
4435 if (!oidset_contains(&interesting, oid)) {
4436 strbuf_addstr(&buf, label_oid(oid, NULL,
4437 &state));
4438 continue;
4439 }
1644c73c 4440
1644c73c
JS
4441 tips_tail = &commit_list_insert(to_merge->item,
4442 tips_tail)->next;
4443
4444 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4445 }
4446 strbuf_addf(&buf, " # %s", oneline.buf);
4447
4448 FLEX_ALLOC_STR(entry, string, buf.buf);
4449 oidcpy(&entry->entry.oid, &commit->object.oid);
4450 oidmap_put(&commit2todo, entry);
4451 }
4452
4453 /*
4454 * Second phase:
4455 * - label branch points
4456 * - add HEAD to the branch tips
4457 */
4458 for (iter = commits; iter; iter = iter->next) {
4459 struct commit_list *parent = iter->item->parents;
4460 for (; parent; parent = parent->next) {
4461 struct object_id *oid = &parent->item->object.oid;
4462 if (!oidset_contains(&interesting, oid))
4463 continue;
6e8fc70f 4464 if (oidset_insert(&child_seen, oid))
1644c73c
JS
4465 label_oid(oid, "branch-point", &state);
4466 }
4467
4468 /* Add HEAD as implict "tip of branch" */
4469 if (!iter->next)
4470 tips_tail = &commit_list_insert(iter->item,
4471 tips_tail)->next;
4472 }
4473
4474 /*
4475 * Third phase: output the todo list. This is a bit tricky, as we
4476 * want to avoid jumping back and forth between revisions. To
4477 * accomplish that goal, we walk backwards from the branch tips,
4478 * gathering commits not yet shown, reversing the list on the fly,
4479 * then outputting that list (labeling revisions as needed).
4480 */
4481 fprintf(out, "%s onto\n", cmd_label);
4482 for (iter = tips; iter; iter = iter->next) {
4483 struct commit_list *list = NULL, *iter2;
4484
4485 commit = iter->item;
4486 if (oidset_contains(&shown, &commit->object.oid))
4487 continue;
4488 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4489
4490 if (entry)
02cfd149 4491 fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c
JS
4492 else
4493 fprintf(out, "\n");
4494
4495 while (oidset_contains(&interesting, &commit->object.oid) &&
4496 !oidset_contains(&shown, &commit->object.oid)) {
4497 commit_list_insert(commit, &list);
4498 if (!commit->parents) {
4499 commit = NULL;
4500 break;
4501 }
4502 commit = commit->parents->item;
4503 }
4504
4505 if (!commit)
8fa6eea0
JS
4506 fprintf(out, "%s %s\n", cmd_reset,
4507 rebase_cousins ? "onto" : "[new root]");
1644c73c
JS
4508 else {
4509 const char *to = NULL;
4510
4511 entry = oidmap_get(&state.commit2label,
4512 &commit->object.oid);
4513 if (entry)
4514 to = entry->string;
7543f6f4
JS
4515 else if (!rebase_cousins)
4516 to = label_oid(&commit->object.oid, NULL,
4517 &state);
1644c73c
JS
4518
4519 if (!to || !strcmp(to, "onto"))
4520 fprintf(out, "%s onto\n", cmd_reset);
4521 else {
4522 strbuf_reset(&oneline);
4523 pretty_print_commit(pp, commit, &oneline);
4524 fprintf(out, "%s %s # %s\n",
4525 cmd_reset, to, oneline.buf);
4526 }
4527 }
4528
4529 for (iter2 = list; iter2; iter2 = iter2->next) {
4530 struct object_id *oid = &iter2->item->object.oid;
4531 entry = oidmap_get(&commit2todo, oid);
4532 /* only show if not already upstream */
4533 if (entry)
4534 fprintf(out, "%s\n", entry->string);
4535 entry = oidmap_get(&state.commit2label, oid);
4536 if (entry)
4537 fprintf(out, "%s %s\n",
4538 cmd_label, entry->string);
4539 oidset_insert(&shown, oid);
4540 }
4541
4542 free_commit_list(list);
4543 }
4544
4545 free_commit_list(commits);
4546 free_commit_list(tips);
4547
4548 strbuf_release(&label);
4549 strbuf_release(&oneline);
4550 strbuf_release(&buf);
4551
4552 oidmap_free(&commit2todo, 1);
4553 oidmap_free(&state.commit2label, 1);
4554 hashmap_free(&state.labels, 1);
4555 strbuf_release(&state.buf);
4556
4557 return 0;
4558}
4559
f11c9580
NTND
4560int sequencer_make_script(struct repository *r, FILE *out,
4561 int argc, const char **argv,
313a48ea 4562 unsigned flags)
62db5247
JS
4563{
4564 char *format = NULL;
4565 struct pretty_print_context pp = {0};
4566 struct strbuf buf = STRBUF_INIT;
4567 struct rev_info revs;
4568 struct commit *commit;
313a48ea 4569 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 4570 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 4571 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
62db5247 4572
f11c9580 4573 repo_init_revisions(r, &revs, NULL);
62db5247 4574 revs.verbose_header = 1;
1644c73c
JS
4575 if (!rebase_merges)
4576 revs.max_parents = 1;
76ea2358 4577 revs.cherry_mark = 1;
62db5247
JS
4578 revs.limited = 1;
4579 revs.reverse = 1;
4580 revs.right_only = 1;
4581 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4582 revs.topo_order = 1;
4583
4584 revs.pretty_given = 1;
4585 git_config_get_string("rebase.instructionFormat", &format);
4586 if (!format || !*format) {
4587 free(format);
4588 format = xstrdup("%s");
4589 }
4590 get_commit_format(format, &revs);
4591 free(format);
4592 pp.fmt = revs.commit_format;
4593 pp.output_encoding = get_log_output_encoding();
4594
4595 if (setup_revisions(argc, argv, &revs, NULL) > 1)
4596 return error(_("make_script: unhandled options"));
4597
4598 if (prepare_revision_walk(&revs) < 0)
4599 return error(_("make_script: error preparing revisions"));
4600
1644c73c
JS
4601 if (rebase_merges)
4602 return make_script_with_merges(&pp, &revs, out, flags);
4603
62db5247 4604 while ((commit = get_revision(&revs))) {
76ea2358
PW
4605 int is_empty = is_original_commit_empty(commit);
4606
4607 if (!is_empty && (commit->object.flags & PATCHSAME))
4608 continue;
62db5247 4609 strbuf_reset(&buf);
76ea2358 4610 if (!keep_empty && is_empty)
62db5247 4611 strbuf_addf(&buf, "%c ", comment_line_char);
d8ae6c84
LB
4612 strbuf_addf(&buf, "%s %s ", insn,
4613 oid_to_hex(&commit->object.oid));
62db5247
JS
4614 pretty_print_commit(&pp, commit, &buf);
4615 strbuf_addch(&buf, '\n');
4616 fputs(buf.buf, out);
4617 }
4618 strbuf_release(&buf);
4619 return 0;
4620}
3546c8d9 4621
0cce4a27
LB
4622/*
4623 * Add commands after pick and (series of) squash/fixup commands
4624 * in the todo list.
4625 */
005af339
NTND
4626int sequencer_add_exec_commands(struct repository *r,
4627 const char *commands)
3546c8d9
JS
4628{
4629 const char *todo_file = rebase_path_todo();
4630 struct todo_list todo_list = TODO_LIST_INIT;
0cce4a27
LB
4631 struct strbuf *buf = &todo_list.buf;
4632 size_t offset = 0, commands_len = strlen(commands);
1ace63bc 4633 int i, insert;
3546c8d9 4634
0cce4a27 4635 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 4636 return error(_("could not read '%s'."), todo_file);
3546c8d9 4637
005af339 4638 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
3546c8d9
JS
4639 todo_list_release(&todo_list);
4640 return error(_("unusable todo list: '%s'"), todo_file);
4641 }
4642
1ace63bc
JS
4643 /*
4644 * Insert <commands> after every pick. Here, fixup/squash chains
4645 * are considered part of the pick, so we insert the commands *after*
4646 * those chains if there are any.
4647 */
4648 insert = -1;
4649 for (i = 0; i < todo_list.nr; i++) {
4650 enum todo_command command = todo_list.items[i].command;
4651
4652 if (insert >= 0) {
4653 /* skip fixup/squash chains */
4654 if (command == TODO_COMMENT)
4655 continue;
4656 else if (is_fixup(command)) {
4657 insert = i + 1;
4658 continue;
4659 }
4660 strbuf_insert(buf,
4661 todo_list.items[insert].offset_in_buf +
4662 offset, commands, commands_len);
0cce4a27 4663 offset += commands_len;
1ace63bc 4664 insert = -1;
0cce4a27 4665 }
1ace63bc
JS
4666
4667 if (command == TODO_PICK || command == TODO_MERGE)
4668 insert = i + 1;
0cce4a27
LB
4669 }
4670
1ace63bc
JS
4671 /* insert or append final <commands> */
4672 if (insert >= 0 && insert < todo_list.nr)
4673 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4674 offset, commands, commands_len);
4675 else if (insert >= 0 || !offset)
4676 strbuf_add(buf, commands, commands_len);
0cce4a27
LB
4677
4678 i = write_message(buf->buf, buf->len, todo_file, 0);
4679 todo_list_release(&todo_list);
4680 return i;
4681}
3546c8d9 4682
005af339 4683int transform_todos(struct repository *r, unsigned flags)
3546c8d9
JS
4684{
4685 const char *todo_file = rebase_path_todo();
4686 struct todo_list todo_list = TODO_LIST_INIT;
8dccc7a6
LB
4687 struct strbuf buf = STRBUF_INIT;
4688 struct todo_item *item;
4689 int i;
3546c8d9 4690
8dccc7a6 4691 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 4692 return error(_("could not read '%s'."), todo_file);
3546c8d9 4693
005af339 4694 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list)) {
3546c8d9 4695 todo_list_release(&todo_list);
3546c8d9
JS
4696 return error(_("unusable todo list: '%s'"), todo_file);
4697 }
4698
8dccc7a6
LB
4699 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4700 /* if the item is not a command write it and continue */
4701 if (item->command >= TODO_COMMENT) {
4702 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4703 continue;
3546c8d9 4704 }
8dccc7a6
LB
4705
4706 /* add command to the buffer */
d8ae6c84
LB
4707 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4708 strbuf_addch(&buf, command_to_char(item->command));
4709 else
4710 strbuf_addstr(&buf, command_to_string(item->command));
8dccc7a6
LB
4711
4712 /* add commit id */
4713 if (item->commit) {
313a48ea 4714 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
4715 short_commit_name(item->commit) :
4716 oid_to_hex(&item->commit->object.oid);
4717
4c68e7dd
JS
4718 if (item->command == TODO_MERGE) {
4719 if (item->flags & TODO_EDIT_MERGE_MSG)
4720 strbuf_addstr(&buf, " -c");
4721 else
4722 strbuf_addstr(&buf, " -C");
4723 }
4724
8dccc7a6 4725 strbuf_addf(&buf, " %s", oid);
3546c8d9 4726 }
4c68e7dd 4727
8dccc7a6 4728 /* add all the rest */
c7b4d79c
JS
4729 if (!item->arg_len)
4730 strbuf_addch(&buf, '\n');
4731 else
4732 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3546c8d9 4733 }
8dccc7a6
LB
4734
4735 i = write_message(buf.buf, buf.len, todo_file, 0);
3546c8d9 4736 todo_list_release(&todo_list);
8dccc7a6 4737 return i;
3546c8d9 4738}
94399949 4739
44b776c3 4740enum missing_commit_check_level get_missing_commit_check_level(void)
94399949
JS
4741{
4742 const char *value;
4743
4744 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4745 !strcasecmp("ignore", value))
44b776c3 4746 return MISSING_COMMIT_CHECK_IGNORE;
94399949 4747 if (!strcasecmp("warn", value))
44b776c3 4748 return MISSING_COMMIT_CHECK_WARN;
94399949 4749 if (!strcasecmp("error", value))
44b776c3 4750 return MISSING_COMMIT_CHECK_ERROR;
dfab1eac 4751 warning(_("unrecognized setting %s for option "
94399949 4752 "rebase.missingCommitsCheck. Ignoring."), value);
44b776c3 4753 return MISSING_COMMIT_CHECK_IGNORE;
94399949
JS
4754}
4755
8315bd20 4756define_commit_slab(commit_seen, unsigned char);
94399949
JS
4757/*
4758 * Check if the user dropped some commits by mistake
4759 * Behaviour determined by rebase.missingCommitsCheck.
4760 * Check if there is an unrecognized command or a
4761 * bad SHA-1 in a command.
4762 */
005af339 4763int check_todo_list(struct repository *r)
94399949 4764{
44b776c3 4765 enum missing_commit_check_level check_level = get_missing_commit_check_level();
94399949
JS
4766 struct strbuf todo_file = STRBUF_INIT;
4767 struct todo_list todo_list = TODO_LIST_INIT;
4768 struct strbuf missing = STRBUF_INIT;
87805600 4769 int advise_to_edit_todo = 0, res = 0, i;
8315bd20
NTND
4770 struct commit_seen commit_seen;
4771
4772 init_commit_seen(&commit_seen);
94399949
JS
4773
4774 strbuf_addstr(&todo_file, rebase_path_todo());
87805600
RS
4775 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4776 res = -1;
94399949
JS
4777 goto leave_check;
4778 }
94399949 4779 advise_to_edit_todo = res =
005af339 4780 parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
94399949 4781
44b776c3 4782 if (res || check_level == MISSING_COMMIT_CHECK_IGNORE)
94399949
JS
4783 goto leave_check;
4784
4785 /* Mark the commits in git-rebase-todo as seen */
4786 for (i = 0; i < todo_list.nr; i++) {
4787 struct commit *commit = todo_list.items[i].commit;
4788 if (commit)
8315bd20 4789 *commit_seen_at(&commit_seen, commit) = 1;
94399949
JS
4790 }
4791
4792 todo_list_release(&todo_list);
4793 strbuf_addstr(&todo_file, ".backup");
87805600
RS
4794 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4795 res = -1;
94399949
JS
4796 goto leave_check;
4797 }
94399949 4798 strbuf_release(&todo_file);
005af339 4799 res = !!parse_insn_buffer(r, todo_list.buf.buf, &todo_list);
94399949
JS
4800
4801 /* Find commits in git-rebase-todo.backup yet unseen */
4802 for (i = todo_list.nr - 1; i >= 0; i--) {
4803 struct todo_item *item = todo_list.items + i;
4804 struct commit *commit = item->commit;
8315bd20 4805 if (commit && !*commit_seen_at(&commit_seen, commit)) {
94399949
JS
4806 strbuf_addf(&missing, " - %s %.*s\n",
4807 short_commit_name(commit),
4808 item->arg_len, item->arg);
8315bd20 4809 *commit_seen_at(&commit_seen, commit) = 1;
94399949
JS
4810 }
4811 }
4812
4813 /* Warn about missing commits */
4814 if (!missing.len)
4815 goto leave_check;
4816
44b776c3 4817 if (check_level == MISSING_COMMIT_CHECK_ERROR)
94399949
JS
4818 advise_to_edit_todo = res = 1;
4819
4820 fprintf(stderr,
4821 _("Warning: some commits may have been dropped accidentally.\n"
4822 "Dropped commits (newer to older):\n"));
4823
4824 /* Make the list user-friendly and display */
4825 fputs(missing.buf, stderr);
4826 strbuf_release(&missing);
4827
4828 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4829 "explicitly remove a commit.\n\n"
4830 "Use 'git config rebase.missingCommitsCheck' to change "
4831 "the level of warnings.\n"
4832 "The possible behaviours are: ignore, warn, error.\n\n"));
4833
4834leave_check:
8315bd20 4835 clear_commit_seen(&commit_seen);
94399949
JS
4836 strbuf_release(&todo_file);
4837 todo_list_release(&todo_list);
4838
4839 if (advise_to_edit_todo)
4840 fprintf(stderr,
4841 _("You can fix this with 'git rebase --edit-todo' "
4842 "and then run 'git rebase --continue'.\n"
4843 "Or you can abort the rebase with 'git rebase"
4844 " --abort'.\n"));
4845
4846 return res;
4847}
cdac2b01 4848
73646bfd
RS
4849static int rewrite_file(const char *path, const char *buf, size_t len)
4850{
4851 int rc = 0;
c8cee96e 4852 int fd = open(path, O_WRONLY | O_TRUNC);
73646bfd
RS
4853 if (fd < 0)
4854 return error_errno(_("could not open '%s' for writing"), path);
4855 if (write_in_full(fd, buf, len) < 0)
4856 rc = error_errno(_("could not write to '%s'"), path);
9360ec00
SR
4857 if (close(fd) && !rc)
4858 rc = error_errno(_("could not close '%s'"), path);
73646bfd
RS
4859 return rc;
4860}
4861
cdac2b01 4862/* skip picking commits whose parents are unchanged */
005af339 4863static int skip_unnecessary_picks(struct repository *r, struct object_id *output_oid)
cdac2b01
JS
4864{
4865 const char *todo_file = rebase_path_todo();
4866 struct strbuf buf = STRBUF_INIT;
4867 struct todo_list todo_list = TODO_LIST_INIT;
d4ed5d77 4868 struct object_id *parent_oid;
cdac2b01
JS
4869 int fd, i;
4870
4871 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4872 return error(_("could not read 'onto'"));
d4ed5d77 4873 if (get_oid(buf.buf, output_oid)) {
cdac2b01
JS
4874 strbuf_release(&buf);
4875 return error(_("need a HEAD to fixup"));
4876 }
4877 strbuf_release(&buf);
4878
87805600
RS
4879 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4880 return -1;
005af339 4881 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
cdac2b01
JS
4882 todo_list_release(&todo_list);
4883 return -1;
4884 }
4885
4886 for (i = 0; i < todo_list.nr; i++) {
4887 struct todo_item *item = todo_list.items + i;
4888
4889 if (item->command >= TODO_NOOP)
4890 continue;
4891 if (item->command != TODO_PICK)
4892 break;
4893 if (parse_commit(item->commit)) {
4894 todo_list_release(&todo_list);
4895 return error(_("could not parse commit '%s'"),
4896 oid_to_hex(&item->commit->object.oid));
4897 }
4898 if (!item->commit->parents)
4899 break; /* root commit */
4900 if (item->commit->parents->next)
4901 break; /* merge commit */
4902 parent_oid = &item->commit->parents->item->object.oid;
b49ef560 4903 if (!oideq(parent_oid, output_oid))
cdac2b01 4904 break;
d4ed5d77 4905 oidcpy(output_oid, &item->commit->object.oid);
cdac2b01
JS
4906 }
4907 if (i > 0) {
a01c2a5f 4908 int offset = get_item_line_offset(&todo_list, i);
cdac2b01
JS
4909 const char *done_path = rebase_path_done();
4910
4911 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4912 if (fd < 0) {
4913 error_errno(_("could not open '%s' for writing"),
4914 done_path);
4915 todo_list_release(&todo_list);
4916 return -1;
4917 }
4918 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4919 error_errno(_("could not write to '%s'"), done_path);
4920 todo_list_release(&todo_list);
4921 close(fd);
4922 return -1;
4923 }
4924 close(fd);
4925
73646bfd
RS
4926 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4927 todo_list.buf.len - offset) < 0) {
cdac2b01 4928 todo_list_release(&todo_list);
cdac2b01
JS
4929 return -1;
4930 }
cdac2b01
JS
4931
4932 todo_list.current = i;
4933 if (is_fixup(peek_command(&todo_list, 0)))
d4ed5d77 4934 record_in_rewritten(output_oid, peek_command(&todo_list, 0));
cdac2b01
JS
4935 }
4936
4937 todo_list_release(&todo_list);
cdac2b01
JS
4938
4939 return 0;
4940}
c44a4c65 4941
005af339 4942int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873
AG
4943 const char *shortrevisions, const char *onto_name,
4944 const char *onto, const char *orig_head, const char *cmd,
4945 unsigned autosquash)
4946{
4947 const char *shortonto, *todo_file = rebase_path_todo();
4948 struct todo_list todo_list = TODO_LIST_INIT;
4949 struct strbuf *buf = &(todo_list.buf);
4950 struct object_id oid;
4951 struct stat st;
4952
4953 get_oid(onto, &oid);
4954 shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4955
4956 if (!lstat(todo_file, &st) && st.st_size == 0 &&
4957 write_message("noop\n", 5, todo_file, 0))
4958 return -1;
4959
005af339 4960 if (autosquash && rearrange_squash(r))
b97e1873
AG
4961 return -1;
4962
4963 if (cmd && *cmd)
005af339 4964 sequencer_add_exec_commands(r, cmd);
b97e1873
AG
4965
4966 if (strbuf_read_file(buf, todo_file, 0) < 0)
4967 return error_errno(_("could not read '%s'."), todo_file);
4968
005af339 4969 if (parse_insn_buffer(r, buf->buf, &todo_list)) {
b97e1873
AG
4970 todo_list_release(&todo_list);
4971 return error(_("unusable todo list: '%s'"), todo_file);
4972 }
4973
4974 if (count_commands(&todo_list) == 0) {
4975 apply_autostash(opts);
4976 sequencer_remove_state(opts);
4977 todo_list_release(&todo_list);
4978
4979 return error(_("nothing to do"));
4980 }
4981
4982 strbuf_addch(buf, '\n');
4983 strbuf_commented_addf(buf, Q_("Rebase %s onto %s (%d command)",
4984 "Rebase %s onto %s (%d commands)",
4985 count_commands(&todo_list)),
4986 shortrevisions, shortonto, count_commands(&todo_list));
4987 append_todo_help(0, flags & TODO_LIST_KEEP_EMPTY, buf);
4988
4989 if (write_message(buf->buf, buf->len, todo_file, 0)) {
4990 todo_list_release(&todo_list);
4991 return -1;
4992 }
4993
4994 if (copy_file(rebase_path_todo_backup(), todo_file, 0666))
4995 return error(_("could not copy '%s' to '%s'."), todo_file,
4996 rebase_path_todo_backup());
4997
005af339 4998 if (transform_todos(r, flags | TODO_LIST_SHORTEN_IDS))
b97e1873
AG
4999 return error(_("could not transform the todo list"));
5000
5001 strbuf_reset(buf);
5002
5003 if (launch_sequence_editor(todo_file, buf, NULL)) {
5004 apply_autostash(opts);
5005 sequencer_remove_state(opts);
5006 todo_list_release(&todo_list);
5007
5008 return -1;
5009 }
5010
5011 strbuf_stripspace(buf, 1);
5012 if (buf->len == 0) {
5013 apply_autostash(opts);
5014 sequencer_remove_state(opts);
5015 todo_list_release(&todo_list);
5016
5017 return error(_("nothing to do"));
5018 }
5019
5020 todo_list_release(&todo_list);
5021
005af339 5022 if (check_todo_list(r)) {
b97e1873
AG
5023 checkout_onto(opts, onto_name, onto, orig_head);
5024 return -1;
5025 }
5026
005af339 5027 if (transform_todos(r, flags & ~(TODO_LIST_SHORTEN_IDS)))
b97e1873
AG
5028 return error(_("could not transform the todo list"));
5029
005af339 5030 if (opts->allow_ff && skip_unnecessary_picks(r, &oid))
b97e1873
AG
5031 return error(_("could not skip unnecessary pick commands"));
5032
5033 if (checkout_onto(opts, onto_name, oid_to_hex(&oid), orig_head))
5034 return -1;
29d51e21 5035
005af339 5036 if (require_clean_work_tree(r, "rebase", "", 1, 1))
b97e1873
AG
5037 return -1;
5038
005af339 5039 return sequencer_continue(r, opts);
b97e1873
AG
5040}
5041
c44a4c65
JS
5042struct subject2item_entry {
5043 struct hashmap_entry entry;
5044 int i;
5045 char subject[FLEX_ARRAY];
5046};
5047
5048static int subject2item_cmp(const void *fndata,
5049 const struct subject2item_entry *a,
5050 const struct subject2item_entry *b, const void *key)
5051{
5052 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5053}
5054
3cc0287b
NTND
5055define_commit_slab(commit_todo_item, struct todo_item *);
5056
c44a4c65
JS
5057/*
5058 * Rearrange the todo list that has both "pick commit-id msg" and "pick
5059 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5060 * after the former, and change "pick" to "fixup"/"squash".
5061 *
5062 * Note that if the config has specified a custom instruction format, each log
5063 * message will have to be retrieved from the commit (as the oneline in the
5064 * script cannot be trusted) in order to normalize the autosquash arrangement.
5065 */
005af339 5066int rearrange_squash(struct repository *r)
c44a4c65
JS
5067{
5068 const char *todo_file = rebase_path_todo();
5069 struct todo_list todo_list = TODO_LIST_INIT;
5070 struct hashmap subject2item;
87805600 5071 int res = 0, rearranged = 0, *next, *tail, i;
c44a4c65 5072 char **subjects;
3cc0287b 5073 struct commit_todo_item commit_todo;
c44a4c65 5074
87805600
RS
5075 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
5076 return -1;
005af339 5077 if (parse_insn_buffer(r, todo_list.buf.buf, &todo_list) < 0) {
c44a4c65
JS
5078 todo_list_release(&todo_list);
5079 return -1;
5080 }
5081
3cc0287b 5082 init_commit_todo_item(&commit_todo);
c44a4c65
JS
5083 /*
5084 * The hashmap maps onelines to the respective todo list index.
5085 *
5086 * If any items need to be rearranged, the next[i] value will indicate
5087 * which item was moved directly after the i'th.
5088 *
5089 * In that case, last[i] will indicate the index of the latest item to
5090 * be moved to appear after the i'th.
5091 */
5092 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
5093 NULL, todo_list.nr);
5094 ALLOC_ARRAY(next, todo_list.nr);
5095 ALLOC_ARRAY(tail, todo_list.nr);
5096 ALLOC_ARRAY(subjects, todo_list.nr);
5097 for (i = 0; i < todo_list.nr; i++) {
5098 struct strbuf buf = STRBUF_INIT;
5099 struct todo_item *item = todo_list.items + i;
5100 const char *commit_buffer, *subject, *p;
5101 size_t subject_len;
5102 int i2 = -1;
5103 struct subject2item_entry *entry;
5104
5105 next[i] = tail[i] = -1;
2f6b1d13 5106 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
5107 subjects[i] = NULL;
5108 continue;
5109 }
5110
5111 if (is_fixup(item->command)) {
5112 todo_list_release(&todo_list);
3cc0287b 5113 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5114 return error(_("the script was already rearranged."));
5115 }
5116
3cc0287b 5117 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
5118
5119 parse_commit(item->commit);
5120 commit_buffer = get_commit_buffer(item->commit, NULL);
5121 find_commit_subject(commit_buffer, &subject);
5122 format_subject(&buf, subject, " ");
5123 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5124 unuse_commit_buffer(item->commit, commit_buffer);
5125 if ((skip_prefix(subject, "fixup! ", &p) ||
5126 skip_prefix(subject, "squash! ", &p))) {
5127 struct commit *commit2;
5128
5129 for (;;) {
5130 while (isspace(*p))
5131 p++;
5132 if (!skip_prefix(p, "fixup! ", &p) &&
5133 !skip_prefix(p, "squash! ", &p))
5134 break;
5135 }
5136
5137 if ((entry = hashmap_get_from_hash(&subject2item,
5138 strhash(p), p)))
5139 /* found by title */
5140 i2 = entry->i;
5141 else if (!strchr(p, ' ') &&
5142 (commit2 =
5143 lookup_commit_reference_by_name(p)) &&
3cc0287b 5144 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 5145 /* found by commit name */
3cc0287b 5146 i2 = *commit_todo_item_at(&commit_todo, commit2)
c44a4c65
JS
5147 - todo_list.items;
5148 else {
5149 /* copy can be a prefix of the commit subject */
5150 for (i2 = 0; i2 < i; i2++)
5151 if (subjects[i2] &&
5152 starts_with(subjects[i2], p))
5153 break;
5154 if (i2 == i)
5155 i2 = -1;
5156 }
5157 }
5158 if (i2 >= 0) {
5159 rearranged = 1;
5160 todo_list.items[i].command =
5161 starts_with(subject, "fixup!") ?
5162 TODO_FIXUP : TODO_SQUASH;
5163 if (next[i2] < 0)
5164 next[i2] = i;
5165 else
5166 next[tail[i2]] = i;
5167 tail[i2] = i;
5168 } else if (!hashmap_get_from_hash(&subject2item,
5169 strhash(subject), subject)) {
5170 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5171 entry->i = i;
5172 hashmap_entry_init(entry, strhash(entry->subject));
5173 hashmap_put(&subject2item, entry);
5174 }
5175 }
5176
5177 if (rearranged) {
5178 struct strbuf buf = STRBUF_INIT;
5179
5180 for (i = 0; i < todo_list.nr; i++) {
5181 enum todo_command command = todo_list.items[i].command;
5182 int cur = i;
5183
5184 /*
5185 * Initially, all commands are 'pick's. If it is a
5186 * fixup or a squash now, we have rearranged it.
5187 */
5188 if (is_fixup(command))
5189 continue;
5190
5191 while (cur >= 0) {
a01c2a5f
JS
5192 const char *bol =
5193 get_item_line(&todo_list, cur);
5194 const char *eol =
5195 get_item_line(&todo_list, cur + 1);
c44a4c65
JS
5196
5197 /* replace 'pick', by 'fixup' or 'squash' */
5198 command = todo_list.items[cur].command;
5199 if (is_fixup(command)) {
5200 strbuf_addstr(&buf,
5201 todo_command_info[command].str);
5202 bol += strcspn(bol, " \t");
5203 }
5204
5205 strbuf_add(&buf, bol, eol - bol);
5206
5207 cur = next[cur];
5208 }
5209 }
5210
73646bfd 5211 res = rewrite_file(todo_file, buf.buf, buf.len);
c44a4c65
JS
5212 strbuf_release(&buf);
5213 }
5214
5215 free(next);
5216 free(tail);
5217 for (i = 0; i < todo_list.nr; i++)
5218 free(subjects[i]);
5219 free(subjects);
5220 hashmap_free(&subject2item, 1);
5221 todo_list_release(&todo_list);
5222
3cc0287b 5223 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
5224 return res;
5225}