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