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