]> git.ipfire.org Git - thirdparty/git.git/blame - sequencer.c
sequencer: handle post-rewrite for merge commands
[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);
2813 for (j = bases; j; j = j->next)
2814 commit_list_insert(j->item, &reversed);
2815 free_commit_list(bases);
2816
2817 read_cache();
2818 init_merge_options(&o);
2819 o.branch1 = "HEAD";
2820 o.branch2 = ref_name.buf;
2821 o.buffer_output = 2;
2822
2823 ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2824 if (ret <= 0)
2825 fputs(o.obuf.buf, stdout);
2826 strbuf_release(&o.obuf);
2827 if (ret < 0) {
2828 error(_("could not even attempt to merge '%.*s'"),
2829 merge_arg_len, arg);
2830 goto leave_merge;
2831 }
2832 /*
2833 * The return value of merge_recursive() is 1 on clean, and 0 on
2834 * unclean merge.
2835 *
2836 * Let's reverse that, so that do_merge() returns 0 upon success and
2837 * 1 upon failed merge (keeping the return value -1 for the cases where
2838 * we will want to reschedule the `merge` command).
2839 */
2840 ret = !ret;
2841
2842 if (active_cache_changed &&
2843 write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2844 ret = error(_("merge: Unable to write new index file"));
2845 goto leave_merge;
2846 }
2847
2848 rollback_lock_file(&lock);
2849 if (ret)
2850 rerere(opts->allow_rerere_auto);
2851 else
2852 /*
2853 * In case of problems, we now want to return a positive
2854 * value (a negative one would indicate that the `merge`
2855 * command needs to be rescheduled).
2856 */
2857 ret = !!run_git_commit(git_path_merge_msg(), opts,
2858 run_commit_flags);
2859
2860leave_merge:
2861 strbuf_release(&ref_name);
2862 rollback_lock_file(&lock);
2863 return ret;
2864}
2865
6e98de72
JS
2866static int is_final_fixup(struct todo_list *todo_list)
2867{
2868 int i = todo_list->current;
2869
2870 if (!is_fixup(todo_list->items[i].command))
2871 return 0;
2872
2873 while (++i < todo_list->nr)
2874 if (is_fixup(todo_list->items[i].command))
2875 return 0;
2876 else if (!is_noop(todo_list->items[i].command))
2877 break;
2878 return 1;
2879}
2880
25cb8df9
JS
2881static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2882{
2883 int i;
2884
2885 for (i = todo_list->current + offset; i < todo_list->nr; i++)
2886 if (!is_noop(todo_list->items[i].command))
2887 return todo_list->items[i].command;
2888
2889 return -1;
2890}
2891
796c7972
JS
2892static int apply_autostash(struct replay_opts *opts)
2893{
2894 struct strbuf stash_sha1 = STRBUF_INIT;
2895 struct child_process child = CHILD_PROCESS_INIT;
2896 int ret = 0;
2897
2898 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2899 strbuf_release(&stash_sha1);
2900 return 0;
2901 }
2902 strbuf_trim(&stash_sha1);
2903
2904 child.git_cmd = 1;
79a62269
PW
2905 child.no_stdout = 1;
2906 child.no_stderr = 1;
796c7972
JS
2907 argv_array_push(&child.args, "stash");
2908 argv_array_push(&child.args, "apply");
2909 argv_array_push(&child.args, stash_sha1.buf);
2910 if (!run_command(&child))
cdb866b3 2911 fprintf(stderr, _("Applied autostash.\n"));
796c7972
JS
2912 else {
2913 struct child_process store = CHILD_PROCESS_INIT;
2914
2915 store.git_cmd = 1;
2916 argv_array_push(&store.args, "stash");
2917 argv_array_push(&store.args, "store");
2918 argv_array_push(&store.args, "-m");
2919 argv_array_push(&store.args, "autostash");
2920 argv_array_push(&store.args, "-q");
2921 argv_array_push(&store.args, stash_sha1.buf);
2922 if (run_command(&store))
2923 ret = error(_("cannot store %s"), stash_sha1.buf);
2924 else
cdb866b3
JS
2925 fprintf(stderr,
2926 _("Applying autostash resulted in conflicts.\n"
2927 "Your changes are safe in the stash.\n"
2928 "You can run \"git stash pop\" or"
2929 " \"git stash drop\" at any time.\n"));
796c7972
JS
2930 }
2931
2932 strbuf_release(&stash_sha1);
2933 return ret;
2934}
2935
96e832a5
JS
2936static const char *reflog_message(struct replay_opts *opts,
2937 const char *sub_action, const char *fmt, ...)
2938{
2939 va_list ap;
2940 static struct strbuf buf = STRBUF_INIT;
2941
2942 va_start(ap, fmt);
2943 strbuf_reset(&buf);
2944 strbuf_addstr(&buf, action_name(opts));
2945 if (sub_action)
2946 strbuf_addf(&buf, " (%s)", sub_action);
2947 if (fmt) {
2948 strbuf_addstr(&buf, ": ");
2949 strbuf_vaddf(&buf, fmt, ap);
2950 }
2951 va_end(ap);
2952
2953 return buf.buf;
2954}
2955
cb5206ea
JS
2956static const char rescheduled_advice[] =
2957N_("Could not execute the todo command\n"
2958"\n"
2959" %.*s"
2960"\n"
2961"It has been rescheduled; To edit the command before continuing, please\n"
2962"edit the todo list first:\n"
2963"\n"
2964" git rebase --edit-todo\n"
2965" git rebase --continue\n");
2966
004fefa7 2967static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
043a4492 2968{
9055e401 2969 int res = 0, reschedule = 0;
043a4492
RR
2970
2971 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2972 if (opts->allow_ff)
2973 assert(!(opts->signoff || opts->no_commit ||
2974 opts->record_origin || opts->edit));
0d9c6dc9
JS
2975 if (read_and_refresh_cache(opts))
2976 return -1;
043a4492 2977
004fefa7
JS
2978 while (todo_list->current < todo_list->nr) {
2979 struct todo_item *item = todo_list->items + todo_list->current;
2980 if (save_todo(todo_list, opts))
221675de 2981 return -1;
6e98de72 2982 if (is_rebase_i(opts)) {
ef80069a
JS
2983 if (item->command != TODO_COMMENT) {
2984 FILE *f = fopen(rebase_path_msgnum(), "w");
2985
2986 todo_list->done_nr++;
2987
2988 if (f) {
2989 fprintf(f, "%d\n", todo_list->done_nr);
2990 fclose(f);
2991 }
968492e4 2992 fprintf(stderr, "Rebasing (%d/%d)%s",
ef80069a 2993 todo_list->done_nr,
968492e4
JS
2994 todo_list->total_nr,
2995 opts->verbose ? "\n" : "\r");
ef80069a 2996 }
6e98de72
JS
2997 unlink(rebase_path_message());
2998 unlink(rebase_path_author_script());
2999 unlink(rebase_path_stopped_sha());
3000 unlink(rebase_path_amend());
fbd7a232 3001 delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
6e98de72
JS
3002 }
3003 if (item->command <= TODO_SQUASH) {
8ab37ef2
JS
3004 if (is_rebase_i(opts))
3005 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3006 command_to_string(item->command), NULL),
3007 1);
25c43667 3008 res = do_pick_commit(item->command, item->commit,
6e98de72 3009 opts, is_final_fixup(todo_list));
9d7bf3cf
JS
3010 if (is_rebase_i(opts) && res < 0) {
3011 /* Reschedule */
cb5206ea
JS
3012 advise(_(rescheduled_advice),
3013 get_item_line_length(todo_list,
3014 todo_list->current),
3015 get_item_line(todo_list,
3016 todo_list->current));
9d7bf3cf
JS
3017 todo_list->current--;
3018 if (save_todo(todo_list, opts))
3019 return -1;
3020 }
56dc3ab0
JS
3021 if (item->command == TODO_EDIT) {
3022 struct commit *commit = item->commit;
3023 if (!res)
99429213 3024 fprintf(stderr,
a42e1b41 3025 _("Stopped at %s... %.*s\n"),
56dc3ab0
JS
3026 short_commit_name(commit),
3027 item->arg_len, item->arg);
3028 return error_with_patch(commit,
3029 item->arg, item->arg_len, opts, res,
3030 !res);
3031 }
25cb8df9
JS
3032 if (is_rebase_i(opts) && !res)
3033 record_in_rewritten(&item->commit->object.oid,
3034 peek_command(todo_list, 1));
6e98de72
JS
3035 if (res && is_fixup(item->command)) {
3036 if (res == 1)
3037 intend_to_amend();
3038 return error_failed_squash(item->commit, opts,
3039 item->arg_len, item->arg);
9055e401 3040 } else if (res && is_rebase_i(opts) && item->commit)
4a5146f9 3041 return res | error_with_patch(item->commit,
04efc8b5
JS
3042 item->arg, item->arg_len, opts, res,
3043 item->command == TODO_REWORD);
311af526
JS
3044 } else if (item->command == TODO_EXEC) {
3045 char *end_of_arg = (char *)(item->arg + item->arg_len);
3046 int saved = *end_of_arg;
54fd3243 3047 struct stat st;
311af526
JS
3048
3049 *end_of_arg = '\0';
3050 res = do_exec(item->arg);
3051 *end_of_arg = saved;
54fd3243
SH
3052
3053 /* Reread the todo file if it has changed. */
3054 if (res)
3055 ; /* fall through */
3056 else if (stat(get_todo_path(opts), &st))
3057 res = error_errno(_("could not stat '%s'"),
3058 get_todo_path(opts));
3059 else if (match_stat_data(&todo_list->stat, &st)) {
3060 todo_list_release(todo_list);
3061 if (read_populate_todo(todo_list, opts))
3062 res = -1; /* message was printed */
3063 /* `current` will be incremented below */
3064 todo_list->current = -1;
3065 }
9055e401
JS
3066 } else if (item->command == TODO_LABEL) {
3067 if ((res = do_label(item->arg, item->arg_len)))
3068 reschedule = 1;
3069 } else if (item->command == TODO_RESET) {
3070 if ((res = do_reset(item->arg, item->arg_len, opts)))
3071 reschedule = 1;
4c68e7dd
JS
3072 } else if (item->command == TODO_MERGE) {
3073 if ((res = do_merge(item->commit,
3074 item->arg, item->arg_len,
3075 item->flags, opts)) < 0)
3076 reschedule = 1;
537e7d61
JS
3077 else if (item->commit)
3078 record_in_rewritten(&item->commit->object.oid,
3079 peek_command(todo_list, 1));
3080 if (res > 0)
4c68e7dd
JS
3081 /* failed with merge conflicts */
3082 return error_with_patch(item->commit,
3083 item->arg,
3084 item->arg_len, opts,
3085 res, 0);
56dc3ab0 3086 } else if (!is_noop(item->command))
25c43667
JS
3087 return error(_("unknown command %d"), item->command);
3088
9055e401
JS
3089 if (reschedule) {
3090 advise(_(rescheduled_advice),
3091 get_item_line_length(todo_list,
3092 todo_list->current),
3093 get_item_line(todo_list, todo_list->current));
3094 todo_list->current--;
3095 if (save_todo(todo_list, opts))
3096 return -1;
4c68e7dd
JS
3097 if (item->commit)
3098 return error_with_patch(item->commit,
3099 item->arg,
3100 item->arg_len, opts,
3101 res, 0);
9055e401
JS
3102 }
3103
004fefa7 3104 todo_list->current++;
043a4492
RR
3105 if (res)
3106 return res;
3107 }
3108
56dc3ab0 3109 if (is_rebase_i(opts)) {
4b83ce9f 3110 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
25cb8df9 3111 struct stat st;
556907f1 3112
56dc3ab0
JS
3113 /* Stopped in the middle, as planned? */
3114 if (todo_list->current < todo_list->nr)
3115 return 0;
556907f1 3116
4b83ce9f
JS
3117 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3118 starts_with(head_ref.buf, "refs/")) {
96e832a5 3119 const char *msg;
092bbcdf 3120 struct object_id head, orig;
4b83ce9f
JS
3121 int res;
3122
092bbcdf 3123 if (get_oid("HEAD", &head)) {
4b83ce9f
JS
3124 res = error(_("cannot read HEAD"));
3125cleanup_head_ref:
3126 strbuf_release(&head_ref);
3127 strbuf_release(&buf);
3128 return res;
3129 }
3130 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
092bbcdf 3131 get_oid_hex(buf.buf, &orig)) {
4b83ce9f
JS
3132 res = error(_("could not read orig-head"));
3133 goto cleanup_head_ref;
3134 }
4ab867b8 3135 strbuf_reset(&buf);
4b83ce9f
JS
3136 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3137 res = error(_("could not read 'onto'"));
3138 goto cleanup_head_ref;
3139 }
96e832a5
JS
3140 msg = reflog_message(opts, "finish", "%s onto %s",
3141 head_ref.buf, buf.buf);
ae077771 3142 if (update_ref(msg, head_ref.buf, &head, &orig,
91774afc 3143 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4b83ce9f
JS
3144 res = error(_("could not update %s"),
3145 head_ref.buf);
3146 goto cleanup_head_ref;
3147 }
96e832a5 3148 msg = reflog_message(opts, "finish", "returning to %s",
4b83ce9f 3149 head_ref.buf);
96e832a5 3150 if (create_symref("HEAD", head_ref.buf, msg)) {
4b83ce9f
JS
3151 res = error(_("could not update HEAD to %s"),
3152 head_ref.buf);
3153 goto cleanup_head_ref;
3154 }
3155 strbuf_reset(&buf);
3156 }
3157
556907f1
JS
3158 if (opts->verbose) {
3159 struct rev_info log_tree_opt;
3160 struct object_id orig, head;
3161
3162 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3163 init_revisions(&log_tree_opt, NULL);
3164 log_tree_opt.diff = 1;
3165 log_tree_opt.diffopt.output_format =
3166 DIFF_FORMAT_DIFFSTAT;
3167 log_tree_opt.disable_stdin = 1;
3168
3169 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
e82caf38 3170 !get_oid(buf.buf, &orig) &&
3171 !get_oid("HEAD", &head)) {
66f414f8
BW
3172 diff_tree_oid(&orig, &head, "",
3173 &log_tree_opt.diffopt);
556907f1
JS
3174 log_tree_diff_flush(&log_tree_opt);
3175 }
3176 }
25cb8df9
JS
3177 flush_rewritten_pending();
3178 if (!stat(rebase_path_rewritten_list(), &st) &&
3179 st.st_size > 0) {
3180 struct child_process child = CHILD_PROCESS_INIT;
79516045
JS
3181 const char *post_rewrite_hook =
3182 find_hook("post-rewrite");
25cb8df9
JS
3183
3184 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3185 child.git_cmd = 1;
3186 argv_array_push(&child.args, "notes");
3187 argv_array_push(&child.args, "copy");
3188 argv_array_push(&child.args, "--for-rewrite=rebase");
3189 /* we don't care if this copying failed */
3190 run_command(&child);
79516045
JS
3191
3192 if (post_rewrite_hook) {
3193 struct child_process hook = CHILD_PROCESS_INIT;
3194
3195 hook.in = open(rebase_path_rewritten_list(),
3196 O_RDONLY);
3197 hook.stdout_to_stderr = 1;
3198 argv_array_push(&hook.args, post_rewrite_hook);
3199 argv_array_push(&hook.args, "rebase");
3200 /* we don't care if this hook failed */
3201 run_command(&hook);
3202 }
25cb8df9 3203 }
796c7972 3204 apply_autostash(opts);
25cb8df9 3205
5da4966f
JS
3206 fprintf(stderr, "Successfully rebased and updated %s.\n",
3207 head_ref.buf);
3208
556907f1 3209 strbuf_release(&buf);
4b83ce9f 3210 strbuf_release(&head_ref);
56dc3ab0
JS
3211 }
3212
043a4492
RR
3213 /*
3214 * Sequence of picks finished successfully; cleanup by
3215 * removing the .git/sequencer directory
3216 */
2863584f 3217 return sequencer_remove_state(opts);
043a4492
RR
3218}
3219
3220static int continue_single_pick(void)
3221{
3222 const char *argv[] = { "commit", NULL };
3223
f932729c
JK
3224 if (!file_exists(git_path_cherry_pick_head()) &&
3225 !file_exists(git_path_revert_head()))
043a4492
RR
3226 return error(_("no cherry-pick or revert in progress"));
3227 return run_command_v_opt(argv, RUN_GIT_CMD);
3228}
3229
9d93ccd1
JS
3230static int commit_staged_changes(struct replay_opts *opts)
3231{
789b3eff 3232 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
9d93ccd1
JS
3233
3234 if (has_unstaged_changes(1))
3235 return error(_("cannot rebase: You have unstaged changes."));
52632209 3236 if (!has_uncommitted_changes(0)) {
ca03e067 3237 const char *cherry_pick_head = git_path_cherry_pick_head();
52632209
JS
3238
3239 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3240 return error(_("could not remove CHERRY_PICK_HEAD"));
9d93ccd1 3241 return 0;
52632209 3242 }
9d93ccd1
JS
3243
3244 if (file_exists(rebase_path_amend())) {
3245 struct strbuf rev = STRBUF_INIT;
092bbcdf 3246 struct object_id head, to_amend;
9d93ccd1 3247
092bbcdf 3248 if (get_oid("HEAD", &head))
9d93ccd1
JS
3249 return error(_("cannot amend non-existing commit"));
3250 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3251 return error(_("invalid file: '%s'"), rebase_path_amend());
092bbcdf 3252 if (get_oid_hex(rev.buf, &to_amend))
9d93ccd1
JS
3253 return error(_("invalid contents: '%s'"),
3254 rebase_path_amend());
092bbcdf 3255 if (oidcmp(&head, &to_amend))
9d93ccd1
JS
3256 return error(_("\nYou have uncommitted changes in your "
3257 "working tree. Please, commit them\n"
3258 "first and then run 'git rebase "
3259 "--continue' again."));
3260
3261 strbuf_release(&rev);
789b3eff 3262 flags |= AMEND_MSG;
9d93ccd1
JS
3263 }
3264
789b3eff 3265 if (run_git_commit(rebase_path_message(), opts, flags))
9d93ccd1
JS
3266 return error(_("could not commit staged changes."));
3267 unlink(rebase_path_amend());
3268 return 0;
3269}
3270
2863584f 3271int sequencer_continue(struct replay_opts *opts)
043a4492 3272{
004fefa7
JS
3273 struct todo_list todo_list = TODO_LIST_INIT;
3274 int res;
043a4492 3275
2863584f
JS
3276 if (read_and_refresh_cache(opts))
3277 return -1;
3278
9d93ccd1
JS
3279 if (is_rebase_i(opts)) {
3280 if (commit_staged_changes(opts))
3281 return -1;
4258a6da 3282 } else if (!file_exists(get_todo_path(opts)))
043a4492 3283 return continue_single_pick();
004fefa7 3284 if (read_populate_opts(opts))
0ae42a03 3285 return -1;
004fefa7
JS
3286 if ((res = read_populate_todo(&todo_list, opts)))
3287 goto release_todo_list;
043a4492 3288
4258a6da
JS
3289 if (!is_rebase_i(opts)) {
3290 /* Verify that the conflict has been resolved */
3291 if (file_exists(git_path_cherry_pick_head()) ||
3292 file_exists(git_path_revert_head())) {
3293 res = continue_single_pick();
3294 if (res)
3295 goto release_todo_list;
3296 }
02f2f56b 3297 if (index_differs_from("HEAD", NULL, 0)) {
4258a6da 3298 res = error_dirty_index(opts);
004fefa7 3299 goto release_todo_list;
4258a6da
JS
3300 }
3301 todo_list.current++;
ca98c6d4
JS
3302 } else if (file_exists(rebase_path_stopped_sha())) {
3303 struct strbuf buf = STRBUF_INIT;
3304 struct object_id oid;
3305
3306 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
e82caf38 3307 !get_oid_committish(buf.buf, &oid))
ca98c6d4
JS
3308 record_in_rewritten(&oid, peek_command(&todo_list, 0));
3309 strbuf_release(&buf);
043a4492 3310 }
4258a6da 3311
004fefa7
JS
3312 res = pick_commits(&todo_list, opts);
3313release_todo_list:
3314 todo_list_release(&todo_list);
3315 return res;
043a4492
RR
3316}
3317
3318static int single_pick(struct commit *cmit, struct replay_opts *opts)
3319{
3320 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
004fefa7 3321 return do_pick_commit(opts->action == REPLAY_PICK ?
6e98de72 3322 TODO_PICK : TODO_REVERT, cmit, opts, 0);
043a4492
RR
3323}
3324
3325int sequencer_pick_revisions(struct replay_opts *opts)
3326{
004fefa7 3327 struct todo_list todo_list = TODO_LIST_INIT;
1e43ed98 3328 struct object_id oid;
004fefa7 3329 int i, res;
043a4492 3330
2863584f 3331 assert(opts->revs);
0d9c6dc9
JS
3332 if (read_and_refresh_cache(opts))
3333 return -1;
043a4492 3334
21246dbb 3335 for (i = 0; i < opts->revs->pending.nr; i++) {
1e43ed98 3336 struct object_id oid;
21246dbb
MV
3337 const char *name = opts->revs->pending.objects[i].name;
3338
3339 /* This happens when using --stdin. */
3340 if (!strlen(name))
3341 continue;
3342
1e43ed98 3343 if (!get_oid(name, &oid)) {
bc83266a 3344 if (!lookup_commit_reference_gently(&oid, 1)) {
abef9020 3345 enum object_type type = oid_object_info(&oid,
3346 NULL);
b9b946d4 3347 return error(_("%s: can't cherry-pick a %s"),
debca9d2 3348 name, type_name(type));
7c0b0d8d 3349 }
21246dbb 3350 } else
b9b946d4 3351 return error(_("%s: bad revision"), name);
21246dbb
MV
3352 }
3353
043a4492
RR
3354 /*
3355 * If we were called as "git cherry-pick <commit>", just
3356 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3357 * REVERT_HEAD, and don't touch the sequencer state.
3358 * This means it is possible to cherry-pick in the middle
3359 * of a cherry-pick sequence.
3360 */
3361 if (opts->revs->cmdline.nr == 1 &&
3362 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3363 opts->revs->no_walk &&
3364 !opts->revs->cmdline.rev->flags) {
3365 struct commit *cmit;
3366 if (prepare_revision_walk(opts->revs))
b9b946d4 3367 return error(_("revision walk setup failed"));
043a4492
RR
3368 cmit = get_revision(opts->revs);
3369 if (!cmit || get_revision(opts->revs))
b9b946d4 3370 return error("BUG: expected exactly one commit from walk");
043a4492
RR
3371 return single_pick(cmit, opts);
3372 }
3373
3374 /*
3375 * Start a new cherry-pick/ revert sequence; but
3376 * first, make sure that an existing one isn't in
3377 * progress
3378 */
3379
34b0528b
JS
3380 if (walk_revs_populate_todo(&todo_list, opts) ||
3381 create_seq_dir() < 0)
043a4492 3382 return -1;
1e43ed98 3383 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
93b3df6f 3384 return error(_("can't revert as initial commit"));
1e43ed98 3385 if (save_head(oid_to_hex(&oid)))
311fd397 3386 return -1;
88d5a271
JS
3387 if (save_opts(opts))
3388 return -1;
1e41229d 3389 update_abort_safety_file();
004fefa7
JS
3390 res = pick_commits(&todo_list, opts);
3391 todo_list_release(&todo_list);
3392 return res;
043a4492 3393}
5ed75e2a 3394
bab4d109 3395void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
5ed75e2a 3396{
bab4d109 3397 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5ed75e2a 3398 struct strbuf sob = STRBUF_INIT;
bab4d109 3399 int has_footer;
5ed75e2a
MV
3400
3401 strbuf_addstr(&sob, sign_off_header);
3402 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3403 getenv("GIT_COMMITTER_EMAIL")));
3404 strbuf_addch(&sob, '\n');
bab4d109 3405
44dc738a
JT
3406 if (!ignore_footer)
3407 strbuf_complete_line(msgbuf);
3408
bab4d109
BC
3409 /*
3410 * If the whole message buffer is equal to the sob, pretend that we
3411 * found a conforming footer with a matching sob
3412 */
3413 if (msgbuf->len - ignore_footer == sob.len &&
3414 !strncmp(msgbuf->buf, sob.buf, sob.len))
3415 has_footer = 3;
3416 else
3417 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3418
33f2f9ab
BC
3419 if (!has_footer) {
3420 const char *append_newlines = NULL;
3421 size_t len = msgbuf->len - ignore_footer;
3422
8c613fd5
BC
3423 if (!len) {
3424 /*
3425 * The buffer is completely empty. Leave foom for
3426 * the title and body to be filled in by the user.
3427 */
33f2f9ab 3428 append_newlines = "\n\n";
8c613fd5
BC
3429 } else if (len == 1) {
3430 /*
3431 * Buffer contains a single newline. Add another
3432 * so that we leave room for the title and body.
3433 */
3434 append_newlines = "\n";
3435 } else if (msgbuf->buf[len - 2] != '\n') {
3436 /*
3437 * Buffer ends with a single newline. Add another
3438 * so that there is an empty line between the message
3439 * body and the sob.
3440 */
33f2f9ab 3441 append_newlines = "\n";
8c613fd5 3442 } /* else, the buffer already ends with two newlines. */
33f2f9ab
BC
3443
3444 if (append_newlines)
3445 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3446 append_newlines, strlen(append_newlines));
5ed75e2a 3447 }
bab4d109
BC
3448
3449 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3450 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3451 sob.buf, sob.len);
3452
5ed75e2a
MV
3453 strbuf_release(&sob);
3454}
62db5247 3455
1644c73c
JS
3456struct labels_entry {
3457 struct hashmap_entry entry;
3458 char label[FLEX_ARRAY];
3459};
3460
3461static int labels_cmp(const void *fndata, const struct labels_entry *a,
3462 const struct labels_entry *b, const void *key)
3463{
3464 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3465}
3466
3467struct string_entry {
3468 struct oidmap_entry entry;
3469 char string[FLEX_ARRAY];
3470};
3471
3472struct label_state {
3473 struct oidmap commit2label;
3474 struct hashmap labels;
3475 struct strbuf buf;
3476};
3477
3478static const char *label_oid(struct object_id *oid, const char *label,
3479 struct label_state *state)
3480{
3481 struct labels_entry *labels_entry;
3482 struct string_entry *string_entry;
3483 struct object_id dummy;
3484 size_t len;
3485 int i;
3486
3487 string_entry = oidmap_get(&state->commit2label, oid);
3488 if (string_entry)
3489 return string_entry->string;
3490
3491 /*
3492 * For "uninteresting" commits, i.e. commits that are not to be
3493 * rebased, and which can therefore not be labeled, we use a unique
3494 * abbreviation of the commit name. This is slightly more complicated
3495 * than calling find_unique_abbrev() because we also need to make
3496 * sure that the abbreviation does not conflict with any other
3497 * label.
3498 *
3499 * We disallow "interesting" commits to be labeled by a string that
3500 * is a valid full-length hash, to ensure that we always can find an
3501 * abbreviation for any uninteresting commit's names that does not
3502 * clash with any other label.
3503 */
3504 if (!label) {
3505 char *p;
3506
3507 strbuf_reset(&state->buf);
3508 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3509 label = p = state->buf.buf;
3510
3511 find_unique_abbrev_r(p, oid, default_abbrev);
3512
3513 /*
3514 * We may need to extend the abbreviated hash so that there is
3515 * no conflicting label.
3516 */
3517 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3518 size_t i = strlen(p) + 1;
3519
3520 oid_to_hex_r(p, oid);
3521 for (; i < GIT_SHA1_HEXSZ; i++) {
3522 char save = p[i];
3523 p[i] = '\0';
3524 if (!hashmap_get_from_hash(&state->labels,
3525 strihash(p), p))
3526 break;
3527 p[i] = save;
3528 }
3529 }
3530 } else if (((len = strlen(label)) == GIT_SHA1_RAWSZ &&
3531 !get_oid_hex(label, &dummy)) ||
3532 (len == 1 && *label == '#') ||
3533 hashmap_get_from_hash(&state->labels,
3534 strihash(label), label)) {
3535 /*
3536 * If the label already exists, or if the label is a valid full
3537 * OID, or the label is a '#' (which we use as a separator
3538 * between merge heads and oneline), we append a dash and a
3539 * number to make it unique.
3540 */
3541 struct strbuf *buf = &state->buf;
3542
3543 strbuf_reset(buf);
3544 strbuf_add(buf, label, len);
3545
3546 for (i = 2; ; i++) {
3547 strbuf_setlen(buf, len);
3548 strbuf_addf(buf, "-%d", i);
3549 if (!hashmap_get_from_hash(&state->labels,
3550 strihash(buf->buf),
3551 buf->buf))
3552 break;
3553 }
3554
3555 label = buf->buf;
3556 }
3557
3558 FLEX_ALLOC_STR(labels_entry, label, label);
3559 hashmap_entry_init(labels_entry, strihash(label));
3560 hashmap_add(&state->labels, labels_entry);
3561
3562 FLEX_ALLOC_STR(string_entry, string, label);
3563 oidcpy(&string_entry->entry.oid, oid);
3564 oidmap_put(&state->commit2label, string_entry);
3565
3566 return string_entry->string;
3567}
3568
3569static int make_script_with_merges(struct pretty_print_context *pp,
3570 struct rev_info *revs, FILE *out,
3571 unsigned flags)
3572{
3573 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3574 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3575 struct strbuf label = STRBUF_INIT;
3576 struct commit_list *commits = NULL, **tail = &commits, *iter;
3577 struct commit_list *tips = NULL, **tips_tail = &tips;
3578 struct commit *commit;
3579 struct oidmap commit2todo = OIDMAP_INIT;
3580 struct string_entry *entry;
3581 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3582 shown = OIDSET_INIT;
3583 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3584
3585 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3586 const char *cmd_pick = abbr ? "p" : "pick",
3587 *cmd_label = abbr ? "l" : "label",
3588 *cmd_reset = abbr ? "t" : "reset",
3589 *cmd_merge = abbr ? "m" : "merge";
3590
3591 oidmap_init(&commit2todo, 0);
3592 oidmap_init(&state.commit2label, 0);
3593 hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3594 strbuf_init(&state.buf, 32);
3595
3596 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3597 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3598 FLEX_ALLOC_STR(entry, string, "onto");
3599 oidcpy(&entry->entry.oid, oid);
3600 oidmap_put(&state.commit2label, entry);
3601 }
3602
3603 /*
3604 * First phase:
3605 * - get onelines for all commits
3606 * - gather all branch tips (i.e. 2nd or later parents of merges)
3607 * - label all branch tips
3608 */
3609 while ((commit = get_revision(revs))) {
3610 struct commit_list *to_merge;
3611 int is_octopus;
3612 const char *p1, *p2;
3613 struct object_id *oid;
3614 int is_empty;
3615
3616 tail = &commit_list_insert(commit, tail)->next;
3617 oidset_insert(&interesting, &commit->object.oid);
3618
3619 is_empty = is_original_commit_empty(commit);
3620 if (!is_empty && (commit->object.flags & PATCHSAME))
3621 continue;
3622
3623 strbuf_reset(&oneline);
3624 pretty_print_commit(pp, commit, &oneline);
3625
3626 to_merge = commit->parents ? commit->parents->next : NULL;
3627 if (!to_merge) {
3628 /* non-merge commit: easy case */
3629 strbuf_reset(&buf);
3630 if (!keep_empty && is_empty)
3631 strbuf_addf(&buf, "%c ", comment_line_char);
3632 strbuf_addf(&buf, "%s %s %s", cmd_pick,
3633 oid_to_hex(&commit->object.oid),
3634 oneline.buf);
3635
3636 FLEX_ALLOC_STR(entry, string, buf.buf);
3637 oidcpy(&entry->entry.oid, &commit->object.oid);
3638 oidmap_put(&commit2todo, entry);
3639
3640 continue;
3641 }
3642
3643 is_octopus = to_merge && to_merge->next;
3644
3645 if (is_octopus)
3646 BUG("Octopus merges not yet supported");
3647
3648 /* Create a label */
3649 strbuf_reset(&label);
3650 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3651 (p1 = strchr(p1, '\'')) &&
3652 (p2 = strchr(++p1, '\'')))
3653 strbuf_add(&label, p1, p2 - p1);
3654 else if (skip_prefix(oneline.buf, "Merge pull request ",
3655 &p1) &&
3656 (p1 = strstr(p1, " from ")))
3657 strbuf_addstr(&label, p1 + strlen(" from "));
3658 else
3659 strbuf_addbuf(&label, &oneline);
3660
3661 for (p1 = label.buf; *p1; p1++)
3662 if (isspace(*p1))
3663 *(char *)p1 = '-';
3664
3665 strbuf_reset(&buf);
3666 strbuf_addf(&buf, "%s -C %s",
3667 cmd_merge, oid_to_hex(&commit->object.oid));
3668
3669 /* label the tip of merged branch */
3670 oid = &to_merge->item->object.oid;
3671 strbuf_addch(&buf, ' ');
3672
3673 if (!oidset_contains(&interesting, oid))
3674 strbuf_addstr(&buf, label_oid(oid, NULL, &state));
3675 else {
3676 tips_tail = &commit_list_insert(to_merge->item,
3677 tips_tail)->next;
3678
3679 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
3680 }
3681 strbuf_addf(&buf, " # %s", oneline.buf);
3682
3683 FLEX_ALLOC_STR(entry, string, buf.buf);
3684 oidcpy(&entry->entry.oid, &commit->object.oid);
3685 oidmap_put(&commit2todo, entry);
3686 }
3687
3688 /*
3689 * Second phase:
3690 * - label branch points
3691 * - add HEAD to the branch tips
3692 */
3693 for (iter = commits; iter; iter = iter->next) {
3694 struct commit_list *parent = iter->item->parents;
3695 for (; parent; parent = parent->next) {
3696 struct object_id *oid = &parent->item->object.oid;
3697 if (!oidset_contains(&interesting, oid))
3698 continue;
3699 if (!oidset_contains(&child_seen, oid))
3700 oidset_insert(&child_seen, oid);
3701 else
3702 label_oid(oid, "branch-point", &state);
3703 }
3704
3705 /* Add HEAD as implict "tip of branch" */
3706 if (!iter->next)
3707 tips_tail = &commit_list_insert(iter->item,
3708 tips_tail)->next;
3709 }
3710
3711 /*
3712 * Third phase: output the todo list. This is a bit tricky, as we
3713 * want to avoid jumping back and forth between revisions. To
3714 * accomplish that goal, we walk backwards from the branch tips,
3715 * gathering commits not yet shown, reversing the list on the fly,
3716 * then outputting that list (labeling revisions as needed).
3717 */
3718 fprintf(out, "%s onto\n", cmd_label);
3719 for (iter = tips; iter; iter = iter->next) {
3720 struct commit_list *list = NULL, *iter2;
3721
3722 commit = iter->item;
3723 if (oidset_contains(&shown, &commit->object.oid))
3724 continue;
3725 entry = oidmap_get(&state.commit2label, &commit->object.oid);
3726
3727 if (entry)
3728 fprintf(out, "\n# Branch %s\n", entry->string);
3729 else
3730 fprintf(out, "\n");
3731
3732 while (oidset_contains(&interesting, &commit->object.oid) &&
3733 !oidset_contains(&shown, &commit->object.oid)) {
3734 commit_list_insert(commit, &list);
3735 if (!commit->parents) {
3736 commit = NULL;
3737 break;
3738 }
3739 commit = commit->parents->item;
3740 }
3741
3742 if (!commit)
3743 fprintf(out, "%s onto\n", cmd_reset);
3744 else {
3745 const char *to = NULL;
3746
3747 entry = oidmap_get(&state.commit2label,
3748 &commit->object.oid);
3749 if (entry)
3750 to = entry->string;
3751
3752 if (!to || !strcmp(to, "onto"))
3753 fprintf(out, "%s onto\n", cmd_reset);
3754 else {
3755 strbuf_reset(&oneline);
3756 pretty_print_commit(pp, commit, &oneline);
3757 fprintf(out, "%s %s # %s\n",
3758 cmd_reset, to, oneline.buf);
3759 }
3760 }
3761
3762 for (iter2 = list; iter2; iter2 = iter2->next) {
3763 struct object_id *oid = &iter2->item->object.oid;
3764 entry = oidmap_get(&commit2todo, oid);
3765 /* only show if not already upstream */
3766 if (entry)
3767 fprintf(out, "%s\n", entry->string);
3768 entry = oidmap_get(&state.commit2label, oid);
3769 if (entry)
3770 fprintf(out, "%s %s\n",
3771 cmd_label, entry->string);
3772 oidset_insert(&shown, oid);
3773 }
3774
3775 free_commit_list(list);
3776 }
3777
3778 free_commit_list(commits);
3779 free_commit_list(tips);
3780
3781 strbuf_release(&label);
3782 strbuf_release(&oneline);
3783 strbuf_release(&buf);
3784
3785 oidmap_free(&commit2todo, 1);
3786 oidmap_free(&state.commit2label, 1);
3787 hashmap_free(&state.labels, 1);
3788 strbuf_release(&state.buf);
3789
3790 return 0;
3791}
3792
313a48ea
LB
3793int sequencer_make_script(FILE *out, int argc, const char **argv,
3794 unsigned flags)
62db5247
JS
3795{
3796 char *format = NULL;
3797 struct pretty_print_context pp = {0};
3798 struct strbuf buf = STRBUF_INIT;
3799 struct rev_info revs;
3800 struct commit *commit;
313a48ea 3801 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
d8ae6c84 3802 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
1644c73c 3803 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
62db5247
JS
3804
3805 init_revisions(&revs, NULL);
3806 revs.verbose_header = 1;
1644c73c
JS
3807 if (!rebase_merges)
3808 revs.max_parents = 1;
76ea2358 3809 revs.cherry_mark = 1;
62db5247
JS
3810 revs.limited = 1;
3811 revs.reverse = 1;
3812 revs.right_only = 1;
3813 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3814 revs.topo_order = 1;
3815
3816 revs.pretty_given = 1;
3817 git_config_get_string("rebase.instructionFormat", &format);
3818 if (!format || !*format) {
3819 free(format);
3820 format = xstrdup("%s");
3821 }
3822 get_commit_format(format, &revs);
3823 free(format);
3824 pp.fmt = revs.commit_format;
3825 pp.output_encoding = get_log_output_encoding();
3826
3827 if (setup_revisions(argc, argv, &revs, NULL) > 1)
3828 return error(_("make_script: unhandled options"));
3829
3830 if (prepare_revision_walk(&revs) < 0)
3831 return error(_("make_script: error preparing revisions"));
3832
1644c73c
JS
3833 if (rebase_merges)
3834 return make_script_with_merges(&pp, &revs, out, flags);
3835
62db5247 3836 while ((commit = get_revision(&revs))) {
76ea2358
PW
3837 int is_empty = is_original_commit_empty(commit);
3838
3839 if (!is_empty && (commit->object.flags & PATCHSAME))
3840 continue;
62db5247 3841 strbuf_reset(&buf);
76ea2358 3842 if (!keep_empty && is_empty)
62db5247 3843 strbuf_addf(&buf, "%c ", comment_line_char);
d8ae6c84
LB
3844 strbuf_addf(&buf, "%s %s ", insn,
3845 oid_to_hex(&commit->object.oid));
62db5247
JS
3846 pretty_print_commit(&pp, commit, &buf);
3847 strbuf_addch(&buf, '\n');
3848 fputs(buf.buf, out);
3849 }
3850 strbuf_release(&buf);
3851 return 0;
3852}
3546c8d9 3853
0cce4a27
LB
3854/*
3855 * Add commands after pick and (series of) squash/fixup commands
3856 * in the todo list.
3857 */
3858int sequencer_add_exec_commands(const char *commands)
3546c8d9
JS
3859{
3860 const char *todo_file = rebase_path_todo();
3861 struct todo_list todo_list = TODO_LIST_INIT;
0cce4a27
LB
3862 struct todo_item *item;
3863 struct strbuf *buf = &todo_list.buf;
3864 size_t offset = 0, commands_len = strlen(commands);
3865 int i, first;
3546c8d9 3866
0cce4a27 3867 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 3868 return error(_("could not read '%s'."), todo_file);
3546c8d9 3869
0cce4a27 3870 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3546c8d9
JS
3871 todo_list_release(&todo_list);
3872 return error(_("unusable todo list: '%s'"), todo_file);
3873 }
3874
0cce4a27
LB
3875 first = 1;
3876 /* insert <commands> before every pick except the first one */
3877 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3878 if (item->command == TODO_PICK && !first) {
3879 strbuf_insert(buf, item->offset_in_buf + offset,
3880 commands, commands_len);
3881 offset += commands_len;
3882 }
3883 first = 0;
3884 }
3885
3886 /* append final <commands> */
3887 strbuf_add(buf, commands, commands_len);
3888
3889 i = write_message(buf->buf, buf->len, todo_file, 0);
3890 todo_list_release(&todo_list);
3891 return i;
3892}
3546c8d9 3893
313a48ea 3894int transform_todos(unsigned flags)
3546c8d9
JS
3895{
3896 const char *todo_file = rebase_path_todo();
3897 struct todo_list todo_list = TODO_LIST_INIT;
8dccc7a6
LB
3898 struct strbuf buf = STRBUF_INIT;
3899 struct todo_item *item;
3900 int i;
3546c8d9 3901
8dccc7a6 3902 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3546c8d9 3903 return error(_("could not read '%s'."), todo_file);
3546c8d9 3904
8dccc7a6 3905 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3546c8d9 3906 todo_list_release(&todo_list);
3546c8d9
JS
3907 return error(_("unusable todo list: '%s'"), todo_file);
3908 }
3909
8dccc7a6
LB
3910 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3911 /* if the item is not a command write it and continue */
3912 if (item->command >= TODO_COMMENT) {
3913 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3914 continue;
3546c8d9 3915 }
8dccc7a6
LB
3916
3917 /* add command to the buffer */
d8ae6c84
LB
3918 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3919 strbuf_addch(&buf, command_to_char(item->command));
3920 else
3921 strbuf_addstr(&buf, command_to_string(item->command));
8dccc7a6
LB
3922
3923 /* add commit id */
3924 if (item->commit) {
313a48ea 3925 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
8dccc7a6
LB
3926 short_commit_name(item->commit) :
3927 oid_to_hex(&item->commit->object.oid);
3928
4c68e7dd
JS
3929 if (item->command == TODO_MERGE) {
3930 if (item->flags & TODO_EDIT_MERGE_MSG)
3931 strbuf_addstr(&buf, " -c");
3932 else
3933 strbuf_addstr(&buf, " -C");
3934 }
3935
8dccc7a6 3936 strbuf_addf(&buf, " %s", oid);
3546c8d9 3937 }
4c68e7dd 3938
8dccc7a6 3939 /* add all the rest */
c7b4d79c
JS
3940 if (!item->arg_len)
3941 strbuf_addch(&buf, '\n');
3942 else
3943 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3546c8d9 3944 }
8dccc7a6
LB
3945
3946 i = write_message(buf.buf, buf.len, todo_file, 0);
3546c8d9 3947 todo_list_release(&todo_list);
8dccc7a6 3948 return i;
3546c8d9 3949}
94399949
JS
3950
3951enum check_level {
3952 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3953};
3954
3955static enum check_level get_missing_commit_check_level(void)
3956{
3957 const char *value;
3958
3959 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3960 !strcasecmp("ignore", value))
3961 return CHECK_IGNORE;
3962 if (!strcasecmp("warn", value))
3963 return CHECK_WARN;
3964 if (!strcasecmp("error", value))
3965 return CHECK_ERROR;
dfab1eac 3966 warning(_("unrecognized setting %s for option "
94399949
JS
3967 "rebase.missingCommitsCheck. Ignoring."), value);
3968 return CHECK_IGNORE;
3969}
3970
3971/*
3972 * Check if the user dropped some commits by mistake
3973 * Behaviour determined by rebase.missingCommitsCheck.
3974 * Check if there is an unrecognized command or a
3975 * bad SHA-1 in a command.
3976 */
3977int check_todo_list(void)
3978{
3979 enum check_level check_level = get_missing_commit_check_level();
3980 struct strbuf todo_file = STRBUF_INIT;
3981 struct todo_list todo_list = TODO_LIST_INIT;
3982 struct strbuf missing = STRBUF_INIT;
87805600 3983 int advise_to_edit_todo = 0, res = 0, i;
94399949
JS
3984
3985 strbuf_addstr(&todo_file, rebase_path_todo());
87805600
RS
3986 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3987 res = -1;
94399949
JS
3988 goto leave_check;
3989 }
94399949
JS
3990 advise_to_edit_todo = res =
3991 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3992
3993 if (res || check_level == CHECK_IGNORE)
3994 goto leave_check;
3995
3996 /* Mark the commits in git-rebase-todo as seen */
3997 for (i = 0; i < todo_list.nr; i++) {
3998 struct commit *commit = todo_list.items[i].commit;
3999 if (commit)
4000 commit->util = (void *)1;
4001 }
4002
4003 todo_list_release(&todo_list);
4004 strbuf_addstr(&todo_file, ".backup");
87805600
RS
4005 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4006 res = -1;
94399949
JS
4007 goto leave_check;
4008 }
94399949
JS
4009 strbuf_release(&todo_file);
4010 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4011
4012 /* Find commits in git-rebase-todo.backup yet unseen */
4013 for (i = todo_list.nr - 1; i >= 0; i--) {
4014 struct todo_item *item = todo_list.items + i;
4015 struct commit *commit = item->commit;
4016 if (commit && !commit->util) {
4017 strbuf_addf(&missing, " - %s %.*s\n",
4018 short_commit_name(commit),
4019 item->arg_len, item->arg);
4020 commit->util = (void *)1;
4021 }
4022 }
4023
4024 /* Warn about missing commits */
4025 if (!missing.len)
4026 goto leave_check;
4027
4028 if (check_level == CHECK_ERROR)
4029 advise_to_edit_todo = res = 1;
4030
4031 fprintf(stderr,
4032 _("Warning: some commits may have been dropped accidentally.\n"
4033 "Dropped commits (newer to older):\n"));
4034
4035 /* Make the list user-friendly and display */
4036 fputs(missing.buf, stderr);
4037 strbuf_release(&missing);
4038
4039 fprintf(stderr, _("To avoid this message, use \"drop\" to "
4040 "explicitly remove a commit.\n\n"
4041 "Use 'git config rebase.missingCommitsCheck' to change "
4042 "the level of warnings.\n"
4043 "The possible behaviours are: ignore, warn, error.\n\n"));
4044
4045leave_check:
4046 strbuf_release(&todo_file);
4047 todo_list_release(&todo_list);
4048
4049 if (advise_to_edit_todo)
4050 fprintf(stderr,
4051 _("You can fix this with 'git rebase --edit-todo' "
4052 "and then run 'git rebase --continue'.\n"
4053 "Or you can abort the rebase with 'git rebase"
4054 " --abort'.\n"));
4055
4056 return res;
4057}
cdac2b01 4058
73646bfd
RS
4059static int rewrite_file(const char *path, const char *buf, size_t len)
4060{
4061 int rc = 0;
c8cee96e 4062 int fd = open(path, O_WRONLY | O_TRUNC);
73646bfd
RS
4063 if (fd < 0)
4064 return error_errno(_("could not open '%s' for writing"), path);
4065 if (write_in_full(fd, buf, len) < 0)
4066 rc = error_errno(_("could not write to '%s'"), path);
9360ec00
SR
4067 if (close(fd) && !rc)
4068 rc = error_errno(_("could not close '%s'"), path);
73646bfd
RS
4069 return rc;
4070}
4071
cdac2b01
JS
4072/* skip picking commits whose parents are unchanged */
4073int skip_unnecessary_picks(void)
4074{
4075 const char *todo_file = rebase_path_todo();
4076 struct strbuf buf = STRBUF_INIT;
4077 struct todo_list todo_list = TODO_LIST_INIT;
4078 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4079 int fd, i;
4080
4081 if (!read_oneliner(&buf, rebase_path_onto(), 0))
4082 return error(_("could not read 'onto'"));
4083 if (get_oid(buf.buf, &onto_oid)) {
4084 strbuf_release(&buf);
4085 return error(_("need a HEAD to fixup"));
4086 }
4087 strbuf_release(&buf);
4088
87805600
RS
4089 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4090 return -1;
cdac2b01
JS
4091 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4092 todo_list_release(&todo_list);
4093 return -1;
4094 }
4095
4096 for (i = 0; i < todo_list.nr; i++) {
4097 struct todo_item *item = todo_list.items + i;
4098
4099 if (item->command >= TODO_NOOP)
4100 continue;
4101 if (item->command != TODO_PICK)
4102 break;
4103 if (parse_commit(item->commit)) {
4104 todo_list_release(&todo_list);
4105 return error(_("could not parse commit '%s'"),
4106 oid_to_hex(&item->commit->object.oid));
4107 }
4108 if (!item->commit->parents)
4109 break; /* root commit */
4110 if (item->commit->parents->next)
4111 break; /* merge commit */
4112 parent_oid = &item->commit->parents->item->object.oid;
4113 if (hashcmp(parent_oid->hash, oid->hash))
4114 break;
4115 oid = &item->commit->object.oid;
4116 }
4117 if (i > 0) {
a01c2a5f 4118 int offset = get_item_line_offset(&todo_list, i);
cdac2b01
JS
4119 const char *done_path = rebase_path_done();
4120
4121 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4122 if (fd < 0) {
4123 error_errno(_("could not open '%s' for writing"),
4124 done_path);
4125 todo_list_release(&todo_list);
4126 return -1;
4127 }
4128 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4129 error_errno(_("could not write to '%s'"), done_path);
4130 todo_list_release(&todo_list);
4131 close(fd);
4132 return -1;
4133 }
4134 close(fd);
4135
73646bfd
RS
4136 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4137 todo_list.buf.len - offset) < 0) {
cdac2b01 4138 todo_list_release(&todo_list);
cdac2b01
JS
4139 return -1;
4140 }
cdac2b01
JS
4141
4142 todo_list.current = i;
4143 if (is_fixup(peek_command(&todo_list, 0)))
4144 record_in_rewritten(oid, peek_command(&todo_list, 0));
4145 }
4146
4147 todo_list_release(&todo_list);
4148 printf("%s\n", oid_to_hex(oid));
4149
4150 return 0;
4151}
c44a4c65
JS
4152
4153struct subject2item_entry {
4154 struct hashmap_entry entry;
4155 int i;
4156 char subject[FLEX_ARRAY];
4157};
4158
4159static int subject2item_cmp(const void *fndata,
4160 const struct subject2item_entry *a,
4161 const struct subject2item_entry *b, const void *key)
4162{
4163 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4164}
4165
4166/*
4167 * Rearrange the todo list that has both "pick commit-id msg" and "pick
4168 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4169 * after the former, and change "pick" to "fixup"/"squash".
4170 *
4171 * Note that if the config has specified a custom instruction format, each log
4172 * message will have to be retrieved from the commit (as the oneline in the
4173 * script cannot be trusted) in order to normalize the autosquash arrangement.
4174 */
4175int rearrange_squash(void)
4176{
4177 const char *todo_file = rebase_path_todo();
4178 struct todo_list todo_list = TODO_LIST_INIT;
4179 struct hashmap subject2item;
87805600 4180 int res = 0, rearranged = 0, *next, *tail, i;
c44a4c65
JS
4181 char **subjects;
4182
87805600
RS
4183 if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4184 return -1;
c44a4c65
JS
4185 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4186 todo_list_release(&todo_list);
4187 return -1;
4188 }
4189
4190 /*
4191 * The hashmap maps onelines to the respective todo list index.
4192 *
4193 * If any items need to be rearranged, the next[i] value will indicate
4194 * which item was moved directly after the i'th.
4195 *
4196 * In that case, last[i] will indicate the index of the latest item to
4197 * be moved to appear after the i'th.
4198 */
4199 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4200 NULL, todo_list.nr);
4201 ALLOC_ARRAY(next, todo_list.nr);
4202 ALLOC_ARRAY(tail, todo_list.nr);
4203 ALLOC_ARRAY(subjects, todo_list.nr);
4204 for (i = 0; i < todo_list.nr; i++) {
4205 struct strbuf buf = STRBUF_INIT;
4206 struct todo_item *item = todo_list.items + i;
4207 const char *commit_buffer, *subject, *p;
4208 size_t subject_len;
4209 int i2 = -1;
4210 struct subject2item_entry *entry;
4211
4212 next[i] = tail[i] = -1;
2f6b1d13 4213 if (!item->commit || item->command == TODO_DROP) {
c44a4c65
JS
4214 subjects[i] = NULL;
4215 continue;
4216 }
4217
4218 if (is_fixup(item->command)) {
4219 todo_list_release(&todo_list);
4220 return error(_("the script was already rearranged."));
4221 }
4222
4223 item->commit->util = item;
4224
4225 parse_commit(item->commit);
4226 commit_buffer = get_commit_buffer(item->commit, NULL);
4227 find_commit_subject(commit_buffer, &subject);
4228 format_subject(&buf, subject, " ");
4229 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4230 unuse_commit_buffer(item->commit, commit_buffer);
4231 if ((skip_prefix(subject, "fixup! ", &p) ||
4232 skip_prefix(subject, "squash! ", &p))) {
4233 struct commit *commit2;
4234
4235 for (;;) {
4236 while (isspace(*p))
4237 p++;
4238 if (!skip_prefix(p, "fixup! ", &p) &&
4239 !skip_prefix(p, "squash! ", &p))
4240 break;
4241 }
4242
4243 if ((entry = hashmap_get_from_hash(&subject2item,
4244 strhash(p), p)))
4245 /* found by title */
4246 i2 = entry->i;
4247 else if (!strchr(p, ' ') &&
4248 (commit2 =
4249 lookup_commit_reference_by_name(p)) &&
4250 commit2->util)
4251 /* found by commit name */
4252 i2 = (struct todo_item *)commit2->util
4253 - todo_list.items;
4254 else {
4255 /* copy can be a prefix of the commit subject */
4256 for (i2 = 0; i2 < i; i2++)
4257 if (subjects[i2] &&
4258 starts_with(subjects[i2], p))
4259 break;
4260 if (i2 == i)
4261 i2 = -1;
4262 }
4263 }
4264 if (i2 >= 0) {
4265 rearranged = 1;
4266 todo_list.items[i].command =
4267 starts_with(subject, "fixup!") ?
4268 TODO_FIXUP : TODO_SQUASH;
4269 if (next[i2] < 0)
4270 next[i2] = i;
4271 else
4272 next[tail[i2]] = i;
4273 tail[i2] = i;
4274 } else if (!hashmap_get_from_hash(&subject2item,
4275 strhash(subject), subject)) {
4276 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4277 entry->i = i;
4278 hashmap_entry_init(entry, strhash(entry->subject));
4279 hashmap_put(&subject2item, entry);
4280 }
4281 }
4282
4283 if (rearranged) {
4284 struct strbuf buf = STRBUF_INIT;
4285
4286 for (i = 0; i < todo_list.nr; i++) {
4287 enum todo_command command = todo_list.items[i].command;
4288 int cur = i;
4289
4290 /*
4291 * Initially, all commands are 'pick's. If it is a
4292 * fixup or a squash now, we have rearranged it.
4293 */
4294 if (is_fixup(command))
4295 continue;
4296
4297 while (cur >= 0) {
a01c2a5f
JS
4298 const char *bol =
4299 get_item_line(&todo_list, cur);
4300 const char *eol =
4301 get_item_line(&todo_list, cur + 1);
c44a4c65
JS
4302
4303 /* replace 'pick', by 'fixup' or 'squash' */
4304 command = todo_list.items[cur].command;
4305 if (is_fixup(command)) {
4306 strbuf_addstr(&buf,
4307 todo_command_info[command].str);
4308 bol += strcspn(bol, " \t");
4309 }
4310
4311 strbuf_add(&buf, bol, eol - bol);
4312
4313 cur = next[cur];
4314 }
4315 }
4316
73646bfd 4317 res = rewrite_file(todo_file, buf.buf, buf.len);
c44a4c65
JS
4318 strbuf_release(&buf);
4319 }
4320
4321 free(next);
4322 free(tail);
4323 for (i = 0; i < todo_list.nr; i++)
4324 free(subjects[i]);
4325 free(subjects);
4326 hashmap_free(&subject2item, 1);
4327 todo_list_release(&todo_list);
4328
4329 return res;
4330}