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