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