at commit 0f8e75ab

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