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