114db3b277577cc05770fa530a4f79311a28e7e6
1#include "cache.h"
2#include "config.h"
3#include "lockfile.h"
4#include "sequencer.h"
5#include "dir.h"
6#include "object.h"
7#include "commit.h"
8#include "tag.h"
9#include "run-command.h"
10#include "exec_cmd.h"
11#include "utf8.h"
12#include "cache-tree.h"
13#include "diff.h"
14#include "revision.h"
15#include "rerere.h"
16#include "merge-recursive.h"
17#include "refs.h"
18#include "argv-array.h"
19#include "quote.h"
20#include "trailer.h"
21#include "log-tree.h"
22#include "wt-status.h"
23#include "hashmap.h"
24
25#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
26
27const char sign_off_header[] = "Signed-off-by: ";
28static const char cherry_picked_prefix[] = "(cherry picked from commit ";
29
30GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
31
32static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
33static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
34static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
35static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
36
37static GIT_PATH_FUNC(rebase_path, "rebase-merge")
38/*
39 * The file containing rebase commands, comments, and empty lines.
40 * This file is created by "git rebase -i" then edited by the user. As
41 * the lines are processed, they are removed from the front of this
42 * file and written to the tail of 'done'.
43 */
44static GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
45/*
46 * The rebase command lines that have already been processed. A line
47 * is moved here when it is first handled, before any associated user
48 * actions.
49 */
50static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
51/*
52 * The file to keep track of how many commands were already processed (e.g.
53 * for the prompt).
54 */
55static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum");
56/*
57 * The file to keep track of how many commands are to be processed in total
58 * (e.g. for the prompt).
59 */
60static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end");
61/*
62 * The commit message that is planned to be used for any changes that
63 * need to be committed following a user interaction.
64 */
65static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
66/*
67 * The file into which is accumulated the suggested commit message for
68 * squash/fixup commands. When the first of a series of squash/fixups
69 * is seen, the file is created and the commit message from the
70 * previous commit and from the first squash/fixup commit are written
71 * to it. The commit message for each subsequent squash/fixup commit
72 * is appended to the file as it is processed.
73 *
74 * The first line of the file is of the form
75 * # This is a combination of $count commits.
76 * where $count is the number of commits whose messages have been
77 * written to the file so far (including the initial "pick" commit).
78 * Each time that a commit message is processed, this line is read and
79 * updated. It is deleted just before the combined commit is made.
80 */
81static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
82/*
83 * If the current series of squash/fixups has not yet included a squash
84 * command, then this file exists and holds the commit message of the
85 * original "pick" commit. (If the series ends without a "squash"
86 * command, then this can be used as the commit message of the combined
87 * commit without opening the editor.)
88 */
89static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
90/*
91 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
92 * GIT_AUTHOR_DATE that will be used for the commit that is currently
93 * being rebased.
94 */
95static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
96/*
97 * When an "edit" rebase command is being processed, the SHA1 of the
98 * commit to be edited is recorded in this file. When "git rebase
99 * --continue" is executed, if there are any staged changes then they
100 * will be amended to the HEAD commit, but only provided the HEAD
101 * commit is still the commit to be edited. When any other rebase
102 * command is processed, this file is deleted.
103 */
104static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
105/*
106 * When we stop at a given patch via the "edit" command, this file contains
107 * the abbreviated commit name of the corresponding patch.
108 */
109static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
110/*
111 * For the post-rewrite hook, we make a list of rewritten commits and
112 * their new sha1s. The rewritten-pending list keeps the sha1s of
113 * commits that have been processed, but not committed yet,
114 * e.g. because they are waiting for a 'squash' command.
115 */
116static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
117static GIT_PATH_FUNC(rebase_path_rewritten_pending,
118 "rebase-merge/rewritten-pending")
119/*
120 * The following files are written by git-rebase just after parsing the
121 * command-line (and are only consumed, not modified, by the sequencer).
122 */
123static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
124static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
125static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
126static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
127static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
128static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
129static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
130static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
131static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
132
133static inline int is_rebase_i(const struct replay_opts *opts)
134{
135 return opts->action == REPLAY_INTERACTIVE_REBASE;
136}
137
138static const char *get_dir(const struct replay_opts *opts)
139{
140 if (is_rebase_i(opts))
141 return rebase_path();
142 return git_path_seq_dir();
143}
144
145static const char *get_todo_path(const struct replay_opts *opts)
146{
147 if (is_rebase_i(opts))
148 return rebase_path_todo();
149 return git_path_todo_file();
150}
151
152/*
153 * Returns 0 for non-conforming footer
154 * Returns 1 for conforming footer
155 * Returns 2 when sob exists within conforming footer
156 * Returns 3 when sob exists within conforming footer as last entry
157 */
158static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
159 int ignore_footer)
160{
161 struct trailer_info info;
162 int i;
163 int found_sob = 0, found_sob_last = 0;
164
165 trailer_info_get(&info, sb->buf);
166
167 if (info.trailer_start == info.trailer_end)
168 return 0;
169
170 for (i = 0; i < info.trailer_nr; i++)
171 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
172 found_sob = 1;
173 if (i == info.trailer_nr - 1)
174 found_sob_last = 1;
175 }
176
177 trailer_info_release(&info);
178
179 if (found_sob_last)
180 return 3;
181 if (found_sob)
182 return 2;
183 return 1;
184}
185
186static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
187{
188 static struct strbuf buf = STRBUF_INIT;
189
190 strbuf_reset(&buf);
191 if (opts->gpg_sign)
192 sq_quotef(&buf, "-S%s", opts->gpg_sign);
193 return buf.buf;
194}
195
196int sequencer_remove_state(struct replay_opts *opts)
197{
198 struct strbuf dir = STRBUF_INIT;
199 int i;
200
201 free(opts->gpg_sign);
202 free(opts->strategy);
203 for (i = 0; i < opts->xopts_nr; i++)
204 free(opts->xopts[i]);
205 free(opts->xopts);
206
207 strbuf_addstr(&dir, get_dir(opts));
208 remove_dir_recursively(&dir, 0);
209 strbuf_release(&dir);
210
211 return 0;
212}
213
214static const char *action_name(const struct replay_opts *opts)
215{
216 switch (opts->action) {
217 case REPLAY_REVERT:
218 return N_("revert");
219 case REPLAY_PICK:
220 return N_("cherry-pick");
221 case REPLAY_INTERACTIVE_REBASE:
222 return N_("rebase -i");
223 }
224 die(_("Unknown action: %d"), opts->action);
225}
226
227struct commit_message {
228 char *parent_label;
229 char *label;
230 char *subject;
231 const char *message;
232};
233
234static const char *short_commit_name(struct commit *commit)
235{
236 return find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
237}
238
239static int get_message(struct commit *commit, struct commit_message *out)
240{
241 const char *abbrev, *subject;
242 int subject_len;
243
244 out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
245 abbrev = short_commit_name(commit);
246
247 subject_len = find_commit_subject(out->message, &subject);
248
249 out->subject = xmemdupz(subject, subject_len);
250 out->label = xstrfmt("%s... %s", abbrev, out->subject);
251 out->parent_label = xstrfmt("parent of %s", out->label);
252
253 return 0;
254}
255
256static void free_message(struct commit *commit, struct commit_message *msg)
257{
258 free(msg->parent_label);
259 free(msg->label);
260 free(msg->subject);
261 unuse_commit_buffer(commit, msg->message);
262}
263
264static void print_advice(int show_hint, struct replay_opts *opts)
265{
266 char *msg = getenv("GIT_CHERRY_PICK_HELP");
267
268 if (msg) {
269 fprintf(stderr, "%s\n", msg);
270 /*
271 * A conflict has occurred but the porcelain
272 * (typically rebase --interactive) wants to take care
273 * of the commit itself so remove CHERRY_PICK_HEAD
274 */
275 unlink(git_path_cherry_pick_head());
276 return;
277 }
278
279 if (show_hint) {
280 if (opts->no_commit)
281 advise(_("after resolving the conflicts, mark the corrected paths\n"
282 "with 'git add <paths>' or 'git rm <paths>'"));
283 else
284 advise(_("after resolving the conflicts, mark the corrected paths\n"
285 "with 'git add <paths>' or 'git rm <paths>'\n"
286 "and commit the result with 'git commit'"));
287 }
288}
289
290static int write_message(const void *buf, size_t len, const char *filename,
291 int append_eol)
292{
293 static struct lock_file msg_file;
294
295 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
296 if (msg_fd < 0)
297 return error_errno(_("could not lock '%s'"), filename);
298 if (write_in_full(msg_fd, buf, len) < 0) {
299 error_errno(_("could not write to '%s'"), filename);
300 rollback_lock_file(&msg_file);
301 return -1;
302 }
303 if (append_eol && write(msg_fd, "\n", 1) < 0) {
304 error_errno(_("could not write eol to '%s'"), filename);
305 rollback_lock_file(&msg_file);
306 return -1;
307 }
308 if (commit_lock_file(&msg_file) < 0) {
309 rollback_lock_file(&msg_file);
310 return error(_("failed to finalize '%s'."), filename);
311 }
312
313 return 0;
314}
315
316/*
317 * Reads a file that was presumably written by a shell script, i.e. with an
318 * end-of-line marker that needs to be stripped.
319 *
320 * Note that only the last end-of-line marker is stripped, consistent with the
321 * behavior of "$(cat path)" in a shell script.
322 *
323 * Returns 1 if the file was read, 0 if it could not be read or does not exist.
324 */
325static int read_oneliner(struct strbuf *buf,
326 const char *path, int skip_if_empty)
327{
328 int orig_len = buf->len;
329
330 if (!file_exists(path))
331 return 0;
332
333 if (strbuf_read_file(buf, path, 0) < 0) {
334 warning_errno(_("could not read '%s'"), path);
335 return 0;
336 }
337
338 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
339 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
340 --buf->len;
341 buf->buf[buf->len] = '\0';
342 }
343
344 if (skip_if_empty && buf->len == orig_len)
345 return 0;
346
347 return 1;
348}
349
350static struct tree *empty_tree(void)
351{
352 return lookup_tree(the_hash_algo->empty_tree);
353}
354
355static int error_dirty_index(struct replay_opts *opts)
356{
357 if (read_cache_unmerged())
358 return error_resolve_conflict(_(action_name(opts)));
359
360 error(_("your local changes would be overwritten by %s."),
361 _(action_name(opts)));
362
363 if (advice_commit_before_merge)
364 advise(_("commit your changes or stash them to proceed."));
365 return -1;
366}
367
368static void update_abort_safety_file(void)
369{
370 struct object_id head;
371
372 /* Do nothing on a single-pick */
373 if (!file_exists(git_path_seq_dir()))
374 return;
375
376 if (!get_oid("HEAD", &head))
377 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
378 else
379 write_file(git_path_abort_safety_file(), "%s", "");
380}
381
382static int fast_forward_to(const struct object_id *to, const struct object_id *from,
383 int unborn, struct replay_opts *opts)
384{
385 struct ref_transaction *transaction;
386 struct strbuf sb = STRBUF_INIT;
387 struct strbuf err = STRBUF_INIT;
388
389 read_cache();
390 if (checkout_fast_forward(from, to, 1))
391 return -1; /* the callee should have complained already */
392
393 strbuf_addf(&sb, _("%s: fast-forward"), _(action_name(opts)));
394
395 transaction = ref_transaction_begin(&err);
396 if (!transaction ||
397 ref_transaction_update(transaction, "HEAD",
398 to, unborn ? &null_oid : from,
399 0, sb.buf, &err) ||
400 ref_transaction_commit(transaction, &err)) {
401 ref_transaction_free(transaction);
402 error("%s", err.buf);
403 strbuf_release(&sb);
404 strbuf_release(&err);
405 return -1;
406 }
407
408 strbuf_release(&sb);
409 strbuf_release(&err);
410 ref_transaction_free(transaction);
411 update_abort_safety_file();
412 return 0;
413}
414
415void append_conflicts_hint(struct strbuf *msgbuf)
416{
417 int i;
418
419 strbuf_addch(msgbuf, '\n');
420 strbuf_commented_addf(msgbuf, "Conflicts:\n");
421 for (i = 0; i < active_nr;) {
422 const struct cache_entry *ce = active_cache[i++];
423 if (ce_stage(ce)) {
424 strbuf_commented_addf(msgbuf, "\t%s\n", ce->name);
425 while (i < active_nr && !strcmp(ce->name,
426 active_cache[i]->name))
427 i++;
428 }
429 }
430}
431
432static int do_recursive_merge(struct commit *base, struct commit *next,
433 const char *base_label, const char *next_label,
434 struct object_id *head, struct strbuf *msgbuf,
435 struct replay_opts *opts)
436{
437 struct merge_options o;
438 struct tree *result, *next_tree, *base_tree, *head_tree;
439 int clean;
440 char **xopt;
441 static struct lock_file index_lock;
442
443 if (hold_locked_index(&index_lock, LOCK_REPORT_ON_ERROR) < 0)
444 return -1;
445
446 read_cache();
447
448 init_merge_options(&o);
449 o.ancestor = base ? base_label : "(empty tree)";
450 o.branch1 = "HEAD";
451 o.branch2 = next ? next_label : "(empty tree)";
452 if (is_rebase_i(opts))
453 o.buffer_output = 2;
454 o.show_rename_progress = 1;
455
456 head_tree = parse_tree_indirect(head);
457 next_tree = next ? next->tree : empty_tree();
458 base_tree = base ? base->tree : empty_tree();
459
460 for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
461 parse_merge_opt(&o, *xopt);
462
463 clean = merge_trees(&o,
464 head_tree,
465 next_tree, base_tree, &result);
466 if (is_rebase_i(opts) && clean <= 0)
467 fputs(o.obuf.buf, stdout);
468 strbuf_release(&o.obuf);
469 diff_warn_rename_limit("merge.renamelimit", o.needed_rename_limit, 0);
470 if (clean < 0)
471 return clean;
472
473 if (active_cache_changed &&
474 write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
475 /*
476 * TRANSLATORS: %s will be "revert", "cherry-pick" or
477 * "rebase -i".
478 */
479 return error(_("%s: Unable to write new index file"),
480 _(action_name(opts)));
481 rollback_lock_file(&index_lock);
482
483 if (opts->signoff)
484 append_signoff(msgbuf, 0, 0);
485
486 if (!clean)
487 append_conflicts_hint(msgbuf);
488
489 return !clean;
490}
491
492static int is_index_unchanged(void)
493{
494 struct object_id head_oid;
495 struct commit *head_commit;
496
497 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
498 return error(_("could not resolve HEAD commit"));
499
500 head_commit = lookup_commit(&head_oid);
501
502 /*
503 * If head_commit is NULL, check_commit, called from
504 * lookup_commit, would have indicated that head_commit is not
505 * a commit object already. parse_commit() will return failure
506 * without further complaints in such a case. Otherwise, if
507 * the commit is invalid, parse_commit() will complain. So
508 * there is nothing for us to say here. Just return failure.
509 */
510 if (parse_commit(head_commit))
511 return -1;
512
513 if (!active_cache_tree)
514 active_cache_tree = cache_tree();
515
516 if (!cache_tree_fully_valid(active_cache_tree))
517 if (cache_tree_update(&the_index, 0))
518 return error(_("unable to update cache tree"));
519
520 return !oidcmp(&active_cache_tree->oid,
521 &head_commit->tree->object.oid);
522}
523
524static int write_author_script(const char *message)
525{
526 struct strbuf buf = STRBUF_INIT;
527 const char *eol;
528 int res;
529
530 for (;;)
531 if (!*message || starts_with(message, "\n")) {
532missing_author:
533 /* Missing 'author' line? */
534 unlink(rebase_path_author_script());
535 return 0;
536 } else if (skip_prefix(message, "author ", &message))
537 break;
538 else if ((eol = strchr(message, '\n')))
539 message = eol + 1;
540 else
541 goto missing_author;
542
543 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
544 while (*message && *message != '\n' && *message != '\r')
545 if (skip_prefix(message, " <", &message))
546 break;
547 else if (*message != '\'')
548 strbuf_addch(&buf, *(message++));
549 else
550 strbuf_addf(&buf, "'\\\\%c'", *(message++));
551 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
552 while (*message && *message != '\n' && *message != '\r')
553 if (skip_prefix(message, "> ", &message))
554 break;
555 else if (*message != '\'')
556 strbuf_addch(&buf, *(message++));
557 else
558 strbuf_addf(&buf, "'\\\\%c'", *(message++));
559 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
560 while (*message && *message != '\n' && *message != '\r')
561 if (*message != '\'')
562 strbuf_addch(&buf, *(message++));
563 else
564 strbuf_addf(&buf, "'\\\\%c'", *(message++));
565 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
566 strbuf_release(&buf);
567 return res;
568}
569
570/*
571 * Read a list of environment variable assignments (such as the author-script
572 * file) into an environment block. Returns -1 on error, 0 otherwise.
573 */
574static int read_env_script(struct argv_array *env)
575{
576 struct strbuf script = STRBUF_INIT;
577 int i, count = 0;
578 char *p, *p2;
579
580 if (strbuf_read_file(&script, rebase_path_author_script(), 256) <= 0)
581 return -1;
582
583 for (p = script.buf; *p; p++)
584 if (skip_prefix(p, "'\\\\''", (const char **)&p2))
585 strbuf_splice(&script, p - script.buf, p2 - p, "'", 1);
586 else if (*p == '\'')
587 strbuf_splice(&script, p-- - script.buf, 1, "", 0);
588 else if (*p == '\n') {
589 *p = '\0';
590 count++;
591 }
592
593 for (i = 0, p = script.buf; i < count; i++) {
594 argv_array_push(env, p);
595 p += strlen(p) + 1;
596 }
597
598 return 0;
599}
600
601static const char staged_changes_advice[] =
602N_("you have staged changes in your working tree\n"
603"If these changes are meant to be squashed into the previous commit, run:\n"
604"\n"
605" git commit --amend %s\n"
606"\n"
607"If they are meant to go into a new commit, run:\n"
608"\n"
609" git commit %s\n"
610"\n"
611"In both cases, once you're done, continue with:\n"
612"\n"
613" git rebase --continue\n");
614
615#define ALLOW_EMPTY (1<<0)
616#define EDIT_MSG (1<<1)
617#define AMEND_MSG (1<<2)
618#define CLEANUP_MSG (1<<3)
619#define VERIFY_MSG (1<<4)
620
621/*
622 * If we are cherry-pick, and if the merge did not result in
623 * hand-editing, we will hit this commit and inherit the original
624 * author date and name.
625 *
626 * If we are revert, or if our cherry-pick results in a hand merge,
627 * we had better say that the current user is responsible for that.
628 *
629 * An exception is when run_git_commit() is called during an
630 * interactive rebase: in that case, we will want to retain the
631 * author metadata.
632 */
633static int run_git_commit(const char *defmsg, struct replay_opts *opts,
634 unsigned int flags)
635{
636 struct child_process cmd = CHILD_PROCESS_INIT;
637 const char *value;
638
639 cmd.git_cmd = 1;
640
641 if (is_rebase_i(opts)) {
642 if (!(flags & EDIT_MSG)) {
643 cmd.stdout_to_stderr = 1;
644 cmd.err = -1;
645 }
646
647 if (read_env_script(&cmd.env_array)) {
648 const char *gpg_opt = gpg_sign_opt_quoted(opts);
649
650 return error(_(staged_changes_advice),
651 gpg_opt, gpg_opt);
652 }
653 }
654
655 argv_array_push(&cmd.args, "commit");
656
657 if (!(flags & VERIFY_MSG))
658 argv_array_push(&cmd.args, "-n");
659 if ((flags & AMEND_MSG))
660 argv_array_push(&cmd.args, "--amend");
661 if (opts->gpg_sign)
662 argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
663 if (opts->signoff)
664 argv_array_push(&cmd.args, "-s");
665 if (defmsg)
666 argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
667 if ((flags & CLEANUP_MSG))
668 argv_array_push(&cmd.args, "--cleanup=strip");
669 if ((flags & EDIT_MSG))
670 argv_array_push(&cmd.args, "-e");
671 else if (!(flags & CLEANUP_MSG) &&
672 !opts->signoff && !opts->record_origin &&
673 git_config_get_value("commit.cleanup", &value))
674 argv_array_push(&cmd.args, "--cleanup=verbatim");
675
676 if ((flags & ALLOW_EMPTY))
677 argv_array_push(&cmd.args, "--allow-empty");
678
679 if (opts->allow_empty_message)
680 argv_array_push(&cmd.args, "--allow-empty-message");
681
682 if (cmd.err == -1) {
683 /* hide stderr on success */
684 struct strbuf buf = STRBUF_INIT;
685 int rc = pipe_command(&cmd,
686 NULL, 0,
687 /* stdout is already redirected */
688 NULL, 0,
689 &buf, 0);
690 if (rc)
691 fputs(buf.buf, stderr);
692 strbuf_release(&buf);
693 return rc;
694 }
695
696 return run_command(&cmd);
697}
698
699static int is_original_commit_empty(struct commit *commit)
700{
701 const struct object_id *ptree_oid;
702
703 if (parse_commit(commit))
704 return error(_("could not parse commit %s"),
705 oid_to_hex(&commit->object.oid));
706 if (commit->parents) {
707 struct commit *parent = commit->parents->item;
708 if (parse_commit(parent))
709 return error(_("could not parse parent commit %s"),
710 oid_to_hex(&parent->object.oid));
711 ptree_oid = &parent->tree->object.oid;
712 } else {
713 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
714 }
715
716 return !oidcmp(ptree_oid, &commit->tree->object.oid);
717}
718
719/*
720 * Do we run "git commit" with "--allow-empty"?
721 */
722static int allow_empty(struct replay_opts *opts, struct commit *commit)
723{
724 int index_unchanged, empty_commit;
725
726 /*
727 * Three cases:
728 *
729 * (1) we do not allow empty at all and error out.
730 *
731 * (2) we allow ones that were initially empty, but
732 * forbid the ones that become empty;
733 *
734 * (3) we allow both.
735 */
736 if (!opts->allow_empty)
737 return 0; /* let "git commit" barf as necessary */
738
739 index_unchanged = is_index_unchanged();
740 if (index_unchanged < 0)
741 return index_unchanged;
742 if (!index_unchanged)
743 return 0; /* we do not have to say --allow-empty */
744
745 if (opts->keep_redundant_commits)
746 return 1;
747
748 empty_commit = is_original_commit_empty(commit);
749 if (empty_commit < 0)
750 return empty_commit;
751 if (!empty_commit)
752 return 0;
753 else
754 return 1;
755}
756
757/*
758 * Note that ordering matters in this enum. Not only must it match the mapping
759 * below, it is also divided into several sections that matter. When adding
760 * new commands, make sure you add it in the right section.
761 */
762enum todo_command {
763 /* commands that handle commits */
764 TODO_PICK = 0,
765 TODO_REVERT,
766 TODO_EDIT,
767 TODO_REWORD,
768 TODO_FIXUP,
769 TODO_SQUASH,
770 /* commands that do something else than handling a single commit */
771 TODO_EXEC,
772 /* commands that do nothing but are counted for reporting progress */
773 TODO_NOOP,
774 TODO_DROP,
775 /* comments (not counted for reporting progress) */
776 TODO_COMMENT
777};
778
779static struct {
780 char c;
781 const char *str;
782} todo_command_info[] = {
783 { 'p', "pick" },
784 { 0, "revert" },
785 { 'e', "edit" },
786 { 'r', "reword" },
787 { 'f', "fixup" },
788 { 's', "squash" },
789 { 'x', "exec" },
790 { 0, "noop" },
791 { 'd', "drop" },
792 { 0, NULL }
793};
794
795static const char *command_to_string(const enum todo_command command)
796{
797 if (command < TODO_COMMENT)
798 return todo_command_info[command].str;
799 die("Unknown command: %d", command);
800}
801
802static char command_to_char(const enum todo_command command)
803{
804 if (command < TODO_COMMENT && todo_command_info[command].c)
805 return todo_command_info[command].c;
806 return comment_line_char;
807}
808
809static int is_noop(const enum todo_command command)
810{
811 return TODO_NOOP <= command;
812}
813
814static int is_fixup(enum todo_command command)
815{
816 return command == TODO_FIXUP || command == TODO_SQUASH;
817}
818
819static int update_squash_messages(enum todo_command command,
820 struct commit *commit, struct replay_opts *opts)
821{
822 struct strbuf buf = STRBUF_INIT;
823 int count, res;
824 const char *message, *body;
825
826 if (file_exists(rebase_path_squash_msg())) {
827 struct strbuf header = STRBUF_INIT;
828 char *eol, *p;
829
830 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
831 return error(_("could not read '%s'"),
832 rebase_path_squash_msg());
833
834 p = buf.buf + 1;
835 eol = strchrnul(buf.buf, '\n');
836 if (buf.buf[0] != comment_line_char ||
837 (p += strcspn(p, "0123456789\n")) == eol)
838 return error(_("unexpected 1st line of squash message:"
839 "\n\n\t%.*s"),
840 (int)(eol - buf.buf), buf.buf);
841 count = strtol(p, NULL, 10);
842
843 if (count < 1)
844 return error(_("invalid 1st line of squash message:\n"
845 "\n\t%.*s"),
846 (int)(eol - buf.buf), buf.buf);
847
848 strbuf_addf(&header, "%c ", comment_line_char);
849 strbuf_addf(&header,
850 _("This is a combination of %d commits."), ++count);
851 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
852 strbuf_release(&header);
853 } else {
854 struct object_id head;
855 struct commit *head_commit;
856 const char *head_message, *body;
857
858 if (get_oid("HEAD", &head))
859 return error(_("need a HEAD to fixup"));
860 if (!(head_commit = lookup_commit_reference(&head)))
861 return error(_("could not read HEAD"));
862 if (!(head_message = get_commit_buffer(head_commit, NULL)))
863 return error(_("could not read HEAD's commit message"));
864
865 find_commit_subject(head_message, &body);
866 if (write_message(body, strlen(body),
867 rebase_path_fixup_msg(), 0)) {
868 unuse_commit_buffer(head_commit, head_message);
869 return error(_("cannot write '%s'"),
870 rebase_path_fixup_msg());
871 }
872
873 count = 2;
874 strbuf_addf(&buf, "%c ", comment_line_char);
875 strbuf_addf(&buf, _("This is a combination of %d commits."),
876 count);
877 strbuf_addf(&buf, "\n%c ", comment_line_char);
878 strbuf_addstr(&buf, _("This is the 1st commit message:"));
879 strbuf_addstr(&buf, "\n\n");
880 strbuf_addstr(&buf, body);
881
882 unuse_commit_buffer(head_commit, head_message);
883 }
884
885 if (!(message = get_commit_buffer(commit, NULL)))
886 return error(_("could not read commit message of %s"),
887 oid_to_hex(&commit->object.oid));
888 find_commit_subject(message, &body);
889
890 if (command == TODO_SQUASH) {
891 unlink(rebase_path_fixup_msg());
892 strbuf_addf(&buf, "\n%c ", comment_line_char);
893 strbuf_addf(&buf, _("This is the commit message #%d:"), count);
894 strbuf_addstr(&buf, "\n\n");
895 strbuf_addstr(&buf, body);
896 } else if (command == TODO_FIXUP) {
897 strbuf_addf(&buf, "\n%c ", comment_line_char);
898 strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
899 count);
900 strbuf_addstr(&buf, "\n\n");
901 strbuf_add_commented_lines(&buf, body, strlen(body));
902 } else
903 return error(_("unknown command: %d"), command);
904 unuse_commit_buffer(commit, message);
905
906 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
907 strbuf_release(&buf);
908 return res;
909}
910
911static void flush_rewritten_pending(void) {
912 struct strbuf buf = STRBUF_INIT;
913 struct object_id newoid;
914 FILE *out;
915
916 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
917 !get_oid("HEAD", &newoid) &&
918 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
919 char *bol = buf.buf, *eol;
920
921 while (*bol) {
922 eol = strchrnul(bol, '\n');
923 fprintf(out, "%.*s %s\n", (int)(eol - bol),
924 bol, oid_to_hex(&newoid));
925 if (!*eol)
926 break;
927 bol = eol + 1;
928 }
929 fclose(out);
930 unlink(rebase_path_rewritten_pending());
931 }
932 strbuf_release(&buf);
933}
934
935static void record_in_rewritten(struct object_id *oid,
936 enum todo_command next_command) {
937 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
938
939 if (!out)
940 return;
941
942 fprintf(out, "%s\n", oid_to_hex(oid));
943 fclose(out);
944
945 if (!is_fixup(next_command))
946 flush_rewritten_pending();
947}
948
949static int do_pick_commit(enum todo_command command, struct commit *commit,
950 struct replay_opts *opts, int final_fixup)
951{
952 unsigned int flags = opts->edit ? EDIT_MSG : 0;
953 const char *msg_file = opts->edit ? NULL : git_path_merge_msg();
954 struct object_id head;
955 struct commit *base, *next, *parent;
956 const char *base_label, *next_label;
957 struct commit_message msg = { NULL, NULL, NULL, NULL };
958 struct strbuf msgbuf = STRBUF_INIT;
959 int res, unborn = 0, allow;
960
961 if (opts->no_commit) {
962 /*
963 * We do not intend to commit immediately. We just want to
964 * merge the differences in, so let's compute the tree
965 * that represents the "current" state for merge-recursive
966 * to work on.
967 */
968 if (write_cache_as_tree(head.hash, 0, NULL))
969 return error(_("your index file is unmerged."));
970 } else {
971 unborn = get_oid("HEAD", &head);
972 if (unborn)
973 oidcpy(&head, the_hash_algo->empty_tree);
974 if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
975 NULL, 0))
976 return error_dirty_index(opts);
977 }
978 discard_cache();
979
980 if (!commit->parents)
981 parent = NULL;
982 else if (commit->parents->next) {
983 /* Reverting or cherry-picking a merge commit */
984 int cnt;
985 struct commit_list *p;
986
987 if (!opts->mainline)
988 return error(_("commit %s is a merge but no -m option was given."),
989 oid_to_hex(&commit->object.oid));
990
991 for (cnt = 1, p = commit->parents;
992 cnt != opts->mainline && p;
993 cnt++)
994 p = p->next;
995 if (cnt != opts->mainline || !p)
996 return error(_("commit %s does not have parent %d"),
997 oid_to_hex(&commit->object.oid), opts->mainline);
998 parent = p->item;
999 } else if (0 < opts->mainline)
1000 return error(_("mainline was specified but commit %s is not a merge."),
1001 oid_to_hex(&commit->object.oid));
1002 else
1003 parent = commit->parents->item;
1004
1005 if (get_message(commit, &msg) != 0)
1006 return error(_("cannot get commit message for %s"),
1007 oid_to_hex(&commit->object.oid));
1008
1009 if (opts->allow_ff && !is_fixup(command) &&
1010 ((parent && !oidcmp(&parent->object.oid, &head)) ||
1011 (!parent && unborn))) {
1012 if (is_rebase_i(opts))
1013 write_author_script(msg.message);
1014 res = fast_forward_to(&commit->object.oid, &head, unborn,
1015 opts);
1016 if (res || command != TODO_REWORD)
1017 goto leave;
1018 flags |= EDIT_MSG | AMEND_MSG | VERIFY_MSG;
1019 msg_file = NULL;
1020 goto fast_forward_edit;
1021 }
1022 if (parent && parse_commit(parent) < 0)
1023 /* TRANSLATORS: The first %s will be a "todo" command like
1024 "revert" or "pick", the second %s a SHA1. */
1025 return error(_("%s: cannot parse parent commit %s"),
1026 command_to_string(command),
1027 oid_to_hex(&parent->object.oid));
1028
1029 /*
1030 * "commit" is an existing commit. We would want to apply
1031 * the difference it introduces since its first parent "prev"
1032 * on top of the current HEAD if we are cherry-pick. Or the
1033 * reverse of it if we are revert.
1034 */
1035
1036 if (command == TODO_REVERT) {
1037 base = commit;
1038 base_label = msg.label;
1039 next = parent;
1040 next_label = msg.parent_label;
1041 strbuf_addstr(&msgbuf, "Revert \"");
1042 strbuf_addstr(&msgbuf, msg.subject);
1043 strbuf_addstr(&msgbuf, "\"\n\nThis reverts commit ");
1044 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1045
1046 if (commit->parents && commit->parents->next) {
1047 strbuf_addstr(&msgbuf, ", reversing\nchanges made to ");
1048 strbuf_addstr(&msgbuf, oid_to_hex(&parent->object.oid));
1049 }
1050 strbuf_addstr(&msgbuf, ".\n");
1051 } else {
1052 const char *p;
1053
1054 base = parent;
1055 base_label = msg.parent_label;
1056 next = commit;
1057 next_label = msg.label;
1058
1059 /* Append the commit log message to msgbuf. */
1060 if (find_commit_subject(msg.message, &p))
1061 strbuf_addstr(&msgbuf, p);
1062
1063 if (opts->record_origin) {
1064 strbuf_complete_line(&msgbuf);
1065 if (!has_conforming_footer(&msgbuf, NULL, 0))
1066 strbuf_addch(&msgbuf, '\n');
1067 strbuf_addstr(&msgbuf, cherry_picked_prefix);
1068 strbuf_addstr(&msgbuf, oid_to_hex(&commit->object.oid));
1069 strbuf_addstr(&msgbuf, ")\n");
1070 }
1071 }
1072
1073 if (command == TODO_REWORD)
1074 flags |= EDIT_MSG | VERIFY_MSG;
1075 else if (is_fixup(command)) {
1076 if (update_squash_messages(command, commit, opts))
1077 return -1;
1078 flags |= AMEND_MSG;
1079 if (!final_fixup)
1080 msg_file = rebase_path_squash_msg();
1081 else if (file_exists(rebase_path_fixup_msg())) {
1082 flags |= CLEANUP_MSG;
1083 msg_file = rebase_path_fixup_msg();
1084 } else {
1085 const char *dest = git_path_squash_msg();
1086 unlink(dest);
1087 if (copy_file(dest, rebase_path_squash_msg(), 0666))
1088 return error(_("could not rename '%s' to '%s'"),
1089 rebase_path_squash_msg(), dest);
1090 unlink(git_path_merge_msg());
1091 msg_file = dest;
1092 flags |= EDIT_MSG;
1093 }
1094 }
1095
1096 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
1097 res = -1;
1098 else if (!opts->strategy || !strcmp(opts->strategy, "recursive") || command == TODO_REVERT) {
1099 res = do_recursive_merge(base, next, base_label, next_label,
1100 &head, &msgbuf, opts);
1101 if (res < 0)
1102 return res;
1103 res |= write_message(msgbuf.buf, msgbuf.len,
1104 git_path_merge_msg(), 0);
1105 } else {
1106 struct commit_list *common = NULL;
1107 struct commit_list *remotes = NULL;
1108
1109 res = write_message(msgbuf.buf, msgbuf.len,
1110 git_path_merge_msg(), 0);
1111
1112 commit_list_insert(base, &common);
1113 commit_list_insert(next, &remotes);
1114 res |= try_merge_command(opts->strategy,
1115 opts->xopts_nr, (const char **)opts->xopts,
1116 common, oid_to_hex(&head), remotes);
1117 free_commit_list(common);
1118 free_commit_list(remotes);
1119 }
1120 strbuf_release(&msgbuf);
1121
1122 /*
1123 * If the merge was clean or if it failed due to conflict, we write
1124 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
1125 * However, if the merge did not even start, then we don't want to
1126 * write it at all.
1127 */
1128 if (command == TODO_PICK && !opts->no_commit && (res == 0 || res == 1) &&
1129 update_ref(NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
1130 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1131 res = -1;
1132 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
1133 update_ref(NULL, "REVERT_HEAD", &commit->object.oid, NULL,
1134 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1135 res = -1;
1136
1137 if (res) {
1138 error(command == TODO_REVERT
1139 ? _("could not revert %s... %s")
1140 : _("could not apply %s... %s"),
1141 short_commit_name(commit), msg.subject);
1142 print_advice(res == 1, opts);
1143 rerere(opts->allow_rerere_auto);
1144 goto leave;
1145 }
1146
1147 allow = allow_empty(opts, commit);
1148 if (allow < 0) {
1149 res = allow;
1150 goto leave;
1151 } else if (allow)
1152 flags |= ALLOW_EMPTY;
1153 if (!opts->no_commit)
1154fast_forward_edit:
1155 res = run_git_commit(msg_file, opts, flags);
1156
1157 if (!res && final_fixup) {
1158 unlink(rebase_path_fixup_msg());
1159 unlink(rebase_path_squash_msg());
1160 }
1161
1162leave:
1163 free_message(commit, &msg);
1164 update_abort_safety_file();
1165
1166 return res;
1167}
1168
1169static int prepare_revs(struct replay_opts *opts)
1170{
1171 /*
1172 * picking (but not reverting) ranges (but not individual revisions)
1173 * should be done in reverse
1174 */
1175 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
1176 opts->revs->reverse ^= 1;
1177
1178 if (prepare_revision_walk(opts->revs))
1179 return error(_("revision walk setup failed"));
1180
1181 if (!opts->revs->commits)
1182 return error(_("empty commit set passed"));
1183 return 0;
1184}
1185
1186static int read_and_refresh_cache(struct replay_opts *opts)
1187{
1188 static struct lock_file index_lock;
1189 int index_fd = hold_locked_index(&index_lock, 0);
1190 if (read_index_preload(&the_index, NULL) < 0) {
1191 rollback_lock_file(&index_lock);
1192 return error(_("git %s: failed to read the index"),
1193 _(action_name(opts)));
1194 }
1195 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
1196 if (the_index.cache_changed && index_fd >= 0) {
1197 if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {
1198 return error(_("git %s: failed to refresh the index"),
1199 _(action_name(opts)));
1200 }
1201 }
1202 rollback_lock_file(&index_lock);
1203 return 0;
1204}
1205
1206struct todo_item {
1207 enum todo_command command;
1208 struct commit *commit;
1209 const char *arg;
1210 int arg_len;
1211 size_t offset_in_buf;
1212};
1213
1214struct todo_list {
1215 struct strbuf buf;
1216 struct todo_item *items;
1217 int nr, alloc, current;
1218 int done_nr, total_nr;
1219 struct stat_data stat;
1220};
1221
1222#define TODO_LIST_INIT { STRBUF_INIT }
1223
1224static void todo_list_release(struct todo_list *todo_list)
1225{
1226 strbuf_release(&todo_list->buf);
1227 FREE_AND_NULL(todo_list->items);
1228 todo_list->nr = todo_list->alloc = 0;
1229}
1230
1231static struct todo_item *append_new_todo(struct todo_list *todo_list)
1232{
1233 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
1234 return todo_list->items + todo_list->nr++;
1235}
1236
1237static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
1238{
1239 struct object_id commit_oid;
1240 char *end_of_object_name;
1241 int i, saved, status, padding;
1242
1243 /* left-trim */
1244 bol += strspn(bol, " \t");
1245
1246 if (bol == eol || *bol == '\r' || *bol == comment_line_char) {
1247 item->command = TODO_COMMENT;
1248 item->commit = NULL;
1249 item->arg = bol;
1250 item->arg_len = eol - bol;
1251 return 0;
1252 }
1253
1254 for (i = 0; i < TODO_COMMENT; i++)
1255 if (skip_prefix(bol, todo_command_info[i].str, &bol)) {
1256 item->command = i;
1257 break;
1258 } else if (bol[1] == ' ' && *bol == todo_command_info[i].c) {
1259 bol++;
1260 item->command = i;
1261 break;
1262 }
1263 if (i >= TODO_COMMENT)
1264 return -1;
1265
1266 /* Eat up extra spaces/ tabs before object name */
1267 padding = strspn(bol, " \t");
1268 bol += padding;
1269
1270 if (item->command == TODO_NOOP) {
1271 if (bol != eol)
1272 return error(_("%s does not accept arguments: '%s'"),
1273 command_to_string(item->command), bol);
1274 item->commit = NULL;
1275 item->arg = bol;
1276 item->arg_len = eol - bol;
1277 return 0;
1278 }
1279
1280 if (!padding)
1281 return error(_("missing arguments for %s"),
1282 command_to_string(item->command));
1283
1284 if (item->command == TODO_EXEC) {
1285 item->commit = NULL;
1286 item->arg = bol;
1287 item->arg_len = (int)(eol - bol);
1288 return 0;
1289 }
1290
1291 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
1292 saved = *end_of_object_name;
1293 *end_of_object_name = '\0';
1294 status = get_oid(bol, &commit_oid);
1295 *end_of_object_name = saved;
1296
1297 item->arg = end_of_object_name + strspn(end_of_object_name, " \t");
1298 item->arg_len = (int)(eol - item->arg);
1299
1300 if (status < 0)
1301 return -1;
1302
1303 item->commit = lookup_commit_reference(&commit_oid);
1304 return !item->commit;
1305}
1306
1307static int parse_insn_buffer(char *buf, struct todo_list *todo_list)
1308{
1309 struct todo_item *item;
1310 char *p = buf, *next_p;
1311 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
1312
1313 for (i = 1; *p; i++, p = next_p) {
1314 char *eol = strchrnul(p, '\n');
1315
1316 next_p = *eol ? eol + 1 /* skip LF */ : eol;
1317
1318 if (p != eol && eol[-1] == '\r')
1319 eol--; /* strip Carriage Return */
1320
1321 item = append_new_todo(todo_list);
1322 item->offset_in_buf = p - todo_list->buf.buf;
1323 if (parse_insn_line(item, p, eol)) {
1324 res = error(_("invalid line %d: %.*s"),
1325 i, (int)(eol - p), p);
1326 item->command = TODO_NOOP;
1327 }
1328
1329 if (fixup_okay)
1330 ; /* do nothing */
1331 else if (is_fixup(item->command))
1332 return error(_("cannot '%s' without a previous commit"),
1333 command_to_string(item->command));
1334 else if (!is_noop(item->command))
1335 fixup_okay = 1;
1336 }
1337
1338 return res;
1339}
1340
1341static int count_commands(struct todo_list *todo_list)
1342{
1343 int count = 0, i;
1344
1345 for (i = 0; i < todo_list->nr; i++)
1346 if (todo_list->items[i].command != TODO_COMMENT)
1347 count++;
1348
1349 return count;
1350}
1351
1352static int read_populate_todo(struct todo_list *todo_list,
1353 struct replay_opts *opts)
1354{
1355 struct stat st;
1356 const char *todo_file = get_todo_path(opts);
1357 int fd, res;
1358
1359 strbuf_reset(&todo_list->buf);
1360 fd = open(todo_file, O_RDONLY);
1361 if (fd < 0)
1362 return error_errno(_("could not open '%s'"), todo_file);
1363 if (strbuf_read(&todo_list->buf, fd, 0) < 0) {
1364 close(fd);
1365 return error(_("could not read '%s'."), todo_file);
1366 }
1367 close(fd);
1368
1369 res = stat(todo_file, &st);
1370 if (res)
1371 return error(_("could not stat '%s'"), todo_file);
1372 fill_stat_data(&todo_list->stat, &st);
1373
1374 res = parse_insn_buffer(todo_list->buf.buf, todo_list);
1375 if (res) {
1376 if (is_rebase_i(opts))
1377 return error(_("please fix this using "
1378 "'git rebase --edit-todo'."));
1379 return error(_("unusable instruction sheet: '%s'"), todo_file);
1380 }
1381
1382 if (!todo_list->nr &&
1383 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
1384 return error(_("no commits parsed."));
1385
1386 if (!is_rebase_i(opts)) {
1387 enum todo_command valid =
1388 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
1389 int i;
1390
1391 for (i = 0; i < todo_list->nr; i++)
1392 if (valid == todo_list->items[i].command)
1393 continue;
1394 else if (valid == TODO_PICK)
1395 return error(_("cannot cherry-pick during a revert."));
1396 else
1397 return error(_("cannot revert during a cherry-pick."));
1398 }
1399
1400 if (is_rebase_i(opts)) {
1401 struct todo_list done = TODO_LIST_INIT;
1402 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
1403
1404 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
1405 !parse_insn_buffer(done.buf.buf, &done))
1406 todo_list->done_nr = count_commands(&done);
1407 else
1408 todo_list->done_nr = 0;
1409
1410 todo_list->total_nr = todo_list->done_nr
1411 + count_commands(todo_list);
1412 todo_list_release(&done);
1413
1414 if (f) {
1415 fprintf(f, "%d\n", todo_list->total_nr);
1416 fclose(f);
1417 }
1418 }
1419
1420 return 0;
1421}
1422
1423static int git_config_string_dup(char **dest,
1424 const char *var, const char *value)
1425{
1426 if (!value)
1427 return config_error_nonbool(var);
1428 free(*dest);
1429 *dest = xstrdup(value);
1430 return 0;
1431}
1432
1433static int populate_opts_cb(const char *key, const char *value, void *data)
1434{
1435 struct replay_opts *opts = data;
1436 int error_flag = 1;
1437
1438 if (!value)
1439 error_flag = 0;
1440 else if (!strcmp(key, "options.no-commit"))
1441 opts->no_commit = git_config_bool_or_int(key, value, &error_flag);
1442 else if (!strcmp(key, "options.edit"))
1443 opts->edit = git_config_bool_or_int(key, value, &error_flag);
1444 else if (!strcmp(key, "options.signoff"))
1445 opts->signoff = git_config_bool_or_int(key, value, &error_flag);
1446 else if (!strcmp(key, "options.record-origin"))
1447 opts->record_origin = git_config_bool_or_int(key, value, &error_flag);
1448 else if (!strcmp(key, "options.allow-ff"))
1449 opts->allow_ff = git_config_bool_or_int(key, value, &error_flag);
1450 else if (!strcmp(key, "options.mainline"))
1451 opts->mainline = git_config_int(key, value);
1452 else if (!strcmp(key, "options.strategy"))
1453 git_config_string_dup(&opts->strategy, key, value);
1454 else if (!strcmp(key, "options.gpg-sign"))
1455 git_config_string_dup(&opts->gpg_sign, key, value);
1456 else if (!strcmp(key, "options.strategy-option")) {
1457 ALLOC_GROW(opts->xopts, opts->xopts_nr + 1, opts->xopts_alloc);
1458 opts->xopts[opts->xopts_nr++] = xstrdup(value);
1459 } else if (!strcmp(key, "options.allow-rerere-auto"))
1460 opts->allow_rerere_auto =
1461 git_config_bool_or_int(key, value, &error_flag) ?
1462 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
1463 else
1464 return error(_("invalid key: %s"), key);
1465
1466 if (!error_flag)
1467 return error(_("invalid value for %s: %s"), key, value);
1468
1469 return 0;
1470}
1471
1472static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
1473{
1474 int i;
1475
1476 strbuf_reset(buf);
1477 if (!read_oneliner(buf, rebase_path_strategy(), 0))
1478 return;
1479 opts->strategy = strbuf_detach(buf, NULL);
1480 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
1481 return;
1482
1483 opts->xopts_nr = split_cmdline(buf->buf, (const char ***)&opts->xopts);
1484 for (i = 0; i < opts->xopts_nr; i++) {
1485 const char *arg = opts->xopts[i];
1486
1487 skip_prefix(arg, "--", &arg);
1488 opts->xopts[i] = xstrdup(arg);
1489 }
1490}
1491
1492static int read_populate_opts(struct replay_opts *opts)
1493{
1494 if (is_rebase_i(opts)) {
1495 struct strbuf buf = STRBUF_INIT;
1496
1497 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(), 1)) {
1498 if (!starts_with(buf.buf, "-S"))
1499 strbuf_reset(&buf);
1500 else {
1501 free(opts->gpg_sign);
1502 opts->gpg_sign = xstrdup(buf.buf + 2);
1503 }
1504 strbuf_reset(&buf);
1505 }
1506
1507 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(), 1)) {
1508 if (!strcmp(buf.buf, "--rerere-autoupdate"))
1509 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
1510 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
1511 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
1512 strbuf_reset(&buf);
1513 }
1514
1515 if (file_exists(rebase_path_verbose()))
1516 opts->verbose = 1;
1517
1518 read_strategy_opts(opts, &buf);
1519 strbuf_release(&buf);
1520
1521 return 0;
1522 }
1523
1524 if (!file_exists(git_path_opts_file()))
1525 return 0;
1526 /*
1527 * The function git_parse_source(), called from git_config_from_file(),
1528 * may die() in case of a syntactically incorrect file. We do not care
1529 * about this case, though, because we wrote that file ourselves, so we
1530 * are pretty certain that it is syntactically correct.
1531 */
1532 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
1533 return error(_("malformed options sheet: '%s'"),
1534 git_path_opts_file());
1535 return 0;
1536}
1537
1538static int walk_revs_populate_todo(struct todo_list *todo_list,
1539 struct replay_opts *opts)
1540{
1541 enum todo_command command = opts->action == REPLAY_PICK ?
1542 TODO_PICK : TODO_REVERT;
1543 const char *command_string = todo_command_info[command].str;
1544 struct commit *commit;
1545
1546 if (prepare_revs(opts))
1547 return -1;
1548
1549 while ((commit = get_revision(opts->revs))) {
1550 struct todo_item *item = append_new_todo(todo_list);
1551 const char *commit_buffer = get_commit_buffer(commit, NULL);
1552 const char *subject;
1553 int subject_len;
1554
1555 item->command = command;
1556 item->commit = commit;
1557 item->arg = NULL;
1558 item->arg_len = 0;
1559 item->offset_in_buf = todo_list->buf.len;
1560 subject_len = find_commit_subject(commit_buffer, &subject);
1561 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
1562 short_commit_name(commit), subject_len, subject);
1563 unuse_commit_buffer(commit, commit_buffer);
1564 }
1565 return 0;
1566}
1567
1568static int create_seq_dir(void)
1569{
1570 if (file_exists(git_path_seq_dir())) {
1571 error(_("a cherry-pick or revert is already in progress"));
1572 advise(_("try \"git cherry-pick (--continue | --quit | --abort)\""));
1573 return -1;
1574 } else if (mkdir(git_path_seq_dir(), 0777) < 0)
1575 return error_errno(_("could not create sequencer directory '%s'"),
1576 git_path_seq_dir());
1577 return 0;
1578}
1579
1580static int save_head(const char *head)
1581{
1582 static struct lock_file head_lock;
1583 struct strbuf buf = STRBUF_INIT;
1584 int fd;
1585 ssize_t written;
1586
1587 fd = hold_lock_file_for_update(&head_lock, git_path_head_file(), 0);
1588 if (fd < 0) {
1589 error_errno(_("could not lock HEAD"));
1590 rollback_lock_file(&head_lock);
1591 return -1;
1592 }
1593 strbuf_addf(&buf, "%s\n", head);
1594 written = write_in_full(fd, buf.buf, buf.len);
1595 strbuf_release(&buf);
1596 if (written < 0) {
1597 error_errno(_("could not write to '%s'"), git_path_head_file());
1598 rollback_lock_file(&head_lock);
1599 return -1;
1600 }
1601 if (commit_lock_file(&head_lock) < 0) {
1602 rollback_lock_file(&head_lock);
1603 return error(_("failed to finalize '%s'."), git_path_head_file());
1604 }
1605 return 0;
1606}
1607
1608static int rollback_is_safe(void)
1609{
1610 struct strbuf sb = STRBUF_INIT;
1611 struct object_id expected_head, actual_head;
1612
1613 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
1614 strbuf_trim(&sb);
1615 if (get_oid_hex(sb.buf, &expected_head)) {
1616 strbuf_release(&sb);
1617 die(_("could not parse %s"), git_path_abort_safety_file());
1618 }
1619 strbuf_release(&sb);
1620 }
1621 else if (errno == ENOENT)
1622 oidclr(&expected_head);
1623 else
1624 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
1625
1626 if (get_oid("HEAD", &actual_head))
1627 oidclr(&actual_head);
1628
1629 return !oidcmp(&actual_head, &expected_head);
1630}
1631
1632static int reset_for_rollback(const struct object_id *oid)
1633{
1634 const char *argv[4]; /* reset --merge <arg> + NULL */
1635
1636 argv[0] = "reset";
1637 argv[1] = "--merge";
1638 argv[2] = oid_to_hex(oid);
1639 argv[3] = NULL;
1640 return run_command_v_opt(argv, RUN_GIT_CMD);
1641}
1642
1643static int rollback_single_pick(void)
1644{
1645 struct object_id head_oid;
1646
1647 if (!file_exists(git_path_cherry_pick_head()) &&
1648 !file_exists(git_path_revert_head()))
1649 return error(_("no cherry-pick or revert in progress"));
1650 if (read_ref_full("HEAD", 0, &head_oid, NULL))
1651 return error(_("cannot resolve HEAD"));
1652 if (is_null_oid(&head_oid))
1653 return error(_("cannot abort from a branch yet to be born"));
1654 return reset_for_rollback(&head_oid);
1655}
1656
1657int sequencer_rollback(struct replay_opts *opts)
1658{
1659 FILE *f;
1660 struct object_id oid;
1661 struct strbuf buf = STRBUF_INIT;
1662 const char *p;
1663
1664 f = fopen(git_path_head_file(), "r");
1665 if (!f && errno == ENOENT) {
1666 /*
1667 * There is no multiple-cherry-pick in progress.
1668 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
1669 * a single-cherry-pick in progress, abort that.
1670 */
1671 return rollback_single_pick();
1672 }
1673 if (!f)
1674 return error_errno(_("cannot open '%s'"), git_path_head_file());
1675 if (strbuf_getline_lf(&buf, f)) {
1676 error(_("cannot read '%s': %s"), git_path_head_file(),
1677 ferror(f) ? strerror(errno) : _("unexpected end of file"));
1678 fclose(f);
1679 goto fail;
1680 }
1681 fclose(f);
1682 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
1683 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
1684 git_path_head_file());
1685 goto fail;
1686 }
1687 if (is_null_oid(&oid)) {
1688 error(_("cannot abort from a branch yet to be born"));
1689 goto fail;
1690 }
1691
1692 if (!rollback_is_safe()) {
1693 /* Do not error, just do not rollback */
1694 warning(_("You seem to have moved HEAD. "
1695 "Not rewinding, check your HEAD!"));
1696 } else
1697 if (reset_for_rollback(&oid))
1698 goto fail;
1699 strbuf_release(&buf);
1700 return sequencer_remove_state(opts);
1701fail:
1702 strbuf_release(&buf);
1703 return -1;
1704}
1705
1706static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
1707{
1708 static struct lock_file todo_lock;
1709 const char *todo_path = get_todo_path(opts);
1710 int next = todo_list->current, offset, fd;
1711
1712 /*
1713 * rebase -i writes "git-rebase-todo" without the currently executing
1714 * command, appending it to "done" instead.
1715 */
1716 if (is_rebase_i(opts))
1717 next++;
1718
1719 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
1720 if (fd < 0)
1721 return error_errno(_("could not lock '%s'"), todo_path);
1722 offset = next < todo_list->nr ?
1723 todo_list->items[next].offset_in_buf : todo_list->buf.len;
1724 if (write_in_full(fd, todo_list->buf.buf + offset,
1725 todo_list->buf.len - offset) < 0)
1726 return error_errno(_("could not write to '%s'"), todo_path);
1727 if (commit_lock_file(&todo_lock) < 0)
1728 return error(_("failed to finalize '%s'."), todo_path);
1729
1730 if (is_rebase_i(opts)) {
1731 const char *done_path = rebase_path_done();
1732 int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
1733 int prev_offset = !next ? 0 :
1734 todo_list->items[next - 1].offset_in_buf;
1735
1736 if (fd >= 0 && offset > prev_offset &&
1737 write_in_full(fd, todo_list->buf.buf + prev_offset,
1738 offset - prev_offset) < 0) {
1739 close(fd);
1740 return error_errno(_("could not write to '%s'"),
1741 done_path);
1742 }
1743 if (fd >= 0)
1744 close(fd);
1745 }
1746 return 0;
1747}
1748
1749static int save_opts(struct replay_opts *opts)
1750{
1751 const char *opts_file = git_path_opts_file();
1752 int res = 0;
1753
1754 if (opts->no_commit)
1755 res |= git_config_set_in_file_gently(opts_file, "options.no-commit", "true");
1756 if (opts->edit)
1757 res |= git_config_set_in_file_gently(opts_file, "options.edit", "true");
1758 if (opts->signoff)
1759 res |= git_config_set_in_file_gently(opts_file, "options.signoff", "true");
1760 if (opts->record_origin)
1761 res |= git_config_set_in_file_gently(opts_file, "options.record-origin", "true");
1762 if (opts->allow_ff)
1763 res |= git_config_set_in_file_gently(opts_file, "options.allow-ff", "true");
1764 if (opts->mainline) {
1765 struct strbuf buf = STRBUF_INIT;
1766 strbuf_addf(&buf, "%d", opts->mainline);
1767 res |= git_config_set_in_file_gently(opts_file, "options.mainline", buf.buf);
1768 strbuf_release(&buf);
1769 }
1770 if (opts->strategy)
1771 res |= git_config_set_in_file_gently(opts_file, "options.strategy", opts->strategy);
1772 if (opts->gpg_sign)
1773 res |= git_config_set_in_file_gently(opts_file, "options.gpg-sign", opts->gpg_sign);
1774 if (opts->xopts) {
1775 int i;
1776 for (i = 0; i < opts->xopts_nr; i++)
1777 res |= git_config_set_multivar_in_file_gently(opts_file,
1778 "options.strategy-option",
1779 opts->xopts[i], "^$", 0);
1780 }
1781 if (opts->allow_rerere_auto)
1782 res |= git_config_set_in_file_gently(opts_file, "options.allow-rerere-auto",
1783 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
1784 "true" : "false");
1785 return res;
1786}
1787
1788static int make_patch(struct commit *commit, struct replay_opts *opts)
1789{
1790 struct strbuf buf = STRBUF_INIT;
1791 struct rev_info log_tree_opt;
1792 const char *subject, *p;
1793 int res = 0;
1794
1795 p = short_commit_name(commit);
1796 if (write_message(p, strlen(p), rebase_path_stopped_sha(), 1) < 0)
1797 return -1;
1798
1799 strbuf_addf(&buf, "%s/patch", get_dir(opts));
1800 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
1801 init_revisions(&log_tree_opt, NULL);
1802 log_tree_opt.abbrev = 0;
1803 log_tree_opt.diff = 1;
1804 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
1805 log_tree_opt.disable_stdin = 1;
1806 log_tree_opt.no_commit_id = 1;
1807 log_tree_opt.diffopt.file = fopen(buf.buf, "w");
1808 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
1809 if (!log_tree_opt.diffopt.file)
1810 res |= error_errno(_("could not open '%s'"), buf.buf);
1811 else {
1812 res |= log_tree_commit(&log_tree_opt, commit);
1813 fclose(log_tree_opt.diffopt.file);
1814 }
1815 strbuf_reset(&buf);
1816
1817 strbuf_addf(&buf, "%s/message", get_dir(opts));
1818 if (!file_exists(buf.buf)) {
1819 const char *commit_buffer = get_commit_buffer(commit, NULL);
1820 find_commit_subject(commit_buffer, &subject);
1821 res |= write_message(subject, strlen(subject), buf.buf, 1);
1822 unuse_commit_buffer(commit, commit_buffer);
1823 }
1824 strbuf_release(&buf);
1825
1826 return res;
1827}
1828
1829static int intend_to_amend(void)
1830{
1831 struct object_id head;
1832 char *p;
1833
1834 if (get_oid("HEAD", &head))
1835 return error(_("cannot read HEAD"));
1836
1837 p = oid_to_hex(&head);
1838 return write_message(p, strlen(p), rebase_path_amend(), 1);
1839}
1840
1841static int error_with_patch(struct commit *commit,
1842 const char *subject, int subject_len,
1843 struct replay_opts *opts, int exit_code, int to_amend)
1844{
1845 if (make_patch(commit, opts))
1846 return -1;
1847
1848 if (to_amend) {
1849 if (intend_to_amend())
1850 return -1;
1851
1852 fprintf(stderr, "You can amend the commit now, with\n"
1853 "\n"
1854 " git commit --amend %s\n"
1855 "\n"
1856 "Once you are satisfied with your changes, run\n"
1857 "\n"
1858 " git rebase --continue\n", gpg_sign_opt_quoted(opts));
1859 } else if (exit_code)
1860 fprintf(stderr, "Could not apply %s... %.*s\n",
1861 short_commit_name(commit), subject_len, subject);
1862
1863 return exit_code;
1864}
1865
1866static int error_failed_squash(struct commit *commit,
1867 struct replay_opts *opts, int subject_len, const char *subject)
1868{
1869 if (rename(rebase_path_squash_msg(), rebase_path_message()))
1870 return error(_("could not rename '%s' to '%s'"),
1871 rebase_path_squash_msg(), rebase_path_message());
1872 unlink(rebase_path_fixup_msg());
1873 unlink(git_path_merge_msg());
1874 if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
1875 return error(_("could not copy '%s' to '%s'"),
1876 rebase_path_message(), git_path_merge_msg());
1877 return error_with_patch(commit, subject, subject_len, opts, 1, 0);
1878}
1879
1880static int do_exec(const char *command_line)
1881{
1882 struct argv_array child_env = ARGV_ARRAY_INIT;
1883 const char *child_argv[] = { NULL, NULL };
1884 int dirty, status;
1885
1886 fprintf(stderr, "Executing: %s\n", command_line);
1887 child_argv[0] = command_line;
1888 argv_array_pushf(&child_env, "GIT_DIR=%s", absolute_path(get_git_dir()));
1889 status = run_command_v_opt_cd_env(child_argv, RUN_USING_SHELL, NULL,
1890 child_env.argv);
1891
1892 /* force re-reading of the cache */
1893 if (discard_cache() < 0 || read_cache() < 0)
1894 return error(_("could not read index"));
1895
1896 dirty = require_clean_work_tree("rebase", NULL, 1, 1);
1897
1898 if (status) {
1899 warning(_("execution failed: %s\n%s"
1900 "You can fix the problem, and then run\n"
1901 "\n"
1902 " git rebase --continue\n"
1903 "\n"),
1904 command_line,
1905 dirty ? N_("and made changes to the index and/or the "
1906 "working tree\n") : "");
1907 if (status == 127)
1908 /* command not found */
1909 status = 1;
1910 } else if (dirty) {
1911 warning(_("execution succeeded: %s\nbut "
1912 "left changes to the index and/or the working tree\n"
1913 "Commit or stash your changes, and then run\n"
1914 "\n"
1915 " git rebase --continue\n"
1916 "\n"), command_line);
1917 status = 1;
1918 }
1919
1920 argv_array_clear(&child_env);
1921
1922 return status;
1923}
1924
1925static int is_final_fixup(struct todo_list *todo_list)
1926{
1927 int i = todo_list->current;
1928
1929 if (!is_fixup(todo_list->items[i].command))
1930 return 0;
1931
1932 while (++i < todo_list->nr)
1933 if (is_fixup(todo_list->items[i].command))
1934 return 0;
1935 else if (!is_noop(todo_list->items[i].command))
1936 break;
1937 return 1;
1938}
1939
1940static enum todo_command peek_command(struct todo_list *todo_list, int offset)
1941{
1942 int i;
1943
1944 for (i = todo_list->current + offset; i < todo_list->nr; i++)
1945 if (!is_noop(todo_list->items[i].command))
1946 return todo_list->items[i].command;
1947
1948 return -1;
1949}
1950
1951static int apply_autostash(struct replay_opts *opts)
1952{
1953 struct strbuf stash_sha1 = STRBUF_INIT;
1954 struct child_process child = CHILD_PROCESS_INIT;
1955 int ret = 0;
1956
1957 if (!read_oneliner(&stash_sha1, rebase_path_autostash(), 1)) {
1958 strbuf_release(&stash_sha1);
1959 return 0;
1960 }
1961 strbuf_trim(&stash_sha1);
1962
1963 child.git_cmd = 1;
1964 child.no_stdout = 1;
1965 child.no_stderr = 1;
1966 argv_array_push(&child.args, "stash");
1967 argv_array_push(&child.args, "apply");
1968 argv_array_push(&child.args, stash_sha1.buf);
1969 if (!run_command(&child))
1970 fprintf(stderr, _("Applied autostash.\n"));
1971 else {
1972 struct child_process store = CHILD_PROCESS_INIT;
1973
1974 store.git_cmd = 1;
1975 argv_array_push(&store.args, "stash");
1976 argv_array_push(&store.args, "store");
1977 argv_array_push(&store.args, "-m");
1978 argv_array_push(&store.args, "autostash");
1979 argv_array_push(&store.args, "-q");
1980 argv_array_push(&store.args, stash_sha1.buf);
1981 if (run_command(&store))
1982 ret = error(_("cannot store %s"), stash_sha1.buf);
1983 else
1984 fprintf(stderr,
1985 _("Applying autostash resulted in conflicts.\n"
1986 "Your changes are safe in the stash.\n"
1987 "You can run \"git stash pop\" or"
1988 " \"git stash drop\" at any time.\n"));
1989 }
1990
1991 strbuf_release(&stash_sha1);
1992 return ret;
1993}
1994
1995static const char *reflog_message(struct replay_opts *opts,
1996 const char *sub_action, const char *fmt, ...)
1997{
1998 va_list ap;
1999 static struct strbuf buf = STRBUF_INIT;
2000
2001 va_start(ap, fmt);
2002 strbuf_reset(&buf);
2003 strbuf_addstr(&buf, action_name(opts));
2004 if (sub_action)
2005 strbuf_addf(&buf, " (%s)", sub_action);
2006 if (fmt) {
2007 strbuf_addstr(&buf, ": ");
2008 strbuf_vaddf(&buf, fmt, ap);
2009 }
2010 va_end(ap);
2011
2012 return buf.buf;
2013}
2014
2015static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
2016{
2017 int res = 0;
2018
2019 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2020 if (opts->allow_ff)
2021 assert(!(opts->signoff || opts->no_commit ||
2022 opts->record_origin || opts->edit));
2023 if (read_and_refresh_cache(opts))
2024 return -1;
2025
2026 while (todo_list->current < todo_list->nr) {
2027 struct todo_item *item = todo_list->items + todo_list->current;
2028 if (save_todo(todo_list, opts))
2029 return -1;
2030 if (is_rebase_i(opts)) {
2031 if (item->command != TODO_COMMENT) {
2032 FILE *f = fopen(rebase_path_msgnum(), "w");
2033
2034 todo_list->done_nr++;
2035
2036 if (f) {
2037 fprintf(f, "%d\n", todo_list->done_nr);
2038 fclose(f);
2039 }
2040 fprintf(stderr, "Rebasing (%d/%d)%s",
2041 todo_list->done_nr,
2042 todo_list->total_nr,
2043 opts->verbose ? "\n" : "\r");
2044 }
2045 unlink(rebase_path_message());
2046 unlink(rebase_path_author_script());
2047 unlink(rebase_path_stopped_sha());
2048 unlink(rebase_path_amend());
2049 }
2050 if (item->command <= TODO_SQUASH) {
2051 if (is_rebase_i(opts))
2052 setenv("GIT_REFLOG_ACTION", reflog_message(opts,
2053 command_to_string(item->command), NULL),
2054 1);
2055 res = do_pick_commit(item->command, item->commit,
2056 opts, is_final_fixup(todo_list));
2057 if (is_rebase_i(opts) && res < 0) {
2058 /* Reschedule */
2059 todo_list->current--;
2060 if (save_todo(todo_list, opts))
2061 return -1;
2062 }
2063 if (item->command == TODO_EDIT) {
2064 struct commit *commit = item->commit;
2065 if (!res)
2066 fprintf(stderr,
2067 _("Stopped at %s... %.*s\n"),
2068 short_commit_name(commit),
2069 item->arg_len, item->arg);
2070 return error_with_patch(commit,
2071 item->arg, item->arg_len, opts, res,
2072 !res);
2073 }
2074 if (is_rebase_i(opts) && !res)
2075 record_in_rewritten(&item->commit->object.oid,
2076 peek_command(todo_list, 1));
2077 if (res && is_fixup(item->command)) {
2078 if (res == 1)
2079 intend_to_amend();
2080 return error_failed_squash(item->commit, opts,
2081 item->arg_len, item->arg);
2082 } else if (res && is_rebase_i(opts))
2083 return res | error_with_patch(item->commit,
2084 item->arg, item->arg_len, opts, res,
2085 item->command == TODO_REWORD);
2086 } else if (item->command == TODO_EXEC) {
2087 char *end_of_arg = (char *)(item->arg + item->arg_len);
2088 int saved = *end_of_arg;
2089 struct stat st;
2090
2091 *end_of_arg = '\0';
2092 res = do_exec(item->arg);
2093 *end_of_arg = saved;
2094
2095 /* Reread the todo file if it has changed. */
2096 if (res)
2097 ; /* fall through */
2098 else if (stat(get_todo_path(opts), &st))
2099 res = error_errno(_("could not stat '%s'"),
2100 get_todo_path(opts));
2101 else if (match_stat_data(&todo_list->stat, &st)) {
2102 todo_list_release(todo_list);
2103 if (read_populate_todo(todo_list, opts))
2104 res = -1; /* message was printed */
2105 /* `current` will be incremented below */
2106 todo_list->current = -1;
2107 }
2108 } else if (!is_noop(item->command))
2109 return error(_("unknown command %d"), item->command);
2110
2111 todo_list->current++;
2112 if (res)
2113 return res;
2114 }
2115
2116 if (is_rebase_i(opts)) {
2117 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
2118 struct stat st;
2119
2120 /* Stopped in the middle, as planned? */
2121 if (todo_list->current < todo_list->nr)
2122 return 0;
2123
2124 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
2125 starts_with(head_ref.buf, "refs/")) {
2126 const char *msg;
2127 struct object_id head, orig;
2128 int res;
2129
2130 if (get_oid("HEAD", &head)) {
2131 res = error(_("cannot read HEAD"));
2132cleanup_head_ref:
2133 strbuf_release(&head_ref);
2134 strbuf_release(&buf);
2135 return res;
2136 }
2137 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
2138 get_oid_hex(buf.buf, &orig)) {
2139 res = error(_("could not read orig-head"));
2140 goto cleanup_head_ref;
2141 }
2142 strbuf_reset(&buf);
2143 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
2144 res = error(_("could not read 'onto'"));
2145 goto cleanup_head_ref;
2146 }
2147 msg = reflog_message(opts, "finish", "%s onto %s",
2148 head_ref.buf, buf.buf);
2149 if (update_ref(msg, head_ref.buf, &head, &orig,
2150 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
2151 res = error(_("could not update %s"),
2152 head_ref.buf);
2153 goto cleanup_head_ref;
2154 }
2155 msg = reflog_message(opts, "finish", "returning to %s",
2156 head_ref.buf);
2157 if (create_symref("HEAD", head_ref.buf, msg)) {
2158 res = error(_("could not update HEAD to %s"),
2159 head_ref.buf);
2160 goto cleanup_head_ref;
2161 }
2162 strbuf_reset(&buf);
2163 }
2164
2165 if (opts->verbose) {
2166 struct rev_info log_tree_opt;
2167 struct object_id orig, head;
2168
2169 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
2170 init_revisions(&log_tree_opt, NULL);
2171 log_tree_opt.diff = 1;
2172 log_tree_opt.diffopt.output_format =
2173 DIFF_FORMAT_DIFFSTAT;
2174 log_tree_opt.disable_stdin = 1;
2175
2176 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
2177 !get_oid(buf.buf, &orig) &&
2178 !get_oid("HEAD", &head)) {
2179 diff_tree_oid(&orig, &head, "",
2180 &log_tree_opt.diffopt);
2181 log_tree_diff_flush(&log_tree_opt);
2182 }
2183 }
2184 flush_rewritten_pending();
2185 if (!stat(rebase_path_rewritten_list(), &st) &&
2186 st.st_size > 0) {
2187 struct child_process child = CHILD_PROCESS_INIT;
2188 const char *post_rewrite_hook =
2189 find_hook("post-rewrite");
2190
2191 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
2192 child.git_cmd = 1;
2193 argv_array_push(&child.args, "notes");
2194 argv_array_push(&child.args, "copy");
2195 argv_array_push(&child.args, "--for-rewrite=rebase");
2196 /* we don't care if this copying failed */
2197 run_command(&child);
2198
2199 if (post_rewrite_hook) {
2200 struct child_process hook = CHILD_PROCESS_INIT;
2201
2202 hook.in = open(rebase_path_rewritten_list(),
2203 O_RDONLY);
2204 hook.stdout_to_stderr = 1;
2205 argv_array_push(&hook.args, post_rewrite_hook);
2206 argv_array_push(&hook.args, "rebase");
2207 /* we don't care if this hook failed */
2208 run_command(&hook);
2209 }
2210 }
2211 apply_autostash(opts);
2212
2213 fprintf(stderr, "Successfully rebased and updated %s.\n",
2214 head_ref.buf);
2215
2216 strbuf_release(&buf);
2217 strbuf_release(&head_ref);
2218 }
2219
2220 /*
2221 * Sequence of picks finished successfully; cleanup by
2222 * removing the .git/sequencer directory
2223 */
2224 return sequencer_remove_state(opts);
2225}
2226
2227static int continue_single_pick(void)
2228{
2229 const char *argv[] = { "commit", NULL };
2230
2231 if (!file_exists(git_path_cherry_pick_head()) &&
2232 !file_exists(git_path_revert_head()))
2233 return error(_("no cherry-pick or revert in progress"));
2234 return run_command_v_opt(argv, RUN_GIT_CMD);
2235}
2236
2237static int commit_staged_changes(struct replay_opts *opts)
2238{
2239 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
2240
2241 if (has_unstaged_changes(1))
2242 return error(_("cannot rebase: You have unstaged changes."));
2243 if (!has_uncommitted_changes(0)) {
2244 const char *cherry_pick_head = git_path_cherry_pick_head();
2245
2246 if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
2247 return error(_("could not remove CHERRY_PICK_HEAD"));
2248 return 0;
2249 }
2250
2251 if (file_exists(rebase_path_amend())) {
2252 struct strbuf rev = STRBUF_INIT;
2253 struct object_id head, to_amend;
2254
2255 if (get_oid("HEAD", &head))
2256 return error(_("cannot amend non-existing commit"));
2257 if (!read_oneliner(&rev, rebase_path_amend(), 0))
2258 return error(_("invalid file: '%s'"), rebase_path_amend());
2259 if (get_oid_hex(rev.buf, &to_amend))
2260 return error(_("invalid contents: '%s'"),
2261 rebase_path_amend());
2262 if (oidcmp(&head, &to_amend))
2263 return error(_("\nYou have uncommitted changes in your "
2264 "working tree. Please, commit them\n"
2265 "first and then run 'git rebase "
2266 "--continue' again."));
2267
2268 strbuf_release(&rev);
2269 flags |= AMEND_MSG;
2270 }
2271
2272 if (run_git_commit(rebase_path_message(), opts, flags))
2273 return error(_("could not commit staged changes."));
2274 unlink(rebase_path_amend());
2275 return 0;
2276}
2277
2278int sequencer_continue(struct replay_opts *opts)
2279{
2280 struct todo_list todo_list = TODO_LIST_INIT;
2281 int res;
2282
2283 if (read_and_refresh_cache(opts))
2284 return -1;
2285
2286 if (is_rebase_i(opts)) {
2287 if (commit_staged_changes(opts))
2288 return -1;
2289 } else if (!file_exists(get_todo_path(opts)))
2290 return continue_single_pick();
2291 if (read_populate_opts(opts))
2292 return -1;
2293 if ((res = read_populate_todo(&todo_list, opts)))
2294 goto release_todo_list;
2295
2296 if (!is_rebase_i(opts)) {
2297 /* Verify that the conflict has been resolved */
2298 if (file_exists(git_path_cherry_pick_head()) ||
2299 file_exists(git_path_revert_head())) {
2300 res = continue_single_pick();
2301 if (res)
2302 goto release_todo_list;
2303 }
2304 if (index_differs_from("HEAD", NULL, 0)) {
2305 res = error_dirty_index(opts);
2306 goto release_todo_list;
2307 }
2308 todo_list.current++;
2309 } else if (file_exists(rebase_path_stopped_sha())) {
2310 struct strbuf buf = STRBUF_INIT;
2311 struct object_id oid;
2312
2313 if (read_oneliner(&buf, rebase_path_stopped_sha(), 1) &&
2314 !get_oid_committish(buf.buf, &oid))
2315 record_in_rewritten(&oid, peek_command(&todo_list, 0));
2316 strbuf_release(&buf);
2317 }
2318
2319 res = pick_commits(&todo_list, opts);
2320release_todo_list:
2321 todo_list_release(&todo_list);
2322 return res;
2323}
2324
2325static int single_pick(struct commit *cmit, struct replay_opts *opts)
2326{
2327 setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
2328 return do_pick_commit(opts->action == REPLAY_PICK ?
2329 TODO_PICK : TODO_REVERT, cmit, opts, 0);
2330}
2331
2332int sequencer_pick_revisions(struct replay_opts *opts)
2333{
2334 struct todo_list todo_list = TODO_LIST_INIT;
2335 struct object_id oid;
2336 int i, res;
2337
2338 assert(opts->revs);
2339 if (read_and_refresh_cache(opts))
2340 return -1;
2341
2342 for (i = 0; i < opts->revs->pending.nr; i++) {
2343 struct object_id oid;
2344 const char *name = opts->revs->pending.objects[i].name;
2345
2346 /* This happens when using --stdin. */
2347 if (!strlen(name))
2348 continue;
2349
2350 if (!get_oid(name, &oid)) {
2351 if (!lookup_commit_reference_gently(&oid, 1)) {
2352 enum object_type type = sha1_object_info(oid.hash, NULL);
2353 return error(_("%s: can't cherry-pick a %s"),
2354 name, typename(type));
2355 }
2356 } else
2357 return error(_("%s: bad revision"), name);
2358 }
2359
2360 /*
2361 * If we were called as "git cherry-pick <commit>", just
2362 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
2363 * REVERT_HEAD, and don't touch the sequencer state.
2364 * This means it is possible to cherry-pick in the middle
2365 * of a cherry-pick sequence.
2366 */
2367 if (opts->revs->cmdline.nr == 1 &&
2368 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
2369 opts->revs->no_walk &&
2370 !opts->revs->cmdline.rev->flags) {
2371 struct commit *cmit;
2372 if (prepare_revision_walk(opts->revs))
2373 return error(_("revision walk setup failed"));
2374 cmit = get_revision(opts->revs);
2375 if (!cmit || get_revision(opts->revs))
2376 return error("BUG: expected exactly one commit from walk");
2377 return single_pick(cmit, opts);
2378 }
2379
2380 /*
2381 * Start a new cherry-pick/ revert sequence; but
2382 * first, make sure that an existing one isn't in
2383 * progress
2384 */
2385
2386 if (walk_revs_populate_todo(&todo_list, opts) ||
2387 create_seq_dir() < 0)
2388 return -1;
2389 if (get_oid("HEAD", &oid) && (opts->action == REPLAY_REVERT))
2390 return error(_("can't revert as initial commit"));
2391 if (save_head(oid_to_hex(&oid)))
2392 return -1;
2393 if (save_opts(opts))
2394 return -1;
2395 update_abort_safety_file();
2396 res = pick_commits(&todo_list, opts);
2397 todo_list_release(&todo_list);
2398 return res;
2399}
2400
2401void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
2402{
2403 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
2404 struct strbuf sob = STRBUF_INIT;
2405 int has_footer;
2406
2407 strbuf_addstr(&sob, sign_off_header);
2408 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
2409 getenv("GIT_COMMITTER_EMAIL")));
2410 strbuf_addch(&sob, '\n');
2411
2412 if (!ignore_footer)
2413 strbuf_complete_line(msgbuf);
2414
2415 /*
2416 * If the whole message buffer is equal to the sob, pretend that we
2417 * found a conforming footer with a matching sob
2418 */
2419 if (msgbuf->len - ignore_footer == sob.len &&
2420 !strncmp(msgbuf->buf, sob.buf, sob.len))
2421 has_footer = 3;
2422 else
2423 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
2424
2425 if (!has_footer) {
2426 const char *append_newlines = NULL;
2427 size_t len = msgbuf->len - ignore_footer;
2428
2429 if (!len) {
2430 /*
2431 * The buffer is completely empty. Leave foom for
2432 * the title and body to be filled in by the user.
2433 */
2434 append_newlines = "\n\n";
2435 } else if (len == 1) {
2436 /*
2437 * Buffer contains a single newline. Add another
2438 * so that we leave room for the title and body.
2439 */
2440 append_newlines = "\n";
2441 } else if (msgbuf->buf[len - 2] != '\n') {
2442 /*
2443 * Buffer ends with a single newline. Add another
2444 * so that there is an empty line between the message
2445 * body and the sob.
2446 */
2447 append_newlines = "\n";
2448 } /* else, the buffer already ends with two newlines. */
2449
2450 if (append_newlines)
2451 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2452 append_newlines, strlen(append_newlines));
2453 }
2454
2455 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
2456 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
2457 sob.buf, sob.len);
2458
2459 strbuf_release(&sob);
2460}
2461
2462int sequencer_make_script(FILE *out, int argc, const char **argv,
2463 unsigned flags)
2464{
2465 char *format = NULL;
2466 struct pretty_print_context pp = {0};
2467 struct strbuf buf = STRBUF_INIT;
2468 struct rev_info revs;
2469 struct commit *commit;
2470 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
2471 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
2472
2473 init_revisions(&revs, NULL);
2474 revs.verbose_header = 1;
2475 revs.max_parents = 1;
2476 revs.cherry_pick = 1;
2477 revs.limited = 1;
2478 revs.reverse = 1;
2479 revs.right_only = 1;
2480 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
2481 revs.topo_order = 1;
2482
2483 revs.pretty_given = 1;
2484 git_config_get_string("rebase.instructionFormat", &format);
2485 if (!format || !*format) {
2486 free(format);
2487 format = xstrdup("%s");
2488 }
2489 get_commit_format(format, &revs);
2490 free(format);
2491 pp.fmt = revs.commit_format;
2492 pp.output_encoding = get_log_output_encoding();
2493
2494 if (setup_revisions(argc, argv, &revs, NULL) > 1)
2495 return error(_("make_script: unhandled options"));
2496
2497 if (prepare_revision_walk(&revs) < 0)
2498 return error(_("make_script: error preparing revisions"));
2499
2500 while ((commit = get_revision(&revs))) {
2501 strbuf_reset(&buf);
2502 if (!keep_empty && is_original_commit_empty(commit))
2503 strbuf_addf(&buf, "%c ", comment_line_char);
2504 strbuf_addf(&buf, "%s %s ", insn,
2505 oid_to_hex(&commit->object.oid));
2506 pretty_print_commit(&pp, commit, &buf);
2507 strbuf_addch(&buf, '\n');
2508 fputs(buf.buf, out);
2509 }
2510 strbuf_release(&buf);
2511 return 0;
2512}
2513
2514/*
2515 * Add commands after pick and (series of) squash/fixup commands
2516 * in the todo list.
2517 */
2518int sequencer_add_exec_commands(const char *commands)
2519{
2520 const char *todo_file = rebase_path_todo();
2521 struct todo_list todo_list = TODO_LIST_INIT;
2522 struct todo_item *item;
2523 struct strbuf *buf = &todo_list.buf;
2524 size_t offset = 0, commands_len = strlen(commands);
2525 int i, first;
2526
2527 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
2528 return error(_("could not read '%s'."), todo_file);
2529
2530 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
2531 todo_list_release(&todo_list);
2532 return error(_("unusable todo list: '%s'"), todo_file);
2533 }
2534
2535 first = 1;
2536 /* insert <commands> before every pick except the first one */
2537 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
2538 if (item->command == TODO_PICK && !first) {
2539 strbuf_insert(buf, item->offset_in_buf + offset,
2540 commands, commands_len);
2541 offset += commands_len;
2542 }
2543 first = 0;
2544 }
2545
2546 /* append final <commands> */
2547 strbuf_add(buf, commands, commands_len);
2548
2549 i = write_message(buf->buf, buf->len, todo_file, 0);
2550 todo_list_release(&todo_list);
2551 return i;
2552}
2553
2554int transform_todos(unsigned flags)
2555{
2556 const char *todo_file = rebase_path_todo();
2557 struct todo_list todo_list = TODO_LIST_INIT;
2558 struct strbuf buf = STRBUF_INIT;
2559 struct todo_item *item;
2560 int i;
2561
2562 if (strbuf_read_file(&todo_list.buf, todo_file, 0) < 0)
2563 return error(_("could not read '%s'."), todo_file);
2564
2565 if (parse_insn_buffer(todo_list.buf.buf, &todo_list)) {
2566 todo_list_release(&todo_list);
2567 return error(_("unusable todo list: '%s'"), todo_file);
2568 }
2569
2570 for (item = todo_list.items, i = 0; i < todo_list.nr; i++, item++) {
2571 /* if the item is not a command write it and continue */
2572 if (item->command >= TODO_COMMENT) {
2573 strbuf_addf(&buf, "%.*s\n", item->arg_len, item->arg);
2574 continue;
2575 }
2576
2577 /* add command to the buffer */
2578 if (flags & TODO_LIST_ABBREVIATE_CMDS)
2579 strbuf_addch(&buf, command_to_char(item->command));
2580 else
2581 strbuf_addstr(&buf, command_to_string(item->command));
2582
2583 /* add commit id */
2584 if (item->commit) {
2585 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
2586 short_commit_name(item->commit) :
2587 oid_to_hex(&item->commit->object.oid);
2588
2589 strbuf_addf(&buf, " %s", oid);
2590 }
2591 /* add all the rest */
2592 if (!item->arg_len)
2593 strbuf_addch(&buf, '\n');
2594 else
2595 strbuf_addf(&buf, " %.*s\n", item->arg_len, item->arg);
2596 }
2597
2598 i = write_message(buf.buf, buf.len, todo_file, 0);
2599 todo_list_release(&todo_list);
2600 return i;
2601}
2602
2603enum check_level {
2604 CHECK_IGNORE = 0, CHECK_WARN, CHECK_ERROR
2605};
2606
2607static enum check_level get_missing_commit_check_level(void)
2608{
2609 const char *value;
2610
2611 if (git_config_get_value("rebase.missingcommitscheck", &value) ||
2612 !strcasecmp("ignore", value))
2613 return CHECK_IGNORE;
2614 if (!strcasecmp("warn", value))
2615 return CHECK_WARN;
2616 if (!strcasecmp("error", value))
2617 return CHECK_ERROR;
2618 warning(_("unrecognized setting %s for option "
2619 "rebase.missingCommitsCheck. Ignoring."), value);
2620 return CHECK_IGNORE;
2621}
2622
2623/*
2624 * Check if the user dropped some commits by mistake
2625 * Behaviour determined by rebase.missingCommitsCheck.
2626 * Check if there is an unrecognized command or a
2627 * bad SHA-1 in a command.
2628 */
2629int check_todo_list(void)
2630{
2631 enum check_level check_level = get_missing_commit_check_level();
2632 struct strbuf todo_file = STRBUF_INIT;
2633 struct todo_list todo_list = TODO_LIST_INIT;
2634 struct strbuf missing = STRBUF_INIT;
2635 int advise_to_edit_todo = 0, res = 0, fd, i;
2636
2637 strbuf_addstr(&todo_file, rebase_path_todo());
2638 fd = open(todo_file.buf, O_RDONLY);
2639 if (fd < 0) {
2640 res = error_errno(_("could not open '%s'"), todo_file.buf);
2641 goto leave_check;
2642 }
2643 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2644 close(fd);
2645 res = error(_("could not read '%s'."), todo_file.buf);
2646 goto leave_check;
2647 }
2648 close(fd);
2649 advise_to_edit_todo = res =
2650 parse_insn_buffer(todo_list.buf.buf, &todo_list);
2651
2652 if (res || check_level == CHECK_IGNORE)
2653 goto leave_check;
2654
2655 /* Mark the commits in git-rebase-todo as seen */
2656 for (i = 0; i < todo_list.nr; i++) {
2657 struct commit *commit = todo_list.items[i].commit;
2658 if (commit)
2659 commit->util = (void *)1;
2660 }
2661
2662 todo_list_release(&todo_list);
2663 strbuf_addstr(&todo_file, ".backup");
2664 fd = open(todo_file.buf, O_RDONLY);
2665 if (fd < 0) {
2666 res = error_errno(_("could not open '%s'"), todo_file.buf);
2667 goto leave_check;
2668 }
2669 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2670 close(fd);
2671 res = error(_("could not read '%s'."), todo_file.buf);
2672 goto leave_check;
2673 }
2674 close(fd);
2675 strbuf_release(&todo_file);
2676 res = !!parse_insn_buffer(todo_list.buf.buf, &todo_list);
2677
2678 /* Find commits in git-rebase-todo.backup yet unseen */
2679 for (i = todo_list.nr - 1; i >= 0; i--) {
2680 struct todo_item *item = todo_list.items + i;
2681 struct commit *commit = item->commit;
2682 if (commit && !commit->util) {
2683 strbuf_addf(&missing, " - %s %.*s\n",
2684 short_commit_name(commit),
2685 item->arg_len, item->arg);
2686 commit->util = (void *)1;
2687 }
2688 }
2689
2690 /* Warn about missing commits */
2691 if (!missing.len)
2692 goto leave_check;
2693
2694 if (check_level == CHECK_ERROR)
2695 advise_to_edit_todo = res = 1;
2696
2697 fprintf(stderr,
2698 _("Warning: some commits may have been dropped accidentally.\n"
2699 "Dropped commits (newer to older):\n"));
2700
2701 /* Make the list user-friendly and display */
2702 fputs(missing.buf, stderr);
2703 strbuf_release(&missing);
2704
2705 fprintf(stderr, _("To avoid this message, use \"drop\" to "
2706 "explicitly remove a commit.\n\n"
2707 "Use 'git config rebase.missingCommitsCheck' to change "
2708 "the level of warnings.\n"
2709 "The possible behaviours are: ignore, warn, error.\n\n"));
2710
2711leave_check:
2712 strbuf_release(&todo_file);
2713 todo_list_release(&todo_list);
2714
2715 if (advise_to_edit_todo)
2716 fprintf(stderr,
2717 _("You can fix this with 'git rebase --edit-todo' "
2718 "and then run 'git rebase --continue'.\n"
2719 "Or you can abort the rebase with 'git rebase"
2720 " --abort'.\n"));
2721
2722 return res;
2723}
2724
2725static int rewrite_file(const char *path, const char *buf, size_t len)
2726{
2727 int rc = 0;
2728 int fd = open(path, O_WRONLY | O_TRUNC);
2729 if (fd < 0)
2730 return error_errno(_("could not open '%s' for writing"), path);
2731 if (write_in_full(fd, buf, len) < 0)
2732 rc = error_errno(_("could not write to '%s'"), path);
2733 if (close(fd) && !rc)
2734 rc = error_errno(_("could not close '%s'"), path);
2735 return rc;
2736}
2737
2738/* skip picking commits whose parents are unchanged */
2739int skip_unnecessary_picks(void)
2740{
2741 const char *todo_file = rebase_path_todo();
2742 struct strbuf buf = STRBUF_INIT;
2743 struct todo_list todo_list = TODO_LIST_INIT;
2744 struct object_id onto_oid, *oid = &onto_oid, *parent_oid;
2745 int fd, i;
2746
2747 if (!read_oneliner(&buf, rebase_path_onto(), 0))
2748 return error(_("could not read 'onto'"));
2749 if (get_oid(buf.buf, &onto_oid)) {
2750 strbuf_release(&buf);
2751 return error(_("need a HEAD to fixup"));
2752 }
2753 strbuf_release(&buf);
2754
2755 fd = open(todo_file, O_RDONLY);
2756 if (fd < 0) {
2757 return error_errno(_("could not open '%s'"), todo_file);
2758 }
2759 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2760 close(fd);
2761 return error(_("could not read '%s'."), todo_file);
2762 }
2763 close(fd);
2764 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2765 todo_list_release(&todo_list);
2766 return -1;
2767 }
2768
2769 for (i = 0; i < todo_list.nr; i++) {
2770 struct todo_item *item = todo_list.items + i;
2771
2772 if (item->command >= TODO_NOOP)
2773 continue;
2774 if (item->command != TODO_PICK)
2775 break;
2776 if (parse_commit(item->commit)) {
2777 todo_list_release(&todo_list);
2778 return error(_("could not parse commit '%s'"),
2779 oid_to_hex(&item->commit->object.oid));
2780 }
2781 if (!item->commit->parents)
2782 break; /* root commit */
2783 if (item->commit->parents->next)
2784 break; /* merge commit */
2785 parent_oid = &item->commit->parents->item->object.oid;
2786 if (hashcmp(parent_oid->hash, oid->hash))
2787 break;
2788 oid = &item->commit->object.oid;
2789 }
2790 if (i > 0) {
2791 int offset = i < todo_list.nr ?
2792 todo_list.items[i].offset_in_buf : todo_list.buf.len;
2793 const char *done_path = rebase_path_done();
2794
2795 fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
2796 if (fd < 0) {
2797 error_errno(_("could not open '%s' for writing"),
2798 done_path);
2799 todo_list_release(&todo_list);
2800 return -1;
2801 }
2802 if (write_in_full(fd, todo_list.buf.buf, offset) < 0) {
2803 error_errno(_("could not write to '%s'"), done_path);
2804 todo_list_release(&todo_list);
2805 close(fd);
2806 return -1;
2807 }
2808 close(fd);
2809
2810 if (rewrite_file(rebase_path_todo(), todo_list.buf.buf + offset,
2811 todo_list.buf.len - offset) < 0) {
2812 todo_list_release(&todo_list);
2813 return -1;
2814 }
2815
2816 todo_list.current = i;
2817 if (is_fixup(peek_command(&todo_list, 0)))
2818 record_in_rewritten(oid, peek_command(&todo_list, 0));
2819 }
2820
2821 todo_list_release(&todo_list);
2822 printf("%s\n", oid_to_hex(oid));
2823
2824 return 0;
2825}
2826
2827struct subject2item_entry {
2828 struct hashmap_entry entry;
2829 int i;
2830 char subject[FLEX_ARRAY];
2831};
2832
2833static int subject2item_cmp(const void *fndata,
2834 const struct subject2item_entry *a,
2835 const struct subject2item_entry *b, const void *key)
2836{
2837 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
2838}
2839
2840/*
2841 * Rearrange the todo list that has both "pick commit-id msg" and "pick
2842 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
2843 * after the former, and change "pick" to "fixup"/"squash".
2844 *
2845 * Note that if the config has specified a custom instruction format, each log
2846 * message will have to be retrieved from the commit (as the oneline in the
2847 * script cannot be trusted) in order to normalize the autosquash arrangement.
2848 */
2849int rearrange_squash(void)
2850{
2851 const char *todo_file = rebase_path_todo();
2852 struct todo_list todo_list = TODO_LIST_INIT;
2853 struct hashmap subject2item;
2854 int res = 0, rearranged = 0, *next, *tail, fd, i;
2855 char **subjects;
2856
2857 fd = open(todo_file, O_RDONLY);
2858 if (fd < 0)
2859 return error_errno(_("could not open '%s'"), todo_file);
2860 if (strbuf_read(&todo_list.buf, fd, 0) < 0) {
2861 close(fd);
2862 return error(_("could not read '%s'."), todo_file);
2863 }
2864 close(fd);
2865 if (parse_insn_buffer(todo_list.buf.buf, &todo_list) < 0) {
2866 todo_list_release(&todo_list);
2867 return -1;
2868 }
2869
2870 /*
2871 * The hashmap maps onelines to the respective todo list index.
2872 *
2873 * If any items need to be rearranged, the next[i] value will indicate
2874 * which item was moved directly after the i'th.
2875 *
2876 * In that case, last[i] will indicate the index of the latest item to
2877 * be moved to appear after the i'th.
2878 */
2879 hashmap_init(&subject2item, (hashmap_cmp_fn) subject2item_cmp,
2880 NULL, todo_list.nr);
2881 ALLOC_ARRAY(next, todo_list.nr);
2882 ALLOC_ARRAY(tail, todo_list.nr);
2883 ALLOC_ARRAY(subjects, todo_list.nr);
2884 for (i = 0; i < todo_list.nr; i++) {
2885 struct strbuf buf = STRBUF_INIT;
2886 struct todo_item *item = todo_list.items + i;
2887 const char *commit_buffer, *subject, *p;
2888 size_t subject_len;
2889 int i2 = -1;
2890 struct subject2item_entry *entry;
2891
2892 next[i] = tail[i] = -1;
2893 if (item->command >= TODO_EXEC) {
2894 subjects[i] = NULL;
2895 continue;
2896 }
2897
2898 if (is_fixup(item->command)) {
2899 todo_list_release(&todo_list);
2900 return error(_("the script was already rearranged."));
2901 }
2902
2903 item->commit->util = item;
2904
2905 parse_commit(item->commit);
2906 commit_buffer = get_commit_buffer(item->commit, NULL);
2907 find_commit_subject(commit_buffer, &subject);
2908 format_subject(&buf, subject, " ");
2909 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
2910 unuse_commit_buffer(item->commit, commit_buffer);
2911 if ((skip_prefix(subject, "fixup! ", &p) ||
2912 skip_prefix(subject, "squash! ", &p))) {
2913 struct commit *commit2;
2914
2915 for (;;) {
2916 while (isspace(*p))
2917 p++;
2918 if (!skip_prefix(p, "fixup! ", &p) &&
2919 !skip_prefix(p, "squash! ", &p))
2920 break;
2921 }
2922
2923 if ((entry = hashmap_get_from_hash(&subject2item,
2924 strhash(p), p)))
2925 /* found by title */
2926 i2 = entry->i;
2927 else if (!strchr(p, ' ') &&
2928 (commit2 =
2929 lookup_commit_reference_by_name(p)) &&
2930 commit2->util)
2931 /* found by commit name */
2932 i2 = (struct todo_item *)commit2->util
2933 - todo_list.items;
2934 else {
2935 /* copy can be a prefix of the commit subject */
2936 for (i2 = 0; i2 < i; i2++)
2937 if (subjects[i2] &&
2938 starts_with(subjects[i2], p))
2939 break;
2940 if (i2 == i)
2941 i2 = -1;
2942 }
2943 }
2944 if (i2 >= 0) {
2945 rearranged = 1;
2946 todo_list.items[i].command =
2947 starts_with(subject, "fixup!") ?
2948 TODO_FIXUP : TODO_SQUASH;
2949 if (next[i2] < 0)
2950 next[i2] = i;
2951 else
2952 next[tail[i2]] = i;
2953 tail[i2] = i;
2954 } else if (!hashmap_get_from_hash(&subject2item,
2955 strhash(subject), subject)) {
2956 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
2957 entry->i = i;
2958 hashmap_entry_init(entry, strhash(entry->subject));
2959 hashmap_put(&subject2item, entry);
2960 }
2961 }
2962
2963 if (rearranged) {
2964 struct strbuf buf = STRBUF_INIT;
2965
2966 for (i = 0; i < todo_list.nr; i++) {
2967 enum todo_command command = todo_list.items[i].command;
2968 int cur = i;
2969
2970 /*
2971 * Initially, all commands are 'pick's. If it is a
2972 * fixup or a squash now, we have rearranged it.
2973 */
2974 if (is_fixup(command))
2975 continue;
2976
2977 while (cur >= 0) {
2978 int offset = todo_list.items[cur].offset_in_buf;
2979 int end_offset = cur + 1 < todo_list.nr ?
2980 todo_list.items[cur + 1].offset_in_buf :
2981 todo_list.buf.len;
2982 char *bol = todo_list.buf.buf + offset;
2983 char *eol = todo_list.buf.buf + end_offset;
2984
2985 /* replace 'pick', by 'fixup' or 'squash' */
2986 command = todo_list.items[cur].command;
2987 if (is_fixup(command)) {
2988 strbuf_addstr(&buf,
2989 todo_command_info[command].str);
2990 bol += strcspn(bol, " \t");
2991 }
2992
2993 strbuf_add(&buf, bol, eol - bol);
2994
2995 cur = next[cur];
2996 }
2997 }
2998
2999 res = rewrite_file(todo_file, buf.buf, buf.len);
3000 strbuf_release(&buf);
3001 }
3002
3003 free(next);
3004 free(tail);
3005 for (i = 0; i < todo_list.nr; i++)
3006 free(subjects[i]);
3007 free(subjects);
3008 hashmap_free(&subject2item, 1);
3009 todo_list_release(&todo_list);
3010
3011 return res;
3012}