Raw
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
3
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "advice.h"
7 #include "config.h"
8 #include "copy.h"
9 #include "environment.h"
10 #include "gettext.h"
11 #include "hex.h"
12 #include "lockfile.h"
13 #include "dir.h"
14 #include "object-file.h"
15 #include "object-name.h"
16 #include "odb.h"
17 #include "object.h"
18 #include "pager.h"
19 #include "commit.h"
20 #include "sequencer.h"
21 #include "run-command.h"
22 #include "hook.h"
23 #include "utf8.h"
24 #include "cache-tree.h"
25 #include "diff.h"
26 #include "path.h"
27 #include "revision.h"
28 #include "rerere.h"
29 #include "merge.h"
30 #include "merge-ort.h"
31 #include "merge-ort-wrappers.h"
32 #include "refs.h"
33 #include "sparse-index.h"
34 #include "strvec.h"
35 #include "quote.h"
36 #include "trailer.h"
37 #include "log-tree.h"
38 #include "wt-status.h"
39 #include "hashmap.h"
40 #include "notes-utils.h"
41 #include "sigchain.h"
42 #include "unpack-trees.h"
43 #include "oidmap.h"
44 #include "oidset.h"
45 #include "commit-slab.h"
46 #include "alias.h"
47 #include "commit-reach.h"
48 #include "rebase-interactive.h"
49 #include "reset.h"
50 #include "branch.h"
51
52 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
53
54 /*
55 * To accommodate common filesystem limitations, where the loose refs' file
56 * names must not exceed `NAME_MAX`, the labels generated by `git rebase
57 * --rebase-merges` need to be truncated if the corresponding commit subjects
58 * are too long.
59 * Add some margin to stay clear from reaching `NAME_MAX`.
60 */
61 #define GIT_MAX_LABEL_LENGTH ((NAME_MAX) - (LOCK_SUFFIX_LEN) - 16)
62
63 static const char sign_off_header[] = "Signed-off-by: ";
64 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
65
66 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
67
68 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
69
70 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
71 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
72 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
73 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
74
75 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
76 /*
77 * The file containing rebase commands, comments, and empty lines.
78 * This file is created by "git rebase -i" then edited by the user. As
79 * the lines are processed, they are removed from the front of this
80 * file and written to the tail of 'done'.
81 */
82 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
83 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
84
85 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
86
87 /*
88 * The rebase command lines that have already been processed. A line
89 * is moved here when it is first handled, before any associated user
90 * actions.
91 */
92 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
93 /*
94 * The file to keep track of how many commands were already processed (e.g.
95 * for the prompt).
96 */
97 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
98 /*
99 * The file to keep track of how many commands are to be processed in total
100 * (e.g. for the prompt).
101 */
102 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
103 /*
104 * The commit message that is planned to be used for any changes that
105 * need to be committed following a user interaction.
106 */
107 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
108 /*
109 * The file into which is accumulated the suggested commit message for
110 * squash/fixup commands. When the first of a series of squash/fixups
111 * is seen, the file is created and the commit message from the
112 * previous commit and from the first squash/fixup commit are written
113 * to it. The commit message for each subsequent squash/fixup commit
114 * is appended to the file as it is processed.
115 */
116 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
117 /*
118 * If the current series of squash/fixups has not yet included a squash
119 * command, then this file exists and holds the commit message of the
120 * original "pick" commit. (If the series ends without a "squash"
121 * command, then this can be used as the commit message of the combined
122 * commit without opening the editor.)
123 */
124 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
125 /*
126 * This file contains the list fixup/squash commands that have been
127 * accumulated into message-fixup or message-squash so far.
128 */
129 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
130 /*
131 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
132 * GIT_AUTHOR_DATE that will be used for the commit that is currently
133 * being rebased.
134 */
135 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
136 /*
137 * When an "edit" rebase command is being processed, the SHA1 of the
138 * commit to be edited is recorded in this file. When "git rebase
139 * --continue" is executed, if there are any staged changes then they
140 * will be amended to the HEAD commit, but only provided the HEAD
141 * commit is still the commit to be edited. When any other rebase
142 * command is processed, this file is deleted.
143 */
144 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
145 /*
146 * When we stop at a given patch via the "edit" command, this file contains
147 * the commit object name of the corresponding patch.
148 */
149 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
150 /*
151 * When we stop for the user to resolve conflicts this file contains
152 * the patch of the commit that is being picked.
153 */
154 static GIT_PATH_FUNC(rebase_path_patch, "rebase-merge/patch")
155 /*
156 * For the post-rewrite hook, we make a list of rewritten commits and
157 * their new sha1s. The rewritten-pending list keeps the sha1s of
158 * commits that have been processed, but not committed yet,
159 * e.g. because they are waiting for a 'squash' command.
160 */
161 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
162 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
163 "rebase-merge/rewritten-pending")
164
165 /*
166 * The path of the file containing the OID of the "squash onto" commit, i.e.
167 * the dummy commit used for `reset [new root]`.
168 */
169 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
170
171 /*
172 * The path of the file listing refs that need to be deleted after the rebase
173 * finishes. This is used by the `label` command to record the need for cleanup.
174 */
175 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
176
177 /*
178 * The update-refs file stores a list of refs that will be updated at the end
179 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
180 * update the OIDs for the refs in this file, but the refs are not updated
181 * until the end of the rebase sequence.
182 *
183 * rebase_path_update_refs() returns the path to this file for a given
184 * worktree directory. For the current worktree, pass the_repository->gitdir.
185 */
186 static char *rebase_path_update_refs(const char *wt_git_dir)
187 {
188 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
189 }
190
191 /*
192 * The following files are written by git-rebase just after parsing the
193 * command-line.
194 */
195 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
196 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
197 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
198 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
199 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
200 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
201 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
202 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
203 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
204 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
205 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
206 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
207 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
208 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
209 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
210 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
211 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
212 static GIT_PATH_FUNC(rebase_path_trailer, "rebase-merge/trailer")
213
214 /*
215 * A 'struct replay_ctx' represents the private state of the sequencer.
216 */
217 struct replay_ctx {
218 /*
219 * The commit message that will be used except at the end of a
220 * chain of fixup and squash commands.
221 */
222 struct strbuf message;
223 /*
224 * The list of completed fixup and squash commands in the
225 * current chain.
226 */
227 struct strbuf current_fixups;
228 /*
229 * The number of completed fixup and squash commands in the
230 * current chain.
231 */
232 int current_fixup_count;
233 /*
234 * Whether message contains a commit message.
235 */
236 unsigned have_message :1;
237 };
238
239 struct replay_ctx* replay_ctx_new(void)
240 {
241 struct replay_ctx *ctx = xcalloc(1, sizeof(*ctx));
242
243 strbuf_init(&ctx->current_fixups, 0);
244 strbuf_init(&ctx->message, 0);
245
246 return ctx;
247 }
248
249 /**
250 * A 'struct update_refs_record' represents a value in the update-refs
251 * list. We use a string_list to map refs to these (before, after) pairs.
252 */
253 struct update_ref_record {
254 struct object_id before;
255 struct object_id after;
256 };
257
258 static struct update_ref_record *init_update_ref_record(const char *ref)
259 {
260 struct update_ref_record *rec;
261
262 CALLOC_ARRAY(rec, 1);
263
264 oidcpy(&rec->before, null_oid(the_hash_algo));
265 oidcpy(&rec->after, null_oid(the_hash_algo));
266
267 /* This may fail, but that's fine, we will keep the null OID. */
268 refs_read_ref(get_main_ref_store(the_repository), ref, &rec->before);
269
270 return rec;
271 }
272
273 static int git_sequencer_config(const char *k, const char *v,
274 const struct config_context *ctx, void *cb)
275 {
276 struct replay_opts *opts = cb;
277
278 if (!strcmp(k, "commit.cleanup")) {
279 if (!v)
280 return config_error_nonbool(k);
281
282 if (!strcmp(v, "verbatim")) {
283 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
284 opts->explicit_cleanup = 1;
285 } else if (!strcmp(v, "whitespace")) {
286 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
287 opts->explicit_cleanup = 1;
288 } else if (!strcmp(v, "strip")) {
289 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
290 opts->explicit_cleanup = 1;
291 } else if (!strcmp(v, "scissors")) {
292 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
293 opts->explicit_cleanup = 1;
294 } else {
295 warning(_("invalid commit message cleanup mode '%s'"),
296 v);
297 }
298
299 return 0;
300 }
301
302 if (!strcmp(k, "commit.gpgsign")) {
303 free(opts->gpg_sign);
304 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
305 return 0;
306 }
307
308 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
309 int ret = git_config_string(&opts->default_strategy, k, v);
310 if (ret == 0) {
311 /*
312 * pull.twohead is allowed to be multi-valued; we only
313 * care about the first value.
314 */
315 char *tmp = strchr(opts->default_strategy, ' ');
316 if (tmp)
317 *tmp = '\0';
318 }
319 return ret;
320 }
321
322 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
323 opts->commit_use_reference = git_config_bool(k, v);
324
325 return git_diff_basic_config(k, v, ctx, NULL);
326 }
327
328 void sequencer_init_config(struct replay_opts *opts)
329 {
330 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
331 repo_config(the_repository, git_sequencer_config, opts);
332 }
333
334 static inline int is_rebase_i(const struct replay_opts *opts)
335 {
336 return opts->action == REPLAY_INTERACTIVE_REBASE;
337 }
338
339 static const char *get_dir(const struct replay_opts *opts)
340 {
341 if (is_rebase_i(opts))
342 return rebase_path();
343 return git_path_seq_dir();
344 }
345
346 static const char *get_todo_path(const struct replay_opts *opts)
347 {
348 if (is_rebase_i(opts))
349 return rebase_path_todo();
350 return git_path_todo_file();
351 }
352
353 /*
354 * Returns 0 for non-conforming footer
355 * Returns 1 for conforming footer
356 * Returns 2 when sob exists within conforming footer
357 * Returns 3 when sob exists within conforming footer as last entry
358 */
359 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
360 size_t ignore_footer)
361 {
362 struct trailer_iterator iter;
363 size_t i = 0;
364 int found_sob = 0, found_sob_last = 0;
365 char saved_char;
366
367 if (ignore_footer) {
368 saved_char = sb->buf[sb->len - ignore_footer];
369 sb->buf[sb->len - ignore_footer] = '\0';
370 }
371
372 trailer_iterator_init(&iter, sb->buf);
373
374 if (ignore_footer)
375 sb->buf[sb->len - ignore_footer] = saved_char;
376
377 while (trailer_iterator_advance(&iter)) {
378 i++;
379 if (sob && !strncmp(iter.raw, sob->buf, sob->len))
380 found_sob = i;
381 }
382 trailer_iterator_release(&iter);
383
384 if (!i)
385 return 0;
386
387 found_sob_last = (int)i == found_sob;
388
389 if (found_sob_last)
390 return 3;
391 if (found_sob)
392 return 2;
393 return 1;
394 }
395
396 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
397 {
398 static struct strbuf buf = STRBUF_INIT;
399
400 strbuf_reset(&buf);
401 if (opts->gpg_sign)
402 sq_quotef(&buf, "-S%s", opts->gpg_sign);
403 return buf.buf;
404 }
405
406 static void replay_ctx_release(struct replay_ctx *ctx)
407 {
408 strbuf_release(&ctx->current_fixups);
409 strbuf_release(&ctx->message);
410 }
411
412 void replay_opts_release(struct replay_opts *opts)
413 {
414 struct replay_ctx *ctx = opts->ctx;
415
416 free(opts->gpg_sign);
417 free(opts->reflog_action);
418 free(opts->default_strategy);
419 free(opts->strategy);
420 strvec_clear (&opts->xopts);
421 if (opts->revs)
422 release_revisions(opts->revs);
423 free(opts->revs);
424 strvec_clear(&opts->trailer_args);
425 replay_ctx_release(ctx);
426 free(opts->ctx);
427 }
428
429 int sequencer_remove_state(struct replay_opts *opts)
430 {
431 struct strbuf buf = STRBUF_INIT;
432 int ret = 0;
433
434 if (is_rebase_i(opts) &&
435 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
436 char *p = buf.buf;
437 while (*p) {
438 char *eol = strchr(p, '\n');
439 if (eol)
440 *eol = '\0';
441 if (refs_delete_ref(get_main_ref_store(the_repository), "(rebase) cleanup", p, NULL, 0) < 0) {
442 warning(_("could not delete '%s'"), p);
443 ret = -1;
444 }
445 if (!eol)
446 break;
447 p = eol + 1;
448 }
449 }
450
451 strbuf_reset(&buf);
452 strbuf_addstr(&buf, get_dir(opts));
453 if (remove_dir_recursively(&buf, 0))
454 ret = error(_("could not remove '%s'"), buf.buf);
455 strbuf_release(&buf);
456
457 return ret;
458 }
459
460 static const char *action_name(const struct replay_opts *opts)
461 {
462 switch (opts->action) {
463 case REPLAY_REVERT:
464 return N_("revert");
465 case REPLAY_PICK:
466 return N_("cherry-pick");
467 case REPLAY_INTERACTIVE_REBASE:
468 return N_("rebase");
469 }
470 die(_("unknown action: %d"), opts->action);
471 }
472
473 struct commit_message {
474 char *parent_label;
475 char *label;
476 char *subject;
477 const char *message;
478 };
479
480 static const char *short_commit_name(struct repository *r, struct commit *commit)
481 {
482 return repo_find_unique_abbrev(r, &commit->object.oid, DEFAULT_ABBREV);
483 }
484
485 static int get_message(struct commit *commit, struct commit_message *out)
486 {
487 const char *abbrev, *subject;
488 int subject_len;
489
490 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
491 get_commit_output_encoding());
492 abbrev = short_commit_name(the_repository, commit);
493
494 subject_len = find_commit_subject(out->message, &subject);
495
496 out->subject = xmemdupz(subject, subject_len);
497 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
498 out->parent_label = xstrfmt("parent of %s", out->label);
499
500 return 0;
501 }
502
503 static void free_message(struct commit *commit, struct commit_message *msg)
504 {
505 free(msg->parent_label);
506 free(msg->label);
507 free(msg->subject);
508 repo_unuse_commit_buffer(the_repository, commit, msg->message);
509 }
510
511 const char *rebase_resolvemsg =
512 N_("Resolve all conflicts manually, mark them as resolved with\n"
513 "\"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\n"
514 "You can instead skip this commit: run \"git rebase --skip\".\n"
515 "To abort and get back to the state before \"git rebase\", run "
516 "\"git rebase --abort\".");
517
518 static void print_advice(struct repository *r, int show_hint,
519 struct replay_opts *opts)
520 {
521 const char *msg;
522
523 if (is_rebase_i(opts))
524 msg = rebase_resolvemsg;
525 else
526 msg = getenv("GIT_CHERRY_PICK_HELP");
527
528 if (msg) {
529 advise_if_enabled(ADVICE_MERGE_CONFLICT, "%s", msg);
530 /*
531 * A conflict has occurred but the porcelain
532 * (typically rebase --interactive) wants to take care
533 * of the commit itself so remove CHERRY_PICK_HEAD
534 */
535 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
536 NULL, REF_NO_DEREF);
537 return;
538 }
539
540 if (show_hint) {
541 if (opts->no_commit)
542 advise_if_enabled(ADVICE_MERGE_CONFLICT,
543 _("after resolving the conflicts, mark the corrected paths\n"
544 "with 'git add <paths>' or 'git rm <paths>'"));
545 else if (opts->action == REPLAY_PICK)
546 advise_if_enabled(ADVICE_MERGE_CONFLICT,
547 _("After resolving the conflicts, mark them with\n"
548 "\"git add/rm <pathspec>\", then run\n"
549 "\"git cherry-pick --continue\".\n"
550 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
551 "To abort and get back to the state before \"git cherry-pick\",\n"
552 "run \"git cherry-pick --abort\"."));
553 else if (opts->action == REPLAY_REVERT)
554 advise_if_enabled(ADVICE_MERGE_CONFLICT,
555 _("After resolving the conflicts, mark them with\n"
556 "\"git add/rm <pathspec>\", then run\n"
557 "\"git revert --continue\".\n"
558 "You can instead skip this commit with \"git revert --skip\".\n"
559 "To abort and get back to the state before \"git revert\",\n"
560 "run \"git revert --abort\"."));
561 else
562 BUG("unexpected pick action in print_advice()");
563 }
564 }
565
566 static int write_message(const void *buf, size_t len, const char *filename,
567 int append_eol)
568 {
569 struct lock_file msg_file = LOCK_INIT;
570
571 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
572 if (msg_fd < 0)
573 return error_errno(_("could not lock '%s'"), filename);
574 if (write_in_full(msg_fd, buf, len) < 0) {
575 error_errno(_("could not write to '%s'"), filename);
576 rollback_lock_file(&msg_file);
577 return -1;
578 }
579 if (append_eol && write(msg_fd, "\n", 1) < 0) {
580 error_errno(_("could not write eol to '%s'"), filename);
581 rollback_lock_file(&msg_file);
582 return -1;
583 }
584 if (commit_lock_file(&msg_file) < 0)
585 return error(_("failed to finalize '%s'"), filename);
586
587 return 0;
588 }
589
590 int read_oneliner(struct strbuf *buf,
591 const char *path, unsigned flags)
592 {
593 int orig_len = buf->len;
594
595 if (strbuf_read_file(buf, path, 0) < 0) {
596 if ((flags & READ_ONELINER_WARN_MISSING) ||
597 (errno != ENOENT && errno != ENOTDIR))
598 warning_errno(_("could not read '%s'"), path);
599 return 0;
600 }
601
602 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
603 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
604 --buf->len;
605 buf->buf[buf->len] = '\0';
606 }
607
608 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
609 return 0;
610
611 return 1;
612 }
613
614 static struct tree *empty_tree(struct repository *r)
615 {
616 return lookup_tree(r, the_hash_algo->empty_tree);
617 }
618
619 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
620 {
621 if (repo_read_index_unmerged(repo))
622 return error_resolve_conflict(action_name(opts));
623
624 error(_("your local changes would be overwritten by %s."),
625 _(action_name(opts)));
626
627 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
628 advise(_("commit your changes or stash them to proceed."));
629 return -1;
630 }
631
632 static void update_abort_safety_file(void)
633 {
634 struct object_id head;
635
636 /* Do nothing on a single-pick */
637 if (!file_exists(git_path_seq_dir()))
638 return;
639
640 if (!repo_get_oid(the_repository, "HEAD", &head))
641 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
642 else
643 write_file(git_path_abort_safety_file(), "%s", "");
644 }
645
646 static int fast_forward_to(struct repository *r,
647 const struct object_id *to,
648 const struct object_id *from,
649 int unborn,
650 struct replay_opts *opts)
651 {
652 struct ref_transaction *transaction;
653 struct strbuf sb = STRBUF_INIT;
654 struct strbuf err = STRBUF_INIT;
655
656 repo_read_index(r);
657 if (checkout_fast_forward(r, from, to, 1))
658 return -1; /* the callee should have complained already */
659
660 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
661
662 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
663 0, &err);
664 if (!transaction ||
665 ref_transaction_update(transaction, "HEAD",
666 to, unborn && !is_rebase_i(opts) ?
667 null_oid(the_hash_algo) : from, NULL, NULL,
668 0, sb.buf, &err) ||
669 ref_transaction_commit(transaction, &err)) {
670 ref_transaction_free(transaction);
671 error("%s", err.buf);
672 strbuf_release(&sb);
673 strbuf_release(&err);
674 return -1;
675 }
676
677 strbuf_release(&sb);
678 strbuf_release(&err);
679 ref_transaction_free(transaction);
680 update_abort_safety_file();
681 return 0;
682 }
683
684 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
685 int use_editor)
686 {
687 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
688 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
689 COMMIT_MSG_CLEANUP_SPACE;
690 else if (!strcmp(cleanup_arg, "verbatim"))
691 return COMMIT_MSG_CLEANUP_NONE;
692 else if (!strcmp(cleanup_arg, "whitespace"))
693 return COMMIT_MSG_CLEANUP_SPACE;
694 else if (!strcmp(cleanup_arg, "strip"))
695 return COMMIT_MSG_CLEANUP_ALL;
696 else if (!strcmp(cleanup_arg, "scissors"))
697 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
698 COMMIT_MSG_CLEANUP_SPACE;
699 else
700 die(_("Invalid cleanup mode %s"), cleanup_arg);
701 }
702
703 /*
704 * NB using int rather than enum cleanup_mode to stop clang's
705 * -Wtautological-constant-out-of-range-compare complaining that the comparison
706 * is always true.
707 */
708 static const char *describe_cleanup_mode(int cleanup_mode)
709 {
710 static const char *modes[] = { "whitespace",
711 "verbatim",
712 "scissors",
713 "strip" };
714
715 if (cleanup_mode < ARRAY_SIZE(modes))
716 return modes[cleanup_mode];
717
718 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
719 }
720
721 void append_conflicts_hint(struct index_state *istate,
722 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
723 {
724 int i;
725
726 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
727 strbuf_addch(msgbuf, '\n');
728 wt_status_append_cut_line(msgbuf);
729 strbuf_addstr(msgbuf, comment_line_str);
730 }
731
732 strbuf_addch(msgbuf, '\n');
733 strbuf_commented_addf(msgbuf, comment_line_str, "Conflicts:\n");
734 for (i = 0; i < istate->cache_nr;) {
735 const struct cache_entry *ce = istate->cache[i++];
736 if (ce_stage(ce)) {
737 strbuf_commented_addf(msgbuf, comment_line_str,
738 "\t%s\n", ce->name);
739 while (i < istate->cache_nr &&
740 !strcmp(ce->name, istate->cache[i]->name))
741 i++;
742 }
743 }
744 }
745
746 static int do_recursive_merge(struct repository *r,
747 struct commit *base, struct commit *next,
748 const char *base_label, const char *next_label,
749 struct object_id *head, struct strbuf *msgbuf,
750 struct replay_opts *opts)
751 {
752 struct merge_options o;
753 struct merge_result result;
754 struct tree *next_tree, *base_tree, *head_tree;
755 int clean, show_output;
756 int i;
757 struct lock_file index_lock = LOCK_INIT;
758
759 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
760 return -1;
761
762 repo_read_index(r);
763
764 init_ui_merge_options(&o, r);
765 o.ancestor = base ? base_label : "(empty tree)";
766 o.branch1 = "HEAD";
767 o.branch2 = next ? next_label : "(empty tree)";
768 if (is_rebase_i(opts))
769 o.buffer_output = 2;
770 o.show_rename_progress = 1;
771
772 head_tree = repo_parse_tree_indirect(the_repository, head);
773 if (!head_tree)
774 return error(_("unable to read tree (%s)"), oid_to_hex(head));
775 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
776 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
777
778 for (i = 0; i < opts->xopts.nr; i++)
779 parse_merge_opt(&o, opts->xopts.v[i]);
780
781 memset(&result, 0, sizeof(result));
782 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree, &result);
783 show_output = !is_rebase_i(opts) || !result.clean;
784 /*
785 * TODO: merge_switch_to_result will update index/working tree;
786 * we only really want to do that if !result.clean || this is
787 * the final patch to be picked. But determining this is the
788 * final patch would take some work, and "head_tree" would need
789 * to be replace with the tree the index matched before we
790 * started doing any picks.
791 */
792 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
793 clean = result.clean;
794 if (clean < 0) {
795 rollback_lock_file(&index_lock);
796 return clean;
797 }
798
799 if (write_locked_index(r->index, &index_lock,
800 COMMIT_LOCK | SKIP_IF_UNCHANGED))
801 /*
802 * TRANSLATORS: %s will be "revert", "cherry-pick" or
803 * "rebase".
804 */
805 return error(_("%s: Unable to write new index file"),
806 _(action_name(opts)));
807
808 if (!clean)
809 append_conflicts_hint(r->index, msgbuf,
810 opts->default_msg_cleanup);
811
812 return !clean;
813 }
814
815 static struct object_id *get_cache_tree_oid(struct index_state *istate)
816 {
817 if (!cache_tree_fully_valid(istate->cache_tree))
818 if (cache_tree_update(istate, 0)) {
819 error(_("unable to update cache tree"));
820 return NULL;
821 }
822
823 return &istate->cache_tree->oid;
824 }
825
826 static int is_index_unchanged(struct repository *r)
827 {
828 struct object_id head_oid, *cache_tree_oid;
829 const struct object_id *head_tree_oid;
830 struct commit *head_commit;
831 struct index_state *istate = r->index;
832 const char *head_name;
833
834 if (!refs_resolve_ref_unsafe(get_main_ref_store(the_repository), "HEAD", RESOLVE_REF_READING, &head_oid, NULL)) {
835 /* Check to see if this is an unborn branch */
836 head_name = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
837 "HEAD",
838 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,
839 &head_oid, NULL);
840 if (!head_name ||
841 !starts_with(head_name, "refs/heads/") ||
842 !is_null_oid(&head_oid))
843 return error(_("could not resolve HEAD commit"));
844 head_tree_oid = the_hash_algo->empty_tree;
845 } else {
846 head_commit = lookup_commit(r, &head_oid);
847
848 /*
849 * If head_commit is NULL, check_commit, called from
850 * lookup_commit, would have indicated that head_commit is not
851 * a commit object already. repo_parse_commit() will return failure
852 * without further complaints in such a case. Otherwise, if
853 * the commit is invalid, repo_parse_commit() will complain. So
854 * there is nothing for us to say here. Just return failure.
855 */
856 if (repo_parse_commit(r, head_commit))
857 return -1;
858
859 head_tree_oid = get_commit_tree_oid(head_commit);
860 }
861
862 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
863 return -1;
864
865 return oideq(cache_tree_oid, head_tree_oid);
866 }
867
868 static int write_author_script(const char *message)
869 {
870 struct strbuf buf = STRBUF_INIT;
871 const char *eol;
872 int res;
873
874 for (;;)
875 if (!*message || starts_with(message, "\n")) {
876 missing_author:
877 /* Missing 'author' line? */
878 unlink(rebase_path_author_script());
879 return 0;
880 } else if (skip_prefix(message, "author ", &message))
881 break;
882 else if ((eol = strchr(message, '\n')))
883 message = eol + 1;
884 else
885 goto missing_author;
886
887 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
888 while (*message && *message != '\n' && *message != '\r')
889 if (skip_prefix(message, " <", &message))
890 break;
891 else if (*message != '\'')
892 strbuf_addch(&buf, *(message++));
893 else
894 strbuf_addf(&buf, "'\\%c'", *(message++));
895 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
896 while (*message && *message != '\n' && *message != '\r')
897 if (skip_prefix(message, "> ", &message))
898 break;
899 else if (*message != '\'')
900 strbuf_addch(&buf, *(message++));
901 else
902 strbuf_addf(&buf, "'\\%c'", *(message++));
903 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
904 while (*message && *message != '\n' && *message != '\r')
905 if (*message != '\'')
906 strbuf_addch(&buf, *(message++));
907 else
908 strbuf_addf(&buf, "'\\%c'", *(message++));
909 strbuf_addch(&buf, '\'');
910 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
911 strbuf_release(&buf);
912 return res;
913 }
914
915 /**
916 * Take a series of KEY='VALUE' lines where VALUE part is
917 * sq-quoted, and append <KEY, VALUE> at the end of the string list
918 */
919 static int parse_key_value_squoted(char *buf, struct string_list *list)
920 {
921 while (*buf) {
922 struct string_list_item *item;
923 char *np;
924 char *cp = strchr(buf, '=');
925 if (!cp) {
926 np = strchrnul(buf, '\n');
927 return error(_("no key present in '%.*s'"),
928 (int) (np - buf), buf);
929 }
930 np = strchrnul(cp, '\n');
931 *cp++ = '\0';
932 item = string_list_append(list, buf);
933
934 buf = np + (*np == '\n');
935 *np = '\0';
936 cp = sq_dequote(cp);
937 if (!cp)
938 return error(_("unable to dequote value of '%s'"),
939 item->string);
940 item->util = xstrdup(cp);
941 }
942 return 0;
943 }
944
945 /**
946 * Reads and parses the state directory's "author-script" file, and sets name,
947 * email and date accordingly.
948 * Returns 0 on success, -1 if the file could not be parsed.
949 *
950 * The author script is of the format:
951 *
952 * GIT_AUTHOR_NAME='$author_name'
953 * GIT_AUTHOR_EMAIL='$author_email'
954 * GIT_AUTHOR_DATE='$author_date'
955 *
956 * where $author_name, $author_email and $author_date are quoted. We are strict
957 * with our parsing, as the file was meant to be eval'd in the now-removed
958 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
959 * from what this function expects, it is better to bail out than to do
960 * something that the user does not expect.
961 */
962 int read_author_script(const char *path, char **name, char **email, char **date,
963 int allow_missing)
964 {
965 struct strbuf buf = STRBUF_INIT;
966 struct string_list kv = STRING_LIST_INIT_DUP;
967 int retval = -1; /* assume failure */
968 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
969
970 if (strbuf_read_file(&buf, path, 256) <= 0) {
971 strbuf_release(&buf);
972 if (errno == ENOENT && allow_missing)
973 return 0;
974 else
975 return error_errno(_("could not open '%s' for reading"),
976 path);
977 }
978
979 if (parse_key_value_squoted(buf.buf, &kv))
980 goto finish;
981
982 for (i = 0; i < kv.nr; i++) {
983 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
984 if (name_i != -2)
985 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
986 else
987 name_i = i;
988 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
989 if (email_i != -2)
990 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
991 else
992 email_i = i;
993 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
994 if (date_i != -2)
995 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
996 else
997 date_i = i;
998 } else {
999 err = error(_("unknown variable '%s'"),
1000 kv.items[i].string);
1001 }
1002 }
1003 if (name_i == -2)
1004 error(_("missing 'GIT_AUTHOR_NAME'"));
1005 if (email_i == -2)
1006 error(_("missing 'GIT_AUTHOR_EMAIL'"));
1007 if (date_i == -2)
1008 error(_("missing 'GIT_AUTHOR_DATE'"));
1009 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
1010 goto finish;
1011 *name = kv.items[name_i].util;
1012 *email = kv.items[email_i].util;
1013 *date = kv.items[date_i].util;
1014 retval = 0;
1015 finish:
1016 string_list_clear(&kv, !!retval);
1017 strbuf_release(&buf);
1018 return retval;
1019 }
1020
1021 /*
1022 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
1023 * file with shell quoting into struct strvec. Returns -1 on
1024 * error, 0 otherwise.
1025 */
1026 static int read_env_script(struct strvec *env)
1027 {
1028 char *name, *email, *date;
1029
1030 if (read_author_script(rebase_path_author_script(),
1031 &name, &email, &date, 0))
1032 return -1;
1033
1034 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
1035 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
1036 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
1037 free(name);
1038 free(email);
1039 free(date);
1040
1041 return 0;
1042 }
1043
1044 static char *get_author(const char *message)
1045 {
1046 size_t len;
1047 const char *a;
1048
1049 a = find_commit_header(message, "author", &len);
1050 if (a)
1051 return xmemdupz(a, len);
1052
1053 return NULL;
1054 }
1055
1056 static const char *author_date_from_env(const struct strvec *env)
1057 {
1058 int i;
1059 const char *date;
1060
1061 for (i = 0; i < env->nr; i++)
1062 if (skip_prefix(env->v[i],
1063 "GIT_AUTHOR_DATE=", &date))
1064 return date;
1065 /*
1066 * If GIT_AUTHOR_DATE is missing we should have already errored out when
1067 * reading the script
1068 */
1069 BUG("GIT_AUTHOR_DATE missing from author script");
1070 }
1071
1072 static const char staged_changes_advice[] =
1073 N_("you have staged changes in your working tree\n"
1074 "If these changes are meant to be squashed into the previous commit, run:\n"
1075 "\n"
1076 " git commit --amend %s\n"
1077 "\n"
1078 "If they are meant to go into a new commit, run:\n"
1079 "\n"
1080 " git commit %s\n"
1081 "\n"
1082 "In both cases, once you're done, continue with:\n"
1083 "\n"
1084 " git rebase --continue\n");
1085
1086 #define ALLOW_EMPTY (1<<0)
1087 #define EDIT_MSG (1<<1)
1088 #define AMEND_MSG (1<<2)
1089 #define CLEANUP_MSG (1<<3)
1090 #define VERIFY_MSG (1<<4)
1091 #define CREATE_ROOT_COMMIT (1<<5)
1092
1093 static int run_command_silent_on_success(struct child_process *cmd)
1094 {
1095 struct strbuf buf = STRBUF_INIT;
1096 int rc;
1097
1098 cmd->stdout_to_stderr = 1;
1099 rc = pipe_command(cmd,
1100 NULL, 0,
1101 NULL, 0,
1102 &buf, 0);
1103
1104 if (rc)
1105 fputs(buf.buf, stderr);
1106 strbuf_release(&buf);
1107 return rc;
1108 }
1109
1110 /*
1111 * If we are cherry-pick, and if the merge did not result in
1112 * hand-editing, we will hit this commit and inherit the original
1113 * author date and name.
1114 *
1115 * If we are revert, or if our cherry-pick results in a hand merge,
1116 * we had better say that the current user is responsible for that.
1117 *
1118 * An exception is when run_git_commit() is called during an
1119 * interactive rebase: in that case, we will want to retain the
1120 * author metadata.
1121 */
1122 static int run_git_commit(const char *defmsg,
1123 const char *reflog_action,
1124 struct replay_opts *opts,
1125 unsigned int flags)
1126 {
1127 struct child_process cmd = CHILD_PROCESS_INIT;
1128
1129 cmd.git_cmd = 1;
1130
1131 if (is_rebase_i(opts) &&
1132 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1133 !(!defmsg && (flags & AMEND_MSG))) &&
1134 read_env_script(&cmd.env)) {
1135 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1136
1137 return error(_(staged_changes_advice),
1138 gpg_opt, gpg_opt);
1139 }
1140
1141 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", reflog_action);
1142
1143 if (opts->committer_date_is_author_date)
1144 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1145 opts->ignore_date ?
1146 "" :
1147 author_date_from_env(&cmd.env));
1148 if (opts->ignore_date)
1149 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1150
1151 strvec_push(&cmd.args, "commit");
1152
1153 if (!(flags & VERIFY_MSG))
1154 strvec_push(&cmd.args, "-n");
1155 if ((flags & AMEND_MSG))
1156 strvec_push(&cmd.args, "--amend");
1157 if (opts->gpg_sign)
1158 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1159 else
1160 strvec_push(&cmd.args, "--no-gpg-sign");
1161 if (defmsg)
1162 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1163 else if (!(flags & EDIT_MSG))
1164 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1165 if ((flags & CLEANUP_MSG))
1166 strvec_push(&cmd.args, "--cleanup=strip");
1167 if ((flags & EDIT_MSG))
1168 strvec_push(&cmd.args, "-e");
1169 else if (!(flags & CLEANUP_MSG) &&
1170 !opts->signoff && !opts->record_origin &&
1171 !opts->explicit_cleanup)
1172 strvec_push(&cmd.args, "--cleanup=verbatim");
1173
1174 if ((flags & ALLOW_EMPTY))
1175 strvec_push(&cmd.args, "--allow-empty");
1176
1177 if (!(flags & EDIT_MSG))
1178 strvec_push(&cmd.args, "--allow-empty-message");
1179
1180 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1181 return run_command_silent_on_success(&cmd);
1182 else
1183 return run_command(&cmd);
1184 }
1185
1186 static int rest_is_empty(const struct strbuf *sb, int start)
1187 {
1188 int i, eol;
1189 const char *nl;
1190
1191 /* Check if the rest is just whitespace and Signed-off-by's. */
1192 for (i = start; i < sb->len; i++) {
1193 nl = memchr(sb->buf + i, '\n', sb->len - i);
1194 if (nl)
1195 eol = nl - sb->buf;
1196 else
1197 eol = sb->len;
1198
1199 if (strlen(sign_off_header) <= eol - i &&
1200 starts_with(sb->buf + i, sign_off_header)) {
1201 i = eol;
1202 continue;
1203 }
1204 while (i < eol)
1205 if (!isspace(sb->buf[i++]))
1206 return 0;
1207 }
1208
1209 return 1;
1210 }
1211
1212 void cleanup_message(struct strbuf *msgbuf,
1213 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1214 {
1215 if (verbose || /* Truncate the message just before the diff, if any. */
1216 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1217 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1218 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1219 strbuf_stripspace(msgbuf,
1220 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1221 }
1222
1223 /*
1224 * Find out if the message in the strbuf contains only whitespace and
1225 * Signed-off-by lines.
1226 */
1227 int message_is_empty(const struct strbuf *sb,
1228 enum commit_msg_cleanup_mode cleanup_mode)
1229 {
1230 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1231 return 0;
1232 return rest_is_empty(sb, 0);
1233 }
1234
1235 /*
1236 * See if the user edited the message in the editor or left what
1237 * was in the template intact
1238 */
1239 int template_untouched(const struct strbuf *sb, const char *template_file,
1240 enum commit_msg_cleanup_mode cleanup_mode)
1241 {
1242 struct strbuf tmpl = STRBUF_INIT;
1243 const char *start;
1244
1245 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1246 return 0;
1247
1248 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1249 return 0;
1250
1251 strbuf_stripspace(&tmpl,
1252 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1253 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1254 start = sb->buf;
1255 strbuf_release(&tmpl);
1256 return rest_is_empty(sb, start - sb->buf);
1257 }
1258
1259 int update_head_with_reflog(const struct commit *old_head,
1260 const struct object_id *new_head,
1261 const char *action, const struct strbuf *msg,
1262 struct strbuf *err)
1263 {
1264 struct ref_transaction *transaction;
1265 struct strbuf sb = STRBUF_INIT;
1266 const char *nl;
1267 int ret = 0;
1268
1269 if (action) {
1270 strbuf_addstr(&sb, action);
1271 strbuf_addstr(&sb, ": ");
1272 }
1273
1274 nl = strchr(msg->buf, '\n');
1275 if (nl) {
1276 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1277 } else {
1278 strbuf_addbuf(&sb, msg);
1279 strbuf_addch(&sb, '\n');
1280 }
1281
1282 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1283 0, err);
1284 if (!transaction ||
1285 ref_transaction_update(transaction, "HEAD", new_head,
1286 old_head ? &old_head->object.oid : null_oid(the_hash_algo),
1287 NULL, NULL, 0, sb.buf, err) ||
1288 ref_transaction_commit(transaction, err)) {
1289 ret = -1;
1290 }
1291 ref_transaction_free(transaction);
1292 strbuf_release(&sb);
1293
1294 return ret;
1295 }
1296
1297 static int pipe_from_strbuf(int hook_stdin_fd, void *pp_cb, void *pp_task_cb UNUSED)
1298 {
1299 struct hook_cb_data *hook_cb = pp_cb;
1300 struct strbuf *to_pipe = hook_cb->options->feed_pipe_ctx;
1301 int ret;
1302
1303 if (!to_pipe)
1304 BUG("pipe_from_strbuf called without feed_pipe_ctx");
1305
1306 ret = write_in_full(hook_stdin_fd, to_pipe->buf, to_pipe->len);
1307 if (ret < 0 && errno != EPIPE)
1308 return ret;
1309
1310 return 1; /* done writing */
1311 }
1312
1313 static int run_rewrite_hook(const struct object_id *oldoid,
1314 const struct object_id *newoid)
1315 {
1316 struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
1317 int code;
1318 struct strbuf sb = STRBUF_INIT;
1319
1320 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1321
1322 opt.feed_pipe_ctx = &sb;
1323 opt.feed_pipe = pipe_from_strbuf;
1324
1325 strvec_push(&opt.args, "amend");
1326
1327 code = run_hooks_opt(the_repository, "post-rewrite", &opt);
1328
1329 strbuf_release(&sb);
1330 return code;
1331 }
1332
1333 void commit_post_rewrite(struct repository *r,
1334 const struct commit *old_head,
1335 const struct object_id *new_head)
1336 {
1337 struct notes_rewrite_cfg *cfg;
1338
1339 cfg = init_copy_notes_for_rewrite("amend");
1340 if (cfg) {
1341 /* we are amending, so old_head is not NULL */
1342 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1343 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1344 }
1345 run_rewrite_hook(&old_head->object.oid, new_head);
1346 }
1347
1348 static int run_prepare_commit_msg_hook(struct repository *r,
1349 struct strbuf *msg,
1350 const char *commit)
1351 {
1352 int ret = 0;
1353 const char *name, *arg1 = NULL, *arg2 = NULL;
1354
1355 name = git_path_commit_editmsg();
1356 if (write_message(msg->buf, msg->len, name, 0))
1357 return -1;
1358
1359 if (commit) {
1360 arg1 = "commit";
1361 arg2 = commit;
1362 } else {
1363 arg1 = "message";
1364 }
1365 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1366 arg1, arg2, NULL))
1367 ret = error(_("'prepare-commit-msg' hook failed"));
1368
1369 return ret;
1370 }
1371
1372 static const char implicit_ident_advice_noconfig[] =
1373 N_("Your name and email address were configured automatically based\n"
1374 "on your username and hostname. Please check that they are accurate.\n"
1375 "You can suppress this message by setting them explicitly. Run the\n"
1376 "following command and follow the instructions in your editor to edit\n"
1377 "your configuration file:\n"
1378 "\n"
1379 " git config --global --edit\n"
1380 "\n"
1381 "After doing this, you may fix the identity used for this commit with:\n"
1382 "\n"
1383 " git commit --amend --reset-author\n");
1384
1385 static const char implicit_ident_advice_config[] =
1386 N_("Your name and email address were configured automatically based\n"
1387 "on your username and hostname. Please check that they are accurate.\n"
1388 "You can suppress this message by setting them explicitly:\n"
1389 "\n"
1390 " git config --global user.name \"Your Name\"\n"
1391 " git config --global user.email you@example.com\n"
1392 "\n"
1393 "After doing this, you may fix the identity used for this commit with:\n"
1394 "\n"
1395 " git commit --amend --reset-author\n");
1396
1397 static const char *implicit_ident_advice(void)
1398 {
1399 char *user_config = interpolate_path("~/.gitconfig", 0);
1400 char *xdg_config = xdg_config_home("config");
1401 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1402
1403 free(user_config);
1404 free(xdg_config);
1405
1406 if (config_exists)
1407 return _(implicit_ident_advice_config);
1408 else
1409 return _(implicit_ident_advice_noconfig);
1410
1411 }
1412
1413 void print_commit_summary(struct repository *r,
1414 const char *prefix,
1415 const struct object_id *oid,
1416 unsigned int flags)
1417 {
1418 struct rev_info rev;
1419 struct commit *commit;
1420 struct strbuf format = STRBUF_INIT;
1421 const char *head;
1422 struct pretty_print_context pctx = {0};
1423 struct strbuf author_ident = STRBUF_INIT;
1424 struct strbuf committer_ident = STRBUF_INIT;
1425 struct ref_store *refs;
1426
1427 commit = lookup_commit(r, oid);
1428 if (!commit)
1429 die(_("couldn't look up newly created commit"));
1430 if (repo_parse_commit(r, commit))
1431 die(_("could not parse newly created commit"));
1432
1433 strbuf_addstr(&format, "format:%h] %s");
1434
1435 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1436 &pctx);
1437 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1438 &pctx);
1439 if (strbuf_cmp(&author_ident, &committer_ident)) {
1440 strbuf_addstr(&format, "\n Author: ");
1441 strbuf_addbuf_percentquote(&format, &author_ident);
1442 }
1443 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1444 struct strbuf date = STRBUF_INIT;
1445
1446 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1447 strbuf_addstr(&format, "\n Date: ");
1448 strbuf_addbuf_percentquote(&format, &date);
1449 strbuf_release(&date);
1450 }
1451 if (!committer_ident_sufficiently_given()) {
1452 strbuf_addstr(&format, "\n Committer: ");
1453 strbuf_addbuf_percentquote(&format, &committer_ident);
1454 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1455 strbuf_addch(&format, '\n');
1456 strbuf_addstr(&format, implicit_ident_advice());
1457 }
1458 }
1459 strbuf_release(&author_ident);
1460 strbuf_release(&committer_ident);
1461
1462 repo_init_revisions(r, &rev, prefix);
1463 setup_revisions(0, NULL, &rev, NULL);
1464
1465 rev.diff = 1;
1466 rev.diffopt.output_format =
1467 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1468
1469 rev.verbose_header = 1;
1470 rev.show_root_diff = 1;
1471 get_commit_format(format.buf, &rev);
1472 rev.always_show_header = 0;
1473 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1474 diff_setup_done(&rev.diffopt);
1475
1476 refs = get_main_ref_store(r);
1477 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1478 if (!head)
1479 die(_("unable to resolve HEAD after creating commit"));
1480 if (!strcmp(head, "HEAD"))
1481 head = _("detached HEAD");
1482 else
1483 skip_prefix(head, "refs/heads/", &head);
1484 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1485 _(" (root-commit)") : "");
1486
1487 if (!log_tree_commit(&rev, commit)) {
1488 rev.always_show_header = 1;
1489 rev.use_terminator = 1;
1490 log_tree_commit(&rev, commit);
1491 }
1492
1493 release_revisions(&rev);
1494 strbuf_release(&format);
1495 }
1496
1497 static int parse_head(struct repository *r, struct commit **head)
1498 {
1499 struct commit *current_head;
1500 struct object_id oid;
1501
1502 if (repo_get_oid(r, "HEAD", &oid)) {
1503 current_head = NULL;
1504 } else {
1505 current_head = lookup_commit_reference(r, &oid);
1506 if (!current_head)
1507 return error(_("could not parse HEAD"));
1508 if (!oideq(&oid, &current_head->object.oid)) {
1509 warning(_("HEAD %s is not a commit!"),
1510 oid_to_hex(&oid));
1511 }
1512 if (repo_parse_commit(r, current_head))
1513 return error(_("could not parse HEAD commit"));
1514 }
1515 *head = current_head;
1516
1517 return 0;
1518 }
1519
1520 /*
1521 * Try to commit without forking 'git commit'. In some cases we need
1522 * to run 'git commit' to display an error message
1523 *
1524 * Returns:
1525 * -1 - error unable to commit
1526 * 0 - success
1527 * 1 - run 'git commit'
1528 */
1529 static int try_to_commit(struct repository *r,
1530 struct strbuf *msg, const char *author,
1531 const char *reflog_action,
1532 struct replay_opts *opts, unsigned int flags,
1533 struct object_id *oid)
1534 {
1535 struct object_id tree;
1536 struct commit *current_head = NULL;
1537 struct commit_list *parents = NULL;
1538 struct commit_extra_header *extra = NULL;
1539 struct strbuf err = STRBUF_INIT;
1540 struct strbuf commit_msg = STRBUF_INIT;
1541 char *amend_author = NULL;
1542 const char *committer = NULL;
1543 const char *hook_commit = NULL;
1544 enum commit_msg_cleanup_mode cleanup;
1545 int res = 0;
1546
1547 if (parse_head(r, &current_head))
1548 return -1;
1549
1550 if (flags & AMEND_MSG) {
1551 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1552 const char *out_enc = get_commit_output_encoding();
1553 const char *message = repo_logmsg_reencode(r, current_head,
1554 NULL, out_enc);
1555
1556 if (!msg) {
1557 const char *orig_message = NULL;
1558
1559 find_commit_subject(message, &orig_message);
1560 msg = &commit_msg;
1561 strbuf_addstr(msg, orig_message);
1562 hook_commit = "HEAD";
1563 }
1564 author = amend_author = get_author(message);
1565 repo_unuse_commit_buffer(r, current_head,
1566 message);
1567 if (!author) {
1568 res = error(_("unable to parse commit author"));
1569 goto out;
1570 }
1571 parents = commit_list_copy(current_head->parents);
1572 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1573 } else if (current_head &&
1574 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1575 commit_list_insert(current_head, &parents);
1576 }
1577
1578 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1579 res = error(_("git write-tree failed to write a tree"));
1580 goto out;
1581 }
1582
1583 if (!(flags & ALLOW_EMPTY)) {
1584 struct commit *first_parent = current_head;
1585
1586 if (flags & AMEND_MSG) {
1587 if (current_head->parents) {
1588 first_parent = current_head->parents->item;
1589 if (repo_parse_commit(r, first_parent)) {
1590 res = error(_("could not parse HEAD commit"));
1591 goto out;
1592 }
1593 } else {
1594 first_parent = NULL;
1595 }
1596 }
1597 if (oideq(first_parent
1598 ? get_commit_tree_oid(first_parent)
1599 : the_hash_algo->empty_tree,
1600 &tree)) {
1601 res = 1; /* run 'git commit' to display error message */
1602 goto out;
1603 }
1604 }
1605
1606 if (hook_exists(r, "prepare-commit-msg")) {
1607 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1608 if (res)
1609 goto out;
1610 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1611 2048) < 0) {
1612 res = error_errno(_("unable to read commit message "
1613 "from '%s'"),
1614 git_path_commit_editmsg());
1615 goto out;
1616 }
1617 msg = &commit_msg;
1618 }
1619
1620 if (flags & CLEANUP_MSG)
1621 cleanup = COMMIT_MSG_CLEANUP_ALL;
1622 else if ((opts->signoff || opts->record_origin) &&
1623 !opts->explicit_cleanup)
1624 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1625 else
1626 cleanup = opts->default_msg_cleanup;
1627
1628 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1629 strbuf_stripspace(msg,
1630 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_str : NULL);
1631 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1632 res = 1; /* run 'git commit' to display error message */
1633 goto out;
1634 }
1635
1636 if (opts->committer_date_is_author_date) {
1637 struct ident_split id;
1638 struct strbuf date = STRBUF_INIT;
1639
1640 if (!opts->ignore_date) {
1641 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1642 res = error(_("invalid author identity '%s'"),
1643 author);
1644 goto out;
1645 }
1646 if (!id.date_begin) {
1647 res = error(_(
1648 "corrupt author: missing date information"));
1649 goto out;
1650 }
1651 strbuf_addf(&date, "@%.*s %.*s",
1652 (int)(id.date_end - id.date_begin),
1653 id.date_begin,
1654 (int)(id.tz_end - id.tz_begin),
1655 id.tz_begin);
1656 } else {
1657 reset_ident_date();
1658 }
1659 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1660 getenv("GIT_COMMITTER_EMAIL"),
1661 WANT_COMMITTER_IDENT,
1662 opts->ignore_date ? NULL : date.buf,
1663 IDENT_STRICT);
1664 strbuf_release(&date);
1665 } else {
1666 reset_ident_date();
1667 }
1668
1669 if (opts->ignore_date) {
1670 struct ident_split id;
1671 char *name, *email;
1672
1673 if (split_ident_line(&id, author, strlen(author)) < 0) {
1674 error(_("invalid author identity '%s'"), author);
1675 goto out;
1676 }
1677 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1678 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1679 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1680 IDENT_STRICT);
1681 free(name);
1682 free(email);
1683 }
1684
1685 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1686 author, committer, opts->gpg_sign, extra)) {
1687 res = error(_("failed to write commit object"));
1688 goto out;
1689 }
1690
1691 if (update_head_with_reflog(current_head, oid, reflog_action,
1692 msg, &err)) {
1693 res = error("%s", err.buf);
1694 goto out;
1695 }
1696
1697 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1698 if (flags & AMEND_MSG)
1699 commit_post_rewrite(r, current_head, oid);
1700
1701 out:
1702 free_commit_extra_headers(extra);
1703 commit_list_free(parents);
1704 strbuf_release(&err);
1705 strbuf_release(&commit_msg);
1706 free(amend_author);
1707
1708 return res;
1709 }
1710
1711 static int write_rebase_head(struct object_id *oid)
1712 {
1713 if (refs_update_ref(get_main_ref_store(the_repository), "rebase", "REBASE_HEAD", oid,
1714 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1715 return error(_("could not update %s"), "REBASE_HEAD");
1716
1717 return 0;
1718 }
1719
1720 static int do_commit(struct repository *r,
1721 const char *msg_file, const char *author,
1722 const char *reflog_action,
1723 struct replay_opts *opts, unsigned int flags,
1724 struct object_id *oid)
1725 {
1726 int res = 1;
1727
1728 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1729 struct object_id oid;
1730 struct strbuf sb = STRBUF_INIT;
1731
1732 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1733 return error_errno(_("unable to read commit message "
1734 "from '%s'"),
1735 msg_file);
1736
1737 res = try_to_commit(r, msg_file ? &sb : NULL,
1738 author, reflog_action, opts, flags, &oid);
1739 strbuf_release(&sb);
1740 if (!res) {
1741 refs_delete_ref(get_main_ref_store(r), "",
1742 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF);
1743 unlink(git_path_merge_msg(r));
1744 if (!is_rebase_i(opts))
1745 print_commit_summary(r, NULL, &oid,
1746 SUMMARY_SHOW_AUTHOR_DATE);
1747 return res;
1748 }
1749 }
1750 if (res == 1) {
1751 if (is_rebase_i(opts) && oid)
1752 if (write_rebase_head(oid))
1753 return -1;
1754 return run_git_commit(msg_file, reflog_action, opts, flags);
1755 }
1756
1757 return res;
1758 }
1759
1760 static int is_original_commit_empty(struct commit *commit)
1761 {
1762 const struct object_id *ptree_oid;
1763
1764 if (repo_parse_commit(the_repository, commit))
1765 return error(_("could not parse commit %s"),
1766 oid_to_hex(&commit->object.oid));
1767 if (commit->parents) {
1768 struct commit *parent = commit->parents->item;
1769 if (repo_parse_commit(the_repository, parent))
1770 return error(_("could not parse parent commit %s"),
1771 oid_to_hex(&parent->object.oid));
1772 ptree_oid = get_commit_tree_oid(parent);
1773 } else {
1774 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1775 }
1776
1777 return oideq(ptree_oid, get_commit_tree_oid(commit));
1778 }
1779
1780 /*
1781 * Should empty commits be allowed? Return status:
1782 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1783 * 0: Halt on empty commit
1784 * 1: Allow empty commit
1785 * 2: Drop empty commit
1786 */
1787 static int allow_empty(struct repository *r,
1788 struct replay_opts *opts,
1789 struct commit *commit)
1790 {
1791 int index_unchanged, originally_empty;
1792
1793 /*
1794 * For a commit that is initially empty, allow_empty determines if it
1795 * should be kept or not
1796 *
1797 * For a commit that becomes empty, keep_redundant_commits and
1798 * drop_redundant_commits determine whether the commit should be kept or
1799 * dropped. If neither is specified, halt.
1800 */
1801 index_unchanged = is_index_unchanged(r);
1802 if (index_unchanged < 0)
1803 return index_unchanged;
1804 if (!index_unchanged)
1805 return 0; /* we do not have to say --allow-empty */
1806
1807 originally_empty = is_original_commit_empty(commit);
1808 if (originally_empty < 0)
1809 return originally_empty;
1810 if (originally_empty)
1811 return opts->allow_empty;
1812 else if (opts->keep_redundant_commits)
1813 return 1;
1814 else if (opts->drop_redundant_commits)
1815 return 2;
1816 else
1817 return 0;
1818 }
1819
1820 static struct {
1821 char c;
1822 const char *str;
1823 } todo_command_info[] = {
1824 [TODO_PICK] = { 'p', "pick" },
1825 [TODO_REVERT] = { 0, "revert" },
1826 [TODO_EDIT] = { 'e', "edit" },
1827 [TODO_REWORD] = { 'r', "reword" },
1828 [TODO_FIXUP] = { 'f', "fixup" },
1829 [TODO_SQUASH] = { 's', "squash" },
1830 [TODO_EXEC] = { 'x', "exec" },
1831 [TODO_BREAK] = { 'b', "break" },
1832 [TODO_LABEL] = { 'l', "label" },
1833 [TODO_RESET] = { 't', "reset" },
1834 [TODO_MERGE] = { 'm', "merge" },
1835 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1836 [TODO_NOOP] = { 0, "noop" },
1837 [TODO_DROP] = { 'd', "drop" },
1838 [TODO_COMMENT] = { 0, NULL },
1839 };
1840
1841 static const char *command_to_string(const enum todo_command command)
1842 {
1843 if (command < TODO_COMMENT)
1844 return todo_command_info[command].str;
1845 if (command == TODO_COMMENT)
1846 return comment_line_str;
1847 die(_("unknown command: %d"), command);
1848 }
1849
1850 static char command_to_char(const enum todo_command command)
1851 {
1852 if (command < TODO_COMMENT)
1853 return todo_command_info[command].c;
1854 return 0;
1855 }
1856
1857 static int is_noop(const enum todo_command command)
1858 {
1859 return TODO_NOOP <= command;
1860 }
1861
1862 static int is_fixup(enum todo_command command)
1863 {
1864 return command == TODO_FIXUP || command == TODO_SQUASH;
1865 }
1866
1867 /* Does this command create a (non-merge) commit? */
1868 static int is_pick_or_similar(enum todo_command command)
1869 {
1870 switch (command) {
1871 case TODO_PICK:
1872 case TODO_REVERT:
1873 case TODO_EDIT:
1874 case TODO_REWORD:
1875 case TODO_FIXUP:
1876 case TODO_SQUASH:
1877 return 1;
1878 default:
1879 return 0;
1880 }
1881 }
1882
1883 enum todo_item_flags {
1884 TODO_EDIT_MERGE_MSG = (1 << 0),
1885 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1886 TODO_EDIT_FIXUP_MSG = (1 << 2),
1887 };
1888
1889 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1890 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1891 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1892 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1893 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1894
1895 static int is_fixup_flag(enum todo_command command, unsigned flag)
1896 {
1897 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1898 (flag & TODO_EDIT_FIXUP_MSG));
1899 }
1900
1901 /*
1902 * Wrapper around strbuf_add_commented_lines() which avoids double
1903 * commenting commit subjects.
1904 */
1905 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1906 {
1907 const char *s = str;
1908 while (starts_with_mem(s, len, comment_line_str)) {
1909 size_t count;
1910 const char *n = memchr(s, '\n', len);
1911 if (!n)
1912 count = len;
1913 else
1914 count = n - s + 1;
1915 strbuf_add(buf, s, count);
1916 s += count;
1917 len -= count;
1918 }
1919 strbuf_add_commented_lines(buf, s, len, comment_line_str);
1920 }
1921
1922 /* Does the current fixup chain contain a squash command? */
1923 static int seen_squash(struct replay_ctx *ctx)
1924 {
1925 return starts_with(ctx->current_fixups.buf, "squash") ||
1926 strstr(ctx->current_fixups.buf, "\nsquash");
1927 }
1928
1929 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1930 {
1931 strbuf_setlen(buf1, strlen(comment_line_str) + 1);
1932 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1933 strbuf_addch(buf1, '\n');
1934 strbuf_setlen(buf2, strlen(comment_line_str) + 1);
1935 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1936 strbuf_addch(buf2, '\n');
1937 }
1938
1939 /*
1940 * Comment out any un-commented commit messages, updating the message comments
1941 * to say they will be skipped but do not comment out the empty lines that
1942 * surround commit messages and their comments.
1943 */
1944 static void update_squash_message_for_fixup(struct strbuf *msg)
1945 {
1946 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1947 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1948 const char *s, *start;
1949 char *orig_msg;
1950 size_t orig_msg_len;
1951 int i = 1;
1952
1953 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str),
1954 strlen(_(first_commit_msg_str)),
1955 comment_line_str);
1956 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str),
1957 strlen(_(skip_first_commit_msg_str)),
1958 comment_line_str);
1959 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1960 while (s) {
1961 const char *next;
1962 size_t off;
1963 if (skip_prefix(s, buf1.buf, &next)) {
1964 /*
1965 * Copy the last message, preserving the blank line
1966 * preceding the current line
1967 */
1968 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1969 copy_lines(msg, start, s - start - off);
1970 if (off)
1971 strbuf_addch(msg, '\n');
1972 /*
1973 * The next message needs to be commented out but the
1974 * message header is already commented out so just copy
1975 * it and the blank line that follows it.
1976 */
1977 strbuf_addbuf(msg, &buf2);
1978 if (*next == '\n')
1979 strbuf_addch(msg, *next++);
1980 start = s = next;
1981 copy_lines = add_commented_lines;
1982 update_comment_bufs(&buf1, &buf2, ++i);
1983 } else if (skip_prefix(s, buf2.buf, &next)) {
1984 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1985 copy_lines(msg, start, s - start - off);
1986 start = s - off;
1987 s = next;
1988 copy_lines = strbuf_add;
1989 update_comment_bufs(&buf1, &buf2, ++i);
1990 } else {
1991 s = strchr(s, '\n');
1992 if (s)
1993 s++;
1994 }
1995 }
1996 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1997 free(orig_msg);
1998 strbuf_release(&buf1);
1999 strbuf_release(&buf2);
2000 }
2001
2002 static int append_squash_message(struct strbuf *buf, const char *body,
2003 enum todo_command command, struct replay_opts *opts,
2004 unsigned flag)
2005 {
2006 struct replay_ctx *ctx = opts->ctx;
2007 const char *fixup_msg;
2008 size_t commented_len = 0, fixup_off;
2009 /*
2010 * amend is non-interactive and not normally used with fixup!
2011 * or squash! commits, so only comment out those subjects when
2012 * squashing commit messages.
2013 */
2014 if (starts_with(body, "amend!") ||
2015 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2016 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2017 commented_len = commit_subject_length(body);
2018
2019 strbuf_addf(buf, "\n%s ", comment_line_str);
2020 strbuf_addf(buf, _(nth_commit_msg_fmt),
2021 ++ctx->current_fixup_count + 1);
2022 strbuf_addstr(buf, "\n\n");
2023 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2024 /* buf->buf may be reallocated so store an offset into the buffer */
2025 fixup_off = buf->len;
2026 strbuf_addstr(buf, body + commented_len);
2027
2028 /* fixup -C after squash behaves like squash */
2029 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2030 /*
2031 * We're replacing the commit message so we need to
2032 * append any trailers if the user requested
2033 * '--signoff' or '--trailer'.
2034 */
2035 if (opts->signoff)
2036 append_signoff(buf, 0, 0);
2037
2038 if (opts->trailer_args.nr)
2039 amend_strbuf_with_trailers(buf, &opts->trailer_args);
2040
2041 if ((command == TODO_FIXUP) &&
2042 (flag & TODO_REPLACE_FIXUP_MSG) &&
2043 (file_exists(rebase_path_fixup_msg()) ||
2044 !file_exists(rebase_path_squash_msg()))) {
2045 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2046 if (write_message(fixup_msg, strlen(fixup_msg),
2047 rebase_path_fixup_msg(), 0) < 0)
2048 return error(_("cannot write '%s'"),
2049 rebase_path_fixup_msg());
2050 } else {
2051 unlink(rebase_path_fixup_msg());
2052 }
2053 } else {
2054 unlink(rebase_path_fixup_msg());
2055 }
2056
2057 return 0;
2058 }
2059
2060 static int update_squash_messages(struct repository *r,
2061 enum todo_command command,
2062 struct commit *commit,
2063 struct replay_opts *opts,
2064 unsigned flag)
2065 {
2066 struct replay_ctx *ctx = opts->ctx;
2067 struct strbuf buf = STRBUF_INIT;
2068 int res = 0;
2069 const char *message, *body;
2070 const char *encoding = get_commit_output_encoding();
2071
2072 if (!is_fixup(command))
2073 BUG("not a FIXUP or SQUASH %d", command);
2074
2075 if (ctx->current_fixup_count > 0) {
2076 struct strbuf header = STRBUF_INIT;
2077 char *eol;
2078
2079 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2080 return error(_("could not read '%s'"),
2081 rebase_path_squash_msg());
2082
2083 eol = !starts_with(buf.buf, comment_line_str) ?
2084 buf.buf : strchrnul(buf.buf, '\n');
2085
2086 strbuf_addf(&header, "%s ", comment_line_str);
2087 strbuf_addf(&header, _(combined_commit_msg_fmt),
2088 ctx->current_fixup_count + 2);
2089 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2090 strbuf_release(&header);
2091 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2092 update_squash_message_for_fixup(&buf);
2093 } else {
2094 struct object_id head;
2095 struct commit *head_commit;
2096 const char *head_message, *body;
2097
2098 if (repo_get_oid(r, "HEAD", &head))
2099 return error(_("need a HEAD to fixup"));
2100 if (!(head_commit = lookup_commit_reference(r, &head)))
2101 return error(_("could not read HEAD"));
2102 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2103 encoding)))
2104 return error(_("could not read HEAD's commit message"));
2105
2106 find_commit_subject(head_message, &body);
2107 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2108 rebase_path_fixup_msg(), 0) < 0) {
2109 repo_unuse_commit_buffer(r, head_commit, head_message);
2110 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2111 }
2112 strbuf_addf(&buf, "%s ", comment_line_str);
2113 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2114 strbuf_addf(&buf, "\n%s ", comment_line_str);
2115 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2116 _(skip_first_commit_msg_str) :
2117 _(first_commit_msg_str));
2118 strbuf_addstr(&buf, "\n\n");
2119 if (is_fixup_flag(command, flag))
2120 strbuf_add_commented_lines(&buf, body, strlen(body),
2121 comment_line_str);
2122 else
2123 strbuf_addstr(&buf, body);
2124
2125 repo_unuse_commit_buffer(r, head_commit, head_message);
2126 }
2127
2128 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2129 return error(_("could not read commit message of %s"),
2130 oid_to_hex(&commit->object.oid));
2131 find_commit_subject(message, &body);
2132
2133 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2134 res = append_squash_message(&buf, body, command, opts, flag);
2135 } else if (command == TODO_FIXUP) {
2136 strbuf_addf(&buf, "\n%s ", comment_line_str);
2137 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2138 ++ctx->current_fixup_count + 1);
2139 strbuf_addstr(&buf, "\n\n");
2140 strbuf_add_commented_lines(&buf, body, strlen(body),
2141 comment_line_str);
2142 }
2143 repo_unuse_commit_buffer(r, commit, message);
2144
2145 if (!res)
2146 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2147 0);
2148 strbuf_release(&buf);
2149
2150 if (!res) {
2151 strbuf_addf(&ctx->current_fixups, "%s%s %s",
2152 ctx->current_fixups.len ? "\n" : "",
2153 command_to_string(command),
2154 oid_to_hex(&commit->object.oid));
2155 res = write_message(ctx->current_fixups.buf,
2156 ctx->current_fixups.len,
2157 rebase_path_current_fixups(), 0);
2158 }
2159
2160 return res;
2161 }
2162
2163 static void flush_rewritten_pending(void)
2164 {
2165 struct strbuf buf = STRBUF_INIT;
2166 struct object_id newoid;
2167 FILE *out;
2168
2169 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2170 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2171 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2172 char *bol = buf.buf, *eol;
2173
2174 while (*bol) {
2175 eol = strchrnul(bol, '\n');
2176 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2177 bol, oid_to_hex(&newoid));
2178 if (!*eol)
2179 break;
2180 bol = eol + 1;
2181 }
2182 fclose(out);
2183 unlink(rebase_path_rewritten_pending());
2184 }
2185 strbuf_release(&buf);
2186 }
2187
2188 static void record_in_rewritten(struct object_id *oid,
2189 enum todo_command next_command)
2190 {
2191 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2192
2193 if (!out)
2194 return;
2195
2196 fprintf(out, "%s\n", oid_to_hex(oid));
2197 fclose(out);
2198
2199 if (!is_fixup(next_command))
2200 flush_rewritten_pending();
2201 }
2202
2203 static int should_edit(struct replay_opts *opts) {
2204 if (opts->edit < 0)
2205 /*
2206 * Note that we only handle the case of non-conflicted
2207 * commits; continue_single_pick() handles the conflicted
2208 * commits itself instead of calling this function.
2209 */
2210 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2211 return opts->edit;
2212 }
2213
2214 static void refer_to_commit(struct repository *r, struct strbuf *msgbuf,
2215 const struct commit *commit,
2216 bool use_commit_reference)
2217 {
2218 if (use_commit_reference) {
2219 struct pretty_print_context ctx = {
2220 .abbrev = DEFAULT_ABBREV,
2221 .date_mode.type = DATE_SHORT,
2222 };
2223 repo_format_commit_message(r, commit,
2224 "%h (%s, %ad)", msgbuf, &ctx);
2225 } else {
2226 strbuf_add_oid_hex(msgbuf, &commit->object.oid);
2227 }
2228 }
2229
2230 static const char *sequencer_reflog_action(struct replay_opts *opts)
2231 {
2232 if (!opts->reflog_action) {
2233 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
2234 opts->reflog_action =
2235 xstrdup(opts->reflog_action ? opts->reflog_action
2236 : action_name(opts));
2237 }
2238
2239 return opts->reflog_action;
2240 }
2241
2242 __attribute__((format (printf, 3, 4)))
2243 static const char *reflog_message(struct replay_opts *opts,
2244 const char *sub_action, const char *fmt, ...)
2245 {
2246 va_list ap;
2247 static struct strbuf buf = STRBUF_INIT;
2248
2249 va_start(ap, fmt);
2250 strbuf_reset(&buf);
2251 strbuf_addstr(&buf, sequencer_reflog_action(opts));
2252 if (sub_action)
2253 strbuf_addf(&buf, " (%s)", sub_action);
2254 if (fmt) {
2255 strbuf_addstr(&buf, ": ");
2256 strbuf_vaddf(&buf, fmt, ap);
2257 }
2258 va_end(ap);
2259
2260 return buf.buf;
2261 }
2262
2263 enum pick_result {
2264 PICK_RESULT_ERROR = -1,
2265 PICK_RESULT_OK,
2266 PICK_RESULT_CONFLICTS,
2267 PICK_RESULT_DROPPED,
2268 };
2269
2270 static enum pick_result 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 = 0;
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(r, 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 if (write_message(ctx->message.buf, ctx->message.len,
2464 git_path_merge_msg(r), 0)) {
2465 res = -1;
2466 goto leave;
2467 }
2468
2469 commit_list_insert(base, &common);
2470 commit_list_insert(next, &remotes);
2471 res = try_merge_command(r, opts->strategy,
2472 opts->xopts.nr, opts->xopts.v,
2473 common, oid_to_hex(&head), remotes);
2474 /*
2475 * If there were conflicts, try_merge_command() returns 1,
2476 * any other no-zero return code means that either the merge
2477 * command could not be run, or it failed to merge.
2478 */
2479 if (res && res != 1)
2480 res = -1;
2481
2482 commit_list_free(common);
2483 commit_list_free(remotes);
2484 }
2485
2486 /*
2487 * If the merge was clean or if it failed due to conflict, we write
2488 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2489 * However, if the merge did not even start, then we don't want to
2490 * write it at all.
2491 */
2492 if ((command == TODO_PICK || command == TODO_REWORD ||
2493 command == TODO_EDIT) && !opts->no_commit &&
2494 (res == 0 || res == 1) &&
2495 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2496 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2497 res = -1;
2498 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2499 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2500 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2501 res = -1;
2502
2503 if (res) {
2504 error(command == TODO_REVERT
2505 ? _("could not revert %s... %s")
2506 : _("could not apply %s... %s"),
2507 short_commit_name(r, commit), msg.subject);
2508 print_advice(r, res == 1, opts);
2509 repo_rerere(r, opts->allow_rerere_auto);
2510 goto leave;
2511 }
2512
2513 allow = allow_empty(r, opts, commit);
2514 if (allow < 0) {
2515 res = allow;
2516 goto leave;
2517 } else if (allow == 1) {
2518 flags |= ALLOW_EMPTY;
2519 } else if (allow == 2) {
2520 drop_commit = 1;
2521 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2522 NULL, REF_NO_DEREF);
2523 unlink(git_path_merge_msg(r));
2524 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2525 NULL, REF_NO_DEREF);
2526 fprintf(stderr,
2527 _("dropping %s %s -- patch contents already upstream\n"),
2528 oid_to_hex(&commit->object.oid), msg.subject);
2529 } /* else allow == 0 and there's nothing special to do */
2530 if (!opts->no_commit && !drop_commit) {
2531 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2532 res = do_commit(r, msg_file, author, reflog_action,
2533 opts, flags,
2534 commit? &commit->object.oid : NULL);
2535 else
2536 res = error(_("unable to parse commit author"));
2537 *check_todo = !!(flags & EDIT_MSG);
2538 if (!res && reword) {
2539 fast_forward_edit:
2540 /*
2541 * To reword we amend the commit we just
2542 * picked or fast-forwarded. As the commit has
2543 * already been picked we want to use the same
2544 * set of commit flags regardless of how we
2545 * got here.
2546 */
2547 flags = EDIT_MSG | VERIFY_MSG | AMEND_MSG | ALLOW_EMPTY;
2548 res = run_git_commit(NULL, reflog_action, opts, flags);
2549 *check_todo = 1;
2550 }
2551 /*
2552 * If "git commit" failed to run then res == -1, but we don't
2553 * want reschedule the last command because the picking the
2554 * commit was successful.
2555 */
2556 res = !!res;
2557 }
2558
2559
2560 if (!res && final_fixup) {
2561 unlink(rebase_path_fixup_msg());
2562 unlink(rebase_path_squash_msg());
2563 unlink(rebase_path_current_fixups());
2564 strbuf_reset(&ctx->current_fixups);
2565 ctx->current_fixup_count = 0;
2566 }
2567
2568 leave:
2569 free_message(commit, &msg);
2570 free(author);
2571 update_abort_safety_file();
2572
2573 if (res < 0)
2574 return PICK_RESULT_ERROR;
2575 else if (res > 0)
2576 return PICK_RESULT_CONFLICTS;
2577 else if (drop_commit)
2578 return PICK_RESULT_DROPPED;
2579 else
2580 return PICK_RESULT_OK;
2581 }
2582
2583 static int prepare_revs(struct replay_opts *opts)
2584 {
2585 /*
2586 * picking (but not reverting) ranges (but not individual revisions)
2587 * should be done in reverse
2588 */
2589 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2590 opts->revs->reverse ^= 1;
2591
2592 if (prepare_revision_walk(opts->revs))
2593 return error(_("revision walk setup failed"));
2594
2595 return 0;
2596 }
2597
2598 static int read_and_refresh_cache(struct repository *r,
2599 struct replay_opts *opts)
2600 {
2601 struct lock_file index_lock = LOCK_INIT;
2602 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2603 if (repo_read_index(r) < 0) {
2604 rollback_lock_file(&index_lock);
2605 return error(_("git %s: failed to read the index"),
2606 action_name(opts));
2607 }
2608 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2609
2610 if (index_fd >= 0) {
2611 if (write_locked_index(r->index, &index_lock,
2612 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2613 return error(_("git %s: failed to refresh the index"),
2614 action_name(opts));
2615 }
2616 }
2617
2618 /*
2619 * If we are resolving merges in any way other than "ort", then
2620 * expand the sparse index.
2621 */
2622 if (opts->strategy && strcmp(opts->strategy, "ort"))
2623 ensure_full_index(r->index);
2624 return 0;
2625 }
2626
2627 void todo_list_release(struct todo_list *todo_list)
2628 {
2629 strbuf_release(&todo_list->buf);
2630 FREE_AND_NULL(todo_list->items);
2631 todo_list->nr = todo_list->alloc = 0;
2632 }
2633
2634 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2635 {
2636 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2637 return todo_list->items + todo_list->nr++;
2638 }
2639
2640 const char *todo_item_get_arg(struct todo_list *todo_list,
2641 struct todo_item *item)
2642 {
2643 return todo_list->buf.buf + item->arg_offset;
2644 }
2645
2646 static int is_command(enum todo_command command, const char **bol)
2647 {
2648 const char *str = todo_command_info[command].str;
2649 const char nick = todo_command_info[command].c;
2650 const char *p = *bol;
2651
2652 if ((skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2653 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p)) {
2654 *bol = p;
2655 return 1;
2656 }
2657 return 0;
2658 }
2659
2660 bool sequencer_parse_todo_command(const char **p, enum todo_command *cmd)
2661 {
2662 const char *s = *p;
2663
2664 for (int i = 0; i < TODO_COMMENT; i++)
2665 if (is_command(i, p)) {
2666 *cmd = i;
2667 return true;
2668 }
2669
2670 if (starts_with(s, comment_line_str)) {
2671 *cmd = TODO_COMMENT;
2672 return true;
2673 } else if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n') || !s[0]) {
2674 *cmd = TODO_COMMENT;
2675 return true;
2676 }
2677
2678 return false;
2679 }
2680
2681 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2682 {
2683 switch (command) {
2684 case TODO_LABEL:
2685 /*
2686 * '#' is not a valid label as the merge command uses it to
2687 * separate merge parents from the commit subject.
2688 */
2689 if (!strcmp(arg, "#") ||
2690 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2691 return error(_("'%s' is not a valid label"), arg);
2692 break;
2693
2694 case TODO_UPDATE_REF:
2695 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2696 return error(_("'%s' is not a valid refname"), arg);
2697 if (check_refname_format(arg, 0))
2698 return error(_("update-ref requires a fully qualified "
2699 "refname e.g. refs/heads/%s"), arg);
2700 break;
2701
2702 default:
2703 BUG("unexpected todo_command");
2704 }
2705
2706 return 0;
2707 }
2708
2709 static int check_merge_commit_insn(enum todo_command command)
2710 {
2711 switch(command) {
2712 case TODO_PICK:
2713 error(_("'%s' does not accept merge commits"),
2714 todo_command_info[command].str);
2715 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2716 /*
2717 * TRANSLATORS: 'pick' and 'merge -C' should not be
2718 * translated.
2719 */
2720 "'pick' does not take a merge commit. If you wanted to\n"
2721 "replay the merge, use 'merge -C' on the commit."));
2722 return -1;
2723
2724 case TODO_REWORD:
2725 error(_("'%s' does not accept merge commits"),
2726 todo_command_info[command].str);
2727 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2728 /*
2729 * TRANSLATORS: 'reword' and 'merge -c' should not be
2730 * translated.
2731 */
2732 "'reword' does not take a merge commit. If you wanted to\n"
2733 "replay the merge and reword the commit message, use\n"
2734 "'merge -c' on the commit"));
2735 return -1;
2736
2737 case TODO_EDIT:
2738 error(_("'%s' does not accept merge commits"),
2739 todo_command_info[command].str);
2740 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2741 /*
2742 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2743 * not be translated.
2744 */
2745 "'edit' does not take a merge commit. If you wanted to\n"
2746 "replay the merge, use 'merge -C' on the commit, and then\n"
2747 "'break' to give the control back to you so that you can\n"
2748 "do 'git commit --amend && git rebase --continue'."));
2749 return -1;
2750
2751 case TODO_FIXUP:
2752 case TODO_SQUASH:
2753 return error(_("cannot squash merge commit into another commit"));
2754
2755 case TODO_MERGE:
2756 case TODO_DROP:
2757 return 0;
2758
2759 default:
2760 BUG("unexpected todo_command");
2761 }
2762 }
2763
2764 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2765 struct todo_item *item, const char *buf,
2766 const char *bol, char *eol)
2767 {
2768 struct object_id commit_oid;
2769 char *end_of_object_name;
2770 int saved, status, padding;
2771
2772 item->flags = 0;
2773
2774 /* left-trim */
2775 bol += strspn(bol, " \t");
2776
2777 if (!sequencer_parse_todo_command(&bol, &item->command))
2778 return error(_("invalid command '%.*s'"),
2779 (int)strcspn(bol, " \t\r\n"), bol);
2780
2781 if (item->command == TODO_COMMENT) {
2782 item->commit = NULL;
2783 item->arg_offset = bol - buf;
2784 item->arg_len = eol - bol;
2785 return 0;
2786 }
2787
2788 /* Eat up extra spaces/ tabs before object name */
2789 padding = strspn(bol, " \t");
2790 bol += padding;
2791
2792 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2793 if (bol != eol)
2794 return error(_("%s does not accept arguments: '%s'"),
2795 command_to_string(item->command), bol);
2796 item->commit = NULL;
2797 item->arg_offset = bol - buf;
2798 item->arg_len = eol - bol;
2799 return 0;
2800 }
2801
2802 if (!padding)
2803 return error(_("missing arguments for %s"),
2804 command_to_string(item->command));
2805
2806 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2807 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2808 int ret = 0;
2809
2810 item->commit = NULL;
2811 item->arg_offset = bol - buf;
2812 item->arg_len = (int)(eol - bol);
2813 if (item->command == TODO_LABEL ||
2814 item->command == TODO_UPDATE_REF) {
2815 saved = *eol;
2816 *eol = '\0';
2817 ret = check_label_or_ref_arg(item->command, bol);
2818 *eol = saved;
2819 }
2820 return ret;
2821 }
2822
2823 if (item->command == TODO_FIXUP) {
2824 if (skip_prefix(bol, "-C", &bol)) {
2825 bol += strspn(bol, " \t");
2826 item->flags |= TODO_REPLACE_FIXUP_MSG;
2827 } else if (skip_prefix(bol, "-c", &bol)) {
2828 bol += strspn(bol, " \t");
2829 item->flags |= TODO_EDIT_FIXUP_MSG;
2830 }
2831 }
2832
2833 if (item->command == TODO_MERGE) {
2834 if (skip_prefix(bol, "-C", &bol))
2835 bol += strspn(bol, " \t");
2836 else if (skip_prefix(bol, "-c", &bol)) {
2837 bol += strspn(bol, " \t");
2838 item->flags |= TODO_EDIT_MERGE_MSG;
2839 } else {
2840 item->flags |= TODO_EDIT_MERGE_MSG;
2841 item->commit = NULL;
2842 item->arg_offset = bol - buf;
2843 item->arg_len = (int)(eol - bol);
2844 return 0;
2845 }
2846 }
2847
2848 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2849 saved = *end_of_object_name;
2850 *end_of_object_name = '\0';
2851 status = repo_get_oid(r, bol, &commit_oid);
2852 if (status < 0)
2853 error(_("could not parse '%s'"), bol); /* return later */
2854 *end_of_object_name = saved;
2855
2856 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2857 item->arg_offset = bol - buf;
2858 item->arg_len = (int)(eol - bol);
2859
2860 if (status < 0)
2861 return status;
2862
2863 item->commit = lookup_commit_reference(r, &commit_oid);
2864 if (!item->commit)
2865 return -1;
2866 if (is_rebase_i(opts) &&
2867 item->commit->parents && item->commit->parents->next)
2868 return check_merge_commit_insn(item->command);
2869 return 0;
2870 }
2871
2872 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2873 {
2874 const char *todo_file, *bol;
2875 struct strbuf buf = STRBUF_INIT;
2876 int ret = 0;
2877
2878 todo_file = git_path_todo_file();
2879 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2880 if (errno == ENOENT || errno == ENOTDIR)
2881 return -1;
2882 else
2883 return error_errno("unable to open '%s'", todo_file);
2884 }
2885 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2886 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2887 *action = REPLAY_PICK;
2888 else if (is_command(TODO_REVERT, &bol) &&
2889 (*bol == ' ' || *bol == '\t'))
2890 *action = REPLAY_REVERT;
2891 else
2892 ret = -1;
2893
2894 strbuf_release(&buf);
2895
2896 return ret;
2897 }
2898
2899 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2900 char *buf, struct todo_list *todo_list)
2901 {
2902 struct todo_item *item;
2903 char *p = buf, *next_p;
2904 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2905
2906 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2907
2908 for (i = 1; *p; i++, p = next_p) {
2909 char *eol = strchrnul(p, '\n');
2910
2911 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2912
2913 if (p != eol && eol[-1] == '\r')
2914 eol--; /* strip Carriage Return */
2915
2916 item = append_new_todo(todo_list);
2917 item->offset_in_buf = p - todo_list->buf.buf;
2918 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2919 res = error(_("invalid line %d: %.*s"),
2920 i, (int)(eol - p), p);
2921 item->command = TODO_COMMENT + 1;
2922 item->arg_offset = p - buf;
2923 item->arg_len = (int)(eol - p);
2924 item->commit = NULL;
2925 }
2926
2927 if (item->command != TODO_COMMENT)
2928 todo_list->total_nr++;
2929
2930 if (fixup_okay)
2931 ; /* do nothing */
2932 else if (is_fixup(item->command))
2933 res = error(_("cannot '%s' without a previous commit"),
2934 command_to_string(item->command));
2935 else if (!is_noop(item->command))
2936 fixup_okay = 1;
2937 }
2938
2939 return res;
2940 }
2941
2942 static int count_commands(struct todo_list *todo_list)
2943 {
2944 int count = 0, i;
2945
2946 for (i = 0; i < todo_list->nr; i++)
2947 if (todo_list->items[i].command != TODO_COMMENT)
2948 count++;
2949
2950 return count;
2951 }
2952
2953 static int get_item_line_offset(struct todo_list *todo_list, int index)
2954 {
2955 return index < todo_list->nr ?
2956 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2957 }
2958
2959 static const char *get_item_line(struct todo_list *todo_list, int index)
2960 {
2961 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2962 }
2963
2964 static int get_item_line_length(struct todo_list *todo_list, int index)
2965 {
2966 return get_item_line_offset(todo_list, index + 1)
2967 - get_item_line_offset(todo_list, index);
2968 }
2969
2970 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2971 {
2972 int fd;
2973 ssize_t len;
2974
2975 fd = open(path, O_RDONLY);
2976 if (fd < 0)
2977 return error_errno(_("could not open '%s'"), path);
2978 len = strbuf_read(sb, fd, 0);
2979 close(fd);
2980 if (len < 0)
2981 return error(_("could not read '%s'."), path);
2982 return len;
2983 }
2984
2985 static int have_finished_the_last_pick(void)
2986 {
2987 struct strbuf buf = STRBUF_INIT;
2988 const char *eol;
2989 const char *todo_path = git_path_todo_file();
2990 int ret = 0;
2991
2992 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
2993 if (errno == ENOENT) {
2994 return 0;
2995 } else {
2996 error_errno("unable to open '%s'", todo_path);
2997 return 0;
2998 }
2999 }
3000 /* If there is only one line then we are done */
3001 eol = strchr(buf.buf, '\n');
3002 if (!eol || !eol[1])
3003 ret = 1;
3004
3005 strbuf_release(&buf);
3006
3007 return ret;
3008 }
3009
3010 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
3011 {
3012 struct replay_opts opts = REPLAY_OPTS_INIT;
3013 int need_cleanup = 0;
3014
3015 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
3016 if (!refs_delete_ref(get_main_ref_store(r), "",
3017 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
3018 verbose)
3019 warning(_("cancelling a cherry picking in progress"));
3020 opts.action = REPLAY_PICK;
3021 need_cleanup = 1;
3022 }
3023
3024 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3025 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
3026 NULL, REF_NO_DEREF) &&
3027 verbose)
3028 warning(_("cancelling a revert in progress"));
3029 opts.action = REPLAY_REVERT;
3030 need_cleanup = 1;
3031 }
3032
3033 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
3034 NULL, REF_NO_DEREF);
3035
3036 if (!need_cleanup)
3037 goto out;
3038
3039 if (!have_finished_the_last_pick())
3040 goto out;
3041
3042 sequencer_remove_state(&opts);
3043 out:
3044 replay_opts_release(&opts);
3045 }
3046
3047 static void todo_list_write_total_nr(struct todo_list *todo_list)
3048 {
3049 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
3050
3051 if (f) {
3052 fprintf(f, "%d\n", todo_list->total_nr);
3053 fclose(f);
3054 }
3055 }
3056
3057 static int read_populate_todo(struct repository *r,
3058 struct todo_list *todo_list,
3059 struct replay_opts *opts)
3060 {
3061 const char *todo_file = get_todo_path(opts);
3062 int res;
3063
3064 strbuf_reset(&todo_list->buf);
3065 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
3066 return -1;
3067
3068 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
3069 if (res) {
3070 if (is_rebase_i(opts))
3071 return error(_("please fix this using "
3072 "'git rebase --edit-todo'."));
3073 return error(_("unusable instruction sheet: '%s'"), todo_file);
3074 }
3075
3076 if (!todo_list->nr &&
3077 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3078 return error(_("no commits parsed."));
3079
3080 if (!is_rebase_i(opts)) {
3081 enum todo_command valid =
3082 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3083 int i;
3084
3085 for (i = 0; i < todo_list->nr; i++)
3086 if (valid == todo_list->items[i].command)
3087 continue;
3088 else if (valid == TODO_PICK)
3089 return error(_("cannot cherry-pick during a revert."));
3090 else
3091 return error(_("cannot revert during a cherry-pick."));
3092 }
3093
3094 if (is_rebase_i(opts)) {
3095 struct todo_list done = TODO_LIST_INIT;
3096
3097 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3098 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3099 todo_list->done_nr = count_commands(&done);
3100 else
3101 todo_list->done_nr = 0;
3102
3103 todo_list->total_nr = todo_list->done_nr
3104 + count_commands(todo_list);
3105 todo_list_release(&done);
3106
3107 todo_list_write_total_nr(todo_list);
3108 }
3109
3110 return 0;
3111 }
3112
3113 static int git_config_string_dup(char **dest,
3114 const char *var, const char *value)
3115 {
3116 if (!value)
3117 return config_error_nonbool(var);
3118 free(*dest);
3119 *dest = xstrdup(value);
3120 return 0;
3121 }
3122
3123 static int populate_opts_cb(const char *key, const char *value,
3124 const struct config_context *ctx,
3125 void *data)
3126 {
3127 struct replay_opts *opts = data;
3128 int error_flag = 1;
3129
3130 if (!value)
3131 error_flag = 0;
3132 else if (!strcmp(key, "options.no-commit"))
3133 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3134 else if (!strcmp(key, "options.edit"))
3135 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3136 else if (!strcmp(key, "options.allow-empty"))
3137 opts->allow_empty =
3138 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3139 else if (!strcmp(key, "options.allow-empty-message"))
3140 opts->allow_empty_message =
3141 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3142 else if (!strcmp(key, "options.drop-redundant-commits"))
3143 opts->drop_redundant_commits =
3144 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3145 else if (!strcmp(key, "options.keep-redundant-commits"))
3146 opts->keep_redundant_commits =
3147 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3148 else if (!strcmp(key, "options.signoff"))
3149 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3150 else if (!strcmp(key, "options.record-origin"))
3151 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3152 else if (!strcmp(key, "options.allow-ff"))
3153 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3154 else if (!strcmp(key, "options.mainline"))
3155 opts->mainline = git_config_int(key, value, ctx->kvi);
3156 else if (!strcmp(key, "options.strategy"))
3157 git_config_string_dup(&opts->strategy, key, value);
3158 else if (!strcmp(key, "options.gpg-sign"))
3159 git_config_string_dup(&opts->gpg_sign, key, value);
3160 else if (!strcmp(key, "options.strategy-option")) {
3161 strvec_push(&opts->xopts, value);
3162 } else if (!strcmp(key, "options.allow-rerere-auto"))
3163 opts->allow_rerere_auto =
3164 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3165 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3166 else if (!strcmp(key, "options.default-msg-cleanup")) {
3167 opts->explicit_cleanup = 1;
3168 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3169 } else
3170 return error(_("invalid key: %s"), key);
3171
3172 if (!error_flag)
3173 return error(_("invalid value for '%s': '%s'"), key, value);
3174
3175 return 0;
3176 }
3177
3178 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3179 {
3180 int i;
3181 int count;
3182 const char **argv;
3183 char *strategy_opts_string = raw_opts;
3184
3185 if (*strategy_opts_string == ' ')
3186 strategy_opts_string++;
3187
3188 count = split_cmdline(strategy_opts_string, &argv);
3189 if (count < 0)
3190 BUG("could not split '%s': %s", strategy_opts_string,
3191 split_cmdline_strerror(count));
3192 for (i = 0; i < count; i++) {
3193 const char *arg = argv[i];
3194
3195 skip_prefix(arg, "--", &arg);
3196 strvec_push(&opts->xopts, arg);
3197 }
3198 free(argv);
3199 }
3200
3201 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3202 {
3203 strbuf_reset(buf);
3204 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3205 return;
3206 opts->strategy = strbuf_detach(buf, NULL);
3207 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3208 return;
3209
3210 parse_strategy_opts(opts, buf->buf);
3211 }
3212
3213 static int read_trailers(struct replay_opts *opts, struct strbuf *buf)
3214 {
3215 ssize_t len;
3216
3217 strbuf_reset(buf);
3218 len = strbuf_read_file(buf, rebase_path_trailer(), 0);
3219 if (len > 0) {
3220 char *p = buf->buf, *nl;
3221
3222 trailer_config_init();
3223
3224 while ((nl = strchr(p, '\n'))) {
3225 *nl = '\0';
3226 if (!*p)
3227 return error(_("trailers file contains empty line"));
3228 strvec_push(&opts->trailer_args, p);
3229 p = nl + 1;
3230 }
3231 } else if (!len) {
3232 return error(_("trailers file is empty"));
3233 } else if (errno != ENOENT) {
3234 return error(_("cannot read trailers files"));
3235 }
3236
3237 return 0;
3238 }
3239
3240 static int read_populate_opts(struct replay_opts *opts)
3241 {
3242 struct replay_ctx *ctx = opts->ctx;
3243
3244 if (is_rebase_i(opts)) {
3245 struct strbuf buf = STRBUF_INIT;
3246 int ret = 0;
3247
3248 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3249 READ_ONELINER_SKIP_IF_EMPTY)) {
3250 if (!starts_with(buf.buf, "-S"))
3251 strbuf_reset(&buf);
3252 else {
3253 free(opts->gpg_sign);
3254 opts->gpg_sign = xstrdup(buf.buf + 2);
3255 }
3256 strbuf_reset(&buf);
3257 }
3258
3259 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3260 READ_ONELINER_SKIP_IF_EMPTY)) {
3261 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3262 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3263 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3264 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3265 strbuf_reset(&buf);
3266 }
3267
3268 if (file_exists(rebase_path_verbose()))
3269 opts->verbose = 1;
3270
3271 if (file_exists(rebase_path_quiet()))
3272 opts->quiet = 1;
3273
3274 if (file_exists(rebase_path_signoff())) {
3275 opts->allow_ff = 0;
3276 opts->signoff = 1;
3277 }
3278
3279 if (file_exists(rebase_path_cdate_is_adate())) {
3280 opts->allow_ff = 0;
3281 opts->committer_date_is_author_date = 1;
3282 }
3283
3284 if (file_exists(rebase_path_ignore_date())) {
3285 opts->allow_ff = 0;
3286 opts->ignore_date = 1;
3287 }
3288
3289 if (file_exists(rebase_path_reschedule_failed_exec()))
3290 opts->reschedule_failed_exec = 1;
3291 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3292 opts->reschedule_failed_exec = 0;
3293
3294 if (file_exists(rebase_path_drop_redundant_commits()))
3295 opts->drop_redundant_commits = 1;
3296
3297 if (file_exists(rebase_path_keep_redundant_commits()))
3298 opts->keep_redundant_commits = 1;
3299
3300 read_strategy_opts(opts, &buf);
3301
3302 if (read_trailers(opts, &buf)) {
3303 ret = -1;
3304 goto done_rebase_i;
3305 }
3306 strbuf_reset(&buf);
3307
3308 if (read_oneliner(&ctx->current_fixups,
3309 rebase_path_current_fixups(),
3310 READ_ONELINER_SKIP_IF_EMPTY)) {
3311 const char *p = ctx->current_fixups.buf;
3312 ctx->current_fixup_count = 1;
3313 while ((p = strchr(p, '\n'))) {
3314 ctx->current_fixup_count++;
3315 p++;
3316 }
3317 }
3318
3319 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3320 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3321 ret = error(_("unusable squash-onto"));
3322 goto done_rebase_i;
3323 }
3324 opts->have_squash_onto = 1;
3325 }
3326
3327 done_rebase_i:
3328 strbuf_release(&buf);
3329 return ret;
3330 }
3331
3332 if (!file_exists(git_path_opts_file()))
3333 return 0;
3334 /*
3335 * The function git_parse_source(), called from git_config_from_file(),
3336 * may die() in case of a syntactically incorrect file. We do not care
3337 * about this case, though, because we wrote that file ourselves, so we
3338 * are pretty certain that it is syntactically correct.
3339 */
3340 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3341 return error(_("malformed options sheet: '%s'"),
3342 git_path_opts_file());
3343 return 0;
3344 }
3345
3346 static void write_strategy_opts(struct replay_opts *opts)
3347 {
3348 struct strbuf buf = STRBUF_INIT;
3349
3350 /*
3351 * Quote strategy options so that they can be read correctly
3352 * by split_cmdline().
3353 */
3354 quote_cmdline(&buf, opts->xopts.v);
3355 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3356 strbuf_release(&buf);
3357 }
3358
3359 int write_basic_state(struct replay_opts *opts, const char *head_name,
3360 struct commit *onto, const struct object_id *orig_head)
3361 {
3362 if (head_name)
3363 write_file(rebase_path_head_name(), "%s\n", head_name);
3364 if (onto)
3365 write_file(rebase_path_onto(), "%s\n",
3366 oid_to_hex(&onto->object.oid));
3367 if (orig_head)
3368 write_file(rebase_path_orig_head(), "%s\n",
3369 oid_to_hex(orig_head));
3370
3371 if (opts->quiet)
3372 write_file(rebase_path_quiet(), "%s", "");
3373 if (opts->verbose)
3374 write_file(rebase_path_verbose(), "%s", "");
3375 if (opts->strategy)
3376 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3377 if (opts->xopts.nr > 0)
3378 write_strategy_opts(opts);
3379
3380 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3381 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3382 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3383 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3384
3385 if (opts->gpg_sign)
3386 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3387 if (opts->signoff)
3388 write_file(rebase_path_signoff(), "--signoff\n");
3389 if (opts->drop_redundant_commits)
3390 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3391 if (opts->keep_redundant_commits)
3392 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3393 if (opts->committer_date_is_author_date)
3394 write_file(rebase_path_cdate_is_adate(), "%s", "");
3395 if (opts->ignore_date)
3396 write_file(rebase_path_ignore_date(), "%s", "");
3397 if (opts->reschedule_failed_exec)
3398 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3399 else
3400 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3401 if (opts->trailer_args.nr) {
3402 struct strbuf buf = STRBUF_INIT;
3403
3404 for (size_t i = 0; i < opts->trailer_args.nr; i++)
3405 strbuf_addf(&buf, "%s\n", opts->trailer_args.v[i]);
3406 write_file(rebase_path_trailer(), "%s", buf.buf);
3407 strbuf_release(&buf);
3408 }
3409
3410 return 0;
3411 }
3412
3413 static int walk_revs_populate_todo(struct todo_list *todo_list,
3414 struct replay_opts *opts)
3415 {
3416 enum todo_command command = opts->action == REPLAY_PICK ?
3417 TODO_PICK : TODO_REVERT;
3418 const char *command_string = todo_command_info[command].str;
3419 const char *encoding;
3420 struct commit *commit;
3421
3422 if (prepare_revs(opts))
3423 return -1;
3424
3425 encoding = get_log_output_encoding();
3426
3427 while ((commit = get_revision(opts->revs))) {
3428 struct todo_item *item = append_new_todo(todo_list);
3429 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3430 commit, NULL,
3431 encoding);
3432 const char *subject;
3433 int subject_len;
3434
3435 item->command = command;
3436 item->commit = commit;
3437 item->arg_offset = 0;
3438 item->arg_len = 0;
3439 item->offset_in_buf = todo_list->buf.len;
3440 subject_len = find_commit_subject(commit_buffer, &subject);
3441 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3442 short_commit_name(the_repository, commit),
3443 subject_len, subject);
3444 repo_unuse_commit_buffer(the_repository, commit,
3445 commit_buffer);
3446 }
3447
3448 if (!todo_list->nr)
3449 return error(_("empty commit set passed"));
3450
3451 return 0;
3452 }
3453
3454 static int create_seq_dir(struct repository *r)
3455 {
3456 enum replay_action action;
3457 const char *in_progress_error = NULL;
3458 const char *in_progress_advice = NULL;
3459 unsigned int advise_skip =
3460 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3461 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3462
3463 if (!sequencer_get_last_command(r, &action)) {
3464 switch (action) {
3465 case REPLAY_REVERT:
3466 in_progress_error = _("revert is already in progress");
3467 in_progress_advice =
3468 _("try \"git revert (--continue | %s--abort | --quit)\"");
3469 break;
3470 case REPLAY_PICK:
3471 in_progress_error = _("cherry-pick is already in progress");
3472 in_progress_advice =
3473 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3474 break;
3475 default:
3476 BUG("unexpected action in create_seq_dir");
3477 }
3478 }
3479 if (in_progress_error) {
3480 error("%s", in_progress_error);
3481 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3482 advise(in_progress_advice,
3483 advise_skip ? "--skip | " : "");
3484 return -1;
3485 }
3486 if (mkdir(git_path_seq_dir(), 0777) < 0)
3487 return error_errno(_("could not create sequencer directory '%s'"),
3488 git_path_seq_dir());
3489
3490 return 0;
3491 }
3492
3493 static int save_head(const char *head)
3494 {
3495 return write_message(head, strlen(head), git_path_head_file(), 1);
3496 }
3497
3498 static int rollback_is_safe(void)
3499 {
3500 struct strbuf sb = STRBUF_INIT;
3501 struct object_id expected_head, actual_head;
3502
3503 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3504 strbuf_trim(&sb);
3505 if (get_oid_hex(sb.buf, &expected_head)) {
3506 strbuf_release(&sb);
3507 die(_("could not parse %s"), git_path_abort_safety_file());
3508 }
3509 strbuf_release(&sb);
3510 }
3511 else if (errno == ENOENT)
3512 oidclr(&expected_head, the_repository->hash_algo);
3513 else
3514 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3515
3516 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3517 oidclr(&actual_head, the_repository->hash_algo);
3518
3519 return oideq(&actual_head, &expected_head);
3520 }
3521
3522 static int reset_merge(const struct object_id *oid)
3523 {
3524 struct child_process cmd = CHILD_PROCESS_INIT;
3525
3526 cmd.git_cmd = 1;
3527 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3528
3529 if (!is_null_oid(oid))
3530 strvec_push(&cmd.args, oid_to_hex(oid));
3531
3532 return run_command(&cmd);
3533 }
3534
3535 static int rollback_single_pick(struct repository *r)
3536 {
3537 struct object_id head_oid;
3538
3539 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3540 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3541 return error(_("no cherry-pick or revert in progress"));
3542 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3543 return error(_("cannot resolve HEAD"));
3544 if (is_null_oid(&head_oid))
3545 return error(_("cannot abort from a branch yet to be born"));
3546 return reset_merge(&head_oid);
3547 }
3548
3549 static int skip_single_pick(void)
3550 {
3551 struct object_id head;
3552
3553 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3554 return error(_("cannot resolve HEAD"));
3555 return reset_merge(&head);
3556 }
3557
3558 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3559 {
3560 FILE *f;
3561 struct object_id oid;
3562 struct strbuf buf = STRBUF_INIT;
3563 const char *p;
3564
3565 f = fopen(git_path_head_file(), "r");
3566 if (!f && errno == ENOENT) {
3567 /*
3568 * There is no multiple-cherry-pick in progress.
3569 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3570 * a single-cherry-pick in progress, abort that.
3571 */
3572 return rollback_single_pick(r);
3573 }
3574 if (!f)
3575 return error_errno(_("cannot open '%s'"), git_path_head_file());
3576 if (strbuf_getline_lf(&buf, f)) {
3577 error(_("cannot read '%s': %s"), git_path_head_file(),
3578 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3579 fclose(f);
3580 goto fail;
3581 }
3582 fclose(f);
3583 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3584 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3585 git_path_head_file());
3586 goto fail;
3587 }
3588 if (is_null_oid(&oid)) {
3589 error(_("cannot abort from a branch yet to be born"));
3590 goto fail;
3591 }
3592
3593 if (!rollback_is_safe()) {
3594 /* Do not error, just do not rollback */
3595 warning(_("You seem to have moved HEAD. "
3596 "Not rewinding, check your HEAD!"));
3597 } else
3598 if (reset_merge(&oid))
3599 goto fail;
3600 strbuf_release(&buf);
3601 return sequencer_remove_state(opts);
3602 fail:
3603 strbuf_release(&buf);
3604 return -1;
3605 }
3606
3607 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3608 {
3609 enum replay_action action = -1;
3610 sequencer_get_last_command(r, &action);
3611
3612 /*
3613 * Check whether the subcommand requested to skip the commit is actually
3614 * in progress and that it's safe to skip the commit.
3615 *
3616 * opts->action tells us which subcommand requested to skip the commit.
3617 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3618 * action is in progress and we can skip the commit.
3619 *
3620 * Otherwise we check that the last instruction was related to the
3621 * particular subcommand we're trying to execute and barf if that's not
3622 * the case.
3623 *
3624 * Finally we check that the rollback is "safe", i.e., has the HEAD
3625 * moved? In this case, it doesn't make sense to "reset the merge" and
3626 * "skip the commit" as the user already handled this by committing. But
3627 * we'd not want to barf here, instead give advice on how to proceed. We
3628 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3629 * it gets removed when the user commits, so if it still exists we're
3630 * sure the user can't have committed before.
3631 */
3632 switch (opts->action) {
3633 case REPLAY_REVERT:
3634 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3635 if (action != REPLAY_REVERT)
3636 return error(_("no revert in progress"));
3637 if (!rollback_is_safe())
3638 goto give_advice;
3639 }
3640 break;
3641 case REPLAY_PICK:
3642 if (!refs_ref_exists(get_main_ref_store(r),
3643 "CHERRY_PICK_HEAD")) {
3644 if (action != REPLAY_PICK)
3645 return error(_("no cherry-pick in progress"));
3646 if (!rollback_is_safe())
3647 goto give_advice;
3648 }
3649 break;
3650 default:
3651 BUG("unexpected action in sequencer_skip");
3652 }
3653
3654 if (skip_single_pick())
3655 return error(_("failed to skip the commit"));
3656 if (!is_directory(git_path_seq_dir()))
3657 return 0;
3658
3659 return sequencer_continue(r, opts);
3660
3661 give_advice:
3662 error(_("there is nothing to skip"));
3663
3664 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3665 advise(_("have you committed already?\n"
3666 "try \"git %s --continue\""),
3667 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3668 }
3669 return -1;
3670 }
3671
3672 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3673 int reschedule)
3674 {
3675 struct lock_file todo_lock = LOCK_INIT;
3676 const char *todo_path = get_todo_path(opts);
3677 int next = todo_list->current, offset, fd;
3678
3679 /*
3680 * rebase -i writes "git-rebase-todo" without the currently executing
3681 * command, appending it to "done" instead.
3682 */
3683 if (is_rebase_i(opts) && !reschedule)
3684 next++;
3685
3686 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3687 if (fd < 0)
3688 return error_errno(_("could not lock '%s'"), todo_path);
3689 offset = get_item_line_offset(todo_list, next);
3690 if (write_in_full(fd, todo_list->buf.buf + offset,
3691 todo_list->buf.len - offset) < 0)
3692 return error_errno(_("could not write to '%s'"), todo_path);
3693 if (commit_lock_file(&todo_lock) < 0)
3694 return error(_("failed to finalize '%s'"), todo_path);
3695
3696 if (is_rebase_i(opts) && !reschedule && next > 0) {
3697 const char *done = rebase_path_done();
3698 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3699 int ret = 0;
3700
3701 if (fd < 0)
3702 return 0;
3703 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3704 get_item_line_length(todo_list, next - 1))
3705 < 0)
3706 ret = error_errno(_("could not write to '%s'"), done);
3707 if (close(fd) < 0)
3708 ret = error_errno(_("failed to finalize '%s'"), done);
3709 return ret;
3710 }
3711 return 0;
3712 }
3713
3714 static int save_opts(struct replay_opts *opts)
3715 {
3716 const char *opts_file = git_path_opts_file();
3717 int res = 0;
3718
3719 if (opts->no_commit)
3720 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3721 "options.no-commit", NULL, "true");
3722 if (opts->edit >= 0)
3723 res |= repo_config_set_in_file_gently(the_repository, opts_file, "options.edit", NULL,
3724 opts->edit ? "true" : "false");
3725 if (opts->allow_empty)
3726 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3727 "options.allow-empty", NULL, "true");
3728 if (opts->allow_empty_message)
3729 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3730 "options.allow-empty-message", NULL, "true");
3731 if (opts->drop_redundant_commits)
3732 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3733 "options.drop-redundant-commits", NULL, "true");
3734 if (opts->keep_redundant_commits)
3735 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3736 "options.keep-redundant-commits", NULL, "true");
3737 if (opts->signoff)
3738 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3739 "options.signoff", NULL, "true");
3740 if (opts->record_origin)
3741 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3742 "options.record-origin", NULL, "true");
3743 if (opts->allow_ff)
3744 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3745 "options.allow-ff", NULL, "true");
3746 if (opts->mainline) {
3747 struct strbuf buf = STRBUF_INIT;
3748 strbuf_addf(&buf, "%d", opts->mainline);
3749 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3750 "options.mainline", NULL, buf.buf);
3751 strbuf_release(&buf);
3752 }
3753 if (opts->strategy)
3754 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3755 "options.strategy", NULL, opts->strategy);
3756 if (opts->gpg_sign)
3757 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3758 "options.gpg-sign", NULL, opts->gpg_sign);
3759 for (size_t i = 0; i < opts->xopts.nr; i++)
3760 res |= repo_config_set_multivar_in_file_gently(the_repository, opts_file,
3761 "options.strategy-option",
3762 opts->xopts.v[i], "^$", NULL, 0);
3763 if (opts->allow_rerere_auto)
3764 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3765 "options.allow-rerere-auto", NULL,
3766 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3767 "true" : "false");
3768
3769 if (opts->explicit_cleanup)
3770 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3771 "options.default-msg-cleanup", NULL,
3772 describe_cleanup_mode(opts->default_msg_cleanup));
3773 return res;
3774 }
3775
3776 static int make_patch(struct repository *r,
3777 struct commit *commit,
3778 struct replay_opts *opts)
3779 {
3780 struct rev_info log_tree_opt;
3781 const char *subject;
3782 char hex[GIT_MAX_HEXSZ + 1];
3783 int res = 0;
3784
3785 if (!is_rebase_i(opts))
3786 BUG("make_patch should only be called when rebasing");
3787
3788 oid_to_hex_r(hex, &commit->object.oid);
3789 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3790 return -1;
3791 res |= write_rebase_head(&commit->object.oid);
3792
3793 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3794 repo_init_revisions(r, &log_tree_opt, NULL);
3795 log_tree_opt.abbrev = 0;
3796 log_tree_opt.diff = 1;
3797 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3798 log_tree_opt.disable_stdin = 1;
3799 log_tree_opt.no_commit_id = 1;
3800 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3801 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3802 if (!log_tree_opt.diffopt.file)
3803 res |= error_errno(_("could not open '%s'"),
3804 rebase_path_patch());
3805 else {
3806 res |= log_tree_commit(&log_tree_opt, commit);
3807 fclose(log_tree_opt.diffopt.file);
3808 }
3809
3810 if (!file_exists(rebase_path_message())) {
3811 const char *encoding = get_commit_output_encoding();
3812 const char *commit_buffer = repo_logmsg_reencode(r,
3813 commit, NULL,
3814 encoding);
3815 find_commit_subject(commit_buffer, &subject);
3816 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3817 repo_unuse_commit_buffer(r, commit,
3818 commit_buffer);
3819 }
3820 release_revisions(&log_tree_opt);
3821
3822 return res;
3823 }
3824
3825 static int intend_to_amend(void)
3826 {
3827 struct object_id head;
3828 char *p;
3829
3830 if (repo_get_oid(the_repository, "HEAD", &head))
3831 return error(_("cannot read HEAD"));
3832
3833 p = oid_to_hex(&head);
3834 return write_message(p, strlen(p), rebase_path_amend(), 1);
3835 }
3836
3837 static int error_with_patch(struct repository *r,
3838 struct commit *commit,
3839 const char *subject, int subject_len,
3840 struct replay_opts *opts,
3841 int exit_code, int to_amend)
3842 {
3843 struct replay_ctx *ctx = opts->ctx;
3844
3845 /*
3846 * Write the commit message to be used by "git rebase
3847 * --continue". If a "fixup" or "squash" command has conflicts
3848 * then we will have already written rebase_path_message() in
3849 * error_failed_squash(). If an "edit" command was
3850 * fast-forwarded then we don't have a message in ctx->message
3851 * and rely on make_patch() to write rebase_path_message()
3852 * instead.
3853 */
3854 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3855 write_message(ctx->message.buf, ctx->message.len,
3856 rebase_path_message(), 0))
3857 return error(_("could not write commit message file"));
3858
3859 if (commit && make_patch(r, commit, opts))
3860 return -1;
3861
3862 if (to_amend) {
3863 if (intend_to_amend())
3864 return -1;
3865
3866 fprintf(stderr,
3867 _("You can amend the commit now, with\n"
3868 "\n"
3869 " git commit --amend %s\n"
3870 "\n"
3871 "Once you are satisfied with your changes, run\n"
3872 "\n"
3873 " git rebase --continue\n"),
3874 gpg_sign_opt_quoted(opts));
3875 } else if (exit_code) {
3876 if (commit)
3877 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3878 short_commit_name(r, commit), subject_len, subject);
3879 else
3880 /*
3881 * We don't have the hash of the parent so
3882 * just print the line from the todo file.
3883 */
3884 fprintf_ln(stderr, _("Could not merge %.*s"),
3885 subject_len, subject);
3886 }
3887
3888 return exit_code;
3889 }
3890
3891 static int error_failed_squash(struct repository *r,
3892 struct commit *commit,
3893 struct replay_opts *opts,
3894 int subject_len,
3895 const char *subject)
3896 {
3897 if (copy_file(r, rebase_path_message(), rebase_path_squash_msg(), 0666))
3898 return error(_("could not copy '%s' to '%s'"),
3899 rebase_path_squash_msg(), rebase_path_message());
3900 unlink(git_path_merge_msg(r));
3901 if (copy_file(r, git_path_merge_msg(r), rebase_path_message(), 0666))
3902 return error(_("could not copy '%s' to '%s'"),
3903 rebase_path_message(),
3904 git_path_merge_msg(r));
3905 return error_with_patch(r, commit, subject, subject_len, opts, 1, 1);
3906 }
3907
3908 static int do_exec(struct repository *r, const char *command_line, int quiet)
3909 {
3910 struct child_process cmd = CHILD_PROCESS_INIT;
3911 int dirty, status;
3912
3913 if (!quiet)
3914 fprintf(stderr, _("Executing: %s\n"), command_line);
3915 cmd.use_shell = 1;
3916 strvec_push(&cmd.args, command_line);
3917 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3918 status = run_command(&cmd);
3919
3920 /* force re-reading of the cache */
3921 discard_index(r->index);
3922 if (repo_read_index(r) < 0)
3923 return error(_("could not read index"));
3924
3925 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3926
3927 if (status) {
3928 warning(_("execution failed: %s\n%s"
3929 "You can fix the problem, and then run\n"
3930 "\n"
3931 " git rebase --continue\n"
3932 "\n"),
3933 command_line,
3934 dirty ? _("and made changes to the index and/or the "
3935 "working tree.\n") : "");
3936 if (status == 127)
3937 /* command not found */
3938 status = 1;
3939 } else if (dirty) {
3940 warning(_("execution succeeded: %s\nbut "
3941 "left changes to the index and/or the working tree.\n"
3942 "Commit or stash your changes, and then run\n"
3943 "\n"
3944 " git rebase --continue\n"
3945 "\n"), command_line);
3946 status = 1;
3947 }
3948
3949 return status;
3950 }
3951
3952 __attribute__((format (printf, 2, 3)))
3953 static int safe_append(const char *filename, const char *fmt, ...)
3954 {
3955 va_list ap;
3956 struct lock_file lock = LOCK_INIT;
3957 int fd = hold_lock_file_for_update(&lock, filename,
3958 LOCK_REPORT_ON_ERROR);
3959 struct strbuf buf = STRBUF_INIT;
3960
3961 if (fd < 0)
3962 return -1;
3963
3964 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3965 error_errno(_("could not read '%s'"), filename);
3966 rollback_lock_file(&lock);
3967 return -1;
3968 }
3969 strbuf_complete(&buf, '\n');
3970 va_start(ap, fmt);
3971 strbuf_vaddf(&buf, fmt, ap);
3972 va_end(ap);
3973
3974 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3975 error_errno(_("could not write to '%s'"), filename);
3976 strbuf_release(&buf);
3977 rollback_lock_file(&lock);
3978 return -1;
3979 }
3980 if (commit_lock_file(&lock) < 0) {
3981 strbuf_release(&buf);
3982 return error(_("failed to finalize '%s'"), filename);
3983 }
3984
3985 strbuf_release(&buf);
3986 return 0;
3987 }
3988
3989 static int do_label(struct repository *r, const char *name, int len)
3990 {
3991 struct ref_store *refs = get_main_ref_store(r);
3992 struct ref_transaction *transaction;
3993 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
3994 struct strbuf msg = STRBUF_INIT;
3995 int ret = 0;
3996 struct object_id head_oid;
3997
3998 if (len == 1 && *name == '#')
3999 return error(_("illegal label name: '%.*s'"), len, name);
4000
4001 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
4002 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
4003
4004 transaction = ref_store_transaction_begin(refs, 0, &err);
4005 if (!transaction) {
4006 error("%s", err.buf);
4007 ret = -1;
4008 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
4009 error(_("could not read HEAD"));
4010 ret = -1;
4011 } else if (ref_transaction_update(transaction, ref_name.buf,
4012 &head_oid, NULL, NULL, NULL,
4013 0, msg.buf, &err) < 0 ||
4014 ref_transaction_commit(transaction, &err)) {
4015 error("%s", err.buf);
4016 ret = -1;
4017 }
4018 ref_transaction_free(transaction);
4019 strbuf_release(&err);
4020 strbuf_release(&msg);
4021
4022 if (!ret)
4023 ret = safe_append(rebase_path_refs_to_delete(),
4024 "%s\n", ref_name.buf);
4025 strbuf_release(&ref_name);
4026
4027 return ret;
4028 }
4029
4030 static struct commit *lookup_label(struct repository *r, const char *label,
4031 int len, struct strbuf *buf)
4032 {
4033 struct commit *commit;
4034 struct object_id oid;
4035
4036 strbuf_reset(buf);
4037 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
4038 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
4039 commit = lookup_commit_object(r, &oid);
4040 } else {
4041 /* fall back to non-rewritten ref or commit */
4042 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
4043 commit = lookup_commit_reference_by_name(buf->buf);
4044 }
4045
4046 if (!commit)
4047 error(_("could not resolve '%s'"), buf->buf);
4048
4049 return commit;
4050 }
4051
4052 static int do_reset(struct repository *r,
4053 const char *name, int len,
4054 struct replay_opts *opts)
4055 {
4056 struct strbuf ref_name = STRBUF_INIT;
4057 struct object_id oid;
4058 struct lock_file lock = LOCK_INIT;
4059 struct tree_desc desc = { 0 };
4060 struct tree *tree;
4061 struct unpack_trees_options unpack_tree_opts = { 0 };
4062 int ret = 0;
4063
4064 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
4065 return -1;
4066
4067 if (len == 10 && !strncmp("[new root]", name, len)) {
4068 if (!opts->have_squash_onto) {
4069 const char *hex;
4070 if (commit_tree("", 0, the_hash_algo->empty_tree,
4071 NULL, &opts->squash_onto,
4072 NULL, NULL))
4073 return error(_("writing fake root commit"));
4074 opts->have_squash_onto = 1;
4075 hex = oid_to_hex(&opts->squash_onto);
4076 if (write_message(hex, strlen(hex),
4077 rebase_path_squash_onto(), 0))
4078 return error(_("writing squash-onto"));
4079 }
4080 oidcpy(&oid, &opts->squash_onto);
4081 } else {
4082 int i;
4083 struct commit *commit;
4084
4085 /* Determine the length of the label */
4086 for (i = 0; i < len; i++)
4087 if (isspace(name[i]))
4088 break;
4089 len = i;
4090
4091 commit = lookup_label(r, name, len, &ref_name);
4092 if (!commit) {
4093 ret = -1;
4094 goto cleanup;
4095 }
4096 oid = commit->object.oid;
4097 }
4098
4099 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4100 unpack_tree_opts.head_idx = 1;
4101 unpack_tree_opts.src_index = r->index;
4102 unpack_tree_opts.dst_index = r->index;
4103 unpack_tree_opts.fn = oneway_merge;
4104 unpack_tree_opts.merge = 1;
4105 unpack_tree_opts.update = 1;
4106 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4107 unpack_tree_opts.skip_cache_tree_update = 1;
4108 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4109
4110 if (repo_read_index_unmerged(r)) {
4111 ret = error_resolve_conflict(action_name(opts));
4112 goto cleanup;
4113 }
4114
4115 if (!fill_tree_descriptor(r, &desc, &oid)) {
4116 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4117 goto cleanup;
4118 }
4119
4120 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4121 ret = -1;
4122 goto cleanup;
4123 }
4124
4125 tree = repo_parse_tree_indirect(the_repository, &oid);
4126 if (!tree)
4127 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4128 prime_cache_tree(r, r->index, tree);
4129
4130 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4131 ret = error(_("could not write index"));
4132
4133 if (!ret)
4134 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4135 len, name),
4136 "HEAD", &oid,
4137 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4138 cleanup:
4139 free((void *)desc.buffer);
4140 if (ret < 0)
4141 rollback_lock_file(&lock);
4142 strbuf_release(&ref_name);
4143 clear_unpack_trees_porcelain(&unpack_tree_opts);
4144 return ret;
4145 }
4146
4147 static int do_merge(struct repository *r,
4148 struct commit *commit,
4149 const char *arg, int arg_len,
4150 int flags, int *check_todo, struct replay_opts *opts)
4151 {
4152 struct replay_ctx *ctx = opts->ctx;
4153 int run_commit_flags = 0;
4154 struct strbuf ref_name = STRBUF_INIT;
4155 struct commit *head_commit, *merge_commit, *i;
4156 struct commit_list *bases = NULL, *j;
4157 struct commit_list *to_merge = NULL, **tail = &to_merge;
4158 const char *strategy = !opts->xopts.nr &&
4159 (!opts->strategy ||
4160 !strcmp(opts->strategy, "recursive") ||
4161 !strcmp(opts->strategy, "ort")) ?
4162 NULL : opts->strategy;
4163 struct merge_options o;
4164 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4165 static struct lock_file lock;
4166 const char *p;
4167 const char *reflog_action = reflog_message(opts, "merge", NULL);
4168
4169 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4170 ret = -1;
4171 goto leave_merge;
4172 }
4173
4174 head_commit = lookup_commit_reference_by_name("HEAD");
4175 if (!head_commit) {
4176 ret = error(_("cannot merge without a current revision"));
4177 goto leave_merge;
4178 }
4179
4180 /*
4181 * For octopus merges, the arg starts with the list of revisions to be
4182 * merged. The list is optionally followed by '#' and the oneline.
4183 */
4184 merge_arg_len = oneline_offset = arg_len;
4185 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4186 if (!*p)
4187 break;
4188 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4189 p += 1 + strspn(p + 1, " \t\n");
4190 oneline_offset = p - arg;
4191 break;
4192 }
4193 k = strcspn(p, " \t\n");
4194 if (!k)
4195 continue;
4196 merge_commit = lookup_label(r, p, k, &ref_name);
4197 if (!merge_commit) {
4198 ret = error(_("unable to parse '%.*s'"), k, p);
4199 goto leave_merge;
4200 }
4201 tail = &commit_list_insert(merge_commit, tail)->next;
4202 p += k;
4203 merge_arg_len = p - arg;
4204 }
4205
4206 if (!to_merge) {
4207 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4208 goto leave_merge;
4209 }
4210
4211 if (opts->have_squash_onto &&
4212 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4213 /*
4214 * When the user tells us to "merge" something into a
4215 * "[new root]", let's simply fast-forward to the merge head.
4216 */
4217 rollback_lock_file(&lock);
4218 if (to_merge->next)
4219 ret = error(_("octopus merge cannot be executed on "
4220 "top of a [new root]"));
4221 else
4222 ret = fast_forward_to(r, &to_merge->item->object.oid,
4223 &head_commit->object.oid, 0,
4224 opts);
4225 goto leave_merge;
4226 }
4227
4228 /*
4229 * If HEAD is not identical to the first parent of the original merge
4230 * commit, we cannot fast-forward.
4231 */
4232 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4233 oideq(&commit->parents->item->object.oid,
4234 &head_commit->object.oid);
4235
4236 /*
4237 * If any merge head is different from the original one, we cannot
4238 * fast-forward.
4239 */
4240 if (can_fast_forward) {
4241 struct commit_list *p = commit->parents->next;
4242
4243 for (j = to_merge; j && p; j = j->next, p = p->next)
4244 if (!oideq(&j->item->object.oid,
4245 &p->item->object.oid)) {
4246 can_fast_forward = 0;
4247 break;
4248 }
4249 /*
4250 * If the number of merge heads differs from the original merge
4251 * commit, we cannot fast-forward.
4252 */
4253 if (j || p)
4254 can_fast_forward = 0;
4255 }
4256
4257 if (can_fast_forward) {
4258 rollback_lock_file(&lock);
4259 ret = fast_forward_to(r, &commit->object.oid,
4260 &head_commit->object.oid, 0, opts);
4261 if (flags & TODO_EDIT_MERGE_MSG)
4262 goto fast_forward_edit;
4263
4264 goto leave_merge;
4265 }
4266
4267 if (commit) {
4268 const char *encoding = get_commit_output_encoding();
4269 const char *message = repo_logmsg_reencode(r, commit, NULL,
4270 encoding);
4271 const char *body;
4272 int len;
4273
4274 if (!message) {
4275 ret = error(_("could not get commit message of '%s'"),
4276 oid_to_hex(&commit->object.oid));
4277 goto leave_merge;
4278 }
4279 write_author_script(message);
4280 find_commit_subject(message, &body);
4281 len = strlen(body);
4282 strbuf_add(&ctx->message, body, len);
4283 repo_unuse_commit_buffer(r, commit, message);
4284 } else {
4285 struct strbuf buf = STRBUF_INIT;
4286
4287 strbuf_addf(&buf, "author %s", git_author_info(0));
4288 write_author_script(buf.buf);
4289 strbuf_release(&buf);
4290
4291 if (oneline_offset < arg_len) {
4292 strbuf_add(&ctx->message, arg + oneline_offset,
4293 arg_len - oneline_offset);
4294 } else {
4295 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4296 to_merge->next ? "branches" : "branch",
4297 merge_arg_len, arg);
4298 }
4299 }
4300 ctx->have_message = 1;
4301 if (write_message(ctx->message.buf, ctx->message.len,
4302 git_path_merge_msg(r), 0)) {
4303 ret = error_errno(_("could not write '%s'"),
4304 git_path_merge_msg(r));
4305 goto leave_merge;
4306 }
4307
4308 if (strategy || to_merge->next) {
4309 /* Octopus merge */
4310 struct child_process cmd = CHILD_PROCESS_INIT;
4311
4312 if (read_env_script(&cmd.env)) {
4313 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4314
4315 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4316 goto leave_merge;
4317 }
4318
4319 if (opts->committer_date_is_author_date)
4320 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4321 opts->ignore_date ?
4322 "" :
4323 author_date_from_env(&cmd.env));
4324 if (opts->ignore_date)
4325 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4326
4327 cmd.git_cmd = 1;
4328 strvec_push(&cmd.args, "merge");
4329 strvec_push(&cmd.args, "-s");
4330 if (!strategy)
4331 strvec_push(&cmd.args, "octopus");
4332 else {
4333 strvec_push(&cmd.args, strategy);
4334 for (k = 0; k < opts->xopts.nr; k++)
4335 strvec_pushf(&cmd.args,
4336 "-X%s", opts->xopts.v[k]);
4337 }
4338 if (!(flags & TODO_EDIT_MERGE_MSG))
4339 strvec_push(&cmd.args, "--no-edit");
4340 else
4341 strvec_push(&cmd.args, "--edit");
4342 strvec_push(&cmd.args, "--no-ff");
4343 strvec_push(&cmd.args, "--no-log");
4344 strvec_push(&cmd.args, "--no-stat");
4345 strvec_push(&cmd.args, "-F");
4346 strvec_push(&cmd.args, git_path_merge_msg(r));
4347 if (opts->gpg_sign)
4348 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4349 else
4350 strvec_push(&cmd.args, "--no-gpg-sign");
4351
4352 /* Add the tips to be merged */
4353 for (j = to_merge; j; j = j->next)
4354 strvec_push(&cmd.args,
4355 oid_to_hex(&j->item->object.oid));
4356
4357 strbuf_release(&ref_name);
4358 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4359 NULL, REF_NO_DEREF);
4360 rollback_lock_file(&lock);
4361
4362 ret = run_command(&cmd);
4363
4364 /* force re-reading of the cache */
4365 if (!ret) {
4366 discard_index(r->index);
4367 if (repo_read_index(r) < 0)
4368 ret = error(_("could not read index"));
4369 }
4370 goto leave_merge;
4371 }
4372
4373 merge_commit = to_merge->item;
4374 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4375 ret = -1;
4376 goto leave_merge;
4377 }
4378
4379 if (bases && oideq(&merge_commit->object.oid,
4380 &bases->item->object.oid)) {
4381 ret = 0;
4382 /* skip merging an ancestor of HEAD */
4383 goto leave_merge;
4384 }
4385
4386 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4387 git_path_merge_head(r), 0);
4388 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4389
4390 bases = commit_list_reverse(bases);
4391
4392 repo_read_index(r);
4393 init_ui_merge_options(&o, r);
4394 o.branch1 = "HEAD";
4395 o.branch2 = ref_name.buf;
4396 o.buffer_output = 2;
4397
4398 /*
4399 * TODO: Should use merge_incore_recursive() and
4400 * merge_switch_to_result(), skipping the call to
4401 * merge_switch_to_result() when we don't actually need to
4402 * update the index and working copy immediately.
4403 */
4404 ret = merge_ort_recursive(&o, head_commit, merge_commit, bases, &i);
4405 if (ret <= 0)
4406 fputs(o.obuf.buf, stdout);
4407 strbuf_release(&o.obuf);
4408 if (ret < 0) {
4409 error(_("could not even attempt to merge '%.*s'"),
4410 merge_arg_len, arg);
4411 unlink(git_path_merge_msg(r));
4412 goto leave_merge;
4413 }
4414 /*
4415 * The return value of merge_ort_recursive() is 1 on clean, and 0 on
4416 * unclean merge.
4417 *
4418 * Let's reverse that, so that do_merge() returns 0 upon success and
4419 * 1 upon failed merge (keeping the return value -1 for the cases where
4420 * we will want to reschedule the `merge` command).
4421 */
4422 ret = !ret;
4423
4424 if (r->index->cache_changed &&
4425 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4426 ret = error(_("merge: Unable to write new index file"));
4427 goto leave_merge;
4428 }
4429
4430 rollback_lock_file(&lock);
4431 if (ret)
4432 repo_rerere(r, opts->allow_rerere_auto);
4433 else
4434 /*
4435 * In case of problems, we now want to return a positive
4436 * value (a negative one would indicate that the `merge`
4437 * command needs to be rescheduled).
4438 */
4439 ret = !!run_git_commit(git_path_merge_msg(r), reflog_action,
4440 opts, run_commit_flags);
4441
4442 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4443 fast_forward_edit:
4444 *check_todo = 1;
4445 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4446 ret = !!run_git_commit(NULL, reflog_action, opts,
4447 run_commit_flags);
4448 }
4449
4450
4451 leave_merge:
4452 strbuf_release(&ref_name);
4453 rollback_lock_file(&lock);
4454 commit_list_free(to_merge);
4455 commit_list_free(bases);
4456 return ret;
4457 }
4458
4459 static int write_update_refs_state(struct string_list *refs_to_oids)
4460 {
4461 int result = 0;
4462 struct lock_file lock = LOCK_INIT;
4463 FILE *fp = NULL;
4464 struct string_list_item *item;
4465 char *path;
4466
4467 path = rebase_path_update_refs(the_repository->gitdir);
4468
4469 if (!refs_to_oids->nr) {
4470 if (unlink(path) && errno != ENOENT)
4471 result = error_errno(_("could not unlink: %s"), path);
4472 goto cleanup;
4473 }
4474
4475 if (safe_create_leading_directories(the_repository, path)) {
4476 result = error(_("unable to create leading directories of %s"),
4477 path);
4478 goto cleanup;
4479 }
4480
4481 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4482 result = error(_("another 'rebase' process appears to be running; "
4483 "'%s.lock' already exists"),
4484 path);
4485 goto cleanup;
4486 }
4487
4488 fp = fdopen_lock_file(&lock, "w");
4489 if (!fp) {
4490 result = error_errno(_("could not open '%s' for writing"), path);
4491 rollback_lock_file(&lock);
4492 goto cleanup;
4493 }
4494
4495 for_each_string_list_item(item, refs_to_oids) {
4496 struct update_ref_record *rec = item->util;
4497 fprintf(fp, "%s\n%s\n%s\n", item->string,
4498 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4499 }
4500
4501 result = commit_lock_file(&lock);
4502
4503 cleanup:
4504 free(path);
4505 return result;
4506 }
4507
4508 /*
4509 * Parse the update-refs file for the current rebase, then remove the
4510 * refs that do not appear in the todo_list (and have not had updated
4511 * values stored) and add refs that are in the todo_list but not
4512 * represented in the update-refs file.
4513 *
4514 * If there are changes to the update-refs list, then write the new state
4515 * to disk.
4516 */
4517 void todo_list_filter_update_refs(struct repository *r,
4518 struct todo_list *todo_list)
4519 {
4520 int i;
4521 int updated = 0;
4522 struct string_list update_refs = STRING_LIST_INIT_DUP;
4523
4524 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4525
4526 /*
4527 * For each item in the update_refs list, if it has no updated
4528 * value and does not appear in the todo_list, then remove it
4529 * from the update_refs list.
4530 */
4531 for (i = 0; i < update_refs.nr; i++) {
4532 int j;
4533 int found = 0;
4534 const char *ref = update_refs.items[i].string;
4535 size_t reflen = strlen(ref);
4536 struct update_ref_record *rec = update_refs.items[i].util;
4537
4538 /* OID already stored as updated. */
4539 if (!is_null_oid(&rec->after))
4540 continue;
4541
4542 for (j = 0; !found && j < todo_list->nr; j++) {
4543 struct todo_item *item = &todo_list->items[j];
4544 const char *arg = todo_list->buf.buf + item->arg_offset;
4545
4546 if (item->command != TODO_UPDATE_REF)
4547 continue;
4548
4549 if (item->arg_len != reflen ||
4550 strncmp(arg, ref, reflen))
4551 continue;
4552
4553 found = 1;
4554 }
4555
4556 if (!found) {
4557 free(update_refs.items[i].string);
4558 free(update_refs.items[i].util);
4559
4560 update_refs.nr--;
4561 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4562
4563 updated = 1;
4564 i--;
4565 }
4566 }
4567
4568 /*
4569 * For each todo_item, check if its ref is in the update_refs list.
4570 * If not, then add it as an un-updated ref.
4571 */
4572 for (i = 0; i < todo_list->nr; i++) {
4573 struct todo_item *item = &todo_list->items[i];
4574 const char *arg = todo_list->buf.buf + item->arg_offset;
4575 int j, found = 0;
4576
4577 if (item->command != TODO_UPDATE_REF)
4578 continue;
4579
4580 for (j = 0; !found && j < update_refs.nr; j++) {
4581 const char *ref = update_refs.items[j].string;
4582
4583 found = strlen(ref) == item->arg_len &&
4584 !strncmp(ref, arg, item->arg_len);
4585 }
4586
4587 if (!found) {
4588 struct string_list_item *inserted;
4589 struct strbuf argref = STRBUF_INIT;
4590
4591 strbuf_add(&argref, arg, item->arg_len);
4592 inserted = string_list_insert(&update_refs, argref.buf);
4593 inserted->util = init_update_ref_record(argref.buf);
4594 strbuf_release(&argref);
4595 updated = 1;
4596 }
4597 }
4598
4599 if (updated)
4600 write_update_refs_state(&update_refs);
4601 string_list_clear(&update_refs, 1);
4602 }
4603
4604 static int do_update_ref(struct repository *r, const char *refname)
4605 {
4606 struct string_list_item *item;
4607 struct string_list list = STRING_LIST_INIT_DUP;
4608
4609 if (sequencer_get_update_refs_state(r->gitdir, &list))
4610 return -1;
4611
4612 for_each_string_list_item(item, &list) {
4613 if (!strcmp(item->string, refname)) {
4614 struct update_ref_record *rec = item->util;
4615 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4616 return -1;
4617 break;
4618 }
4619 }
4620
4621 write_update_refs_state(&list);
4622 string_list_clear(&list, 1);
4623 return 0;
4624 }
4625
4626 static int do_update_refs(struct repository *r, int quiet)
4627 {
4628 int res = 0;
4629 struct string_list_item *item;
4630 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4631 struct ref_store *refs = get_main_ref_store(r);
4632 struct strbuf update_msg = STRBUF_INIT;
4633 struct strbuf error_msg = STRBUF_INIT;
4634
4635 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4636 return res;
4637
4638 for_each_string_list_item(item, &refs_to_oids) {
4639 struct update_ref_record *rec = item->util;
4640 int loop_res;
4641
4642 loop_res = refs_update_ref(refs, "rewritten during rebase",
4643 item->string,
4644 &rec->after, &rec->before,
4645 0, UPDATE_REFS_MSG_ON_ERR);
4646 res |= loop_res;
4647
4648 if (quiet)
4649 continue;
4650
4651 if (loop_res)
4652 strbuf_addf(&error_msg, "\t%s\n", item->string);
4653 else
4654 strbuf_addf(&update_msg, "\t%s\n", item->string);
4655 }
4656
4657 if (!quiet &&
4658 (update_msg.len || error_msg.len)) {
4659 fprintf(stderr,
4660 _("Updated the following refs with %s:\n%s"),
4661 "--update-refs",
4662 update_msg.buf);
4663
4664 if (res)
4665 fprintf(stderr,
4666 _("Failed to update the following refs with %s:\n%s"),
4667 "--update-refs",
4668 error_msg.buf);
4669 }
4670
4671 string_list_clear(&refs_to_oids, 1);
4672 strbuf_release(&update_msg);
4673 strbuf_release(&error_msg);
4674 return res;
4675 }
4676
4677 static int is_final_fixup(struct todo_list *todo_list)
4678 {
4679 int i = todo_list->current;
4680
4681 if (!is_fixup(todo_list->items[i].command))
4682 return 0;
4683
4684 while (++i < todo_list->nr)
4685 if (is_fixup(todo_list->items[i].command))
4686 return 0;
4687 else if (!is_noop(todo_list->items[i].command))
4688 break;
4689 return 1;
4690 }
4691
4692 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4693 {
4694 int i;
4695
4696 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4697 if (!is_noop(todo_list->items[i].command))
4698 return todo_list->items[i].command;
4699
4700 return -1;
4701 }
4702
4703 static void create_autostash_internal(struct repository *r,
4704 const char *path,
4705 const char *refname,
4706 const char *message,
4707 bool silent)
4708 {
4709 struct strbuf buf = STRBUF_INIT;
4710 struct lock_file lock_file = LOCK_INIT;
4711 int fd;
4712
4713 if (path && refname)
4714 BUG("can only pass path or refname");
4715
4716 fd = repo_hold_locked_index(r, &lock_file, 0);
4717 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4718 if (0 <= fd)
4719 repo_update_index_if_able(r, &lock_file);
4720 rollback_lock_file(&lock_file);
4721
4722 if (has_unstaged_changes(r, 1) ||
4723 has_uncommitted_changes(r, 1)) {
4724 struct child_process stash = CHILD_PROCESS_INIT;
4725 struct reset_working_tree_options ropts = {
4726 .flags = RESET_WORKING_TREE_HARD |
4727 RESET_WORKING_TREE_UPDATE_HEAD,
4728 };
4729 struct object_id oid;
4730
4731 strvec_pushl(&stash.args,
4732 "stash", "create",
4733 message ? message : "autostash", NULL);
4734 stash.git_cmd = 1;
4735 stash.no_stdin = 1;
4736 strbuf_reset(&buf);
4737 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4738 die(_("Cannot autostash"));
4739 strbuf_trim_trailing_newline(&buf);
4740 if (repo_get_oid(r, buf.buf, &oid))
4741 die(_("Unexpected stash response: '%s'"),
4742 buf.buf);
4743 strbuf_reset(&buf);
4744 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4745
4746 if (path) {
4747 if (safe_create_leading_directories_const(the_repository, path))
4748 die(_("Could not create directory for '%s'"),
4749 path);
4750 write_file(path, "%s", oid_to_hex(&oid));
4751 } else {
4752 refs_update_ref(get_main_ref_store(r), "", refname,
4753 &oid, null_oid(the_hash_algo), 0, UPDATE_REFS_DIE_ON_ERR);
4754 }
4755
4756 if (!silent)
4757 printf(_("Created autostash: %s\n"), buf.buf);
4758 if (reset_working_tree(r, &ropts) < 0)
4759 die(_("could not reset --hard"));
4760 discard_index(r->index);
4761 if (repo_read_index(r) < 0)
4762 die(_("could not read index"));
4763 }
4764 strbuf_release(&buf);
4765 }
4766
4767 void create_autostash(struct repository *r, const char *path)
4768 {
4769 create_autostash_internal(r, path, NULL, NULL, false);
4770 }
4771
4772 void create_autostash_ref(struct repository *r, const char *refname,
4773 const char *message, bool silent)
4774 {
4775 create_autostash_internal(r, NULL, refname, message, silent);
4776 }
4777
4778 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply,
4779 const char *label_ours, const char *label_theirs,
4780 const char *label_base,
4781 const char *stash_msg)
4782 {
4783 struct child_process child = CHILD_PROCESS_INIT;
4784 int ret = 0;
4785
4786 if (attempt_apply) {
4787 child.git_cmd = 1;
4788 child.no_stdout = 1;
4789 child.no_stderr = 1;
4790 strvec_push(&child.args, "stash");
4791 strvec_push(&child.args, "apply");
4792 if (label_ours)
4793 strvec_pushf(&child.args, "--label-ours=%s", label_ours);
4794 if (label_theirs)
4795 strvec_pushf(&child.args, "--label-theirs=%s", label_theirs);
4796 if (label_base)
4797 strvec_pushf(&child.args, "--label-base=%s", label_base);
4798 strvec_push(&child.args, stash_oid);
4799 ret = run_command(&child);
4800 }
4801
4802 if (attempt_apply && !ret)
4803 fprintf(stderr, _("Applied autostash.\n"));
4804 else {
4805 struct child_process store = CHILD_PROCESS_INIT;
4806
4807 store.git_cmd = 1;
4808 strvec_push(&store.args, "stash");
4809 strvec_push(&store.args, "store");
4810 strvec_push(&store.args, "-m");
4811 strvec_push(&store.args, stash_msg ? stash_msg : "autostash");
4812 strvec_push(&store.args, "-q");
4813 strvec_push(&store.args, stash_oid);
4814 if (run_command(&store))
4815 ret = error(_("cannot store %s"), stash_oid);
4816 else if (attempt_apply)
4817 fprintf(stderr,
4818 _("Your local changes are stashed, however applying them\n"
4819 "resulted in conflicts. You can either resolve the conflicts\n"
4820 "and then discard the stash with \"git stash drop\", or, if you\n"
4821 "do not want to resolve them now, run \"git reset --hard\" and\n"
4822 "apply the local changes later by running \"git stash pop\".\n"));
4823 else
4824 fprintf(stderr,
4825 _("Autostash exists; creating a new stash entry.\n"
4826 "Your changes are safe in the stash.\n"
4827 "You can run \"git stash pop\" or"
4828 " \"git stash drop\" at any time.\n"));
4829 }
4830
4831 return ret;
4832 }
4833
4834 static int apply_save_autostash(const char *path, int attempt_apply)
4835 {
4836 struct strbuf stash_oid = STRBUF_INIT;
4837 int ret = 0;
4838
4839 if (!read_oneliner(&stash_oid, path,
4840 READ_ONELINER_SKIP_IF_EMPTY)) {
4841 strbuf_release(&stash_oid);
4842 return 0;
4843 }
4844 strbuf_trim(&stash_oid);
4845
4846 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply,
4847 NULL, NULL, NULL, NULL);
4848
4849 unlink(path);
4850 strbuf_release(&stash_oid);
4851 return ret;
4852 }
4853
4854 int save_autostash(const char *path)
4855 {
4856 return apply_save_autostash(path, 0);
4857 }
4858
4859 int apply_autostash(const char *path)
4860 {
4861 return apply_save_autostash(path, 1);
4862 }
4863
4864 int apply_autostash_oid(const char *stash_oid)
4865 {
4866 return apply_save_autostash_oid(stash_oid, 1, NULL, NULL, NULL, NULL);
4867 }
4868
4869 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4870 int attempt_apply,
4871 const char *label_ours, const char *label_theirs,
4872 const char *label_base,
4873 const char *stash_msg)
4874 {
4875 struct object_id stash_oid;
4876 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4877 int flag, ret;
4878
4879 if (!refs_ref_exists(get_main_ref_store(r), refname))
4880 return 0;
4881
4882 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4883 RESOLVE_REF_READING, &stash_oid, &flag))
4884 return -1;
4885 if (flag & REF_ISSYMREF)
4886 return error(_("autostash reference is a symref"));
4887
4888 oid_to_hex_r(stash_oid_hex, &stash_oid);
4889 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply,
4890 label_ours, label_theirs, label_base,
4891 stash_msg);
4892
4893 refs_delete_ref(get_main_ref_store(r), "", refname,
4894 &stash_oid, REF_NO_DEREF);
4895
4896 return ret;
4897 }
4898
4899 int save_autostash_ref(struct repository *r, const char *refname)
4900 {
4901 return apply_save_autostash_ref(r, refname, 0,
4902 NULL, NULL, NULL, NULL);
4903 }
4904
4905 int apply_autostash_ref(struct repository *r, const char *refname,
4906 const char *label_ours, const char *label_theirs,
4907 const char *label_base, const char *stash_msg)
4908 {
4909 return apply_save_autostash_ref(r, refname, 1,
4910 label_ours, label_theirs, label_base,
4911 stash_msg);
4912 }
4913
4914 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4915 const char *onto_name, const struct object_id *onto,
4916 const struct object_id *orig_head)
4917 {
4918 struct reset_working_tree_options ropts = {
4919 .oid = onto,
4920 .orig_head = orig_head,
4921 .flags = RESET_WORKING_TREE_DETACH |
4922 RESET_WORKING_TREE_UPDATE_HEAD |
4923 RESET_WORKING_TREE_UPDATE_ORIG_HEAD |
4924 RESET_WORKING_TREE_RUN_POST_CHECKOUT_HOOK,
4925 .head_msg = reflog_message(opts, "start", "checkout %s",
4926 onto_name),
4927 .default_reflog_action = sequencer_reflog_action(opts)
4928 };
4929 if (reset_working_tree(r, &ropts)) {
4930 apply_autostash(rebase_path_autostash());
4931 sequencer_remove_state(opts);
4932 return error(_("could not detach HEAD"));
4933 }
4934
4935 return 0;
4936 }
4937
4938 static int stopped_at_head(struct repository *r)
4939 {
4940 struct object_id head;
4941 struct commit *commit;
4942 struct commit_message message;
4943
4944 if (repo_get_oid(r, "HEAD", &head) ||
4945 !(commit = lookup_commit(r, &head)) ||
4946 repo_parse_commit(r, commit) || get_message(commit, &message))
4947 fprintf(stderr, _("Stopped at HEAD\n"));
4948 else {
4949 fprintf(stderr, _("Stopped at %s\n"), message.label);
4950 free_message(commit, &message);
4951 }
4952 return 0;
4953
4954 }
4955
4956 static int reread_todo_if_changed(struct repository *r,
4957 struct todo_list *todo_list,
4958 struct replay_opts *opts)
4959 {
4960 int offset;
4961 struct strbuf buf = STRBUF_INIT;
4962
4963 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4964 return -1;
4965 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4966 if (buf.len != todo_list->buf.len - offset ||
4967 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4968 /* Reread the todo file if it has changed. */
4969 todo_list_release(todo_list);
4970 if (read_populate_todo(r, todo_list, opts))
4971 return -1; /* message was printed */
4972 /* `current` will be incremented on return */
4973 todo_list->current = -1;
4974 }
4975 strbuf_release(&buf);
4976
4977 return 0;
4978 }
4979
4980 static const char rescheduled_advice[] =
4981 N_("Could not execute the todo command\n"
4982 "\n"
4983 " %.*s"
4984 "\n"
4985 "It has been rescheduled; To edit the command before continuing, please\n"
4986 "edit the todo list first:\n"
4987 "\n"
4988 " git rebase --edit-todo\n"
4989 " git rebase --continue\n");
4990
4991 static int pick_one_commit(struct repository *r,
4992 struct todo_list *todo_list,
4993 struct replay_opts *opts,
4994 int *check_todo, int* reschedule)
4995 {
4996 enum pick_result pick_res;
4997 struct todo_item *item = todo_list->items + todo_list->current;
4998 const char *arg = todo_item_get_arg(todo_list, item);
4999
5000 pick_res = do_pick_commit(r, item, opts, is_final_fixup(todo_list),
Showing first 5,000 of 6,997 lines. View raw