sequencer: rename a few functions
[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 size_t subject_length(const char *body)
1728 {
1729         const char *p = body;
1730         while (*p) {
1731                 const char *next = skip_blank_lines(p);
1732                 if (next != p)
1733                         break;
1734                 p = strchrnul(p, '\n');
1735                 if (*p)
1736                         p++;
1737         }
1738         return p - body;
1739 }
1740
1741 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1742 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1743 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1744 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1745 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1746
1747 static int is_fixup_flag(enum todo_command command, unsigned flag)
1748 {
1749         return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1750                                          (flag & TODO_EDIT_FIXUP_MSG));
1751 }
1752
1753 /*
1754  * Wrapper around strbuf_add_commented_lines() which avoids double
1755  * commenting commit subjects.
1756  */
1757 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1758 {
1759         const char *s = str;
1760         while (len > 0 && s[0] == comment_line_char) {
1761                 size_t count;
1762                 const char *n = memchr(s, '\n', len);
1763                 if (!n)
1764                         count = len;
1765                 else
1766                         count = n - s + 1;
1767                 strbuf_add(buf, s, count);
1768                 s += count;
1769                 len -= count;
1770         }
1771         strbuf_add_commented_lines(buf, s, len);
1772 }
1773
1774 /* Does the current fixup chain contain a squash command? */
1775 static int seen_squash(struct replay_opts *opts)
1776 {
1777         return starts_with(opts->current_fixups.buf, "squash") ||
1778                 strstr(opts->current_fixups.buf, "\nsquash");
1779 }
1780
1781 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1782 {
1783         strbuf_setlen(buf1, 2);
1784         strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1785         strbuf_addch(buf1, '\n');
1786         strbuf_setlen(buf2, 2);
1787         strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1788         strbuf_addch(buf2, '\n');
1789 }
1790
1791 /*
1792  * Comment out any un-commented commit messages, updating the message comments
1793  * to say they will be skipped but do not comment out the empty lines that
1794  * surround commit messages and their comments.
1795  */
1796 static void update_squash_message_for_fixup(struct strbuf *msg)
1797 {
1798         void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1799         struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1800         const char *s, *start;
1801         char *orig_msg;
1802         size_t orig_msg_len;
1803         int i = 1;
1804
1805         strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1806         strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1807         s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1808         while (s) {
1809                 const char *next;
1810                 size_t off;
1811                 if (skip_prefix(s, buf1.buf, &next)) {
1812                         /*
1813                          * Copy the last message, preserving the blank line
1814                          * preceding the current line
1815                          */
1816                         off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1817                         copy_lines(msg, start, s - start - off);
1818                         if (off)
1819                                 strbuf_addch(msg, '\n');
1820                         /*
1821                          * The next message needs to be commented out but the
1822                          * message header is already commented out so just copy
1823                          * it and the blank line that follows it.
1824                          */
1825                         strbuf_addbuf(msg, &buf2);
1826                         if (*next == '\n')
1827                                 strbuf_addch(msg, *next++);
1828                         start = s = next;
1829                         copy_lines = add_commented_lines;
1830                         update_comment_bufs(&buf1, &buf2, ++i);
1831                 } else if (skip_prefix(s, buf2.buf, &next)) {
1832                         off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1833                         copy_lines(msg, start, s - start - off);
1834                         start = s - off;
1835                         s = next;
1836                         copy_lines = strbuf_add;
1837                         update_comment_bufs(&buf1, &buf2, ++i);
1838                 } else {
1839                         s = strchr(s, '\n');
1840                         if (s)
1841                                 s++;
1842                 }
1843         }
1844         copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1845         free(orig_msg);
1846         strbuf_release(&buf1);
1847         strbuf_release(&buf2);
1848 }
1849
1850 static int append_squash_message(struct strbuf *buf, const char *body,
1851                          enum todo_command command, struct replay_opts *opts,
1852                          unsigned flag)
1853 {
1854         const char *fixup_msg;
1855         size_t commented_len = 0, fixup_off;
1856         /*
1857          * amend is non-interactive and not normally used with fixup!
1858          * or squash! commits, so only comment out those subjects when
1859          * squashing commit messages.
1860          */
1861         if (starts_with(body, "amend!") ||
1862             ((command == TODO_SQUASH || seen_squash(opts)) &&
1863              (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1864                 commented_len = subject_length(body);
1865
1866         strbuf_addf(buf, "\n%c ", comment_line_char);
1867         strbuf_addf(buf, _(nth_commit_msg_fmt),
1868                     ++opts->current_fixup_count + 1);
1869         strbuf_addstr(buf, "\n\n");
1870         strbuf_add_commented_lines(buf, body, commented_len);
1871         /* buf->buf may be reallocated so store an offset into the buffer */
1872         fixup_off = buf->len;
1873         strbuf_addstr(buf, body + commented_len);
1874
1875         /* fixup -C after squash behaves like squash */
1876         if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1877                 /*
1878                  * We're replacing the commit message so we need to
1879                  * append the Signed-off-by: trailer if the user
1880                  * requested '--signoff'.
1881                  */
1882                 if (opts->signoff)
1883                         append_signoff(buf, 0, 0);
1884
1885                 if ((command == TODO_FIXUP) &&
1886                     (flag & TODO_REPLACE_FIXUP_MSG) &&
1887                     (file_exists(rebase_path_fixup_msg()) ||
1888                      !file_exists(rebase_path_squash_msg()))) {
1889                         fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1890                         if (write_message(fixup_msg, strlen(fixup_msg),
1891                                         rebase_path_fixup_msg(), 0) < 0)
1892                                 return error(_("cannot write '%s'"),
1893                                         rebase_path_fixup_msg());
1894                 } else {
1895                         unlink(rebase_path_fixup_msg());
1896                 }
1897         } else  {
1898                 unlink(rebase_path_fixup_msg());
1899         }
1900
1901         return 0;
1902 }
1903
1904 static int update_squash_messages(struct repository *r,
1905                                   enum todo_command command,
1906                                   struct commit *commit,
1907                                   struct replay_opts *opts,
1908                                   unsigned flag)
1909 {
1910         struct strbuf buf = STRBUF_INIT;
1911         int res = 0;
1912         const char *message, *body;
1913         const char *encoding = get_commit_output_encoding();
1914
1915         if (opts->current_fixup_count > 0) {
1916                 struct strbuf header = STRBUF_INIT;
1917                 char *eol;
1918
1919                 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1920                         return error(_("could not read '%s'"),
1921                                 rebase_path_squash_msg());
1922
1923                 eol = buf.buf[0] != comment_line_char ?
1924                         buf.buf : strchrnul(buf.buf, '\n');
1925
1926                 strbuf_addf(&header, "%c ", comment_line_char);
1927                 strbuf_addf(&header, _(combined_commit_msg_fmt),
1928                             opts->current_fixup_count + 2);
1929                 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
1930                 strbuf_release(&header);
1931                 if (is_fixup_flag(command, flag) && !seen_squash(opts))
1932                         update_squash_message_for_fixup(&buf);
1933         } else {
1934                 struct object_id head;
1935                 struct commit *head_commit;
1936                 const char *head_message, *body;
1937
1938                 if (get_oid("HEAD", &head))
1939                         return error(_("need a HEAD to fixup"));
1940                 if (!(head_commit = lookup_commit_reference(r, &head)))
1941                         return error(_("could not read HEAD"));
1942                 if (!(head_message = logmsg_reencode(head_commit, NULL, encoding)))
1943                         return error(_("could not read HEAD's commit message"));
1944
1945                 find_commit_subject(head_message, &body);
1946                 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
1947                                                         rebase_path_fixup_msg(), 0) < 0) {
1948                         unuse_commit_buffer(head_commit, head_message);
1949                         return error(_("cannot write '%s'"), rebase_path_fixup_msg());
1950                 }
1951                 strbuf_addf(&buf, "%c ", comment_line_char);
1952                 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
1953                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1954                 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
1955                               _(skip_first_commit_msg_str) :
1956                               _(first_commit_msg_str));
1957                 strbuf_addstr(&buf, "\n\n");
1958                 if (is_fixup_flag(command, flag))
1959                         strbuf_add_commented_lines(&buf, body, strlen(body));
1960                 else
1961                         strbuf_addstr(&buf, body);
1962
1963                 unuse_commit_buffer(head_commit, head_message);
1964         }
1965
1966         if (!(message = logmsg_reencode(commit, NULL, encoding)))
1967                 return error(_("could not read commit message of %s"),
1968                              oid_to_hex(&commit->object.oid));
1969         find_commit_subject(message, &body);
1970
1971         if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
1972                 res = append_squash_message(&buf, body, command, opts, flag);
1973         } else if (command == TODO_FIXUP) {
1974                 strbuf_addf(&buf, "\n%c ", comment_line_char);
1975                 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
1976                             ++opts->current_fixup_count + 1);
1977                 strbuf_addstr(&buf, "\n\n");
1978                 strbuf_add_commented_lines(&buf, body, strlen(body));
1979         } else
1980                 return error(_("unknown command: %d"), command);
1981         unuse_commit_buffer(commit, message);
1982
1983         if (!res)
1984                 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
1985                                     0);
1986         strbuf_release(&buf);
1987
1988         if (!res) {
1989                 strbuf_addf(&opts->current_fixups, "%s%s %s",
1990                             opts->current_fixups.len ? "\n" : "",
1991                             command_to_string(command),
1992                             oid_to_hex(&commit->object.oid));
1993                 res = write_message(opts->current_fixups.buf,
1994                                     opts->current_fixups.len,
1995                                     rebase_path_current_fixups(), 0);
1996         }
1997
1998         return res;
1999 }
2000
2001 static void flush_rewritten_pending(void)
2002 {
2003         struct strbuf buf = STRBUF_INIT;
2004         struct object_id newoid;
2005         FILE *out;
2006
2007         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2008             !get_oid("HEAD", &newoid) &&
2009             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2010                 char *bol = buf.buf, *eol;
2011
2012                 while (*bol) {
2013                         eol = strchrnul(bol, '\n');
2014                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
2015                                         bol, oid_to_hex(&newoid));
2016                         if (!*eol)
2017                                 break;
2018                         bol = eol + 1;
2019                 }
2020                 fclose(out);
2021                 unlink(rebase_path_rewritten_pending());
2022         }
2023         strbuf_release(&buf);
2024 }
2025
2026 static void record_in_rewritten(struct object_id *oid,
2027                 enum todo_command next_command)
2028 {
2029         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2030
2031         if (!out)
2032                 return;
2033
2034         fprintf(out, "%s\n", oid_to_hex(oid));
2035         fclose(out);
2036
2037         if (!is_fixup(next_command))
2038                 flush_rewritten_pending();
2039 }
2040
2041 static int do_pick_commit(struct repository *r,
2042                           struct todo_item *item,
2043                           struct replay_opts *opts,
2044                           int final_fixup, int *check_todo)
2045 {
2046         unsigned int flags = opts->edit ? EDIT_MSG : 0;
2047         const char *msg_file = opts->edit ? NULL : git_path_merge_msg(r);
2048         struct object_id head;
2049         struct commit *base, *next, *parent;
2050         const char *base_label, *next_label;
2051         char *author = NULL;
2052         struct commit_message msg = { NULL, NULL, NULL, NULL };
2053         struct strbuf msgbuf = STRBUF_INIT;
2054         int res, unborn = 0, reword = 0, allow, drop_commit;
2055         enum todo_command command = item->command;
2056         struct commit *commit = item->commit;
2057
2058         if (opts->no_commit) {
2059                 /*
2060                  * We do not intend to commit immediately.  We just want to
2061                  * merge the differences in, so let's compute the tree
2062                  * that represents the "current" state for merge-recursive
2063                  * to work on.
2064                  */
2065                 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2066                         return error(_("your index file is unmerged."));
2067         } else {
2068                 unborn = get_oid("HEAD", &head);
2069                 /* Do we want to generate a root commit? */
2070                 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2071                     oideq(&head, &opts->squash_onto)) {
2072                         if (is_fixup(command))
2073                                 return error(_("cannot fixup root commit"));
2074                         flags |= CREATE_ROOT_COMMIT;
2075                         unborn = 1;
2076                 } else if (unborn)
2077                         oidcpy(&head, the_hash_algo->empty_tree);
2078                 if (index_differs_from(r, unborn ? empty_tree_oid_hex() : "HEAD",
2079                                        NULL, 0))
2080                         return error_dirty_index(r, opts);
2081         }
2082         discard_index(r->index);
2083
2084         if (!commit->parents)
2085                 parent = NULL;
2086         else if (commit->parents->next) {
2087                 /* Reverting or cherry-picking a merge commit */
2088                 int cnt;
2089                 struct commit_list *p;
2090
2091                 if (!opts->mainline)
2092                         return error(_("commit %s is a merge but no -m option was given."),
2093                                 oid_to_hex(&commit->object.oid));
2094
2095                 for (cnt = 1, p = commit->parents;
2096                      cnt != opts->mainline && p;
2097                      cnt++)
2098                         p = p->next;
2099                 if (cnt != opts->mainline || !p)
2100                         return error(_("commit %s does not have parent %d"),
2101                                 oid_to_hex(&commit->object.oid), opts->mainline);
2102                 parent = p->item;
2103         } else if (1 < opts->mainline)
2104                 /*
2105                  *  Non-first parent explicitly specified as mainline for
2106                  *  non-merge commit
2107                  */
2108                 return error(_("commit %s does not have parent %d"),
2109                              oid_to_hex(&commit->object.oid), opts->mainline);
2110         else
2111                 parent = commit->parents->item;
2112
2113         if (get_message(commit, &msg) != 0)
2114                 return error(_("cannot get commit message for %s"),
2115                         oid_to_hex(&commit->object.oid));
2116
2117         if (opts->allow_ff && !is_fixup(command) &&
2118             ((parent && oideq(&parent->object.oid, &head)) ||
2119              (!parent && unborn))) {
2120                 if (is_rebase_i(opts))
2121                         write_author_script(msg.message);
2122                 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2123                         opts);
2124                 if (res || command != TODO_REWORD)
2125                         goto leave;
2126                 reword = 1;
2127                 msg_file = NULL;
2128                 goto fast_forward_edit;
2129         }
2130         if (parent && parse_commit(parent) < 0)
2131                 /* TRANSLATORS: The first %s will be a "todo" command like
2132                    "revert" or "pick", the second %s a SHA1. */
2133                 return error(_("%s: cannot parse parent commit %s"),
2134                         command_to_string(command),
2135                         oid_to_hex(&parent->object.oid));
2136
2137         /*
2138          * "commit" is an existing commit.  We would want to apply
2139          * the difference it introduces since its first parent "prev"
2140          * on top of the current HEAD if we are cherry-pick.  Or the
2141          * reverse of it if we are revert.
2142          */
2143
2144         if (command == TODO_REVERT) {
2145                 base = commit;
2146                 base_label = msg.label;
2147                 next = parent;
2148                 next_label = msg.parent_label;
2149                 strbuf_addstr(&msgbuf, "Revert \"");
2150                 strbuf_addstr(&msgbuf, msg.subject);
2151                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
2152                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2153
2154                 if (commit->parents && commit->parents->next) {
2155                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
2156                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
2157                 }
2158                 strbuf_addstr(&msgbuf, ".\n");
2159         } else {
2160                 const char *p;
2161
2162                 base = parent;
2163                 base_label = msg.parent_label;
2164                 next = commit;
2165                 next_label = msg.label;
2166
2167                 /* Append the commit log message to msgbuf. */
2168                 if (find_commit_subject(msg.message, &p))
2169                         strbuf_addstr(&msgbuf, p);
2170
2171                 if (opts->record_origin) {
2172                         strbuf_complete_line(&msgbuf);
2173                         if (!has_conforming_footer(&msgbuf, NULL, 0))
2174                                 strbuf_addch(&msgbuf, '\n');
2175                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
2176                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
2177                         strbuf_addstr(&msgbuf, ")\n");
2178                 }
2179                 if (!is_fixup(command))
2180                         author = get_author(msg.message);
2181         }
2182
2183         if (command == TODO_REWORD)
2184                 reword = 1;
2185         else if (is_fixup(command)) {
2186                 if (update_squash_messages(r, command, commit,
2187                                            opts, item->flags))
2188                         return -1;
2189                 flags |= AMEND_MSG;
2190                 if (!final_fixup)
2191                         msg_file = rebase_path_squash_msg();
2192                 else if (file_exists(rebase_path_fixup_msg())) {
2193                         flags |= CLEANUP_MSG;
2194                         msg_file = rebase_path_fixup_msg();
2195                 } else {
2196                         const char *dest = git_path_squash_msg(r);
2197                         unlink(dest);
2198                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
2199                                 return error(_("could not rename '%s' to '%s'"),
2200                                              rebase_path_squash_msg(), dest);
2201                         unlink(git_path_merge_msg(r));
2202                         msg_file = dest;
2203                         flags |= EDIT_MSG;
2204                 }
2205         }
2206
2207         if (opts->signoff && !is_fixup(command))
2208                 append_signoff(&msgbuf, 0, 0);
2209
2210         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2211                 res = -1;
2212         else if (!opts->strategy ||
2213                  !strcmp(opts->strategy, "recursive") ||
2214                  !strcmp(opts->strategy, "ort") ||
2215                  command == TODO_REVERT) {
2216                 res = do_recursive_merge(r, base, next, base_label, next_label,
2217                                          &head, &msgbuf, opts);
2218                 if (res < 0)
2219                         goto leave;
2220
2221                 res |= write_message(msgbuf.buf, msgbuf.len,
2222                                      git_path_merge_msg(r), 0);
2223         } else {
2224                 struct commit_list *common = NULL;
2225                 struct commit_list *remotes = NULL;
2226
2227                 res = write_message(msgbuf.buf, msgbuf.len,
2228                                     git_path_merge_msg(r), 0);
2229
2230                 commit_list_insert(base, &common);
2231                 commit_list_insert(next, &remotes);
2232                 res |= try_merge_command(r, opts->strategy,
2233                                          opts->xopts_nr, (const char **)opts->xopts,
2234                                         common, oid_to_hex(&head), remotes);
2235                 free_commit_list(common);
2236                 free_commit_list(remotes);
2237         }
2238         strbuf_release(&msgbuf);
2239
2240         /*
2241          * If the merge was clean or if it failed due to conflict, we write
2242          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2243          * However, if the merge did not even start, then we don't want to
2244          * write it at all.
2245          */
2246         if ((command == TODO_PICK || command == TODO_REWORD ||
2247              command == TODO_EDIT) && !opts->no_commit &&
2248             (res == 0 || res == 1) &&
2249             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2250                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2251                 res = -1;
2252         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2253             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2254                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2255                 res = -1;
2256
2257         if (res) {
2258                 error(command == TODO_REVERT
2259                       ? _("could not revert %s... %s")
2260                       : _("could not apply %s... %s"),
2261                       short_commit_name(commit), msg.subject);
2262                 print_advice(r, res == 1, opts);
2263                 repo_rerere(r, opts->allow_rerere_auto);
2264                 goto leave;
2265         }
2266
2267         drop_commit = 0;
2268         allow = allow_empty(r, opts, commit);
2269         if (allow < 0) {
2270                 res = allow;
2271                 goto leave;
2272         } else if (allow == 1) {
2273                 flags |= ALLOW_EMPTY;
2274         } else if (allow == 2) {
2275                 drop_commit = 1;
2276                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2277                                 NULL, 0);
2278                 unlink(git_path_merge_msg(r));
2279                 fprintf(stderr,
2280                         _("dropping %s %s -- patch contents already upstream\n"),
2281                         oid_to_hex(&commit->object.oid), msg.subject);
2282         } /* else allow == 0 and there's nothing special to do */
2283         if (!opts->no_commit && !drop_commit) {
2284                 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2285                         res = do_commit(r, msg_file, author, opts, flags,
2286                                         commit? &commit->object.oid : NULL);
2287                 else
2288                         res = error(_("unable to parse commit author"));
2289                 *check_todo = !!(flags & EDIT_MSG);
2290                 if (!res && reword) {
2291 fast_forward_edit:
2292                         res = run_git_commit(NULL, opts, EDIT_MSG |
2293                                              VERIFY_MSG | AMEND_MSG |
2294                                              (flags & ALLOW_EMPTY));
2295                         *check_todo = 1;
2296                 }
2297         }
2298
2299
2300         if (!res && final_fixup) {
2301                 unlink(rebase_path_fixup_msg());
2302                 unlink(rebase_path_squash_msg());
2303                 unlink(rebase_path_current_fixups());
2304                 strbuf_reset(&opts->current_fixups);
2305                 opts->current_fixup_count = 0;
2306         }
2307
2308 leave:
2309         free_message(commit, &msg);
2310         free(author);
2311         update_abort_safety_file();
2312
2313         return res;
2314 }
2315
2316 static int prepare_revs(struct replay_opts *opts)
2317 {
2318         /*
2319          * picking (but not reverting) ranges (but not individual revisions)
2320          * should be done in reverse
2321          */
2322         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2323                 opts->revs->reverse ^= 1;
2324
2325         if (prepare_revision_walk(opts->revs))
2326                 return error(_("revision walk setup failed"));
2327
2328         return 0;
2329 }
2330
2331 static int read_and_refresh_cache(struct repository *r,
2332                                   struct replay_opts *opts)
2333 {
2334         struct lock_file index_lock = LOCK_INIT;
2335         int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2336         if (repo_read_index(r) < 0) {
2337                 rollback_lock_file(&index_lock);
2338                 return error(_("git %s: failed to read the index"),
2339                         _(action_name(opts)));
2340         }
2341         refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2342         if (index_fd >= 0) {
2343                 if (write_locked_index(r->index, &index_lock,
2344                                        COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2345                         return error(_("git %s: failed to refresh the index"),
2346                                 _(action_name(opts)));
2347                 }
2348         }
2349         return 0;
2350 }
2351
2352 void todo_list_release(struct todo_list *todo_list)
2353 {
2354         strbuf_release(&todo_list->buf);
2355         FREE_AND_NULL(todo_list->items);
2356         todo_list->nr = todo_list->alloc = 0;
2357 }
2358
2359 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2360 {
2361         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2362         todo_list->total_nr++;
2363         return todo_list->items + todo_list->nr++;
2364 }
2365
2366 const char *todo_item_get_arg(struct todo_list *todo_list,
2367                               struct todo_item *item)
2368 {
2369         return todo_list->buf.buf + item->arg_offset;
2370 }
2371
2372 static int is_command(enum todo_command command, const char **bol)
2373 {
2374         const char *str = todo_command_info[command].str;
2375         const char nick = todo_command_info[command].c;
2376         const char *p = *bol + 1;
2377
2378         return skip_prefix(*bol, str, bol) ||
2379                 ((nick && **bol == nick) &&
2380                  (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p) &&
2381                  (*bol = p));
2382 }
2383
2384 static int parse_insn_line(struct repository *r, struct todo_item *item,
2385                            const char *buf, const char *bol, char *eol)
2386 {
2387         struct object_id commit_oid;
2388         char *end_of_object_name;
2389         int i, saved, status, padding;
2390
2391         item->flags = 0;
2392
2393         /* left-trim */
2394         bol += strspn(bol, " \t");
2395
2396         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2397                 item->command = TODO_COMMENT;
2398                 item->commit = NULL;
2399                 item->arg_offset = bol - buf;
2400                 item->arg_len = eol - bol;
2401                 return 0;
2402         }
2403
2404         for (i = 0; i < TODO_COMMENT; i++)
2405                 if (is_command(i, &bol)) {
2406                         item->command = i;
2407                         break;
2408                 }
2409         if (i >= TODO_COMMENT)
2410                 return -1;
2411
2412         /* Eat up extra spaces/ tabs before object name */
2413         padding = strspn(bol, " \t");
2414         bol += padding;
2415
2416         if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2417                 if (bol != eol)
2418                         return error(_("%s does not accept arguments: '%s'"),
2419                                      command_to_string(item->command), bol);
2420                 item->commit = NULL;
2421                 item->arg_offset = bol - buf;
2422                 item->arg_len = eol - bol;
2423                 return 0;
2424         }
2425
2426         if (!padding)
2427                 return error(_("missing arguments for %s"),
2428                              command_to_string(item->command));
2429
2430         if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2431             item->command == TODO_RESET) {
2432                 item->commit = NULL;
2433                 item->arg_offset = bol - buf;
2434                 item->arg_len = (int)(eol - bol);
2435                 return 0;
2436         }
2437
2438         if (item->command == TODO_FIXUP) {
2439                 if (skip_prefix(bol, "-C", &bol) &&
2440                    (*bol == ' ' || *bol == '\t')) {
2441                         bol += strspn(bol, " \t");
2442                         item->flags |= TODO_REPLACE_FIXUP_MSG;
2443                 } else if (skip_prefix(bol, "-c", &bol) &&
2444                                   (*bol == ' ' || *bol == '\t')) {
2445                         bol += strspn(bol, " \t");
2446                         item->flags |= TODO_EDIT_FIXUP_MSG;
2447                 }
2448         }
2449
2450         if (item->command == TODO_MERGE) {
2451                 if (skip_prefix(bol, "-C", &bol))
2452                         bol += strspn(bol, " \t");
2453                 else if (skip_prefix(bol, "-c", &bol)) {
2454                         bol += strspn(bol, " \t");
2455                         item->flags |= TODO_EDIT_MERGE_MSG;
2456                 } else {
2457                         item->flags |= TODO_EDIT_MERGE_MSG;
2458                         item->commit = NULL;
2459                         item->arg_offset = bol - buf;
2460                         item->arg_len = (int)(eol - bol);
2461                         return 0;
2462                 }
2463         }
2464
2465         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2466         saved = *end_of_object_name;
2467         *end_of_object_name = '\0';
2468         status = get_oid(bol, &commit_oid);
2469         if (status < 0)
2470                 error(_("could not parse '%s'"), bol); /* return later */
2471         *end_of_object_name = saved;
2472
2473         bol = end_of_object_name + strspn(end_of_object_name, " \t");
2474         item->arg_offset = bol - buf;
2475         item->arg_len = (int)(eol - bol);
2476
2477         if (status < 0)
2478                 return status;
2479
2480         item->commit = lookup_commit_reference(r, &commit_oid);
2481         return item->commit ? 0 : -1;
2482 }
2483
2484 int sequencer_get_last_command(struct repository *r, enum replay_action *action)
2485 {
2486         const char *todo_file, *bol;
2487         struct strbuf buf = STRBUF_INIT;
2488         int ret = 0;
2489
2490         todo_file = git_path_todo_file();
2491         if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2492                 if (errno == ENOENT || errno == ENOTDIR)
2493                         return -1;
2494                 else
2495                         return error_errno("unable to open '%s'", todo_file);
2496         }
2497         bol = buf.buf + strspn(buf.buf, " \t\r\n");
2498         if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2499                 *action = REPLAY_PICK;
2500         else if (is_command(TODO_REVERT, &bol) &&
2501                  (*bol == ' ' || *bol == '\t'))
2502                 *action = REPLAY_REVERT;
2503         else
2504                 ret = -1;
2505
2506         strbuf_release(&buf);
2507
2508         return ret;
2509 }
2510
2511 int todo_list_parse_insn_buffer(struct repository *r, char *buf,
2512                                 struct todo_list *todo_list)
2513 {
2514         struct todo_item *item;
2515         char *p = buf, *next_p;
2516         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2517
2518         todo_list->current = todo_list->nr = 0;
2519
2520         for (i = 1; *p; i++, p = next_p) {
2521                 char *eol = strchrnul(p, '\n');
2522
2523                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2524
2525                 if (p != eol && eol[-1] == '\r')
2526                         eol--; /* strip Carriage Return */
2527
2528                 item = append_new_todo(todo_list);
2529                 item->offset_in_buf = p - todo_list->buf.buf;
2530                 if (parse_insn_line(r, item, buf, p, eol)) {
2531                         res = error(_("invalid line %d: %.*s"),
2532                                 i, (int)(eol - p), p);
2533                         item->command = TODO_COMMENT + 1;
2534                         item->arg_offset = p - buf;
2535                         item->arg_len = (int)(eol - p);
2536                         item->commit = NULL;
2537                 }
2538
2539                 if (fixup_okay)
2540                         ; /* do nothing */
2541                 else if (is_fixup(item->command))
2542                         return error(_("cannot '%s' without a previous commit"),
2543                                 command_to_string(item->command));
2544                 else if (!is_noop(item->command))
2545                         fixup_okay = 1;
2546         }
2547
2548         return res;
2549 }
2550
2551 static int count_commands(struct todo_list *todo_list)
2552 {
2553         int count = 0, i;
2554
2555         for (i = 0; i < todo_list->nr; i++)
2556                 if (todo_list->items[i].command != TODO_COMMENT)
2557                         count++;
2558
2559         return count;
2560 }
2561
2562 static int get_item_line_offset(struct todo_list *todo_list, int index)
2563 {
2564         return index < todo_list->nr ?
2565                 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2566 }
2567
2568 static const char *get_item_line(struct todo_list *todo_list, int index)
2569 {
2570         return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2571 }
2572
2573 static int get_item_line_length(struct todo_list *todo_list, int index)
2574 {
2575         return get_item_line_offset(todo_list, index + 1)
2576                 -  get_item_line_offset(todo_list, index);
2577 }
2578
2579 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2580 {
2581         int fd;
2582         ssize_t len;
2583
2584         fd = open(path, O_RDONLY);
2585         if (fd < 0)
2586                 return error_errno(_("could not open '%s'"), path);
2587         len = strbuf_read(sb, fd, 0);
2588         close(fd);
2589         if (len < 0)
2590                 return error(_("could not read '%s'."), path);
2591         return len;
2592 }
2593
2594 static int have_finished_the_last_pick(void)
2595 {
2596         struct strbuf buf = STRBUF_INIT;
2597         const char *eol;
2598         const char *todo_path = git_path_todo_file();
2599         int ret = 0;
2600
2601         if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2602                 if (errno == ENOENT) {
2603                         return 0;
2604                 } else {
2605                         error_errno("unable to open '%s'", todo_path);
2606                         return 0;
2607                 }
2608         }
2609         /* If there is only one line then we are done */
2610         eol = strchr(buf.buf, '\n');
2611         if (!eol || !eol[1])
2612                 ret = 1;
2613
2614         strbuf_release(&buf);
2615
2616         return ret;
2617 }
2618
2619 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
2620 {
2621         struct replay_opts opts = REPLAY_OPTS_INIT;
2622         int need_cleanup = 0;
2623
2624         if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
2625                 if (!refs_delete_ref(get_main_ref_store(r), "",
2626                                      "CHERRY_PICK_HEAD", NULL, 0) &&
2627                     verbose)
2628                         warning(_("cancelling a cherry picking in progress"));
2629                 opts.action = REPLAY_PICK;
2630                 need_cleanup = 1;
2631         }
2632
2633         if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2634                 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2635                                      NULL, 0) &&
2636                     verbose)
2637                         warning(_("cancelling a revert in progress"));
2638                 opts.action = REPLAY_REVERT;
2639                 need_cleanup = 1;
2640         }
2641
2642         if (!need_cleanup)
2643                 return;
2644
2645         if (!have_finished_the_last_pick())
2646                 return;
2647
2648         sequencer_remove_state(&opts);
2649 }
2650
2651 static void todo_list_write_total_nr(struct todo_list *todo_list)
2652 {
2653         FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2654
2655         if (f) {
2656                 fprintf(f, "%d\n", todo_list->total_nr);
2657                 fclose(f);
2658         }
2659 }
2660
2661 static int read_populate_todo(struct repository *r,
2662                               struct todo_list *todo_list,
2663                               struct replay_opts *opts)
2664 {
2665         struct stat st;
2666         const char *todo_file = get_todo_path(opts);
2667         int res;
2668
2669         strbuf_reset(&todo_list->buf);
2670         if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2671                 return -1;
2672
2673         res = stat(todo_file, &st);
2674         if (res)
2675                 return error(_("could not stat '%s'"), todo_file);
2676         fill_stat_data(&todo_list->stat, &st);
2677
2678         res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2679         if (res) {
2680                 if (is_rebase_i(opts))
2681                         return error(_("please fix this using "
2682                                        "'git rebase --edit-todo'."));
2683                 return error(_("unusable instruction sheet: '%s'"), todo_file);
2684         }
2685
2686         if (!todo_list->nr &&
2687             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2688                 return error(_("no commits parsed."));
2689
2690         if (!is_rebase_i(opts)) {
2691                 enum todo_command valid =
2692                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2693                 int i;
2694
2695                 for (i = 0; i < todo_list->nr; i++)
2696                         if (valid == todo_list->items[i].command)
2697                                 continue;
2698                         else if (valid == TODO_PICK)
2699                                 return error(_("cannot cherry-pick during a revert."));
2700                         else
2701                                 return error(_("cannot revert during a cherry-pick."));
2702         }
2703
2704         if (is_rebase_i(opts)) {
2705                 struct todo_list done = TODO_LIST_INIT;
2706
2707                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2708                     !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2709                         todo_list->done_nr = count_commands(&done);
2710                 else
2711                         todo_list->done_nr = 0;
2712
2713                 todo_list->total_nr = todo_list->done_nr
2714                         + count_commands(todo_list);
2715                 todo_list_release(&done);
2716
2717                 todo_list_write_total_nr(todo_list);
2718         }
2719
2720         return 0;
2721 }
2722
2723 static int git_config_string_dup(char **dest,
2724                                  const char *var, const char *value)
2725 {
2726         if (!value)
2727                 return config_error_nonbool(var);
2728         free(*dest);
2729         *dest = xstrdup(value);
2730         return 0;
2731 }
2732
2733 static int populate_opts_cb(const char *key, const char *value, void *data)
2734 {
2735         struct replay_opts *opts = data;
2736         int error_flag = 1;
2737
2738         if (!value)
2739                 error_flag = 0;
2740         else if (!strcmp(key, "options.no-commit"))
2741                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2742         else if (!strcmp(key, "options.edit"))
2743                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2744         else if (!strcmp(key, "options.allow-empty"))
2745                 opts->allow_empty =
2746                         git_config_bool_or_int(key, value, &error_flag);
2747         else if (!strcmp(key, "options.allow-empty-message"))
2748                 opts->allow_empty_message =
2749                         git_config_bool_or_int(key, value, &error_flag);
2750         else if (!strcmp(key, "options.keep-redundant-commits"))
2751                 opts->keep_redundant_commits =
2752                         git_config_bool_or_int(key, value, &error_flag);
2753         else if (!strcmp(key, "options.signoff"))
2754                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2755         else if (!strcmp(key, "options.record-origin"))
2756                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2757         else if (!strcmp(key, "options.allow-ff"))
2758                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2759         else if (!strcmp(key, "options.mainline"))
2760                 opts->mainline = git_config_int(key, value);
2761         else if (!strcmp(key, "options.strategy"))
2762                 git_config_string_dup(&opts->strategy, key, value);
2763         else if (!strcmp(key, "options.gpg-sign"))
2764                 git_config_string_dup(&opts->gpg_sign, key, value);
2765         else if (!strcmp(key, "options.strategy-option")) {
2766                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2767                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2768         } else if (!strcmp(key, "options.allow-rerere-auto"))
2769                 opts->allow_rerere_auto =
2770                         git_config_bool_or_int(key, value, &error_flag) ?
2771                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2772         else if (!strcmp(key, "options.default-msg-cleanup")) {
2773                 opts->explicit_cleanup = 1;
2774                 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2775         } else
2776                 return error(_("invalid key: %s"), key);
2777
2778         if (!error_flag)
2779                 return error(_("invalid value for %s: %s"), key, value);
2780
2781         return 0;
2782 }
2783
2784 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2785 {
2786         int i;
2787         char *strategy_opts_string = raw_opts;
2788
2789         if (*strategy_opts_string == ' ')
2790                 strategy_opts_string++;
2791
2792         opts->xopts_nr = split_cmdline(strategy_opts_string,
2793                                        (const char ***)&opts->xopts);
2794         for (i = 0; i < opts->xopts_nr; i++) {
2795                 const char *arg = opts->xopts[i];
2796
2797                 skip_prefix(arg, "--", &arg);
2798                 opts->xopts[i] = xstrdup(arg);
2799         }
2800 }
2801
2802 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2803 {
2804         strbuf_reset(buf);
2805         if (!read_oneliner(buf, rebase_path_strategy(), 0))
2806                 return;
2807         opts->strategy = strbuf_detach(buf, NULL);
2808         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2809                 return;
2810
2811         parse_strategy_opts(opts, buf->buf);
2812 }
2813
2814 static int read_populate_opts(struct replay_opts *opts)
2815 {
2816         if (is_rebase_i(opts)) {
2817                 struct strbuf buf = STRBUF_INIT;
2818                 int ret = 0;
2819
2820                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2821                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2822                         if (!starts_with(buf.buf, "-S"))
2823                                 strbuf_reset(&buf);
2824                         else {
2825                                 free(opts->gpg_sign);
2826                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2827                         }
2828                         strbuf_reset(&buf);
2829                 }
2830
2831                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2832                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2833                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2834                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2835                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2836                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2837                         strbuf_reset(&buf);
2838                 }
2839
2840                 if (file_exists(rebase_path_verbose()))
2841                         opts->verbose = 1;
2842
2843                 if (file_exists(rebase_path_quiet()))
2844                         opts->quiet = 1;
2845
2846                 if (file_exists(rebase_path_signoff())) {
2847                         opts->allow_ff = 0;
2848                         opts->signoff = 1;
2849                 }
2850
2851                 if (file_exists(rebase_path_cdate_is_adate())) {
2852                         opts->allow_ff = 0;
2853                         opts->committer_date_is_author_date = 1;
2854                 }
2855
2856                 if (file_exists(rebase_path_ignore_date())) {
2857                         opts->allow_ff = 0;
2858                         opts->ignore_date = 1;
2859                 }
2860
2861                 if (file_exists(rebase_path_reschedule_failed_exec()))
2862                         opts->reschedule_failed_exec = 1;
2863
2864                 if (file_exists(rebase_path_drop_redundant_commits()))
2865                         opts->drop_redundant_commits = 1;
2866
2867                 if (file_exists(rebase_path_keep_redundant_commits()))
2868                         opts->keep_redundant_commits = 1;
2869
2870                 read_strategy_opts(opts, &buf);
2871                 strbuf_reset(&buf);
2872
2873                 if (read_oneliner(&opts->current_fixups,
2874                                   rebase_path_current_fixups(),
2875                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2876                         const char *p = opts->current_fixups.buf;
2877                         opts->current_fixup_count = 1;
2878                         while ((p = strchr(p, '\n'))) {
2879                                 opts->current_fixup_count++;
2880                                 p++;
2881                         }
2882                 }
2883
2884                 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2885                         if (get_oid_committish(buf.buf, &opts->squash_onto) < 0) {
2886                                 ret = error(_("unusable squash-onto"));
2887                                 goto done_rebase_i;
2888                         }
2889                         opts->have_squash_onto = 1;
2890                 }
2891
2892 done_rebase_i:
2893                 strbuf_release(&buf);
2894                 return ret;
2895         }
2896
2897         if (!file_exists(git_path_opts_file()))
2898                 return 0;
2899         /*
2900          * The function git_parse_source(), called from git_config_from_file(),
2901          * may die() in case of a syntactically incorrect file. We do not care
2902          * about this case, though, because we wrote that file ourselves, so we
2903          * are pretty certain that it is syntactically correct.
2904          */
2905         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2906                 return error(_("malformed options sheet: '%s'"),
2907                         git_path_opts_file());
2908         return 0;
2909 }
2910
2911 static void write_strategy_opts(struct replay_opts *opts)
2912 {
2913         int i;
2914         struct strbuf buf = STRBUF_INIT;
2915
2916         for (i = 0; i < opts->xopts_nr; ++i)
2917                 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2918
2919         write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2920         strbuf_release(&buf);
2921 }
2922
2923 int write_basic_state(struct replay_opts *opts, const char *head_name,
2924                       struct commit *onto, const struct object_id *orig_head)
2925 {
2926         if (head_name)
2927                 write_file(rebase_path_head_name(), "%s\n", head_name);
2928         if (onto)
2929                 write_file(rebase_path_onto(), "%s\n",
2930                            oid_to_hex(&onto->object.oid));
2931         if (orig_head)
2932                 write_file(rebase_path_orig_head(), "%s\n",
2933                            oid_to_hex(orig_head));
2934
2935         if (opts->quiet)
2936                 write_file(rebase_path_quiet(), "%s", "");
2937         if (opts->verbose)
2938                 write_file(rebase_path_verbose(), "%s", "");
2939         if (opts->strategy)
2940                 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2941         if (opts->xopts_nr > 0)
2942                 write_strategy_opts(opts);
2943
2944         if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2945                 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2946         else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2947                 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2948
2949         if (opts->gpg_sign)
2950                 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2951         if (opts->signoff)
2952                 write_file(rebase_path_signoff(), "--signoff\n");
2953         if (opts->drop_redundant_commits)
2954                 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2955         if (opts->keep_redundant_commits)
2956                 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2957         if (opts->committer_date_is_author_date)
2958                 write_file(rebase_path_cdate_is_adate(), "%s", "");
2959         if (opts->ignore_date)
2960                 write_file(rebase_path_ignore_date(), "%s", "");
2961         if (opts->reschedule_failed_exec)
2962                 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2963
2964         return 0;
2965 }
2966
2967 static int walk_revs_populate_todo(struct todo_list *todo_list,
2968                                 struct replay_opts *opts)
2969 {
2970         enum todo_command command = opts->action == REPLAY_PICK ?
2971                 TODO_PICK : TODO_REVERT;
2972         const char *command_string = todo_command_info[command].str;
2973         const char *encoding;
2974         struct commit *commit;
2975
2976         if (prepare_revs(opts))
2977                 return -1;
2978
2979         encoding = get_log_output_encoding();
2980
2981         while ((commit = get_revision(opts->revs))) {
2982                 struct todo_item *item = append_new_todo(todo_list);
2983                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2984                 const char *subject;
2985                 int subject_len;
2986
2987                 item->command = command;
2988                 item->commit = commit;
2989                 item->arg_offset = 0;
2990                 item->arg_len = 0;
2991                 item->offset_in_buf = todo_list->buf.len;
2992                 subject_len = find_commit_subject(commit_buffer, &subject);
2993                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2994                         short_commit_name(commit), subject_len, subject);
2995                 unuse_commit_buffer(commit, commit_buffer);
2996         }
2997
2998         if (!todo_list->nr)
2999                 return error(_("empty commit set passed"));
3000
3001         return 0;
3002 }
3003
3004 static int create_seq_dir(struct repository *r)
3005 {
3006         enum replay_action action;
3007         const char *in_progress_error = NULL;
3008         const char *in_progress_advice = NULL;
3009         unsigned int advise_skip =
3010                 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3011                 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3012
3013         if (!sequencer_get_last_command(r, &action)) {
3014                 switch (action) {
3015                 case REPLAY_REVERT:
3016                         in_progress_error = _("revert is already in progress");
3017                         in_progress_advice =
3018                         _("try \"git revert (--continue | %s--abort | --quit)\"");
3019                         break;
3020                 case REPLAY_PICK:
3021                         in_progress_error = _("cherry-pick is already in progress");
3022                         in_progress_advice =
3023                         _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3024                         break;
3025                 default:
3026                         BUG("unexpected action in create_seq_dir");
3027                 }
3028         }
3029         if (in_progress_error) {
3030                 error("%s", in_progress_error);
3031                 if (advice_sequencer_in_use)
3032                         advise(in_progress_advice,
3033                                 advise_skip ? "--skip | " : "");
3034                 return -1;
3035         }
3036         if (mkdir(git_path_seq_dir(), 0777) < 0)
3037                 return error_errno(_("could not create sequencer directory '%s'"),
3038                                    git_path_seq_dir());
3039
3040         return 0;
3041 }
3042
3043 static int save_head(const char *head)
3044 {
3045         struct lock_file head_lock = LOCK_INIT;
3046         struct strbuf buf = STRBUF_INIT;
3047         int fd;
3048         ssize_t written;
3049
3050         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
3051         if (fd < 0)
3052                 return error_errno(_("could not lock HEAD"));
3053         strbuf_addf(&buf, "%s\n", head);
3054         written = write_in_full(fd, buf.buf, buf.len);
3055         strbuf_release(&buf);
3056         if (written < 0) {
3057                 error_errno(_("could not write to '%s'"), git_path_head_file());
3058                 rollback_lock_file(&head_lock);
3059                 return -1;
3060         }
3061         if (commit_lock_file(&head_lock) < 0)
3062                 return error(_("failed to finalize '%s'"), git_path_head_file());
3063         return 0;
3064 }
3065
3066 static int rollback_is_safe(void)
3067 {
3068         struct strbuf sb = STRBUF_INIT;
3069         struct object_id expected_head, actual_head;
3070
3071         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3072                 strbuf_trim(&sb);
3073                 if (get_oid_hex(sb.buf, &expected_head)) {
3074                         strbuf_release(&sb);
3075                         die(_("could not parse %s"), git_path_abort_safety_file());
3076                 }
3077                 strbuf_release(&sb);
3078         }
3079         else if (errno == ENOENT)
3080                 oidclr(&expected_head);
3081         else
3082                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3083
3084         if (get_oid("HEAD", &actual_head))
3085                 oidclr(&actual_head);
3086
3087         return oideq(&actual_head, &expected_head);
3088 }
3089
3090 static int reset_merge(const struct object_id *oid)
3091 {
3092         int ret;
3093         struct strvec argv = STRVEC_INIT;
3094
3095         strvec_pushl(&argv, "reset", "--merge", NULL);
3096
3097         if (!is_null_oid(oid))
3098                 strvec_push(&argv, oid_to_hex(oid));
3099
3100         ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
3101         strvec_clear(&argv);
3102
3103         return ret;
3104 }
3105
3106 static int rollback_single_pick(struct repository *r)
3107 {
3108         struct object_id head_oid;
3109
3110         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3111             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3112                 return error(_("no cherry-pick or revert in progress"));
3113         if (read_ref_full("HEAD", 0, &head_oid, NULL))
3114                 return error(_("cannot resolve HEAD"));
3115         if (is_null_oid(&head_oid))
3116                 return error(_("cannot abort from a branch yet to be born"));
3117         return reset_merge(&head_oid);
3118 }
3119
3120 static int skip_single_pick(void)
3121 {
3122         struct object_id head;
3123
3124         if (read_ref_full("HEAD", 0, &head, NULL))
3125                 return error(_("cannot resolve HEAD"));
3126         return reset_merge(&head);
3127 }
3128
3129 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3130 {
3131         FILE *f;
3132         struct object_id oid;
3133         struct strbuf buf = STRBUF_INIT;
3134         const char *p;
3135
3136         f = fopen(git_path_head_file(), "r");
3137         if (!f && errno == ENOENT) {
3138                 /*
3139                  * There is no multiple-cherry-pick in progress.
3140                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3141                  * a single-cherry-pick in progress, abort that.
3142                  */
3143                 return rollback_single_pick(r);
3144         }
3145         if (!f)
3146                 return error_errno(_("cannot open '%s'"), git_path_head_file());
3147         if (strbuf_getline_lf(&buf, f)) {
3148                 error(_("cannot read '%s': %s"), git_path_head_file(),
3149                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
3150                 fclose(f);
3151                 goto fail;
3152         }
3153         fclose(f);
3154         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3155                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3156                         git_path_head_file());
3157                 goto fail;
3158         }
3159         if (is_null_oid(&oid)) {
3160                 error(_("cannot abort from a branch yet to be born"));
3161                 goto fail;
3162         }
3163
3164         if (!rollback_is_safe()) {
3165                 /* Do not error, just do not rollback */
3166                 warning(_("You seem to have moved HEAD. "
3167                           "Not rewinding, check your HEAD!"));
3168         } else
3169         if (reset_merge(&oid))
3170                 goto fail;
3171         strbuf_release(&buf);
3172         return sequencer_remove_state(opts);
3173 fail:
3174         strbuf_release(&buf);
3175         return -1;
3176 }
3177
3178 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3179 {
3180         enum replay_action action = -1;
3181         sequencer_get_last_command(r, &action);
3182
3183         /*
3184          * Check whether the subcommand requested to skip the commit is actually
3185          * in progress and that it's safe to skip the commit.
3186          *
3187          * opts->action tells us which subcommand requested to skip the commit.
3188          * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3189          * action is in progress and we can skip the commit.
3190          *
3191          * Otherwise we check that the last instruction was related to the
3192          * particular subcommand we're trying to execute and barf if that's not
3193          * the case.
3194          *
3195          * Finally we check that the rollback is "safe", i.e., has the HEAD
3196          * moved? In this case, it doesn't make sense to "reset the merge" and
3197          * "skip the commit" as the user already handled this by committing. But
3198          * we'd not want to barf here, instead give advice on how to proceed. We
3199          * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3200          * it gets removed when the user commits, so if it still exists we're
3201          * sure the user can't have committed before.
3202          */
3203         switch (opts->action) {
3204         case REPLAY_REVERT:
3205                 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3206                         if (action != REPLAY_REVERT)
3207                                 return error(_("no revert in progress"));
3208                         if (!rollback_is_safe())
3209                                 goto give_advice;
3210                 }
3211                 break;
3212         case REPLAY_PICK:
3213                 if (!refs_ref_exists(get_main_ref_store(r),
3214                                      "CHERRY_PICK_HEAD")) {
3215                         if (action != REPLAY_PICK)
3216                                 return error(_("no cherry-pick in progress"));
3217                         if (!rollback_is_safe())
3218                                 goto give_advice;
3219                 }
3220                 break;
3221         default:
3222                 BUG("unexpected action in sequencer_skip");
3223         }
3224
3225         if (skip_single_pick())
3226                 return error(_("failed to skip the commit"));
3227         if (!is_directory(git_path_seq_dir()))
3228                 return 0;
3229
3230         return sequencer_continue(r, opts);
3231
3232 give_advice:
3233         error(_("there is nothing to skip"));
3234
3235         if (advice_resolve_conflict) {
3236                 advise(_("have you committed already?\n"
3237                          "try \"git %s --continue\""),
3238                          action == REPLAY_REVERT ? "revert" : "cherry-pick");
3239         }
3240         return -1;
3241 }
3242
3243 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
3244 {
3245         struct lock_file todo_lock = LOCK_INIT;
3246         const char *todo_path = get_todo_path(opts);
3247         int next = todo_list->current, offset, fd;
3248
3249         /*
3250          * rebase -i writes "git-rebase-todo" without the currently executing
3251          * command, appending it to "done" instead.
3252          */
3253         if (is_rebase_i(opts))
3254                 next++;
3255
3256         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3257         if (fd < 0)
3258                 return error_errno(_("could not lock '%s'"), todo_path);
3259         offset = get_item_line_offset(todo_list, next);
3260         if (write_in_full(fd, todo_list->buf.buf + offset,
3261                         todo_list->buf.len - offset) < 0)
3262                 return error_errno(_("could not write to '%s'"), todo_path);
3263         if (commit_lock_file(&todo_lock) < 0)
3264                 return error(_("failed to finalize '%s'"), todo_path);
3265
3266         if (is_rebase_i(opts) && next > 0) {
3267                 const char *done = rebase_path_done();
3268                 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3269                 int ret = 0;
3270
3271                 if (fd < 0)
3272                         return 0;
3273                 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3274                                   get_item_line_length(todo_list, next - 1))
3275                     < 0)
3276                         ret = error_errno(_("could not write to '%s'"), done);
3277                 if (close(fd) < 0)
3278                         ret = error_errno(_("failed to finalize '%s'"), done);
3279                 return ret;
3280         }
3281         return 0;
3282 }
3283
3284 static int save_opts(struct replay_opts *opts)
3285 {
3286         const char *opts_file = git_path_opts_file();
3287         int res = 0;
3288
3289         if (opts->no_commit)
3290                 res |= git_config_set_in_file_gently(opts_file,
3291                                         "options.no-commit", "true");
3292         if (opts->edit)
3293                 res |= git_config_set_in_file_gently(opts_file,
3294                                         "options.edit", "true");
3295         if (opts->allow_empty)
3296                 res |= git_config_set_in_file_gently(opts_file,
3297                                         "options.allow-empty", "true");
3298         if (opts->allow_empty_message)
3299                 res |= git_config_set_in_file_gently(opts_file,
3300                                 "options.allow-empty-message", "true");
3301         if (opts->keep_redundant_commits)
3302                 res |= git_config_set_in_file_gently(opts_file,
3303                                 "options.keep-redundant-commits", "true");
3304         if (opts->signoff)
3305                 res |= git_config_set_in_file_gently(opts_file,
3306                                         "options.signoff", "true");
3307         if (opts->record_origin)
3308                 res |= git_config_set_in_file_gently(opts_file,
3309                                         "options.record-origin", "true");
3310         if (opts->allow_ff)
3311                 res |= git_config_set_in_file_gently(opts_file,
3312                                         "options.allow-ff", "true");
3313         if (opts->mainline) {
3314                 struct strbuf buf = STRBUF_INIT;
3315                 strbuf_addf(&buf, "%d", opts->mainline);
3316                 res |= git_config_set_in_file_gently(opts_file,
3317                                         "options.mainline", buf.buf);
3318                 strbuf_release(&buf);
3319         }
3320         if (opts->strategy)
3321                 res |= git_config_set_in_file_gently(opts_file,
3322                                         "options.strategy", opts->strategy);
3323         if (opts->gpg_sign)
3324                 res |= git_config_set_in_file_gently(opts_file,
3325                                         "options.gpg-sign", opts->gpg_sign);
3326         if (opts->xopts) {
3327                 int i;
3328                 for (i = 0; i < opts->xopts_nr; i++)
3329                         res |= git_config_set_multivar_in_file_gently(opts_file,
3330                                         "options.strategy-option",
3331                                         opts->xopts[i], "^$", 0);
3332         }
3333         if (opts->allow_rerere_auto)
3334                 res |= git_config_set_in_file_gently(opts_file,
3335                                 "options.allow-rerere-auto",
3336                                 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3337                                 "true" : "false");
3338
3339         if (opts->explicit_cleanup)
3340                 res |= git_config_set_in_file_gently(opts_file,
3341                                 "options.default-msg-cleanup",
3342                                 describe_cleanup_mode(opts->default_msg_cleanup));
3343         return res;
3344 }
3345
3346 static int make_patch(struct repository *r,
3347                       struct commit *commit,
3348                       struct replay_opts *opts)
3349 {
3350         struct strbuf buf = STRBUF_INIT;
3351         struct rev_info log_tree_opt;
3352         const char *subject;
3353         char hex[GIT_MAX_HEXSZ + 1];
3354         int res = 0;
3355
3356         oid_to_hex_r(hex, &commit->object.oid);
3357         if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3358                 return -1;
3359         res |= write_rebase_head(&commit->object.oid);
3360
3361         strbuf_addf(&buf, "%s/patch", get_dir(opts));
3362         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3363         repo_init_revisions(r, &log_tree_opt, NULL);
3364         log_tree_opt.abbrev = 0;
3365         log_tree_opt.diff = 1;
3366         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3367         log_tree_opt.disable_stdin = 1;
3368         log_tree_opt.no_commit_id = 1;
3369         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3370         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3371         if (!log_tree_opt.diffopt.file)
3372                 res |= error_errno(_("could not open '%s'"), buf.buf);
3373         else {
3374                 res |= log_tree_commit(&log_tree_opt, commit);
3375                 fclose(log_tree_opt.diffopt.file);
3376         }
3377         strbuf_reset(&buf);
3378
3379         strbuf_addf(&buf, "%s/message", get_dir(opts));
3380         if (!file_exists(buf.buf)) {
3381                 const char *encoding = get_commit_output_encoding();
3382                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3383                 find_commit_subject(commit_buffer, &subject);
3384                 res |= write_message(subject, strlen(subject), buf.buf, 1);
3385                 unuse_commit_buffer(commit, commit_buffer);
3386         }
3387         strbuf_release(&buf);
3388
3389         return res;
3390 }
3391
3392 static int intend_to_amend(void)
3393 {
3394         struct object_id head;
3395         char *p;
3396
3397         if (get_oid("HEAD", &head))
3398                 return error(_("cannot read HEAD"));
3399
3400         p = oid_to_hex(&head);
3401         return write_message(p, strlen(p), rebase_path_amend(), 1);
3402 }
3403
3404 static int error_with_patch(struct repository *r,
3405                             struct commit *commit,
3406                             const char *subject, int subject_len,
3407                             struct replay_opts *opts,
3408                             int exit_code, int to_amend)
3409 {
3410         if (commit) {
3411                 if (make_patch(r, commit, opts))
3412                         return -1;
3413         } else if (copy_file(rebase_path_message(),
3414                              git_path_merge_msg(r), 0666))
3415                 return error(_("unable to copy '%s' to '%s'"),
3416                              git_path_merge_msg(r), rebase_path_message());
3417
3418         if (to_amend) {
3419                 if (intend_to_amend())
3420                         return -1;
3421
3422                 fprintf(stderr,
3423                         _("You can amend the commit now, with\n"
3424                           "\n"
3425                           "  git commit --amend %s\n"
3426                           "\n"
3427                           "Once you are satisfied with your changes, run\n"
3428                           "\n"
3429                           "  git rebase --continue\n"),
3430                         gpg_sign_opt_quoted(opts));
3431         } else if (exit_code) {
3432                 if (commit)
3433                         fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3434                                    short_commit_name(commit), subject_len, subject);
3435                 else
3436                         /*
3437                          * We don't have the hash of the parent so
3438                          * just print the line from the todo file.
3439                          */
3440                         fprintf_ln(stderr, _("Could not merge %.*s"),
3441                                    subject_len, subject);
3442         }
3443
3444         return exit_code;
3445 }
3446
3447 static int error_failed_squash(struct repository *r,
3448                                struct commit *commit,
3449                                struct replay_opts *opts,
3450                                int subject_len,
3451                                const char *subject)
3452 {
3453         if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3454                 return error(_("could not copy '%s' to '%s'"),
3455                         rebase_path_squash_msg(), rebase_path_message());
3456         unlink(git_path_merge_msg(r));
3457         if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3458                 return error(_("could not copy '%s' to '%s'"),
3459                              rebase_path_message(),
3460                              git_path_merge_msg(r));
3461         return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3462 }
3463
3464 static int do_exec(struct repository *r, const char *command_line)
3465 {
3466         struct strvec child_env = STRVEC_INIT;
3467         const char *child_argv[] = { NULL, NULL };
3468         int dirty, status;
3469
3470         fprintf(stderr, _("Executing: %s\n"), command_line);
3471         child_argv[0] = command_line;
3472         strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3473         strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3474                      absolute_path(get_git_work_tree()));
3475         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3476                                           child_env.v);
3477
3478         /* force re-reading of the cache */
3479         if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3480                 return error(_("could not read index"));
3481
3482         dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3483
3484         if (status) {
3485                 warning(_("execution failed: %s\n%s"
3486                           "You can fix the problem, and then run\n"
3487                           "\n"
3488                           "  git rebase --continue\n"
3489                           "\n"),
3490                         command_line,
3491                         dirty ? N_("and made changes to the index and/or the "
3492                                 "working tree\n") : "");
3493                 if (status == 127)
3494                         /* command not found */
3495                         status = 1;
3496         } else if (dirty) {
3497                 warning(_("execution succeeded: %s\nbut "
3498                           "left changes to the index and/or the working tree\n"
3499                           "Commit or stash your changes, and then run\n"
3500                           "\n"
3501                           "  git rebase --continue\n"
3502                           "\n"), command_line);
3503                 status = 1;
3504         }
3505
3506         strvec_clear(&child_env);
3507
3508         return status;
3509 }
3510
3511 static int safe_append(const char *filename, const char *fmt, ...)
3512 {
3513         va_list ap;
3514         struct lock_file lock = LOCK_INIT;
3515         int fd = hold_lock_file_for_update(&lock, filename,
3516                                            LOCK_REPORT_ON_ERROR);
3517         struct strbuf buf = STRBUF_INIT;
3518
3519         if (fd < 0)
3520                 return -1;
3521
3522         if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3523                 error_errno(_("could not read '%s'"), filename);
3524                 rollback_lock_file(&lock);
3525                 return -1;
3526         }
3527         strbuf_complete(&buf, '\n');
3528         va_start(ap, fmt);
3529         strbuf_vaddf(&buf, fmt, ap);
3530         va_end(ap);
3531
3532         if (write_in_full(fd, buf.buf, buf.len) < 0) {
3533                 error_errno(_("could not write to '%s'"), filename);
3534                 strbuf_release(&buf);
3535                 rollback_lock_file(&lock);
3536                 return -1;
3537         }
3538         if (commit_lock_file(&lock) < 0) {
3539                 strbuf_release(&buf);
3540                 rollback_lock_file(&lock);
3541                 return error(_("failed to finalize '%s'"), filename);
3542         }
3543
3544         strbuf_release(&buf);
3545         return 0;
3546 }
3547
3548 static int do_label(struct repository *r, const char *name, int len)
3549 {
3550         struct ref_store *refs = get_main_ref_store(r);
3551         struct ref_transaction *transaction;
3552         struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3553         struct strbuf msg = STRBUF_INIT;
3554         int ret = 0;
3555         struct object_id head_oid;
3556
3557         if (len == 1 && *name == '#')
3558                 return error(_("illegal label name: '%.*s'"), len, name);
3559
3560         strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3561         strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3562
3563         transaction = ref_store_transaction_begin(refs, &err);
3564         if (!transaction) {
3565                 error("%s", err.buf);
3566                 ret = -1;
3567         } else if (get_oid("HEAD", &head_oid)) {
3568                 error(_("could not read HEAD"));
3569                 ret = -1;
3570         } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3571                                           NULL, 0, msg.buf, &err) < 0 ||
3572                    ref_transaction_commit(transaction, &err)) {
3573                 error("%s", err.buf);
3574                 ret = -1;
3575         }
3576         ref_transaction_free(transaction);
3577         strbuf_release(&err);
3578         strbuf_release(&msg);
3579
3580         if (!ret)
3581                 ret = safe_append(rebase_path_refs_to_delete(),
3582                                   "%s\n", ref_name.buf);
3583         strbuf_release(&ref_name);
3584
3585         return ret;
3586 }
3587
3588 static const char *reflog_message(struct replay_opts *opts,
3589         const char *sub_action, const char *fmt, ...);
3590
3591 static int do_reset(struct repository *r,
3592                     const char *name, int len,
3593                     struct replay_opts *opts)
3594 {
3595         struct strbuf ref_name = STRBUF_INIT;
3596         struct object_id oid;
3597         struct lock_file lock = LOCK_INIT;
3598         struct tree_desc desc;
3599         struct tree *tree;
3600         struct unpack_trees_options unpack_tree_opts;
3601         int ret = 0;
3602
3603         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3604                 return -1;
3605
3606         if (len == 10 && !strncmp("[new root]", name, len)) {
3607                 if (!opts->have_squash_onto) {
3608                         const char *hex;
3609                         if (commit_tree("", 0, the_hash_algo->empty_tree,
3610                                         NULL, &opts->squash_onto,
3611                                         NULL, NULL))
3612                                 return error(_("writing fake root commit"));
3613                         opts->have_squash_onto = 1;
3614                         hex = oid_to_hex(&opts->squash_onto);
3615                         if (write_message(hex, strlen(hex),
3616                                           rebase_path_squash_onto(), 0))
3617                                 return error(_("writing squash-onto"));
3618                 }
3619                 oidcpy(&oid, &opts->squash_onto);
3620         } else {
3621                 int i;
3622
3623                 /* Determine the length of the label */
3624                 for (i = 0; i < len; i++)
3625                         if (isspace(name[i]))
3626                                 break;
3627                 len = i;
3628
3629                 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3630                 if (get_oid(ref_name.buf, &oid) &&
3631                     get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3632                         error(_("could not read '%s'"), ref_name.buf);
3633                         rollback_lock_file(&lock);
3634                         strbuf_release(&ref_name);
3635                         return -1;
3636                 }
3637         }
3638
3639         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3640         setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3641         unpack_tree_opts.head_idx = 1;
3642         unpack_tree_opts.src_index = r->index;
3643         unpack_tree_opts.dst_index = r->index;
3644         unpack_tree_opts.fn = oneway_merge;
3645         unpack_tree_opts.merge = 1;
3646         unpack_tree_opts.update = 1;
3647         init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3648
3649         if (repo_read_index_unmerged(r)) {
3650                 rollback_lock_file(&lock);
3651                 strbuf_release(&ref_name);
3652                 return error_resolve_conflict(_(action_name(opts)));
3653         }
3654
3655         if (!fill_tree_descriptor(r, &desc, &oid)) {
3656                 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3657                 rollback_lock_file(&lock);
3658                 free((void *)desc.buffer);
3659                 strbuf_release(&ref_name);
3660                 return -1;
3661         }
3662
3663         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3664                 rollback_lock_file(&lock);
3665                 free((void *)desc.buffer);
3666                 strbuf_release(&ref_name);
3667                 return -1;
3668         }
3669
3670         tree = parse_tree_indirect(&oid);
3671         prime_cache_tree(r, r->index, tree);
3672
3673         if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3674                 ret = error(_("could not write index"));
3675         free((void *)desc.buffer);
3676
3677         if (!ret)
3678                 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3679                                                 len, name), "HEAD", &oid,
3680                                  NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3681
3682         strbuf_release(&ref_name);
3683         return ret;
3684 }
3685
3686 static struct commit *lookup_label(const char *label, int len,
3687                                    struct strbuf *buf)
3688 {
3689         struct commit *commit;
3690
3691         strbuf_reset(buf);
3692         strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3693         commit = lookup_commit_reference_by_name(buf->buf);
3694         if (!commit) {
3695                 /* fall back to non-rewritten ref or commit */
3696                 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3697                 commit = lookup_commit_reference_by_name(buf->buf);
3698         }
3699
3700         if (!commit)
3701                 error(_("could not resolve '%s'"), buf->buf);
3702
3703         return commit;
3704 }
3705
3706 static int do_merge(struct repository *r,
3707                     struct commit *commit,
3708                     const char *arg, int arg_len,
3709                     int flags, struct replay_opts *opts)
3710 {
3711         int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3712                 EDIT_MSG | VERIFY_MSG : 0;
3713         struct strbuf ref_name = STRBUF_INIT;
3714         struct commit *head_commit, *merge_commit, *i;
3715         struct commit_list *bases, *j, *reversed = NULL;
3716         struct commit_list *to_merge = NULL, **tail = &to_merge;
3717         const char *strategy = !opts->xopts_nr &&
3718                 (!opts->strategy ||
3719                  !strcmp(opts->strategy, "recursive") ||
3720                  !strcmp(opts->strategy, "ort")) ?
3721                 NULL : opts->strategy;
3722         struct merge_options o;
3723         int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3724         static struct lock_file lock;
3725         const char *p;
3726
3727         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3728                 ret = -1;
3729                 goto leave_merge;
3730         }
3731
3732         head_commit = lookup_commit_reference_by_name("HEAD");
3733         if (!head_commit) {
3734                 ret = error(_("cannot merge without a current revision"));
3735                 goto leave_merge;
3736         }
3737
3738         /*
3739          * For octopus merges, the arg starts with the list of revisions to be
3740          * merged. The list is optionally followed by '#' and the oneline.
3741          */
3742         merge_arg_len = oneline_offset = arg_len;
3743         for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3744                 if (!*p)
3745                         break;
3746                 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3747                         p += 1 + strspn(p + 1, " \t\n");
3748                         oneline_offset = p - arg;
3749                         break;
3750                 }
3751                 k = strcspn(p, " \t\n");
3752                 if (!k)
3753                         continue;
3754                 merge_commit = lookup_label(p, k, &ref_name);
3755                 if (!merge_commit) {
3756                         ret = error(_("unable to parse '%.*s'"), k, p);
3757                         goto leave_merge;
3758                 }
3759                 tail = &commit_list_insert(merge_commit, tail)->next;
3760                 p += k;
3761                 merge_arg_len = p - arg;
3762         }
3763
3764         if (!to_merge) {
3765                 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3766                 goto leave_merge;
3767         }
3768
3769         if (opts->have_squash_onto &&
3770             oideq(&head_commit->object.oid, &opts->squash_onto)) {
3771                 /*
3772                  * When the user tells us to "merge" something into a
3773                  * "[new root]", let's simply fast-forward to the merge head.
3774                  */
3775                 rollback_lock_file(&lock);
3776                 if (to_merge->next)
3777                         ret = error(_("octopus merge cannot be executed on "
3778                                       "top of a [new root]"));
3779                 else
3780                         ret = fast_forward_to(r, &to_merge->item->object.oid,
3781                                               &head_commit->object.oid, 0,
3782                                               opts);
3783                 goto leave_merge;
3784         }
3785
3786         if (commit) {
3787                 const char *encoding = get_commit_output_encoding();
3788                 const char *message = logmsg_reencode(commit, NULL, encoding);
3789                 const char *body;
3790                 int len;
3791
3792                 if (!message) {
3793                         ret = error(_("could not get commit message of '%s'"),
3794                                     oid_to_hex(&commit->object.oid));
3795                         goto leave_merge;
3796                 }
3797                 write_author_script(message);
3798                 find_commit_subject(message, &body);
3799                 len = strlen(body);
3800                 ret = write_message(body, len, git_path_merge_msg(r), 0);
3801                 unuse_commit_buffer(commit, message);
3802                 if (ret) {
3803                         error_errno(_("could not write '%s'"),
3804                                     git_path_merge_msg(r));
3805                         goto leave_merge;
3806                 }
3807         } else {
3808                 struct strbuf buf = STRBUF_INIT;
3809                 int len;
3810
3811                 strbuf_addf(&buf, "author %s", git_author_info(0));
3812                 write_author_script(buf.buf);
3813                 strbuf_reset(&buf);
3814
3815                 if (oneline_offset < arg_len) {
3816                         p = arg + oneline_offset;
3817                         len = arg_len - oneline_offset;
3818                 } else {
3819                         strbuf_addf(&buf, "Merge %s '%.*s'",
3820                                     to_merge->next ? "branches" : "branch",
3821                                     merge_arg_len, arg);
3822                         p = buf.buf;
3823                         len = buf.len;
3824                 }
3825
3826                 ret = write_message(p, len, git_path_merge_msg(r), 0);
3827                 strbuf_release(&buf);
3828                 if (ret) {
3829                         error_errno(_("could not write '%s'"),
3830                                     git_path_merge_msg(r));
3831                         goto leave_merge;
3832                 }
3833         }
3834
3835         /*
3836          * If HEAD is not identical to the first parent of the original merge
3837          * commit, we cannot fast-forward.
3838          */
3839         can_fast_forward = opts->allow_ff && commit && commit->parents &&
3840                 oideq(&commit->parents->item->object.oid,
3841                       &head_commit->object.oid);
3842
3843         /*
3844          * If any merge head is different from the original one, we cannot
3845          * fast-forward.
3846          */
3847         if (can_fast_forward) {
3848                 struct commit_list *p = commit->parents->next;
3849
3850                 for (j = to_merge; j && p; j = j->next, p = p->next)
3851                         if (!oideq(&j->item->object.oid,
3852                                    &p->item->object.oid)) {
3853                                 can_fast_forward = 0;
3854                                 break;
3855                         }
3856                 /*
3857                  * If the number of merge heads differs from the original merge
3858                  * commit, we cannot fast-forward.
3859                  */
3860                 if (j || p)
3861                         can_fast_forward = 0;
3862         }
3863
3864         if (can_fast_forward) {
3865                 rollback_lock_file(&lock);
3866                 ret = fast_forward_to(r, &commit->object.oid,
3867                                       &head_commit->object.oid, 0, opts);
3868                 if (flags & TODO_EDIT_MERGE_MSG) {
3869                         run_commit_flags |= AMEND_MSG;
3870                         goto fast_forward_edit;
3871                 }
3872                 goto leave_merge;
3873         }
3874
3875         if (strategy || to_merge->next) {
3876                 /* Octopus merge */
3877                 struct child_process cmd = CHILD_PROCESS_INIT;
3878
3879                 if (read_env_script(&cmd.env_array)) {
3880                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
3881
3882                         ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3883                         goto leave_merge;
3884                 }
3885
3886                 if (opts->committer_date_is_author_date)
3887                         strvec_pushf(&cmd.env_array, "GIT_COMMITTER_DATE=%s",
3888                                      opts->ignore_date ?
3889                                      "" :
3890                                      author_date_from_env_array(&cmd.env_array));
3891                 if (opts->ignore_date)
3892                         strvec_push(&cmd.env_array, "GIT_AUTHOR_DATE=");
3893
3894                 cmd.git_cmd = 1;
3895                 strvec_push(&cmd.args, "merge");
3896                 strvec_push(&cmd.args, "-s");
3897                 if (!strategy)
3898                         strvec_push(&cmd.args, "octopus");
3899                 else {
3900                         strvec_push(&cmd.args, strategy);
3901                         for (k = 0; k < opts->xopts_nr; k++)
3902                                 strvec_pushf(&cmd.args,
3903                                              "-X%s", opts->xopts[k]);
3904                 }
3905                 strvec_push(&cmd.args, "--no-edit");
3906                 strvec_push(&cmd.args, "--no-ff");
3907                 strvec_push(&cmd.args, "--no-log");
3908                 strvec_push(&cmd.args, "--no-stat");
3909                 strvec_push(&cmd.args, "-F");
3910                 strvec_push(&cmd.args, git_path_merge_msg(r));
3911                 if (opts->gpg_sign)
3912                         strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
3913                 else
3914                         strvec_push(&cmd.args, "--no-gpg-sign");
3915
3916                 /* Add the tips to be merged */
3917                 for (j = to_merge; j; j = j->next)
3918                         strvec_push(&cmd.args,
3919                                     oid_to_hex(&j->item->object.oid));
3920
3921                 strbuf_release(&ref_name);
3922                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3923                                 NULL, 0);
3924                 rollback_lock_file(&lock);
3925
3926                 ret = run_command(&cmd);
3927
3928                 /* force re-reading of the cache */
3929                 if (!ret && (discard_index(r->index) < 0 ||
3930                              repo_read_index(r) < 0))
3931                         ret = error(_("could not read index"));
3932                 goto leave_merge;
3933         }
3934
3935         merge_commit = to_merge->item;
3936         bases = get_merge_bases(head_commit, merge_commit);
3937         if (bases && oideq(&merge_commit->object.oid,
3938                            &bases->item->object.oid)) {
3939                 ret = 0;
3940                 /* skip merging an ancestor of HEAD */
3941                 goto leave_merge;
3942         }
3943
3944         write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3945                       git_path_merge_head(r), 0);
3946         write_message("no-ff", 5, git_path_merge_mode(r), 0);
3947
3948         for (j = bases; j; j = j->next)
3949                 commit_list_insert(j->item, &reversed);
3950         free_commit_list(bases);
3951
3952         repo_read_index(r);
3953         init_merge_options(&o, r);
3954         o.branch1 = "HEAD";
3955         o.branch2 = ref_name.buf;
3956         o.buffer_output = 2;
3957
3958         if (opts->strategy && !strcmp(opts->strategy, "ort")) {
3959                 /*
3960                  * TODO: Should use merge_incore_recursive() and
3961                  * merge_switch_to_result(), skipping the call to
3962                  * merge_switch_to_result() when we don't actually need to
3963                  * update the index and working copy immediately.
3964                  */
3965                 ret = merge_ort_recursive(&o,
3966                                           head_commit, merge_commit, reversed,
3967                                           &i);
3968         } else {
3969                 ret = merge_recursive(&o, head_commit, merge_commit, reversed,
3970                                       &i);
3971         }
3972         if (ret <= 0)
3973                 fputs(o.obuf.buf, stdout);
3974         strbuf_release(&o.obuf);
3975         if (ret < 0) {
3976                 error(_("could not even attempt to merge '%.*s'"),
3977                       merge_arg_len, arg);
3978                 goto leave_merge;
3979         }
3980         /*
3981          * The return value of merge_recursive() is 1 on clean, and 0 on
3982          * unclean merge.
3983          *
3984          * Let's reverse that, so that do_merge() returns 0 upon success and
3985          * 1 upon failed merge (keeping the return value -1 for the cases where
3986          * we will want to reschedule the `merge` command).
3987          */
3988         ret = !ret;
3989
3990         if (r->index->cache_changed &&
3991             write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3992                 ret = error(_("merge: Unable to write new index file"));
3993                 goto leave_merge;
3994         }
3995
3996         rollback_lock_file(&lock);
3997         if (ret)
3998                 repo_rerere(r, opts->allow_rerere_auto);
3999         else
4000                 /*
4001                  * In case of problems, we now want to return a positive
4002                  * value (a negative one would indicate that the `merge`
4003                  * command needs to be rescheduled).
4004                  */
4005         fast_forward_edit:
4006                 ret = !!run_git_commit(git_path_merge_msg(r), opts,
4007                                        run_commit_flags);
4008
4009 leave_merge:
4010         strbuf_release(&ref_name);
4011         rollback_lock_file(&lock);
4012         free_commit_list(to_merge);
4013         return ret;
4014 }
4015
4016 static int is_final_fixup(struct todo_list *todo_list)
4017 {
4018         int i = todo_list->current;
4019
4020         if (!is_fixup(todo_list->items[i].command))
4021                 return 0;
4022
4023         while (++i < todo_list->nr)
4024                 if (is_fixup(todo_list->items[i].command))
4025                         return 0;
4026                 else if (!is_noop(todo_list->items[i].command))
4027                         break;
4028         return 1;
4029 }
4030
4031 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4032 {
4033         int i;
4034
4035         for (i = todo_list->current + offset; i < todo_list->nr; i++)
4036                 if (!is_noop(todo_list->items[i].command))
4037                         return todo_list->items[i].command;
4038
4039         return -1;
4040 }
4041
4042 void create_autostash(struct repository *r, const char *path,
4043                       const char *default_reflog_action)
4044 {
4045         struct strbuf buf = STRBUF_INIT;
4046         struct lock_file lock_file = LOCK_INIT;
4047         int fd;
4048
4049         fd = repo_hold_locked_index(r, &lock_file, 0);
4050         refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4051         if (0 <= fd)
4052                 repo_update_index_if_able(r, &lock_file);
4053         rollback_lock_file(&lock_file);
4054
4055         if (has_unstaged_changes(r, 1) ||
4056             has_uncommitted_changes(r, 1)) {
4057                 struct child_process stash = CHILD_PROCESS_INIT;
4058                 struct object_id oid;
4059
4060                 strvec_pushl(&stash.args,
4061                              "stash", "create", "autostash", NULL);
4062                 stash.git_cmd = 1;
4063                 stash.no_stdin = 1;
4064                 strbuf_reset(&buf);
4065                 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4066                         die(_("Cannot autostash"));
4067                 strbuf_trim_trailing_newline(&buf);
4068                 if (get_oid(buf.buf, &oid))
4069                         die(_("Unexpected stash response: '%s'"),
4070                             buf.buf);
4071                 strbuf_reset(&buf);
4072                 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4073
4074                 if (safe_create_leading_directories_const(path))
4075                         die(_("Could not create directory for '%s'"),
4076                             path);
4077                 write_file(path, "%s", oid_to_hex(&oid));
4078                 printf(_("Created autostash: %s\n"), buf.buf);
4079                 if (reset_head(r, NULL, "reset --hard",
4080                                NULL, RESET_HEAD_HARD, NULL, NULL,
4081                                default_reflog_action) < 0)
4082                         die(_("could not reset --hard"));
4083
4084                 if (discard_index(r->index) < 0 ||
4085                         repo_read_index(r) < 0)
4086                         die(_("could not read index"));
4087         }
4088         strbuf_release(&buf);
4089 }
4090
4091 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
4092 {
4093         struct child_process child = CHILD_PROCESS_INIT;
4094         int ret = 0;
4095
4096         if (attempt_apply) {
4097                 child.git_cmd = 1;
4098                 child.no_stdout = 1;
4099                 child.no_stderr = 1;
4100                 strvec_push(&child.args, "stash");
4101                 strvec_push(&child.args, "apply");
4102                 strvec_push(&child.args, stash_oid);
4103                 ret = run_command(&child);
4104         }
4105
4106         if (attempt_apply && !ret)
4107                 fprintf(stderr, _("Applied autostash.\n"));
4108         else {
4109                 struct child_process store = CHILD_PROCESS_INIT;
4110
4111                 store.git_cmd = 1;
4112                 strvec_push(&store.args, "stash");
4113                 strvec_push(&store.args, "store");
4114                 strvec_push(&store.args, "-m");
4115                 strvec_push(&store.args, "autostash");
4116                 strvec_push(&store.args, "-q");
4117                 strvec_push(&store.args, stash_oid);
4118                 if (run_command(&store))
4119                         ret = error(_("cannot store %s"), stash_oid);
4120                 else
4121                         fprintf(stderr,
4122                                 _("%s\n"
4123                                   "Your changes are safe in the stash.\n"
4124                                   "You can run \"git stash pop\" or"
4125                                   " \"git stash drop\" at any time.\n"),
4126                                 attempt_apply ?
4127                                 _("Applying autostash resulted in conflicts.") :
4128                                 _("Autostash exists; creating a new stash entry."));
4129         }
4130
4131         return ret;
4132 }
4133
4134 static int apply_save_autostash(const char *path, int attempt_apply)
4135 {
4136         struct strbuf stash_oid = STRBUF_INIT;
4137         int ret = 0;
4138
4139         if (!read_oneliner(&stash_oid, path,
4140                            READ_ONELINER_SKIP_IF_EMPTY)) {
4141                 strbuf_release(&stash_oid);
4142                 return 0;
4143         }
4144         strbuf_trim(&stash_oid);
4145
4146         ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
4147
4148         unlink(path);
4149         strbuf_release(&stash_oid);
4150         return ret;
4151 }
4152
4153 int save_autostash(const char *path)
4154 {
4155         return apply_save_autostash(path, 0);
4156 }
4157
4158 int apply_autostash(const char *path)
4159 {
4160         return apply_save_autostash(path, 1);
4161 }
4162
4163 int apply_autostash_oid(const char *stash_oid)
4164 {
4165         return apply_save_autostash_oid(stash_oid, 1);
4166 }
4167
4168 static const char *reflog_message(struct replay_opts *opts,
4169         const char *sub_action, const char *fmt, ...)
4170 {
4171         va_list ap;
4172         static struct strbuf buf = STRBUF_INIT;
4173         char *reflog_action = getenv(GIT_REFLOG_ACTION);
4174
4175         va_start(ap, fmt);
4176         strbuf_reset(&buf);
4177         strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
4178         if (sub_action)
4179                 strbuf_addf(&buf, " (%s)", sub_action);
4180         if (fmt) {
4181                 strbuf_addstr(&buf, ": ");
4182                 strbuf_vaddf(&buf, fmt, ap);
4183         }
4184         va_end(ap);
4185
4186         return buf.buf;
4187 }
4188
4189 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
4190                             const char *commit, const char *action)
4191 {
4192         struct child_process cmd = CHILD_PROCESS_INIT;
4193         int ret;
4194
4195         cmd.git_cmd = 1;
4196
4197         strvec_push(&cmd.args, "checkout");
4198         strvec_push(&cmd.args, commit);
4199         strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
4200
4201         if (opts->verbose)
4202                 ret = run_command(&cmd);
4203         else
4204                 ret = run_command_silent_on_success(&cmd);
4205
4206         if (!ret)
4207                 discard_index(r->index);
4208
4209         return ret;
4210 }
4211
4212 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4213                          const char *onto_name, const struct object_id *onto,
4214                          const struct object_id *orig_head)
4215 {
4216         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
4217
4218         if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
4219                 apply_autostash(rebase_path_autostash());
4220                 sequencer_remove_state(opts);
4221                 return error(_("could not detach HEAD"));
4222         }
4223
4224         return update_ref(NULL, "ORIG_HEAD", orig_head, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4225 }
4226
4227 static int stopped_at_head(struct repository *r)
4228 {
4229         struct object_id head;
4230         struct commit *commit;
4231         struct commit_message message;
4232
4233         if (get_oid("HEAD", &head) ||
4234             !(commit = lookup_commit(r, &head)) ||
4235             parse_commit(commit) || get_message(commit, &message))
4236                 fprintf(stderr, _("Stopped at HEAD\n"));
4237         else {
4238                 fprintf(stderr, _("Stopped at %s\n"), message.label);
4239                 free_message(commit, &message);
4240         }
4241         return 0;
4242
4243 }
4244
4245 static const char rescheduled_advice[] =
4246 N_("Could not execute the todo command\n"
4247 "\n"
4248 "    %.*s"
4249 "\n"
4250 "It has been rescheduled; To edit the command before continuing, please\n"
4251 "edit the todo list first:\n"
4252 "\n"
4253 "    git rebase --edit-todo\n"
4254 "    git rebase --continue\n");
4255
4256 static int pick_commits(struct repository *r,
4257                         struct todo_list *todo_list,
4258                         struct replay_opts *opts)
4259 {
4260         int res = 0, reschedule = 0;
4261         char *prev_reflog_action;
4262
4263         /* Note that 0 for 3rd parameter of setenv means set only if not set */
4264         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4265         prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
4266         if (opts->allow_ff)
4267                 assert(!(opts->signoff || opts->no_commit ||
4268                          opts->record_origin || opts->edit ||
4269                          opts->committer_date_is_author_date ||
4270                          opts->ignore_date));
4271         if (read_and_refresh_cache(r, opts))
4272                 return -1;
4273
4274         while (todo_list->current < todo_list->nr) {
4275                 struct todo_item *item = todo_list->items + todo_list->current;
4276                 const char *arg = todo_item_get_arg(todo_list, item);
4277                 int check_todo = 0;
4278
4279                 if (save_todo(todo_list, opts))
4280                         return -1;
4281                 if (is_rebase_i(opts)) {
4282                         if (item->command != TODO_COMMENT) {
4283                                 FILE *f = fopen(rebase_path_msgnum(), "w");
4284
4285                                 todo_list->done_nr++;
4286
4287                                 if (f) {
4288                                         fprintf(f, "%d\n", todo_list->done_nr);
4289                                         fclose(f);
4290                                 }
4291                                 if (!opts->quiet)
4292                                         fprintf(stderr, _("Rebasing (%d/%d)%s"),
4293                                                 todo_list->done_nr,
4294                                                 todo_list->total_nr,
4295                                                 opts->verbose ? "\n" : "\r");
4296                         }
4297                         unlink(rebase_path_message());
4298                         unlink(rebase_path_author_script());
4299                         unlink(rebase_path_stopped_sha());
4300                         unlink(rebase_path_amend());
4301                         unlink(git_path_merge_head(r));
4302                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
4303
4304                         if (item->command == TODO_BREAK) {
4305                                 if (!opts->verbose)
4306                                         term_clear_line();
4307                                 return stopped_at_head(r);
4308                         }
4309                 }
4310                 if (item->command <= TODO_SQUASH) {
4311                         if (is_rebase_i(opts))
4312                                 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
4313                                         command_to_string(item->command), NULL),
4314                                         1);
4315                         res = do_pick_commit(r, item, opts,
4316                                              is_final_fixup(todo_list),
4317                                              &check_todo);
4318                         if (is_rebase_i(opts))
4319                                 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
4320                         if (is_rebase_i(opts) && res < 0) {
4321                                 /* Reschedule */
4322                                 advise(_(rescheduled_advice),
4323                                        get_item_line_length(todo_list,
4324                                                             todo_list->current),
4325                                        get_item_line(todo_list,
4326                                                      todo_list->current));
4327                                 todo_list->current--;
4328                                 if (save_todo(todo_list, opts))
4329                                         return -1;
4330                         }
4331                         if (item->command == TODO_EDIT) {
4332                                 struct commit *commit = item->commit;
4333                                 if (!res) {
4334                                         if (!opts->verbose)
4335                                                 term_clear_line();
4336                                         fprintf(stderr,
4337                                                 _("Stopped at %s...  %.*s\n"),
4338                                                 short_commit_name(commit),
4339                                                 item->arg_len, arg);
4340                                 }
4341                                 return error_with_patch(r, commit,
4342                                         arg, item->arg_len, opts, res, !res);
4343                         }
4344                         if (is_rebase_i(opts) && !res)
4345                                 record_in_rewritten(&item->commit->object.oid,
4346                                         peek_command(todo_list, 1));
4347                         if (res && is_fixup(item->command)) {
4348                                 if (res == 1)
4349                                         intend_to_amend();
4350                                 return error_failed_squash(r, item->commit, opts,
4351                                         item->arg_len, arg);
4352                         } else if (res && is_rebase_i(opts) && item->commit) {
4353                                 int to_amend = 0;
4354                                 struct object_id oid;
4355
4356                                 /*
4357                                  * If we are rewording and have either
4358                                  * fast-forwarded already, or are about to
4359                                  * create a new root commit, we want to amend,
4360                                  * otherwise we do not.
4361                                  */
4362                                 if (item->command == TODO_REWORD &&
4363                                     !get_oid("HEAD", &oid) &&
4364                                     (oideq(&item->commit->object.oid, &oid) ||
4365                                      (opts->have_squash_onto &&
4366                                       oideq(&opts->squash_onto, &oid))))
4367                                         to_amend = 1;
4368
4369                                 return res | error_with_patch(r, item->commit,
4370                                                 arg, item->arg_len, opts,
4371                                                 res, to_amend);
4372                         }
4373                 } else if (item->command == TODO_EXEC) {
4374                         char *end_of_arg = (char *)(arg + item->arg_len);
4375                         int saved = *end_of_arg;
4376
4377                         if (!opts->verbose)
4378                                 term_clear_line();
4379                         *end_of_arg = '\0';
4380                         res = do_exec(r, arg);
4381                         *end_of_arg = saved;
4382
4383                         if (res) {
4384                                 if (opts->reschedule_failed_exec)
4385                                         reschedule = 1;
4386                         }
4387                         check_todo = 1;
4388                 } else if (item->command == TODO_LABEL) {
4389                         if ((res = do_label(r, arg, item->arg_len)))
4390                                 reschedule = 1;
4391                 } else if (item->command == TODO_RESET) {
4392                         if ((res = do_reset(r, arg, item->arg_len, opts)))
4393                                 reschedule = 1;
4394                 } else if (item->command == TODO_MERGE) {
4395                         if ((res = do_merge(r, item->commit,
4396                                             arg, item->arg_len,
4397                                             item->flags, opts)) < 0)
4398                                 reschedule = 1;
4399                         else if (item->commit)
4400                                 record_in_rewritten(&item->commit->object.oid,
4401                                                     peek_command(todo_list, 1));
4402                         if (res > 0)
4403                                 /* failed with merge conflicts */
4404                                 return error_with_patch(r, item->commit,
4405                                                         arg, item->arg_len,
4406                                                         opts, res, 0);
4407                 } else if (!is_noop(item->command))
4408                         return error(_("unknown command %d"), item->command);
4409
4410                 if (reschedule) {
4411                         advise(_(rescheduled_advice),
4412                                get_item_line_length(todo_list,
4413                                                     todo_list->current),
4414                                get_item_line(todo_list, todo_list->current));
4415                         todo_list->current--;
4416                         if (save_todo(todo_list, opts))
4417                                 return -1;
4418                         if (item->commit)
4419                                 return error_with_patch(r,
4420                                                         item->commit,
4421                                                         arg, item->arg_len,
4422                                                         opts, res, 0);
4423                 } else if (is_rebase_i(opts) && check_todo && !res) {
4424                         struct stat st;
4425
4426                         if (stat(get_todo_path(opts), &st)) {
4427                                 res = error_errno(_("could not stat '%s'"),
4428                                                   get_todo_path(opts));
4429                         } else if (match_stat_data(&todo_list->stat, &st)) {
4430                                 /* Reread the todo file if it has changed. */
4431                                 todo_list_release(todo_list);
4432                                 if (read_populate_todo(r, todo_list, opts))
4433                                         res = -1; /* message was printed */
4434                                 /* `current` will be incremented below */
4435                                 todo_list->current = -1;
4436                         }
4437                 }
4438
4439                 todo_list->current++;
4440                 if (res)
4441                         return res;
4442         }
4443
4444         if (is_rebase_i(opts)) {
4445                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4446                 struct stat st;
4447
4448                 /* Stopped in the middle, as planned? */
4449                 if (todo_list->current < todo_list->nr)
4450                         return 0;
4451
4452                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4453                                 starts_with(head_ref.buf, "refs/")) {
4454                         const char *msg;
4455                         struct object_id head, orig;
4456                         int res;
4457
4458                         if (get_oid("HEAD", &head)) {
4459                                 res = error(_("cannot read HEAD"));
4460 cleanup_head_ref:
4461                                 strbuf_release(&head_ref);
4462                                 strbuf_release(&buf);
4463                                 return res;
4464                         }
4465                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4466                                         get_oid_hex(buf.buf, &orig)) {
4467                                 res = error(_("could not read orig-head"));
4468                                 goto cleanup_head_ref;
4469                         }
4470                         strbuf_reset(&buf);
4471                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4472                                 res = error(_("could not read 'onto'"));
4473                                 goto cleanup_head_ref;
4474                         }
4475                         msg = reflog_message(opts, "finish", "%s onto %s",
4476                                 head_ref.buf, buf.buf);
4477                         if (update_ref(msg, head_ref.buf, &head, &orig,
4478                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4479                                 res = error(_("could not update %s"),
4480                                         head_ref.buf);
4481                                 goto cleanup_head_ref;
4482                         }
4483                         msg = reflog_message(opts, "finish", "returning to %s",
4484                                 head_ref.buf);
4485                         if (create_symref("HEAD", head_ref.buf, msg)) {
4486                                 res = error(_("could not update HEAD to %s"),
4487                                         head_ref.buf);
4488                                 goto cleanup_head_ref;
4489                         }
4490                         strbuf_reset(&buf);
4491                 }
4492
4493                 if (opts->verbose) {
4494                         struct rev_info log_tree_opt;
4495                         struct object_id orig, head;
4496
4497                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4498                         repo_init_revisions(r, &log_tree_opt, NULL);
4499                         log_tree_opt.diff = 1;
4500                         log_tree_opt.diffopt.output_format =
4501                                 DIFF_FORMAT_DIFFSTAT;
4502                         log_tree_opt.disable_stdin = 1;
4503
4504                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4505                             !get_oid(buf.buf, &orig) &&
4506                             !get_oid("HEAD", &head)) {
4507                                 diff_tree_oid(&orig, &head, "",
4508                                               &log_tree_opt.diffopt);
4509                                 log_tree_diff_flush(&log_tree_opt);
4510                         }
4511                 }
4512                 flush_rewritten_pending();
4513                 if (!stat(rebase_path_rewritten_list(), &st) &&
4514                                 st.st_size > 0) {
4515                         struct child_process child = CHILD_PROCESS_INIT;
4516                         const char *post_rewrite_hook =
4517                                 find_hook("post-rewrite");
4518
4519                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4520                         child.git_cmd = 1;
4521                         strvec_push(&child.args, "notes");
4522                         strvec_push(&child.args, "copy");
4523                         strvec_push(&child.args, "--for-rewrite=rebase");
4524                         /* we don't care if this copying failed */
4525                         run_command(&child);
4526
4527                         if (post_rewrite_hook) {
4528                                 struct child_process hook = CHILD_PROCESS_INIT;
4529
4530                                 hook.in = open(rebase_path_rewritten_list(),
4531                                         O_RDONLY);
4532                                 hook.stdout_to_stderr = 1;
4533                                 hook.trace2_hook_name = "post-rewrite";
4534                                 strvec_push(&hook.args, post_rewrite_hook);
4535                                 strvec_push(&hook.args, "rebase");
4536                                 /* we don't care if this hook failed */
4537                                 run_command(&hook);
4538                         }
4539                 }
4540                 apply_autostash(rebase_path_autostash());
4541
4542                 if (!opts->quiet) {
4543                         if (!opts->verbose)
4544                                 term_clear_line();
4545                         fprintf(stderr,
4546                                 _("Successfully rebased and updated %s.\n"),
4547                                 head_ref.buf);
4548                 }
4549
4550                 strbuf_release(&buf);
4551                 strbuf_release(&head_ref);
4552         }
4553
4554         /*
4555          * Sequence of picks finished successfully; cleanup by
4556          * removing the .git/sequencer directory
4557          */
4558         return sequencer_remove_state(opts);
4559 }
4560
4561 static int continue_single_pick(struct repository *r)
4562 {
4563         const char *argv[] = { "commit", NULL };
4564
4565         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4566             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4567                 return error(_("no cherry-pick or revert in progress"));
4568         return run_command_v_opt(argv, RUN_GIT_CMD);
4569 }
4570
4571 static int commit_staged_changes(struct repository *r,
4572                                  struct replay_opts *opts,
4573                                  struct todo_list *todo_list)
4574 {
4575         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4576         unsigned int final_fixup = 0, is_clean;
4577
4578         if (has_unstaged_changes(r, 1))
4579                 return error(_("cannot rebase: You have unstaged changes."));
4580
4581         is_clean = !has_uncommitted_changes(r, 0);
4582
4583         if (file_exists(rebase_path_amend())) {
4584                 struct strbuf rev = STRBUF_INIT;
4585                 struct object_id head, to_amend;
4586
4587                 if (get_oid("HEAD", &head))
4588                         return error(_("cannot amend non-existing commit"));
4589                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4590                         return error(_("invalid file: '%s'"), rebase_path_amend());
4591                 if (get_oid_hex(rev.buf, &to_amend))
4592                         return error(_("invalid contents: '%s'"),
4593                                 rebase_path_amend());
4594                 if (!is_clean && !oideq(&head, &to_amend))
4595                         return error(_("\nYou have uncommitted changes in your "
4596                                        "working tree. Please, commit them\n"
4597                                        "first and then run 'git rebase "
4598                                        "--continue' again."));
4599                 /*
4600                  * When skipping a failed fixup/squash, we need to edit the
4601                  * commit message, the current fixup list and count, and if it
4602                  * was the last fixup/squash in the chain, we need to clean up
4603                  * the commit message and if there was a squash, let the user
4604                  * edit it.
4605                  */
4606                 if (!is_clean || !opts->current_fixup_count)
4607                         ; /* this is not the final fixup */
4608                 else if (!oideq(&head, &to_amend) ||
4609                          !file_exists(rebase_path_stopped_sha())) {
4610                         /* was a final fixup or squash done manually? */
4611                         if (!is_fixup(peek_command(todo_list, 0))) {
4612                                 unlink(rebase_path_fixup_msg());
4613                                 unlink(rebase_path_squash_msg());
4614                                 unlink(rebase_path_current_fixups());
4615                                 strbuf_reset(&opts->current_fixups);
4616                                 opts->current_fixup_count = 0;
4617                         }
4618                 } else {
4619                         /* we are in a fixup/squash chain */
4620                         const char *p = opts->current_fixups.buf;
4621                         int len = opts->current_fixups.len;
4622
4623                         opts->current_fixup_count--;
4624                         if (!len)
4625                                 BUG("Incorrect current_fixups:\n%s", p);
4626                         while (len && p[len - 1] != '\n')
4627                                 len--;
4628                         strbuf_setlen(&opts->current_fixups, len);
4629                         if (write_message(p, len, rebase_path_current_fixups(),
4630                                           0) < 0)
4631                                 return error(_("could not write file: '%s'"),
4632                                              rebase_path_current_fixups());
4633
4634                         /*
4635                          * If a fixup/squash in a fixup/squash chain failed, the
4636                          * commit message is already correct, no need to commit
4637                          * it again.
4638                          *
4639                          * Only if it is the final command in the fixup/squash
4640                          * chain, and only if the chain is longer than a single
4641                          * fixup/squash command (which was just skipped), do we
4642                          * actually need to re-commit with a cleaned up commit
4643                          * message.
4644                          */
4645                         if (opts->current_fixup_count > 0 &&
4646                             !is_fixup(peek_command(todo_list, 0))) {
4647                                 final_fixup = 1;
4648                                 /*
4649                                  * If there was not a single "squash" in the
4650                                  * chain, we only need to clean up the commit
4651                                  * message, no need to bother the user with
4652                                  * opening the commit message in the editor.
4653                                  */
4654                                 if (!starts_with(p, "squash ") &&
4655                                     !strstr(p, "\nsquash "))
4656                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4657                         } else if (is_fixup(peek_command(todo_list, 0))) {
4658                                 /*
4659                                  * We need to update the squash message to skip
4660                                  * the latest commit message.
4661                                  */
4662                                 struct commit *commit;
4663                                 const char *path = rebase_path_squash_msg();
4664                                 const char *encoding = get_commit_output_encoding();
4665
4666                                 if (parse_head(r, &commit) ||
4667                                     !(p = logmsg_reencode(commit, NULL, encoding)) ||
4668                                     write_message(p, strlen(p), path, 0)) {
4669                                         unuse_commit_buffer(commit, p);
4670                                         return error(_("could not write file: "
4671                                                        "'%s'"), path);
4672                                 }
4673                                 unuse_commit_buffer(commit, p);
4674                         }
4675                 }
4676
4677                 strbuf_release(&rev);
4678                 flags |= AMEND_MSG;
4679         }
4680
4681         if (is_clean) {
4682                 if (refs_ref_exists(get_main_ref_store(r),
4683                                     "CHERRY_PICK_HEAD") &&
4684                     refs_delete_ref(get_main_ref_store(r), "",
4685                                     "CHERRY_PICK_HEAD", NULL, 0))
4686                         return error(_("could not remove CHERRY_PICK_HEAD"));
4687                 if (!final_fixup)
4688                         return 0;
4689         }
4690
4691         if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
4692                            opts, flags))
4693                 return error(_("could not commit staged changes."));
4694         unlink(rebase_path_amend());
4695         unlink(git_path_merge_head(r));
4696         if (final_fixup) {
4697                 unlink(rebase_path_fixup_msg());
4698                 unlink(rebase_path_squash_msg());
4699         }
4700         if (opts->current_fixup_count > 0) {
4701                 /*
4702                  * Whether final fixup or not, we just cleaned up the commit
4703                  * message...
4704                  */
4705                 unlink(rebase_path_current_fixups());
4706                 strbuf_reset(&opts->current_fixups);
4707                 opts->current_fixup_count = 0;
4708         }
4709         return 0;
4710 }
4711
4712 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4713 {
4714         struct todo_list todo_list = TODO_LIST_INIT;
4715         int res;
4716
4717         if (read_and_refresh_cache(r, opts))
4718                 return -1;
4719
4720         if (read_populate_opts(opts))
4721                 return -1;
4722         if (is_rebase_i(opts)) {
4723                 if ((res = read_populate_todo(r, &todo_list, opts)))
4724                         goto release_todo_list;
4725
4726                 if (file_exists(rebase_path_dropped())) {
4727                         if ((res = todo_list_check_against_backup(r, &todo_list)))
4728                                 goto release_todo_list;
4729
4730                         unlink(rebase_path_dropped());
4731                 }
4732
4733                 if (commit_staged_changes(r, opts, &todo_list)) {
4734                         res = -1;
4735                         goto release_todo_list;
4736                 }
4737         } else if (!file_exists(get_todo_path(opts)))
4738                 return continue_single_pick(r);
4739         else if ((res = read_populate_todo(r, &todo_list, opts)))
4740                 goto release_todo_list;
4741
4742         if (!is_rebase_i(opts)) {
4743                 /* Verify that the conflict has been resolved */
4744                 if (refs_ref_exists(get_main_ref_store(r),
4745                                     "CHERRY_PICK_HEAD") ||
4746                     refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4747                         res = continue_single_pick(r);
4748                         if (res)
4749                                 goto release_todo_list;
4750                 }
4751                 if (index_differs_from(r, "HEAD", NULL, 0)) {
4752                         res = error_dirty_index(r, opts);
4753                         goto release_todo_list;
4754                 }
4755                 todo_list.current++;
4756         } else if (file_exists(rebase_path_stopped_sha())) {
4757                 struct strbuf buf = STRBUF_INIT;
4758                 struct object_id oid;
4759
4760                 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4761                                   READ_ONELINER_SKIP_IF_EMPTY) &&
4762                     !get_oid_hex(buf.buf, &oid))
4763                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
4764                 strbuf_release(&buf);
4765         }
4766
4767         res = pick_commits(r, &todo_list, opts);
4768 release_todo_list:
4769         todo_list_release(&todo_list);
4770         return res;
4771 }
4772
4773 static int single_pick(struct repository *r,
4774                        struct commit *cmit,
4775                        struct replay_opts *opts)
4776 {
4777         int check_todo;
4778         struct todo_item item;
4779
4780         item.command = opts->action == REPLAY_PICK ?
4781                         TODO_PICK : TODO_REVERT;
4782         item.commit = cmit;
4783
4784         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4785         return do_pick_commit(r, &item, opts, 0, &check_todo);
4786 }
4787
4788 int sequencer_pick_revisions(struct repository *r,
4789                              struct replay_opts *opts)
4790 {
4791         struct todo_list todo_list = TODO_LIST_INIT;
4792         struct object_id oid;
4793         int i, res;
4794
4795         assert(opts->revs);
4796         if (read_and_refresh_cache(r, opts))
4797                 return -1;
4798
4799         for (i = 0; i < opts->revs->pending.nr; i++) {
4800                 struct object_id oid;
4801                 const char *name = opts->revs->pending.objects[i].name;
4802
4803                 /* This happens when using --stdin. */
4804                 if (!strlen(name))
4805                         continue;
4806
4807                 if (!get_oid(name, &oid)) {
4808                         if (!lookup_commit_reference_gently(r, &oid, 1)) {
4809                                 enum object_type type = oid_object_info(r,
4810                                                                         &oid,
4811                                                                         NULL);
4812                                 return error(_("%s: can't cherry-pick a %s"),
4813                                         name, type_name(type));
4814                         }
4815                 } else
4816                         return error(_("%s: bad revision"), name);
4817         }
4818
4819         /*
4820          * If we were called as "git cherry-pick <commit>", just
4821          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4822          * REVERT_HEAD, and don't touch the sequencer state.
4823          * This means it is possible to cherry-pick in the middle
4824          * of a cherry-pick sequence.
4825          */
4826         if (opts->revs->cmdline.nr == 1 &&
4827             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4828             opts->revs->no_walk &&
4829             !opts->revs->cmdline.rev->flags) {
4830                 struct commit *cmit;
4831                 if (prepare_revision_walk(opts->revs))
4832                         return error(_("revision walk setup failed"));
4833                 cmit = get_revision(opts->revs);
4834                 if (!cmit)
4835                         return error(_("empty commit set passed"));
4836                 if (get_revision(opts->revs))
4837                         BUG("unexpected extra commit from walk");
4838                 return single_pick(r, cmit, opts);
4839         }
4840
4841         /*
4842          * Start a new cherry-pick/ revert sequence; but
4843          * first, make sure that an existing one isn't in
4844          * progress
4845          */
4846
4847         if (walk_revs_populate_todo(&todo_list, opts) ||
4848                         create_seq_dir(r) < 0)
4849                 return -1;
4850         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4851                 return error(_("can't revert as initial commit"));
4852         if (save_head(oid_to_hex(&oid)))
4853                 return -1;
4854         if (save_opts(opts))
4855                 return -1;
4856         update_abort_safety_file();
4857         res = pick_commits(r, &todo_list, opts);
4858         todo_list_release(&todo_list);
4859         return res;
4860 }
4861
4862 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4863 {
4864         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4865         struct strbuf sob = STRBUF_INIT;
4866         int has_footer;
4867
4868         strbuf_addstr(&sob, sign_off_header);
4869         strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4870         strbuf_addch(&sob, '\n');
4871
4872         if (!ignore_footer)
4873                 strbuf_complete_line(msgbuf);
4874
4875         /*
4876          * If the whole message buffer is equal to the sob, pretend that we
4877          * found a conforming footer with a matching sob
4878          */
4879         if (msgbuf->len - ignore_footer == sob.len &&
4880             !strncmp(msgbuf->buf, sob.buf, sob.len))
4881                 has_footer = 3;
4882         else
4883                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4884
4885         if (!has_footer) {
4886                 const char *append_newlines = NULL;
4887                 size_t len = msgbuf->len - ignore_footer;
4888
4889                 if (!len) {
4890                         /*
4891                          * The buffer is completely empty.  Leave foom for
4892                          * the title and body to be filled in by the user.
4893                          */
4894                         append_newlines = "\n\n";
4895                 } else if (len == 1) {
4896                         /*
4897                          * Buffer contains a single newline.  Add another
4898                          * so that we leave room for the title and body.
4899                          */
4900                         append_newlines = "\n";
4901                 } else if (msgbuf->buf[len - 2] != '\n') {
4902                         /*
4903                          * Buffer ends with a single newline.  Add another
4904                          * so that there is an empty line between the message
4905                          * body and the sob.
4906                          */
4907                         append_newlines = "\n";
4908                 } /* else, the buffer already ends with two newlines. */
4909
4910                 if (append_newlines)
4911                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4912                                 append_newlines, strlen(append_newlines));
4913         }
4914
4915         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4916                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4917                                 sob.buf, sob.len);
4918
4919         strbuf_release(&sob);
4920 }
4921
4922 struct labels_entry {
4923         struct hashmap_entry entry;
4924         char label[FLEX_ARRAY];
4925 };
4926
4927 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4928                       const struct hashmap_entry *entry_or_key, const void *key)
4929 {
4930         const struct labels_entry *a, *b;
4931
4932         a = container_of(eptr, const struct labels_entry, entry);
4933         b = container_of(entry_or_key, const struct labels_entry, entry);
4934
4935         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4936 }
4937
4938 struct string_entry {
4939         struct oidmap_entry entry;
4940         char string[FLEX_ARRAY];
4941 };
4942
4943 struct label_state {
4944         struct oidmap commit2label;
4945         struct hashmap labels;
4946         struct strbuf buf;
4947 };
4948
4949 static const char *label_oid(struct object_id *oid, const char *label,
4950                              struct label_state *state)
4951 {
4952         struct labels_entry *labels_entry;
4953         struct string_entry *string_entry;
4954         struct object_id dummy;
4955         int i;
4956
4957         string_entry = oidmap_get(&state->commit2label, oid);
4958         if (string_entry)
4959                 return string_entry->string;
4960
4961         /*
4962          * For "uninteresting" commits, i.e. commits that are not to be
4963          * rebased, and which can therefore not be labeled, we use a unique
4964          * abbreviation of the commit name. This is slightly more complicated
4965          * than calling find_unique_abbrev() because we also need to make
4966          * sure that the abbreviation does not conflict with any other
4967          * label.
4968          *
4969          * We disallow "interesting" commits to be labeled by a string that
4970          * is a valid full-length hash, to ensure that we always can find an
4971          * abbreviation for any uninteresting commit's names that does not
4972          * clash with any other label.
4973          */
4974         strbuf_reset(&state->buf);
4975         if (!label) {
4976                 char *p;
4977
4978                 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4979                 label = p = state->buf.buf;
4980
4981                 find_unique_abbrev_r(p, oid, default_abbrev);
4982
4983                 /*
4984                  * We may need to extend the abbreviated hash so that there is
4985                  * no conflicting label.
4986                  */
4987                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4988                         size_t i = strlen(p) + 1;
4989
4990                         oid_to_hex_r(p, oid);
4991                         for (; i < the_hash_algo->hexsz; i++) {
4992                                 char save = p[i];
4993                                 p[i] = '\0';
4994                                 if (!hashmap_get_from_hash(&state->labels,
4995                                                            strihash(p), p))
4996                                         break;
4997                                 p[i] = save;
4998                         }
4999                 }
5000         } else {
5001                 struct strbuf *buf = &state->buf;
5002
5003                 /*
5004                  * Sanitize labels by replacing non-alpha-numeric characters
5005                  * (including white-space ones) by dashes, as they might be
5006                  * illegal in file names (and hence in ref names).
5007                  *
5008                  * Note that we retain non-ASCII UTF-8 characters (identified
5009                  * via the most significant bit). They should be all acceptable
5010                  * in file names. We do not validate the UTF-8 here, that's not
5011                  * the job of this function.
5012                  */
5013                 for (; *label; label++)
5014                         if ((*label & 0x80) || isalnum(*label))
5015                                 strbuf_addch(buf, *label);
5016                         /* avoid leading dash and double-dashes */
5017                         else if (buf->len && buf->buf[buf->len - 1] != '-')
5018                                 strbuf_addch(buf, '-');
5019                 if (!buf->len) {
5020                         strbuf_addstr(buf, "rev-");
5021                         strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5022                 }
5023                 label = buf->buf;
5024
5025                 if ((buf->len == the_hash_algo->hexsz &&
5026                      !get_oid_hex(label, &dummy)) ||
5027                     (buf->len == 1 && *label == '#') ||
5028                     hashmap_get_from_hash(&state->labels,
5029                                           strihash(label), label)) {
5030                         /*
5031                          * If the label already exists, or if the label is a
5032                          * valid full OID, or the label is a '#' (which we use
5033                          * as a separator between merge heads and oneline), we
5034                          * append a dash and a number to make it unique.
5035                          */
5036                         size_t len = buf->len;
5037
5038                         for (i = 2; ; i++) {
5039                                 strbuf_setlen(buf, len);
5040                                 strbuf_addf(buf, "-%d", i);
5041                                 if (!hashmap_get_from_hash(&state->labels,
5042                                                            strihash(buf->buf),
5043                                                            buf->buf))
5044                                         break;
5045                         }
5046
5047                         label = buf->buf;
5048                 }
5049         }
5050
5051         FLEX_ALLOC_STR(labels_entry, label, label);
5052         hashmap_entry_init(&labels_entry->entry, strihash(label));
5053         hashmap_add(&state->labels, &labels_entry->entry);
5054
5055         FLEX_ALLOC_STR(string_entry, string, label);
5056         oidcpy(&string_entry->entry.oid, oid);
5057         oidmap_put(&state->commit2label, string_entry);
5058
5059         return string_entry->string;
5060 }
5061
5062 static int make_script_with_merges(struct pretty_print_context *pp,
5063                                    struct rev_info *revs, struct strbuf *out,
5064                                    unsigned flags)
5065 {
5066         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5067         int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5068         int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5069         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5070         struct strbuf label = STRBUF_INIT;
5071         struct commit_list *commits = NULL, **tail = &commits, *iter;
5072         struct commit_list *tips = NULL, **tips_tail = &tips;
5073         struct commit *commit;
5074         struct oidmap commit2todo = OIDMAP_INIT;
5075         struct string_entry *entry;
5076         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5077                 shown = OIDSET_INIT;
5078         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5079
5080         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5081         const char *cmd_pick = abbr ? "p" : "pick",
5082                 *cmd_label = abbr ? "l" : "label",
5083                 *cmd_reset = abbr ? "t" : "reset",
5084                 *cmd_merge = abbr ? "m" : "merge";
5085
5086         oidmap_init(&commit2todo, 0);
5087         oidmap_init(&state.commit2label, 0);
5088         hashmap_init(&state.labels, labels_cmp, NULL, 0);
5089         strbuf_init(&state.buf, 32);
5090
5091         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5092                 struct labels_entry *onto_label_entry;
5093                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5094                 FLEX_ALLOC_STR(entry, string, "onto");
5095                 oidcpy(&entry->entry.oid, oid);
5096                 oidmap_put(&state.commit2label, entry);
5097
5098                 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5099                 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5100                 hashmap_add(&state.labels, &onto_label_entry->entry);
5101         }
5102
5103         /*
5104          * First phase:
5105          * - get onelines for all commits
5106          * - gather all branch tips (i.e. 2nd or later parents of merges)
5107          * - label all branch tips
5108          */
5109         while ((commit = get_revision(revs))) {
5110                 struct commit_list *to_merge;
5111                 const char *p1, *p2;
5112                 struct object_id *oid;
5113                 int is_empty;
5114
5115                 tail = &commit_list_insert(commit, tail)->next;
5116                 oidset_insert(&interesting, &commit->object.oid);
5117
5118                 is_empty = is_original_commit_empty(commit);
5119                 if (!is_empty && (commit->object.flags & PATCHSAME))
5120                         continue;
5121                 if (is_empty && !keep_empty)
5122                         continue;
5123
5124                 strbuf_reset(&oneline);
5125                 pretty_print_commit(pp, commit, &oneline);
5126
5127                 to_merge = commit->parents ? commit->parents->next : NULL;
5128                 if (!to_merge) {
5129                         /* non-merge commit: easy case */
5130                         strbuf_reset(&buf);
5131                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
5132                                     oid_to_hex(&commit->object.oid),
5133                                     oneline.buf);
5134                         if (is_empty)
5135                                 strbuf_addf(&buf, " %c empty",
5136                                             comment_line_char);
5137
5138                         FLEX_ALLOC_STR(entry, string, buf.buf);
5139                         oidcpy(&entry->entry.oid, &commit->object.oid);
5140                         oidmap_put(&commit2todo, entry);
5141
5142                         continue;
5143                 }
5144
5145                 /* Create a label */
5146                 strbuf_reset(&label);
5147                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5148                     (p1 = strchr(p1, '\'')) &&
5149                     (p2 = strchr(++p1, '\'')))
5150                         strbuf_add(&label, p1, p2 - p1);
5151                 else if (skip_prefix(oneline.buf, "Merge pull request ",
5152                                      &p1) &&
5153                          (p1 = strstr(p1, " from ")))
5154                         strbuf_addstr(&label, p1 + strlen(" from "));
5155                 else
5156                         strbuf_addbuf(&label, &oneline);
5157
5158                 strbuf_reset(&buf);
5159                 strbuf_addf(&buf, "%s -C %s",
5160                             cmd_merge, oid_to_hex(&commit->object.oid));
5161
5162                 /* label the tips of merged branches */
5163                 for (; to_merge; to_merge = to_merge->next) {
5164                         oid = &to_merge->item->object.oid;
5165                         strbuf_addch(&buf, ' ');
5166
5167                         if (!oidset_contains(&interesting, oid)) {
5168                                 strbuf_addstr(&buf, label_oid(oid, NULL,
5169                                                               &state));
5170                                 continue;
5171                         }
5172
5173                         tips_tail = &commit_list_insert(to_merge->item,
5174                                                         tips_tail)->next;
5175
5176                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5177                 }
5178                 strbuf_addf(&buf, " # %s", oneline.buf);
5179
5180                 FLEX_ALLOC_STR(entry, string, buf.buf);
5181                 oidcpy(&entry->entry.oid, &commit->object.oid);
5182                 oidmap_put(&commit2todo, entry);
5183         }
5184
5185         /*
5186          * Second phase:
5187          * - label branch points
5188          * - add HEAD to the branch tips
5189          */
5190         for (iter = commits; iter; iter = iter->next) {
5191                 struct commit_list *parent = iter->item->parents;
5192                 for (; parent; parent = parent->next) {
5193                         struct object_id *oid = &parent->item->object.oid;
5194                         if (!oidset_contains(&interesting, oid))
5195                                 continue;
5196                         if (oidset_insert(&child_seen, oid))
5197                                 label_oid(oid, "branch-point", &state);
5198                 }
5199
5200                 /* Add HEAD as implicit "tip of branch" */
5201                 if (!iter->next)
5202                         tips_tail = &commit_list_insert(iter->item,
5203                                                         tips_tail)->next;
5204         }
5205
5206         /*
5207          * Third phase: output the todo list. This is a bit tricky, as we
5208          * want to avoid jumping back and forth between revisions. To
5209          * accomplish that goal, we walk backwards from the branch tips,
5210          * gathering commits not yet shown, reversing the list on the fly,
5211          * then outputting that list (labeling revisions as needed).
5212          */
5213         strbuf_addf(out, "%s onto\n", cmd_label);
5214         for (iter = tips; iter; iter = iter->next) {
5215                 struct commit_list *list = NULL, *iter2;
5216
5217                 commit = iter->item;
5218                 if (oidset_contains(&shown, &commit->object.oid))
5219                         continue;
5220                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5221
5222                 if (entry)
5223                         strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5224                 else
5225                         strbuf_addch(out, '\n');
5226
5227                 while (oidset_contains(&interesting, &commit->object.oid) &&
5228                        !oidset_contains(&shown, &commit->object.oid)) {
5229                         commit_list_insert(commit, &list);
5230                         if (!commit->parents) {
5231                                 commit = NULL;
5232                                 break;
5233                         }
5234                         commit = commit->parents->item;
5235                 }
5236
5237                 if (!commit)
5238                         strbuf_addf(out, "%s %s\n", cmd_reset,
5239                                     rebase_cousins || root_with_onto ?
5240                                     "onto" : "[new root]");
5241                 else {
5242                         const char *to = NULL;
5243
5244                         entry = oidmap_get(&state.commit2label,
5245                                            &commit->object.oid);
5246                         if (entry)
5247                                 to = entry->string;
5248                         else if (!rebase_cousins)
5249                                 to = label_oid(&commit->object.oid, NULL,
5250                                                &state);
5251
5252                         if (!to || !strcmp(to, "onto"))
5253                                 strbuf_addf(out, "%s onto\n", cmd_reset);
5254                         else {
5255                                 strbuf_reset(&oneline);
5256                                 pretty_print_commit(pp, commit, &oneline);
5257                                 strbuf_addf(out, "%s %s # %s\n",
5258                                             cmd_reset, to, oneline.buf);
5259                         }
5260                 }
5261
5262                 for (iter2 = list; iter2; iter2 = iter2->next) {
5263                         struct object_id *oid = &iter2->item->object.oid;
5264                         entry = oidmap_get(&commit2todo, oid);
5265                         /* only show if not already upstream */
5266                         if (entry)
5267                                 strbuf_addf(out, "%s\n", entry->string);
5268                         entry = oidmap_get(&state.commit2label, oid);
5269                         if (entry)
5270                                 strbuf_addf(out, "%s %s\n",
5271                                             cmd_label, entry->string);
5272                         oidset_insert(&shown, oid);
5273                 }
5274
5275                 free_commit_list(list);
5276         }
5277
5278         free_commit_list(commits);
5279         free_commit_list(tips);
5280
5281         strbuf_release(&label);
5282         strbuf_release(&oneline);
5283         strbuf_release(&buf);
5284
5285         oidmap_free(&commit2todo, 1);
5286         oidmap_free(&state.commit2label, 1);
5287         hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5288         strbuf_release(&state.buf);
5289
5290         return 0;
5291 }
5292
5293 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5294                           const char **argv, unsigned flags)
5295 {
5296         char *format = NULL;
5297         struct pretty_print_context pp = {0};
5298         struct rev_info revs;
5299         struct commit *commit;
5300         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5301         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5302         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5303         int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5304
5305         repo_init_revisions(r, &revs, NULL);
5306         revs.verbose_header = 1;
5307         if (!rebase_merges)
5308                 revs.max_parents = 1;
5309         revs.cherry_mark = !reapply_cherry_picks;
5310         revs.limited = 1;
5311         revs.reverse = 1;
5312         revs.right_only = 1;
5313         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5314         revs.topo_order = 1;
5315
5316         revs.pretty_given = 1;
5317         git_config_get_string("rebase.instructionFormat", &format);
5318         if (!format || !*format) {
5319                 free(format);
5320                 format = xstrdup("%s");
5321         }
5322         get_commit_format(format, &revs);
5323         free(format);
5324         pp.fmt = revs.commit_format;
5325         pp.output_encoding = get_log_output_encoding();
5326
5327         if (setup_revisions(argc, argv, &revs, NULL) > 1)
5328                 return error(_("make_script: unhandled options"));
5329
5330         if (prepare_revision_walk(&revs) < 0)
5331                 return error(_("make_script: error preparing revisions"));
5332
5333         if (rebase_merges)
5334                 return make_script_with_merges(&pp, &revs, out, flags);
5335
5336         while ((commit = get_revision(&revs))) {
5337                 int is_empty = is_original_commit_empty(commit);
5338
5339                 if (!is_empty && (commit->object.flags & PATCHSAME))
5340                         continue;
5341                 if (is_empty && !keep_empty)
5342                         continue;
5343                 strbuf_addf(out, "%s %s ", insn,
5344                             oid_to_hex(&commit->object.oid));
5345                 pretty_print_commit(&pp, commit, out);
5346                 if (is_empty)
5347                         strbuf_addf(out, " %c empty", comment_line_char);
5348                 strbuf_addch(out, '\n');
5349         }
5350         return 0;
5351 }
5352
5353 /*
5354  * Add commands after pick and (series of) squash/fixup commands
5355  * in the todo list.
5356  */
5357 void todo_list_add_exec_commands(struct todo_list *todo_list,
5358                                  struct string_list *commands)
5359 {
5360         struct strbuf *buf = &todo_list->buf;
5361         size_t base_offset = buf->len;
5362         int i, insert, nr = 0, alloc = 0;
5363         struct todo_item *items = NULL, *base_items = NULL;
5364
5365         base_items = xcalloc(commands->nr, sizeof(struct todo_item));
5366         for (i = 0; i < commands->nr; i++) {
5367                 size_t command_len = strlen(commands->items[i].string);
5368
5369                 strbuf_addstr(buf, commands->items[i].string);
5370                 strbuf_addch(buf, '\n');
5371
5372                 base_items[i].command = TODO_EXEC;
5373                 base_items[i].offset_in_buf = base_offset;
5374                 base_items[i].arg_offset = base_offset + strlen("exec ");
5375                 base_items[i].arg_len = command_len - strlen("exec ");
5376
5377                 base_offset += command_len + 1;
5378         }
5379
5380         /*
5381          * Insert <commands> after every pick. Here, fixup/squash chains
5382          * are considered part of the pick, so we insert the commands *after*
5383          * those chains if there are any.
5384          *
5385          * As we insert the exec commands immediately after rearranging
5386          * any fixups and before the user edits the list, a fixup chain
5387          * can never contain comments (any comments are empty picks that
5388          * have been commented out because the user did not specify
5389          * --keep-empty).  So, it is safe to insert an exec command
5390          * without looking at the command following a comment.
5391          */
5392         insert = 0;
5393         for (i = 0; i < todo_list->nr; i++) {
5394                 enum todo_command command = todo_list->items[i].command;
5395                 if (insert && !is_fixup(command)) {
5396                         ALLOC_GROW(items, nr + commands->nr, alloc);
5397                         COPY_ARRAY(items + nr, base_items, commands->nr);
5398                         nr += commands->nr;
5399
5400                         insert = 0;
5401                 }
5402
5403                 ALLOC_GROW(items, nr + 1, alloc);
5404                 items[nr++] = todo_list->items[i];
5405
5406                 if (command == TODO_PICK || command == TODO_MERGE)
5407                         insert = 1;
5408         }
5409
5410         /* insert or append final <commands> */
5411         if (insert || nr == todo_list->nr) {
5412                 ALLOC_GROW(items, nr + commands->nr, alloc);
5413                 COPY_ARRAY(items + nr, base_items, commands->nr);
5414                 nr += commands->nr;
5415         }
5416
5417         free(base_items);
5418         FREE_AND_NULL(todo_list->items);
5419         todo_list->items = items;
5420         todo_list->nr = nr;
5421         todo_list->alloc = alloc;
5422 }
5423
5424 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5425                                 struct strbuf *buf, int num, unsigned flags)
5426 {
5427         struct todo_item *item;
5428         int i, max = todo_list->nr;
5429
5430         if (num > 0 && num < max)
5431                 max = num;
5432
5433         for (item = todo_list->items, i = 0; i < max; i++, item++) {
5434                 char cmd;
5435
5436                 /* if the item is not a command write it and continue */
5437                 if (item->command >= TODO_COMMENT) {
5438                         strbuf_addf(buf, "%.*s\n", item->arg_len,
5439                                     todo_item_get_arg(todo_list, item));
5440                         continue;
5441                 }
5442
5443                 /* add command to the buffer */
5444                 cmd = command_to_char(item->command);
5445                 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5446                         strbuf_addch(buf, cmd);
5447                 else
5448                         strbuf_addstr(buf, command_to_string(item->command));
5449
5450                 /* add commit id */
5451                 if (item->commit) {
5452                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5453                                           short_commit_name(item->commit) :
5454                                           oid_to_hex(&item->commit->object.oid);
5455
5456                         if (item->command == TODO_FIXUP) {
5457                                 if (item->flags & TODO_EDIT_FIXUP_MSG)
5458                                         strbuf_addstr(buf, " -c");
5459                                 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5460                                         strbuf_addstr(buf, " -C");
5461                                 }
5462                         }
5463
5464                         if (item->command == TODO_MERGE) {
5465                                 if (item->flags & TODO_EDIT_MERGE_MSG)
5466                                         strbuf_addstr(buf, " -c");
5467                                 else
5468                                         strbuf_addstr(buf, " -C");
5469                         }
5470
5471                         strbuf_addf(buf, " %s", oid);
5472                 }
5473
5474                 /* add all the rest */
5475                 if (!item->arg_len)
5476                         strbuf_addch(buf, '\n');
5477                 else
5478                         strbuf_addf(buf, " %.*s\n", item->arg_len,
5479                                     todo_item_get_arg(todo_list, item));
5480         }
5481 }
5482
5483 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5484                             const char *file, const char *shortrevisions,
5485                             const char *shortonto, int num, unsigned flags)
5486 {
5487         int res;
5488         struct strbuf buf = STRBUF_INIT;
5489
5490         todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5491         if (flags & TODO_LIST_APPEND_TODO_HELP)
5492                 append_todo_help(count_commands(todo_list),
5493                                  shortrevisions, shortonto, &buf);
5494
5495         res = write_message(buf.buf, buf.len, file, 0);
5496         strbuf_release(&buf);
5497
5498         return res;
5499 }
5500
5501 /* skip picking commits whose parents are unchanged */
5502 static int skip_unnecessary_picks(struct repository *r,
5503                                   struct todo_list *todo_list,
5504                                   struct object_id *base_oid)
5505 {
5506         struct object_id *parent_oid;
5507         int i;
5508
5509         for (i = 0; i < todo_list->nr; i++) {
5510                 struct todo_item *item = todo_list->items + i;
5511
5512                 if (item->command >= TODO_NOOP)
5513                         continue;
5514                 if (item->command != TODO_PICK)
5515                         break;
5516                 if (parse_commit(item->commit)) {
5517                         return error(_("could not parse commit '%s'"),
5518                                 oid_to_hex(&item->commit->object.oid));
5519                 }
5520                 if (!item->commit->parents)
5521                         break; /* root commit */
5522                 if (item->commit->parents->next)
5523                         break; /* merge commit */
5524                 parent_oid = &item->commit->parents->item->object.oid;
5525                 if (!oideq(parent_oid, base_oid))
5526                         break;
5527                 oidcpy(base_oid, &item->commit->object.oid);
5528         }
5529         if (i > 0) {
5530                 const char *done_path = rebase_path_done();
5531
5532                 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5533                         error_errno(_("could not write to '%s'"), done_path);
5534                         return -1;
5535                 }
5536
5537                 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5538                 todo_list->nr -= i;
5539                 todo_list->current = 0;
5540                 todo_list->done_nr += i;
5541
5542                 if (is_fixup(peek_command(todo_list, 0)))
5543                         record_in_rewritten(base_oid, peek_command(todo_list, 0));
5544         }
5545
5546         return 0;
5547 }
5548
5549 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5550                     const char *shortrevisions, const char *onto_name,
5551                     struct commit *onto, const struct object_id *orig_head,
5552                     struct string_list *commands, unsigned autosquash,
5553                     struct todo_list *todo_list)
5554 {
5555         char shortonto[GIT_MAX_HEXSZ + 1];
5556         const char *todo_file = rebase_path_todo();
5557         struct todo_list new_todo = TODO_LIST_INIT;
5558         struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5559         struct object_id oid = onto->object.oid;
5560         int res;
5561
5562         find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5563
5564         if (buf->len == 0) {
5565                 struct todo_item *item = append_new_todo(todo_list);
5566                 item->command = TODO_NOOP;
5567                 item->commit = NULL;
5568                 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5569         }
5570
5571         if (autosquash && todo_list_rearrange_squash(todo_list))
5572                 return -1;
5573
5574         if (commands->nr)
5575                 todo_list_add_exec_commands(todo_list, commands);
5576
5577         if (count_commands(todo_list) == 0) {
5578                 apply_autostash(rebase_path_autostash());
5579                 sequencer_remove_state(opts);
5580
5581                 return error(_("nothing to do"));
5582         }
5583
5584         res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5585                              shortonto, flags);
5586         if (res == -1)
5587                 return -1;
5588         else if (res == -2) {
5589                 apply_autostash(rebase_path_autostash());
5590                 sequencer_remove_state(opts);
5591
5592                 return -1;
5593         } else if (res == -3) {
5594                 apply_autostash(rebase_path_autostash());
5595                 sequencer_remove_state(opts);
5596                 todo_list_release(&new_todo);
5597
5598                 return error(_("nothing to do"));
5599         } else if (res == -4) {
5600                 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5601                 todo_list_release(&new_todo);
5602
5603                 return -1;
5604         }
5605
5606         /* Expand the commit IDs */
5607         todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5608         strbuf_swap(&new_todo.buf, &buf2);
5609         strbuf_release(&buf2);
5610         new_todo.total_nr -= new_todo.nr;
5611         if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5612                 BUG("invalid todo list after expanding IDs:\n%s",
5613                     new_todo.buf.buf);
5614
5615         if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5616                 todo_list_release(&new_todo);
5617                 return error(_("could not skip unnecessary pick commands"));
5618         }
5619
5620         if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5621                                     flags & ~(TODO_LIST_SHORTEN_IDS))) {
5622                 todo_list_release(&new_todo);
5623                 return error_errno(_("could not write '%s'"), todo_file);
5624         }
5625
5626         res = -1;
5627
5628         if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5629                 goto cleanup;
5630
5631         if (require_clean_work_tree(r, "rebase", "", 1, 1))
5632                 goto cleanup;
5633
5634         todo_list_write_total_nr(&new_todo);
5635         res = pick_commits(r, &new_todo, opts);
5636
5637 cleanup:
5638         todo_list_release(&new_todo);
5639
5640         return res;
5641 }
5642
5643 struct subject2item_entry {
5644         struct hashmap_entry entry;
5645         int i;
5646         char subject[FLEX_ARRAY];
5647 };
5648
5649 static int subject2item_cmp(const void *fndata,
5650                             const struct hashmap_entry *eptr,
5651                             const struct hashmap_entry *entry_or_key,
5652                             const void *key)
5653 {
5654         const struct subject2item_entry *a, *b;
5655
5656         a = container_of(eptr, const struct subject2item_entry, entry);
5657         b = container_of(entry_or_key, const struct subject2item_entry, entry);
5658
5659         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5660 }
5661
5662 define_commit_slab(commit_todo_item, struct todo_item *);
5663
5664 static int skip_fixupish(const char *subject, const char **p) {
5665         return skip_prefix(subject, "fixup! ", p) ||
5666                skip_prefix(subject, "amend! ", p) ||
5667                skip_prefix(subject, "squash! ", p);
5668 }
5669
5670 /*
5671  * Rearrange the todo list that has both "pick commit-id msg" and "pick
5672  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5673  * after the former, and change "pick" to "fixup"/"squash".
5674  *
5675  * Note that if the config has specified a custom instruction format, each log
5676  * message will have to be retrieved from the commit (as the oneline in the
5677  * script cannot be trusted) in order to normalize the autosquash arrangement.
5678  */
5679 int todo_list_rearrange_squash(struct todo_list *todo_list)
5680 {
5681         struct hashmap subject2item;
5682         int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5683         char **subjects;
5684         struct commit_todo_item commit_todo;
5685         struct todo_item *items = NULL;
5686
5687         init_commit_todo_item(&commit_todo);
5688         /*
5689          * The hashmap maps onelines to the respective todo list index.
5690          *
5691          * If any items need to be rearranged, the next[i] value will indicate
5692          * which item was moved directly after the i'th.
5693          *
5694          * In that case, last[i] will indicate the index of the latest item to
5695          * be moved to appear after the i'th.
5696          */
5697         hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5698         ALLOC_ARRAY(next, todo_list->nr);
5699         ALLOC_ARRAY(tail, todo_list->nr);
5700         ALLOC_ARRAY(subjects, todo_list->nr);
5701         for (i = 0; i < todo_list->nr; i++) {
5702                 struct strbuf buf = STRBUF_INIT;
5703                 struct todo_item *item = todo_list->items + i;
5704                 const char *commit_buffer, *subject, *p;
5705                 size_t subject_len;
5706                 int i2 = -1;
5707                 struct subject2item_entry *entry;
5708
5709                 next[i] = tail[i] = -1;
5710                 if (!item->commit || item->command == TODO_DROP) {
5711                         subjects[i] = NULL;
5712                         continue;
5713                 }
5714
5715                 if (is_fixup(item->command)) {
5716                         clear_commit_todo_item(&commit_todo);
5717                         return error(_("the script was already rearranged."));
5718                 }
5719
5720                 *commit_todo_item_at(&commit_todo, item->commit) = item;
5721
5722                 parse_commit(item->commit);
5723                 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5724                 find_commit_subject(commit_buffer, &subject);
5725                 format_subject(&buf, subject, " ");
5726                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5727                 unuse_commit_buffer(item->commit, commit_buffer);
5728                 if (skip_fixupish(subject, &p)) {
5729                         struct commit *commit2;
5730
5731                         for (;;) {
5732                                 while (isspace(*p))
5733                                         p++;
5734                                 if (!skip_fixupish(p, &p))
5735                                         break;
5736                         }
5737
5738                         entry = hashmap_get_entry_from_hash(&subject2item,
5739                                                 strhash(p), p,
5740                                                 struct subject2item_entry,
5741                                                 entry);
5742                         if (entry)
5743                                 /* found by title */
5744                                 i2 = entry->i;
5745                         else if (!strchr(p, ' ') &&
5746                                  (commit2 =
5747                                   lookup_commit_reference_by_name(p)) &&
5748                                  *commit_todo_item_at(&commit_todo, commit2))
5749                                 /* found by commit name */
5750                                 i2 = *commit_todo_item_at(&commit_todo, commit2)
5751                                         - todo_list->items;
5752                         else {
5753                                 /* copy can be a prefix of the commit subject */
5754                                 for (i2 = 0; i2 < i; i2++)
5755                                         if (subjects[i2] &&
5756                                             starts_with(subjects[i2], p))
5757                                                 break;
5758                                 if (i2 == i)
5759                                         i2 = -1;
5760                         }
5761                 }
5762                 if (i2 >= 0) {
5763                         rearranged = 1;
5764                         if (starts_with(subject, "fixup!")) {
5765                                 todo_list->items[i].command = TODO_FIXUP;
5766                         } else if (starts_with(subject, "amend!")) {
5767                                 todo_list->items[i].command = TODO_FIXUP;
5768                                 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
5769                         } else {
5770                                 todo_list->items[i].command = TODO_SQUASH;
5771                         }
5772                         if (tail[i2] < 0) {
5773                                 next[i] = next[i2];
5774                                 next[i2] = i;
5775                         } else {
5776                                 next[i] = next[tail[i2]];
5777                                 next[tail[i2]] = i;
5778                         }
5779                         tail[i2] = i;
5780                 } else if (!hashmap_get_from_hash(&subject2item,
5781                                                 strhash(subject), subject)) {
5782                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5783                         entry->i = i;
5784                         hashmap_entry_init(&entry->entry,
5785                                         strhash(entry->subject));
5786                         hashmap_put(&subject2item, &entry->entry);
5787                 }
5788         }
5789
5790         if (rearranged) {
5791                 for (i = 0; i < todo_list->nr; i++) {
5792                         enum todo_command command = todo_list->items[i].command;
5793                         int cur = i;
5794
5795                         /*
5796                          * Initially, all commands are 'pick's. If it is a
5797                          * fixup or a squash now, we have rearranged it.
5798                          */
5799                         if (is_fixup(command))
5800                                 continue;
5801
5802                         while (cur >= 0) {
5803                                 ALLOC_GROW(items, nr + 1, alloc);
5804                                 items[nr++] = todo_list->items[cur];
5805                                 cur = next[cur];
5806                         }
5807                 }
5808
5809                 FREE_AND_NULL(todo_list->items);
5810                 todo_list->items = items;
5811                 todo_list->nr = nr;
5812                 todo_list->alloc = alloc;
5813         }
5814
5815         free(next);
5816         free(tail);
5817         for (i = 0; i < todo_list->nr; i++)
5818                 free(subjects[i]);
5819         free(subjects);
5820         hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
5821
5822         clear_commit_todo_item(&commit_todo);
5823
5824         return 0;
5825 }
5826
5827 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5828 {
5829         if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5830                 struct object_id cherry_pick_head, rebase_head;
5831
5832                 if (file_exists(git_path_seq_dir()))
5833                         *whence = FROM_CHERRY_PICK_MULTI;
5834                 if (file_exists(rebase_path()) &&
5835                     !get_oid("REBASE_HEAD", &rebase_head) &&
5836                     !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5837                     oideq(&rebase_head, &cherry_pick_head))
5838                         *whence = FROM_REBASE_PICK;
5839                 else
5840                         *whence = FROM_CHERRY_PICK_SINGLE;
5841
5842                 return 1;
5843         }
5844
5845         return 0;
5846 }