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