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