at commit 786fc390

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