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