sequencer: make refs generated by the `label` command worktree-local
[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         for (j = bases; j; j = j->next)
2814                 commit_list_insert(j->item, &reversed);
2815         free_commit_list(bases);
2816
2817         read_cache();
2818         init_merge_options(&o);
2819         o.branch1 = "HEAD";
2820         o.branch2 = ref_name.buf;
2821         o.buffer_output = 2;
2822
2823         ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
2824         if (ret <= 0)
2825                 fputs(o.obuf.buf, stdout);
2826         strbuf_release(&o.obuf);
2827         if (ret < 0) {
2828                 error(_("could not even attempt to merge '%.*s'"),
2829                       merge_arg_len, arg);
2830                 goto leave_merge;
2831         }
2832         /*
2833          * The return value of merge_recursive() is 1 on clean, and 0 on
2834          * unclean merge.
2835          *
2836          * Let's reverse that, so that do_merge() returns 0 upon success and
2837          * 1 upon failed merge (keeping the return value -1 for the cases where
2838          * we will want to reschedule the `merge` command).
2839          */
2840         ret = !ret;
2841
2842         if (active_cache_changed &&
2843             write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
2844                 ret = error(_("merge: Unable to write new index file"));
2845                 goto leave_merge;
2846         }
2847
2848         rollback_lock_file(&lock);
2849         if (ret)
2850                 rerere(opts->allow_rerere_auto);
2851         else
2852                 /*
2853                  * In case of problems, we now want to return a positive
2854                  * value (a negative one would indicate that the `merge`
2855                  * command needs to be rescheduled).
2856                  */
2857                 ret = !!run_git_commit(git_path_merge_msg(), opts,
2858                                      run_commit_flags);
2859
2860 leave_merge:
2861         strbuf_release(&ref_name);
2862         rollback_lock_file(&lock);
2863         return ret;
2864 }
2865
2866 static int is_final_fixup(struct todo_list *todo_list)
2867 {
2868         int i = todo_list->current;
2869
2870         if (!is_fixup(todo_list->items[i].command))
2871                 return 0;
2872
2873         while (++i < todo_list->nr)
2874                 if (is_fixup(todo_list->items[i].command))
2875                         return 0;
2876                 else if (!is_noop(todo_list->items[i].command))
2877                         break;
2878         return 1;
2879 }
2880
2881 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
2882 {
2883         int i;
2884
2885         for (i = todo_list->current + offset; i < todo_list->nr; i++)
2886                 if (!is_noop(todo_list->items[i].command))
2887                         return todo_list->items[i].command;
2888
2889         return -1;
2890 }
2891
2892 static int apply_autostash(struct replay_opts *opts)
2893 {
2894         struct strbuf stash_sha1 = STRBUF_INIT;
2895         struct child_process child = CHILD_PROCESS_INIT;
2896         int ret = 0;
2897
2898         if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
2899                 strbuf_release(&stash_sha1);
2900                 return 0;
2901         }
2902         strbuf_trim(&stash_sha1);
2903
2904         child.git_cmd = 1;
2905         child.no_stdout = 1;
2906         child.no_stderr = 1;
2907         argv_array_push(&child.args, "stash");
2908         argv_array_push(&child.args, "apply");
2909         argv_array_push(&child.args, stash_sha1.buf);
2910         if (!run_command(&child))
2911                 fprintf(stderr, _("Applied autostash.\n"));
2912         else {
2913                 struct child_process store = CHILD_PROCESS_INIT;
2914
2915                 store.git_cmd = 1;
2916                 argv_array_push(&store.args, "stash");
2917                 argv_array_push(&store.args, "store");
2918                 argv_array_push(&store.args, "-m");
2919                 argv_array_push(&store.args, "autostash");
2920                 argv_array_push(&store.args, "-q");
2921                 argv_array_push(&store.args, stash_sha1.buf);
2922                 if (run_command(&store))
2923                         ret = error(_("cannot store %s"), stash_sha1.buf);
2924                 else
2925                         fprintf(stderr,
2926                                 _("Applying autostash resulted in conflicts.\n"
2927                                   "Your changes are safe in the stash.\n"
2928                                   "You can run \"git stash pop\" or"
2929                                   " \"git stash drop\" at any time.\n"));
2930         }
2931
2932         strbuf_release(&stash_sha1);
2933         return ret;
2934 }
2935
2936 static const char *reflog_message(struct replay_opts *opts,
2937         const char *sub_action, const char *fmt, ...)
2938 {
2939         va_list ap;
2940         static struct strbuf buf = STRBUF_INIT;
2941
2942         va_start(ap, fmt);
2943         strbuf_reset(&buf);
2944         strbuf_addstr(&buf, action_name(opts));
2945         if (sub_action)
2946                 strbuf_addf(&buf, " (%s)", sub_action);
2947         if (fmt) {
2948                 strbuf_addstr(&buf, ": ");
2949                 strbuf_vaddf(&buf, fmt, ap);
2950         }
2951         va_end(ap);
2952
2953         return buf.buf;
2954 }
2955
2956 static const char rescheduled_advice[] =
2957 N_("Could not execute the todo command\n"
2958 "\n"
2959 "    %.*s"
2960 "\n"
2961 "It has been rescheduled; To edit the command before continuing, please\n"
2962 "edit the todo list first:\n"
2963 "\n"
2964 "    git rebase --edit-todo\n"
2965 "    git rebase --continue\n");
2966
2967 static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2968 {
2969         int res = 0, reschedule = 0;
2970
2971         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2972         if (opts->allow_ff)
2973                 assert(!(opts->signoff || opts->no_commit ||
2974                                 opts->record_origin || opts->edit));
2975         if (read_and_refresh_cache(opts))
2976                 return -1;
2977
2978         while (todo_list->current < todo_list->nr) {
2979                 struct todo_item *item = todo_list->items + todo_list->current;
2980                 if (save_todo(todo_list, opts))
2981                         return -1;
2982                 if (is_rebase_i(opts)) {
2983                         if (item->command != TODO_COMMENT) {
2984                                 FILE *f = fopen(rebase_path_msgnum(), "w");
2985
2986                                 todo_list->done_nr++;
2987
2988                                 if (f) {
2989                                         fprintf(f, "%d\n", todo_list->done_nr);
2990                                         fclose(f);
2991                                 }
2992                                 fprintf(stderr, "Rebasing (%d/%d)%s",
2993                                         todo_list->done_nr,
2994                                         todo_list->total_nr,
2995                                         opts->verbose ? "\n" : "\r");
2996                         }
2997                         unlink(rebase_path_message());
2998                         unlink(rebase_path_author_script());
2999                         unlink(rebase_path_stopped_sha());
3000                         unlink(rebase_path_amend());
3001                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3002                 }
3003                 if (item->command <= TODO_SQUASH) {
3004                         if (is_rebase_i(opts))
3005                                 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
3006                                         command_to_string(item->command), NULL),
3007                                         1);
3008                         res = do_pick_commit(item->command, item->commit,
3009                                         opts, is_final_fixup(todo_list));
3010                         if (is_rebase_i(opts) && res < 0) {
3011                                 /* Reschedule */
3012                                 advise(_(rescheduled_advice),
3013                                        get_item_line_length(todo_list,
3014                                                             todo_list->current),
3015                                        get_item_line(todo_list,
3016                                                      todo_list->current));
3017                                 todo_list->current--;
3018                                 if (save_todo(todo_list, opts))
3019                                         return -1;
3020                         }
3021                         if (item->command == TODO_EDIT) {
3022                                 struct commit *commit = item->commit;
3023                                 if (!res)
3024                                         fprintf(stderr,
3025                                                 _("Stopped at %s...  %.*s\n"),
3026                                                 short_commit_name(commit),
3027                                                 item->arg_len, item->arg);
3028                                 return error_with_patch(commit,
3029                                         item->arg, item->arg_len, opts, res,
3030                                         !res);
3031                         }
3032                         if (is_rebase_i(opts) && !res)
3033                                 record_in_rewritten(&item->commit->object.oid,
3034                                         peek_command(todo_list, 1));
3035                         if (res && is_fixup(item->command)) {
3036                                 if (res == 1)
3037                                         intend_to_amend();
3038                                 return error_failed_squash(item->commit, opts,
3039                                         item->arg_len, item->arg);
3040                         } else if (res && is_rebase_i(opts) && item->commit)
3041                                 return res | error_with_patch(item->commit,
3042                                         item->arg, item->arg_len, opts, res,
3043                                         item->command == TODO_REWORD);
3044                 } else if (item->command == TODO_EXEC) {
3045                         char *end_of_arg = (char *)(item->arg + item->arg_len);
3046                         int saved = *end_of_arg;
3047                         struct stat st;
3048
3049                         *end_of_arg = '\0';
3050                         res = do_exec(item->arg);
3051                         *end_of_arg = saved;
3052
3053                         /* Reread the todo file if it has changed. */
3054                         if (res)
3055                                 ; /* fall through */
3056                         else if (stat(get_todo_path(opts), &st))
3057                                 res = error_errno(_("could not stat '%s'"),
3058                                                   get_todo_path(opts));
3059                         else if (match_stat_data(&todo_list->stat, &st)) {
3060                                 todo_list_release(todo_list);
3061                                 if (read_populate_todo(todo_list, opts))
3062                                         res = -1; /* message was printed */
3063                                 /* `current` will be incremented below */
3064                                 todo_list->current = -1;
3065                         }
3066                 } else if (item->command == TODO_LABEL) {
3067                         if ((res = do_label(item->arg, item->arg_len)))
3068                                 reschedule = 1;
3069                 } else if (item->command == TODO_RESET) {
3070                         if ((res = do_reset(item->arg, item->arg_len, opts)))
3071                                 reschedule = 1;
3072                 } else if (item->command == TODO_MERGE) {
3073                         if ((res = do_merge(item->commit,
3074                                             item->arg, item->arg_len,
3075                                             item->flags, opts)) < 0)
3076                                 reschedule = 1;
3077                         else if (res > 0)
3078                                 /* failed with merge conflicts */
3079                                 return error_with_patch(item->commit,
3080                                                         item->arg,
3081                                                         item->arg_len, opts,
3082                                                         res, 0);
3083                 } else if (!is_noop(item->command))
3084                         return error(_("unknown command %d"), item->command);
3085
3086                 if (reschedule) {
3087                         advise(_(rescheduled_advice),
3088                                get_item_line_length(todo_list,
3089                                                     todo_list->current),
3090                                get_item_line(todo_list, todo_list->current));
3091                         todo_list->current--;
3092                         if (save_todo(todo_list, opts))
3093                                 return -1;
3094                         if (item->commit)
3095                                 return error_with_patch(item->commit,
3096                                                         item->arg,
3097                                                         item->arg_len, opts,
3098                                                         res, 0);
3099                 }
3100
3101                 todo_list->current++;
3102                 if (res)
3103                         return res;
3104         }
3105
3106         if (is_rebase_i(opts)) {
3107                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
3108                 struct stat st;
3109
3110                 /* Stopped in the middle, as planned? */
3111                 if (todo_list->current < todo_list->nr)
3112                         return 0;
3113
3114                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
3115                                 starts_with(head_ref.buf, "refs/")) {
3116                         const char *msg;
3117                         struct object_id head, orig;
3118                         int res;
3119
3120                         if (get_oid("HEAD", &head)) {
3121                                 res = error(_("cannot read HEAD"));
3122 cleanup_head_ref:
3123                                 strbuf_release(&head_ref);
3124                                 strbuf_release(&buf);
3125                                 return res;
3126                         }
3127                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
3128                                         get_oid_hex(buf.buf, &orig)) {
3129                                 res = error(_("could not read orig-head"));
3130                                 goto cleanup_head_ref;
3131                         }
3132                         strbuf_reset(&buf);
3133                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
3134                                 res = error(_("could not read 'onto'"));
3135                                 goto cleanup_head_ref;
3136                         }
3137                         msg = reflog_message(opts, "finish", "%s onto %s",
3138                                 head_ref.buf, buf.buf);
3139                         if (update_ref(msg, head_ref.buf, &head, &orig,
3140                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
3141                                 res = error(_("could not update %s"),
3142                                         head_ref.buf);
3143                                 goto cleanup_head_ref;
3144                         }
3145                         msg = reflog_message(opts, "finish", "returning to %s",
3146                                 head_ref.buf);
3147                         if (create_symref("HEAD", head_ref.buf, msg)) {
3148                                 res = error(_("could not update HEAD to %s"),
3149                                         head_ref.buf);
3150                                 goto cleanup_head_ref;
3151                         }
3152                         strbuf_reset(&buf);
3153                 }
3154
3155                 if (opts->verbose) {
3156                         struct rev_info log_tree_opt;
3157                         struct object_id orig, head;
3158
3159                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3160                         init_revisions(&log_tree_opt, NULL);
3161                         log_tree_opt.diff = 1;
3162                         log_tree_opt.diffopt.output_format =
3163                                 DIFF_FORMAT_DIFFSTAT;
3164                         log_tree_opt.disable_stdin = 1;
3165
3166                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
3167                             !get_oid(buf.buf, &orig) &&
3168                             !get_oid("HEAD", &head)) {
3169                                 diff_tree_oid(&orig, &head, "",
3170                                               &log_tree_opt.diffopt);
3171                                 log_tree_diff_flush(&log_tree_opt);
3172                         }
3173                 }
3174                 flush_rewritten_pending();
3175                 if (!stat(rebase_path_rewritten_list(), &st) &&
3176                                 st.st_size > 0) {
3177                         struct child_process child = CHILD_PROCESS_INIT;
3178                         const char *post_rewrite_hook =
3179                                 find_hook("post-rewrite");
3180
3181                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
3182                         child.git_cmd = 1;
3183                         argv_array_push(&child.args, "notes");
3184                         argv_array_push(&child.args, "copy");
3185                         argv_array_push(&child.args, "--for-rewrite=rebase");
3186                         /* we don't care if this copying failed */
3187                         run_command(&child);
3188
3189                         if (post_rewrite_hook) {
3190                                 struct child_process hook = CHILD_PROCESS_INIT;
3191
3192                                 hook.in = open(rebase_path_rewritten_list(),
3193                                         O_RDONLY);
3194                                 hook.stdout_to_stderr = 1;
3195                                 argv_array_push(&hook.args, post_rewrite_hook);
3196                                 argv_array_push(&hook.args, "rebase");
3197                                 /* we don't care if this hook failed */
3198                                 run_command(&hook);
3199                         }
3200                 }
3201                 apply_autostash(opts);
3202
3203                 fprintf(stderr, "Successfully rebased and updated %s.\n",
3204                         head_ref.buf);
3205
3206                 strbuf_release(&buf);
3207                 strbuf_release(&head_ref);
3208         }
3209
3210         /*
3211          * Sequence of picks finished successfully; cleanup by
3212          * removing the .git/sequencer directory
3213          */
3214         return sequencer_remove_state(opts);
3215 }
3216
3217 static int continue_single_pick(void)
3218 {
3219         const char *argv[] = { "commit", NULL };
3220
3221         if (!file_exists(git_path_cherry_pick_head()) &&
3222             !file_exists(git_path_revert_head()))
3223                 return error(_("no cherry-pick or revert in progress"));
3224         return run_command_v_opt(argv, RUN_GIT_CMD);
3225 }
3226
3227 static int commit_staged_changes(struct replay_opts *opts)
3228 {
3229         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
3230
3231         if (has_unstaged_changes(1))
3232                 return error(_("cannot rebase: You have unstaged changes."));
3233         if (!has_uncommitted_changes(0)) {
3234                 const char *cherry_pick_head = git_path_cherry_pick_head();
3235
3236                 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
3237                         return error(_("could not remove CHERRY_PICK_HEAD"));
3238                 return 0;
3239         }
3240
3241         if (file_exists(rebase_path_amend())) {
3242                 struct strbuf rev = STRBUF_INIT;
3243                 struct object_id head, to_amend;
3244
3245                 if (get_oid("HEAD", &head))
3246                         return error(_("cannot amend non-existing commit"));
3247                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
3248                         return error(_("invalid file: '%s'"), rebase_path_amend());
3249                 if (get_oid_hex(rev.buf, &to_amend))
3250                         return error(_("invalid contents: '%s'"),
3251                                 rebase_path_amend());
3252                 if (oidcmp(&head, &to_amend))
3253                         return error(_("\nYou have uncommitted changes in your "
3254                                        "working tree. Please, commit them\n"
3255                                        "first and then run 'git rebase "
3256                                        "--continue' again."));
3257
3258                 strbuf_release(&rev);
3259                 flags |= AMEND_MSG;
3260         }
3261
3262         if (run_git_commit(rebase_path_message(), opts, flags))
3263                 return error(_("could not commit staged changes."));
3264         unlink(rebase_path_amend());
3265         return 0;
3266 }
3267
3268 int sequencer_continue(struct replay_opts *opts)
3269 {
3270         struct todo_list todo_list = TODO_LIST_INIT;
3271         int res;
3272
3273         if (read_and_refresh_cache(opts))
3274                 return -1;
3275
3276         if (is_rebase_i(opts)) {
3277                 if (commit_staged_changes(opts))
3278                         return -1;
3279         } else if (!file_exists(get_todo_path(opts)))
3280                 return continue_single_pick();
3281         if (read_populate_opts(opts))
3282                 return -1;
3283         if ((res = read_populate_todo(&todo_list, opts)))
3284                 goto release_todo_list;
3285
3286         if (!is_rebase_i(opts)) {
3287                 /* Verify that the conflict has been resolved */
3288                 if (file_exists(git_path_cherry_pick_head()) ||
3289                     file_exists(git_path_revert_head())) {
3290                         res = continue_single_pick();
3291                         if (res)
3292                                 goto release_todo_list;
3293                 }
3294                 if (index_differs_from("HEAD", NULL, 0)) {
3295                         res = error_dirty_index(opts);
3296                         goto release_todo_list;
3297                 }
3298                 todo_list.current++;
3299         } else if (file_exists(rebase_path_stopped_sha())) {
3300                 struct strbuf buf = STRBUF_INIT;
3301                 struct object_id oid;
3302
3303                 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
3304                     !get_oid_committish(buf.buf, &oid))
3305                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
3306                 strbuf_release(&buf);
3307         }
3308
3309         res = pick_commits(&todo_list, opts);
3310 release_todo_list:
3311         todo_list_release(&todo_list);
3312         return res;
3313 }
3314
3315 static int single_pick(struct commit *cmit, struct replay_opts *opts)
3316 {
3317         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3318         return do_pick_commit(opts->action == REPLAY_PICK ?
3319                 TODO_PICK : TODO_REVERT, cmit, opts, 0);
3320 }
3321
3322 int sequencer_pick_revisions(struct replay_opts *opts)
3323 {
3324         struct todo_list todo_list = TODO_LIST_INIT;
3325         struct object_id oid;
3326         int i, res;
3327
3328         assert(opts->revs);
3329         if (read_and_refresh_cache(opts))
3330                 return -1;
3331
3332         for (i = 0; i < opts->revs->pending.nr; i++) {
3333                 struct object_id oid;
3334                 const char *name = opts->revs->pending.objects[i].name;
3335
3336                 /* This happens when using --stdin. */
3337                 if (!strlen(name))
3338                         continue;
3339
3340                 if (!get_oid(name, &oid)) {
3341                         if (!lookup_commit_reference_gently(&oid, 1)) {
3342                                 enum object_type type = oid_object_info(&oid,
3343                                                                         NULL);
3344                                 return error(_("%s: can't cherry-pick a %s"),
3345                                         name, type_name(type));
3346                         }
3347                 } else
3348                         return error(_("%s: bad revision"), name);
3349         }
3350
3351         /*
3352          * If we were called as "git cherry-pick <commit>", just
3353          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
3354          * REVERT_HEAD, and don't touch the sequencer state.
3355          * This means it is possible to cherry-pick in the middle
3356          * of a cherry-pick sequence.
3357          */
3358         if (opts->revs->cmdline.nr == 1 &&
3359             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
3360             opts->revs->no_walk &&
3361             !opts->revs->cmdline.rev->flags) {
3362                 struct commit *cmit;
3363                 if (prepare_revision_walk(opts->revs))
3364                         return error(_("revision walk setup failed"));
3365                 cmit = get_revision(opts->revs);
3366                 if (!cmit || get_revision(opts->revs))
3367                         return error("BUG: expected exactly one commit from walk");
3368                 return single_pick(cmit, opts);
3369         }
3370
3371         /*
3372          * Start a new cherry-pick/ revert sequence; but
3373          * first, make sure that an existing one isn't in
3374          * progress
3375          */
3376
3377         if (walk_revs_populate_todo(&todo_list, opts) ||
3378                         create_seq_dir() < 0)
3379                 return -1;
3380         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
3381                 return error(_("can't revert as initial commit"));
3382         if (save_head(oid_to_hex(&oid)))
3383                 return -1;
3384         if (save_opts(opts))
3385                 return -1;
3386         update_abort_safety_file();
3387         res = pick_commits(&todo_list, opts);
3388         todo_list_release(&todo_list);
3389         return res;
3390 }
3391
3392 void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
3393 {
3394         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
3395         struct strbuf sob = STRBUF_INIT;
3396         int has_footer;
3397
3398         strbuf_addstr(&sob, sign_off_header);
3399         strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
3400                                 getenv("GIT_COMMITTER_EMAIL")));
3401         strbuf_addch(&sob, '\n');
3402
3403         if (!ignore_footer)
3404                 strbuf_complete_line(msgbuf);
3405
3406         /*
3407          * If the whole message buffer is equal to the sob, pretend that we
3408          * found a conforming footer with a matching sob
3409          */
3410         if (msgbuf->len - ignore_footer == sob.len &&
3411             !strncmp(msgbuf->buf, sob.buf, sob.len))
3412                 has_footer = 3;
3413         else
3414                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
3415
3416         if (!has_footer) {
3417                 const char *append_newlines = NULL;
3418                 size_t len = msgbuf->len - ignore_footer;
3419
3420                 if (!len) {
3421                         /*
3422                          * The buffer is completely empty.  Leave foom for
3423                          * the title and body to be filled in by the user.
3424                          */
3425                         append_newlines = "\n\n";
3426                 } else if (len == 1) {
3427                         /*
3428                          * Buffer contains a single newline.  Add another
3429                          * so that we leave room for the title and body.
3430                          */
3431                         append_newlines = "\n";
3432                 } else if (msgbuf->buf[len - 2] != '\n') {
3433                         /*
3434                          * Buffer ends with a single newline.  Add another
3435                          * so that there is an empty line between the message
3436                          * body and the sob.
3437                          */
3438                         append_newlines = "\n";
3439                 } /* else, the buffer already ends with two newlines. */
3440
3441                 if (append_newlines)
3442                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3443                                 append_newlines, strlen(append_newlines));
3444         }
3445
3446         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
3447                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
3448                                 sob.buf, sob.len);
3449
3450         strbuf_release(&sob);
3451 }
3452
3453 struct labels_entry {
3454         struct hashmap_entry entry;
3455         char label[FLEX_ARRAY];
3456 };
3457
3458 static int labels_cmp(const void *fndata, const struct labels_entry *a,
3459                       const struct labels_entry *b, const void *key)
3460 {
3461         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
3462 }
3463
3464 struct string_entry {
3465         struct oidmap_entry entry;
3466         char string[FLEX_ARRAY];
3467 };
3468
3469 struct label_state {
3470         struct oidmap commit2label;
3471         struct hashmap labels;
3472         struct strbuf buf;
3473 };
3474
3475 static const char *label_oid(struct object_id *oid, const char *label,
3476                              struct label_state *state)
3477 {
3478         struct labels_entry *labels_entry;
3479         struct string_entry *string_entry;
3480         struct object_id dummy;
3481         size_t len;
3482         int i;
3483
3484         string_entry = oidmap_get(&state->commit2label, oid);
3485         if (string_entry)
3486                 return string_entry->string;
3487
3488         /*
3489          * For "uninteresting" commits, i.e. commits that are not to be
3490          * rebased, and which can therefore not be labeled, we use a unique
3491          * abbreviation of the commit name. This is slightly more complicated
3492          * than calling find_unique_abbrev() because we also need to make
3493          * sure that the abbreviation does not conflict with any other
3494          * label.
3495          *
3496          * We disallow "interesting" commits to be labeled by a string that
3497          * is a valid full-length hash, to ensure that we always can find an
3498          * abbreviation for any uninteresting commit's names that does not
3499          * clash with any other label.
3500          */
3501         if (!label) {
3502                 char *p;
3503
3504                 strbuf_reset(&state->buf);
3505                 strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
3506                 label = p = state->buf.buf;
3507
3508                 find_unique_abbrev_r(p, oid, default_abbrev);
3509
3510                 /*
3511                  * We may need to extend the abbreviated hash so that there is
3512                  * no conflicting label.
3513                  */
3514                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
3515                         size_t i = strlen(p) + 1;
3516
3517                         oid_to_hex_r(p, oid);
3518                         for (; i < GIT_SHA1_HEXSZ; i++) {
3519                                 char save = p[i];
3520                                 p[i] = '\0';
3521                                 if (!hashmap_get_from_hash(&state->labels,
3522                                                            strihash(p), p))
3523                                         break;
3524                                 p[i] = save;
3525                         }
3526                 }
3527         } else if (((len = strlen(label)) == GIT_SHA1_RAWSZ &&
3528                     !get_oid_hex(label, &dummy)) ||
3529                    (len == 1 && *label == '#') ||
3530                    hashmap_get_from_hash(&state->labels,
3531                                          strihash(label), label)) {
3532                 /*
3533                  * If the label already exists, or if the label is a valid full
3534                  * OID, or the label is a '#' (which we use as a separator
3535                  * between merge heads and oneline), we append a dash and a
3536                  * number to make it unique.
3537                  */
3538                 struct strbuf *buf = &state->buf;
3539
3540                 strbuf_reset(buf);
3541                 strbuf_add(buf, label, len);
3542
3543                 for (i = 2; ; i++) {
3544                         strbuf_setlen(buf, len);
3545                         strbuf_addf(buf, "-%d", i);
3546                         if (!hashmap_get_from_hash(&state->labels,
3547                                                    strihash(buf->buf),
3548                                                    buf->buf))
3549                                 break;
3550                 }
3551
3552                 label = buf->buf;
3553         }
3554
3555         FLEX_ALLOC_STR(labels_entry, label, label);
3556         hashmap_entry_init(labels_entry, strihash(label));
3557         hashmap_add(&state->labels, labels_entry);
3558
3559         FLEX_ALLOC_STR(string_entry, string, label);
3560         oidcpy(&string_entry->entry.oid, oid);
3561         oidmap_put(&state->commit2label, string_entry);
3562
3563         return string_entry->string;
3564 }
3565
3566 static int make_script_with_merges(struct pretty_print_context *pp,
3567                                    struct rev_info *revs, FILE *out,
3568                                    unsigned flags)
3569 {
3570         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3571         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
3572         struct strbuf label = STRBUF_INIT;
3573         struct commit_list *commits = NULL, **tail = &commits, *iter;
3574         struct commit_list *tips = NULL, **tips_tail = &tips;
3575         struct commit *commit;
3576         struct oidmap commit2todo = OIDMAP_INIT;
3577         struct string_entry *entry;
3578         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
3579                 shown = OIDSET_INIT;
3580         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
3581
3582         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
3583         const char *cmd_pick = abbr ? "p" : "pick",
3584                 *cmd_label = abbr ? "l" : "label",
3585                 *cmd_reset = abbr ? "t" : "reset",
3586                 *cmd_merge = abbr ? "m" : "merge";
3587
3588         oidmap_init(&commit2todo, 0);
3589         oidmap_init(&state.commit2label, 0);
3590         hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
3591         strbuf_init(&state.buf, 32);
3592
3593         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
3594                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
3595                 FLEX_ALLOC_STR(entry, string, "onto");
3596                 oidcpy(&entry->entry.oid, oid);
3597                 oidmap_put(&state.commit2label, entry);
3598         }
3599
3600         /*
3601          * First phase:
3602          * - get onelines for all commits
3603          * - gather all branch tips (i.e. 2nd or later parents of merges)
3604          * - label all branch tips
3605          */
3606         while ((commit = get_revision(revs))) {
3607                 struct commit_list *to_merge;
3608                 int is_octopus;
3609                 const char *p1, *p2;
3610                 struct object_id *oid;
3611                 int is_empty;
3612
3613                 tail = &commit_list_insert(commit, tail)->next;
3614                 oidset_insert(&interesting, &commit->object.oid);
3615
3616                 is_empty = is_original_commit_empty(commit);
3617                 if (!is_empty && (commit->object.flags & PATCHSAME))
3618                         continue;
3619
3620                 strbuf_reset(&oneline);
3621                 pretty_print_commit(pp, commit, &oneline);
3622
3623                 to_merge = commit->parents ? commit->parents->next : NULL;
3624                 if (!to_merge) {
3625                         /* non-merge commit: easy case */
3626                         strbuf_reset(&buf);
3627                         if (!keep_empty && is_empty)
3628                                 strbuf_addf(&buf, "%c ", comment_line_char);
3629                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
3630                                     oid_to_hex(&commit->object.oid),
3631                                     oneline.buf);
3632
3633                         FLEX_ALLOC_STR(entry, string, buf.buf);
3634                         oidcpy(&entry->entry.oid, &commit->object.oid);
3635                         oidmap_put(&commit2todo, entry);
3636
3637                         continue;
3638                 }
3639
3640                 is_octopus = to_merge && to_merge->next;
3641
3642                 if (is_octopus)
3643                         BUG("Octopus merges not yet supported");
3644
3645                 /* Create a label */
3646                 strbuf_reset(&label);
3647                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
3648                     (p1 = strchr(p1, '\'')) &&
3649                     (p2 = strchr(++p1, '\'')))
3650                         strbuf_add(&label, p1, p2 - p1);
3651                 else if (skip_prefix(oneline.buf, "Merge pull request ",
3652                                      &p1) &&
3653                          (p1 = strstr(p1, " from ")))
3654                         strbuf_addstr(&label, p1 + strlen(" from "));
3655                 else
3656                         strbuf_addbuf(&label, &oneline);
3657
3658                 for (p1 = label.buf; *p1; p1++)
3659                         if (isspace(*p1))
3660                                 *(char *)p1 = '-';
3661
3662                 strbuf_reset(&buf);
3663                 strbuf_addf(&buf, "%s -C %s",
3664                             cmd_merge, oid_to_hex(&commit->object.oid));
3665
3666                 /* label the tip of merged branch */
3667                 oid = &to_merge->item->object.oid;
3668                 strbuf_addch(&buf, ' ');
3669
3670                 if (!oidset_contains(&interesting, oid))
3671                         strbuf_addstr(&buf, label_oid(oid, NULL, &state));
3672                 else {
3673                         tips_tail = &commit_list_insert(to_merge->item,
3674                                                         tips_tail)->next;
3675
3676                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
3677                 }
3678                 strbuf_addf(&buf, " # %s", oneline.buf);
3679
3680                 FLEX_ALLOC_STR(entry, string, buf.buf);
3681                 oidcpy(&entry->entry.oid, &commit->object.oid);
3682                 oidmap_put(&commit2todo, entry);
3683         }
3684
3685         /*
3686          * Second phase:
3687          * - label branch points
3688          * - add HEAD to the branch tips
3689          */
3690         for (iter = commits; iter; iter = iter->next) {
3691                 struct commit_list *parent = iter->item->parents;
3692                 for (; parent; parent = parent->next) {
3693                         struct object_id *oid = &parent->item->object.oid;
3694                         if (!oidset_contains(&interesting, oid))
3695                                 continue;
3696                         if (!oidset_contains(&child_seen, oid))
3697                                 oidset_insert(&child_seen, oid);
3698                         else
3699                                 label_oid(oid, "branch-point", &state);
3700                 }
3701
3702                 /* Add HEAD as implict "tip of branch" */
3703                 if (!iter->next)
3704                         tips_tail = &commit_list_insert(iter->item,
3705                                                         tips_tail)->next;
3706         }
3707
3708         /*
3709          * Third phase: output the todo list. This is a bit tricky, as we
3710          * want to avoid jumping back and forth between revisions. To
3711          * accomplish that goal, we walk backwards from the branch tips,
3712          * gathering commits not yet shown, reversing the list on the fly,
3713          * then outputting that list (labeling revisions as needed).
3714          */
3715         fprintf(out, "%s onto\n", cmd_label);
3716         for (iter = tips; iter; iter = iter->next) {
3717                 struct commit_list *list = NULL, *iter2;
3718
3719                 commit = iter->item;
3720                 if (oidset_contains(&shown, &commit->object.oid))
3721                         continue;
3722                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
3723
3724                 if (entry)
3725                         fprintf(out, "\n# Branch %s\n", entry->string);
3726                 else
3727                         fprintf(out, "\n");
3728
3729                 while (oidset_contains(&interesting, &commit->object.oid) &&
3730                        !oidset_contains(&shown, &commit->object.oid)) {
3731                         commit_list_insert(commit, &list);
3732                         if (!commit->parents) {
3733                                 commit = NULL;
3734                                 break;
3735                         }
3736                         commit = commit->parents->item;
3737                 }
3738
3739                 if (!commit)
3740                         fprintf(out, "%s onto\n", cmd_reset);
3741                 else {
3742                         const char *to = NULL;
3743
3744                         entry = oidmap_get(&state.commit2label,
3745                                            &commit->object.oid);
3746                         if (entry)
3747                                 to = entry->string;
3748
3749                         if (!to || !strcmp(to, "onto"))
3750                                 fprintf(out, "%s onto\n", cmd_reset);
3751                         else {
3752                                 strbuf_reset(&oneline);
3753                                 pretty_print_commit(pp, commit, &oneline);
3754                                 fprintf(out, "%s %s # %s\n",
3755                                         cmd_reset, to, oneline.buf);
3756                         }
3757                 }
3758
3759                 for (iter2 = list; iter2; iter2 = iter2->next) {
3760                         struct object_id *oid = &iter2->item->object.oid;
3761                         entry = oidmap_get(&commit2todo, oid);
3762                         /* only show if not already upstream */
3763                         if (entry)
3764                                 fprintf(out, "%s\n", entry->string);
3765                         entry = oidmap_get(&state.commit2label, oid);
3766                         if (entry)
3767                                 fprintf(out, "%s %s\n",
3768                                         cmd_label, entry->string);
3769                         oidset_insert(&shown, oid);
3770                 }
3771
3772                 free_commit_list(list);
3773         }
3774
3775         free_commit_list(commits);
3776         free_commit_list(tips);
3777
3778         strbuf_release(&label);
3779         strbuf_release(&oneline);
3780         strbuf_release(&buf);
3781
3782         oidmap_free(&commit2todo, 1);
3783         oidmap_free(&state.commit2label, 1);
3784         hashmap_free(&state.labels, 1);
3785         strbuf_release(&state.buf);
3786
3787         return 0;
3788 }
3789
3790 int sequencer_make_script(FILE *out, int argc, const char **argv,
3791                           unsigned flags)
3792 {
3793         char *format = NULL;
3794         struct pretty_print_context pp = {0};
3795         struct strbuf buf = STRBUF_INIT;
3796         struct rev_info revs;
3797         struct commit *commit;
3798         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
3799         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
3800         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
3801
3802         init_revisions(&revs, NULL);
3803         revs.verbose_header = 1;
3804         if (!rebase_merges)
3805                 revs.max_parents = 1;
3806         revs.cherry_mark = 1;
3807         revs.limited = 1;
3808         revs.reverse = 1;
3809         revs.right_only = 1;
3810         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
3811         revs.topo_order = 1;
3812
3813         revs.pretty_given = 1;
3814         git_config_get_string("rebase.instructionFormat", &format);
3815         if (!format || !*format) {
3816                 free(format);
3817                 format = xstrdup("%s");
3818         }
3819         get_commit_format(format, &revs);
3820         free(format);
3821         pp.fmt = revs.commit_format;
3822         pp.output_encoding = get_log_output_encoding();
3823
3824         if (setup_revisions(argc, argv, &revs, NULL) > 1)
3825                 return error(_("make_script: unhandled options"));
3826
3827         if (prepare_revision_walk(&revs) < 0)
3828                 return error(_("make_script: error preparing revisions"));
3829
3830         if (rebase_merges)
3831                 return make_script_with_merges(&pp, &revs, out, flags);
3832
3833         while ((commit = get_revision(&revs))) {
3834                 int is_empty  = is_original_commit_empty(commit);
3835
3836                 if (!is_empty && (commit->object.flags & PATCHSAME))
3837                         continue;
3838                 strbuf_reset(&buf);
3839                 if (!keep_empty && is_empty)
3840                         strbuf_addf(&buf, "%c ", comment_line_char);
3841                 strbuf_addf(&buf, "%s %s ", insn,
3842                             oid_to_hex(&commit->object.oid));
3843                 pretty_print_commit(&pp, commit, &buf);
3844                 strbuf_addch(&buf, '\n');
3845                 fputs(buf.buf, out);
3846         }
3847         strbuf_release(&buf);
3848         return 0;
3849 }
3850
3851 /*
3852  * Add commands after pick and (series of) squash/fixup commands
3853  * in the todo list.
3854  */
3855 int sequencer_add_exec_commands(const char *commands)
3856 {
3857         const char *todo_file = rebase_path_todo();
3858         struct todo_list todo_list = TODO_LIST_INIT;
3859         struct todo_item *item;
3860         struct strbuf *buf = &todo_list.buf;
3861         size_t offset = 0, commands_len = strlen(commands);
3862         int i, first;
3863
3864         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3865                 return error(_("could not read '%s'."), todo_file);
3866
3867         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3868                 todo_list_release(&todo_list);
3869                 return error(_("unusable todo list: '%s'"), todo_file);
3870         }
3871
3872         first = 1;
3873         /* insert <commands> before every pick except the first one */
3874         for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3875                 if (item->command == TODO_PICK && !first) {
3876                         strbuf_insert(buf, item->offset_in_buf + offset,
3877                                       commands, commands_len);
3878                         offset += commands_len;
3879                 }
3880                 first = 0;
3881         }
3882
3883         /* append final <commands> */
3884         strbuf_add(buf, commands, commands_len);
3885
3886         i = write_message(buf->buf, buf->len, todo_file, 0);
3887         todo_list_release(&todo_list);
3888         return i;
3889 }
3890
3891 int transform_todos(unsigned flags)
3892 {
3893         const char *todo_file = rebase_path_todo();
3894         struct todo_list todo_list = TODO_LIST_INIT;
3895         struct strbuf buf = STRBUF_INIT;
3896         struct todo_item *item;
3897         int i;
3898
3899         if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
3900                 return error(_("could not read '%s'."), todo_file);
3901
3902         if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
3903                 todo_list_release(&todo_list);
3904                 return error(_("unusable todo list: '%s'"), todo_file);
3905         }
3906
3907         for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
3908                 /* if the item is not a command write it and continue */
3909                 if (item->command >= TODO_COMMENT) {
3910                         strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
3911                         continue;
3912                 }
3913
3914                 /* add command to the buffer */
3915                 if (flags & TODO_LIST_ABBREVIATE_CMDS)
3916                         strbuf_addch(&buf, command_to_char(item->command));
3917                 else
3918                         strbuf_addstr(&buf, command_to_string(item->command));
3919
3920                 /* add commit id */
3921                 if (item->commit) {
3922                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
3923                                           short_commit_name(item->commit) :
3924                                           oid_to_hex(&item->commit->object.oid);
3925
3926                         if (item->command == TODO_MERGE) {
3927                                 if (item->flags & TODO_EDIT_MERGE_MSG)
3928                                         strbuf_addstr(&buf, " -c");
3929                                 else
3930                                         strbuf_addstr(&buf, " -C");
3931                         }
3932
3933                         strbuf_addf(&buf, " %s", oid);
3934                 }
3935
3936                 /* add all the rest */
3937                 if (!item->arg_len)
3938                         strbuf_addch(&buf, '\n');
3939                 else
3940                         strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
3941         }
3942
3943         i = write_message(buf.buf, buf.len, todo_file, 0);
3944         todo_list_release(&todo_list);
3945         return i;
3946 }
3947
3948 enum check_level {
3949         CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
3950 };
3951
3952 static enum check_level get_missing_commit_check_level(void)
3953 {
3954         const char *value;
3955
3956         if (git_config_get_value("rebase.missingcommitscheck", &value) ||
3957                         !strcasecmp("ignore", value))
3958                 return CHECK_IGNORE;
3959         if (!strcasecmp("warn", value))
3960                 return CHECK_WARN;
3961         if (!strcasecmp("error", value))
3962                 return CHECK_ERROR;
3963         warning(_("unrecognized setting %s for option "
3964                   "rebase.missingCommitsCheck. Ignoring."), value);
3965         return CHECK_IGNORE;
3966 }
3967
3968 /*
3969  * Check if the user dropped some commits by mistake
3970  * Behaviour determined by rebase.missingCommitsCheck.
3971  * Check if there is an unrecognized command or a
3972  * bad SHA-1 in a command.
3973  */
3974 int check_todo_list(void)
3975 {
3976         enum check_level check_level = get_missing_commit_check_level();
3977         struct strbuf todo_file = STRBUF_INIT;
3978         struct todo_list todo_list = TODO_LIST_INIT;
3979         struct strbuf missing = STRBUF_INIT;
3980         int advise_to_edit_todo = 0, res = 0, i;
3981
3982         strbuf_addstr(&todo_file, rebase_path_todo());
3983         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
3984                 res = -1;
3985                 goto leave_check;
3986         }
3987         advise_to_edit_todo = res =
3988                 parse_insn_buffer(todo_list.buf.buf, &todo_list);
3989
3990         if (res || check_level == CHECK_IGNORE)
3991                 goto leave_check;
3992
3993         /* Mark the commits in git-rebase-todo as seen */
3994         for (i = 0; i < todo_list.nr; i++) {
3995                 struct commit *commit = todo_list.items[i].commit;
3996                 if (commit)
3997                         commit->util = (void *)1;
3998         }
3999
4000         todo_list_release(&todo_list);
4001         strbuf_addstr(&todo_file, ".backup");
4002         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file.buf) < 0) {
4003                 res = -1;
4004                 goto leave_check;
4005         }
4006         strbuf_release(&todo_file);
4007         res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
4008
4009         /* Find commits in git-rebase-todo.backup yet unseen */
4010         for (i = todo_list.nr - 1; i >= 0; i--) {
4011                 struct todo_item *item = todo_list.items + i;
4012                 struct commit *commit = item->commit;
4013                 if (commit && !commit->util) {
4014                         strbuf_addf(&missing, " - %s %.*s\n",
4015                                     short_commit_name(commit),
4016                                     item->arg_len, item->arg);
4017                         commit->util = (void *)1;
4018                 }
4019         }
4020
4021         /* Warn about missing commits */
4022         if (!missing.len)
4023                 goto leave_check;
4024
4025         if (check_level == CHECK_ERROR)
4026                 advise_to_edit_todo = res = 1;
4027
4028         fprintf(stderr,
4029                 _("Warning: some commits may have been dropped accidentally.\n"
4030                 "Dropped commits (newer to older):\n"));
4031
4032         /* Make the list user-friendly and display */
4033         fputs(missing.buf, stderr);
4034         strbuf_release(&missing);
4035
4036         fprintf(stderr, _("To avoid this message, use \"drop\" to "
4037                 "explicitly remove a commit.\n\n"
4038                 "Use 'git config rebase.missingCommitsCheck' to change "
4039                 "the level of warnings.\n"
4040                 "The possible behaviours are: ignore, warn, error.\n\n"));
4041
4042 leave_check:
4043         strbuf_release(&todo_file);
4044         todo_list_release(&todo_list);
4045
4046         if (advise_to_edit_todo)
4047                 fprintf(stderr,
4048                         _("You can fix this with 'git rebase --edit-todo' "
4049                           "and then run 'git rebase --continue'.\n"
4050                           "Or you can abort the rebase with 'git rebase"
4051                           " --abort'.\n"));
4052
4053         return res;
4054 }
4055
4056 static int rewrite_file(const char *path, const char *buf, size_t len)
4057 {
4058         int rc = 0;
4059         int fd = open(path, O_WRONLY | O_TRUNC);
4060         if (fd < 0)
4061                 return error_errno(_("could not open '%s' for writing"), path);
4062         if (write_in_full(fd, buf, len) < 0)
4063                 rc = error_errno(_("could not write to '%s'"), path);
4064         if (close(fd) && !rc)
4065                 rc = error_errno(_("could not close '%s'"), path);
4066         return rc;
4067 }
4068
4069 /* skip picking commits whose parents are unchanged */
4070 int skip_unnecessary_picks(void)
4071 {
4072         const char *todo_file = rebase_path_todo();
4073         struct strbuf buf = STRBUF_INIT;
4074         struct todo_list todo_list = TODO_LIST_INIT;
4075         struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
4076         int fd, i;
4077
4078         if (!read_oneliner(&buf, rebase_path_onto(), 0))
4079                 return error(_("could not read 'onto'"));
4080         if (get_oid(buf.buf, &onto_oid)) {
4081                 strbuf_release(&buf);
4082                 return error(_("need a HEAD to fixup"));
4083         }
4084         strbuf_release(&buf);
4085
4086         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4087                 return -1;
4088         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4089                 todo_list_release(&todo_list);
4090                 return -1;
4091         }
4092
4093         for (i = 0; i < todo_list.nr; i++) {
4094                 struct todo_item *item = todo_list.items + i;
4095
4096                 if (item->command >= TODO_NOOP)
4097                         continue;
4098                 if (item->command != TODO_PICK)
4099                         break;
4100                 if (parse_commit(item->commit)) {
4101                         todo_list_release(&todo_list);
4102                         return error(_("could not parse commit '%s'"),
4103                                 oid_to_hex(&item->commit->object.oid));
4104                 }
4105                 if (!item->commit->parents)
4106                         break; /* root commit */
4107                 if (item->commit->parents->next)
4108                         break; /* merge commit */
4109                 parent_oid = &item->commit->parents->item->object.oid;
4110                 if (hashcmp(parent_oid->hash, oid->hash))
4111                         break;
4112                 oid = &item->commit->object.oid;
4113         }
4114         if (i > 0) {
4115                 int offset = get_item_line_offset(&todo_list, i);
4116                 const char *done_path = rebase_path_done();
4117
4118                 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
4119                 if (fd < 0) {
4120                         error_errno(_("could not open '%s' for writing"),
4121                                     done_path);
4122                         todo_list_release(&todo_list);
4123                         return -1;
4124                 }
4125                 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
4126                         error_errno(_("could not write to '%s'"), done_path);
4127                         todo_list_release(&todo_list);
4128                         close(fd);
4129                         return -1;
4130                 }
4131                 close(fd);
4132
4133                 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
4134                                  todo_list.buf.len - offset) < 0) {
4135                         todo_list_release(&todo_list);
4136                         return -1;
4137                 }
4138
4139                 todo_list.current = i;
4140                 if (is_fixup(peek_command(&todo_list, 0)))
4141                         record_in_rewritten(oid, peek_command(&todo_list, 0));
4142         }
4143
4144         todo_list_release(&todo_list);
4145         printf("%s\n", oid_to_hex(oid));
4146
4147         return 0;
4148 }
4149
4150 struct subject2item_entry {
4151         struct hashmap_entry entry;
4152         int i;
4153         char subject[FLEX_ARRAY];
4154 };
4155
4156 static int subject2item_cmp(const void *fndata,
4157                             const struct subject2item_entry *a,
4158                             const struct subject2item_entry *b, const void *key)
4159 {
4160         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
4161 }
4162
4163 /*
4164  * Rearrange the todo list that has both "pick commit-id msg" and "pick
4165  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
4166  * after the former, and change "pick" to "fixup"/"squash".
4167  *
4168  * Note that if the config has specified a custom instruction format, each log
4169  * message will have to be retrieved from the commit (as the oneline in the
4170  * script cannot be trusted) in order to normalize the autosquash arrangement.
4171  */
4172 int rearrange_squash(void)
4173 {
4174         const char *todo_file = rebase_path_todo();
4175         struct todo_list todo_list = TODO_LIST_INIT;
4176         struct hashmap subject2item;
4177         int res = 0, rearranged = 0, *next, *tail, i;
4178         char **subjects;
4179
4180         if (strbuf_read_file_or_whine(&todo_list.buf, todo_file) < 0)
4181                 return -1;
4182         if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
4183                 todo_list_release(&todo_list);
4184                 return -1;
4185         }
4186
4187         /*
4188          * The hashmap maps onelines to the respective todo list index.
4189          *
4190          * If any items need to be rearranged, the next[i] value will indicate
4191          * which item was moved directly after the i'th.
4192          *
4193          * In that case, last[i] will indicate the index of the latest item to
4194          * be moved to appear after the i'th.
4195          */
4196         hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
4197                      NULL, todo_list.nr);
4198         ALLOC_ARRAY(next, todo_list.nr);
4199         ALLOC_ARRAY(tail, todo_list.nr);
4200         ALLOC_ARRAY(subjects, todo_list.nr);
4201         for (i = 0; i < todo_list.nr; i++) {
4202                 struct strbuf buf = STRBUF_INIT;
4203                 struct todo_item *item = todo_list.items + i;
4204                 const char *commit_buffer, *subject, *p;
4205                 size_t subject_len;
4206                 int i2 = -1;
4207                 struct subject2item_entry *entry;
4208
4209                 next[i] = tail[i] = -1;
4210                 if (!item->commit || item->command == TODO_DROP) {
4211                         subjects[i] = NULL;
4212                         continue;
4213                 }
4214
4215                 if (is_fixup(item->command)) {
4216                         todo_list_release(&todo_list);
4217                         return error(_("the script was already rearranged."));
4218                 }
4219
4220                 item->commit->util = item;
4221
4222                 parse_commit(item->commit);
4223                 commit_buffer = get_commit_buffer(item->commit, NULL);
4224                 find_commit_subject(commit_buffer, &subject);
4225                 format_subject(&buf, subject, " ");
4226                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
4227                 unuse_commit_buffer(item->commit, commit_buffer);
4228                 if ((skip_prefix(subject, "fixup! ", &p) ||
4229                      skip_prefix(subject, "squash! ", &p))) {
4230                         struct commit *commit2;
4231
4232                         for (;;) {
4233                                 while (isspace(*p))
4234                                         p++;
4235                                 if (!skip_prefix(p, "fixup! ", &p) &&
4236                                     !skip_prefix(p, "squash! ", &p))
4237                                         break;
4238                         }
4239
4240                         if ((entry = hashmap_get_from_hash(&subject2item,
4241                                                            strhash(p), p)))
4242                                 /* found by title */
4243                                 i2 = entry->i;
4244                         else if (!strchr(p, ' ') &&
4245                                  (commit2 =
4246                                   lookup_commit_reference_by_name(p)) &&
4247                                  commit2->util)
4248                                 /* found by commit name */
4249                                 i2 = (struct todo_item *)commit2->util
4250                                         - todo_list.items;
4251                         else {
4252                                 /* copy can be a prefix of the commit subject */
4253                                 for (i2 = 0; i2 < i; i2++)
4254                                         if (subjects[i2] &&
4255                                             starts_with(subjects[i2], p))
4256                                                 break;
4257                                 if (i2 == i)
4258                                         i2 = -1;
4259                         }
4260                 }
4261                 if (i2 >= 0) {
4262                         rearranged = 1;
4263                         todo_list.items[i].command =
4264                                 starts_with(subject, "fixup!") ?
4265                                 TODO_FIXUP : TODO_SQUASH;
4266                         if (next[i2] < 0)
4267                                 next[i2] = i;
4268                         else
4269                                 next[tail[i2]] = i;
4270                         tail[i2] = i;
4271                 } else if (!hashmap_get_from_hash(&subject2item,
4272                                                 strhash(subject), subject)) {
4273                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
4274                         entry->i = i;
4275                         hashmap_entry_init(entry, strhash(entry->subject));
4276                         hashmap_put(&subject2item, entry);
4277                 }
4278         }
4279
4280         if (rearranged) {
4281                 struct strbuf buf = STRBUF_INIT;
4282
4283                 for (i = 0; i < todo_list.nr; i++) {
4284                         enum todo_command command = todo_list.items[i].command;
4285                         int cur = i;
4286
4287                         /*
4288                          * Initially, all commands are 'pick's. If it is a
4289                          * fixup or a squash now, we have rearranged it.
4290                          */
4291                         if (is_fixup(command))
4292                                 continue;
4293
4294                         while (cur >= 0) {
4295                                 const char *bol =
4296                                         get_item_line(&todo_list, cur);
4297                                 const char *eol =
4298                                         get_item_line(&todo_list, cur + 1);
4299
4300                                 /* replace 'pick', by 'fixup' or 'squash' */
4301                                 command = todo_list.items[cur].command;
4302                                 if (is_fixup(command)) {
4303                                         strbuf_addstr(&buf,
4304                                                 todo_command_info[command].str);
4305                                         bol += strcspn(bol, " \t");
4306                                 }
4307
4308                                 strbuf_add(&buf, bol, eol - bol);
4309
4310                                 cur = next[cur];
4311                         }
4312                 }
4313
4314                 res = rewrite_file(todo_file, buf.buf, buf.len);
4315                 strbuf_release(&buf);
4316         }
4317
4318         free(next);
4319         free(tail);
4320         for (i = 0; i < todo_list.nr; i++)
4321                 free(subjects[i]);
4322         free(subjects);
4323         hashmap_free(&subject2item, 1);
4324         todo_list_release(&todo_list);
4325
4326         return res;
4327 }