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