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