interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / sequencer.c

7094 lines · 200787 bytes Raw Blame History
1#define USE_THE_REPOSITORY_VARIABLE
2#define DISABLE_SIGN_COMPARE_WARNINGS
3
4#include "git-compat-util.h"
5#include "abspath.h"
6#include "advice.h"
7#include "config.h"
8#include "copy.h"
9#include "environment.h"
10#include "gettext.h"
11#include "hex.h"
12#include "lockfile.h"
13#include "dir.h"
14#include "object-file.h"
15#include "object-name.h"
16#include "odb.h"
17#include "object.h"
18#include "pager.h"
19#include "commit.h"
20#include "sequencer.h"
21#include "run-command.h"
22#include "stash.h"
23#include "hook.h"
24#include "utf8.h"
25#include "cache-tree.h"
26#include "diff.h"
27#include "path.h"
28#include "revision.h"
29#include "rerere.h"
30#include "merge.h"
31#include "merge-ort.h"
32#include "merge-ort-wrappers.h"
33#include "refs.h"
34#include "sparse-index.h"
35#include "strvec.h"
36#include "quote.h"
37#include "trailer.h"
38#include "log-tree.h"
39#include "wt-status.h"
40#include "hashmap.h"
41#include "notes-utils.h"
42#include "sigchain.h"
43#include "unpack-trees.h"
44#include "oidmap.h"
45#include "oidset.h"
46#include "commit-slab.h"
47#include "alias.h"
48#include "commit-reach.h"
49#include "rebase-interactive.h"
50#include "reset.h"
51#include "branch.h"
52
53#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
54
55/*
56 * To accommodate common filesystem limitations, where the loose refs' file
57 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
58 * --rebase-merges` need to be truncated if the corresponding commit subjects
59 * are too long.
60 * Add some margin to stay clear from reaching `NAME_MAX`.
61 */
62#define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
63
64static const char sign_off_header[] = "Signed-off-by: ";
65static const char cherry_picked_prefix[] = "(cherry picked from commit ";
66
67GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
68
69static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
70
71static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
72static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
73static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
74static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
75
76static GIT_PATH_FUNC(rebase_path, "rebase-merge")
77/*
78 * The file containing rebase commands, comments, and empty lines.
79 * This file is created by "git rebase -i" then edited by the user. As
80 * the lines are processed, they are removed from the front of this
81 * file and written to the tail of 'done'.
82 */
83GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
84GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
85
86GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
87
88/*
89 * The rebase command lines that have already been processed. A line
90 * is moved here when it is first handled, before any associated user
91 * actions.
92 */
93static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
94/*
95 * The file to keep track of how many commands were already processed (e.g.
96 * for the prompt).
97 */
98static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
99/*
100 * The file to keep track of how many commands are to be processed in total
101 * (e.g. for the prompt).
102 */
103static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
104/*
105 * The commit message that is planned to be used for any changes that
106 * need to be committed following a user interaction.
107 */
108static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
109/*
110 * The file into which is accumulated the suggested commit message for
111 * squash/fixup commands. When the first of a series of squash/fixups
112 * is seen, the file is created and the commit message from the
113 * previous commit and from the first squash/fixup commit are written
114 * to it. The commit message for each subsequent squash/fixup commit
115 * is appended to the file as it is processed.
116 */
117static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
118/*
119 * If the current series of squash/fixups has not yet included a squash
120 * command, then this file exists and holds the commit message of the
121 * original "pick" commit. (If the series ends without a "squash"
122 * command, then this can be used as the commit message of the combined
123 * commit without opening the editor.)
124 */
125static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
126/*
127 * This file contains the list fixup/squash commands that have been
128 * accumulated into message-fixup or message-squash so far.
129 */
130static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
131/*
132 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
133 * GIT_AUTHOR_DATE that will be used for the commit that is currently
134 * being rebased.
135 */
136static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
137/*
138 * When an "edit" rebase command is being processed, the SHA1 of the
139 * commit to be edited is recorded in this file. When "git rebase
140 * --continue" is executed, if there are any staged changes then they
141 * will be amended to the HEAD commit, but only provided the HEAD
142 * commit is still the commit to be edited. When any other rebase
143 * command is processed, this file is deleted.
144 */
145static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
146/*
147 * When we stop at a given patch via the "edit" command, this file contains
148 * the commit object name of the corresponding patch.
149 */
150static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
151/*
152 * When we stop for the user to resolve conflicts this file contains
153 * the patch of the commit that is being picked.
154 */
155static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
156/*
157 * For the post-rewrite hook, we make a list of rewritten commits and
158 * their new sha1s. The rewritten-pending list keeps the sha1s of
159 * commits that have been processed, but not committed yet,
160 * e.g. because they are waiting for a 'squash' command.
161 */
162static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
163static GIT_PATH_FUNC(rebase_path_rewritten_pending,
164 "rebase-merge/rewritten-pending")
165
166/*
167 * The path of the file containing the OID of the "squash onto" commit, i.e.
168 * the dummy commit used for `reset [new root]`.
169 */
170static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
171
172/*
173 * The path of the file listing refs that need to be deleted after the rebase
174 * finishes. This is used by the `label` command to record the need for cleanup.
175 */
176static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
177
178/*
179 * The update-refs file stores a list of refs that will be updated at the end
180 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
181 * update the OIDs for the refs in this file, but the refs are not updated
182 * until the end of the rebase sequence.
183 *
184 * rebase_path_update_refs() returns the path to this file for a given
185 * worktree directory. For the current worktree, pass the_repository->gitdir.
186 */
187static char *rebase_path_update_refs(const char *wt_git_dir)
188{
189 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
190}
191
192/*
193 * The following files are written by git-rebase just after parsing the
194 * command-line.
195 */
196static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
197static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
198static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
199static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
200static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
201static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
202static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
203static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
204static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
205static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
206static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
207static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
208static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
209static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
210static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
211static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
212static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
213static GIT_PATH_FUNC(rebase_path_trailer, "rebase-merge/trailer")
214
215/*
216 * A 'struct replay_ctx' represents the private state of the sequencer.
217 */
218struct replay_ctx {
219 /*
220 * The commit message that will be used except at the end of a
221 * chain of fixup and squash commands.
222 */
223 struct strbuf message;
224 /*
225 * The list of completed fixup and squash commands in the
226 * current chain.
227 */
228 struct strbuf current_fixups;
229 /*
230 * The number of completed fixup and squash commands in the
231 * current chain.
232 */
233 int current_fixup_count;
234 /*
235 * Whether message contains a commit message.
236 */
237 unsigned have_message :1;
238 /*
239 * GIT_CONFIG_PARAMETERS for the commands we spawn, with auto
240 * maintenance turned off. Built on first use.
241 */
242 char *config_parameters;
243};
244
245struct replay_ctx* replay_ctx_new(void)
246{
247 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
248
249 strbuf_init(&ctx->current_fixups, 0);
250 strbuf_init(&ctx->message, 0);
251
252 return ctx;
253}
254
255/**
256 * A 'struct update_refs_record' represents a value in the update-refs
257 * list. We use a string_list to map refs to these (before, after) pairs.
258 */
259struct update_ref_record {
260 struct object_id before;
261 struct object_id after;
262};
263
264static struct update_ref_record *init_update_ref_record(const char *ref)
265{
266 struct update_ref_record *rec;
267
268 CALLOC_ARRAY(rec, 1);
269
270 oidcpy(&rec->before, null_oid(the_hash_algo));
271 oidcpy(&rec->after, null_oid(the_hash_algo));
272
273 /* This may fail, but that's fine, we will keep the null OID. */
274 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
275
276 return rec;
277}
278
279static int git_sequencer_config(const char *k, const char *v,
280 const struct config_context *ctx, void *cb)
281{
282 struct replay_opts *opts = cb;
283
284 if (!strcmp(k, "commit.cleanup")) {
285 if (!v)
286 return config_error_nonbool(k);
287
288 if (!strcmp(v, "verbatim")) {
289 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
290 opts->explicit_cleanup = 1;
291 } else if (!strcmp(v, "whitespace")) {
292 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
293 opts->explicit_cleanup = 1;
294 } else if (!strcmp(v, "strip")) {
295 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
296 opts->explicit_cleanup = 1;
297 } else if (!strcmp(v, "scissors")) {
298 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
299 opts->explicit_cleanup = 1;
300 } else {
301 warning(_("invalid commit message cleanup mode '%s'"),
302 v);
303 }
304
305 return 0;
306 }
307
308 if (!strcmp(k, "commit.gpgsign")) {
309 free(opts->gpg_sign);
310 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
311 return 0;
312 }
313
314 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
315 int ret = git_config_string(&opts->default_strategy, k, v);
316 if (ret == 0) {
317 /*
318 * pull.twohead is allowed to be multi-valued; we only
319 * care about the first value.
320 */
321 char *tmp = strchr(opts->default_strategy, ' ');
322 if (tmp)
323 *tmp = '\0';
324 }
325 return ret;
326 }
327
328 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
329 opts->commit_use_reference = git_config_bool(k, v);
330
331 return git_diff_basic_config(k, v, ctx, NULL);
332}
333
334void sequencer_init_config(struct replay_opts *opts)
335{
336 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
337 repo_config(the_repository, git_sequencer_config, opts);
338}
339
340static inline int is_rebase_i(const struct replay_opts *opts)
341{
342 return opts->action == REPLAY_INTERACTIVE_REBASE;
343}
344
345static const char *get_dir(const struct replay_opts *opts)
346{
347 if (is_rebase_i(opts))
348 return rebase_path();
349 return git_path_seq_dir();
350}
351
352static const char *get_todo_path(const struct replay_opts *opts)
353{
354 if (is_rebase_i(opts))
355 return rebase_path_todo();
356 return git_path_todo_file();
357}
358
359/*
360 * Returns 0 for non-conforming footer
361 * Returns 1 for conforming footer
362 * Returns 2 when sob exists within conforming footer
363 * Returns 3 when sob exists within conforming footer as last entry
364 */
365static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
366 size_t ignore_footer)
367{
368 struct trailer_iterator iter;
369 size_t i = 0;
370 int found_sob = 0, found_sob_last = 0;
371 char saved_char;
372
373 if (ignore_footer) {
374 saved_char = sb->buf[sb->len - ignore_footer];
375 sb->buf[sb->len - ignore_footer] = '\0';
376 }
377
378 trailer_iterator_init(&iter, sb->buf);
379
380 if (ignore_footer)
381 sb->buf[sb->len - ignore_footer] = saved_char;
382
383 while (trailer_iterator_advance(&iter)) {
384 i++;
385 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
386 found_sob = i;
387 }
388 trailer_iterator_release(&iter);
389
390 if (!i)
391 return 0;
392
393 found_sob_last = (int)i == found_sob;
394
395 if (found_sob_last)
396 return 3;
397 if (found_sob)
398 return 2;
399 return 1;
400}
401
402static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
403{
404 static struct strbuf buf = STRBUF_INIT;
405
406 strbuf_reset(&buf);
407 if (opts->gpg_sign)
408 sq_quotef(&buf, "-S%s", opts->gpg_sign);
409 return buf.buf;
410}
411
412static void replay_ctx_release(struct replay_ctx *ctx)
413{
414 strbuf_release(&ctx->current_fixups);
415 strbuf_release(&ctx->message);
416 free(ctx->config_parameters);
417}
418
419void replay_opts_release(struct replay_opts *opts)
420{
421 struct replay_ctx *ctx = opts->ctx;
422
423 free(opts->gpg_sign);
424 free(opts->reflog_action);
425 free(opts->default_strategy);
426 free(opts->strategy);
427 strvec_clear (&opts->xopts);
428 if (opts->revs)
429 release_revisions(opts->revs);
430 free(opts->revs);
431 strvec_clear(&opts->trailer_args);
432 replay_ctx_release(ctx);
433 free(opts->ctx);
434}
435
436int sequencer_remove_state(struct replay_opts *opts)
437{
438 struct strbuf buf = STRBUF_INIT;
439 int ret = 0;
440
441 if (is_rebase_i(opts) &&
442 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
443 char *p = buf.buf;
444 while (*p) {
445 char *eol = strchr(p, '\n');
446 if (eol)
447 *eol = '\0';
448 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
449 warning(_("could not delete '%s'"), p);
450 ret = -1;
451 }
452 if (!eol)
453 break;
454 p = eol + 1;
455 }
456 }
457
458 strbuf_reset(&buf);
459 strbuf_addstr(&buf, get_dir(opts));
460 if (remove_dir_recursively(&buf, 0))
461 ret = error(_("could not remove '%s'"), buf.buf);
462 strbuf_release(&buf);
463
464 return ret;
465}
466
467static const char *action_name(const struct replay_opts *opts)
468{
469 switch (opts->action) {
470 case REPLAY_REVERT:
471 return N_("revert");
472 case REPLAY_PICK:
473 return N_("cherry-pick");
474 case REPLAY_INTERACTIVE_REBASE:
475 return N_("rebase");
476 }
477 die(_("unknown action: %d"), opts->action);
478}
479
480struct commit_message {
481 char *parent_label;
482 char *label;
483 char *subject;
484 const char *message;
485};
486
487static const char *short_commit_name(struct repository *r, struct commit *commit)
488{
489 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
490}
491
492static int get_message(struct commit *commit, struct commit_message *out)
493{
494 const char *abbrev, *subject;
495 int subject_len;
496
497 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
498 get_commit_output_encoding());
499 abbrev = short_commit_name(the_repository, commit);
500
501 subject_len = find_commit_subject(out->message, &subject);
502
503 out->subject = xmemdupz(subject, subject_len);
504 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
505 out->parent_label = xstrfmt("parent of %s", out->label);
506
507 return 0;
508}
509
510static void free_message(struct commit *commit, struct commit_message *msg)
511{
512 free(msg->parent_label);
513 free(msg->label);
514 free(msg->subject);
515 repo_unuse_commit_buffer(the_repository, commit, msg->message);
516}
517
518const char *rebase_resolvemsg =
519N_("Resolve all conflicts manually, mark them as resolved with\n"
520"\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
521"You can instead skip this commit: run \"git rebase --skip\".\n"
522"To abort and get back to the state before \"git rebase\", run "
523"\"git rebase --abort\".");
524
525static void print_advice(struct repository *r, int show_hint,
526 struct replay_opts *opts)
527{
528 const char *msg;
529
530 if (is_rebase_i(opts))
531 msg = rebase_resolvemsg;
532 else
533 msg = getenv("GIT_CHERRY_PICK_HELP");
534
535 if (msg) {
536 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
537 /*
538 * A conflict has occurred but the porcelain
539 * (typically rebase --interactive) wants to take care
540 * of the commit itself so remove CHERRY_PICK_HEAD
541 */
542 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
543 NULL, REF_NO_DEREF);
544 return;
545 }
546
547 if (show_hint) {
548 if (opts->no_commit)
549 advise_if_enabled(ADVICE_MERGE_CONFLICT,
550 _("after resolving the conflicts, mark the corrected paths\n"
551 "with 'git add <paths>' or 'git rm <paths>'"));
552 else if (opts->action == REPLAY_PICK)
553 advise_if_enabled(ADVICE_MERGE_CONFLICT,
554 _("After resolving the conflicts, mark them with\n"
555 "\"git add/rm <pathspec>\", then run\n"
556 "\"git cherry-pick --continue\".\n"
557 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
558 "To abort and get back to the state before \"git cherry-pick\",\n"
559 "run \"git cherry-pick --abort\"."));
560 else if (opts->action == REPLAY_REVERT)
561 advise_if_enabled(ADVICE_MERGE_CONFLICT,
562 _("After resolving the conflicts, mark them with\n"
563 "\"git add/rm <pathspec>\", then run\n"
564 "\"git revert --continue\".\n"
565 "You can instead skip this commit with \"git revert --skip\".\n"
566 "To abort and get back to the state before \"git revert\",\n"
567 "run \"git revert --abort\"."));
568 else
569 BUG("unexpected pick action in print_advice()");
570 }
571}
572
573static int write_message(const void *buf, size_t len, const char *filename,
574 int append_eol)
575{
576 struct lock_file msg_file = LOCK_INIT;
577
578 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
579 if (msg_fd < 0)
580 return error_errno(_("could not lock '%s'"), filename);
581 if (write_in_full(msg_fd, buf, len) < 0) {
582 error_errno(_("could not write to '%s'"), filename);
583 rollback_lock_file(&msg_file);
584 return -1;
585 }
586 if (append_eol && write(msg_fd, "\n", 1) < 0) {
587 error_errno(_("could not write eol to '%s'"), filename);
588 rollback_lock_file(&msg_file);
589 return -1;
590 }
591 if (commit_lock_file(&msg_file) < 0)
592 return error(_("failed to finalize '%s'"), filename);
593
594 return 0;
595}
596
597int read_oneliner(struct strbuf *buf,
598 const char *path, unsigned flags)
599{
600 int orig_len = buf->len;
601
602 if (strbuf_read_file(buf, path, 0) < 0) {
603 if ((flags & READ_ONELINER_WARN_MISSING) ||
604 (errno != ENOENT && errno != ENOTDIR))
605 warning_errno(_("could not read '%s'"), path);
606 return 0;
607 }
608
609 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
610 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
611 --buf->len;
612 buf->buf[buf->len] = '\0';
613 }
614
615 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
616 return 0;
617
618 return 1;
619}
620
621static struct tree *empty_tree(struct repository *r)
622{
623 return lookup_tree(r, the_hash_algo->empty_tree);
624}
625
626static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
627{
628 if (repo_read_index_unmerged(repo))
629 return error_resolve_conflict(action_name(opts));
630
631 error(_("your local changes would be overwritten by %s."),
632 _(action_name(opts)));
633
634 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
635 advise(_("commit your changes or stash them to proceed."));
636 return -1;
637}
638
639static void update_abort_safety_file(void)
640{
641 struct object_id head;
642
643 /* Do nothing on a single-pick */
644 if (!file_exists(git_path_seq_dir()))
645 return;
646
647 if (!repo_get_oid(the_repository, "HEAD", &head))
648 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
649 else
650 write_file(git_path_abort_safety_file(), "%s", "");
651}
652
653static int fast_forward_to(struct repository *r,
654 const struct object_id *to,
655 const struct object_id *from,
656 int unborn,
657 struct replay_opts *opts)
658{
659 struct ref_transaction *transaction;
660 struct strbuf sb = STRBUF_INIT;
661 struct strbuf err = STRBUF_INIT;
662
663 repo_read_index(r);
664 if (checkout_fast_forward(r, from, to, 1))
665 return -1; /* the callee should have complained already */
666
667 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
668
669 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
670 0, &err);
671 if (!transaction ||
672 ref_transaction_update(transaction, "HEAD",
673 to, unborn && !is_rebase_i(opts) ?
674 null_oid(the_hash_algo) : from, NULL, NULL,
675 0, sb.buf, &err) ||
676 ref_transaction_commit(transaction, &err)) {
677 ref_transaction_free(transaction);
678 error("%s", err.buf);
679 strbuf_release(&sb);
680 strbuf_release(&err);
681 return -1;
682 }
683
684 strbuf_release(&sb);
685 strbuf_release(&err);
686 ref_transaction_free(transaction);
687 update_abort_safety_file();
688 return 0;
689}
690
691enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
692 int use_editor)
693{
694 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
695 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
696 COMMIT_MSG_CLEANUP_SPACE;
697 else if (!strcmp(cleanup_arg, "verbatim"))
698 return COMMIT_MSG_CLEANUP_NONE;
699 else if (!strcmp(cleanup_arg, "whitespace"))
700 return COMMIT_MSG_CLEANUP_SPACE;
701 else if (!strcmp(cleanup_arg, "strip"))
702 return COMMIT_MSG_CLEANUP_ALL;
703 else if (!strcmp(cleanup_arg, "scissors"))
704 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
705 COMMIT_MSG_CLEANUP_SPACE;
706 else
707 die(_("Invalid cleanup mode %s"), cleanup_arg);
708}
709
710/*
711 * NB using int rather than enum cleanup_mode to stop clang's
712 * -Wtautological-constant-out-of-range-compare complaining that the comparison
713 * is always true.
714 */
715static const char *describe_cleanup_mode(int cleanup_mode)
716{
717 static const char *modes[] = { "whitespace",
718 "verbatim",
719 "scissors",
720 "strip" };
721
722 if (cleanup_mode < ARRAY_SIZE(modes))
723 return modes[cleanup_mode];
724
725 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
726}
727
728void append_conflicts_hint(struct index_state *istate,
729 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
730{
731 int i;
732
733 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
734 strbuf_addch(msgbuf, '\n');
735 wt_status_append_cut_line(msgbuf);
736 strbuf_addstr(msgbuf, comment_line_str);
737 }
738
739 strbuf_addch(msgbuf, '\n');
740 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
741 for (i = 0; i < istate->cache_nr;) {
742 const struct cache_entry *ce = istate->cache[i++];
743 if (ce_stage(ce)) {
744 strbuf_commented_addf(msgbuf, comment_line_str,
745 "\t%s\n", ce->name);
746 while (i < istate->cache_nr &&
747 !strcmp(ce->name, istate->cache[i]->name))
748 i++;
749 }
750 }
751}
752
753static int do_recursive_merge(struct repository *r,
754 struct commit *base, struct commit *next,
755 const char *base_label, const char *next_label,
756 struct object_id *head, struct strbuf *msgbuf,
757 struct replay_opts *opts)
758{
759 struct merge_options o;
760 struct merge_result result;
761 struct tree *next_tree, *base_tree, *head_tree;
762 int clean, show_output;
763 int i;
764 struct lock_file index_lock = LOCK_INIT;
765
766 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
767 return -1;
768
769 repo_read_index(r);
770
771 init_ui_merge_options(&o, r);
772 o.ancestor = base ? base_label : "(empty tree)";
773 o.branch1 = "HEAD";
774 o.branch2 = next ? next_label : "(empty tree)";
775 if (is_rebase_i(opts))
776 o.buffer_output = 2;
777 o.show_rename_progress = 1;
778
779 head_tree = repo_parse_tree_indirect(the_repository, head);
780 if (!head_tree)
781 return error(_("unable to read tree (%s)"), oid_to_hex(head));
782 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
783 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
784
785 for (i = 0; i < opts->xopts.nr; i++)
786 parse_merge_opt(&o, opts->xopts.v[i]);
787
788 memset(&result, 0, sizeof(result));
789 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree, &result);
790 show_output = !is_rebase_i(opts) || !result.clean;
791 /*
792 * TODO: merge_switch_to_result will update index/working tree;
793 * we only really want to do that if !result.clean || this is
794 * the final patch to be picked. But determining this is the
795 * final patch would take some work, and "head_tree" would need
796 * to be replace with the tree the index matched before we
797 * started doing any picks.
798 */
799 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
800 clean = result.clean;
801 if (clean < 0) {
802 rollback_lock_file(&index_lock);
803 return clean;
804 }
805
806 if (write_locked_index(r->index, &index_lock,
807 COMMIT_LOCK | SKIP_IF_UNCHANGED))
808 /*
809 * TRANSLATORS: %s will be "revert", "cherry-pick" or
810 * "rebase".
811 */
812 return error(_("%s: Unable to write new index file"),
813 _(action_name(opts)));
814
815 if (!clean)
816 append_conflicts_hint(r->index, msgbuf,
817 opts->default_msg_cleanup);
818
819 return !clean;
820}
821
822static struct object_id *get_cache_tree_oid(struct index_state *istate)
823{
824 if (!cache_tree_fully_valid(istate))
825 if (cache_tree_update(istate, 0)) {
826 error(_("unable to update cache tree"));
827 return NULL;
828 }
829
830 return &istate->cache_tree->oid;
831}
832
833static int is_index_unchanged(struct repository *r)
834{
835 struct object_id head_oid, *cache_tree_oid;
836 const struct object_id *head_tree_oid;
837 struct commit *head_commit;
838 struct index_state *istate = r->index;
839 const char *head_name;
840
841 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
842 /* Check to see if this is an unborn branch */
843 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
844 "HEAD",
845 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
846 &head_oid, NULL);
847 if (!head_name ||
848 !starts_with(head_name, "refs/heads/") ||
849 !is_null_oid(&head_oid))
850 return error(_("could not resolve HEAD commit"));
851 head_tree_oid = the_hash_algo->empty_tree;
852 } else {
853 head_commit = lookup_commit(r, &head_oid);
854
855 /*
856 * If head_commit is NULL, check_commit, called from
857 * lookup_commit, would have indicated that head_commit is not
858 * a commit object already. repo_parse_commit() will return failure
859 * without further complaints in such a case. Otherwise, if
860 * the commit is invalid, repo_parse_commit() will complain. So
861 * there is nothing for us to say here. Just return failure.
862 */
863 if (repo_parse_commit(r, head_commit))
864 return -1;
865
866 head_tree_oid = get_commit_tree_oid(head_commit);
867 }
868
869 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
870 return -1;
871
872 return oideq(cache_tree_oid, head_tree_oid);
873}
874
875static int write_author_script(const char *message)
876{
877 struct strbuf buf = STRBUF_INIT;
878 const char *eol;
879 int res;
880
881 for (;;)
882 if (!*message || starts_with(message, "\n")) {
883missing_author:
884 /* Missing 'author' line? */
885 unlink(rebase_path_author_script());
886 return 0;
887 } else if (skip_prefix(message, "author ", &message))
888 break;
889 else if ((eol = strchr(message, '\n')))
890 message = eol + 1;
891 else
892 goto missing_author;
893
894 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
895 while (*message && *message != '\n' && *message != '\r')
896 if (skip_prefix(message, " <", &message))
897 break;
898 else if (*message != '\'')
899 strbuf_addch(&buf, *(message++));
900 else
901 strbuf_addf(&buf, "'\\%c'", *(message++));
902 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
903 while (*message && *message != '\n' && *message != '\r')
904 if (skip_prefix(message, "> ", &message))
905 break;
906 else if (*message != '\'')
907 strbuf_addch(&buf, *(message++));
908 else
909 strbuf_addf(&buf, "'\\%c'", *(message++));
910 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
911 while (*message && *message != '\n' && *message != '\r')
912 if (*message != '\'')
913 strbuf_addch(&buf, *(message++));
914 else
915 strbuf_addf(&buf, "'\\%c'", *(message++));
916 strbuf_addch(&buf, '\'');
917 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
918 strbuf_release(&buf);
919 return res;
920}
921
922/**
923 * Take a series of KEY='VALUE' lines where VALUE part is
924 * sq-quoted, and append <KEY, VALUE> at the end of the string list
925 */
926static int parse_key_value_squoted(char *buf, struct string_list *list)
927{
928 while (*buf) {
929 struct string_list_item *item;
930 char *np;
931 char *cp = strchr(buf, '=');
932 if (!cp) {
933 np = strchrnul(buf, '\n');
934 return error(_("no key present in '%.*s'"),
935 (int) (np - buf), buf);
936 }
937 np = strchrnul(cp, '\n');
938 *cp++ = '\0';
939 item = string_list_append(list, buf);
940
941 buf = np + (*np == '\n');
942 *np = '\0';
943 cp = sq_dequote(cp);
944 if (!cp)
945 return error(_("unable to dequote value of '%s'"),
946 item->string);
947 item->util = xstrdup(cp);
948 }
949 return 0;
950}
951
952/**
953 * Reads and parses the state directory's "author-script" file, and sets name,
954 * email and date accordingly.
955 * Returns 0 on success, -1 if the file could not be parsed.
956 *
957 * The author script is of the format:
958 *
959 * GIT_AUTHOR_NAME='$author_name'
960 * GIT_AUTHOR_EMAIL='$author_email'
961 * GIT_AUTHOR_DATE='$author_date'
962 *
963 * where $author_name, $author_email and $author_date are quoted. We are strict
964 * with our parsing, as the file was meant to be eval'd in the now-removed
965 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
966 * from what this function expects, it is better to bail out than to do
967 * something that the user does not expect.
968 */
969int read_author_script(const char *path, char **name, char **email, char **date,
970 int allow_missing)
971{
972 struct strbuf buf = STRBUF_INIT;
973 struct string_list kv = STRING_LIST_INIT_DUP;
974 int retval = -1; /* assume failure */
975 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
976
977 if (strbuf_read_file(&buf, path, 256) <= 0) {
978 strbuf_release(&buf);
979 if (errno == ENOENT && allow_missing)
980 return 0;
981 else
982 return error_errno(_("could not open '%s' for reading"),
983 path);
984 }
985
986 if (parse_key_value_squoted(buf.buf, &kv))
987 goto finish;
988
989 for (i = 0; i < kv.nr; i++) {
990 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
991 if (name_i != -2)
992 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
993 else
994 name_i = i;
995 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
996 if (email_i != -2)
997 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
998 else
999 email_i = i;
1000 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
1001 if (date_i != -2)
1002 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
1003 else
1004 date_i = i;
1005 } else {
1006 err = error(_("unknown variable '%s'"),
1007 kv.items[i].string);
1008 }
1009 }
1010 if (name_i == -2)
1011 error(_("missing 'GIT_AUTHOR_NAME'"));
1012 if (email_i == -2)
1013 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1014 if (date_i == -2)
1015 error(_("missing 'GIT_AUTHOR_DATE'"));
1016 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1017 goto finish;
1018 *name = kv.items[name_i].util;
1019 *email = kv.items[email_i].util;
1020 *date = kv.items[date_i].util;
1021 retval = 0;
1022finish:
1023 string_list_clear(&kv, !!retval);
1024 strbuf_release(&buf);
1025 return retval;
1026}
1027
1028/*
1029 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1030 * file with shell quoting into struct strvec. Returns -1 on
1031 * error, 0 otherwise.
1032 */
1033static int read_env_script(struct strvec *env)
1034{
1035 char *name, *email, *date;
1036
1037 if (read_author_script(rebase_path_author_script(),
1038 &name, &email, &date, 0))
1039 return -1;
1040
1041 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1042 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1043 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1044 free(name);
1045 free(email);
1046 free(date);
1047
1048 return 0;
1049}
1050
1051static char *get_author(const char *message)
1052{
1053 size_t len;
1054 const char *a;
1055
1056 a = find_commit_header(message, "author", &len);
1057 if (a)
1058 return xmemdupz(a, len);
1059
1060 return NULL;
1061}
1062
1063static const char *author_date_from_env(const struct strvec *env)
1064{
1065 int i;
1066 const char *date;
1067
1068 for (i = 0; i < env->nr; i++)
1069 if (skip_prefix(env->v[i],
1070 "GIT_AUTHOR_DATE=", &date))
1071 return date;
1072 /*
1073 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1074 * reading the script
1075 */
1076 BUG("GIT_AUTHOR_DATE missing from author script");
1077}
1078
1079static const char staged_changes_advice[] =
1080N_("you have staged changes in your working tree\n"
1081"If these changes are meant to be squashed into the previous commit, run:\n"
1082"\n"
1083" git commit --amend %s\n"
1084"\n"
1085"If they are meant to go into a new commit, run:\n"
1086"\n"
1087" git commit %s\n"
1088"\n"
1089"In both cases, once you're done, continue with:\n"
1090"\n"
1091" git rebase --continue\n");
1092
1093#define ALLOW_EMPTY (1<<0)
1094#define EDIT_MSG (1<<1)
1095#define AMEND_MSG (1<<2)
1096#define CLEANUP_MSG (1<<3)
1097#define VERIFY_MSG (1<<4)
1098#define CREATE_ROOT_COMMIT (1<<5)
1099
1100static int run_command_silent_on_success(struct child_process *cmd)
1101{
1102 struct strbuf buf = STRBUF_INIT;
1103 int rc;
1104
1105 cmd->stdout_to_stderr = 1;
1106 rc = pipe_command(cmd,
1107 NULL, 0,
1108 NULL, 0,
1109 &buf, 0);
1110
1111 if (rc)
1112 fputs(buf.buf, stderr);
1113 strbuf_release(&buf);
1114 return rc;
1115}
1116
1117/*
1118 * Don't let the commands we spawn run auto maintenance. It would race
1119 * us for MERGE_RR.lock or delete packs we still have open. Our caller
1120 * runs it once the sequence is done.
1121 */
1122static void disable_auto_maintenance(struct replay_opts *opts,
1123 struct child_process *cmd)
1124{
1125 if (!opts->ctx->config_parameters) {
1126 const char *old = getenv(CONFIG_DATA_ENVIRONMENT);
1127 struct strbuf buf = STRBUF_INIT;
1128
1129 if (old && *old)
1130 strbuf_addstr(&buf, old);
1131 git_config_append_parameter(&buf, "maintenance.auto", "false");
1132 opts->ctx->config_parameters = strbuf_detach(&buf, NULL);
1133 }
1134 strvec_pushf(&cmd->env, "%s=%s", CONFIG_DATA_ENVIRONMENT,
1135 opts->ctx->config_parameters);
1136}
1137
1138/*
1139 * If we are cherry-pick, and if the merge did not result in
1140 * hand-editing, we will hit this commit and inherit the original
1141 * author date and name.
1142 *
1143 * If we are revert, or if our cherry-pick results in a hand merge,
1144 * we had better say that the current user is responsible for that.
1145 *
1146 * An exception is when run_git_commit() is called during an
1147 * interactive rebase: in that case, we will want to retain the
1148 * author metadata.
1149 */
1150static int run_git_commit(const char *defmsg,
1151 const char *reflog_action,
1152 struct replay_opts *opts,
1153 unsigned int flags)
1154{
1155 struct child_process cmd = CHILD_PROCESS_INIT;
1156
1157 cmd.git_cmd = 1;
1158 cmd.odb_to_close = the_repository->objects;
1159
1160 if (is_rebase_i(opts) &&
1161 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1162 !(!defmsg && (flags & AMEND_MSG))) &&
1163 read_env_script(&cmd.env)) {
1164 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1165
1166 return error(_(staged_changes_advice),
1167 gpg_opt, gpg_opt);
1168 }
1169
1170 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", reflog_action);
1171
1172 if (opts->committer_date_is_author_date)
1173 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1174 opts->ignore_date ?
1175 "" :
1176 author_date_from_env(&cmd.env));
1177 if (opts->ignore_date)
1178 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1179 disable_auto_maintenance(opts, &cmd);
1180
1181 strvec_push(&cmd.args, "commit");
1182
1183 if (!(flags & VERIFY_MSG))
1184 strvec_push(&cmd.args, "-n");
1185 if ((flags & AMEND_MSG))
1186 strvec_push(&cmd.args, "--amend");
1187 if (opts->gpg_sign)
1188 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1189 else
1190 strvec_push(&cmd.args, "--no-gpg-sign");
1191 if (defmsg)
1192 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1193 else if (!(flags & EDIT_MSG))
1194 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1195 if ((flags & CLEANUP_MSG))
1196 strvec_push(&cmd.args, "--cleanup=strip");
1197 if ((flags & EDIT_MSG))
1198 strvec_push(&cmd.args, "-e");
1199 else if (!(flags & CLEANUP_MSG) &&
1200 !opts->signoff && !opts->record_origin &&
1201 !opts->explicit_cleanup)
1202 strvec_push(&cmd.args, "--cleanup=verbatim");
1203
1204 if ((flags & ALLOW_EMPTY))
1205 strvec_push(&cmd.args, "--allow-empty");
1206
1207 if (!(flags & EDIT_MSG))
1208 strvec_push(&cmd.args, "--allow-empty-message");
1209
1210 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1211 return run_command_silent_on_success(&cmd);
1212 else
1213 return run_command(&cmd);
1214}
1215
1216static int rest_is_empty(const struct strbuf *sb, int start)
1217{
1218 int i, eol;
1219 const char *nl;
1220
1221 /* Check if the rest is just whitespace and Signed-off-by's. */
1222 for (i = start; i < sb->len; i++) {
1223 nl = memchr(sb->buf + i, '\n', sb->len - i);
1224 if (nl)
1225 eol = nl - sb->buf;
1226 else
1227 eol = sb->len;
1228
1229 if (strlen(sign_off_header) <= eol - i &&
1230 starts_with(sb->buf + i, sign_off_header)) {
1231 i = eol;
1232 continue;
1233 }
1234 while (i < eol)
1235 if (!isspace(sb->buf[i++]))
1236 return 0;
1237 }
1238
1239 return 1;
1240}
1241
1242void cleanup_message(struct strbuf *msgbuf,
1243 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1244{
1245 if (verbose || /* Truncate the message just before the diff, if any. */
1246 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1247 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1248 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1249 strbuf_stripspace(msgbuf,
1250 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1251}
1252
1253/*
1254 * Find out if the message in the strbuf contains only whitespace and
1255 * Signed-off-by lines.
1256 */
1257int message_is_empty(const struct strbuf *sb,
1258 enum commit_msg_cleanup_mode cleanup_mode)
1259{
1260 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1261 return 0;
1262 return rest_is_empty(sb, 0);
1263}
1264
1265/*
1266 * See if the user edited the message in the editor or left what
1267 * was in the template intact
1268 */
1269int template_untouched(const struct strbuf *sb, const char *template_file,
1270 enum commit_msg_cleanup_mode cleanup_mode)
1271{
1272 struct strbuf tmpl = STRBUF_INIT;
1273 const char *start;
1274
1275 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1276 return 0;
1277
1278 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1279 return 0;
1280
1281 strbuf_stripspace(&tmpl,
1282 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1283 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1284 start = sb->buf;
1285 strbuf_release(&tmpl);
1286 return rest_is_empty(sb, start - sb->buf);
1287}
1288
1289int update_head_with_reflog(const struct commit *old_head,
1290 const struct object_id *new_head,
1291 const char *action, const struct strbuf *msg,
1292 struct strbuf *err)
1293{
1294 struct ref_transaction *transaction;
1295 struct strbuf sb = STRBUF_INIT;
1296 const char *nl;
1297 int ret = 0;
1298
1299 if (action) {
1300 strbuf_addstr(&sb, action);
1301 strbuf_addstr(&sb, ": ");
1302 }
1303
1304 nl = strchr(msg->buf, '\n');
1305 if (nl) {
1306 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1307 } else {
1308 strbuf_addbuf(&sb, msg);
1309 strbuf_addch(&sb, '\n');
1310 }
1311
1312 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1313 0, err);
1314 if (!transaction ||
1315 ref_transaction_update(transaction, "HEAD", new_head,
1316 old_head ? &old_head->object.oid : null_oid(the_hash_algo),
1317 NULL, NULL, 0, sb.buf, err) ||
1318 ref_transaction_commit(transaction, err)) {
1319 ret = -1;
1320 }
1321 ref_transaction_free(transaction);
1322 strbuf_release(&sb);
1323
1324 return ret;
1325}
1326
1327static int pipe_from_strbuf(int hook_stdin_fd, void *pp_cb, void *pp_task_cb UNUSED)
1328{
1329 struct hook_cb_data *hook_cb = pp_cb;
1330 struct strbuf *to_pipe = hook_cb->options->feed_pipe_ctx;
1331 int ret;
1332
1333 if (!to_pipe)
1334 BUG("pipe_from_strbuf called without feed_pipe_ctx");
1335
1336 ret = write_in_full(hook_stdin_fd, to_pipe->buf, to_pipe->len);
1337 if (ret < 0 && errno != EPIPE)
1338 return ret;
1339
1340 return 1; /* done writing */
1341}
1342
1343static int run_rewrite_hook(const struct object_id *oldoid,
1344 const struct object_id *newoid)
1345{
1346 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1347 int code;
1348 struct strbuf sb = STRBUF_INIT;
1349
1350 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1351
1352 opt.feed_pipe_ctx = &sb;
1353 opt.feed_pipe = pipe_from_strbuf;
1354
1355 strvec_push(&opt.args, "amend");
1356
1357 code = run_hooks_opt(the_repository, "post-rewrite", &opt);
1358
1359 strbuf_release(&sb);
1360 return code;
1361}
1362
1363void commit_post_rewrite(struct repository *r,
1364 const struct commit *old_head,
1365 const struct object_id *new_head)
1366{
1367 struct notes_rewrite_cfg *cfg;
1368
1369 cfg = init_copy_notes_for_rewrite("amend");
1370 if (cfg) {
1371 /* we are amending, so old_head is not NULL */
1372 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1373 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1374 }
1375 run_rewrite_hook(&old_head->object.oid, new_head);
1376}
1377
1378static int run_prepare_commit_msg_hook(struct repository *r,
1379 struct strbuf *msg,
1380 const char *commit)
1381{
1382 int ret = 0;
1383 const char *name, *arg1 = NULL, *arg2 = NULL;
1384
1385 name = git_path_commit_editmsg();
1386 if (write_message(msg->buf, msg->len, name, 0))
1387 return -1;
1388
1389 if (commit) {
1390 arg1 = "commit";
1391 arg2 = commit;
1392 } else {
1393 arg1 = "message";
1394 }
1395 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1396 arg1, arg2, NULL))
1397 ret = error(_("'prepare-commit-msg' hook failed"));
1398
1399 return ret;
1400}
1401
1402static const char implicit_ident_advice_noconfig[] =
1403N_("Your name and email address were configured automatically based\n"
1404"on your username and hostname. Please check that they are accurate.\n"
1405"You can suppress this message by setting them explicitly. Run the\n"
1406"following command and follow the instructions in your editor to edit\n"
1407"your configuration file:\n"
1408"\n"
1409" git config --global --edit\n"
1410"\n"
1411"After doing this, you may fix the identity used for this commit with:\n"
1412"\n"
1413" git commit --amend --reset-author\n");
1414
1415static const char implicit_ident_advice_config[] =
1416N_("Your name and email address were configured automatically based\n"
1417"on your username and hostname. Please check that they are accurate.\n"
1418"You can suppress this message by setting them explicitly:\n"
1419"\n"
1420" git config --global user.name \"Your Name\"\n"
1421" git config --global user.email you@example.com\n"
1422"\n"
1423"After doing this, you may fix the identity used for this commit with:\n"
1424"\n"
1425" git commit --amend --reset-author\n");
1426
1427static const char *implicit_ident_advice(void)
1428{
1429 char *user_config = interpolate_path("~/.gitconfig", 0);
1430 char *xdg_config = xdg_config_home("config");
1431 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1432
1433 free(user_config);
1434 free(xdg_config);
1435
1436 if (config_exists)
1437 return _(implicit_ident_advice_config);
1438 else
1439 return _(implicit_ident_advice_noconfig);
1440
1441}
1442
1443void print_commit_summary(struct repository *r,
1444 const char *prefix,
1445 const struct object_id *oid,
1446 unsigned int flags)
1447{
1448 struct rev_info rev;
1449 struct commit *commit;
1450 struct strbuf format = STRBUF_INIT;
1451 const char *head;
1452 struct pretty_print_context pctx = {0};
1453 struct strbuf author_ident = STRBUF_INIT;
1454 struct strbuf committer_ident = STRBUF_INIT;
1455 struct ref_store *refs;
1456
1457 commit = lookup_commit(r, oid);
1458 if (!commit)
1459 die(_("couldn't look up newly created commit"));
1460 if (repo_parse_commit(r, commit))
1461 die(_("could not parse newly created commit"));
1462
1463 strbuf_addstr(&format, "format:%h] %s");
1464
1465 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1466 &pctx);
1467 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1468 &pctx);
1469 if (strbuf_cmp(&author_ident, &committer_ident)) {
1470 strbuf_addstr(&format, "\n Author: ");
1471 strbuf_addbuf_percentquote(&format, &author_ident);
1472 }
1473 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1474 struct strbuf date = STRBUF_INIT;
1475
1476 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1477 strbuf_addstr(&format, "\n Date: ");
1478 strbuf_addbuf_percentquote(&format, &date);
1479 strbuf_release(&date);
1480 }
1481 if (!committer_ident_sufficiently_given()) {
1482 strbuf_addstr(&format, "\n Committer: ");
1483 strbuf_addbuf_percentquote(&format, &committer_ident);
1484 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1485 strbuf_addch(&format, '\n');
1486 strbuf_addstr(&format, implicit_ident_advice());
1487 }
1488 }
1489 strbuf_release(&author_ident);
1490 strbuf_release(&committer_ident);
1491
1492 repo_init_revisions(r, &rev, prefix);
1493 setup_revisions(0, NULL, &rev, NULL);
1494
1495 rev.diff = 1;
1496 rev.diffopt.output_format =
1497 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1498
1499 rev.verbose_header = 1;
1500 rev.show_root_diff = 1;
1501 get_commit_format(format.buf, &rev);
1502 rev.always_show_header = 0;
1503 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1504 diff_setup_done(&rev.diffopt);
1505
1506 refs = get_main_ref_store(r);
1507 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1508 if (!head)
1509 die(_("unable to resolve HEAD after creating commit"));
1510 if (!strcmp(head, "HEAD"))
1511 head = _("detached HEAD");
1512 else
1513 skip_prefix(head, "refs/heads/", &head);
1514 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1515 _(" (root-commit)") : "");
1516
1517 if (!log_tree_commit(&rev, commit)) {
1518 rev.always_show_header = 1;
1519 rev.use_terminator = 1;
1520 log_tree_commit(&rev, commit);
1521 }
1522
1523 release_revisions(&rev);
1524 strbuf_release(&format);
1525}
1526
1527static int parse_head(struct repository *r, struct commit **head)
1528{
1529 struct commit *current_head;
1530 struct object_id oid;
1531
1532 if (repo_get_oid(r, "HEAD", &oid)) {
1533 current_head = NULL;
1534 } else {
1535 current_head = lookup_commit_reference(r, &oid);
1536 if (!current_head)
1537 return error(_("could not parse HEAD"));
1538 if (!oideq(&oid, &current_head->object.oid)) {
1539 warning(_("HEAD %s is not a commit!"),
1540 oid_to_hex(&oid));
1541 }
1542 if (repo_parse_commit(r, current_head))
1543 return error(_("could not parse HEAD commit"));
1544 }
1545 *head = current_head;
1546
1547 return 0;
1548}
1549
1550/*
1551 * Try to commit without forking 'git commit'. In some cases we need
1552 * to run 'git commit' to display an error message
1553 *
1554 * Returns:
1555 * -1 - error unable to commit
1556 * 0 - success
1557 * 1 - run 'git commit'
1558 */
1559static int try_to_commit(struct repository *r,
1560 struct strbuf *msg, const char *author,
1561 const char *reflog_action,
1562 struct replay_opts *opts, unsigned int flags,
1563 struct object_id *oid)
1564{
1565 struct object_id tree;
1566 struct commit *current_head = NULL;
1567 struct commit_list *parents = NULL;
1568 struct commit_extra_header *extra = NULL;
1569 struct strbuf err = STRBUF_INIT;
1570 struct strbuf commit_msg = STRBUF_INIT;
1571 char *amend_author = NULL;
1572 const char *committer = NULL;
1573 const char *hook_commit = NULL;
1574 enum commit_msg_cleanup_mode cleanup;
1575 int res = 0;
1576
1577 if (parse_head(r, &current_head))
1578 return -1;
1579
1580 if (flags & AMEND_MSG) {
1581 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1582 const char *out_enc = get_commit_output_encoding();
1583 const char *message = repo_logmsg_reencode(r, current_head,
1584 NULL, out_enc);
1585
1586 if (!msg) {
1587 const char *orig_message = NULL;
1588
1589 find_commit_subject(message, &orig_message);
1590 msg = &commit_msg;
1591 strbuf_addstr(msg, orig_message);
1592 hook_commit = "HEAD";
1593 }
1594 author = amend_author = get_author(message);
1595 repo_unuse_commit_buffer(r, current_head,
1596 message);
1597 if (!author) {
1598 res = error(_("unable to parse commit author"));
1599 goto out;
1600 }
1601 parents = commit_list_copy(current_head->parents);
1602 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1603 } else if (current_head &&
1604 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1605 commit_list_insert(current_head, &parents);
1606 }
1607
1608 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1609 res = error(_("git write-tree failed to write a tree"));
1610 goto out;
1611 }
1612
1613 if (!(flags & ALLOW_EMPTY)) {
1614 struct commit *first_parent = current_head;
1615
1616 if (flags & AMEND_MSG) {
1617 if (current_head->parents) {
1618 first_parent = current_head->parents->item;
1619 if (repo_parse_commit(r, first_parent)) {
1620 res = error(_("could not parse HEAD commit"));
1621 goto out;
1622 }
1623 } else {
1624 first_parent = NULL;
1625 }
1626 }
1627 if (oideq(first_parent
1628 ? get_commit_tree_oid(first_parent)
1629 : the_hash_algo->empty_tree,
1630 &tree)) {
1631 res = 1; /* run 'git commit' to display error message */
1632 goto out;
1633 }
1634 }
1635
1636 if (hook_exists(r, "prepare-commit-msg")) {
1637 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1638 if (res)
1639 goto out;
1640 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1641 2048) < 0) {
1642 res = error_errno(_("unable to read commit message "
1643 "from '%s'"),
1644 git_path_commit_editmsg());
1645 goto out;
1646 }
1647 msg = &commit_msg;
1648 }
1649
1650 if (flags & CLEANUP_MSG)
1651 cleanup = COMMIT_MSG_CLEANUP_ALL;
1652 else if ((opts->signoff || opts->record_origin) &&
1653 !opts->explicit_cleanup)
1654 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1655 else
1656 cleanup = opts->default_msg_cleanup;
1657
1658 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1659 strbuf_stripspace(msg,
1660 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1661 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1662 res = 1; /* run 'git commit' to display error message */
1663 goto out;
1664 }
1665
1666 if (opts->committer_date_is_author_date) {
1667 struct ident_split id;
1668 struct strbuf date = STRBUF_INIT;
1669
1670 if (!opts->ignore_date) {
1671 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1672 res = error(_("invalid author identity '%s'"),
1673 author);
1674 goto out;
1675 }
1676 if (!id.date_begin) {
1677 res = error(_(
1678 "corrupt author: missing date information"));
1679 goto out;
1680 }
1681 strbuf_addf(&date, "@%.*s %.*s",
1682 (int)(id.date_end - id.date_begin),
1683 id.date_begin,
1684 (int)(id.tz_end - id.tz_begin),
1685 id.tz_begin);
1686 } else {
1687 reset_ident_date();
1688 }
1689 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1690 getenv("GIT_COMMITTER_EMAIL"),
1691 WANT_COMMITTER_IDENT,
1692 opts->ignore_date ? NULL : date.buf,
1693 IDENT_STRICT);
1694 strbuf_release(&date);
1695 } else {
1696 reset_ident_date();
1697 }
1698
1699 if (opts->ignore_date) {
1700 struct ident_split id;
1701 char *name, *email;
1702
1703 if (split_ident_line(&id, author, strlen(author)) < 0) {
1704 error(_("invalid author identity '%s'"), author);
1705 goto out;
1706 }
1707 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1708 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1709 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1710 IDENT_STRICT);
1711 free(name);
1712 free(email);
1713 }
1714
1715 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1716 author, committer, opts->gpg_sign, extra)) {
1717 res = error(_("failed to write commit object"));
1718 goto out;
1719 }
1720
1721 if (update_head_with_reflog(current_head, oid, reflog_action,
1722 msg, &err)) {
1723 res = error("%s", err.buf);
1724 goto out;
1725 }
1726
1727 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1728 if (flags & AMEND_MSG)
1729 commit_post_rewrite(r, current_head, oid);
1730
1731out:
1732 free_commit_extra_headers(extra);
1733 commit_list_free(parents);
1734 strbuf_release(&err);
1735 strbuf_release(&commit_msg);
1736 free(amend_author);
1737
1738 return res;
1739}
1740
1741static int write_rebase_head(struct object_id *oid)
1742{
1743 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1744 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1745 return error(_("could not update %s"), "REBASE_HEAD");
1746
1747 return 0;
1748}
1749
1750static int do_commit(struct repository *r,
1751 const char *msg_file, const char *author,
1752 const char *reflog_action,
1753 struct replay_opts *opts, unsigned int flags,
1754 struct object_id *oid)
1755{
1756 int res = 1;
1757
1758 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1759 struct object_id oid;
1760 struct strbuf sb = STRBUF_INIT;
1761
1762 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1763 return error_errno(_("unable to read commit message "
1764 "from '%s'"),
1765 msg_file);
1766
1767 res = try_to_commit(r, msg_file ? &sb : NULL,
1768 author, reflog_action, opts, flags, &oid);
1769 strbuf_release(&sb);
1770 if (!res) {
1771 refs_delete_ref(get_main_ref_store(r), "",
1772 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1773 unlink(git_path_merge_msg(r));
1774 if (!is_rebase_i(opts))
1775 print_commit_summary(r, NULL, &oid,
1776 SUMMARY_SHOW_AUTHOR_DATE);
1777 return res;
1778 }
1779 }
1780 if (res == 1) {
1781 if (is_rebase_i(opts) && oid)
1782 if (write_rebase_head(oid))
1783 return -1;
1784 res = run_git_commit(msg_file, reflog_action, opts, flags);
1785 if (!res && is_rebase_i(opts) && oid)
1786 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD",
1787 NULL, REF_NO_DEREF);
1788 }
1789
1790 return res;
1791}
1792
1793static int is_original_commit_empty(struct commit *commit)
1794{
1795 const struct object_id *ptree_oid;
1796
1797 if (repo_parse_commit(the_repository, commit))
1798 return error(_("could not parse commit %s"),
1799 oid_to_hex(&commit->object.oid));
1800 if (commit->parents) {
1801 struct commit *parent = commit->parents->item;
1802 if (repo_parse_commit(the_repository, parent))
1803 return error(_("could not parse parent commit %s"),
1804 oid_to_hex(&parent->object.oid));
1805 ptree_oid = get_commit_tree_oid(parent);
1806 } else {
1807 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1808 }
1809
1810 return oideq(ptree_oid, get_commit_tree_oid(commit));
1811}
1812
1813/*
1814 * Should empty commits be allowed? Return status:
1815 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1816 * 0: Halt on empty commit
1817 * 1: Allow empty commit
1818 * 2: Drop empty commit
1819 */
1820static int allow_empty(struct repository *r,
1821 struct replay_opts *opts,
1822 struct commit *commit)
1823{
1824 int index_unchanged, originally_empty;
1825
1826 /*
1827 * For a commit that is initially empty, allow_empty determines if it
1828 * should be kept or not
1829 *
1830 * For a commit that becomes empty, keep_redundant_commits and
1831 * drop_redundant_commits determine whether the commit should be kept or
1832 * dropped. If neither is specified, halt.
1833 */
1834 index_unchanged = is_index_unchanged(r);
1835 if (index_unchanged < 0)
1836 return index_unchanged;
1837 if (!index_unchanged)
1838 return 0; /* we do not have to say --allow-empty */
1839
1840 originally_empty = is_original_commit_empty(commit);
1841 if (originally_empty < 0)
1842 return originally_empty;
1843 if (originally_empty)
1844 return opts->allow_empty;
1845 else if (opts->keep_redundant_commits)
1846 return 1;
1847 else if (opts->drop_redundant_commits)
1848 return 2;
1849 else
1850 return 0;
1851}
1852
1853static struct {
1854 char c;
1855 const char *str;
1856} todo_command_info[] = {
1857 [TODO_PICK] = { 'p', "pick" },
1858 [TODO_REVERT] = { 0, "revert" },
1859 [TODO_EDIT] = { 'e', "edit" },
1860 [TODO_REWORD] = { 'r', "reword" },
1861 [TODO_FIXUP] = { 'f', "fixup" },
1862 [TODO_SQUASH] = { 's', "squash" },
1863 [TODO_EXEC] = { 'x', "exec" },
1864 [TODO_BREAK] = { 'b', "break" },
1865 [TODO_LABEL] = { 'l', "label" },
1866 [TODO_RESET] = { 't', "reset" },
1867 [TODO_MERGE] = { 'm', "merge" },
1868 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1869 [TODO_NOOP] = { 0, "noop" },
1870 [TODO_DROP] = { 'd', "drop" },
1871 [TODO_COMMENT] = { 0, NULL },
1872};
1873
1874static const char *command_to_string(const enum todo_command command)
1875{
1876 if (command < TODO_COMMENT)
1877 return todo_command_info[command].str;
1878 if (command == TODO_COMMENT)
1879 return comment_line_str;
1880 die(_("unknown command: %d"), command);
1881}
1882
1883static char command_to_char(const enum todo_command command)
1884{
1885 if (command < TODO_COMMENT)
1886 return todo_command_info[command].c;
1887 return 0;
1888}
1889
1890static int is_noop(const enum todo_command command)
1891{
1892 return TODO_NOOP <= command;
1893}
1894
1895static int is_fixup(enum todo_command command)
1896{
1897 return command == TODO_FIXUP || command == TODO_SQUASH;
1898}
1899
1900/* Does this command create a (non-merge) commit? */
1901static int is_pick_or_similar(enum todo_command command)
1902{
1903 switch (command) {
1904 case TODO_PICK:
1905 case TODO_REVERT:
1906 case TODO_EDIT:
1907 case TODO_REWORD:
1908 case TODO_FIXUP:
1909 case TODO_SQUASH:
1910 return 1;
1911 default:
1912 return 0;
1913 }
1914}
1915
1916static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1917static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1918static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1919static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1920static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1921
1922void add_squash_combination_header(struct strbuf *buf, int n)
1923{
1924 strbuf_addf(buf, "%s ", comment_line_str);
1925 strbuf_addf(buf, _(combined_commit_msg_fmt), n);
1926}
1927
1928void add_squash_message_header(struct strbuf *buf, int n, int skip)
1929{
1930 strbuf_addf(buf, "%s ", comment_line_str);
1931 if (n == 1)
1932 strbuf_addstr(buf, skip ? _(skip_first_commit_msg_str) :
1933 _(first_commit_msg_str));
1934 else
1935 strbuf_addf(buf, skip ? _(skip_nth_commit_msg_fmt) :
1936 _(nth_commit_msg_fmt), n);
1937}
1938
1939size_t squash_subject_comment_len(const char *body, int squashing)
1940{
1941 if (starts_with(body, "amend!") ||
1942 (squashing && (starts_with(body, "squash!") ||
1943 starts_with(body, "fixup!"))))
1944 return commit_subject_length(body);
1945 return 0;
1946}
1947
1948static int is_fixup_flag(enum todo_command command, unsigned flag)
1949{
1950 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1951 (flag & TODO_EDIT_FIXUP_MSG));
1952}
1953
1954/*
1955 * Wrapper around strbuf_add_commented_lines() which avoids double
1956 * commenting commit subjects.
1957 */
1958static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1959{
1960 const char *s = str;
1961 while (starts_with_mem(s, len, comment_line_str)) {
1962 size_t count;
1963 const char *n = memchr(s, '\n', len);
1964 if (!n)
1965 count = len;
1966 else
1967 count = n - s + 1;
1968 strbuf_add(buf, s, count);
1969 s += count;
1970 len -= count;
1971 }
1972 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1973}
1974
1975/* Does the current fixup chain contain a squash command? */
1976static int seen_squash(struct replay_ctx *ctx)
1977{
1978 return starts_with(ctx->current_fixups.buf, "squash") ||
1979 strstr(ctx->current_fixups.buf, "\nsquash");
1980}
1981
1982/* Does the current fixup chain contain a "fixup -c" command? */
1983static int seen_fixup_edit_msg(struct replay_ctx *ctx)
1984{
1985 return starts_with(ctx->current_fixups.buf, "fixup -c") ||
1986 strstr(ctx->current_fixups.buf, "\nfixup -c");
1987}
1988
1989static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1990{
1991 strbuf_setlen(buf1, strlen(comment_line_str) + 1);
1992 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1993 strbuf_addch(buf1, '\n');
1994 strbuf_setlen(buf2, strlen(comment_line_str) + 1);
1995 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1996 strbuf_addch(buf2, '\n');
1997}
1998
1999/*
2000 * Comment out any un-commented commit messages, updating the message comments
2001 * to say they will be skipped but do not comment out the empty lines that
2002 * surround commit messages and their comments.
2003 */
2004static void update_squash_message_for_fixup(struct strbuf *msg)
2005{
2006 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
2007 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
2008 const char *s, *start;
2009 char *orig_msg;
2010 size_t orig_msg_len;
2011 int i = 1;
2012
2013 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str),
2014 strlen(_(first_commit_msg_str)),
2015 comment_line_str);
2016 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str),
2017 strlen(_(skip_first_commit_msg_str)),
2018 comment_line_str);
2019 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
2020 while (s) {
2021 const char *next;
2022 size_t off;
2023 if (skip_prefix(s, buf1.buf, &next)) {
2024 /*
2025 * Copy the last message, preserving the blank line
2026 * preceding the current line
2027 */
2028 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
2029 copy_lines(msg, start, s - start - off);
2030 if (off)
2031 strbuf_addch(msg, '\n');
2032 /*
2033 * The next message needs to be commented out but the
2034 * message header is already commented out so just copy
2035 * it and the blank line that follows it.
2036 */
2037 strbuf_addbuf(msg, &buf2);
2038 if (*next == '\n')
2039 strbuf_addch(msg, *next++);
2040 start = s = next;
2041 copy_lines = add_commented_lines;
2042 update_comment_bufs(&buf1, &buf2, ++i);
2043 } else if (skip_prefix(s, buf2.buf, &next)) {
2044 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
2045 copy_lines(msg, start, s - start - off);
2046 start = s - off;
2047 s = next;
2048 copy_lines = strbuf_add;
2049 update_comment_bufs(&buf1, &buf2, ++i);
2050 } else {
2051 s = strchr(s, '\n');
2052 if (s)
2053 s++;
2054 }
2055 }
2056 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2057 free(orig_msg);
2058 strbuf_release(&buf1);
2059 strbuf_release(&buf2);
2060}
2061
2062static int append_squash_message(struct strbuf *buf, const char *body,
2063 enum todo_command command, struct replay_opts *opts,
2064 unsigned flag)
2065{
2066 struct replay_ctx *ctx = opts->ctx;
2067 const char *fixup_msg;
2068 size_t commented_len, fixup_off;
2069
2070 commented_len = squash_subject_comment_len(body,
2071 command == TODO_SQUASH || seen_squash(ctx));
2072
2073 strbuf_addch(buf, '\n');
2074 add_squash_message_header(buf, ++ctx->current_fixup_count + 1, 0);
2075 strbuf_addstr(buf, "\n\n");
2076 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2077 /* buf->buf may be reallocated so store an offset into the buffer */
2078 fixup_off = buf->len;
2079 strbuf_addstr(buf, body + commented_len);
2080
2081 /* fixup -C after squash behaves like squash */
2082 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2083 /*
2084 * We're replacing the commit message so we need to
2085 * append any trailers if the user requested
2086 * '--signoff' or '--trailer'.
2087 */
2088 if (opts->signoff)
2089 append_signoff(buf, 0, 0);
2090
2091 if (opts->trailer_args.nr)
2092 amend_strbuf_with_trailers(buf, &opts->trailer_args);
2093
2094 if ((command == TODO_FIXUP) &&
2095 (flag & TODO_REPLACE_FIXUP_MSG) &&
2096 (file_exists(rebase_path_fixup_msg()) ||
2097 !file_exists(rebase_path_squash_msg()))) {
2098 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2099 if (write_message(fixup_msg, strlen(fixup_msg),
2100 rebase_path_fixup_msg(), 0) < 0)
2101 return error(_("cannot write '%s'"),
2102 rebase_path_fixup_msg());
2103 } else {
2104 unlink(rebase_path_fixup_msg());
2105 }
2106 } else {
2107 unlink(rebase_path_fixup_msg());
2108 }
2109
2110 return 0;
2111}
2112
2113static int update_squash_messages(struct repository *r,
2114 enum todo_command command,
2115 struct commit *commit,
2116 struct replay_opts *opts,
2117 unsigned flag)
2118{
2119 struct replay_ctx *ctx = opts->ctx;
2120 struct strbuf buf = STRBUF_INIT;
2121 int res = 0;
2122 const char *message, *body;
2123 const char *encoding = get_commit_output_encoding();
2124
2125 if (!is_fixup(command))
2126 BUG("not a FIXUP or SQUASH %d", command);
2127
2128 if (ctx->current_fixup_count > 0) {
2129 struct strbuf header = STRBUF_INIT;
2130 char *eol;
2131
2132 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2133 return error(_("could not read '%s'"),
2134 rebase_path_squash_msg());
2135
2136 eol = !starts_with(buf.buf, comment_line_str) ?
2137 buf.buf : strchrnul(buf.buf, '\n');
2138
2139 add_squash_combination_header(&header,
2140 ctx->current_fixup_count + 2);
2141 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2142 strbuf_release(&header);
2143 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2144 update_squash_message_for_fixup(&buf);
2145 } else {
2146 struct object_id head;
2147 struct commit *head_commit;
2148 const char *head_message, *body;
2149
2150 if (repo_get_oid(r, "HEAD", &head))
2151 return error(_("need a HEAD to fixup"));
2152 if (!(head_commit = lookup_commit_reference(r, &head)))
2153 return error(_("could not read HEAD"));
2154 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2155 encoding)))
2156 return error(_("could not read HEAD's commit message"));
2157
2158 find_commit_subject(head_message, &body);
2159 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2160 rebase_path_fixup_msg(), 0) < 0) {
2161 repo_unuse_commit_buffer(r, head_commit, head_message);
2162 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2163 }
2164 add_squash_combination_header(&buf, 2);
2165 strbuf_addch(&buf, '\n');
2166 add_squash_message_header(&buf, 1, is_fixup_flag(command, flag));
2167 strbuf_addstr(&buf, "\n\n");
2168 if (is_fixup_flag(command, flag))
2169 strbuf_add_commented_lines(&buf, body, strlen(body),
2170 comment_line_str);
2171 else
2172 strbuf_addstr(&buf, body);
2173
2174 repo_unuse_commit_buffer(r, head_commit, head_message);
2175 }
2176
2177 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2178 return error(_("could not read commit message of %s"),
2179 oid_to_hex(&commit->object.oid));
2180 find_commit_subject(message, &body);
2181
2182 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2183 res = append_squash_message(&buf, body, command, opts, flag);
2184 } else if (command == TODO_FIXUP) {
2185 strbuf_addch(&buf, '\n');
2186 add_squash_message_header(&buf, ++ctx->current_fixup_count + 1, 1);
2187 strbuf_addstr(&buf, "\n\n");
2188 strbuf_add_commented_lines(&buf, body, strlen(body),
2189 comment_line_str);
2190 }
2191 repo_unuse_commit_buffer(r, commit, message);
2192
2193 if (!res)
2194 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2195 0);
2196 strbuf_release(&buf);
2197
2198 if (!res) {
2199 const char *fixup_flag = "";
2200
2201 if (is_fixup_flag(command, flag) && (flag & TODO_EDIT_FIXUP_MSG))
2202 fixup_flag = " -c";
2203
2204 strbuf_addf(&ctx->current_fixups, "%s%s%s %s",
2205 ctx->current_fixups.len ? "\n" : "",
2206 command_to_string(command), fixup_flag,
2207 oid_to_hex(&commit->object.oid));
2208 res = write_message(ctx->current_fixups.buf,
2209 ctx->current_fixups.len,
2210 rebase_path_current_fixups(), 0);
2211 }
2212
2213 return res;
2214}
2215
2216static void flush_rewritten_pending(void)
2217{
2218 struct strbuf buf = STRBUF_INIT;
2219 struct object_id newoid;
2220 FILE *out;
2221
2222 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2223 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2224 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2225 char *bol = buf.buf, *eol;
2226
2227 while (*bol) {
2228 eol = strchrnul(bol, '\n');
2229 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2230 bol, oid_to_hex(&newoid));
2231 if (!*eol)
2232 break;
2233 bol = eol + 1;
2234 }
2235 fclose(out);
2236 unlink(rebase_path_rewritten_pending());
2237 }
2238 strbuf_release(&buf);
2239}
2240
2241static void record_in_rewritten(struct object_id *oid,
2242 enum todo_command next_command)
2243{
2244 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2245
2246 if (!out)
2247 return;
2248
2249 fprintf(out, "%s\n", oid_to_hex(oid));
2250 fclose(out);
2251
2252 if (!is_fixup(next_command))
2253 flush_rewritten_pending();
2254}
2255
2256static int should_edit(struct replay_opts *opts) {
2257 if (opts->edit < 0)
2258 /*
2259 * Note that we only handle the case of non-conflicted
2260 * commits; continue_single_pick() handles the conflicted
2261 * commits itself instead of calling this function.
2262 */
2263 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2264 return opts->edit;
2265}
2266
2267static void refer_to_commit(struct repository *r, struct strbuf *msgbuf,
2268 const struct commit *commit,
2269 bool use_commit_reference)
2270{
2271 if (use_commit_reference) {
2272 struct pretty_print_context ctx = {
2273 .abbrev = DEFAULT_ABBREV,
2274 .date_mode.type = DATE_SHORT,
2275 };
2276 repo_format_commit_message(r, commit,
2277 "%h (%s, %ad)", msgbuf, &ctx);
2278 } else {
2279 strbuf_add_oid_hex(msgbuf, &commit->object.oid);
2280 }
2281}
2282
2283static const char *sequencer_reflog_action(struct replay_opts *opts)
2284{
2285 if (!opts->reflog_action) {
2286 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
2287 opts->reflog_action =
2288 xstrdup(opts->reflog_action ? opts->reflog_action
2289 : action_name(opts));
2290 }
2291
2292 return opts->reflog_action;
2293}
2294
2295__attribute__((format (printf, 3, 4)))
2296static const char *reflog_message(struct replay_opts *opts,
2297 const char *sub_action, const char *fmt, ...)
2298{
2299 va_list ap;
2300 static struct strbuf buf = STRBUF_INIT;
2301
2302 va_start(ap, fmt);
2303 strbuf_reset(&buf);
2304 strbuf_addstr(&buf, sequencer_reflog_action(opts));
2305 if (sub_action)
2306 strbuf_addf(&buf, " (%s)", sub_action);
2307 if (fmt) {
2308 strbuf_addstr(&buf, ": ");
2309 strbuf_vaddf(&buf, fmt, ap);
2310 }
2311 va_end(ap);
2312
2313 return buf.buf;
2314}
2315
2316enum pick_result {
2317 PICK_RESULT_ERROR = -1,
2318 PICK_RESULT_OK,
2319 PICK_RESULT_CONFLICTS,
2320 PICK_RESULT_DROPPED,
2321};
2322
2323static enum pick_result do_pick_commit(struct repository *r,
2324 struct todo_item *item,
2325 struct replay_opts *opts,
2326 int final_fixup, int *check_todo)
2327{
2328 struct replay_ctx *ctx = opts->ctx;
2329 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2330 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2331 struct object_id head;
2332 struct commit *base, *next, *parent;
2333 const char *base_label, *next_label, *reflog_action;
2334 char *author = NULL;
2335 struct commit_message msg = { NULL, NULL, NULL, NULL };
2336 int res, unborn = 0, reword = 0, allow, drop_commit = 0;
2337 enum todo_command command = item->command;
2338 struct commit *commit = item->commit;
2339
2340 if (is_rebase_i(opts))
2341 reflog_action = reflog_message(
2342 opts, command_to_string(item->command), NULL);
2343 else
2344 reflog_action = sequencer_reflog_action(opts);
2345
2346 if (opts->no_commit) {
2347 /*
2348 * We do not intend to commit immediately. We just want to
2349 * merge the differences in, so let's compute the tree
2350 * that represents the "current" state for the merge machinery
2351 * to work on.
2352 */
2353 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2354 return error(_("your index file is unmerged."));
2355 } else {
2356 unborn = repo_get_oid(r, "HEAD", &head);
2357 /* Do we want to generate a root commit? */
2358 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2359 oideq(&head, &opts->squash_onto)) {
2360 if (is_fixup(command))
2361 return error(_("cannot fixup root commit"));
2362 flags |= CREATE_ROOT_COMMIT;
2363 unborn = 1;
2364 } else if (unborn)
2365 oidcpy(&head, the_hash_algo->empty_tree);
2366 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
2367 NULL, 0))
2368 return error_dirty_index(r, opts);
2369 }
2370 discard_index(r->index);
2371
2372 if (!commit->parents)
2373 parent = NULL;
2374 else if (commit->parents->next) {
2375 /* Reverting or cherry-picking a merge commit */
2376 int cnt;
2377 struct commit_list *p;
2378
2379 if (!opts->mainline)
2380 return error(_("commit %s is a merge but no -m option was given."),
2381 oid_to_hex(&commit->object.oid));
2382
2383 for (cnt = 1, p = commit->parents;
2384 cnt != opts->mainline && p;
2385 cnt++)
2386 p = p->next;
2387 if (cnt != opts->mainline || !p)
2388 return error(_("commit %s does not have parent %d"),
2389 oid_to_hex(&commit->object.oid), opts->mainline);
2390 parent = p->item;
2391 } else if (1 < opts->mainline)
2392 /*
2393 * Non-first parent explicitly specified as mainline for
2394 * non-merge commit
2395 */
2396 return error(_("commit %s does not have parent %d"),
2397 oid_to_hex(&commit->object.oid), opts->mainline);
2398 else
2399 parent = commit->parents->item;
2400
2401 if (get_message(commit, &msg) != 0)
2402 return error(_("cannot get commit message for %s"),
2403 oid_to_hex(&commit->object.oid));
2404
2405 if (opts->allow_ff && !is_fixup(command) &&
2406 ((parent && oideq(&parent->object.oid, &head)) ||
2407 (!parent && unborn))) {
2408 if (is_rebase_i(opts))
2409 write_author_script(msg.message);
2410 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2411 opts);
2412 if (res || command != TODO_REWORD)
2413 goto leave;
2414 reword = 1;
2415 msg_file = NULL;
2416 goto fast_forward_edit;
2417 }
2418 if (parent && repo_parse_commit(r, parent) < 0)
2419 /* TRANSLATORS: The first %s will be a "todo" command like
2420 "revert" or "pick", the second %s a SHA1. */
2421 return error(_("%s: cannot parse parent commit %s"),
2422 command_to_string(command),
2423 oid_to_hex(&parent->object.oid));
2424
2425 /*
2426 * "commit" is an existing commit. We would want to apply
2427 * the difference it introduces since its first parent "prev"
2428 * on top of the current HEAD if we are cherry-pick. Or the
2429 * reverse of it if we are revert.
2430 */
2431
2432 if (command == TODO_REVERT) {
2433 base = commit;
2434 base_label = msg.label;
2435 next = parent;
2436 next_label = msg.parent_label;
2437 sequencer_format_revert_message(r, msg.subject, commit,
2438 parent,
2439 opts->commit_use_reference,
2440 &ctx->message);
2441 } else {
2442 const char *p;
2443
2444 base = parent;
2445 base_label = msg.parent_label;
2446 next = commit;
2447 next_label = msg.label;
2448
2449 /* Append the commit log message to ctx->message. */
2450 if (find_commit_subject(msg.message, &p))
2451 strbuf_addstr(&ctx->message, p);
2452
2453 if (opts->record_origin) {
2454 strbuf_complete_line(&ctx->message);
2455 if (!has_conforming_footer(&ctx->message, NULL, 0))
2456 strbuf_addch(&ctx->message, '\n');
2457 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2458 strbuf_add_oid_hex(&ctx->message, &commit->object.oid);
2459 strbuf_addstr(&ctx->message, ")\n");
2460 }
2461 if (!is_fixup(command))
2462 author = get_author(msg.message);
2463 }
2464 ctx->have_message = 1;
2465
2466 if (command == TODO_REWORD)
2467 reword = 1;
2468 else if (is_fixup(command)) {
2469 if (update_squash_messages(r, command, commit,
2470 opts, item->flags)) {
2471 res = -1;
2472 goto leave;
2473 }
2474 flags |= AMEND_MSG;
2475 if (!final_fixup)
2476 msg_file = rebase_path_squash_msg();
2477 else if (file_exists(rebase_path_fixup_msg())) {
2478 msg_file = rebase_path_fixup_msg();
2479 } else {
2480 const char *dest = git_path_squash_msg(r);
2481 unlink(dest);
2482 if (copy_file(r, dest, rebase_path_squash_msg(), 0666)) {
2483 res = error(_("could not copy '%s' to '%s'"),
2484 rebase_path_squash_msg(), dest);
2485 goto leave;
2486 }
2487 unlink(git_path_merge_msg(r));
2488 msg_file = dest;
2489 flags |= EDIT_MSG;
2490 }
2491 }
2492
2493 if (opts->signoff && !is_fixup(command))
2494 append_signoff(&ctx->message, 0, 0);
2495
2496 if (opts->trailer_args.nr && !is_fixup(command))
2497 amend_strbuf_with_trailers(&ctx->message, &opts->trailer_args);
2498
2499 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2500 res = -1;
2501 else if (!opts->strategy ||
2502 !strcmp(opts->strategy, "recursive") ||
2503 !strcmp(opts->strategy, "ort") ||
2504 command == TODO_REVERT) {
2505 res = do_recursive_merge(r, base, next, base_label, next_label,
2506 &head, &ctx->message, opts);
2507 if (res < 0)
2508 goto leave;
2509
2510 res |= write_message(ctx->message.buf, ctx->message.len,
2511 git_path_merge_msg(r), 0);
2512 } else {
2513 struct commit_list *common = NULL;
2514 struct commit_list *remotes = NULL;
2515
2516 if (write_message(ctx->message.buf, ctx->message.len,
2517 git_path_merge_msg(r), 0)) {
2518 res = -1;
2519 goto leave;
2520 }
2521
2522 commit_list_insert(base, &common);
2523 commit_list_insert(next, &remotes);
2524 res = try_merge_command(r, opts->strategy,
2525 opts->xopts.nr, opts->xopts.v,
2526 common, oid_to_hex(&head), remotes);
2527 /*
2528 * If there were conflicts, try_merge_command() returns 1,
2529 * any other no-zero return code means that either the merge
2530 * command could not be run, or it failed to merge.
2531 */
2532 if (res && res != 1)
2533 res = -1;
2534
2535 commit_list_free(common);
2536 commit_list_free(remotes);
2537 }
2538
2539 /*
2540 * If the merge was clean or if it failed due to conflict, we write
2541 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2542 * However, if the merge did not even start, then we don't want to
2543 * write it at all.
2544 */
2545 if ((command == TODO_PICK || command == TODO_REWORD ||
2546 command == TODO_EDIT) && !opts->no_commit &&
2547 (res == 0 || res == 1) &&
2548 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2549 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2550 res = -1;
2551 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2552 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2553 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2554 res = -1;
2555
2556 if (res) {
2557 error(command == TODO_REVERT
2558 ? _("could not revert %s... %s")
2559 : _("could not apply %s... %s"),
2560 short_commit_name(r, commit), msg.subject);
2561 print_advice(r, res == 1, opts);
2562 repo_rerere(r, opts->allow_rerere_auto);
2563 goto leave;
2564 }
2565
2566 allow = allow_empty(r, opts, commit);
2567 if (allow < 0) {
2568 res = allow;
2569 goto leave;
2570 } else if (allow == 1) {
2571 flags |= ALLOW_EMPTY;
2572 } else if (allow == 2) {
2573 drop_commit = 1;
2574 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2575 NULL, REF_NO_DEREF);
2576 unlink(git_path_merge_msg(r));
2577 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2578 NULL, REF_NO_DEREF);
2579 fprintf(stderr,
2580 _("dropping %s %s -- patch contents already upstream\n"),
2581 oid_to_hex(&commit->object.oid), msg.subject);
2582 } /* else allow == 0 and there's nothing special to do */
2583 if (!opts->no_commit && !drop_commit) {
2584 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2585 res = do_commit(r, msg_file, author, reflog_action,
2586 opts, flags,
2587 commit? &commit->object.oid : NULL);
2588 else
2589 res = error(_("unable to parse commit author"));
2590 *check_todo = !!(flags & EDIT_MSG);
2591 if (!res && reword) {
2592fast_forward_edit:
2593 /*
2594 * To reword we amend the commit we just
2595 * picked or fast-forwarded. As the commit has
2596 * already been picked we want to use the same
2597 * set of commit flags regardless of how we
2598 * got here.
2599 */
2600 flags = EDIT_MSG | VERIFY_MSG | AMEND_MSG | ALLOW_EMPTY;
2601 res = run_git_commit(NULL, reflog_action, opts, flags);
2602 *check_todo = 1;
2603 }
2604 /*
2605 * If "git commit" failed to run then res == -1, but we don't
2606 * want reschedule the last command because the picking the
2607 * commit was successful.
2608 */
2609 res = !!res;
2610 }
2611
2612
2613 if (!res && final_fixup) {
2614 unlink(rebase_path_fixup_msg());
2615 unlink(rebase_path_squash_msg());
2616 unlink(rebase_path_current_fixups());
2617 strbuf_reset(&ctx->current_fixups);
2618 ctx->current_fixup_count = 0;
2619 }
2620
2621leave:
2622 free_message(commit, &msg);
2623 free(author);
2624 update_abort_safety_file();
2625
2626 if (res < 0)
2627 return PICK_RESULT_ERROR;
2628 else if (res > 0)
2629 return PICK_RESULT_CONFLICTS;
2630 else if (drop_commit)
2631 return PICK_RESULT_DROPPED;
2632 else
2633 return PICK_RESULT_OK;
2634}
2635
2636static int prepare_revs(struct replay_opts *opts)
2637{
2638 /*
2639 * picking (but not reverting) ranges (but not individual revisions)
2640 * should be done in reverse
2641 */
2642 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2643 opts->revs->reverse ^= 1;
2644
2645 if (prepare_revision_walk(opts->revs))
2646 return error(_("revision walk setup failed"));
2647
2648 return 0;
2649}
2650
2651static int read_and_refresh_cache(struct repository *r,
2652 struct replay_opts *opts)
2653{
2654 struct lock_file index_lock = LOCK_INIT;
2655 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2656 if (repo_read_index(r) < 0) {
2657 rollback_lock_file(&index_lock);
2658 return error(_("git %s: failed to read the index"),
2659 action_name(opts));
2660 }
2661 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2662
2663 if (index_fd >= 0) {
2664 if (write_locked_index(r->index, &index_lock,
2665 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2666 return error(_("git %s: failed to refresh the index"),
2667 action_name(opts));
2668 }
2669 }
2670
2671 /*
2672 * If we are resolving merges in any way other than "ort", then
2673 * expand the sparse index.
2674 */
2675 if (opts->strategy && strcmp(opts->strategy, "ort"))
2676 ensure_full_index(r->index);
2677 return 0;
2678}
2679
2680void todo_list_release(struct todo_list *todo_list)
2681{
2682 strbuf_release(&todo_list->buf);
2683 FREE_AND_NULL(todo_list->items);
2684 todo_list->nr = todo_list->alloc = 0;
2685}
2686
2687static struct todo_item *append_new_todo(struct todo_list *todo_list)
2688{
2689 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2690 return todo_list->items + todo_list->nr++;
2691}
2692
2693const char *todo_item_get_arg(struct todo_list *todo_list,
2694 struct todo_item *item)
2695{
2696 return todo_list->buf.buf + item->arg_offset;
2697}
2698
2699static int is_command(enum todo_command command, const char **bol)
2700{
2701 const char *str = todo_command_info[command].str;
2702 const char nick = todo_command_info[command].c;
2703 const char *p = *bol;
2704
2705 if ((skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2706 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p)) {
2707 *bol = p;
2708 return 1;
2709 }
2710 return 0;
2711}
2712
2713bool sequencer_parse_todo_command(const char **p, enum todo_command *cmd)
2714{
2715 const char *s = *p;
2716
2717 for (int i = 0; i < TODO_COMMENT; i++)
2718 if (is_command(i, p)) {
2719 *cmd = i;
2720 return true;
2721 }
2722
2723 if (starts_with(s, comment_line_str)) {
2724 *cmd = TODO_COMMENT;
2725 return true;
2726 } else if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n') || !s[0]) {
2727 *cmd = TODO_COMMENT;
2728 return true;
2729 }
2730
2731 return false;
2732}
2733
2734static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2735{
2736 switch (command) {
2737 case TODO_LABEL:
2738 /*
2739 * '#' is not a valid label as the merge command uses it to
2740 * separate merge parents from the commit subject.
2741 */
2742 if (!strcmp(arg, "#") ||
2743 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2744 return error(_("'%s' is not a valid label"), arg);
2745 break;
2746
2747 case TODO_UPDATE_REF:
2748 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2749 return error(_("'%s' is not a valid refname"), arg);
2750 if (check_refname_format(arg, 0))
2751 return error(_("update-ref requires a fully qualified "
2752 "refname e.g. refs/heads/%s"), arg);
2753 break;
2754
2755 default:
2756 BUG("unexpected todo_command");
2757 }
2758
2759 return 0;
2760}
2761
2762static int check_merge_commit_insn(enum todo_command command)
2763{
2764 switch(command) {
2765 case TODO_PICK:
2766 error(_("'%s' does not accept merge commits"),
2767 todo_command_info[command].str);
2768 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2769 /*
2770 * TRANSLATORS: 'pick' and 'merge -C' should not be
2771 * translated.
2772 */
2773 "'pick' does not take a merge commit. If you wanted to\n"
2774 "replay the merge, use 'merge -C' on the commit."));
2775 return -1;
2776
2777 case TODO_REWORD:
2778 error(_("'%s' does not accept merge commits"),
2779 todo_command_info[command].str);
2780 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2781 /*
2782 * TRANSLATORS: 'reword' and 'merge -c' should not be
2783 * translated.
2784 */
2785 "'reword' does not take a merge commit. If you wanted to\n"
2786 "replay the merge and reword the commit message, use\n"
2787 "'merge -c' on the commit"));
2788 return -1;
2789
2790 case TODO_EDIT:
2791 error(_("'%s' does not accept merge commits"),
2792 todo_command_info[command].str);
2793 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2794 /*
2795 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2796 * not be translated.
2797 */
2798 "'edit' does not take a merge commit. If you wanted to\n"
2799 "replay the merge, use 'merge -C' on the commit, and then\n"
2800 "'break' to give the control back to you so that you can\n"
2801 "do 'git commit --amend && git rebase --continue'."));
2802 return -1;
2803
2804 case TODO_FIXUP:
2805 case TODO_SQUASH:
2806 return error(_("cannot squash merge commit into another commit"));
2807
2808 case TODO_MERGE:
2809 case TODO_DROP:
2810 return 0;
2811
2812 default:
2813 BUG("unexpected todo_command");
2814 }
2815}
2816
2817static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2818 struct todo_item *item, const char *buf,
2819 const char *bol, char *eol)
2820{
2821 struct object_id commit_oid;
2822 char *end_of_object_name;
2823 int saved, status, padding;
2824
2825 item->flags = 0;
2826
2827 /* left-trim */
2828 bol += strspn(bol, " \t");
2829
2830 if (!sequencer_parse_todo_command(&bol, &item->command))
2831 return error(_("invalid command '%.*s'"),
2832 (int)strcspn(bol, " \t\r\n"), bol);
2833
2834 if (item->command == TODO_COMMENT) {
2835 item->commit = NULL;
2836 item->arg_offset = bol - buf;
2837 item->arg_len = eol - bol;
2838 return 0;
2839 }
2840
2841 /* Eat up extra spaces/ tabs before object name */
2842 padding = strspn(bol, " \t");
2843 bol += padding;
2844
2845 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2846 if (bol != eol)
2847 return error(_("%s does not accept arguments: '%s'"),
2848 command_to_string(item->command), bol);
2849 item->commit = NULL;
2850 item->arg_offset = bol - buf;
2851 item->arg_len = eol - bol;
2852 return 0;
2853 }
2854
2855 if (!padding)
2856 return error(_("missing arguments for %s"),
2857 command_to_string(item->command));
2858
2859 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2860 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2861 int ret = 0;
2862
2863 item->commit = NULL;
2864 item->arg_offset = bol - buf;
2865 item->arg_len = (int)(eol - bol);
2866 if (item->command == TODO_LABEL ||
2867 item->command == TODO_UPDATE_REF) {
2868 saved = *eol;
2869 *eol = '\0';
2870 ret = check_label_or_ref_arg(item->command, bol);
2871 *eol = saved;
2872 }
2873 return ret;
2874 }
2875
2876 if (item->command == TODO_FIXUP) {
2877 if (skip_prefix(bol, "-C", &bol)) {
2878 bol += strspn(bol, " \t");
2879 item->flags |= TODO_REPLACE_FIXUP_MSG;
2880 } else if (skip_prefix(bol, "-c", &bol)) {
2881 bol += strspn(bol, " \t");
2882 item->flags |= TODO_EDIT_FIXUP_MSG;
2883 }
2884 }
2885
2886 if (item->command == TODO_MERGE) {
2887 if (skip_prefix(bol, "-C", &bol))
2888 bol += strspn(bol, " \t");
2889 else if (skip_prefix(bol, "-c", &bol)) {
2890 bol += strspn(bol, " \t");
2891 item->flags |= TODO_EDIT_MERGE_MSG;
2892 } else {
2893 item->flags |= TODO_EDIT_MERGE_MSG;
2894 item->commit = NULL;
2895 item->arg_offset = bol - buf;
2896 item->arg_len = (int)(eol - bol);
2897 return 0;
2898 }
2899 }
2900
2901 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2902 saved = *end_of_object_name;
2903 *end_of_object_name = '\0';
2904 status = repo_get_oid(r, bol, &commit_oid);
2905 if (status < 0)
2906 error(_("could not parse '%s'"), bol); /* return later */
2907 *end_of_object_name = saved;
2908
2909 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2910 item->arg_offset = bol - buf;
2911 item->arg_len = (int)(eol - bol);
2912
2913 if (status < 0)
2914 return status;
2915
2916 item->commit = lookup_commit_reference(r, &commit_oid);
2917 if (!item->commit)
2918 return -1;
2919 if (is_rebase_i(opts) &&
2920 item->commit->parents && item->commit->parents->next)
2921 return check_merge_commit_insn(item->command);
2922 return 0;
2923}
2924
2925int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2926{
2927 const char *todo_file, *bol;
2928 struct strbuf buf = STRBUF_INIT;
2929 int ret = 0;
2930
2931 todo_file = git_path_todo_file();
2932 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2933 if (errno == ENOENT || errno == ENOTDIR)
2934 return -1;
2935 else
2936 return error_errno("unable to open '%s'", todo_file);
2937 }
2938 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2939 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2940 *action = REPLAY_PICK;
2941 else if (is_command(TODO_REVERT, &bol) &&
2942 (*bol == ' ' || *bol == '\t'))
2943 *action = REPLAY_REVERT;
2944 else
2945 ret = -1;
2946
2947 strbuf_release(&buf);
2948
2949 return ret;
2950}
2951
2952int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2953 char *buf, struct todo_list *todo_list)
2954{
2955 struct todo_item *item;
2956 char *p = buf, *next_p;
2957 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2958
2959 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2960
2961 for (i = 1; *p; i++, p = next_p) {
2962 char *eol = strchrnul(p, '\n');
2963
2964 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2965
2966 if (p != eol && eol[-1] == '\r')
2967 eol--; /* strip Carriage Return */
2968
2969 item = append_new_todo(todo_list);
2970 item->offset_in_buf = p - todo_list->buf.buf;
2971 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2972 res = error(_("invalid line %d: %.*s"),
2973 i, (int)(eol - p), p);
2974 item->command = TODO_COMMENT + 1;
2975 item->arg_offset = p - buf;
2976 item->arg_len = (int)(eol - p);
2977 item->commit = NULL;
2978 }
2979
2980 if (item->command != TODO_COMMENT)
2981 todo_list->total_nr++;
2982
2983 if (fixup_okay)
2984 ; /* do nothing */
2985 else if (is_fixup(item->command))
2986 res = error(_("cannot '%s' without a previous commit"),
2987 command_to_string(item->command));
2988 else if (!is_noop(item->command))
2989 fixup_okay = 1;
2990 }
2991
2992 return res;
2993}
2994
2995static int count_commands(struct todo_list *todo_list)
2996{
2997 int count = 0, i;
2998
2999 for (i = 0; i < todo_list->nr; i++)
3000 if (todo_list->items[i].command != TODO_COMMENT)
3001 count++;
3002
3003 return count;
3004}
3005
3006static int get_item_line_offset(struct todo_list *todo_list, int index)
3007{
3008 return index < todo_list->nr ?
3009 todo_list->items[index].offset_in_buf : todo_list->buf.len;
3010}
3011
3012static const char *get_item_line(struct todo_list *todo_list, int index)
3013{
3014 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
3015}
3016
3017static int get_item_line_length(struct todo_list *todo_list, int index)
3018{
3019 return get_item_line_offset(todo_list, index + 1)
3020 - get_item_line_offset(todo_list, index);
3021}
3022
3023static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
3024{
3025 int fd;
3026 ssize_t len;
3027
3028 fd = open(path, O_RDONLY);
3029 if (fd < 0)
3030 return error_errno(_("could not open '%s'"), path);
3031 len = strbuf_read(sb, fd, 0);
3032 close(fd);
3033 if (len < 0)
3034 return error(_("could not read '%s'."), path);
3035 return len;
3036}
3037
3038static int have_finished_the_last_pick(void)
3039{
3040 struct strbuf buf = STRBUF_INIT;
3041 const char *eol;
3042 const char *todo_path = git_path_todo_file();
3043 int ret = 0;
3044
3045 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
3046 if (errno == ENOENT) {
3047 return 0;
3048 } else {
3049 error_errno("unable to open '%s'", todo_path);
3050 return 0;
3051 }
3052 }
3053 /* If there is only one line then we are done */
3054 eol = strchr(buf.buf, '\n');
3055 if (!eol || !eol[1])
3056 ret = 1;
3057
3058 strbuf_release(&buf);
3059
3060 return ret;
3061}
3062
3063void sequencer_post_commit_cleanup(struct repository *r, int verbose)
3064{
3065 struct replay_opts opts = REPLAY_OPTS_INIT;
3066 int need_cleanup = 0;
3067
3068 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
3069 if (!refs_delete_ref(get_main_ref_store(r), "",
3070 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
3071 verbose)
3072 warning(_("cancelling a cherry picking in progress"));
3073 opts.action = REPLAY_PICK;
3074 need_cleanup = 1;
3075 }
3076
3077 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3078 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
3079 NULL, REF_NO_DEREF) &&
3080 verbose)
3081 warning(_("cancelling a revert in progress"));
3082 opts.action = REPLAY_REVERT;
3083 need_cleanup = 1;
3084 }
3085
3086 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
3087 NULL, REF_NO_DEREF);
3088
3089 if (!need_cleanup)
3090 goto out;
3091
3092 if (!have_finished_the_last_pick())
3093 goto out;
3094
3095 sequencer_remove_state(&opts);
3096out:
3097 replay_opts_release(&opts);
3098}
3099
3100static void todo_list_write_total_nr(struct todo_list *todo_list)
3101{
3102 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
3103
3104 if (f) {
3105 fprintf(f, "%d\n", todo_list->total_nr);
3106 fclose(f);
3107 }
3108}
3109
3110static int read_populate_todo(struct repository *r,
3111 struct todo_list *todo_list,
3112 struct replay_opts *opts)
3113{
3114 const char *todo_file = get_todo_path(opts);
3115 int res;
3116
3117 strbuf_reset(&todo_list->buf);
3118 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
3119 return -1;
3120
3121 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
3122 if (res) {
3123 if (is_rebase_i(opts))
3124 return error(_("please fix this using "
3125 "'git rebase --edit-todo'."));
3126 return error(_("unusable instruction sheet: '%s'"), todo_file);
3127 }
3128
3129 if (!todo_list->nr &&
3130 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3131 return error(_("no commits parsed."));
3132
3133 if (!is_rebase_i(opts)) {
3134 enum todo_command valid =
3135 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3136 int i;
3137
3138 for (i = 0; i < todo_list->nr; i++)
3139 if (valid == todo_list->items[i].command)
3140 continue;
3141 else if (valid == TODO_PICK)
3142 return error(_("cannot cherry-pick during a revert."));
3143 else
3144 return error(_("cannot revert during a cherry-pick."));
3145 }
3146
3147 if (is_rebase_i(opts)) {
3148 struct todo_list done = TODO_LIST_INIT;
3149
3150 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3151 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3152 todo_list->done_nr = count_commands(&done);
3153 else
3154 todo_list->done_nr = 0;
3155
3156 todo_list->total_nr = todo_list->done_nr
3157 + count_commands(todo_list);
3158 todo_list_release(&done);
3159
3160 todo_list_write_total_nr(todo_list);
3161 }
3162
3163 return 0;
3164}
3165
3166static int git_config_string_dup(char **dest,
3167 const char *var, const char *value)
3168{
3169 if (!value)
3170 return config_error_nonbool(var);
3171 free(*dest);
3172 *dest = xstrdup(value);
3173 return 0;
3174}
3175
3176static int populate_opts_cb(const char *key, const char *value,
3177 const struct config_context *ctx,
3178 void *data)
3179{
3180 struct replay_opts *opts = data;
3181 int error_flag = 1;
3182
3183 if (!value)
3184 error_flag = 0;
3185 else if (!strcmp(key, "options.no-commit"))
3186 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3187 else if (!strcmp(key, "options.edit"))
3188 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3189 else if (!strcmp(key, "options.allow-empty"))
3190 opts->allow_empty =
3191 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3192 else if (!strcmp(key, "options.allow-empty-message"))
3193 opts->allow_empty_message =
3194 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3195 else if (!strcmp(key, "options.drop-redundant-commits"))
3196 opts->drop_redundant_commits =
3197 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3198 else if (!strcmp(key, "options.keep-redundant-commits"))
3199 opts->keep_redundant_commits =
3200 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3201 else if (!strcmp(key, "options.signoff"))
3202 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3203 else if (!strcmp(key, "options.record-origin"))
3204 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3205 else if (!strcmp(key, "options.allow-ff"))
3206 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3207 else if (!strcmp(key, "options.mainline"))
3208 opts->mainline = git_config_int(key, value, ctx->kvi);
3209 else if (!strcmp(key, "options.strategy"))
3210 git_config_string_dup(&opts->strategy, key, value);
3211 else if (!strcmp(key, "options.gpg-sign"))
3212 git_config_string_dup(&opts->gpg_sign, key, value);
3213 else if (!strcmp(key, "options.strategy-option")) {
3214 strvec_push(&opts->xopts, value);
3215 } else if (!strcmp(key, "options.allow-rerere-auto"))
3216 opts->allow_rerere_auto =
3217 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3218 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3219 else if (!strcmp(key, "options.default-msg-cleanup")) {
3220 opts->explicit_cleanup = 1;
3221 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3222 } else
3223 return error(_("invalid key: %s"), key);
3224
3225 if (!error_flag)
3226 return error(_("invalid value for '%s': '%s'"), key, value);
3227
3228 return 0;
3229}
3230
3231static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3232{
3233 int i;
3234 int count;
3235 const char **argv;
3236 char *strategy_opts_string = raw_opts;
3237
3238 if (*strategy_opts_string == ' ')
3239 strategy_opts_string++;
3240
3241 count = split_cmdline(strategy_opts_string, &argv);
3242 if (count < 0)
3243 BUG("could not split '%s': %s", strategy_opts_string,
3244 split_cmdline_strerror(count));
3245 for (i = 0; i < count; i++) {
3246 const char *arg = argv[i];
3247
3248 skip_prefix(arg, "--", &arg);
3249 strvec_push(&opts->xopts, arg);
3250 }
3251 free(argv);
3252}
3253
3254static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3255{
3256 strbuf_reset(buf);
3257 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3258 return;
3259 opts->strategy = strbuf_detach(buf, NULL);
3260 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3261 return;
3262
3263 parse_strategy_opts(opts, buf->buf);
3264}
3265
3266static int read_trailers(struct replay_opts *opts, struct strbuf *buf)
3267{
3268 ssize_t len;
3269
3270 strbuf_reset(buf);
3271 len = strbuf_read_file(buf, rebase_path_trailer(), 0);
3272 if (len > 0) {
3273 char *p = buf->buf, *nl;
3274
3275 trailer_config_init();
3276
3277 while ((nl = strchr(p, '\n'))) {
3278 *nl = '\0';
3279 if (!*p)
3280 return error(_("trailers file contains empty line"));
3281 strvec_push(&opts->trailer_args, p);
3282 p = nl + 1;
3283 }
3284 } else if (!len) {
3285 return error(_("trailers file is empty"));
3286 } else if (errno != ENOENT) {
3287 return error(_("cannot read trailers files"));
3288 }
3289
3290 return 0;
3291}
3292
3293static int read_populate_opts(struct replay_opts *opts)
3294{
3295 struct replay_ctx *ctx = opts->ctx;
3296
3297 if (is_rebase_i(opts)) {
3298 struct strbuf buf = STRBUF_INIT;
3299 int ret = 0;
3300
3301 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3302 READ_ONELINER_SKIP_IF_EMPTY)) {
3303 if (!starts_with(buf.buf, "-S"))
3304 strbuf_reset(&buf);
3305 else {
3306 free(opts->gpg_sign);
3307 opts->gpg_sign = xstrdup(buf.buf + 2);
3308 }
3309 strbuf_reset(&buf);
3310 }
3311
3312 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3313 READ_ONELINER_SKIP_IF_EMPTY)) {
3314 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3315 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3316 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3317 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3318 strbuf_reset(&buf);
3319 }
3320
3321 if (file_exists(rebase_path_verbose()))
3322 opts->verbose = 1;
3323
3324 if (file_exists(rebase_path_quiet()))
3325 opts->quiet = 1;
3326
3327 if (file_exists(rebase_path_signoff())) {
3328 opts->allow_ff = 0;
3329 opts->signoff = 1;
3330 }
3331
3332 if (file_exists(rebase_path_cdate_is_adate())) {
3333 opts->allow_ff = 0;
3334 opts->committer_date_is_author_date = 1;
3335 }
3336
3337 if (file_exists(rebase_path_ignore_date())) {
3338 opts->allow_ff = 0;
3339 opts->ignore_date = 1;
3340 }
3341
3342 if (file_exists(rebase_path_reschedule_failed_exec()))
3343 opts->reschedule_failed_exec = 1;
3344 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3345 opts->reschedule_failed_exec = 0;
3346
3347 if (file_exists(rebase_path_drop_redundant_commits()))
3348 opts->drop_redundant_commits = 1;
3349
3350 if (file_exists(rebase_path_keep_redundant_commits()))
3351 opts->keep_redundant_commits = 1;
3352
3353 read_strategy_opts(opts, &buf);
3354
3355 if (read_trailers(opts, &buf)) {
3356 ret = -1;
3357 goto done_rebase_i;
3358 }
3359 strbuf_reset(&buf);
3360
3361 if (read_oneliner(&ctx->current_fixups,
3362 rebase_path_current_fixups(),
3363 READ_ONELINER_SKIP_IF_EMPTY)) {
3364 const char *p = ctx->current_fixups.buf;
3365 ctx->current_fixup_count = 1;
3366 while ((p = strchr(p, '\n'))) {
3367 /*
3368 * Older versions of git accidentally
3369 * inserted blank lines when a fixup
3370 * was skipped.
3371 */
3372 if (p[1] && p[1] != '\n')
3373 ctx->current_fixup_count++;
3374 p++;
3375 }
3376 }
3377
3378 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3379 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3380 ret = error(_("unusable squash-onto"));
3381 goto done_rebase_i;
3382 }
3383 opts->have_squash_onto = 1;
3384 }
3385
3386done_rebase_i:
3387 strbuf_release(&buf);
3388 return ret;
3389 }
3390
3391 if (!file_exists(git_path_opts_file()))
3392 return 0;
3393 /*
3394 * The function git_parse_source(), called from git_config_from_file(),
3395 * may die() in case of a syntactically incorrect file. We do not care
3396 * about this case, though, because we wrote that file ourselves, so we
3397 * are pretty certain that it is syntactically correct.
3398 */
3399 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3400 return error(_("malformed options sheet: '%s'"),
3401 git_path_opts_file());
3402 return 0;
3403}
3404
3405static void write_strategy_opts(struct replay_opts *opts)
3406{
3407 struct strbuf buf = STRBUF_INIT;
3408
3409 /*
3410 * Quote strategy options so that they can be read correctly
3411 * by split_cmdline().
3412 */
3413 quote_cmdline(&buf, opts->xopts.v);
3414 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3415 strbuf_release(&buf);
3416}
3417
3418int write_basic_state(struct replay_opts *opts, const char *head_name,
3419 struct commit *onto, const struct object_id *orig_head)
3420{
3421 if (head_name)
3422 write_file(rebase_path_head_name(), "%s\n", head_name);
3423 if (onto)
3424 write_file(rebase_path_onto(), "%s\n",
3425 oid_to_hex(&onto->object.oid));
3426 if (orig_head)
3427 write_file(rebase_path_orig_head(), "%s\n",
3428 oid_to_hex(orig_head));
3429
3430 if (opts->quiet)
3431 write_file(rebase_path_quiet(), "%s", "");
3432 if (opts->verbose)
3433 write_file(rebase_path_verbose(), "%s", "");
3434 if (opts->strategy)
3435 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3436 if (opts->xopts.nr > 0)
3437 write_strategy_opts(opts);
3438
3439 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3440 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3441 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3442 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3443
3444 if (opts->gpg_sign)
3445 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3446 if (opts->signoff)
3447 write_file(rebase_path_signoff(), "--signoff\n");
3448 if (opts->drop_redundant_commits)
3449 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3450 if (opts->keep_redundant_commits)
3451 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3452 if (opts->committer_date_is_author_date)
3453 write_file(rebase_path_cdate_is_adate(), "%s", "");
3454 if (opts->ignore_date)
3455 write_file(rebase_path_ignore_date(), "%s", "");
3456 if (opts->reschedule_failed_exec)
3457 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3458 else
3459 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3460 if (opts->trailer_args.nr) {
3461 struct strbuf buf = STRBUF_INIT;
3462
3463 for (size_t i = 0; i < opts->trailer_args.nr; i++)
3464 strbuf_addf(&buf, "%s\n", opts->trailer_args.v[i]);
3465 write_file(rebase_path_trailer(), "%s", buf.buf);
3466 strbuf_release(&buf);
3467 }
3468
3469 return 0;
3470}
3471
3472static int walk_revs_populate_todo(struct todo_list *todo_list,
3473 struct replay_opts *opts)
3474{
3475 enum todo_command command = opts->action == REPLAY_PICK ?
3476 TODO_PICK : TODO_REVERT;
3477 const char *command_string = todo_command_info[command].str;
3478 const char *encoding;
3479 struct commit *commit;
3480
3481 if (prepare_revs(opts))
3482 return -1;
3483
3484 encoding = get_log_output_encoding();
3485
3486 while ((commit = get_revision(opts->revs))) {
3487 struct todo_item *item = append_new_todo(todo_list);
3488 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3489 commit, NULL,
3490 encoding);
3491 const char *subject;
3492 int subject_len;
3493
3494 item->command = command;
3495 item->commit = commit;
3496 item->arg_offset = 0;
3497 item->arg_len = 0;
3498 item->offset_in_buf = todo_list->buf.len;
3499 subject_len = find_commit_subject(commit_buffer, &subject);
3500 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3501 short_commit_name(the_repository, commit),
3502 subject_len, subject);
3503 repo_unuse_commit_buffer(the_repository, commit,
3504 commit_buffer);
3505 }
3506
3507 if (!todo_list->nr)
3508 return error(_("empty commit set passed"));
3509
3510 return 0;
3511}
3512
3513static int create_seq_dir(struct repository *r)
3514{
3515 enum replay_action action;
3516 const char *in_progress_error = NULL;
3517 const char *in_progress_advice = NULL;
3518 unsigned int advise_skip =
3519 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3520 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3521
3522 if (!sequencer_get_last_command(r, &action)) {
3523 switch (action) {
3524 case REPLAY_REVERT:
3525 in_progress_error = _("revert is already in progress");
3526 in_progress_advice =
3527 _("try \"git revert (--continue | %s--abort | --quit)\"");
3528 break;
3529 case REPLAY_PICK:
3530 in_progress_error = _("cherry-pick is already in progress");
3531 in_progress_advice =
3532 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3533 break;
3534 default:
3535 BUG("unexpected action in create_seq_dir");
3536 }
3537 }
3538 if (in_progress_error) {
3539 error("%s", in_progress_error);
3540 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3541 advise(in_progress_advice,
3542 advise_skip ? "--skip | " : "");
3543 return -1;
3544 }
3545 if (mkdir(git_path_seq_dir(), 0777) < 0)
3546 return error_errno(_("could not create sequencer directory '%s'"),
3547 git_path_seq_dir());
3548
3549 return 0;
3550}
3551
3552static int save_head(const char *head)
3553{
3554 return write_message(head, strlen(head), git_path_head_file(), 1);
3555}
3556
3557static int rollback_is_safe(void)
3558{
3559 struct strbuf sb = STRBUF_INIT;
3560 struct object_id expected_head, actual_head;
3561
3562 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3563 strbuf_trim(&sb);
3564 if (get_oid_hex(sb.buf, &expected_head)) {
3565 strbuf_release(&sb);
3566 die(_("could not parse %s"), git_path_abort_safety_file());
3567 }
3568 strbuf_release(&sb);
3569 }
3570 else if (errno == ENOENT)
3571 oidclr(&expected_head, the_repository->hash_algo);
3572 else
3573 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3574
3575 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3576 oidclr(&actual_head, the_repository->hash_algo);
3577
3578 return oideq(&actual_head, &expected_head);
3579}
3580
3581static int reset_merge(const struct object_id *oid)
3582{
3583 struct child_process cmd = CHILD_PROCESS_INIT;
3584
3585 cmd.git_cmd = 1;
3586 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3587
3588 if (!is_null_oid(oid))
3589 strvec_push(&cmd.args, oid_to_hex(oid));
3590
3591 return run_command(&cmd);
3592}
3593
3594static int rollback_single_pick(struct repository *r)
3595{
3596 struct object_id head_oid;
3597
3598 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3599 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3600 return error(_("no cherry-pick or revert in progress"));
3601 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3602 return error(_("cannot resolve HEAD"));
3603 if (is_null_oid(&head_oid))
3604 return error(_("cannot abort from a branch yet to be born"));
3605 return reset_merge(&head_oid);
3606}
3607
3608static int skip_single_pick(void)
3609{
3610 struct object_id head;
3611
3612 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3613 return error(_("cannot resolve HEAD"));
3614 return reset_merge(&head);
3615}
3616
3617int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3618{
3619 FILE *f;
3620 struct object_id oid;
3621 struct strbuf buf = STRBUF_INIT;
3622 const char *p;
3623
3624 f = fopen(git_path_head_file(), "r");
3625 if (!f && errno == ENOENT) {
3626 /*
3627 * There is no multiple-cherry-pick in progress.
3628 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3629 * a single-cherry-pick in progress, abort that.
3630 */
3631 return rollback_single_pick(r);
3632 }
3633 if (!f)
3634 return error_errno(_("cannot open '%s'"), git_path_head_file());
3635 if (strbuf_getline_lf(&buf, f)) {
3636 error(_("cannot read '%s': %s"), git_path_head_file(),
3637 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3638 fclose(f);
3639 goto fail;
3640 }
3641 fclose(f);
3642 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3643 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3644 git_path_head_file());
3645 goto fail;
3646 }
3647 if (is_null_oid(&oid)) {
3648 error(_("cannot abort from a branch yet to be born"));
3649 goto fail;
3650 }
3651
3652 if (!rollback_is_safe()) {
3653 /* Do not error, just do not rollback */
3654 warning(_("You seem to have moved HEAD. "
3655 "Not rewinding, check your HEAD!"));
3656 } else
3657 if (reset_merge(&oid))
3658 goto fail;
3659 strbuf_release(&buf);
3660 return sequencer_remove_state(opts);
3661fail:
3662 strbuf_release(&buf);
3663 return -1;
3664}
3665
3666int sequencer_skip(struct repository *r, struct replay_opts *opts)
3667{
3668 enum replay_action action = -1;
3669 sequencer_get_last_command(r, &action);
3670
3671 /*
3672 * Check whether the subcommand requested to skip the commit is actually
3673 * in progress and that it's safe to skip the commit.
3674 *
3675 * opts->action tells us which subcommand requested to skip the commit.
3676 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3677 * action is in progress and we can skip the commit.
3678 *
3679 * Otherwise we check that the last instruction was related to the
3680 * particular subcommand we're trying to execute and barf if that's not
3681 * the case.
3682 *
3683 * Finally we check that the rollback is "safe", i.e., has the HEAD
3684 * moved? In this case, it doesn't make sense to "reset the merge" and
3685 * "skip the commit" as the user already handled this by committing. But
3686 * we'd not want to barf here, instead give advice on how to proceed. We
3687 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3688 * it gets removed when the user commits, so if it still exists we're
3689 * sure the user can't have committed before.
3690 */
3691 switch (opts->action) {
3692 case REPLAY_REVERT:
3693 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3694 if (action != REPLAY_REVERT)
3695 return error(_("no revert in progress"));
3696 if (!rollback_is_safe())
3697 goto give_advice;
3698 }
3699 break;
3700 case REPLAY_PICK:
3701 if (!refs_ref_exists(get_main_ref_store(r),
3702 "CHERRY_PICK_HEAD")) {
3703 if (action != REPLAY_PICK)
3704 return error(_("no cherry-pick in progress"));
3705 if (!rollback_is_safe())
3706 goto give_advice;
3707 }
3708 break;
3709 default:
3710 BUG("unexpected action in sequencer_skip");
3711 }
3712
3713 if (skip_single_pick())
3714 return error(_("failed to skip the commit"));
3715 if (!is_directory(git_path_seq_dir()))
3716 return 0;
3717
3718 return sequencer_continue(r, opts);
3719
3720give_advice:
3721 error(_("there is nothing to skip"));
3722
3723 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3724 advise(_("have you committed already?\n"
3725 "try \"git %s --continue\""),
3726 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3727 }
3728 return -1;
3729}
3730
3731static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3732 int reschedule)
3733{
3734 struct lock_file todo_lock = LOCK_INIT;
3735 const char *todo_path = get_todo_path(opts);
3736 int next = todo_list->current, offset, fd;
3737
3738 /*
3739 * rebase -i writes "git-rebase-todo" without the currently executing
3740 * command, appending it to "done" instead.
3741 */
3742 if (is_rebase_i(opts) && !reschedule)
3743 next++;
3744
3745 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3746 if (fd < 0)
3747 return error_errno(_("could not lock '%s'"), todo_path);
3748 offset = get_item_line_offset(todo_list, next);
3749 if (write_in_full(fd, todo_list->buf.buf + offset,
3750 todo_list->buf.len - offset) < 0)
3751 return error_errno(_("could not write to '%s'"), todo_path);
3752 if (commit_lock_file(&todo_lock) < 0)
3753 return error(_("failed to finalize '%s'"), todo_path);
3754
3755 if (is_rebase_i(opts) && !reschedule && next > 0) {
3756 const char *done = rebase_path_done();
3757 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3758 int ret = 0;
3759
3760 if (fd < 0)
3761 return 0;
3762 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3763 get_item_line_length(todo_list, next - 1))
3764 < 0)
3765 ret = error_errno(_("could not write to '%s'"), done);
3766 if (close(fd) < 0)
3767 ret = error_errno(_("failed to finalize '%s'"), done);
3768 return ret;
3769 }
3770 return 0;
3771}
3772
3773static int save_opts(struct replay_opts *opts)
3774{
3775 const char *opts_file = git_path_opts_file();
3776 int res = 0;
3777
3778 if (opts->no_commit)
3779 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3780 "options.no-commit", NULL, "true");
3781 if (opts->edit >= 0)
3782 res |= repo_config_set_in_file_gently(the_repository, opts_file, "options.edit", NULL,
3783 opts->edit ? "true" : "false");
3784 if (opts->allow_empty)
3785 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3786 "options.allow-empty", NULL, "true");
3787 if (opts->allow_empty_message)
3788 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3789 "options.allow-empty-message", NULL, "true");
3790 if (opts->drop_redundant_commits)
3791 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3792 "options.drop-redundant-commits", NULL, "true");
3793 if (opts->keep_redundant_commits)
3794 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3795 "options.keep-redundant-commits", NULL, "true");
3796 if (opts->signoff)
3797 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3798 "options.signoff", NULL, "true");
3799 if (opts->record_origin)
3800 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3801 "options.record-origin", NULL, "true");
3802 if (opts->allow_ff)
3803 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3804 "options.allow-ff", NULL, "true");
3805 if (opts->mainline) {
3806 struct strbuf buf = STRBUF_INIT;
3807 strbuf_addf(&buf, "%d", opts->mainline);
3808 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3809 "options.mainline", NULL, buf.buf);
3810 strbuf_release(&buf);
3811 }
3812 if (opts->strategy)
3813 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3814 "options.strategy", NULL, opts->strategy);
3815 if (opts->gpg_sign)
3816 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3817 "options.gpg-sign", NULL, opts->gpg_sign);
3818 for (size_t i = 0; i < opts->xopts.nr; i++)
3819 res |= repo_config_set_multivar_in_file_gently(the_repository, opts_file,
3820 "options.strategy-option",
3821 opts->xopts.v[i], "^$", NULL, 0);
3822 if (opts->allow_rerere_auto)
3823 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3824 "options.allow-rerere-auto", NULL,
3825 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3826 "true" : "false");
3827
3828 if (opts->explicit_cleanup)
3829 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3830 "options.default-msg-cleanup", NULL,
3831 describe_cleanup_mode(opts->default_msg_cleanup));
3832 return res;
3833}
3834
3835static int make_patch(struct repository *r,
3836 struct commit *commit,
3837 struct replay_opts *opts)
3838{
3839 struct rev_info log_tree_opt;
3840 const char *subject;
3841 char hex[GIT_MAX_HEXSZ + 1];
3842 int res = 0;
3843
3844 if (!is_rebase_i(opts))
3845 BUG("make_patch should only be called when rebasing");
3846
3847 oid_to_hex_r(hex, &commit->object.oid);
3848 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3849 return -1;
3850 res |= write_rebase_head(&commit->object.oid);
3851
3852 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3853 repo_init_revisions(r, &log_tree_opt, NULL);
3854 log_tree_opt.abbrev = 0;
3855 log_tree_opt.diff = 1;
3856 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3857 log_tree_opt.disable_stdin = 1;
3858 log_tree_opt.no_commit_id = 1;
3859 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3860 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3861 if (!log_tree_opt.diffopt.file)
3862 res |= error_errno(_("could not open '%s'"),
3863 rebase_path_patch());
3864 else {
3865 res |= log_tree_commit(&log_tree_opt, commit);
3866 fclose(log_tree_opt.diffopt.file);
3867 }
3868
3869 if (!file_exists(rebase_path_message())) {
3870 const char *encoding = get_commit_output_encoding();
3871 const char *commit_buffer = repo_logmsg_reencode(r,
3872 commit, NULL,
3873 encoding);
3874 find_commit_subject(commit_buffer, &subject);
3875 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3876 repo_unuse_commit_buffer(r, commit,
3877 commit_buffer);
3878 }
3879 release_revisions(&log_tree_opt);
3880
3881 return res;
3882}
3883
3884static int intend_to_amend(void)
3885{
3886 struct object_id head;
3887 char *p;
3888
3889 if (repo_get_oid(the_repository, "HEAD", &head))
3890 return error(_("cannot read HEAD"));
3891
3892 p = oid_to_hex(&head);
3893 return write_message(p, strlen(p), rebase_path_amend(), 1);
3894}
3895
3896static int error_with_patch(struct repository *r,
3897 struct commit *commit,
3898 const char *subject, int subject_len,
3899 struct replay_opts *opts,
3900 int exit_code, int to_amend)
3901{
3902 struct replay_ctx *ctx = opts->ctx;
3903
3904 /*
3905 * Write the commit message to be used by "git rebase
3906 * --continue". If a "fixup" or "squash" command has conflicts
3907 * then we will have already written rebase_path_message() in
3908 * error_failed_squash(). If an "edit" command was
3909 * fast-forwarded then we don't have a message in ctx->message
3910 * and rely on make_patch() to write rebase_path_message()
3911 * instead.
3912 */
3913 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3914 write_message(ctx->message.buf, ctx->message.len,
3915 rebase_path_message(), 0))
3916 return error(_("could not write commit message file"));
3917
3918 if (commit && make_patch(r, commit, opts))
3919 return -1;
3920
3921 if (to_amend) {
3922 if (intend_to_amend())
3923 return -1;
3924
3925 fprintf(stderr,
3926 _("You can amend the commit now, with\n"
3927 "\n"
3928 " git commit --amend %s\n"
3929 "\n"
3930 "Once you are satisfied with your changes, run\n"
3931 "\n"
3932 " git rebase --continue\n"),
3933 gpg_sign_opt_quoted(opts));
3934 } else if (exit_code) {
3935 if (commit)
3936 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3937 short_commit_name(r, commit), subject_len, subject);
3938 else
3939 /*
3940 * We don't have the hash of the parent so
3941 * just print the line from the todo file.
3942 */
3943 fprintf_ln(stderr, _("Could not merge %.*s"),
3944 subject_len, subject);
3945 }
3946
3947 return exit_code;
3948}
3949
3950static int error_failed_squash(struct repository *r,
3951 struct commit *commit,
3952 struct replay_opts *opts,
3953 int subject_len,
3954 const char *subject)
3955{
3956 if (copy_file(r, rebase_path_message(), rebase_path_squash_msg(), 0666))
3957 return error(_("could not copy '%s' to '%s'"),
3958 rebase_path_squash_msg(), rebase_path_message());
3959 unlink(git_path_merge_msg(r));
3960 if (copy_file(r, git_path_merge_msg(r), rebase_path_message(), 0666))
3961 return error(_("could not copy '%s' to '%s'"),
3962 rebase_path_message(),
3963 git_path_merge_msg(r));
3964 return error_with_patch(r, commit, subject, subject_len, opts, 1, 1);
3965}
3966
3967static int do_exec(struct repository *r, const char *command_line,
3968 struct replay_opts *opts)
3969{
3970 struct child_process cmd = CHILD_PROCESS_INIT;
3971 int dirty, status;
3972
3973 if (!opts->quiet)
3974 fprintf(stderr, _("Executing: %s\n"), command_line);
3975 cmd.use_shell = 1;
3976 strvec_push(&cmd.args, command_line);
3977 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3978 disable_auto_maintenance(opts, &cmd);
3979 status = run_command(&cmd);
3980
3981 /* force re-reading of the cache */
3982 discard_index(r->index);
3983 if (repo_read_index(r) < 0)
3984 return error(_("could not read index"));
3985
3986 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3987
3988 if (status) {
3989 warning(_("execution failed: %s\n%s"
3990 "You can fix the problem, and then run\n"
3991 "\n"
3992 " git rebase --continue\n"
3993 "\n"),
3994 command_line,
3995 dirty ? _("and made changes to the index and/or the "
3996 "working tree.\n") : "");
3997 if (status == 127)
3998 /* command not found */
3999 status = 1;
4000 } else if (dirty) {
4001 warning(_("execution succeeded: %s\nbut "
4002 "left changes to the index and/or the working tree.\n"
4003 "Commit or stash your changes, and then run\n"
4004 "\n"
4005 " git rebase --continue\n"
4006 "\n"), command_line);
4007 status = 1;
4008 }
4009
4010 return status;
4011}
4012
4013__attribute__((format (printf, 2, 3)))
4014static int safe_append(const char *filename, const char *fmt, ...)
4015{
4016 va_list ap;
4017 struct lock_file lock = LOCK_INIT;
4018 int fd = hold_lock_file_for_update(&lock, filename,
4019 LOCK_REPORT_ON_ERROR);
4020 struct strbuf buf = STRBUF_INIT;
4021
4022 if (fd < 0)
4023 return -1;
4024
4025 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
4026 error_errno(_("could not read '%s'"), filename);
4027 rollback_lock_file(&lock);
4028 return -1;
4029 }
4030 strbuf_complete(&buf, '\n');
4031 va_start(ap, fmt);
4032 strbuf_vaddf(&buf, fmt, ap);
4033 va_end(ap);
4034
4035 if (write_in_full(fd, buf.buf, buf.len) < 0) {
4036 error_errno(_("could not write to '%s'"), filename);
4037 strbuf_release(&buf);
4038 rollback_lock_file(&lock);
4039 return -1;
4040 }
4041 if (commit_lock_file(&lock) < 0) {
4042 strbuf_release(&buf);
4043 return error(_("failed to finalize '%s'"), filename);
4044 }
4045
4046 strbuf_release(&buf);
4047 return 0;
4048}
4049
4050static int do_label(struct repository *r, const char *name, int len)
4051{
4052 struct ref_store *refs = get_main_ref_store(r);
4053 struct ref_transaction *transaction;
4054 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
4055 struct strbuf msg = STRBUF_INIT;
4056 int ret = 0;
4057 struct object_id head_oid;
4058
4059 if (len == 1 && *name == '#')
4060 return error(_("illegal label name: '%.*s'"), len, name);
4061
4062 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
4063 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
4064
4065 transaction = ref_store_transaction_begin(refs, 0, &err);
4066 if (!transaction) {
4067 error("%s", err.buf);
4068 ret = -1;
4069 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
4070 error(_("could not read HEAD"));
4071 ret = -1;
4072 } else if (ref_transaction_update(transaction, ref_name.buf,
4073 &head_oid, NULL, NULL, NULL,
4074 0, msg.buf, &err) < 0 ||
4075 ref_transaction_commit(transaction, &err)) {
4076 error("%s", err.buf);
4077 ret = -1;
4078 }
4079 ref_transaction_free(transaction);
4080 strbuf_release(&err);
4081 strbuf_release(&msg);
4082
4083 if (!ret)
4084 ret = safe_append(rebase_path_refs_to_delete(),
4085 "%s\n", ref_name.buf);
4086 strbuf_release(&ref_name);
4087
4088 return ret;
4089}
4090
4091static struct commit *lookup_label(struct repository *r, const char *label,
4092 int len, struct strbuf *buf)
4093{
4094 struct commit *commit;
4095 struct object_id oid;
4096
4097 strbuf_reset(buf);
4098 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
4099 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
4100 commit = lookup_commit_object(r, &oid);
4101 } else {
4102 /* fall back to non-rewritten ref or commit */
4103 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
4104 commit = lookup_commit_reference_by_name(buf->buf);
4105 }
4106
4107 if (!commit)
4108 error(_("could not resolve '%s'"), buf->buf);
4109
4110 return commit;
4111}
4112
4113static int do_reset(struct repository *r,
4114 const char *name, int len,
4115 struct replay_opts *opts)
4116{
4117 struct strbuf ref_name = STRBUF_INIT;
4118 struct object_id oid;
4119 struct lock_file lock = LOCK_INIT;
4120 struct tree_desc desc = { 0 };
4121 struct tree *tree;
4122 struct unpack_trees_options unpack_tree_opts = { 0 };
4123 int ret = 0;
4124
4125 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
4126 return -1;
4127
4128 if (len == 10 && !strncmp("[new root]", name, len)) {
4129 if (!opts->have_squash_onto) {
4130 const char *hex;
4131 if (commit_tree("", 0, the_hash_algo->empty_tree,
4132 NULL, &opts->squash_onto,
4133 NULL, NULL))
4134 return error(_("writing fake root commit"));
4135 opts->have_squash_onto = 1;
4136 hex = oid_to_hex(&opts->squash_onto);
4137 if (write_message(hex, strlen(hex),
4138 rebase_path_squash_onto(), 0))
4139 return error(_("writing squash-onto"));
4140 }
4141 oidcpy(&oid, &opts->squash_onto);
4142 } else {
4143 int i;
4144 struct commit *commit;
4145
4146 /* Determine the length of the label */
4147 for (i = 0; i < len; i++)
4148 if (isspace(name[i]))
4149 break;
4150 len = i;
4151
4152 commit = lookup_label(r, name, len, &ref_name);
4153 if (!commit) {
4154 ret = -1;
4155 goto cleanup;
4156 }
4157 oid = commit->object.oid;
4158 }
4159
4160 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4161 unpack_tree_opts.head_idx = 1;
4162 unpack_tree_opts.src_index = r->index;
4163 unpack_tree_opts.dst_index = r->index;
4164 unpack_tree_opts.fn = oneway_merge;
4165 unpack_tree_opts.merge = 1;
4166 unpack_tree_opts.update = 1;
4167 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4168 unpack_tree_opts.skip_cache_tree_update = 1;
4169 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4170
4171 if (repo_read_index_unmerged(r)) {
4172 ret = error_resolve_conflict(action_name(opts));
4173 goto cleanup;
4174 }
4175
4176 if (!fill_tree_descriptor(r, &desc, &oid)) {
4177 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4178 goto cleanup;
4179 }
4180
4181 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4182 ret = -1;
4183 goto cleanup;
4184 }
4185
4186 tree = repo_parse_tree_indirect(the_repository, &oid);
4187 if (!tree)
4188 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4189 prime_cache_tree(r, r->index, tree);
4190
4191 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4192 ret = error(_("could not write index"));
4193
4194 if (!ret)
4195 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4196 len, name),
4197 "HEAD", &oid,
4198 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4199cleanup:
4200 free((void *)desc.buffer);
4201 if (ret < 0)
4202 rollback_lock_file(&lock);
4203 strbuf_release(&ref_name);
4204 clear_unpack_trees_porcelain(&unpack_tree_opts);
4205 return ret;
4206}
4207
4208static int do_merge(struct repository *r,
4209 struct commit *commit,
4210 const char *arg, int arg_len,
4211 int flags, int *check_todo, struct replay_opts *opts)
4212{
4213 struct replay_ctx *ctx = opts->ctx;
4214 int run_commit_flags = 0;
4215 struct strbuf ref_name = STRBUF_INIT;
4216 struct commit *head_commit, *merge_commit, *i;
4217 struct commit_list *bases = NULL, *j;
4218 struct commit_list *to_merge = NULL, **tail = &to_merge;
4219 const char *strategy = !opts->xopts.nr &&
4220 (!opts->strategy ||
4221 !strcmp(opts->strategy, "recursive") ||
4222 !strcmp(opts->strategy, "ort")) ?
4223 NULL : opts->strategy;
4224 struct merge_options o;
4225 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4226 static struct lock_file lock;
4227 const char *p;
4228 const char *reflog_action = reflog_message(opts, "merge", NULL);
4229
4230 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4231 ret = -1;
4232 goto leave_merge;
4233 }
4234
4235 head_commit = lookup_commit_reference_by_name("HEAD");
4236 if (!head_commit) {
4237 ret = error(_("cannot merge without a current revision"));
4238 goto leave_merge;
4239 }
4240
4241 /*
4242 * For octopus merges, the arg starts with the list of revisions to be
4243 * merged. The list is optionally followed by '#' and the oneline.
4244 */
4245 merge_arg_len = oneline_offset = arg_len;
4246 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4247 if (!*p)
4248 break;
4249 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4250 p += 1 + strspn(p + 1, " \t\n");
4251 oneline_offset = p - arg;
4252 break;
4253 }
4254 k = strcspn(p, " \t\n");
4255 if (!k)
4256 continue;
4257 merge_commit = lookup_label(r, p, k, &ref_name);
4258 if (!merge_commit) {
4259 ret = error(_("unable to parse '%.*s'"), k, p);
4260 goto leave_merge;
4261 }
4262 tail = &commit_list_insert(merge_commit, tail)->next;
4263 p += k;
4264 merge_arg_len = p - arg;
4265 }
4266
4267 if (!to_merge) {
4268 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4269 goto leave_merge;
4270 }
4271
4272 if (opts->have_squash_onto &&
4273 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4274 /*
4275 * When the user tells us to "merge" something into a
4276 * "[new root]", let's simply fast-forward to the merge head.
4277 */
4278 rollback_lock_file(&lock);
4279 if (to_merge->next)
4280 ret = error(_("octopus merge cannot be executed on "
4281 "top of a [new root]"));
4282 else
4283 ret = fast_forward_to(r, &to_merge->item->object.oid,
4284 &head_commit->object.oid, 0,
4285 opts);
4286 goto leave_merge;
4287 }
4288
4289 /*
4290 * If HEAD is not identical to the first parent of the original merge
4291 * commit, we cannot fast-forward.
4292 */
4293 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4294 oideq(&commit->parents->item->object.oid,
4295 &head_commit->object.oid);
4296
4297 /*
4298 * If any merge head is different from the original one, we cannot
4299 * fast-forward.
4300 */
4301 if (can_fast_forward) {
4302 struct commit_list *p = commit->parents->next;
4303
4304 for (j = to_merge; j && p; j = j->next, p = p->next)
4305 if (!oideq(&j->item->object.oid,
4306 &p->item->object.oid)) {
4307 can_fast_forward = 0;
4308 break;
4309 }
4310 /*
4311 * If the number of merge heads differs from the original merge
4312 * commit, we cannot fast-forward.
4313 */
4314 if (j || p)
4315 can_fast_forward = 0;
4316 }
4317
4318 if (can_fast_forward) {
4319 rollback_lock_file(&lock);
4320 ret = fast_forward_to(r, &commit->object.oid,
4321 &head_commit->object.oid, 0, opts);
4322 if (flags & TODO_EDIT_MERGE_MSG)
4323 goto fast_forward_edit;
4324
4325 goto leave_merge;
4326 }
4327
4328 if (commit) {
4329 const char *encoding = get_commit_output_encoding();
4330 const char *message = repo_logmsg_reencode(r, commit, NULL,
4331 encoding);
4332 const char *body;
4333 int len;
4334
4335 if (!message) {
4336 ret = error(_("could not get commit message of '%s'"),
4337 oid_to_hex(&commit->object.oid));
4338 goto leave_merge;
4339 }
4340 write_author_script(message);
4341 find_commit_subject(message, &body);
4342 len = strlen(body);
4343 strbuf_add(&ctx->message, body, len);
4344 repo_unuse_commit_buffer(r, commit, message);
4345 } else {
4346 struct strbuf buf = STRBUF_INIT;
4347
4348 strbuf_addf(&buf, "author %s", git_author_info(0));
4349 write_author_script(buf.buf);
4350 strbuf_release(&buf);
4351
4352 if (oneline_offset < arg_len) {
4353 strbuf_add(&ctx->message, arg + oneline_offset,
4354 arg_len - oneline_offset);
4355 } else {
4356 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4357 to_merge->next ? "branches" : "branch",
4358 merge_arg_len, arg);
4359 }
4360 }
4361 ctx->have_message = 1;
4362 if (write_message(ctx->message.buf, ctx->message.len,
4363 git_path_merge_msg(r), 0)) {
4364 ret = error_errno(_("could not write '%s'"),
4365 git_path_merge_msg(r));
4366 goto leave_merge;
4367 }
4368
4369 if (strategy || to_merge->next) {
4370 /* Octopus merge */
4371 struct child_process cmd = CHILD_PROCESS_INIT;
4372
4373 if (read_env_script(&cmd.env)) {
4374 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4375
4376 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4377 goto leave_merge;
4378 }
4379
4380 if (opts->committer_date_is_author_date)
4381 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4382 opts->ignore_date ?
4383 "" :
4384 author_date_from_env(&cmd.env));
4385 if (opts->ignore_date)
4386 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4387 disable_auto_maintenance(opts, &cmd);
4388
4389 cmd.git_cmd = 1;
4390 strvec_push(&cmd.args, "merge");
4391 strvec_push(&cmd.args, "-s");
4392 if (!strategy)
4393 strvec_push(&cmd.args, "octopus");
4394 else {
4395 strvec_push(&cmd.args, strategy);
4396 for (k = 0; k < opts->xopts.nr; k++)
4397 strvec_pushf(&cmd.args,
4398 "-X%s", opts->xopts.v[k]);
4399 }
4400 if (!(flags & TODO_EDIT_MERGE_MSG))
4401 strvec_push(&cmd.args, "--no-edit");
4402 else
4403 strvec_push(&cmd.args, "--edit");
4404 strvec_push(&cmd.args, "--no-ff");
4405 strvec_push(&cmd.args, "--no-log");
4406 strvec_push(&cmd.args, "--no-stat");
4407 strvec_push(&cmd.args, "-F");
4408 strvec_push(&cmd.args, git_path_merge_msg(r));
4409 if (opts->gpg_sign)
4410 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4411 else
4412 strvec_push(&cmd.args, "--no-gpg-sign");
4413
4414 /* Add the tips to be merged */
4415 for (j = to_merge; j; j = j->next)
4416 strvec_push(&cmd.args,
4417 oid_to_hex(&j->item->object.oid));
4418
4419 strbuf_release(&ref_name);
4420 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4421 NULL, REF_NO_DEREF);
4422 rollback_lock_file(&lock);
4423
4424 ret = run_command(&cmd);
4425
4426 /* force re-reading of the cache */
4427 if (!ret) {
4428 discard_index(r->index);
4429 if (repo_read_index(r) < 0)
4430 ret = error(_("could not read index"));
4431 }
4432 goto leave_merge;
4433 }
4434
4435 merge_commit = to_merge->item;
4436 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4437 ret = -1;
4438 goto leave_merge;
4439 }
4440
4441 if (bases && oideq(&merge_commit->object.oid,
4442 &bases->item->object.oid)) {
4443 ret = 0;
4444 /* skip merging an ancestor of HEAD */
4445 goto leave_merge;
4446 }
4447
4448 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4449 git_path_merge_head(r), 0);
4450 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4451
4452 bases = commit_list_reverse(bases);
4453
4454 repo_read_index(r);
4455 init_ui_merge_options(&o, r);
4456 o.branch1 = "HEAD";
4457 o.branch2 = ref_name.buf;
4458 o.buffer_output = 2;
4459
4460 /*
4461 * TODO: Should use merge_incore_recursive() and
4462 * merge_switch_to_result(), skipping the call to
4463 * merge_switch_to_result() when we don't actually need to
4464 * update the index and working copy immediately.
4465 */
4466 ret = merge_ort_recursive(&o, head_commit, merge_commit, bases, &i);
4467 if (ret <= 0)
4468 fputs(o.obuf.buf, stdout);
4469 strbuf_release(&o.obuf);
4470 if (ret < 0) {
4471 error(_("could not even attempt to merge '%.*s'"),
4472 merge_arg_len, arg);
4473 unlink(git_path_merge_msg(r));
4474 goto leave_merge;
4475 }
4476 /*
4477 * The return value of merge_ort_recursive() is 1 on clean, and 0 on
4478 * unclean merge.
4479 *
4480 * Let's reverse that, so that do_merge() returns 0 upon success and
4481 * 1 upon failed merge (keeping the return value -1 for the cases where
4482 * we will want to reschedule the `merge` command).
4483 */
4484 ret = !ret;
4485
4486 if (r->index->cache_changed &&
4487 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4488 ret = error(_("merge: Unable to write new index file"));
4489 goto leave_merge;
4490 }
4491
4492 rollback_lock_file(&lock);
4493 if (ret)
4494 repo_rerere(r, opts->allow_rerere_auto);
4495 else
4496 /*
4497 * In case of problems, we now want to return a positive
4498 * value (a negative one would indicate that the `merge`
4499 * command needs to be rescheduled).
4500 */
4501 ret = !!run_git_commit(git_path_merge_msg(r), reflog_action,
4502 opts, run_commit_flags);
4503
4504 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4505 fast_forward_edit:
4506 *check_todo = 1;
4507 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4508 ret = !!run_git_commit(NULL, reflog_action, opts,
4509 run_commit_flags);
4510 }
4511
4512
4513leave_merge:
4514 strbuf_release(&ref_name);
4515 rollback_lock_file(&lock);
4516 commit_list_free(to_merge);
4517 commit_list_free(bases);
4518 return ret;
4519}
4520
4521static int write_update_refs_state(struct string_list *refs_to_oids)
4522{
4523 int result = 0;
4524 struct lock_file lock = LOCK_INIT;
4525 FILE *fp = NULL;
4526 struct string_list_item *item;
4527 char *path;
4528
4529 path = rebase_path_update_refs(the_repository->gitdir);
4530
4531 if (!refs_to_oids->nr) {
4532 if (unlink(path) && errno != ENOENT)
4533 result = error_errno(_("could not unlink: %s"), path);
4534 goto cleanup;
4535 }
4536
4537 if (safe_create_leading_directories(the_repository, path)) {
4538 result = error(_("unable to create leading directories of %s"),
4539 path);
4540 goto cleanup;
4541 }
4542
4543 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4544 result = error(_("another 'rebase' process appears to be running; "
4545 "'%s.lock' already exists"),
4546 path);
4547 goto cleanup;
4548 }
4549
4550 fp = fdopen_lock_file(&lock, "w");
4551 if (!fp) {
4552 result = error_errno(_("could not open '%s' for writing"), path);
4553 rollback_lock_file(&lock);
4554 goto cleanup;
4555 }
4556
4557 for_each_string_list_item(item, refs_to_oids) {
4558 struct update_ref_record *rec = item->util;
4559 fprintf(fp, "%s\n%s\n%s\n", item->string,
4560 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4561 }
4562
4563 result = commit_lock_file(&lock);
4564
4565cleanup:
4566 free(path);
4567 return result;
4568}
4569
4570/*
4571 * Parse the update-refs file for the current rebase, then remove the
4572 * refs that do not appear in the todo_list (and have not had updated
4573 * values stored) and add refs that are in the todo_list but not
4574 * represented in the update-refs file.
4575 *
4576 * If there are changes to the update-refs list, then write the new state
4577 * to disk.
4578 */
4579void todo_list_filter_update_refs(struct repository *r,
4580 struct todo_list *todo_list)
4581{
4582 int i;
4583 int updated = 0;
4584 struct string_list update_refs = STRING_LIST_INIT_DUP;
4585
4586 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4587
4588 /*
4589 * For each item in the update_refs list, if it has no updated
4590 * value and does not appear in the todo_list, then remove it
4591 * from the update_refs list.
4592 */
4593 for (i = 0; i < update_refs.nr; i++) {
4594 int j;
4595 int found = 0;
4596 const char *ref = update_refs.items[i].string;
4597 size_t reflen = strlen(ref);
4598 struct update_ref_record *rec = update_refs.items[i].util;
4599
4600 /* OID already stored as updated. */
4601 if (!is_null_oid(&rec->after))
4602 continue;
4603
4604 for (j = 0; !found && j < todo_list->nr; j++) {
4605 struct todo_item *item = &todo_list->items[j];
4606 const char *arg = todo_list->buf.buf + item->arg_offset;
4607
4608 if (item->command != TODO_UPDATE_REF)
4609 continue;
4610
4611 if (item->arg_len != reflen ||
4612 strncmp(arg, ref, reflen))
4613 continue;
4614
4615 found = 1;
4616 }
4617
4618 if (!found) {
4619 free(update_refs.items[i].string);
4620 free(update_refs.items[i].util);
4621
4622 update_refs.nr--;
4623 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4624
4625 updated = 1;
4626 i--;
4627 }
4628 }
4629
4630 /*
4631 * For each todo_item, check if its ref is in the update_refs list.
4632 * If not, then add it as an un-updated ref.
4633 */
4634 for (i = 0; i < todo_list->nr; i++) {
4635 struct todo_item *item = &todo_list->items[i];
4636 const char *arg = todo_list->buf.buf + item->arg_offset;
4637 int j, found = 0;
4638
4639 if (item->command != TODO_UPDATE_REF)
4640 continue;
4641
4642 for (j = 0; !found && j < update_refs.nr; j++) {
4643 const char *ref = update_refs.items[j].string;
4644
4645 found = strlen(ref) == item->arg_len &&
4646 !strncmp(ref, arg, item->arg_len);
4647 }
4648
4649 if (!found) {
4650 struct string_list_item *inserted;
4651 struct strbuf argref = STRBUF_INIT;
4652
4653 strbuf_add(&argref, arg, item->arg_len);
4654 inserted = string_list_insert(&update_refs, argref.buf);
4655 inserted->util = init_update_ref_record(argref.buf);
4656 strbuf_release(&argref);
4657 updated = 1;
4658 }
4659 }
4660
4661 if (updated)
4662 write_update_refs_state(&update_refs);
4663 string_list_clear(&update_refs, 1);
4664}
4665
4666static int do_update_ref(struct repository *r, const char *refname)
4667{
4668 struct string_list_item *item;
4669 struct string_list list = STRING_LIST_INIT_DUP;
4670
4671 if (sequencer_get_update_refs_state(r->gitdir, &list))
4672 return -1;
4673
4674 for_each_string_list_item(item, &list) {
4675 if (!strcmp(item->string, refname)) {
4676 struct update_ref_record *rec = item->util;
4677 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4678 return -1;
4679 break;
4680 }
4681 }
4682
4683 write_update_refs_state(&list);
4684 string_list_clear(&list, 1);
4685 return 0;
4686}
4687
4688static int do_update_refs(struct repository *r, int quiet)
4689{
4690 int res = 0;
4691 struct string_list_item *item;
4692 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4693 struct ref_store *refs = get_main_ref_store(r);
4694 struct strbuf update_msg = STRBUF_INIT;
4695 struct strbuf error_msg = STRBUF_INIT;
4696
4697 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4698 return res;
4699
4700 for_each_string_list_item(item, &refs_to_oids) {
4701 struct update_ref_record *rec = item->util;
4702 int loop_res;
4703
4704 loop_res = refs_update_ref(refs, "rewritten during rebase",
4705 item->string,
4706 &rec->after, &rec->before,
4707 0, UPDATE_REFS_MSG_ON_ERR);
4708 res |= loop_res;
4709
4710 if (quiet)
4711 continue;
4712
4713 if (loop_res)
4714 strbuf_addf(&error_msg, "\t%s\n", item->string);
4715 else
4716 strbuf_addf(&update_msg, "\t%s\n", item->string);
4717 }
4718
4719 if (!quiet &&
4720 (update_msg.len || error_msg.len)) {
4721 fprintf(stderr,
4722 _("Updated the following refs with %s:\n%s"),
4723 "--update-refs",
4724 update_msg.buf);
4725
4726 if (res)
4727 fprintf(stderr,
4728 _("Failed to update the following refs with %s:\n%s"),
4729 "--update-refs",
4730 error_msg.buf);
4731 }
4732
4733 string_list_clear(&refs_to_oids, 1);
4734 strbuf_release(&update_msg);
4735 strbuf_release(&error_msg);
4736 return res;
4737}
4738
4739static int is_final_fixup(struct todo_list *todo_list)
4740{
4741 int i = todo_list->current;
4742
4743 if (!is_fixup(todo_list->items[i].command))
4744 return 0;
4745
4746 while (++i < todo_list->nr)
4747 if (is_fixup(todo_list->items[i].command))
4748 return 0;
4749 else if (!is_noop(todo_list->items[i].command))
4750 break;
4751 return 1;
4752}
4753
4754static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4755{
4756 int i;
4757
4758 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4759 if (!is_noop(todo_list->items[i].command))
4760 return todo_list->items[i].command;
4761
4762 return -1;
4763}
4764
4765static void create_autostash_internal(struct repository *r,
4766 const char *path,
4767 const char *refname,
4768 const char *message,
4769 bool silent)
4770{
4771 struct strbuf buf = STRBUF_INIT;
4772 struct lock_file lock_file = LOCK_INIT;
4773 int fd;
4774
4775 if (path && refname)
4776 BUG("can only pass path or refname");
4777
4778 fd = repo_hold_locked_index(r, &lock_file, 0);
4779 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4780 if (0 <= fd)
4781 repo_update_index_if_able(r, &lock_file);
4782 rollback_lock_file(&lock_file);
4783
4784 if (has_unstaged_changes(r, 1) ||
4785 has_uncommitted_changes(r, 1)) {
4786 struct child_process stash = CHILD_PROCESS_INIT;
4787 struct reset_working_tree_options ropts = {
4788 .flags = RESET_WORKING_TREE_HARD |
4789 RESET_WORKING_TREE_UPDATE_HEAD,
4790 };
4791 struct object_id oid;
4792
4793 strvec_pushl(&stash.args,
4794 "stash", "create",
4795 message ? message : "autostash", NULL);
4796 stash.git_cmd = 1;
4797 stash.no_stdin = 1;
4798 strbuf_reset(&buf);
4799 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4800 die(_("Cannot autostash"));
4801 strbuf_trim_trailing_newline(&buf);
4802 if (repo_get_oid(r, buf.buf, &oid))
4803 die(_("Unexpected stash response: '%s'"),
4804 buf.buf);
4805 strbuf_reset(&buf);
4806 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4807
4808 if (path) {
4809 if (safe_create_leading_directories_const(the_repository, path))
4810 die(_("Could not create directory for '%s'"),
4811 path);
4812 write_file(path, "%s", oid_to_hex(&oid));
4813 } else {
4814 refs_update_ref(get_main_ref_store(r), "", refname,
4815 &oid, null_oid(the_hash_algo), 0, UPDATE_REFS_DIE_ON_ERR);
4816 }
4817
4818 if (!silent)
4819 printf(_("Created autostash: %s\n"), buf.buf);
4820 if (reset_working_tree(r, &ropts) < 0)
4821 die(_("could not reset --hard"));
4822 discard_index(r->index);
4823 if (repo_read_index(r) < 0)
4824 die(_("could not read index"));
4825 }
4826 strbuf_release(&buf);
4827}
4828
4829void create_autostash(struct repository *r, const char *path)
4830{
4831 create_autostash_internal(r, path, NULL, NULL, false);
4832}
4833
4834void create_autostash_ref(struct repository *r, const char *refname,
4835 const char *message, bool silent)
4836{
4837 create_autostash_internal(r, NULL, refname, message, silent);
4838}
4839
4840static enum stash_apply_result do_stash_apply(const char *stash_oid,
4841 const char *label_ours,
4842 const char *label_theirs,
4843 const char *label_base)
4844{
4845 struct child_process child = CHILD_PROCESS_INIT;
4846
4847 child.git_cmd = 1;
4848 child.no_stdout = 1;
4849 child.no_stderr = 1;
4850 strvec_push(&child.args, "stash");
4851 strvec_push(&child.args, "apply");
4852 if (label_ours)
4853 strvec_pushf(&child.args, "--label-ours=%s", label_ours);
4854 if (label_theirs)
4855 strvec_pushf(&child.args, "--label-theirs=%s", label_theirs);
4856 if (label_base)
4857 strvec_pushf(&child.args, "--label-base=%s", label_base);
4858 strvec_push(&child.args, stash_oid);
4859
4860 switch (run_command(&child)) {
4861 case 0:
4862 return STASH_APPLY_CLEAN;
4863 case STASH_APPLY_CONFLICT:
4864 return STASH_APPLY_CONFLICT;
4865 default:
4866 return STASH_APPLY_ERROR;
4867 }
4868}
4869
4870static enum stash_apply_result apply_save_autostash_oid(const char *stash_oid,
4871 int attempt_apply,
4872 const char *label_ours,
4873 const char *label_theirs,
4874 const char *label_base,
4875 const char *stash_msg)
4876{
4877 enum stash_apply_result ret = STASH_APPLY_CLEAN;
4878
4879 if (attempt_apply)
4880 ret = do_stash_apply(stash_oid, label_ours, label_theirs,
4881 label_base);
4882
4883 if (attempt_apply && ret == STASH_APPLY_CLEAN)
4884 fprintf(stderr, _("Applied autostash.\n"));
4885 else {
4886 struct child_process store = CHILD_PROCESS_INIT;
4887
4888 store.git_cmd = 1;
4889 strvec_push(&store.args, "stash");
4890 strvec_push(&store.args, "store");
4891 strvec_push(&store.args, "-m");
4892 strvec_push(&store.args, stash_msg ? stash_msg : "autostash");
4893 strvec_push(&store.args, "-q");
4894 strvec_push(&store.args, stash_oid);
4895 if (run_command(&store))
4896 ret = error(_("cannot store %s"), stash_oid);
4897 else if (attempt_apply && ret == STASH_APPLY_CONFLICT)
4898 fprintf(stderr,
4899 _("Your local changes are stashed, however applying them\n"
4900 "resulted in conflicts. You can either resolve the conflicts\n"
4901 "and then discard the stash with \"git stash drop\", or, if you\n"
4902 "do not want to resolve them now, run \"git reset --hard\" and\n"
4903 "apply the local changes later by running \"git stash pop\".\n"));
4904 else if (attempt_apply)
4905 ret = error(_("could not apply autostash; "
4906 "your changes are safe in the stash"));
4907 else
4908 fprintf(stderr,
4909 _("Autostash exists; creating a new stash entry.\n"
4910 "Your changes are safe in the stash.\n"
4911 "You can run \"git stash pop\" or"
4912 " \"git stash drop\" at any time.\n"));
4913 }
4914
4915 return ret;
4916}
4917
4918static enum stash_apply_result apply_save_autostash(const char *path,
4919 int attempt_apply)
4920{
4921 struct strbuf stash_oid = STRBUF_INIT;
4922 enum stash_apply_result ret = STASH_APPLY_CLEAN;
4923
4924 if (!read_oneliner(&stash_oid, path,
4925 READ_ONELINER_SKIP_IF_EMPTY)) {
4926 strbuf_release(&stash_oid);
4927 return STASH_APPLY_CLEAN;
4928 }
4929 strbuf_trim(&stash_oid);
4930
4931 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply,
4932 NULL, NULL, NULL, NULL);
4933
4934 unlink(path);
4935 strbuf_release(&stash_oid);
4936 return ret;
4937}
4938
4939enum stash_apply_result save_autostash(const char *path)
4940{
4941 return apply_save_autostash(path, 0);
4942}
4943
4944enum stash_apply_result apply_autostash(const char *path)
4945{
4946 return apply_save_autostash(path, 1);
4947}
4948
4949enum stash_apply_result apply_autostash_oid(const char *stash_oid)
4950{
4951 return apply_save_autostash_oid(stash_oid, 1, NULL, NULL, NULL, NULL);
4952}
4953
4954static enum stash_apply_result apply_save_autostash_ref(struct repository *r,
4955 const char *refname,
4956 int attempt_apply,
4957 const char *label_ours,
4958 const char *label_theirs,
4959 const char *label_base,
4960 const char *stash_msg)
4961{
4962 struct object_id stash_oid;
4963 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4964 int flag;
4965 enum stash_apply_result ret;
4966
4967 if (!refs_ref_exists(get_main_ref_store(r), refname))
4968 return STASH_APPLY_CLEAN;
4969
4970 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4971 RESOLVE_REF_READING, &stash_oid, &flag))
4972 return STASH_APPLY_ERROR;
4973 if (flag & REF_ISSYMREF)
4974 return error(_("autostash reference is a symref"));
4975
4976 oid_to_hex_r(stash_oid_hex, &stash_oid);
4977 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply,
4978 label_ours, label_theirs, label_base,
4979 stash_msg);
4980
4981 refs_delete_ref(get_main_ref_store(r), "", refname,
4982 &stash_oid, REF_NO_DEREF);
4983
4984 return ret;
4985}
4986
4987enum stash_apply_result save_autostash_ref(struct repository *r,
4988 const char *refname)
4989{
4990 return apply_save_autostash_ref(r, refname, 0,
4991 NULL, NULL, NULL, NULL);
4992}
4993
4994enum stash_apply_result apply_autostash_ref(struct repository *r,
4995 const char *refname,
4996 const char *label_ours,
4997 const char *label_theirs,
4998 const char *label_base,
4999 const char *stash_msg)
5000{
5001 return apply_save_autostash_ref(r, refname, 1,
5002 label_ours, label_theirs, label_base,
5003 stash_msg);
5004}
5005
5006static int checkout_onto(struct repository *r, struct replay_opts *opts,
5007 const char *onto_name, const struct object_id *onto,
5008 const struct object_id *orig_head)
5009{
5010 struct reset_working_tree_options ropts = {
5011 .oid = onto,
5012 .orig_head = orig_head,
5013 .flags = RESET_WORKING_TREE_DETACH |
5014 RESET_WORKING_TREE_UPDATE_HEAD |
5015 RESET_WORKING_TREE_UPDATE_ORIG_HEAD |
5016 RESET_WORKING_TREE_RUN_POST_CHECKOUT_HOOK,
5017 .head_msg = reflog_message(opts, "start", "checkout %s",
5018 onto_name),
5019 .default_reflog_action = sequencer_reflog_action(opts)
5020 };
5021 if (reset_working_tree(r, &ropts)) {
5022 apply_autostash(rebase_path_autostash());
5023 sequencer_remove_state(opts);
5024 return error(_("could not detach HEAD"));
5025 }
5026
5027 return 0;
5028}
5029
5030static int stopped_at_head(struct repository *r)
5031{
5032 struct object_id head;
5033 struct commit *commit;
5034 struct commit_message message;
5035
5036 if (repo_get_oid(r, "HEAD", &head) ||
5037 !(commit = lookup_commit(r, &head)) ||
5038 repo_parse_commit(r, commit) || get_message(commit, &message))
5039 fprintf(stderr, _("Stopped at HEAD\n"));
5040 else {
5041 fprintf(stderr, _("Stopped at %s\n"), message.label);
5042 free_message(commit, &message);
5043 }
5044 return 0;
5045
5046}
5047
5048static int reread_todo_if_changed(struct repository *r,
5049 struct todo_list *todo_list,
5050 struct replay_opts *opts)
5051{
5052 int offset;
5053 struct strbuf buf = STRBUF_INIT;
5054
5055 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
5056 return -1;
5057 offset = get_item_line_offset(todo_list, todo_list->current + 1);
5058 if (buf.len != todo_list->buf.len - offset ||
5059 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
5060 /* Reread the todo file if it has changed. */
5061 todo_list_release(todo_list);
5062 if (read_populate_todo(r, todo_list, opts))
5063 return -1; /* message was printed */
5064 /* `current` will be incremented on return */
5065 todo_list->current = -1;
5066 }
5067 strbuf_release(&buf);
5068
5069 return 0;
5070}
5071
5072static const char rescheduled_advice[] =
5073N_("Could not execute the todo command\n"
5074"\n"
5075" %.*s"
5076"\n"
5077"It has been rescheduled; To edit the command before continuing, please\n"
5078"edit the todo list first:\n"
5079"\n"
5080" git rebase --edit-todo\n"
5081" git rebase --continue\n");
5082
5083static int pick_one_commit(struct repository *r,
5084 struct todo_list *todo_list,
5085 struct replay_opts *opts,
5086 int *check_todo, int* reschedule)
5087{
5088 enum pick_result pick_res;
5089 struct todo_item *item = todo_list->items + todo_list->current;
5090 const char *arg = todo_item_get_arg(todo_list, item);
5091
5092 pick_res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
5093 check_todo);
5094 if (!is_rebase_i(opts))
5095 switch (pick_res) {
5096 case PICK_RESULT_ERROR:
5097 return -1;
5098 case PICK_RESULT_CONFLICTS:
5099 return 1;
5100 default:
5101 return 0;
5102 }
5103
5104 if (pick_res == PICK_RESULT_ERROR) {
5105 /* Reschedule */
5106 *reschedule = 1;
5107 return -1;
5108 } else if (item->command == TODO_EDIT) {
5109 struct commit *commit = item->commit;
5110 int res = pick_res == PICK_RESULT_CONFLICTS;
5111 int to_amend = pick_res != PICK_RESULT_CONFLICTS &&
5112 pick_res != PICK_RESULT_DROPPED;
5113
5114 /*
5115 * NEEDSWORK: Do not record the commit as rewritten when
5116 * continuing if it was dropped. Does it even make sense
5117 * to stop if the commit was dropped?
5118 */
5119 if (pick_res == PICK_RESULT_OK ||
5120 pick_res == PICK_RESULT_DROPPED) {
5121 if (!opts->verbose)
5122 term_clear_line();
5123 fprintf(stderr, _("Stopped at %s... %.*s\n"),
5124 short_commit_name(r, commit), item->arg_len, arg);
5125 }
5126 return error_with_patch(r, commit, arg, item->arg_len, opts,
5127 res, to_amend);
5128 } else if (pick_res == PICK_RESULT_OK) {
5129 record_in_rewritten(&item->commit->object.oid,
5130 peek_command(todo_list, 1));
5131 return 0;
5132 } else if (pick_res == PICK_RESULT_DROPPED) {
5133 if (is_final_fixup(todo_list))
5134 flush_rewritten_pending();
5135 return 0;
5136 } else if (pick_res == PICK_RESULT_CONFLICTS &&
5137 is_fixup(item->command)) {
5138 return error_failed_squash(r, item->commit, opts,
5139 item->arg_len, arg);
5140 } else if (pick_res == PICK_RESULT_CONFLICTS) {
5141 int to_amend = 0;
5142 struct object_id oid;
5143
5144 /*
5145 * If we are rewording and have either
5146 * fast-forwarded already, or are about to
5147 * create a new root commit, we want to amend,
5148 * otherwise we do not.
5149 */
5150 if (item->command == TODO_REWORD &&
5151 !repo_get_oid(r, "HEAD", &oid) &&
5152 (oideq(&item->commit->object.oid, &oid) ||
5153 (opts->have_squash_onto &&
5154 oideq(&opts->squash_onto, &oid))))
5155 to_amend = 1;
5156
5157 return error_with_patch(r, item->commit, arg, item->arg_len,
5158 opts, 1, to_amend);
5159 }
5160
5161 BUG("Unhandled return value from do_pick_commit()");
5162}
5163
5164static int pick_commits(struct repository *r,
5165 struct todo_list *todo_list,
5166 struct replay_opts *opts)
5167{
5168 struct replay_ctx *ctx = opts->ctx;
5169 int res = 0, reschedule = 0;
5170
5171 if (opts->allow_ff)
5172 ASSERT(!(opts->signoff || opts->no_commit ||
5173 opts->record_origin || should_edit(opts) ||
5174 opts->committer_date_is_author_date ||
5175 opts->ignore_date));
5176 if (read_and_refresh_cache(r, opts))
5177 return -1;
5178
5179 unlink(rebase_path_message());
5180 unlink(rebase_path_stopped_sha());
5181 unlink(rebase_path_amend());
5182 unlink(rebase_path_patch());
5183 unlink(git_path_merge_labels(r));
5184 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE", NULL,
5185 REF_NO_DEREF);
5186 refs_delete_ref(get_main_ref_store(r), "", "REBASE_HEAD", NULL,
5187 REF_NO_DEREF);
5188
5189 while (todo_list->current < todo_list->nr) {
5190 struct todo_item *item = todo_list->items + todo_list->current;
5191 const char *arg = todo_item_get_arg(todo_list, item);
5192 int check_todo = 0;
5193
5194 if (save_todo(todo_list, opts, reschedule))
5195 return -1;
5196 if (is_rebase_i(opts)) {
5197 if (item->command != TODO_COMMENT) {
5198 FILE *f = fopen(rebase_path_msgnum(), "w");
5199
5200 todo_list->done_nr++;
5201
5202 if (f) {
5203 fprintf(f, "%d\n", todo_list->done_nr);
5204 fclose(f);
5205 }
5206 if (!opts->quiet)
5207 fprintf(stderr, _("Rebasing (%d/%d)%s"),
5208 todo_list->done_nr,
5209 todo_list->total_nr,
5210 opts->verbose ? "\n" : "\r");
5211 }
5212 unlink(rebase_path_author_script());
5213 unlink(git_path_merge_head(r));
5214
5215 if (item->command == TODO_BREAK) {
5216 if (!opts->verbose)
5217 term_clear_line();
5218 return stopped_at_head(r);
5219 }
5220 }
5221 strbuf_reset(&ctx->message);
5222 ctx->have_message = 0;
5223 if (item->command <= TODO_SQUASH) {
5224 res = pick_one_commit(r, todo_list, opts, &check_todo,
5225 &reschedule);
5226 if (!res && item->command == TODO_EDIT)
5227 return 0;
5228 } else if (item->command == TODO_EXEC) {
5229 char *end_of_arg = (char *)(arg + item->arg_len);
5230 int saved = *end_of_arg;
5231
5232 if (!opts->verbose)
5233 term_clear_line();
5234 *end_of_arg = '\0';
5235 res = do_exec(r, arg, opts);
5236 *end_of_arg = saved;
5237
5238 if (res) {
5239 if (opts->reschedule_failed_exec)
5240 reschedule = 1;
5241 }
5242 check_todo = 1;
5243 } else if (item->command == TODO_LABEL) {
5244 if ((res = do_label(r, arg, item->arg_len)))
5245 reschedule = 1;
5246 } else if (item->command == TODO_RESET) {
5247 if ((res = do_reset(r, arg, item->arg_len, opts)))
5248 reschedule = 1;
5249 } else if (item->command == TODO_MERGE) {
5250 if ((res = do_merge(r, item->commit, arg, item->arg_len,
5251 item->flags, &check_todo, opts)) < 0)
5252 reschedule = 1;
5253 else if (item->commit)
5254 record_in_rewritten(&item->commit->object.oid,
5255 peek_command(todo_list, 1));
5256 if (res > 0)
5257 /* failed with merge conflicts */
5258 return error_with_patch(r, item->commit,
5259 arg, item->arg_len,
5260 opts, res, 0);
5261 } else if (item->command == TODO_UPDATE_REF) {
5262 struct strbuf ref = STRBUF_INIT;
5263 strbuf_add(&ref, arg, item->arg_len);
5264 if ((res = do_update_ref(r, ref.buf)))
5265 reschedule = 1;
5266 strbuf_release(&ref);
5267 } else if (!is_noop(item->command))
5268 return error(_("unknown command %d"), item->command);
5269
5270 if (reschedule) {
5271 advise(_(rescheduled_advice),
5272 get_item_line_length(todo_list,
5273 todo_list->current),
5274 get_item_line(todo_list, todo_list->current));
5275 if (save_todo(todo_list, opts, reschedule))
5276 return -1;
5277 if (item->commit)
5278 write_rebase_head(&item->commit->object.oid);
5279 } else if (is_rebase_i(opts) && check_todo && !res &&
5280 reread_todo_if_changed(r, todo_list, opts)) {
5281 return -1;
5282 }
5283
5284 if (res)
5285 return res;
5286
5287 todo_list->current++;
5288 }
5289
5290 if (is_rebase_i(opts)) {
5291 struct strbuf head_ref = STRBUF_INIT, buf = STRBUF_INIT;
5292 struct stat st;
5293
5294 if (read_oneliner(&head_ref, rebase_path_head_name(), 0) &&
5295 starts_with(head_ref.buf, "refs/")) {
5296 const char *msg;
5297 struct object_id head, orig;
5298 int res;
5299
5300 if (repo_get_oid(r, "HEAD", &head)) {
5301 res = error(_("cannot read HEAD"));
5302cleanup_head_ref:
5303 strbuf_release(&head_ref);
5304 strbuf_release(&buf);
5305 return res;
5306 }
5307 if (!read_oneliner(&buf, rebase_path_orig_head(), 0) ||
5308 get_oid_hex(buf.buf, &orig)) {
5309 res = error(_("could not read orig-head"));
5310 goto cleanup_head_ref;
5311 }
5312 strbuf_reset(&buf);
5313 if (!read_oneliner(&buf, rebase_path_onto(), 0)) {
5314 res = error(_("could not read 'onto'"));
5315 goto cleanup_head_ref;
5316 }
5317 msg = reflog_message(opts, "finish", "%s onto %s",
5318 head_ref.buf, buf.buf);
5319 if (refs_update_ref(get_main_ref_store(the_repository), msg, head_ref.buf, &head, &orig,
5320 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR)) {
5321 res = error(_("could not update %s"),
5322 head_ref.buf);
5323 goto cleanup_head_ref;
5324 }
5325 msg = reflog_message(opts, "finish", "returning to %s",
5326 head_ref.buf);
5327 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", head_ref.buf, msg)) {
5328 res = error(_("could not update HEAD to %s"),
5329 head_ref.buf);
5330 goto cleanup_head_ref;
5331 }
5332 strbuf_reset(&buf);
5333 }
5334
5335 if (opts->verbose) {
5336 struct rev_info log_tree_opt;
5337 struct object_id orig, head;
5338
5339 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
5340 repo_init_revisions(r, &log_tree_opt, NULL);
5341 log_tree_opt.diff = 1;
5342 log_tree_opt.diffopt.output_format =
5343 DIFF_FORMAT_DIFFSTAT;
5344 log_tree_opt.disable_stdin = 1;
5345
5346 if (read_oneliner(&buf, rebase_path_orig_head(), 0) &&
5347 !repo_get_oid(r, buf.buf, &orig) &&
5348 !repo_get_oid(r, "HEAD", &head)) {
5349 diff_tree_oid(&orig, &head, "",
5350 &log_tree_opt.diffopt);
5351 log_tree_diff_flush(&log_tree_opt);
5352 }
5353 release_revisions(&log_tree_opt);
5354 }
5355 flush_rewritten_pending();
5356 if (!stat(rebase_path_rewritten_list(), &st) &&
5357 st.st_size > 0) {
5358 struct child_process child = CHILD_PROCESS_INIT;
5359 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
5360
5361 child.in = open(rebase_path_rewritten_list(), O_RDONLY);
5362 child.git_cmd = 1;
5363 strvec_push(&child.args, "notes");
5364 strvec_push(&child.args, "copy");
5365 strvec_push(&child.args, "--for-rewrite=rebase");
5366 /* we don't care if this copying failed */
5367 run_command(&child);
5368
5369 hook_opt.path_to_stdin = rebase_path_rewritten_list();
5370 strvec_push(&hook_opt.args, "rebase");
5371 run_hooks_opt(r, "post-rewrite", &hook_opt);
5372 }
5373 apply_autostash(rebase_path_autostash());
5374
5375 if (!opts->quiet) {
5376 if (!opts->verbose)
5377 term_clear_line();
5378 fprintf(stderr,
5379 _("Successfully rebased and updated %s.\n"),
5380 head_ref.buf);
5381 }
5382
5383 strbuf_release(&buf);
5384 strbuf_release(&head_ref);
5385
5386 if (do_update_refs(r, opts->quiet))
5387 return -1;
5388 }
5389
5390 /*
5391 * Sequence of picks finished successfully; cleanup by
5392 * removing the .git/sequencer directory
5393 */
5394 return sequencer_remove_state(opts);
5395}
5396
5397static int continue_single_pick(struct repository *r, struct replay_opts *opts)
5398{
5399 struct child_process cmd = CHILD_PROCESS_INIT;
5400
5401 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
5402 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
5403 return error(_("no cherry-pick or revert in progress"));
5404
5405 cmd.git_cmd = 1;
5406 disable_auto_maintenance(opts, &cmd);
5407 strvec_push(&cmd.args, "commit");
5408
5409 /*
5410 * continue_single_pick() handles the case of recovering from a
5411 * conflict. should_edit() doesn't handle that case; for a conflict,
5412 * we want to edit if the user asked for it, or if they didn't specify
5413 * and stdin is a tty.
5414 */
5415 if (!opts->edit || (opts->edit < 0 && !isatty(0)))
5416 /*
5417 * Include --cleanup=strip as well because we don't want the
5418 * "# Conflicts:" messages.
5419 */
5420 strvec_pushl(&cmd.args, "--no-edit", "--cleanup=strip", NULL);
5421
5422 return run_command(&cmd);
5423}
5424
5425static int commit_staged_changes(struct repository *r,
5426 struct replay_opts *opts,
5427 struct todo_list *todo_list)
5428{
5429 struct replay_ctx *ctx = opts->ctx;
5430 unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
5431 unsigned int final_fixup = 0, is_clean;
5432 struct strbuf rev = STRBUF_INIT;
5433 const char *reflog_action = reflog_message(opts, "continue", NULL);
5434 int ret;
5435
5436 if (has_unstaged_changes(r, 1)) {
5437 ret = error(_("cannot rebase: You have unstaged changes."));
5438 goto out;
5439 }
5440
5441 is_clean = !has_uncommitted_changes(r, 0);
5442
5443 if (!is_clean && !file_exists(rebase_path_message())) {
5444 const char *gpg_opt = gpg_sign_opt_quoted(opts);
5445 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
5446 goto out;
5447 }
5448
5449 if (file_exists(rebase_path_amend())) {
5450 struct object_id head, to_amend;
5451
5452 if (repo_get_oid(r, "HEAD", &head)) {
5453 ret = error(_("cannot amend non-existing commit"));
5454 goto out;
5455 }
5456
5457 if (!read_oneliner(&rev, rebase_path_amend(), 0)) {
5458 ret = error(_("invalid file: '%s'"), rebase_path_amend());
5459 goto out;
5460 }
5461
5462 if (get_oid_hex(rev.buf, &to_amend)) {
5463 ret = error(_("invalid contents: '%s'"),
5464 rebase_path_amend());
5465 goto out;
5466 }
5467 if (!is_clean && !oideq(&head, &to_amend)) {
5468 ret = error(_("\nYou have uncommitted changes in your "
5469 "working tree. Please, commit them\n"
5470 "first and then run 'git rebase "
5471 "--continue' again."));
5472 goto out;
5473 }
5474 /*
5475 * When skipping a failed fixup/squash, we need to edit the
5476 * commit message, the current fixup list and count, and if it
5477 * was the last fixup/squash in the chain, we need to clean up
5478 * the commit message and if there was a squash, let the user
5479 * edit it.
5480 */
5481 if (!is_clean || !ctx->current_fixup_count)
5482 ; /* this is not the final fixup */
5483 else if (!oideq(&head, &to_amend) ||
5484 !file_exists(rebase_path_stopped_sha())) {
5485 /* was a final fixup or squash done manually? */
5486 if (!is_fixup(peek_command(todo_list, 0))) {
5487 unlink(rebase_path_fixup_msg());
5488 unlink(rebase_path_squash_msg());
5489 unlink(rebase_path_current_fixups());
5490 strbuf_reset(&ctx->current_fixups);
5491 ctx->current_fixup_count = 0;
5492 }
5493 } else {
5494 /* we are in a fixup/squash chain */
5495 const char *p = ctx->current_fixups.buf;
5496 int len = ctx->current_fixups.len;
5497
5498 ctx->current_fixup_count--;
5499 if (!len)
5500 BUG("Incorrect current_fixups:\n%s", p);
5501 while (len && p[len - 1] != '\n')
5502 len--;
5503 /* Remove trailing newline */
5504 if (len)
5505 len--;
5506 strbuf_setlen(&ctx->current_fixups, len);
5507 if (write_message(p, len, rebase_path_current_fixups(),
5508 0) < 0) {
5509 ret = error(_("could not write file: '%s'"),
5510 rebase_path_current_fixups());
5511 goto out;
5512 }
5513
5514 /*
5515 * If a fixup/squash in a fixup/squash chain failed, the
5516 * commit message is already correct, no need to commit
5517 * it again.
5518 *
5519 * Only if it is the final command in the fixup/squash
5520 * chain, and only if the chain is longer than a single
5521 * fixup/squash command (which was just skipped), do we
5522 * actually need to re-commit with a cleaned up commit
5523 * message.
5524 */
5525 if (ctx->current_fixup_count > 0 &&
5526 !is_fixup(peek_command(todo_list, 0))) {
5527 final_fixup = 1;
5528 /*
5529 * If there was not a single "squash" in the
5530 * chain, we only need to clean up the commit
5531 * message, no need to bother the user with
5532 * opening the commit message in the editor.
5533 */
5534 if (!seen_squash(ctx) &&
5535 !seen_fixup_edit_msg(ctx))
5536 flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
5537 } else if (is_fixup(peek_command(todo_list, 0))) {
5538 /*
5539 * We need to update the squash message to skip
5540 * the latest commit message.
5541 */
5542 struct commit *commit;
5543 const char *msg;
5544 const char *path = rebase_path_squash_msg();
5545 const char *encoding = get_commit_output_encoding();
5546
5547 if (parse_head(r, &commit)) {
5548 ret = error(_("could not parse HEAD"));
5549 goto out;
5550 }
5551
5552 p = repo_logmsg_reencode(r, commit, NULL, encoding);
5553 if (!p) {
5554 ret = error(_("could not parse commit %s"),
5555 oid_to_hex(&commit->object.oid));
5556 goto unuse_commit_buffer;
5557 }
5558 find_commit_subject(p, &msg);
5559 if (write_message(msg, strlen(msg), path, 0)) {
5560 ret = error(_("could not write file: "
5561 "'%s'"), path);
5562 goto unuse_commit_buffer;
5563 }
5564
5565 ret = 0;
5566
5567 unuse_commit_buffer:
5568 repo_unuse_commit_buffer(r, commit, p);
5569 if (ret)
5570 goto out;
5571 }
5572 }
5573
5574 flags |= AMEND_MSG;
5575 }
5576
5577 if (is_clean) {
5578 if (refs_ref_exists(get_main_ref_store(r),
5579 "CHERRY_PICK_HEAD") &&
5580 refs_delete_ref(get_main_ref_store(r), "",
5581 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF)) {
5582 ret = error(_("could not remove CHERRY_PICK_HEAD"));
5583 goto out;
5584 }
5585
5586 if (unlink(git_path_merge_msg(r)) && errno != ENOENT) {
5587 ret = error_errno(_("could not remove '%s'"),
5588 git_path_merge_msg(r));
5589 goto out;
5590 }
5591
5592 if (!final_fixup) {
5593 ret = 0;
5594 goto out;
5595 }
5596 }
5597
5598 if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
5599 reflog_action, opts, flags)) {
5600 ret = error(_("could not commit staged changes."));
5601 goto out;
5602 }
5603
5604 unlink(rebase_path_amend());
5605 unlink(git_path_merge_head(r));
5606 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
5607 NULL, REF_NO_DEREF);
5608 if (final_fixup) {
5609 unlink(rebase_path_fixup_msg());
5610 unlink(rebase_path_squash_msg());
5611 }
5612 if (ctx->current_fixup_count > 0) {
5613 /*
5614 * Whether final fixup or not, we just cleaned up the commit
5615 * message...
5616 */
5617 unlink(rebase_path_current_fixups());
5618 strbuf_reset(&ctx->current_fixups);
5619 ctx->current_fixup_count = 0;
5620 }
5621
5622 ret = 0;
5623
5624out:
5625 strbuf_release(&rev);
5626 return ret;
5627}
5628
5629int sequencer_continue(struct repository *r, struct replay_opts *opts)
5630{
5631 struct todo_list todo_list = TODO_LIST_INIT;
5632 int res;
5633
5634 if (read_and_refresh_cache(r, opts))
5635 return -1;
5636
5637 if (read_populate_opts(opts))
5638 return -1;
5639 if (is_rebase_i(opts)) {
5640 if ((res = read_populate_todo(r, &todo_list, opts)))
5641 goto release_todo_list;
5642
5643 if (file_exists(rebase_path_dropped())) {
5644 if ((res = todo_list_check_against_backup(r, opts,
5645 &todo_list)))
5646 goto release_todo_list;
5647
5648 unlink(rebase_path_dropped());
5649 }
5650
5651 if (commit_staged_changes(r, opts, &todo_list)) {
5652 res = -1;
5653 goto release_todo_list;
5654 }
5655 } else if (!file_exists(get_todo_path(opts)))
5656 return continue_single_pick(r, opts);
5657 else if ((res = read_populate_todo(r, &todo_list, opts)))
5658 goto release_todo_list;
5659
5660 if (!is_rebase_i(opts)) {
5661 /* Verify that the conflict has been resolved */
5662 if (refs_ref_exists(get_main_ref_store(r),
5663 "CHERRY_PICK_HEAD") ||
5664 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
5665 res = continue_single_pick(r, opts);
5666 if (res)
5667 goto release_todo_list;
5668 }
5669 if (index_differs_from(r, "HEAD", NULL, 0)) {
5670 res = error_dirty_index(r, opts);
5671 goto release_todo_list;
5672 }
5673 todo_list.current++;
5674 } else if (file_exists(rebase_path_stopped_sha())) {
5675 struct strbuf buf = STRBUF_INIT;
5676 struct object_id oid;
5677
5678 if (read_oneliner(&buf, rebase_path_stopped_sha(),
5679 READ_ONELINER_SKIP_IF_EMPTY) &&
5680 !get_oid_hex(buf.buf, &oid))
5681 record_in_rewritten(&oid, peek_command(&todo_list, 0));
5682 strbuf_release(&buf);
5683 }
5684
5685 res = pick_commits(r, &todo_list, opts);
5686release_todo_list:
5687 todo_list_release(&todo_list);
5688 return res;
5689}
5690
5691static int single_pick(struct repository *r,
5692 struct commit *cmit,
5693 struct replay_opts *opts)
5694{
5695 int check_todo;
5696 struct todo_item item;
5697
5698 item.command = opts->action == REPLAY_PICK ?
5699 TODO_PICK : TODO_REVERT;
5700 item.commit = cmit;
5701
5702 switch (do_pick_commit(r, &item, opts, 0, &check_todo)) {
5703 case PICK_RESULT_ERROR:
5704 return -1;
5705 case PICK_RESULT_CONFLICTS:
5706 return 1;
5707 default:
5708 return 0;
5709 }
5710
5711}
5712
5713int sequencer_pick_revisions(struct repository *r,
5714 struct replay_opts *opts)
5715{
5716 struct todo_list todo_list = TODO_LIST_INIT;
5717 struct object_id oid;
5718 int i, res;
5719
5720 assert(opts->revs);
5721 if (read_and_refresh_cache(r, opts)) {
5722 res = -1;
5723 goto out;
5724 }
5725
5726 for (i = 0; i < opts->revs->pending.nr; i++) {
5727 struct object_id oid;
5728 const char *name = opts->revs->pending.objects[i].name;
5729
5730 /* This happens when using --stdin. */
5731 if (!strlen(name))
5732 continue;
5733
5734 if (!repo_get_oid(r, name, &oid)) {
5735 if (!lookup_commit_reference_gently(r, &oid, 1)) {
5736 enum object_type type = odb_read_object_info(r->objects,
5737 &oid, NULL);
5738 res = error(_("%s: can't cherry-pick a %s"),
5739 name, type_name(type));
5740 goto out;
5741 }
5742 } else {
5743 res = error(_("%s: bad revision"), name);
5744 goto out;
5745 }
5746 }
5747
5748 /*
5749 * If we were called as "git cherry-pick <commit>", just
5750 * cherry-pick/revert it, set CHERRY_PICK_HEAD /
5751 * REVERT_HEAD, and don't touch the sequencer state.
5752 * This means it is possible to cherry-pick in the middle
5753 * of a cherry-pick sequence.
5754 */
5755 if (opts->revs->cmdline.nr == 1 &&
5756 opts->revs->cmdline.rev->whence == REV_CMD_REV &&
5757 opts->revs->no_walk &&
5758 !opts->revs->cmdline.rev->flags) {
5759 struct commit *cmit;
5760
5761 if (prepare_revision_walk(opts->revs)) {
5762 res = error(_("revision walk setup failed"));
5763 goto out;
5764 }
5765
5766 cmit = get_revision(opts->revs);
5767 if (!cmit) {
5768 res = error(_("empty commit set passed"));
5769 goto out;
5770 }
5771
5772 if (get_revision(opts->revs))
5773 BUG("unexpected extra commit from walk");
5774
5775 res = single_pick(r, cmit, opts);
5776 goto out;
5777 }
5778
5779 /*
5780 * Start a new cherry-pick/ revert sequence; but
5781 * first, make sure that an existing one isn't in
5782 * progress
5783 */
5784
5785 if (walk_revs_populate_todo(&todo_list, opts) ||
5786 create_seq_dir(r) < 0) {
5787 res = -1;
5788 goto out;
5789 }
5790
5791 if (repo_get_oid(r, "HEAD", &oid) && (opts->action == REPLAY_REVERT)) {
5792 res = error(_("can't revert as initial commit"));
5793 goto out;
5794 }
5795
5796 if (save_head(oid_to_hex(&oid))) {
5797 res = -1;
5798 goto out;
5799 }
5800
5801 if (save_opts(opts)) {
5802 res = -1;
5803 goto out;
5804 }
5805
5806 update_abort_safety_file();
5807 res = pick_commits(r, &todo_list, opts);
5808
5809out:
5810 todo_list_release(&todo_list);
5811 return res;
5812}
5813
5814void sequencer_format_revert_message(struct repository *r,
5815 const char *subject,
5816 const struct commit *commit,
5817 const struct commit *parent,
5818 bool use_commit_reference,
5819 struct strbuf *message)
5820{
5821 const char *orig_subject;
5822
5823 if (use_commit_reference) {
5824 strbuf_commented_addf(message, comment_line_str,
5825 "*** SAY WHY WE ARE REVERTING ON THE TITLE LINE ***");
5826 } else if (skip_prefix(subject, "Revert \"", &orig_subject) &&
5827 /*
5828 * We don't touch pre-existing repeated reverts, because
5829 * theoretically these can be nested arbitrarily deeply,
5830 * thus requiring excessive complexity to deal with.
5831 */
5832 !starts_with(orig_subject, "Revert \"")) {
5833 strbuf_addstr(message, "Reapply \"");
5834 strbuf_addstr(message, orig_subject);
5835 strbuf_addstr(message, "\n");
5836 } else {
5837 strbuf_addstr(message, "Revert \"");
5838 strbuf_addstr(message, subject);
5839 strbuf_addstr(message, "\"\n");
5840 }
5841 strbuf_addstr(message, "\nThis reverts commit ");
5842 refer_to_commit(r, message, commit, use_commit_reference);
5843
5844 if (commit->parents && commit->parents->next) {
5845 strbuf_addstr(message, ", reversing\nchanges made to ");
5846 refer_to_commit(r, message, parent, use_commit_reference);
5847 }
5848 strbuf_addstr(message, ".\n");
5849}
5850
5851void append_signoff(struct strbuf *msgbuf, size_t ignore_footer, unsigned flag)
5852{
5853 unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;
5854 struct strbuf sob = STRBUF_INIT;
5855 int has_footer;
5856
5857 strbuf_addstr(&sob, sign_off_header);
5858 strbuf_addstr(&sob, fmt_name(WANT_COMMITTER_IDENT));
5859 strbuf_addch(&sob, '\n');
5860
5861 if (!ignore_footer)
5862 strbuf_complete_line(msgbuf);
5863
5864 /*
5865 * If the whole message buffer is equal to the sob, pretend that we
5866 * found a conforming footer with a matching sob
5867 */
5868 if (msgbuf->len - ignore_footer == sob.len &&
5869 !strncmp(msgbuf->buf, sob.buf, sob.len))
5870 has_footer = 3;
5871 else
5872 has_footer = has_conforming_footer(msgbuf, &sob, ignore_footer);
5873
5874 if (!has_footer) {
5875 const char *append_newlines = NULL;
5876 size_t len = msgbuf->len - ignore_footer;
5877
5878 if (!len) {
5879 /*
5880 * The buffer is completely empty. Leave foom for
5881 * the title and body to be filled in by the user.
5882 */
5883 append_newlines = "\n\n";
5884 } else if (len == 1) {
5885 /*
5886 * Buffer contains a single newline. Add another
5887 * so that we leave room for the title and body.
5888 */
5889 append_newlines = "\n";
5890 } else if (msgbuf->buf[len - 2] != '\n') {
5891 /*
5892 * Buffer ends with a single newline. Add another
5893 * so that there is an empty line between the message
5894 * body and the sob.
5895 */
5896 append_newlines = "\n";
5897 } /* else, the buffer already ends with two newlines. */
5898
5899 if (append_newlines)
5900 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5901 append_newlines, strlen(append_newlines));
5902 }
5903
5904 if (has_footer != 3 && (!no_dup_sob || has_footer != 2))
5905 strbuf_splice(msgbuf, msgbuf->len - ignore_footer, 0,
5906 sob.buf, sob.len);
5907
5908 strbuf_release(&sob);
5909}
5910
5911struct labels_entry {
5912 struct hashmap_entry entry;
5913 char label[FLEX_ARRAY];
5914};
5915
5916static int labels_cmp(const void *fndata UNUSED,
5917 const struct hashmap_entry *eptr,
5918 const struct hashmap_entry *entry_or_key, const void *key)
5919{
5920 const struct labels_entry *a, *b;
5921
5922 a = container_of(eptr, const struct labels_entry, entry);
5923 b = container_of(entry_or_key, const struct labels_entry, entry);
5924
5925 return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
5926}
5927
5928struct string_entry {
5929 struct oidmap_entry entry;
5930 char string[FLEX_ARRAY];
5931};
5932
5933struct label_state {
5934 struct oidmap commit2label;
5935 struct hashmap labels;
5936 struct strbuf buf;
5937 int max_label_length;
5938};
5939
5940static const char *label_oid(struct object_id *oid, const char *label,
5941 struct label_state *state)
5942{
5943 struct labels_entry *labels_entry;
5944 struct string_entry *string_entry;
5945 struct object_id dummy;
5946 int i;
5947
5948 string_entry = oidmap_get(&state->commit2label, oid);
5949 if (string_entry)
5950 return string_entry->string;
5951
5952 /*
5953 * For "uninteresting" commits, i.e. commits that are not to be
5954 * rebased, and which can therefore not be labeled, we use a unique
5955 * abbreviation of the commit name. This is slightly more complicated
5956 * than calling repo_find_unique_abbrev() because we also need to make
5957 * sure that the abbreviation does not conflict with any other
5958 * label.
5959 *
5960 * We disallow "interesting" commits to be labeled by a string that
5961 * is a valid full-length hash, to ensure that we always can find an
5962 * abbreviation for any uninteresting commit's names that does not
5963 * clash with any other label.
5964 */
5965 strbuf_reset(&state->buf);
5966 if (!label) {
5967 char *p;
5968
5969 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5970 label = p = state->buf.buf;
5971
5972 repo_find_unique_abbrev_r(the_repository, p, oid,
5973 default_abbrev);
5974
5975 /*
5976 * We may need to extend the abbreviated hash so that there is
5977 * no conflicting label.
5978 */
5979 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5980 size_t i = strlen(p) + 1;
5981
5982 oid_to_hex_r(p, oid);
5983 for (; i < the_hash_algo->hexsz; i++) {
5984 char save = p[i];
5985 p[i] = '\0';
5986 if (!hashmap_get_from_hash(&state->labels,
5987 strihash(p), p))
5988 break;
5989 p[i] = save;
5990 }
5991 }
5992 } else {
5993 struct strbuf *buf = &state->buf;
5994 int label_is_utf8 = 1; /* start with this assumption */
5995 size_t max_len = buf->len + state->max_label_length;
5996
5997 /*
5998 * Sanitize labels by replacing non-alpha-numeric characters
5999 * (including white-space ones) by dashes, as they might be
6000 * illegal in file names (and hence in ref names).
6001 *
6002 * Note that we retain non-ASCII UTF-8 characters (identified
6003 * via the most significant bit). They should be all acceptable
6004 * in file names.
6005 *
6006 * As we will use the labels as names of (loose) refs, it is
6007 * vital that the name not be longer than the maximum component
6008 * size of the file system (`NAME_MAX`). We are careful to
6009 * truncate the label accordingly, allowing for the `.lock`
6010 * suffix and for the label to be UTF-8 encoded (i.e. we avoid
6011 * truncating in the middle of a character).
6012 */
6013 for (; *label && buf->len + 1 < max_len; label++)
6014 if (isalnum(*label) ||
6015 (!label_is_utf8 && (*label & 0x80)))
6016 strbuf_addch(buf, *label);
6017 else if (*label & 0x80) {
6018 const char *p = label;
6019
6020 utf8_width(&p, NULL);
6021 if (p) {
6022 if (buf->len + (p - label) > max_len)
6023 break;
6024 strbuf_add(buf, label, p - label);
6025 label = p - 1;
6026 } else {
6027 label_is_utf8 = 0;
6028 strbuf_addch(buf, *label);
6029 }
6030 /* avoid leading dash and double-dashes */
6031 } else if (buf->len && buf->buf[buf->len - 1] != '-')
6032 strbuf_addch(buf, '-');
6033 if (!buf->len) {
6034 strbuf_addstr(buf, "rev-");
6035 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
6036 }
6037 label = buf->buf;
6038
6039 if ((buf->len == the_hash_algo->hexsz &&
6040 !get_oid_hex(label, &dummy)) ||
6041 (buf->len == 1 && *label == '#') ||
6042 hashmap_get_from_hash(&state->labels,
6043 strihash(label), label)) {
6044 /*
6045 * If the label already exists, or if the label is a
6046 * valid full OID, or the label is a '#' (which we use
6047 * as a separator between merge heads and oneline), we
6048 * append a dash and a number to make it unique.
6049 */
6050 size_t len = buf->len;
6051
6052 for (i = 2; ; i++) {
6053 strbuf_setlen(buf, len);
6054 strbuf_addf(buf, "-%d", i);
6055 if (!hashmap_get_from_hash(&state->labels,
6056 strihash(buf->buf),
6057 buf->buf))
6058 break;
6059 }
6060
6061 label = buf->buf;
6062 }
6063 }
6064
6065 FLEX_ALLOC_STR(labels_entry, label, label);
6066 hashmap_entry_init(&labels_entry->entry, strihash(label));
6067 hashmap_add(&state->labels, &labels_entry->entry);
6068
6069 FLEX_ALLOC_STR(string_entry, string, label);
6070 oidcpy(&string_entry->entry.oid, oid);
6071 oidmap_put(&state->commit2label, string_entry);
6072
6073 return string_entry->string;
6074}
6075
6076static int make_script_with_merges(struct pretty_print_context *pp,
6077 struct rev_info *revs, struct strbuf *out,
6078 unsigned flags)
6079{
6080 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
6081 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
6082 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
6083 int skipped_commit = 0;
6084 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
6085 struct strbuf label_from_message = STRBUF_INIT;
6086 struct commit_list *commits = NULL, **tail = &commits, *iter;
6087 struct commit_list *tips = NULL, **tips_tail = &tips;
6088 struct commit *commit;
6089 struct oidmap commit2todo = OIDMAP_INIT;
6090 struct string_entry *entry;
6091 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
6092 shown = OIDSET_INIT;
6093 struct label_state state =
6094 { OIDMAP_INIT, { NULL }, STRBUF_INIT, GIT_MAX_LABEL_LENGTH };
6095
6096 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
6097 const char *cmd_pick = abbr ? "p" : "pick",
6098 *cmd_label = abbr ? "l" : "label",
6099 *cmd_reset = abbr ? "t" : "reset",
6100 *cmd_merge = abbr ? "m" : "merge";
6101
6102 repo_config_get_int(the_repository, "rebase.maxlabellength", &state.max_label_length);
6103
6104 oidmap_init(&commit2todo, 0);
6105 oidmap_init(&state.commit2label, 0);
6106 hashmap_init(&state.labels, labels_cmp, NULL, 0);
6107 strbuf_init(&state.buf, 32);
6108 load_branch_decorations();
6109
6110 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
6111 struct labels_entry *onto_label_entry;
6112 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
6113 FLEX_ALLOC_STR(entry, string, "onto");
6114 oidcpy(&entry->entry.oid, oid);
6115 oidmap_put(&state.commit2label, entry);
6116
6117 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
6118 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
6119 hashmap_add(&state.labels, &onto_label_entry->entry);
6120 }
6121
6122 /*
6123 * First phase:
6124 * - get onelines for all commits
6125 * - gather all branch tips (i.e. 2nd or later parents of merges)
6126 * - label all branch tips
6127 */
6128 while ((commit = get_revision(revs))) {
6129 struct commit_list *to_merge;
6130 const char *p1, *p2;
6131 struct object_id *oid;
6132 int is_empty;
6133
6134 tail = &commit_list_insert(commit, tail)->next;
6135 oidset_insert(&interesting, &commit->object.oid);
6136
6137 is_empty = is_original_commit_empty(commit);
6138 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6139 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6140 warning(_("skipped previously applied commit %s"),
6141 short_commit_name(the_repository, commit));
6142 skipped_commit = 1;
6143 continue;
6144 }
6145 if (is_empty && !keep_empty)
6146 continue;
6147
6148 strbuf_reset(&oneline);
6149 pretty_print_commit(pp, commit, &oneline);
6150
6151 to_merge = commit->parents ? commit->parents->next : NULL;
6152 if (!to_merge) {
6153 /* non-merge commit: easy case */
6154 strbuf_reset(&buf);
6155 strbuf_addf(&buf, "%s %s %s", cmd_pick,
6156 oid_to_hex(&commit->object.oid),
6157 oneline.buf);
6158 if (is_empty)
6159 strbuf_addf(&buf, " %s empty",
6160 comment_line_str);
6161
6162 FLEX_ALLOC_STR(entry, string, buf.buf);
6163 oidcpy(&entry->entry.oid, &commit->object.oid);
6164 oidmap_put(&commit2todo, entry);
6165
6166 continue;
6167 }
6168
6169 /* Create a label from the commit message */
6170 strbuf_reset(&label_from_message);
6171 if (skip_prefix(oneline.buf, "# Merge ", &p1) &&
6172 (p1 = strchr(p1, '\'')) &&
6173 (p2 = strchr(++p1, '\'')))
6174 strbuf_add(&label_from_message, p1, p2 - p1);
6175 else if (skip_prefix(oneline.buf, "# Merge pull request ",
6176 &p1) &&
6177 (p1 = strstr(p1, " from ")))
6178 strbuf_addstr(&label_from_message, p1 + strlen(" from "));
6179 else
6180 strbuf_addbuf(&label_from_message, &oneline);
6181
6182 strbuf_reset(&buf);
6183 strbuf_addf(&buf, "%s -C %s",
6184 cmd_merge, oid_to_hex(&commit->object.oid));
6185
6186 /* label the tips of merged branches */
6187 for (; to_merge; to_merge = to_merge->next) {
6188 const char *label = label_from_message.buf;
6189 const struct name_decoration *decoration =
6190 get_name_decoration(&to_merge->item->object);
6191
6192 if (decoration)
6193 skip_prefix(decoration->name, "refs/heads/",
6194 &label);
6195
6196 oid = &to_merge->item->object.oid;
6197 strbuf_addch(&buf, ' ');
6198
6199 if (!oidset_contains(&interesting, oid)) {
6200 strbuf_addstr(&buf, label_oid(oid, NULL,
6201 &state));
6202 continue;
6203 }
6204
6205 tips_tail = &commit_list_insert(to_merge->item,
6206 tips_tail)->next;
6207
6208 strbuf_addstr(&buf, label_oid(oid, label, &state));
6209 }
6210 strbuf_addf(&buf, " %s", oneline.buf);
6211
6212 FLEX_ALLOC_STR(entry, string, buf.buf);
6213 oidcpy(&entry->entry.oid, &commit->object.oid);
6214 oidmap_put(&commit2todo, entry);
6215 }
6216 if (skipped_commit)
6217 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6218 _("use --reapply-cherry-picks to include skipped commits"));
6219
6220 /*
6221 * Second phase:
6222 * - label branch points
6223 * - add HEAD to the branch tips
6224 */
6225 for (iter = commits; iter; iter = iter->next) {
6226 struct commit_list *parent = iter->item->parents;
6227 for (; parent; parent = parent->next) {
6228 struct object_id *oid = &parent->item->object.oid;
6229 if (!oidset_contains(&interesting, oid))
6230 continue;
6231 if (oidset_insert(&child_seen, oid))
6232 label_oid(oid, "branch-point", &state);
6233 }
6234
6235 /* Add HEAD as implicit "tip of branch" */
6236 if (!iter->next)
6237 tips_tail = &commit_list_insert(iter->item,
6238 tips_tail)->next;
6239 }
6240
6241 /*
6242 * Third phase: output the todo list. This is a bit tricky, as we
6243 * want to avoid jumping back and forth between revisions. To
6244 * accomplish that goal, we walk backwards from the branch tips,
6245 * gathering commits not yet shown, reversing the list on the fly,
6246 * then outputting that list (labeling revisions as needed).
6247 */
6248 strbuf_addf(out, "%s onto\n", cmd_label);
6249 for (iter = tips; iter; iter = iter->next) {
6250 struct commit_list *list = NULL, *iter2;
6251
6252 commit = iter->item;
6253 if (oidset_contains(&shown, &commit->object.oid))
6254 continue;
6255 entry = oidmap_get(&state.commit2label, &commit->object.oid);
6256
6257 if (entry)
6258 strbuf_addf(out, "\n%s Branch %s\n", comment_line_str, entry->string);
6259 else
6260 strbuf_addch(out, '\n');
6261
6262 while (oidset_contains(&interesting, &commit->object.oid) &&
6263 !oidset_contains(&shown, &commit->object.oid)) {
6264 commit_list_insert(commit, &list);
6265 if (!commit->parents) {
6266 commit = NULL;
6267 break;
6268 }
6269 commit = commit->parents->item;
6270 }
6271
6272 if (!commit)
6273 strbuf_addf(out, "%s %s\n", cmd_reset,
6274 rebase_cousins || root_with_onto ?
6275 "onto" : "[new root]");
6276 else {
6277 const char *to = NULL;
6278
6279 entry = oidmap_get(&state.commit2label,
6280 &commit->object.oid);
6281 if (entry)
6282 to = entry->string;
6283 else if (!rebase_cousins)
6284 to = label_oid(&commit->object.oid, NULL,
6285 &state);
6286
6287 if (!to || !strcmp(to, "onto"))
6288 strbuf_addf(out, "%s onto\n", cmd_reset);
6289 else {
6290 strbuf_reset(&oneline);
6291 pretty_print_commit(pp, commit, &oneline);
6292 strbuf_addf(out, "%s %s %s\n",
6293 cmd_reset, to, oneline.buf);
6294 }
6295 }
6296
6297 for (iter2 = list; iter2; iter2 = iter2->next) {
6298 struct object_id *oid = &iter2->item->object.oid;
6299 entry = oidmap_get(&commit2todo, oid);
6300 /* only show if not already upstream */
6301 if (entry)
6302 strbuf_addf(out, "%s\n", entry->string);
6303 entry = oidmap_get(&state.commit2label, oid);
6304 if (entry)
6305 strbuf_addf(out, "%s %s\n",
6306 cmd_label, entry->string);
6307 oidset_insert(&shown, oid);
6308 }
6309
6310 commit_list_free(list);
6311 }
6312
6313 commit_list_free(commits);
6314 commit_list_free(tips);
6315
6316 strbuf_release(&label_from_message);
6317 strbuf_release(&oneline);
6318 strbuf_release(&buf);
6319
6320 oidset_clear(&interesting);
6321 oidset_clear(&child_seen);
6322 oidset_clear(&shown);
6323 oidmap_clear(&commit2todo, 1);
6324 oidmap_clear(&state.commit2label, 1);
6325 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
6326 strbuf_release(&state.buf);
6327
6328 return 0;
6329}
6330
6331int sequencer_make_script(struct repository *r, struct strbuf *out,
6332 struct strvec *argv, unsigned flags)
6333{
6334 char *format = NULL;
6335 struct pretty_print_context pp = {0};
6336 struct rev_info revs;
6337 struct commit *commit;
6338 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
6339 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
6340 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
6341 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
6342 int skipped_commit = 0;
6343 int ret = 0;
6344
6345 repo_init_revisions(r, &revs, NULL);
6346 revs.verbose_header = 1;
6347 if (!rebase_merges)
6348 revs.max_parents = 1;
6349 revs.cherry_mark = !reapply_cherry_picks;
6350 revs.limited = 1;
6351 revs.reverse = 1;
6352 revs.right_only = 1;
6353 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
6354 revs.topo_order = 1;
6355
6356 repo_config_get_string(the_repository, "rebase.instructionFormat", &format);
6357 if (!format || !*format) {
6358 free(format);
6359 format = xstrdup("# %s");
6360 }
6361 if (*format != '#') {
6362 char *temp = format;
6363 format = xstrfmt("# %s", temp);
6364 free(temp);
6365 }
6366
6367 get_commit_format(format, &revs);
6368 free(format);
6369 pp.fmt = revs.commit_format;
6370 pp.output_encoding = get_log_output_encoding();
6371
6372 setup_revisions_from_strvec(argv, &revs, NULL);
6373 if (argv->nr > 1) {
6374 ret = error(_("make_script: unhandled options"));
6375 goto cleanup;
6376 }
6377
6378 if (prepare_revision_walk(&revs) < 0) {
6379 ret = error(_("make_script: error preparing revisions"));
6380 goto cleanup;
6381 }
6382
6383 if (rebase_merges) {
6384 ret = make_script_with_merges(&pp, &revs, out, flags);
6385 goto cleanup;
6386 }
6387
6388 while ((commit = get_revision(&revs))) {
6389 int is_empty = is_original_commit_empty(commit);
6390
6391 if (!is_empty && (commit->object.flags & PATCHSAME)) {
6392 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
6393 warning(_("skipped previously applied commit %s"),
6394 short_commit_name(r, commit));
6395 skipped_commit = 1;
6396 continue;
6397 }
6398 if (is_empty && !keep_empty)
6399 continue;
6400 strbuf_addf(out, "%s %s ", insn,
6401 oid_to_hex(&commit->object.oid));
6402 pretty_print_commit(&pp, commit, out);
6403 if (is_empty)
6404 strbuf_addf(out, " %s empty", comment_line_str);
6405 strbuf_addch(out, '\n');
6406 }
6407 if (skipped_commit)
6408 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
6409 _("use --reapply-cherry-picks to include skipped commits"));
6410cleanup:
6411 release_revisions(&revs);
6412 return ret;
6413}
6414
6415/*
6416 * Add commands after pick and (series of) squash/fixup commands
6417 * in the todo list.
6418 */
6419static void todo_list_add_exec_commands(struct todo_list *todo_list,
6420 struct string_list *commands)
6421{
6422 struct strbuf *buf = &todo_list->buf;
6423 size_t base_offset = buf->len;
6424 int i, insert, nr = 0, alloc = 0;
6425 struct todo_item *items = NULL, *base_items = NULL;
6426
6427 CALLOC_ARRAY(base_items, commands->nr);
6428 for (i = 0; i < commands->nr; i++) {
6429 size_t command_len = strlen(commands->items[i].string);
6430
6431 strbuf_addstr(buf, commands->items[i].string);
6432 strbuf_addch(buf, '\n');
6433
6434 base_items[i].command = TODO_EXEC;
6435 base_items[i].offset_in_buf = base_offset;
6436 base_items[i].arg_offset = base_offset;
6437 base_items[i].arg_len = command_len;
6438
6439 base_offset += command_len + 1;
6440 }
6441
6442 /*
6443 * Insert <commands> after every pick. Here, fixup/squash chains
6444 * are considered part of the pick, so we insert the commands *after*
6445 * those chains if there are any.
6446 *
6447 * As we insert the exec commands immediately after rearranging
6448 * any fixups and before the user edits the list, a fixup chain
6449 * can never contain comments (any comments are empty picks that
6450 * have been commented out because the user did not specify
6451 * --keep-empty). So, it is safe to insert an exec command
6452 * without looking at the command following a comment.
6453 */
6454 insert = 0;
6455 for (i = 0; i < todo_list->nr; i++) {
6456 enum todo_command command = todo_list->items[i].command;
6457 if (insert && !is_fixup(command)) {
6458 ALLOC_GROW(items, nr + commands->nr, alloc);
6459 COPY_ARRAY(items + nr, base_items, commands->nr);
6460 nr += commands->nr;
6461
6462 insert = 0;
6463 }
6464
6465 ALLOC_GROW(items, nr + 1, alloc);
6466 items[nr++] = todo_list->items[i];
6467
6468 if (command == TODO_PICK || command == TODO_MERGE)
6469 insert = 1;
6470 }
6471
6472 /* insert or append final <commands> */
6473 if (insert) {
6474 ALLOC_GROW(items, nr + commands->nr, alloc);
6475 COPY_ARRAY(items + nr, base_items, commands->nr);
6476 nr += commands->nr;
6477 }
6478
6479 free(base_items);
6480 FREE_AND_NULL(todo_list->items);
6481 todo_list->items = items;
6482 todo_list->nr = nr;
6483 todo_list->alloc = alloc;
6484}
6485
6486static void todo_list_to_strbuf(struct repository *r,
6487 struct todo_list *todo_list,
6488 struct strbuf *buf, int num, unsigned flags)
6489{
6490 struct todo_item *item;
6491 int i, max = todo_list->nr;
6492
6493 if (num > 0 && num < max)
6494 max = num;
6495
6496 for (item = todo_list->items, i = 0; i < max; i++, item++) {
6497 char cmd;
6498
6499 /* if the item is not a command write it and continue */
6500 if (item->command >= TODO_COMMENT) {
6501 strbuf_addf(buf, "%.*s\n", item->arg_len,
6502 todo_item_get_arg(todo_list, item));
6503 continue;
6504 }
6505
6506 /* add command to the buffer */
6507 cmd = command_to_char(item->command);
6508 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
6509 strbuf_addch(buf, cmd);
6510 else
6511 strbuf_addstr(buf, command_to_string(item->command));
6512
6513 /* add commit id */
6514 if (item->commit) {
6515 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
6516 short_commit_name(r, item->commit) :
6517 oid_to_hex(&item->commit->object.oid);
6518
6519 if (item->command == TODO_FIXUP) {
6520 if (item->flags & TODO_EDIT_FIXUP_MSG)
6521 strbuf_addstr(buf, " -c");
6522 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
6523 strbuf_addstr(buf, " -C");
6524 }
6525 }
6526
6527 if (item->command == TODO_MERGE) {
6528 if (item->flags & TODO_EDIT_MERGE_MSG)
6529 strbuf_addstr(buf, " -c");
6530 else
6531 strbuf_addstr(buf, " -C");
6532 }
6533
6534 strbuf_addf(buf, " %s", oid);
6535 }
6536
6537 /* add all the rest */
6538 if (!item->arg_len)
6539 strbuf_addch(buf, '\n');
6540 else
6541 strbuf_addf(buf, " %.*s\n", item->arg_len,
6542 todo_item_get_arg(todo_list, item));
6543 }
6544}
6545
6546int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
6547 const char *file, const char *shortrevisions,
6548 const char *shortonto, int num, unsigned flags)
6549{
6550 int res;
6551 struct strbuf buf = STRBUF_INIT;
6552
6553 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
6554 if (flags & TODO_LIST_APPEND_TODO_HELP)
6555 append_todo_help(count_commands(todo_list),
6556 shortrevisions, shortonto, &buf);
6557
6558 res = write_message(buf.buf, buf.len, file, 0);
6559 strbuf_release(&buf);
6560
6561 return res;
6562}
6563
6564/* skip picking commits whose parents are unchanged */
6565static int skip_unnecessary_picks(struct repository *r,
6566 struct todo_list *todo_list,
6567 struct object_id *base_oid)
6568{
6569 struct object_id *parent_oid;
6570 int i;
6571
6572 for (i = 0; i < todo_list->nr; i++) {
6573 struct todo_item *item = todo_list->items + i;
6574
6575 if (item->command >= TODO_NOOP)
6576 continue;
6577 if (item->command != TODO_PICK)
6578 break;
6579 if (repo_parse_commit(r, item->commit)) {
6580 return error(_("could not parse commit '%s'"),
6581 oid_to_hex(&item->commit->object.oid));
6582 }
6583 if (!item->commit->parents)
6584 break; /* root commit */
6585 if (item->commit->parents->next)
6586 break; /* merge commit */
6587 parent_oid = &item->commit->parents->item->object.oid;
6588 if (!oideq(parent_oid, base_oid))
6589 break;
6590 oidcpy(base_oid, &item->commit->object.oid);
6591 }
6592 if (i > 0) {
6593 const char *done_path = rebase_path_done();
6594
6595 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
6596 error_errno(_("could not write to '%s'"), done_path);
6597 return -1;
6598 }
6599
6600 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
6601 todo_list->nr -= i;
6602 todo_list->current = 0;
6603 todo_list->done_nr += i;
6604
6605 if (is_fixup(peek_command(todo_list, 0)))
6606 record_in_rewritten(base_oid, peek_command(todo_list, 0));
6607 }
6608
6609 return 0;
6610}
6611
6612struct todo_add_branch_context {
6613 struct todo_item *items;
6614 size_t items_nr;
6615 size_t items_alloc;
6616 struct strbuf *buf;
6617 struct string_list refs_to_oids;
6618};
6619
6620static int add_decorations_to_list(const struct commit *commit,
6621 struct todo_add_branch_context *ctx)
6622{
6623 const struct name_decoration *decoration = get_name_decoration(&commit->object);
6624 char *head_ref = refs_resolve_refdup(get_main_ref_store(the_repository),
6625 "HEAD",
6626 RESOLVE_REF_READING,
6627 NULL,
6628 NULL);
6629
6630 while (decoration) {
6631 struct todo_item *item;
6632 const char *path;
6633 size_t base_offset = ctx->buf->len;
6634
6635 /*
6636 * If the branch is the current HEAD, then it will be
6637 * updated by the default rebase behavior.
6638 * Exclude it from the list of refs to update,
6639 * as well as any non-branch decorations.
6640 * Non-branch decorations may be present if the pretty format
6641 * includes "%d", which would have loaded all refs
6642 * into the global decoration table.
6643 */
6644 if ((head_ref && !strcmp(head_ref, decoration->name)) ||
6645 (decoration->type != DECORATION_REF_LOCAL)) {
6646 decoration = decoration->next;
6647 continue;
6648 }
6649
6650 ALLOC_GROW(ctx->items,
6651 ctx->items_nr + 1,
6652 ctx->items_alloc);
6653 item = &ctx->items[ctx->items_nr];
6654 memset(item, 0, sizeof(*item));
6655
6656 /* If the branch is checked out, then leave a comment instead. */
6657 if ((path = branch_checked_out(decoration->name))) {
6658 item->command = TODO_COMMENT;
6659 strbuf_commented_addf(ctx->buf, comment_line_str,
6660 "Ref %s checked out at '%s'\n",
6661 decoration->name, path);
6662 } else {
6663 struct string_list_item *sti;
6664 item->command = TODO_UPDATE_REF;
6665 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6666
6667 sti = string_list_insert(&ctx->refs_to_oids,
6668 decoration->name);
6669 sti->util = init_update_ref_record(decoration->name);
6670 }
6671
6672 item->offset_in_buf = base_offset;
6673 item->arg_offset = base_offset;
6674 item->arg_len = ctx->buf->len - base_offset;
6675 ctx->items_nr++;
6676
6677 decoration = decoration->next;
6678 }
6679
6680 free(head_ref);
6681 return 0;
6682}
6683
6684/*
6685 * For each 'pick' command, find out if the commit has a decoration in
6686 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6687 */
6688static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6689{
6690 int i, res;
6691 struct todo_add_branch_context ctx = {
6692 .buf = &todo_list->buf,
6693 .refs_to_oids = STRING_LIST_INIT_DUP,
6694 };
6695
6696 ctx.items_alloc = 2 * todo_list->nr + 1;
6697 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6698
6699 load_branch_decorations();
6700
6701 for (i = 0; i < todo_list->nr; ) {
6702 struct todo_item *item = &todo_list->items[i];
6703
6704 /* insert ith item into new list */
6705 ALLOC_GROW(ctx.items,
6706 ctx.items_nr + 1,
6707 ctx.items_alloc);
6708
6709 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6710
6711 if (item->commit) {
6712 add_decorations_to_list(item->commit, &ctx);
6713 }
6714 }
6715
6716 res = write_update_refs_state(&ctx.refs_to_oids);
6717
6718 string_list_clear(&ctx.refs_to_oids, 1);
6719
6720 if (res) {
6721 /* we failed, so clean up the new list. */
6722 free(ctx.items);
6723 return res;
6724 }
6725
6726 free(todo_list->items);
6727 todo_list->items = ctx.items;
6728 todo_list->nr = ctx.items_nr;
6729 todo_list->alloc = ctx.items_alloc;
6730
6731 return 0;
6732}
6733
6734int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6735 const char *shortrevisions, const char *onto_name,
6736 struct commit *onto, const struct object_id *orig_head,
6737 struct string_list *commands, unsigned autosquash,
6738 unsigned update_refs,
6739 struct todo_list *todo_list)
6740{
6741 char shortonto[GIT_MAX_HEXSZ + 1];
6742 const char *todo_file = rebase_path_todo();
6743 struct todo_list new_todo = TODO_LIST_INIT;
6744 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6745 struct object_id oid = onto->object.oid;
6746 int res;
6747
6748 repo_find_unique_abbrev_r(r, shortonto, &oid,
6749 DEFAULT_ABBREV);
6750
6751 if (buf->len == 0) {
6752 struct todo_item *item = append_new_todo(todo_list);
6753 item->command = TODO_NOOP;
6754 item->commit = NULL;
6755 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6756 }
6757
6758 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6759 return -1;
6760
6761 if (autosquash && todo_list_rearrange_squash(todo_list))
6762 return -1;
6763
6764 if (commands->nr)
6765 todo_list_add_exec_commands(todo_list, commands);
6766
6767 if (count_commands(todo_list) == 0) {
6768 apply_autostash(rebase_path_autostash());
6769 sequencer_remove_state(opts);
6770
6771 return error(_("nothing to do"));
6772 }
6773
6774 res = edit_todo_list(r, opts, todo_list, &new_todo, shortrevisions,
6775 shortonto, flags);
6776 if (res == -1)
6777 return -1;
6778 else if (res == -2) {
6779 apply_autostash(rebase_path_autostash());
6780 sequencer_remove_state(opts);
6781
6782 return -1;
6783 } else if (res == -3) {
6784 apply_autostash(rebase_path_autostash());
6785 sequencer_remove_state(opts);
6786 todo_list_release(&new_todo);
6787
6788 return error(_("nothing to do"));
6789 } else if (res == -4) {
6790 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6791 todo_list_release(&new_todo);
6792
6793 return -1;
6794 }
6795
6796 /* Expand the commit IDs */
6797 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6798 strbuf_swap(&new_todo.buf, &buf2);
6799 strbuf_release(&buf2);
6800 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6801 new_todo.total_nr = 0;
6802 if (todo_list_parse_insn_buffer(r, opts, new_todo.buf.buf, &new_todo) < 0)
6803 BUG("invalid todo list after expanding IDs:\n%s",
6804 new_todo.buf.buf);
6805
6806 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6807 todo_list_release(&new_todo);
6808 return error(_("could not skip unnecessary pick commands"));
6809 }
6810
6811 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6812 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6813 todo_list_release(&new_todo);
6814 return error_errno(_("could not write '%s'"), todo_file);
6815 }
6816
6817 res = -1;
6818
6819 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6820 goto cleanup;
6821
6822 if (require_clean_work_tree(r, "rebase", NULL, 1, 1))
6823 goto cleanup;
6824
6825 todo_list_write_total_nr(&new_todo);
6826 res = pick_commits(r, &new_todo, opts);
6827
6828cleanup:
6829 todo_list_release(&new_todo);
6830
6831 return res;
6832}
6833
6834struct subject2item_entry {
6835 struct hashmap_entry entry;
6836 int i;
6837 char subject[FLEX_ARRAY];
6838};
6839
6840static int subject2item_cmp(const void *fndata UNUSED,
6841 const struct hashmap_entry *eptr,
6842 const struct hashmap_entry *entry_or_key,
6843 const void *key)
6844{
6845 const struct subject2item_entry *a, *b;
6846
6847 a = container_of(eptr, const struct subject2item_entry, entry);
6848 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6849
6850 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6851}
6852
6853define_commit_slab(commit_todo_item, struct todo_item *);
6854
6855static int skip_fixupish(const char *subject, const char **p) {
6856 return skip_prefix(subject, "fixup! ", p) ||
6857 skip_prefix(subject, "amend! ", p) ||
6858 skip_prefix(subject, "squash! ", p);
6859}
6860
6861/*
6862 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6863 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6864 * after the former, and change "pick" to "fixup"/"squash".
6865 *
6866 * Note that if the config has specified a custom instruction format, each log
6867 * message will have to be retrieved from the commit (as the oneline in the
6868 * script cannot be trusted) in order to normalize the autosquash arrangement.
6869 */
6870int todo_list_rearrange_squash(struct todo_list *todo_list)
6871{
6872 struct hashmap subject2item;
6873 int rearranged = 0, *next, *tail, i, nr = 0;
6874 char **subjects;
6875 struct commit_todo_item commit_todo;
6876 struct todo_item *items = NULL;
6877 int ret = 0;
6878
6879 init_commit_todo_item(&commit_todo);
6880 /*
6881 * The hashmap maps onelines to the respective todo list index.
6882 *
6883 * If any items need to be rearranged, the next[i] value will indicate
6884 * which item was moved directly after the i'th.
6885 *
6886 * In that case, last[i] will indicate the index of the latest item to
6887 * be moved to appear after the i'th.
6888 */
6889 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6890 ALLOC_ARRAY(next, todo_list->nr);
6891 ALLOC_ARRAY(tail, todo_list->nr);
6892 ALLOC_ARRAY(subjects, todo_list->nr);
6893 for (i = 0; i < todo_list->nr; i++) {
6894 struct strbuf buf = STRBUF_INIT;
6895 struct todo_item *item = todo_list->items + i;
6896 const char *commit_buffer, *subject, *p;
6897 size_t subject_len;
6898 int i2 = -1;
6899 struct subject2item_entry *entry;
6900
6901 next[i] = tail[i] = -1;
6902 if (!item->commit || item->command == TODO_DROP) {
6903 subjects[i] = NULL;
6904 continue;
6905 }
6906
6907 if (is_fixup(item->command)) {
6908 ret = error(_("the script was already rearranged."));
6909 goto cleanup;
6910 }
6911
6912 repo_parse_commit(the_repository, item->commit);
6913 commit_buffer = repo_logmsg_reencode(the_repository,
6914 item->commit, NULL,
6915 "UTF-8");
6916 find_commit_subject(commit_buffer, &subject);
6917 format_subject(&buf, subject, " ");
6918 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6919 repo_unuse_commit_buffer(the_repository, item->commit,
6920 commit_buffer);
6921 if (skip_fixupish(subject, &p)) {
6922 struct commit *commit2;
6923
6924 for (;;) {
6925 while (isspace(*p))
6926 p++;
6927 if (!skip_fixupish(p, &p))
6928 break;
6929 }
6930
6931 entry = hashmap_get_entry_from_hash(&subject2item,
6932 strhash(p), p,
6933 struct subject2item_entry,
6934 entry);
6935 if (entry)
6936 /* found by title */
6937 i2 = entry->i;
6938 else if (!strchr(p, ' ') &&
6939 (commit2 =
6940 lookup_commit_reference_by_name(p)) &&
6941 *commit_todo_item_at(&commit_todo, commit2))
6942 /* found by commit name */
6943 i2 = *commit_todo_item_at(&commit_todo, commit2)
6944 - todo_list->items;
6945 else {
6946 /* copy can be a prefix of the commit subject */
6947 for (i2 = 0; i2 < i; i2++)
6948 if (subjects[i2] &&
6949 starts_with(subjects[i2], p))
6950 break;
6951 if (i2 == i)
6952 i2 = -1;
6953 }
6954 }
6955 if (i2 >= 0) {
6956 rearranged = 1;
6957 if (starts_with(subject, "fixup!")) {
6958 todo_list->items[i].command = TODO_FIXUP;
6959 } else if (starts_with(subject, "amend!")) {
6960 todo_list->items[i].command = TODO_FIXUP;
6961 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6962 } else {
6963 todo_list->items[i].command = TODO_SQUASH;
6964 }
6965 if (tail[i2] < 0) {
6966 next[i] = next[i2];
6967 next[i2] = i;
6968 } else {
6969 next[i] = next[tail[i2]];
6970 next[tail[i2]] = i;
6971 }
6972 tail[i2] = i;
6973 } else if (!hashmap_get_from_hash(&subject2item,
6974 strhash(subject), subject)) {
6975 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6976 entry->i = i;
6977 hashmap_entry_init(&entry->entry,
6978 strhash(entry->subject));
6979 hashmap_put(&subject2item, &entry->entry);
6980 }
6981
6982 *commit_todo_item_at(&commit_todo, item->commit) = item;
6983 }
6984
6985 if (rearranged) {
6986 ALLOC_ARRAY(items, todo_list->nr);
6987
6988 for (i = 0; i < todo_list->nr; i++) {
6989 enum todo_command command = todo_list->items[i].command;
6990 int cur = i;
6991
6992 /*
6993 * Initially, all commands are 'pick's. If it is a
6994 * fixup or a squash now, we have rearranged it.
6995 */
6996 if (is_fixup(command))
6997 continue;
6998
6999 while (cur >= 0) {
7000 items[nr++] = todo_list->items[cur];
7001 cur = next[cur];
7002 }
7003 }
7004
7005 assert(nr == todo_list->nr);
7006 todo_list->alloc = nr;
7007 FREE_AND_NULL(todo_list->items);
7008 todo_list->items = items;
7009 }
7010
7011cleanup:
7012 free(next);
7013 free(tail);
7014 for (i = 0; i < todo_list->nr; i++)
7015 free(subjects[i]);
7016 free(subjects);
7017 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
7018
7019 clear_commit_todo_item(&commit_todo);
7020
7021 return ret;
7022}
7023
7024int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
7025{
7026 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
7027 struct object_id cherry_pick_head, rebase_head;
7028
7029 if (file_exists(git_path_seq_dir()))
7030 *whence = FROM_CHERRY_PICK_MULTI;
7031 if (file_exists(rebase_path()) &&
7032 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
7033 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
7034 oideq(&rebase_head, &cherry_pick_head))
7035 *whence = FROM_REBASE_PICK;
7036 else
7037 *whence = FROM_CHERRY_PICK_SINGLE;
7038
7039 return 1;
7040 }
7041
7042 return 0;
7043}
7044
7045int sequencer_get_update_refs_state(const char *wt_dir,
7046 struct string_list *refs)
7047{
7048 int result = 0;
7049 FILE *fp = NULL;
7050 struct strbuf ref = STRBUF_INIT;
7051 struct strbuf hash = STRBUF_INIT;
7052 struct update_ref_record *rec = NULL;
7053
7054 char *path = rebase_path_update_refs(wt_dir);
7055
7056 fp = fopen(path, "r");
7057 if (!fp)
7058 goto cleanup;
7059
7060 while (strbuf_getline(&ref, fp) != EOF) {
7061 struct string_list_item *item;
7062
7063 CALLOC_ARRAY(rec, 1);
7064
7065 if (strbuf_getline(&hash, fp) == EOF ||
7066 get_oid_hex(hash.buf, &rec->before)) {
7067 warning(_("update-refs file at '%s' is invalid"),
7068 path);
7069 result = -1;
7070 goto cleanup;
7071 }
7072
7073 if (strbuf_getline(&hash, fp) == EOF ||
7074 get_oid_hex(hash.buf, &rec->after)) {
7075 warning(_("update-refs file at '%s' is invalid"),
7076 path);
7077 result = -1;
7078 goto cleanup;
7079 }
7080
7081 item = string_list_insert(refs, ref.buf);
7082 item->util = rec;
7083 rec = NULL;
7084 }
7085
7086cleanup:
7087 if (fp)
7088 fclose(fp);
7089 free(path);
7090 free(rec);
7091 strbuf_release(&ref);
7092 strbuf_release(&hash);
7093 return result;
7094}