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