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