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