core.abbrev=no disables abbreviations
[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 (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2321                 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
2322                                      NULL, 0) &&
2323                     verbose)
2324                         warning(_("cancelling a revert in progress"));
2325                 opts.action = REPLAY_REVERT;
2326                 need_cleanup = 1;
2327         }
2328
2329         if (!need_cleanup)
2330                 return;
2331
2332         if (!have_finished_the_last_pick())
2333                 return;
2334
2335         sequencer_remove_state(&opts);
2336 }
2337
2338 static void todo_list_write_total_nr(struct todo_list *todo_list)
2339 {
2340         FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
2341
2342         if (f) {
2343                 fprintf(f, "%d\n", todo_list->total_nr);
2344                 fclose(f);
2345         }
2346 }
2347
2348 static int read_populate_todo(struct repository *r,
2349                               struct todo_list *todo_list,
2350                               struct replay_opts *opts)
2351 {
2352         struct stat st;
2353         const char *todo_file = get_todo_path(opts);
2354         int res;
2355
2356         strbuf_reset(&todo_list->buf);
2357         if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
2358                 return -1;
2359
2360         res = stat(todo_file, &st);
2361         if (res)
2362                 return error(_("could not stat '%s'"), todo_file);
2363         fill_stat_data(&todo_list->stat, &st);
2364
2365         res = todo_list_parse_insn_buffer(r, todo_list->buf.buf, todo_list);
2366         if (res) {
2367                 if (is_rebase_i(opts))
2368                         return error(_("please fix this using "
2369                                        "'git rebase --edit-todo'."));
2370                 return error(_("unusable instruction sheet: '%s'"), todo_file);
2371         }
2372
2373         if (!todo_list->nr &&
2374             (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
2375                 return error(_("no commits parsed."));
2376
2377         if (!is_rebase_i(opts)) {
2378                 enum todo_command valid =
2379                         opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
2380                 int i;
2381
2382                 for (i = 0; i < todo_list->nr; i++)
2383                         if (valid == todo_list->items[i].command)
2384                                 continue;
2385                         else if (valid == TODO_PICK)
2386                                 return error(_("cannot cherry-pick during a revert."));
2387                         else
2388                                 return error(_("cannot revert during a cherry-pick."));
2389         }
2390
2391         if (is_rebase_i(opts)) {
2392                 struct todo_list done = TODO_LIST_INIT;
2393
2394                 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
2395                     !todo_list_parse_insn_buffer(r, done.buf.buf, &done))
2396                         todo_list->done_nr = count_commands(&done);
2397                 else
2398                         todo_list->done_nr = 0;
2399
2400                 todo_list->total_nr = todo_list->done_nr
2401                         + count_commands(todo_list);
2402                 todo_list_release(&done);
2403
2404                 todo_list_write_total_nr(todo_list);
2405         }
2406
2407         return 0;
2408 }
2409
2410 static int git_config_string_dup(char **dest,
2411                                  const char *var, const char *value)
2412 {
2413         if (!value)
2414                 return config_error_nonbool(var);
2415         free(*dest);
2416         *dest = xstrdup(value);
2417         return 0;
2418 }
2419
2420 static int populate_opts_cb(const char *key, const char *value, void *data)
2421 {
2422         struct replay_opts *opts = data;
2423         int error_flag = 1;
2424
2425         if (!value)
2426                 error_flag = 0;
2427         else if (!strcmp(key, "options.no-commit"))
2428                 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
2429         else if (!strcmp(key, "options.edit"))
2430                 opts->edit = git_config_bool_or_int(key, value, &error_flag);
2431         else if (!strcmp(key, "options.allow-empty"))
2432                 opts->allow_empty =
2433                         git_config_bool_or_int(key, value, &error_flag);
2434         else if (!strcmp(key, "options.allow-empty-message"))
2435                 opts->allow_empty_message =
2436                         git_config_bool_or_int(key, value, &error_flag);
2437         else if (!strcmp(key, "options.keep-redundant-commits"))
2438                 opts->keep_redundant_commits =
2439                         git_config_bool_or_int(key, value, &error_flag);
2440         else if (!strcmp(key, "options.signoff"))
2441                 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
2442         else if (!strcmp(key, "options.record-origin"))
2443                 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
2444         else if (!strcmp(key, "options.allow-ff"))
2445                 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
2446         else if (!strcmp(key, "options.mainline"))
2447                 opts->mainline = git_config_int(key, value);
2448         else if (!strcmp(key, "options.strategy"))
2449                 git_config_string_dup(&opts->strategy, key, value);
2450         else if (!strcmp(key, "options.gpg-sign"))
2451                 git_config_string_dup(&opts->gpg_sign, key, value);
2452         else if (!strcmp(key, "options.strategy-option")) {
2453                 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
2454                 opts->xopts[opts->xopts_nr++] = xstrdup(value);
2455         } else if (!strcmp(key, "options.allow-rerere-auto"))
2456                 opts->allow_rerere_auto =
2457                         git_config_bool_or_int(key, value, &error_flag) ?
2458                                 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
2459         else if (!strcmp(key, "options.default-msg-cleanup")) {
2460                 opts->explicit_cleanup = 1;
2461                 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
2462         } else
2463                 return error(_("invalid key: %s"), key);
2464
2465         if (!error_flag)
2466                 return error(_("invalid value for %s: %s"), key, value);
2467
2468         return 0;
2469 }
2470
2471 void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
2472 {
2473         int i;
2474         char *strategy_opts_string = raw_opts;
2475
2476         if (*strategy_opts_string == ' ')
2477                 strategy_opts_string++;
2478
2479         opts->xopts_nr = split_cmdline(strategy_opts_string,
2480                                        (const char ***)&opts->xopts);
2481         for (i = 0; i < opts->xopts_nr; i++) {
2482                 const char *arg = opts->xopts[i];
2483
2484                 skip_prefix(arg, "--", &arg);
2485                 opts->xopts[i] = xstrdup(arg);
2486         }
2487 }
2488
2489 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
2490 {
2491         strbuf_reset(buf);
2492         if (!read_oneliner(buf, rebase_path_strategy(), 0))
2493                 return;
2494         opts->strategy = strbuf_detach(buf, NULL);
2495         if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
2496                 return;
2497
2498         parse_strategy_opts(opts, buf->buf);
2499 }
2500
2501 static int read_populate_opts(struct replay_opts *opts)
2502 {
2503         if (is_rebase_i(opts)) {
2504                 struct strbuf buf = STRBUF_INIT;
2505                 int ret = 0;
2506
2507                 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
2508                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2509                         if (!starts_with(buf.buf, "-S"))
2510                                 strbuf_reset(&buf);
2511                         else {
2512                                 free(opts->gpg_sign);
2513                                 opts->gpg_sign = xstrdup(buf.buf + 2);
2514                         }
2515                         strbuf_reset(&buf);
2516                 }
2517
2518                 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
2519                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2520                         if (!strcmp(buf.buf, "--rerere-autoupdate"))
2521                                 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
2522                         else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
2523                                 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
2524                         strbuf_reset(&buf);
2525                 }
2526
2527                 if (file_exists(rebase_path_verbose()))
2528                         opts->verbose = 1;
2529
2530                 if (file_exists(rebase_path_quiet()))
2531                         opts->quiet = 1;
2532
2533                 if (file_exists(rebase_path_signoff())) {
2534                         opts->allow_ff = 0;
2535                         opts->signoff = 1;
2536                 }
2537
2538                 if (file_exists(rebase_path_reschedule_failed_exec()))
2539                         opts->reschedule_failed_exec = 1;
2540
2541                 if (file_exists(rebase_path_drop_redundant_commits()))
2542                         opts->drop_redundant_commits = 1;
2543
2544                 if (file_exists(rebase_path_keep_redundant_commits()))
2545                         opts->keep_redundant_commits = 1;
2546
2547                 read_strategy_opts(opts, &buf);
2548                 strbuf_reset(&buf);
2549
2550                 if (read_oneliner(&opts->current_fixups,
2551                                   rebase_path_current_fixups(),
2552                                   READ_ONELINER_SKIP_IF_EMPTY)) {
2553                         const char *p = opts->current_fixups.buf;
2554                         opts->current_fixup_count = 1;
2555                         while ((p = strchr(p, '\n'))) {
2556                                 opts->current_fixup_count++;
2557                                 p++;
2558                         }
2559                 }
2560
2561                 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
2562                         if (get_oid_hex(buf.buf, &opts->squash_onto) < 0) {
2563                                 ret = error(_("unusable squash-onto"));
2564                                 goto done_rebase_i;
2565                         }
2566                         opts->have_squash_onto = 1;
2567                 }
2568
2569 done_rebase_i:
2570                 strbuf_release(&buf);
2571                 return ret;
2572         }
2573
2574         if (!file_exists(git_path_opts_file()))
2575                 return 0;
2576         /*
2577          * The function git_parse_source(), called from git_config_from_file(),
2578          * may die() in case of a syntactically incorrect file. We do not care
2579          * about this case, though, because we wrote that file ourselves, so we
2580          * are pretty certain that it is syntactically correct.
2581          */
2582         if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
2583                 return error(_("malformed options sheet: '%s'"),
2584                         git_path_opts_file());
2585         return 0;
2586 }
2587
2588 static void write_strategy_opts(struct replay_opts *opts)
2589 {
2590         int i;
2591         struct strbuf buf = STRBUF_INIT;
2592
2593         for (i = 0; i < opts->xopts_nr; ++i)
2594                 strbuf_addf(&buf, " --%s", opts->xopts[i]);
2595
2596         write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
2597         strbuf_release(&buf);
2598 }
2599
2600 int write_basic_state(struct replay_opts *opts, const char *head_name,
2601                       struct commit *onto, const char *orig_head)
2602 {
2603         if (head_name)
2604                 write_file(rebase_path_head_name(), "%s\n", head_name);
2605         if (onto)
2606                 write_file(rebase_path_onto(), "%s\n",
2607                            oid_to_hex(&onto->object.oid));
2608         if (orig_head)
2609                 write_file(rebase_path_orig_head(), "%s\n", orig_head);
2610
2611         if (opts->quiet)
2612                 write_file(rebase_path_quiet(), "%s", "");
2613         if (opts->verbose)
2614                 write_file(rebase_path_verbose(), "%s", "");
2615         if (opts->strategy)
2616                 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
2617         if (opts->xopts_nr > 0)
2618                 write_strategy_opts(opts);
2619
2620         if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
2621                 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
2622         else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
2623                 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
2624
2625         if (opts->gpg_sign)
2626                 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
2627         if (opts->signoff)
2628                 write_file(rebase_path_signoff(), "--signoff\n");
2629         if (opts->drop_redundant_commits)
2630                 write_file(rebase_path_drop_redundant_commits(), "%s", "");
2631         if (opts->keep_redundant_commits)
2632                 write_file(rebase_path_keep_redundant_commits(), "%s", "");
2633         if (opts->reschedule_failed_exec)
2634                 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
2635
2636         return 0;
2637 }
2638
2639 static int walk_revs_populate_todo(struct todo_list *todo_list,
2640                                 struct replay_opts *opts)
2641 {
2642         enum todo_command command = opts->action == REPLAY_PICK ?
2643                 TODO_PICK : TODO_REVERT;
2644         const char *command_string = todo_command_info[command].str;
2645         const char *encoding;
2646         struct commit *commit;
2647
2648         if (prepare_revs(opts))
2649                 return -1;
2650
2651         encoding = get_log_output_encoding();
2652
2653         while ((commit = get_revision(opts->revs))) {
2654                 struct todo_item *item = append_new_todo(todo_list);
2655                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
2656                 const char *subject;
2657                 int subject_len;
2658
2659                 item->command = command;
2660                 item->commit = commit;
2661                 item->arg_offset = 0;
2662                 item->arg_len = 0;
2663                 item->offset_in_buf = todo_list->buf.len;
2664                 subject_len = find_commit_subject(commit_buffer, &subject);
2665                 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
2666                         short_commit_name(commit), subject_len, subject);
2667                 unuse_commit_buffer(commit, commit_buffer);
2668         }
2669
2670         if (!todo_list->nr)
2671                 return error(_("empty commit set passed"));
2672
2673         return 0;
2674 }
2675
2676 static int create_seq_dir(struct repository *r)
2677 {
2678         enum replay_action action;
2679         const char *in_progress_error = NULL;
2680         const char *in_progress_advice = NULL;
2681         unsigned int advise_skip =
2682                 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
2683                 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
2684
2685         if (!sequencer_get_last_command(r, &action)) {
2686                 switch (action) {
2687                 case REPLAY_REVERT:
2688                         in_progress_error = _("revert is already in progress");
2689                         in_progress_advice =
2690                         _("try \"git revert (--continue | %s--abort | --quit)\"");
2691                         break;
2692                 case REPLAY_PICK:
2693                         in_progress_error = _("cherry-pick is already in progress");
2694                         in_progress_advice =
2695                         _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
2696                         break;
2697                 default:
2698                         BUG("unexpected action in create_seq_dir");
2699                 }
2700         }
2701         if (in_progress_error) {
2702                 error("%s", in_progress_error);
2703                 if (advice_sequencer_in_use)
2704                         advise(in_progress_advice,
2705                                 advise_skip ? "--skip | " : "");
2706                 return -1;
2707         }
2708         if (mkdir(git_path_seq_dir(), 0777) < 0)
2709                 return error_errno(_("could not create sequencer directory '%s'"),
2710                                    git_path_seq_dir());
2711
2712         return 0;
2713 }
2714
2715 static int save_head(const char *head)
2716 {
2717         struct lock_file head_lock = LOCK_INIT;
2718         struct strbuf buf = STRBUF_INIT;
2719         int fd;
2720         ssize_t written;
2721
2722         fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
2723         if (fd < 0)
2724                 return error_errno(_("could not lock HEAD"));
2725         strbuf_addf(&buf, "%s\n", head);
2726         written = write_in_full(fd, buf.buf, buf.len);
2727         strbuf_release(&buf);
2728         if (written < 0) {
2729                 error_errno(_("could not write to '%s'"), git_path_head_file());
2730                 rollback_lock_file(&head_lock);
2731                 return -1;
2732         }
2733         if (commit_lock_file(&head_lock) < 0)
2734                 return error(_("failed to finalize '%s'"), git_path_head_file());
2735         return 0;
2736 }
2737
2738 static int rollback_is_safe(void)
2739 {
2740         struct strbuf sb = STRBUF_INIT;
2741         struct object_id expected_head, actual_head;
2742
2743         if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
2744                 strbuf_trim(&sb);
2745                 if (get_oid_hex(sb.buf, &expected_head)) {
2746                         strbuf_release(&sb);
2747                         die(_("could not parse %s"), git_path_abort_safety_file());
2748                 }
2749                 strbuf_release(&sb);
2750         }
2751         else if (errno == ENOENT)
2752                 oidclr(&expected_head);
2753         else
2754                 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
2755
2756         if (get_oid("HEAD", &actual_head))
2757                 oidclr(&actual_head);
2758
2759         return oideq(&actual_head, &expected_head);
2760 }
2761
2762 static int reset_merge(const struct object_id *oid)
2763 {
2764         int ret;
2765         struct strvec argv = STRVEC_INIT;
2766
2767         strvec_pushl(&argv, "reset", "--merge", NULL);
2768
2769         if (!is_null_oid(oid))
2770                 strvec_push(&argv, oid_to_hex(oid));
2771
2772         ret = run_command_v_opt(argv.v, RUN_GIT_CMD);
2773         strvec_clear(&argv);
2774
2775         return ret;
2776 }
2777
2778 static int rollback_single_pick(struct repository *r)
2779 {
2780         struct object_id head_oid;
2781
2782         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
2783             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
2784                 return error(_("no cherry-pick or revert in progress"));
2785         if (read_ref_full("HEAD", 0, &head_oid, NULL))
2786                 return error(_("cannot resolve HEAD"));
2787         if (is_null_oid(&head_oid))
2788                 return error(_("cannot abort from a branch yet to be born"));
2789         return reset_merge(&head_oid);
2790 }
2791
2792 static int skip_single_pick(void)
2793 {
2794         struct object_id head;
2795
2796         if (read_ref_full("HEAD", 0, &head, NULL))
2797                 return error(_("cannot resolve HEAD"));
2798         return reset_merge(&head);
2799 }
2800
2801 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
2802 {
2803         FILE *f;
2804         struct object_id oid;
2805         struct strbuf buf = STRBUF_INIT;
2806         const char *p;
2807
2808         f = fopen(git_path_head_file(), "r");
2809         if (!f && errno == ENOENT) {
2810                 /*
2811                  * There is no multiple-cherry-pick in progress.
2812                  * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
2813                  * a single-cherry-pick in progress, abort that.
2814                  */
2815                 return rollback_single_pick(r);
2816         }
2817         if (!f)
2818                 return error_errno(_("cannot open '%s'"), git_path_head_file());
2819         if (strbuf_getline_lf(&buf, f)) {
2820                 error(_("cannot read '%s': %s"), git_path_head_file(),
2821                       ferror(f) ?  strerror(errno) : _("unexpected end of file"));
2822                 fclose(f);
2823                 goto fail;
2824         }
2825         fclose(f);
2826         if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
2827                 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
2828                         git_path_head_file());
2829                 goto fail;
2830         }
2831         if (is_null_oid(&oid)) {
2832                 error(_("cannot abort from a branch yet to be born"));
2833                 goto fail;
2834         }
2835
2836         if (!rollback_is_safe()) {
2837                 /* Do not error, just do not rollback */
2838                 warning(_("You seem to have moved HEAD. "
2839                           "Not rewinding, check your HEAD!"));
2840         } else
2841         if (reset_merge(&oid))
2842                 goto fail;
2843         strbuf_release(&buf);
2844         return sequencer_remove_state(opts);
2845 fail:
2846         strbuf_release(&buf);
2847         return -1;
2848 }
2849
2850 int sequencer_skip(struct repository *r, struct replay_opts *opts)
2851 {
2852         enum replay_action action = -1;
2853         sequencer_get_last_command(r, &action);
2854
2855         /*
2856          * Check whether the subcommand requested to skip the commit is actually
2857          * in progress and that it's safe to skip the commit.
2858          *
2859          * opts->action tells us which subcommand requested to skip the commit.
2860          * If the corresponding .git/<ACTION>_HEAD exists, we know that the
2861          * action is in progress and we can skip the commit.
2862          *
2863          * Otherwise we check that the last instruction was related to the
2864          * particular subcommand we're trying to execute and barf if that's not
2865          * the case.
2866          *
2867          * Finally we check that the rollback is "safe", i.e., has the HEAD
2868          * moved? In this case, it doesn't make sense to "reset the merge" and
2869          * "skip the commit" as the user already handled this by committing. But
2870          * we'd not want to barf here, instead give advice on how to proceed. We
2871          * only need to check that when .git/<ACTION>_HEAD doesn't exist because
2872          * it gets removed when the user commits, so if it still exists we're
2873          * sure the user can't have committed before.
2874          */
2875         switch (opts->action) {
2876         case REPLAY_REVERT:
2877                 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
2878                         if (action != REPLAY_REVERT)
2879                                 return error(_("no revert in progress"));
2880                         if (!rollback_is_safe())
2881                                 goto give_advice;
2882                 }
2883                 break;
2884         case REPLAY_PICK:
2885                 if (!refs_ref_exists(get_main_ref_store(r),
2886                                      "CHERRY_PICK_HEAD")) {
2887                         if (action != REPLAY_PICK)
2888                                 return error(_("no cherry-pick in progress"));
2889                         if (!rollback_is_safe())
2890                                 goto give_advice;
2891                 }
2892                 break;
2893         default:
2894                 BUG("unexpected action in sequencer_skip");
2895         }
2896
2897         if (skip_single_pick())
2898                 return error(_("failed to skip the commit"));
2899         if (!is_directory(git_path_seq_dir()))
2900                 return 0;
2901
2902         return sequencer_continue(r, opts);
2903
2904 give_advice:
2905         error(_("there is nothing to skip"));
2906
2907         if (advice_resolve_conflict) {
2908                 advise(_("have you committed already?\n"
2909                          "try \"git %s --continue\""),
2910                          action == REPLAY_REVERT ? "revert" : "cherry-pick");
2911         }
2912         return -1;
2913 }
2914
2915 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
2916 {
2917         struct lock_file todo_lock = LOCK_INIT;
2918         const char *todo_path = get_todo_path(opts);
2919         int next = todo_list->current, offset, fd;
2920
2921         /*
2922          * rebase -i writes "git-rebase-todo" without the currently executing
2923          * command, appending it to "done" instead.
2924          */
2925         if (is_rebase_i(opts))
2926                 next++;
2927
2928         fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
2929         if (fd < 0)
2930                 return error_errno(_("could not lock '%s'"), todo_path);
2931         offset = get_item_line_offset(todo_list, next);
2932         if (write_in_full(fd, todo_list->buf.buf + offset,
2933                         todo_list->buf.len - offset) < 0)
2934                 return error_errno(_("could not write to '%s'"), todo_path);
2935         if (commit_lock_file(&todo_lock) < 0)
2936                 return error(_("failed to finalize '%s'"), todo_path);
2937
2938         if (is_rebase_i(opts) && next > 0) {
2939                 const char *done = rebase_path_done();
2940                 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
2941                 int ret = 0;
2942
2943                 if (fd < 0)
2944                         return 0;
2945                 if (write_in_full(fd, get_item_line(todo_list, next - 1),
2946                                   get_item_line_length(todo_list, next - 1))
2947                     < 0)
2948                         ret = error_errno(_("could not write to '%s'"), done);
2949                 if (close(fd) < 0)
2950                         ret = error_errno(_("failed to finalize '%s'"), done);
2951                 return ret;
2952         }
2953         return 0;
2954 }
2955
2956 static int save_opts(struct replay_opts *opts)
2957 {
2958         const char *opts_file = git_path_opts_file();
2959         int res = 0;
2960
2961         if (opts->no_commit)
2962                 res |= git_config_set_in_file_gently(opts_file,
2963                                         "options.no-commit", "true");
2964         if (opts->edit)
2965                 res |= git_config_set_in_file_gently(opts_file,
2966                                         "options.edit", "true");
2967         if (opts->allow_empty)
2968                 res |= git_config_set_in_file_gently(opts_file,
2969                                         "options.allow-empty", "true");
2970         if (opts->allow_empty_message)
2971                 res |= git_config_set_in_file_gently(opts_file,
2972                                 "options.allow-empty-message", "true");
2973         if (opts->keep_redundant_commits)
2974                 res |= git_config_set_in_file_gently(opts_file,
2975                                 "options.keep-redundant-commits", "true");
2976         if (opts->signoff)
2977                 res |= git_config_set_in_file_gently(opts_file,
2978                                         "options.signoff", "true");
2979         if (opts->record_origin)
2980                 res |= git_config_set_in_file_gently(opts_file,
2981                                         "options.record-origin", "true");
2982         if (opts->allow_ff)
2983                 res |= git_config_set_in_file_gently(opts_file,
2984                                         "options.allow-ff", "true");
2985         if (opts->mainline) {
2986                 struct strbuf buf = STRBUF_INIT;
2987                 strbuf_addf(&buf, "%d", opts->mainline);
2988                 res |= git_config_set_in_file_gently(opts_file,
2989                                         "options.mainline", buf.buf);
2990                 strbuf_release(&buf);
2991         }
2992         if (opts->strategy)
2993                 res |= git_config_set_in_file_gently(opts_file,
2994                                         "options.strategy", opts->strategy);
2995         if (opts->gpg_sign)
2996                 res |= git_config_set_in_file_gently(opts_file,
2997                                         "options.gpg-sign", opts->gpg_sign);
2998         if (opts->xopts) {
2999                 int i;
3000                 for (i = 0; i < opts->xopts_nr; i++)
3001                         res |= git_config_set_multivar_in_file_gently(opts_file,
3002                                         "options.strategy-option",
3003                                         opts->xopts[i], "^$", 0);
3004         }
3005         if (opts->allow_rerere_auto)
3006                 res |= git_config_set_in_file_gently(opts_file,
3007                                 "options.allow-rerere-auto",
3008                                 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3009                                 "true" : "false");
3010
3011         if (opts->explicit_cleanup)
3012                 res |= git_config_set_in_file_gently(opts_file,
3013                                 "options.default-msg-cleanup",
3014                                 describe_cleanup_mode(opts->default_msg_cleanup));
3015         return res;
3016 }
3017
3018 static int make_patch(struct repository *r,
3019                       struct commit *commit,
3020                       struct replay_opts *opts)
3021 {
3022         struct strbuf buf = STRBUF_INIT;
3023         struct rev_info log_tree_opt;
3024         const char *subject, *p;
3025         int res = 0;
3026
3027         p = short_commit_name(commit);
3028         if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
3029                 return -1;
3030         res |= write_rebase_head(&commit->object.oid);
3031
3032         strbuf_addf(&buf, "%s/patch", get_dir(opts));
3033         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3034         repo_init_revisions(r, &log_tree_opt, NULL);
3035         log_tree_opt.abbrev = 0;
3036         log_tree_opt.diff = 1;
3037         log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3038         log_tree_opt.disable_stdin = 1;
3039         log_tree_opt.no_commit_id = 1;
3040         log_tree_opt.diffopt.file = fopen(buf.buf, "w");
3041         log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3042         if (!log_tree_opt.diffopt.file)
3043                 res |= error_errno(_("could not open '%s'"), buf.buf);
3044         else {
3045                 res |= log_tree_commit(&log_tree_opt, commit);
3046                 fclose(log_tree_opt.diffopt.file);
3047         }
3048         strbuf_reset(&buf);
3049
3050         strbuf_addf(&buf, "%s/message", get_dir(opts));
3051         if (!file_exists(buf.buf)) {
3052                 const char *encoding = get_commit_output_encoding();
3053                 const char *commit_buffer = logmsg_reencode(commit, NULL, encoding);
3054                 find_commit_subject(commit_buffer, &subject);
3055                 res |= write_message(subject, strlen(subject), buf.buf, 1);
3056                 unuse_commit_buffer(commit, commit_buffer);
3057         }
3058         strbuf_release(&buf);
3059
3060         return res;
3061 }
3062
3063 static int intend_to_amend(void)
3064 {
3065         struct object_id head;
3066         char *p;
3067
3068         if (get_oid("HEAD", &head))
3069                 return error(_("cannot read HEAD"));
3070
3071         p = oid_to_hex(&head);
3072         return write_message(p, strlen(p), rebase_path_amend(), 1);
3073 }
3074
3075 static int error_with_patch(struct repository *r,
3076                             struct commit *commit,
3077                             const char *subject, int subject_len,
3078                             struct replay_opts *opts,
3079                             int exit_code, int to_amend)
3080 {
3081         if (commit) {
3082                 if (make_patch(r, commit, opts))
3083                         return -1;
3084         } else if (copy_file(rebase_path_message(),
3085                              git_path_merge_msg(r), 0666))
3086                 return error(_("unable to copy '%s' to '%s'"),
3087                              git_path_merge_msg(r), rebase_path_message());
3088
3089         if (to_amend) {
3090                 if (intend_to_amend())
3091                         return -1;
3092
3093                 fprintf(stderr,
3094                         _("You can amend the commit now, with\n"
3095                           "\n"
3096                           "  git commit --amend %s\n"
3097                           "\n"
3098                           "Once you are satisfied with your changes, run\n"
3099                           "\n"
3100                           "  git rebase --continue\n"),
3101                         gpg_sign_opt_quoted(opts));
3102         } else if (exit_code) {
3103                 if (commit)
3104                         fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3105                                    short_commit_name(commit), subject_len, subject);
3106                 else
3107                         /*
3108                          * We don't have the hash of the parent so
3109                          * just print the line from the todo file.
3110                          */
3111                         fprintf_ln(stderr, _("Could not merge %.*s"),
3112                                    subject_len, subject);
3113         }
3114
3115         return exit_code;
3116 }
3117
3118 static int error_failed_squash(struct repository *r,
3119                                struct commit *commit,
3120                                struct replay_opts *opts,
3121                                int subject_len,
3122                                const char *subject)
3123 {
3124         if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
3125                 return error(_("could not copy '%s' to '%s'"),
3126                         rebase_path_squash_msg(), rebase_path_message());
3127         unlink(git_path_merge_msg(r));
3128         if (copy_file(git_path_merge_msg(r), rebase_path_message(), 0666))
3129                 return error(_("could not copy '%s' to '%s'"),
3130                              rebase_path_message(),
3131                              git_path_merge_msg(r));
3132         return error_with_patch(r, commit, subject, subject_len, opts, 1, 0);
3133 }
3134
3135 static int do_exec(struct repository *r, const char *command_line)
3136 {
3137         struct strvec child_env = STRVEC_INIT;
3138         const char *child_argv[] = { NULL, NULL };
3139         int dirty, status;
3140
3141         fprintf(stderr, _("Executing: %s\n"), command_line);
3142         child_argv[0] = command_line;
3143         strvec_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
3144         strvec_pushf(&child_env, "GIT_WORK_TREE=%s",
3145                      absolute_path(get_git_work_tree()));
3146         status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
3147                                           child_env.v);
3148
3149         /* force re-reading of the cache */
3150         if (discard_index(r->index) < 0 || repo_read_index(r) < 0)
3151                 return error(_("could not read index"));
3152
3153         dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3154
3155         if (status) {
3156                 warning(_("execution failed: %s\n%s"
3157                           "You can fix the problem, and then run\n"
3158                           "\n"
3159                           "  git rebase --continue\n"
3160                           "\n"),
3161                         command_line,
3162                         dirty ? N_("and made changes to the index and/or the "
3163                                 "working tree\n") : "");
3164                 if (status == 127)
3165                         /* command not found */
3166                         status = 1;
3167         } else if (dirty) {
3168                 warning(_("execution succeeded: %s\nbut "
3169                           "left changes to the index and/or the working tree\n"
3170                           "Commit or stash your changes, and then run\n"
3171                           "\n"
3172                           "  git rebase --continue\n"
3173                           "\n"), command_line);
3174                 status = 1;
3175         }
3176
3177         strvec_clear(&child_env);
3178
3179         return status;
3180 }
3181
3182 static int safe_append(const char *filename, const char *fmt, ...)
3183 {
3184         va_list ap;
3185         struct lock_file lock = LOCK_INIT;
3186         int fd = hold_lock_file_for_update(&lock, filename,
3187                                            LOCK_REPORT_ON_ERROR);
3188         struct strbuf buf = STRBUF_INIT;
3189
3190         if (fd < 0)
3191                 return -1;
3192
3193         if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3194                 error_errno(_("could not read '%s'"), filename);
3195                 rollback_lock_file(&lock);
3196                 return -1;
3197         }
3198         strbuf_complete(&buf, '\n');
3199         va_start(ap, fmt);
3200         strbuf_vaddf(&buf, fmt, ap);
3201         va_end(ap);
3202
3203         if (write_in_full(fd, buf.buf, buf.len) < 0) {
3204                 error_errno(_("could not write to '%s'"), filename);
3205                 strbuf_release(&buf);
3206                 rollback_lock_file(&lock);
3207                 return -1;
3208         }
3209         if (commit_lock_file(&lock) < 0) {
3210                 strbuf_release(&buf);
3211                 rollback_lock_file(&lock);
3212                 return error(_("failed to finalize '%s'"), filename);
3213         }
3214
3215         strbuf_release(&buf);
3216         return 0;
3217 }
3218
3219 static int do_label(struct repository *r, const char *name, int len)
3220 {
3221         struct ref_store *refs = get_main_ref_store(r);
3222         struct ref_transaction *transaction;
3223         struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3224         struct strbuf msg = STRBUF_INIT;
3225         int ret = 0;
3226         struct object_id head_oid;
3227
3228         if (len == 1 && *name == '#')
3229                 return error(_("illegal label name: '%.*s'"), len, name);
3230
3231         strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3232         strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
3233
3234         transaction = ref_store_transaction_begin(refs, &err);
3235         if (!transaction) {
3236                 error("%s", err.buf);
3237                 ret = -1;
3238         } else if (get_oid("HEAD", &head_oid)) {
3239                 error(_("could not read HEAD"));
3240                 ret = -1;
3241         } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
3242                                           NULL, 0, msg.buf, &err) < 0 ||
3243                    ref_transaction_commit(transaction, &err)) {
3244                 error("%s", err.buf);
3245                 ret = -1;
3246         }
3247         ref_transaction_free(transaction);
3248         strbuf_release(&err);
3249         strbuf_release(&msg);
3250
3251         if (!ret)
3252                 ret = safe_append(rebase_path_refs_to_delete(),
3253                                   "%s\n", ref_name.buf);
3254         strbuf_release(&ref_name);
3255
3256         return ret;
3257 }
3258
3259 static const char *reflog_message(struct replay_opts *opts,
3260         const char *sub_action, const char *fmt, ...);
3261
3262 static int do_reset(struct repository *r,
3263                     const char *name, int len,
3264                     struct replay_opts *opts)
3265 {
3266         struct strbuf ref_name = STRBUF_INIT;
3267         struct object_id oid;
3268         struct lock_file lock = LOCK_INIT;
3269         struct tree_desc desc;
3270         struct tree *tree;
3271         struct unpack_trees_options unpack_tree_opts;
3272         int ret = 0;
3273
3274         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
3275                 return -1;
3276
3277         if (len == 10 && !strncmp("[new root]", name, len)) {
3278                 if (!opts->have_squash_onto) {
3279                         const char *hex;
3280                         if (commit_tree("", 0, the_hash_algo->empty_tree,
3281                                         NULL, &opts->squash_onto,
3282                                         NULL, NULL))
3283                                 return error(_("writing fake root commit"));
3284                         opts->have_squash_onto = 1;
3285                         hex = oid_to_hex(&opts->squash_onto);
3286                         if (write_message(hex, strlen(hex),
3287                                           rebase_path_squash_onto(), 0))
3288                                 return error(_("writing squash-onto"));
3289                 }
3290                 oidcpy(&oid, &opts->squash_onto);
3291         } else {
3292                 int i;
3293
3294                 /* Determine the length of the label */
3295                 for (i = 0; i < len; i++)
3296                         if (isspace(name[i]))
3297                                 break;
3298                 len = i;
3299
3300                 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
3301                 if (get_oid(ref_name.buf, &oid) &&
3302                     get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
3303                         error(_("could not read '%s'"), ref_name.buf);
3304                         rollback_lock_file(&lock);
3305                         strbuf_release(&ref_name);
3306                         return -1;
3307                 }
3308         }
3309
3310         memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
3311         setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
3312         unpack_tree_opts.head_idx = 1;
3313         unpack_tree_opts.src_index = r->index;
3314         unpack_tree_opts.dst_index = r->index;
3315         unpack_tree_opts.fn = oneway_merge;
3316         unpack_tree_opts.merge = 1;
3317         unpack_tree_opts.update = 1;
3318         init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
3319
3320         if (repo_read_index_unmerged(r)) {
3321                 rollback_lock_file(&lock);
3322                 strbuf_release(&ref_name);
3323                 return error_resolve_conflict(_(action_name(opts)));
3324         }
3325
3326         if (!fill_tree_descriptor(r, &desc, &oid)) {
3327                 error(_("failed to find tree of %s"), oid_to_hex(&oid));
3328                 rollback_lock_file(&lock);
3329                 free((void *)desc.buffer);
3330                 strbuf_release(&ref_name);
3331                 return -1;
3332         }
3333
3334         if (unpack_trees(1, &desc, &unpack_tree_opts)) {
3335                 rollback_lock_file(&lock);
3336                 free((void *)desc.buffer);
3337                 strbuf_release(&ref_name);
3338                 return -1;
3339         }
3340
3341         tree = parse_tree_indirect(&oid);
3342         prime_cache_tree(r, r->index, tree);
3343
3344         if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
3345                 ret = error(_("could not write index"));
3346         free((void *)desc.buffer);
3347
3348         if (!ret)
3349                 ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
3350                                                 len, name), "HEAD", &oid,
3351                                  NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3352
3353         strbuf_release(&ref_name);
3354         return ret;
3355 }
3356
3357 static struct commit *lookup_label(const char *label, int len,
3358                                    struct strbuf *buf)
3359 {
3360         struct commit *commit;
3361
3362         strbuf_reset(buf);
3363         strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
3364         commit = lookup_commit_reference_by_name(buf->buf);
3365         if (!commit) {
3366                 /* fall back to non-rewritten ref or commit */
3367                 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
3368                 commit = lookup_commit_reference_by_name(buf->buf);
3369         }
3370
3371         if (!commit)
3372                 error(_("could not resolve '%s'"), buf->buf);
3373
3374         return commit;
3375 }
3376
3377 static int do_merge(struct repository *r,
3378                     struct commit *commit,
3379                     const char *arg, int arg_len,
3380                     int flags, struct replay_opts *opts)
3381 {
3382         int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
3383                 EDIT_MSG | VERIFY_MSG : 0;
3384         struct strbuf ref_name = STRBUF_INIT;
3385         struct commit *head_commit, *merge_commit, *i;
3386         struct commit_list *bases, *j, *reversed = NULL;
3387         struct commit_list *to_merge = NULL, **tail = &to_merge;
3388         const char *strategy = !opts->xopts_nr &&
3389                 (!opts->strategy || !strcmp(opts->strategy, "recursive")) ?
3390                 NULL : opts->strategy;
3391         struct merge_options o;
3392         int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
3393         static struct lock_file lock;
3394         const char *p;
3395
3396         if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
3397                 ret = -1;
3398                 goto leave_merge;
3399         }
3400
3401         head_commit = lookup_commit_reference_by_name("HEAD");
3402         if (!head_commit) {
3403                 ret = error(_("cannot merge without a current revision"));
3404                 goto leave_merge;
3405         }
3406
3407         /*
3408          * For octopus merges, the arg starts with the list of revisions to be
3409          * merged. The list is optionally followed by '#' and the oneline.
3410          */
3411         merge_arg_len = oneline_offset = arg_len;
3412         for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
3413                 if (!*p)
3414                         break;
3415                 if (*p == '#' && (!p[1] || isspace(p[1]))) {
3416                         p += 1 + strspn(p + 1, " \t\n");
3417                         oneline_offset = p - arg;
3418                         break;
3419                 }
3420                 k = strcspn(p, " \t\n");
3421                 if (!k)
3422                         continue;
3423                 merge_commit = lookup_label(p, k, &ref_name);
3424                 if (!merge_commit) {
3425                         ret = error(_("unable to parse '%.*s'"), k, p);
3426                         goto leave_merge;
3427                 }
3428                 tail = &commit_list_insert(merge_commit, tail)->next;
3429                 p += k;
3430                 merge_arg_len = p - arg;
3431         }
3432
3433         if (!to_merge) {
3434                 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
3435                 goto leave_merge;
3436         }
3437
3438         if (opts->have_squash_onto &&
3439             oideq(&head_commit->object.oid, &opts->squash_onto)) {
3440                 /*
3441                  * When the user tells us to "merge" something into a
3442                  * "[new root]", let's simply fast-forward to the merge head.
3443                  */
3444                 rollback_lock_file(&lock);
3445                 if (to_merge->next)
3446                         ret = error(_("octopus merge cannot be executed on "
3447                                       "top of a [new root]"));
3448                 else
3449                         ret = fast_forward_to(r, &to_merge->item->object.oid,
3450                                               &head_commit->object.oid, 0,
3451                                               opts);
3452                 goto leave_merge;
3453         }
3454
3455         if (commit) {
3456                 const char *encoding = get_commit_output_encoding();
3457                 const char *message = logmsg_reencode(commit, NULL, encoding);
3458                 const char *body;
3459                 int len;
3460
3461                 if (!message) {
3462                         ret = error(_("could not get commit message of '%s'"),
3463                                     oid_to_hex(&commit->object.oid));
3464                         goto leave_merge;
3465                 }
3466                 write_author_script(message);
3467                 find_commit_subject(message, &body);
3468                 len = strlen(body);
3469                 ret = write_message(body, len, git_path_merge_msg(r), 0);
3470                 unuse_commit_buffer(commit, message);
3471                 if (ret) {
3472                         error_errno(_("could not write '%s'"),
3473                                     git_path_merge_msg(r));
3474                         goto leave_merge;
3475                 }
3476         } else {
3477                 struct strbuf buf = STRBUF_INIT;
3478                 int len;
3479
3480                 strbuf_addf(&buf, "author %s", git_author_info(0));
3481                 write_author_script(buf.buf);
3482                 strbuf_reset(&buf);
3483
3484                 if (oneline_offset < arg_len) {
3485                         p = arg + oneline_offset;
3486                         len = arg_len - oneline_offset;
3487                 } else {
3488                         strbuf_addf(&buf, "Merge %s '%.*s'",
3489                                     to_merge->next ? "branches" : "branch",
3490                                     merge_arg_len, arg);
3491                         p = buf.buf;
3492                         len = buf.len;
3493                 }
3494
3495                 ret = write_message(p, len, git_path_merge_msg(r), 0);
3496                 strbuf_release(&buf);
3497                 if (ret) {
3498                         error_errno(_("could not write '%s'"),
3499                                     git_path_merge_msg(r));
3500                         goto leave_merge;
3501                 }
3502         }
3503
3504         /*
3505          * If HEAD is not identical to the first parent of the original merge
3506          * commit, we cannot fast-forward.
3507          */
3508         can_fast_forward = opts->allow_ff && commit && commit->parents &&
3509                 oideq(&commit->parents->item->object.oid,
3510                       &head_commit->object.oid);
3511
3512         /*
3513          * If any merge head is different from the original one, we cannot
3514          * fast-forward.
3515          */
3516         if (can_fast_forward) {
3517                 struct commit_list *p = commit->parents->next;
3518
3519                 for (j = to_merge; j && p; j = j->next, p = p->next)
3520                         if (!oideq(&j->item->object.oid,
3521                                    &p->item->object.oid)) {
3522                                 can_fast_forward = 0;
3523                                 break;
3524                         }
3525                 /*
3526                  * If the number of merge heads differs from the original merge
3527                  * commit, we cannot fast-forward.
3528                  */
3529                 if (j || p)
3530                         can_fast_forward = 0;
3531         }
3532
3533         if (can_fast_forward) {
3534                 rollback_lock_file(&lock);
3535                 ret = fast_forward_to(r, &commit->object.oid,
3536                                       &head_commit->object.oid, 0, opts);
3537                 if (flags & TODO_EDIT_MERGE_MSG) {
3538                         run_commit_flags |= AMEND_MSG;
3539                         goto fast_forward_edit;
3540                 }
3541                 goto leave_merge;
3542         }
3543
3544         if (strategy || to_merge->next) {
3545                 /* Octopus merge */
3546                 struct child_process cmd = CHILD_PROCESS_INIT;
3547
3548                 if (read_env_script(&cmd.env_array)) {
3549                         const char *gpg_opt = gpg_sign_opt_quoted(opts);
3550
3551                         ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
3552                         goto leave_merge;
3553                 }
3554
3555                 cmd.git_cmd = 1;
3556                 strvec_push(&cmd.args, "merge");
3557                 strvec_push(&cmd.args, "-s");
3558                 if (!strategy)
3559                         strvec_push(&cmd.args, "octopus");
3560                 else {
3561                         strvec_push(&cmd.args, strategy);
3562                         for (k = 0; k < opts->xopts_nr; k++)
3563                                 strvec_pushf(&cmd.args,
3564                                              "-X%s", opts->xopts[k]);
3565                 }
3566                 strvec_push(&cmd.args, "--no-edit");
3567                 strvec_push(&cmd.args, "--no-ff");
3568                 strvec_push(&cmd.args, "--no-log");
3569                 strvec_push(&cmd.args, "--no-stat");
3570                 strvec_push(&cmd.args, "-F");
3571                 strvec_push(&cmd.args, git_path_merge_msg(r));
3572                 if (opts->gpg_sign)
3573                         strvec_push(&cmd.args, opts->gpg_sign);
3574
3575                 /* Add the tips to be merged */
3576                 for (j = to_merge; j; j = j->next)
3577                         strvec_push(&cmd.args,
3578                                     oid_to_hex(&j->item->object.oid));
3579
3580                 strbuf_release(&ref_name);
3581                 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
3582                                 NULL, 0);
3583                 rollback_lock_file(&lock);
3584
3585                 rollback_lock_file(&lock);
3586                 ret = run_command(&cmd);
3587
3588                 /* force re-reading of the cache */
3589                 if (!ret && (discard_index(r->index) < 0 ||
3590                              repo_read_index(r) < 0))
3591                         ret = error(_("could not read index"));
3592                 goto leave_merge;
3593         }
3594
3595         merge_commit = to_merge->item;
3596         bases = get_merge_bases(head_commit, merge_commit);
3597         if (bases && oideq(&merge_commit->object.oid,
3598                            &bases->item->object.oid)) {
3599                 ret = 0;
3600                 /* skip merging an ancestor of HEAD */
3601                 goto leave_merge;
3602         }
3603
3604         write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
3605                       git_path_merge_head(r), 0);
3606         write_message("no-ff", 5, git_path_merge_mode(r), 0);
3607
3608         for (j = bases; j; j = j->next)
3609                 commit_list_insert(j->item, &reversed);
3610         free_commit_list(bases);
3611
3612         repo_read_index(r);
3613         init_merge_options(&o, r);
3614         o.branch1 = "HEAD";
3615         o.branch2 = ref_name.buf;
3616         o.buffer_output = 2;
3617
3618         ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
3619         if (ret <= 0)
3620                 fputs(o.obuf.buf, stdout);
3621         strbuf_release(&o.obuf);
3622         if (ret < 0) {
3623                 error(_("could not even attempt to merge '%.*s'"),
3624                       merge_arg_len, arg);
3625                 goto leave_merge;
3626         }
3627         /*
3628          * The return value of merge_recursive() is 1 on clean, and 0 on
3629          * unclean merge.
3630          *
3631          * Let's reverse that, so that do_merge() returns 0 upon success and
3632          * 1 upon failed merge (keeping the return value -1 for the cases where
3633          * we will want to reschedule the `merge` command).
3634          */
3635         ret = !ret;
3636
3637         if (r->index->cache_changed &&
3638             write_locked_index(r->index, &lock, COMMIT_LOCK)) {
3639                 ret = error(_("merge: Unable to write new index file"));
3640                 goto leave_merge;
3641         }
3642
3643         rollback_lock_file(&lock);
3644         if (ret)
3645                 repo_rerere(r, opts->allow_rerere_auto);
3646         else
3647                 /*
3648                  * In case of problems, we now want to return a positive
3649                  * value (a negative one would indicate that the `merge`
3650                  * command needs to be rescheduled).
3651                  */
3652         fast_forward_edit:
3653                 ret = !!run_git_commit(r, git_path_merge_msg(r), opts,
3654                                        run_commit_flags);
3655
3656 leave_merge:
3657         strbuf_release(&ref_name);
3658         rollback_lock_file(&lock);
3659         free_commit_list(to_merge);
3660         return ret;
3661 }
3662
3663 static int is_final_fixup(struct todo_list *todo_list)
3664 {
3665         int i = todo_list->current;
3666
3667         if (!is_fixup(todo_list->items[i].command))
3668                 return 0;
3669
3670         while (++i < todo_list->nr)
3671                 if (is_fixup(todo_list->items[i].command))
3672                         return 0;
3673                 else if (!is_noop(todo_list->items[i].command))
3674                         break;
3675         return 1;
3676 }
3677
3678 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
3679 {
3680         int i;
3681
3682         for (i = todo_list->current + offset; i < todo_list->nr; i++)
3683                 if (!is_noop(todo_list->items[i].command))
3684                         return todo_list->items[i].command;
3685
3686         return -1;
3687 }
3688
3689 void create_autostash(struct repository *r, const char *path,
3690                       const char *default_reflog_action)
3691 {
3692         struct strbuf buf = STRBUF_INIT;
3693         struct lock_file lock_file = LOCK_INIT;
3694         int fd;
3695
3696         fd = repo_hold_locked_index(r, &lock_file, 0);
3697         refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
3698         if (0 <= fd)
3699                 repo_update_index_if_able(r, &lock_file);
3700         rollback_lock_file(&lock_file);
3701
3702         if (has_unstaged_changes(r, 1) ||
3703             has_uncommitted_changes(r, 1)) {
3704                 struct child_process stash = CHILD_PROCESS_INIT;
3705                 struct object_id oid;
3706
3707                 strvec_pushl(&stash.args,
3708                              "stash", "create", "autostash", NULL);
3709                 stash.git_cmd = 1;
3710                 stash.no_stdin = 1;
3711                 strbuf_reset(&buf);
3712                 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
3713                         die(_("Cannot autostash"));
3714                 strbuf_trim_trailing_newline(&buf);
3715                 if (get_oid(buf.buf, &oid))
3716                         die(_("Unexpected stash response: '%s'"),
3717                             buf.buf);
3718                 strbuf_reset(&buf);
3719                 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
3720
3721                 if (safe_create_leading_directories_const(path))
3722                         die(_("Could not create directory for '%s'"),
3723                             path);
3724                 write_file(path, "%s", oid_to_hex(&oid));
3725                 printf(_("Created autostash: %s\n"), buf.buf);
3726                 if (reset_head(r, NULL, "reset --hard",
3727                                NULL, RESET_HEAD_HARD, NULL, NULL,
3728                                default_reflog_action) < 0)
3729                         die(_("could not reset --hard"));
3730
3731                 if (discard_index(r->index) < 0 ||
3732                         repo_read_index(r) < 0)
3733                         die(_("could not read index"));
3734         }
3735         strbuf_release(&buf);
3736 }
3737
3738 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply)
3739 {
3740         struct child_process child = CHILD_PROCESS_INIT;
3741         int ret = 0;
3742
3743         if (attempt_apply) {
3744                 child.git_cmd = 1;
3745                 child.no_stdout = 1;
3746                 child.no_stderr = 1;
3747                 strvec_push(&child.args, "stash");
3748                 strvec_push(&child.args, "apply");
3749                 strvec_push(&child.args, stash_oid);
3750                 ret = run_command(&child);
3751         }
3752
3753         if (attempt_apply && !ret)
3754                 fprintf(stderr, _("Applied autostash.\n"));
3755         else {
3756                 struct child_process store = CHILD_PROCESS_INIT;
3757
3758                 store.git_cmd = 1;
3759                 strvec_push(&store.args, "stash");
3760                 strvec_push(&store.args, "store");
3761                 strvec_push(&store.args, "-m");
3762                 strvec_push(&store.args, "autostash");
3763                 strvec_push(&store.args, "-q");
3764                 strvec_push(&store.args, stash_oid);
3765                 if (run_command(&store))
3766                         ret = error(_("cannot store %s"), stash_oid);
3767                 else
3768                         fprintf(stderr,
3769                                 _("%s\n"
3770                                   "Your changes are safe in the stash.\n"
3771                                   "You can run \"git stash pop\" or"
3772                                   " \"git stash drop\" at any time.\n"),
3773                                 attempt_apply ?
3774                                 _("Applying autostash resulted in conflicts.") :
3775                                 _("Autostash exists; creating a new stash entry."));
3776         }
3777
3778         return ret;
3779 }
3780
3781 static int apply_save_autostash(const char *path, int attempt_apply)
3782 {
3783         struct strbuf stash_oid = STRBUF_INIT;
3784         int ret = 0;
3785
3786         if (!read_oneliner(&stash_oid, path,
3787                            READ_ONELINER_SKIP_IF_EMPTY)) {
3788                 strbuf_release(&stash_oid);
3789                 return 0;
3790         }
3791         strbuf_trim(&stash_oid);
3792
3793         ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply);
3794
3795         unlink(path);
3796         strbuf_release(&stash_oid);
3797         return ret;
3798 }
3799
3800 int save_autostash(const char *path)
3801 {
3802         return apply_save_autostash(path, 0);
3803 }
3804
3805 int apply_autostash(const char *path)
3806 {
3807         return apply_save_autostash(path, 1);
3808 }
3809
3810 int apply_autostash_oid(const char *stash_oid)
3811 {
3812         return apply_save_autostash_oid(stash_oid, 1);
3813 }
3814
3815 static const char *reflog_message(struct replay_opts *opts,
3816         const char *sub_action, const char *fmt, ...)
3817 {
3818         va_list ap;
3819         static struct strbuf buf = STRBUF_INIT;
3820         char *reflog_action = getenv(GIT_REFLOG_ACTION);
3821
3822         va_start(ap, fmt);
3823         strbuf_reset(&buf);
3824         strbuf_addstr(&buf, reflog_action ? reflog_action : action_name(opts));
3825         if (sub_action)
3826                 strbuf_addf(&buf, " (%s)", sub_action);
3827         if (fmt) {
3828                 strbuf_addstr(&buf, ": ");
3829                 strbuf_vaddf(&buf, fmt, ap);
3830         }
3831         va_end(ap);
3832
3833         return buf.buf;
3834 }
3835
3836 static int run_git_checkout(struct repository *r, struct replay_opts *opts,
3837                             const char *commit, const char *action)
3838 {
3839         struct child_process cmd = CHILD_PROCESS_INIT;
3840         int ret;
3841
3842         cmd.git_cmd = 1;
3843
3844         strvec_push(&cmd.args, "checkout");
3845         strvec_push(&cmd.args, commit);
3846         strvec_pushf(&cmd.env_array, GIT_REFLOG_ACTION "=%s", action);
3847
3848         if (opts->verbose)
3849                 ret = run_command(&cmd);
3850         else
3851                 ret = run_command_silent_on_success(&cmd);
3852
3853         if (!ret)
3854                 discard_index(r->index);
3855
3856         return ret;
3857 }
3858
3859 static int checkout_onto(struct repository *r, struct replay_opts *opts,
3860                          const char *onto_name, const struct object_id *onto,
3861                          const char *orig_head)
3862 {
3863         struct object_id oid;
3864         const char *action = reflog_message(opts, "start", "checkout %s", onto_name);
3865
3866         if (get_oid(orig_head, &oid))
3867                 return error(_("%s: not a valid OID"), orig_head);
3868
3869         if (run_git_checkout(r, opts, oid_to_hex(onto), action)) {
3870                 apply_autostash(rebase_path_autostash());
3871                 sequencer_remove_state(opts);
3872                 return error(_("could not detach HEAD"));
3873         }
3874
3875         return update_ref(NULL, "ORIG_HEAD", &oid, NULL, 0, UPDATE_REFS_MSG_ON_ERR);
3876 }
3877
3878 static int stopped_at_head(struct repository *r)
3879 {
3880         struct object_id head;
3881         struct commit *commit;
3882         struct commit_message message;
3883
3884         if (get_oid("HEAD", &head) ||
3885             !(commit = lookup_commit(r, &head)) ||
3886             parse_commit(commit) || get_message(commit, &message))
3887                 fprintf(stderr, _("Stopped at HEAD\n"));
3888         else {
3889                 fprintf(stderr, _("Stopped at %s\n"), message.label);
3890                 free_message(commit, &message);
3891         }
3892         return 0;
3893
3894 }
3895
3896 static const char rescheduled_advice[] =
3897 N_("Could not execute the todo command\n"
3898 "\n"
3899 "    %.*s"
3900 "\n"
3901 "It has been rescheduled; To edit the command before continuing, please\n"
3902 "edit the todo list first:\n"
3903 "\n"
3904 "    git rebase --edit-todo\n"
3905 "    git rebase --continue\n");
3906
3907 static int pick_commits(struct repository *r,
3908                         struct todo_list *todo_list,
3909                         struct replay_opts *opts)
3910 {
3911         int res = 0, reschedule = 0;
3912         char *prev_reflog_action;
3913
3914         /* Note that 0 for 3rd parameter of setenv means set only if not set */
3915         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
3916         prev_reflog_action = xstrdup(getenv(GIT_REFLOG_ACTION));
3917         if (opts->allow_ff)
3918                 assert(!(opts->signoff || opts->no_commit ||
3919                                 opts->record_origin || opts->edit));
3920         if (read_and_refresh_cache(r, opts))
3921                 return -1;
3922
3923         while (todo_list->current < todo_list->nr) {
3924                 struct todo_item *item = todo_list->items + todo_list->current;
3925                 const char *arg = todo_item_get_arg(todo_list, item);
3926                 int check_todo = 0;
3927
3928                 if (save_todo(todo_list, opts))
3929                         return -1;
3930                 if (is_rebase_i(opts)) {
3931                         if (item->command != TODO_COMMENT) {
3932                                 FILE *f = fopen(rebase_path_msgnum(), "w");
3933
3934                                 todo_list->done_nr++;
3935
3936                                 if (f) {
3937                                         fprintf(f, "%d\n", todo_list->done_nr);
3938                                         fclose(f);
3939                                 }
3940                                 if (!opts->quiet)
3941                                         fprintf(stderr, _("Rebasing (%d/%d)%s"),
3942                                                 todo_list->done_nr,
3943                                                 todo_list->total_nr,
3944                                                 opts->verbose ? "\n" : "\r");
3945                         }
3946                         unlink(rebase_path_message());
3947                         unlink(rebase_path_author_script());
3948                         unlink(rebase_path_stopped_sha());
3949                         unlink(rebase_path_amend());
3950                         unlink(git_path_merge_head(r));
3951                         delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
3952
3953                         if (item->command == TODO_BREAK) {
3954                                 if (!opts->verbose)
3955                                         term_clear_line();
3956                                 return stopped_at_head(r);
3957                         }
3958                 }
3959                 if (item->command <= TODO_SQUASH) {
3960                         if (is_rebase_i(opts))
3961                                 setenv(GIT_REFLOG_ACTION, reflog_message(opts,
3962                                         command_to_string(item->command), NULL),
3963                                         1);
3964                         res = do_pick_commit(r, item->command, item->commit,
3965                                              opts, is_final_fixup(todo_list),
3966                                              &check_todo);
3967                         if (is_rebase_i(opts))
3968                                 setenv(GIT_REFLOG_ACTION, prev_reflog_action, 1);
3969                         if (is_rebase_i(opts) && res < 0) {
3970                                 /* Reschedule */
3971                                 advise(_(rescheduled_advice),
3972                                        get_item_line_length(todo_list,
3973                                                             todo_list->current),
3974                                        get_item_line(todo_list,
3975                                                      todo_list->current));
3976                                 todo_list->current--;
3977                                 if (save_todo(todo_list, opts))
3978                                         return -1;
3979                         }
3980                         if (item->command == TODO_EDIT) {
3981                                 struct commit *commit = item->commit;
3982                                 if (!res) {
3983                                         if (!opts->verbose)
3984                                                 term_clear_line();
3985                                         fprintf(stderr,
3986                                                 _("Stopped at %s...  %.*s\n"),
3987                                                 short_commit_name(commit),
3988                                                 item->arg_len, arg);
3989                                 }
3990                                 return error_with_patch(r, commit,
3991                                         arg, item->arg_len, opts, res, !res);
3992                         }
3993                         if (is_rebase_i(opts) && !res)
3994                                 record_in_rewritten(&item->commit->object.oid,
3995                                         peek_command(todo_list, 1));
3996                         if (res && is_fixup(item->command)) {
3997                                 if (res == 1)
3998                                         intend_to_amend();
3999                                 return error_failed_squash(r, item->commit, opts,
4000                                         item->arg_len, arg);
4001                         } else if (res && is_rebase_i(opts) && item->commit) {
4002                                 int to_amend = 0;
4003                                 struct object_id oid;
4004
4005                                 /*
4006                                  * If we are rewording and have either
4007                                  * fast-forwarded already, or are about to
4008                                  * create a new root commit, we want to amend,
4009                                  * otherwise we do not.
4010                                  */
4011                                 if (item->command == TODO_REWORD &&
4012                                     !get_oid("HEAD", &oid) &&
4013                                     (oideq(&item->commit->object.oid, &oid) ||
4014                                      (opts->have_squash_onto &&
4015                                       oideq(&opts->squash_onto, &oid))))
4016                                         to_amend = 1;
4017
4018                                 return res | error_with_patch(r, item->commit,
4019                                                 arg, item->arg_len, opts,
4020                                                 res, to_amend);
4021                         }
4022                 } else if (item->command == TODO_EXEC) {
4023                         char *end_of_arg = (char *)(arg + item->arg_len);
4024                         int saved = *end_of_arg;
4025
4026                         if (!opts->verbose)
4027                                 term_clear_line();
4028                         *end_of_arg = '\0';
4029                         res = do_exec(r, arg);
4030                         *end_of_arg = saved;
4031
4032                         if (res) {
4033                                 if (opts->reschedule_failed_exec)
4034                                         reschedule = 1;
4035                         }
4036                         check_todo = 1;
4037                 } else if (item->command == TODO_LABEL) {
4038                         if ((res = do_label(r, arg, item->arg_len)))
4039                                 reschedule = 1;
4040                 } else if (item->command == TODO_RESET) {
4041                         if ((res = do_reset(r, arg, item->arg_len, opts)))
4042                                 reschedule = 1;
4043                 } else if (item->command == TODO_MERGE) {
4044                         if ((res = do_merge(r, item->commit,
4045                                             arg, item->arg_len,
4046                                             item->flags, opts)) < 0)
4047                                 reschedule = 1;
4048                         else if (item->commit)
4049                                 record_in_rewritten(&item->commit->object.oid,
4050                                                     peek_command(todo_list, 1));
4051                         if (res > 0)
4052                                 /* failed with merge conflicts */
4053                                 return error_with_patch(r, item->commit,
4054                                                         arg, item->arg_len,
4055                                                         opts, res, 0);
4056                 } else if (!is_noop(item->command))
4057                         return error(_("unknown command %d"), item->command);
4058
4059                 if (reschedule) {
4060                         advise(_(rescheduled_advice),
4061                                get_item_line_length(todo_list,
4062                                                     todo_list->current),
4063                                get_item_line(todo_list, todo_list->current));
4064                         todo_list->current--;
4065                         if (save_todo(todo_list, opts))
4066                                 return -1;
4067                         if (item->commit)
4068                                 return error_with_patch(r,
4069                                                         item->commit,
4070                                                         arg, item->arg_len,
4071                                                         opts, res, 0);
4072                 } else if (is_rebase_i(opts) && check_todo && !res) {
4073                         struct stat st;
4074
4075                         if (stat(get_todo_path(opts), &st)) {
4076                                 res = error_errno(_("could not stat '%s'"),
4077                                                   get_todo_path(opts));
4078                         } else if (match_stat_data(&todo_list->stat, &st)) {
4079                                 /* Reread the todo file if it has changed. */
4080                                 todo_list_release(todo_list);
4081                                 if (read_populate_todo(r, todo_list, opts))
4082                                         res = -1; /* message was printed */
4083                                 /* `current` will be incremented below */
4084                                 todo_list->current = -1;
4085                         }
4086                 }
4087
4088                 todo_list->current++;
4089                 if (res)
4090                         return res;
4091         }
4092
4093         if (is_rebase_i(opts)) {
4094                 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
4095                 struct stat st;
4096
4097                 /* Stopped in the middle, as planned? */
4098                 if (todo_list->current < todo_list->nr)
4099                         return 0;
4100
4101                 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
4102                                 starts_with(head_ref.buf, "refs/")) {
4103                         const char *msg;
4104                         struct object_id head, orig;
4105                         int res;
4106
4107                         if (get_oid("HEAD", &head)) {
4108                                 res = error(_("cannot read HEAD"));
4109 cleanup_head_ref:
4110                                 strbuf_release(&head_ref);
4111                                 strbuf_release(&buf);
4112                                 return res;
4113                         }
4114                         if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
4115                                         get_oid_hex(buf.buf, &orig)) {
4116                                 res = error(_("could not read orig-head"));
4117                                 goto cleanup_head_ref;
4118                         }
4119                         strbuf_reset(&buf);
4120                         if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
4121                                 res = error(_("could not read 'onto'"));
4122                                 goto cleanup_head_ref;
4123                         }
4124                         msg = reflog_message(opts, "finish", "%s onto %s",
4125                                 head_ref.buf, buf.buf);
4126                         if (update_ref(msg, head_ref.buf, &head, &orig,
4127                                        REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
4128                                 res = error(_("could not update %s"),
4129                                         head_ref.buf);
4130                                 goto cleanup_head_ref;
4131                         }
4132                         msg = reflog_message(opts, "finish", "returning to %s",
4133                                 head_ref.buf);
4134                         if (create_symref("HEAD", head_ref.buf, msg)) {
4135                                 res = error(_("could not update HEAD to %s"),
4136                                         head_ref.buf);
4137                                 goto cleanup_head_ref;
4138                         }
4139                         strbuf_reset(&buf);
4140                 }
4141
4142                 if (opts->verbose) {
4143                         struct rev_info log_tree_opt;
4144                         struct object_id orig, head;
4145
4146                         memset(&log_tree_opt, 0, sizeof(log_tree_opt));
4147                         repo_init_revisions(r, &log_tree_opt, NULL);
4148                         log_tree_opt.diff = 1;
4149                         log_tree_opt.diffopt.output_format =
4150                                 DIFF_FORMAT_DIFFSTAT;
4151                         log_tree_opt.disable_stdin = 1;
4152
4153                         if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
4154                             !get_oid(buf.buf, &orig) &&
4155                             !get_oid("HEAD", &head)) {
4156                                 diff_tree_oid(&orig, &head, "",
4157                                               &log_tree_opt.diffopt);
4158                                 log_tree_diff_flush(&log_tree_opt);
4159                         }
4160                 }
4161                 flush_rewritten_pending();
4162                 if (!stat(rebase_path_rewritten_list(), &st) &&
4163                                 st.st_size > 0) {
4164                         struct child_process child = CHILD_PROCESS_INIT;
4165                         const char *post_rewrite_hook =
4166                                 find_hook("post-rewrite");
4167
4168                         child.in = open(rebase_path_rewritten_list(), O_RDONLY);
4169                         child.git_cmd = 1;
4170                         strvec_push(&child.args, "notes");
4171                         strvec_push(&child.args, "copy");
4172                         strvec_push(&child.args, "--for-rewrite=rebase");
4173                         /* we don't care if this copying failed */
4174                         run_command(&child);
4175
4176                         if (post_rewrite_hook) {
4177                                 struct child_process hook = CHILD_PROCESS_INIT;
4178
4179                                 hook.in = open(rebase_path_rewritten_list(),
4180                                         O_RDONLY);
4181                                 hook.stdout_to_stderr = 1;
4182                                 hook.trace2_hook_name = "post-rewrite";
4183                                 strvec_push(&hook.args, post_rewrite_hook);
4184                                 strvec_push(&hook.args, "rebase");
4185                                 /* we don't care if this hook failed */
4186                                 run_command(&hook);
4187                         }
4188                 }
4189                 apply_autostash(rebase_path_autostash());
4190
4191                 if (!opts->quiet) {
4192                         if (!opts->verbose)
4193                                 term_clear_line();
4194                         fprintf(stderr,
4195                                 _("Successfully rebased and updated %s.\n"),
4196                                 head_ref.buf);
4197                 }
4198
4199                 strbuf_release(&buf);
4200                 strbuf_release(&head_ref);
4201         }
4202
4203         /*
4204          * Sequence of picks finished successfully; cleanup by
4205          * removing the .git/sequencer directory
4206          */
4207         return sequencer_remove_state(opts);
4208 }
4209
4210 static int continue_single_pick(struct repository *r)
4211 {
4212         const char *argv[] = { "commit", NULL };
4213
4214         if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
4215             !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
4216                 return error(_("no cherry-pick or revert in progress"));
4217         return run_command_v_opt(argv, RUN_GIT_CMD);
4218 }
4219
4220 static int commit_staged_changes(struct repository *r,
4221                                  struct replay_opts *opts,
4222                                  struct todo_list *todo_list)
4223 {
4224         unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
4225         unsigned int final_fixup = 0, is_clean;
4226
4227         if (has_unstaged_changes(r, 1))
4228                 return error(_("cannot rebase: You have unstaged changes."));
4229
4230         is_clean = !has_uncommitted_changes(r, 0);
4231
4232         if (file_exists(rebase_path_amend())) {
4233                 struct strbuf rev = STRBUF_INIT;
4234                 struct object_id head, to_amend;
4235
4236                 if (get_oid("HEAD", &head))
4237                         return error(_("cannot amend non-existing commit"));
4238                 if (!read_oneliner(&rev, rebase_path_amend(), 0))
4239                         return error(_("invalid file: '%s'"), rebase_path_amend());
4240                 if (get_oid_hex(rev.buf, &to_amend))
4241                         return error(_("invalid contents: '%s'"),
4242                                 rebase_path_amend());
4243                 if (!is_clean && !oideq(&head, &to_amend))
4244                         return error(_("\nYou have uncommitted changes in your "
4245                                        "working tree. Please, commit them\n"
4246                                        "first and then run 'git rebase "
4247                                        "--continue' again."));
4248                 /*
4249                  * When skipping a failed fixup/squash, we need to edit the
4250                  * commit message, the current fixup list and count, and if it
4251                  * was the last fixup/squash in the chain, we need to clean up
4252                  * the commit message and if there was a squash, let the user
4253                  * edit it.
4254                  */
4255                 if (!is_clean || !opts->current_fixup_count)
4256                         ; /* this is not the final fixup */
4257                 else if (!oideq(&head, &to_amend) ||
4258                          !file_exists(rebase_path_stopped_sha())) {
4259                         /* was a final fixup or squash done manually? */
4260                         if (!is_fixup(peek_command(todo_list, 0))) {
4261                                 unlink(rebase_path_fixup_msg());
4262                                 unlink(rebase_path_squash_msg());
4263                                 unlink(rebase_path_current_fixups());
4264                                 strbuf_reset(&opts->current_fixups);
4265                                 opts->current_fixup_count = 0;
4266                         }
4267                 } else {
4268                         /* we are in a fixup/squash chain */
4269                         const char *p = opts->current_fixups.buf;
4270                         int len = opts->current_fixups.len;
4271
4272                         opts->current_fixup_count--;
4273                         if (!len)
4274                                 BUG("Incorrect current_fixups:\n%s", p);
4275                         while (len && p[len - 1] != '\n')
4276                                 len--;
4277                         strbuf_setlen(&opts->current_fixups, len);
4278                         if (write_message(p, len, rebase_path_current_fixups(),
4279                                           0) < 0)
4280                                 return error(_("could not write file: '%s'"),
4281                                              rebase_path_current_fixups());
4282
4283                         /*
4284                          * If a fixup/squash in a fixup/squash chain failed, the
4285                          * commit message is already correct, no need to commit
4286                          * it again.
4287                          *
4288                          * Only if it is the final command in the fixup/squash
4289                          * chain, and only if the chain is longer than a single
4290                          * fixup/squash command (which was just skipped), do we
4291                          * actually need to re-commit with a cleaned up commit
4292                          * message.
4293                          */
4294                         if (opts->current_fixup_count > 0 &&
4295                             !is_fixup(peek_command(todo_list, 0))) {
4296                                 final_fixup = 1;
4297                                 /*
4298                                  * If there was not a single "squash" in the
4299                                  * chain, we only need to clean up the commit
4300                                  * message, no need to bother the user with
4301                                  * opening the commit message in the editor.
4302                                  */
4303                                 if (!starts_with(p, "squash ") &&
4304                                     !strstr(p, "\nsquash "))
4305                                         flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
4306                         } else if (is_fixup(peek_command(todo_list, 0))) {
4307                                 /*
4308                                  * We need to update the squash message to skip
4309                                  * the latest commit message.
4310                                  */
4311                                 struct commit *commit;
4312                                 const char *path = rebase_path_squash_msg();
4313                                 const char *encoding = get_commit_output_encoding();
4314
4315                                 if (parse_head(r, &commit) ||
4316                                     !(p = logmsg_reencode(commit, NULL, encoding)) ||
4317                                     write_message(p, strlen(p), path, 0)) {
4318                                         unuse_commit_buffer(commit, p);
4319                                         return error(_("could not write file: "
4320                                                        "'%s'"), path);
4321                                 }
4322                                 unuse_commit_buffer(commit, p);
4323                         }
4324                 }
4325
4326                 strbuf_release(&rev);
4327                 flags |= AMEND_MSG;
4328         }
4329
4330         if (is_clean) {
4331                 if (refs_ref_exists(get_main_ref_store(r),
4332                                     "CHERRY_PICK_HEAD") &&
4333                     refs_delete_ref(get_main_ref_store(r), "",
4334                                     "CHERRY_PICK_HEAD", NULL, 0))
4335                         return error(_("could not remove CHERRY_PICK_HEAD"));
4336                 if (!final_fixup)
4337                         return 0;
4338         }
4339
4340         if (run_git_commit(r, final_fixup ? NULL : rebase_path_message(),
4341                            opts, flags))
4342                 return error(_("could not commit staged changes."));
4343         unlink(rebase_path_amend());
4344         unlink(git_path_merge_head(r));
4345         if (final_fixup) {
4346                 unlink(rebase_path_fixup_msg());
4347                 unlink(rebase_path_squash_msg());
4348         }
4349         if (opts->current_fixup_count > 0) {
4350                 /*
4351                  * Whether final fixup or not, we just cleaned up the commit
4352                  * message...
4353                  */
4354                 unlink(rebase_path_current_fixups());
4355                 strbuf_reset(&opts->current_fixups);
4356                 opts->current_fixup_count = 0;
4357         }
4358         return 0;
4359 }
4360
4361 int sequencer_continue(struct repository *r, struct replay_opts *opts)
4362 {
4363         struct todo_list todo_list = TODO_LIST_INIT;
4364         int res;
4365
4366         if (read_and_refresh_cache(r, opts))
4367                 return -1;
4368
4369         if (read_populate_opts(opts))
4370                 return -1;
4371         if (is_rebase_i(opts)) {
4372                 if ((res = read_populate_todo(r, &todo_list, opts)))
4373                         goto release_todo_list;
4374
4375                 if (file_exists(rebase_path_dropped())) {
4376                         if ((res = todo_list_check_against_backup(r, &todo_list)))
4377                                 goto release_todo_list;
4378
4379                         unlink(rebase_path_dropped());
4380                 }
4381
4382                 if (commit_staged_changes(r, opts, &todo_list)) {
4383                         res = -1;
4384                         goto release_todo_list;
4385                 }
4386         } else if (!file_exists(get_todo_path(opts)))
4387                 return continue_single_pick(r);
4388         else if ((res = read_populate_todo(r, &todo_list, opts)))
4389                 goto release_todo_list;
4390
4391         if (!is_rebase_i(opts)) {
4392                 /* Verify that the conflict has been resolved */
4393                 if (refs_ref_exists(get_main_ref_store(r),
4394                                     "CHERRY_PICK_HEAD") ||
4395                     refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
4396                         res = continue_single_pick(r);
4397                         if (res)
4398                                 goto release_todo_list;
4399                 }
4400                 if (index_differs_from(r, "HEAD", NULL, 0)) {
4401                         res = error_dirty_index(r, opts);
4402                         goto release_todo_list;
4403                 }
4404                 todo_list.current++;
4405         } else if (file_exists(rebase_path_stopped_sha())) {
4406                 struct strbuf buf = STRBUF_INIT;
4407                 struct object_id oid;
4408
4409                 if (read_oneliner(&buf, rebase_path_stopped_sha(),
4410                                   READ_ONELINER_SKIP_IF_EMPTY) &&
4411                     !get_oid_committish(buf.buf, &oid))
4412                         record_in_rewritten(&oid, peek_command(&todo_list, 0));
4413                 strbuf_release(&buf);
4414         }
4415
4416         res = pick_commits(r, &todo_list, opts);
4417 release_todo_list:
4418         todo_list_release(&todo_list);
4419         return res;
4420 }
4421
4422 static int single_pick(struct repository *r,
4423                        struct commit *cmit,
4424                        struct replay_opts *opts)
4425 {
4426         int check_todo;
4427
4428         setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
4429         return do_pick_commit(r, opts->action == REPLAY_PICK ?
4430                               TODO_PICK : TODO_REVERT, cmit, opts, 0,
4431                               &check_todo);
4432 }
4433
4434 int sequencer_pick_revisions(struct repository *r,
4435                              struct replay_opts *opts)
4436 {
4437         struct todo_list todo_list = TODO_LIST_INIT;
4438         struct object_id oid;
4439         int i, res;
4440
4441         assert(opts->revs);
4442         if (read_and_refresh_cache(r, opts))
4443                 return -1;
4444
4445         for (i = 0; i < opts->revs->pending.nr; i++) {
4446                 struct object_id oid;
4447                 const char *name = opts->revs->pending.objects[i].name;
4448
4449                 /* This happens when using --stdin. */
4450                 if (!strlen(name))
4451                         continue;
4452
4453                 if (!get_oid(name, &oid)) {
4454                         if (!lookup_commit_reference_gently(r, &oid, 1)) {
4455                                 enum object_type type = oid_object_info(r,
4456                                                                         &oid,
4457                                                                         NULL);
4458                                 return error(_("%s: can't cherry-pick a %s"),
4459                                         name, type_name(type));
4460                         }
4461                 } else
4462                         return error(_("%s: bad revision"), name);
4463         }
4464
4465         /*
4466          * If we were called as "git cherry-pick <commit>", just
4467          * cherry-pick/revert it, set CHERRY_PICK_HEAD /
4468          * REVERT_HEAD, and don't touch the sequencer state.
4469          * This means it is possible to cherry-pick in the middle
4470          * of a cherry-pick sequence.
4471          */
4472         if (opts->revs->cmdline.nr == 1 &&
4473             opts->revs->cmdline.rev->whence == REV_CMD_REV &&
4474             opts->revs->no_walk &&
4475             !opts->revs->cmdline.rev->flags) {
4476                 struct commit *cmit;
4477                 if (prepare_revision_walk(opts->revs))
4478                         return error(_("revision walk setup failed"));
4479                 cmit = get_revision(opts->revs);
4480                 if (!cmit)
4481                         return error(_("empty commit set passed"));
4482                 if (get_revision(opts->revs))
4483                         BUG("unexpected extra commit from walk");
4484                 return single_pick(r, cmit, opts);
4485         }
4486
4487         /*
4488          * Start a new cherry-pick/ revert sequence; but
4489          * first, make sure that an existing one isn't in
4490          * progress
4491          */
4492
4493         if (walk_revs_populate_todo(&todo_list, opts) ||
4494                         create_seq_dir(r) < 0)
4495                 return -1;
4496         if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
4497                 return error(_("can't revert as initial commit"));
4498         if (save_head(oid_to_hex(&oid)))
4499                 return -1;
4500         if (save_opts(opts))
4501                 return -1;
4502         update_abort_safety_file();
4503         res = pick_commits(r, &todo_list, opts);
4504         todo_list_release(&todo_list);
4505         return res;
4506 }
4507
4508 void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
4509 {
4510         unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
4511         struct strbuf sob = STRBUF_INIT;
4512         int has_footer;
4513
4514         strbuf_addstr(&sob, sign_off_header);
4515         strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
4516         strbuf_addch(&sob, '\n');
4517
4518         if (!ignore_footer)
4519                 strbuf_complete_line(msgbuf);
4520
4521         /*
4522          * If the whole message buffer is equal to the sob, pretend that we
4523          * found a conforming footer with a matching sob
4524          */
4525         if (msgbuf->len - ignore_footer == sob.len &&
4526             !strncmp(msgbuf->buf, sob.buf, sob.len))
4527                 has_footer = 3;
4528         else
4529                 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
4530
4531         if (!has_footer) {
4532                 const char *append_newlines = NULL;
4533                 size_t len = msgbuf->len - ignore_footer;
4534
4535                 if (!len) {
4536                         /*
4537                          * The buffer is completely empty.  Leave foom for
4538                          * the title and body to be filled in by the user.
4539                          */
4540                         append_newlines = "\n\n";
4541                 } else if (len == 1) {
4542                         /*
4543                          * Buffer contains a single newline.  Add another
4544                          * so that we leave room for the title and body.
4545                          */
4546                         append_newlines = "\n";
4547                 } else if (msgbuf->buf[len - 2] != '\n') {
4548                         /*
4549                          * Buffer ends with a single newline.  Add another
4550                          * so that there is an empty line between the message
4551                          * body and the sob.
4552                          */
4553                         append_newlines = "\n";
4554                 } /* else, the buffer already ends with two newlines. */
4555
4556                 if (append_newlines)
4557                         strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4558                                 append_newlines, strlen(append_newlines));
4559         }
4560
4561         if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
4562                 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
4563                                 sob.buf, sob.len);
4564
4565         strbuf_release(&sob);
4566 }
4567
4568 struct labels_entry {
4569         struct hashmap_entry entry;
4570         char label[FLEX_ARRAY];
4571 };
4572
4573 static int labels_cmp(const void *fndata, const struct hashmap_entry *eptr,
4574                       const struct hashmap_entry *entry_or_key, const void *key)
4575 {
4576         const struct labels_entry *a, *b;
4577
4578         a = container_of(eptr, const struct labels_entry, entry);
4579         b = container_of(entry_or_key, const struct labels_entry, entry);
4580
4581         return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
4582 }
4583
4584 struct string_entry {
4585         struct oidmap_entry entry;
4586         char string[FLEX_ARRAY];
4587 };
4588
4589 struct label_state {
4590         struct oidmap commit2label;
4591         struct hashmap labels;
4592         struct strbuf buf;
4593 };
4594
4595 static const char *label_oid(struct object_id *oid, const char *label,
4596                              struct label_state *state)
4597 {
4598         struct labels_entry *labels_entry;
4599         struct string_entry *string_entry;
4600         struct object_id dummy;
4601         int i;
4602
4603         string_entry = oidmap_get(&state->commit2label, oid);
4604         if (string_entry)
4605                 return string_entry->string;
4606
4607         /*
4608          * For "uninteresting" commits, i.e. commits that are not to be
4609          * rebased, and which can therefore not be labeled, we use a unique
4610          * abbreviation of the commit name. This is slightly more complicated
4611          * than calling find_unique_abbrev() because we also need to make
4612          * sure that the abbreviation does not conflict with any other
4613          * label.
4614          *
4615          * We disallow "interesting" commits to be labeled by a string that
4616          * is a valid full-length hash, to ensure that we always can find an
4617          * abbreviation for any uninteresting commit's names that does not
4618          * clash with any other label.
4619          */
4620         strbuf_reset(&state->buf);
4621         if (!label) {
4622                 char *p;
4623
4624                 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
4625                 label = p = state->buf.buf;
4626
4627                 find_unique_abbrev_r(p, oid, default_abbrev);
4628
4629                 /*
4630                  * We may need to extend the abbreviated hash so that there is
4631                  * no conflicting label.
4632                  */
4633                 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
4634                         size_t i = strlen(p) + 1;
4635
4636                         oid_to_hex_r(p, oid);
4637                         for (; i < the_hash_algo->hexsz; i++) {
4638                                 char save = p[i];
4639                                 p[i] = '\0';
4640                                 if (!hashmap_get_from_hash(&state->labels,
4641                                                            strihash(p), p))
4642                                         break;
4643                                 p[i] = save;
4644                         }
4645                 }
4646         } else {
4647                 struct strbuf *buf = &state->buf;
4648
4649                 /*
4650                  * Sanitize labels by replacing non-alpha-numeric characters
4651                  * (including white-space ones) by dashes, as they might be
4652                  * illegal in file names (and hence in ref names).
4653                  *
4654                  * Note that we retain non-ASCII UTF-8 characters (identified
4655                  * via the most significant bit). They should be all acceptable
4656                  * in file names. We do not validate the UTF-8 here, that's not
4657                  * the job of this function.
4658                  */
4659                 for (; *label; label++)
4660                         if ((*label & 0x80) || isalnum(*label))
4661                                 strbuf_addch(buf, *label);
4662                         /* avoid leading dash and double-dashes */
4663                         else if (buf->len && buf->buf[buf->len - 1] != '-')
4664                                 strbuf_addch(buf, '-');
4665                 if (!buf->len) {
4666                         strbuf_addstr(buf, "rev-");
4667                         strbuf_add_unique_abbrev(buf, oid, default_abbrev);
4668                 }
4669                 label = buf->buf;
4670
4671                 if ((buf->len == the_hash_algo->hexsz &&
4672                      !get_oid_hex(label, &dummy)) ||
4673                     (buf->len == 1 && *label == '#') ||
4674                     hashmap_get_from_hash(&state->labels,
4675                                           strihash(label), label)) {
4676                         /*
4677                          * If the label already exists, or if the label is a
4678                          * valid full OID, or the label is a '#' (which we use
4679                          * as a separator between merge heads and oneline), we
4680                          * append a dash and a number to make it unique.
4681                          */
4682                         size_t len = buf->len;
4683
4684                         for (i = 2; ; i++) {
4685                                 strbuf_setlen(buf, len);
4686                                 strbuf_addf(buf, "-%d", i);
4687                                 if (!hashmap_get_from_hash(&state->labels,
4688                                                            strihash(buf->buf),
4689                                                            buf->buf))
4690                                         break;
4691                         }
4692
4693                         label = buf->buf;
4694                 }
4695         }
4696
4697         FLEX_ALLOC_STR(labels_entry, label, label);
4698         hashmap_entry_init(&labels_entry->entry, strihash(label));
4699         hashmap_add(&state->labels, &labels_entry->entry);
4700
4701         FLEX_ALLOC_STR(string_entry, string, label);
4702         oidcpy(&string_entry->entry.oid, oid);
4703         oidmap_put(&state->commit2label, string_entry);
4704
4705         return string_entry->string;
4706 }
4707
4708 static int make_script_with_merges(struct pretty_print_context *pp,
4709                                    struct rev_info *revs, struct strbuf *out,
4710                                    unsigned flags)
4711 {
4712         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4713         int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
4714         int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
4715         struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
4716         struct strbuf label = STRBUF_INIT;
4717         struct commit_list *commits = NULL, **tail = &commits, *iter;
4718         struct commit_list *tips = NULL, **tips_tail = &tips;
4719         struct commit *commit;
4720         struct oidmap commit2todo = OIDMAP_INIT;
4721         struct string_entry *entry;
4722         struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
4723                 shown = OIDSET_INIT;
4724         struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
4725
4726         int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
4727         const char *cmd_pick = abbr ? "p" : "pick",
4728                 *cmd_label = abbr ? "l" : "label",
4729                 *cmd_reset = abbr ? "t" : "reset",
4730                 *cmd_merge = abbr ? "m" : "merge";
4731
4732         oidmap_init(&commit2todo, 0);
4733         oidmap_init(&state.commit2label, 0);
4734         hashmap_init(&state.labels, labels_cmp, NULL, 0);
4735         strbuf_init(&state.buf, 32);
4736
4737         if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
4738                 struct labels_entry *onto_label_entry;
4739                 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
4740                 FLEX_ALLOC_STR(entry, string, "onto");
4741                 oidcpy(&entry->entry.oid, oid);
4742                 oidmap_put(&state.commit2label, entry);
4743
4744                 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
4745                 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
4746                 hashmap_add(&state.labels, &onto_label_entry->entry);
4747         }
4748
4749         /*
4750          * First phase:
4751          * - get onelines for all commits
4752          * - gather all branch tips (i.e. 2nd or later parents of merges)
4753          * - label all branch tips
4754          */
4755         while ((commit = get_revision(revs))) {
4756                 struct commit_list *to_merge;
4757                 const char *p1, *p2;
4758                 struct object_id *oid;
4759                 int is_empty;
4760
4761                 tail = &commit_list_insert(commit, tail)->next;
4762                 oidset_insert(&interesting, &commit->object.oid);
4763
4764                 is_empty = is_original_commit_empty(commit);
4765                 if (!is_empty && (commit->object.flags & PATCHSAME))
4766                         continue;
4767                 if (is_empty && !keep_empty)
4768                         continue;
4769
4770                 strbuf_reset(&oneline);
4771                 pretty_print_commit(pp, commit, &oneline);
4772
4773                 to_merge = commit->parents ? commit->parents->next : NULL;
4774                 if (!to_merge) {
4775                         /* non-merge commit: easy case */
4776                         strbuf_reset(&buf);
4777                         strbuf_addf(&buf, "%s %s %s", cmd_pick,
4778                                     oid_to_hex(&commit->object.oid),
4779                                     oneline.buf);
4780                         if (is_empty)
4781                                 strbuf_addf(&buf, " %c empty",
4782                                             comment_line_char);
4783
4784                         FLEX_ALLOC_STR(entry, string, buf.buf);
4785                         oidcpy(&entry->entry.oid, &commit->object.oid);
4786                         oidmap_put(&commit2todo, entry);
4787
4788                         continue;
4789                 }
4790
4791                 /* Create a label */
4792                 strbuf_reset(&label);
4793                 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
4794                     (p1 = strchr(p1, '\'')) &&
4795                     (p2 = strchr(++p1, '\'')))
4796                         strbuf_add(&label, p1, p2 - p1);
4797                 else if (skip_prefix(oneline.buf, "Merge pull request ",
4798                                      &p1) &&
4799                          (p1 = strstr(p1, " from ")))
4800                         strbuf_addstr(&label, p1 + strlen(" from "));
4801                 else
4802                         strbuf_addbuf(&label, &oneline);
4803
4804                 strbuf_reset(&buf);
4805                 strbuf_addf(&buf, "%s -C %s",
4806                             cmd_merge, oid_to_hex(&commit->object.oid));
4807
4808                 /* label the tips of merged branches */
4809                 for (; to_merge; to_merge = to_merge->next) {
4810                         oid = &to_merge->item->object.oid;
4811                         strbuf_addch(&buf, ' ');
4812
4813                         if (!oidset_contains(&interesting, oid)) {
4814                                 strbuf_addstr(&buf, label_oid(oid, NULL,
4815                                                               &state));
4816                                 continue;
4817                         }
4818
4819                         tips_tail = &commit_list_insert(to_merge->item,
4820                                                         tips_tail)->next;
4821
4822                         strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
4823                 }
4824                 strbuf_addf(&buf, " # %s", oneline.buf);
4825
4826                 FLEX_ALLOC_STR(entry, string, buf.buf);
4827                 oidcpy(&entry->entry.oid, &commit->object.oid);
4828                 oidmap_put(&commit2todo, entry);
4829         }
4830
4831         /*
4832          * Second phase:
4833          * - label branch points
4834          * - add HEAD to the branch tips
4835          */
4836         for (iter = commits; iter; iter = iter->next) {
4837                 struct commit_list *parent = iter->item->parents;
4838                 for (; parent; parent = parent->next) {
4839                         struct object_id *oid = &parent->item->object.oid;
4840                         if (!oidset_contains(&interesting, oid))
4841                                 continue;
4842                         if (oidset_insert(&child_seen, oid))
4843                                 label_oid(oid, "branch-point", &state);
4844                 }
4845
4846                 /* Add HEAD as implicit "tip of branch" */
4847                 if (!iter->next)
4848                         tips_tail = &commit_list_insert(iter->item,
4849                                                         tips_tail)->next;
4850         }
4851
4852         /*
4853          * Third phase: output the todo list. This is a bit tricky, as we
4854          * want to avoid jumping back and forth between revisions. To
4855          * accomplish that goal, we walk backwards from the branch tips,
4856          * gathering commits not yet shown, reversing the list on the fly,
4857          * then outputting that list (labeling revisions as needed).
4858          */
4859         strbuf_addf(out, "%s onto\n", cmd_label);
4860         for (iter = tips; iter; iter = iter->next) {
4861                 struct commit_list *list = NULL, *iter2;
4862
4863                 commit = iter->item;
4864                 if (oidset_contains(&shown, &commit->object.oid))
4865                         continue;
4866                 entry = oidmap_get(&state.commit2label, &commit->object.oid);
4867
4868                 if (entry)
4869                         strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
4870                 else
4871                         strbuf_addch(out, '\n');
4872
4873                 while (oidset_contains(&interesting, &commit->object.oid) &&
4874                        !oidset_contains(&shown, &commit->object.oid)) {
4875                         commit_list_insert(commit, &list);
4876                         if (!commit->parents) {
4877                                 commit = NULL;
4878                                 break;
4879                         }
4880                         commit = commit->parents->item;
4881                 }
4882
4883                 if (!commit)
4884                         strbuf_addf(out, "%s %s\n", cmd_reset,
4885                                     rebase_cousins || root_with_onto ?
4886                                     "onto" : "[new root]");
4887                 else {
4888                         const char *to = NULL;
4889
4890                         entry = oidmap_get(&state.commit2label,
4891                                            &commit->object.oid);
4892                         if (entry)
4893                                 to = entry->string;
4894                         else if (!rebase_cousins)
4895                                 to = label_oid(&commit->object.oid, NULL,
4896                                                &state);
4897
4898                         if (!to || !strcmp(to, "onto"))
4899                                 strbuf_addf(out, "%s onto\n", cmd_reset);
4900                         else {
4901                                 strbuf_reset(&oneline);
4902                                 pretty_print_commit(pp, commit, &oneline);
4903                                 strbuf_addf(out, "%s %s # %s\n",
4904                                             cmd_reset, to, oneline.buf);
4905                         }
4906                 }
4907
4908                 for (iter2 = list; iter2; iter2 = iter2->next) {
4909                         struct object_id *oid = &iter2->item->object.oid;
4910                         entry = oidmap_get(&commit2todo, oid);
4911                         /* only show if not already upstream */
4912                         if (entry)
4913                                 strbuf_addf(out, "%s\n", entry->string);
4914                         entry = oidmap_get(&state.commit2label, oid);
4915                         if (entry)
4916                                 strbuf_addf(out, "%s %s\n",
4917                                             cmd_label, entry->string);
4918                         oidset_insert(&shown, oid);
4919                 }
4920
4921                 free_commit_list(list);
4922         }
4923
4924         free_commit_list(commits);
4925         free_commit_list(tips);
4926
4927         strbuf_release(&label);
4928         strbuf_release(&oneline);
4929         strbuf_release(&buf);
4930
4931         oidmap_free(&commit2todo, 1);
4932         oidmap_free(&state.commit2label, 1);
4933         hashmap_free_entries(&state.labels, struct labels_entry, entry);
4934         strbuf_release(&state.buf);
4935
4936         return 0;
4937 }
4938
4939 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
4940                           const char **argv, unsigned flags)
4941 {
4942         char *format = NULL;
4943         struct pretty_print_context pp = {0};
4944         struct rev_info revs;
4945         struct commit *commit;
4946         int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
4947         const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
4948         int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
4949         int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
4950
4951         repo_init_revisions(r, &revs, NULL);
4952         revs.verbose_header = 1;
4953         if (!rebase_merges)
4954                 revs.max_parents = 1;
4955         revs.cherry_mark = !reapply_cherry_picks;
4956         revs.limited = 1;
4957         revs.reverse = 1;
4958         revs.right_only = 1;
4959         revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
4960         revs.topo_order = 1;
4961
4962         revs.pretty_given = 1;
4963         git_config_get_string("rebase.instructionFormat", &format);
4964         if (!format || !*format) {
4965                 free(format);
4966                 format = xstrdup("%s");
4967         }
4968         get_commit_format(format, &revs);
4969         free(format);
4970         pp.fmt = revs.commit_format;
4971         pp.output_encoding = get_log_output_encoding();
4972
4973         if (setup_revisions(argc, argv, &revs, NULL) > 1)
4974                 return error(_("make_script: unhandled options"));
4975
4976         if (prepare_revision_walk(&revs) < 0)
4977                 return error(_("make_script: error preparing revisions"));
4978
4979         if (rebase_merges)
4980                 return make_script_with_merges(&pp, &revs, out, flags);
4981
4982         while ((commit = get_revision(&revs))) {
4983                 int is_empty = is_original_commit_empty(commit);
4984
4985                 if (!is_empty && (commit->object.flags & PATCHSAME))
4986                         continue;
4987                 if (is_empty && !keep_empty)
4988                         continue;
4989                 strbuf_addf(out, "%s %s ", insn,
4990                             oid_to_hex(&commit->object.oid));
4991                 pretty_print_commit(&pp, commit, out);
4992                 if (is_empty)
4993                         strbuf_addf(out, " %c empty", comment_line_char);
4994                 strbuf_addch(out, '\n');
4995         }
4996         return 0;
4997 }
4998
4999 /*
5000  * Add commands after pick and (series of) squash/fixup commands
5001  * in the todo list.
5002  */
5003 void todo_list_add_exec_commands(struct todo_list *todo_list,
5004                                  struct string_list *commands)
5005 {
5006         struct strbuf *buf = &todo_list->buf;
5007         size_t base_offset = buf->len;
5008         int i, insert, nr = 0, alloc = 0;
5009         struct todo_item *items = NULL, *base_items = NULL;
5010
5011         base_items = xcalloc(commands->nr, sizeof(struct todo_item));
5012         for (i = 0; i < commands->nr; i++) {
5013                 size_t command_len = strlen(commands->items[i].string);
5014
5015                 strbuf_addstr(buf, commands->items[i].string);
5016                 strbuf_addch(buf, '\n');
5017
5018                 base_items[i].command = TODO_EXEC;
5019                 base_items[i].offset_in_buf = base_offset;
5020                 base_items[i].arg_offset = base_offset + strlen("exec ");
5021                 base_items[i].arg_len = command_len - strlen("exec ");
5022
5023                 base_offset += command_len + 1;
5024         }
5025
5026         /*
5027          * Insert <commands> after every pick. Here, fixup/squash chains
5028          * are considered part of the pick, so we insert the commands *after*
5029          * those chains if there are any.
5030          *
5031          * As we insert the exec commands immediately after rearranging
5032          * any fixups and before the user edits the list, a fixup chain
5033          * can never contain comments (any comments are empty picks that
5034          * have been commented out because the user did not specify
5035          * --keep-empty).  So, it is safe to insert an exec command
5036          * without looking at the command following a comment.
5037          */
5038         insert = 0;
5039         for (i = 0; i < todo_list->nr; i++) {
5040                 enum todo_command command = todo_list->items[i].command;
5041                 if (insert && !is_fixup(command)) {
5042                         ALLOC_GROW(items, nr + commands->nr, alloc);
5043                         COPY_ARRAY(items + nr, base_items, commands->nr);
5044                         nr += commands->nr;
5045
5046                         insert = 0;
5047                 }
5048
5049                 ALLOC_GROW(items, nr + 1, alloc);
5050                 items[nr++] = todo_list->items[i];
5051
5052                 if (command == TODO_PICK || command == TODO_MERGE)
5053                         insert = 1;
5054         }
5055
5056         /* insert or append final <commands> */
5057         if (insert || nr == todo_list->nr) {
5058                 ALLOC_GROW(items, nr + commands->nr, alloc);
5059                 COPY_ARRAY(items + nr, base_items, commands->nr);
5060                 nr += commands->nr;
5061         }
5062
5063         free(base_items);
5064         FREE_AND_NULL(todo_list->items);
5065         todo_list->items = items;
5066         todo_list->nr = nr;
5067         todo_list->alloc = alloc;
5068 }
5069
5070 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5071                                 struct strbuf *buf, int num, unsigned flags)
5072 {
5073         struct todo_item *item;
5074         int i, max = todo_list->nr;
5075
5076         if (num > 0 && num < max)
5077                 max = num;
5078
5079         for (item = todo_list->items, i = 0; i < max; i++, item++) {
5080                 char cmd;
5081
5082                 /* if the item is not a command write it and continue */
5083                 if (item->command >= TODO_COMMENT) {
5084                         strbuf_addf(buf, "%.*s\n", item->arg_len,
5085                                     todo_item_get_arg(todo_list, item));
5086                         continue;
5087                 }
5088
5089                 /* add command to the buffer */
5090                 cmd = command_to_char(item->command);
5091                 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5092                         strbuf_addch(buf, cmd);
5093                 else
5094                         strbuf_addstr(buf, command_to_string(item->command));
5095
5096                 /* add commit id */
5097                 if (item->commit) {
5098                         const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5099                                           short_commit_name(item->commit) :
5100                                           oid_to_hex(&item->commit->object.oid);
5101
5102                         if (item->command == TODO_MERGE) {
5103                                 if (item->flags & TODO_EDIT_MERGE_MSG)
5104                                         strbuf_addstr(buf, " -c");
5105                                 else
5106                                         strbuf_addstr(buf, " -C");
5107                         }
5108
5109                         strbuf_addf(buf, " %s", oid);
5110                 }
5111
5112                 /* add all the rest */
5113                 if (!item->arg_len)
5114                         strbuf_addch(buf, '\n');
5115                 else
5116                         strbuf_addf(buf, " %.*s\n", item->arg_len,
5117                                     todo_item_get_arg(todo_list, item));
5118         }
5119 }
5120
5121 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5122                             const char *file, const char *shortrevisions,
5123                             const char *shortonto, int num, unsigned flags)
5124 {
5125         int res;
5126         struct strbuf buf = STRBUF_INIT;
5127
5128         todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5129         if (flags & TODO_LIST_APPEND_TODO_HELP)
5130                 append_todo_help(count_commands(todo_list),
5131                                  shortrevisions, shortonto, &buf);
5132
5133         res = write_message(buf.buf, buf.len, file, 0);
5134         strbuf_release(&buf);
5135
5136         return res;
5137 }
5138
5139 /* skip picking commits whose parents are unchanged */
5140 static int skip_unnecessary_picks(struct repository *r,
5141                                   struct todo_list *todo_list,
5142                                   struct object_id *base_oid)
5143 {
5144         struct object_id *parent_oid;
5145         int i;
5146
5147         for (i = 0; i < todo_list->nr; i++) {
5148                 struct todo_item *item = todo_list->items + i;
5149
5150                 if (item->command >= TODO_NOOP)
5151                         continue;
5152                 if (item->command != TODO_PICK)
5153                         break;
5154                 if (parse_commit(item->commit)) {
5155                         return error(_("could not parse commit '%s'"),
5156                                 oid_to_hex(&item->commit->object.oid));
5157                 }
5158                 if (!item->commit->parents)
5159                         break; /* root commit */
5160                 if (item->commit->parents->next)
5161                         break; /* merge commit */
5162                 parent_oid = &item->commit->parents->item->object.oid;
5163                 if (!oideq(parent_oid, base_oid))
5164                         break;
5165                 oidcpy(base_oid, &item->commit->object.oid);
5166         }
5167         if (i > 0) {
5168                 const char *done_path = rebase_path_done();
5169
5170                 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5171                         error_errno(_("could not write to '%s'"), done_path);
5172                         return -1;
5173                 }
5174
5175                 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5176                 todo_list->nr -= i;
5177                 todo_list->current = 0;
5178                 todo_list->done_nr += i;
5179
5180                 if (is_fixup(peek_command(todo_list, 0)))
5181                         record_in_rewritten(base_oid, peek_command(todo_list, 0));
5182         }
5183
5184         return 0;
5185 }
5186
5187 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
5188                     const char *shortrevisions, const char *onto_name,
5189                     struct commit *onto, const char *orig_head,
5190                     struct string_list *commands, unsigned autosquash,
5191                     struct todo_list *todo_list)
5192 {
5193         char shortonto[GIT_MAX_HEXSZ + 1];
5194         const char *todo_file = rebase_path_todo();
5195         struct todo_list new_todo = TODO_LIST_INIT;
5196         struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
5197         struct object_id oid = onto->object.oid;
5198         int res;
5199
5200         find_unique_abbrev_r(shortonto, &oid, DEFAULT_ABBREV);
5201
5202         if (buf->len == 0) {
5203                 struct todo_item *item = append_new_todo(todo_list);
5204                 item->command = TODO_NOOP;
5205                 item->commit = NULL;
5206                 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
5207         }
5208
5209         if (autosquash && todo_list_rearrange_squash(todo_list))
5210                 return -1;
5211
5212         if (commands->nr)
5213                 todo_list_add_exec_commands(todo_list, commands);
5214
5215         if (count_commands(todo_list) == 0) {
5216                 apply_autostash(rebase_path_autostash());
5217                 sequencer_remove_state(opts);
5218
5219                 return error(_("nothing to do"));
5220         }
5221
5222         res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
5223                              shortonto, flags);
5224         if (res == -1)
5225                 return -1;
5226         else if (res == -2) {
5227                 apply_autostash(rebase_path_autostash());
5228                 sequencer_remove_state(opts);
5229
5230                 return -1;
5231         } else if (res == -3) {
5232                 apply_autostash(rebase_path_autostash());
5233                 sequencer_remove_state(opts);
5234                 todo_list_release(&new_todo);
5235
5236                 return error(_("nothing to do"));
5237         } else if (res == -4) {
5238                 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
5239                 todo_list_release(&new_todo);
5240
5241                 return -1;
5242         }
5243
5244         /* Expand the commit IDs */
5245         todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
5246         strbuf_swap(&new_todo.buf, &buf2);
5247         strbuf_release(&buf2);
5248         new_todo.total_nr -= new_todo.nr;
5249         if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
5250                 BUG("invalid todo list after expanding IDs:\n%s",
5251                     new_todo.buf.buf);
5252
5253         if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
5254                 todo_list_release(&new_todo);
5255                 return error(_("could not skip unnecessary pick commands"));
5256         }
5257
5258         if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
5259                                     flags & ~(TODO_LIST_SHORTEN_IDS))) {
5260                 todo_list_release(&new_todo);
5261                 return error_errno(_("could not write '%s'"), todo_file);
5262         }
5263
5264         res = -1;
5265
5266         if (checkout_onto(r, opts, onto_name, &oid, orig_head))
5267                 goto cleanup;
5268
5269         if (require_clean_work_tree(r, "rebase", "", 1, 1))
5270                 goto cleanup;
5271
5272         todo_list_write_total_nr(&new_todo);
5273         res = pick_commits(r, &new_todo, opts);
5274
5275 cleanup:
5276         todo_list_release(&new_todo);
5277
5278         return res;
5279 }
5280
5281 struct subject2item_entry {
5282         struct hashmap_entry entry;
5283         int i;
5284         char subject[FLEX_ARRAY];
5285 };
5286
5287 static int subject2item_cmp(const void *fndata,
5288                             const struct hashmap_entry *eptr,
5289                             const struct hashmap_entry *entry_or_key,
5290                             const void *key)
5291 {
5292         const struct subject2item_entry *a, *b;
5293
5294         a = container_of(eptr, const struct subject2item_entry, entry);
5295         b = container_of(entry_or_key, const struct subject2item_entry, entry);
5296
5297         return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
5298 }
5299
5300 define_commit_slab(commit_todo_item, struct todo_item *);
5301
5302 /*
5303  * Rearrange the todo list that has both "pick commit-id msg" and "pick
5304  * commit-id fixup!/squash! msg" in it so that the latter is put immediately
5305  * after the former, and change "pick" to "fixup"/"squash".
5306  *
5307  * Note that if the config has specified a custom instruction format, each log
5308  * message will have to be retrieved from the commit (as the oneline in the
5309  * script cannot be trusted) in order to normalize the autosquash arrangement.
5310  */
5311 int todo_list_rearrange_squash(struct todo_list *todo_list)
5312 {
5313         struct hashmap subject2item;
5314         int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
5315         char **subjects;
5316         struct commit_todo_item commit_todo;
5317         struct todo_item *items = NULL;
5318
5319         init_commit_todo_item(&commit_todo);
5320         /*
5321          * The hashmap maps onelines to the respective todo list index.
5322          *
5323          * If any items need to be rearranged, the next[i] value will indicate
5324          * which item was moved directly after the i'th.
5325          *
5326          * In that case, last[i] will indicate the index of the latest item to
5327          * be moved to appear after the i'th.
5328          */
5329         hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
5330         ALLOC_ARRAY(next, todo_list->nr);
5331         ALLOC_ARRAY(tail, todo_list->nr);
5332         ALLOC_ARRAY(subjects, todo_list->nr);
5333         for (i = 0; i < todo_list->nr; i++) {
5334                 struct strbuf buf = STRBUF_INIT;
5335                 struct todo_item *item = todo_list->items + i;
5336                 const char *commit_buffer, *subject, *p;
5337                 size_t subject_len;
5338                 int i2 = -1;
5339                 struct subject2item_entry *entry;
5340
5341                 next[i] = tail[i] = -1;
5342                 if (!item->commit || item->command == TODO_DROP) {
5343                         subjects[i] = NULL;
5344                         continue;
5345                 }
5346
5347                 if (is_fixup(item->command)) {
5348                         clear_commit_todo_item(&commit_todo);
5349                         return error(_("the script was already rearranged."));
5350                 }
5351
5352                 *commit_todo_item_at(&commit_todo, item->commit) = item;
5353
5354                 parse_commit(item->commit);
5355                 commit_buffer = logmsg_reencode(item->commit, NULL, "UTF-8");
5356                 find_commit_subject(commit_buffer, &subject);
5357                 format_subject(&buf, subject, " ");
5358                 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
5359                 unuse_commit_buffer(item->commit, commit_buffer);
5360                 if ((skip_prefix(subject, "fixup! ", &p) ||
5361                      skip_prefix(subject, "squash! ", &p))) {
5362                         struct commit *commit2;
5363
5364                         for (;;) {
5365                                 while (isspace(*p))
5366                                         p++;
5367                                 if (!skip_prefix(p, "fixup! ", &p) &&
5368                                     !skip_prefix(p, "squash! ", &p))
5369                                         break;
5370                         }
5371
5372                         entry = hashmap_get_entry_from_hash(&subject2item,
5373                                                 strhash(p), p,
5374                                                 struct subject2item_entry,
5375                                                 entry);
5376                         if (entry)
5377                                 /* found by title */
5378                                 i2 = entry->i;
5379                         else if (!strchr(p, ' ') &&
5380                                  (commit2 =
5381                                   lookup_commit_reference_by_name(p)) &&
5382                                  *commit_todo_item_at(&commit_todo, commit2))
5383                                 /* found by commit name */
5384                                 i2 = *commit_todo_item_at(&commit_todo, commit2)
5385                                         - todo_list->items;
5386                         else {
5387                                 /* copy can be a prefix of the commit subject */
5388                                 for (i2 = 0; i2 < i; i2++)
5389                                         if (subjects[i2] &&
5390                                             starts_with(subjects[i2], p))
5391                                                 break;
5392                                 if (i2 == i)
5393                                         i2 = -1;
5394                         }
5395                 }
5396                 if (i2 >= 0) {
5397                         rearranged = 1;
5398                         todo_list->items[i].command =
5399                                 starts_with(subject, "fixup!") ?
5400                                 TODO_FIXUP : TODO_SQUASH;
5401                         if (tail[i2] < 0) {
5402                                 next[i] = next[i2];
5403                                 next[i2] = i;
5404                         } else {
5405                                 next[i] = next[tail[i2]];
5406                                 next[tail[i2]] = i;
5407                         }
5408                         tail[i2] = i;
5409                 } else if (!hashmap_get_from_hash(&subject2item,
5410                                                 strhash(subject), subject)) {
5411                         FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
5412                         entry->i = i;
5413                         hashmap_entry_init(&entry->entry,
5414                                         strhash(entry->subject));
5415                         hashmap_put(&subject2item, &entry->entry);
5416                 }
5417         }
5418
5419         if (rearranged) {
5420                 for (i = 0; i < todo_list->nr; i++) {
5421                         enum todo_command command = todo_list->items[i].command;
5422                         int cur = i;
5423
5424                         /*
5425                          * Initially, all commands are 'pick's. If it is a
5426                          * fixup or a squash now, we have rearranged it.
5427                          */
5428                         if (is_fixup(command))
5429                                 continue;
5430
5431                         while (cur >= 0) {
5432                                 ALLOC_GROW(items, nr + 1, alloc);
5433                                 items[nr++] = todo_list->items[cur];
5434                                 cur = next[cur];
5435                         }
5436                 }
5437
5438                 FREE_AND_NULL(todo_list->items);
5439                 todo_list->items = items;
5440                 todo_list->nr = nr;
5441                 todo_list->alloc = alloc;
5442         }
5443
5444         free(next);
5445         free(tail);
5446         for (i = 0; i < todo_list->nr; i++)
5447                 free(subjects[i]);
5448         free(subjects);
5449         hashmap_free_entries(&subject2item, struct subject2item_entry, entry);
5450
5451         clear_commit_todo_item(&commit_todo);
5452
5453         return 0;
5454 }
5455
5456 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
5457 {
5458         if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
5459                 struct object_id cherry_pick_head, rebase_head;
5460
5461                 if (file_exists(git_path_seq_dir()))
5462                         *whence = FROM_CHERRY_PICK_MULTI;
5463                 if (file_exists(rebase_path()) &&
5464                     !get_oid("REBASE_HEAD", &rebase_head) &&
5465                     !get_oid("CHERRY_PICK_HEAD", &cherry_pick_head) &&
5466                     oideq(&rebase_head, &cherry_pick_head))
5467                         *whence = FROM_REBASE_PICK;
5468                 else
5469                         *whence = FROM_CHERRY_PICK_SINGLE;
5470
5471                 return 1;
5472         }
5473
5474         return 0;
5475 }