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