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