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