rebase-interactive: warn if commit is dropped with `rebase --edit-todo'
[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         char **xopt;
594         struct lock_file index_lock = LOCK_INIT;
595
596         if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
597                 return -1;
598
599         repo_read_index(r);
600
601         init_merge_options(&o, r);
602         o.ancestor = base ? base_label : "(empty tree)";
603         o.branch1 = "HEAD";
604         o.branch2 = next ? next_label : "(empty tree)";
605         if (is_rebase_i(opts))
606                 o.buffer_output = 2;
607         o.show_rename_progress = 1;
608
609         head_tree = parse_tree_indirect(head);
610         next_tree = next ? get_commit_tree(next) : empty_tree(r);
611         base_tree = base ? get_commit_tree(base) : empty_tree(r);
612
613         for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
614                 parse_merge_opt(&o, *xopt);
615
616         clean = merge_trees(&o,
617                             head_tree,
618                             next_tree, base_tree);
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 int prepare_branch_to_be_rebased(struct repository *r, struct replay_opts *opts,
3722                                  const char *commit)
3723 {
3724         const char *action;
3725
3726         if (commit && *commit) {
3727                 action = reflog_message(opts, "start", "checkout %s", commit);
3728                 if (run_git_checkout(r, opts, commit, action))
3729                         return error(_("could not checkout %s"), commit);
3730         }
3731
3732         return 0;
3733 }
3734
3735 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3736                          const char *onto_name, const struct object_id *onto,
3737                          const char *orig_head)
3738 {
3739         struct object_id oid;
3740         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3741
3742         if (get_oid(orig_head, &oid))
3743                 return error(_("%s: not a valid OID"), orig_head);
3744
3745         if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3746                 apply_autostash(opts);
3747                 sequencer_remove_state(opts);
3748                 return error(_("could not detach HEAD"));
3749         }
3750
3751         return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3752 }
3753
3754 static int stopped_at_head(struct repository *r)
3755 {
3756         struct object_id head;
3757         struct commit *commit;
3758         struct commit_message message;
3759
3760         if (get_oid("HEAD", &head) ||
3761             !(commit = lookup_commit(r, &head)) ||
3762             parse_commit(commit) || get_message(commit, &message))
3763                 fprintf(stderr, _("Stopped at HEAD\n"));
3764         else {
3765                 fprintf(stderr, _("Stopped at %s\n"), message.label);
3766                 free_message(commit, &message);
3767         }
3768         return 0;
3769
3770 }
3771
3772 static const char rescheduled_advice[] =
3773 N_("Could not execute the todo command\n"
3774 "\n"
3775 "    %.*s"
3776 "\n"
3777 "It has been rescheduled; To edit the command before continuing, please\n"
3778 "edit the todo list first:\n"
3779 "\n"
3780 "    git rebase --edit-todo\n"
3781 "    git rebase --continue\n");
3782
3783 static int pick_commits(struct repository *r,
3784                         struct todo_list *todo_list,
3785                         struct replay_opts *opts)
3786 {
3787         int res = 0, reschedule = 0;
3788
3789         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3790         if (opts->allow_ff)
3791                 assert(!(opts->signoff || opts->no_commit ||
3792                                 opts->record_origin || opts->edit));
3793         if (read_and_refresh_cache(r, opts))
3794                 return -1;
3795
3796         while (todo_list->current < todo_list->nr) {
3797                 struct todo_item *item = todo_list->items + todo_list->current;
3798                 const char *arg = todo_item_get_arg(todo_list, item);
3799                 int check_todo = 0;
3800
3801                 if (save_todo(todo_list, opts))
3802                         return -1;
3803                 if (is_rebase_i(opts)) {
3804                         if (item->command != TODO_COMMENT) {
3805                                 FILE *f = fopen(rebase_path_msgnum(), "w");
3806
3807                                 todo_list->done_nr++;
3808
3809                                 if (f) {
3810                                         fprintf(f, "%d\n", todo_list->done_nr);
3811                                         fclose(f);
3812                                 }
3813                                 if (!opts->quiet)
3814                                         fprintf(stderr, "Rebasing (%d/%d)%s",
3815                                                 todo_list->done_nr,
3816                                                 todo_list->total_nr,
3817                                                 opts->verbose ? "\n" : "\r");
3818                         }
3819                         unlink(rebase_path_message());
3820                         unlink(rebase_path_author_script());
3821                         unlink(rebase_path_stopped_sha());
3822                         unlink(rebase_path_amend());
3823                         unlink(git_path_merge_head(r));
3824                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3825
3826                         if (item->command == TODO_BREAK) {
3827                                 if (!opts->verbose)
3828                                         term_clear_line();
3829                                 return stopped_at_head(r);
3830                         }
3831                 }
3832                 if (item->command <= TODO_SQUASH) {
3833                         if (is_rebase_i(opts))
3834                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3835                                         command_to_string(item->command), NULL),
3836                                         1);
3837                         res = do_pick_commit(r, item->command, item->commit,
3838                                              opts, is_final_fixup(todo_list),
3839                                              &check_todo);
3840                         if (is_rebase_i(opts) && res < 0) {
3841                                 /* Reschedule */
3842                                 advise(_(rescheduled_advice),
3843                                        get_item_line_length(todo_list,
3844                                                             todo_list->current),
3845                                        get_item_line(todo_list,
3846                                                      todo_list->current));
3847                                 todo_list->current--;
3848                                 if (save_todo(todo_list, opts))
3849                                         return -1;
3850                         }
3851                         if (item->command == TODO_EDIT) {
3852                                 struct commit *commit = item->commit;
3853                                 if (!res) {
3854                                         if (!opts->verbose)
3855                                                 term_clear_line();
3856                                         fprintf(stderr,
3857                                                 _("Stopped at %s...  %.*s\n"),
3858                                                 short_commit_name(commit),
3859                                                 item->arg_len, arg);
3860                                 }
3861                                 return error_with_patch(r, commit,
3862                                         arg, item->arg_len, opts, res, !res);
3863                         }
3864                         if (is_rebase_i(opts) && !res)
3865                                 record_in_rewritten(&item->commit->object.oid,
3866                                         peek_command(todo_list, 1));
3867                         if (res && is_fixup(item->command)) {
3868                                 if (res == 1)
3869                                         intend_to_amend();
3870                                 return error_failed_squash(r, item->commit, opts,
3871                                         item->arg_len, arg);
3872                         } else if (res && is_rebase_i(opts) && item->commit) {
3873                                 int to_amend = 0;
3874                                 struct object_id oid;
3875
3876                                 /*
3877                                  * If we are rewording and have either
3878                                  * fast-forwarded already, or are about to
3879                                  * create a new root commit, we want to amend,
3880                                  * otherwise we do not.
3881                                  */
3882                                 if (item->command == TODO_REWORD &&
3883                                     !get_oid("HEAD", &oid) &&
3884                                     (oideq(&item->commit->object.oid, &oid) ||
3885                                      (opts->have_squash_onto &&
3886                                       oideq(&opts->squash_onto, &oid))))
3887                                         to_amend = 1;
3888
3889                                 return res | error_with_patch(r, item->commit,
3890                                                 arg, item->arg_len, opts,
3891                                                 res, to_amend);
3892                         }
3893                 } else if (item->command == TODO_EXEC) {
3894                         char *end_of_arg = (char *)(arg + item->arg_len);
3895                         int saved = *end_of_arg;
3896
3897                         if (!opts->verbose)
3898                                 term_clear_line();
3899                         *end_of_arg = '\0';
3900                         res = do_exec(r, arg);
3901                         *end_of_arg = saved;
3902
3903                         if (res) {
3904                                 if (opts->reschedule_failed_exec)
3905                                         reschedule = 1;
3906                         }
3907                         check_todo = 1;
3908                 } else if (item->command == TODO_LABEL) {
3909                         if ((res = do_label(r, arg, item->arg_len)))
3910                                 reschedule = 1;
3911                 } else if (item->command == TODO_RESET) {
3912                         if ((res = do_reset(r, arg, item->arg_len, opts)))
3913                                 reschedule = 1;
3914                 } else if (item->command == TODO_MERGE) {
3915                         if ((res = do_merge(r, item->commit,
3916                                             arg, item->arg_len,
3917                                             item->flags, opts)) < 0)
3918                                 reschedule = 1;
3919                         else if (item->commit)
3920                                 record_in_rewritten(&item->commit->object.oid,
3921                                                     peek_command(todo_list, 1));
3922                         if (res > 0)
3923                                 /* failed with merge conflicts */
3924                                 return error_with_patch(r, item->commit,
3925                                                         arg, item->arg_len,
3926                                                         opts, res, 0);
3927                 } else if (!is_noop(item->command))
3928                         return error(_("unknown command %d"), item->command);
3929
3930                 if (reschedule) {
3931                         advise(_(rescheduled_advice),
3932                                get_item_line_length(todo_list,
3933                                                     todo_list->current),
3934                                get_item_line(todo_list, todo_list->current));
3935                         todo_list->current--;
3936                         if (save_todo(todo_list, opts))
3937                                 return -1;
3938                         if (item->commit)
3939                                 return error_with_patch(r,
3940                                                         item->commit,
3941                                                         arg, item->arg_len,
3942                                                         opts, res, 0);
3943                 } else if (is_rebase_i(opts) && check_todo && !res) {
3944                         struct stat st;
3945
3946                         if (stat(get_todo_path(opts), &st)) {
3947                                 res = error_errno(_("could not stat '%s'"),
3948                                                   get_todo_path(opts));
3949                         } else if (match_stat_data(&todo_list->stat, &st)) {
3950                                 /* Reread the todo file if it has changed. */
3951                                 todo_list_release(todo_list);
3952                                 if (read_populate_todo(r, todo_list, opts))
3953                                         res = -1; /* message was printed */
3954                                 /* `current` will be incremented below */
3955                                 todo_list->current = -1;
3956                         }
3957                 }
3958
3959                 todo_list->current++;
3960                 if (res)
3961                         return res;
3962         }
3963
3964         if (is_rebase_i(opts)) {
3965                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3966                 struct stat st;
3967
3968                 /* Stopped in the middle, as planned? */
3969                 if (todo_list->current < todo_list->nr)
3970                         return 0;
3971
3972                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3973                                 starts_with(head_ref.buf, "refs/")) {
3974                         const char *msg;
3975                         struct object_id head, orig;
3976                         int res;
3977
3978                         if (get_oid("HEAD", &head)) {
3979                                 res = error(_("cannot read HEAD"));
3980 cleanup_head_ref:
3981                                 strbuf_release(&head_ref);
3982                                 strbuf_release(&buf);
3983                                 return res;
3984                         }
3985                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3986                                         get_oid_hex(buf.buf, &orig)) {
3987                                 res = error(_("could not read orig-head"));
3988                                 goto cleanup_head_ref;
3989                         }
3990                         strbuf_reset(&buf);
3991                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3992                                 res = error(_("could not read 'onto'"));
3993                                 goto cleanup_head_ref;
3994                         }
3995                         msg = reflog_message(opts, "finish", "%s onto %s",
3996                                 head_ref.buf, buf.buf);
3997                         if (update_ref(msg, head_ref.buf, &head, &orig,
3998                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3999                                 res = error(_("could not update %s"),
4000                                         head_ref.buf);
4001                                 goto cleanup_head_ref;
4002                         }
4003                         msg = reflog_message(opts, "finish", "returning to %s",
4004                                 head_ref.buf);
4005                         if (create_symref("HEAD", head_ref.buf, msg)) {
4006                                 res = error(_("could not update HEAD to %s"),
4007                                         head_ref.buf);
4008                                 goto cleanup_head_ref;
4009                         }
4010                         strbuf_reset(&buf);
4011                 }
4012
4013                 if (opts->verbose) {
4014                         struct rev_info log_tree_opt;
4015                         struct object_id orig, head;
4016
4017                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4018                         repo_init_revisions(r, &log_tree_opt, NULL);
4019                         log_tree_opt.diff = 1;
4020                         log_tree_opt.diffopt.output_format =
4021                                 DIFF_FORMAT_DIFFSTAT;
4022                         log_tree_opt.disable_stdin = 1;
4023
4024                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4025                             !get_oid(buf.buf, &orig) &&
4026                             !get_oid("HEAD", &head)) {
4027                                 diff_tree_oid(&orig, &head, "",
4028                                               &log_tree_opt.diffopt);
4029                                 log_tree_diff_flush(&log_tree_opt);
4030                         }
4031                 }
4032                 flush_rewritten_pending();
4033                 if (!stat(rebase_path_rewritten_list(), &st) &&
4034                                 st.st_size > 0) {
4035                         struct child_process child = CHILD_PROCESS_INIT;
4036                         const char *post_rewrite_hook =
4037                                 find_hook("post-rewrite");
4038
4039                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4040                         child.git_cmd = 1;
4041                         argv_array_push(&child.args, "notes");
4042                         argv_array_push(&child.args, "copy");
4043                         argv_array_push(&child.args, "--for-rewrite=rebase");
4044                         /* we don't care if this copying failed */
4045                         run_command(&child);
4046
4047                         if (post_rewrite_hook) {
4048                                 struct child_process hook = CHILD_PROCESS_INIT;
4049
4050                                 hook.in = open(rebase_path_rewritten_list(),
4051                                         O_RDONLY);
4052                                 hook.stdout_to_stderr = 1;
4053                                 hook.trace2_hook_name = "post-rewrite";
4054                                 argv_array_push(&hook.args, post_rewrite_hook);
4055                                 argv_array_push(&hook.args, "rebase");
4056                                 /* we don't care if this hook failed */
4057                                 run_command(&hook);
4058                         }
4059                 }
4060                 apply_autostash(opts);
4061
4062                 if (!opts->quiet) {
4063                         if (!opts->verbose)
4064                                 term_clear_line();
4065                         fprintf(stderr,
4066                                 "Successfully rebased and updated %s.\n",
4067                                 head_ref.buf);
4068                 }
4069
4070                 strbuf_release(&buf);
4071                 strbuf_release(&head_ref);
4072         }
4073
4074         /*
4075          * Sequence of picks finished successfully; cleanup by
4076          * removing the .git/sequencer directory
4077          */
4078         return sequencer_remove_state(opts);
4079 }
4080
4081 static int continue_single_pick(struct repository *r)
4082 {
4083         const char *argv[] = { "commit", NULL };
4084
4085         if (!file_exists(git_path_cherry_pick_head(r)) &&
4086             !file_exists(git_path_revert_head(r)))
4087                 return error(_("no cherry-pick or revert in progress"));
4088         return run_command_v_opt(argv, RUN_GIT_CMD);
4089 }
4090
4091 static int commit_staged_changes(struct repository *r,
4092                                  struct replay_opts *opts,
4093                                  struct todo_list *todo_list)
4094 {
4095         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4096         unsigned int final_fixup = 0, is_clean;
4097
4098         if (has_unstaged_changes(r, 1))
4099                 return error(_("cannot rebase: You have unstaged changes."));
4100
4101         is_clean = !has_uncommitted_changes(r, 0);
4102
4103         if (file_exists(rebase_path_amend())) {
4104                 struct strbuf rev = STRBUF_INIT;
4105                 struct object_id head, to_amend;
4106
4107                 if (get_oid("HEAD", &head))
4108                         return error(_("cannot amend non-existing commit"));
4109                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4110                         return error(_("invalid file: '%s'"), rebase_path_amend());
4111                 if (get_oid_hex(rev.buf, &to_amend))
4112                         return error(_("invalid contents: '%s'"),
4113                                 rebase_path_amend());
4114                 if (!is_clean && !oideq(&head, &to_amend))
4115                         return error(_("\nYou have uncommitted changes in your "
4116                                        "working tree. Please, commit them\n"
4117                                        "first and then run 'git rebase "
4118                                        "--continue' again."));
4119                 /*
4120                  * When skipping a failed fixup/squash, we need to edit the
4121                  * commit message, the current fixup list and count, and if it
4122                  * was the last fixup/squash in the chain, we need to clean up
4123                  * the commit message and if there was a squash, let the user
4124                  * edit it.
4125                  */
4126                 if (!is_clean || !opts->current_fixup_count)
4127                         ; /* this is not the final fixup */
4128                 else if (!oideq(&head, &to_amend) ||
4129                          !file_exists(rebase_path_stopped_sha())) {
4130                         /* was a final fixup or squash done manually? */
4131                         if (!is_fixup(peek_command(todo_list, 0))) {
4132                                 unlink(rebase_path_fixup_msg());
4133                                 unlink(rebase_path_squash_msg());
4134                                 unlink(rebase_path_current_fixups());
4135                                 strbuf_reset(&opts->current_fixups);
4136                                 opts->current_fixup_count = 0;
4137                         }
4138                 } else {
4139                         /* we are in a fixup/squash chain */
4140                         const char *p = opts->current_fixups.buf;
4141                         int len = opts->current_fixups.len;
4142
4143                         opts->current_fixup_count--;
4144                         if (!len)
4145                                 BUG("Incorrect current_fixups:\n%s", p);
4146                         while (len && p[len - 1] != '\n')
4147                                 len--;
4148                         strbuf_setlen(&opts->current_fixups, len);
4149                         if (write_message(p, len, rebase_path_current_fixups(),
4150                                           0) < 0)
4151                                 return error(_("could not write file: '%s'"),
4152                                              rebase_path_current_fixups());
4153
4154                         /*
4155                          * If a fixup/squash in a fixup/squash chain failed, the
4156                          * commit message is already correct, no need to commit
4157                          * it again.
4158                          *
4159                          * Only if it is the final command in the fixup/squash
4160                          * chain, and only if the chain is longer than a single
4161                          * fixup/squash command (which was just skipped), do we
4162                          * actually need to re-commit with a cleaned up commit
4163                          * message.
4164                          */
4165                         if (opts->current_fixup_count > 0 &&
4166                             !is_fixup(peek_command(todo_list, 0))) {
4167                                 final_fixup = 1;
4168                                 /*
4169                                  * If there was not a single "squash" in the
4170                                  * chain, we only need to clean up the commit
4171                                  * message, no need to bother the user with
4172                                  * opening the commit message in the editor.
4173                                  */
4174                                 if (!starts_with(p, "squash ") &&
4175                                     !strstr(p, "\nsquash "))
4176                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4177                         } else if (is_fixup(peek_command(todo_list, 0))) {
4178                                 /*
4179                                  * We need to update the squash message to skip
4180                                  * the latest commit message.
4181                                  */
4182                                 struct commit *commit;
4183                                 const char *path = rebase_path_squash_msg();
4184                                 const char *encoding = get_commit_output_encoding();
4185
4186                                 if (parse_head(r, &commit) ||
4187                                     !(p = logmsg_reencode(commit, NULL, encoding)) ||
4188                                     write_message(p, strlen(p), path, 0)) {
4189                                         unuse_commit_buffer(commit, p);
4190                                         return error(_("could not write file: "
4191                                                        "'%s'"), path);
4192                                 }
4193                                 unuse_commit_buffer(commit, p);
4194                         }
4195                 }
4196
4197                 strbuf_release(&rev);
4198                 flags |= AMEND_MSG;
4199         }
4200
4201         if (is_clean) {
4202                 const char *cherry_pick_head = git_path_cherry_pick_head(r);
4203
4204                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
4205                         return error(_("could not remove CHERRY_PICK_HEAD"));
4206                 if (!final_fixup)
4207                         return 0;
4208         }
4209
4210         if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4211                            opts, flags))
4212                 return error(_("could not commit staged changes."));
4213         unlink(rebase_path_amend());
4214         unlink(git_path_merge_head(r));
4215         if (final_fixup) {
4216                 unlink(rebase_path_fixup_msg());
4217                 unlink(rebase_path_squash_msg());
4218         }
4219         if (opts->current_fixup_count > 0) {
4220                 /*
4221                  * Whether final fixup or not, we just cleaned up the commit
4222                  * message...
4223                  */
4224                 unlink(rebase_path_current_fixups());
4225                 strbuf_reset(&opts->current_fixups);
4226                 opts->current_fixup_count = 0;
4227         }
4228         return 0;
4229 }
4230
4231 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4232 {
4233         struct todo_list todo_list = TODO_LIST_INIT;
4234         int res;
4235
4236         if (read_and_refresh_cache(r, opts))
4237                 return -1;
4238
4239         if (read_populate_opts(opts))
4240                 return -1;
4241         if (is_rebase_i(opts)) {
4242                 if ((res = read_populate_todo(r, &todo_list, opts)))
4243                         goto release_todo_list;
4244
4245                 if (file_exists(rebase_path_dropped())) {
4246                         if ((res = todo_list_check_against_backup(r, &todo_list)))
4247                                 goto release_todo_list;
4248
4249                         unlink(rebase_path_dropped());
4250                 }
4251
4252                 if (commit_staged_changes(r, opts, &todo_list)) {
4253                         res = -1;
4254                         goto release_todo_list;
4255                 }
4256         } else if (!file_exists(get_todo_path(opts)))
4257                 return continue_single_pick(r);
4258         else if ((res = read_populate_todo(r, &todo_list, opts)))
4259                 goto release_todo_list;
4260
4261         if (!is_rebase_i(opts)) {
4262                 /* Verify that the conflict has been resolved */
4263                 if (file_exists(git_path_cherry_pick_head(r)) ||
4264                     file_exists(git_path_revert_head(r))) {
4265                         res = continue_single_pick(r);
4266                         if (res)
4267                                 goto release_todo_list;
4268                 }
4269                 if (index_differs_from(r, "HEAD", NULL, 0)) {
4270                         res = error_dirty_index(r, opts);
4271                         goto release_todo_list;
4272                 }
4273                 todo_list.current++;
4274         } else if (file_exists(rebase_path_stopped_sha())) {
4275                 struct strbuf buf = STRBUF_INIT;
4276                 struct object_id oid;
4277
4278                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
4279                     !get_oid_committish(buf.buf, &oid))
4280                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
4281                 strbuf_release(&buf);
4282         }
4283
4284         res = pick_commits(r, &todo_list, opts);
4285 release_todo_list:
4286         todo_list_release(&todo_list);
4287         return res;
4288 }
4289
4290 static int single_pick(struct repository *r,
4291                        struct commit *cmit,
4292                        struct replay_opts *opts)
4293 {
4294         int check_todo;
4295
4296         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4297         return do_pick_commit(r, opts->action == REPLAY_PICK ?
4298                               TODO_PICK : TODO_REVERT, cmit, opts, 0,
4299                               &check_todo);
4300 }
4301
4302 int sequencer_pick_revisions(struct repository *r,
4303                              struct replay_opts *opts)
4304 {
4305         struct todo_list todo_list = TODO_LIST_INIT;
4306         struct object_id oid;
4307         int i, res;
4308
4309         assert(opts->revs);
4310         if (read_and_refresh_cache(r, opts))
4311                 return -1;
4312
4313         for (i = 0; i < opts->revs->pending.nr; i++) {
4314                 struct object_id oid;
4315                 const char *name = opts->revs->pending.objects[i].name;
4316
4317                 /* This happens when using --stdin. */
4318                 if (!strlen(name))
4319                         continue;
4320
4321                 if (!get_oid(name, &oid)) {
4322                         if (!lookup_commit_reference_gently(r, &oid, 1)) {
4323                                 enum object_type type = oid_object_info(r,
4324                                                                         &oid,
4325                                                                         NULL);
4326                                 return error(_("%s: can't cherry-pick a %s"),
4327                                         name, type_name(type));
4328                         }
4329                 } else
4330                         return error(_("%s: bad revision"), name);
4331         }
4332
4333         /*
4334          * If we were called as "git cherry-pick <commit>", just
4335          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4336          * REVERT_HEAD, and don't touch the sequencer state.
4337          * This means it is possible to cherry-pick in the middle
4338          * of a cherry-pick sequence.
4339          */
4340         if (opts->revs->cmdline.nr == 1 &&
4341             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4342             opts->revs->no_walk &&
4343             !opts->revs->cmdline.rev->flags) {
4344                 struct commit *cmit;
4345                 if (prepare_revision_walk(opts->revs))
4346                         return error(_("revision walk setup failed"));
4347                 cmit = get_revision(opts->revs);
4348                 if (!cmit)
4349                         return error(_("empty commit set passed"));
4350                 if (get_revision(opts->revs))
4351                         BUG("unexpected extra commit from walk");
4352                 return single_pick(r, cmit, opts);
4353         }
4354
4355         /*
4356          * Start a new cherry-pick/ revert sequence; but
4357          * first, make sure that an existing one isn't in
4358          * progress
4359          */
4360
4361         if (walk_revs_populate_todo(&todo_list, opts) ||
4362                         create_seq_dir(r) < 0)
4363                 return -1;
4364         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4365                 return error(_("can't revert as initial commit"));
4366         if (save_head(oid_to_hex(&oid)))
4367                 return -1;
4368         if (save_opts(opts))
4369                 return -1;
4370         update_abort_safety_file();
4371         res = pick_commits(r, &todo_list, opts);
4372         todo_list_release(&todo_list);
4373         return res;
4374 }
4375
4376 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4377 {
4378         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4379         struct strbuf sob = STRBUF_INIT;
4380         int has_footer;
4381
4382         strbuf_addstr(&sob, sign_off_header);
4383         strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4384         strbuf_addch(&sob, '\n');
4385
4386         if (!ignore_footer)
4387                 strbuf_complete_line(msgbuf);
4388
4389         /*
4390          * If the whole message buffer is equal to the sob, pretend that we
4391          * found a conforming footer with a matching sob
4392          */
4393         if (msgbuf->len - ignore_footer == sob.len &&
4394             !strncmp(msgbuf->buf, sob.buf, sob.len))
4395                 has_footer = 3;
4396         else
4397                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4398
4399         if (!has_footer) {
4400                 const char *append_newlines = NULL;
4401                 size_t len = msgbuf->len - ignore_footer;
4402
4403                 if (!len) {
4404                         /*
4405                          * The buffer is completely empty.  Leave foom for
4406                          * the title and body to be filled in by the user.
4407                          */
4408                         append_newlines = "\n\n";
4409                 } else if (len == 1) {
4410                         /*
4411                          * Buffer contains a single newline.  Add another
4412                          * so that we leave room for the title and body.
4413                          */
4414                         append_newlines = "\n";
4415                 } else if (msgbuf->buf[len - 2] != '\n') {
4416                         /*
4417                          * Buffer ends with a single newline.  Add another
4418                          * so that there is an empty line between the message
4419                          * body and the sob.
4420                          */
4421                         append_newlines = "\n";
4422                 } /* else, the buffer already ends with two newlines. */
4423
4424                 if (append_newlines)
4425                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4426                                 append_newlines, strlen(append_newlines));
4427         }
4428
4429         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4430                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4431                                 sob.buf, sob.len);
4432
4433         strbuf_release(&sob);
4434 }
4435
4436 struct labels_entry {
4437         struct hashmap_entry entry;
4438         char label[FLEX_ARRAY];
4439 };
4440
4441 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4442                       const struct hashmap_entry *entry_or_key, const void *key)
4443 {
4444         const struct labels_entry *a, *b;
4445
4446         a = container_of(eptr, const struct labels_entry, entry);
4447         b = container_of(entry_or_key, const struct labels_entry, entry);
4448
4449         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4450 }
4451
4452 struct string_entry {
4453         struct oidmap_entry entry;
4454         char string[FLEX_ARRAY];
4455 };
4456
4457 struct label_state {
4458         struct oidmap commit2label;
4459         struct hashmap labels;
4460         struct strbuf buf;
4461 };
4462
4463 static const char *label_oid(struct object_id *oid, const char *label,
4464                              struct label_state *state)
4465 {
4466         struct labels_entry *labels_entry;
4467         struct string_entry *string_entry;
4468         struct object_id dummy;
4469         int i;
4470
4471         string_entry = oidmap_get(&state->commit2label, oid);
4472         if (string_entry)
4473                 return string_entry->string;
4474
4475         /*
4476          * For "uninteresting" commits, i.e. commits that are not to be
4477          * rebased, and which can therefore not be labeled, we use a unique
4478          * abbreviation of the commit name. This is slightly more complicated
4479          * than calling find_unique_abbrev() because we also need to make
4480          * sure that the abbreviation does not conflict with any other
4481          * label.
4482          *
4483          * We disallow "interesting" commits to be labeled by a string that
4484          * is a valid full-length hash, to ensure that we always can find an
4485          * abbreviation for any uninteresting commit's names that does not
4486          * clash with any other label.
4487          */
4488         strbuf_reset(&state->buf);
4489         if (!label) {
4490                 char *p;
4491
4492                 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4493                 label = p = state->buf.buf;
4494
4495                 find_unique_abbrev_r(p, oid, default_abbrev);
4496
4497                 /*
4498                  * We may need to extend the abbreviated hash so that there is
4499                  * no conflicting label.
4500                  */
4501                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4502                         size_t i = strlen(p) + 1;
4503
4504                         oid_to_hex_r(p, oid);
4505                         for (; i < the_hash_algo->hexsz; i++) {
4506                                 char save = p[i];
4507                                 p[i] = '\0';
4508                                 if (!hashmap_get_from_hash(&state->labels,
4509                                                            strihash(p), p))
4510                                         break;
4511                                 p[i] = save;
4512                         }
4513                 }
4514         } else {
4515                 struct strbuf *buf = &state->buf;
4516
4517                 /*
4518                  * Sanitize labels by replacing non-alpha-numeric characters
4519                  * (including white-space ones) by dashes, as they might be
4520                  * illegal in file names (and hence in ref names).
4521                  *
4522                  * Note that we retain non-ASCII UTF-8 characters (identified
4523                  * via the most significant bit). They should be all acceptable
4524                  * in file names. We do not validate the UTF-8 here, that's not
4525                  * the job of this function.
4526                  */
4527                 for (; *label; label++)
4528                         if ((*label & 0x80) || isalnum(*label))
4529                                 strbuf_addch(buf, *label);
4530                         /* avoid leading dash and double-dashes */
4531                         else if (buf->len && buf->buf[buf->len - 1] != '-')
4532                                 strbuf_addch(buf, '-');
4533                 if (!buf->len) {
4534                         strbuf_addstr(buf, "rev-");
4535                         strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4536                 }
4537                 label = buf->buf;
4538
4539                 if ((buf->len == the_hash_algo->hexsz &&
4540                      !get_oid_hex(label, &dummy)) ||
4541                     (buf->len == 1 && *label == '#') ||
4542                     hashmap_get_from_hash(&state->labels,
4543                                           strihash(label), label)) {
4544                         /*
4545                          * If the label already exists, or if the label is a
4546                          * valid full OID, or the label is a '#' (which we use
4547                          * as a separator between merge heads and oneline), we
4548                          * append a dash and a number to make it unique.
4549                          */
4550                         size_t len = buf->len;
4551
4552                         for (i = 2; ; i++) {
4553                                 strbuf_setlen(buf, len);
4554                                 strbuf_addf(buf, "-%d", i);
4555                                 if (!hashmap_get_from_hash(&state->labels,
4556                                                            strihash(buf->buf),
4557                                                            buf->buf))
4558                                         break;
4559                         }
4560
4561                         label = buf->buf;
4562                 }
4563         }
4564
4565         FLEX_ALLOC_STR(labels_entry, label, label);
4566         hashmap_entry_init(&labels_entry->entry, strihash(label));
4567         hashmap_add(&state->labels, &labels_entry->entry);
4568
4569         FLEX_ALLOC_STR(string_entry, string, label);
4570         oidcpy(&string_entry->entry.oid, oid);
4571         oidmap_put(&state->commit2label, string_entry);
4572
4573         return string_entry->string;
4574 }
4575
4576 static int make_script_with_merges(struct pretty_print_context *pp,
4577                                    struct rev_info *revs, struct strbuf *out,
4578                                    unsigned flags)
4579 {
4580         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4581         int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4582         int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4583         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4584         struct strbuf label = STRBUF_INIT;
4585         struct commit_list *commits = NULL, **tail = &commits, *iter;
4586         struct commit_list *tips = NULL, **tips_tail = &tips;
4587         struct commit *commit;
4588         struct oidmap commit2todo = OIDMAP_INIT;
4589         struct string_entry *entry;
4590         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4591                 shown = OIDSET_INIT;
4592         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4593
4594         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4595         const char *cmd_pick = abbr ? "p" : "pick",
4596                 *cmd_label = abbr ? "l" : "label",
4597                 *cmd_reset = abbr ? "t" : "reset",
4598                 *cmd_merge = abbr ? "m" : "merge";
4599
4600         oidmap_init(&commit2todo, 0);
4601         oidmap_init(&state.commit2label, 0);
4602         hashmap_init(&state.labels, labels_cmp, NULL, 0);
4603         strbuf_init(&state.buf, 32);
4604
4605         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4606                 struct labels_entry *onto_label_entry;
4607                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4608                 FLEX_ALLOC_STR(entry, string, "onto");
4609                 oidcpy(&entry->entry.oid, oid);
4610                 oidmap_put(&state.commit2label, entry);
4611
4612                 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4613                 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4614                 hashmap_add(&state.labels, &onto_label_entry->entry);
4615         }
4616
4617         /*
4618          * First phase:
4619          * - get onelines for all commits
4620          * - gather all branch tips (i.e. 2nd or later parents of merges)
4621          * - label all branch tips
4622          */
4623         while ((commit = get_revision(revs))) {
4624                 struct commit_list *to_merge;
4625                 const char *p1, *p2;
4626                 struct object_id *oid;
4627                 int is_empty;
4628
4629                 tail = &commit_list_insert(commit, tail)->next;
4630                 oidset_insert(&interesting, &commit->object.oid);
4631
4632                 is_empty = is_original_commit_empty(commit);
4633                 if (!is_empty && (commit->object.flags & PATCHSAME))
4634                         continue;
4635
4636                 strbuf_reset(&oneline);
4637                 pretty_print_commit(pp, commit, &oneline);
4638
4639                 to_merge = commit->parents ? commit->parents->next : NULL;
4640                 if (!to_merge) {
4641                         /* non-merge commit: easy case */
4642                         strbuf_reset(&buf);
4643                         if (!keep_empty && is_empty)
4644                                 strbuf_addf(&buf, "%c ", comment_line_char);
4645                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
4646                                     oid_to_hex(&commit->object.oid),
4647                                     oneline.buf);
4648
4649                         FLEX_ALLOC_STR(entry, string, buf.buf);
4650                         oidcpy(&entry->entry.oid, &commit->object.oid);
4651                         oidmap_put(&commit2todo, entry);
4652
4653                         continue;
4654                 }
4655
4656                 /* Create a label */
4657                 strbuf_reset(&label);
4658                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4659                     (p1 = strchr(p1, '\'')) &&
4660                     (p2 = strchr(++p1, '\'')))
4661                         strbuf_add(&label, p1, p2 - p1);
4662                 else if (skip_prefix(oneline.buf, "Merge pull request ",
4663                                      &p1) &&
4664                          (p1 = strstr(p1, " from ")))
4665                         strbuf_addstr(&label, p1 + strlen(" from "));
4666                 else
4667                         strbuf_addbuf(&label, &oneline);
4668
4669                 strbuf_reset(&buf);
4670                 strbuf_addf(&buf, "%s -C %s",
4671                             cmd_merge, oid_to_hex(&commit->object.oid));
4672
4673                 /* label the tips of merged branches */
4674                 for (; to_merge; to_merge = to_merge->next) {
4675                         oid = &to_merge->item->object.oid;
4676                         strbuf_addch(&buf, ' ');
4677
4678                         if (!oidset_contains(&interesting, oid)) {
4679                                 strbuf_addstr(&buf, label_oid(oid, NULL,
4680                                                               &state));
4681                                 continue;
4682                         }
4683
4684                         tips_tail = &commit_list_insert(to_merge->item,
4685                                                         tips_tail)->next;
4686
4687                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4688                 }
4689                 strbuf_addf(&buf, " # %s", oneline.buf);
4690
4691                 FLEX_ALLOC_STR(entry, string, buf.buf);
4692                 oidcpy(&entry->entry.oid, &commit->object.oid);
4693                 oidmap_put(&commit2todo, entry);
4694         }
4695
4696         /*
4697          * Second phase:
4698          * - label branch points
4699          * - add HEAD to the branch tips
4700          */
4701         for (iter = commits; iter; iter = iter->next) {
4702                 struct commit_list *parent = iter->item->parents;
4703                 for (; parent; parent = parent->next) {
4704                         struct object_id *oid = &parent->item->object.oid;
4705                         if (!oidset_contains(&interesting, oid))
4706                                 continue;
4707                         if (oidset_insert(&child_seen, oid))
4708                                 label_oid(oid, "branch-point", &state);
4709                 }
4710
4711                 /* Add HEAD as implicit "tip of branch" */
4712                 if (!iter->next)
4713                         tips_tail = &commit_list_insert(iter->item,
4714                                                         tips_tail)->next;
4715         }
4716
4717         /*
4718          * Third phase: output the todo list. This is a bit tricky, as we
4719          * want to avoid jumping back and forth between revisions. To
4720          * accomplish that goal, we walk backwards from the branch tips,
4721          * gathering commits not yet shown, reversing the list on the fly,
4722          * then outputting that list (labeling revisions as needed).
4723          */
4724         strbuf_addf(out, "%s onto\n", cmd_label);
4725         for (iter = tips; iter; iter = iter->next) {
4726                 struct commit_list *list = NULL, *iter2;
4727
4728                 commit = iter->item;
4729                 if (oidset_contains(&shown, &commit->object.oid))
4730                         continue;
4731                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4732
4733                 if (entry)
4734                         strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4735                 else
4736                         strbuf_addch(out, '\n');
4737
4738                 while (oidset_contains(&interesting, &commit->object.oid) &&
4739                        !oidset_contains(&shown, &commit->object.oid)) {
4740                         commit_list_insert(commit, &list);
4741                         if (!commit->parents) {
4742                                 commit = NULL;
4743                                 break;
4744                         }
4745                         commit = commit->parents->item;
4746                 }
4747
4748                 if (!commit)
4749                         strbuf_addf(out, "%s %s\n", cmd_reset,
4750                                     rebase_cousins || root_with_onto ?
4751                                     "onto" : "[new root]");
4752                 else {
4753                         const char *to = NULL;
4754
4755                         entry = oidmap_get(&state.commit2label,
4756                                            &commit->object.oid);
4757                         if (entry)
4758                                 to = entry->string;
4759                         else if (!rebase_cousins)
4760                                 to = label_oid(&commit->object.oid, NULL,
4761                                                &state);
4762
4763                         if (!to || !strcmp(to, "onto"))
4764                                 strbuf_addf(out, "%s onto\n", cmd_reset);
4765                         else {
4766                                 strbuf_reset(&oneline);
4767                                 pretty_print_commit(pp, commit, &oneline);
4768                                 strbuf_addf(out, "%s %s # %s\n",
4769                                             cmd_reset, to, oneline.buf);
4770                         }
4771                 }
4772
4773                 for (iter2 = list; iter2; iter2 = iter2->next) {
4774                         struct object_id *oid = &iter2->item->object.oid;
4775                         entry = oidmap_get(&commit2todo, oid);
4776                         /* only show if not already upstream */
4777                         if (entry)
4778                                 strbuf_addf(out, "%s\n", entry->string);
4779                         entry = oidmap_get(&state.commit2label, oid);
4780                         if (entry)
4781                                 strbuf_addf(out, "%s %s\n",
4782                                             cmd_label, entry->string);
4783                         oidset_insert(&shown, oid);
4784                 }
4785
4786                 free_commit_list(list);
4787         }
4788
4789         free_commit_list(commits);
4790         free_commit_list(tips);
4791
4792         strbuf_release(&label);
4793         strbuf_release(&oneline);
4794         strbuf_release(&buf);
4795
4796         oidmap_free(&commit2todo, 1);
4797         oidmap_free(&state.commit2label, 1);
4798         hashmap_free_entries(&state.labels, struct labels_entry, entry);
4799         strbuf_release(&state.buf);
4800
4801         return 0;
4802 }
4803
4804 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4805                           const char **argv, unsigned flags)
4806 {
4807         char *format = NULL;
4808         struct pretty_print_context pp = {0};
4809         struct rev_info revs;
4810         struct commit *commit;
4811         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4812         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4813         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4814
4815         repo_init_revisions(r, &revs, NULL);
4816         revs.verbose_header = 1;
4817         if (!rebase_merges)
4818                 revs.max_parents = 1;
4819         revs.cherry_mark = 1;
4820         revs.limited = 1;
4821         revs.reverse = 1;
4822         revs.right_only = 1;
4823         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4824         revs.topo_order = 1;
4825
4826         revs.pretty_given = 1;
4827         git_config_get_string("rebase.instructionFormat", &format);
4828         if (!format || !*format) {
4829                 free(format);
4830                 format = xstrdup("%s");
4831         }
4832         get_commit_format(format, &revs);
4833         free(format);
4834         pp.fmt = revs.commit_format;
4835         pp.output_encoding = get_log_output_encoding();
4836
4837         if (setup_revisions(argc, argv, &revs, NULL) > 1)
4838                 return error(_("make_script: unhandled options"));
4839
4840         if (prepare_revision_walk(&revs) < 0)
4841                 return error(_("make_script: error preparing revisions"));
4842
4843         if (rebase_merges)
4844                 return make_script_with_merges(&pp, &revs, out, flags);
4845
4846         while ((commit = get_revision(&revs))) {
4847                 int is_empty  = is_original_commit_empty(commit);
4848
4849                 if (!is_empty && (commit->object.flags & PATCHSAME))
4850                         continue;
4851                 if (!keep_empty && is_empty)
4852                         strbuf_addf(out, "%c ", comment_line_char);
4853                 strbuf_addf(out, "%s %s ", insn,
4854                             oid_to_hex(&commit->object.oid));
4855                 pretty_print_commit(&pp, commit, out);
4856                 strbuf_addch(out, '\n');
4857         }
4858         return 0;
4859 }
4860
4861 /*
4862  * Add commands after pick and (series of) squash/fixup commands
4863  * in the todo list.
4864  */
4865 void todo_list_add_exec_commands(struct todo_list *todo_list,
4866                                  struct string_list *commands)
4867 {
4868         struct strbuf *buf = &todo_list->buf;
4869         size_t base_offset = buf->len;
4870         int i, insert, nr = 0, alloc = 0;
4871         struct todo_item *items = NULL, *base_items = NULL;
4872
4873         base_items = xcalloc(commands->nr, sizeof(struct todo_item));
4874         for (i = 0; i < commands->nr; i++) {
4875                 size_t command_len = strlen(commands->items[i].string);
4876
4877                 strbuf_addstr(buf, commands->items[i].string);
4878                 strbuf_addch(buf, '\n');
4879
4880                 base_items[i].command = TODO_EXEC;
4881                 base_items[i].offset_in_buf = base_offset;
4882                 base_items[i].arg_offset = base_offset + strlen("exec ");
4883                 base_items[i].arg_len = command_len - strlen("exec ");
4884
4885                 base_offset += command_len + 1;
4886         }
4887
4888         /*
4889          * Insert <commands> after every pick. Here, fixup/squash chains
4890          * are considered part of the pick, so we insert the commands *after*
4891          * those chains if there are any.
4892          *
4893          * As we insert the exec commands immediately after rearranging
4894          * any fixups and before the user edits the list, a fixup chain
4895          * can never contain comments (any comments are empty picks that
4896          * have been commented out because the user did not specify
4897          * --keep-empty).  So, it is safe to insert an exec command
4898          * without looking at the command following a comment.
4899          */
4900         insert = 0;
4901         for (i = 0; i < todo_list->nr; i++) {
4902                 enum todo_command command = todo_list->items[i].command;
4903                 if (insert && !is_fixup(command)) {
4904                         ALLOC_GROW(items, nr + commands->nr, alloc);
4905                         COPY_ARRAY(items + nr, base_items, commands->nr);
4906                         nr += commands->nr;
4907
4908                         insert = 0;
4909                 }
4910
4911                 ALLOC_GROW(items, nr + 1, alloc);
4912                 items[nr++] = todo_list->items[i];
4913
4914                 if (command == TODO_PICK || command == TODO_MERGE)
4915                         insert = 1;
4916         }
4917
4918         /* insert or append final <commands> */
4919         if (insert || nr == todo_list->nr) {
4920                 ALLOC_GROW(items, nr + commands->nr, alloc);
4921                 COPY_ARRAY(items + nr, base_items, commands->nr);
4922                 nr += commands->nr;
4923         }
4924
4925         free(base_items);
4926         FREE_AND_NULL(todo_list->items);
4927         todo_list->items = items;
4928         todo_list->nr = nr;
4929         todo_list->alloc = alloc;
4930 }
4931
4932 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
4933                                 struct strbuf *buf, int num, unsigned flags)
4934 {
4935         struct todo_item *item;
4936         int i, max = todo_list->nr;
4937
4938         if (num > 0 && num < max)
4939                 max = num;
4940
4941         for (item = todo_list->items, i = 0; i < max; i++, item++) {
4942                 /* if the item is not a command write it and continue */
4943                 if (item->command >= TODO_COMMENT) {
4944                         strbuf_addf(buf, "%.*s\n", item->arg_len,
4945                                     todo_item_get_arg(todo_list, item));
4946                         continue;
4947                 }
4948
4949                 /* add command to the buffer */
4950                 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4951                         strbuf_addch(buf, command_to_char(item->command));
4952                 else
4953                         strbuf_addstr(buf, command_to_string(item->command));
4954
4955                 /* add commit id */
4956                 if (item->commit) {
4957                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4958                                           short_commit_name(item->commit) :
4959                                           oid_to_hex(&item->commit->object.oid);
4960
4961                         if (item->command == TODO_MERGE) {
4962                                 if (item->flags & TODO_EDIT_MERGE_MSG)
4963                                         strbuf_addstr(buf, " -c");
4964                                 else
4965                                         strbuf_addstr(buf, " -C");
4966                         }
4967
4968                         strbuf_addf(buf, " %s", oid);
4969                 }
4970
4971                 /* add all the rest */
4972                 if (!item->arg_len)
4973                         strbuf_addch(buf, '\n');
4974                 else
4975                         strbuf_addf(buf, " %.*s\n", item->arg_len,
4976                                     todo_item_get_arg(todo_list, item));
4977         }
4978 }
4979
4980 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
4981                             const char *file, const char *shortrevisions,
4982                             const char *shortonto, int num, unsigned flags)
4983 {
4984         int res;
4985         struct strbuf buf = STRBUF_INIT;
4986
4987         todo_list_to_strbuf(r, todo_list, &buf, num, flags);
4988         if (flags & TODO_LIST_APPEND_TODO_HELP)
4989                 append_todo_help(flags & TODO_LIST_KEEP_EMPTY, count_commands(todo_list),
4990                                  shortrevisions, shortonto, &buf);
4991
4992         res = write_message(buf.buf, buf.len, file, 0);
4993         strbuf_release(&buf);
4994
4995         return res;
4996 }
4997
4998 /* skip picking commits whose parents are unchanged */
4999 static int skip_unnecessary_picks(struct repository *r,
5000                                   struct todo_list *todo_list,
5001                                   struct object_id *base_oid)
5002 {
5003         struct object_id *parent_oid;
5004         int i;
5005
5006         for (i = 0; i < todo_list->nr; i++) {
5007                 struct todo_item *item = todo_list->items + i;
5008
5009                 if (item->command >= TODO_NOOP)
5010                         continue;
5011                 if (item->command != TODO_PICK)
5012                         break;
5013                 if (parse_commit(item->commit)) {
5014                         return error(_("could not parse commit '%s'"),
5015                                 oid_to_hex(&item->commit->object.oid));
5016                 }
5017                 if (!item->commit->parents)
5018                         break; /* root commit */
5019                 if (item->commit->parents->next)
5020                         break; /* merge commit */
5021                 parent_oid = &item->commit->parents->item->object.oid;
5022                 if (!oideq(parent_oid, base_oid))
5023                         break;
5024                 oidcpy(base_oid, &item->commit->object.oid);
5025         }
5026         if (i > 0) {
5027                 const char *done_path = rebase_path_done();
5028
5029                 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5030                         error_errno(_("could not write to '%s'"), done_path);
5031                         return -1;
5032                 }
5033
5034                 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5035                 todo_list->nr -= i;
5036                 todo_list->current = 0;
5037                 todo_list->done_nr += i;
5038
5039                 if (is_fixup(peek_command(todo_list, 0)))
5040                         record_in_rewritten(base_oid, peek_command(todo_list, 0));
5041         }
5042
5043         return 0;
5044 }
5045
5046 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5047                     const char *shortrevisions, const char *onto_name,
5048                     struct commit *onto, const char *orig_head,
5049                     struct string_list *commands, unsigned autosquash,
5050                     struct todo_list *todo_list)
5051 {
5052         const char *shortonto, *todo_file = rebase_path_todo();
5053         struct todo_list new_todo = TODO_LIST_INIT;
5054         struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5055         struct object_id oid = onto->object.oid;
5056         int res;
5057
5058         shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
5059
5060         if (buf->len == 0) {
5061                 struct todo_item *item = append_new_todo(todo_list);
5062                 item->command = TODO_NOOP;
5063                 item->commit = NULL;
5064                 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5065         }
5066
5067         if (autosquash && todo_list_rearrange_squash(todo_list))
5068                 return -1;
5069
5070         if (commands->nr)
5071                 todo_list_add_exec_commands(todo_list, commands);
5072
5073         if (count_commands(todo_list) == 0) {
5074                 apply_autostash(opts);
5075                 sequencer_remove_state(opts);
5076
5077                 return error(_("nothing to do"));
5078         }
5079
5080         res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5081                              shortonto, flags);
5082         if (res == -1)
5083                 return -1;
5084         else if (res == -2) {
5085                 apply_autostash(opts);
5086                 sequencer_remove_state(opts);
5087
5088                 return -1;
5089         } else if (res == -3) {
5090                 apply_autostash(opts);
5091                 sequencer_remove_state(opts);
5092                 todo_list_release(&new_todo);
5093
5094                 return error(_("nothing to do"));
5095         } else if (res == -4) {
5096                 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5097                 todo_list_release(&new_todo);
5098
5099                 return -1;
5100         }
5101
5102         /* Expand the commit IDs */
5103         todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5104         strbuf_swap(&new_todo.buf, &buf2);
5105         strbuf_release(&buf2);
5106         new_todo.total_nr -= new_todo.nr;
5107         if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5108                 BUG("invalid todo list after expanding IDs:\n%s",
5109                     new_todo.buf.buf);
5110
5111         if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5112                 todo_list_release(&new_todo);
5113                 return error(_("could not skip unnecessary pick commands"));
5114         }
5115
5116         if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5117                                     flags & ~(TODO_LIST_SHORTEN_IDS))) {
5118                 todo_list_release(&new_todo);
5119                 return error_errno(_("could not write '%s'"), todo_file);
5120         }
5121
5122         res = -1;
5123
5124         if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5125                 goto cleanup;
5126
5127         if (require_clean_work_tree(r, "rebase", "", 1, 1))
5128                 goto cleanup;
5129
5130         todo_list_write_total_nr(&new_todo);
5131         res = pick_commits(r, &new_todo, opts);
5132
5133 cleanup:
5134         todo_list_release(&new_todo);
5135
5136         return res;
5137 }
5138
5139 struct subject2item_entry {
5140         struct hashmap_entry entry;
5141         int i;
5142         char subject[FLEX_ARRAY];
5143 };
5144
5145 static int subject2item_cmp(const void *fndata,
5146                             const struct hashmap_entry *eptr,
5147                             const struct hashmap_entry *entry_or_key,
5148                             const void *key)
5149 {
5150         const struct subject2item_entry *a, *b;
5151
5152         a = container_of(eptr, const struct subject2item_entry, entry);
5153         b = container_of(entry_or_key, const struct subject2item_entry, entry);
5154
5155         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5156 }
5157
5158 define_commit_slab(commit_todo_item, struct todo_item *);
5159
5160 /*
5161  * Rearrange the todo list that has both "pick commit-id msg" and "pick
5162  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5163  * after the former, and change "pick" to "fixup"/"squash".
5164  *
5165  * Note that if the config has specified a custom instruction format, each log
5166  * message will have to be retrieved from the commit (as the oneline in the
5167  * script cannot be trusted) in order to normalize the autosquash arrangement.
5168  */
5169 int todo_list_rearrange_squash(struct todo_list *todo_list)
5170 {
5171         struct hashmap subject2item;
5172         int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5173         char **subjects;
5174         struct commit_todo_item commit_todo;
5175         struct todo_item *items = NULL;
5176
5177         init_commit_todo_item(&commit_todo);
5178         /*
5179          * The hashmap maps onelines to the respective todo list index.
5180          *
5181          * If any items need to be rearranged, the next[i] value will indicate
5182          * which item was moved directly after the i'th.
5183          *
5184          * In that case, last[i] will indicate the index of the latest item to
5185          * be moved to appear after the i'th.
5186          */
5187         hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5188         ALLOC_ARRAY(next, todo_list->nr);
5189         ALLOC_ARRAY(tail, todo_list->nr);
5190         ALLOC_ARRAY(subjects, todo_list->nr);
5191         for (i = 0; i < todo_list->nr; i++) {
5192                 struct strbuf buf = STRBUF_INIT;
5193                 struct todo_item *item = todo_list->items + i;
5194                 const char *commit_buffer, *subject, *p;
5195                 size_t subject_len;
5196                 int i2 = -1;
5197                 struct subject2item_entry *entry;
5198
5199                 next[i] = tail[i] = -1;
5200                 if (!item->commit || item->command == TODO_DROP) {
5201                         subjects[i] = NULL;
5202                         continue;
5203                 }
5204
5205                 if (is_fixup(item->command)) {
5206                         clear_commit_todo_item(&commit_todo);
5207                         return error(_("the script was already rearranged."));
5208                 }
5209
5210                 *commit_todo_item_at(&commit_todo, item->commit) = item;
5211
5212                 parse_commit(item->commit);
5213                 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5214                 find_commit_subject(commit_buffer, &subject);
5215                 format_subject(&buf, subject, " ");
5216                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5217                 unuse_commit_buffer(item->commit, commit_buffer);
5218                 if ((skip_prefix(subject, "fixup! ", &p) ||
5219                      skip_prefix(subject, "squash! ", &p))) {
5220                         struct commit *commit2;
5221
5222                         for (;;) {
5223                                 while (isspace(*p))
5224                                         p++;
5225                                 if (!skip_prefix(p, "fixup! ", &p) &&
5226                                     !skip_prefix(p, "squash! ", &p))
5227                                         break;
5228                         }
5229
5230                         entry = hashmap_get_entry_from_hash(&subject2item,
5231                                                 strhash(p), p,
5232                                                 struct subject2item_entry,
5233                                                 entry);
5234                         if (entry)
5235                                 /* found by title */
5236                                 i2 = entry->i;
5237                         else if (!strchr(p, ' ') &&
5238                                  (commit2 =
5239                                   lookup_commit_reference_by_name(p)) &&
5240                                  *commit_todo_item_at(&commit_todo, commit2))
5241                                 /* found by commit name */
5242                                 i2 = *commit_todo_item_at(&commit_todo, commit2)
5243                                         - todo_list->items;
5244                         else {
5245                                 /* copy can be a prefix of the commit subject */
5246                                 for (i2 = 0; i2 < i; i2++)
5247                                         if (subjects[i2] &&
5248                                             starts_with(subjects[i2], p))
5249                                                 break;
5250                                 if (i2 == i)
5251                                         i2 = -1;
5252                         }
5253                 }
5254                 if (i2 >= 0) {
5255                         rearranged = 1;
5256                         todo_list->items[i].command =
5257                                 starts_with(subject, "fixup!") ?
5258                                 TODO_FIXUP : TODO_SQUASH;
5259                         if (next[i2] < 0)
5260                                 next[i2] = i;
5261                         else
5262                                 next[tail[i2]] = i;
5263                         tail[i2] = i;
5264                 } else if (!hashmap_get_from_hash(&subject2item,
5265                                                 strhash(subject), subject)) {
5266                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5267                         entry->i = i;
5268                         hashmap_entry_init(&entry->entry,
5269                                         strhash(entry->subject));
5270                         hashmap_put(&subject2item, &entry->entry);
5271                 }
5272         }
5273
5274         if (rearranged) {
5275                 for (i = 0; i < todo_list->nr; i++) {
5276                         enum todo_command command = todo_list->items[i].command;
5277                         int cur = i;
5278
5279                         /*
5280                          * Initially, all commands are 'pick's. If it is a
5281                          * fixup or a squash now, we have rearranged it.
5282                          */
5283                         if (is_fixup(command))
5284                                 continue;
5285
5286                         while (cur >= 0) {
5287                                 ALLOC_GROW(items, nr + 1, alloc);
5288                                 items[nr++] = todo_list->items[cur];
5289                                 cur = next[cur];
5290                         }
5291                 }
5292
5293                 FREE_AND_NULL(todo_list->items);
5294                 todo_list->items = items;
5295                 todo_list->nr = nr;
5296                 todo_list->alloc = alloc;
5297         }
5298
5299         free(next);
5300         free(tail);
5301         for (i = 0; i < todo_list->nr; i++)
5302                 free(subjects[i]);
5303         free(subjects);
5304         hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5305
5306         clear_commit_todo_item(&commit_todo);
5307
5308         return 0;
5309 }