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