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