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