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