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