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