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