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