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