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