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