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