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