]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
cocci: apply the "revision.h" part of "the_repository.pending"
[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"
5e3aba33 11#include "hook.h"
d807c4a0 12#include "exec-cmd.h"
043a4492
RR
13#include "utf8.h"
14#include "cache-tree.h"
15#include "diff.h"
16#include "revision.h"
17#include "rerere.h"
14c4586c
EN
18#include "merge-ort.h"
19#include "merge-ort-wrappers.h"
043a4492 20#include "refs.h"
dbbcd44f 21#include "strvec.h"
a1c75762 22#include "quote.h"
967dfd4d 23#include "trailer.h"
56dc3ab0 24#include "log-tree.h"
311af526 25#include "wt-status.h"
c44a4c65 26#include "hashmap.h"
a87a6f3c
PW
27#include "notes-utils.h"
28#include "sigchain.h"
9055e401
JS
29#include "unpack-trees.h"
30#include "worktree.h"
1644c73c
JS
31#include "oidmap.h"
32#include "oidset.h"
8315bd20 33#include "commit-slab.h"
65b5f948 34#include "alias.h"
64043556 35#include "commit-reach.h"
b97e1873 36#include "rebase-interactive.h"
0816f1df 37#include "reset.h"
900b50c2 38#include "branch.h"
043a4492
RR
39
40#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26ae337b 41
5fe81438 42static const char sign_off_header[] = "Signed-off-by: ";
cd650a4e 43static const char cherry_picked_prefix[] = "(cherry picked from commit ";
5ed75e2a 44
66618a50
PW
45GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
46
901ba7b1 47static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
8a2a0f53
JS
48
49static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
50static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
51static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
1e41229d 52static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
f932729c 53
84583957
JS
54static GIT_PATH_FUNC(rebase_path, "rebase-merge")
55/*
56 * The file containing rebase commands, comments, and empty lines.
57 * This file is created by "git rebase -i" then edited by the user. As
58 * the lines are processed, they are removed from the front of this
59 * file and written to the tail of 'done'.
60 */
44b776c3 61GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
a930eb03 62GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
b97e1873 63
5a5445d8
AG
64GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
65
1df6df0c
JS
66/*
67 * The rebase command lines that have already been processed. A line
68 * is moved here when it is first handled, before any associated user
69 * actions.
70 */
71static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
ef80069a
JS
72/*
73 * The file to keep track of how many commands were already processed (e.g.
74 * for the prompt).
75 */
9ad36356 76static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
ef80069a
JS
77/*
78 * The file to keep track of how many commands are to be processed in total
79 * (e.g. for the prompt).
80 */
9ad36356 81static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
6e98de72
JS
82/*
83 * The commit message that is planned to be used for any changes that
84 * need to be committed following a user interaction.
85 */
86static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
87/*
88 * The file into which is accumulated the suggested commit message for
89 * squash/fixup commands. When the first of a series of squash/fixups
90 * is seen, the file is created and the commit message from the
91 * previous commit and from the first squash/fixup commit are written
92 * to it. The commit message for each subsequent squash/fixup commit
93 * is appended to the file as it is processed.
6e98de72
JS
94 */
95static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
96/*
97 * If the current series of squash/fixups has not yet included a squash
98 * command, then this file exists and holds the commit message of the
99 * original "pick" commit. (If the series ends without a "squash"
100 * command, then this can be used as the commit message of the combined
101 * commit without opening the editor.)
102 */
103static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
e12a7ef5
JS
104/*
105 * This file contains the list fixup/squash commands that have been
106 * accumulated into message-fixup or message-squash so far.
107 */
108static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
b5a67045
JS
109/*
110 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
111 * GIT_AUTHOR_DATE that will be used for the commit that is currently
112 * being rebased.
113 */
114static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
56dc3ab0
JS
115/*
116 * When an "edit" rebase command is being processed, the SHA1 of the
117 * commit to be edited is recorded in this file. When "git rebase
118 * --continue" is executed, if there are any staged changes then they
119 * will be amended to the HEAD commit, but only provided the HEAD
120 * commit is still the commit to be edited. When any other rebase
121 * command is processed, this file is deleted.
122 */
123static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
124/*
125 * When we stop at a given patch via the "edit" command, this file contains
0512eabd 126 * the commit object name of the corresponding patch.
56dc3ab0
JS
127 */
128static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
25cb8df9
JS
129/*
130 * For the post-rewrite hook, we make a list of rewritten commits and
131 * their new sha1s. The rewritten-pending list keeps the sha1s of
132 * commits that have been processed, but not committed yet,
133 * e.g. because they are waiting for a 'squash' command.
134 */
135static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
136static GIT_PATH_FUNC(rebase_path_rewritten_pending,
137 "rebase-merge/rewritten-pending")
9055e401 138
d87d48b2 139/*
15beaaa3 140 * The path of the file containing the OID of the "squash onto" commit, i.e.
d87d48b2
JS
141 * the dummy commit used for `reset [new root]`.
142 */
143static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
144
9055e401
JS
145/*
146 * The path of the file listing refs that need to be deleted after the rebase
147 * finishes. This is used by the `label` command to record the need for cleanup.
148 */
149static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
150
aa7f2fd1
DS
151/*
152 * The update-refs file stores a list of refs that will be updated at the end
153 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
154 * update the OIDs for the refs in this file, but the refs are not updated
155 * until the end of the rebase sequence.
156 *
157 * rebase_path_update_refs() returns the path to this file for a given
158 * worktree directory. For the current worktree, pass the_repository->gitdir.
159 */
160static char *rebase_path_update_refs(const char *wt_git_dir)
161{
162 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
163}
164
a1c75762
JS
165/*
166 * The following files are written by git-rebase just after parsing the
65850686 167 * command-line.
a1c75762
JS
168 */
169static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
7573cec5 170static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
a3894aad 171static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
556907f1
JS
172static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
173static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
899b49c4 174static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
a852ec7f 175static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
4b83ce9f
JS
176static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
177static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
796c7972 178static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
ca6c6b45
JS
179static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
180static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
9b6d7a62 181static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
d421afa0 182static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
e5b32bff 183static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
e98c4269
EN
184static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
185static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
b5a67045 186
aa7f2fd1
DS
187/**
188 * A 'struct update_refs_record' represents a value in the update-refs
189 * list. We use a string_list to map refs to these (before, after) pairs.
190 */
191struct update_ref_record {
192 struct object_id before;
193 struct object_id after;
194};
195
89fc0b53
DS
196static struct update_ref_record *init_update_ref_record(const char *ref)
197{
198 struct update_ref_record *rec;
199
200 CALLOC_ARRAY(rec, 1);
201
202 oidcpy(&rec->before, null_oid());
203 oidcpy(&rec->after, null_oid());
204
205 /* This may fail, but that's fine, we will keep the null OID. */
206 read_ref(ref, &rec->before);
207
208 return rec;
209}
210
28d6daed
PW
211static int git_sequencer_config(const char *k, const char *v, void *cb)
212{
213 struct replay_opts *opts = cb;
214 int status;
215
216 if (!strcmp(k, "commit.cleanup")) {
217 const char *s;
218
219 status = git_config_string(&s, k, v);
220 if (status)
221 return status;
222
d74f3e58 223 if (!strcmp(s, "verbatim")) {
28d6daed 224 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
225 opts->explicit_cleanup = 1;
226 } else if (!strcmp(s, "whitespace")) {
28d6daed 227 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
d74f3e58
PW
228 opts->explicit_cleanup = 1;
229 } else if (!strcmp(s, "strip")) {
28d6daed 230 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
d74f3e58
PW
231 opts->explicit_cleanup = 1;
232 } else if (!strcmp(s, "scissors")) {
1a2b985f 233 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
d74f3e58
PW
234 opts->explicit_cleanup = 1;
235 } else {
28d6daed
PW
236 warning(_("invalid commit message cleanup mode '%s'"),
237 s);
d74f3e58 238 }
28d6daed 239
f40f3c16 240 free((char *)s);
28d6daed
PW
241 return status;
242 }
243
244 if (!strcmp(k, "commit.gpgsign")) {
ed1e5282 245 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
28d6daed
PW
246 return 0;
247 }
248
14c4586c
EN
249 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
250 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
251 if (ret == 0) {
252 /*
253 * pull.twohead is allowed to be multi-valued; we only
254 * care about the first value.
255 */
256 char *tmp = strchr(opts->default_strategy, ' ');
257 if (tmp)
258 *tmp = '\0';
259 }
260 return ret;
261 }
262
191faaf7 263 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
43966ab3
JH
264 opts->commit_use_reference = git_config_bool(k, v);
265
28d6daed
PW
266 status = git_gpg_config(k, v, NULL);
267 if (status)
268 return status;
269
270 return git_diff_basic_config(k, v, NULL);
271}
272
273void sequencer_init_config(struct replay_opts *opts)
274{
275 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
276 git_config(git_sequencer_config, opts);
277}
278
b5a67045
JS
279static inline int is_rebase_i(const struct replay_opts *opts)
280{
84583957 281 return opts->action == REPLAY_INTERACTIVE_REBASE;
b5a67045
JS
282}
283
285abf56
JS
284static const char *get_dir(const struct replay_opts *opts)
285{
84583957
JS
286 if (is_rebase_i(opts))
287 return rebase_path();
285abf56
JS
288 return git_path_seq_dir();
289}
290
c0246501
JS
291static const char *get_todo_path(const struct replay_opts *opts)
292{
84583957
JS
293 if (is_rebase_i(opts))
294 return rebase_path_todo();
c0246501
JS
295 return git_path_todo_file();
296}
297
bab4d109
BC
298/*
299 * Returns 0 for non-conforming footer
300 * Returns 1 for conforming footer
301 * Returns 2 when sob exists within conforming footer
302 * Returns 3 when sob exists within conforming footer as last entry
303 */
304static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
66e83d9b 305 size_t ignore_footer)
b971e04f 306{
00a21f5c 307 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
967dfd4d 308 struct trailer_info info;
a3b636e2 309 size_t i;
967dfd4d 310 int found_sob = 0, found_sob_last = 0;
9dad073d 311 char saved_char;
b971e04f 312
ffce7f59
JK
313 opts.no_divider = 1;
314
9dad073d
JK
315 if (ignore_footer) {
316 saved_char = sb->buf[sb->len - ignore_footer];
317 sb->buf[sb->len - ignore_footer] = '\0';
318 }
319
00a21f5c 320 trailer_info_get(&info, sb->buf, &opts);
b971e04f 321
9dad073d
JK
322 if (ignore_footer)
323 sb->buf[sb->len - ignore_footer] = saved_char;
324
967dfd4d 325 if (info.trailer_start == info.trailer_end)
b971e04f
BC
326 return 0;
327
967dfd4d
JT
328 for (i = 0; i < info.trailer_nr; i++)
329 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
330 found_sob = 1;
331 if (i == info.trailer_nr - 1)
332 found_sob_last = 1;
333 }
b971e04f 334
967dfd4d 335 trailer_info_release(&info);
bab4d109 336
967dfd4d 337 if (found_sob_last)
bab4d109
BC
338 return 3;
339 if (found_sob)
340 return 2;
b971e04f
BC
341 return 1;
342}
5ed75e2a 343
a1c75762
JS
344static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
345{
346 static struct strbuf buf = STRBUF_INIT;
347
348 strbuf_reset(&buf);
349 if (opts->gpg_sign)
350 sq_quotef(&buf, "-S%s", opts->gpg_sign);
351 return buf.buf;
352}
353
9ff2f060 354void replay_opts_release(struct replay_opts *opts)
6a09c3a9
ÆAB
355{
356 free(opts->gpg_sign);
357 free(opts->reflog_action);
358 free(opts->default_strategy);
359 free(opts->strategy);
360 for (size_t i = 0; i < opts->xopts_nr; i++)
361 free(opts->xopts[i]);
362 free(opts->xopts);
363 strbuf_release(&opts->current_fixups);
a6a700a4
ÆAB
364 if (opts->revs)
365 release_revisions(opts->revs);
366 free(opts->revs);
6a09c3a9
ÆAB
367}
368
2863584f 369int sequencer_remove_state(struct replay_opts *opts)
26ae337b 370{
9055e401 371 struct strbuf buf = STRBUF_INIT;
6a09c3a9 372 int ret = 0;
03a4e260 373
9055e401
JS
374 if (is_rebase_i(opts) &&
375 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
376 char *p = buf.buf;
377 while (*p) {
378 char *eol = strchr(p, '\n');
379 if (eol)
380 *eol = '\0';
c2417d3a 381 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
9055e401 382 warning(_("could not delete '%s'"), p);
37e9ee5c
PW
383 ret = -1;
384 }
9055e401
JS
385 if (!eol)
386 break;
387 p = eol + 1;
388 }
389 }
390
9055e401
JS
391 strbuf_reset(&buf);
392 strbuf_addstr(&buf, get_dir(opts));
37e9ee5c
PW
393 if (remove_dir_recursively(&buf, 0))
394 ret = error(_("could not remove '%s'"), buf.buf);
9055e401 395 strbuf_release(&buf);
2863584f 396
37e9ee5c 397 return ret;
26ae337b 398}
043a4492
RR
399
400static const char *action_name(const struct replay_opts *opts)
401{
84583957
JS
402 switch (opts->action) {
403 case REPLAY_REVERT:
404 return N_("revert");
405 case REPLAY_PICK:
406 return N_("cherry-pick");
407 case REPLAY_INTERACTIVE_REBASE:
c2417d3a 408 return N_("rebase");
84583957 409 }
1a07e59c 410 die(_("unknown action: %d"), opts->action);
043a4492
RR
411}
412
043a4492
RR
413struct commit_message {
414 char *parent_label;
7b35eaf8
JK
415 char *label;
416 char *subject;
043a4492
RR
417 const char *message;
418};
419
39755964
JS
420static const char *short_commit_name(struct commit *commit)
421{
d850b7a5
ÆAB
422 return repo_find_unique_abbrev(the_repository, &commit->object.oid,
423 DEFAULT_ABBREV);
39755964
JS
424}
425
043a4492
RR
426static int get_message(struct commit *commit, struct commit_message *out)
427{
043a4492 428 const char *abbrev, *subject;
7b35eaf8 429 int subject_len;
043a4492 430
ecb5091f
ÆAB
431 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
432 get_commit_output_encoding());
39755964 433 abbrev = short_commit_name(commit);
043a4492
RR
434
435 subject_len = find_commit_subject(out->message, &subject);
436
7b35eaf8 437 out->subject = xmemdupz(subject, subject_len);
7d056dea 438 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
7b35eaf8
JK
439 out->parent_label = xstrfmt("parent of %s", out->label);
440
043a4492
RR
441 return 0;
442}
443
d74a4e57 444static void free_message(struct commit *commit, struct commit_message *msg)
043a4492
RR
445{
446 free(msg->parent_label);
7b35eaf8
JK
447 free(msg->label);
448 free(msg->subject);
ecb5091f 449 repo_unuse_commit_buffer(the_repository, commit, msg->message);
043a4492
RR
450}
451
005af339
NTND
452static void print_advice(struct repository *r, int show_hint,
453 struct replay_opts *opts)
043a4492
RR
454{
455 char *msg = getenv("GIT_CHERRY_PICK_HELP");
456
457 if (msg) {
f172556b 458 advise("%s\n", msg);
043a4492 459 /*
41ccfdd9 460 * A conflict has occurred but the porcelain
043a4492
RR
461 * (typically rebase --interactive) wants to take care
462 * of the commit itself so remove CHERRY_PICK_HEAD
463 */
c8e4159e
HWN
464 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
465 NULL, 0);
043a4492
RR
466 return;
467 }
468
ed727b19
PH
469 if (show_hint) {
470 if (opts->no_commit)
471 advise(_("after resolving the conflicts, mark the corrected paths\n"
472 "with 'git add <paths>' or 'git rm <paths>'"));
f172556b
ZH
473 else if (opts->action == REPLAY_PICK)
474 advise(_("After resolving the conflicts, mark them with\n"
475 "\"git add/rm <pathspec>\", then run\n"
476 "\"git cherry-pick --continue\".\n"
477 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
478 "To abort and get back to the state before \"git cherry-pick\",\n"
479 "run \"git cherry-pick --abort\"."));
480 else if (opts->action == REPLAY_REVERT)
481 advise(_("After resolving the conflicts, mark them with\n"
482 "\"git add/rm <pathspec>\", then run\n"
483 "\"git revert --continue\".\n"
484 "You can instead skip this commit with \"git revert --skip\".\n"
485 "To abort and get back to the state before \"git revert\",\n"
486 "run \"git revert --abort\"."));
ed727b19 487 else
f172556b 488 BUG("unexpected pick action in print_advice()");
ed727b19 489 }
043a4492
RR
490}
491
ddb81e50
AG
492static int write_message(const void *buf, size_t len, const char *filename,
493 int append_eol)
043a4492 494{
14bca6c6 495 struct lock_file msg_file = LOCK_INIT;
043a4492 496
4ef3d8f0
JS
497 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
498 if (msg_fd < 0)
93b3df6f 499 return error_errno(_("could not lock '%s'"), filename);
75871495 500 if (write_in_full(msg_fd, buf, len) < 0) {
bf5c0571 501 error_errno(_("could not write to '%s'"), filename);
4f66c837 502 rollback_lock_file(&msg_file);
bf5c0571 503 return -1;
4f66c837 504 }
f56fffef 505 if (append_eol && write(msg_fd, "\n", 1) < 0) {
bf5c0571 506 error_errno(_("could not write eol to '%s'"), filename);
f56fffef 507 rollback_lock_file(&msg_file);
bf5c0571 508 return -1;
f56fffef 509 }
350292a1
510 if (commit_lock_file(&msg_file) < 0)
511 return error(_("failed to finalize '%s'"), filename);
4ef3d8f0
JS
512
513 return 0;
043a4492
RR
514}
515
c20de8be 516int read_oneliner(struct strbuf *buf,
3442c3d1 517 const char *path, unsigned flags)
1dfc84e9
JS
518{
519 int orig_len = buf->len;
520
1dfc84e9 521 if (strbuf_read_file(buf, path, 0) < 0) {
bfa50c2c
DL
522 if ((flags & READ_ONELINER_WARN_MISSING) ||
523 (errno != ENOENT && errno != ENOTDIR))
5b2f6d9c 524 warning_errno(_("could not read '%s'"), path);
1dfc84e9
JS
525 return 0;
526 }
527
528 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
529 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
530 --buf->len;
531 buf->buf[buf->len] = '\0';
532 }
533
3442c3d1 534 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
1dfc84e9
JS
535 return 0;
536
537 return 1;
538}
539
005af339 540static struct tree *empty_tree(struct repository *r)
043a4492 541{
005af339 542 return lookup_tree(r, the_hash_algo->empty_tree);
043a4492
RR
543}
544
e1ff0a32 545static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
043a4492 546{
e1ff0a32 547 if (repo_read_index_unmerged(repo))
1c8dfc36 548 return error_resolve_conflict(action_name(opts));
043a4492 549
93b3df6f 550 error(_("your local changes would be overwritten by %s."),
c28cbc5e 551 _(action_name(opts)));
043a4492 552
ed9bff08 553 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
93b3df6f 554 advise(_("commit your changes or stash them to proceed."));
043a4492
RR
555 return -1;
556}
557
1e41229d
SB
558static void update_abort_safety_file(void)
559{
560 struct object_id head;
561
562 /* Do nothing on a single-pick */
563 if (!file_exists(git_path_seq_dir()))
564 return;
565
d850b7a5 566 if (!repo_get_oid(the_repository, "HEAD", &head))
1e41229d
SB
567 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
568 else
569 write_file(git_path_abort_safety_file(), "%s", "");
570}
571
f11c9580
NTND
572static int fast_forward_to(struct repository *r,
573 const struct object_id *to,
574 const struct object_id *from,
575 int unborn,
576 struct replay_opts *opts)
043a4492 577{
d668d16c 578 struct ref_transaction *transaction;
eb4be1cb 579 struct strbuf sb = STRBUF_INIT;
d668d16c 580 struct strbuf err = STRBUF_INIT;
043a4492 581
e1ff0a32 582 repo_read_index(r);
f11c9580 583 if (checkout_fast_forward(r, from, to, 1))
0e408fc3 584 return -1; /* the callee should have complained already */
651ab9f5 585
5670e0ec 586 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
d668d16c
RS
587
588 transaction = ref_transaction_begin(&err);
589 if (!transaction ||
590 ref_transaction_update(transaction, "HEAD",
d87d48b2 591 to, unborn && !is_rebase_i(opts) ?
14228447 592 null_oid() : from,
1d147bdf 593 0, sb.buf, &err) ||
db7516ab 594 ref_transaction_commit(transaction, &err)) {
d668d16c
RS
595 ref_transaction_free(transaction);
596 error("%s", err.buf);
597 strbuf_release(&sb);
598 strbuf_release(&err);
599 return -1;
600 }
651ab9f5 601
eb4be1cb 602 strbuf_release(&sb);
d668d16c
RS
603 strbuf_release(&err);
604 ref_transaction_free(transaction);
1e41229d 605 update_abort_safety_file();
d668d16c 606 return 0;
043a4492
RR
607}
608
f29cd862
DL
609enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
610 int use_editor)
611{
612 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
613 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
614 COMMIT_MSG_CLEANUP_SPACE;
615 else if (!strcmp(cleanup_arg, "verbatim"))
616 return COMMIT_MSG_CLEANUP_NONE;
617 else if (!strcmp(cleanup_arg, "whitespace"))
618 return COMMIT_MSG_CLEANUP_SPACE;
619 else if (!strcmp(cleanup_arg, "strip"))
620 return COMMIT_MSG_CLEANUP_ALL;
621 else if (!strcmp(cleanup_arg, "scissors"))
622 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
623 COMMIT_MSG_CLEANUP_SPACE;
624 else
625 die(_("Invalid cleanup mode %s"), cleanup_arg);
626}
627
dc42e9a8
PW
628/*
629 * NB using int rather than enum cleanup_mode to stop clang's
630 * -Wtautological-constant-out-of-range-compare complaining that the comparison
631 * is always true.
632 */
633static const char *describe_cleanup_mode(int cleanup_mode)
634{
635 static const char *modes[] = { "whitespace",
636 "verbatim",
637 "scissors",
638 "strip" };
639
640 if (cleanup_mode < ARRAY_SIZE(modes))
641 return modes[cleanup_mode];
642
643 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
644}
645
f11c9580 646void append_conflicts_hint(struct index_state *istate,
1a2b985f 647 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
75c961b7
JH
648{
649 int i;
650
1a2b985f
DL
651 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
652 strbuf_addch(msgbuf, '\n');
653 wt_status_append_cut_line(msgbuf);
654 strbuf_addch(msgbuf, comment_line_char);
655 }
656
261f315b
JH
657 strbuf_addch(msgbuf, '\n');
658 strbuf_commented_addf(msgbuf, "Conflicts:\n");
f11c9580
NTND
659 for (i = 0; i < istate->cache_nr;) {
660 const struct cache_entry *ce = istate->cache[i++];
75c961b7 661 if (ce_stage(ce)) {
261f315b 662 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
f11c9580
NTND
663 while (i < istate->cache_nr &&
664 !strcmp(ce->name, istate->cache[i]->name))
75c961b7
JH
665 i++;
666 }
667 }
668}
669
f11c9580
NTND
670static int do_recursive_merge(struct repository *r,
671 struct commit *base, struct commit *next,
043a4492 672 const char *base_label, const char *next_label,
48be4c62 673 struct object_id *head, struct strbuf *msgbuf,
043a4492
RR
674 struct replay_opts *opts)
675{
676 struct merge_options o;
14c4586c 677 struct merge_result result;
b4db8a2b 678 struct tree *next_tree, *base_tree, *head_tree;
14c4586c 679 int clean, show_output;
d20bc01a 680 int i;
14bca6c6 681 struct lock_file index_lock = LOCK_INIT;
043a4492 682
3a95f31d 683 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
bd588867 684 return -1;
043a4492 685
e1ff0a32 686 repo_read_index(r);
043a4492 687
0d6caa2d 688 init_merge_options(&o, r);
043a4492
RR
689 o.ancestor = base ? base_label : "(empty tree)";
690 o.branch1 = "HEAD";
691 o.branch2 = next ? next_label : "(empty tree)";
62fdb652
JS
692 if (is_rebase_i(opts))
693 o.buffer_output = 2;
9268cf4a 694 o.show_rename_progress = 1;
043a4492
RR
695
696 head_tree = parse_tree_indirect(head);
ecb5091f
ÆAB
697 next_tree = next ? repo_get_commit_tree(the_repository, next) : empty_tree(r);
698 base_tree = base ? repo_get_commit_tree(the_repository, base) : empty_tree(r);
043a4492 699
d20bc01a
JK
700 for (i = 0; i < opts->xopts_nr; i++)
701 parse_merge_opt(&o, opts->xopts[i]);
043a4492 702
6a5fb966 703 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
14c4586c
EN
704 memset(&result, 0, sizeof(result));
705 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
706 &result);
707 show_output = !is_rebase_i(opts) || !result.clean;
708 /*
709 * TODO: merge_switch_to_result will update index/working tree;
710 * we only really want to do that if !result.clean || this is
711 * the final patch to be picked. But determining this is the
712 * final patch would take some work, and "head_tree" would need
713 * to be replace with the tree the index matched before we
714 * started doing any picks.
715 */
716 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
717 clean = result.clean;
718 } else {
5d9c9349 719 ensure_full_index(r->index);
14c4586c
EN
720 clean = merge_trees(&o, head_tree, next_tree, base_tree);
721 if (is_rebase_i(opts) && clean <= 0)
722 fputs(o.obuf.buf, stdout);
723 strbuf_release(&o.obuf);
724 }
64816524
725 if (clean < 0) {
726 rollback_lock_file(&index_lock);
f241ff0d 727 return clean;
64816524 728 }
043a4492 729
f11c9580 730 if (write_locked_index(r->index, &index_lock,
61000814 731 COMMIT_LOCK | SKIP_IF_UNCHANGED))
66f5f6dc
ÆAB
732 /*
733 * TRANSLATORS: %s will be "revert", "cherry-pick" or
c2417d3a 734 * "rebase".
84583957 735 */
c527b55e 736 return error(_("%s: Unable to write new index file"),
c28cbc5e 737 _(action_name(opts)));
043a4492 738
75c961b7 739 if (!clean)
1a2b985f
DL
740 append_conflicts_hint(r->index, msgbuf,
741 opts->default_msg_cleanup);
043a4492
RR
742
743 return !clean;
744}
745
f11c9580 746static struct object_id *get_cache_tree_oid(struct index_state *istate)
ba97aea1 747{
f11c9580
NTND
748 if (!cache_tree_fully_valid(istate->cache_tree))
749 if (cache_tree_update(istate, 0)) {
ba97aea1
JS
750 error(_("unable to update cache tree"));
751 return NULL;
752 }
753
f11c9580 754 return &istate->cache_tree->oid;
ba97aea1
JS
755}
756
005af339 757static int is_index_unchanged(struct repository *r)
b27cfb0d 758{
ba97aea1 759 struct object_id head_oid, *cache_tree_oid;
b27cfb0d 760 struct commit *head_commit;
005af339 761 struct index_state *istate = r->index;
b27cfb0d 762
49e61479 763 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
aee42e1f 764 return error(_("could not resolve HEAD commit"));
b27cfb0d 765
005af339 766 head_commit = lookup_commit(r, &head_oid);
4b580061
NH
767
768 /*
769 * If head_commit is NULL, check_commit, called from
770 * lookup_commit, would have indicated that head_commit is not
771 * a commit object already. parse_commit() will return failure
772 * without further complaints in such a case. Otherwise, if
773 * the commit is invalid, parse_commit() will complain. So
774 * there is nothing for us to say here. Just return failure.
775 */
ecb5091f 776 if (repo_parse_commit(the_repository, head_commit))
4b580061 777 return -1;
b27cfb0d 778
f11c9580 779 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
ba97aea1 780 return -1;
b27cfb0d 781
4a7e27e9 782 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
b27cfb0d
NH
783}
784
0473f28a
JS
785static int write_author_script(const char *message)
786{
787 struct strbuf buf = STRBUF_INIT;
788 const char *eol;
789 int res;
790
791 for (;;)
792 if (!*message || starts_with(message, "\n")) {
793missing_author:
794 /* Missing 'author' line? */
795 unlink(rebase_path_author_script());
796 return 0;
797 } else if (skip_prefix(message, "author ", &message))
798 break;
799 else if ((eol = strchr(message, '\n')))
800 message = eol + 1;
801 else
802 goto missing_author;
803
804 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
805 while (*message && *message != '\n' && *message != '\r')
806 if (skip_prefix(message, " <", &message))
807 break;
808 else if (*message != '\'')
809 strbuf_addch(&buf, *(message++));
810 else
4aa5ff94 811 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
812 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
813 while (*message && *message != '\n' && *message != '\r')
814 if (skip_prefix(message, "> ", &message))
815 break;
816 else if (*message != '\'')
817 strbuf_addch(&buf, *(message++));
818 else
4aa5ff94 819 strbuf_addf(&buf, "'\\%c'", *(message++));
0473f28a
JS
820 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
821 while (*message && *message != '\n' && *message != '\r')
822 if (*message != '\'')
823 strbuf_addch(&buf, *(message++));
824 else
4aa5ff94 825 strbuf_addf(&buf, "'\\%c'", *(message++));
0f16c09a 826 strbuf_addch(&buf, '\'');
0473f28a
JS
827 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
828 strbuf_release(&buf);
829 return res;
830}
831
bcd33ec2
PW
832/**
833 * Take a series of KEY='VALUE' lines where VALUE part is
834 * sq-quoted, and append <KEY, VALUE> at the end of the string list
835 */
836static int parse_key_value_squoted(char *buf, struct string_list *list)
837{
838 while (*buf) {
839 struct string_list_item *item;
840 char *np;
841 char *cp = strchr(buf, '=');
842 if (!cp) {
843 np = strchrnul(buf, '\n');
844 return error(_("no key present in '%.*s'"),
845 (int) (np - buf), buf);
846 }
847 np = strchrnul(cp, '\n');
848 *cp++ = '\0';
849 item = string_list_append(list, buf);
850
851 buf = np + (*np == '\n');
852 *np = '\0';
853 cp = sq_dequote(cp);
854 if (!cp)
855 return error(_("unable to dequote value of '%s'"),
856 item->string);
857 item->util = xstrdup(cp);
858 }
859 return 0;
860}
4aa5ff94 861
bcd33ec2
PW
862/**
863 * Reads and parses the state directory's "author-script" file, and sets name,
864 * email and date accordingly.
865 * Returns 0 on success, -1 if the file could not be parsed.
866 *
867 * The author script is of the format:
868 *
869 * GIT_AUTHOR_NAME='$author_name'
870 * GIT_AUTHOR_EMAIL='$author_email'
871 * GIT_AUTHOR_DATE='$author_date'
872 *
873 * where $author_name, $author_email and $author_date are quoted. We are strict
c3c003e7 874 * with our parsing, as the file was meant to be eval'd in the now-removed
bcd33ec2
PW
875 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
876 * from what this function expects, it is better to bail out than to do
877 * something that the user does not expect.
4aa5ff94 878 */
bcd33ec2
PW
879int read_author_script(const char *path, char **name, char **email, char **date,
880 int allow_missing)
4aa5ff94 881{
bcd33ec2
PW
882 struct strbuf buf = STRBUF_INIT;
883 struct string_list kv = STRING_LIST_INIT_DUP;
884 int retval = -1; /* assume failure */
885 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
4aa5ff94 886
bcd33ec2
PW
887 if (strbuf_read_file(&buf, path, 256) <= 0) {
888 strbuf_release(&buf);
889 if (errno == ENOENT && allow_missing)
890 return 0;
891 else
892 return error_errno(_("could not open '%s' for reading"),
893 path);
894 }
895
896 if (parse_key_value_squoted(buf.buf, &kv))
897 goto finish;
898
899 for (i = 0; i < kv.nr; i++) {
900 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
901 if (name_i != -2)
902 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
903 else
904 name_i = i;
905 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
906 if (email_i != -2)
907 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
908 else
909 email_i = i;
910 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
911 if (date_i != -2)
912 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
913 else
914 date_i = i;
915 } else {
916 err = error(_("unknown variable '%s'"),
917 kv.items[i].string);
918 }
919 }
920 if (name_i == -2)
921 error(_("missing 'GIT_AUTHOR_NAME'"));
922 if (email_i == -2)
923 error(_("missing 'GIT_AUTHOR_EMAIL'"));
924 if (date_i == -2)
925 error(_("missing 'GIT_AUTHOR_DATE'"));
45350aeb 926 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
bcd33ec2 927 goto finish;
4d924528
JH
928 *name = kv.items[name_i].util;
929 *email = kv.items[email_i].util;
930 *date = kv.items[date_i].util;
bcd33ec2
PW
931 retval = 0;
932finish:
933 string_list_clear(&kv, !!retval);
934 strbuf_release(&buf);
935 return retval;
4aa5ff94
PW
936}
937
b5a67045 938/*
4d010a75 939 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
c972bf4c 940 * file with shell quoting into struct strvec. Returns -1 on
4d010a75 941 * error, 0 otherwise.
b5a67045 942 */
c972bf4c 943static int read_env_script(struct strvec *env)
b5a67045 944{
4d010a75 945 char *name, *email, *date;
b5a67045 946
4d010a75
PW
947 if (read_author_script(rebase_path_author_script(),
948 &name, &email, &date, 0))
a2a20b0d 949 return -1;
b5a67045 950
c972bf4c
JK
951 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
952 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
953 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
4d010a75
PW
954 free(name);
955 free(email);
956 free(date);
b5a67045 957
a2a20b0d 958 return 0;
b5a67045
JS
959}
960
356ee465
PW
961static char *get_author(const char *message)
962{
963 size_t len;
964 const char *a;
965
966 a = find_commit_header(message, "author", &len);
967 if (a)
968 return xmemdupz(a, len);
969
970 return NULL;
971}
972
b3193252 973static const char *author_date_from_env(const struct strvec *env)
7573cec5
PW
974{
975 int i;
976 const char *date;
977
9c31b19d
JH
978 for (i = 0; i < env->nr; i++)
979 if (skip_prefix(env->v[i],
7573cec5
PW
980 "GIT_AUTHOR_DATE=", &date))
981 return date;
982 /*
983 * If GIT_AUTHOR_DATE is missing we should have already errored out when
984 * reading the script
985 */
986 BUG("GIT_AUTHOR_DATE missing from author script");
987}
988
791eb870
JS
989static const char staged_changes_advice[] =
990N_("you have staged changes in your working tree\n"
991"If these changes are meant to be squashed into the previous commit, run:\n"
992"\n"
993" git commit --amend %s\n"
994"\n"
995"If they are meant to go into a new commit, run:\n"
996"\n"
997" git commit %s\n"
998"\n"
999"In both cases, once you're done, continue with:\n"
1000"\n"
1001" git rebase --continue\n");
1002
789b3eff
JS
1003#define ALLOW_EMPTY (1<<0)
1004#define EDIT_MSG (1<<1)
1005#define AMEND_MSG (1<<2)
1006#define CLEANUP_MSG (1<<3)
b92ff6e8 1007#define VERIFY_MSG (1<<4)
d87d48b2 1008#define CREATE_ROOT_COMMIT (1<<5)
f7d42cee 1009#define VERBATIM_MSG (1<<6)
789b3eff 1010
34bec2c4
AG
1011static int run_command_silent_on_success(struct child_process *cmd)
1012{
1013 struct strbuf buf = STRBUF_INIT;
1014 int rc;
1015
1016 cmd->stdout_to_stderr = 1;
1017 rc = pipe_command(cmd,
1018 NULL, 0,
1019 NULL, 0,
1020 &buf, 0);
1021
1022 if (rc)
1023 fputs(buf.buf, stderr);
1024 strbuf_release(&buf);
1025 return rc;
1026}
1027
043a4492
RR
1028/*
1029 * If we are cherry-pick, and if the merge did not result in
1030 * hand-editing, we will hit this commit and inherit the original
1031 * author date and name.
b5a67045 1032 *
043a4492
RR
1033 * If we are revert, or if our cherry-pick results in a hand merge,
1034 * we had better say that the current user is responsible for that.
b5a67045
JS
1035 *
1036 * An exception is when run_git_commit() is called during an
1037 * interactive rebase: in that case, we will want to retain the
1038 * author metadata.
043a4492 1039 */
20f4b044 1040static int run_git_commit(const char *defmsg,
f11c9580 1041 struct replay_opts *opts,
789b3eff 1042 unsigned int flags)
043a4492 1043{
07d968ef 1044 struct child_process cmd = CHILD_PROCESS_INIT;
b27cfb0d 1045
f7d42cee
JS
1046 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1047 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1048
07d968ef
JS
1049 cmd.git_cmd = 1;
1050
9d6b9df1
PW
1051 if (is_rebase_i(opts) &&
1052 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1053 !(!defmsg && (flags & AMEND_MSG))) &&
29fda24d 1054 read_env_script(&cmd.env)) {
34bec2c4 1055 const char *gpg_opt = gpg_sign_opt_quoted(opts);
a1c75762 1056
34bec2c4
AG
1057 return error(_(staged_changes_advice),
1058 gpg_opt, gpg_opt);
b5a67045
JS
1059 }
1060
d188a60d
PW
1061 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1062
7573cec5 1063 if (opts->committer_date_is_author_date)
29fda24d 1064 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
9c31b19d
JH
1065 opts->ignore_date ?
1066 "" :
b3193252 1067 author_date_from_env(&cmd.env));
a3894aad 1068 if (opts->ignore_date)
29fda24d 1069 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
7573cec5 1070
c972bf4c 1071 strvec_push(&cmd.args, "commit");
043a4492 1072
b92ff6e8 1073 if (!(flags & VERIFY_MSG))
c972bf4c 1074 strvec_push(&cmd.args, "-n");
789b3eff 1075 if ((flags & AMEND_MSG))
c972bf4c 1076 strvec_push(&cmd.args, "--amend");
3bdd5522 1077 if (opts->gpg_sign)
c972bf4c 1078 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
cf0ad4d1 1079 else
c972bf4c 1080 strvec_push(&cmd.args, "--no-gpg-sign");
b5a67045 1081 if (defmsg)
c972bf4c 1082 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
dc4b5bc3 1083 else if (!(flags & EDIT_MSG))
c972bf4c 1084 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
789b3eff 1085 if ((flags & CLEANUP_MSG))
c972bf4c 1086 strvec_push(&cmd.args, "--cleanup=strip");
f7d42cee
JS
1087 if ((flags & VERBATIM_MSG))
1088 strvec_push(&cmd.args, "--cleanup=verbatim");
789b3eff 1089 if ((flags & EDIT_MSG))
c972bf4c 1090 strvec_push(&cmd.args, "-e");
789b3eff 1091 else if (!(flags & CLEANUP_MSG) &&
0009426d 1092 !opts->signoff && !opts->record_origin &&
1a2b985f 1093 !opts->explicit_cleanup)
c972bf4c 1094 strvec_push(&cmd.args, "--cleanup=verbatim");
b27cfb0d 1095
789b3eff 1096 if ((flags & ALLOW_EMPTY))
c972bf4c 1097 strvec_push(&cmd.args, "--allow-empty");
df478b74 1098
a3ec9eaf 1099 if (!(flags & EDIT_MSG))
c972bf4c 1100 strvec_push(&cmd.args, "--allow-empty-message");
4bee9584 1101
34bec2c4
AG
1102 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1103 return run_command_silent_on_success(&cmd);
1104 else
1105 return run_command(&cmd);
b27cfb0d
NH
1106}
1107
d0aaa46f
PW
1108static int rest_is_empty(const struct strbuf *sb, int start)
1109{
1110 int i, eol;
1111 const char *nl;
1112
1113 /* Check if the rest is just whitespace and Signed-off-by's. */
1114 for (i = start; i < sb->len; i++) {
1115 nl = memchr(sb->buf + i, '\n', sb->len - i);
1116 if (nl)
1117 eol = nl - sb->buf;
1118 else
1119 eol = sb->len;
1120
1121 if (strlen(sign_off_header) <= eol - i &&
1122 starts_with(sb->buf + i, sign_off_header)) {
1123 i = eol;
1124 continue;
1125 }
1126 while (i < eol)
1127 if (!isspace(sb->buf[i++]))
1128 return 0;
1129 }
1130
1131 return 1;
1132}
1133
f29cd862
DL
1134void cleanup_message(struct strbuf *msgbuf,
1135 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1136{
1137 if (verbose || /* Truncate the message just before the diff, if any. */
1138 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1139 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1140 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1141 strbuf_stripspace(msgbuf, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1142}
1143
d0aaa46f
PW
1144/*
1145 * Find out if the message in the strbuf contains only whitespace and
1146 * Signed-off-by lines.
1147 */
1148int message_is_empty(const struct strbuf *sb,
1149 enum commit_msg_cleanup_mode cleanup_mode)
1150{
1151 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1152 return 0;
1153 return rest_is_empty(sb, 0);
1154}
1155
1156/*
1157 * See if the user edited the message in the editor or left what
1158 * was in the template intact
1159 */
1160int template_untouched(const struct strbuf *sb, const char *template_file,
1161 enum commit_msg_cleanup_mode cleanup_mode)
1162{
1163 struct strbuf tmpl = STRBUF_INIT;
1164 const char *start;
1165
1166 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1167 return 0;
1168
1169 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1170 return 0;
1171
1172 strbuf_stripspace(&tmpl, cleanup_mode == COMMIT_MSG_CLEANUP_ALL);
1173 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1174 start = sb->buf;
1175 strbuf_release(&tmpl);
1176 return rest_is_empty(sb, start - sb->buf);
1177}
1178
0505d604
PW
1179int update_head_with_reflog(const struct commit *old_head,
1180 const struct object_id *new_head,
1181 const char *action, const struct strbuf *msg,
1182 struct strbuf *err)
1183{
1184 struct ref_transaction *transaction;
1185 struct strbuf sb = STRBUF_INIT;
1186 const char *nl;
1187 int ret = 0;
1188
1189 if (action) {
1190 strbuf_addstr(&sb, action);
1191 strbuf_addstr(&sb, ": ");
1192 }
1193
1194 nl = strchr(msg->buf, '\n');
1195 if (nl) {
1196 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1197 } else {
1198 strbuf_addbuf(&sb, msg);
1199 strbuf_addch(&sb, '\n');
1200 }
1201
1202 transaction = ref_transaction_begin(err);
1203 if (!transaction ||
1204 ref_transaction_update(transaction, "HEAD", new_head,
14228447 1205 old_head ? &old_head->object.oid : null_oid(),
0505d604
PW
1206 0, sb.buf, err) ||
1207 ref_transaction_commit(transaction, err)) {
1208 ret = -1;
1209 }
1210 ref_transaction_free(transaction);
1211 strbuf_release(&sb);
1212
1213 return ret;
1214}
1215
a87a6f3c
PW
1216static int run_rewrite_hook(const struct object_id *oldoid,
1217 const struct object_id *newoid)
1218{
1219 struct child_process proc = CHILD_PROCESS_INIT;
a87a6f3c
PW
1220 int code;
1221 struct strbuf sb = STRBUF_INIT;
2b709893 1222 const char *hook_path = find_hook("post-rewrite");
a87a6f3c 1223
2b709893 1224 if (!hook_path)
a87a6f3c
PW
1225 return 0;
1226
2b709893 1227 strvec_pushl(&proc.args, hook_path, "amend", NULL);
a87a6f3c
PW
1228 proc.in = -1;
1229 proc.stdout_to_stderr = 1;
6206286e 1230 proc.trace2_hook_name = "post-rewrite";
a87a6f3c
PW
1231
1232 code = start_command(&proc);
1233 if (code)
1234 return code;
1235 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1236 sigchain_push(SIGPIPE, SIG_IGN);
1237 write_in_full(proc.in, sb.buf, sb.len);
1238 close(proc.in);
1239 strbuf_release(&sb);
1240 sigchain_pop(SIGPIPE);
1241 return finish_command(&proc);
1242}
1243
1d18d758
NTND
1244void commit_post_rewrite(struct repository *r,
1245 const struct commit *old_head,
a87a6f3c
PW
1246 const struct object_id *new_head)
1247{
1248 struct notes_rewrite_cfg *cfg;
1249
1250 cfg = init_copy_notes_for_rewrite("amend");
1251 if (cfg) {
1252 /* we are amending, so old_head is not NULL */
1253 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1d18d758 1254 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
a87a6f3c
PW
1255 }
1256 run_rewrite_hook(&old_head->object.oid, new_head);
1257}
1258
f11c9580
NTND
1259static int run_prepare_commit_msg_hook(struct repository *r,
1260 struct strbuf *msg,
1261 const char *commit)
66618a50 1262{
49697cb7
PW
1263 int ret = 0;
1264 const char *name, *arg1 = NULL, *arg2 = NULL;
66618a50
PW
1265
1266 name = git_path_commit_editmsg();
1267 if (write_message(msg->buf, msg->len, name, 0))
1268 return -1;
1269
49697cb7
PW
1270 if (commit) {
1271 arg1 = "commit";
1272 arg2 = commit;
1273 } else {
1274 arg1 = "message";
1275 }
a8cc5943 1276 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
49697cb7 1277 arg1, arg2, NULL))
66618a50 1278 ret = error(_("'prepare-commit-msg' hook failed"));
66618a50
PW
1279
1280 return ret;
1281}
1282
e47c6caf
PW
1283static const char implicit_ident_advice_noconfig[] =
1284N_("Your name and email address were configured automatically based\n"
1285"on your username and hostname. Please check that they are accurate.\n"
1286"You can suppress this message by setting them explicitly. Run the\n"
1287"following command and follow the instructions in your editor to edit\n"
1288"your configuration file:\n"
1289"\n"
1290" git config --global --edit\n"
1291"\n"
1292"After doing this, you may fix the identity used for this commit with:\n"
1293"\n"
1294" git commit --amend --reset-author\n");
1295
1296static const char implicit_ident_advice_config[] =
1297N_("Your name and email address were configured automatically based\n"
1298"on your username and hostname. Please check that they are accurate.\n"
1299"You can suppress this message by setting them explicitly:\n"
1300"\n"
1301" git config --global user.name \"Your Name\"\n"
1302" git config --global user.email you@example.com\n"
1303"\n"
1304"After doing this, you may fix the identity used for this commit with:\n"
1305"\n"
1306" git commit --amend --reset-author\n");
1307
1308static const char *implicit_ident_advice(void)
1309{
a03b097d 1310 char *user_config = interpolate_path("~/.gitconfig", 0);
e47c6caf
PW
1311 char *xdg_config = xdg_config_home("config");
1312 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1313
1314 free(user_config);
1315 free(xdg_config);
1316
1317 if (config_exists)
1318 return _(implicit_ident_advice_config);
1319 else
1320 return _(implicit_ident_advice_noconfig);
1321
1322}
1323
f11c9580
NTND
1324void print_commit_summary(struct repository *r,
1325 const char *prefix,
1326 const struct object_id *oid,
e47c6caf
PW
1327 unsigned int flags)
1328{
1329 struct rev_info rev;
1330 struct commit *commit;
1331 struct strbuf format = STRBUF_INIT;
1332 const char *head;
1333 struct pretty_print_context pctx = {0};
1334 struct strbuf author_ident = STRBUF_INIT;
1335 struct strbuf committer_ident = STRBUF_INIT;
ed90f041 1336 struct ref_store *refs;
e47c6caf 1337
f11c9580 1338 commit = lookup_commit(r, oid);
e47c6caf
PW
1339 if (!commit)
1340 die(_("couldn't look up newly created commit"));
ecb5091f 1341 if (repo_parse_commit(the_repository, commit))
e47c6caf
PW
1342 die(_("could not parse newly created commit"));
1343
1344 strbuf_addstr(&format, "format:%h] %s");
1345
bab82164
ÆAB
1346 repo_format_commit_message(the_repository, commit, "%an <%ae>",
1347 &author_ident, &pctx);
1348 repo_format_commit_message(the_repository, commit, "%cn <%ce>",
1349 &committer_ident, &pctx);
e47c6caf
PW
1350 if (strbuf_cmp(&author_ident, &committer_ident)) {
1351 strbuf_addstr(&format, "\n Author: ");
1352 strbuf_addbuf_percentquote(&format, &author_ident);
1353 }
1354 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1355 struct strbuf date = STRBUF_INIT;
1356
bab82164
ÆAB
1357 repo_format_commit_message(the_repository, commit, "%ad",
1358 &date, &pctx);
e47c6caf
PW
1359 strbuf_addstr(&format, "\n Date: ");
1360 strbuf_addbuf_percentquote(&format, &date);
1361 strbuf_release(&date);
1362 }
1363 if (!committer_ident_sufficiently_given()) {
1364 strbuf_addstr(&format, "\n Committer: ");
1365 strbuf_addbuf_percentquote(&format, &committer_ident);
ed9bff08 1366 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
e47c6caf
PW
1367 strbuf_addch(&format, '\n');
1368 strbuf_addstr(&format, implicit_ident_advice());
1369 }
1370 }
1371 strbuf_release(&author_ident);
1372 strbuf_release(&committer_ident);
1373
f11c9580 1374 repo_init_revisions(r, &rev, prefix);
e47c6caf
PW
1375 setup_revisions(0, NULL, &rev, NULL);
1376
1377 rev.diff = 1;
1378 rev.diffopt.output_format =
1379 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1380
1381 rev.verbose_header = 1;
1382 rev.show_root_diff = 1;
1383 get_commit_format(format.buf, &rev);
1384 rev.always_show_header = 0;
0f57f731 1385 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
e47c6caf
PW
1386 diff_setup_done(&rev.diffopt);
1387
ed90f041 1388 refs = get_main_ref_store(the_repository);
ce14de03 1389 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
09444e74
ÆAB
1390 if (!head)
1391 die(_("unable to resolve HEAD after creating commit"));
e47c6caf
PW
1392 if (!strcmp(head, "HEAD"))
1393 head = _("detached HEAD");
1394 else
1395 skip_prefix(head, "refs/heads/", &head);
1396 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1397 _(" (root-commit)") : "");
1398
1399 if (!log_tree_commit(&rev, commit)) {
1400 rev.always_show_header = 1;
1401 rev.use_terminator = 1;
1402 log_tree_commit(&rev, commit);
1403 }
1404
2108fe4a 1405 release_revisions(&rev);
e47c6caf
PW
1406 strbuf_release(&format);
1407}
1408
005af339 1409static int parse_head(struct repository *r, struct commit **head)
356ee465
PW
1410{
1411 struct commit *current_head;
1412 struct object_id oid;
1413
d850b7a5 1414 if (repo_get_oid(the_repository, "HEAD", &oid)) {
356ee465
PW
1415 current_head = NULL;
1416 } else {
005af339 1417 current_head = lookup_commit_reference(r, &oid);
356ee465
PW
1418 if (!current_head)
1419 return error(_("could not parse HEAD"));
9001dc2a 1420 if (!oideq(&oid, &current_head->object.oid)) {
356ee465
PW
1421 warning(_("HEAD %s is not a commit!"),
1422 oid_to_hex(&oid));
1423 }
ecb5091f 1424 if (repo_parse_commit(the_repository, current_head))
356ee465
PW
1425 return error(_("could not parse HEAD commit"));
1426 }
1427 *head = current_head;
1428
1429 return 0;
1430}
1431
1432/*
1433 * Try to commit without forking 'git commit'. In some cases we need
1434 * to run 'git commit' to display an error message
1435 *
1436 * Returns:
1437 * -1 - error unable to commit
1438 * 0 - success
1439 * 1 - run 'git commit'
1440 */
f11c9580
NTND
1441static int try_to_commit(struct repository *r,
1442 struct strbuf *msg, const char *author,
356ee465
PW
1443 struct replay_opts *opts, unsigned int flags,
1444 struct object_id *oid)
1445{
1446 struct object_id tree;
b0a31861 1447 struct commit *current_head = NULL;
356ee465
PW
1448 struct commit_list *parents = NULL;
1449 struct commit_extra_header *extra = NULL;
1450 struct strbuf err = STRBUF_INIT;
66618a50 1451 struct strbuf commit_msg = STRBUF_INIT;
4d924528 1452 char *amend_author = NULL;
7573cec5 1453 const char *committer = NULL;
66618a50 1454 const char *hook_commit = NULL;
356ee465
PW
1455 enum commit_msg_cleanup_mode cleanup;
1456 int res = 0;
1457
f7d42cee
JS
1458 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1459 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1460
005af339 1461 if (parse_head(r, &current_head))
356ee465 1462 return -1;
4d924528 1463
356ee465 1464 if (flags & AMEND_MSG) {
42d4e1d1 1465 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
356ee465 1466 const char *out_enc = get_commit_output_encoding();
ecb5091f
ÆAB
1467 const char *message = repo_logmsg_reencode(the_repository,
1468 current_head, NULL,
1469 out_enc);
356ee465
PW
1470
1471 if (!msg) {
1472 const char *orig_message = NULL;
1473
1474 find_commit_subject(message, &orig_message);
66618a50 1475 msg = &commit_msg;
356ee465 1476 strbuf_addstr(msg, orig_message);
66618a50 1477 hook_commit = "HEAD";
356ee465 1478 }
4d924528 1479 author = amend_author = get_author(message);
ecb5091f
ÆAB
1480 repo_unuse_commit_buffer(the_repository, current_head,
1481 message);
356ee465
PW
1482 if (!author) {
1483 res = error(_("unable to parse commit author"));
1484 goto out;
1485 }
1486 parents = copy_commit_list(current_head->parents);
1487 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
b0a31861
PW
1488 } else if (current_head &&
1489 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
356ee465
PW
1490 commit_list_insert(current_head, &parents);
1491 }
1492
f11c9580 1493 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
356ee465
PW
1494 res = error(_("git write-tree failed to write a tree"));
1495 goto out;
1496 }
1497
2d05ef27
PW
1498 if (!(flags & ALLOW_EMPTY)) {
1499 struct commit *first_parent = current_head;
1500
1501 if (flags & AMEND_MSG) {
1502 if (current_head->parents) {
1503 first_parent = current_head->parents->item;
1504 if (repo_parse_commit(r, first_parent)) {
1505 res = error(_("could not parse HEAD commit"));
1506 goto out;
1507 }
1508 } else {
1509 first_parent = NULL;
1510 }
1511 }
1512 if (oideq(first_parent
1513 ? get_commit_tree_oid(first_parent)
1514 : the_hash_algo->empty_tree,
1515 &tree)) {
1516 res = 1; /* run 'git commit' to display error message */
1517 goto out;
1518 }
356ee465
PW
1519 }
1520
07a348e7 1521 if (hook_exists("prepare-commit-msg")) {
f11c9580 1522 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
66618a50
PW
1523 if (res)
1524 goto out;
1525 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1526 2048) < 0) {
1527 res = error_errno(_("unable to read commit message "
1528 "from '%s'"),
1529 git_path_commit_editmsg());
1530 goto out;
1531 }
1532 msg = &commit_msg;
1533 }
1534
d74f3e58
PW
1535 if (flags & CLEANUP_MSG)
1536 cleanup = COMMIT_MSG_CLEANUP_ALL;
f7d42cee
JS
1537 else if (flags & VERBATIM_MSG)
1538 cleanup = COMMIT_MSG_CLEANUP_NONE;
d74f3e58
PW
1539 else if ((opts->signoff || opts->record_origin) &&
1540 !opts->explicit_cleanup)
1541 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1542 else
1543 cleanup = opts->default_msg_cleanup;
66618a50
PW
1544
1545 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1546 strbuf_stripspace(msg, cleanup == COMMIT_MSG_CLEANUP_ALL);
a3ec9eaf 1547 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
66618a50
PW
1548 res = 1; /* run 'git commit' to display error message */
1549 goto out;
1550 }
1551
7573cec5
PW
1552 if (opts->committer_date_is_author_date) {
1553 struct ident_split id;
1554 struct strbuf date = STRBUF_INIT;
1555
a3894aad
PW
1556 if (!opts->ignore_date) {
1557 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1558 res = error(_("invalid author identity '%s'"),
1559 author);
1560 goto out;
1561 }
1562 if (!id.date_begin) {
1563 res = error(_(
1564 "corrupt author: missing date information"));
1565 goto out;
1566 }
1567 strbuf_addf(&date, "@%.*s %.*s",
1568 (int)(id.date_end - id.date_begin),
1569 id.date_begin,
1570 (int)(id.tz_end - id.tz_begin),
1571 id.tz_begin);
1572 } else {
1573 reset_ident_date();
7573cec5 1574 }
2020451c
JK
1575 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1576 getenv("GIT_COMMITTER_EMAIL"),
a3894aad
PW
1577 WANT_COMMITTER_IDENT,
1578 opts->ignore_date ? NULL : date.buf,
7573cec5
PW
1579 IDENT_STRICT);
1580 strbuf_release(&date);
1581 } else {
1582 reset_ident_date();
1583 }
12f7babd 1584
a3894aad
PW
1585 if (opts->ignore_date) {
1586 struct ident_split id;
1587 char *name, *email;
12f7babd 1588
a3894aad
PW
1589 if (split_ident_line(&id, author, strlen(author)) < 0) {
1590 error(_("invalid author identity '%s'"), author);
1591 goto out;
1592 }
1593 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1594 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1595 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1596 IDENT_STRICT);
1597 free(name);
1598 free(email);
1599 }
1600
e8cbe211 1601 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
7573cec5 1602 author, committer, opts->gpg_sign, extra)) {
356ee465
PW
1603 res = error(_("failed to write commit object"));
1604 goto out;
1605 }
1606
d188a60d
PW
1607 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1608 msg, &err)) {
356ee465
PW
1609 res = error("%s", err.buf);
1610 goto out;
1611 }
1612
a8cc5943 1613 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
356ee465 1614 if (flags & AMEND_MSG)
1d18d758 1615 commit_post_rewrite(r, current_head, oid);
356ee465
PW
1616
1617out:
1618 free_commit_extra_headers(extra);
1619 strbuf_release(&err);
66618a50 1620 strbuf_release(&commit_msg);
4d924528 1621 free(amend_author);
356ee465
PW
1622
1623 return res;
1624}
1625
430b75f7
PW
1626static int write_rebase_head(struct object_id *oid)
1627{
1628 if (update_ref("rebase", "REBASE_HEAD", oid,
1629 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1630 return error(_("could not update %s"), "REBASE_HEAD");
1631
1632 return 0;
1633}
1634
f11c9580
NTND
1635static int do_commit(struct repository *r,
1636 const char *msg_file, const char *author,
430b75f7
PW
1637 struct replay_opts *opts, unsigned int flags,
1638 struct object_id *oid)
356ee465
PW
1639{
1640 int res = 1;
1641
b0a31861 1642 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
356ee465
PW
1643 struct object_id oid;
1644 struct strbuf sb = STRBUF_INIT;
1645
1646 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1647 return error_errno(_("unable to read commit message "
1648 "from '%s'"),
1649 msg_file);
1650
f11c9580
NTND
1651 res = try_to_commit(r, msg_file ? &sb : NULL,
1652 author, opts, flags, &oid);
356ee465
PW
1653 strbuf_release(&sb);
1654 if (!res) {
c8e4159e
HWN
1655 refs_delete_ref(get_main_ref_store(r), "",
1656 "CHERRY_PICK_HEAD", NULL, 0);
f11c9580 1657 unlink(git_path_merge_msg(r));
356ee465 1658 if (!is_rebase_i(opts))
f11c9580 1659 print_commit_summary(r, NULL, &oid,
356ee465
PW
1660 SUMMARY_SHOW_AUTHOR_DATE);
1661 return res;
1662 }
1663 }
430b75f7
PW
1664 if (res == 1) {
1665 if (is_rebase_i(opts) && oid)
1666 if (write_rebase_head(oid))
1667 return -1;
20f4b044 1668 return run_git_commit(msg_file, opts, flags);
430b75f7 1669 }
356ee465
PW
1670
1671 return res;
1672}
1673
b27cfb0d
NH
1674static int is_original_commit_empty(struct commit *commit)
1675{
092bbcdf 1676 const struct object_id *ptree_oid;
b27cfb0d 1677
ecb5091f 1678 if (repo_parse_commit(the_repository, commit))
aee42e1f 1679 return error(_("could not parse commit %s"),
f2fd0760 1680 oid_to_hex(&commit->object.oid));
b27cfb0d
NH
1681 if (commit->parents) {
1682 struct commit *parent = commit->parents->item;
ecb5091f 1683 if (repo_parse_commit(the_repository, parent))
aee42e1f 1684 return error(_("could not parse parent commit %s"),
f2fd0760 1685 oid_to_hex(&parent->object.oid));
2e27bd77 1686 ptree_oid = get_commit_tree_oid(parent);
b27cfb0d 1687 } else {
eb0ccfd7 1688 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
043a4492 1689 }
043a4492 1690
4a7e27e9 1691 return oideq(ptree_oid, get_commit_tree_oid(commit));
043a4492
RR
1692}
1693
ac2b0e8f 1694/*
e98c4269
EN
1695 * Should empty commits be allowed? Return status:
1696 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1697 * 0: Halt on empty commit
1698 * 1: Allow empty commit
1699 * 2: Drop empty commit
ac2b0e8f 1700 */
f11c9580
NTND
1701static int allow_empty(struct repository *r,
1702 struct replay_opts *opts,
1703 struct commit *commit)
ac2b0e8f 1704{
d48e5e21 1705 int index_unchanged, originally_empty;
ac2b0e8f
JH
1706
1707 /*
e98c4269 1708 * Four cases:
ac2b0e8f
JH
1709 *
1710 * (1) we do not allow empty at all and error out.
1711 *
e98c4269
EN
1712 * (2) we allow ones that were initially empty, and
1713 * just drop the ones that become empty
ac2b0e8f 1714 *
e98c4269
EN
1715 * (3) we allow ones that were initially empty, but
1716 * halt for the ones that become empty;
1717 *
1718 * (4) we allow both.
ac2b0e8f
JH
1719 */
1720 if (!opts->allow_empty)
1721 return 0; /* let "git commit" barf as necessary */
1722
005af339 1723 index_unchanged = is_index_unchanged(r);
ac2b0e8f
JH
1724 if (index_unchanged < 0)
1725 return index_unchanged;
1726 if (!index_unchanged)
1727 return 0; /* we do not have to say --allow-empty */
1728
1729 if (opts->keep_redundant_commits)
1730 return 1;
1731
d48e5e21
EN
1732 originally_empty = is_original_commit_empty(commit);
1733 if (originally_empty < 0)
1734 return originally_empty;
e98c4269 1735 if (originally_empty)
ac2b0e8f 1736 return 1;
e98c4269
EN
1737 else if (opts->drop_redundant_commits)
1738 return 2;
1739 else
1740 return 0;
ac2b0e8f
JH
1741}
1742
414697a9
JS
1743static struct {
1744 char c;
1745 const char *str;
1746} todo_command_info[] = {
d7ce9a22
DS
1747 [TODO_PICK] = { 'p', "pick" },
1748 [TODO_REVERT] = { 0, "revert" },
1749 [TODO_EDIT] = { 'e', "edit" },
1750 [TODO_REWORD] = { 'r', "reword" },
1751 [TODO_FIXUP] = { 'f', "fixup" },
1752 [TODO_SQUASH] = { 's', "squash" },
1753 [TODO_EXEC] = { 'x', "exec" },
1754 [TODO_BREAK] = { 'b', "break" },
1755 [TODO_LABEL] = { 'l', "label" },
1756 [TODO_RESET] = { 't', "reset" },
1757 [TODO_MERGE] = { 'm', "merge" },
a97d7916 1758 [TODO_UPDATE_REF] = { 'u', "update-ref" },
d7ce9a22
DS
1759 [TODO_NOOP] = { 0, "noop" },
1760 [TODO_DROP] = { 'd', "drop" },
1761 [TODO_COMMENT] = { 0, NULL },
004fefa7
JS
1762};
1763
1764static const char *command_to_string(const enum todo_command command)
1765{
ac191470 1766 if (command < TODO_COMMENT)
414697a9 1767 return todo_command_info[command].str;
02127c63 1768 die(_("unknown command: %d"), command);
004fefa7
JS
1769}
1770
ee5462d6 1771static char command_to_char(const enum todo_command command)
d8ae6c84 1772{
68e7090f 1773 if (command < TODO_COMMENT)
d8ae6c84
LB
1774 return todo_command_info[command].c;
1775 return comment_line_char;
1776}
1777
25c43667
JS
1778static int is_noop(const enum todo_command command)
1779{
b3fdd581 1780 return TODO_NOOP <= command;
25c43667 1781}
004fefa7 1782
6e98de72
JS
1783static int is_fixup(enum todo_command command)
1784{
1785 return command == TODO_FIXUP || command == TODO_SQUASH;
1786}
1787
d87d48b2
JS
1788/* Does this command create a (non-merge) commit? */
1789static int is_pick_or_similar(enum todo_command command)
1790{
1791 switch (command) {
1792 case TODO_PICK:
1793 case TODO_REVERT:
1794 case TODO_EDIT:
1795 case TODO_REWORD:
1796 case TODO_FIXUP:
1797 case TODO_SQUASH:
1798 return 1;
1799 default:
1800 return 0;
1801 }
1802}
1803
9e3cebd9
CM
1804enum todo_item_flags {
1805 TODO_EDIT_MERGE_MSG = (1 << 0),
1806 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1807 TODO_EDIT_FIXUP_MSG = (1 << 2),
1808};
1809
71ee81cd
CM
1810static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1811static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
9e3cebd9 1812static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
71ee81cd
CM
1813static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1814static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1815
1f969601 1816static int is_fixup_flag(enum todo_command command, unsigned flag)
498bb5b8 1817{
9e3cebd9
CM
1818 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1819 (flag & TODO_EDIT_FIXUP_MSG));
1820}
7cdb9682 1821
9e3cebd9
CM
1822/*
1823 * Wrapper around strbuf_add_commented_lines() which avoids double
1824 * commenting commit subjects.
1825 */
1826static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1827{
1828 const char *s = str;
1829 while (len > 0 && s[0] == comment_line_char) {
1830 size_t count;
1831 const char *n = memchr(s, '\n', len);
1832 if (!n)
1833 count = len;
1834 else
1835 count = n - s + 1;
1836 strbuf_add(buf, s, count);
1837 s += count;
1838 len -= count;
1839 }
1840 strbuf_add_commented_lines(buf, s, len);
1841}
1842
1843/* Does the current fixup chain contain a squash command? */
1844static int seen_squash(struct replay_opts *opts)
1845{
1846 return starts_with(opts->current_fixups.buf, "squash") ||
1847 strstr(opts->current_fixups.buf, "\nsquash");
1848}
1849
1850static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1851{
1852 strbuf_setlen(buf1, 2);
1853 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1854 strbuf_addch(buf1, '\n');
1855 strbuf_setlen(buf2, 2);
1856 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1857 strbuf_addch(buf2, '\n');
1858}
1859
1860/*
1861 * Comment out any un-commented commit messages, updating the message comments
1862 * to say they will be skipped but do not comment out the empty lines that
1863 * surround commit messages and their comments.
1864 */
1865static void update_squash_message_for_fixup(struct strbuf *msg)
1866{
1867 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1868 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1869 const char *s, *start;
1870 char *orig_msg;
1871 size_t orig_msg_len;
1872 int i = 1;
1873
1874 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1875 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1876 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1877 while (s) {
1878 const char *next;
1879 size_t off;
1880 if (skip_prefix(s, buf1.buf, &next)) {
1881 /*
1882 * Copy the last message, preserving the blank line
1883 * preceding the current line
1884 */
1885 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1886 copy_lines(msg, start, s - start - off);
1887 if (off)
1888 strbuf_addch(msg, '\n');
1889 /*
1890 * The next message needs to be commented out but the
1891 * message header is already commented out so just copy
1892 * it and the blank line that follows it.
1893 */
1894 strbuf_addbuf(msg, &buf2);
1895 if (*next == '\n')
1896 strbuf_addch(msg, *next++);
1897 start = s = next;
1898 copy_lines = add_commented_lines;
1899 update_comment_bufs(&buf1, &buf2, ++i);
1900 } else if (skip_prefix(s, buf2.buf, &next)) {
1901 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1902 copy_lines(msg, start, s - start - off);
1903 start = s - off;
1904 s = next;
1905 copy_lines = strbuf_add;
1906 update_comment_bufs(&buf1, &buf2, ++i);
1907 } else {
1908 s = strchr(s, '\n');
1909 if (s)
1910 s++;
1911 }
1912 }
1913 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1914 free(orig_msg);
1915 strbuf_release(&buf1);
1916 strbuf_release(&buf2);
1917}
1918
1919static int append_squash_message(struct strbuf *buf, const char *body,
1920 enum todo_command command, struct replay_opts *opts,
a25314c1 1921 unsigned flag)
9e3cebd9
CM
1922{
1923 const char *fixup_msg;
1924 size_t commented_len = 0, fixup_off;
1925 /*
1926 * amend is non-interactive and not normally used with fixup!
1927 * or squash! commits, so only comment out those subjects when
1928 * squashing commit messages.
1929 */
1930 if (starts_with(body, "amend!") ||
1931 ((command == TODO_SQUASH || seen_squash(opts)) &&
1932 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
6e0e2887 1933 commented_len = commit_subject_length(body);
9e3cebd9 1934
498bb5b8 1935 strbuf_addf(buf, "\n%c ", comment_line_char);
71ee81cd 1936 strbuf_addf(buf, _(nth_commit_msg_fmt),
498bb5b8
PW
1937 ++opts->current_fixup_count + 1);
1938 strbuf_addstr(buf, "\n\n");
7cdb9682 1939 strbuf_add_commented_lines(buf, body, commented_len);
9e3cebd9
CM
1940 /* buf->buf may be reallocated so store an offset into the buffer */
1941 fixup_off = buf->len;
7cdb9682 1942 strbuf_addstr(buf, body + commented_len);
9e3cebd9
CM
1943
1944 /* fixup -C after squash behaves like squash */
1f969601 1945 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
9e3cebd9
CM
1946 /*
1947 * We're replacing the commit message so we need to
1948 * append the Signed-off-by: trailer if the user
1949 * requested '--signoff'.
1950 */
1951 if (opts->signoff)
1952 append_signoff(buf, 0, 0);
1953
1954 if ((command == TODO_FIXUP) &&
1955 (flag & TODO_REPLACE_FIXUP_MSG) &&
1956 (file_exists(rebase_path_fixup_msg()) ||
1957 !file_exists(rebase_path_squash_msg()))) {
1958 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1959 if (write_message(fixup_msg, strlen(fixup_msg),
1960 rebase_path_fixup_msg(), 0) < 0)
1961 return error(_("cannot write '%s'"),
1962 rebase_path_fixup_msg());
1963 } else {
1964 unlink(rebase_path_fixup_msg());
1965 }
1966 } else {
1967 unlink(rebase_path_fixup_msg());
1968 }
1969
1970 return 0;
498bb5b8
PW
1971}
1972
005af339
NTND
1973static int update_squash_messages(struct repository *r,
1974 enum todo_command command,
1975 struct commit *commit,
9e3cebd9 1976 struct replay_opts *opts,
a25314c1 1977 unsigned flag)
6e98de72
JS
1978{
1979 struct strbuf buf = STRBUF_INIT;
9e3cebd9 1980 int res = 0;
6e98de72 1981 const char *message, *body;
b3757442 1982 const char *encoding = get_commit_output_encoding();
6e98de72 1983
e12a7ef5 1984 if (opts->current_fixup_count > 0) {
6e98de72 1985 struct strbuf header = STRBUF_INIT;
e12a7ef5 1986 char *eol;
6e98de72 1987
e12a7ef5 1988 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
1989 return error(_("could not read '%s'"),
1990 rebase_path_squash_msg());
1991
e12a7ef5
JS
1992 eol = buf.buf[0] != comment_line_char ?
1993 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
1994
1995 strbuf_addf(&header, "%c ", comment_line_char);
71ee81cd 1996 strbuf_addf(&header, _(combined_commit_msg_fmt),
e12a7ef5 1997 opts->current_fixup_count + 2);
6e98de72
JS
1998 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1999 strbuf_release(&header);
1f969601 2000 if (is_fixup_flag(command, flag) && !seen_squash(opts))
9e3cebd9 2001 update_squash_message_for_fixup(&buf);
6e98de72 2002 } else {
33d66df3 2003 struct object_id head;
6e98de72
JS
2004 struct commit *head_commit;
2005 const char *head_message, *body;
2006
d850b7a5 2007 if (repo_get_oid(the_repository, "HEAD", &head))
6e98de72 2008 return error(_("need a HEAD to fixup"));
005af339 2009 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72 2010 return error(_("could not read HEAD"));
ecb5091f 2011 if (!(head_message = repo_logmsg_reencode(the_repository, head_commit, NULL, encoding)))
6e98de72
JS
2012 return error(_("could not read HEAD's commit message"));
2013
2014 find_commit_subject(head_message, &body);
9e3cebd9 2015 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
eab0df0e 2016 rebase_path_fixup_msg(), 0) < 0) {
ecb5091f
ÆAB
2017 repo_unuse_commit_buffer(the_repository, head_commit,
2018 head_message);
eab0df0e 2019 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
6e98de72 2020 }
6e98de72 2021 strbuf_addf(&buf, "%c ", comment_line_char);
71ee81cd 2022 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
6e98de72 2023 strbuf_addf(&buf, "\n%c ", comment_line_char);
1f969601 2024 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
9e3cebd9
CM
2025 _(skip_first_commit_msg_str) :
2026 _(first_commit_msg_str));
6e98de72 2027 strbuf_addstr(&buf, "\n\n");
1f969601 2028 if (is_fixup_flag(command, flag))
9e3cebd9
CM
2029 strbuf_add_commented_lines(&buf, body, strlen(body));
2030 else
2031 strbuf_addstr(&buf, body);
6e98de72 2032
ecb5091f
ÆAB
2033 repo_unuse_commit_buffer(the_repository, head_commit,
2034 head_message);
6e98de72
JS
2035 }
2036
ecb5091f 2037 if (!(message = repo_logmsg_reencode(the_repository, commit, NULL, encoding)))
6e98de72
JS
2038 return error(_("could not read commit message of %s"),
2039 oid_to_hex(&commit->object.oid));
2040 find_commit_subject(message, &body);
2041
1f969601 2042 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
9e3cebd9 2043 res = append_squash_message(&buf, body, command, opts, flag);
6e98de72
JS
2044 } else if (command == TODO_FIXUP) {
2045 strbuf_addf(&buf, "\n%c ", comment_line_char);
71ee81cd 2046 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
dd2e36eb 2047 ++opts->current_fixup_count + 1);
6e98de72
JS
2048 strbuf_addstr(&buf, "\n\n");
2049 strbuf_add_commented_lines(&buf, body, strlen(body));
2050 } else
2051 return error(_("unknown command: %d"), command);
ecb5091f 2052 repo_unuse_commit_buffer(the_repository, commit, message);
6e98de72 2053
9e3cebd9
CM
2054 if (!res)
2055 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2056 0);
6e98de72 2057 strbuf_release(&buf);
e12a7ef5
JS
2058
2059 if (!res) {
2060 strbuf_addf(&opts->current_fixups, "%s%s %s",
2061 opts->current_fixups.len ? "\n" : "",
2062 command_to_string(command),
2063 oid_to_hex(&commit->object.oid));
2064 res = write_message(opts->current_fixups.buf,
2065 opts->current_fixups.len,
2066 rebase_path_current_fixups(), 0);
2067 }
2068
6e98de72
JS
2069 return res;
2070}
2071
3b335762
NTND
2072static void flush_rewritten_pending(void)
2073{
25cb8df9 2074 struct strbuf buf = STRBUF_INIT;
092bbcdf 2075 struct object_id newoid;
25cb8df9
JS
2076 FILE *out;
2077
092bbcdf 2078 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
d850b7a5 2079 !repo_get_oid(the_repository, "HEAD", &newoid) &&
e9d983f1 2080 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
2081 char *bol = buf.buf, *eol;
2082
2083 while (*bol) {
2084 eol = strchrnul(bol, '\n');
2085 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 2086 bol, oid_to_hex(&newoid));
25cb8df9
JS
2087 if (!*eol)
2088 break;
2089 bol = eol + 1;
2090 }
2091 fclose(out);
2092 unlink(rebase_path_rewritten_pending());
2093 }
2094 strbuf_release(&buf);
2095}
2096
2097static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
2098 enum todo_command next_command)
2099{
e9d983f1 2100 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
2101
2102 if (!out)
2103 return;
2104
2105 fprintf(out, "%s\n", oid_to_hex(oid));
2106 fclose(out);
2107
2108 if (!is_fixup(next_command))
2109 flush_rewritten_pending();
2110}
2111
39edfd5c
EN
2112static int should_edit(struct replay_opts *opts) {
2113 if (opts->edit < 0)
2114 /*
2115 * Note that we only handle the case of non-conflicted
2116 * commits; continue_single_pick() handles the conflicted
2117 * commits itself instead of calling this function.
2118 */
2119 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2120 return opts->edit;
2121}
2122
43966ab3
JH
2123static void refer_to_commit(struct replay_opts *opts,
2124 struct strbuf *msgbuf, struct commit *commit)
2125{
2126 if (opts->commit_use_reference) {
2127 struct pretty_print_context ctx = {
2128 .abbrev = DEFAULT_ABBREV,
2129 .date_mode.type = DATE_SHORT,
2130 };
bab82164
ÆAB
2131 repo_format_commit_message(the_repository, commit,
2132 "%h (%s, %ad)", msgbuf, &ctx);
43966ab3
JH
2133 } else {
2134 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2135 }
2136}
2137
f11c9580 2138static int do_pick_commit(struct repository *r,
ae70e34f 2139 struct todo_item *item,
f11c9580 2140 struct replay_opts *opts,
a47ba3c7 2141 int final_fixup, int *check_todo)
043a4492 2142{
39edfd5c
EN
2143 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2144 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
ace976b2 2145 struct object_id head;
043a4492
RR
2146 struct commit *base, *next, *parent;
2147 const char *base_label, *next_label;
356ee465 2148 char *author = NULL;
d74a4e57 2149 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 2150 struct strbuf msgbuf = STRBUF_INIT;
e98c4269 2151 int res, unborn = 0, reword = 0, allow, drop_commit;
ae70e34f
CM
2152 enum todo_command command = item->command;
2153 struct commit *commit = item->commit;
043a4492
RR
2154
2155 if (opts->no_commit) {
2156 /*
2157 * We do not intend to commit immediately. We just want to
2158 * merge the differences in, so let's compute the tree
81483fe6 2159 * that represents the "current" state for the merge machinery
043a4492
RR
2160 * to work on.
2161 */
f11c9580 2162 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 2163 return error(_("your index file is unmerged."));
043a4492 2164 } else {
d850b7a5 2165 unborn = repo_get_oid(the_repository, "HEAD", &head);
d87d48b2
JS
2166 /* Do we want to generate a root commit? */
2167 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 2168 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
2169 if (is_fixup(command))
2170 return error(_("cannot fixup root commit"));
2171 flags |= CREATE_ROOT_COMMIT;
2172 unborn = 1;
2173 } else if (unborn)
eb0ccfd7 2174 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 2175 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 2176 NULL, 0))
e1ff0a32 2177 return error_dirty_index(r, opts);
043a4492 2178 }
f11c9580 2179 discard_index(r->index);
043a4492 2180
637666c8 2181 if (!commit->parents)
043a4492 2182 parent = NULL;
043a4492
RR
2183 else if (commit->parents->next) {
2184 /* Reverting or cherry-picking a merge commit */
2185 int cnt;
2186 struct commit_list *p;
2187
2188 if (!opts->mainline)
93b3df6f 2189 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 2190 oid_to_hex(&commit->object.oid));
043a4492
RR
2191
2192 for (cnt = 1, p = commit->parents;
2193 cnt != opts->mainline && p;
2194 cnt++)
2195 p = p->next;
2196 if (cnt != opts->mainline || !p)
93b3df6f 2197 return error(_("commit %s does not have parent %d"),
f2fd0760 2198 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 2199 parent = p->item;
37897bfc
SO
2200 } else if (1 < opts->mainline)
2201 /*
2202 * Non-first parent explicitly specified as mainline for
2203 * non-merge commit
2204 */
2205 return error(_("commit %s does not have parent %d"),
2206 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
2207 else
2208 parent = commit->parents->item;
2209
bcbb68be
JS
2210 if (get_message(commit, &msg) != 0)
2211 return error(_("cannot get commit message for %s"),
2212 oid_to_hex(&commit->object.oid));
2213
6e98de72 2214 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 2215 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
2216 (!parent && unborn))) {
2217 if (is_rebase_i(opts))
2218 write_author_script(msg.message);
f11c9580 2219 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
2220 opts);
2221 if (res || command != TODO_REWORD)
2222 goto leave;
450efe2d 2223 reword = 1;
bcbb68be
JS
2224 msg_file = NULL;
2225 goto fast_forward_edit;
2226 }
ecb5091f 2227 if (parent && repo_parse_commit(the_repository, parent) < 0)
004fefa7
JS
2228 /* TRANSLATORS: The first %s will be a "todo" command like
2229 "revert" or "pick", the second %s a SHA1. */
043a4492 2230 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
2231 command_to_string(command),
2232 oid_to_hex(&parent->object.oid));
043a4492 2233
043a4492
RR
2234 /*
2235 * "commit" is an existing commit. We would want to apply
2236 * the difference it introduces since its first parent "prev"
2237 * on top of the current HEAD if we are cherry-pick. Or the
2238 * reverse of it if we are revert.
2239 */
2240
004fefa7 2241 if (command == TODO_REVERT) {
043a4492
RR
2242 base = commit;
2243 base_label = msg.label;
2244 next = parent;
2245 next_label = msg.parent_label;
43966ab3
JH
2246 if (opts->commit_use_reference) {
2247 strbuf_addstr(&msgbuf,
2248 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
2249 } else {
2250 strbuf_addstr(&msgbuf, "Revert \"");
2251 strbuf_addstr(&msgbuf, msg.subject);
2252 strbuf_addstr(&msgbuf, "\"");
2253 }
2254 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2255 refer_to_commit(opts, &msgbuf, commit);
043a4492
RR
2256
2257 if (commit->parents && commit->parents->next) {
2258 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
43966ab3 2259 refer_to_commit(opts, &msgbuf, parent);
043a4492
RR
2260 }
2261 strbuf_addstr(&msgbuf, ".\n");
2262 } else {
2263 const char *p;
2264
2265 base = parent;
2266 base_label = msg.parent_label;
2267 next = commit;
2268 next_label = msg.label;
2269
23aa5142
JS
2270 /* Append the commit log message to msgbuf. */
2271 if (find_commit_subject(msg.message, &p))
2272 strbuf_addstr(&msgbuf, p);
043a4492
RR
2273
2274 if (opts->record_origin) {
44dc738a 2275 strbuf_complete_line(&msgbuf);
bab4d109 2276 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 2277 strbuf_addch(&msgbuf, '\n');
cd650a4e 2278 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 2279 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
2280 strbuf_addstr(&msgbuf, ")\n");
2281 }
356ee465
PW
2282 if (!is_fixup(command))
2283 author = get_author(msg.message);
043a4492
RR
2284 }
2285
04efc8b5 2286 if (command == TODO_REWORD)
450efe2d 2287 reword = 1;
04efc8b5 2288 else if (is_fixup(command)) {
9e3cebd9 2289 if (update_squash_messages(r, command, commit,
a5792e9d
ÆAB
2290 opts, item->flags)) {
2291 res = -1;
2292 goto leave;
2293 }
789b3eff 2294 flags |= AMEND_MSG;
6e98de72
JS
2295 if (!final_fixup)
2296 msg_file = rebase_path_squash_msg();
2297 else if (file_exists(rebase_path_fixup_msg())) {
f7d42cee 2298 flags |= VERBATIM_MSG;
6e98de72
JS
2299 msg_file = rebase_path_fixup_msg();
2300 } else {
f11c9580 2301 const char *dest = git_path_squash_msg(r);
6e98de72 2302 unlink(dest);
a5792e9d
ÆAB
2303 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
2304 res = error(_("could not rename '%s' to '%s'"),
2305 rebase_path_squash_msg(), dest);
2306 goto leave;
2307 }
f11c9580 2308 unlink(git_path_merge_msg(r));
6e98de72 2309 msg_file = dest;
789b3eff 2310 flags |= EDIT_MSG;
6e98de72
JS
2311 }
2312 }
2313
a852ec7f 2314 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
2315 append_signoff(&msgbuf, 0, 0);
2316
0473f28a
JS
2317 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2318 res = -1;
14c4586c
EN
2319 else if (!opts->strategy ||
2320 !strcmp(opts->strategy, "recursive") ||
2321 !strcmp(opts->strategy, "ort") ||
2322 command == TODO_REVERT) {
f11c9580 2323 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 2324 &head, &msgbuf, opts);
f241ff0d 2325 if (res < 0)
19517fb9
SB
2326 goto leave;
2327
75871495 2328 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 2329 git_path_merge_msg(r), 0);
043a4492
RR
2330 } else {
2331 struct commit_list *common = NULL;
2332 struct commit_list *remotes = NULL;
2333
75871495 2334 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 2335 git_path_merge_msg(r), 0);
043a4492
RR
2336
2337 commit_list_insert(base, &common);
2338 commit_list_insert(next, &remotes);
f11c9580 2339 res |= try_merge_command(r, opts->strategy,
03a4e260 2340 opts->xopts_nr, (const char **)opts->xopts,
ace976b2 2341 common, oid_to_hex(&head), remotes);
043a4492
RR
2342 free_commit_list(common);
2343 free_commit_list(remotes);
2344 }
2345
2346 /*
2347 * If the merge was clean or if it failed due to conflict, we write
2348 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2349 * However, if the merge did not even start, then we don't want to
2350 * write it at all.
2351 */
21b11c6d
PW
2352 if ((command == TODO_PICK || command == TODO_REWORD ||
2353 command == TODO_EDIT) && !opts->no_commit &&
2354 (res == 0 || res == 1) &&
ae077771 2355 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 2356 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2357 res = -1;
004fefa7 2358 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 2359 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 2360 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2361 res = -1;
043a4492
RR
2362
2363 if (res) {
004fefa7 2364 error(command == TODO_REVERT
043a4492
RR
2365 ? _("could not revert %s... %s")
2366 : _("could not apply %s... %s"),
39755964 2367 short_commit_name(commit), msg.subject);
005af339 2368 print_advice(r, res == 1, opts);
f11c9580 2369 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 2370 goto leave;
043a4492
RR
2371 }
2372
e98c4269 2373 drop_commit = 0;
f11c9580 2374 allow = allow_empty(r, opts, commit);
706728a3
FC
2375 if (allow < 0) {
2376 res = allow;
2377 goto leave;
e98c4269 2378 } else if (allow == 1) {
789b3eff 2379 flags |= ALLOW_EMPTY;
e98c4269
EN
2380 } else if (allow == 2) {
2381 drop_commit = 1;
c8e4159e
HWN
2382 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2383 NULL, 0);
9a1b7474 2384 unlink(git_path_merge_msg(r));
5291828d 2385 unlink(git_path_auto_merge(r));
e98c4269
EN
2386 fprintf(stderr,
2387 _("dropping %s %s -- patch contents already upstream\n"),
2388 oid_to_hex(&commit->object.oid), msg.subject);
2389 } /* else allow == 0 and there's nothing special to do */
2390 if (!opts->no_commit && !drop_commit) {
356ee465 2391 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
430b75f7
PW
2392 res = do_commit(r, msg_file, author, opts, flags,
2393 commit? &commit->object.oid : NULL);
356ee465
PW
2394 else
2395 res = error(_("unable to parse commit author"));
a47ba3c7
PW
2396 *check_todo = !!(flags & EDIT_MSG);
2397 if (!res && reword) {
450efe2d 2398fast_forward_edit:
20f4b044 2399 res = run_git_commit(NULL, opts, EDIT_MSG |
450efe2d
PW
2400 VERIFY_MSG | AMEND_MSG |
2401 (flags & ALLOW_EMPTY));
a47ba3c7
PW
2402 *check_todo = 1;
2403 }
356ee465 2404 }
6e98de72 2405
450efe2d 2406
6e98de72
JS
2407 if (!res && final_fixup) {
2408 unlink(rebase_path_fixup_msg());
2409 unlink(rebase_path_squash_msg());
e12a7ef5
JS
2410 unlink(rebase_path_current_fixups());
2411 strbuf_reset(&opts->current_fixups);
2412 opts->current_fixup_count = 0;
6e98de72 2413 }
c8d1351d
FC
2414
2415leave:
d74a4e57 2416 free_message(commit, &msg);
356ee465 2417 free(author);
a5792e9d 2418 strbuf_release(&msgbuf);
1e41229d 2419 update_abort_safety_file();
043a4492
RR
2420
2421 return res;
2422}
2423
c3e8618c 2424static int prepare_revs(struct replay_opts *opts)
043a4492 2425{
a73e22e9
MZ
2426 /*
2427 * picking (but not reverting) ranges (but not individual revisions)
2428 * should be done in reverse
2429 */
2430 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2431 opts->revs->reverse ^= 1;
2432
2433 if (prepare_revision_walk(opts->revs))
c3e8618c 2434 return error(_("revision walk setup failed"));
043a4492 2435
c3e8618c 2436 return 0;
043a4492
RR
2437}
2438
f11c9580
NTND
2439static int read_and_refresh_cache(struct repository *r,
2440 struct replay_opts *opts)
043a4492 2441{
14bca6c6 2442 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2443 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2444 if (repo_read_index(r) < 0) {
49fb937e 2445 rollback_lock_file(&index_lock);
0d9c6dc9 2446 return error(_("git %s: failed to read the index"),
629444ad 2447 action_name(opts));
49fb937e 2448 }
f11c9580 2449 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
5d9c9349 2450
61000814 2451 if (index_fd >= 0) {
f11c9580 2452 if (write_locked_index(r->index, &index_lock,
61000814 2453 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2454 return error(_("git %s: failed to refresh the index"),
629444ad 2455 action_name(opts));
49fb937e 2456 }
043a4492 2457 }
5d9c9349
DS
2458
2459 /*
2460 * If we are resolving merges in any way other than "ort", then
2461 * expand the sparse index.
2462 */
2463 if (opts->strategy && strcmp(opts->strategy, "ort"))
2464 ensure_full_index(r->index);
0d9c6dc9 2465 return 0;
043a4492
RR
2466}
2467
5d94d545 2468void todo_list_release(struct todo_list *todo_list)
043a4492 2469{
004fefa7 2470 strbuf_release(&todo_list->buf);
6a83d902 2471 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2472 todo_list->nr = todo_list->alloc = 0;
2473}
043a4492 2474
004fefa7
JS
2475static struct todo_item *append_new_todo(struct todo_list *todo_list)
2476{
2477 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
8638114e 2478 todo_list->total_nr++;
004fefa7 2479 return todo_list->items + todo_list->nr++;
043a4492
RR
2480}
2481
6ad656db
AG
2482const char *todo_item_get_arg(struct todo_list *todo_list,
2483 struct todo_item *item)
2484{
2485 return todo_list->buf.buf + item->arg_offset;
2486}
2487
3e81bccd
PW
2488static int is_command(enum todo_command command, const char **bol)
2489{
2490 const char *str = todo_command_info[command].str;
2491 const char nick = todo_command_info[command].c;
7aed2c05 2492 const char *p = *bol;
3e81bccd 2493
7aed2c05
PW
2494 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2495 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2496 (*bol = p);
3e81bccd
PW
2497}
2498
16b3880d
PW
2499static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2500{
2501 switch (command) {
2502 case TODO_LABEL:
2503 /*
2504 * '#' is not a valid label as the merge command uses it to
2505 * separate merge parents from the commit subject.
2506 */
2507 if (!strcmp(arg, "#") ||
2508 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2509 return error(_("'%s' is not a valid label"), arg);
2510 break;
2511
2512 case TODO_UPDATE_REF:
2513 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2514 return error(_("'%s' is not a valid refname"), arg);
2515 if (check_refname_format(arg, 0))
2516 return error(_("update-ref requires a fully qualified "
2517 "refname e.g. refs/heads/%s"), arg);
2518 break;
2519
2520 default:
2521 BUG("unexpected todo_command");
2522 }
2523
2524 return 0;
2525}
2526
005af339 2527static int parse_insn_line(struct repository *r, struct todo_item *item,
6ad656db 2528 const char *buf, const char *bol, char *eol)
043a4492 2529{
1e43ed98 2530 struct object_id commit_oid;
043a4492 2531 char *end_of_object_name;
004fefa7
JS
2532 int i, saved, status, padding;
2533
4c68e7dd
JS
2534 item->flags = 0;
2535
8f8550b3
JS
2536 /* left-trim */
2537 bol += strspn(bol, " \t");
2538
25c43667 2539 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2540 item->command = TODO_COMMENT;
25c43667 2541 item->commit = NULL;
6ad656db 2542 item->arg_offset = bol - buf;
25c43667
JS
2543 item->arg_len = eol - bol;
2544 return 0;
2545 }
2546
ac191470 2547 for (i = 0; i < TODO_COMMENT; i++)
3e81bccd 2548 if (is_command(i, &bol)) {
004fefa7
JS
2549 item->command = i;
2550 break;
2551 }
ac191470 2552 if (i >= TODO_COMMENT)
7aed2c05
PW
2553 return error(_("invalid command '%.*s'"),
2554 (int)strcspn(bol, " \t\r\n"), bol);
043a4492 2555
66afa24f
JS
2556 /* Eat up extra spaces/ tabs before object name */
2557 padding = strspn(bol, " \t");
2558 bol += padding;
2559
71f82465 2560 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2561 if (bol != eol)
2562 return error(_("%s does not accept arguments: '%s'"),
2563 command_to_string(item->command), bol);
25c43667 2564 item->commit = NULL;
6ad656db 2565 item->arg_offset = bol - buf;
25c43667
JS
2566 item->arg_len = eol - bol;
2567 return 0;
2568 }
2569
043a4492 2570 if (!padding)
66afa24f
JS
2571 return error(_("missing arguments for %s"),
2572 command_to_string(item->command));
043a4492 2573
9055e401 2574 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
a97d7916 2575 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
16b3880d
PW
2576 int ret = 0;
2577
7dcbb3cb 2578 item->commit = NULL;
6ad656db 2579 item->arg_offset = bol - buf;
311af526 2580 item->arg_len = (int)(eol - bol);
16b3880d
PW
2581 if (item->command == TODO_LABEL ||
2582 item->command == TODO_UPDATE_REF) {
2583 saved = *eol;
2584 *eol = '\0';
2585 ret = check_label_or_ref_arg(item->command, bol);
2586 *eol = saved;
2587 }
2588 return ret;
311af526
JS
2589 }
2590
9e3cebd9 2591 if (item->command == TODO_FIXUP) {
666b6e11 2592 if (skip_prefix(bol, "-C", &bol)) {
9e3cebd9
CM
2593 bol += strspn(bol, " \t");
2594 item->flags |= TODO_REPLACE_FIXUP_MSG;
666b6e11 2595 } else if (skip_prefix(bol, "-c", &bol)) {
9e3cebd9
CM
2596 bol += strspn(bol, " \t");
2597 item->flags |= TODO_EDIT_FIXUP_MSG;
2598 }
2599 }
2600
4c68e7dd
JS
2601 if (item->command == TODO_MERGE) {
2602 if (skip_prefix(bol, "-C", &bol))
2603 bol += strspn(bol, " \t");
2604 else if (skip_prefix(bol, "-c", &bol)) {
2605 bol += strspn(bol, " \t");
2606 item->flags |= TODO_EDIT_MERGE_MSG;
2607 } else {
2608 item->flags |= TODO_EDIT_MERGE_MSG;
2609 item->commit = NULL;
6ad656db 2610 item->arg_offset = bol - buf;
4c68e7dd
JS
2611 item->arg_len = (int)(eol - bol);
2612 return 0;
2613 }
2614 }
2615
004fefa7 2616 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2617 saved = *end_of_object_name;
2618 *end_of_object_name = '\0';
d850b7a5 2619 status = repo_get_oid(the_repository, bol, &commit_oid);
d859dcad
JS
2620 if (status < 0)
2621 error(_("could not parse '%s'"), bol); /* return later */
043a4492
RR
2622 *end_of_object_name = saved;
2623
6ad656db
AG
2624 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2625 item->arg_offset = bol - buf;
2626 item->arg_len = (int)(eol - bol);
c22f7dfb 2627
043a4492 2628 if (status < 0)
d859dcad 2629 return status;
043a4492 2630
005af339 2631 item->commit = lookup_commit_reference(r, &commit_oid);
d859dcad 2632 return item->commit ? 0 : -1;
043a4492
RR
2633}
2634
4a72486d
PW
2635int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2636{
ed5b1ca1 2637 const char *todo_file, *bol;
4a72486d 2638 struct strbuf buf = STRBUF_INIT;
ed5b1ca1 2639 int ret = 0;
4a72486d
PW
2640
2641 todo_file = git_path_todo_file();
2642 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
ed5b1ca1 2643 if (errno == ENOENT || errno == ENOTDIR)
4a72486d
PW
2644 return -1;
2645 else
2646 return error_errno("unable to open '%s'", todo_file);
2647 }
ed5b1ca1
PW
2648 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2649 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
4a72486d 2650 *action = REPLAY_PICK;
ed5b1ca1
PW
2651 else if (is_command(TODO_REVERT, &bol) &&
2652 (*bol == ' ' || *bol == '\t'))
4a72486d
PW
2653 *action = REPLAY_REVERT;
2654 else
ed5b1ca1 2655 ret = -1;
4a72486d 2656
4a72486d
PW
2657 strbuf_release(&buf);
2658
2659 return ret;
2660}
2661
5d94d545
AG
2662int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2663 struct todo_list *todo_list)
043a4492 2664{
004fefa7
JS
2665 struct todo_item *item;
2666 char *p = buf, *next_p;
6e98de72 2667 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2668
2b71595d
AG
2669 todo_list->current = todo_list->nr = 0;
2670
004fefa7 2671 for (i = 1; *p; i++, p = next_p) {
043a4492 2672 char *eol = strchrnul(p, '\n');
004fefa7
JS
2673
2674 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2675
6307041d
JS
2676 if (p != eol && eol[-1] == '\r')
2677 eol--; /* strip Carriage Return */
2678
004fefa7
JS
2679 item = append_new_todo(todo_list);
2680 item->offset_in_buf = p - todo_list->buf.buf;
6ad656db 2681 if (parse_insn_line(r, item, buf, p, eol)) {
93b3df6f 2682 res = error(_("invalid line %d: %.*s"),
004fefa7 2683 i, (int)(eol - p), p);
2b71595d 2684 item->command = TODO_COMMENT + 1;
6ad656db 2685 item->arg_offset = p - buf;
2b71595d
AG
2686 item->arg_len = (int)(eol - p);
2687 item->commit = NULL;
004fefa7 2688 }
6e98de72
JS
2689
2690 if (fixup_okay)
2691 ; /* do nothing */
2692 else if (is_fixup(item->command))
2693 return error(_("cannot '%s' without a previous commit"),
2694 command_to_string(item->command));
2695 else if (!is_noop(item->command))
2696 fixup_okay = 1;
043a4492 2697 }
52865279 2698
004fefa7 2699 return res;
043a4492
RR
2700}
2701
968492e4
JS
2702static int count_commands(struct todo_list *todo_list)
2703{
2704 int count = 0, i;
2705
2706 for (i = 0; i < todo_list->nr; i++)
2707 if (todo_list->items[i].command != TODO_COMMENT)
2708 count++;
2709
2710 return count;
2711}
2712
a01c2a5f
JS
2713static int get_item_line_offset(struct todo_list *todo_list, int index)
2714{
2715 return index < todo_list->nr ?
2716 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2717}
2718
2719static const char *get_item_line(struct todo_list *todo_list, int index)
2720{
2721 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2722}
2723
2724static int get_item_line_length(struct todo_list *todo_list, int index)
2725{
2726 return get_item_line_offset(todo_list, index + 1)
2727 - get_item_line_offset(todo_list, index);
2728}
2729
87805600
RS
2730static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2731{
2732 int fd;
2733 ssize_t len;
2734
2735 fd = open(path, O_RDONLY);
2736 if (fd < 0)
2737 return error_errno(_("could not open '%s'"), path);
2738 len = strbuf_read(sb, fd, 0);
2739 close(fd);
2740 if (len < 0)
2741 return error(_("could not read '%s'."), path);
2742 return len;
2743}
2744
b07d9bfd
PW
2745static int have_finished_the_last_pick(void)
2746{
2747 struct strbuf buf = STRBUF_INIT;
2748 const char *eol;
2749 const char *todo_path = git_path_todo_file();
2750 int ret = 0;
2751
2752 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2753 if (errno == ENOENT) {
2754 return 0;
2755 } else {
2756 error_errno("unable to open '%s'", todo_path);
2757 return 0;
2758 }
2759 }
2760 /* If there is only one line then we are done */
2761 eol = strchr(buf.buf, '\n');
2762 if (!eol || !eol[1])
2763 ret = 1;
2764
2765 strbuf_release(&buf);
2766
2767 return ret;
2768}
2769
f496b064 2770void sequencer_post_commit_cleanup(struct repository *r, int verbose)
b07d9bfd
PW
2771{
2772 struct replay_opts opts = REPLAY_OPTS_INIT;
2773 int need_cleanup = 0;
2774
c8e4159e
HWN
2775 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2776 if (!refs_delete_ref(get_main_ref_store(r), "",
2777 "CHERRY_PICK_HEAD", NULL, 0) &&
2778 verbose)
f496b064 2779 warning(_("cancelling a cherry picking in progress"));
b07d9bfd
PW
2780 opts.action = REPLAY_PICK;
2781 need_cleanup = 1;
2782 }
2783
b8825ef2
HWN
2784 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2785 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2786 NULL, 0) &&
2787 verbose)
f496b064 2788 warning(_("cancelling a revert in progress"));
b07d9bfd
PW
2789 opts.action = REPLAY_REVERT;
2790 need_cleanup = 1;
2791 }
2792
5291828d
EN
2793 unlink(git_path_auto_merge(r));
2794
b07d9bfd
PW
2795 if (!need_cleanup)
2796 return;
2797
2798 if (!have_finished_the_last_pick())
2799 return;
2800
2801 sequencer_remove_state(&opts);
2802}
2803
3f34f2d8
AG
2804static void todo_list_write_total_nr(struct todo_list *todo_list)
2805{
2806 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2807
2808 if (f) {
2809 fprintf(f, "%d\n", todo_list->total_nr);
2810 fclose(f);
2811 }
2812}
2813
005af339
NTND
2814static int read_populate_todo(struct repository *r,
2815 struct todo_list *todo_list,
2816 struct replay_opts *opts)
043a4492 2817{
c0246501 2818 const char *todo_file = get_todo_path(opts);
87805600 2819 int res;
043a4492 2820
004fefa7 2821 strbuf_reset(&todo_list->buf);
87805600
RS
2822 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2823 return -1;
043a4492 2824
5d94d545 2825 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2826 if (res) {
2827 if (is_rebase_i(opts))
2828 return error(_("please fix this using "
2829 "'git rebase --edit-todo'."));
93b3df6f 2830 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2831 }
2eeaf1b3 2832
52865279
JS
2833 if (!todo_list->nr &&
2834 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2835 return error(_("no commits parsed."));
2836
2eeaf1b3 2837 if (!is_rebase_i(opts)) {
004fefa7
JS
2838 enum todo_command valid =
2839 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2840 int i;
2841
2842 for (i = 0; i < todo_list->nr; i++)
2843 if (valid == todo_list->items[i].command)
2844 continue;
2845 else if (valid == TODO_PICK)
93b3df6f 2846 return error(_("cannot cherry-pick during a revert."));
004fefa7 2847 else
93b3df6f 2848 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2849 }
2850
968492e4
JS
2851 if (is_rebase_i(opts)) {
2852 struct todo_list done = TODO_LIST_INIT;
2853
2854 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
5d94d545 2855 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2856 todo_list->done_nr = count_commands(&done);
2857 else
2858 todo_list->done_nr = 0;
2859
2860 todo_list->total_nr = todo_list->done_nr
2861 + count_commands(todo_list);
968492e4 2862 todo_list_release(&done);
ef80069a 2863
3f34f2d8 2864 todo_list_write_total_nr(todo_list);
968492e4
JS
2865 }
2866
0ae42a03 2867 return 0;
043a4492
RR
2868}
2869
03a4e260
JS
2870static int git_config_string_dup(char **dest,
2871 const char *var, const char *value)
2872{
2873 if (!value)
2874 return config_error_nonbool(var);
2875 free(*dest);
2876 *dest = xstrdup(value);
2877 return 0;
2878}
2879
043a4492
RR
2880static int populate_opts_cb(const char *key, const char *value, void *data)
2881{
2882 struct replay_opts *opts = data;
2883 int error_flag = 1;
2884
2885 if (!value)
2886 error_flag = 0;
2887 else if (!strcmp(key, "options.no-commit"))
2888 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2889 else if (!strcmp(key, "options.edit"))
2890 opts->edit = git_config_bool_or_int(key, value, &error_flag);
6860ce5d
PW
2891 else if (!strcmp(key, "options.allow-empty"))
2892 opts->allow_empty =
2893 git_config_bool_or_int(key, value, &error_flag);
2894 else if (!strcmp(key, "options.allow-empty-message"))
2895 opts->allow_empty_message =
2896 git_config_bool_or_int(key, value, &error_flag);
2897 else if (!strcmp(key, "options.keep-redundant-commits"))
2898 opts->keep_redundant_commits =
2899 git_config_bool_or_int(key, value, &error_flag);
043a4492
RR
2900 else if (!strcmp(key, "options.signoff"))
2901 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2902 else if (!strcmp(key, "options.record-origin"))
2903 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2904 else if (!strcmp(key, "options.allow-ff"))
2905 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2906 else if (!strcmp(key, "options.mainline"))
2907 opts->mainline = git_config_int(key, value);
2908 else if (!strcmp(key, "options.strategy"))
03a4e260 2909 git_config_string_dup(&opts->strategy, key, value);
3253553e 2910 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2911 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492
RR
2912 else if (!strcmp(key, "options.strategy-option")) {
2913 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2914 opts->xopts[opts->xopts_nr++] = xstrdup(value);
8d8cb4b0
PW
2915 } else if (!strcmp(key, "options.allow-rerere-auto"))
2916 opts->allow_rerere_auto =
2917 git_config_bool_or_int(key, value, &error_flag) ?
2918 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2919 else if (!strcmp(key, "options.default-msg-cleanup")) {
2920 opts->explicit_cleanup = 1;
2921 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2922 } else
93b3df6f 2923 return error(_("invalid key: %s"), key);
043a4492
RR
2924
2925 if (!error_flag)
1a8aea85 2926 return error(_("invalid value for '%s': '%s'"), key, value);
043a4492
RR
2927
2928 return 0;
2929}
2930
65850686 2931void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2932{
2933 int i;
65850686 2934 char *strategy_opts_string = raw_opts;
ca6c6b45 2935
0060041d
EN
2936 if (*strategy_opts_string == ' ')
2937 strategy_opts_string++;
65850686 2938
0060041d
EN
2939 opts->xopts_nr = split_cmdline(strategy_opts_string,
2940 (const char ***)&opts->xopts);
ca6c6b45
JS
2941 for (i = 0; i < opts->xopts_nr; i++) {
2942 const char *arg = opts->xopts[i];
2943
2944 skip_prefix(arg, "--", &arg);
2945 opts->xopts[i] = xstrdup(arg);
2946 }
2947}
2948
65850686
AG
2949static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2950{
2951 strbuf_reset(buf);
2952 if (!read_oneliner(buf, rebase_path_strategy(), 0))
2953 return;
f1f4ebf4 2954 free(opts->strategy);
65850686
AG
2955 opts->strategy = strbuf_detach(buf, NULL);
2956 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2957 return;
2958
2959 parse_strategy_opts(opts, buf->buf);
2960}
2961
5adf9bdc 2962static int read_populate_opts(struct replay_opts *opts)
043a4492 2963{
a1c75762
JS
2964 if (is_rebase_i(opts)) {
2965 struct strbuf buf = STRBUF_INIT;
65c425a2 2966 int ret = 0;
a1c75762 2967
3442c3d1
DL
2968 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2969 READ_ONELINER_SKIP_IF_EMPTY)) {
a1c75762
JS
2970 if (!starts_with(buf.buf, "-S"))
2971 strbuf_reset(&buf);
2972 else {
2973 free(opts->gpg_sign);
2974 opts->gpg_sign = xstrdup(buf.buf + 2);
2975 }
9b6d7a62
PW
2976 strbuf_reset(&buf);
2977 }
2978
3442c3d1
DL
2979 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2980 READ_ONELINER_SKIP_IF_EMPTY)) {
9b6d7a62
PW
2981 if (!strcmp(buf.buf, "--rerere-autoupdate"))
2982 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2983 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2984 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2985 strbuf_reset(&buf);
a1c75762 2986 }
a1c75762 2987
556907f1
JS
2988 if (file_exists(rebase_path_verbose()))
2989 opts->verbose = 1;
2990
899b49c4
EN
2991 if (file_exists(rebase_path_quiet()))
2992 opts->quiet = 1;
2993
a852ec7f
PW
2994 if (file_exists(rebase_path_signoff())) {
2995 opts->allow_ff = 0;
2996 opts->signoff = 1;
2997 }
2998
7573cec5
PW
2999 if (file_exists(rebase_path_cdate_is_adate())) {
3000 opts->allow_ff = 0;
3001 opts->committer_date_is_author_date = 1;
3002 }
3003
a3894aad
PW
3004 if (file_exists(rebase_path_ignore_date())) {
3005 opts->allow_ff = 0;
3006 opts->ignore_date = 1;
3007 }
3008
d421afa0
JS
3009 if (file_exists(rebase_path_reschedule_failed_exec()))
3010 opts->reschedule_failed_exec = 1;
e5b32bff
ÆAB
3011 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3012 opts->reschedule_failed_exec = 0;
d421afa0 3013
e98c4269
EN
3014 if (file_exists(rebase_path_drop_redundant_commits()))
3015 opts->drop_redundant_commits = 1;
3016
3017 if (file_exists(rebase_path_keep_redundant_commits()))
3018 opts->keep_redundant_commits = 1;
3019
ca6c6b45 3020 read_strategy_opts(opts, &buf);
65c425a2 3021 strbuf_reset(&buf);
ca6c6b45 3022
e12a7ef5 3023 if (read_oneliner(&opts->current_fixups,
3442c3d1
DL
3024 rebase_path_current_fixups(),
3025 READ_ONELINER_SKIP_IF_EMPTY)) {
e12a7ef5
JS
3026 const char *p = opts->current_fixups.buf;
3027 opts->current_fixup_count = 1;
3028 while ((p = strchr(p, '\n'))) {
3029 opts->current_fixup_count++;
3030 p++;
3031 }
3032 }
3033
d87d48b2 3034 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
d850b7a5 3035 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
65c425a2
DL
3036 ret = error(_("unusable squash-onto"));
3037 goto done_rebase_i;
3038 }
d87d48b2
JS
3039 opts->have_squash_onto = 1;
3040 }
3041
65c425a2
DL
3042done_rebase_i:
3043 strbuf_release(&buf);
3044 return ret;
a1c75762 3045 }
b5a67045 3046
f932729c 3047 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
3048 return 0;
3049 /*
3050 * The function git_parse_source(), called from git_config_from_file(),
3051 * may die() in case of a syntactically incorrect file. We do not care
3052 * about this case, though, because we wrote that file ourselves, so we
3053 * are pretty certain that it is syntactically correct.
3054 */
5adf9bdc 3055 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 3056 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
3057 git_path_opts_file());
3058 return 0;
043a4492
RR
3059}
3060
65850686
AG
3061static void write_strategy_opts(struct replay_opts *opts)
3062{
3063 int i;
3064 struct strbuf buf = STRBUF_INIT;
3065
3066 for (i = 0; i < opts->xopts_nr; ++i)
3067 strbuf_addf(&buf, " --%s", opts->xopts[i]);
3068
3069 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3070 strbuf_release(&buf);
3071}
3072
3073int write_basic_state(struct replay_opts *opts, const char *head_name,
a2bb10d0 3074 struct commit *onto, const struct object_id *orig_head)
65850686 3075{
65850686
AG
3076 if (head_name)
3077 write_file(rebase_path_head_name(), "%s\n", head_name);
3078 if (onto)
7d3488eb
PW
3079 write_file(rebase_path_onto(), "%s\n",
3080 oid_to_hex(&onto->object.oid));
65850686 3081 if (orig_head)
a2bb10d0
PW
3082 write_file(rebase_path_orig_head(), "%s\n",
3083 oid_to_hex(orig_head));
65850686 3084
8a997ed1
EN
3085 if (opts->quiet)
3086 write_file(rebase_path_quiet(), "%s", "");
65850686 3087 if (opts->verbose)
4af51741 3088 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
3089 if (opts->strategy)
3090 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3091 if (opts->xopts_nr > 0)
3092 write_strategy_opts(opts);
3093
3094 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3095 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3096 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3097 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3098
3099 if (opts->gpg_sign)
3100 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3101 if (opts->signoff)
3102 write_file(rebase_path_signoff(), "--signoff\n");
e98c4269
EN
3103 if (opts->drop_redundant_commits)
3104 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3105 if (opts->keep_redundant_commits)
3106 write_file(rebase_path_keep_redundant_commits(), "%s", "");
7573cec5
PW
3107 if (opts->committer_date_is_author_date)
3108 write_file(rebase_path_cdate_is_adate(), "%s", "");
a3894aad
PW
3109 if (opts->ignore_date)
3110 write_file(rebase_path_ignore_date(), "%s", "");
d421afa0
JS
3111 if (opts->reschedule_failed_exec)
3112 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
e5b32bff
ÆAB
3113 else
3114 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
65850686
AG
3115
3116 return 0;
3117}
3118
004fefa7 3119static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
3120 struct replay_opts *opts)
3121{
004fefa7
JS
3122 enum todo_command command = opts->action == REPLAY_PICK ?
3123 TODO_PICK : TODO_REVERT;
414697a9 3124 const char *command_string = todo_command_info[command].str;
019a9d83 3125 const char *encoding;
043a4492 3126 struct commit *commit;
043a4492 3127
34b0528b
JS
3128 if (prepare_revs(opts))
3129 return -1;
043a4492 3130
019a9d83
ĐTCD
3131 encoding = get_log_output_encoding();
3132
004fefa7
JS
3133 while ((commit = get_revision(opts->revs))) {
3134 struct todo_item *item = append_new_todo(todo_list);
ecb5091f
ÆAB
3135 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3136 commit, NULL,
3137 encoding);
004fefa7
JS
3138 const char *subject;
3139 int subject_len;
3140
3141 item->command = command;
3142 item->commit = commit;
6ad656db 3143 item->arg_offset = 0;
c22f7dfb 3144 item->arg_len = 0;
004fefa7
JS
3145 item->offset_in_buf = todo_list->buf.len;
3146 subject_len = find_commit_subject(commit_buffer, &subject);
3147 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3148 short_commit_name(commit), subject_len, subject);
ecb5091f
ÆAB
3149 repo_unuse_commit_buffer(the_repository, commit,
3150 commit_buffer);
004fefa7 3151 }
8530c739
JK
3152
3153 if (!todo_list->nr)
3154 return error(_("empty commit set passed"));
3155
34b0528b 3156 return 0;
043a4492
RR
3157}
3158
6a1f9046 3159static int create_seq_dir(struct repository *r)
043a4492 3160{
6a1f9046
RA
3161 enum replay_action action;
3162 const char *in_progress_error = NULL;
3163 const char *in_progress_advice = NULL;
c8e4159e 3164 unsigned int advise_skip =
b8825ef2 3165 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
c8e4159e 3166 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
6a1f9046
RA
3167
3168 if (!sequencer_get_last_command(r, &action)) {
3169 switch (action) {
3170 case REPLAY_REVERT:
3171 in_progress_error = _("revert is already in progress");
3172 in_progress_advice =
dcb500dc 3173 _("try \"git revert (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3174 break;
3175 case REPLAY_PICK:
3176 in_progress_error = _("cherry-pick is already in progress");
3177 in_progress_advice =
dcb500dc 3178 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3179 break;
3180 default:
3181 BUG("unexpected action in create_seq_dir");
3182 }
3183 }
3184 if (in_progress_error) {
3185 error("%s", in_progress_error);
ed9bff08 3186 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
dcb500dc
RA
3187 advise(in_progress_advice,
3188 advise_skip ? "--skip | " : "");
043a4492 3189 return -1;
6a1f9046
RA
3190 }
3191 if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 3192 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 3193 git_path_seq_dir());
6a1f9046 3194
043a4492
RR
3195 return 0;
3196}
3197
311fd397 3198static int save_head(const char *head)
043a4492 3199{
14bca6c6 3200 struct lock_file head_lock = LOCK_INIT;
043a4492
RR
3201 struct strbuf buf = STRBUF_INIT;
3202 int fd;
ed3f9a12 3203 ssize_t written;
043a4492 3204
311fd397 3205 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
350292a1 3206 if (fd < 0)
93b3df6f 3207 return error_errno(_("could not lock HEAD"));
043a4492 3208 strbuf_addf(&buf, "%s\n", head);
ed3f9a12
RS
3209 written = write_in_full(fd, buf.buf, buf.len);
3210 strbuf_release(&buf);
3211 if (written < 0) {
bf5c0571 3212 error_errno(_("could not write to '%s'"), git_path_head_file());
311fd397 3213 rollback_lock_file(&head_lock);
bf5c0571 3214 return -1;
311fd397 3215 }
350292a1
3216 if (commit_lock_file(&head_lock) < 0)
3217 return error(_("failed to finalize '%s'"), git_path_head_file());
311fd397 3218 return 0;
043a4492
RR
3219}
3220
1e41229d
SB
3221static int rollback_is_safe(void)
3222{
3223 struct strbuf sb = STRBUF_INIT;
3224 struct object_id expected_head, actual_head;
3225
3226 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3227 strbuf_trim(&sb);
3228 if (get_oid_hex(sb.buf, &expected_head)) {
3229 strbuf_release(&sb);
3230 die(_("could not parse %s"), git_path_abort_safety_file());
3231 }
3232 strbuf_release(&sb);
3233 }
3234 else if (errno == ENOENT)
3235 oidclr(&expected_head);
3236 else
3237 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3238
d850b7a5 3239 if (repo_get_oid(the_repository, "HEAD", &actual_head))
1e41229d
SB
3240 oidclr(&actual_head);
3241
4a7e27e9 3242 return oideq(&actual_head, &expected_head);
1e41229d
SB
3243}
3244
918d1e6e 3245static int reset_merge(const struct object_id *oid)
043a4492 3246{
0e906739 3247 struct child_process cmd = CHILD_PROCESS_INIT;
1e41229d 3248
0e906739
RS
3249 cmd.git_cmd = 1;
3250 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
265ab48f
RA
3251
3252 if (!is_null_oid(oid))
0e906739 3253 strvec_push(&cmd.args, oid_to_hex(oid));
265ab48f 3254
0e906739 3255 return run_command(&cmd);
043a4492
RR
3256}
3257
005af339 3258static int rollback_single_pick(struct repository *r)
043a4492 3259{
092bbcdf 3260 struct object_id head_oid;
043a4492 3261
c8e4159e 3262 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 3263 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 3264 return error(_("no cherry-pick or revert in progress"));
34c290a6 3265 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 3266 return error(_("cannot resolve HEAD"));
092bbcdf 3267 if (is_null_oid(&head_oid))
043a4492 3268 return error(_("cannot abort from a branch yet to be born"));
918d1e6e 3269 return reset_merge(&head_oid);
043a4492
RR
3270}
3271
de81ca3f
RA
3272static int skip_single_pick(void)
3273{
3274 struct object_id head;
3275
3276 if (read_ref_full("HEAD", 0, &head, NULL))
3277 return error(_("cannot resolve HEAD"));
3278 return reset_merge(&head);
043a4492
RR
3279}
3280
005af339 3281int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 3282{
043a4492 3283 FILE *f;
092bbcdf 3284 struct object_id oid;
043a4492 3285 struct strbuf buf = STRBUF_INIT;
092bbcdf 3286 const char *p;
043a4492 3287
f932729c 3288 f = fopen(git_path_head_file(), "r");
043a4492
RR
3289 if (!f && errno == ENOENT) {
3290 /*
3291 * There is no multiple-cherry-pick in progress.
3292 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3293 * a single-cherry-pick in progress, abort that.
3294 */
005af339 3295 return rollback_single_pick(r);
043a4492
RR
3296 }
3297 if (!f)
f7ed1953 3298 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 3299 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 3300 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 3301 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
3302 fclose(f);
3303 goto fail;
3304 }
3305 fclose(f);
092bbcdf 3306 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 3307 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 3308 git_path_head_file());
043a4492
RR
3309 goto fail;
3310 }
092bbcdf 3311 if (is_null_oid(&oid)) {
0f974e21
MG
3312 error(_("cannot abort from a branch yet to be born"));
3313 goto fail;
3314 }
1e41229d
SB
3315
3316 if (!rollback_is_safe()) {
3317 /* Do not error, just do not rollback */
3318 warning(_("You seem to have moved HEAD. "
3319 "Not rewinding, check your HEAD!"));
3320 } else
918d1e6e 3321 if (reset_merge(&oid))
043a4492 3322 goto fail;
043a4492 3323 strbuf_release(&buf);
2863584f 3324 return sequencer_remove_state(opts);
043a4492
RR
3325fail:
3326 strbuf_release(&buf);
3327 return -1;
3328}
3329
de81ca3f
RA
3330int sequencer_skip(struct repository *r, struct replay_opts *opts)
3331{
3332 enum replay_action action = -1;
3333 sequencer_get_last_command(r, &action);
3334
3335 /*
3336 * Check whether the subcommand requested to skip the commit is actually
3337 * in progress and that it's safe to skip the commit.
3338 *
3339 * opts->action tells us which subcommand requested to skip the commit.
3340 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3341 * action is in progress and we can skip the commit.
3342 *
3343 * Otherwise we check that the last instruction was related to the
3344 * particular subcommand we're trying to execute and barf if that's not
3345 * the case.
3346 *
3347 * Finally we check that the rollback is "safe", i.e., has the HEAD
3348 * moved? In this case, it doesn't make sense to "reset the merge" and
3349 * "skip the commit" as the user already handled this by committing. But
3350 * we'd not want to barf here, instead give advice on how to proceed. We
3351 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3352 * it gets removed when the user commits, so if it still exists we're
3353 * sure the user can't have committed before.
3354 */
3355 switch (opts->action) {
3356 case REPLAY_REVERT:
b8825ef2 3357 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
de81ca3f
RA
3358 if (action != REPLAY_REVERT)
3359 return error(_("no revert in progress"));
3360 if (!rollback_is_safe())
3361 goto give_advice;
3362 }
3363 break;
3364 case REPLAY_PICK:
c8e4159e
HWN
3365 if (!refs_ref_exists(get_main_ref_store(r),
3366 "CHERRY_PICK_HEAD")) {
de81ca3f
RA
3367 if (action != REPLAY_PICK)
3368 return error(_("no cherry-pick in progress"));
3369 if (!rollback_is_safe())
3370 goto give_advice;
3371 }
3372 break;
3373 default:
3374 BUG("unexpected action in sequencer_skip");
3375 }
3376
3377 if (skip_single_pick())
3378 return error(_("failed to skip the commit"));
3379 if (!is_directory(git_path_seq_dir()))
3380 return 0;
3381
3382 return sequencer_continue(r, opts);
3383
3384give_advice:
3385 error(_("there is nothing to skip"));
3386
ed9bff08 3387 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
de81ca3f
RA
3388 advise(_("have you committed already?\n"
3389 "try \"git %s --continue\""),
3390 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3391 }
3392 return -1;
3393}
3394
004fefa7 3395static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 3396{
14bca6c6 3397 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
3398 const char *todo_path = get_todo_path(opts);
3399 int next = todo_list->current, offset, fd;
043a4492 3400
84583957
JS
3401 /*
3402 * rebase -i writes "git-rebase-todo" without the currently executing
3403 * command, appending it to "done" instead.
3404 */
3405 if (is_rebase_i(opts))
3406 next++;
3407
004fefa7 3408 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 3409 if (fd < 0)
93b3df6f 3410 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 3411 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
3412 if (write_in_full(fd, todo_list->buf.buf + offset,
3413 todo_list->buf.len - offset) < 0)
93b3df6f 3414 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 3415 if (commit_lock_file(&todo_lock) < 0)
350292a1 3416 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 3417
a01c2a5f
JS
3418 if (is_rebase_i(opts) && next > 0) {
3419 const char *done = rebase_path_done();
3420 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3421 int ret = 0;
1df6df0c 3422
a01c2a5f
JS
3423 if (fd < 0)
3424 return 0;
3425 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3426 get_item_line_length(todo_list, next - 1))
3427 < 0)
3428 ret = error_errno(_("could not write to '%s'"), done);
3429 if (close(fd) < 0)
3430 ret = error_errno(_("failed to finalize '%s'"), done);
3431 return ret;
1df6df0c 3432 }
221675de 3433 return 0;
043a4492
RR
3434}
3435
88d5a271 3436static int save_opts(struct replay_opts *opts)
043a4492 3437{
f932729c 3438 const char *opts_file = git_path_opts_file();
88d5a271 3439 int res = 0;
043a4492
RR
3440
3441 if (opts->no_commit)
f59199d5
PW
3442 res |= git_config_set_in_file_gently(opts_file,
3443 "options.no-commit", "true");
39edfd5c
EN
3444 if (opts->edit >= 0)
3445 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3446 opts->edit ? "true" : "false");
6860ce5d
PW
3447 if (opts->allow_empty)
3448 res |= git_config_set_in_file_gently(opts_file,
3449 "options.allow-empty", "true");
3450 if (opts->allow_empty_message)
3451 res |= git_config_set_in_file_gently(opts_file,
3452 "options.allow-empty-message", "true");
3453 if (opts->keep_redundant_commits)
3454 res |= git_config_set_in_file_gently(opts_file,
3455 "options.keep-redundant-commits", "true");
043a4492 3456 if (opts->signoff)
f59199d5
PW
3457 res |= git_config_set_in_file_gently(opts_file,
3458 "options.signoff", "true");
043a4492 3459 if (opts->record_origin)
f59199d5
PW
3460 res |= git_config_set_in_file_gently(opts_file,
3461 "options.record-origin", "true");
043a4492 3462 if (opts->allow_ff)
f59199d5
PW
3463 res |= git_config_set_in_file_gently(opts_file,
3464 "options.allow-ff", "true");
043a4492
RR
3465 if (opts->mainline) {
3466 struct strbuf buf = STRBUF_INIT;
3467 strbuf_addf(&buf, "%d", opts->mainline);
f59199d5
PW
3468 res |= git_config_set_in_file_gently(opts_file,
3469 "options.mainline", buf.buf);
043a4492
RR
3470 strbuf_release(&buf);
3471 }
3472 if (opts->strategy)
f59199d5
PW
3473 res |= git_config_set_in_file_gently(opts_file,
3474 "options.strategy", opts->strategy);
3253553e 3475 if (opts->gpg_sign)
f59199d5
PW
3476 res |= git_config_set_in_file_gently(opts_file,
3477 "options.gpg-sign", opts->gpg_sign);
043a4492
RR
3478 if (opts->xopts) {
3479 int i;
3480 for (i = 0; i < opts->xopts_nr; i++)
88d5a271 3481 res |= git_config_set_multivar_in_file_gently(opts_file,
f59199d5
PW
3482 "options.strategy-option",
3483 opts->xopts[i], "^$", 0);
043a4492 3484 }
8d8cb4b0 3485 if (opts->allow_rerere_auto)
f59199d5
PW
3486 res |= git_config_set_in_file_gently(opts_file,
3487 "options.allow-rerere-auto",
3488 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3489 "true" : "false");
dc42e9a8
PW
3490
3491 if (opts->explicit_cleanup)
3492 res |= git_config_set_in_file_gently(opts_file,
3493 "options.default-msg-cleanup",
3494 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 3495 return res;
043a4492
RR
3496}
3497
f11c9580
NTND
3498static int make_patch(struct repository *r,
3499 struct commit *commit,
3500 struct replay_opts *opts)
56dc3ab0
JS
3501{
3502 struct strbuf buf = STRBUF_INIT;
3503 struct rev_info log_tree_opt;
0512eabd
JH
3504 const char *subject;
3505 char hex[GIT_MAX_HEXSZ + 1];
56dc3ab0
JS
3506 int res = 0;
3507
0512eabd
JH
3508 oid_to_hex_r(hex, &commit->object.oid);
3509 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
56dc3ab0 3510 return -1;
430b75f7 3511 res |= write_rebase_head(&commit->object.oid);
56dc3ab0
JS
3512
3513 strbuf_addf(&buf, "%s/patch", get_dir(opts));
3514 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3515 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
3516 log_tree_opt.abbrev = 0;
3517 log_tree_opt.diff = 1;
3518 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3519 log_tree_opt.disable_stdin = 1;
3520 log_tree_opt.no_commit_id = 1;
3521 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3522 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3523 if (!log_tree_opt.diffopt.file)
3524 res |= error_errno(_("could not open '%s'"), buf.buf);
3525 else {
3526 res |= log_tree_commit(&log_tree_opt, commit);
3527 fclose(log_tree_opt.diffopt.file);
3528 }
3529 strbuf_reset(&buf);
3530
3531 strbuf_addf(&buf, "%s/message", get_dir(opts));
3532 if (!file_exists(buf.buf)) {
52f52e5a 3533 const char *encoding = get_commit_output_encoding();
ecb5091f
ÆAB
3534 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3535 commit, NULL,
3536 encoding);
56dc3ab0
JS
3537 find_commit_subject(commit_buffer, &subject);
3538 res |= write_message(subject, strlen(subject), buf.buf, 1);
ecb5091f
ÆAB
3539 repo_unuse_commit_buffer(the_repository, commit,
3540 commit_buffer);
56dc3ab0
JS
3541 }
3542 strbuf_release(&buf);
2108fe4a 3543 release_revisions(&log_tree_opt);
56dc3ab0
JS
3544
3545 return res;
3546}
3547
3548static int intend_to_amend(void)
3549{
092bbcdf 3550 struct object_id head;
56dc3ab0
JS
3551 char *p;
3552
d850b7a5 3553 if (repo_get_oid(the_repository, "HEAD", &head))
56dc3ab0
JS
3554 return error(_("cannot read HEAD"));
3555
092bbcdf 3556 p = oid_to_hex(&head);
56dc3ab0
JS
3557 return write_message(p, strlen(p), rebase_path_amend(), 1);
3558}
3559
f11c9580
NTND
3560static int error_with_patch(struct repository *r,
3561 struct commit *commit,
3562 const char *subject, int subject_len,
3563 struct replay_opts *opts,
3564 int exit_code, int to_amend)
56dc3ab0 3565{
bc9238bb 3566 if (commit) {
f11c9580 3567 if (make_patch(r, commit, opts))
bc9238bb 3568 return -1;
5a5c5e95 3569 } else if (copy_file(rebase_path_message(),
f11c9580 3570 git_path_merge_msg(r), 0666))
bc9238bb 3571 return error(_("unable to copy '%s' to '%s'"),
f11c9580 3572 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
3573
3574 if (to_amend) {
3575 if (intend_to_amend())
3576 return -1;
3577
02127c63
NTND
3578 fprintf(stderr,
3579 _("You can amend the commit now, with\n"
3580 "\n"
3581 " git commit --amend %s\n"
3582 "\n"
3583 "Once you are satisfied with your changes, run\n"
3584 "\n"
3585 " git rebase --continue\n"),
3586 gpg_sign_opt_quoted(opts));
bc9238bb
PW
3587 } else if (exit_code) {
3588 if (commit)
5a5c5e95
JH
3589 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3590 short_commit_name(commit), subject_len, subject);
bc9238bb
PW
3591 else
3592 /*
3593 * We don't have the hash of the parent so
3594 * just print the line from the todo file.
3595 */
5a5c5e95
JH
3596 fprintf_ln(stderr, _("Could not merge %.*s"),
3597 subject_len, subject);
bc9238bb 3598 }
56dc3ab0
JS
3599
3600 return exit_code;
3601}
3602
f11c9580
NTND
3603static int error_failed_squash(struct repository *r,
3604 struct commit *commit,
3605 struct replay_opts *opts,
3606 int subject_len,
3607 const char *subject)
6e98de72 3608{
e12a7ef5
JS
3609 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3610 return error(_("could not copy '%s' to '%s'"),
6e98de72 3611 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
3612 unlink(git_path_merge_msg(r));
3613 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 3614 return error(_("could not copy '%s' to '%s'"),
102de880 3615 rebase_path_message(),
f11c9580
NTND
3616 git_path_merge_msg(r));
3617 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
3618}
3619
f11c9580 3620static int do_exec(struct repository *r, const char *command_line)
311af526 3621{
ddbb47fd 3622 struct child_process cmd = CHILD_PROCESS_INIT;
311af526
JS
3623 int dirty, status;
3624
4d55d63b 3625 fprintf(stderr, _("Executing: %s\n"), command_line);
ddbb47fd
RS
3626 cmd.use_shell = 1;
3627 strvec_push(&cmd.args, command_line);
3628 status = run_command(&cmd);
311af526
JS
3629
3630 /* force re-reading of the cache */
9c5f3ee3
ÆAB
3631 discard_index(r->index);
3632 if (repo_read_index(r) < 0)
311af526
JS
3633 return error(_("could not read index"));
3634
f11c9580 3635 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
3636
3637 if (status) {
3638 warning(_("execution failed: %s\n%s"
3639 "You can fix the problem, and then run\n"
3640 "\n"
3641 " git rebase --continue\n"
3642 "\n"),
3643 command_line,
3644 dirty ? N_("and made changes to the index and/or the "
3645 "working tree\n") : "");
3646 if (status == 127)
3647 /* command not found */
3648 status = 1;
3649 } else if (dirty) {
3650 warning(_("execution succeeded: %s\nbut "
3651 "left changes to the index and/or the working tree\n"
3652 "Commit or stash your changes, and then run\n"
3653 "\n"
3654 " git rebase --continue\n"
3655 "\n"), command_line);
3656 status = 1;
3657 }
3658
3659 return status;
3660}
3661
48ca53ca 3662__attribute__((format (printf, 2, 3)))
9055e401
JS
3663static int safe_append(const char *filename, const char *fmt, ...)
3664{
3665 va_list ap;
3666 struct lock_file lock = LOCK_INIT;
3667 int fd = hold_lock_file_for_update(&lock, filename,
3668 LOCK_REPORT_ON_ERROR);
3669 struct strbuf buf = STRBUF_INIT;
3670
3671 if (fd < 0)
3672 return -1;
3673
3674 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3675 error_errno(_("could not read '%s'"), filename);
3676 rollback_lock_file(&lock);
3677 return -1;
3678 }
3679 strbuf_complete(&buf, '\n');
3680 va_start(ap, fmt);
3681 strbuf_vaddf(&buf, fmt, ap);
3682 va_end(ap);
3683
3684 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3685 error_errno(_("could not write to '%s'"), filename);
3686 strbuf_release(&buf);
3687 rollback_lock_file(&lock);
3688 return -1;
3689 }
3690 if (commit_lock_file(&lock) < 0) {
3691 strbuf_release(&buf);
3692 rollback_lock_file(&lock);
3693 return error(_("failed to finalize '%s'"), filename);
3694 }
3695
3696 strbuf_release(&buf);
3697 return 0;
3698}
3699
f11c9580 3700static int do_label(struct repository *r, const char *name, int len)
9055e401 3701{
f11c9580 3702 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3703 struct ref_transaction *transaction;
3704 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3705 struct strbuf msg = STRBUF_INIT;
3706 int ret = 0;
3707 struct object_id head_oid;
3708
3709 if (len == 1 && *name == '#')
02127c63 3710 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3711
3712 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3713 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401 3714
c6da34a6 3715 transaction = ref_store_transaction_begin(refs, &err);
9055e401
JS
3716 if (!transaction) {
3717 error("%s", err.buf);
3718 ret = -1;
d850b7a5 3719 } else if (repo_get_oid(the_repository, "HEAD", &head_oid)) {
9055e401
JS
3720 error(_("could not read HEAD"));
3721 ret = -1;
3722 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3723 NULL, 0, msg.buf, &err) < 0 ||
3724 ref_transaction_commit(transaction, &err)) {
3725 error("%s", err.buf);
3726 ret = -1;
3727 }
3728 ref_transaction_free(transaction);
3729 strbuf_release(&err);
3730 strbuf_release(&msg);
3731
3732 if (!ret)
3733 ret = safe_append(rebase_path_refs_to_delete(),
3734 "%s\n", ref_name.buf);
3735 strbuf_release(&ref_name);
3736
3737 return ret;
3738}
3739
d188a60d
PW
3740static const char *sequencer_reflog_action(struct replay_opts *opts)
3741{
3742 if (!opts->reflog_action) {
3743 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3744 opts->reflog_action =
3745 xstrdup(opts->reflog_action ? opts->reflog_action
3746 : action_name(opts));
3747 }
3748
3749 return opts->reflog_action;
3750}
3751
48ca53ca 3752__attribute__((format (printf, 3, 4)))
9055e401 3753static const char *reflog_message(struct replay_opts *opts,
d4ac3050
ÆAB
3754 const char *sub_action, const char *fmt, ...)
3755{
3756 va_list ap;
3757 static struct strbuf buf = STRBUF_INIT;
d4ac3050
ÆAB
3758
3759 va_start(ap, fmt);
3760 strbuf_reset(&buf);
d188a60d 3761 strbuf_addstr(&buf, sequencer_reflog_action(opts));
d4ac3050
ÆAB
3762 if (sub_action)
3763 strbuf_addf(&buf, " (%s)", sub_action);
3764 if (fmt) {
3765 strbuf_addstr(&buf, ": ");
3766 strbuf_vaddf(&buf, fmt, ap);
3767 }
3768 va_end(ap);
3769
3770 return buf.buf;
3771}
9055e401 3772
688d82f2
PW
3773static struct commit *lookup_label(struct repository *r, const char *label,
3774 int len, struct strbuf *buf)
82766b29
PW
3775{
3776 struct commit *commit;
688d82f2 3777 struct object_id oid;
82766b29
PW
3778
3779 strbuf_reset(buf);
3780 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
688d82f2
PW
3781 if (!read_ref(buf->buf, &oid)) {
3782 commit = lookup_commit_object(r, &oid);
3783 } else {
82766b29
PW
3784 /* fall back to non-rewritten ref or commit */
3785 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3786 commit = lookup_commit_reference_by_name(buf->buf);
3787 }
3788
3789 if (!commit)
3790 error(_("could not resolve '%s'"), buf->buf);
3791
3792 return commit;
3793}
3794
f11c9580
NTND
3795static int do_reset(struct repository *r,
3796 const char *name, int len,
3797 struct replay_opts *opts)
9055e401
JS
3798{
3799 struct strbuf ref_name = STRBUF_INIT;
3800 struct object_id oid;
3801 struct lock_file lock = LOCK_INIT;
0c52cf8e 3802 struct tree_desc desc = { 0 };
9055e401 3803 struct tree *tree;
6e658547 3804 struct unpack_trees_options unpack_tree_opts = { 0 };
71571cd7 3805 int ret = 0;
9055e401 3806
3a95f31d 3807 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3808 return -1;
3809
ebddf393
JS
3810 if (len == 10 && !strncmp("[new root]", name, len)) {
3811 if (!opts->have_squash_onto) {
3812 const char *hex;
3813 if (commit_tree("", 0, the_hash_algo->empty_tree,
3814 NULL, &opts->squash_onto,
3815 NULL, NULL))
3816 return error(_("writing fake root commit"));
3817 opts->have_squash_onto = 1;
3818 hex = oid_to_hex(&opts->squash_onto);
3819 if (write_message(hex, strlen(hex),
3820 rebase_path_squash_onto(), 0))
3821 return error(_("writing squash-onto"));
3822 }
3823 oidcpy(&oid, &opts->squash_onto);
3824 } else {
71571cd7 3825 int i;
82766b29 3826 struct commit *commit;
71571cd7 3827
ebddf393
JS
3828 /* Determine the length of the label */
3829 for (i = 0; i < len; i++)
3830 if (isspace(name[i]))
71571cd7
3831 break;
3832 len = i;
ebddf393 3833
688d82f2 3834 commit = lookup_label(r, name, len, &ref_name);
82766b29
PW
3835 if (!commit) {
3836 ret = -1;
0c52cf8e 3837 goto cleanup;
ebddf393 3838 }
82766b29 3839 oid = commit->object.oid;
9055e401
JS
3840 }
3841
9055e401
JS
3842 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3843 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3844 unpack_tree_opts.src_index = r->index;
3845 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3846 unpack_tree_opts.fn = oneway_merge;
3847 unpack_tree_opts.merge = 1;
3848 unpack_tree_opts.update = 1;
1b5f3733 3849 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
652bd021 3850 unpack_tree_opts.skip_cache_tree_update = 1;
3f267856 3851 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
9055e401 3852
e1ff0a32 3853 if (repo_read_index_unmerged(r)) {
1c8dfc36 3854 ret = error_resolve_conflict(action_name(opts));
0c52cf8e 3855 goto cleanup;
9055e401
JS
3856 }
3857
5e575807 3858 if (!fill_tree_descriptor(r, &desc, &oid)) {
0c52cf8e
ÆAB
3859 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3860 goto cleanup;
9055e401
JS
3861 }
3862
3863 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
0c52cf8e
ÆAB
3864 ret = -1;
3865 goto cleanup;
9055e401
JS
3866 }
3867
3868 tree = parse_tree_indirect(&oid);
c207e9e1 3869 prime_cache_tree(r, r->index, tree);
9055e401 3870
f11c9580 3871 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401 3872 ret = error(_("could not write index"));
9055e401
JS
3873
3874 if (!ret)
3875 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3876 len, name), "HEAD", &oid,
3877 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
0c52cf8e
ÆAB
3878cleanup:
3879 free((void *)desc.buffer);
3880 if (ret < 0)
3881 rollback_lock_file(&lock);
9055e401 3882 strbuf_release(&ref_name);
6e658547 3883 clear_unpack_trees_porcelain(&unpack_tree_opts);
9055e401
JS
3884 return ret;
3885}
3886
f11c9580
NTND
3887static int do_merge(struct repository *r,
3888 struct commit *commit,
3889 const char *arg, int arg_len,
2be6b6f4 3890 int flags, int *check_todo, struct replay_opts *opts)
4c68e7dd 3891{
2be6b6f4 3892 int run_commit_flags = 0;
4c68e7dd
JS
3893 struct strbuf ref_name = STRBUF_INIT;
3894 struct commit *head_commit, *merge_commit, *i;
5327d898 3895 struct commit_list *bases, *j;
2b6ad0f4 3896 struct commit_list *to_merge = NULL, **tail = &to_merge;
e145d993 3897 const char *strategy = !opts->xopts_nr &&
14c4586c
EN
3898 (!opts->strategy ||
3899 !strcmp(opts->strategy, "recursive") ||
3900 !strcmp(opts->strategy, "ort")) ?
e145d993 3901 NULL : opts->strategy;
4c68e7dd 3902 struct merge_options o;
2b6ad0f4 3903 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3904 static struct lock_file lock;
3905 const char *p;
3906
3a95f31d 3907 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3908 ret = -1;
3909 goto leave_merge;
3910 }
3911
3912 head_commit = lookup_commit_reference_by_name("HEAD");
3913 if (!head_commit) {
3914 ret = error(_("cannot merge without a current revision"));
3915 goto leave_merge;
3916 }
3917
2b6ad0f4
JS
3918 /*
3919 * For octopus merges, the arg starts with the list of revisions to be
3920 * merged. The list is optionally followed by '#' and the oneline.
3921 */
3922 merge_arg_len = oneline_offset = arg_len;
3923 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3924 if (!*p)
3925 break;
3926 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3927 p += 1 + strspn(p + 1, " \t\n");
3928 oneline_offset = p - arg;
3929 break;
3930 }
3931 k = strcspn(p, " \t\n");
3932 if (!k)
3933 continue;
688d82f2 3934 merge_commit = lookup_label(r, p, k, &ref_name);
2b6ad0f4
JS
3935 if (!merge_commit) {
3936 ret = error(_("unable to parse '%.*s'"), k, p);
3937 goto leave_merge;
3938 }
3939 tail = &commit_list_insert(merge_commit, tail)->next;
3940 p += k;
3941 merge_arg_len = p - arg;
4c68e7dd
JS
3942 }
3943
2b6ad0f4
JS
3944 if (!to_merge) {
3945 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3946 goto leave_merge;
3947 }
3948
9c85a1c2 3949 if (opts->have_squash_onto &&
4a7e27e9 3950 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3951 /*
3952 * When the user tells us to "merge" something into a
3953 * "[new root]", let's simply fast-forward to the merge head.
3954 */
3955 rollback_lock_file(&lock);
2b6ad0f4
JS
3956 if (to_merge->next)
3957 ret = error(_("octopus merge cannot be executed on "
3958 "top of a [new root]"));
3959 else
f11c9580 3960 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
3961 &head_commit->object.oid, 0,
3962 opts);
9c85a1c2
JS
3963 goto leave_merge;
3964 }
3965
baf8ec8d
PW
3966 /*
3967 * If HEAD is not identical to the first parent of the original merge
3968 * commit, we cannot fast-forward.
3969 */
3970 can_fast_forward = opts->allow_ff && commit && commit->parents &&
3971 oideq(&commit->parents->item->object.oid,
3972 &head_commit->object.oid);
3973
3974 /*
3975 * If any merge head is different from the original one, we cannot
3976 * fast-forward.
3977 */
3978 if (can_fast_forward) {
3979 struct commit_list *p = commit->parents->next;
3980
3981 for (j = to_merge; j && p; j = j->next, p = p->next)
3982 if (!oideq(&j->item->object.oid,
3983 &p->item->object.oid)) {
3984 can_fast_forward = 0;
3985 break;
3986 }
3987 /*
3988 * If the number of merge heads differs from the original merge
3989 * commit, we cannot fast-forward.
3990 */
3991 if (j || p)
3992 can_fast_forward = 0;
3993 }
3994
3995 if (can_fast_forward) {
3996 rollback_lock_file(&lock);
3997 ret = fast_forward_to(r, &commit->object.oid,
3998 &head_commit->object.oid, 0, opts);
3999 if (flags & TODO_EDIT_MERGE_MSG)
4000 goto fast_forward_edit;
4001
4002 goto leave_merge;
4003 }
4004
4c68e7dd 4005 if (commit) {
5772b0c7 4006 const char *encoding = get_commit_output_encoding();
ecb5091f
ÆAB
4007 const char *message = repo_logmsg_reencode(the_repository,
4008 commit, NULL,
4009 encoding);
4c68e7dd
JS
4010 const char *body;
4011 int len;
4012
4013 if (!message) {
4014 ret = error(_("could not get commit message of '%s'"),
4015 oid_to_hex(&commit->object.oid));
4016 goto leave_merge;
4017 }
4018 write_author_script(message);
4019 find_commit_subject(message, &body);
4020 len = strlen(body);
f11c9580 4021 ret = write_message(body, len, git_path_merge_msg(r), 0);
ecb5091f 4022 repo_unuse_commit_buffer(the_repository, commit, message);
4c68e7dd
JS
4023 if (ret) {
4024 error_errno(_("could not write '%s'"),
f11c9580 4025 git_path_merge_msg(r));
4c68e7dd
JS
4026 goto leave_merge;
4027 }
4028 } else {
4029 struct strbuf buf = STRBUF_INIT;
4030 int len;
4031
4032 strbuf_addf(&buf, "author %s", git_author_info(0));
4033 write_author_script(buf.buf);
4034 strbuf_reset(&buf);
4035
4036 if (oneline_offset < arg_len) {
4037 p = arg + oneline_offset;
4038 len = arg_len - oneline_offset;
4039 } else {
2b6ad0f4
JS
4040 strbuf_addf(&buf, "Merge %s '%.*s'",
4041 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
4042 merge_arg_len, arg);
4043 p = buf.buf;
4044 len = buf.len;
4045 }
4046
f11c9580 4047 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
4048 strbuf_release(&buf);
4049 if (ret) {
4050 error_errno(_("could not write '%s'"),
f11c9580 4051 git_path_merge_msg(r));
4c68e7dd
JS
4052 goto leave_merge;
4053 }
4054 }
4055
e145d993 4056 if (strategy || to_merge->next) {
2b6ad0f4
JS
4057 /* Octopus merge */
4058 struct child_process cmd = CHILD_PROCESS_INIT;
4059
29fda24d 4060 if (read_env_script(&cmd.env)) {
2b6ad0f4
JS
4061 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4062
4063 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4064 goto leave_merge;
4065 }
4066
7573cec5 4067 if (opts->committer_date_is_author_date)
29fda24d 4068 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
9c31b19d
JH
4069 opts->ignore_date ?
4070 "" :
b3193252 4071 author_date_from_env(&cmd.env));
a3894aad 4072 if (opts->ignore_date)
29fda24d 4073 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
7573cec5 4074
2b6ad0f4 4075 cmd.git_cmd = 1;
c972bf4c
JK
4076 strvec_push(&cmd.args, "merge");
4077 strvec_push(&cmd.args, "-s");
e145d993 4078 if (!strategy)
c972bf4c 4079 strvec_push(&cmd.args, "octopus");
e145d993 4080 else {
c972bf4c 4081 strvec_push(&cmd.args, strategy);
e145d993 4082 for (k = 0; k < opts->xopts_nr; k++)
c972bf4c 4083 strvec_pushf(&cmd.args,
f6d8942b 4084 "-X%s", opts->xopts[k]);
e145d993 4085 }
f2563c9e
PW
4086 if (!(flags & TODO_EDIT_MERGE_MSG))
4087 strvec_push(&cmd.args, "--no-edit");
4088 else
4089 strvec_push(&cmd.args, "--edit");
c972bf4c
JK
4090 strvec_push(&cmd.args, "--no-ff");
4091 strvec_push(&cmd.args, "--no-log");
4092 strvec_push(&cmd.args, "--no-stat");
4093 strvec_push(&cmd.args, "-F");
4094 strvec_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4 4095 if (opts->gpg_sign)
ae03c97a 4096 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
19dad040
4097 else
4098 strvec_push(&cmd.args, "--no-gpg-sign");
2b6ad0f4
JS
4099
4100 /* Add the tips to be merged */
4101 for (j = to_merge; j; j = j->next)
c972bf4c 4102 strvec_push(&cmd.args,
f6d8942b 4103 oid_to_hex(&j->item->object.oid));
2b6ad0f4
JS
4104
4105 strbuf_release(&ref_name);
c8e4159e
HWN
4106 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4107 NULL, 0);
2b6ad0f4
JS
4108 rollback_lock_file(&lock);
4109
2b6ad0f4
JS
4110 ret = run_command(&cmd);
4111
4112 /* force re-reading of the cache */
9c5f3ee3
ÆAB
4113 if (!ret) {
4114 discard_index(r->index);
4115 if (repo_read_index(r) < 0)
4116 ret = error(_("could not read index"));
4117 }
2b6ad0f4
JS
4118 goto leave_merge;
4119 }
4120
4121 merge_commit = to_merge->item;
cb338c23
ÆAB
4122 bases = repo_get_merge_bases(the_repository, head_commit,
4123 merge_commit);
4a7e27e9
JK
4124 if (bases && oideq(&merge_commit->object.oid,
4125 &bases->item->object.oid)) {
7ccdf65b
JS
4126 ret = 0;
4127 /* skip merging an ancestor of HEAD */
4128 goto leave_merge;
4129 }
4130
4439c7a3 4131 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
4132 git_path_merge_head(r), 0);
4133 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 4134
5327d898 4135 bases = reverse_commit_list(bases);
4c68e7dd 4136
e1ff0a32 4137 repo_read_index(r);
0d6caa2d 4138 init_merge_options(&o, r);
4c68e7dd
JS
4139 o.branch1 = "HEAD";
4140 o.branch2 = ref_name.buf;
4141 o.buffer_output = 2;
4142
6a5fb966 4143 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
14c4586c
EN
4144 /*
4145 * TODO: Should use merge_incore_recursive() and
4146 * merge_switch_to_result(), skipping the call to
4147 * merge_switch_to_result() when we don't actually need to
4148 * update the index and working copy immediately.
4149 */
4150 ret = merge_ort_recursive(&o,
5327d898 4151 head_commit, merge_commit, bases,
14c4586c
EN
4152 &i);
4153 } else {
5327d898 4154 ret = merge_recursive(&o, head_commit, merge_commit, bases,
14c4586c
EN
4155 &i);
4156 }
4c68e7dd
JS
4157 if (ret <= 0)
4158 fputs(o.obuf.buf, stdout);
4159 strbuf_release(&o.obuf);
4160 if (ret < 0) {
4161 error(_("could not even attempt to merge '%.*s'"),
4162 merge_arg_len, arg);
4163 goto leave_merge;
4164 }
4165 /*
4166 * The return value of merge_recursive() is 1 on clean, and 0 on
4167 * unclean merge.
4168 *
4169 * Let's reverse that, so that do_merge() returns 0 upon success and
4170 * 1 upon failed merge (keeping the return value -1 for the cases where
4171 * we will want to reschedule the `merge` command).
4172 */
4173 ret = !ret;
4174
f11c9580
NTND
4175 if (r->index->cache_changed &&
4176 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
4177 ret = error(_("merge: Unable to write new index file"));
4178 goto leave_merge;
4179 }
4180
4181 rollback_lock_file(&lock);
4182 if (ret)
f11c9580 4183 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
4184 else
4185 /*
4186 * In case of problems, we now want to return a positive
4187 * value (a negative one would indicate that the `merge`
4188 * command needs to be rescheduled).
4189 */
20f4b044 4190 ret = !!run_git_commit(git_path_merge_msg(r), opts,
f11c9580 4191 run_commit_flags);
4c68e7dd 4192
2be6b6f4
PW
4193 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4194 fast_forward_edit:
4195 *check_todo = 1;
4196 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4197 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4198 }
4199
4200
4c68e7dd
JS
4201leave_merge:
4202 strbuf_release(&ref_name);
4203 rollback_lock_file(&lock);
2b6ad0f4 4204 free_commit_list(to_merge);
4c68e7dd
JS
4205 return ret;
4206}
4207
89fc0b53
DS
4208static int write_update_refs_state(struct string_list *refs_to_oids)
4209{
4210 int result = 0;
4211 struct lock_file lock = LOCK_INIT;
4212 FILE *fp = NULL;
4213 struct string_list_item *item;
4214 char *path;
4215
89fc0b53
DS
4216 path = rebase_path_update_refs(the_repository->gitdir);
4217
44da9e08
VD
4218 if (!refs_to_oids->nr) {
4219 if (unlink(path) && errno != ENOENT)
4220 result = error_errno(_("could not unlink: %s"), path);
4221 goto cleanup;
4222 }
4223
89fc0b53
DS
4224 if (safe_create_leading_directories(path)) {
4225 result = error(_("unable to create leading directories of %s"),
4226 path);
4227 goto cleanup;
4228 }
4229
4230 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4231 result = error(_("another 'rebase' process appears to be running; "
4232 "'%s.lock' already exists"),
4233 path);
4234 goto cleanup;
4235 }
4236
4237 fp = fdopen_lock_file(&lock, "w");
4238 if (!fp) {
4239 result = error_errno(_("could not open '%s' for writing"), path);
4240 rollback_lock_file(&lock);
4241 goto cleanup;
4242 }
4243
4244 for_each_string_list_item(item, refs_to_oids) {
4245 struct update_ref_record *rec = item->util;
4246 fprintf(fp, "%s\n%s\n%s\n", item->string,
4247 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4248 }
4249
4250 result = commit_lock_file(&lock);
4251
4252cleanup:
4253 free(path);
4254 return result;
4255}
4256
b3b1a21d
DS
4257/*
4258 * Parse the update-refs file for the current rebase, then remove the
4259 * refs that do not appear in the todo_list (and have not had updated
4260 * values stored) and add refs that are in the todo_list but not
4261 * represented in the update-refs file.
4262 *
4263 * If there are changes to the update-refs list, then write the new state
4264 * to disk.
4265 */
4266void todo_list_filter_update_refs(struct repository *r,
4267 struct todo_list *todo_list)
4268{
4269 int i;
4270 int updated = 0;
4271 struct string_list update_refs = STRING_LIST_INIT_DUP;
4272
4273 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4274
4275 /*
4276 * For each item in the update_refs list, if it has no updated
4277 * value and does not appear in the todo_list, then remove it
4278 * from the update_refs list.
4279 */
4280 for (i = 0; i < update_refs.nr; i++) {
4281 int j;
4282 int found = 0;
4283 const char *ref = update_refs.items[i].string;
4284 size_t reflen = strlen(ref);
4285 struct update_ref_record *rec = update_refs.items[i].util;
4286
4287 /* OID already stored as updated. */
4288 if (!is_null_oid(&rec->after))
4289 continue;
4290
4291 for (j = 0; !found && j < todo_list->total_nr; j++) {
4292 struct todo_item *item = &todo_list->items[j];
4293 const char *arg = todo_list->buf.buf + item->arg_offset;
4294
4295 if (item->command != TODO_UPDATE_REF)
4296 continue;
4297
4298 if (item->arg_len != reflen ||
4299 strncmp(arg, ref, reflen))
4300 continue;
4301
4302 found = 1;
4303 }
4304
4305 if (!found) {
4306 free(update_refs.items[i].string);
4307 free(update_refs.items[i].util);
4308
4309 update_refs.nr--;
4310 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4311
4312 updated = 1;
4313 i--;
4314 }
4315 }
4316
4317 /*
4318 * For each todo_item, check if its ref is in the update_refs list.
4319 * If not, then add it as an un-updated ref.
4320 */
4321 for (i = 0; i < todo_list->total_nr; i++) {
4322 struct todo_item *item = &todo_list->items[i];
4323 const char *arg = todo_list->buf.buf + item->arg_offset;
4324 int j, found = 0;
4325
4326 if (item->command != TODO_UPDATE_REF)
4327 continue;
4328
4329 for (j = 0; !found && j < update_refs.nr; j++) {
4330 const char *ref = update_refs.items[j].string;
4331
4332 found = strlen(ref) == item->arg_len &&
4333 !strncmp(ref, arg, item->arg_len);
4334 }
4335
4336 if (!found) {
4337 struct string_list_item *inserted;
4338 struct strbuf argref = STRBUF_INIT;
4339
4340 strbuf_add(&argref, arg, item->arg_len);
4341 inserted = string_list_insert(&update_refs, argref.buf);
4342 inserted->util = init_update_ref_record(argref.buf);
4343 strbuf_release(&argref);
4344 updated = 1;
4345 }
4346 }
4347
4348 if (updated)
4349 write_update_refs_state(&update_refs);
4350 string_list_clear(&update_refs, 1);
4351}
4352
89fc0b53 4353static int do_update_ref(struct repository *r, const char *refname)
a97d7916 4354{
89fc0b53
DS
4355 struct string_list_item *item;
4356 struct string_list list = STRING_LIST_INIT_DUP;
4357
4358 if (sequencer_get_update_refs_state(r->gitdir, &list))
4359 return -1;
4360
4361 for_each_string_list_item(item, &list) {
4362 if (!strcmp(item->string, refname)) {
4363 struct update_ref_record *rec = item->util;
4364 if (read_ref("HEAD", &rec->after))
4365 return -1;
4366 break;
4367 }
4368 }
4369
4370 write_update_refs_state(&list);
4371 string_list_clear(&list, 1);
a97d7916
DS
4372 return 0;
4373}
4374
4611884e 4375static int do_update_refs(struct repository *r, int quiet)
89fc0b53
DS
4376{
4377 int res = 0;
4378 struct string_list_item *item;
4379 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4380 struct ref_store *refs = get_main_ref_store(r);
4611884e
DS
4381 struct strbuf update_msg = STRBUF_INIT;
4382 struct strbuf error_msg = STRBUF_INIT;
89fc0b53
DS
4383
4384 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4385 return res;
4386
4387 for_each_string_list_item(item, &refs_to_oids) {
4388 struct update_ref_record *rec = item->util;
4611884e 4389 int loop_res;
89fc0b53 4390
4611884e
DS
4391 loop_res = refs_update_ref(refs, "rewritten during rebase",
4392 item->string,
4393 &rec->after, &rec->before,
4394 0, UPDATE_REFS_MSG_ON_ERR);
4395 res |= loop_res;
4396
4397 if (quiet)
4398 continue;
4399
4400 if (loop_res)
4401 strbuf_addf(&error_msg, "\t%s\n", item->string);
4402 else
4403 strbuf_addf(&update_msg, "\t%s\n", item->string);
4404 }
4405
4406 if (!quiet &&
4407 (update_msg.len || error_msg.len)) {
4408 fprintf(stderr,
4409 _("Updated the following refs with %s:\n%s"),
4410 "--update-refs",
4411 update_msg.buf);
4412
4413 if (res)
4414 fprintf(stderr,
4415 _("Failed to update the following refs with %s:\n%s"),
4416 "--update-refs",
4417 error_msg.buf);
89fc0b53
DS
4418 }
4419
4420 string_list_clear(&refs_to_oids, 1);
4611884e
DS
4421 strbuf_release(&update_msg);
4422 strbuf_release(&error_msg);
89fc0b53
DS
4423 return res;
4424}
4425
6e98de72
JS
4426static int is_final_fixup(struct todo_list *todo_list)
4427{
4428 int i = todo_list->current;
4429
4430 if (!is_fixup(todo_list->items[i].command))
4431 return 0;
4432
4433 while (++i < todo_list->nr)
4434 if (is_fixup(todo_list->items[i].command))
4435 return 0;
4436 else if (!is_noop(todo_list->items[i].command))
4437 break;
4438 return 1;
4439}
4440
25cb8df9
JS
4441static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4442{
4443 int i;
4444
4445 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4446 if (!is_noop(todo_list->items[i].command))
4447 return todo_list->items[i].command;
4448
4449 return -1;
4450}
4451
b7de153b 4452void create_autostash(struct repository *r, const char *path)
0816f1df
DL
4453{
4454 struct strbuf buf = STRBUF_INIT;
4455 struct lock_file lock_file = LOCK_INIT;
4456 int fd;
4457
4458 fd = repo_hold_locked_index(r, &lock_file, 0);
4459 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4460 if (0 <= fd)
4461 repo_update_index_if_able(r, &lock_file);
4462 rollback_lock_file(&lock_file);
4463
4464 if (has_unstaged_changes(r, 1) ||
4465 has_uncommitted_changes(r, 1)) {
4466 struct child_process stash = CHILD_PROCESS_INIT;
6ae80861 4467 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
0816f1df
DL
4468 struct object_id oid;
4469
c972bf4c 4470 strvec_pushl(&stash.args,
f6d8942b 4471 "stash", "create", "autostash", NULL);
0816f1df
DL
4472 stash.git_cmd = 1;
4473 stash.no_stdin = 1;
4474 strbuf_reset(&buf);
4475 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4476 die(_("Cannot autostash"));
4477 strbuf_trim_trailing_newline(&buf);
d850b7a5 4478 if (repo_get_oid(the_repository, buf.buf, &oid))
0816f1df
DL
4479 die(_("Unexpected stash response: '%s'"),
4480 buf.buf);
4481 strbuf_reset(&buf);
4482 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4483
4484 if (safe_create_leading_directories_const(path))
4485 die(_("Could not create directory for '%s'"),
4486 path);
4487 write_file(path, "%s", oid_to_hex(&oid));
4488 printf(_("Created autostash: %s\n"), buf.buf);
6ae80861 4489 if (reset_head(r, &ropts) < 0)
0816f1df 4490 die(_("could not reset --hard"));
9c5f3ee3
ÆAB
4491 discard_index(r->index);
4492 if (repo_read_index(r) < 0)
0816f1df
DL
4493 die(_("could not read index"));
4494 }
4495 strbuf_release(&buf);
4496}
4497
804fe315 4498static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
796c7972 4499{
796c7972
JS
4500 struct child_process child = CHILD_PROCESS_INIT;
4501 int ret = 0;
4502
12b6e136
DL
4503 if (attempt_apply) {
4504 child.git_cmd = 1;
4505 child.no_stdout = 1;
4506 child.no_stderr = 1;
c972bf4c
JK
4507 strvec_push(&child.args, "stash");
4508 strvec_push(&child.args, "apply");
4509 strvec_push(&child.args, stash_oid);
12b6e136 4510 ret = run_command(&child);
796c7972 4511 }
796c7972 4512
12b6e136 4513 if (attempt_apply && !ret)
cdb866b3 4514 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
4515 else {
4516 struct child_process store = CHILD_PROCESS_INIT;
4517
4518 store.git_cmd = 1;
c972bf4c
JK
4519 strvec_push(&store.args, "stash");
4520 strvec_push(&store.args, "store");
4521 strvec_push(&store.args, "-m");
4522 strvec_push(&store.args, "autostash");
4523 strvec_push(&store.args, "-q");
4524 strvec_push(&store.args, stash_oid);
796c7972 4525 if (run_command(&store))
804fe315 4526 ret = error(_("cannot store %s"), stash_oid);
796c7972 4527 else
cdb866b3 4528 fprintf(stderr,
12b6e136 4529 _("%s\n"
cdb866b3
JS
4530 "Your changes are safe in the stash.\n"
4531 "You can run \"git stash pop\" or"
12b6e136
DL
4532 " \"git stash drop\" at any time.\n"),
4533 attempt_apply ?
4534 _("Applying autostash resulted in conflicts.") :
4535 _("Autostash exists; creating a new stash entry."));
796c7972
JS
4536 }
4537
796c7972
JS
4538 return ret;
4539}
4540
804fe315
DL
4541static int apply_save_autostash(const char *path, int attempt_apply)
4542{
4543 struct strbuf stash_oid = STRBUF_INIT;
4544 int ret = 0;
4545
4546 if (!read_oneliner(&stash_oid, path,
4547 READ_ONELINER_SKIP_IF_EMPTY)) {
4548 strbuf_release(&stash_oid);
4549 return 0;
4550 }
4551 strbuf_trim(&stash_oid);
4552
4553 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4554
0dd562e0 4555 unlink(path);
facca7f0 4556 strbuf_release(&stash_oid);
796c7972
JS
4557 return ret;
4558}
4559
12b6e136
DL
4560int save_autostash(const char *path)
4561{
4562 return apply_save_autostash(path, 0);
4563}
4564
4565int apply_autostash(const char *path)
4566{
4567 return apply_save_autostash(path, 1);
4568}
4569
804fe315
DL
4570int apply_autostash_oid(const char *stash_oid)
4571{
4572 return apply_save_autostash_oid(stash_oid, 1);
4573}
4574
fc4a6735 4575static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 4576 const char *onto_name, const struct object_id *onto,
f3e27a02 4577 const struct object_id *orig_head)
4df66c40 4578{
38c541ce
PW
4579 struct reset_head_opts ropts = {
4580 .oid = onto,
4581 .orig_head = orig_head,
4582 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4583 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4584 .head_msg = reflog_message(opts, "start", "checkout %s",
4585 onto_name),
d188a60d 4586 .default_reflog_action = sequencer_reflog_action(opts)
38c541ce
PW
4587 };
4588 if (reset_head(r, &ropts)) {
be1bb600 4589 apply_autostash(rebase_path_autostash());
4df66c40
AG
4590 sequencer_remove_state(opts);
4591 return error(_("could not detach HEAD"));
4592 }
4593
38c541ce 4594 return 0;
4df66c40
AG
4595}
4596
005af339 4597static int stopped_at_head(struct repository *r)
71f82465
JS
4598{
4599 struct object_id head;
4600 struct commit *commit;
4601 struct commit_message message;
4602
d850b7a5 4603 if (repo_get_oid(the_repository, "HEAD", &head) ||
005af339 4604 !(commit = lookup_commit(r, &head)) ||
ecb5091f 4605 repo_parse_commit(the_repository, commit) || get_message(commit, &message))
71f82465
JS
4606 fprintf(stderr, _("Stopped at HEAD\n"));
4607 else {
4608 fprintf(stderr, _("Stopped at %s\n"), message.label);
4609 free_message(commit, &message);
4610 }
4611 return 0;
4612
4613}
4614
dfa8bae5
PW
4615static int reread_todo_if_changed(struct repository *r,
4616 struct todo_list *todo_list,
4617 struct replay_opts *opts)
4618{
2b88fe06
PW
4619 int offset;
4620 struct strbuf buf = STRBUF_INIT;
dfa8bae5 4621
2b88fe06
PW
4622 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4623 return -1;
4624 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4625 if (buf.len != todo_list->buf.len - offset ||
4626 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
dfa8bae5
PW
4627 /* Reread the todo file if it has changed. */
4628 todo_list_release(todo_list);
4629 if (read_populate_todo(r, todo_list, opts))
4630 return -1; /* message was printed */
4631 /* `current` will be incremented on return */
4632 todo_list->current = -1;
4633 }
2b88fe06 4634 strbuf_release(&buf);
dfa8bae5
PW
4635
4636 return 0;
4637}
4638
cb5206ea
JS
4639static const char rescheduled_advice[] =
4640N_("Could not execute the todo command\n"
4641"\n"
4642" %.*s"
4643"\n"
4644"It has been rescheduled; To edit the command before continuing, please\n"
4645"edit the todo list first:\n"
4646"\n"
4647" git rebase --edit-todo\n"
4648" git rebase --continue\n");
4649
f11c9580
NTND
4650static int pick_commits(struct repository *r,
4651 struct todo_list *todo_list,
4652 struct replay_opts *opts)
043a4492 4653{
9055e401 4654 int res = 0, reschedule = 0;
043a4492 4655
d188a60d 4656 opts->reflog_message = sequencer_reflog_action(opts);
043a4492
RR
4657 if (opts->allow_ff)
4658 assert(!(opts->signoff || opts->no_commit ||
39edfd5c 4659 opts->record_origin || should_edit(opts) ||
a3894aad
PW
4660 opts->committer_date_is_author_date ||
4661 opts->ignore_date));
f11c9580 4662 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4663 return -1;
043a4492 4664
004fefa7
JS
4665 while (todo_list->current < todo_list->nr) {
4666 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 4667 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 4668 int check_todo = 0;
6ad656db 4669
004fefa7 4670 if (save_todo(todo_list, opts))
221675de 4671 return -1;
6e98de72 4672 if (is_rebase_i(opts)) {
ef80069a
JS
4673 if (item->command != TODO_COMMENT) {
4674 FILE *f = fopen(rebase_path_msgnum(), "w");
4675
4676 todo_list->done_nr++;
4677
4678 if (f) {
4679 fprintf(f, "%d\n", todo_list->done_nr);
4680 fclose(f);
4681 }
899b49c4 4682 if (!opts->quiet)
4d55d63b 4683 fprintf(stderr, _("Rebasing (%d/%d)%s"),
899b49c4
EN
4684 todo_list->done_nr,
4685 todo_list->total_nr,
4686 opts->verbose ? "\n" : "\r");
ef80069a 4687 }
6e98de72
JS
4688 unlink(rebase_path_message());
4689 unlink(rebase_path_author_script());
4690 unlink(rebase_path_stopped_sha());
4691 unlink(rebase_path_amend());
34e7771b 4692 unlink(git_path_merge_head(r));
5291828d 4693 unlink(git_path_auto_merge(r));
fbd7a232 4694 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
71f82465 4695
d7d90885
SG
4696 if (item->command == TODO_BREAK) {
4697 if (!opts->verbose)
4698 term_clear_line();
005af339 4699 return stopped_at_head(r);
d7d90885 4700 }
6e98de72
JS
4701 }
4702 if (item->command <= TODO_SQUASH) {
8ab37ef2 4703 if (is_rebase_i(opts))
d188a60d
PW
4704 opts->reflog_message = reflog_message(opts,
4705 command_to_string(item->command), NULL);
4706
ae70e34f
CM
4707 res = do_pick_commit(r, item, opts,
4708 is_final_fixup(todo_list),
a47ba3c7 4709 &check_todo);
9d7bf3cf
JS
4710 if (is_rebase_i(opts) && res < 0) {
4711 /* Reschedule */
cb5206ea
JS
4712 advise(_(rescheduled_advice),
4713 get_item_line_length(todo_list,
4714 todo_list->current),
4715 get_item_line(todo_list,
4716 todo_list->current));
9d7bf3cf
JS
4717 todo_list->current--;
4718 if (save_todo(todo_list, opts))
4719 return -1;
4720 }
56dc3ab0
JS
4721 if (item->command == TODO_EDIT) {
4722 struct commit *commit = item->commit;
d7d90885
SG
4723 if (!res) {
4724 if (!opts->verbose)
4725 term_clear_line();
99429213 4726 fprintf(stderr,
a42e1b41 4727 _("Stopped at %s... %.*s\n"),
56dc3ab0 4728 short_commit_name(commit),
6ad656db 4729 item->arg_len, arg);
d7d90885 4730 }
f11c9580 4731 return error_with_patch(r, commit,
6ad656db 4732 arg, item->arg_len, opts, res, !res);
56dc3ab0 4733 }
25cb8df9
JS
4734 if (is_rebase_i(opts) && !res)
4735 record_in_rewritten(&item->commit->object.oid,
4736 peek_command(todo_list, 1));
6e98de72
JS
4737 if (res && is_fixup(item->command)) {
4738 if (res == 1)
4739 intend_to_amend();
f11c9580 4740 return error_failed_squash(r, item->commit, opts,
6ad656db 4741 item->arg_len, arg);
a9279c67
PW
4742 } else if (res && is_rebase_i(opts) && item->commit) {
4743 int to_amend = 0;
4744 struct object_id oid;
4745
4746 /*
4747 * If we are rewording and have either
4748 * fast-forwarded already, or are about to
4749 * create a new root commit, we want to amend,
4750 * otherwise we do not.
4751 */
4752 if (item->command == TODO_REWORD &&
d850b7a5 4753 !repo_get_oid(the_repository, "HEAD", &oid) &&
4a7e27e9 4754 (oideq(&item->commit->object.oid, &oid) ||
a9279c67 4755 (opts->have_squash_onto &&
4a7e27e9 4756 oideq(&opts->squash_onto, &oid))))
a9279c67
PW
4757 to_amend = 1;
4758
f11c9580 4759 return res | error_with_patch(r, item->commit,
6ad656db 4760 arg, item->arg_len, opts,
a9279c67
PW
4761 res, to_amend);
4762 }
311af526 4763 } else if (item->command == TODO_EXEC) {
6ad656db 4764 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
4765 int saved = *end_of_arg;
4766
d7d90885
SG
4767 if (!opts->verbose)
4768 term_clear_line();
311af526 4769 *end_of_arg = '\0';
6ad656db 4770 res = do_exec(r, arg);
311af526 4771 *end_of_arg = saved;
54fd3243 4772
d421afa0
JS
4773 if (res) {
4774 if (opts->reschedule_failed_exec)
4775 reschedule = 1;
54fd3243 4776 }
a47ba3c7 4777 check_todo = 1;
9055e401 4778 } else if (item->command == TODO_LABEL) {
6ad656db 4779 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
4780 reschedule = 1;
4781 } else if (item->command == TODO_RESET) {
6ad656db 4782 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 4783 reschedule = 1;
4c68e7dd 4784 } else if (item->command == TODO_MERGE) {
2be6b6f4
PW
4785 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4786 item->flags, &check_todo, opts)) < 0)
4c68e7dd 4787 reschedule = 1;
537e7d61
JS
4788 else if (item->commit)
4789 record_in_rewritten(&item->commit->object.oid,
4790 peek_command(todo_list, 1));
4791 if (res > 0)
4c68e7dd 4792 /* failed with merge conflicts */
f11c9580 4793 return error_with_patch(r, item->commit,
6ad656db
AG
4794 arg, item->arg_len,
4795 opts, res, 0);
a97d7916
DS
4796 } else if (item->command == TODO_UPDATE_REF) {
4797 struct strbuf ref = STRBUF_INIT;
4798 strbuf_add(&ref, arg, item->arg_len);
4799 if ((res = do_update_ref(r, ref.buf)))
4800 reschedule = 1;
4801 strbuf_release(&ref);
56dc3ab0 4802 } else if (!is_noop(item->command))
25c43667
JS
4803 return error(_("unknown command %d"), item->command);
4804
9055e401
JS
4805 if (reschedule) {
4806 advise(_(rescheduled_advice),
4807 get_item_line_length(todo_list,
4808 todo_list->current),
4809 get_item_line(todo_list, todo_list->current));
4810 todo_list->current--;
4811 if (save_todo(todo_list, opts))
4812 return -1;
4c68e7dd 4813 if (item->commit)
f11c9580
NTND
4814 return error_with_patch(r,
4815 item->commit,
6ad656db
AG
4816 arg, item->arg_len,
4817 opts, res, 0);
dfa8bae5
PW
4818 } else if (is_rebase_i(opts) && check_todo && !res &&
4819 reread_todo_if_changed(r, todo_list, opts)) {
4820 return -1;
9055e401
JS
4821 }
4822
004fefa7 4823 todo_list->current++;
043a4492
RR
4824 if (res)
4825 return res;
4826 }
4827
56dc3ab0 4828 if (is_rebase_i(opts)) {
4b83ce9f 4829 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 4830 struct stat st;
556907f1 4831
56dc3ab0
JS
4832 /* Stopped in the middle, as planned? */
4833 if (todo_list->current < todo_list->nr)
4834 return 0;
556907f1 4835
4b83ce9f
JS
4836 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4837 starts_with(head_ref.buf, "refs/")) {
96e832a5 4838 const char *msg;
092bbcdf 4839 struct object_id head, orig;
4b83ce9f
JS
4840 int res;
4841
d850b7a5 4842 if (repo_get_oid(the_repository, "HEAD", &head)) {
4b83ce9f
JS
4843 res = error(_("cannot read HEAD"));
4844cleanup_head_ref:
4845 strbuf_release(&head_ref);
4846 strbuf_release(&buf);
4847 return res;
4848 }
4849 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 4850 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
4851 res = error(_("could not read orig-head"));
4852 goto cleanup_head_ref;
4853 }
4ab867b8 4854 strbuf_reset(&buf);
4b83ce9f
JS
4855 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4856 res = error(_("could not read 'onto'"));
4857 goto cleanup_head_ref;
4858 }
96e832a5
JS
4859 msg = reflog_message(opts, "finish", "%s onto %s",
4860 head_ref.buf, buf.buf);
ae077771 4861 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 4862 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
4863 res = error(_("could not update %s"),
4864 head_ref.buf);
4865 goto cleanup_head_ref;
4866 }
96e832a5 4867 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 4868 head_ref.buf);
96e832a5 4869 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
4870 res = error(_("could not update HEAD to %s"),
4871 head_ref.buf);
4872 goto cleanup_head_ref;
4873 }
4874 strbuf_reset(&buf);
4875 }
4876
556907f1
JS
4877 if (opts->verbose) {
4878 struct rev_info log_tree_opt;
4879 struct object_id orig, head;
4880
4881 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 4882 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
4883 log_tree_opt.diff = 1;
4884 log_tree_opt.diffopt.output_format =
4885 DIFF_FORMAT_DIFFSTAT;
4886 log_tree_opt.disable_stdin = 1;
4887
4888 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
d850b7a5
ÆAB
4889 !repo_get_oid(the_repository, buf.buf, &orig) &&
4890 !repo_get_oid(the_repository, "HEAD", &head)) {
66f414f8
BW
4891 diff_tree_oid(&orig, &head, "",
4892 &log_tree_opt.diffopt);
556907f1
JS
4893 log_tree_diff_flush(&log_tree_opt);
4894 }
2108fe4a 4895 release_revisions(&log_tree_opt);
556907f1 4896 }
25cb8df9
JS
4897 flush_rewritten_pending();
4898 if (!stat(rebase_path_rewritten_list(), &st) &&
4899 st.st_size > 0) {
4900 struct child_process child = CHILD_PROCESS_INIT;
96af564d 4901 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
25cb8df9
JS
4902
4903 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4904 child.git_cmd = 1;
c972bf4c
JK
4905 strvec_push(&child.args, "notes");
4906 strvec_push(&child.args, "copy");
4907 strvec_push(&child.args, "--for-rewrite=rebase");
25cb8df9
JS
4908 /* we don't care if this copying failed */
4909 run_command(&child);
79516045 4910
96af564d
ES
4911 hook_opt.path_to_stdin = rebase_path_rewritten_list();
4912 strvec_push(&hook_opt.args, "rebase");
4913 run_hooks_opt("post-rewrite", &hook_opt);
25cb8df9 4914 }
be1bb600 4915 apply_autostash(rebase_path_autostash());
25cb8df9 4916
d7d90885
SG
4917 if (!opts->quiet) {
4918 if (!opts->verbose)
4919 term_clear_line();
899b49c4 4920 fprintf(stderr,
4d55d63b 4921 _("Successfully rebased and updated %s.\n"),
899b49c4 4922 head_ref.buf);
d7d90885 4923 }
5da4966f 4924
556907f1 4925 strbuf_release(&buf);
4b83ce9f 4926 strbuf_release(&head_ref);
89fc0b53 4927
4611884e 4928 if (do_update_refs(r, opts->quiet))
89fc0b53 4929 return -1;
56dc3ab0
JS
4930 }
4931
043a4492
RR
4932 /*
4933 * Sequence of picks finished successfully; cleanup by
4934 * removing the .git/sequencer directory
4935 */
2863584f 4936 return sequencer_remove_state(opts);
043a4492
RR
4937}
4938
39edfd5c 4939static int continue_single_pick(struct repository *r, struct replay_opts *opts)
043a4492 4940{
0e906739 4941 struct child_process cmd = CHILD_PROCESS_INIT;
043a4492 4942
c8e4159e 4943 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 4944 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 4945 return error(_("no cherry-pick or revert in progress"));
39edfd5c 4946
0e906739
RS
4947 cmd.git_cmd = 1;
4948 strvec_push(&cmd.args, "commit");
39edfd5c
EN
4949
4950 /*
4951 * continue_single_pick() handles the case of recovering from a
4952 * conflict. should_edit() doesn't handle that case; for a conflict,
4953 * we want to edit if the user asked for it, or if they didn't specify
4954 * and stdin is a tty.
4955 */
4956 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
4957 /*
4958 * Include --cleanup=strip as well because we don't want the
4959 * "# Conflicts:" messages.
4960 */
0e906739 4961 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
39edfd5c 4962
0e906739 4963 return run_command(&cmd);
043a4492
RR
4964}
4965
f11c9580
NTND
4966static int commit_staged_changes(struct repository *r,
4967 struct replay_opts *opts,
15ef6931 4968 struct todo_list *todo_list)
9d93ccd1 4969{
789b3eff 4970 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 4971 unsigned int final_fixup = 0, is_clean;
9d93ccd1 4972
f11c9580 4973 if (has_unstaged_changes(r, 1))
9d93ccd1 4974 return error(_("cannot rebase: You have unstaged changes."));
52632209 4975
f11c9580 4976 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1
JS
4977
4978 if (file_exists(rebase_path_amend())) {
4979 struct strbuf rev = STRBUF_INIT;
092bbcdf 4980 struct object_id head, to_amend;
9d93ccd1 4981
d850b7a5 4982 if (repo_get_oid(the_repository, "HEAD", &head))
9d93ccd1
JS
4983 return error(_("cannot amend non-existing commit"));
4984 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4985 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 4986 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
4987 return error(_("invalid contents: '%s'"),
4988 rebase_path_amend());
9001dc2a 4989 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
4990 return error(_("\nYou have uncommitted changes in your "
4991 "working tree. Please, commit them\n"
4992 "first and then run 'git rebase "
4993 "--continue' again."));
15ef6931
JS
4994 /*
4995 * When skipping a failed fixup/squash, we need to edit the
4996 * commit message, the current fixup list and count, and if it
4997 * was the last fixup/squash in the chain, we need to clean up
4998 * the commit message and if there was a squash, let the user
4999 * edit it.
5000 */
10d2f354
JS
5001 if (!is_clean || !opts->current_fixup_count)
5002 ; /* this is not the final fixup */
87ae8a1a 5003 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
5004 !file_exists(rebase_path_stopped_sha())) {
5005 /* was a final fixup or squash done manually? */
5006 if (!is_fixup(peek_command(todo_list, 0))) {
5007 unlink(rebase_path_fixup_msg());
5008 unlink(rebase_path_squash_msg());
5009 unlink(rebase_path_current_fixups());
5010 strbuf_reset(&opts->current_fixups);
5011 opts->current_fixup_count = 0;
5012 }
5013 } else {
5014 /* we are in a fixup/squash chain */
15ef6931
JS
5015 const char *p = opts->current_fixups.buf;
5016 int len = opts->current_fixups.len;
5017
5018 opts->current_fixup_count--;
5019 if (!len)
5020 BUG("Incorrect current_fixups:\n%s", p);
5021 while (len && p[len - 1] != '\n')
5022 len--;
5023 strbuf_setlen(&opts->current_fixups, len);
5024 if (write_message(p, len, rebase_path_current_fixups(),
5025 0) < 0)
5026 return error(_("could not write file: '%s'"),
5027 rebase_path_current_fixups());
5028
5029 /*
5030 * If a fixup/squash in a fixup/squash chain failed, the
5031 * commit message is already correct, no need to commit
5032 * it again.
5033 *
5034 * Only if it is the final command in the fixup/squash
5035 * chain, and only if the chain is longer than a single
5036 * fixup/squash command (which was just skipped), do we
5037 * actually need to re-commit with a cleaned up commit
5038 * message.
5039 */
5040 if (opts->current_fixup_count > 0 &&
5041 !is_fixup(peek_command(todo_list, 0))) {
5042 final_fixup = 1;
5043 /*
5044 * If there was not a single "squash" in the
5045 * chain, we only need to clean up the commit
5046 * message, no need to bother the user with
5047 * opening the commit message in the editor.
5048 */
5049 if (!starts_with(p, "squash ") &&
5050 !strstr(p, "\nsquash "))
5051 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5052 } else if (is_fixup(peek_command(todo_list, 0))) {
5053 /*
5054 * We need to update the squash message to skip
5055 * the latest commit message.
5056 */
5057 struct commit *commit;
5058 const char *path = rebase_path_squash_msg();
b3757442 5059 const char *encoding = get_commit_output_encoding();
15ef6931 5060
005af339 5061 if (parse_head(r, &commit) ||
ecb5091f 5062 !(p = repo_logmsg_reencode(the_repository, commit, NULL, encoding)) ||
15ef6931 5063 write_message(p, strlen(p), path, 0)) {
ecb5091f
ÆAB
5064 repo_unuse_commit_buffer(the_repository,
5065 commit, p);
15ef6931
JS
5066 return error(_("could not write file: "
5067 "'%s'"), path);
5068 }
ecb5091f
ÆAB
5069 repo_unuse_commit_buffer(the_repository,
5070 commit, p);
15ef6931
JS
5071 }
5072 }
9d93ccd1
JS
5073
5074 strbuf_release(&rev);
789b3eff 5075 flags |= AMEND_MSG;
9d93ccd1
JS
5076 }
5077
15ef6931 5078 if (is_clean) {
c8e4159e
HWN
5079 if (refs_ref_exists(get_main_ref_store(r),
5080 "CHERRY_PICK_HEAD") &&
5081 refs_delete_ref(get_main_ref_store(r), "",
5082 "CHERRY_PICK_HEAD", NULL, 0))
15ef6931 5083 return error(_("could not remove CHERRY_PICK_HEAD"));
e5ee33e8
PW
5084 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5085 return error_errno(_("could not remove '%s'"),
5086 git_path_merge_msg(r));
15ef6931
JS
5087 if (!final_fixup)
5088 return 0;
5089 }
5090
20f4b044 5091 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
15ef6931 5092 opts, flags))
9d93ccd1
JS
5093 return error(_("could not commit staged changes."));
5094 unlink(rebase_path_amend());
34e7771b 5095 unlink(git_path_merge_head(r));
5291828d 5096 unlink(git_path_auto_merge(r));
15ef6931
JS
5097 if (final_fixup) {
5098 unlink(rebase_path_fixup_msg());
5099 unlink(rebase_path_squash_msg());
5100 }
5101 if (opts->current_fixup_count > 0) {
5102 /*
5103 * Whether final fixup or not, we just cleaned up the commit
5104 * message...
5105 */
5106 unlink(rebase_path_current_fixups());
5107 strbuf_reset(&opts->current_fixups);
5108 opts->current_fixup_count = 0;
5109 }
9d93ccd1
JS
5110 return 0;
5111}
5112
f11c9580 5113int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 5114{
004fefa7
JS
5115 struct todo_list todo_list = TODO_LIST_INIT;
5116 int res;
043a4492 5117
f11c9580 5118 if (read_and_refresh_cache(r, opts))
2863584f
JS
5119 return -1;
5120
15ef6931
JS
5121 if (read_populate_opts(opts))
5122 return -1;
9d93ccd1 5123 if (is_rebase_i(opts)) {
005af339 5124 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 5125 goto release_todo_list;
5a5445d8
AG
5126
5127 if (file_exists(rebase_path_dropped())) {
5128 if ((res = todo_list_check_against_backup(r, &todo_list)))
5129 goto release_todo_list;
5130
5131 unlink(rebase_path_dropped());
5132 }
5133
d188a60d 5134 opts->reflog_message = reflog_message(opts, "continue", NULL);
f6b9413b
AG
5135 if (commit_staged_changes(r, opts, &todo_list)) {
5136 res = -1;
5137 goto release_todo_list;
5138 }
4258a6da 5139 } else if (!file_exists(get_todo_path(opts)))
39edfd5c 5140 return continue_single_pick(r, opts);
005af339 5141 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 5142 goto release_todo_list;
043a4492 5143
4258a6da
JS
5144 if (!is_rebase_i(opts)) {
5145 /* Verify that the conflict has been resolved */
c8e4159e
HWN
5146 if (refs_ref_exists(get_main_ref_store(r),
5147 "CHERRY_PICK_HEAD") ||
b8825ef2 5148 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
39edfd5c 5149 res = continue_single_pick(r, opts);
4258a6da
JS
5150 if (res)
5151 goto release_todo_list;
5152 }
ffc00a48 5153 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 5154 res = error_dirty_index(r, opts);
004fefa7 5155 goto release_todo_list;
4258a6da
JS
5156 }
5157 todo_list.current++;
ca98c6d4
JS
5158 } else if (file_exists(rebase_path_stopped_sha())) {
5159 struct strbuf buf = STRBUF_INIT;
5160 struct object_id oid;
5161
3442c3d1
DL
5162 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5163 READ_ONELINER_SKIP_IF_EMPTY) &&
0512eabd 5164 !get_oid_hex(buf.buf, &oid))
ca98c6d4
JS
5165 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5166 strbuf_release(&buf);
043a4492 5167 }
4258a6da 5168
f11c9580 5169 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
5170release_todo_list:
5171 todo_list_release(&todo_list);
5172 return res;
043a4492
RR
5173}
5174
f11c9580
NTND
5175static int single_pick(struct repository *r,
5176 struct commit *cmit,
5177 struct replay_opts *opts)
043a4492 5178{
a47ba3c7 5179 int check_todo;
ae70e34f
CM
5180 struct todo_item item;
5181
5182 item.command = opts->action == REPLAY_PICK ?
5183 TODO_PICK : TODO_REVERT;
5184 item.commit = cmit;
a47ba3c7 5185
d188a60d 5186 opts->reflog_message = sequencer_reflog_action(opts);
ae70e34f 5187 return do_pick_commit(r, &item, opts, 0, &check_todo);
043a4492
RR
5188}
5189
f11c9580
NTND
5190int sequencer_pick_revisions(struct repository *r,
5191 struct replay_opts *opts)
043a4492 5192{
004fefa7 5193 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 5194 struct object_id oid;
004fefa7 5195 int i, res;
043a4492 5196
2863584f 5197 assert(opts->revs);
f11c9580 5198 if (read_and_refresh_cache(r, opts))
0d9c6dc9 5199 return -1;
043a4492 5200
21246dbb 5201 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 5202 struct object_id oid;
21246dbb
MV
5203 const char *name = opts->revs->pending.objects[i].name;
5204
5205 /* This happens when using --stdin. */
5206 if (!strlen(name))
5207 continue;
5208
d850b7a5 5209 if (!repo_get_oid(the_repository, name, &oid)) {
f11c9580
NTND
5210 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5211 enum object_type type = oid_object_info(r,
0df8e965 5212 &oid,
abef9020 5213 NULL);
b9b946d4 5214 return error(_("%s: can't cherry-pick a %s"),
debca9d2 5215 name, type_name(type));
7c0b0d8d 5216 }
21246dbb 5217 } else
b9b946d4 5218 return error(_("%s: bad revision"), name);
21246dbb
MV
5219 }
5220
043a4492
RR
5221 /*
5222 * If we were called as "git cherry-pick <commit>", just
5223 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5224 * REVERT_HEAD, and don't touch the sequencer state.
5225 * This means it is possible to cherry-pick in the middle
5226 * of a cherry-pick sequence.
5227 */
5228 if (opts->revs->cmdline.nr == 1 &&
5229 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5230 opts->revs->no_walk &&
5231 !opts->revs->cmdline.rev->flags) {
5232 struct commit *cmit;
5233 if (prepare_revision_walk(opts->revs))
b9b946d4 5234 return error(_("revision walk setup failed"));
043a4492 5235 cmit = get_revision(opts->revs);
c5e358d0
JK
5236 if (!cmit)
5237 return error(_("empty commit set passed"));
5238 if (get_revision(opts->revs))
5239 BUG("unexpected extra commit from walk");
f11c9580 5240 return single_pick(r, cmit, opts);
043a4492
RR
5241 }
5242
5243 /*
5244 * Start a new cherry-pick/ revert sequence; but
5245 * first, make sure that an existing one isn't in
5246 * progress
5247 */
5248
34b0528b 5249 if (walk_revs_populate_todo(&todo_list, opts) ||
6a1f9046 5250 create_seq_dir(r) < 0)
043a4492 5251 return -1;
d850b7a5 5252 if (repo_get_oid(the_repository, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 5253 return error(_("can't revert as initial commit"));
1e43ed98 5254 if (save_head(oid_to_hex(&oid)))
311fd397 5255 return -1;
88d5a271
JS
5256 if (save_opts(opts))
5257 return -1;
1e41229d 5258 update_abort_safety_file();
f11c9580 5259 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
5260 todo_list_release(&todo_list);
5261 return res;
043a4492 5262}
5ed75e2a 5263
66e83d9b 5264void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 5265{
bab4d109 5266 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 5267 struct strbuf sob = STRBUF_INIT;
bab4d109 5268 int has_footer;
5ed75e2a
MV
5269
5270 strbuf_addstr(&sob, sign_off_header);
39ab4d09 5271 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 5272 strbuf_addch(&sob, '\n');
bab4d109 5273
44dc738a
JT
5274 if (!ignore_footer)
5275 strbuf_complete_line(msgbuf);
5276
bab4d109
BC
5277 /*
5278 * If the whole message buffer is equal to the sob, pretend that we
5279 * found a conforming footer with a matching sob
5280 */
5281 if (msgbuf->len - ignore_footer == sob.len &&
5282 !strncmp(msgbuf->buf, sob.buf, sob.len))
5283 has_footer = 3;
5284 else
5285 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5286
33f2f9ab
BC
5287 if (!has_footer) {
5288 const char *append_newlines = NULL;
5289 size_t len = msgbuf->len - ignore_footer;
5290
8c613fd5
BC
5291 if (!len) {
5292 /*
5293 * The buffer is completely empty. Leave foom for
5294 * the title and body to be filled in by the user.
5295 */
33f2f9ab 5296 append_newlines = "\n\n";
8c613fd5
BC
5297 } else if (len == 1) {
5298 /*
5299 * Buffer contains a single newline. Add another
5300 * so that we leave room for the title and body.
5301 */
5302 append_newlines = "\n";
5303 } else if (msgbuf->buf[len - 2] != '\n') {
5304 /*
5305 * Buffer ends with a single newline. Add another
5306 * so that there is an empty line between the message
5307 * body and the sob.
5308 */
33f2f9ab 5309 append_newlines = "\n";
8c613fd5 5310 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
5311
5312 if (append_newlines)
5313 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5314 append_newlines, strlen(append_newlines));
5ed75e2a 5315 }
bab4d109
BC
5316
5317 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5318 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5319 sob.buf, sob.len);
5320
5ed75e2a
MV
5321 strbuf_release(&sob);
5322}
62db5247 5323
1644c73c
JS
5324struct labels_entry {
5325 struct hashmap_entry entry;
5326 char label[FLEX_ARRAY];
5327};
5328
5cf88fd8 5329static int labels_cmp(const void *fndata UNUSED,
02c3c59e 5330 const struct hashmap_entry *eptr,
939af16e 5331 const struct hashmap_entry *entry_or_key, const void *key)
1644c73c 5332{
939af16e
EW
5333 const struct labels_entry *a, *b;
5334
5335 a = container_of(eptr, const struct labels_entry, entry);
5336 b = container_of(entry_or_key, const struct labels_entry, entry);
5337
1644c73c
JS
5338 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5339}
5340
5341struct string_entry {
5342 struct oidmap_entry entry;
5343 char string[FLEX_ARRAY];
5344};
5345
5346struct label_state {
5347 struct oidmap commit2label;
5348 struct hashmap labels;
5349 struct strbuf buf;
5350};
5351
5352static const char *label_oid(struct object_id *oid, const char *label,
5353 struct label_state *state)
5354{
5355 struct labels_entry *labels_entry;
5356 struct string_entry *string_entry;
5357 struct object_id dummy;
1644c73c
JS
5358 int i;
5359
5360 string_entry = oidmap_get(&state->commit2label, oid);
5361 if (string_entry)
5362 return string_entry->string;
5363
5364 /*
5365 * For "uninteresting" commits, i.e. commits that are not to be
5366 * rebased, and which can therefore not be labeled, we use a unique
5367 * abbreviation of the commit name. This is slightly more complicated
5368 * than calling find_unique_abbrev() because we also need to make
5369 * sure that the abbreviation does not conflict with any other
5370 * label.
5371 *
5372 * We disallow "interesting" commits to be labeled by a string that
5373 * is a valid full-length hash, to ensure that we always can find an
5374 * abbreviation for any uninteresting commit's names that does not
5375 * clash with any other label.
5376 */
867bc1d2 5377 strbuf_reset(&state->buf);
1644c73c
JS
5378 if (!label) {
5379 char *p;
5380
4439c7a3 5381 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
1644c73c
JS
5382 label = p = state->buf.buf;
5383
d850b7a5
ÆAB
5384 repo_find_unique_abbrev_r(the_repository, p, oid,
5385 default_abbrev);
1644c73c
JS
5386
5387 /*
5388 * We may need to extend the abbreviated hash so that there is
5389 * no conflicting label.
5390 */
5391 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5392 size_t i = strlen(p) + 1;
5393
5394 oid_to_hex_r(p, oid);
4439c7a3 5395 for (; i < the_hash_algo->hexsz; i++) {
1644c73c
JS
5396 char save = p[i];
5397 p[i] = '\0';
5398 if (!hashmap_get_from_hash(&state->labels,
5399 strihash(p), p))
5400 break;
5401 p[i] = save;
5402 }
5403 }
867bc1d2 5404 } else {
1644c73c
JS
5405 struct strbuf *buf = &state->buf;
5406
1644c73c 5407 /*
cd552227
MR
5408 * Sanitize labels by replacing non-alpha-numeric characters
5409 * (including white-space ones) by dashes, as they might be
5410 * illegal in file names (and hence in ref names).
5411 *
5412 * Note that we retain non-ASCII UTF-8 characters (identified
5413 * via the most significant bit). They should be all acceptable
5414 * in file names. We do not validate the UTF-8 here, that's not
5415 * the job of this function.
1644c73c 5416 */
867bc1d2 5417 for (; *label; label++)
cd552227
MR
5418 if ((*label & 0x80) || isalnum(*label))
5419 strbuf_addch(buf, *label);
5420 /* avoid leading dash and double-dashes */
5421 else if (buf->len && buf->buf[buf->len - 1] != '-')
5422 strbuf_addch(buf, '-');
5423 if (!buf->len) {
5424 strbuf_addstr(buf, "rev-");
5425 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5426 }
867bc1d2 5427 label = buf->buf;
1644c73c 5428
867bc1d2
JS
5429 if ((buf->len == the_hash_algo->hexsz &&
5430 !get_oid_hex(label, &dummy)) ||
5431 (buf->len == 1 && *label == '#') ||
5432 hashmap_get_from_hash(&state->labels,
5433 strihash(label), label)) {
5434 /*
5435 * If the label already exists, or if the label is a
5436 * valid full OID, or the label is a '#' (which we use
5437 * as a separator between merge heads and oneline), we
5438 * append a dash and a number to make it unique.
5439 */
5440 size_t len = buf->len;
1644c73c 5441
867bc1d2
JS
5442 for (i = 2; ; i++) {
5443 strbuf_setlen(buf, len);
5444 strbuf_addf(buf, "-%d", i);
5445 if (!hashmap_get_from_hash(&state->labels,
5446 strihash(buf->buf),
5447 buf->buf))
5448 break;
5449 }
1644c73c 5450
867bc1d2
JS
5451 label = buf->buf;
5452 }
1644c73c
JS
5453 }
5454
5455 FLEX_ALLOC_STR(labels_entry, label, label);
d22245a2 5456 hashmap_entry_init(&labels_entry->entry, strihash(label));
b94e5c1d 5457 hashmap_add(&state->labels, &labels_entry->entry);
1644c73c
JS
5458
5459 FLEX_ALLOC_STR(string_entry, string, label);
5460 oidcpy(&string_entry->entry.oid, oid);
5461 oidmap_put(&state->commit2label, string_entry);
5462
5463 return string_entry->string;
5464}
5465
5466static int make_script_with_merges(struct pretty_print_context *pp,
d358fc28 5467 struct rev_info *revs, struct strbuf *out,
1644c73c
JS
5468 unsigned flags)
5469{
b9cbd295 5470 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 5471 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
e1fac531 5472 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
767a4ca6 5473 int skipped_commit = 0;
1644c73c
JS
5474 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5475 struct strbuf label = STRBUF_INIT;
5476 struct commit_list *commits = NULL, **tail = &commits, *iter;
5477 struct commit_list *tips = NULL, **tips_tail = &tips;
5478 struct commit *commit;
5479 struct oidmap commit2todo = OIDMAP_INIT;
5480 struct string_entry *entry;
5481 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5482 shown = OIDSET_INIT;
5483 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5484
5485 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5486 const char *cmd_pick = abbr ? "p" : "pick",
5487 *cmd_label = abbr ? "l" : "label",
5488 *cmd_reset = abbr ? "t" : "reset",
5489 *cmd_merge = abbr ? "m" : "merge";
5490
5491 oidmap_init(&commit2todo, 0);
5492 oidmap_init(&state.commit2label, 0);
939af16e 5493 hashmap_init(&state.labels, labels_cmp, NULL, 0);
1644c73c
JS
5494 strbuf_init(&state.buf, 32);
5495
5496 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
e02058a7 5497 struct labels_entry *onto_label_entry;
1644c73c
JS
5498 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5499 FLEX_ALLOC_STR(entry, string, "onto");
5500 oidcpy(&entry->entry.oid, oid);
5501 oidmap_put(&state.commit2label, entry);
e02058a7
ĐTCD
5502
5503 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5504 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5505 hashmap_add(&state.labels, &onto_label_entry->entry);
1644c73c
JS
5506 }
5507
5508 /*
5509 * First phase:
5510 * - get onelines for all commits
5511 * - gather all branch tips (i.e. 2nd or later parents of merges)
5512 * - label all branch tips
5513 */
5514 while ((commit = get_revision(revs))) {
5515 struct commit_list *to_merge;
1644c73c
JS
5516 const char *p1, *p2;
5517 struct object_id *oid;
5518 int is_empty;
5519
5520 tail = &commit_list_insert(commit, tail)->next;
5521 oidset_insert(&interesting, &commit->object.oid);
5522
5523 is_empty = is_original_commit_empty(commit);
767a4ca6
JS
5524 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5525 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5526 warning(_("skipped previously applied commit %s"),
5527 short_commit_name(commit));
5528 skipped_commit = 1;
1644c73c 5529 continue;
767a4ca6 5530 }
b9cbd295
EN
5531 if (is_empty && !keep_empty)
5532 continue;
1644c73c
JS
5533
5534 strbuf_reset(&oneline);
5535 pretty_print_commit(pp, commit, &oneline);
5536
5537 to_merge = commit->parents ? commit->parents->next : NULL;
5538 if (!to_merge) {
5539 /* non-merge commit: easy case */
5540 strbuf_reset(&buf);
1644c73c
JS
5541 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5542 oid_to_hex(&commit->object.oid),
5543 oneline.buf);
1b5735f7
EN
5544 if (is_empty)
5545 strbuf_addf(&buf, " %c empty",
5546 comment_line_char);
1644c73c
JS
5547
5548 FLEX_ALLOC_STR(entry, string, buf.buf);
5549 oidcpy(&entry->entry.oid, &commit->object.oid);
5550 oidmap_put(&commit2todo, entry);
5551
5552 continue;
5553 }
5554
1644c73c
JS
5555 /* Create a label */
5556 strbuf_reset(&label);
5557 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5558 (p1 = strchr(p1, '\'')) &&
5559 (p2 = strchr(++p1, '\'')))
5560 strbuf_add(&label, p1, p2 - p1);
5561 else if (skip_prefix(oneline.buf, "Merge pull request ",
5562 &p1) &&
5563 (p1 = strstr(p1, " from ")))
5564 strbuf_addstr(&label, p1 + strlen(" from "));
5565 else
5566 strbuf_addbuf(&label, &oneline);
5567
1644c73c
JS
5568 strbuf_reset(&buf);
5569 strbuf_addf(&buf, "%s -C %s",
5570 cmd_merge, oid_to_hex(&commit->object.oid));
5571
2b6ad0f4
JS
5572 /* label the tips of merged branches */
5573 for (; to_merge; to_merge = to_merge->next) {
5574 oid = &to_merge->item->object.oid;
5575 strbuf_addch(&buf, ' ');
5576
5577 if (!oidset_contains(&interesting, oid)) {
5578 strbuf_addstr(&buf, label_oid(oid, NULL,
5579 &state));
5580 continue;
5581 }
1644c73c 5582
1644c73c
JS
5583 tips_tail = &commit_list_insert(to_merge->item,
5584 tips_tail)->next;
5585
5586 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5587 }
5588 strbuf_addf(&buf, " # %s", oneline.buf);
5589
5590 FLEX_ALLOC_STR(entry, string, buf.buf);
5591 oidcpy(&entry->entry.oid, &commit->object.oid);
5592 oidmap_put(&commit2todo, entry);
5593 }
767a4ca6
JS
5594 if (skipped_commit)
5595 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5596 _("use --reapply-cherry-picks to include skipped commits"));
1644c73c
JS
5597
5598 /*
5599 * Second phase:
5600 * - label branch points
5601 * - add HEAD to the branch tips
5602 */
5603 for (iter = commits; iter; iter = iter->next) {
5604 struct commit_list *parent = iter->item->parents;
5605 for (; parent; parent = parent->next) {
5606 struct object_id *oid = &parent->item->object.oid;
5607 if (!oidset_contains(&interesting, oid))
5608 continue;
6e8fc70f 5609 if (oidset_insert(&child_seen, oid))
1644c73c
JS
5610 label_oid(oid, "branch-point", &state);
5611 }
5612
15beaaa3 5613 /* Add HEAD as implicit "tip of branch" */
1644c73c
JS
5614 if (!iter->next)
5615 tips_tail = &commit_list_insert(iter->item,
5616 tips_tail)->next;
5617 }
5618
5619 /*
5620 * Third phase: output the todo list. This is a bit tricky, as we
5621 * want to avoid jumping back and forth between revisions. To
5622 * accomplish that goal, we walk backwards from the branch tips,
5623 * gathering commits not yet shown, reversing the list on the fly,
5624 * then outputting that list (labeling revisions as needed).
5625 */
d358fc28 5626 strbuf_addf(out, "%s onto\n", cmd_label);
1644c73c
JS
5627 for (iter = tips; iter; iter = iter->next) {
5628 struct commit_list *list = NULL, *iter2;
5629
5630 commit = iter->item;
5631 if (oidset_contains(&shown, &commit->object.oid))
5632 continue;
5633 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5634
5635 if (entry)
d358fc28 5636 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c 5637 else
d358fc28 5638 strbuf_addch(out, '\n');
1644c73c
JS
5639
5640 while (oidset_contains(&interesting, &commit->object.oid) &&
5641 !oidset_contains(&shown, &commit->object.oid)) {
5642 commit_list_insert(commit, &list);
5643 if (!commit->parents) {
5644 commit = NULL;
5645 break;
5646 }
5647 commit = commit->parents->item;
5648 }
5649
5650 if (!commit)
d358fc28 5651 strbuf_addf(out, "%s %s\n", cmd_reset,
e1fac531
JS
5652 rebase_cousins || root_with_onto ?
5653 "onto" : "[new root]");
1644c73c
JS
5654 else {
5655 const char *to = NULL;
5656
5657 entry = oidmap_get(&state.commit2label,
5658 &commit->object.oid);
5659 if (entry)
5660 to = entry->string;
7543f6f4
JS
5661 else if (!rebase_cousins)
5662 to = label_oid(&commit->object.oid, NULL,
5663 &state);
1644c73c
JS
5664
5665 if (!to || !strcmp(to, "onto"))
d358fc28 5666 strbuf_addf(out, "%s onto\n", cmd_reset);
1644c73c
JS
5667 else {
5668 strbuf_reset(&oneline);
5669 pretty_print_commit(pp, commit, &oneline);
d358fc28
AG
5670 strbuf_addf(out, "%s %s # %s\n",
5671 cmd_reset, to, oneline.buf);
1644c73c
JS
5672 }
5673 }
5674
5675 for (iter2 = list; iter2; iter2 = iter2->next) {
5676 struct object_id *oid = &iter2->item->object.oid;
5677 entry = oidmap_get(&commit2todo, oid);
5678 /* only show if not already upstream */
5679 if (entry)
d358fc28 5680 strbuf_addf(out, "%s\n", entry->string);
1644c73c
JS
5681 entry = oidmap_get(&state.commit2label, oid);
5682 if (entry)
d358fc28
AG
5683 strbuf_addf(out, "%s %s\n",
5684 cmd_label, entry->string);
1644c73c
JS
5685 oidset_insert(&shown, oid);
5686 }
5687
5688 free_commit_list(list);
5689 }
5690
5691 free_commit_list(commits);
5692 free_commit_list(tips);
5693
5694 strbuf_release(&label);
5695 strbuf_release(&oneline);
5696 strbuf_release(&buf);
5697
5698 oidmap_free(&commit2todo, 1);
5699 oidmap_free(&state.commit2label, 1);
6da1a258 5700 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
1644c73c
JS
5701 strbuf_release(&state.buf);
5702
5703 return 0;
5704}
5705
d358fc28
AG
5706int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5707 const char **argv, unsigned flags)
62db5247
JS
5708{
5709 char *format = NULL;
5710 struct pretty_print_context pp = {0};
62db5247
JS
5711 struct rev_info revs;
5712 struct commit *commit;
b9cbd295 5713 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 5714 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 5715 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
0fcb4f6b 5716 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
767a4ca6 5717 int skipped_commit = 0;
0139c58a 5718 int ret = 0;
62db5247 5719
f11c9580 5720 repo_init_revisions(r, &revs, NULL);
62db5247 5721 revs.verbose_header = 1;
1644c73c
JS
5722 if (!rebase_merges)
5723 revs.max_parents = 1;
0fcb4f6b 5724 revs.cherry_mark = !reapply_cherry_picks;
62db5247
JS
5725 revs.limited = 1;
5726 revs.reverse = 1;
5727 revs.right_only = 1;
5728 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5729 revs.topo_order = 1;
5730
5731 revs.pretty_given = 1;
5732 git_config_get_string("rebase.instructionFormat", &format);
5733 if (!format || !*format) {
5734 free(format);
5735 format = xstrdup("%s");
5736 }
5737 get_commit_format(format, &revs);
5738 free(format);
5739 pp.fmt = revs.commit_format;
5740 pp.output_encoding = get_log_output_encoding();
5741
0139c58a
ÆAB
5742 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5743 ret = error(_("make_script: unhandled options"));
5744 goto cleanup;
5745 }
62db5247 5746
0139c58a
ÆAB
5747 if (prepare_revision_walk(&revs) < 0) {
5748 ret = error(_("make_script: error preparing revisions"));
5749 goto cleanup;
5750 }
62db5247 5751
0139c58a
ÆAB
5752 if (rebase_merges) {
5753 ret = make_script_with_merges(&pp, &revs, out, flags);
5754 goto cleanup;
5755 }
1644c73c 5756
62db5247 5757 while ((commit = get_revision(&revs))) {
d48e5e21 5758 int is_empty = is_original_commit_empty(commit);
76ea2358 5759
767a4ca6
JS
5760 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5761 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5762 warning(_("skipped previously applied commit %s"),
5763 short_commit_name(commit));
5764 skipped_commit = 1;
76ea2358 5765 continue;
767a4ca6 5766 }
b9cbd295
EN
5767 if (is_empty && !keep_empty)
5768 continue;
d358fc28 5769 strbuf_addf(out, "%s %s ", insn,
d8ae6c84 5770 oid_to_hex(&commit->object.oid));
d358fc28 5771 pretty_print_commit(&pp, commit, out);
1b5735f7
EN
5772 if (is_empty)
5773 strbuf_addf(out, " %c empty", comment_line_char);
d358fc28 5774 strbuf_addch(out, '\n');
62db5247 5775 }
767a4ca6
JS
5776 if (skipped_commit)
5777 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5778 _("use --reapply-cherry-picks to include skipped commits"));
0139c58a
ÆAB
5779cleanup:
5780 release_revisions(&revs);
5781 return ret;
62db5247 5782}
3546c8d9 5783
0cce4a27
LB
5784/*
5785 * Add commands after pick and (series of) squash/fixup commands
5786 * in the todo list.
5787 */
17919c35
JS
5788static void todo_list_add_exec_commands(struct todo_list *todo_list,
5789 struct string_list *commands)
3546c8d9 5790{
683153a4
AG
5791 struct strbuf *buf = &todo_list->buf;
5792 size_t base_offset = buf->len;
5793 int i, insert, nr = 0, alloc = 0;
5794 struct todo_item *items = NULL, *base_items = NULL;
3546c8d9 5795
ca56dadb 5796 CALLOC_ARRAY(base_items, commands->nr);
683153a4
AG
5797 for (i = 0; i < commands->nr; i++) {
5798 size_t command_len = strlen(commands->items[i].string);
3546c8d9 5799
683153a4
AG
5800 strbuf_addstr(buf, commands->items[i].string);
5801 strbuf_addch(buf, '\n');
3546c8d9 5802
683153a4
AG
5803 base_items[i].command = TODO_EXEC;
5804 base_items[i].offset_in_buf = base_offset;
e57d2c59
PW
5805 base_items[i].arg_offset = base_offset;
5806 base_items[i].arg_len = command_len;
3546c8d9 5807
683153a4 5808 base_offset += command_len + 1;
3546c8d9
JS
5809 }
5810
1ace63bc
JS
5811 /*
5812 * Insert <commands> after every pick. Here, fixup/squash chains
5813 * are considered part of the pick, so we insert the commands *after*
5814 * those chains if there are any.
683153a4 5815 *
15beaaa3 5816 * As we insert the exec commands immediately after rearranging
683153a4
AG
5817 * any fixups and before the user edits the list, a fixup chain
5818 * can never contain comments (any comments are empty picks that
5819 * have been commented out because the user did not specify
5820 * --keep-empty). So, it is safe to insert an exec command
5821 * without looking at the command following a comment.
1ace63bc 5822 */
683153a4
AG
5823 insert = 0;
5824 for (i = 0; i < todo_list->nr; i++) {
5825 enum todo_command command = todo_list->items[i].command;
5826 if (insert && !is_fixup(command)) {
5827 ALLOC_GROW(items, nr + commands->nr, alloc);
5828 COPY_ARRAY(items + nr, base_items, commands->nr);
5829 nr += commands->nr;
5830
5831 insert = 0;
0cce4a27 5832 }
1ace63bc 5833
683153a4
AG
5834 ALLOC_GROW(items, nr + 1, alloc);
5835 items[nr++] = todo_list->items[i];
5836
1ace63bc 5837 if (command == TODO_PICK || command == TODO_MERGE)
683153a4 5838 insert = 1;
0cce4a27
LB
5839 }
5840
1ace63bc 5841 /* insert or append final <commands> */
cc9dcdee 5842 if (insert) {
683153a4
AG
5843 ALLOC_GROW(items, nr + commands->nr, alloc);
5844 COPY_ARRAY(items + nr, base_items, commands->nr);
5845 nr += commands->nr;
5846 }
0cce4a27 5847
683153a4
AG
5848 free(base_items);
5849 FREE_AND_NULL(todo_list->items);
5850 todo_list->items = items;
5851 todo_list->nr = nr;
5852 todo_list->alloc = alloc;
0cce4a27 5853}
3546c8d9 5854
616d7740
AG
5855static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5856 struct strbuf *buf, int num, unsigned flags)
3546c8d9 5857{
8dccc7a6 5858 struct todo_item *item;
616d7740 5859 int i, max = todo_list->nr;
3546c8d9 5860
616d7740
AG
5861 if (num > 0 && num < max)
5862 max = num;
3546c8d9 5863
616d7740 5864 for (item = todo_list->items, i = 0; i < max; i++, item++) {
68e7090f
AG
5865 char cmd;
5866
8dccc7a6
LB
5867 /* if the item is not a command write it and continue */
5868 if (item->command >= TODO_COMMENT) {
616d7740 5869 strbuf_addf(buf, "%.*s\n", item->arg_len,
cbef27d6 5870 todo_item_get_arg(todo_list, item));
8dccc7a6 5871 continue;
3546c8d9 5872 }
8dccc7a6
LB
5873
5874 /* add command to the buffer */
68e7090f
AG
5875 cmd = command_to_char(item->command);
5876 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5877 strbuf_addch(buf, cmd);
d8ae6c84 5878 else
616d7740 5879 strbuf_addstr(buf, command_to_string(item->command));
8dccc7a6
LB
5880
5881 /* add commit id */
5882 if (item->commit) {
313a48ea 5883 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
5884 short_commit_name(item->commit) :
5885 oid_to_hex(&item->commit->object.oid);
5886
9e3cebd9
CM
5887 if (item->command == TODO_FIXUP) {
5888 if (item->flags & TODO_EDIT_FIXUP_MSG)
5889 strbuf_addstr(buf, " -c");
5890 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5891 strbuf_addstr(buf, " -C");
5892 }
5893 }
5894
4c68e7dd
JS
5895 if (item->command == TODO_MERGE) {
5896 if (item->flags & TODO_EDIT_MERGE_MSG)
616d7740 5897 strbuf_addstr(buf, " -c");
4c68e7dd 5898 else
616d7740 5899 strbuf_addstr(buf, " -C");
4c68e7dd
JS
5900 }
5901
616d7740 5902 strbuf_addf(buf, " %s", oid);
3546c8d9 5903 }
4c68e7dd 5904
8dccc7a6 5905 /* add all the rest */
c7b4d79c 5906 if (!item->arg_len)
616d7740 5907 strbuf_addch(buf, '\n');
c7b4d79c 5908 else
616d7740 5909 strbuf_addf(buf, " %.*s\n", item->arg_len,
cbef27d6 5910 todo_item_get_arg(todo_list, item));
3546c8d9 5911 }
3546c8d9 5912}
94399949 5913
616d7740
AG
5914int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5915 const char *file, const char *shortrevisions,
5916 const char *shortonto, int num, unsigned flags)
94399949 5917{
af1fc3ad 5918 int res;
616d7740 5919 struct strbuf buf = STRBUF_INIT;
94399949 5920
616d7740 5921 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
af1fc3ad 5922 if (flags & TODO_LIST_APPEND_TODO_HELP)
d48e5e21 5923 append_todo_help(count_commands(todo_list),
af1fc3ad 5924 shortrevisions, shortonto, &buf);
94399949 5925
616d7740 5926 res = write_message(buf.buf, buf.len, file, 0);
cbef27d6 5927 strbuf_release(&buf);
8315bd20 5928
616d7740 5929 return res;
cbef27d6 5930}
94399949 5931
cdac2b01 5932/* skip picking commits whose parents are unchanged */
6bfeb7f1
AG
5933static int skip_unnecessary_picks(struct repository *r,
5934 struct todo_list *todo_list,
5935 struct object_id *base_oid)
cdac2b01 5936{
d4ed5d77 5937 struct object_id *parent_oid;
6bfeb7f1 5938 int i;
cdac2b01 5939
6bfeb7f1
AG
5940 for (i = 0; i < todo_list->nr; i++) {
5941 struct todo_item *item = todo_list->items + i;
cdac2b01
JS
5942
5943 if (item->command >= TODO_NOOP)
5944 continue;
5945 if (item->command != TODO_PICK)
5946 break;
ecb5091f 5947 if (repo_parse_commit(the_repository, item->commit)) {
cdac2b01
JS
5948 return error(_("could not parse commit '%s'"),
5949 oid_to_hex(&item->commit->object.oid));
5950 }
5951 if (!item->commit->parents)
5952 break; /* root commit */
5953 if (item->commit->parents->next)
5954 break; /* merge commit */
5955 parent_oid = &item->commit->parents->item->object.oid;
6bfeb7f1 5956 if (!oideq(parent_oid, base_oid))
cdac2b01 5957 break;
6bfeb7f1 5958 oidcpy(base_oid, &item->commit->object.oid);
cdac2b01
JS
5959 }
5960 if (i > 0) {
cdac2b01
JS
5961 const char *done_path = rebase_path_done();
5962
6bfeb7f1 5963 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
cdac2b01 5964 error_errno(_("could not write to '%s'"), done_path);
cdac2b01
JS
5965 return -1;
5966 }
cdac2b01 5967
6bfeb7f1
AG
5968 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5969 todo_list->nr -= i;
5970 todo_list->current = 0;
34065541 5971 todo_list->done_nr += i;
cdac2b01 5972
6bfeb7f1
AG
5973 if (is_fixup(peek_command(todo_list, 0)))
5974 record_in_rewritten(base_oid, peek_command(todo_list, 0));
cdac2b01
JS
5975 }
5976
cdac2b01
JS
5977 return 0;
5978}
c44a4c65 5979
900b50c2
DS
5980struct todo_add_branch_context {
5981 struct todo_item *items;
5982 size_t items_nr;
5983 size_t items_alloc;
5984 struct strbuf *buf;
5985 struct commit *commit;
5986 struct string_list refs_to_oids;
5987};
5988
5989static int add_decorations_to_list(const struct commit *commit,
5990 struct todo_add_branch_context *ctx)
5991{
5992 const struct name_decoration *decoration = get_name_decoration(&commit->object);
aa37f3e1
DS
5993 const char *head_ref = resolve_ref_unsafe("HEAD",
5994 RESOLVE_REF_READING,
5995 NULL,
5996 NULL);
900b50c2
DS
5997
5998 while (decoration) {
5999 struct todo_item *item;
6000 const char *path;
6001 size_t base_offset = ctx->buf->len;
6002
aa37f3e1
DS
6003 /*
6004 * If the branch is the current HEAD, then it will be
6005 * updated by the default rebase behavior.
6006 */
6007 if (head_ref && !strcmp(head_ref, decoration->name)) {
6008 decoration = decoration->next;
6009 continue;
6010 }
6011
900b50c2
DS
6012 ALLOC_GROW(ctx->items,
6013 ctx->items_nr + 1,
6014 ctx->items_alloc);
6015 item = &ctx->items[ctx->items_nr];
6016 memset(item, 0, sizeof(*item));
6017
6018 /* If the branch is checked out, then leave a comment instead. */
6019 if ((path = branch_checked_out(decoration->name))) {
6020 item->command = TODO_COMMENT;
6021 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6022 decoration->name, path);
6023 } else {
6024 struct string_list_item *sti;
6025 item->command = TODO_UPDATE_REF;
6026 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6027
6028 sti = string_list_insert(&ctx->refs_to_oids,
6029 decoration->name);
89fc0b53 6030 sti->util = init_update_ref_record(decoration->name);
900b50c2
DS
6031 }
6032
6033 item->offset_in_buf = base_offset;
6034 item->arg_offset = base_offset;
6035 item->arg_len = ctx->buf->len - base_offset;
6036 ctx->items_nr++;
6037
6038 decoration = decoration->next;
6039 }
6040
6041 return 0;
6042}
6043
6044/*
6045 * For each 'pick' command, find out if the commit has a decoration in
6046 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6047 */
6048static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6049{
89fc0b53 6050 int i, res;
900b50c2
DS
6051 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6052 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6053 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6054 struct decoration_filter decoration_filter = {
6055 .include_ref_pattern = &decorate_refs_include,
6056 .exclude_ref_pattern = &decorate_refs_exclude,
6057 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6058 };
6059 struct todo_add_branch_context ctx = {
6060 .buf = &todo_list->buf,
6061 .refs_to_oids = STRING_LIST_INIT_DUP,
6062 };
6063
6064 ctx.items_alloc = 2 * todo_list->nr + 1;
6065 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6066
6067 string_list_append(&decorate_refs_include, "refs/heads/");
6068 load_ref_decorations(&decoration_filter, 0);
6069
6070 for (i = 0; i < todo_list->nr; ) {
6071 struct todo_item *item = &todo_list->items[i];
6072
6073 /* insert ith item into new list */
6074 ALLOC_GROW(ctx.items,
6075 ctx.items_nr + 1,
6076 ctx.items_alloc);
6077
6078 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6079
6080 if (item->commit) {
6081 ctx.commit = item->commit;
6082 add_decorations_to_list(item->commit, &ctx);
6083 }
6084 }
6085
89fc0b53
DS
6086 res = write_update_refs_state(&ctx.refs_to_oids);
6087
900b50c2 6088 string_list_clear(&ctx.refs_to_oids, 1);
89fc0b53
DS
6089
6090 if (res) {
6091 /* we failed, so clean up the new list. */
6092 free(ctx.items);
6093 return res;
6094 }
6095
900b50c2
DS
6096 free(todo_list->items);
6097 todo_list->items = ctx.items;
6098 todo_list->nr = ctx.items_nr;
6099 todo_list->alloc = ctx.items_alloc;
6100
6101 return 0;
6102}
6103
005af339 6104int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873 6105 const char *shortrevisions, const char *onto_name,
f3e27a02 6106 struct commit *onto, const struct object_id *orig_head,
7d3488eb 6107 struct string_list *commands, unsigned autosquash,
900b50c2 6108 unsigned update_refs,
7d3488eb 6109 struct todo_list *todo_list)
b97e1873 6110{
5da69c0d
AK
6111 char shortonto[GIT_MAX_HEXSZ + 1];
6112 const char *todo_file = rebase_path_todo();
94bcad79 6113 struct todo_list new_todo = TODO_LIST_INIT;
b6992261 6114 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
7d3488eb 6115 struct object_id oid = onto->object.oid;
1451d0f6 6116 int res;
b97e1873 6117
d850b7a5
ÆAB
6118 repo_find_unique_abbrev_r(the_repository, shortonto, &oid,
6119 DEFAULT_ABBREV);
b97e1873 6120
94bcad79
AG
6121 if (buf->len == 0) {
6122 struct todo_item *item = append_new_todo(todo_list);
6123 item->command = TODO_NOOP;
6124 item->commit = NULL;
6125 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6126 }
b97e1873 6127
900b50c2
DS
6128 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6129 return -1;
6130
94bcad79 6131 if (autosquash && todo_list_rearrange_squash(todo_list))
b97e1873
AG
6132 return -1;
6133
683153a4 6134 if (commands->nr)
94bcad79 6135 todo_list_add_exec_commands(todo_list, commands);
b97e1873 6136
94bcad79 6137 if (count_commands(todo_list) == 0) {
be1bb600 6138 apply_autostash(rebase_path_autostash());
b97e1873 6139 sequencer_remove_state(opts);
b97e1873
AG
6140
6141 return error(_("nothing to do"));
6142 }
6143
1451d0f6
AG
6144 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6145 shortonto, flags);
6146 if (res == -1)
b97e1873 6147 return -1;
1451d0f6 6148 else if (res == -2) {
be1bb600 6149 apply_autostash(rebase_path_autostash());
b97e1873 6150 sequencer_remove_state(opts);
b97e1873
AG
6151
6152 return -1;
1451d0f6 6153 } else if (res == -3) {
be1bb600 6154 apply_autostash(rebase_path_autostash());
b97e1873 6155 sequencer_remove_state(opts);
94bcad79 6156 todo_list_release(&new_todo);
b97e1873
AG
6157
6158 return error(_("nothing to do"));
5a5445d8 6159 } else if (res == -4) {
7d3488eb 6160 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
94bcad79
AG
6161 todo_list_release(&new_todo);
6162
b97e1873
AG
6163 return -1;
6164 }
6165
b6992261
JS
6166 /* Expand the commit IDs */
6167 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6168 strbuf_swap(&new_todo.buf, &buf2);
6169 strbuf_release(&buf2);
6170 new_todo.total_nr -= new_todo.nr;
6171 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6172 BUG("invalid todo list after expanding IDs:\n%s",
6173 new_todo.buf.buf);
6174
6bfeb7f1
AG
6175 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6176 todo_list_release(&new_todo);
b97e1873 6177 return error(_("could not skip unnecessary pick commands"));
6bfeb7f1
AG
6178 }
6179
94bcad79
AG
6180 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6181 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6182 todo_list_release(&new_todo);
6183 return error_errno(_("could not write '%s'"), todo_file);
6184 }
6185
393adf7a 6186 res = -1;
b97e1873 6187
7d3488eb 6188 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
393adf7a 6189 goto cleanup;
29d51e21 6190
005af339 6191 if (require_clean_work_tree(r, "rebase", "", 1, 1))
393adf7a 6192 goto cleanup;
b97e1873 6193
393adf7a
AG
6194 todo_list_write_total_nr(&new_todo);
6195 res = pick_commits(r, &new_todo, opts);
6196
6197cleanup:
6198 todo_list_release(&new_todo);
6199
6200 return res;
b97e1873
AG
6201}
6202
c44a4c65
JS
6203struct subject2item_entry {
6204 struct hashmap_entry entry;
6205 int i;
6206 char subject[FLEX_ARRAY];
6207};
6208
5cf88fd8 6209static int subject2item_cmp(const void *fndata UNUSED,
939af16e
EW
6210 const struct hashmap_entry *eptr,
6211 const struct hashmap_entry *entry_or_key,
6212 const void *key)
c44a4c65 6213{
939af16e
EW
6214 const struct subject2item_entry *a, *b;
6215
6216 a = container_of(eptr, const struct subject2item_entry, entry);
6217 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6218
c44a4c65
JS
6219 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6220}
6221
3cc0287b
NTND
6222define_commit_slab(commit_todo_item, struct todo_item *);
6223
1f969601 6224static int skip_fixupish(const char *subject, const char **p) {
bae5b4ae
CM
6225 return skip_prefix(subject, "fixup! ", p) ||
6226 skip_prefix(subject, "amend! ", p) ||
6227 skip_prefix(subject, "squash! ", p);
6228}
6229
c44a4c65
JS
6230/*
6231 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6232 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6233 * after the former, and change "pick" to "fixup"/"squash".
6234 *
6235 * Note that if the config has specified a custom instruction format, each log
6236 * message will have to be retrieved from the commit (as the oneline in the
6237 * script cannot be trusted) in order to normalize the autosquash arrangement.
6238 */
79d7e883 6239int todo_list_rearrange_squash(struct todo_list *todo_list)
c44a4c65 6240{
c44a4c65 6241 struct hashmap subject2item;
f2a04904 6242 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
c44a4c65 6243 char **subjects;
3cc0287b 6244 struct commit_todo_item commit_todo;
f2a04904 6245 struct todo_item *items = NULL;
c44a4c65 6246
3cc0287b 6247 init_commit_todo_item(&commit_todo);
c44a4c65
JS
6248 /*
6249 * The hashmap maps onelines to the respective todo list index.
6250 *
6251 * If any items need to be rearranged, the next[i] value will indicate
6252 * which item was moved directly after the i'th.
6253 *
6254 * In that case, last[i] will indicate the index of the latest item to
6255 * be moved to appear after the i'th.
6256 */
939af16e 6257 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
f2a04904
AG
6258 ALLOC_ARRAY(next, todo_list->nr);
6259 ALLOC_ARRAY(tail, todo_list->nr);
6260 ALLOC_ARRAY(subjects, todo_list->nr);
6261 for (i = 0; i < todo_list->nr; i++) {
c44a4c65 6262 struct strbuf buf = STRBUF_INIT;
f2a04904 6263 struct todo_item *item = todo_list->items + i;
c44a4c65
JS
6264 const char *commit_buffer, *subject, *p;
6265 size_t subject_len;
6266 int i2 = -1;
6267 struct subject2item_entry *entry;
6268
6269 next[i] = tail[i] = -1;
2f6b1d13 6270 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
6271 subjects[i] = NULL;
6272 continue;
6273 }
6274
6275 if (is_fixup(item->command)) {
3cc0287b 6276 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
6277 return error(_("the script was already rearranged."));
6278 }
6279
ecb5091f
ÆAB
6280 repo_parse_commit(the_repository, item->commit);
6281 commit_buffer = repo_logmsg_reencode(the_repository,
6282 item->commit, NULL,
6283 "UTF-8");
c44a4c65
JS
6284 find_commit_subject(commit_buffer, &subject);
6285 format_subject(&buf, subject, " ");
6286 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
ecb5091f
ÆAB
6287 repo_unuse_commit_buffer(the_repository, item->commit,
6288 commit_buffer);
1f969601 6289 if (skip_fixupish(subject, &p)) {
c44a4c65
JS
6290 struct commit *commit2;
6291
6292 for (;;) {
6293 while (isspace(*p))
6294 p++;
1f969601 6295 if (!skip_fixupish(p, &p))
c44a4c65
JS
6296 break;
6297 }
6298
f23a4651
EW
6299 entry = hashmap_get_entry_from_hash(&subject2item,
6300 strhash(p), p,
6301 struct subject2item_entry,
6302 entry);
6303 if (entry)
c44a4c65
JS
6304 /* found by title */
6305 i2 = entry->i;
6306 else if (!strchr(p, ' ') &&
6307 (commit2 =
6308 lookup_commit_reference_by_name(p)) &&
3cc0287b 6309 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 6310 /* found by commit name */
3cc0287b 6311 i2 = *commit_todo_item_at(&commit_todo, commit2)
f2a04904 6312 - todo_list->items;
c44a4c65
JS
6313 else {
6314 /* copy can be a prefix of the commit subject */
6315 for (i2 = 0; i2 < i; i2++)
6316 if (subjects[i2] &&
6317 starts_with(subjects[i2], p))
6318 break;
6319 if (i2 == i)
6320 i2 = -1;
6321 }
6322 }
6323 if (i2 >= 0) {
6324 rearranged = 1;
bae5b4ae
CM
6325 if (starts_with(subject, "fixup!")) {
6326 todo_list->items[i].command = TODO_FIXUP;
6327 } else if (starts_with(subject, "amend!")) {
6328 todo_list->items[i].command = TODO_FIXUP;
6329 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6330 } else {
6331 todo_list->items[i].command = TODO_SQUASH;
6332 }
02471e7e
JS
6333 if (tail[i2] < 0) {
6334 next[i] = next[i2];
c44a4c65 6335 next[i2] = i;
02471e7e
JS
6336 } else {
6337 next[i] = next[tail[i2]];
c44a4c65 6338 next[tail[i2]] = i;
02471e7e 6339 }
c44a4c65
JS
6340 tail[i2] = i;
6341 } else if (!hashmap_get_from_hash(&subject2item,
6342 strhash(subject), subject)) {
6343 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6344 entry->i = i;
d22245a2
EW
6345 hashmap_entry_init(&entry->entry,
6346 strhash(entry->subject));
26b455f2 6347 hashmap_put(&subject2item, &entry->entry);
c44a4c65 6348 }
3e367a5f
JA
6349
6350 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
6351 }
6352
6353 if (rearranged) {
f2a04904
AG
6354 for (i = 0; i < todo_list->nr; i++) {
6355 enum todo_command command = todo_list->items[i].command;
c44a4c65
JS
6356 int cur = i;
6357
6358 /*
6359 * Initially, all commands are 'pick's. If it is a
6360 * fixup or a squash now, we have rearranged it.
6361 */
6362 if (is_fixup(command))
6363 continue;
6364
6365 while (cur >= 0) {
f2a04904
AG
6366 ALLOC_GROW(items, nr + 1, alloc);
6367 items[nr++] = todo_list->items[cur];
c44a4c65
JS
6368 cur = next[cur];
6369 }
6370 }
6371
f2a04904
AG
6372 FREE_AND_NULL(todo_list->items);
6373 todo_list->items = items;
6374 todo_list->nr = nr;
6375 todo_list->alloc = alloc;
c44a4c65
JS
6376 }
6377
6378 free(next);
6379 free(tail);
f2a04904 6380 for (i = 0; i < todo_list->nr; i++)
c44a4c65
JS
6381 free(subjects[i]);
6382 free(subjects);
6da1a258 6383 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
c44a4c65 6384
3cc0287b 6385 clear_commit_todo_item(&commit_todo);
f2a04904
AG
6386
6387 return 0;
c44a4c65 6388}
901ba7b1
PW
6389
6390int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6391{
c8e4159e 6392 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
430b75f7
PW
6393 struct object_id cherry_pick_head, rebase_head;
6394
6395 if (file_exists(git_path_seq_dir()))
6396 *whence = FROM_CHERRY_PICK_MULTI;
6397 if (file_exists(rebase_path()) &&
d850b7a5
ÆAB
6398 !repo_get_oid(the_repository, "REBASE_HEAD", &rebase_head) &&
6399 !repo_get_oid(the_repository, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
430b75f7
PW
6400 oideq(&rebase_head, &cherry_pick_head))
6401 *whence = FROM_REBASE_PICK;
6402 else
6403 *whence = FROM_CHERRY_PICK_SINGLE;
6404
901ba7b1
PW
6405 return 1;
6406 }
6407
6408 return 0;
6409}
aa7f2fd1
DS
6410
6411int sequencer_get_update_refs_state(const char *wt_dir,
6412 struct string_list *refs)
6413{
6414 int result = 0;
6415 FILE *fp = NULL;
6416 struct strbuf ref = STRBUF_INIT;
6417 struct strbuf hash = STRBUF_INIT;
6418 struct update_ref_record *rec = NULL;
6419
6420 char *path = rebase_path_update_refs(wt_dir);
6421
6422 fp = fopen(path, "r");
6423 if (!fp)
6424 goto cleanup;
6425
6426 while (strbuf_getline(&ref, fp) != EOF) {
6427 struct string_list_item *item;
6428
6429 CALLOC_ARRAY(rec, 1);
6430
6431 if (strbuf_getline(&hash, fp) == EOF ||
6432 get_oid_hex(hash.buf, &rec->before)) {
6433 warning(_("update-refs file at '%s' is invalid"),
6434 path);
6435 result = -1;
6436 goto cleanup;
6437 }
6438
6439 if (strbuf_getline(&hash, fp) == EOF ||
6440 get_oid_hex(hash.buf, &rec->after)) {
6441 warning(_("update-refs file at '%s' is invalid"),
6442 path);
6443 result = -1;
6444 goto cleanup;
6445 }
6446
6447 item = string_list_insert(refs, ref.buf);
6448 item->util = rec;
6449 rec = NULL;
6450 }
6451
6452cleanup:
6453 if (fp)
6454 fclose(fp);
6455 free(path);
6456 free(rec);
6457 strbuf_release(&ref);
6458 strbuf_release(&hash);
6459 return result;
6460}