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