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