at commit b4dedbc0

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