Merge branch 'ab/range-diff-no-patch'
[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         struct strbuf buf = STRBUF_INIT;
1675         struct object_id newoid;
1676         FILE *out;
1677
1678         if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
1679             !get_oid("HEAD", &newoid) &&
1680             (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
1681                 char *bol = buf.buf, *eol;
1682
1683                 while (*bol) {
1684                         eol = strchrnul(bol, '\n');
1685                         fprintf(out, "%.*s %s\n", (int)(eol - bol),
1686                                         bol, oid_to_hex(&newoid));
1687                         if (!*eol)
1688                                 break;
1689                         bol = eol + 1;
1690                 }
1691                 fclose(out);
1692                 unlink(rebase_path_rewritten_pending());
1693         }
1694         strbuf_release(&buf);
1695 }
1696
1697 static void record_in_rewritten(struct object_id *oid,
1698                 enum todo_command next_command) {
1699         FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
1700
1701         if (!out)
1702                 return;
1703
1704         fprintf(out, "%s\n", oid_to_hex(oid));
1705         fclose(out);
1706
1707         if (!is_fixup(next_command))
1708                 flush_rewritten_pending();
1709 }
1710
1711 static int do_pick_commit(enum todo_command command, struct commit *commit,
1712                 struct replay_opts *opts, int final_fixup)
1713 {
1714         unsigned int flags = opts->edit ? EDIT_MSG : 0;
1715         const char *msg_file = opts->edit ? NULL : git_path_merge_msg(the_repository);
1716         struct object_id head;
1717         struct commit *base, *next, *parent;
1718         const char *base_label, *next_label;
1719         char *author = NULL;
1720         struct commit_message msg = { NULL, NULL, NULL, NULL };
1721         struct strbuf msgbuf = STRBUF_INIT;
1722         int res, unborn = 0, allow;
1723
1724         if (opts->no_commit) {
1725                 /*
1726                  * We do not intend to commit immediately.  We just want to
1727                  * merge the differences in, so let's compute the tree
1728                  * that represents the "current" state for merge-recursive
1729                  * to work on.
1730                  */
1731                 if (write_index_as_tree(&head, &the_index, get_index_file(), 0, NULL))
1732                         return error(_("your index file is unmerged."));
1733         } else {
1734                 unborn = get_oid("HEAD", &head);
1735                 /* Do we want to generate a root commit? */
1736                 if (is_pick_or_similar(command) && opts->have_squash_onto &&
1737                     oideq(&head, &opts->squash_onto)) {
1738                         if (is_fixup(command))
1739                                 return error(_("cannot fixup root commit"));
1740                         flags |= CREATE_ROOT_COMMIT;
1741                         unborn = 1;
1742                 } else if (unborn)
1743                         oidcpy(&head, the_hash_algo->empty_tree);
1744                 if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
1745                                        NULL, 0))
1746                         return error_dirty_index(opts);
1747         }
1748         discard_cache();
1749
1750         if (!commit->parents)
1751                 parent = NULL;
1752         else if (commit->parents->next) {
1753                 /* Reverting or cherry-picking a merge commit */
1754                 int cnt;
1755                 struct commit_list *p;
1756
1757                 if (!opts->mainline)
1758                         return error(_("commit %s is a merge but no -m option was given."),
1759                                 oid_to_hex(&commit->object.oid));
1760
1761                 for (cnt = 1, p = commit->parents;
1762                      cnt != opts->mainline && p;
1763                      cnt++)
1764                         p = p->next;
1765                 if (cnt != opts->mainline || !p)
1766                         return error(_("commit %s does not have parent %d"),
1767                                 oid_to_hex(&commit->object.oid), opts->mainline);
1768                 parent = p->item;
1769         } else if (0 < opts->mainline)
1770                 return error(_("mainline was specified but commit %s is not a merge."),
1771                         oid_to_hex(&commit->object.oid));
1772         else
1773                 parent = commit->parents->item;
1774
1775         if (get_message(commit, &msg) != 0)
1776                 return error(_("cannot get commit message for %s"),
1777                         oid_to_hex(&commit->object.oid));
1778
1779         if (opts->allow_ff && !is_fixup(command) &&
1780             ((parent && oideq(&parent->object.oid, &head)) ||
1781              (!parent && unborn))) {
1782                 if (is_rebase_i(opts))
1783                         write_author_script(msg.message);
1784                 res = fast_forward_to(&commit->object.oid, &head, unborn,
1785                         opts);
1786                 if (res || command != TODO_REWORD)
1787                         goto leave;
1788                 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1789                 msg_file = NULL;
1790                 goto fast_forward_edit;
1791         }
1792         if (parent && parse_commit(parent) < 0)
1793                 /* TRANSLATORS: The first %s will be a "todo" command like
1794                    "revert" or "pick", the second %s a SHA1. */
1795                 return error(_("%s: cannot parse parent commit %s"),
1796                         command_to_string(command),
1797                         oid_to_hex(&parent->object.oid));
1798
1799         /*
1800          * "commit" is an existing commit.  We would want to apply
1801          * the difference it introduces since its first parent "prev"
1802          * on top of the current HEAD if we are cherry-pick.  Or the
1803          * reverse of it if we are revert.
1804          */
1805
1806         if (command == TODO_REVERT) {
1807                 base = commit;
1808                 base_label = msg.label;
1809                 next = parent;
1810                 next_label = msg.parent_label;
1811                 strbuf_addstr(&msgbuf, "Revert \"");
1812                 strbuf_addstr(&msgbuf, msg.subject);
1813                 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1814                 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1815
1816                 if (commit->parents && commit->parents->next) {
1817                         strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1818                         strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1819                 }
1820                 strbuf_addstr(&msgbuf, ".\n");
1821         } else {
1822                 const char *p;
1823
1824                 base = parent;
1825                 base_label = msg.parent_label;
1826                 next = commit;
1827                 next_label = msg.label;
1828
1829                 /* Append the commit log message to msgbuf. */
1830                 if (find_commit_subject(msg.message, &p))
1831                         strbuf_addstr(&msgbuf, p);
1832
1833                 if (opts->record_origin) {
1834                         strbuf_complete_line(&msgbuf);
1835                         if (!has_conforming_footer(&msgbuf, NULL, 0))
1836                                 strbuf_addch(&msgbuf, '\n');
1837                         strbuf_addstr(&msgbuf, cherry_picked_prefix);
1838                         strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1839                         strbuf_addstr(&msgbuf, ")\n");
1840                 }
1841                 if (!is_fixup(command))
1842                         author = get_author(msg.message);
1843         }
1844
1845         if (command == TODO_REWORD)
1846                 flags |= EDIT_MSG | VERIFY_MSG;
1847         else if (is_fixup(command)) {
1848                 if (update_squash_messages(command, commit, opts))
1849                         return -1;
1850                 flags |= AMEND_MSG;
1851                 if (!final_fixup)
1852                         msg_file = rebase_path_squash_msg();
1853                 else if (file_exists(rebase_path_fixup_msg())) {
1854                         flags |= CLEANUP_MSG;
1855                         msg_file = rebase_path_fixup_msg();
1856                 } else {
1857                         const char *dest = git_path_squash_msg(the_repository);
1858                         unlink(dest);
1859                         if (copy_file(dest, rebase_path_squash_msg(), 0666))
1860                                 return error(_("could not rename '%s' to '%s'"),
1861                                              rebase_path_squash_msg(), dest);
1862                         unlink(git_path_merge_msg(the_repository));
1863                         msg_file = dest;
1864                         flags |= EDIT_MSG;
1865                 }
1866         }
1867
1868         if (opts->signoff && !is_fixup(command))
1869                 append_signoff(&msgbuf, 0, 0);
1870
1871         if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1872                 res = -1;
1873         else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1874                 res = do_recursive_merge(base, next, base_label, next_label,
1875                                          &head, &msgbuf, opts);
1876                 if (res < 0)
1877                         goto leave;
1878
1879                 res |= write_message(msgbuf.buf, msgbuf.len,
1880                                      git_path_merge_msg(the_repository), 0);
1881         } else {
1882                 struct commit_list *common = NULL;
1883                 struct commit_list *remotes = NULL;
1884
1885                 res = write_message(msgbuf.buf, msgbuf.len,
1886                                     git_path_merge_msg(the_repository), 0);
1887
1888                 commit_list_insert(base, &common);
1889                 commit_list_insert(next, &remotes);
1890                 res |= try_merge_command(the_repository, opts->strategy,
1891                                          opts->xopts_nr, (const char **)opts->xopts,
1892                                         common, oid_to_hex(&head), remotes);
1893                 free_commit_list(common);
1894                 free_commit_list(remotes);
1895         }
1896         strbuf_release(&msgbuf);
1897
1898         /*
1899          * If the merge was clean or if it failed due to conflict, we write
1900          * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1901          * However, if the merge did not even start, then we don't want to
1902          * write it at all.
1903          */
1904         if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1905             update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1906                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1907                 res = -1;
1908         if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1909             update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1910                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1911                 res = -1;
1912
1913         if (res) {
1914                 error(command == TODO_REVERT
1915                       ? _("could not revert %s... %s")
1916                       : _("could not apply %s... %s"),
1917                       short_commit_name(commit), msg.subject);
1918                 print_advice(res == 1, opts);
1919                 repo_rerere(the_repository, opts->allow_rerere_auto);
1920                 goto leave;
1921         }
1922
1923         allow = allow_empty(opts, commit);
1924         if (allow < 0) {
1925                 res = allow;
1926                 goto leave;
1927         } else if (allow)
1928                 flags |= ALLOW_EMPTY;
1929         if (!opts->no_commit) {
1930 fast_forward_edit:
1931                 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
1932                         res = do_commit(msg_file, author, opts, flags);
1933                 else
1934                         res = error(_("unable to parse commit author"));
1935         }
1936
1937         if (!res && final_fixup) {
1938                 unlink(rebase_path_fixup_msg());
1939                 unlink(rebase_path_squash_msg());
1940                 unlink(rebase_path_current_fixups());
1941                 strbuf_reset(&opts->current_fixups);
1942                 opts->current_fixup_count = 0;
1943         }
1944
1945 leave:
1946         free_message(commit, &msg);
1947         free(author);
1948         update_abort_safety_file();
1949
1950         return res;
1951 }
1952
1953 static int prepare_revs(struct replay_opts *opts)
1954 {
1955         /*
1956          * picking (but not reverting) ranges (but not individual revisions)
1957          * should be done in reverse
1958          */
1959         if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1960                 opts->revs->reverse ^= 1;
1961
1962         if (prepare_revision_walk(opts->revs))
1963                 return error(_("revision walk setup failed"));
1964
1965         return 0;
1966 }
1967
1968 static int read_and_refresh_cache(struct replay_opts *opts)
1969 {
1970         struct lock_file index_lock = LOCK_INIT;
1971         int index_fd = hold_locked_index(&index_lock, 0);
1972         if (read_index(&the_index) < 0) {
1973                 rollback_lock_file(&index_lock);
1974                 return error(_("git %s: failed to read the index"),
1975                         _(action_name(opts)));
1976         }
1977         refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1978         if (index_fd >= 0) {
1979                 if (write_locked_index(&the_index, &index_lock,
1980                                        COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
1981                         return error(_("git %s: failed to refresh the index"),
1982                                 _(action_name(opts)));
1983                 }
1984         }
1985         return 0;
1986 }
1987
1988 enum todo_item_flags {
1989         TODO_EDIT_MERGE_MSG = 1
1990 };
1991
1992 struct todo_item {
1993         enum todo_command command;
1994         struct commit *commit;
1995         unsigned int flags;
1996         const char *arg;
1997         int arg_len;
1998         size_t offset_in_buf;
1999 };
2000
2001 struct todo_list {
2002         struct strbuf buf;
2003         struct todo_item *items;
2004         int nr, alloc, current;
2005         int done_nr, total_nr;
2006         struct stat_data stat;
2007 };
2008
2009 #define TODO_LIST_INIT { STRBUF_INIT }
2010
2011 static void todo_list_release(struct todo_list *todo_list)
2012 {
2013         strbuf_release(&todo_list->buf);
2014         FREE_AND_NULL(todo_list->items);
2015         todo_list->nr = todo_list->alloc = 0;
2016 }
2017
2018 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2019 {
2020         ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2021         return todo_list->items + todo_list->nr++;
2022 }
2023
2024 static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
2025 {
2026         struct object_id commit_oid;
2027         char *end_of_object_name;
2028         int i, saved, status, padding;
2029
2030         item->flags = 0;
2031
2032         /* left-trim */
2033         bol += strspn(bol, " \t");
2034
2035         if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
2036                 item->command = TODO_COMMENT;
2037                 item->commit = NULL;
2038                 item->arg = bol;
2039                 item->arg_len = eol - bol;
2040                 return 0;
2041         }
2042
2043         for (i = 0; i < TODO_COMMENT; i++)
2044                 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
2045                         item->command = i;
2046                         break;
2047                 } else if ((bol + 1 == eol || bol[1] == ' ') &&
2048                            *bol == todo_command_info[i].c) {
2049                         bol++;
2050                         item->command = i;
2051                         break;
2052                 }
2053         if (i >= TODO_COMMENT)
2054                 return -1;
2055
2056         /* Eat up extra spaces/ tabs before object name */
2057         padding = strspn(bol, " \t");
2058         bol += padding;
2059
2060         if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2061                 if (bol != eol)
2062                         return error(_("%s does not accept arguments: '%s'"),
2063                                      command_to_string(item->command), bol);
2064                 item->commit = NULL;
2065                 item->arg = bol;
2066                 item->arg_len = eol - bol;
2067                 return 0;
2068         }
2069
2070         if (!padding)
2071                 return error(_("missing arguments for %s"),
2072                              command_to_string(item->command));
2073
2074         if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2075             item->command == TODO_RESET) {
2076                 item->commit = NULL;
2077                 item->arg = bol;
2078                 item->arg_len = (int)(eol - bol);
2079                 return 0;
2080         }
2081
2082         if (item->command == TODO_MERGE) {
2083                 if (skip_prefix(bol, "-C", &bol))
2084                         bol += strspn(bol, " \t");
2085                 else if (skip_prefix(bol, "-c", &bol)) {
2086                         bol += strspn(bol, " \t");
2087                         item->flags |= TODO_EDIT_MERGE_MSG;
2088                 } else {
2089                         item->flags |= TODO_EDIT_MERGE_MSG;
2090                         item->commit = NULL;
2091                         item->arg = bol;
2092                         item->arg_len = (int)(eol - bol);
2093                         return 0;
2094                 }
2095         }
2096
2097         end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2098         saved = *end_of_object_name;
2099         *end_of_object_name = '\0';
2100         status = get_oid(bol, &commit_oid);
2101         *end_of_object_name = saved;
2102
2103         item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
2104         item->arg_len = (int)(eol - item->arg);
2105
2106         if (status < 0)
2107                 return -1;
2108
2109         item->commit = lookup_commit_reference(the_repository, &commit_oid);
2110         return !item->commit;
2111 }
2112
2113 static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
2114 {
2115         struct todo_item *item;
2116         char *p = buf, *next_p;
2117         int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2118
2119         for (i = 1; *p; i++, p = next_p) {
2120                 char *eol = strchrnul(p, '\n');
2121
2122                 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2123
2124                 if (p != eol && eol[-1] == '\r')
2125                         eol--; /* strip Carriage Return */
2126
2127                 item = append_new_todo(todo_list);
2128                 item->offset_in_buf = p - todo_list->buf.buf;
2129                 if (parse_insn_line(item, p, eol)) {
2130                         res = error(_("invalid line %d: %.*s"),
2131                                 i, (int)(eol - p), p);
2132                         item->command = TODO_NOOP;
2133                 }
2134
2135                 if (fixup_okay)
2136                         ; /* do nothing */
2137                 else if (is_fixup(item->command))
2138                         return error(_("cannot '%s' without a previous commit"),
2139                                 command_to_string(item->command));
2140                 else if (!is_noop(item->command))
2141                         fixup_okay = 1;
2142         }
2143
2144         return res;
2145 }
2146
2147 static int count_commands(struct todo_list *todo_list)
2148 {
2149         int count = 0, i;
2150
2151         for (i = 0; i < todo_list->nr; i++)
2152                 if (todo_list->items[i].command != TODO_COMMENT)
2153                         count++;
2154
2155         return count;
2156 }
2157
2158 static int get_item_line_offset(struct todo_list *todo_list, int index)
2159 {
2160         return index < todo_list->nr ?
2161                 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2162 }
2163
2164 static const char *get_item_line(struct todo_list *todo_list, int index)
2165 {
2166         return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2167 }
2168
2169 static int get_item_line_length(struct todo_list *todo_list, int index)
2170 {
2171         return get_item_line_offset(todo_list, index + 1)
2172                 -  get_item_line_offset(todo_list, index);
2173 }
2174
2175 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2176 {
2177         int fd;
2178         ssize_t len;
2179
2180         fd = open(path, O_RDONLY);
2181         if (fd < 0)
2182                 return error_errno(_("could not open '%s'"), path);
2183         len = strbuf_read(sb, fd, 0);
2184         close(fd);
2185         if (len < 0)
2186                 return error(_("could not read '%s'."), path);
2187         return len;
2188 }
2189
2190 static int read_populate_todo(struct todo_list *todo_list,
2191                         struct replay_opts *opts)
2192 {
2193         struct stat st;
2194         const char *todo_file = get_todo_path(opts);
2195         int res;
2196
2197         strbuf_reset(&todo_list->buf);
2198         if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2199                 return -1;
2200
2201         res = stat(todo_file, &st);
2202         if (res)
2203                 return error(_("could not stat '%s'"), todo_file);
2204         fill_stat_data(&todo_list->stat, &st);
2205
2206         res = parse_insn_buffer(todo_list->buf.buf, todo_list);
2207         if (res) {
2208                 if (is_rebase_i(opts))
2209                         return error(_("please fix this using "
2210                                        "'git rebase --edit-todo'."));
2211                 return error(_("unusable instruction sheet: '%s'"), todo_file);
2212         }
2213
2214         if (!todo_list->nr &&
2215             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2216                 return error(_("no commits parsed."));
2217
2218         if (!is_rebase_i(opts)) {
2219                 enum todo_command valid =
2220                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2221                 int i;
2222
2223                 for (i = 0; i < todo_list->nr; i++)
2224                         if (valid == todo_list->items[i].command)
2225                                 continue;
2226                         else if (valid == TODO_PICK)
2227                                 return error(_("cannot cherry-pick during a revert."));
2228                         else
2229                                 return error(_("cannot revert during a cherry-pick."));
2230         }
2231
2232         if (is_rebase_i(opts)) {
2233                 struct todo_list done = TODO_LIST_INIT;
2234                 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2235
2236                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2237                                 !parse_insn_buffer(done.buf.buf, &done))
2238                         todo_list->done_nr = count_commands(&done);
2239                 else
2240                         todo_list->done_nr = 0;
2241
2242                 todo_list->total_nr = todo_list->done_nr
2243                         + count_commands(todo_list);
2244                 todo_list_release(&done);
2245
2246                 if (f) {
2247                         fprintf(f, "%d\n", todo_list->total_nr);
2248                         fclose(f);
2249                 }
2250         }
2251
2252         return 0;
2253 }
2254
2255 static int git_config_string_dup(char **dest,
2256                                  const char *var, const char *value)
2257 {
2258         if (!value)
2259                 return config_error_nonbool(var);
2260         free(*dest);
2261         *dest = xstrdup(value);
2262         return 0;
2263 }
2264
2265 static int populate_opts_cb(const char *key, const char *value, void *data)
2266 {
2267         struct replay_opts *opts = data;
2268         int error_flag = 1;
2269
2270         if (!value)
2271                 error_flag = 0;
2272         else if (!strcmp(key, "options.no-commit"))
2273                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2274         else if (!strcmp(key, "options.edit"))
2275                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2276         else if (!strcmp(key, "options.signoff"))
2277                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2278         else if (!strcmp(key, "options.record-origin"))
2279                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2280         else if (!strcmp(key, "options.allow-ff"))
2281                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2282         else if (!strcmp(key, "options.mainline"))
2283                 opts->mainline = git_config_int(key, value);
2284         else if (!strcmp(key, "options.strategy"))
2285                 git_config_string_dup(&opts->strategy, key, value);
2286         else if (!strcmp(key, "options.gpg-sign"))
2287                 git_config_string_dup(&opts->gpg_sign, key, value);
2288         else if (!strcmp(key, "options.strategy-option")) {
2289                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2290                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2291         } else if (!strcmp(key, "options.allow-rerere-auto"))
2292                 opts->allow_rerere_auto =
2293                         git_config_bool_or_int(key, value, &error_flag) ?
2294                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2295         else
2296                 return error(_("invalid key: %s"), key);
2297
2298         if (!error_flag)
2299                 return error(_("invalid value for %s: %s"), key, value);
2300
2301         return 0;
2302 }
2303
2304 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2305 {
2306         int i;
2307         char *strategy_opts_string = raw_opts;
2308
2309         if (*strategy_opts_string == ' ')
2310                 strategy_opts_string++;
2311
2312         opts->xopts_nr = split_cmdline(strategy_opts_string,
2313                                        (const char ***)&opts->xopts);
2314         for (i = 0; i < opts->xopts_nr; i++) {
2315                 const char *arg = opts->xopts[i];
2316
2317                 skip_prefix(arg, "--", &arg);
2318                 opts->xopts[i] = xstrdup(arg);
2319         }
2320 }
2321
2322 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2323 {
2324         strbuf_reset(buf);
2325         if (!read_oneliner(buf, rebase_path_strategy(), 0))
2326                 return;
2327         opts->strategy = strbuf_detach(buf, NULL);
2328         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2329                 return;
2330
2331         parse_strategy_opts(opts, buf->buf);
2332 }
2333
2334 static int read_populate_opts(struct replay_opts *opts)
2335 {
2336         if (is_rebase_i(opts)) {
2337                 struct strbuf buf = STRBUF_INIT;
2338
2339                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
2340                         if (!starts_with(buf.buf, "-S"))
2341                                 strbuf_reset(&buf);
2342                         else {
2343                                 free(opts->gpg_sign);
2344                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2345                         }
2346                         strbuf_reset(&buf);
2347                 }
2348
2349                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
2350                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2351                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2352                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2353                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2354                         strbuf_reset(&buf);
2355                 }
2356
2357                 if (file_exists(rebase_path_verbose()))
2358                         opts->verbose = 1;
2359
2360                 if (file_exists(rebase_path_signoff())) {
2361                         opts->allow_ff = 0;
2362                         opts->signoff = 1;
2363                 }
2364
2365                 read_strategy_opts(opts, &buf);
2366                 strbuf_release(&buf);
2367
2368                 if (read_oneliner(&opts->current_fixups,
2369                                   rebase_path_current_fixups(), 1)) {
2370                         const char *p = opts->current_fixups.buf;
2371                         opts->current_fixup_count = 1;
2372                         while ((p = strchr(p, '\n'))) {
2373                                 opts->current_fixup_count++;
2374                                 p++;
2375                         }
2376                 }
2377
2378                 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2379                         if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
2380                                 return error(_("unusable squash-onto"));
2381                         opts->have_squash_onto = 1;
2382                 }
2383
2384                 return 0;
2385         }
2386
2387         if (!file_exists(git_path_opts_file()))
2388                 return 0;
2389         /*
2390          * The function git_parse_source(), called from git_config_from_file(),
2391          * may die() in case of a syntactically incorrect file. We do not care
2392          * about this case, though, because we wrote that file ourselves, so we
2393          * are pretty certain that it is syntactically correct.
2394          */
2395         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2396                 return error(_("malformed options sheet: '%s'"),
2397                         git_path_opts_file());
2398         return 0;
2399 }
2400
2401 static void write_strategy_opts(struct replay_opts *opts)
2402 {
2403         int i;
2404         struct strbuf buf = STRBUF_INIT;
2405
2406         for (i = 0; i < opts->xopts_nr; ++i)
2407                 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2408
2409         write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2410         strbuf_release(&buf);
2411 }
2412
2413 int write_basic_state(struct replay_opts *opts, const char *head_name,
2414                       const char *onto, const char *orig_head)
2415 {
2416         const char *quiet = getenv("GIT_QUIET");
2417
2418         if (head_name)
2419                 write_file(rebase_path_head_name(), "%s\n", head_name);
2420         if (onto)
2421                 write_file(rebase_path_onto(), "%s\n", onto);
2422         if (orig_head)
2423                 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2424
2425         if (quiet)
2426                 write_file(rebase_path_quiet(), "%s\n", quiet);
2427         else
2428                 write_file(rebase_path_quiet(), "\n");
2429
2430         if (opts->verbose)
2431                 write_file(rebase_path_verbose(), "%s", "");
2432         if (opts->strategy)
2433                 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2434         if (opts->xopts_nr > 0)
2435                 write_strategy_opts(opts);
2436
2437         if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2438                 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2439         else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2440                 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2441
2442         if (opts->gpg_sign)
2443                 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2444         if (opts->signoff)
2445                 write_file(rebase_path_signoff(), "--signoff\n");
2446
2447         return 0;
2448 }
2449
2450 static int walk_revs_populate_todo(struct todo_list *todo_list,
2451                                 struct replay_opts *opts)
2452 {
2453         enum todo_command command = opts->action == REPLAY_PICK ?
2454                 TODO_PICK : TODO_REVERT;
2455         const char *command_string = todo_command_info[command].str;
2456         struct commit *commit;
2457
2458         if (prepare_revs(opts))
2459                 return -1;
2460
2461         while ((commit = get_revision(opts->revs))) {
2462                 struct todo_item *item = append_new_todo(todo_list);
2463                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2464                 const char *subject;
2465                 int subject_len;
2466
2467                 item->command = command;
2468                 item->commit = commit;
2469                 item->arg = NULL;
2470                 item->arg_len = 0;
2471                 item->offset_in_buf = todo_list->buf.len;
2472                 subject_len = find_commit_subject(commit_buffer, &subject);
2473                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2474                         short_commit_name(commit), subject_len, subject);
2475                 unuse_commit_buffer(commit, commit_buffer);
2476         }
2477
2478         if (!todo_list->nr)
2479                 return error(_("empty commit set passed"));
2480
2481         return 0;
2482 }
2483
2484 static int create_seq_dir(void)
2485 {
2486         if (file_exists(git_path_seq_dir())) {
2487                 error(_("a cherry-pick or revert is already in progress"));
2488                 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
2489                 return -1;
2490         } else if (mkdir(git_path_seq_dir(), 0777) < 0)
2491                 return error_errno(_("could not create sequencer directory '%s'"),
2492                                    git_path_seq_dir());
2493         return 0;
2494 }
2495
2496 static int save_head(const char *head)
2497 {
2498         struct lock_file head_lock = LOCK_INIT;
2499         struct strbuf buf = STRBUF_INIT;
2500         int fd;
2501         ssize_t written;
2502
2503         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2504         if (fd < 0)
2505                 return error_errno(_("could not lock HEAD"));
2506         strbuf_addf(&buf, "%s\n", head);
2507         written = write_in_full(fd, buf.buf, buf.len);
2508         strbuf_release(&buf);
2509         if (written < 0) {
2510                 error_errno(_("could not write to '%s'"), git_path_head_file());
2511                 rollback_lock_file(&head_lock);
2512                 return -1;
2513         }
2514         if (commit_lock_file(&head_lock) < 0)
2515                 return error(_("failed to finalize '%s'"), git_path_head_file());
2516         return 0;
2517 }
2518
2519 static int rollback_is_safe(void)
2520 {
2521         struct strbuf sb = STRBUF_INIT;
2522         struct object_id expected_head, actual_head;
2523
2524         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2525                 strbuf_trim(&sb);
2526                 if (get_oid_hex(sb.buf, &expected_head)) {
2527                         strbuf_release(&sb);
2528                         die(_("could not parse %s"), git_path_abort_safety_file());
2529                 }
2530                 strbuf_release(&sb);
2531         }
2532         else if (errno == ENOENT)
2533                 oidclr(&expected_head);
2534         else
2535                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2536
2537         if (get_oid("HEAD", &actual_head))
2538                 oidclr(&actual_head);
2539
2540         return oideq(&actual_head, &expected_head);
2541 }
2542
2543 static int reset_for_rollback(const struct object_id *oid)
2544 {
2545         const char *argv[4];    /* reset --merge <arg> + NULL */
2546
2547         argv[0] = "reset";
2548         argv[1] = "--merge";
2549         argv[2] = oid_to_hex(oid);
2550         argv[3] = NULL;
2551         return run_command_v_opt(argv, RUN_GIT_CMD);
2552 }
2553
2554 static int rollback_single_pick(void)
2555 {
2556         struct object_id head_oid;
2557
2558         if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
2559             !file_exists(git_path_revert_head(the_repository)))
2560                 return error(_("no cherry-pick or revert in progress"));
2561         if (read_ref_full("HEAD", 0, &head_oid, NULL))
2562                 return error(_("cannot resolve HEAD"));
2563         if (is_null_oid(&head_oid))
2564                 return error(_("cannot abort from a branch yet to be born"));
2565         return reset_for_rollback(&head_oid);
2566 }
2567
2568 int sequencer_rollback(struct replay_opts *opts)
2569 {
2570         FILE *f;
2571         struct object_id oid;
2572         struct strbuf buf = STRBUF_INIT;
2573         const char *p;
2574
2575         f = fopen(git_path_head_file(), "r");
2576         if (!f && errno == ENOENT) {
2577                 /*
2578                  * There is no multiple-cherry-pick in progress.
2579                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2580                  * a single-cherry-pick in progress, abort that.
2581                  */
2582                 return rollback_single_pick();
2583         }
2584         if (!f)
2585                 return error_errno(_("cannot open '%s'"), git_path_head_file());
2586         if (strbuf_getline_lf(&buf, f)) {
2587                 error(_("cannot read '%s': %s"), git_path_head_file(),
2588                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2589                 fclose(f);
2590                 goto fail;
2591         }
2592         fclose(f);
2593         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2594                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2595                         git_path_head_file());
2596                 goto fail;
2597         }
2598         if (is_null_oid(&oid)) {
2599                 error(_("cannot abort from a branch yet to be born"));
2600                 goto fail;
2601         }
2602
2603         if (!rollback_is_safe()) {
2604                 /* Do not error, just do not rollback */
2605                 warning(_("You seem to have moved HEAD. "
2606                           "Not rewinding, check your HEAD!"));
2607         } else
2608         if (reset_for_rollback(&oid))
2609                 goto fail;
2610         strbuf_release(&buf);
2611         return sequencer_remove_state(opts);
2612 fail:
2613         strbuf_release(&buf);
2614         return -1;
2615 }
2616
2617 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2618 {
2619         struct lock_file todo_lock = LOCK_INIT;
2620         const char *todo_path = get_todo_path(opts);
2621         int next = todo_list->current, offset, fd;
2622
2623         /*
2624          * rebase -i writes "git-rebase-todo" without the currently executing
2625          * command, appending it to "done" instead.
2626          */
2627         if (is_rebase_i(opts))
2628                 next++;
2629
2630         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2631         if (fd < 0)
2632                 return error_errno(_("could not lock '%s'"), todo_path);
2633         offset = get_item_line_offset(todo_list, next);
2634         if (write_in_full(fd, todo_list->buf.buf + offset,
2635                         todo_list->buf.len - offset) < 0)
2636                 return error_errno(_("could not write to '%s'"), todo_path);
2637         if (commit_lock_file(&todo_lock) < 0)
2638                 return error(_("failed to finalize '%s'"), todo_path);
2639
2640         if (is_rebase_i(opts) && next > 0) {
2641                 const char *done = rebase_path_done();
2642                 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2643                 int ret = 0;
2644
2645                 if (fd < 0)
2646                         return 0;
2647                 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2648                                   get_item_line_length(todo_list, next - 1))
2649                     < 0)
2650                         ret = error_errno(_("could not write to '%s'"), done);
2651                 if (close(fd) < 0)
2652                         ret = error_errno(_("failed to finalize '%s'"), done);
2653                 return ret;
2654         }
2655         return 0;
2656 }
2657
2658 static int save_opts(struct replay_opts *opts)
2659 {
2660         const char *opts_file = git_path_opts_file();
2661         int res = 0;
2662
2663         if (opts->no_commit)
2664                 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
2665         if (opts->edit)
2666                 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
2667         if (opts->signoff)
2668                 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
2669         if (opts->record_origin)
2670                 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
2671         if (opts->allow_ff)
2672                 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
2673         if (opts->mainline) {
2674                 struct strbuf buf = STRBUF_INIT;
2675                 strbuf_addf(&buf, "%d", opts->mainline);
2676                 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
2677                 strbuf_release(&buf);
2678         }
2679         if (opts->strategy)
2680                 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
2681         if (opts->gpg_sign)
2682                 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
2683         if (opts->xopts) {
2684                 int i;
2685                 for (i = 0; i < opts->xopts_nr; i++)
2686                         res |= git_config_set_multivar_in_file_gently(opts_file,
2687                                                         "options.strategy-option",
2688                                                         opts->xopts[i], "^$", 0);
2689         }
2690         if (opts->allow_rerere_auto)
2691                 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
2692                                                      opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
2693                                                      "true" : "false");
2694         return res;
2695 }
2696
2697 static int make_patch(struct commit *commit, struct replay_opts *opts)
2698 {
2699         struct strbuf buf = STRBUF_INIT;
2700         struct rev_info log_tree_opt;
2701         const char *subject, *p;
2702         int res = 0;
2703
2704         p = short_commit_name(commit);
2705         if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
2706                 return -1;
2707         if (update_ref("rebase", "REBASE_HEAD", &commit->object.oid,
2708                        NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2709                 res |= error(_("could not update %s"), "REBASE_HEAD");
2710
2711         strbuf_addf(&buf, "%s/patch", get_dir(opts));
2712         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2713         repo_init_revisions(the_repository, &log_tree_opt, NULL);
2714         log_tree_opt.abbrev = 0;
2715         log_tree_opt.diff = 1;
2716         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
2717         log_tree_opt.disable_stdin = 1;
2718         log_tree_opt.no_commit_id = 1;
2719         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
2720         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
2721         if (!log_tree_opt.diffopt.file)
2722                 res |= error_errno(_("could not open '%s'"), buf.buf);
2723         else {
2724                 res |= log_tree_commit(&log_tree_opt, commit);
2725                 fclose(log_tree_opt.diffopt.file);
2726         }
2727         strbuf_reset(&buf);
2728
2729         strbuf_addf(&buf, "%s/message", get_dir(opts));
2730         if (!file_exists(buf.buf)) {
2731                 const char *commit_buffer = get_commit_buffer(commit, NULL);
2732                 find_commit_subject(commit_buffer, &subject);
2733                 res |= write_message(subject, strlen(subject), buf.buf, 1);
2734                 unuse_commit_buffer(commit, commit_buffer);
2735         }
2736         strbuf_release(&buf);
2737
2738         return res;
2739 }
2740
2741 static int intend_to_amend(void)
2742 {
2743         struct object_id head;
2744         char *p;
2745
2746         if (get_oid("HEAD", &head))
2747                 return error(_("cannot read HEAD"));
2748
2749         p = oid_to_hex(&head);
2750         return write_message(p, strlen(p), rebase_path_amend(), 1);
2751 }
2752
2753 static int error_with_patch(struct commit *commit,
2754         const char *subject, int subject_len,
2755         struct replay_opts *opts, int exit_code, int to_amend)
2756 {
2757         if (commit) {
2758                 if (make_patch(commit, opts))
2759                         return -1;
2760         } else if (copy_file(rebase_path_message(),
2761                              git_path_merge_msg(the_repository), 0666))
2762                 return error(_("unable to copy '%s' to '%s'"),
2763                              git_path_merge_msg(the_repository), rebase_path_message());
2764
2765         if (to_amend) {
2766                 if (intend_to_amend())
2767                         return -1;
2768
2769                 fprintf(stderr,
2770                         _("You can amend the commit now, with\n"
2771                           "\n"
2772                           "  git commit --amend %s\n"
2773                           "\n"
2774                           "Once you are satisfied with your changes, run\n"
2775                           "\n"
2776                           "  git rebase --continue\n"),
2777                         gpg_sign_opt_quoted(opts));
2778         } else if (exit_code) {
2779                 if (commit)
2780                         fprintf_ln(stderr, _("Could not apply %s... %.*s"),
2781                                    short_commit_name(commit), subject_len, subject);
2782                 else
2783                         /*
2784                          * We don't have the hash of the parent so
2785                          * just print the line from the todo file.
2786                          */
2787                         fprintf_ln(stderr, _("Could not merge %.*s"),
2788                                    subject_len, subject);
2789         }
2790
2791         return exit_code;
2792 }
2793
2794 static int error_failed_squash(struct commit *commit,
2795         struct replay_opts *opts, int subject_len, const char *subject)
2796 {
2797         if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
2798                 return error(_("could not copy '%s' to '%s'"),
2799                         rebase_path_squash_msg(), rebase_path_message());
2800         unlink(git_path_merge_msg(the_repository));
2801         if (copy_file(git_path_merge_msg(the_repository), rebase_path_message(), 0666))
2802                 return error(_("could not copy '%s' to '%s'"),
2803                              rebase_path_message(),
2804                              git_path_merge_msg(the_repository));
2805         return error_with_patch(commit, subject, subject_len, opts, 1, 0);
2806 }
2807
2808 static int do_exec(const char *command_line)
2809 {
2810         struct argv_array child_env = ARGV_ARRAY_INIT;
2811         const char *child_argv[] = { NULL, NULL };
2812         int dirty, status;
2813
2814         fprintf(stderr, "Executing: %s\n", command_line);
2815         child_argv[0] = command_line;
2816         argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
2817         argv_array_pushf(&child_env, "GIT_WORK_TREE=%s",
2818                          absolute_path(get_git_work_tree()));
2819         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
2820                                           child_env.argv);
2821
2822         /* force re-reading of the cache */
2823         if (discard_cache() < 0 || read_cache() < 0)
2824                 return error(_("could not read index"));
2825
2826         dirty = require_clean_work_tree("rebase", NULL, 1, 1);
2827
2828         if (status) {
2829                 warning(_("execution failed: %s\n%s"
2830                           "You can fix the problem, and then run\n"
2831                           "\n"
2832                           "  git rebase --continue\n"
2833                           "\n"),
2834                         command_line,
2835                         dirty ? N_("and made changes to the index and/or the "
2836                                 "working tree\n") : "");
2837                 if (status == 127)
2838                         /* command not found */
2839                         status = 1;
2840         } else if (dirty) {
2841                 warning(_("execution succeeded: %s\nbut "
2842                           "left changes to the index and/or the working tree\n"
2843                           "Commit or stash your changes, and then run\n"
2844                           "\n"
2845                           "  git rebase --continue\n"
2846                           "\n"), command_line);
2847                 status = 1;
2848         }
2849
2850         argv_array_clear(&child_env);
2851
2852         return status;
2853 }
2854
2855 static int safe_append(const char *filename, const char *fmt, ...)
2856 {
2857         va_list ap;
2858         struct lock_file lock = LOCK_INIT;
2859         int fd = hold_lock_file_for_update(&lock, filename,
2860                                            LOCK_REPORT_ON_ERROR);
2861         struct strbuf buf = STRBUF_INIT;
2862
2863         if (fd < 0)
2864                 return -1;
2865
2866         if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
2867                 error_errno(_("could not read '%s'"), filename);
2868                 rollback_lock_file(&lock);
2869                 return -1;
2870         }
2871         strbuf_complete(&buf, '\n');
2872         va_start(ap, fmt);
2873         strbuf_vaddf(&buf, fmt, ap);
2874         va_end(ap);
2875
2876         if (write_in_full(fd, buf.buf, buf.len) < 0) {
2877                 error_errno(_("could not write to '%s'"), filename);
2878                 strbuf_release(&buf);
2879                 rollback_lock_file(&lock);
2880                 return -1;
2881         }
2882         if (commit_lock_file(&lock) < 0) {
2883                 strbuf_release(&buf);
2884                 rollback_lock_file(&lock);
2885                 return error(_("failed to finalize '%s'"), filename);
2886         }
2887
2888         strbuf_release(&buf);
2889         return 0;
2890 }
2891
2892 static int do_label(const char *name, int len)
2893 {
2894         struct ref_store *refs = get_main_ref_store(the_repository);
2895         struct ref_transaction *transaction;
2896         struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
2897         struct strbuf msg = STRBUF_INIT;
2898         int ret = 0;
2899         struct object_id head_oid;
2900
2901         if (len == 1 && *name == '#')
2902                 return error(_("illegal label name: '%.*s'"), len, name);
2903
2904         strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2905         strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
2906
2907         transaction = ref_store_transaction_begin(refs, &err);
2908         if (!transaction) {
2909                 error("%s", err.buf);
2910                 ret = -1;
2911         } else if (get_oid("HEAD", &head_oid)) {
2912                 error(_("could not read HEAD"));
2913                 ret = -1;
2914         } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
2915                                           NULL, 0, msg.buf, &err) < 0 ||
2916                    ref_transaction_commit(transaction, &err)) {
2917                 error("%s", err.buf);
2918                 ret = -1;
2919         }
2920         ref_transaction_free(transaction);
2921         strbuf_release(&err);
2922         strbuf_release(&msg);
2923
2924         if (!ret)
2925                 ret = safe_append(rebase_path_refs_to_delete(),
2926                                   "%s\n", ref_name.buf);
2927         strbuf_release(&ref_name);
2928
2929         return ret;
2930 }
2931
2932 static const char *reflog_message(struct replay_opts *opts,
2933         const char *sub_action, const char *fmt, ...);
2934
2935 static int do_reset(const char *name, int len, struct replay_opts *opts)
2936 {
2937         struct strbuf ref_name = STRBUF_INIT;
2938         struct object_id oid;
2939         struct lock_file lock = LOCK_INIT;
2940         struct tree_desc desc;
2941         struct tree *tree;
2942         struct unpack_trees_options unpack_tree_opts;
2943         int ret = 0;
2944
2945         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
2946                 return -1;
2947
2948         if (len == 10 && !strncmp("[new root]", name, len)) {
2949                 if (!opts->have_squash_onto) {
2950                         const char *hex;
2951                         if (commit_tree("", 0, the_hash_algo->empty_tree,
2952                                         NULL, &opts->squash_onto,
2953                                         NULL, NULL))
2954                                 return error(_("writing fake root commit"));
2955                         opts->have_squash_onto = 1;
2956                         hex = oid_to_hex(&opts->squash_onto);
2957                         if (write_message(hex, strlen(hex),
2958                                           rebase_path_squash_onto(), 0))
2959                                 return error(_("writing squash-onto"));
2960                 }
2961                 oidcpy(&oid, &opts->squash_onto);
2962         } else {
2963                 int i;
2964
2965                 /* Determine the length of the label */
2966                 for (i = 0; i < len; i++)
2967                         if (isspace(name[i]))
2968                                 break;
2969                 len = i;
2970
2971                 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
2972                 if (get_oid(ref_name.buf, &oid) &&
2973                     get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
2974                         error(_("could not read '%s'"), ref_name.buf);
2975                         rollback_lock_file(&lock);
2976                         strbuf_release(&ref_name);
2977                         return -1;
2978                 }
2979         }
2980
2981         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
2982         setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
2983         unpack_tree_opts.head_idx = 1;
2984         unpack_tree_opts.src_index = &the_index;
2985         unpack_tree_opts.dst_index = &the_index;
2986         unpack_tree_opts.fn = oneway_merge;
2987         unpack_tree_opts.merge = 1;
2988         unpack_tree_opts.update = 1;
2989
2990         if (read_cache_unmerged()) {
2991                 rollback_lock_file(&lock);
2992                 strbuf_release(&ref_name);
2993                 return error_resolve_conflict(_(action_name(opts)));
2994         }
2995
2996         if (!fill_tree_descriptor(&desc, &oid)) {
2997                 error(_("failed to find tree of %s"), oid_to_hex(&oid));
2998                 rollback_lock_file(&lock);
2999                 free((void *)desc.buffer);
3000                 strbuf_release(&ref_name);
3001                 return -1;
3002         }
3003
3004         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3005                 rollback_lock_file(&lock);
3006                 free((void *)desc.buffer);
3007                 strbuf_release(&ref_name);
3008                 return -1;
3009         }
3010
3011         tree = parse_tree_indirect(&oid);
3012         prime_cache_tree(&the_index, tree);
3013
3014         if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
3015                 ret = error(_("could not write index"));
3016         free((void *)desc.buffer);
3017
3018         if (!ret)
3019                 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3020                                                 len, name), "HEAD", &oid,
3021                                  NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3022
3023         strbuf_release(&ref_name);
3024         return ret;
3025 }
3026
3027 static struct commit *lookup_label(const char *label, int len,
3028                                    struct strbuf *buf)
3029 {
3030         struct commit *commit;
3031
3032         strbuf_reset(buf);
3033         strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3034         commit = lookup_commit_reference_by_name(buf->buf);
3035         if (!commit) {
3036                 /* fall back to non-rewritten ref or commit */
3037                 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3038                 commit = lookup_commit_reference_by_name(buf->buf);
3039         }
3040
3041         if (!commit)
3042                 error(_("could not resolve '%s'"), buf->buf);
3043
3044         return commit;
3045 }
3046
3047 static int do_merge(struct commit *commit, const char *arg, int arg_len,
3048                     int flags, struct replay_opts *opts)
3049 {
3050         int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3051                 EDIT_MSG | VERIFY_MSG : 0;
3052         struct strbuf ref_name = STRBUF_INIT;
3053         struct commit *head_commit, *merge_commit, *i;
3054         struct commit_list *bases, *j, *reversed = NULL;
3055         struct commit_list *to_merge = NULL, **tail = &to_merge;
3056         struct merge_options o;
3057         int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3058         static struct lock_file lock;
3059         const char *p;
3060
3061         if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
3062                 ret = -1;
3063                 goto leave_merge;
3064         }
3065
3066         head_commit = lookup_commit_reference_by_name("HEAD");
3067         if (!head_commit) {
3068                 ret = error(_("cannot merge without a current revision"));
3069                 goto leave_merge;
3070         }
3071
3072         /*
3073          * For octopus merges, the arg starts with the list of revisions to be
3074          * merged. The list is optionally followed by '#' and the oneline.
3075          */
3076         merge_arg_len = oneline_offset = arg_len;
3077         for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3078                 if (!*p)
3079                         break;
3080                 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3081                         p += 1 + strspn(p + 1, " \t\n");
3082                         oneline_offset = p - arg;
3083                         break;
3084                 }
3085                 k = strcspn(p, " \t\n");
3086                 if (!k)
3087                         continue;
3088                 merge_commit = lookup_label(p, k, &ref_name);
3089                 if (!merge_commit) {
3090                         ret = error(_("unable to parse '%.*s'"), k, p);
3091                         goto leave_merge;
3092                 }
3093                 tail = &commit_list_insert(merge_commit, tail)->next;
3094                 p += k;
3095                 merge_arg_len = p - arg;
3096         }
3097
3098         if (!to_merge) {
3099                 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3100                 goto leave_merge;
3101         }
3102
3103         if (opts->have_squash_onto &&
3104             oideq(&head_commit->object.oid, &opts->squash_onto)) {
3105                 /*
3106                  * When the user tells us to "merge" something into a
3107                  * "[new root]", let's simply fast-forward to the merge head.
3108                  */
3109                 rollback_lock_file(&lock);
3110                 if (to_merge->next)
3111                         ret = error(_("octopus merge cannot be executed on "
3112                                       "top of a [new root]"));
3113                 else
3114                         ret = fast_forward_to(&to_merge->item->object.oid,
3115                                               &head_commit->object.oid, 0,
3116                                               opts);
3117                 goto leave_merge;
3118         }
3119
3120         if (commit) {
3121                 const char *message = get_commit_buffer(commit, NULL);
3122                 const char *body;
3123                 int len;
3124
3125                 if (!message) {
3126                         ret = error(_("could not get commit message of '%s'"),
3127                                     oid_to_hex(&commit->object.oid));
3128                         goto leave_merge;
3129                 }
3130                 write_author_script(message);
3131                 find_commit_subject(message, &body);
3132                 len = strlen(body);
3133                 ret = write_message(body, len, git_path_merge_msg(the_repository), 0);
3134                 unuse_commit_buffer(commit, message);
3135                 if (ret) {
3136                         error_errno(_("could not write '%s'"),
3137                                     git_path_merge_msg(the_repository));
3138                         goto leave_merge;
3139                 }
3140         } else {
3141                 struct strbuf buf = STRBUF_INIT;
3142                 int len;
3143
3144                 strbuf_addf(&buf, "author %s", git_author_info(0));
3145                 write_author_script(buf.buf);
3146                 strbuf_reset(&buf);
3147
3148                 if (oneline_offset < arg_len) {
3149                         p = arg + oneline_offset;
3150                         len = arg_len - oneline_offset;
3151                 } else {
3152                         strbuf_addf(&buf, "Merge %s '%.*s'",
3153                                     to_merge->next ? "branches" : "branch",
3154                                     merge_arg_len, arg);
3155                         p = buf.buf;
3156                         len = buf.len;
3157                 }
3158
3159                 ret = write_message(p, len, git_path_merge_msg(the_repository), 0);
3160                 strbuf_release(&buf);
3161                 if (ret) {
3162                         error_errno(_("could not write '%s'"),
3163                                     git_path_merge_msg(the_repository));
3164                         goto leave_merge;
3165                 }
3166         }
3167
3168         /*
3169          * If HEAD is not identical to the first parent of the original merge
3170          * commit, we cannot fast-forward.
3171          */
3172         can_fast_forward = opts->allow_ff && commit && commit->parents &&
3173                 oideq(&commit->parents->item->object.oid,
3174                       &head_commit->object.oid);
3175
3176         /*
3177          * If any merge head is different from the original one, we cannot
3178          * fast-forward.
3179          */
3180         if (can_fast_forward) {
3181                 struct commit_list *p = commit->parents->next;
3182
3183                 for (j = to_merge; j && p; j = j->next, p = p->next)
3184                         if (!oideq(&j->item->object.oid,
3185                                    &p->item->object.oid)) {
3186                                 can_fast_forward = 0;
3187                                 break;
3188                         }
3189                 /*
3190                  * If the number of merge heads differs from the original merge
3191                  * commit, we cannot fast-forward.
3192                  */
3193                 if (j || p)
3194                         can_fast_forward = 0;
3195         }
3196
3197         if (can_fast_forward) {
3198                 rollback_lock_file(&lock);
3199                 ret = fast_forward_to(&commit->object.oid,
3200                                       &head_commit->object.oid, 0, opts);
3201                 goto leave_merge;
3202         }
3203
3204         if (to_merge->next) {
3205                 /* Octopus merge */
3206                 struct child_process cmd = CHILD_PROCESS_INIT;
3207
3208                 if (read_env_script(&cmd.env_array)) {
3209                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
3210
3211                         ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3212                         goto leave_merge;
3213                 }
3214
3215                 cmd.git_cmd = 1;
3216                 argv_array_push(&cmd.args, "merge");
3217                 argv_array_push(&cmd.args, "-s");
3218                 argv_array_push(&cmd.args, "octopus");
3219                 argv_array_push(&cmd.args, "--no-edit");
3220                 argv_array_push(&cmd.args, "--no-ff");
3221                 argv_array_push(&cmd.args, "--no-log");
3222                 argv_array_push(&cmd.args, "--no-stat");
3223                 argv_array_push(&cmd.args, "-F");
3224                 argv_array_push(&cmd.args, git_path_merge_msg(the_repository));
3225                 if (opts->gpg_sign)
3226                         argv_array_push(&cmd.args, opts->gpg_sign);
3227
3228                 /* Add the tips to be merged */
3229                 for (j = to_merge; j; j = j->next)
3230                         argv_array_push(&cmd.args,
3231                                         oid_to_hex(&j->item->object.oid));
3232
3233                 strbuf_release(&ref_name);
3234                 unlink(git_path_cherry_pick_head(the_repository));
3235                 rollback_lock_file(&lock);
3236
3237                 rollback_lock_file(&lock);
3238                 ret = run_command(&cmd);
3239
3240                 /* force re-reading of the cache */
3241                 if (!ret && (discard_cache() < 0 || read_cache() < 0))
3242                         ret = error(_("could not read index"));
3243                 goto leave_merge;
3244         }
3245
3246         merge_commit = to_merge->item;
3247         write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
3248                       git_path_merge_head(the_repository), 0);
3249         write_message("no-ff", 5, git_path_merge_mode(the_repository), 0);
3250
3251         bases = get_merge_bases(head_commit, merge_commit);
3252         if (bases && oideq(&merge_commit->object.oid,
3253                            &bases->item->object.oid)) {
3254                 ret = 0;
3255                 /* skip merging an ancestor of HEAD */
3256                 goto leave_merge;
3257         }
3258
3259         for (j = bases; j; j = j->next)
3260                 commit_list_insert(j->item, &reversed);
3261         free_commit_list(bases);
3262
3263         read_cache();
3264         init_merge_options(&o);
3265         o.branch1 = "HEAD";
3266         o.branch2 = ref_name.buf;
3267         o.buffer_output = 2;
3268
3269         ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3270         if (ret <= 0)
3271                 fputs(o.obuf.buf, stdout);
3272         strbuf_release(&o.obuf);
3273         if (ret < 0) {
3274                 error(_("could not even attempt to merge '%.*s'"),
3275                       merge_arg_len, arg);
3276                 goto leave_merge;
3277         }
3278         /*
3279          * The return value of merge_recursive() is 1 on clean, and 0 on
3280          * unclean merge.
3281          *
3282          * Let's reverse that, so that do_merge() returns 0 upon success and
3283          * 1 upon failed merge (keeping the return value -1 for the cases where
3284          * we will want to reschedule the `merge` command).
3285          */
3286         ret = !ret;
3287
3288         if (active_cache_changed &&
3289             write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
3290                 ret = error(_("merge: Unable to write new index file"));
3291                 goto leave_merge;
3292         }
3293
3294         rollback_lock_file(&lock);
3295         if (ret)
3296                 repo_rerere(the_repository, opts->allow_rerere_auto);
3297         else
3298                 /*
3299                  * In case of problems, we now want to return a positive
3300                  * value (a negative one would indicate that the `merge`
3301                  * command needs to be rescheduled).
3302                  */
3303                 ret = !!run_git_commit(git_path_merge_msg(the_repository), opts,
3304                                      run_commit_flags);
3305
3306 leave_merge:
3307         strbuf_release(&ref_name);
3308         rollback_lock_file(&lock);
3309         free_commit_list(to_merge);
3310         return ret;
3311 }
3312
3313 static int is_final_fixup(struct todo_list *todo_list)
3314 {
3315         int i = todo_list->current;
3316
3317         if (!is_fixup(todo_list->items[i].command))
3318                 return 0;
3319
3320         while (++i < todo_list->nr)
3321                 if (is_fixup(todo_list->items[i].command))
3322                         return 0;
3323                 else if (!is_noop(todo_list->items[i].command))
3324                         break;
3325         return 1;
3326 }
3327
3328 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3329 {
3330         int i;
3331
3332         for (i = todo_list->current + offset; i < todo_list->nr; i++)
3333                 if (!is_noop(todo_list->items[i].command))
3334                         return todo_list->items[i].command;
3335
3336         return -1;
3337 }
3338
3339 static int apply_autostash(struct replay_opts *opts)
3340 {
3341         struct strbuf stash_sha1 = STRBUF_INIT;
3342         struct child_process child = CHILD_PROCESS_INIT;
3343         int ret = 0;
3344
3345         if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
3346                 strbuf_release(&stash_sha1);
3347                 return 0;
3348         }
3349         strbuf_trim(&stash_sha1);
3350
3351         child.git_cmd = 1;
3352         child.no_stdout = 1;
3353         child.no_stderr = 1;
3354         argv_array_push(&child.args, "stash");
3355         argv_array_push(&child.args, "apply");
3356         argv_array_push(&child.args, stash_sha1.buf);
3357         if (!run_command(&child))
3358                 fprintf(stderr, _("Applied autostash.\n"));
3359         else {
3360                 struct child_process store = CHILD_PROCESS_INIT;
3361
3362                 store.git_cmd = 1;
3363                 argv_array_push(&store.args, "stash");
3364                 argv_array_push(&store.args, "store");
3365                 argv_array_push(&store.args, "-m");
3366                 argv_array_push(&store.args, "autostash");
3367                 argv_array_push(&store.args, "-q");
3368                 argv_array_push(&store.args, stash_sha1.buf);
3369                 if (run_command(&store))
3370                         ret = error(_("cannot store %s"), stash_sha1.buf);
3371                 else
3372                         fprintf(stderr,
3373                                 _("Applying autostash resulted in conflicts.\n"
3374                                   "Your changes are safe in the stash.\n"
3375                                   "You can run \"git stash pop\" or"
3376                                   " \"git stash drop\" at any time.\n"));
3377         }
3378
3379         strbuf_release(&stash_sha1);
3380         return ret;
3381 }
3382
3383 static const char *reflog_message(struct replay_opts *opts,
3384         const char *sub_action, const char *fmt, ...)
3385 {
3386         va_list ap;
3387         static struct strbuf buf = STRBUF_INIT;
3388
3389         va_start(ap, fmt);
3390         strbuf_reset(&buf);
3391         strbuf_addstr(&buf, action_name(opts));
3392         if (sub_action)
3393                 strbuf_addf(&buf, " (%s)", sub_action);
3394         if (fmt) {
3395                 strbuf_addstr(&buf, ": ");
3396                 strbuf_vaddf(&buf, fmt, ap);
3397         }
3398         va_end(ap);
3399
3400         return buf.buf;
3401 }
3402
3403 static int run_git_checkout(struct replay_opts *opts, const char *commit,
3404                             const char *action)
3405 {
3406         struct child_process cmd = CHILD_PROCESS_INIT;
3407
3408         cmd.git_cmd = 1;
3409
3410         argv_array_push(&cmd.args, "checkout");
3411         argv_array_push(&cmd.args, commit);
3412         argv_array_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3413
3414         if (opts->verbose)
3415                 return run_command(&cmd);
3416         else
3417                 return run_command_silent_on_success(&cmd);
3418 }
3419
3420 int prepare_branch_to_be_rebased(struct replay_opts *opts, const char *commit)
3421 {
3422         const char *action;
3423
3424         if (commit && *commit) {
3425                 action = reflog_message(opts, "start", "checkout %s", commit);
3426                 if (run_git_checkout(opts, commit, action))
3427                         return error(_("could not checkout %s"), commit);
3428         }
3429
3430         return 0;
3431 }
3432
3433 static int checkout_onto(struct replay_opts *opts,
3434                          const char *onto_name, const char *onto,
3435                          const char *orig_head)
3436 {
3437         struct object_id oid;
3438         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3439
3440         if (get_oid(orig_head, &oid))
3441                 return error(_("%s: not a valid OID"), orig_head);
3442
3443         if (run_git_checkout(opts, onto, action)) {
3444                 apply_autostash(opts);
3445                 sequencer_remove_state(opts);
3446                 return error(_("could not detach HEAD"));
3447         }
3448
3449         return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3450 }
3451
3452 static int stopped_at_head(void)
3453 {
3454         struct object_id head;
3455         struct commit *commit;
3456         struct commit_message message;
3457
3458         if (get_oid("HEAD", &head) ||
3459             !(commit = lookup_commit(the_repository, &head)) ||
3460             parse_commit(commit) || get_message(commit, &message))
3461                 fprintf(stderr, _("Stopped at HEAD\n"));
3462         else {
3463                 fprintf(stderr, _("Stopped at %s\n"), message.label);
3464                 free_message(commit, &message);
3465         }
3466         return 0;
3467
3468 }
3469
3470 static const char rescheduled_advice[] =
3471 N_("Could not execute the todo command\n"
3472 "\n"
3473 "    %.*s"
3474 "\n"
3475 "It has been rescheduled; To edit the command before continuing, please\n"
3476 "edit the todo list first:\n"
3477 "\n"
3478 "    git rebase --edit-todo\n"
3479 "    git rebase --continue\n");
3480
3481 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
3482 {
3483         int res = 0, reschedule = 0;
3484
3485         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3486         if (opts->allow_ff)
3487                 assert(!(opts->signoff || opts->no_commit ||
3488                                 opts->record_origin || opts->edit));
3489         if (read_and_refresh_cache(opts))
3490                 return -1;
3491
3492         while (todo_list->current < todo_list->nr) {
3493                 struct todo_item *item = todo_list->items + todo_list->current;
3494                 if (save_todo(todo_list, opts))
3495                         return -1;
3496                 if (is_rebase_i(opts)) {
3497                         if (item->command != TODO_COMMENT) {
3498                                 FILE *f = fopen(rebase_path_msgnum(), "w");
3499
3500                                 todo_list->done_nr++;
3501
3502                                 if (f) {
3503                                         fprintf(f, "%d\n", todo_list->done_nr);
3504                                         fclose(f);
3505                                 }
3506                                 fprintf(stderr, "Rebasing (%d/%d)%s",
3507                                         todo_list->done_nr,
3508                                         todo_list->total_nr,
3509                                         opts->verbose ? "\n" : "\r");
3510                         }
3511                         unlink(rebase_path_message());
3512                         unlink(rebase_path_author_script());
3513                         unlink(rebase_path_stopped_sha());
3514                         unlink(rebase_path_amend());
3515                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3516
3517                         if (item->command == TODO_BREAK)
3518                                 return stopped_at_head();
3519                 }
3520                 if (item->command <= TODO_SQUASH) {
3521                         if (is_rebase_i(opts))
3522                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3523                                         command_to_string(item->command), NULL),
3524                                         1);
3525                         res = do_pick_commit(item->command, item->commit,
3526                                         opts, is_final_fixup(todo_list));
3527                         if (is_rebase_i(opts) && res < 0) {
3528                                 /* Reschedule */
3529                                 advise(_(rescheduled_advice),
3530                                        get_item_line_length(todo_list,
3531                                                             todo_list->current),
3532                                        get_item_line(todo_list,
3533                                                      todo_list->current));
3534                                 todo_list->current--;
3535                                 if (save_todo(todo_list, opts))
3536                                         return -1;
3537                         }
3538                         if (item->command == TODO_EDIT) {
3539                                 struct commit *commit = item->commit;
3540                                 if (!res)
3541                                         fprintf(stderr,
3542                                                 _("Stopped at %s...  %.*s\n"),
3543                                                 short_commit_name(commit),
3544                                                 item->arg_len, item->arg);
3545                                 return error_with_patch(commit,
3546                                         item->arg, item->arg_len, opts, res,
3547                                         !res);
3548                         }
3549                         if (is_rebase_i(opts) && !res)
3550                                 record_in_rewritten(&item->commit->object.oid,
3551                                         peek_command(todo_list, 1));
3552                         if (res && is_fixup(item->command)) {
3553                                 if (res == 1)
3554                                         intend_to_amend();
3555                                 return error_failed_squash(item->commit, opts,
3556                                         item->arg_len, item->arg);
3557                         } else if (res && is_rebase_i(opts) && item->commit) {
3558                                 int to_amend = 0;
3559                                 struct object_id oid;
3560
3561                                 /*
3562                                  * If we are rewording and have either
3563                                  * fast-forwarded already, or are about to
3564                                  * create a new root commit, we want to amend,
3565                                  * otherwise we do not.
3566                                  */
3567                                 if (item->command == TODO_REWORD &&
3568                                     !get_oid("HEAD", &oid) &&
3569                                     (oideq(&item->commit->object.oid, &oid) ||
3570                                      (opts->have_squash_onto &&
3571                                       oideq(&opts->squash_onto, &oid))))
3572                                         to_amend = 1;
3573
3574                                 return res | error_with_patch(item->commit,
3575                                                 item->arg, item->arg_len, opts,
3576                                                 res, to_amend);
3577                         }
3578                 } else if (item->command == TODO_EXEC) {
3579                         char *end_of_arg = (char *)(item->arg + item->arg_len);
3580                         int saved = *end_of_arg;
3581                         struct stat st;
3582
3583                         *end_of_arg = '\0';
3584                         res = do_exec(item->arg);
3585                         *end_of_arg = saved;
3586
3587                         /* Reread the todo file if it has changed. */
3588                         if (res)
3589                                 ; /* fall through */
3590                         else if (stat(get_todo_path(opts), &st))
3591                                 res = error_errno(_("could not stat '%s'"),
3592                                                   get_todo_path(opts));
3593                         else if (match_stat_data(&todo_list->stat, &st)) {
3594                                 todo_list_release(todo_list);
3595                                 if (read_populate_todo(todo_list, opts))
3596                                         res = -1; /* message was printed */
3597                                 /* `current` will be incremented below */
3598                                 todo_list->current = -1;
3599                         }
3600                 } else if (item->command == TODO_LABEL) {
3601                         if ((res = do_label(item->arg, item->arg_len)))
3602                                 reschedule = 1;
3603                 } else if (item->command == TODO_RESET) {
3604                         if ((res = do_reset(item->arg, item->arg_len, opts)))
3605                                 reschedule = 1;
3606                 } else if (item->command == TODO_MERGE) {
3607                         if ((res = do_merge(item->commit,
3608                                             item->arg, item->arg_len,
3609                                             item->flags, opts)) < 0)
3610                                 reschedule = 1;
3611                         else if (item->commit)
3612                                 record_in_rewritten(&item->commit->object.oid,
3613                                                     peek_command(todo_list, 1));
3614                         if (res > 0)
3615                                 /* failed with merge conflicts */
3616                                 return error_with_patch(item->commit,
3617                                                         item->arg,
3618                                                         item->arg_len, opts,
3619                                                         res, 0);
3620                 } else if (!is_noop(item->command))
3621                         return error(_("unknown command %d"), item->command);
3622
3623                 if (reschedule) {
3624                         advise(_(rescheduled_advice),
3625                                get_item_line_length(todo_list,
3626                                                     todo_list->current),
3627                                get_item_line(todo_list, todo_list->current));
3628                         todo_list->current--;
3629                         if (save_todo(todo_list, opts))
3630                                 return -1;
3631                         if (item->commit)
3632                                 return error_with_patch(item->commit,
3633                                                         item->arg,
3634                                                         item->arg_len, opts,
3635                                                         res, 0);
3636                 }
3637
3638                 todo_list->current++;
3639                 if (res)
3640                         return res;
3641         }
3642
3643         if (is_rebase_i(opts)) {
3644                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3645                 struct stat st;
3646
3647                 /* Stopped in the middle, as planned? */
3648                 if (todo_list->current < todo_list->nr)
3649                         return 0;
3650
3651                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3652                                 starts_with(head_ref.buf, "refs/")) {
3653                         const char *msg;
3654                         struct object_id head, orig;
3655                         int res;
3656
3657                         if (get_oid("HEAD", &head)) {
3658                                 res = error(_("cannot read HEAD"));
3659 cleanup_head_ref:
3660                                 strbuf_release(&head_ref);
3661                                 strbuf_release(&buf);
3662                                 return res;
3663                         }
3664                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3665                                         get_oid_hex(buf.buf, &orig)) {
3666                                 res = error(_("could not read orig-head"));
3667                                 goto cleanup_head_ref;
3668                         }
3669                         strbuf_reset(&buf);
3670                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3671                                 res = error(_("could not read 'onto'"));
3672                                 goto cleanup_head_ref;
3673                         }
3674                         msg = reflog_message(opts, "finish", "%s onto %s",
3675                                 head_ref.buf, buf.buf);
3676                         if (update_ref(msg, head_ref.buf, &head, &orig,
3677                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3678                                 res = error(_("could not update %s"),
3679                                         head_ref.buf);
3680                                 goto cleanup_head_ref;
3681                         }
3682                         msg = reflog_message(opts, "finish", "returning to %s",
3683                                 head_ref.buf);
3684                         if (create_symref("HEAD", head_ref.buf, msg)) {
3685                                 res = error(_("could not update HEAD to %s"),
3686                                         head_ref.buf);
3687                                 goto cleanup_head_ref;
3688                         }
3689                         strbuf_reset(&buf);
3690                 }
3691
3692                 if (opts->verbose) {
3693                         struct rev_info log_tree_opt;
3694                         struct object_id orig, head;
3695
3696                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3697                         repo_init_revisions(the_repository, &log_tree_opt, NULL);
3698                         log_tree_opt.diff = 1;
3699                         log_tree_opt.diffopt.output_format =
3700                                 DIFF_FORMAT_DIFFSTAT;
3701                         log_tree_opt.disable_stdin = 1;
3702
3703                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3704                             !get_oid(buf.buf, &orig) &&
3705                             !get_oid("HEAD", &head)) {
3706                                 diff_tree_oid(&orig, &head, "",
3707                                               &log_tree_opt.diffopt);
3708                                 log_tree_diff_flush(&log_tree_opt);
3709                         }
3710                 }
3711                 flush_rewritten_pending();
3712                 if (!stat(rebase_path_rewritten_list(), &st) &&
3713                                 st.st_size > 0) {
3714                         struct child_process child = CHILD_PROCESS_INIT;
3715                         const char *post_rewrite_hook =
3716                                 find_hook("post-rewrite");
3717
3718                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3719                         child.git_cmd = 1;
3720                         argv_array_push(&child.args, "notes");
3721                         argv_array_push(&child.args, "copy");
3722                         argv_array_push(&child.args, "--for-rewrite=rebase");
3723                         /* we don't care if this copying failed */
3724                         run_command(&child);
3725
3726                         if (post_rewrite_hook) {
3727                                 struct child_process hook = CHILD_PROCESS_INIT;
3728
3729                                 hook.in = open(rebase_path_rewritten_list(),
3730                                         O_RDONLY);
3731                                 hook.stdout_to_stderr = 1;
3732                                 argv_array_push(&hook.args, post_rewrite_hook);
3733                                 argv_array_push(&hook.args, "rebase");
3734                                 /* we don't care if this hook failed */
3735                                 run_command(&hook);
3736                         }
3737                 }
3738                 apply_autostash(opts);
3739
3740                 fprintf(stderr, "Successfully rebased and updated %s.\n",
3741                         head_ref.buf);
3742
3743                 strbuf_release(&buf);
3744                 strbuf_release(&head_ref);
3745         }
3746
3747         /*
3748          * Sequence of picks finished successfully; cleanup by
3749          * removing the .git/sequencer directory
3750          */
3751         return sequencer_remove_state(opts);
3752 }
3753
3754 static int continue_single_pick(void)
3755 {
3756         const char *argv[] = { "commit", NULL };
3757
3758         if (!file_exists(git_path_cherry_pick_head(the_repository)) &&
3759             !file_exists(git_path_revert_head(the_repository)))
3760                 return error(_("no cherry-pick or revert in progress"));
3761         return run_command_v_opt(argv, RUN_GIT_CMD);
3762 }
3763
3764 static int commit_staged_changes(struct replay_opts *opts,
3765                                  struct todo_list *todo_list)
3766 {
3767         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3768         unsigned int final_fixup = 0, is_clean;
3769
3770         if (has_unstaged_changes(1))
3771                 return error(_("cannot rebase: You have unstaged changes."));
3772
3773         is_clean = !has_uncommitted_changes(0);
3774
3775         if (file_exists(rebase_path_amend())) {
3776                 struct strbuf rev = STRBUF_INIT;
3777                 struct object_id head, to_amend;
3778
3779                 if (get_oid("HEAD", &head))
3780                         return error(_("cannot amend non-existing commit"));
3781                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3782                         return error(_("invalid file: '%s'"), rebase_path_amend());
3783                 if (get_oid_hex(rev.buf, &to_amend))
3784                         return error(_("invalid contents: '%s'"),
3785                                 rebase_path_amend());
3786                 if (!is_clean && !oideq(&head, &to_amend))
3787                         return error(_("\nYou have uncommitted changes in your "
3788                                        "working tree. Please, commit them\n"
3789                                        "first and then run 'git rebase "
3790                                        "--continue' again."));
3791                 /*
3792                  * When skipping a failed fixup/squash, we need to edit the
3793                  * commit message, the current fixup list and count, and if it
3794                  * was the last fixup/squash in the chain, we need to clean up
3795                  * the commit message and if there was a squash, let the user
3796                  * edit it.
3797                  */
3798                 if (!is_clean || !opts->current_fixup_count)
3799                         ; /* this is not the final fixup */
3800                 else if (!oideq(&head, &to_amend) ||
3801                          !file_exists(rebase_path_stopped_sha())) {
3802                         /* was a final fixup or squash done manually? */
3803                         if (!is_fixup(peek_command(todo_list, 0))) {
3804                                 unlink(rebase_path_fixup_msg());
3805                                 unlink(rebase_path_squash_msg());
3806                                 unlink(rebase_path_current_fixups());
3807                                 strbuf_reset(&opts->current_fixups);
3808                                 opts->current_fixup_count = 0;
3809                         }
3810                 } else {
3811                         /* we are in a fixup/squash chain */
3812                         const char *p = opts->current_fixups.buf;
3813                         int len = opts->current_fixups.len;
3814
3815                         opts->current_fixup_count--;
3816                         if (!len)
3817                                 BUG("Incorrect current_fixups:\n%s", p);
3818                         while (len && p[len - 1] != '\n')
3819                                 len--;
3820                         strbuf_setlen(&opts->current_fixups, len);
3821                         if (write_message(p, len, rebase_path_current_fixups(),
3822                                           0) < 0)
3823                                 return error(_("could not write file: '%s'"),
3824                                              rebase_path_current_fixups());
3825
3826                         /*
3827                          * If a fixup/squash in a fixup/squash chain failed, the
3828                          * commit message is already correct, no need to commit
3829                          * it again.
3830                          *
3831                          * Only if it is the final command in the fixup/squash
3832                          * chain, and only if the chain is longer than a single
3833                          * fixup/squash command (which was just skipped), do we
3834                          * actually need to re-commit with a cleaned up commit
3835                          * message.
3836                          */
3837                         if (opts->current_fixup_count > 0 &&
3838                             !is_fixup(peek_command(todo_list, 0))) {
3839                                 final_fixup = 1;
3840                                 /*
3841                                  * If there was not a single "squash" in the
3842                                  * chain, we only need to clean up the commit
3843                                  * message, no need to bother the user with
3844                                  * opening the commit message in the editor.
3845                                  */
3846                                 if (!starts_with(p, "squash ") &&
3847                                     !strstr(p, "\nsquash "))
3848                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
3849                         } else if (is_fixup(peek_command(todo_list, 0))) {
3850                                 /*
3851                                  * We need to update the squash message to skip
3852                                  * the latest commit message.
3853                                  */
3854                                 struct commit *commit;
3855                                 const char *path = rebase_path_squash_msg();
3856
3857                                 if (parse_head(&commit) ||
3858                                     !(p = get_commit_buffer(commit, NULL)) ||
3859                                     write_message(p, strlen(p), path, 0)) {
3860                                         unuse_commit_buffer(commit, p);
3861                                         return error(_("could not write file: "
3862                                                        "'%s'"), path);
3863                                 }
3864                                 unuse_commit_buffer(commit, p);
3865                         }
3866                 }
3867
3868                 strbuf_release(&rev);
3869                 flags |= AMEND_MSG;
3870         }
3871
3872         if (is_clean) {
3873                 const char *cherry_pick_head = git_path_cherry_pick_head(the_repository);
3874
3875                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3876                         return error(_("could not remove CHERRY_PICK_HEAD"));
3877                 if (!final_fixup)
3878                         return 0;
3879         }
3880
3881         if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
3882                            opts, flags))
3883                 return error(_("could not commit staged changes."));
3884         unlink(rebase_path_amend());
3885         if (final_fixup) {
3886                 unlink(rebase_path_fixup_msg());
3887                 unlink(rebase_path_squash_msg());
3888         }
3889         if (opts->current_fixup_count > 0) {
3890                 /*
3891                  * Whether final fixup or not, we just cleaned up the commit
3892                  * message...
3893                  */
3894                 unlink(rebase_path_current_fixups());
3895                 strbuf_reset(&opts->current_fixups);
3896                 opts->current_fixup_count = 0;
3897         }
3898         return 0;
3899 }
3900
3901 int sequencer_continue(struct replay_opts *opts)
3902 {
3903         struct todo_list todo_list = TODO_LIST_INIT;
3904         int res;
3905
3906         if (read_and_refresh_cache(opts))
3907                 return -1;
3908
3909         if (read_populate_opts(opts))
3910                 return -1;
3911         if (is_rebase_i(opts)) {
3912                 if ((res = read_populate_todo(&todo_list, opts)))
3913                         goto release_todo_list;
3914                 if (commit_staged_changes(opts, &todo_list))
3915                         return -1;
3916         } else if (!file_exists(get_todo_path(opts)))
3917                 return continue_single_pick();
3918         else if ((res = read_populate_todo(&todo_list, opts)))
3919                 goto release_todo_list;
3920
3921         if (!is_rebase_i(opts)) {
3922                 /* Verify that the conflict has been resolved */
3923                 if (file_exists(git_path_cherry_pick_head(the_repository)) ||
3924                     file_exists(git_path_revert_head(the_repository))) {
3925                         res = continue_single_pick();
3926                         if (res)
3927                                 goto release_todo_list;
3928                 }
3929                 if (index_differs_from("HEAD", NULL, 0)) {
3930                         res = error_dirty_index(opts);
3931                         goto release_todo_list;
3932                 }
3933                 todo_list.current++;
3934         } else if (file_exists(rebase_path_stopped_sha())) {
3935                 struct strbuf buf = STRBUF_INIT;
3936                 struct object_id oid;
3937
3938                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3939                     !get_oid_committish(buf.buf, &oid))
3940                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
3941                 strbuf_release(&buf);
3942         }
3943
3944         res = pick_commits(&todo_list, opts);
3945 release_todo_list:
3946         todo_list_release(&todo_list);
3947         return res;
3948 }
3949
3950 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3951 {
3952         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3953         return do_pick_commit(opts->action == REPLAY_PICK ?
3954                 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3955 }
3956
3957 int sequencer_pick_revisions(struct replay_opts *opts)
3958 {
3959         struct todo_list todo_list = TODO_LIST_INIT;
3960         struct object_id oid;
3961         int i, res;
3962
3963         assert(opts->revs);
3964         if (read_and_refresh_cache(opts))
3965                 return -1;
3966
3967         for (i = 0; i < opts->revs->pending.nr; i++) {
3968                 struct object_id oid;
3969                 const char *name = opts->revs->pending.objects[i].name;
3970
3971                 /* This happens when using --stdin. */
3972                 if (!strlen(name))
3973                         continue;
3974
3975                 if (!get_oid(name, &oid)) {
3976                         if (!lookup_commit_reference_gently(the_repository, &oid, 1)) {
3977                                 enum object_type type = oid_object_info(the_repository,
3978                                                                         &oid,
3979                                                                         NULL);
3980                                 return error(_("%s: can't cherry-pick a %s"),
3981                                         name, type_name(type));
3982                         }
3983                 } else
3984                         return error(_("%s: bad revision"), name);
3985         }
3986
3987         /*
3988          * If we were called as "git cherry-pick <commit>", just
3989          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3990          * REVERT_HEAD, and don't touch the sequencer state.
3991          * This means it is possible to cherry-pick in the middle
3992          * of a cherry-pick sequence.
3993          */
3994         if (opts->revs->cmdline.nr == 1 &&
3995             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3996             opts->revs->no_walk &&
3997             !opts->revs->cmdline.rev->flags) {
3998                 struct commit *cmit;
3999                 if (prepare_revision_walk(opts->revs))
4000                         return error(_("revision walk setup failed"));
4001                 cmit = get_revision(opts->revs);
4002                 if (!cmit)
4003                         return error(_("empty commit set passed"));
4004                 if (get_revision(opts->revs))
4005                         BUG("unexpected extra commit from walk");
4006                 return single_pick(cmit, opts);
4007         }
4008
4009         /*
4010          * Start a new cherry-pick/ revert sequence; but
4011          * first, make sure that an existing one isn't in
4012          * progress
4013          */
4014
4015         if (walk_revs_populate_todo(&todo_list, opts) ||
4016                         create_seq_dir() < 0)
4017                 return -1;
4018         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4019                 return error(_("can't revert as initial commit"));
4020         if (save_head(oid_to_hex(&oid)))
4021                 return -1;
4022         if (save_opts(opts))
4023                 return -1;
4024         update_abort_safety_file();
4025         res = pick_commits(&todo_list, opts);
4026         todo_list_release(&todo_list);
4027         return res;
4028 }
4029
4030 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4031 {
4032         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4033         struct strbuf sob = STRBUF_INIT;
4034         int has_footer;
4035
4036         strbuf_addstr(&sob, sign_off_header);
4037         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
4038                                 getenv("GIT_COMMITTER_EMAIL")));
4039         strbuf_addch(&sob, '\n');
4040
4041         if (!ignore_footer)
4042                 strbuf_complete_line(msgbuf);
4043
4044         /*
4045          * If the whole message buffer is equal to the sob, pretend that we
4046          * found a conforming footer with a matching sob
4047          */
4048         if (msgbuf->len - ignore_footer == sob.len &&
4049             !strncmp(msgbuf->buf, sob.buf, sob.len))
4050                 has_footer = 3;
4051         else
4052                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4053
4054         if (!has_footer) {
4055                 const char *append_newlines = NULL;
4056                 size_t len = msgbuf->len - ignore_footer;
4057
4058                 if (!len) {
4059                         /*
4060                          * The buffer is completely empty.  Leave foom for
4061                          * the title and body to be filled in by the user.
4062                          */
4063                         append_newlines = "\n\n";
4064                 } else if (len == 1) {
4065                         /*
4066                          * Buffer contains a single newline.  Add another
4067                          * so that we leave room for the title and body.
4068                          */
4069                         append_newlines = "\n";
4070                 } else if (msgbuf->buf[len - 2] != '\n') {
4071                         /*
4072                          * Buffer ends with a single newline.  Add another
4073                          * so that there is an empty line between the message
4074                          * body and the sob.
4075                          */
4076                         append_newlines = "\n";
4077                 } /* else, the buffer already ends with two newlines. */
4078
4079                 if (append_newlines)
4080                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4081                                 append_newlines, strlen(append_newlines));
4082         }
4083
4084         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4085                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4086                                 sob.buf, sob.len);
4087
4088         strbuf_release(&sob);
4089 }
4090
4091 struct labels_entry {
4092         struct hashmap_entry entry;
4093         char label[FLEX_ARRAY];
4094 };
4095
4096 static int labels_cmp(const void *fndata, const struct labels_entry *a,
4097                       const struct labels_entry *b, const void *key)
4098 {
4099         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4100 }
4101
4102 struct string_entry {
4103         struct oidmap_entry entry;
4104         char string[FLEX_ARRAY];
4105 };
4106
4107 struct label_state {
4108         struct oidmap commit2label;
4109         struct hashmap labels;
4110         struct strbuf buf;
4111 };
4112
4113 static const char *label_oid(struct object_id *oid, const char *label,
4114                              struct label_state *state)
4115 {
4116         struct labels_entry *labels_entry;
4117         struct string_entry *string_entry;
4118         struct object_id dummy;
4119         size_t len;
4120         int i;
4121
4122         string_entry = oidmap_get(&state->commit2label, oid);
4123         if (string_entry)
4124                 return string_entry->string;
4125
4126         /*
4127          * For "uninteresting" commits, i.e. commits that are not to be
4128          * rebased, and which can therefore not be labeled, we use a unique
4129          * abbreviation of the commit name. This is slightly more complicated
4130          * than calling find_unique_abbrev() because we also need to make
4131          * sure that the abbreviation does not conflict with any other
4132          * label.
4133          *
4134          * We disallow "interesting" commits to be labeled by a string that
4135          * is a valid full-length hash, to ensure that we always can find an
4136          * abbreviation for any uninteresting commit's names that does not
4137          * clash with any other label.
4138          */
4139         if (!label) {
4140                 char *p;
4141
4142                 strbuf_reset(&state->buf);
4143                 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
4144                 label = p = state->buf.buf;
4145
4146                 find_unique_abbrev_r(p, oid, default_abbrev);
4147
4148                 /*
4149                  * We may need to extend the abbreviated hash so that there is
4150                  * no conflicting label.
4151                  */
4152                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4153                         size_t i = strlen(p) + 1;
4154
4155                         oid_to_hex_r(p, oid);
4156                         for (; i < GIT_SHA1_HEXSZ; i++) {
4157                                 char save = p[i];
4158                                 p[i] = '\0';
4159                                 if (!hashmap_get_from_hash(&state->labels,
4160                                                            strihash(p), p))
4161                                         break;
4162                                 p[i] = save;
4163                         }
4164                 }
4165         } else if (((len = strlen(label)) == the_hash_algo->hexsz &&
4166                     !get_oid_hex(label, &dummy)) ||
4167                    (len == 1 && *label == '#') ||
4168                    hashmap_get_from_hash(&state->labels,
4169                                          strihash(label), label)) {
4170                 /*
4171                  * If the label already exists, or if the label is a valid full
4172                  * OID, or the label is a '#' (which we use as a separator
4173                  * between merge heads and oneline), we append a dash and a
4174                  * number to make it unique.
4175                  */
4176                 struct strbuf *buf = &state->buf;
4177
4178                 strbuf_reset(buf);
4179                 strbuf_add(buf, label, len);
4180
4181                 for (i = 2; ; i++) {
4182                         strbuf_setlen(buf, len);
4183                         strbuf_addf(buf, "-%d", i);
4184                         if (!hashmap_get_from_hash(&state->labels,
4185                                                    strihash(buf->buf),
4186                                                    buf->buf))
4187                                 break;
4188                 }
4189
4190                 label = buf->buf;
4191         }
4192
4193         FLEX_ALLOC_STR(labels_entry, label, label);
4194         hashmap_entry_init(labels_entry, strihash(label));
4195         hashmap_add(&state->labels, labels_entry);
4196
4197         FLEX_ALLOC_STR(string_entry, string, label);
4198         oidcpy(&string_entry->entry.oid, oid);
4199         oidmap_put(&state->commit2label, string_entry);
4200
4201         return string_entry->string;
4202 }
4203
4204 static int make_script_with_merges(struct pretty_print_context *pp,
4205                                    struct rev_info *revs, FILE *out,
4206                                    unsigned flags)
4207 {
4208         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4209         int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4210         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4211         struct strbuf label = STRBUF_INIT;
4212         struct commit_list *commits = NULL, **tail = &commits, *iter;
4213         struct commit_list *tips = NULL, **tips_tail = &tips;
4214         struct commit *commit;
4215         struct oidmap commit2todo = OIDMAP_INIT;
4216         struct string_entry *entry;
4217         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4218                 shown = OIDSET_INIT;
4219         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4220
4221         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4222         const char *cmd_pick = abbr ? "p" : "pick",
4223                 *cmd_label = abbr ? "l" : "label",
4224                 *cmd_reset = abbr ? "t" : "reset",
4225                 *cmd_merge = abbr ? "m" : "merge";
4226
4227         oidmap_init(&commit2todo, 0);
4228         oidmap_init(&state.commit2label, 0);
4229         hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
4230         strbuf_init(&state.buf, 32);
4231
4232         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4233                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4234                 FLEX_ALLOC_STR(entry, string, "onto");
4235                 oidcpy(&entry->entry.oid, oid);
4236                 oidmap_put(&state.commit2label, entry);
4237         }
4238
4239         /*
4240          * First phase:
4241          * - get onelines for all commits
4242          * - gather all branch tips (i.e. 2nd or later parents of merges)
4243          * - label all branch tips
4244          */
4245         while ((commit = get_revision(revs))) {
4246                 struct commit_list *to_merge;
4247                 const char *p1, *p2;
4248                 struct object_id *oid;
4249                 int is_empty;
4250
4251                 tail = &commit_list_insert(commit, tail)->next;
4252                 oidset_insert(&interesting, &commit->object.oid);
4253
4254                 is_empty = is_original_commit_empty(commit);
4255                 if (!is_empty && (commit->object.flags & PATCHSAME))
4256                         continue;
4257
4258                 strbuf_reset(&oneline);
4259                 pretty_print_commit(pp, commit, &oneline);
4260
4261                 to_merge = commit->parents ? commit->parents->next : NULL;
4262                 if (!to_merge) {
4263                         /* non-merge commit: easy case */
4264                         strbuf_reset(&buf);
4265                         if (!keep_empty && is_empty)
4266                                 strbuf_addf(&buf, "%c ", comment_line_char);
4267                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
4268                                     oid_to_hex(&commit->object.oid),
4269                                     oneline.buf);
4270
4271                         FLEX_ALLOC_STR(entry, string, buf.buf);
4272                         oidcpy(&entry->entry.oid, &commit->object.oid);
4273                         oidmap_put(&commit2todo, entry);
4274
4275                         continue;
4276                 }
4277
4278                 /* Create a label */
4279                 strbuf_reset(&label);
4280                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4281                     (p1 = strchr(p1, '\'')) &&
4282                     (p2 = strchr(++p1, '\'')))
4283                         strbuf_add(&label, p1, p2 - p1);
4284                 else if (skip_prefix(oneline.buf, "Merge pull request ",
4285                                      &p1) &&
4286                          (p1 = strstr(p1, " from ")))
4287                         strbuf_addstr(&label, p1 + strlen(" from "));
4288                 else
4289                         strbuf_addbuf(&label, &oneline);
4290
4291                 for (p1 = label.buf; *p1; p1++)
4292                         if (isspace(*p1))
4293                                 *(char *)p1 = '-';
4294
4295                 strbuf_reset(&buf);
4296                 strbuf_addf(&buf, "%s -C %s",
4297                             cmd_merge, oid_to_hex(&commit->object.oid));
4298
4299                 /* label the tips of merged branches */
4300                 for (; to_merge; to_merge = to_merge->next) {
4301                         oid = &to_merge->item->object.oid;
4302                         strbuf_addch(&buf, ' ');
4303
4304                         if (!oidset_contains(&interesting, oid)) {
4305                                 strbuf_addstr(&buf, label_oid(oid, NULL,
4306                                                               &state));
4307                                 continue;
4308                         }
4309
4310                         tips_tail = &commit_list_insert(to_merge->item,
4311                                                         tips_tail)->next;
4312
4313                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4314                 }
4315                 strbuf_addf(&buf, " # %s", oneline.buf);
4316
4317                 FLEX_ALLOC_STR(entry, string, buf.buf);
4318                 oidcpy(&entry->entry.oid, &commit->object.oid);
4319                 oidmap_put(&commit2todo, entry);
4320         }
4321
4322         /*
4323          * Second phase:
4324          * - label branch points
4325          * - add HEAD to the branch tips
4326          */
4327         for (iter = commits; iter; iter = iter->next) {
4328                 struct commit_list *parent = iter->item->parents;
4329                 for (; parent; parent = parent->next) {
4330                         struct object_id *oid = &parent->item->object.oid;
4331                         if (!oidset_contains(&interesting, oid))
4332                                 continue;
4333                         if (oidset_insert(&child_seen, oid))
4334                                 label_oid(oid, "branch-point", &state);
4335                 }
4336
4337                 /* Add HEAD as implict "tip of branch" */
4338                 if (!iter->next)
4339                         tips_tail = &commit_list_insert(iter->item,
4340                                                         tips_tail)->next;
4341         }
4342
4343         /*
4344          * Third phase: output the todo list. This is a bit tricky, as we
4345          * want to avoid jumping back and forth between revisions. To
4346          * accomplish that goal, we walk backwards from the branch tips,
4347          * gathering commits not yet shown, reversing the list on the fly,
4348          * then outputting that list (labeling revisions as needed).
4349          */
4350         fprintf(out, "%s onto\n", cmd_label);
4351         for (iter = tips; iter; iter = iter->next) {
4352                 struct commit_list *list = NULL, *iter2;
4353
4354                 commit = iter->item;
4355                 if (oidset_contains(&shown, &commit->object.oid))
4356                         continue;
4357                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4358
4359                 if (entry)
4360                         fprintf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4361                 else
4362                         fprintf(out, "\n");
4363
4364                 while (oidset_contains(&interesting, &commit->object.oid) &&
4365                        !oidset_contains(&shown, &commit->object.oid)) {
4366                         commit_list_insert(commit, &list);
4367                         if (!commit->parents) {
4368                                 commit = NULL;
4369                                 break;
4370                         }
4371                         commit = commit->parents->item;
4372                 }
4373
4374                 if (!commit)
4375                         fprintf(out, "%s %s\n", cmd_reset,
4376                                 rebase_cousins ? "onto" : "[new root]");
4377                 else {
4378                         const char *to = NULL;
4379
4380                         entry = oidmap_get(&state.commit2label,
4381                                            &commit->object.oid);
4382                         if (entry)
4383                                 to = entry->string;
4384                         else if (!rebase_cousins)
4385                                 to = label_oid(&commit->object.oid, NULL,
4386                                                &state);
4387
4388                         if (!to || !strcmp(to, "onto"))
4389                                 fprintf(out, "%s onto\n", cmd_reset);
4390                         else {
4391                                 strbuf_reset(&oneline);
4392                                 pretty_print_commit(pp, commit, &oneline);
4393                                 fprintf(out, "%s %s # %s\n",
4394                                         cmd_reset, to, oneline.buf);
4395                         }
4396                 }
4397
4398                 for (iter2 = list; iter2; iter2 = iter2->next) {
4399                         struct object_id *oid = &iter2->item->object.oid;
4400                         entry = oidmap_get(&commit2todo, oid);
4401                         /* only show if not already upstream */
4402                         if (entry)
4403                                 fprintf(out, "%s\n", entry->string);
4404                         entry = oidmap_get(&state.commit2label, oid);
4405                         if (entry)
4406                                 fprintf(out, "%s %s\n",
4407                                         cmd_label, entry->string);
4408                         oidset_insert(&shown, oid);
4409                 }
4410
4411                 free_commit_list(list);
4412         }
4413
4414         free_commit_list(commits);
4415         free_commit_list(tips);
4416
4417         strbuf_release(&label);
4418         strbuf_release(&oneline);
4419         strbuf_release(&buf);
4420
4421         oidmap_free(&commit2todo, 1);
4422         oidmap_free(&state.commit2label, 1);
4423         hashmap_free(&state.labels, 1);
4424         strbuf_release(&state.buf);
4425
4426         return 0;
4427 }
4428
4429 int sequencer_make_script(FILE *out, int argc, const char **argv,
4430                           unsigned flags)
4431 {
4432         char *format = NULL;
4433         struct pretty_print_context pp = {0};
4434         struct strbuf buf = STRBUF_INIT;
4435         struct rev_info revs;
4436         struct commit *commit;
4437         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4438         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4439         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4440
4441         repo_init_revisions(the_repository, &revs, NULL);
4442         revs.verbose_header = 1;
4443         if (!rebase_merges)
4444                 revs.max_parents = 1;
4445         revs.cherry_mark = 1;
4446         revs.limited = 1;
4447         revs.reverse = 1;
4448         revs.right_only = 1;
4449         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4450         revs.topo_order = 1;
4451
4452         revs.pretty_given = 1;
4453         git_config_get_string("rebase.instructionFormat", &format);
4454         if (!format || !*format) {
4455                 free(format);
4456                 format = xstrdup("%s");
4457         }
4458         get_commit_format(format, &revs);
4459         free(format);
4460         pp.fmt = revs.commit_format;
4461         pp.output_encoding = get_log_output_encoding();
4462
4463         if (setup_revisions(argc, argv, &revs, NULL) > 1)
4464                 return error(_("make_script: unhandled options"));
4465
4466         if (prepare_revision_walk(&revs) < 0)
4467                 return error(_("make_script: error preparing revisions"));
4468
4469         if (rebase_merges)
4470                 return make_script_with_merges(&pp, &revs, out, flags);
4471
4472         while ((commit = get_revision(&revs))) {
4473                 int is_empty  = is_original_commit_empty(commit);
4474
4475                 if (!is_empty && (commit->object.flags & PATCHSAME))
4476                         continue;
4477                 strbuf_reset(&buf);
4478                 if (!keep_empty && is_empty)
4479                         strbuf_addf(&buf, "%c ", comment_line_char);
4480                 strbuf_addf(&buf, "%s %s ", insn,
4481                             oid_to_hex(&commit->object.oid));
4482                 pretty_print_commit(&pp, commit, &buf);
4483                 strbuf_addch(&buf, '\n');
4484                 fputs(buf.buf, out);
4485         }
4486         strbuf_release(&buf);
4487         return 0;
4488 }
4489
4490 /*
4491  * Add commands after pick and (series of) squash/fixup commands
4492  * in the todo list.
4493  */
4494 int sequencer_add_exec_commands(const char *commands)
4495 {
4496         const char *todo_file = rebase_path_todo();
4497         struct todo_list todo_list = TODO_LIST_INIT;
4498         struct strbuf *buf = &todo_list.buf;
4499         size_t offset = 0, commands_len = strlen(commands);
4500         int i, insert;
4501
4502         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4503                 return error(_("could not read '%s'."), todo_file);
4504
4505         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4506                 todo_list_release(&todo_list);
4507                 return error(_("unusable todo list: '%s'"), todo_file);
4508         }
4509
4510         /*
4511          * Insert <commands> after every pick. Here, fixup/squash chains
4512          * are considered part of the pick, so we insert the commands *after*
4513          * those chains if there are any.
4514          */
4515         insert = -1;
4516         for (i = 0; i < todo_list.nr; i++) {
4517                 enum todo_command command = todo_list.items[i].command;
4518
4519                 if (insert >= 0) {
4520                         /* skip fixup/squash chains */
4521                         if (command == TODO_COMMENT)
4522                                 continue;
4523                         else if (is_fixup(command)) {
4524                                 insert = i + 1;
4525                                 continue;
4526                         }
4527                         strbuf_insert(buf,
4528                                       todo_list.items[insert].offset_in_buf +
4529                                       offset, commands, commands_len);
4530                         offset += commands_len;
4531                         insert = -1;
4532                 }
4533
4534                 if (command == TODO_PICK || command == TODO_MERGE)
4535                         insert = i + 1;
4536         }
4537
4538         /* insert or append final <commands> */
4539         if (insert >= 0 && insert < todo_list.nr)
4540                 strbuf_insert(buf, todo_list.items[insert].offset_in_buf +
4541                               offset, commands, commands_len);
4542         else if (insert >= 0 || !offset)
4543                 strbuf_add(buf, commands, commands_len);
4544
4545         i = write_message(buf->buf, buf->len, todo_file, 0);
4546         todo_list_release(&todo_list);
4547         return i;
4548 }
4549
4550 int transform_todos(unsigned flags)
4551 {
4552         const char *todo_file = rebase_path_todo();
4553         struct todo_list todo_list = TODO_LIST_INIT;
4554         struct strbuf buf = STRBUF_INIT;
4555         struct todo_item *item;
4556         int i;
4557
4558         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
4559                 return error(_("could not read '%s'."), todo_file);
4560
4561         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
4562                 todo_list_release(&todo_list);
4563                 return error(_("unusable todo list: '%s'"), todo_file);
4564         }
4565
4566         for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
4567                 /* if the item is not a command write it and continue */
4568                 if (item->command >= TODO_COMMENT) {
4569                         strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
4570                         continue;
4571                 }
4572
4573                 /* add command to the buffer */
4574                 if (flags & TODO_LIST_ABBREVIATE_CMDS)
4575                         strbuf_addch(&buf, command_to_char(item->command));
4576                 else
4577                         strbuf_addstr(&buf, command_to_string(item->command));
4578
4579                 /* add commit id */
4580                 if (item->commit) {
4581                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
4582                                           short_commit_name(item->commit) :
4583                                           oid_to_hex(&item->commit->object.oid);
4584
4585                         if (item->command == TODO_MERGE) {
4586                                 if (item->flags & TODO_EDIT_MERGE_MSG)
4587                                         strbuf_addstr(&buf, " -c");
4588                                 else
4589                                         strbuf_addstr(&buf, " -C");
4590                         }
4591
4592                         strbuf_addf(&buf, " %s", oid);
4593                 }
4594
4595                 /* add all the rest */
4596                 if (!item->arg_len)
4597                         strbuf_addch(&buf, '\n');
4598                 else
4599                         strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
4600         }
4601
4602         i = write_message(buf.buf, buf.len, todo_file, 0);
4603         todo_list_release(&todo_list);
4604         return i;
4605 }
4606
4607 enum missing_commit_check_level get_missing_commit_check_level(void)
4608 {
4609         const char *value;
4610
4611         if (git_config_get_value("rebase.missingcommitscheck", &value) ||
4612                         !strcasecmp("ignore", value))
4613                 return MISSING_COMMIT_CHECK_IGNORE;
4614         if (!strcasecmp("warn", value))
4615                 return MISSING_COMMIT_CHECK_WARN;
4616         if (!strcasecmp("error", value))
4617                 return MISSING_COMMIT_CHECK_ERROR;
4618         warning(_("unrecognized setting %s for option "
4619                   "rebase.missingCommitsCheck. Ignoring."), value);
4620         return MISSING_COMMIT_CHECK_IGNORE;
4621 }
4622
4623 define_commit_slab(commit_seen, unsigned char);
4624 /*
4625  * Check if the user dropped some commits by mistake
4626  * Behaviour determined by rebase.missingCommitsCheck.
4627  * Check if there is an unrecognized command or a
4628  * bad SHA-1 in a command.
4629  */
4630 int check_todo_list(void)
4631 {
4632         enum missing_commit_check_level check_level = get_missing_commit_check_level();
4633         struct strbuf todo_file = STRBUF_INIT;
4634         struct todo_list todo_list = TODO_LIST_INIT;
4635         struct strbuf missing = STRBUF_INIT;
4636         int advise_to_edit_todo = 0, res = 0, i;
4637         struct commit_seen commit_seen;
4638
4639         init_commit_seen(&commit_seen);
4640
4641         strbuf_addstr(&todo_file, rebase_path_todo());
4642         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4643                 res = -1;
4644                 goto leave_check;
4645         }
4646         advise_to_edit_todo = res =
4647                 parse_insn_buffer(todo_list.buf.buf, &todo_list);
4648
4649         if (res || check_level == MISSING_COMMIT_CHECK_IGNORE)
4650                 goto leave_check;
4651
4652         /* Mark the commits in git-rebase-todo as seen */
4653         for (i = 0; i < todo_list.nr; i++) {
4654                 struct commit *commit = todo_list.items[i].commit;
4655                 if (commit)
4656                         *commit_seen_at(&commit_seen, commit) = 1;
4657         }
4658
4659         todo_list_release(&todo_list);
4660         strbuf_addstr(&todo_file, ".backup");
4661         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4662                 res = -1;
4663                 goto leave_check;
4664         }
4665         strbuf_release(&todo_file);
4666         res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4667
4668         /* Find commits in git-rebase-todo.backup yet unseen */
4669         for (i = todo_list.nr - 1; i >= 0; i--) {
4670                 struct todo_item *item = todo_list.items + i;
4671                 struct commit *commit = item->commit;
4672                 if (commit && !*commit_seen_at(&commit_seen, commit)) {
4673                         strbuf_addf(&missing, " - %s %.*s\n",
4674                                     short_commit_name(commit),
4675                                     item->arg_len, item->arg);
4676                         *commit_seen_at(&commit_seen, commit) = 1;
4677                 }
4678         }
4679
4680         /* Warn about missing commits */
4681         if (!missing.len)
4682                 goto leave_check;
4683
4684         if (check_level == MISSING_COMMIT_CHECK_ERROR)
4685                 advise_to_edit_todo = res = 1;
4686
4687         fprintf(stderr,
4688                 _("Warning: some commits may have been dropped accidentally.\n"
4689                 "Dropped commits (newer to older):\n"));
4690
4691         /* Make the list user-friendly and display */
4692         fputs(missing.buf, stderr);
4693         strbuf_release(&missing);
4694
4695         fprintf(stderr, _("To avoid this message, use \"drop\" to "
4696                 "explicitly remove a commit.\n\n"
4697                 "Use 'git config rebase.missingCommitsCheck' to change "
4698                 "the level of warnings.\n"
4699                 "The possible behaviours are: ignore, warn, error.\n\n"));
4700
4701 leave_check:
4702         clear_commit_seen(&commit_seen);
4703         strbuf_release(&todo_file);
4704         todo_list_release(&todo_list);
4705
4706         if (advise_to_edit_todo)
4707                 fprintf(stderr,
4708                         _("You can fix this with 'git rebase --edit-todo' "
4709                           "and then run 'git rebase --continue'.\n"
4710                           "Or you can abort the rebase with 'git rebase"
4711                           " --abort'.\n"));
4712
4713         return res;
4714 }
4715
4716 static int rewrite_file(const char *path, const char *buf, size_t len)
4717 {
4718         int rc = 0;
4719         int fd = open(path, O_WRONLY | O_TRUNC);
4720         if (fd < 0)
4721                 return error_errno(_("could not open '%s' for writing"), path);
4722         if (write_in_full(fd, buf, len) < 0)
4723                 rc = error_errno(_("could not write to '%s'"), path);
4724         if (close(fd) && !rc)
4725                 rc = error_errno(_("could not close '%s'"), path);
4726         return rc;
4727 }
4728
4729 /* skip picking commits whose parents are unchanged */
4730 static int skip_unnecessary_picks(struct object_id *output_oid)
4731 {
4732         const char *todo_file = rebase_path_todo();
4733         struct strbuf buf = STRBUF_INIT;
4734         struct todo_list todo_list = TODO_LIST_INIT;
4735         struct object_id *parent_oid;
4736         int fd, i;
4737
4738         if (!read_oneliner(&buf, rebase_path_onto(), 0))
4739                 return error(_("could not read 'onto'"));
4740         if (get_oid(buf.buf, output_oid)) {
4741                 strbuf_release(&buf);
4742                 return error(_("need a HEAD to fixup"));
4743         }
4744         strbuf_release(&buf);
4745
4746         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4747                 return -1;
4748         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4749                 todo_list_release(&todo_list);
4750                 return -1;
4751         }
4752
4753         for (i = 0; i < todo_list.nr; i++) {
4754                 struct todo_item *item = todo_list.items + i;
4755
4756                 if (item->command >= TODO_NOOP)
4757                         continue;
4758                 if (item->command != TODO_PICK)
4759                         break;
4760                 if (parse_commit(item->commit)) {
4761                         todo_list_release(&todo_list);
4762                         return error(_("could not parse commit '%s'"),
4763                                 oid_to_hex(&item->commit->object.oid));
4764                 }
4765                 if (!item->commit->parents)
4766                         break; /* root commit */
4767                 if (item->commit->parents->next)
4768                         break; /* merge commit */
4769                 parent_oid = &item->commit->parents->item->object.oid;
4770                 if (!oideq(parent_oid, output_oid))
4771                         break;
4772                 oidcpy(output_oid, &item->commit->object.oid);
4773         }
4774         if (i > 0) {
4775                 int offset = get_item_line_offset(&todo_list, i);
4776                 const char *done_path = rebase_path_done();
4777
4778                 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4779                 if (fd < 0) {
4780                         error_errno(_("could not open '%s' for writing"),
4781                                     done_path);
4782                         todo_list_release(&todo_list);
4783                         return -1;
4784                 }
4785                 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4786                         error_errno(_("could not write to '%s'"), done_path);
4787                         todo_list_release(&todo_list);
4788                         close(fd);
4789                         return -1;
4790                 }
4791                 close(fd);
4792
4793                 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4794                                  todo_list.buf.len - offset) < 0) {
4795                         todo_list_release(&todo_list);
4796                         return -1;
4797                 }
4798
4799                 todo_list.current = i;
4800                 if (is_fixup(peek_command(&todo_list, 0)))
4801                         record_in_rewritten(output_oid, peek_command(&todo_list, 0));
4802         }
4803
4804         todo_list_release(&todo_list);
4805
4806         return 0;
4807 }
4808
4809 int complete_action(struct replay_opts *opts, unsigned flags,
4810                     const char *shortrevisions, const char *onto_name,
4811                     const char *onto, const char *orig_head, const char *cmd,
4812                     unsigned autosquash)
4813 {
4814         const char *shortonto, *todo_file = rebase_path_todo();
4815         struct todo_list todo_list = TODO_LIST_INIT;
4816         struct strbuf *buf = &(todo_list.buf);
4817         struct object_id oid;
4818         struct stat st;
4819
4820         get_oid(onto, &oid);
4821         shortonto = find_unique_abbrev(&oid, DEFAULT_ABBREV);
4822
4823         if (!lstat(todo_file, &st) && st.st_size == 0 &&
4824             write_message("noop\n", 5, todo_file, 0))
4825                 return -1;
4826
4827         if (autosquash && rearrange_squash())
4828                 return -1;
4829
4830         if (cmd && *cmd)
4831                 sequencer_add_exec_commands(cmd);
4832
4833         if (strbuf_read_file(buf, todo_file, 0) < 0)
4834                 return error_errno(_("could not read '%s'."), todo_file);
4835
4836         if (parse_insn_buffer(buf->buf, &todo_list)) {
4837                 todo_list_release(&todo_list);
4838                 return error(_("unusable todo list: '%s'"), todo_file);
4839         }
4840
4841         if (count_commands(&todo_list) == 0) {
4842                 apply_autostash(opts);
4843                 sequencer_remove_state(opts);
4844                 todo_list_release(&todo_list);
4845
4846                 return error(_("nothing to do"));
4847         }
4848
4849         strbuf_addch(buf, '\n');
4850         strbuf_commented_addf(buf, Q_("Rebase %s onto %s (%d command)",
4851                                       "Rebase %s onto %s (%d commands)",
4852                                       count_commands(&todo_list)),
4853                               shortrevisions, shortonto, count_commands(&todo_list));
4854         append_todo_help(0, flags & TODO_LIST_KEEP_EMPTY, buf);
4855
4856         if (write_message(buf->buf, buf->len, todo_file, 0)) {
4857                 todo_list_release(&todo_list);
4858                 return -1;
4859         }
4860
4861         if (copy_file(rebase_path_todo_backup(), todo_file, 0666))
4862                 return error(_("could not copy '%s' to '%s'."), todo_file,
4863                              rebase_path_todo_backup());
4864
4865         if (transform_todos(flags | TODO_LIST_SHORTEN_IDS))
4866                 return error(_("could not transform the todo list"));
4867
4868         strbuf_reset(buf);
4869
4870         if (launch_sequence_editor(todo_file, buf, NULL)) {
4871                 apply_autostash(opts);
4872                 sequencer_remove_state(opts);
4873                 todo_list_release(&todo_list);
4874
4875                 return -1;
4876         }
4877
4878         strbuf_stripspace(buf, 1);
4879         if (buf->len == 0) {
4880                 apply_autostash(opts);
4881                 sequencer_remove_state(opts);
4882                 todo_list_release(&todo_list);
4883
4884                 return error(_("nothing to do"));
4885         }
4886
4887         todo_list_release(&todo_list);
4888
4889         if (check_todo_list()) {
4890                 checkout_onto(opts, onto_name, onto, orig_head);
4891                 return -1;
4892         }
4893
4894         if (transform_todos(flags & ~(TODO_LIST_SHORTEN_IDS)))
4895                 return error(_("could not transform the todo list"));
4896
4897         if (opts->allow_ff && skip_unnecessary_picks(&oid))
4898                 return error(_("could not skip unnecessary pick commands"));
4899
4900         if (checkout_onto(opts, onto_name, oid_to_hex(&oid), orig_head))
4901                 return -1;
4902
4903         if (require_clean_work_tree("rebase", "", 1, 1))
4904                 return -1;
4905
4906         return sequencer_continue(opts);
4907 }
4908
4909 struct subject2item_entry {
4910         struct hashmap_entry entry;
4911         int i;
4912         char subject[FLEX_ARRAY];
4913 };
4914
4915 static int subject2item_cmp(const void *fndata,
4916                             const struct subject2item_entry *a,
4917                             const struct subject2item_entry *b, const void *key)
4918 {
4919         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4920 }
4921
4922 define_commit_slab(commit_todo_item, struct todo_item *);
4923
4924 /*
4925  * Rearrange the todo list that has both "pick commit-id msg" and "pick
4926  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4927  * after the former, and change "pick" to "fixup"/"squash".
4928  *
4929  * Note that if the config has specified a custom instruction format, each log
4930  * message will have to be retrieved from the commit (as the oneline in the
4931  * script cannot be trusted) in order to normalize the autosquash arrangement.
4932  */
4933 int rearrange_squash(void)
4934 {
4935         const char *todo_file = rebase_path_todo();
4936         struct todo_list todo_list = TODO_LIST_INIT;
4937         struct hashmap subject2item;
4938         int res = 0, rearranged = 0, *next, *tail, i;
4939         char **subjects;
4940         struct commit_todo_item commit_todo;
4941
4942         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4943                 return -1;
4944         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4945                 todo_list_release(&todo_list);
4946                 return -1;
4947         }
4948
4949         init_commit_todo_item(&commit_todo);
4950         /*
4951          * The hashmap maps onelines to the respective todo list index.
4952          *
4953          * If any items need to be rearranged, the next[i] value will indicate
4954          * which item was moved directly after the i'th.
4955          *
4956          * In that case, last[i] will indicate the index of the latest item to
4957          * be moved to appear after the i'th.
4958          */
4959         hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4960                      NULL, todo_list.nr);
4961         ALLOC_ARRAY(next, todo_list.nr);
4962         ALLOC_ARRAY(tail, todo_list.nr);
4963         ALLOC_ARRAY(subjects, todo_list.nr);
4964         for (i = 0; i < todo_list.nr; i++) {
4965                 struct strbuf buf = STRBUF_INIT;
4966                 struct todo_item *item = todo_list.items + i;
4967                 const char *commit_buffer, *subject, *p;
4968                 size_t subject_len;
4969                 int i2 = -1;
4970                 struct subject2item_entry *entry;
4971
4972                 next[i] = tail[i] = -1;
4973                 if (!item->commit || item->command == TODO_DROP) {
4974                         subjects[i] = NULL;
4975                         continue;
4976                 }
4977
4978                 if (is_fixup(item->command)) {
4979                         todo_list_release(&todo_list);
4980                         clear_commit_todo_item(&commit_todo);
4981                         return error(_("the script was already rearranged."));
4982                 }
4983
4984                 *commit_todo_item_at(&commit_todo, item->commit) = item;
4985
4986                 parse_commit(item->commit);
4987                 commit_buffer = get_commit_buffer(item->commit, NULL);
4988                 find_commit_subject(commit_buffer, &subject);
4989                 format_subject(&buf, subject, " ");
4990                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4991                 unuse_commit_buffer(item->commit, commit_buffer);
4992                 if ((skip_prefix(subject, "fixup! ", &p) ||
4993                      skip_prefix(subject, "squash! ", &p))) {
4994                         struct commit *commit2;
4995
4996                         for (;;) {
4997                                 while (isspace(*p))
4998                                         p++;
4999                                 if (!skip_prefix(p, "fixup! ", &p) &&
5000                                     !skip_prefix(p, "squash! ", &p))
5001                                         break;
5002                         }
5003
5004                         if ((entry = hashmap_get_from_hash(&subject2item,
5005                                                            strhash(p), p)))
5006                                 /* found by title */
5007                                 i2 = entry->i;
5008                         else if (!strchr(p, ' ') &&
5009                                  (commit2 =
5010                                   lookup_commit_reference_by_name(p)) &&
5011                                  *commit_todo_item_at(&commit_todo, commit2))
5012                                 /* found by commit name */
5013                                 i2 = *commit_todo_item_at(&commit_todo, commit2)
5014                                         - todo_list.items;
5015                         else {
5016                                 /* copy can be a prefix of the commit subject */
5017                                 for (i2 = 0; i2 < i; i2++)
5018                                         if (subjects[i2] &&
5019                                             starts_with(subjects[i2], p))
5020                                                 break;
5021                                 if (i2 == i)
5022                                         i2 = -1;
5023                         }
5024                 }
5025                 if (i2 >= 0) {
5026                         rearranged = 1;
5027                         todo_list.items[i].command =
5028                                 starts_with(subject, "fixup!") ?
5029                                 TODO_FIXUP : TODO_SQUASH;
5030                         if (next[i2] < 0)
5031                                 next[i2] = i;
5032                         else
5033                                 next[tail[i2]] = i;
5034                         tail[i2] = i;
5035                 } else if (!hashmap_get_from_hash(&subject2item,
5036                                                 strhash(subject), subject)) {
5037                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5038                         entry->i = i;
5039                         hashmap_entry_init(entry, strhash(entry->subject));
5040                         hashmap_put(&subject2item, entry);
5041                 }
5042         }
5043
5044         if (rearranged) {
5045                 struct strbuf buf = STRBUF_INIT;
5046
5047                 for (i = 0; i < todo_list.nr; i++) {
5048                         enum todo_command command = todo_list.items[i].command;
5049                         int cur = i;
5050
5051                         /*
5052                          * Initially, all commands are 'pick's. If it is a
5053                          * fixup or a squash now, we have rearranged it.
5054                          */
5055                         if (is_fixup(command))
5056                                 continue;
5057
5058                         while (cur >= 0) {
5059                                 const char *bol =
5060                                         get_item_line(&todo_list, cur);
5061                                 const char *eol =
5062                                         get_item_line(&todo_list, cur + 1);
5063
5064                                 /* replace 'pick', by 'fixup' or 'squash' */
5065                                 command = todo_list.items[cur].command;
5066                                 if (is_fixup(command)) {
5067                                         strbuf_addstr(&buf,
5068                                                 todo_command_info[command].str);
5069                                         bol += strcspn(bol, " \t");
5070                                 }
5071
5072                                 strbuf_add(&buf, bol, eol - bol);
5073
5074                                 cur = next[cur];
5075                         }
5076                 }
5077
5078                 res = rewrite_file(todo_file, buf.buf, buf.len);
5079                 strbuf_release(&buf);
5080         }
5081
5082         free(next);
5083         free(tail);
5084         for (i = 0; i < todo_list.nr; i++)
5085                 free(subjects[i]);
5086         free(subjects);
5087         hashmap_free(&subject2item, 1);
5088         todo_list_release(&todo_list);
5089
5090         clear_commit_todo_item(&commit_todo);
5091         return res;
5092 }