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