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