at commit 62575882

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