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