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