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