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