]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
Merge branch 'bl/cherry-pick-empty'
[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);
681 strbuf_addch(msgbuf, comment_line_char);
682 }
683
261f315b 684 strbuf_addch(msgbuf, '\n');
787cb8a4 685 strbuf_commented_addf(msgbuf, comment_line_char, "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)) {
787cb8a4
CW
689 strbuf_commented_addf(msgbuf, comment_line_char,
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
CW
1184 strbuf_stripspace(msgbuf,
1185 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
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
CW
1216 strbuf_stripspace(&tmpl,
1217 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
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
CW
1589 strbuf_stripspace(msg,
1590 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
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;
02127c63 1803 die(_("unknown command: %d"), command);
004fefa7
JS
1804}
1805
ee5462d6 1806static char command_to_char(const enum todo_command command)
d8ae6c84 1807{
68e7090f 1808 if (command < TODO_COMMENT)
d8ae6c84
LB
1809 return todo_command_info[command].c;
1810 return comment_line_char;
1811}
1812
25c43667
JS
1813static int is_noop(const enum todo_command command)
1814{
b3fdd581 1815 return TODO_NOOP <= command;
25c43667 1816}
004fefa7 1817
6e98de72
JS
1818static int is_fixup(enum todo_command command)
1819{
1820 return command == TODO_FIXUP || command == TODO_SQUASH;
1821}
1822
d87d48b2
JS
1823/* Does this command create a (non-merge) commit? */
1824static int is_pick_or_similar(enum todo_command command)
1825{
1826 switch (command) {
1827 case TODO_PICK:
1828 case TODO_REVERT:
1829 case TODO_EDIT:
1830 case TODO_REWORD:
1831 case TODO_FIXUP:
1832 case TODO_SQUASH:
1833 return 1;
1834 default:
1835 return 0;
1836 }
1837}
1838
9e3cebd9
CM
1839enum todo_item_flags {
1840 TODO_EDIT_MERGE_MSG = (1 << 0),
1841 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1842 TODO_EDIT_FIXUP_MSG = (1 << 2),
1843};
1844
71ee81cd
CM
1845static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1846static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
9e3cebd9 1847static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
71ee81cd
CM
1848static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1849static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1850
1f969601 1851static int is_fixup_flag(enum todo_command command, unsigned flag)
498bb5b8 1852{
9e3cebd9
CM
1853 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1854 (flag & TODO_EDIT_FIXUP_MSG));
1855}
7cdb9682 1856
9e3cebd9
CM
1857/*
1858 * Wrapper around strbuf_add_commented_lines() which avoids double
1859 * commenting commit subjects.
1860 */
1861static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1862{
1863 const char *s = str;
1864 while (len > 0 && s[0] == comment_line_char) {
1865 size_t count;
1866 const char *n = memchr(s, '\n', len);
1867 if (!n)
1868 count = len;
1869 else
1870 count = n - s + 1;
1871 strbuf_add(buf, s, count);
1872 s += count;
1873 len -= count;
1874 }
787cb8a4 1875 strbuf_add_commented_lines(buf, s, len, comment_line_char);
9e3cebd9
CM
1876}
1877
1878/* Does the current fixup chain contain a squash command? */
1879static int seen_squash(struct replay_opts *opts)
1880{
1881 return starts_with(opts->current_fixups.buf, "squash") ||
1882 strstr(opts->current_fixups.buf, "\nsquash");
1883}
1884
1885static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1886{
1887 strbuf_setlen(buf1, 2);
1888 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1889 strbuf_addch(buf1, '\n');
1890 strbuf_setlen(buf2, 2);
1891 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1892 strbuf_addch(buf2, '\n');
1893}
1894
1895/*
1896 * Comment out any un-commented commit messages, updating the message comments
1897 * to say they will be skipped but do not comment out the empty lines that
1898 * surround commit messages and their comments.
1899 */
1900static void update_squash_message_for_fixup(struct strbuf *msg)
1901{
1902 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1903 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1904 const char *s, *start;
1905 char *orig_msg;
1906 size_t orig_msg_len;
1907 int i = 1;
1908
1909 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1910 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1911 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1912 while (s) {
1913 const char *next;
1914 size_t off;
1915 if (skip_prefix(s, buf1.buf, &next)) {
1916 /*
1917 * Copy the last message, preserving the blank line
1918 * preceding the current line
1919 */
1920 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1921 copy_lines(msg, start, s - start - off);
1922 if (off)
1923 strbuf_addch(msg, '\n');
1924 /*
1925 * The next message needs to be commented out but the
1926 * message header is already commented out so just copy
1927 * it and the blank line that follows it.
1928 */
1929 strbuf_addbuf(msg, &buf2);
1930 if (*next == '\n')
1931 strbuf_addch(msg, *next++);
1932 start = s = next;
1933 copy_lines = add_commented_lines;
1934 update_comment_bufs(&buf1, &buf2, ++i);
1935 } else if (skip_prefix(s, buf2.buf, &next)) {
1936 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1937 copy_lines(msg, start, s - start - off);
1938 start = s - off;
1939 s = next;
1940 copy_lines = strbuf_add;
1941 update_comment_bufs(&buf1, &buf2, ++i);
1942 } else {
1943 s = strchr(s, '\n');
1944 if (s)
1945 s++;
1946 }
1947 }
1948 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1949 free(orig_msg);
1950 strbuf_release(&buf1);
1951 strbuf_release(&buf2);
1952}
1953
1954static int append_squash_message(struct strbuf *buf, const char *body,
1955 enum todo_command command, struct replay_opts *opts,
a25314c1 1956 unsigned flag)
9e3cebd9
CM
1957{
1958 const char *fixup_msg;
1959 size_t commented_len = 0, fixup_off;
1960 /*
1961 * amend is non-interactive and not normally used with fixup!
1962 * or squash! commits, so only comment out those subjects when
1963 * squashing commit messages.
1964 */
1965 if (starts_with(body, "amend!") ||
1966 ((command == TODO_SQUASH || seen_squash(opts)) &&
1967 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
6e0e2887 1968 commented_len = commit_subject_length(body);
9e3cebd9 1969
498bb5b8 1970 strbuf_addf(buf, "\n%c ", comment_line_char);
71ee81cd 1971 strbuf_addf(buf, _(nth_commit_msg_fmt),
498bb5b8
PW
1972 ++opts->current_fixup_count + 1);
1973 strbuf_addstr(buf, "\n\n");
787cb8a4 1974 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
9e3cebd9
CM
1975 /* buf->buf may be reallocated so store an offset into the buffer */
1976 fixup_off = buf->len;
7cdb9682 1977 strbuf_addstr(buf, body + commented_len);
9e3cebd9
CM
1978
1979 /* fixup -C after squash behaves like squash */
1f969601 1980 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
9e3cebd9
CM
1981 /*
1982 * We're replacing the commit message so we need to
1983 * append the Signed-off-by: trailer if the user
1984 * requested '--signoff'.
1985 */
1986 if (opts->signoff)
1987 append_signoff(buf, 0, 0);
1988
1989 if ((command == TODO_FIXUP) &&
1990 (flag & TODO_REPLACE_FIXUP_MSG) &&
1991 (file_exists(rebase_path_fixup_msg()) ||
1992 !file_exists(rebase_path_squash_msg()))) {
1993 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1994 if (write_message(fixup_msg, strlen(fixup_msg),
1995 rebase_path_fixup_msg(), 0) < 0)
1996 return error(_("cannot write '%s'"),
1997 rebase_path_fixup_msg());
1998 } else {
1999 unlink(rebase_path_fixup_msg());
2000 }
2001 } else {
2002 unlink(rebase_path_fixup_msg());
2003 }
2004
2005 return 0;
498bb5b8
PW
2006}
2007
005af339
NTND
2008static int update_squash_messages(struct repository *r,
2009 enum todo_command command,
2010 struct commit *commit,
9e3cebd9 2011 struct replay_opts *opts,
a25314c1 2012 unsigned flag)
6e98de72
JS
2013{
2014 struct strbuf buf = STRBUF_INIT;
9e3cebd9 2015 int res = 0;
6e98de72 2016 const char *message, *body;
b3757442 2017 const char *encoding = get_commit_output_encoding();
6e98de72 2018
e12a7ef5 2019 if (opts->current_fixup_count > 0) {
6e98de72 2020 struct strbuf header = STRBUF_INIT;
e12a7ef5 2021 char *eol;
6e98de72 2022
e12a7ef5 2023 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
6e98de72
JS
2024 return error(_("could not read '%s'"),
2025 rebase_path_squash_msg());
2026
e12a7ef5
JS
2027 eol = buf.buf[0] != comment_line_char ?
2028 buf.buf : strchrnul(buf.buf, '\n');
6e98de72
JS
2029
2030 strbuf_addf(&header, "%c ", comment_line_char);
71ee81cd 2031 strbuf_addf(&header, _(combined_commit_msg_fmt),
e12a7ef5 2032 opts->current_fixup_count + 2);
6e98de72
JS
2033 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2034 strbuf_release(&header);
1f969601 2035 if (is_fixup_flag(command, flag) && !seen_squash(opts))
9e3cebd9 2036 update_squash_message_for_fixup(&buf);
6e98de72 2037 } else {
33d66df3 2038 struct object_id head;
6e98de72
JS
2039 struct commit *head_commit;
2040 const char *head_message, *body;
2041
4a93b899 2042 if (repo_get_oid(r, "HEAD", &head))
6e98de72 2043 return error(_("need a HEAD to fixup"));
005af339 2044 if (!(head_commit = lookup_commit_reference(r, &head)))
6e98de72 2045 return error(_("could not read HEAD"));
4a93b899
ÆAB
2046 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2047 encoding)))
6e98de72
JS
2048 return error(_("could not read HEAD's commit message"));
2049
2050 find_commit_subject(head_message, &body);
9e3cebd9 2051 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
eab0df0e 2052 rebase_path_fixup_msg(), 0) < 0) {
4a93b899 2053 repo_unuse_commit_buffer(r, head_commit, head_message);
eab0df0e 2054 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
6e98de72 2055 }
6e98de72 2056 strbuf_addf(&buf, "%c ", comment_line_char);
71ee81cd 2057 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
6e98de72 2058 strbuf_addf(&buf, "\n%c ", comment_line_char);
1f969601 2059 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
9e3cebd9
CM
2060 _(skip_first_commit_msg_str) :
2061 _(first_commit_msg_str));
6e98de72 2062 strbuf_addstr(&buf, "\n\n");
1f969601 2063 if (is_fixup_flag(command, flag))
787cb8a4
CW
2064 strbuf_add_commented_lines(&buf, body, strlen(body),
2065 comment_line_char);
9e3cebd9
CM
2066 else
2067 strbuf_addstr(&buf, body);
6e98de72 2068
4a93b899 2069 repo_unuse_commit_buffer(r, head_commit, head_message);
6e98de72
JS
2070 }
2071
4a93b899 2072 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
6e98de72
JS
2073 return error(_("could not read commit message of %s"),
2074 oid_to_hex(&commit->object.oid));
2075 find_commit_subject(message, &body);
2076
1f969601 2077 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
9e3cebd9 2078 res = append_squash_message(&buf, body, command, opts, flag);
6e98de72
JS
2079 } else if (command == TODO_FIXUP) {
2080 strbuf_addf(&buf, "\n%c ", comment_line_char);
71ee81cd 2081 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
dd2e36eb 2082 ++opts->current_fixup_count + 1);
6e98de72 2083 strbuf_addstr(&buf, "\n\n");
787cb8a4
CW
2084 strbuf_add_commented_lines(&buf, body, strlen(body),
2085 comment_line_char);
6e98de72
JS
2086 } else
2087 return error(_("unknown command: %d"), command);
4a93b899 2088 repo_unuse_commit_buffer(r, commit, message);
6e98de72 2089
9e3cebd9
CM
2090 if (!res)
2091 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2092 0);
6e98de72 2093 strbuf_release(&buf);
e12a7ef5
JS
2094
2095 if (!res) {
2096 strbuf_addf(&opts->current_fixups, "%s%s %s",
2097 opts->current_fixups.len ? "\n" : "",
2098 command_to_string(command),
2099 oid_to_hex(&commit->object.oid));
2100 res = write_message(opts->current_fixups.buf,
2101 opts->current_fixups.len,
2102 rebase_path_current_fixups(), 0);
2103 }
2104
6e98de72
JS
2105 return res;
2106}
2107
3b335762
NTND
2108static void flush_rewritten_pending(void)
2109{
25cb8df9 2110 struct strbuf buf = STRBUF_INIT;
092bbcdf 2111 struct object_id newoid;
25cb8df9
JS
2112 FILE *out;
2113
092bbcdf 2114 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
d850b7a5 2115 !repo_get_oid(the_repository, "HEAD", &newoid) &&
e9d983f1 2116 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
25cb8df9
JS
2117 char *bol = buf.buf, *eol;
2118
2119 while (*bol) {
2120 eol = strchrnul(bol, '\n');
2121 fprintf(out, "%.*s %s\n", (int)(eol - bol),
092bbcdf 2122 bol, oid_to_hex(&newoid));
25cb8df9
JS
2123 if (!*eol)
2124 break;
2125 bol = eol + 1;
2126 }
2127 fclose(out);
2128 unlink(rebase_path_rewritten_pending());
2129 }
2130 strbuf_release(&buf);
2131}
2132
2133static void record_in_rewritten(struct object_id *oid,
3b335762
NTND
2134 enum todo_command next_command)
2135{
e9d983f1 2136 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
25cb8df9
JS
2137
2138 if (!out)
2139 return;
2140
2141 fprintf(out, "%s\n", oid_to_hex(oid));
2142 fclose(out);
2143
2144 if (!is_fixup(next_command))
2145 flush_rewritten_pending();
2146}
2147
39edfd5c
EN
2148static int should_edit(struct replay_opts *opts) {
2149 if (opts->edit < 0)
2150 /*
2151 * Note that we only handle the case of non-conflicted
2152 * commits; continue_single_pick() handles the conflicted
2153 * commits itself instead of calling this function.
2154 */
2155 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2156 return opts->edit;
2157}
2158
43966ab3
JH
2159static void refer_to_commit(struct replay_opts *opts,
2160 struct strbuf *msgbuf, struct commit *commit)
2161{
2162 if (opts->commit_use_reference) {
2163 struct pretty_print_context ctx = {
2164 .abbrev = DEFAULT_ABBREV,
2165 .date_mode.type = DATE_SHORT,
2166 };
bab82164
ÆAB
2167 repo_format_commit_message(the_repository, commit,
2168 "%h (%s, %ad)", msgbuf, &ctx);
43966ab3
JH
2169 } else {
2170 strbuf_addstr(msgbuf, oid_to_hex(&commit->object.oid));
2171 }
2172}
2173
f11c9580 2174static int do_pick_commit(struct repository *r,
ae70e34f 2175 struct todo_item *item,
f11c9580 2176 struct replay_opts *opts,
a47ba3c7 2177 int final_fixup, int *check_todo)
043a4492 2178{
39edfd5c
EN
2179 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2180 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
ace976b2 2181 struct object_id head;
043a4492
RR
2182 struct commit *base, *next, *parent;
2183 const char *base_label, *next_label;
356ee465 2184 char *author = NULL;
d74a4e57 2185 struct commit_message msg = { NULL, NULL, NULL, NULL };
043a4492 2186 struct strbuf msgbuf = STRBUF_INIT;
e98c4269 2187 int res, unborn = 0, reword = 0, allow, drop_commit;
ae70e34f
CM
2188 enum todo_command command = item->command;
2189 struct commit *commit = item->commit;
043a4492
RR
2190
2191 if (opts->no_commit) {
2192 /*
2193 * We do not intend to commit immediately. We just want to
2194 * merge the differences in, so let's compute the tree
81483fe6 2195 * that represents the "current" state for the merge machinery
043a4492
RR
2196 * to work on.
2197 */
f11c9580 2198 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
93b3df6f 2199 return error(_("your index file is unmerged."));
043a4492 2200 } else {
4a93b899 2201 unborn = repo_get_oid(r, "HEAD", &head);
d87d48b2
JS
2202 /* Do we want to generate a root commit? */
2203 if (is_pick_or_similar(command) && opts->have_squash_onto &&
4a7e27e9 2204 oideq(&head, &opts->squash_onto)) {
d87d48b2
JS
2205 if (is_fixup(command))
2206 return error(_("cannot fixup root commit"));
2207 flags |= CREATE_ROOT_COMMIT;
2208 unborn = 1;
2209 } else if (unborn)
eb0ccfd7 2210 oidcpy(&head, the_hash_algo->empty_tree);
ffc00a48 2211 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
02f2f56b 2212 NULL, 0))
e1ff0a32 2213 return error_dirty_index(r, opts);
043a4492 2214 }
f11c9580 2215 discard_index(r->index);
043a4492 2216
637666c8 2217 if (!commit->parents)
043a4492 2218 parent = NULL;
043a4492
RR
2219 else if (commit->parents->next) {
2220 /* Reverting or cherry-picking a merge commit */
2221 int cnt;
2222 struct commit_list *p;
2223
2224 if (!opts->mainline)
93b3df6f 2225 return error(_("commit %s is a merge but no -m option was given."),
f2fd0760 2226 oid_to_hex(&commit->object.oid));
043a4492
RR
2227
2228 for (cnt = 1, p = commit->parents;
2229 cnt != opts->mainline && p;
2230 cnt++)
2231 p = p->next;
2232 if (cnt != opts->mainline || !p)
93b3df6f 2233 return error(_("commit %s does not have parent %d"),
f2fd0760 2234 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492 2235 parent = p->item;
37897bfc
SO
2236 } else if (1 < opts->mainline)
2237 /*
2238 * Non-first parent explicitly specified as mainline for
2239 * non-merge commit
2240 */
2241 return error(_("commit %s does not have parent %d"),
2242 oid_to_hex(&commit->object.oid), opts->mainline);
043a4492
RR
2243 else
2244 parent = commit->parents->item;
2245
bcbb68be
JS
2246 if (get_message(commit, &msg) != 0)
2247 return error(_("cannot get commit message for %s"),
2248 oid_to_hex(&commit->object.oid));
2249
6e98de72 2250 if (opts->allow_ff && !is_fixup(command) &&
4a7e27e9 2251 ((parent && oideq(&parent->object.oid, &head)) ||
bcbb68be
JS
2252 (!parent && unborn))) {
2253 if (is_rebase_i(opts))
2254 write_author_script(msg.message);
f11c9580 2255 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
bcbb68be
JS
2256 opts);
2257 if (res || command != TODO_REWORD)
2258 goto leave;
450efe2d 2259 reword = 1;
bcbb68be
JS
2260 msg_file = NULL;
2261 goto fast_forward_edit;
2262 }
4a93b899 2263 if (parent && repo_parse_commit(r, parent) < 0)
004fefa7
JS
2264 /* TRANSLATORS: The first %s will be a "todo" command like
2265 "revert" or "pick", the second %s a SHA1. */
043a4492 2266 return error(_("%s: cannot parse parent commit %s"),
004fefa7
JS
2267 command_to_string(command),
2268 oid_to_hex(&parent->object.oid));
043a4492 2269
043a4492
RR
2270 /*
2271 * "commit" is an existing commit. We would want to apply
2272 * the difference it introduces since its first parent "prev"
2273 * on top of the current HEAD if we are cherry-pick. Or the
2274 * reverse of it if we are revert.
2275 */
2276
004fefa7 2277 if (command == TODO_REVERT) {
883cb1b8
OB
2278 const char *orig_subject;
2279
043a4492
RR
2280 base = commit;
2281 base_label = msg.label;
2282 next = parent;
2283 next_label = msg.parent_label;
43966ab3
JH
2284 if (opts->commit_use_reference) {
2285 strbuf_addstr(&msgbuf,
2286 "# *** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
883cb1b8
OB
2287 } else if (skip_prefix(msg.subject, "Revert \"", &orig_subject) &&
2288 /*
2289 * We don't touch pre-existing repeated reverts, because
2290 * theoretically these can be nested arbitrarily deeply,
2291 * thus requiring excessive complexity to deal with.
2292 */
2293 !starts_with(orig_subject, "Revert \"")) {
2294 strbuf_addstr(&msgbuf, "Reapply \"");
2295 strbuf_addstr(&msgbuf, orig_subject);
43966ab3
JH
2296 } else {
2297 strbuf_addstr(&msgbuf, "Revert \"");
2298 strbuf_addstr(&msgbuf, msg.subject);
2299 strbuf_addstr(&msgbuf, "\"");
2300 }
2301 strbuf_addstr(&msgbuf, "\n\nThis reverts commit ");
2302 refer_to_commit(opts, &msgbuf, commit);
043a4492
RR
2303
2304 if (commit->parents && commit->parents->next) {
2305 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
43966ab3 2306 refer_to_commit(opts, &msgbuf, parent);
043a4492
RR
2307 }
2308 strbuf_addstr(&msgbuf, ".\n");
2309 } else {
2310 const char *p;
2311
2312 base = parent;
2313 base_label = msg.parent_label;
2314 next = commit;
2315 next_label = msg.label;
2316
23aa5142
JS
2317 /* Append the commit log message to msgbuf. */
2318 if (find_commit_subject(msg.message, &p))
2319 strbuf_addstr(&msgbuf, p);
043a4492
RR
2320
2321 if (opts->record_origin) {
44dc738a 2322 strbuf_complete_line(&msgbuf);
bab4d109 2323 if (!has_conforming_footer(&msgbuf, NULL, 0))
b971e04f 2324 strbuf_addch(&msgbuf, '\n');
cd650a4e 2325 strbuf_addstr(&msgbuf, cherry_picked_prefix);
f2fd0760 2326 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
043a4492
RR
2327 strbuf_addstr(&msgbuf, ")\n");
2328 }
356ee465
PW
2329 if (!is_fixup(command))
2330 author = get_author(msg.message);
043a4492
RR
2331 }
2332
04efc8b5 2333 if (command == TODO_REWORD)
450efe2d 2334 reword = 1;
04efc8b5 2335 else if (is_fixup(command)) {
9e3cebd9 2336 if (update_squash_messages(r, command, commit,
a5792e9d
ÆAB
2337 opts, item->flags)) {
2338 res = -1;
2339 goto leave;
2340 }
789b3eff 2341 flags |= AMEND_MSG;
6e98de72
JS
2342 if (!final_fixup)
2343 msg_file = rebase_path_squash_msg();
2344 else if (file_exists(rebase_path_fixup_msg())) {
f7d42cee 2345 flags |= VERBATIM_MSG;
6e98de72
JS
2346 msg_file = rebase_path_fixup_msg();
2347 } else {
f11c9580 2348 const char *dest = git_path_squash_msg(r);
6e98de72 2349 unlink(dest);
a5792e9d 2350 if (copy_file(dest, rebase_path_squash_msg(), 0666)) {
82af2c63 2351 res = error(_("could not copy '%s' to '%s'"),
a5792e9d
ÆAB
2352 rebase_path_squash_msg(), dest);
2353 goto leave;
2354 }
f11c9580 2355 unlink(git_path_merge_msg(r));
6e98de72 2356 msg_file = dest;
789b3eff 2357 flags |= EDIT_MSG;
6e98de72
JS
2358 }
2359 }
2360
a852ec7f 2361 if (opts->signoff && !is_fixup(command))
b34eeea3
PW
2362 append_signoff(&msgbuf, 0, 0);
2363
0473f28a
JS
2364 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2365 res = -1;
14c4586c
EN
2366 else if (!opts->strategy ||
2367 !strcmp(opts->strategy, "recursive") ||
2368 !strcmp(opts->strategy, "ort") ||
2369 command == TODO_REVERT) {
f11c9580 2370 res = do_recursive_merge(r, base, next, base_label, next_label,
48be4c62 2371 &head, &msgbuf, opts);
f241ff0d 2372 if (res < 0)
19517fb9
SB
2373 goto leave;
2374
75871495 2375 res |= write_message(msgbuf.buf, msgbuf.len,
f11c9580 2376 git_path_merge_msg(r), 0);
043a4492
RR
2377 } else {
2378 struct commit_list *common = NULL;
2379 struct commit_list *remotes = NULL;
2380
75871495 2381 res = write_message(msgbuf.buf, msgbuf.len,
f11c9580 2382 git_path_merge_msg(r), 0);
043a4492
RR
2383
2384 commit_list_insert(base, &common);
2385 commit_list_insert(next, &remotes);
f11c9580 2386 res |= try_merge_command(r, opts->strategy,
fb60b9f3 2387 opts->xopts.nr, opts->xopts.v,
ace976b2 2388 common, oid_to_hex(&head), remotes);
043a4492
RR
2389 free_commit_list(common);
2390 free_commit_list(remotes);
2391 }
2392
2393 /*
2394 * If the merge was clean or if it failed due to conflict, we write
2395 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2396 * However, if the merge did not even start, then we don't want to
2397 * write it at all.
2398 */
21b11c6d
PW
2399 if ((command == TODO_PICK || command == TODO_REWORD ||
2400 command == TODO_EDIT) && !opts->no_commit &&
2401 (res == 0 || res == 1) &&
ae077771 2402 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
91774afc 2403 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2404 res = -1;
004fefa7 2405 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
ae077771 2406 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
91774afc 2407 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
dbfad033 2408 res = -1;
043a4492
RR
2409
2410 if (res) {
004fefa7 2411 error(command == TODO_REVERT
043a4492
RR
2412 ? _("could not revert %s... %s")
2413 : _("could not apply %s... %s"),
cb646ffb 2414 short_commit_name(r, commit), msg.subject);
005af339 2415 print_advice(r, res == 1, opts);
f11c9580 2416 repo_rerere(r, opts->allow_rerere_auto);
c8d1351d 2417 goto leave;
043a4492
RR
2418 }
2419
e98c4269 2420 drop_commit = 0;
f11c9580 2421 allow = allow_empty(r, opts, commit);
706728a3
FC
2422 if (allow < 0) {
2423 res = allow;
2424 goto leave;
e98c4269 2425 } else if (allow == 1) {
789b3eff 2426 flags |= ALLOW_EMPTY;
e98c4269
EN
2427 } else if (allow == 2) {
2428 drop_commit = 1;
c8e4159e 2429 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
821f6632 2430 NULL, REF_NO_DEREF);
9a1b7474 2431 unlink(git_path_merge_msg(r));
fd7c6ffa
PS
2432 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2433 NULL, REF_NO_DEREF);
e98c4269
EN
2434 fprintf(stderr,
2435 _("dropping %s %s -- patch contents already upstream\n"),
2436 oid_to_hex(&commit->object.oid), msg.subject);
2437 } /* else allow == 0 and there's nothing special to do */
2438 if (!opts->no_commit && !drop_commit) {
356ee465 2439 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
430b75f7
PW
2440 res = do_commit(r, msg_file, author, opts, flags,
2441 commit? &commit->object.oid : NULL);
356ee465
PW
2442 else
2443 res = error(_("unable to parse commit author"));
a47ba3c7
PW
2444 *check_todo = !!(flags & EDIT_MSG);
2445 if (!res && reword) {
450efe2d 2446fast_forward_edit:
20f4b044 2447 res = run_git_commit(NULL, opts, EDIT_MSG |
450efe2d
PW
2448 VERIFY_MSG | AMEND_MSG |
2449 (flags & ALLOW_EMPTY));
a47ba3c7
PW
2450 *check_todo = 1;
2451 }
356ee465 2452 }
6e98de72 2453
450efe2d 2454
6e98de72
JS
2455 if (!res && final_fixup) {
2456 unlink(rebase_path_fixup_msg());
2457 unlink(rebase_path_squash_msg());
e12a7ef5
JS
2458 unlink(rebase_path_current_fixups());
2459 strbuf_reset(&opts->current_fixups);
2460 opts->current_fixup_count = 0;
6e98de72 2461 }
c8d1351d
FC
2462
2463leave:
d74a4e57 2464 free_message(commit, &msg);
356ee465 2465 free(author);
a5792e9d 2466 strbuf_release(&msgbuf);
1e41229d 2467 update_abort_safety_file();
043a4492
RR
2468
2469 return res;
2470}
2471
c3e8618c 2472static int prepare_revs(struct replay_opts *opts)
043a4492 2473{
a73e22e9
MZ
2474 /*
2475 * picking (but not reverting) ranges (but not individual revisions)
2476 * should be done in reverse
2477 */
2478 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
043a4492
RR
2479 opts->revs->reverse ^= 1;
2480
2481 if (prepare_revision_walk(opts->revs))
c3e8618c 2482 return error(_("revision walk setup failed"));
043a4492 2483
c3e8618c 2484 return 0;
043a4492
RR
2485}
2486
f11c9580
NTND
2487static int read_and_refresh_cache(struct repository *r,
2488 struct replay_opts *opts)
043a4492 2489{
14bca6c6 2490 struct lock_file index_lock = LOCK_INIT;
3a95f31d
NTND
2491 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2492 if (repo_read_index(r) < 0) {
49fb937e 2493 rollback_lock_file(&index_lock);
0d9c6dc9 2494 return error(_("git %s: failed to read the index"),
629444ad 2495 action_name(opts));
49fb937e 2496 }
f11c9580 2497 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
5d9c9349 2498
61000814 2499 if (index_fd >= 0) {
f11c9580 2500 if (write_locked_index(r->index, &index_lock,
61000814 2501 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
0d9c6dc9 2502 return error(_("git %s: failed to refresh the index"),
629444ad 2503 action_name(opts));
49fb937e 2504 }
043a4492 2505 }
5d9c9349
DS
2506
2507 /*
2508 * If we are resolving merges in any way other than "ort", then
2509 * expand the sparse index.
2510 */
2511 if (opts->strategy && strcmp(opts->strategy, "ort"))
2512 ensure_full_index(r->index);
0d9c6dc9 2513 return 0;
043a4492
RR
2514}
2515
5d94d545 2516void todo_list_release(struct todo_list *todo_list)
043a4492 2517{
004fefa7 2518 strbuf_release(&todo_list->buf);
6a83d902 2519 FREE_AND_NULL(todo_list->items);
004fefa7
JS
2520 todo_list->nr = todo_list->alloc = 0;
2521}
043a4492 2522
004fefa7
JS
2523static struct todo_item *append_new_todo(struct todo_list *todo_list)
2524{
2525 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2526 return todo_list->items + todo_list->nr++;
043a4492
RR
2527}
2528
6ad656db
AG
2529const char *todo_item_get_arg(struct todo_list *todo_list,
2530 struct todo_item *item)
2531{
2532 return todo_list->buf.buf + item->arg_offset;
2533}
2534
3e81bccd
PW
2535static int is_command(enum todo_command command, const char **bol)
2536{
2537 const char *str = todo_command_info[command].str;
2538 const char nick = todo_command_info[command].c;
7aed2c05 2539 const char *p = *bol;
3e81bccd 2540
7aed2c05
PW
2541 return (skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2542 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2543 (*bol = p);
3e81bccd
PW
2544}
2545
16b3880d
PW
2546static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2547{
2548 switch (command) {
2549 case TODO_LABEL:
2550 /*
2551 * '#' is not a valid label as the merge command uses it to
2552 * separate merge parents from the commit subject.
2553 */
2554 if (!strcmp(arg, "#") ||
2555 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2556 return error(_("'%s' is not a valid label"), arg);
2557 break;
2558
2559 case TODO_UPDATE_REF:
2560 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2561 return error(_("'%s' is not a valid refname"), arg);
2562 if (check_refname_format(arg, 0))
2563 return error(_("update-ref requires a fully qualified "
2564 "refname e.g. refs/heads/%s"), arg);
2565 break;
2566
2567 default:
2568 BUG("unexpected todo_command");
2569 }
2570
2571 return 0;
2572}
2573
005af339 2574static int parse_insn_line(struct repository *r, struct todo_item *item,
6ad656db 2575 const char *buf, const char *bol, char *eol)
043a4492 2576{
1e43ed98 2577 struct object_id commit_oid;
043a4492 2578 char *end_of_object_name;
004fefa7
JS
2579 int i, saved, status, padding;
2580
4c68e7dd
JS
2581 item->flags = 0;
2582
8f8550b3
JS
2583 /* left-trim */
2584 bol += strspn(bol, " \t");
2585
25c43667 2586 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
ac191470 2587 item->command = TODO_COMMENT;
25c43667 2588 item->commit = NULL;
6ad656db 2589 item->arg_offset = bol - buf;
25c43667
JS
2590 item->arg_len = eol - bol;
2591 return 0;
2592 }
2593
ac191470 2594 for (i = 0; i < TODO_COMMENT; i++)
3e81bccd 2595 if (is_command(i, &bol)) {
004fefa7
JS
2596 item->command = i;
2597 break;
2598 }
ac191470 2599 if (i >= TODO_COMMENT)
7aed2c05
PW
2600 return error(_("invalid command '%.*s'"),
2601 (int)strcspn(bol, " \t\r\n"), bol);
043a4492 2602
66afa24f
JS
2603 /* Eat up extra spaces/ tabs before object name */
2604 padding = strspn(bol, " \t");
2605 bol += padding;
2606
71f82465 2607 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
66afa24f
JS
2608 if (bol != eol)
2609 return error(_("%s does not accept arguments: '%s'"),
2610 command_to_string(item->command), bol);
25c43667 2611 item->commit = NULL;
6ad656db 2612 item->arg_offset = bol - buf;
25c43667
JS
2613 item->arg_len = eol - bol;
2614 return 0;
2615 }
2616
043a4492 2617 if (!padding)
66afa24f
JS
2618 return error(_("missing arguments for %s"),
2619 command_to_string(item->command));
043a4492 2620
9055e401 2621 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
a97d7916 2622 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
16b3880d
PW
2623 int ret = 0;
2624
7dcbb3cb 2625 item->commit = NULL;
6ad656db 2626 item->arg_offset = bol - buf;
311af526 2627 item->arg_len = (int)(eol - bol);
16b3880d
PW
2628 if (item->command == TODO_LABEL ||
2629 item->command == TODO_UPDATE_REF) {
2630 saved = *eol;
2631 *eol = '\0';
2632 ret = check_label_or_ref_arg(item->command, bol);
2633 *eol = saved;
2634 }
2635 return ret;
311af526
JS
2636 }
2637
9e3cebd9 2638 if (item->command == TODO_FIXUP) {
666b6e11 2639 if (skip_prefix(bol, "-C", &bol)) {
9e3cebd9
CM
2640 bol += strspn(bol, " \t");
2641 item->flags |= TODO_REPLACE_FIXUP_MSG;
666b6e11 2642 } else if (skip_prefix(bol, "-c", &bol)) {
9e3cebd9
CM
2643 bol += strspn(bol, " \t");
2644 item->flags |= TODO_EDIT_FIXUP_MSG;
2645 }
2646 }
2647
4c68e7dd
JS
2648 if (item->command == TODO_MERGE) {
2649 if (skip_prefix(bol, "-C", &bol))
2650 bol += strspn(bol, " \t");
2651 else if (skip_prefix(bol, "-c", &bol)) {
2652 bol += strspn(bol, " \t");
2653 item->flags |= TODO_EDIT_MERGE_MSG;
2654 } else {
2655 item->flags |= TODO_EDIT_MERGE_MSG;
2656 item->commit = NULL;
6ad656db 2657 item->arg_offset = bol - buf;
4c68e7dd
JS
2658 item->arg_len = (int)(eol - bol);
2659 return 0;
2660 }
2661 }
2662
004fefa7 2663 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
043a4492
RR
2664 saved = *end_of_object_name;
2665 *end_of_object_name = '\0';
4a93b899 2666 status = repo_get_oid(r, bol, &commit_oid);
d859dcad
JS
2667 if (status < 0)
2668 error(_("could not parse '%s'"), bol); /* return later */
043a4492
RR
2669 *end_of_object_name = saved;
2670
6ad656db
AG
2671 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2672 item->arg_offset = bol - buf;
2673 item->arg_len = (int)(eol - bol);
c22f7dfb 2674
043a4492 2675 if (status < 0)
d859dcad 2676 return status;
043a4492 2677
005af339 2678 item->commit = lookup_commit_reference(r, &commit_oid);
d859dcad 2679 return item->commit ? 0 : -1;
043a4492
RR
2680}
2681
c9f7b1e8 2682int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
4a72486d 2683{
ed5b1ca1 2684 const char *todo_file, *bol;
4a72486d 2685 struct strbuf buf = STRBUF_INIT;
ed5b1ca1 2686 int ret = 0;
4a72486d
PW
2687
2688 todo_file = git_path_todo_file();
2689 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
ed5b1ca1 2690 if (errno == ENOENT || errno == ENOTDIR)
4a72486d
PW
2691 return -1;
2692 else
2693 return error_errno("unable to open '%s'", todo_file);
2694 }
ed5b1ca1
PW
2695 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2696 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
4a72486d 2697 *action = REPLAY_PICK;
ed5b1ca1
PW
2698 else if (is_command(TODO_REVERT, &bol) &&
2699 (*bol == ' ' || *bol == '\t'))
4a72486d
PW
2700 *action = REPLAY_REVERT;
2701 else
ed5b1ca1 2702 ret = -1;
4a72486d 2703
4a72486d
PW
2704 strbuf_release(&buf);
2705
2706 return ret;
2707}
2708
5d94d545
AG
2709int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2710 struct todo_list *todo_list)
043a4492 2711{
004fefa7
JS
2712 struct todo_item *item;
2713 char *p = buf, *next_p;
6e98de72 2714 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
043a4492 2715
170eea97 2716 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2b71595d 2717
004fefa7 2718 for (i = 1; *p; i++, p = next_p) {
043a4492 2719 char *eol = strchrnul(p, '\n');
004fefa7
JS
2720
2721 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2722
6307041d
JS
2723 if (p != eol && eol[-1] == '\r')
2724 eol--; /* strip Carriage Return */
2725
004fefa7
JS
2726 item = append_new_todo(todo_list);
2727 item->offset_in_buf = p - todo_list->buf.buf;
6ad656db 2728 if (parse_insn_line(r, item, buf, p, eol)) {
93b3df6f 2729 res = error(_("invalid line %d: %.*s"),
004fefa7 2730 i, (int)(eol - p), p);
2b71595d 2731 item->command = TODO_COMMENT + 1;
6ad656db 2732 item->arg_offset = p - buf;
2b71595d
AG
2733 item->arg_len = (int)(eol - p);
2734 item->commit = NULL;
004fefa7 2735 }
6e98de72 2736
170eea97
JS
2737 if (item->command != TODO_COMMENT)
2738 todo_list->total_nr++;
2739
6e98de72
JS
2740 if (fixup_okay)
2741 ; /* do nothing */
2742 else if (is_fixup(item->command))
9645a087 2743 res = error(_("cannot '%s' without a previous commit"),
6e98de72
JS
2744 command_to_string(item->command));
2745 else if (!is_noop(item->command))
2746 fixup_okay = 1;
043a4492 2747 }
52865279 2748
004fefa7 2749 return res;
043a4492
RR
2750}
2751
968492e4
JS
2752static int count_commands(struct todo_list *todo_list)
2753{
2754 int count = 0, i;
2755
2756 for (i = 0; i < todo_list->nr; i++)
2757 if (todo_list->items[i].command != TODO_COMMENT)
2758 count++;
2759
2760 return count;
2761}
2762
a01c2a5f
JS
2763static int get_item_line_offset(struct todo_list *todo_list, int index)
2764{
2765 return index < todo_list->nr ?
2766 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2767}
2768
2769static const char *get_item_line(struct todo_list *todo_list, int index)
2770{
2771 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2772}
2773
2774static int get_item_line_length(struct todo_list *todo_list, int index)
2775{
2776 return get_item_line_offset(todo_list, index + 1)
2777 - get_item_line_offset(todo_list, index);
2778}
2779
87805600
RS
2780static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2781{
2782 int fd;
2783 ssize_t len;
2784
2785 fd = open(path, O_RDONLY);
2786 if (fd < 0)
2787 return error_errno(_("could not open '%s'"), path);
2788 len = strbuf_read(sb, fd, 0);
2789 close(fd);
2790 if (len < 0)
2791 return error(_("could not read '%s'."), path);
2792 return len;
2793}
2794
b07d9bfd
PW
2795static int have_finished_the_last_pick(void)
2796{
2797 struct strbuf buf = STRBUF_INIT;
2798 const char *eol;
2799 const char *todo_path = git_path_todo_file();
2800 int ret = 0;
2801
2802 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2803 if (errno == ENOENT) {
2804 return 0;
2805 } else {
2806 error_errno("unable to open '%s'", todo_path);
2807 return 0;
2808 }
2809 }
2810 /* If there is only one line then we are done */
2811 eol = strchr(buf.buf, '\n');
2812 if (!eol || !eol[1])
2813 ret = 1;
2814
2815 strbuf_release(&buf);
2816
2817 return ret;
2818}
2819
f496b064 2820void sequencer_post_commit_cleanup(struct repository *r, int verbose)
b07d9bfd
PW
2821{
2822 struct replay_opts opts = REPLAY_OPTS_INIT;
2823 int need_cleanup = 0;
2824
c8e4159e
HWN
2825 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2826 if (!refs_delete_ref(get_main_ref_store(r), "",
821f6632 2827 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
c8e4159e 2828 verbose)
f496b064 2829 warning(_("cancelling a cherry picking in progress"));
b07d9bfd
PW
2830 opts.action = REPLAY_PICK;
2831 need_cleanup = 1;
2832 }
2833
b8825ef2
HWN
2834 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2835 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
821f6632 2836 NULL, REF_NO_DEREF) &&
b8825ef2 2837 verbose)
f496b064 2838 warning(_("cancelling a revert in progress"));
b07d9bfd
PW
2839 opts.action = REPLAY_REVERT;
2840 need_cleanup = 1;
2841 }
2842
fd7c6ffa
PS
2843 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2844 NULL, REF_NO_DEREF);
5291828d 2845
b07d9bfd
PW
2846 if (!need_cleanup)
2847 return;
2848
2849 if (!have_finished_the_last_pick())
2850 return;
2851
2852 sequencer_remove_state(&opts);
2853}
2854
3f34f2d8
AG
2855static void todo_list_write_total_nr(struct todo_list *todo_list)
2856{
2857 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2858
2859 if (f) {
2860 fprintf(f, "%d\n", todo_list->total_nr);
2861 fclose(f);
2862 }
2863}
2864
005af339
NTND
2865static int read_populate_todo(struct repository *r,
2866 struct todo_list *todo_list,
2867 struct replay_opts *opts)
043a4492 2868{
c0246501 2869 const char *todo_file = get_todo_path(opts);
87805600 2870 int res;
043a4492 2871
004fefa7 2872 strbuf_reset(&todo_list->buf);
87805600
RS
2873 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2874 return -1;
043a4492 2875
5d94d545 2876 res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
27fdbb96
JS
2877 if (res) {
2878 if (is_rebase_i(opts))
2879 return error(_("please fix this using "
2880 "'git rebase --edit-todo'."));
93b3df6f 2881 return error(_("unusable instruction sheet: '%s'"), todo_file);
27fdbb96 2882 }
2eeaf1b3 2883
52865279
JS
2884 if (!todo_list->nr &&
2885 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2886 return error(_("no commits parsed."));
2887
2eeaf1b3 2888 if (!is_rebase_i(opts)) {
004fefa7
JS
2889 enum todo_command valid =
2890 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2891 int i;
2892
2893 for (i = 0; i < todo_list->nr; i++)
2894 if (valid == todo_list->items[i].command)
2895 continue;
2896 else if (valid == TODO_PICK)
93b3df6f 2897 return error(_("cannot cherry-pick during a revert."));
004fefa7 2898 else
93b3df6f 2899 return error(_("cannot revert during a cherry-pick."));
004fefa7
JS
2900 }
2901
968492e4
JS
2902 if (is_rebase_i(opts)) {
2903 struct todo_list done = TODO_LIST_INIT;
2904
2905 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
5d94d545 2906 !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
968492e4
JS
2907 todo_list->done_nr = count_commands(&done);
2908 else
2909 todo_list->done_nr = 0;
2910
2911 todo_list->total_nr = todo_list->done_nr
2912 + count_commands(todo_list);
968492e4 2913 todo_list_release(&done);
ef80069a 2914
3f34f2d8 2915 todo_list_write_total_nr(todo_list);
968492e4
JS
2916 }
2917
0ae42a03 2918 return 0;
043a4492
RR
2919}
2920
03a4e260
JS
2921static int git_config_string_dup(char **dest,
2922 const char *var, const char *value)
2923{
2924 if (!value)
2925 return config_error_nonbool(var);
2926 free(*dest);
2927 *dest = xstrdup(value);
2928 return 0;
2929}
2930
a4e7e317 2931static int populate_opts_cb(const char *key, const char *value,
8868b1eb 2932 const struct config_context *ctx,
a4e7e317 2933 void *data)
043a4492
RR
2934{
2935 struct replay_opts *opts = data;
2936 int error_flag = 1;
2937
2938 if (!value)
2939 error_flag = 0;
2940 else if (!strcmp(key, "options.no-commit"))
8868b1eb 2941 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 2942 else if (!strcmp(key, "options.edit"))
8868b1eb 2943 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
2944 else if (!strcmp(key, "options.allow-empty"))
2945 opts->allow_empty =
8868b1eb 2946 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
2947 else if (!strcmp(key, "options.allow-empty-message"))
2948 opts->allow_empty_message =
8868b1eb 2949 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
ec79d763
BL
2950 else if (!strcmp(key, "options.drop-redundant-commits"))
2951 opts->drop_redundant_commits =
2952 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
6860ce5d
PW
2953 else if (!strcmp(key, "options.keep-redundant-commits"))
2954 opts->keep_redundant_commits =
8868b1eb 2955 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 2956 else if (!strcmp(key, "options.signoff"))
8868b1eb 2957 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 2958 else if (!strcmp(key, "options.record-origin"))
8868b1eb 2959 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 2960 else if (!strcmp(key, "options.allow-ff"))
8868b1eb 2961 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
043a4492 2962 else if (!strcmp(key, "options.mainline"))
8868b1eb 2963 opts->mainline = git_config_int(key, value, ctx->kvi);
043a4492 2964 else if (!strcmp(key, "options.strategy"))
03a4e260 2965 git_config_string_dup(&opts->strategy, key, value);
3253553e 2966 else if (!strcmp(key, "options.gpg-sign"))
03a4e260 2967 git_config_string_dup(&opts->gpg_sign, key, value);
043a4492 2968 else if (!strcmp(key, "options.strategy-option")) {
fb60b9f3 2969 strvec_push(&opts->xopts, value);
8d8cb4b0
PW
2970 } else if (!strcmp(key, "options.allow-rerere-auto"))
2971 opts->allow_rerere_auto =
8868b1eb 2972 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
8d8cb4b0 2973 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
dc42e9a8
PW
2974 else if (!strcmp(key, "options.default-msg-cleanup")) {
2975 opts->explicit_cleanup = 1;
2976 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2977 } else
93b3df6f 2978 return error(_("invalid key: %s"), key);
043a4492
RR
2979
2980 if (!error_flag)
1a8aea85 2981 return error(_("invalid value for '%s': '%s'"), key, value);
043a4492
RR
2982
2983 return 0;
2984}
2985
4a8bc986 2986static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
ca6c6b45
JS
2987{
2988 int i;
15a4cc91 2989 int count;
fb60b9f3 2990 const char **argv;
65850686 2991 char *strategy_opts_string = raw_opts;
ca6c6b45 2992
0060041d
EN
2993 if (*strategy_opts_string == ' ')
2994 strategy_opts_string++;
65850686 2995
fb60b9f3 2996 count = split_cmdline(strategy_opts_string, &argv);
15a4cc91 2997 if (count < 0)
4960e5c7 2998 BUG("could not split '%s': %s", strategy_opts_string,
15a4cc91 2999 split_cmdline_strerror(count));
fb60b9f3
PW
3000 for (i = 0; i < count; i++) {
3001 const char *arg = argv[i];
ca6c6b45
JS
3002
3003 skip_prefix(arg, "--", &arg);
fb60b9f3 3004 strvec_push(&opts->xopts, arg);
ca6c6b45 3005 }
fb60b9f3 3006 free(argv);
ca6c6b45
JS
3007}
3008
65850686
AG
3009static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3010{
3011 strbuf_reset(buf);
3012 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3013 return;
3014 opts->strategy = strbuf_detach(buf, NULL);
3015 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3016 return;
3017
3018 parse_strategy_opts(opts, buf->buf);
3019}
3020
5adf9bdc 3021static int read_populate_opts(struct replay_opts *opts)
043a4492 3022{
a1c75762
JS
3023 if (is_rebase_i(opts)) {
3024 struct strbuf buf = STRBUF_INIT;
65c425a2 3025 int ret = 0;
a1c75762 3026
3442c3d1
DL
3027 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3028 READ_ONELINER_SKIP_IF_EMPTY)) {
a1c75762
JS
3029 if (!starts_with(buf.buf, "-S"))
3030 strbuf_reset(&buf);
3031 else {
3032 free(opts->gpg_sign);
3033 opts->gpg_sign = xstrdup(buf.buf + 2);
3034 }
9b6d7a62
PW
3035 strbuf_reset(&buf);
3036 }
3037
3442c3d1
DL
3038 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3039 READ_ONELINER_SKIP_IF_EMPTY)) {
9b6d7a62
PW
3040 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3041 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3042 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3043 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3044 strbuf_reset(&buf);
a1c75762 3045 }
a1c75762 3046
556907f1
JS
3047 if (file_exists(rebase_path_verbose()))
3048 opts->verbose = 1;
3049
899b49c4
EN
3050 if (file_exists(rebase_path_quiet()))
3051 opts->quiet = 1;
3052
a852ec7f
PW
3053 if (file_exists(rebase_path_signoff())) {
3054 opts->allow_ff = 0;
3055 opts->signoff = 1;
3056 }
3057
7573cec5
PW
3058 if (file_exists(rebase_path_cdate_is_adate())) {
3059 opts->allow_ff = 0;
3060 opts->committer_date_is_author_date = 1;
3061 }
3062
a3894aad
PW
3063 if (file_exists(rebase_path_ignore_date())) {
3064 opts->allow_ff = 0;
3065 opts->ignore_date = 1;
3066 }
3067
d421afa0
JS
3068 if (file_exists(rebase_path_reschedule_failed_exec()))
3069 opts->reschedule_failed_exec = 1;
e5b32bff
ÆAB
3070 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3071 opts->reschedule_failed_exec = 0;
d421afa0 3072
e98c4269
EN
3073 if (file_exists(rebase_path_drop_redundant_commits()))
3074 opts->drop_redundant_commits = 1;
3075
3076 if (file_exists(rebase_path_keep_redundant_commits()))
3077 opts->keep_redundant_commits = 1;
3078
ca6c6b45 3079 read_strategy_opts(opts, &buf);
65c425a2 3080 strbuf_reset(&buf);
ca6c6b45 3081
e12a7ef5 3082 if (read_oneliner(&opts->current_fixups,
3442c3d1
DL
3083 rebase_path_current_fixups(),
3084 READ_ONELINER_SKIP_IF_EMPTY)) {
e12a7ef5
JS
3085 const char *p = opts->current_fixups.buf;
3086 opts->current_fixup_count = 1;
3087 while ((p = strchr(p, '\n'))) {
3088 opts->current_fixup_count++;
3089 p++;
3090 }
3091 }
3092
d87d48b2 3093 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
d850b7a5 3094 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
65c425a2
DL
3095 ret = error(_("unusable squash-onto"));
3096 goto done_rebase_i;
3097 }
d87d48b2
JS
3098 opts->have_squash_onto = 1;
3099 }
3100
65c425a2
DL
3101done_rebase_i:
3102 strbuf_release(&buf);
3103 return ret;
a1c75762 3104 }
b5a67045 3105
f932729c 3106 if (!file_exists(git_path_opts_file()))
0d00da7b
JS
3107 return 0;
3108 /*
3109 * The function git_parse_source(), called from git_config_from_file(),
3110 * may die() in case of a syntactically incorrect file. We do not care
3111 * about this case, though, because we wrote that file ourselves, so we
3112 * are pretty certain that it is syntactically correct.
3113 */
5adf9bdc 3114 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
93b3df6f 3115 return error(_("malformed options sheet: '%s'"),
0d00da7b
JS
3116 git_path_opts_file());
3117 return 0;
043a4492
RR
3118}
3119
65850686
AG
3120static void write_strategy_opts(struct replay_opts *opts)
3121{
65850686
AG
3122 struct strbuf buf = STRBUF_INIT;
3123
4960e5c7
PW
3124 /*
3125 * Quote strategy options so that they can be read correctly
3126 * by split_cmdline().
3127 */
3128 quote_cmdline(&buf, opts->xopts.v);
65850686
AG
3129 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3130 strbuf_release(&buf);
3131}
3132
3133int write_basic_state(struct replay_opts *opts, const char *head_name,
a2bb10d0 3134 struct commit *onto, const struct object_id *orig_head)
65850686 3135{
65850686
AG
3136 if (head_name)
3137 write_file(rebase_path_head_name(), "%s\n", head_name);
3138 if (onto)
7d3488eb
PW
3139 write_file(rebase_path_onto(), "%s\n",
3140 oid_to_hex(&onto->object.oid));
65850686 3141 if (orig_head)
a2bb10d0
PW
3142 write_file(rebase_path_orig_head(), "%s\n",
3143 oid_to_hex(orig_head));
65850686 3144
8a997ed1
EN
3145 if (opts->quiet)
3146 write_file(rebase_path_quiet(), "%s", "");
65850686 3147 if (opts->verbose)
4af51741 3148 write_file(rebase_path_verbose(), "%s", "");
65850686
AG
3149 if (opts->strategy)
3150 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
fb60b9f3 3151 if (opts->xopts.nr > 0)
65850686
AG
3152 write_strategy_opts(opts);
3153
3154 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3155 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3156 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3157 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3158
3159 if (opts->gpg_sign)
3160 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3161 if (opts->signoff)
3162 write_file(rebase_path_signoff(), "--signoff\n");
e98c4269
EN
3163 if (opts->drop_redundant_commits)
3164 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3165 if (opts->keep_redundant_commits)
3166 write_file(rebase_path_keep_redundant_commits(), "%s", "");
7573cec5
PW
3167 if (opts->committer_date_is_author_date)
3168 write_file(rebase_path_cdate_is_adate(), "%s", "");
a3894aad
PW
3169 if (opts->ignore_date)
3170 write_file(rebase_path_ignore_date(), "%s", "");
d421afa0
JS
3171 if (opts->reschedule_failed_exec)
3172 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
e5b32bff
ÆAB
3173 else
3174 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
65850686
AG
3175
3176 return 0;
3177}
3178
004fefa7 3179static int walk_revs_populate_todo(struct todo_list *todo_list,
043a4492
RR
3180 struct replay_opts *opts)
3181{
004fefa7
JS
3182 enum todo_command command = opts->action == REPLAY_PICK ?
3183 TODO_PICK : TODO_REVERT;
414697a9 3184 const char *command_string = todo_command_info[command].str;
019a9d83 3185 const char *encoding;
043a4492 3186 struct commit *commit;
043a4492 3187
34b0528b
JS
3188 if (prepare_revs(opts))
3189 return -1;
043a4492 3190
019a9d83
ĐTCD
3191 encoding = get_log_output_encoding();
3192
004fefa7
JS
3193 while ((commit = get_revision(opts->revs))) {
3194 struct todo_item *item = append_new_todo(todo_list);
ecb5091f
ÆAB
3195 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3196 commit, NULL,
3197 encoding);
004fefa7
JS
3198 const char *subject;
3199 int subject_len;
3200
3201 item->command = command;
3202 item->commit = commit;
6ad656db 3203 item->arg_offset = 0;
c22f7dfb 3204 item->arg_len = 0;
004fefa7
JS
3205 item->offset_in_buf = todo_list->buf.len;
3206 subject_len = find_commit_subject(commit_buffer, &subject);
3207 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
cb646ffb
JK
3208 short_commit_name(the_repository, commit),
3209 subject_len, subject);
ecb5091f
ÆAB
3210 repo_unuse_commit_buffer(the_repository, commit,
3211 commit_buffer);
004fefa7 3212 }
8530c739
JK
3213
3214 if (!todo_list->nr)
3215 return error(_("empty commit set passed"));
3216
34b0528b 3217 return 0;
043a4492
RR
3218}
3219
6a1f9046 3220static int create_seq_dir(struct repository *r)
043a4492 3221{
6a1f9046
RA
3222 enum replay_action action;
3223 const char *in_progress_error = NULL;
3224 const char *in_progress_advice = NULL;
c8e4159e 3225 unsigned int advise_skip =
b8825ef2 3226 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
c8e4159e 3227 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
6a1f9046
RA
3228
3229 if (!sequencer_get_last_command(r, &action)) {
3230 switch (action) {
3231 case REPLAY_REVERT:
3232 in_progress_error = _("revert is already in progress");
3233 in_progress_advice =
dcb500dc 3234 _("try \"git revert (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3235 break;
3236 case REPLAY_PICK:
3237 in_progress_error = _("cherry-pick is already in progress");
3238 in_progress_advice =
dcb500dc 3239 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
6a1f9046
RA
3240 break;
3241 default:
3242 BUG("unexpected action in create_seq_dir");
3243 }
3244 }
3245 if (in_progress_error) {
3246 error("%s", in_progress_error);
ed9bff08 3247 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
dcb500dc
RA
3248 advise(in_progress_advice,
3249 advise_skip ? "--skip | " : "");
043a4492 3250 return -1;
6a1f9046
RA
3251 }
3252 if (mkdir(git_path_seq_dir(), 0777) < 0)
93b3df6f 3253 return error_errno(_("could not create sequencer directory '%s'"),
f6e82b0d 3254 git_path_seq_dir());
6a1f9046 3255
043a4492
RR
3256 return 0;
3257}
3258
311fd397 3259static int save_head(const char *head)
043a4492 3260{
54dbd093 3261 return write_message(head, strlen(head), git_path_head_file(), 1);
043a4492
RR
3262}
3263
1e41229d
SB
3264static int rollback_is_safe(void)
3265{
3266 struct strbuf sb = STRBUF_INIT;
3267 struct object_id expected_head, actual_head;
3268
3269 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3270 strbuf_trim(&sb);
3271 if (get_oid_hex(sb.buf, &expected_head)) {
3272 strbuf_release(&sb);
3273 die(_("could not parse %s"), git_path_abort_safety_file());
3274 }
3275 strbuf_release(&sb);
3276 }
3277 else if (errno == ENOENT)
3278 oidclr(&expected_head);
3279 else
3280 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3281
d850b7a5 3282 if (repo_get_oid(the_repository, "HEAD", &actual_head))
1e41229d
SB
3283 oidclr(&actual_head);
3284
4a7e27e9 3285 return oideq(&actual_head, &expected_head);
1e41229d
SB
3286}
3287
918d1e6e 3288static int reset_merge(const struct object_id *oid)
043a4492 3289{
0e906739 3290 struct child_process cmd = CHILD_PROCESS_INIT;
1e41229d 3291
0e906739
RS
3292 cmd.git_cmd = 1;
3293 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
265ab48f
RA
3294
3295 if (!is_null_oid(oid))
0e906739 3296 strvec_push(&cmd.args, oid_to_hex(oid));
265ab48f 3297
0e906739 3298 return run_command(&cmd);
043a4492
RR
3299}
3300
005af339 3301static int rollback_single_pick(struct repository *r)
043a4492 3302{
092bbcdf 3303 struct object_id head_oid;
043a4492 3304
c8e4159e 3305 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 3306 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 3307 return error(_("no cherry-pick or revert in progress"));
34c290a6 3308 if (read_ref_full("HEAD", 0, &head_oid, NULL))
043a4492 3309 return error(_("cannot resolve HEAD"));
092bbcdf 3310 if (is_null_oid(&head_oid))
043a4492 3311 return error(_("cannot abort from a branch yet to be born"));
918d1e6e 3312 return reset_merge(&head_oid);
043a4492
RR
3313}
3314
de81ca3f
RA
3315static int skip_single_pick(void)
3316{
3317 struct object_id head;
3318
3319 if (read_ref_full("HEAD", 0, &head, NULL))
3320 return error(_("cannot resolve HEAD"));
3321 return reset_merge(&head);
043a4492
RR
3322}
3323
005af339 3324int sequencer_rollback(struct repository *r, struct replay_opts *opts)
043a4492 3325{
043a4492 3326 FILE *f;
092bbcdf 3327 struct object_id oid;
043a4492 3328 struct strbuf buf = STRBUF_INIT;
092bbcdf 3329 const char *p;
043a4492 3330
f932729c 3331 f = fopen(git_path_head_file(), "r");
043a4492
RR
3332 if (!f && errno == ENOENT) {
3333 /*
3334 * There is no multiple-cherry-pick in progress.
3335 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3336 * a single-cherry-pick in progress, abort that.
3337 */
005af339 3338 return rollback_single_pick(r);
043a4492
RR
3339 }
3340 if (!f)
f7ed1953 3341 return error_errno(_("cannot open '%s'"), git_path_head_file());
8f309aeb 3342 if (strbuf_getline_lf(&buf, f)) {
f7ed1953 3343 error(_("cannot read '%s': %s"), git_path_head_file(),
f932729c 3344 ferror(f) ? strerror(errno) : _("unexpected end of file"));
043a4492
RR
3345 fclose(f);
3346 goto fail;
3347 }
3348 fclose(f);
092bbcdf 3349 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
043a4492 3350 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
f932729c 3351 git_path_head_file());
043a4492
RR
3352 goto fail;
3353 }
092bbcdf 3354 if (is_null_oid(&oid)) {
0f974e21
MG
3355 error(_("cannot abort from a branch yet to be born"));
3356 goto fail;
3357 }
1e41229d
SB
3358
3359 if (!rollback_is_safe()) {
3360 /* Do not error, just do not rollback */
3361 warning(_("You seem to have moved HEAD. "
3362 "Not rewinding, check your HEAD!"));
3363 } else
918d1e6e 3364 if (reset_merge(&oid))
043a4492 3365 goto fail;
043a4492 3366 strbuf_release(&buf);
2863584f 3367 return sequencer_remove_state(opts);
043a4492
RR
3368fail:
3369 strbuf_release(&buf);
3370 return -1;
3371}
3372
de81ca3f
RA
3373int sequencer_skip(struct repository *r, struct replay_opts *opts)
3374{
3375 enum replay_action action = -1;
3376 sequencer_get_last_command(r, &action);
3377
3378 /*
3379 * Check whether the subcommand requested to skip the commit is actually
3380 * in progress and that it's safe to skip the commit.
3381 *
3382 * opts->action tells us which subcommand requested to skip the commit.
3383 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3384 * action is in progress and we can skip the commit.
3385 *
3386 * Otherwise we check that the last instruction was related to the
3387 * particular subcommand we're trying to execute and barf if that's not
3388 * the case.
3389 *
3390 * Finally we check that the rollback is "safe", i.e., has the HEAD
3391 * moved? In this case, it doesn't make sense to "reset the merge" and
3392 * "skip the commit" as the user already handled this by committing. But
3393 * we'd not want to barf here, instead give advice on how to proceed. We
3394 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3395 * it gets removed when the user commits, so if it still exists we're
3396 * sure the user can't have committed before.
3397 */
3398 switch (opts->action) {
3399 case REPLAY_REVERT:
b8825ef2 3400 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
de81ca3f
RA
3401 if (action != REPLAY_REVERT)
3402 return error(_("no revert in progress"));
3403 if (!rollback_is_safe())
3404 goto give_advice;
3405 }
3406 break;
3407 case REPLAY_PICK:
c8e4159e
HWN
3408 if (!refs_ref_exists(get_main_ref_store(r),
3409 "CHERRY_PICK_HEAD")) {
de81ca3f
RA
3410 if (action != REPLAY_PICK)
3411 return error(_("no cherry-pick in progress"));
3412 if (!rollback_is_safe())
3413 goto give_advice;
3414 }
3415 break;
3416 default:
3417 BUG("unexpected action in sequencer_skip");
3418 }
3419
3420 if (skip_single_pick())
3421 return error(_("failed to skip the commit"));
3422 if (!is_directory(git_path_seq_dir()))
3423 return 0;
3424
3425 return sequencer_continue(r, opts);
3426
3427give_advice:
3428 error(_("there is nothing to skip"));
3429
ed9bff08 3430 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
de81ca3f
RA
3431 advise(_("have you committed already?\n"
3432 "try \"git %s --continue\""),
3433 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3434 }
3435 return -1;
3436}
3437
203573b0
PW
3438static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3439 int reschedule)
043a4492 3440{
14bca6c6 3441 struct lock_file todo_lock = LOCK_INIT;
004fefa7
JS
3442 const char *todo_path = get_todo_path(opts);
3443 int next = todo_list->current, offset, fd;
043a4492 3444
84583957
JS
3445 /*
3446 * rebase -i writes "git-rebase-todo" without the currently executing
3447 * command, appending it to "done" instead.
3448 */
203573b0 3449 if (is_rebase_i(opts) && !reschedule)
84583957
JS
3450 next++;
3451
004fefa7 3452 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
221675de 3453 if (fd < 0)
93b3df6f 3454 return error_errno(_("could not lock '%s'"), todo_path);
a01c2a5f 3455 offset = get_item_line_offset(todo_list, next);
004fefa7
JS
3456 if (write_in_full(fd, todo_list->buf.buf + offset,
3457 todo_list->buf.len - offset) < 0)
93b3df6f 3458 return error_errno(_("could not write to '%s'"), todo_path);
004fefa7 3459 if (commit_lock_file(&todo_lock) < 0)
350292a1 3460 return error(_("failed to finalize '%s'"), todo_path);
1df6df0c 3461
203573b0 3462 if (is_rebase_i(opts) && !reschedule && next > 0) {
a01c2a5f
JS
3463 const char *done = rebase_path_done();
3464 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3465 int ret = 0;
1df6df0c 3466
a01c2a5f
JS
3467 if (fd < 0)
3468 return 0;
3469 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3470 get_item_line_length(todo_list, next - 1))
3471 < 0)
3472 ret = error_errno(_("could not write to '%s'"), done);
3473 if (close(fd) < 0)
3474 ret = error_errno(_("failed to finalize '%s'"), done);
3475 return ret;
1df6df0c 3476 }
221675de 3477 return 0;
043a4492
RR
3478}
3479
88d5a271 3480static int save_opts(struct replay_opts *opts)
043a4492 3481{
f932729c 3482 const char *opts_file = git_path_opts_file();
88d5a271 3483 int res = 0;
043a4492
RR
3484
3485 if (opts->no_commit)
f59199d5
PW
3486 res |= git_config_set_in_file_gently(opts_file,
3487 "options.no-commit", "true");
39edfd5c
EN
3488 if (opts->edit >= 0)
3489 res |= git_config_set_in_file_gently(opts_file, "options.edit",
3490 opts->edit ? "true" : "false");
6860ce5d
PW
3491 if (opts->allow_empty)
3492 res |= git_config_set_in_file_gently(opts_file,
3493 "options.allow-empty", "true");
3494 if (opts->allow_empty_message)
3495 res |= git_config_set_in_file_gently(opts_file,
3496 "options.allow-empty-message", "true");
ec79d763
BL
3497 if (opts->drop_redundant_commits)
3498 res |= git_config_set_in_file_gently(opts_file,
3499 "options.drop-redundant-commits", "true");
6860ce5d
PW
3500 if (opts->keep_redundant_commits)
3501 res |= git_config_set_in_file_gently(opts_file,
3502 "options.keep-redundant-commits", "true");
043a4492 3503 if (opts->signoff)
f59199d5
PW
3504 res |= git_config_set_in_file_gently(opts_file,
3505 "options.signoff", "true");
043a4492 3506 if (opts->record_origin)
f59199d5
PW
3507 res |= git_config_set_in_file_gently(opts_file,
3508 "options.record-origin", "true");
043a4492 3509 if (opts->allow_ff)
f59199d5
PW
3510 res |= git_config_set_in_file_gently(opts_file,
3511 "options.allow-ff", "true");
043a4492
RR
3512 if (opts->mainline) {
3513 struct strbuf buf = STRBUF_INIT;
3514 strbuf_addf(&buf, "%d", opts->mainline);
f59199d5
PW
3515 res |= git_config_set_in_file_gently(opts_file,
3516 "options.mainline", buf.buf);
043a4492
RR
3517 strbuf_release(&buf);
3518 }
3519 if (opts->strategy)
f59199d5
PW
3520 res |= git_config_set_in_file_gently(opts_file,
3521 "options.strategy", opts->strategy);
3253553e 3522 if (opts->gpg_sign)
f59199d5
PW
3523 res |= git_config_set_in_file_gently(opts_file,
3524 "options.gpg-sign", opts->gpg_sign);
fb60b9f3
PW
3525 for (size_t i = 0; i < opts->xopts.nr; i++)
3526 res |= git_config_set_multivar_in_file_gently(opts_file,
3527 "options.strategy-option",
3528 opts->xopts.v[i], "^$", 0);
8d8cb4b0 3529 if (opts->allow_rerere_auto)
f59199d5
PW
3530 res |= git_config_set_in_file_gently(opts_file,
3531 "options.allow-rerere-auto",
3532 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3533 "true" : "false");
dc42e9a8
PW
3534
3535 if (opts->explicit_cleanup)
3536 res |= git_config_set_in_file_gently(opts_file,
3537 "options.default-msg-cleanup",
3538 describe_cleanup_mode(opts->default_msg_cleanup));
88d5a271 3539 return res;
043a4492
RR
3540}
3541
f11c9580
NTND
3542static int make_patch(struct repository *r,
3543 struct commit *commit,
3544 struct replay_opts *opts)
56dc3ab0 3545{
56dc3ab0 3546 struct rev_info log_tree_opt;
0512eabd
JH
3547 const char *subject;
3548 char hex[GIT_MAX_HEXSZ + 1];
56dc3ab0
JS
3549 int res = 0;
3550
206a78d7
PW
3551 if (!is_rebase_i(opts))
3552 BUG("make_patch should only be called when rebasing");
3553
0512eabd
JH
3554 oid_to_hex_r(hex, &commit->object.oid);
3555 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
56dc3ab0 3556 return -1;
430b75f7 3557 res |= write_rebase_head(&commit->object.oid);
56dc3ab0 3558
56dc3ab0 3559 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 3560 repo_init_revisions(r, &log_tree_opt, NULL);
56dc3ab0
JS
3561 log_tree_opt.abbrev = 0;
3562 log_tree_opt.diff = 1;
3563 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3564 log_tree_opt.disable_stdin = 1;
3565 log_tree_opt.no_commit_id = 1;
206a78d7 3566 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
56dc3ab0
JS
3567 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3568 if (!log_tree_opt.diffopt.file)
206a78d7
PW
3569 res |= error_errno(_("could not open '%s'"),
3570 rebase_path_patch());
56dc3ab0
JS
3571 else {
3572 res |= log_tree_commit(&log_tree_opt, commit);
3573 fclose(log_tree_opt.diffopt.file);
3574 }
56dc3ab0 3575
9f67899b 3576 if (!file_exists(rebase_path_message())) {
52f52e5a 3577 const char *encoding = get_commit_output_encoding();
4a93b899 3578 const char *commit_buffer = repo_logmsg_reencode(r,
ecb5091f
ÆAB
3579 commit, NULL,
3580 encoding);
56dc3ab0 3581 find_commit_subject(commit_buffer, &subject);
9f67899b 3582 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
4a93b899 3583 repo_unuse_commit_buffer(r, commit,
ecb5091f 3584 commit_buffer);
56dc3ab0 3585 }
2108fe4a 3586 release_revisions(&log_tree_opt);
56dc3ab0
JS
3587
3588 return res;
3589}
3590
3591static int intend_to_amend(void)
3592{
092bbcdf 3593 struct object_id head;
56dc3ab0
JS
3594 char *p;
3595
d850b7a5 3596 if (repo_get_oid(the_repository, "HEAD", &head))
56dc3ab0
JS
3597 return error(_("cannot read HEAD"));
3598
092bbcdf 3599 p = oid_to_hex(&head);
56dc3ab0
JS
3600 return write_message(p, strlen(p), rebase_path_amend(), 1);
3601}
3602
f11c9580
NTND
3603static int error_with_patch(struct repository *r,
3604 struct commit *commit,
3605 const char *subject, int subject_len,
3606 struct replay_opts *opts,
3607 int exit_code, int to_amend)
56dc3ab0 3608{
bc9238bb 3609 if (commit) {
f11c9580 3610 if (make_patch(r, commit, opts))
bc9238bb 3611 return -1;
5a5c5e95 3612 } else if (copy_file(rebase_path_message(),
f11c9580 3613 git_path_merge_msg(r), 0666))
bc9238bb 3614 return error(_("unable to copy '%s' to '%s'"),
f11c9580 3615 git_path_merge_msg(r), rebase_path_message());
56dc3ab0
JS
3616
3617 if (to_amend) {
3618 if (intend_to_amend())
3619 return -1;
3620
02127c63
NTND
3621 fprintf(stderr,
3622 _("You can amend the commit now, with\n"
3623 "\n"
3624 " git commit --amend %s\n"
3625 "\n"
3626 "Once you are satisfied with your changes, run\n"
3627 "\n"
3628 " git rebase --continue\n"),
3629 gpg_sign_opt_quoted(opts));
bc9238bb
PW
3630 } else if (exit_code) {
3631 if (commit)
5a5c5e95 3632 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
cb646ffb 3633 short_commit_name(r, commit), subject_len, subject);
bc9238bb
PW
3634 else
3635 /*
3636 * We don't have the hash of the parent so
3637 * just print the line from the todo file.
3638 */
5a5c5e95
JH
3639 fprintf_ln(stderr, _("Could not merge %.*s"),
3640 subject_len, subject);
bc9238bb 3641 }
56dc3ab0
JS
3642
3643 return exit_code;
3644}
3645
f11c9580
NTND
3646static int error_failed_squash(struct repository *r,
3647 struct commit *commit,
3648 struct replay_opts *opts,
3649 int subject_len,
3650 const char *subject)
6e98de72 3651{
e12a7ef5
JS
3652 if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3653 return error(_("could not copy '%s' to '%s'"),
6e98de72 3654 rebase_path_squash_msg(), rebase_path_message());
f11c9580
NTND
3655 unlink(git_path_merge_msg(r));
3656 if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
6e98de72 3657 return error(_("could not copy '%s' to '%s'"),
102de880 3658 rebase_path_message(),
f11c9580
NTND
3659 git_path_merge_msg(r));
3660 return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
6e98de72
JS
3661}
3662
f11c9580 3663static int do_exec(struct repository *r, const char *command_line)
311af526 3664{
ddbb47fd 3665 struct child_process cmd = CHILD_PROCESS_INIT;
311af526
JS
3666 int dirty, status;
3667
4d55d63b 3668 fprintf(stderr, _("Executing: %s\n"), command_line);
ddbb47fd
RS
3669 cmd.use_shell = 1;
3670 strvec_push(&cmd.args, command_line);
e4301f73 3671 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
ddbb47fd 3672 status = run_command(&cmd);
311af526
JS
3673
3674 /* force re-reading of the cache */
9c5f3ee3
ÆAB
3675 discard_index(r->index);
3676 if (repo_read_index(r) < 0)
311af526
JS
3677 return error(_("could not read index"));
3678
f11c9580 3679 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
311af526
JS
3680
3681 if (status) {
3682 warning(_("execution failed: %s\n%s"
3683 "You can fix the problem, and then run\n"
3684 "\n"
3685 " git rebase --continue\n"
3686 "\n"),
3687 command_line,
d45cbe3f 3688 dirty ? _("and made changes to the index and/or the "
b734fe49 3689 "working tree.\n") : "");
311af526
JS
3690 if (status == 127)
3691 /* command not found */
3692 status = 1;
3693 } else if (dirty) {
3694 warning(_("execution succeeded: %s\nbut "
b734fe49 3695 "left changes to the index and/or the working tree.\n"
311af526
JS
3696 "Commit or stash your changes, and then run\n"
3697 "\n"
3698 " git rebase --continue\n"
3699 "\n"), command_line);
3700 status = 1;
3701 }
3702
3703 return status;
3704}
3705
48ca53ca 3706__attribute__((format (printf, 2, 3)))
9055e401
JS
3707static int safe_append(const char *filename, const char *fmt, ...)
3708{
3709 va_list ap;
3710 struct lock_file lock = LOCK_INIT;
3711 int fd = hold_lock_file_for_update(&lock, filename,
3712 LOCK_REPORT_ON_ERROR);
3713 struct strbuf buf = STRBUF_INIT;
3714
3715 if (fd < 0)
3716 return -1;
3717
3718 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3719 error_errno(_("could not read '%s'"), filename);
3720 rollback_lock_file(&lock);
3721 return -1;
3722 }
3723 strbuf_complete(&buf, '\n');
3724 va_start(ap, fmt);
3725 strbuf_vaddf(&buf, fmt, ap);
3726 va_end(ap);
3727
3728 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3729 error_errno(_("could not write to '%s'"), filename);
3730 strbuf_release(&buf);
3731 rollback_lock_file(&lock);
3732 return -1;
3733 }
3734 if (commit_lock_file(&lock) < 0) {
3735 strbuf_release(&buf);
9055e401
JS
3736 return error(_("failed to finalize '%s'"), filename);
3737 }
3738
3739 strbuf_release(&buf);
3740 return 0;
3741}
3742
f11c9580 3743static int do_label(struct repository *r, const char *name, int len)
9055e401 3744{
f11c9580 3745 struct ref_store *refs = get_main_ref_store(r);
9055e401
JS
3746 struct ref_transaction *transaction;
3747 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3748 struct strbuf msg = STRBUF_INIT;
3749 int ret = 0;
3750 struct object_id head_oid;
3751
3752 if (len == 1 && *name == '#')
02127c63 3753 return error(_("illegal label name: '%.*s'"), len, name);
9055e401
JS
3754
3755 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
c2417d3a 3756 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
9055e401 3757
c6da34a6 3758 transaction = ref_store_transaction_begin(refs, &err);
9055e401
JS
3759 if (!transaction) {
3760 error("%s", err.buf);
3761 ret = -1;
4a93b899 3762 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
9055e401
JS
3763 error(_("could not read HEAD"));
3764 ret = -1;
3765 } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3766 NULL, 0, msg.buf, &err) < 0 ||
3767 ref_transaction_commit(transaction, &err)) {
3768 error("%s", err.buf);
3769 ret = -1;
3770 }
3771 ref_transaction_free(transaction);
3772 strbuf_release(&err);
3773 strbuf_release(&msg);
3774
3775 if (!ret)
3776 ret = safe_append(rebase_path_refs_to_delete(),
3777 "%s\n", ref_name.buf);
3778 strbuf_release(&ref_name);
3779
3780 return ret;
3781}
3782
d188a60d
PW
3783static const char *sequencer_reflog_action(struct replay_opts *opts)
3784{
3785 if (!opts->reflog_action) {
3786 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
3787 opts->reflog_action =
3788 xstrdup(opts->reflog_action ? opts->reflog_action
3789 : action_name(opts));
3790 }
3791
3792 return opts->reflog_action;
3793}
3794
48ca53ca 3795__attribute__((format (printf, 3, 4)))
9055e401 3796static const char *reflog_message(struct replay_opts *opts,
d4ac3050
ÆAB
3797 const char *sub_action, const char *fmt, ...)
3798{
3799 va_list ap;
3800 static struct strbuf buf = STRBUF_INIT;
d4ac3050
ÆAB
3801
3802 va_start(ap, fmt);
3803 strbuf_reset(&buf);
d188a60d 3804 strbuf_addstr(&buf, sequencer_reflog_action(opts));
d4ac3050
ÆAB
3805 if (sub_action)
3806 strbuf_addf(&buf, " (%s)", sub_action);
3807 if (fmt) {
3808 strbuf_addstr(&buf, ": ");
3809 strbuf_vaddf(&buf, fmt, ap);
3810 }
3811 va_end(ap);
3812
3813 return buf.buf;
3814}
9055e401 3815
688d82f2
PW
3816static struct commit *lookup_label(struct repository *r, const char *label,
3817 int len, struct strbuf *buf)
82766b29
PW
3818{
3819 struct commit *commit;
688d82f2 3820 struct object_id oid;
82766b29
PW
3821
3822 strbuf_reset(buf);
3823 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
688d82f2
PW
3824 if (!read_ref(buf->buf, &oid)) {
3825 commit = lookup_commit_object(r, &oid);
3826 } else {
82766b29
PW
3827 /* fall back to non-rewritten ref or commit */
3828 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3829 commit = lookup_commit_reference_by_name(buf->buf);
3830 }
3831
3832 if (!commit)
3833 error(_("could not resolve '%s'"), buf->buf);
3834
3835 return commit;
3836}
3837
f11c9580
NTND
3838static int do_reset(struct repository *r,
3839 const char *name, int len,
3840 struct replay_opts *opts)
9055e401
JS
3841{
3842 struct strbuf ref_name = STRBUF_INIT;
3843 struct object_id oid;
3844 struct lock_file lock = LOCK_INIT;
0c52cf8e 3845 struct tree_desc desc = { 0 };
9055e401 3846 struct tree *tree;
6e658547 3847 struct unpack_trees_options unpack_tree_opts = { 0 };
71571cd7 3848 int ret = 0;
9055e401 3849
3a95f31d 3850 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
9055e401
JS
3851 return -1;
3852
ebddf393
JS
3853 if (len == 10 && !strncmp("[new root]", name, len)) {
3854 if (!opts->have_squash_onto) {
3855 const char *hex;
3856 if (commit_tree("", 0, the_hash_algo->empty_tree,
3857 NULL, &opts->squash_onto,
3858 NULL, NULL))
3859 return error(_("writing fake root commit"));
3860 opts->have_squash_onto = 1;
3861 hex = oid_to_hex(&opts->squash_onto);
3862 if (write_message(hex, strlen(hex),
3863 rebase_path_squash_onto(), 0))
3864 return error(_("writing squash-onto"));
3865 }
3866 oidcpy(&oid, &opts->squash_onto);
3867 } else {
71571cd7 3868 int i;
82766b29 3869 struct commit *commit;
71571cd7 3870
ebddf393
JS
3871 /* Determine the length of the label */
3872 for (i = 0; i < len; i++)
3873 if (isspace(name[i]))
71571cd7
3874 break;
3875 len = i;
ebddf393 3876
688d82f2 3877 commit = lookup_label(r, name, len, &ref_name);
82766b29
PW
3878 if (!commit) {
3879 ret = -1;
0c52cf8e 3880 goto cleanup;
ebddf393 3881 }
82766b29 3882 oid = commit->object.oid;
9055e401
JS
3883 }
3884
9055e401
JS
3885 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3886 unpack_tree_opts.head_idx = 1;
f11c9580
NTND
3887 unpack_tree_opts.src_index = r->index;
3888 unpack_tree_opts.dst_index = r->index;
9055e401
JS
3889 unpack_tree_opts.fn = oneway_merge;
3890 unpack_tree_opts.merge = 1;
3891 unpack_tree_opts.update = 1;
1b5f3733 3892 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
652bd021 3893 unpack_tree_opts.skip_cache_tree_update = 1;
3f267856 3894 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
9055e401 3895
e1ff0a32 3896 if (repo_read_index_unmerged(r)) {
1c8dfc36 3897 ret = error_resolve_conflict(action_name(opts));
0c52cf8e 3898 goto cleanup;
9055e401
JS
3899 }
3900
5e575807 3901 if (!fill_tree_descriptor(r, &desc, &oid)) {
0c52cf8e
ÆAB
3902 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
3903 goto cleanup;
9055e401
JS
3904 }
3905
3906 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
0c52cf8e
ÆAB
3907 ret = -1;
3908 goto cleanup;
9055e401
JS
3909 }
3910
3911 tree = parse_tree_indirect(&oid);
aa9f6189
JS
3912 if (!tree)
3913 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
c207e9e1 3914 prime_cache_tree(r, r->index, tree);
9055e401 3915
f11c9580 3916 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
9055e401 3917 ret = error(_("could not write index"));
9055e401
JS
3918
3919 if (!ret)
3920 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3921 len, name), "HEAD", &oid,
3922 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
0c52cf8e
ÆAB
3923cleanup:
3924 free((void *)desc.buffer);
3925 if (ret < 0)
3926 rollback_lock_file(&lock);
9055e401 3927 strbuf_release(&ref_name);
6e658547 3928 clear_unpack_trees_porcelain(&unpack_tree_opts);
9055e401
JS
3929 return ret;
3930}
3931
f11c9580
NTND
3932static int do_merge(struct repository *r,
3933 struct commit *commit,
3934 const char *arg, int arg_len,
2be6b6f4 3935 int flags, int *check_todo, struct replay_opts *opts)
4c68e7dd 3936{
2be6b6f4 3937 int run_commit_flags = 0;
4c68e7dd
JS
3938 struct strbuf ref_name = STRBUF_INIT;
3939 struct commit *head_commit, *merge_commit, *i;
76e2a099 3940 struct commit_list *bases = NULL, *j;
2b6ad0f4 3941 struct commit_list *to_merge = NULL, **tail = &to_merge;
fb60b9f3 3942 const char *strategy = !opts->xopts.nr &&
14c4586c
EN
3943 (!opts->strategy ||
3944 !strcmp(opts->strategy, "recursive") ||
3945 !strcmp(opts->strategy, "ort")) ?
e145d993 3946 NULL : opts->strategy;
4c68e7dd 3947 struct merge_options o;
2b6ad0f4 3948 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4c68e7dd
JS
3949 static struct lock_file lock;
3950 const char *p;
3951
3a95f31d 3952 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4c68e7dd
JS
3953 ret = -1;
3954 goto leave_merge;
3955 }
3956
3957 head_commit = lookup_commit_reference_by_name("HEAD");
3958 if (!head_commit) {
3959 ret = error(_("cannot merge without a current revision"));
3960 goto leave_merge;
3961 }
3962
2b6ad0f4
JS
3963 /*
3964 * For octopus merges, the arg starts with the list of revisions to be
3965 * merged. The list is optionally followed by '#' and the oneline.
3966 */
3967 merge_arg_len = oneline_offset = arg_len;
3968 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3969 if (!*p)
3970 break;
3971 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3972 p += 1 + strspn(p + 1, " \t\n");
3973 oneline_offset = p - arg;
3974 break;
3975 }
3976 k = strcspn(p, " \t\n");
3977 if (!k)
3978 continue;
688d82f2 3979 merge_commit = lookup_label(r, p, k, &ref_name);
2b6ad0f4
JS
3980 if (!merge_commit) {
3981 ret = error(_("unable to parse '%.*s'"), k, p);
3982 goto leave_merge;
3983 }
3984 tail = &commit_list_insert(merge_commit, tail)->next;
3985 p += k;
3986 merge_arg_len = p - arg;
4c68e7dd
JS
3987 }
3988
2b6ad0f4
JS
3989 if (!to_merge) {
3990 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4c68e7dd
JS
3991 goto leave_merge;
3992 }
3993
9c85a1c2 3994 if (opts->have_squash_onto &&
4a7e27e9 3995 oideq(&head_commit->object.oid, &opts->squash_onto)) {
9c85a1c2
JS
3996 /*
3997 * When the user tells us to "merge" something into a
3998 * "[new root]", let's simply fast-forward to the merge head.
3999 */
4000 rollback_lock_file(&lock);
2b6ad0f4
JS
4001 if (to_merge->next)
4002 ret = error(_("octopus merge cannot be executed on "
4003 "top of a [new root]"));
4004 else
f11c9580 4005 ret = fast_forward_to(r, &to_merge->item->object.oid,
2b6ad0f4
JS
4006 &head_commit->object.oid, 0,
4007 opts);
9c85a1c2
JS
4008 goto leave_merge;
4009 }
4010
baf8ec8d
PW
4011 /*
4012 * If HEAD is not identical to the first parent of the original merge
4013 * commit, we cannot fast-forward.
4014 */
4015 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4016 oideq(&commit->parents->item->object.oid,
4017 &head_commit->object.oid);
4018
4019 /*
4020 * If any merge head is different from the original one, we cannot
4021 * fast-forward.
4022 */
4023 if (can_fast_forward) {
4024 struct commit_list *p = commit->parents->next;
4025
4026 for (j = to_merge; j && p; j = j->next, p = p->next)
4027 if (!oideq(&j->item->object.oid,
4028 &p->item->object.oid)) {
4029 can_fast_forward = 0;
4030 break;
4031 }
4032 /*
4033 * If the number of merge heads differs from the original merge
4034 * commit, we cannot fast-forward.
4035 */
4036 if (j || p)
4037 can_fast_forward = 0;
4038 }
4039
4040 if (can_fast_forward) {
4041 rollback_lock_file(&lock);
4042 ret = fast_forward_to(r, &commit->object.oid,
4043 &head_commit->object.oid, 0, opts);
4044 if (flags & TODO_EDIT_MERGE_MSG)
4045 goto fast_forward_edit;
4046
4047 goto leave_merge;
4048 }
4049
4c68e7dd 4050 if (commit) {
5772b0c7 4051 const char *encoding = get_commit_output_encoding();
4a93b899 4052 const char *message = repo_logmsg_reencode(r, commit, NULL,
ecb5091f 4053 encoding);
4c68e7dd
JS
4054 const char *body;
4055 int len;
4056
4057 if (!message) {
4058 ret = error(_("could not get commit message of '%s'"),
4059 oid_to_hex(&commit->object.oid));
4060 goto leave_merge;
4061 }
4062 write_author_script(message);
4063 find_commit_subject(message, &body);
4064 len = strlen(body);
f11c9580 4065 ret = write_message(body, len, git_path_merge_msg(r), 0);
4a93b899 4066 repo_unuse_commit_buffer(r, commit, message);
4c68e7dd
JS
4067 if (ret) {
4068 error_errno(_("could not write '%s'"),
f11c9580 4069 git_path_merge_msg(r));
4c68e7dd
JS
4070 goto leave_merge;
4071 }
4072 } else {
4073 struct strbuf buf = STRBUF_INIT;
4074 int len;
4075
4076 strbuf_addf(&buf, "author %s", git_author_info(0));
4077 write_author_script(buf.buf);
4078 strbuf_reset(&buf);
4079
4080 if (oneline_offset < arg_len) {
4081 p = arg + oneline_offset;
4082 len = arg_len - oneline_offset;
4083 } else {
2b6ad0f4
JS
4084 strbuf_addf(&buf, "Merge %s '%.*s'",
4085 to_merge->next ? "branches" : "branch",
4c68e7dd
JS
4086 merge_arg_len, arg);
4087 p = buf.buf;
4088 len = buf.len;
4089 }
4090
f11c9580 4091 ret = write_message(p, len, git_path_merge_msg(r), 0);
4c68e7dd
JS
4092 strbuf_release(&buf);
4093 if (ret) {
4094 error_errno(_("could not write '%s'"),
f11c9580 4095 git_path_merge_msg(r));
4c68e7dd
JS
4096 goto leave_merge;
4097 }
4098 }
4099
e145d993 4100 if (strategy || to_merge->next) {
2b6ad0f4
JS
4101 /* Octopus merge */
4102 struct child_process cmd = CHILD_PROCESS_INIT;
4103
29fda24d 4104 if (read_env_script(&cmd.env)) {
2b6ad0f4
JS
4105 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4106
4107 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4108 goto leave_merge;
4109 }
4110
7573cec5 4111 if (opts->committer_date_is_author_date)
29fda24d 4112 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
9c31b19d
JH
4113 opts->ignore_date ?
4114 "" :
b3193252 4115 author_date_from_env(&cmd.env));
a3894aad 4116 if (opts->ignore_date)
29fda24d 4117 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
7573cec5 4118
2b6ad0f4 4119 cmd.git_cmd = 1;
c972bf4c
JK
4120 strvec_push(&cmd.args, "merge");
4121 strvec_push(&cmd.args, "-s");
e145d993 4122 if (!strategy)
c972bf4c 4123 strvec_push(&cmd.args, "octopus");
e145d993 4124 else {
c972bf4c 4125 strvec_push(&cmd.args, strategy);
fb60b9f3 4126 for (k = 0; k < opts->xopts.nr; k++)
c972bf4c 4127 strvec_pushf(&cmd.args,
fb60b9f3 4128 "-X%s", opts->xopts.v[k]);
e145d993 4129 }
f2563c9e
PW
4130 if (!(flags & TODO_EDIT_MERGE_MSG))
4131 strvec_push(&cmd.args, "--no-edit");
4132 else
4133 strvec_push(&cmd.args, "--edit");
c972bf4c
JK
4134 strvec_push(&cmd.args, "--no-ff");
4135 strvec_push(&cmd.args, "--no-log");
4136 strvec_push(&cmd.args, "--no-stat");
4137 strvec_push(&cmd.args, "-F");
4138 strvec_push(&cmd.args, git_path_merge_msg(r));
2b6ad0f4 4139 if (opts->gpg_sign)
ae03c97a 4140 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
19dad040
4141 else
4142 strvec_push(&cmd.args, "--no-gpg-sign");
2b6ad0f4
JS
4143
4144 /* Add the tips to be merged */
4145 for (j = to_merge; j; j = j->next)
c972bf4c 4146 strvec_push(&cmd.args,
f6d8942b 4147 oid_to_hex(&j->item->object.oid));
2b6ad0f4
JS
4148
4149 strbuf_release(&ref_name);
c8e4159e 4150 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
821f6632 4151 NULL, REF_NO_DEREF);
2b6ad0f4
JS
4152 rollback_lock_file(&lock);
4153
2b6ad0f4
JS
4154 ret = run_command(&cmd);
4155
4156 /* force re-reading of the cache */
9c5f3ee3
ÆAB
4157 if (!ret) {
4158 discard_index(r->index);
4159 if (repo_read_index(r) < 0)
4160 ret = error(_("could not read index"));
4161 }
2b6ad0f4
JS
4162 goto leave_merge;
4163 }
4164
4165 merge_commit = to_merge->item;
76e2a099
JS
4166 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4167 ret = -1;
4168 goto leave_merge;
4169 }
4170
4a7e27e9
JK
4171 if (bases && oideq(&merge_commit->object.oid,
4172 &bases->item->object.oid)) {
7ccdf65b
JS
4173 ret = 0;
4174 /* skip merging an ancestor of HEAD */
4175 goto leave_merge;
4176 }
4177
4439c7a3 4178 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
cde55548
JH
4179 git_path_merge_head(r), 0);
4180 write_message("no-ff", 5, git_path_merge_mode(r), 0);
85f8d9da 4181
5327d898 4182 bases = reverse_commit_list(bases);
4c68e7dd 4183
e1ff0a32 4184 repo_read_index(r);
0d6caa2d 4185 init_merge_options(&o, r);
4c68e7dd
JS
4186 o.branch1 = "HEAD";
4187 o.branch2 = ref_name.buf;
4188 o.buffer_output = 2;
4189
6a5fb966 4190 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
14c4586c
EN
4191 /*
4192 * TODO: Should use merge_incore_recursive() and
4193 * merge_switch_to_result(), skipping the call to
4194 * merge_switch_to_result() when we don't actually need to
4195 * update the index and working copy immediately.
4196 */
4197 ret = merge_ort_recursive(&o,
5327d898 4198 head_commit, merge_commit, bases,
14c4586c
EN
4199 &i);
4200 } else {
5327d898 4201 ret = merge_recursive(&o, head_commit, merge_commit, bases,
14c4586c
EN
4202 &i);
4203 }
4c68e7dd
JS
4204 if (ret <= 0)
4205 fputs(o.obuf.buf, stdout);
4206 strbuf_release(&o.obuf);
4207 if (ret < 0) {
4208 error(_("could not even attempt to merge '%.*s'"),
4209 merge_arg_len, arg);
e032abd5 4210 unlink(git_path_merge_msg(r));
4c68e7dd
JS
4211 goto leave_merge;
4212 }
4213 /*
4214 * The return value of merge_recursive() is 1 on clean, and 0 on
4215 * unclean merge.
4216 *
4217 * Let's reverse that, so that do_merge() returns 0 upon success and
4218 * 1 upon failed merge (keeping the return value -1 for the cases where
4219 * we will want to reschedule the `merge` command).
4220 */
4221 ret = !ret;
4222
f11c9580
NTND
4223 if (r->index->cache_changed &&
4224 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4c68e7dd
JS
4225 ret = error(_("merge: Unable to write new index file"));
4226 goto leave_merge;
4227 }
4228
4229 rollback_lock_file(&lock);
4230 if (ret)
f11c9580 4231 repo_rerere(r, opts->allow_rerere_auto);
4c68e7dd
JS
4232 else
4233 /*
4234 * In case of problems, we now want to return a positive
4235 * value (a negative one would indicate that the `merge`
4236 * command needs to be rescheduled).
4237 */
20f4b044 4238 ret = !!run_git_commit(git_path_merge_msg(r), opts,
f11c9580 4239 run_commit_flags);
4c68e7dd 4240
2be6b6f4
PW
4241 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4242 fast_forward_edit:
4243 *check_todo = 1;
4244 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4245 ret = !!run_git_commit(NULL, opts, run_commit_flags);
4246 }
4247
4248
4c68e7dd
JS
4249leave_merge:
4250 strbuf_release(&ref_name);
4251 rollback_lock_file(&lock);
2b6ad0f4 4252 free_commit_list(to_merge);
4c68e7dd
JS
4253 return ret;
4254}
4255
89fc0b53
DS
4256static int write_update_refs_state(struct string_list *refs_to_oids)
4257{
4258 int result = 0;
4259 struct lock_file lock = LOCK_INIT;
4260 FILE *fp = NULL;
4261 struct string_list_item *item;
4262 char *path;
4263
89fc0b53
DS
4264 path = rebase_path_update_refs(the_repository->gitdir);
4265
44da9e08
VD
4266 if (!refs_to_oids->nr) {
4267 if (unlink(path) && errno != ENOENT)
4268 result = error_errno(_("could not unlink: %s"), path);
4269 goto cleanup;
4270 }
4271
89fc0b53
DS
4272 if (safe_create_leading_directories(path)) {
4273 result = error(_("unable to create leading directories of %s"),
4274 path);
4275 goto cleanup;
4276 }
4277
4278 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4279 result = error(_("another 'rebase' process appears to be running; "
4280 "'%s.lock' already exists"),
4281 path);
4282 goto cleanup;
4283 }
4284
4285 fp = fdopen_lock_file(&lock, "w");
4286 if (!fp) {
4287 result = error_errno(_("could not open '%s' for writing"), path);
4288 rollback_lock_file(&lock);
4289 goto cleanup;
4290 }
4291
4292 for_each_string_list_item(item, refs_to_oids) {
4293 struct update_ref_record *rec = item->util;
4294 fprintf(fp, "%s\n%s\n%s\n", item->string,
4295 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4296 }
4297
4298 result = commit_lock_file(&lock);
4299
4300cleanup:
4301 free(path);
4302 return result;
4303}
4304
b3b1a21d
DS
4305/*
4306 * Parse the update-refs file for the current rebase, then remove the
4307 * refs that do not appear in the todo_list (and have not had updated
4308 * values stored) and add refs that are in the todo_list but not
4309 * represented in the update-refs file.
4310 *
4311 * If there are changes to the update-refs list, then write the new state
4312 * to disk.
4313 */
4314void todo_list_filter_update_refs(struct repository *r,
4315 struct todo_list *todo_list)
4316{
4317 int i;
4318 int updated = 0;
4319 struct string_list update_refs = STRING_LIST_INIT_DUP;
4320
4321 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4322
4323 /*
4324 * For each item in the update_refs list, if it has no updated
4325 * value and does not appear in the todo_list, then remove it
4326 * from the update_refs list.
4327 */
4328 for (i = 0; i < update_refs.nr; i++) {
4329 int j;
4330 int found = 0;
4331 const char *ref = update_refs.items[i].string;
4332 size_t reflen = strlen(ref);
4333 struct update_ref_record *rec = update_refs.items[i].util;
4334
4335 /* OID already stored as updated. */
4336 if (!is_null_oid(&rec->after))
4337 continue;
4338
fa5103dd 4339 for (j = 0; !found && j < todo_list->nr; j++) {
b3b1a21d
DS
4340 struct todo_item *item = &todo_list->items[j];
4341 const char *arg = todo_list->buf.buf + item->arg_offset;
4342
4343 if (item->command != TODO_UPDATE_REF)
4344 continue;
4345
4346 if (item->arg_len != reflen ||
4347 strncmp(arg, ref, reflen))
4348 continue;
4349
4350 found = 1;
4351 }
4352
4353 if (!found) {
4354 free(update_refs.items[i].string);
4355 free(update_refs.items[i].util);
4356
4357 update_refs.nr--;
4358 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4359
4360 updated = 1;
4361 i--;
4362 }
4363 }
4364
4365 /*
4366 * For each todo_item, check if its ref is in the update_refs list.
4367 * If not, then add it as an un-updated ref.
4368 */
fa5103dd 4369 for (i = 0; i < todo_list->nr; i++) {
b3b1a21d
DS
4370 struct todo_item *item = &todo_list->items[i];
4371 const char *arg = todo_list->buf.buf + item->arg_offset;
4372 int j, found = 0;
4373
4374 if (item->command != TODO_UPDATE_REF)
4375 continue;
4376
4377 for (j = 0; !found && j < update_refs.nr; j++) {
4378 const char *ref = update_refs.items[j].string;
4379
4380 found = strlen(ref) == item->arg_len &&
4381 !strncmp(ref, arg, item->arg_len);
4382 }
4383
4384 if (!found) {
4385 struct string_list_item *inserted;
4386 struct strbuf argref = STRBUF_INIT;
4387
4388 strbuf_add(&argref, arg, item->arg_len);
4389 inserted = string_list_insert(&update_refs, argref.buf);
4390 inserted->util = init_update_ref_record(argref.buf);
4391 strbuf_release(&argref);
4392 updated = 1;
4393 }
4394 }
4395
4396 if (updated)
4397 write_update_refs_state(&update_refs);
4398 string_list_clear(&update_refs, 1);
4399}
4400
89fc0b53 4401static int do_update_ref(struct repository *r, const char *refname)
a97d7916 4402{
89fc0b53
DS
4403 struct string_list_item *item;
4404 struct string_list list = STRING_LIST_INIT_DUP;
4405
4406 if (sequencer_get_update_refs_state(r->gitdir, &list))
4407 return -1;
4408
4409 for_each_string_list_item(item, &list) {
4410 if (!strcmp(item->string, refname)) {
4411 struct update_ref_record *rec = item->util;
4412 if (read_ref("HEAD", &rec->after))
4413 return -1;
4414 break;
4415 }
4416 }
4417
4418 write_update_refs_state(&list);
4419 string_list_clear(&list, 1);
a97d7916
DS
4420 return 0;
4421}
4422
4611884e 4423static int do_update_refs(struct repository *r, int quiet)
89fc0b53
DS
4424{
4425 int res = 0;
4426 struct string_list_item *item;
4427 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4428 struct ref_store *refs = get_main_ref_store(r);
4611884e
DS
4429 struct strbuf update_msg = STRBUF_INIT;
4430 struct strbuf error_msg = STRBUF_INIT;
89fc0b53
DS
4431
4432 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4433 return res;
4434
4435 for_each_string_list_item(item, &refs_to_oids) {
4436 struct update_ref_record *rec = item->util;
4611884e 4437 int loop_res;
89fc0b53 4438
4611884e
DS
4439 loop_res = refs_update_ref(refs, "rewritten during rebase",
4440 item->string,
4441 &rec->after, &rec->before,
4442 0, UPDATE_REFS_MSG_ON_ERR);
4443 res |= loop_res;
4444
4445 if (quiet)
4446 continue;
4447
4448 if (loop_res)
4449 strbuf_addf(&error_msg, "\t%s\n", item->string);
4450 else
4451 strbuf_addf(&update_msg, "\t%s\n", item->string);
4452 }
4453
4454 if (!quiet &&
4455 (update_msg.len || error_msg.len)) {
4456 fprintf(stderr,
4457 _("Updated the following refs with %s:\n%s"),
4458 "--update-refs",
4459 update_msg.buf);
4460
4461 if (res)
4462 fprintf(stderr,
4463 _("Failed to update the following refs with %s:\n%s"),
4464 "--update-refs",
4465 error_msg.buf);
89fc0b53
DS
4466 }
4467
4468 string_list_clear(&refs_to_oids, 1);
4611884e
DS
4469 strbuf_release(&update_msg);
4470 strbuf_release(&error_msg);
89fc0b53
DS
4471 return res;
4472}
4473
6e98de72
JS
4474static int is_final_fixup(struct todo_list *todo_list)
4475{
4476 int i = todo_list->current;
4477
4478 if (!is_fixup(todo_list->items[i].command))
4479 return 0;
4480
4481 while (++i < todo_list->nr)
4482 if (is_fixup(todo_list->items[i].command))
4483 return 0;
4484 else if (!is_noop(todo_list->items[i].command))
4485 break;
4486 return 1;
4487}
4488
25cb8df9
JS
4489static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4490{
4491 int i;
4492
4493 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4494 if (!is_noop(todo_list->items[i].command))
4495 return todo_list->items[i].command;
4496
4497 return -1;
4498}
4499
35122dae
PS
4500static void create_autostash_internal(struct repository *r,
4501 const char *path,
4502 const char *refname)
0816f1df
DL
4503{
4504 struct strbuf buf = STRBUF_INIT;
4505 struct lock_file lock_file = LOCK_INIT;
4506 int fd;
4507
35122dae
PS
4508 if (path && refname)
4509 BUG("can only pass path or refname");
4510
0816f1df
DL
4511 fd = repo_hold_locked_index(r, &lock_file, 0);
4512 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4513 if (0 <= fd)
4514 repo_update_index_if_able(r, &lock_file);
4515 rollback_lock_file(&lock_file);
4516
4517 if (has_unstaged_changes(r, 1) ||
4518 has_uncommitted_changes(r, 1)) {
4519 struct child_process stash = CHILD_PROCESS_INIT;
6ae80861 4520 struct reset_head_opts ropts = { .flags = RESET_HEAD_HARD };
0816f1df
DL
4521 struct object_id oid;
4522
c972bf4c 4523 strvec_pushl(&stash.args,
f6d8942b 4524 "stash", "create", "autostash", NULL);
0816f1df
DL
4525 stash.git_cmd = 1;
4526 stash.no_stdin = 1;
4527 strbuf_reset(&buf);
4528 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4529 die(_("Cannot autostash"));
4530 strbuf_trim_trailing_newline(&buf);
4a93b899 4531 if (repo_get_oid(r, buf.buf, &oid))
0816f1df
DL
4532 die(_("Unexpected stash response: '%s'"),
4533 buf.buf);
4534 strbuf_reset(&buf);
4535 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4536
35122dae
PS
4537 if (path) {
4538 if (safe_create_leading_directories_const(path))
4539 die(_("Could not create directory for '%s'"),
4540 path);
4541 write_file(path, "%s", oid_to_hex(&oid));
4542 } else {
4543 refs_update_ref(get_main_ref_store(r), "", refname,
4544 &oid, null_oid(), 0, UPDATE_REFS_DIE_ON_ERR);
4545 }
4546
0816f1df 4547 printf(_("Created autostash: %s\n"), buf.buf);
6ae80861 4548 if (reset_head(r, &ropts) < 0)
0816f1df 4549 die(_("could not reset --hard"));
9c5f3ee3
ÆAB
4550 discard_index(r->index);
4551 if (repo_read_index(r) < 0)
0816f1df
DL
4552 die(_("could not read index"));
4553 }
4554 strbuf_release(&buf);
4555}
4556
35122dae
PS
4557void create_autostash(struct repository *r, const char *path)
4558{
4559 create_autostash_internal(r, path, NULL);
4560}
4561
4562void create_autostash_ref(struct repository *r, const char *refname)
4563{
4564 create_autostash_internal(r, NULL, refname);
4565}
4566
804fe315 4567static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
796c7972 4568{
796c7972
JS
4569 struct child_process child = CHILD_PROCESS_INIT;
4570 int ret = 0;
4571
12b6e136
DL
4572 if (attempt_apply) {
4573 child.git_cmd = 1;
4574 child.no_stdout = 1;
4575 child.no_stderr = 1;
c972bf4c
JK
4576 strvec_push(&child.args, "stash");
4577 strvec_push(&child.args, "apply");
4578 strvec_push(&child.args, stash_oid);
12b6e136 4579 ret = run_command(&child);
796c7972 4580 }
796c7972 4581
12b6e136 4582 if (attempt_apply && !ret)
cdb866b3 4583 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
4584 else {
4585 struct child_process store = CHILD_PROCESS_INIT;
4586
4587 store.git_cmd = 1;
c972bf4c
JK
4588 strvec_push(&store.args, "stash");
4589 strvec_push(&store.args, "store");
4590 strvec_push(&store.args, "-m");
4591 strvec_push(&store.args, "autostash");
4592 strvec_push(&store.args, "-q");
4593 strvec_push(&store.args, stash_oid);
796c7972 4594 if (run_command(&store))
804fe315 4595 ret = error(_("cannot store %s"), stash_oid);
796c7972 4596 else
cdb866b3 4597 fprintf(stderr,
12b6e136 4598 _("%s\n"
cdb866b3
JS
4599 "Your changes are safe in the stash.\n"
4600 "You can run \"git stash pop\" or"
12b6e136
DL
4601 " \"git stash drop\" at any time.\n"),
4602 attempt_apply ?
4603 _("Applying autostash resulted in conflicts.") :
4604 _("Autostash exists; creating a new stash entry."));
796c7972
JS
4605 }
4606
796c7972
JS
4607 return ret;
4608}
4609
804fe315
DL
4610static int apply_save_autostash(const char *path, int attempt_apply)
4611{
4612 struct strbuf stash_oid = STRBUF_INIT;
4613 int ret = 0;
4614
4615 if (!read_oneliner(&stash_oid, path,
4616 READ_ONELINER_SKIP_IF_EMPTY)) {
4617 strbuf_release(&stash_oid);
4618 return 0;
4619 }
4620 strbuf_trim(&stash_oid);
4621
4622 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4623
0dd562e0 4624 unlink(path);
facca7f0 4625 strbuf_release(&stash_oid);
796c7972
JS
4626 return ret;
4627}
4628
12b6e136
DL
4629int save_autostash(const char *path)
4630{
4631 return apply_save_autostash(path, 0);
4632}
4633
4634int apply_autostash(const char *path)
4635{
4636 return apply_save_autostash(path, 1);
4637}
4638
804fe315
DL
4639int apply_autostash_oid(const char *stash_oid)
4640{
4641 return apply_save_autostash_oid(stash_oid, 1);
4642}
4643
35122dae
PS
4644static int apply_save_autostash_ref(struct repository *r, const char *refname,
4645 int attempt_apply)
4646{
4647 struct object_id stash_oid;
4648 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4649 int flag, ret;
4650
4651 if (!refs_ref_exists(get_main_ref_store(r), refname))
4652 return 0;
4653
4654 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4655 RESOLVE_REF_READING, &stash_oid, &flag))
4656 return -1;
4657 if (flag & REF_ISSYMREF)
4658 return error(_("autostash reference is a symref"));
4659
4660 oid_to_hex_r(stash_oid_hex, &stash_oid);
4661 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply);
4662
4663 refs_delete_ref(get_main_ref_store(r), "", refname,
4664 &stash_oid, REF_NO_DEREF);
4665
4666 return ret;
4667}
4668
4669int save_autostash_ref(struct repository *r, const char *refname)
4670{
4671 return apply_save_autostash_ref(r, refname, 0);
4672}
4673
4674int apply_autostash_ref(struct repository *r, const char *refname)
4675{
4676 return apply_save_autostash_ref(r, refname, 1);
4677}
4678
fc4a6735 4679static int checkout_onto(struct repository *r, struct replay_opts *opts,
7d3488eb 4680 const char *onto_name, const struct object_id *onto,
f3e27a02 4681 const struct object_id *orig_head)
4df66c40 4682{
38c541ce
PW
4683 struct reset_head_opts ropts = {
4684 .oid = onto,
4685 .orig_head = orig_head,
4686 .flags = RESET_HEAD_DETACH | RESET_ORIG_HEAD |
4687 RESET_HEAD_RUN_POST_CHECKOUT_HOOK,
4688 .head_msg = reflog_message(opts, "start", "checkout %s",
4689 onto_name),
d188a60d 4690 .default_reflog_action = sequencer_reflog_action(opts)
38c541ce
PW
4691 };
4692 if (reset_head(r, &ropts)) {
be1bb600 4693 apply_autostash(rebase_path_autostash());
4df66c40
AG
4694 sequencer_remove_state(opts);
4695 return error(_("could not detach HEAD"));
4696 }
4697
38c541ce 4698 return 0;
4df66c40
AG
4699}
4700
005af339 4701static int stopped_at_head(struct repository *r)
71f82465
JS
4702{
4703 struct object_id head;
4704 struct commit *commit;
4705 struct commit_message message;
4706
4a93b899 4707 if (repo_get_oid(r, "HEAD", &head) ||
005af339 4708 !(commit = lookup_commit(r, &head)) ||
4a93b899 4709 repo_parse_commit(r, commit) || get_message(commit, &message))
71f82465
JS
4710 fprintf(stderr, _("Stopped at HEAD\n"));
4711 else {
4712 fprintf(stderr, _("Stopped at %s\n"), message.label);
4713 free_message(commit, &message);
4714 }
4715 return 0;
4716
4717}
4718
dfa8bae5
PW
4719static int reread_todo_if_changed(struct repository *r,
4720 struct todo_list *todo_list,
4721 struct replay_opts *opts)
4722{
2b88fe06
PW
4723 int offset;
4724 struct strbuf buf = STRBUF_INIT;
dfa8bae5 4725
2b88fe06
PW
4726 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4727 return -1;
4728 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4729 if (buf.len != todo_list->buf.len - offset ||
4730 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
dfa8bae5
PW
4731 /* Reread the todo file if it has changed. */
4732 todo_list_release(todo_list);
4733 if (read_populate_todo(r, todo_list, opts))
4734 return -1; /* message was printed */
4735 /* `current` will be incremented on return */
4736 todo_list->current = -1;
4737 }
2b88fe06 4738 strbuf_release(&buf);
dfa8bae5
PW
4739
4740 return 0;
4741}
4742
cb5206ea
JS
4743static const char rescheduled_advice[] =
4744N_("Could not execute the todo command\n"
4745"\n"
4746" %.*s"
4747"\n"
4748"It has been rescheduled; To edit the command before continuing, please\n"
4749"edit the todo list first:\n"
4750"\n"
4751" git rebase --edit-todo\n"
4752" git rebase --continue\n");
4753
f2b5f41e
PW
4754static int pick_one_commit(struct repository *r,
4755 struct todo_list *todo_list,
4756 struct replay_opts *opts,
e032abd5 4757 int *check_todo, int* reschedule)
f2b5f41e
PW
4758{
4759 int res;
4760 struct todo_item *item = todo_list->items + todo_list->current;
4761 const char *arg = todo_item_get_arg(todo_list, item);
4762 if (is_rebase_i(opts))
4763 opts->reflog_message = reflog_message(
4764 opts, command_to_string(item->command), NULL);
4765
4766 res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
4767 check_todo);
4768 if (is_rebase_i(opts) && res < 0) {
4769 /* Reschedule */
e032abd5
PW
4770 *reschedule = 1;
4771 return -1;
f2b5f41e
PW
4772 }
4773 if (item->command == TODO_EDIT) {
4774 struct commit *commit = item->commit;
4775 if (!res) {
4776 if (!opts->verbose)
4777 term_clear_line();
4778 fprintf(stderr, _("Stopped at %s... %.*s\n"),
b995e781 4779 short_commit_name(r, commit), item->arg_len, arg);
f2b5f41e
PW
4780 }
4781 return error_with_patch(r, commit,
4782 arg, item->arg_len, opts, res, !res);
4783 }
4784 if (is_rebase_i(opts) && !res)
4785 record_in_rewritten(&item->commit->object.oid,
4786 peek_command(todo_list, 1));
4787 if (res && is_fixup(item->command)) {
4788 if (res == 1)
4789 intend_to_amend();
4790 return error_failed_squash(r, item->commit, opts,
4791 item->arg_len, arg);
4792 } else if (res && is_rebase_i(opts) && item->commit) {
4793 int to_amend = 0;
4794 struct object_id oid;
4795
4796 /*
4797 * If we are rewording and have either
4798 * fast-forwarded already, or are about to
4799 * create a new root commit, we want to amend,
4800 * otherwise we do not.
4801 */
4802 if (item->command == TODO_REWORD &&
4803 !repo_get_oid(r, "HEAD", &oid) &&
4804 (oideq(&item->commit->object.oid, &oid) ||
4805 (opts->have_squash_onto &&
4806 oideq(&opts->squash_onto, &oid))))
4807 to_amend = 1;
4808
4809 return res | error_with_patch(r, item->commit,
4810 arg, item->arg_len, opts,
4811 res, to_amend);
4812 }
4813 return res;
4814}
4815
f11c9580
NTND
4816static int pick_commits(struct repository *r,
4817 struct todo_list *todo_list,
4818 struct replay_opts *opts)
043a4492 4819{
9055e401 4820 int res = 0, reschedule = 0;
043a4492 4821
d188a60d 4822 opts->reflog_message = sequencer_reflog_action(opts);
043a4492
RR
4823 if (opts->allow_ff)
4824 assert(!(opts->signoff || opts->no_commit ||
39edfd5c 4825 opts->record_origin || should_edit(opts) ||
a3894aad
PW
4826 opts->committer_date_is_author_date ||
4827 opts->ignore_date));
f11c9580 4828 if (read_and_refresh_cache(r, opts))
0d9c6dc9 4829 return -1;
043a4492 4830
36ac861a
PW
4831 unlink(rebase_path_message());
4832 unlink(rebase_path_stopped_sha());
4833 unlink(rebase_path_amend());
206a78d7 4834 unlink(rebase_path_patch());
36ac861a 4835
004fefa7
JS
4836 while (todo_list->current < todo_list->nr) {
4837 struct todo_item *item = todo_list->items + todo_list->current;
6ad656db 4838 const char *arg = todo_item_get_arg(todo_list, item);
a47ba3c7 4839 int check_todo = 0;
6ad656db 4840
203573b0 4841 if (save_todo(todo_list, opts, reschedule))
221675de 4842 return -1;
6e98de72 4843 if (is_rebase_i(opts)) {
ef80069a
JS
4844 if (item->command != TODO_COMMENT) {
4845 FILE *f = fopen(rebase_path_msgnum(), "w");
4846
4847 todo_list->done_nr++;
4848
4849 if (f) {
4850 fprintf(f, "%d\n", todo_list->done_nr);
4851 fclose(f);
4852 }
899b49c4 4853 if (!opts->quiet)
4d55d63b 4854 fprintf(stderr, _("Rebasing (%d/%d)%s"),
899b49c4
EN
4855 todo_list->done_nr,
4856 todo_list->total_nr,
4857 opts->verbose ? "\n" : "\r");
ef80069a 4858 }
6e98de72 4859 unlink(rebase_path_author_script());
34e7771b 4860 unlink(git_path_merge_head(r));
fd7c6ffa
PS
4861 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
4862 NULL, REF_NO_DEREF);
bb02e95f
PS
4863 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
4864 NULL, REF_NO_DEREF);
71f82465 4865
d7d90885
SG
4866 if (item->command == TODO_BREAK) {
4867 if (!opts->verbose)
4868 term_clear_line();
005af339 4869 return stopped_at_head(r);
d7d90885 4870 }
6e98de72
JS
4871 }
4872 if (item->command <= TODO_SQUASH) {
e032abd5
PW
4873 res = pick_one_commit(r, todo_list, opts, &check_todo,
4874 &reschedule);
f2b5f41e
PW
4875 if (!res && item->command == TODO_EDIT)
4876 return 0;
311af526 4877 } else if (item->command == TODO_EXEC) {
6ad656db 4878 char *end_of_arg = (char *)(arg + item->arg_len);
311af526
JS
4879 int saved = *end_of_arg;
4880
d7d90885
SG
4881 if (!opts->verbose)
4882 term_clear_line();
311af526 4883 *end_of_arg = '\0';
6ad656db 4884 res = do_exec(r, arg);
311af526 4885 *end_of_arg = saved;
54fd3243 4886
d421afa0
JS
4887 if (res) {
4888 if (opts->reschedule_failed_exec)
4889 reschedule = 1;
54fd3243 4890 }
a47ba3c7 4891 check_todo = 1;
9055e401 4892 } else if (item->command == TODO_LABEL) {
6ad656db 4893 if ((res = do_label(r, arg, item->arg_len)))
9055e401
JS
4894 reschedule = 1;
4895 } else if (item->command == TODO_RESET) {
6ad656db 4896 if ((res = do_reset(r, arg, item->arg_len, opts)))
9055e401 4897 reschedule = 1;
4c68e7dd 4898 } else if (item->command == TODO_MERGE) {
2be6b6f4
PW
4899 if ((res = do_merge(r, item->commit, arg, item->arg_len,
4900 item->flags, &check_todo, opts)) < 0)
4c68e7dd 4901 reschedule = 1;
537e7d61
JS
4902 else if (item->commit)
4903 record_in_rewritten(&item->commit->object.oid,
4904 peek_command(todo_list, 1));
4905 if (res > 0)
4c68e7dd 4906 /* failed with merge conflicts */
f11c9580 4907 return error_with_patch(r, item->commit,
6ad656db
AG
4908 arg, item->arg_len,
4909 opts, res, 0);
a97d7916
DS
4910 } else if (item->command == TODO_UPDATE_REF) {
4911 struct strbuf ref = STRBUF_INIT;
4912 strbuf_add(&ref, arg, item->arg_len);
4913 if ((res = do_update_ref(r, ref.buf)))
4914 reschedule = 1;
4915 strbuf_release(&ref);
56dc3ab0 4916 } else if (!is_noop(item->command))
25c43667
JS
4917 return error(_("unknown command %d"), item->command);
4918
9055e401
JS
4919 if (reschedule) {
4920 advise(_(rescheduled_advice),
4921 get_item_line_length(todo_list,
4922 todo_list->current),
4923 get_item_line(todo_list, todo_list->current));
203573b0 4924 if (save_todo(todo_list, opts, reschedule))
9055e401 4925 return -1;
4c68e7dd 4926 if (item->commit)
e032abd5 4927 write_rebase_head(&item->commit->object.oid);
dfa8bae5
PW
4928 } else if (is_rebase_i(opts) && check_todo && !res &&
4929 reread_todo_if_changed(r, todo_list, opts)) {
4930 return -1;
9055e401
JS
4931 }
4932
043a4492
RR
4933 if (res)
4934 return res;
f2b5f41e
PW
4935
4936 todo_list->current++;
043a4492
RR
4937 }
4938
56dc3ab0 4939 if (is_rebase_i(opts)) {
4b83ce9f 4940 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 4941 struct stat st;
556907f1 4942
4b83ce9f
JS
4943 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4944 starts_with(head_ref.buf, "refs/")) {
96e832a5 4945 const char *msg;
092bbcdf 4946 struct object_id head, orig;
4b83ce9f
JS
4947 int res;
4948
4a93b899 4949 if (repo_get_oid(r, "HEAD", &head)) {
4b83ce9f
JS
4950 res = error(_("cannot read HEAD"));
4951cleanup_head_ref:
4952 strbuf_release(&head_ref);
4953 strbuf_release(&buf);
4954 return res;
4955 }
4956 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 4957 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
4958 res = error(_("could not read orig-head"));
4959 goto cleanup_head_ref;
4960 }
4ab867b8 4961 strbuf_reset(&buf);
4b83ce9f
JS
4962 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4963 res = error(_("could not read 'onto'"));
4964 goto cleanup_head_ref;
4965 }
96e832a5
JS
4966 msg = reflog_message(opts, "finish", "%s onto %s",
4967 head_ref.buf, buf.buf);
ae077771 4968 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 4969 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
4970 res = error(_("could not update %s"),
4971 head_ref.buf);
4972 goto cleanup_head_ref;
4973 }
96e832a5 4974 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 4975 head_ref.buf);
96e832a5 4976 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
4977 res = error(_("could not update HEAD to %s"),
4978 head_ref.buf);
4979 goto cleanup_head_ref;
4980 }
4981 strbuf_reset(&buf);
4982 }
4983
556907f1
JS
4984 if (opts->verbose) {
4985 struct rev_info log_tree_opt;
4986 struct object_id orig, head;
4987
4988 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
f11c9580 4989 repo_init_revisions(r, &log_tree_opt, NULL);
556907f1
JS
4990 log_tree_opt.diff = 1;
4991 log_tree_opt.diffopt.output_format =
4992 DIFF_FORMAT_DIFFSTAT;
4993 log_tree_opt.disable_stdin = 1;
4994
4995 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4a93b899
ÆAB
4996 !repo_get_oid(r, buf.buf, &orig) &&
4997 !repo_get_oid(r, "HEAD", &head)) {
66f414f8
BW
4998 diff_tree_oid(&orig, &head, "",
4999 &log_tree_opt.diffopt);
556907f1
JS
5000 log_tree_diff_flush(&log_tree_opt);
5001 }
2108fe4a 5002 release_revisions(&log_tree_opt);
556907f1 5003 }
25cb8df9
JS
5004 flush_rewritten_pending();
5005 if (!stat(rebase_path_rewritten_list(), &st) &&
5006 st.st_size > 0) {
5007 struct child_process child = CHILD_PROCESS_INIT;
96af564d 5008 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
25cb8df9
JS
5009
5010 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5011 child.git_cmd = 1;
c972bf4c
JK
5012 strvec_push(&child.args, "notes");
5013 strvec_push(&child.args, "copy");
5014 strvec_push(&child.args, "--for-rewrite=rebase");
25cb8df9
JS
5015 /* we don't care if this copying failed */
5016 run_command(&child);
79516045 5017
96af564d
ES
5018 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5019 strvec_push(&hook_opt.args, "rebase");
5020 run_hooks_opt("post-rewrite", &hook_opt);
25cb8df9 5021 }
be1bb600 5022 apply_autostash(rebase_path_autostash());
25cb8df9 5023
d7d90885
SG
5024 if (!opts->quiet) {
5025 if (!opts->verbose)
5026 term_clear_line();
899b49c4 5027 fprintf(stderr,
4d55d63b 5028 _("Successfully rebased and updated %s.\n"),
899b49c4 5029 head_ref.buf);
d7d90885 5030 }
5da4966f 5031
556907f1 5032 strbuf_release(&buf);
4b83ce9f 5033 strbuf_release(&head_ref);
89fc0b53 5034
4611884e 5035 if (do_update_refs(r, opts->quiet))
89fc0b53 5036 return -1;
56dc3ab0
JS
5037 }
5038
043a4492
RR
5039 /*
5040 * Sequence of picks finished successfully; cleanup by
5041 * removing the .git/sequencer directory
5042 */
2863584f 5043 return sequencer_remove_state(opts);
043a4492
RR
5044}
5045
39edfd5c 5046static int continue_single_pick(struct repository *r, struct replay_opts *opts)
043a4492 5047{
0e906739 5048 struct child_process cmd = CHILD_PROCESS_INIT;
043a4492 5049
c8e4159e 5050 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
b8825ef2 5051 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
043a4492 5052 return error(_("no cherry-pick or revert in progress"));
39edfd5c 5053
0e906739
RS
5054 cmd.git_cmd = 1;
5055 strvec_push(&cmd.args, "commit");
39edfd5c
EN
5056
5057 /*
5058 * continue_single_pick() handles the case of recovering from a
5059 * conflict. should_edit() doesn't handle that case; for a conflict,
5060 * we want to edit if the user asked for it, or if they didn't specify
5061 * and stdin is a tty.
5062 */
5063 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5064 /*
5065 * Include --cleanup=strip as well because we don't want the
5066 * "# Conflicts:" messages.
5067 */
0e906739 5068 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
39edfd5c 5069
0e906739 5070 return run_command(&cmd);
043a4492
RR
5071}
5072
f11c9580
NTND
5073static int commit_staged_changes(struct repository *r,
5074 struct replay_opts *opts,
15ef6931 5075 struct todo_list *todo_list)
9d93ccd1 5076{
789b3eff 5077 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
15ef6931 5078 unsigned int final_fixup = 0, is_clean;
9d93ccd1 5079
f11c9580 5080 if (has_unstaged_changes(r, 1))
9d93ccd1 5081 return error(_("cannot rebase: You have unstaged changes."));
52632209 5082
f11c9580 5083 is_clean = !has_uncommitted_changes(r, 0);
9d93ccd1 5084
405509cb
PW
5085 if (!is_clean && !file_exists(rebase_path_message())) {
5086 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5087
5088 return error(_(staged_changes_advice), gpg_opt, gpg_opt);
5089 }
9d93ccd1
JS
5090 if (file_exists(rebase_path_amend())) {
5091 struct strbuf rev = STRBUF_INIT;
092bbcdf 5092 struct object_id head, to_amend;
9d93ccd1 5093
4a93b899 5094 if (repo_get_oid(r, "HEAD", &head))
9d93ccd1
JS
5095 return error(_("cannot amend non-existing commit"));
5096 if (!read_oneliner(&rev, rebase_path_amend(), 0))
5097 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 5098 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
5099 return error(_("invalid contents: '%s'"),
5100 rebase_path_amend());
9001dc2a 5101 if (!is_clean && !oideq(&head, &to_amend))
9d93ccd1
JS
5102 return error(_("\nYou have uncommitted changes in your "
5103 "working tree. Please, commit them\n"
5104 "first and then run 'git rebase "
5105 "--continue' again."));
15ef6931
JS
5106 /*
5107 * When skipping a failed fixup/squash, we need to edit the
5108 * commit message, the current fixup list and count, and if it
5109 * was the last fixup/squash in the chain, we need to clean up
5110 * the commit message and if there was a squash, let the user
5111 * edit it.
5112 */
10d2f354
JS
5113 if (!is_clean || !opts->current_fixup_count)
5114 ; /* this is not the final fixup */
87ae8a1a 5115 else if (!oideq(&head, &to_amend) ||
10d2f354
JS
5116 !file_exists(rebase_path_stopped_sha())) {
5117 /* was a final fixup or squash done manually? */
5118 if (!is_fixup(peek_command(todo_list, 0))) {
5119 unlink(rebase_path_fixup_msg());
5120 unlink(rebase_path_squash_msg());
5121 unlink(rebase_path_current_fixups());
5122 strbuf_reset(&opts->current_fixups);
5123 opts->current_fixup_count = 0;
5124 }
5125 } else {
5126 /* we are in a fixup/squash chain */
15ef6931
JS
5127 const char *p = opts->current_fixups.buf;
5128 int len = opts->current_fixups.len;
5129
5130 opts->current_fixup_count--;
5131 if (!len)
5132 BUG("Incorrect current_fixups:\n%s", p);
5133 while (len && p[len - 1] != '\n')
5134 len--;
5135 strbuf_setlen(&opts->current_fixups, len);
5136 if (write_message(p, len, rebase_path_current_fixups(),
5137 0) < 0)
5138 return error(_("could not write file: '%s'"),
5139 rebase_path_current_fixups());
5140
5141 /*
5142 * If a fixup/squash in a fixup/squash chain failed, the
5143 * commit message is already correct, no need to commit
5144 * it again.
5145 *
5146 * Only if it is the final command in the fixup/squash
5147 * chain, and only if the chain is longer than a single
5148 * fixup/squash command (which was just skipped), do we
5149 * actually need to re-commit with a cleaned up commit
5150 * message.
5151 */
5152 if (opts->current_fixup_count > 0 &&
5153 !is_fixup(peek_command(todo_list, 0))) {
5154 final_fixup = 1;
5155 /*
5156 * If there was not a single "squash" in the
5157 * chain, we only need to clean up the commit
5158 * message, no need to bother the user with
5159 * opening the commit message in the editor.
5160 */
5161 if (!starts_with(p, "squash ") &&
5162 !strstr(p, "\nsquash "))
5163 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5164 } else if (is_fixup(peek_command(todo_list, 0))) {
5165 /*
5166 * We need to update the squash message to skip
5167 * the latest commit message.
5168 */
6ce7afe1 5169 int res = 0;
15ef6931 5170 struct commit *commit;
6ce7afe1 5171 const char *msg;
15ef6931 5172 const char *path = rebase_path_squash_msg();
b3757442 5173 const char *encoding = get_commit_output_encoding();
15ef6931 5174
6ce7afe1
PW
5175 if (parse_head(r, &commit))
5176 return error(_("could not parse HEAD"));
5177
5178 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5179 if (!p) {
5180 res = error(_("could not parse commit %s"),
5181 oid_to_hex(&commit->object.oid));
5182 goto unuse_commit_buffer;
5183 }
5184 find_commit_subject(p, &msg);
5185 if (write_message(msg, strlen(msg), path, 0)) {
5186 res = error(_("could not write file: "
15ef6931 5187 "'%s'"), path);
6ce7afe1 5188 goto unuse_commit_buffer;
15ef6931 5189 }
6ce7afe1
PW
5190 unuse_commit_buffer:
5191 repo_unuse_commit_buffer(r, commit, p);
5192 if (res)
5193 return res;
15ef6931
JS
5194 }
5195 }
9d93ccd1
JS
5196
5197 strbuf_release(&rev);
789b3eff 5198 flags |= AMEND_MSG;
9d93ccd1
JS
5199 }
5200
15ef6931 5201 if (is_clean) {
c8e4159e
HWN
5202 if (refs_ref_exists(get_main_ref_store(r),
5203 "CHERRY_PICK_HEAD") &&
5204 refs_delete_ref(get_main_ref_store(r), "",
821f6632 5205 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF))
15ef6931 5206 return error(_("could not remove CHERRY_PICK_HEAD"));
e5ee33e8
PW
5207 if (unlink(git_path_merge_msg(r)) && errno != ENOENT)
5208 return error_errno(_("could not remove '%s'"),
5209 git_path_merge_msg(r));
15ef6931
JS
5210 if (!final_fixup)
5211 return 0;
5212 }
5213
20f4b044 5214 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
15ef6931 5215 opts, flags))
9d93ccd1
JS
5216 return error(_("could not commit staged changes."));
5217 unlink(rebase_path_amend());
34e7771b 5218 unlink(git_path_merge_head(r));
fd7c6ffa
PS
5219 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5220 NULL, REF_NO_DEREF);
15ef6931
JS
5221 if (final_fixup) {
5222 unlink(rebase_path_fixup_msg());
5223 unlink(rebase_path_squash_msg());
5224 }
5225 if (opts->current_fixup_count > 0) {
5226 /*
5227 * Whether final fixup or not, we just cleaned up the commit
5228 * message...
5229 */
5230 unlink(rebase_path_current_fixups());
5231 strbuf_reset(&opts->current_fixups);
5232 opts->current_fixup_count = 0;
5233 }
9d93ccd1
JS
5234 return 0;
5235}
5236
f11c9580 5237int sequencer_continue(struct repository *r, struct replay_opts *opts)
043a4492 5238{
004fefa7
JS
5239 struct todo_list todo_list = TODO_LIST_INIT;
5240 int res;
043a4492 5241
f11c9580 5242 if (read_and_refresh_cache(r, opts))
2863584f
JS
5243 return -1;
5244
15ef6931
JS
5245 if (read_populate_opts(opts))
5246 return -1;
9d93ccd1 5247 if (is_rebase_i(opts)) {
005af339 5248 if ((res = read_populate_todo(r, &todo_list, opts)))
15ef6931 5249 goto release_todo_list;
5a5445d8
AG
5250
5251 if (file_exists(rebase_path_dropped())) {
5252 if ((res = todo_list_check_against_backup(r, &todo_list)))
5253 goto release_todo_list;
5254
5255 unlink(rebase_path_dropped());
5256 }
5257
d188a60d 5258 opts->reflog_message = reflog_message(opts, "continue", NULL);
f6b9413b
AG
5259 if (commit_staged_changes(r, opts, &todo_list)) {
5260 res = -1;
5261 goto release_todo_list;
5262 }
4258a6da 5263 } else if (!file_exists(get_todo_path(opts)))
39edfd5c 5264 return continue_single_pick(r, opts);
005af339 5265 else if ((res = read_populate_todo(r, &todo_list, opts)))
004fefa7 5266 goto release_todo_list;
043a4492 5267
4258a6da
JS
5268 if (!is_rebase_i(opts)) {
5269 /* Verify that the conflict has been resolved */
c8e4159e
HWN
5270 if (refs_ref_exists(get_main_ref_store(r),
5271 "CHERRY_PICK_HEAD") ||
b8825ef2 5272 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
39edfd5c 5273 res = continue_single_pick(r, opts);
4258a6da
JS
5274 if (res)
5275 goto release_todo_list;
5276 }
ffc00a48 5277 if (index_differs_from(r, "HEAD", NULL, 0)) {
e1ff0a32 5278 res = error_dirty_index(r, opts);
004fefa7 5279 goto release_todo_list;
4258a6da
JS
5280 }
5281 todo_list.current++;
ca98c6d4
JS
5282 } else if (file_exists(rebase_path_stopped_sha())) {
5283 struct strbuf buf = STRBUF_INIT;
5284 struct object_id oid;
5285
3442c3d1
DL
5286 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5287 READ_ONELINER_SKIP_IF_EMPTY) &&
0512eabd 5288 !get_oid_hex(buf.buf, &oid))
ca98c6d4
JS
5289 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5290 strbuf_release(&buf);
043a4492 5291 }
4258a6da 5292
f11c9580 5293 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
5294release_todo_list:
5295 todo_list_release(&todo_list);
5296 return res;
043a4492
RR
5297}
5298
f11c9580
NTND
5299static int single_pick(struct repository *r,
5300 struct commit *cmit,
5301 struct replay_opts *opts)
043a4492 5302{
a47ba3c7 5303 int check_todo;
ae70e34f
CM
5304 struct todo_item item;
5305
5306 item.command = opts->action == REPLAY_PICK ?
5307 TODO_PICK : TODO_REVERT;
5308 item.commit = cmit;
a47ba3c7 5309
d188a60d 5310 opts->reflog_message = sequencer_reflog_action(opts);
ae70e34f 5311 return do_pick_commit(r, &item, opts, 0, &check_todo);
043a4492
RR
5312}
5313
f11c9580
NTND
5314int sequencer_pick_revisions(struct repository *r,
5315 struct replay_opts *opts)
043a4492 5316{
004fefa7 5317 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 5318 struct object_id oid;
004fefa7 5319 int i, res;
043a4492 5320
2863584f 5321 assert(opts->revs);
f11c9580 5322 if (read_and_refresh_cache(r, opts))
0d9c6dc9 5323 return -1;
043a4492 5324
21246dbb 5325 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 5326 struct object_id oid;
21246dbb
MV
5327 const char *name = opts->revs->pending.objects[i].name;
5328
5329 /* This happens when using --stdin. */
5330 if (!strlen(name))
5331 continue;
5332
4a93b899 5333 if (!repo_get_oid(r, name, &oid)) {
f11c9580
NTND
5334 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5335 enum object_type type = oid_object_info(r,
0df8e965 5336 &oid,
abef9020 5337 NULL);
b9b946d4 5338 return error(_("%s: can't cherry-pick a %s"),
debca9d2 5339 name, type_name(type));
7c0b0d8d 5340 }
21246dbb 5341 } else
b9b946d4 5342 return error(_("%s: bad revision"), name);
21246dbb
MV
5343 }
5344
043a4492
RR
5345 /*
5346 * If we were called as "git cherry-pick <commit>", just
5347 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5348 * REVERT_HEAD, and don't touch the sequencer state.
5349 * This means it is possible to cherry-pick in the middle
5350 * of a cherry-pick sequence.
5351 */
5352 if (opts->revs->cmdline.nr == 1 &&
5353 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5354 opts->revs->no_walk &&
5355 !opts->revs->cmdline.rev->flags) {
5356 struct commit *cmit;
5357 if (prepare_revision_walk(opts->revs))
b9b946d4 5358 return error(_("revision walk setup failed"));
043a4492 5359 cmit = get_revision(opts->revs);
c5e358d0
JK
5360 if (!cmit)
5361 return error(_("empty commit set passed"));
5362 if (get_revision(opts->revs))
5363 BUG("unexpected extra commit from walk");
f11c9580 5364 return single_pick(r, cmit, opts);
043a4492
RR
5365 }
5366
5367 /*
5368 * Start a new cherry-pick/ revert sequence; but
5369 * first, make sure that an existing one isn't in
5370 * progress
5371 */
5372
34b0528b 5373 if (walk_revs_populate_todo(&todo_list, opts) ||
6a1f9046 5374 create_seq_dir(r) < 0)
043a4492 5375 return -1;
4a93b899 5376 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 5377 return error(_("can't revert as initial commit"));
1e43ed98 5378 if (save_head(oid_to_hex(&oid)))
311fd397 5379 return -1;
88d5a271
JS
5380 if (save_opts(opts))
5381 return -1;
1e41229d 5382 update_abort_safety_file();
f11c9580 5383 res = pick_commits(r, &todo_list, opts);
004fefa7
JS
5384 todo_list_release(&todo_list);
5385 return res;
043a4492 5386}
5ed75e2a 5387
66e83d9b 5388void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5ed75e2a 5389{
bab4d109 5390 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 5391 struct strbuf sob = STRBUF_INIT;
bab4d109 5392 int has_footer;
5ed75e2a
MV
5393
5394 strbuf_addstr(&sob, sign_off_header);
39ab4d09 5395 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5ed75e2a 5396 strbuf_addch(&sob, '\n');
bab4d109 5397
44dc738a
JT
5398 if (!ignore_footer)
5399 strbuf_complete_line(msgbuf);
5400
bab4d109
BC
5401 /*
5402 * If the whole message buffer is equal to the sob, pretend that we
5403 * found a conforming footer with a matching sob
5404 */
5405 if (msgbuf->len - ignore_footer == sob.len &&
5406 !strncmp(msgbuf->buf, sob.buf, sob.len))
5407 has_footer = 3;
5408 else
5409 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5410
33f2f9ab
BC
5411 if (!has_footer) {
5412 const char *append_newlines = NULL;
5413 size_t len = msgbuf->len - ignore_footer;
5414
8c613fd5
BC
5415 if (!len) {
5416 /*
5417 * The buffer is completely empty. Leave foom for
5418 * the title and body to be filled in by the user.
5419 */
33f2f9ab 5420 append_newlines = "\n\n";
8c613fd5
BC
5421 } else if (len == 1) {
5422 /*
5423 * Buffer contains a single newline. Add another
5424 * so that we leave room for the title and body.
5425 */
5426 append_newlines = "\n";
5427 } else if (msgbuf->buf[len - 2] != '\n') {
5428 /*
5429 * Buffer ends with a single newline. Add another
5430 * so that there is an empty line between the message
5431 * body and the sob.
5432 */
33f2f9ab 5433 append_newlines = "\n";
8c613fd5 5434 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
5435
5436 if (append_newlines)
5437 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5438 append_newlines, strlen(append_newlines));
5ed75e2a 5439 }
bab4d109
BC
5440
5441 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5442 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5443 sob.buf, sob.len);
5444
5ed75e2a
MV
5445 strbuf_release(&sob);
5446}
62db5247 5447
1644c73c
JS
5448struct labels_entry {
5449 struct hashmap_entry entry;
5450 char label[FLEX_ARRAY];
5451};
5452
5cf88fd8 5453static int labels_cmp(const void *fndata UNUSED,
02c3c59e 5454 const struct hashmap_entry *eptr,
939af16e 5455 const struct hashmap_entry *entry_or_key, const void *key)
1644c73c 5456{
939af16e
EW
5457 const struct labels_entry *a, *b;
5458
5459 a = container_of(eptr, const struct labels_entry, entry);
5460 b = container_of(entry_or_key, const struct labels_entry, entry);
5461
1644c73c
JS
5462 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5463}
5464
5465struct string_entry {
5466 struct oidmap_entry entry;
5467 char string[FLEX_ARRAY];
5468};
5469
5470struct label_state {
5471 struct oidmap commit2label;
5472 struct hashmap labels;
5473 struct strbuf buf;
ac300bda 5474 int max_label_length;
1644c73c
JS
5475};
5476
5477static const char *label_oid(struct object_id *oid, const char *label,
5478 struct label_state *state)
5479{
5480 struct labels_entry *labels_entry;
5481 struct string_entry *string_entry;
5482 struct object_id dummy;
1644c73c
JS
5483 int i;
5484
5485 string_entry = oidmap_get(&state->commit2label, oid);
5486 if (string_entry)
5487 return string_entry->string;
5488
5489 /*
5490 * For "uninteresting" commits, i.e. commits that are not to be
5491 * rebased, and which can therefore not be labeled, we use a unique
5492 * abbreviation of the commit name. This is slightly more complicated
c7c33f50 5493 * than calling repo_find_unique_abbrev() because we also need to make
1644c73c
JS
5494 * sure that the abbreviation does not conflict with any other
5495 * label.
5496 *
5497 * We disallow "interesting" commits to be labeled by a string that
5498 * is a valid full-length hash, to ensure that we always can find an
5499 * abbreviation for any uninteresting commit's names that does not
5500 * clash with any other label.
5501 */
867bc1d2 5502 strbuf_reset(&state->buf);
1644c73c
JS
5503 if (!label) {
5504 char *p;
5505
4439c7a3 5506 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
1644c73c
JS
5507 label = p = state->buf.buf;
5508
d850b7a5
ÆAB
5509 repo_find_unique_abbrev_r(the_repository, p, oid,
5510 default_abbrev);
1644c73c
JS
5511
5512 /*
5513 * We may need to extend the abbreviated hash so that there is
5514 * no conflicting label.
5515 */
5516 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5517 size_t i = strlen(p) + 1;
5518
5519 oid_to_hex_r(p, oid);
4439c7a3 5520 for (; i < the_hash_algo->hexsz; i++) {
1644c73c
JS
5521 char save = p[i];
5522 p[i] = '\0';
5523 if (!hashmap_get_from_hash(&state->labels,
5524 strihash(p), p))
5525 break;
5526 p[i] = save;
5527 }
5528 }
867bc1d2 5529 } else {
1644c73c 5530 struct strbuf *buf = &state->buf;
7481d2bf 5531 int label_is_utf8 = 1; /* start with this assumption */
ac300bda 5532 size_t max_len = buf->len + state->max_label_length;
1644c73c 5533
1644c73c 5534 /*
cd552227
MR
5535 * Sanitize labels by replacing non-alpha-numeric characters
5536 * (including white-space ones) by dashes, as they might be
5537 * illegal in file names (and hence in ref names).
5538 *
5539 * Note that we retain non-ASCII UTF-8 characters (identified
5540 * via the most significant bit). They should be all acceptable
7481d2bf
MRP
5541 * in file names.
5542 *
5543 * As we will use the labels as names of (loose) refs, it is
5544 * vital that the name not be longer than the maximum component
5545 * size of the file system (`NAME_MAX`). We are careful to
5546 * truncate the label accordingly, allowing for the `.lock`
5547 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
5548 * truncating in the middle of a character).
1644c73c 5549 */
7481d2bf
MRP
5550 for (; *label && buf->len + 1 < max_len; label++)
5551 if (isalnum(*label) ||
5552 (!label_is_utf8 && (*label & 0x80)))
cd552227 5553 strbuf_addch(buf, *label);
7481d2bf
MRP
5554 else if (*label & 0x80) {
5555 const char *p = label;
5556
5557 utf8_width(&p, NULL);
5558 if (p) {
5559 if (buf->len + (p - label) > max_len)
5560 break;
5561 strbuf_add(buf, label, p - label);
5562 label = p - 1;
5563 } else {
5564 label_is_utf8 = 0;
5565 strbuf_addch(buf, *label);
5566 }
cd552227 5567 /* avoid leading dash and double-dashes */
7481d2bf 5568 } else if (buf->len && buf->buf[buf->len - 1] != '-')
cd552227
MR
5569 strbuf_addch(buf, '-');
5570 if (!buf->len) {
5571 strbuf_addstr(buf, "rev-");
5572 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5573 }
867bc1d2 5574 label = buf->buf;
1644c73c 5575
867bc1d2
JS
5576 if ((buf->len == the_hash_algo->hexsz &&
5577 !get_oid_hex(label, &dummy)) ||
5578 (buf->len == 1 && *label == '#') ||
5579 hashmap_get_from_hash(&state->labels,
5580 strihash(label), label)) {
5581 /*
5582 * If the label already exists, or if the label is a
5583 * valid full OID, or the label is a '#' (which we use
5584 * as a separator between merge heads and oneline), we
5585 * append a dash and a number to make it unique.
5586 */
5587 size_t len = buf->len;
1644c73c 5588
867bc1d2
JS
5589 for (i = 2; ; i++) {
5590 strbuf_setlen(buf, len);
5591 strbuf_addf(buf, "-%d", i);
5592 if (!hashmap_get_from_hash(&state->labels,
5593 strihash(buf->buf),
5594 buf->buf))
5595 break;
5596 }
1644c73c 5597
867bc1d2
JS
5598 label = buf->buf;
5599 }
1644c73c
JS
5600 }
5601
5602 FLEX_ALLOC_STR(labels_entry, label, label);
d22245a2 5603 hashmap_entry_init(&labels_entry->entry, strihash(label));
b94e5c1d 5604 hashmap_add(&state->labels, &labels_entry->entry);
1644c73c
JS
5605
5606 FLEX_ALLOC_STR(string_entry, string, label);
5607 oidcpy(&string_entry->entry.oid, oid);
5608 oidmap_put(&state->commit2label, string_entry);
5609
5610 return string_entry->string;
5611}
5612
5613static int make_script_with_merges(struct pretty_print_context *pp,
d358fc28 5614 struct rev_info *revs, struct strbuf *out,
1644c73c
JS
5615 unsigned flags)
5616{
b9cbd295 5617 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
7543f6f4 5618 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
e1fac531 5619 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
767a4ca6 5620 int skipped_commit = 0;
1644c73c
JS
5621 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5622 struct strbuf label = STRBUF_INIT;
5623 struct commit_list *commits = NULL, **tail = &commits, *iter;
5624 struct commit_list *tips = NULL, **tips_tail = &tips;
5625 struct commit *commit;
5626 struct oidmap commit2todo = OIDMAP_INIT;
5627 struct string_entry *entry;
5628 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5629 shown = OIDSET_INIT;
ac300bda
JS
5630 struct label_state state =
5631 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
1644c73c
JS
5632
5633 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5634 const char *cmd_pick = abbr ? "p" : "pick",
5635 *cmd_label = abbr ? "l" : "label",
5636 *cmd_reset = abbr ? "t" : "reset",
5637 *cmd_merge = abbr ? "m" : "merge";
5638
ac300bda
JS
5639 git_config_get_int("rebase.maxlabellength", &state.max_label_length);
5640
1644c73c
JS
5641 oidmap_init(&commit2todo, 0);
5642 oidmap_init(&state.commit2label, 0);
939af16e 5643 hashmap_init(&state.labels, labels_cmp, NULL, 0);
1644c73c
JS
5644 strbuf_init(&state.buf, 32);
5645
5646 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
e02058a7 5647 struct labels_entry *onto_label_entry;
1644c73c
JS
5648 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5649 FLEX_ALLOC_STR(entry, string, "onto");
5650 oidcpy(&entry->entry.oid, oid);
5651 oidmap_put(&state.commit2label, entry);
e02058a7
ĐTCD
5652
5653 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5654 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5655 hashmap_add(&state.labels, &onto_label_entry->entry);
1644c73c
JS
5656 }
5657
5658 /*
5659 * First phase:
5660 * - get onelines for all commits
5661 * - gather all branch tips (i.e. 2nd or later parents of merges)
5662 * - label all branch tips
5663 */
5664 while ((commit = get_revision(revs))) {
5665 struct commit_list *to_merge;
1644c73c
JS
5666 const char *p1, *p2;
5667 struct object_id *oid;
5668 int is_empty;
5669
5670 tail = &commit_list_insert(commit, tail)->next;
5671 oidset_insert(&interesting, &commit->object.oid);
5672
5673 is_empty = is_original_commit_empty(commit);
767a4ca6
JS
5674 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5675 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5676 warning(_("skipped previously applied commit %s"),
cb646ffb 5677 short_commit_name(the_repository, commit));
767a4ca6 5678 skipped_commit = 1;
1644c73c 5679 continue;
767a4ca6 5680 }
b9cbd295
EN
5681 if (is_empty && !keep_empty)
5682 continue;
1644c73c
JS
5683
5684 strbuf_reset(&oneline);
5685 pretty_print_commit(pp, commit, &oneline);
5686
5687 to_merge = commit->parents ? commit->parents->next : NULL;
5688 if (!to_merge) {
5689 /* non-merge commit: easy case */
5690 strbuf_reset(&buf);
1644c73c
JS
5691 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5692 oid_to_hex(&commit->object.oid),
5693 oneline.buf);
1b5735f7
EN
5694 if (is_empty)
5695 strbuf_addf(&buf, " %c empty",
5696 comment_line_char);
1644c73c
JS
5697
5698 FLEX_ALLOC_STR(entry, string, buf.buf);
5699 oidcpy(&entry->entry.oid, &commit->object.oid);
5700 oidmap_put(&commit2todo, entry);
5701
5702 continue;
5703 }
5704
1644c73c
JS
5705 /* Create a label */
5706 strbuf_reset(&label);
5707 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5708 (p1 = strchr(p1, '\'')) &&
5709 (p2 = strchr(++p1, '\'')))
5710 strbuf_add(&label, p1, p2 - p1);
5711 else if (skip_prefix(oneline.buf, "Merge pull request ",
5712 &p1) &&
5713 (p1 = strstr(p1, " from ")))
5714 strbuf_addstr(&label, p1 + strlen(" from "));
5715 else
5716 strbuf_addbuf(&label, &oneline);
5717
1644c73c
JS
5718 strbuf_reset(&buf);
5719 strbuf_addf(&buf, "%s -C %s",
5720 cmd_merge, oid_to_hex(&commit->object.oid));
5721
2b6ad0f4
JS
5722 /* label the tips of merged branches */
5723 for (; to_merge; to_merge = to_merge->next) {
5724 oid = &to_merge->item->object.oid;
5725 strbuf_addch(&buf, ' ');
5726
5727 if (!oidset_contains(&interesting, oid)) {
5728 strbuf_addstr(&buf, label_oid(oid, NULL,
5729 &state));
5730 continue;
5731 }
1644c73c 5732
1644c73c
JS
5733 tips_tail = &commit_list_insert(to_merge->item,
5734 tips_tail)->next;
5735
5736 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5737 }
5738 strbuf_addf(&buf, " # %s", oneline.buf);
5739
5740 FLEX_ALLOC_STR(entry, string, buf.buf);
5741 oidcpy(&entry->entry.oid, &commit->object.oid);
5742 oidmap_put(&commit2todo, entry);
5743 }
767a4ca6
JS
5744 if (skipped_commit)
5745 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5746 _("use --reapply-cherry-picks to include skipped commits"));
1644c73c
JS
5747
5748 /*
5749 * Second phase:
5750 * - label branch points
5751 * - add HEAD to the branch tips
5752 */
5753 for (iter = commits; iter; iter = iter->next) {
5754 struct commit_list *parent = iter->item->parents;
5755 for (; parent; parent = parent->next) {
5756 struct object_id *oid = &parent->item->object.oid;
5757 if (!oidset_contains(&interesting, oid))
5758 continue;
6e8fc70f 5759 if (oidset_insert(&child_seen, oid))
1644c73c
JS
5760 label_oid(oid, "branch-point", &state);
5761 }
5762
15beaaa3 5763 /* Add HEAD as implicit "tip of branch" */
1644c73c
JS
5764 if (!iter->next)
5765 tips_tail = &commit_list_insert(iter->item,
5766 tips_tail)->next;
5767 }
5768
5769 /*
5770 * Third phase: output the todo list. This is a bit tricky, as we
5771 * want to avoid jumping back and forth between revisions. To
5772 * accomplish that goal, we walk backwards from the branch tips,
5773 * gathering commits not yet shown, reversing the list on the fly,
5774 * then outputting that list (labeling revisions as needed).
5775 */
d358fc28 5776 strbuf_addf(out, "%s onto\n", cmd_label);
1644c73c
JS
5777 for (iter = tips; iter; iter = iter->next) {
5778 struct commit_list *list = NULL, *iter2;
5779
5780 commit = iter->item;
5781 if (oidset_contains(&shown, &commit->object.oid))
5782 continue;
5783 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5784
5785 if (entry)
d358fc28 5786 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
1644c73c 5787 else
d358fc28 5788 strbuf_addch(out, '\n');
1644c73c
JS
5789
5790 while (oidset_contains(&interesting, &commit->object.oid) &&
5791 !oidset_contains(&shown, &commit->object.oid)) {
5792 commit_list_insert(commit, &list);
5793 if (!commit->parents) {
5794 commit = NULL;
5795 break;
5796 }
5797 commit = commit->parents->item;
5798 }
5799
5800 if (!commit)
d358fc28 5801 strbuf_addf(out, "%s %s\n", cmd_reset,
e1fac531
JS
5802 rebase_cousins || root_with_onto ?
5803 "onto" : "[new root]");
1644c73c
JS
5804 else {
5805 const char *to = NULL;
5806
5807 entry = oidmap_get(&state.commit2label,
5808 &commit->object.oid);
5809 if (entry)
5810 to = entry->string;
7543f6f4
JS
5811 else if (!rebase_cousins)
5812 to = label_oid(&commit->object.oid, NULL,
5813 &state);
1644c73c
JS
5814
5815 if (!to || !strcmp(to, "onto"))
d358fc28 5816 strbuf_addf(out, "%s onto\n", cmd_reset);
1644c73c
JS
5817 else {
5818 strbuf_reset(&oneline);
5819 pretty_print_commit(pp, commit, &oneline);
d358fc28
AG
5820 strbuf_addf(out, "%s %s # %s\n",
5821 cmd_reset, to, oneline.buf);
1644c73c
JS
5822 }
5823 }
5824
5825 for (iter2 = list; iter2; iter2 = iter2->next) {
5826 struct object_id *oid = &iter2->item->object.oid;
5827 entry = oidmap_get(&commit2todo, oid);
5828 /* only show if not already upstream */
5829 if (entry)
d358fc28 5830 strbuf_addf(out, "%s\n", entry->string);
1644c73c
JS
5831 entry = oidmap_get(&state.commit2label, oid);
5832 if (entry)
d358fc28
AG
5833 strbuf_addf(out, "%s %s\n",
5834 cmd_label, entry->string);
1644c73c
JS
5835 oidset_insert(&shown, oid);
5836 }
5837
5838 free_commit_list(list);
5839 }
5840
5841 free_commit_list(commits);
5842 free_commit_list(tips);
5843
5844 strbuf_release(&label);
5845 strbuf_release(&oneline);
5846 strbuf_release(&buf);
5847
5848 oidmap_free(&commit2todo, 1);
5849 oidmap_free(&state.commit2label, 1);
6da1a258 5850 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
1644c73c
JS
5851 strbuf_release(&state.buf);
5852
5853 return 0;
5854}
5855
d358fc28
AG
5856int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5857 const char **argv, unsigned flags)
62db5247
JS
5858{
5859 char *format = NULL;
5860 struct pretty_print_context pp = {0};
62db5247
JS
5861 struct rev_info revs;
5862 struct commit *commit;
b9cbd295 5863 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 5864 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 5865 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
0fcb4f6b 5866 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
767a4ca6 5867 int skipped_commit = 0;
0139c58a 5868 int ret = 0;
62db5247 5869
f11c9580 5870 repo_init_revisions(r, &revs, NULL);
62db5247 5871 revs.verbose_header = 1;
1644c73c
JS
5872 if (!rebase_merges)
5873 revs.max_parents = 1;
0fcb4f6b 5874 revs.cherry_mark = !reapply_cherry_picks;
62db5247
JS
5875 revs.limited = 1;
5876 revs.reverse = 1;
5877 revs.right_only = 1;
5878 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5879 revs.topo_order = 1;
5880
5881 revs.pretty_given = 1;
5882 git_config_get_string("rebase.instructionFormat", &format);
5883 if (!format || !*format) {
5884 free(format);
5885 format = xstrdup("%s");
5886 }
5887 get_commit_format(format, &revs);
5888 free(format);
5889 pp.fmt = revs.commit_format;
5890 pp.output_encoding = get_log_output_encoding();
5891
0139c58a
ÆAB
5892 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5893 ret = error(_("make_script: unhandled options"));
5894 goto cleanup;
5895 }
62db5247 5896
0139c58a
ÆAB
5897 if (prepare_revision_walk(&revs) < 0) {
5898 ret = error(_("make_script: error preparing revisions"));
5899 goto cleanup;
5900 }
62db5247 5901
0139c58a
ÆAB
5902 if (rebase_merges) {
5903 ret = make_script_with_merges(&pp, &revs, out, flags);
5904 goto cleanup;
5905 }
1644c73c 5906
62db5247 5907 while ((commit = get_revision(&revs))) {
d48e5e21 5908 int is_empty = is_original_commit_empty(commit);
76ea2358 5909
767a4ca6
JS
5910 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5911 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5912 warning(_("skipped previously applied commit %s"),
cb646ffb 5913 short_commit_name(r, commit));
767a4ca6 5914 skipped_commit = 1;
76ea2358 5915 continue;
767a4ca6 5916 }
b9cbd295
EN
5917 if (is_empty && !keep_empty)
5918 continue;
d358fc28 5919 strbuf_addf(out, "%s %s ", insn,
d8ae6c84 5920 oid_to_hex(&commit->object.oid));
d358fc28 5921 pretty_print_commit(&pp, commit, out);
1b5735f7
EN
5922 if (is_empty)
5923 strbuf_addf(out, " %c empty", comment_line_char);
d358fc28 5924 strbuf_addch(out, '\n');
62db5247 5925 }
767a4ca6
JS
5926 if (skipped_commit)
5927 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5928 _("use --reapply-cherry-picks to include skipped commits"));
0139c58a
ÆAB
5929cleanup:
5930 release_revisions(&revs);
5931 return ret;
62db5247 5932}
3546c8d9 5933
0cce4a27
LB
5934/*
5935 * Add commands after pick and (series of) squash/fixup commands
5936 * in the todo list.
5937 */
17919c35
JS
5938static void todo_list_add_exec_commands(struct todo_list *todo_list,
5939 struct string_list *commands)
3546c8d9 5940{
683153a4
AG
5941 struct strbuf *buf = &todo_list->buf;
5942 size_t base_offset = buf->len;
5943 int i, insert, nr = 0, alloc = 0;
5944 struct todo_item *items = NULL, *base_items = NULL;
3546c8d9 5945
ca56dadb 5946 CALLOC_ARRAY(base_items, commands->nr);
683153a4
AG
5947 for (i = 0; i < commands->nr; i++) {
5948 size_t command_len = strlen(commands->items[i].string);
3546c8d9 5949
683153a4
AG
5950 strbuf_addstr(buf, commands->items[i].string);
5951 strbuf_addch(buf, '\n');
3546c8d9 5952
683153a4
AG
5953 base_items[i].command = TODO_EXEC;
5954 base_items[i].offset_in_buf = base_offset;
e57d2c59
PW
5955 base_items[i].arg_offset = base_offset;
5956 base_items[i].arg_len = command_len;
3546c8d9 5957
683153a4 5958 base_offset += command_len + 1;
3546c8d9
JS
5959 }
5960
1ace63bc
JS
5961 /*
5962 * Insert <commands> after every pick. Here, fixup/squash chains
5963 * are considered part of the pick, so we insert the commands *after*
5964 * those chains if there are any.
683153a4 5965 *
15beaaa3 5966 * As we insert the exec commands immediately after rearranging
683153a4
AG
5967 * any fixups and before the user edits the list, a fixup chain
5968 * can never contain comments (any comments are empty picks that
5969 * have been commented out because the user did not specify
5970 * --keep-empty). So, it is safe to insert an exec command
5971 * without looking at the command following a comment.
1ace63bc 5972 */
683153a4
AG
5973 insert = 0;
5974 for (i = 0; i < todo_list->nr; i++) {
5975 enum todo_command command = todo_list->items[i].command;
5976 if (insert && !is_fixup(command)) {
5977 ALLOC_GROW(items, nr + commands->nr, alloc);
5978 COPY_ARRAY(items + nr, base_items, commands->nr);
5979 nr += commands->nr;
5980
5981 insert = 0;
0cce4a27 5982 }
1ace63bc 5983
683153a4
AG
5984 ALLOC_GROW(items, nr + 1, alloc);
5985 items[nr++] = todo_list->items[i];
5986
1ace63bc 5987 if (command == TODO_PICK || command == TODO_MERGE)
683153a4 5988 insert = 1;
0cce4a27
LB
5989 }
5990
1ace63bc 5991 /* insert or append final <commands> */
cc9dcdee 5992 if (insert) {
683153a4
AG
5993 ALLOC_GROW(items, nr + commands->nr, alloc);
5994 COPY_ARRAY(items + nr, base_items, commands->nr);
5995 nr += commands->nr;
5996 }
0cce4a27 5997
683153a4
AG
5998 free(base_items);
5999 FREE_AND_NULL(todo_list->items);
6000 todo_list->items = items;
6001 todo_list->nr = nr;
6002 todo_list->alloc = alloc;
0cce4a27 6003}
3546c8d9 6004
cb646ffb
JK
6005static void todo_list_to_strbuf(struct repository *r,
6006 struct todo_list *todo_list,
616d7740 6007 struct strbuf *buf, int num, unsigned flags)
3546c8d9 6008{
8dccc7a6 6009 struct todo_item *item;
616d7740 6010 int i, max = todo_list->nr;
3546c8d9 6011
616d7740
AG
6012 if (num > 0 && num < max)
6013 max = num;
3546c8d9 6014
616d7740 6015 for (item = todo_list->items, i = 0; i < max; i++, item++) {
68e7090f
AG
6016 char cmd;
6017
8dccc7a6
LB
6018 /* if the item is not a command write it and continue */
6019 if (item->command >= TODO_COMMENT) {
616d7740 6020 strbuf_addf(buf, "%.*s\n", item->arg_len,
cbef27d6 6021 todo_item_get_arg(todo_list, item));
8dccc7a6 6022 continue;
3546c8d9 6023 }
8dccc7a6
LB
6024
6025 /* add command to the buffer */
68e7090f
AG
6026 cmd = command_to_char(item->command);
6027 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6028 strbuf_addch(buf, cmd);
d8ae6c84 6029 else
616d7740 6030 strbuf_addstr(buf, command_to_string(item->command));
8dccc7a6
LB
6031
6032 /* add commit id */
6033 if (item->commit) {
313a48ea 6034 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
cb646ffb 6035 short_commit_name(r, item->commit) :
8dccc7a6
LB
6036 oid_to_hex(&item->commit->object.oid);
6037
9e3cebd9
CM
6038 if (item->command == TODO_FIXUP) {
6039 if (item->flags & TODO_EDIT_FIXUP_MSG)
6040 strbuf_addstr(buf, " -c");
6041 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6042 strbuf_addstr(buf, " -C");
6043 }
6044 }
6045
4c68e7dd
JS
6046 if (item->command == TODO_MERGE) {
6047 if (item->flags & TODO_EDIT_MERGE_MSG)
616d7740 6048 strbuf_addstr(buf, " -c");
4c68e7dd 6049 else
616d7740 6050 strbuf_addstr(buf, " -C");
4c68e7dd
JS
6051 }
6052
616d7740 6053 strbuf_addf(buf, " %s", oid);
3546c8d9 6054 }
4c68e7dd 6055
8dccc7a6 6056 /* add all the rest */
c7b4d79c 6057 if (!item->arg_len)
616d7740 6058 strbuf_addch(buf, '\n');
c7b4d79c 6059 else
616d7740 6060 strbuf_addf(buf, " %.*s\n", item->arg_len,
cbef27d6 6061 todo_item_get_arg(todo_list, item));
3546c8d9 6062 }
3546c8d9 6063}
94399949 6064
616d7740
AG
6065int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6066 const char *file, const char *shortrevisions,
6067 const char *shortonto, int num, unsigned flags)
94399949 6068{
af1fc3ad 6069 int res;
616d7740 6070 struct strbuf buf = STRBUF_INIT;
94399949 6071
616d7740 6072 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
af1fc3ad 6073 if (flags & TODO_LIST_APPEND_TODO_HELP)
d48e5e21 6074 append_todo_help(count_commands(todo_list),
af1fc3ad 6075 shortrevisions, shortonto, &buf);
94399949 6076
616d7740 6077 res = write_message(buf.buf, buf.len, file, 0);
cbef27d6 6078 strbuf_release(&buf);
8315bd20 6079
616d7740 6080 return res;
cbef27d6 6081}
94399949 6082
cdac2b01 6083/* skip picking commits whose parents are unchanged */
6bfeb7f1
AG
6084static int skip_unnecessary_picks(struct repository *r,
6085 struct todo_list *todo_list,
6086 struct object_id *base_oid)
cdac2b01 6087{
d4ed5d77 6088 struct object_id *parent_oid;
6bfeb7f1 6089 int i;
cdac2b01 6090
6bfeb7f1
AG
6091 for (i = 0; i < todo_list->nr; i++) {
6092 struct todo_item *item = todo_list->items + i;
cdac2b01
JS
6093
6094 if (item->command >= TODO_NOOP)
6095 continue;
6096 if (item->command != TODO_PICK)
6097 break;
4a93b899 6098 if (repo_parse_commit(r, item->commit)) {
cdac2b01
JS
6099 return error(_("could not parse commit '%s'"),
6100 oid_to_hex(&item->commit->object.oid));
6101 }
6102 if (!item->commit->parents)
6103 break; /* root commit */
6104 if (item->commit->parents->next)
6105 break; /* merge commit */
6106 parent_oid = &item->commit->parents->item->object.oid;
6bfeb7f1 6107 if (!oideq(parent_oid, base_oid))
cdac2b01 6108 break;
6bfeb7f1 6109 oidcpy(base_oid, &item->commit->object.oid);
cdac2b01
JS
6110 }
6111 if (i > 0) {
cdac2b01
JS
6112 const char *done_path = rebase_path_done();
6113
6bfeb7f1 6114 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
cdac2b01 6115 error_errno(_("could not write to '%s'"), done_path);
cdac2b01
JS
6116 return -1;
6117 }
cdac2b01 6118
6bfeb7f1
AG
6119 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6120 todo_list->nr -= i;
6121 todo_list->current = 0;
34065541 6122 todo_list->done_nr += i;
cdac2b01 6123
6bfeb7f1
AG
6124 if (is_fixup(peek_command(todo_list, 0)))
6125 record_in_rewritten(base_oid, peek_command(todo_list, 0));
cdac2b01
JS
6126 }
6127
cdac2b01
JS
6128 return 0;
6129}
c44a4c65 6130
900b50c2
DS
6131struct todo_add_branch_context {
6132 struct todo_item *items;
6133 size_t items_nr;
6134 size_t items_alloc;
6135 struct strbuf *buf;
6136 struct commit *commit;
6137 struct string_list refs_to_oids;
6138};
6139
6140static int add_decorations_to_list(const struct commit *commit,
6141 struct todo_add_branch_context *ctx)
6142{
6143 const struct name_decoration *decoration = get_name_decoration(&commit->object);
aa37f3e1
DS
6144 const char *head_ref = resolve_ref_unsafe("HEAD",
6145 RESOLVE_REF_READING,
6146 NULL,
6147 NULL);
900b50c2
DS
6148
6149 while (decoration) {
6150 struct todo_item *item;
6151 const char *path;
6152 size_t base_offset = ctx->buf->len;
6153
aa37f3e1
DS
6154 /*
6155 * If the branch is the current HEAD, then it will be
6156 * updated by the default rebase behavior.
6157 */
6158 if (head_ref && !strcmp(head_ref, decoration->name)) {
6159 decoration = decoration->next;
6160 continue;
6161 }
6162
900b50c2
DS
6163 ALLOC_GROW(ctx->items,
6164 ctx->items_nr + 1,
6165 ctx->items_alloc);
6166 item = &ctx->items[ctx->items_nr];
6167 memset(item, 0, sizeof(*item));
6168
6169 /* If the branch is checked out, then leave a comment instead. */
6170 if ((path = branch_checked_out(decoration->name))) {
6171 item->command = TODO_COMMENT;
6172 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6173 decoration->name, path);
6174 } else {
6175 struct string_list_item *sti;
6176 item->command = TODO_UPDATE_REF;
6177 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6178
6179 sti = string_list_insert(&ctx->refs_to_oids,
6180 decoration->name);
89fc0b53 6181 sti->util = init_update_ref_record(decoration->name);
900b50c2
DS
6182 }
6183
6184 item->offset_in_buf = base_offset;
6185 item->arg_offset = base_offset;
6186 item->arg_len = ctx->buf->len - base_offset;
6187 ctx->items_nr++;
6188
6189 decoration = decoration->next;
6190 }
6191
6192 return 0;
6193}
6194
6195/*
6196 * For each 'pick' command, find out if the commit has a decoration in
6197 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6198 */
6199static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6200{
89fc0b53 6201 int i, res;
900b50c2
DS
6202 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6203 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6204 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6205 struct decoration_filter decoration_filter = {
6206 .include_ref_pattern = &decorate_refs_include,
6207 .exclude_ref_pattern = &decorate_refs_exclude,
6208 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6209 };
6210 struct todo_add_branch_context ctx = {
6211 .buf = &todo_list->buf,
6212 .refs_to_oids = STRING_LIST_INIT_DUP,
6213 };
6214
6215 ctx.items_alloc = 2 * todo_list->nr + 1;
6216 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6217
6218 string_list_append(&decorate_refs_include, "refs/heads/");
6219 load_ref_decorations(&decoration_filter, 0);
6220
6221 for (i = 0; i < todo_list->nr; ) {
6222 struct todo_item *item = &todo_list->items[i];
6223
6224 /* insert ith item into new list */
6225 ALLOC_GROW(ctx.items,
6226 ctx.items_nr + 1,
6227 ctx.items_alloc);
6228
6229 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6230
6231 if (item->commit) {
6232 ctx.commit = item->commit;
6233 add_decorations_to_list(item->commit, &ctx);
6234 }
6235 }
6236
89fc0b53
DS
6237 res = write_update_refs_state(&ctx.refs_to_oids);
6238
900b50c2 6239 string_list_clear(&ctx.refs_to_oids, 1);
89fc0b53
DS
6240
6241 if (res) {
6242 /* we failed, so clean up the new list. */
6243 free(ctx.items);
6244 return res;
6245 }
6246
900b50c2
DS
6247 free(todo_list->items);
6248 todo_list->items = ctx.items;
6249 todo_list->nr = ctx.items_nr;
6250 todo_list->alloc = ctx.items_alloc;
6251
6252 return 0;
6253}
6254
005af339 6255int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
b97e1873 6256 const char *shortrevisions, const char *onto_name,
f3e27a02 6257 struct commit *onto, const struct object_id *orig_head,
7d3488eb 6258 struct string_list *commands, unsigned autosquash,
900b50c2 6259 unsigned update_refs,
7d3488eb 6260 struct todo_list *todo_list)
b97e1873 6261{
5da69c0d
AK
6262 char shortonto[GIT_MAX_HEXSZ + 1];
6263 const char *todo_file = rebase_path_todo();
94bcad79 6264 struct todo_list new_todo = TODO_LIST_INIT;
b6992261 6265 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
7d3488eb 6266 struct object_id oid = onto->object.oid;
1451d0f6 6267 int res;
b97e1873 6268
4a93b899 6269 repo_find_unique_abbrev_r(r, shortonto, &oid,
d850b7a5 6270 DEFAULT_ABBREV);
b97e1873 6271
94bcad79
AG
6272 if (buf->len == 0) {
6273 struct todo_item *item = append_new_todo(todo_list);
6274 item->command = TODO_NOOP;
6275 item->commit = NULL;
6276 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6277 }
b97e1873 6278
900b50c2
DS
6279 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6280 return -1;
6281
94bcad79 6282 if (autosquash && todo_list_rearrange_squash(todo_list))
b97e1873
AG
6283 return -1;
6284
683153a4 6285 if (commands->nr)
94bcad79 6286 todo_list_add_exec_commands(todo_list, commands);
b97e1873 6287
94bcad79 6288 if (count_commands(todo_list) == 0) {
be1bb600 6289 apply_autostash(rebase_path_autostash());
b97e1873 6290 sequencer_remove_state(opts);
b97e1873
AG
6291
6292 return error(_("nothing to do"));
6293 }
6294
1451d0f6
AG
6295 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6296 shortonto, flags);
6297 if (res == -1)
b97e1873 6298 return -1;
1451d0f6 6299 else if (res == -2) {
be1bb600 6300 apply_autostash(rebase_path_autostash());
b97e1873 6301 sequencer_remove_state(opts);
b97e1873
AG
6302
6303 return -1;
1451d0f6 6304 } else if (res == -3) {
be1bb600 6305 apply_autostash(rebase_path_autostash());
b97e1873 6306 sequencer_remove_state(opts);
94bcad79 6307 todo_list_release(&new_todo);
b97e1873
AG
6308
6309 return error(_("nothing to do"));
5a5445d8 6310 } else if (res == -4) {
7d3488eb 6311 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
94bcad79
AG
6312 todo_list_release(&new_todo);
6313
b97e1873
AG
6314 return -1;
6315 }
6316
b6992261
JS
6317 /* Expand the commit IDs */
6318 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6319 strbuf_swap(&new_todo.buf, &buf2);
6320 strbuf_release(&buf2);
170eea97
JS
6321 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6322 new_todo.total_nr = 0;
b6992261
JS
6323 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6324 BUG("invalid todo list after expanding IDs:\n%s",
6325 new_todo.buf.buf);
6326
6bfeb7f1
AG
6327 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6328 todo_list_release(&new_todo);
b97e1873 6329 return error(_("could not skip unnecessary pick commands"));
6bfeb7f1
AG
6330 }
6331
94bcad79
AG
6332 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6333 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6334 todo_list_release(&new_todo);
6335 return error_errno(_("could not write '%s'"), todo_file);
6336 }
6337
393adf7a 6338 res = -1;
b97e1873 6339
7d3488eb 6340 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
393adf7a 6341 goto cleanup;
29d51e21 6342
a9b5955e 6343 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
393adf7a 6344 goto cleanup;
b97e1873 6345
393adf7a
AG
6346 todo_list_write_total_nr(&new_todo);
6347 res = pick_commits(r, &new_todo, opts);
6348
6349cleanup:
6350 todo_list_release(&new_todo);
6351
6352 return res;
b97e1873
AG
6353}
6354
c44a4c65
JS
6355struct subject2item_entry {
6356 struct hashmap_entry entry;
6357 int i;
6358 char subject[FLEX_ARRAY];
6359};
6360
5cf88fd8 6361static int subject2item_cmp(const void *fndata UNUSED,
939af16e
EW
6362 const struct hashmap_entry *eptr,
6363 const struct hashmap_entry *entry_or_key,
6364 const void *key)
c44a4c65 6365{
939af16e
EW
6366 const struct subject2item_entry *a, *b;
6367
6368 a = container_of(eptr, const struct subject2item_entry, entry);
6369 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6370
c44a4c65
JS
6371 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6372}
6373
3cc0287b
NTND
6374define_commit_slab(commit_todo_item, struct todo_item *);
6375
1f969601 6376static int skip_fixupish(const char *subject, const char **p) {
bae5b4ae
CM
6377 return skip_prefix(subject, "fixup! ", p) ||
6378 skip_prefix(subject, "amend! ", p) ||
6379 skip_prefix(subject, "squash! ", p);
6380}
6381
c44a4c65
JS
6382/*
6383 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6384 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6385 * after the former, and change "pick" to "fixup"/"squash".
6386 *
6387 * Note that if the config has specified a custom instruction format, each log
6388 * message will have to be retrieved from the commit (as the oneline in the
6389 * script cannot be trusted) in order to normalize the autosquash arrangement.
6390 */
79d7e883 6391int todo_list_rearrange_squash(struct todo_list *todo_list)
c44a4c65 6392{
c44a4c65 6393 struct hashmap subject2item;
82dc42cb 6394 int rearranged = 0, *next, *tail, i, nr = 0;
c44a4c65 6395 char **subjects;
3cc0287b 6396 struct commit_todo_item commit_todo;
f2a04904 6397 struct todo_item *items = NULL;
c44a4c65 6398
3cc0287b 6399 init_commit_todo_item(&commit_todo);
c44a4c65
JS
6400 /*
6401 * The hashmap maps onelines to the respective todo list index.
6402 *
6403 * If any items need to be rearranged, the next[i] value will indicate
6404 * which item was moved directly after the i'th.
6405 *
6406 * In that case, last[i] will indicate the index of the latest item to
6407 * be moved to appear after the i'th.
6408 */
939af16e 6409 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
f2a04904
AG
6410 ALLOC_ARRAY(next, todo_list->nr);
6411 ALLOC_ARRAY(tail, todo_list->nr);
6412 ALLOC_ARRAY(subjects, todo_list->nr);
6413 for (i = 0; i < todo_list->nr; i++) {
c44a4c65 6414 struct strbuf buf = STRBUF_INIT;
f2a04904 6415 struct todo_item *item = todo_list->items + i;
c44a4c65
JS
6416 const char *commit_buffer, *subject, *p;
6417 size_t subject_len;
6418 int i2 = -1;
6419 struct subject2item_entry *entry;
6420
6421 next[i] = tail[i] = -1;
2f6b1d13 6422 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
6423 subjects[i] = NULL;
6424 continue;
6425 }
6426
6427 if (is_fixup(item->command)) {
3cc0287b 6428 clear_commit_todo_item(&commit_todo);
c44a4c65
JS
6429 return error(_("the script was already rearranged."));
6430 }
6431
ecb5091f
ÆAB
6432 repo_parse_commit(the_repository, item->commit);
6433 commit_buffer = repo_logmsg_reencode(the_repository,
6434 item->commit, NULL,
6435 "UTF-8");
c44a4c65
JS
6436 find_commit_subject(commit_buffer, &subject);
6437 format_subject(&buf, subject, " ");
6438 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
ecb5091f
ÆAB
6439 repo_unuse_commit_buffer(the_repository, item->commit,
6440 commit_buffer);
1f969601 6441 if (skip_fixupish(subject, &p)) {
c44a4c65
JS
6442 struct commit *commit2;
6443
6444 for (;;) {
6445 while (isspace(*p))
6446 p++;
1f969601 6447 if (!skip_fixupish(p, &p))
c44a4c65
JS
6448 break;
6449 }
6450
f23a4651
EW
6451 entry = hashmap_get_entry_from_hash(&subject2item,
6452 strhash(p), p,
6453 struct subject2item_entry,
6454 entry);
6455 if (entry)
c44a4c65
JS
6456 /* found by title */
6457 i2 = entry->i;
6458 else if (!strchr(p, ' ') &&
6459 (commit2 =
6460 lookup_commit_reference_by_name(p)) &&
3cc0287b 6461 *commit_todo_item_at(&commit_todo, commit2))
c44a4c65 6462 /* found by commit name */
3cc0287b 6463 i2 = *commit_todo_item_at(&commit_todo, commit2)
f2a04904 6464 - todo_list->items;
c44a4c65
JS
6465 else {
6466 /* copy can be a prefix of the commit subject */
6467 for (i2 = 0; i2 < i; i2++)
6468 if (subjects[i2] &&
6469 starts_with(subjects[i2], p))
6470 break;
6471 if (i2 == i)
6472 i2 = -1;
6473 }
6474 }
6475 if (i2 >= 0) {
6476 rearranged = 1;
bae5b4ae
CM
6477 if (starts_with(subject, "fixup!")) {
6478 todo_list->items[i].command = TODO_FIXUP;
6479 } else if (starts_with(subject, "amend!")) {
6480 todo_list->items[i].command = TODO_FIXUP;
6481 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6482 } else {
6483 todo_list->items[i].command = TODO_SQUASH;
6484 }
02471e7e
JS
6485 if (tail[i2] < 0) {
6486 next[i] = next[i2];
c44a4c65 6487 next[i2] = i;
02471e7e
JS
6488 } else {
6489 next[i] = next[tail[i2]];
c44a4c65 6490 next[tail[i2]] = i;
02471e7e 6491 }
c44a4c65
JS
6492 tail[i2] = i;
6493 } else if (!hashmap_get_from_hash(&subject2item,
6494 strhash(subject), subject)) {
6495 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6496 entry->i = i;
d22245a2
EW
6497 hashmap_entry_init(&entry->entry,
6498 strhash(entry->subject));
26b455f2 6499 hashmap_put(&subject2item, &entry->entry);
c44a4c65 6500 }
3e367a5f
JA
6501
6502 *commit_todo_item_at(&commit_todo, item->commit) = item;
c44a4c65
JS
6503 }
6504
6505 if (rearranged) {
82dc42cb
OB
6506 ALLOC_ARRAY(items, todo_list->nr);
6507
f2a04904
AG
6508 for (i = 0; i < todo_list->nr; i++) {
6509 enum todo_command command = todo_list->items[i].command;
c44a4c65
JS
6510 int cur = i;
6511
6512 /*
6513 * Initially, all commands are 'pick's. If it is a
6514 * fixup or a squash now, we have rearranged it.
6515 */
6516 if (is_fixup(command))
6517 continue;
6518
6519 while (cur >= 0) {
f2a04904 6520 items[nr++] = todo_list->items[cur];
c44a4c65
JS
6521 cur = next[cur];
6522 }
6523 }
6524
82dc42cb
OB
6525 assert(nr == todo_list->nr);
6526 todo_list->alloc = nr;
f2a04904
AG
6527 FREE_AND_NULL(todo_list->items);
6528 todo_list->items = items;
c44a4c65
JS
6529 }
6530
6531 free(next);
6532 free(tail);
f2a04904 6533 for (i = 0; i < todo_list->nr; i++)
c44a4c65
JS
6534 free(subjects[i]);
6535 free(subjects);
6da1a258 6536 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
c44a4c65 6537
3cc0287b 6538 clear_commit_todo_item(&commit_todo);
f2a04904
AG
6539
6540 return 0;
c44a4c65 6541}
901ba7b1
PW
6542
6543int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6544{
c8e4159e 6545 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
430b75f7
PW
6546 struct object_id cherry_pick_head, rebase_head;
6547
6548 if (file_exists(git_path_seq_dir()))
6549 *whence = FROM_CHERRY_PICK_MULTI;
6550 if (file_exists(rebase_path()) &&
4a93b899
ÆAB
6551 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6552 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
430b75f7
PW
6553 oideq(&rebase_head, &cherry_pick_head))
6554 *whence = FROM_REBASE_PICK;
6555 else
6556 *whence = FROM_CHERRY_PICK_SINGLE;
6557
901ba7b1
PW
6558 return 1;
6559 }
6560
6561 return 0;
6562}
aa7f2fd1
DS
6563
6564int sequencer_get_update_refs_state(const char *wt_dir,
6565 struct string_list *refs)
6566{
6567 int result = 0;
6568 FILE *fp = NULL;
6569 struct strbuf ref = STRBUF_INIT;
6570 struct strbuf hash = STRBUF_INIT;
6571 struct update_ref_record *rec = NULL;
6572
6573 char *path = rebase_path_update_refs(wt_dir);
6574
6575 fp = fopen(path, "r");
6576 if (!fp)
6577 goto cleanup;
6578
6579 while (strbuf_getline(&ref, fp) != EOF) {
6580 struct string_list_item *item;
6581
6582 CALLOC_ARRAY(rec, 1);
6583
6584 if (strbuf_getline(&hash, fp) == EOF ||
6585 get_oid_hex(hash.buf, &rec->before)) {
6586 warning(_("update-refs file at '%s' is invalid"),
6587 path);
6588 result = -1;
6589 goto cleanup;
6590 }
6591
6592 if (strbuf_getline(&hash, fp) == EOF ||
6593 get_oid_hex(hash.buf, &rec->after)) {
6594 warning(_("update-refs file at '%s' is invalid"),
6595 path);
6596 result = -1;
6597 goto cleanup;
6598 }
6599
6600 item = string_list_insert(refs, ref.buf);
6601 item->util = rec;
6602 rec = NULL;
6603 }
6604
6605cleanup:
6606 if (fp)
6607 fclose(fp);
6608 free(path);
6609 free(rec);
6610 strbuf_release(&ref);
6611 strbuf_release(&hash);
6612 return result;
6613}