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