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 /* Does the current fixup chain contain a "fixup -c" command? */
1930 static int seen_fixup_edit_msg(struct replay_ctx *ctx)
1931 {
1932 return starts_with(ctx->current_fixups.buf, "fixup -c") ||
1933 strstr(ctx->current_fixups.buf, "\nfixup -c");
1934 }
1935
1936 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1937 {
1938 strbuf_setlen(buf1, strlen(comment_line_str) + 1);
1939 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1940 strbuf_addch(buf1, '\n');
1941 strbuf_setlen(buf2, strlen(comment_line_str) + 1);
1942 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1943 strbuf_addch(buf2, '\n');
1944 }
1945
1946 /*
1947 * Comment out any un-commented commit messages, updating the message comments
1948 * to say they will be skipped but do not comment out the empty lines that
1949 * surround commit messages and their comments.
1950 */
1951 static void update_squash_message_for_fixup(struct strbuf *msg)
1952 {
1953 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1954 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1955 const char *s, *start;
1956 char *orig_msg;
1957 size_t orig_msg_len;
1958 int i = 1;
1959
1960 strbuf_add_commented_lines(&buf1, _(first_commit_msg_str),
1961 strlen(_(first_commit_msg_str)),
1962 comment_line_str);
1963 strbuf_add_commented_lines(&buf2, _(skip_first_commit_msg_str),
1964 strlen(_(skip_first_commit_msg_str)),
1965 comment_line_str);
1966 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1967 while (s) {
1968 const char *next;
1969 size_t off;
1970 if (skip_prefix(s, buf1.buf, &next)) {
1971 /*
1972 * Copy the last message, preserving the blank line
1973 * preceding the current line
1974 */
1975 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1976 copy_lines(msg, start, s - start - off);
1977 if (off)
1978 strbuf_addch(msg, '\n');
1979 /*
1980 * The next message needs to be commented out but the
1981 * message header is already commented out so just copy
1982 * it and the blank line that follows it.
1983 */
1984 strbuf_addbuf(msg, &buf2);
1985 if (*next == '\n')
1986 strbuf_addch(msg, *next++);
1987 start = s = next;
1988 copy_lines = add_commented_lines;
1989 update_comment_bufs(&buf1, &buf2, ++i);
1990 } else if (skip_prefix(s, buf2.buf, &next)) {
1991 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1992 copy_lines(msg, start, s - start - off);
1993 start = s - off;
1994 s = next;
1995 copy_lines = strbuf_add;
1996 update_comment_bufs(&buf1, &buf2, ++i);
1997 } else {
1998 s = strchr(s, '\n');
1999 if (s)
2000 s++;
2001 }
2002 }
2003 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
2004 free(orig_msg);
2005 strbuf_release(&buf1);
2006 strbuf_release(&buf2);
2007 }
2008
2009 static int append_squash_message(struct strbuf *buf, const char *body,
2010 enum todo_command command, struct replay_opts *opts,
2011 unsigned flag)
2012 {
2013 struct replay_ctx *ctx = opts->ctx;
2014 const char *fixup_msg;
2015 size_t commented_len = 0, fixup_off;
2016 /*
2017 * amend is non-interactive and not normally used with fixup!
2018 * or squash! commits, so only comment out those subjects when
2019 * squashing commit messages.
2020 */
2021 if (starts_with(body, "amend!") ||
2022 ((command == TODO_SQUASH || seen_squash(ctx)) &&
2023 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
2024 commented_len = commit_subject_length(body);
2025
2026 strbuf_addf(buf, "\n%s ", comment_line_str);
2027 strbuf_addf(buf, _(nth_commit_msg_fmt),
2028 ++ctx->current_fixup_count + 1);
2029 strbuf_addstr(buf, "\n\n");
2030 strbuf_add_commented_lines(buf, body, commented_len, comment_line_str);
2031 /* buf->buf may be reallocated so store an offset into the buffer */
2032 fixup_off = buf->len;
2033 strbuf_addstr(buf, body + commented_len);
2034
2035 /* fixup -C after squash behaves like squash */
2036 if (is_fixup_flag(command, flag) && !seen_squash(ctx)) {
2037 /*
2038 * We're replacing the commit message so we need to
2039 * append any trailers if the user requested
2040 * '--signoff' or '--trailer'.
2041 */
2042 if (opts->signoff)
2043 append_signoff(buf, 0, 0);
2044
2045 if (opts->trailer_args.nr)
2046 amend_strbuf_with_trailers(buf, &opts->trailer_args);
2047
2048 if ((command == TODO_FIXUP) &&
2049 (flag & TODO_REPLACE_FIXUP_MSG) &&
2050 (file_exists(rebase_path_fixup_msg()) ||
2051 !file_exists(rebase_path_squash_msg()))) {
2052 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
2053 if (write_message(fixup_msg, strlen(fixup_msg),
2054 rebase_path_fixup_msg(), 0) < 0)
2055 return error(_("cannot write '%s'"),
2056 rebase_path_fixup_msg());
2057 } else {
2058 unlink(rebase_path_fixup_msg());
2059 }
2060 } else {
2061 unlink(rebase_path_fixup_msg());
2062 }
2063
2064 return 0;
2065 }
2066
2067 static int update_squash_messages(struct repository *r,
2068 enum todo_command command,
2069 struct commit *commit,
2070 struct replay_opts *opts,
2071 unsigned flag)
2072 {
2073 struct replay_ctx *ctx = opts->ctx;
2074 struct strbuf buf = STRBUF_INIT;
2075 int res = 0;
2076 const char *message, *body;
2077 const char *encoding = get_commit_output_encoding();
2078
2079 if (!is_fixup(command))
2080 BUG("not a FIXUP or SQUASH %d", command);
2081
2082 if (ctx->current_fixup_count > 0) {
2083 struct strbuf header = STRBUF_INIT;
2084 char *eol;
2085
2086 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
2087 return error(_("could not read '%s'"),
2088 rebase_path_squash_msg());
2089
2090 eol = !starts_with(buf.buf, comment_line_str) ?
2091 buf.buf : strchrnul(buf.buf, '\n');
2092
2093 strbuf_addf(&header, "%s ", comment_line_str);
2094 strbuf_addf(&header, _(combined_commit_msg_fmt),
2095 ctx->current_fixup_count + 2);
2096 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2097 strbuf_release(&header);
2098 if (is_fixup_flag(command, flag) && !seen_squash(ctx))
2099 update_squash_message_for_fixup(&buf);
2100 } else {
2101 struct object_id head;
2102 struct commit *head_commit;
2103 const char *head_message, *body;
2104
2105 if (repo_get_oid(r, "HEAD", &head))
2106 return error(_("need a HEAD to fixup"));
2107 if (!(head_commit = lookup_commit_reference(r, &head)))
2108 return error(_("could not read HEAD"));
2109 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2110 encoding)))
2111 return error(_("could not read HEAD's commit message"));
2112
2113 find_commit_subject(head_message, &body);
2114 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2115 rebase_path_fixup_msg(), 0) < 0) {
2116 repo_unuse_commit_buffer(r, head_commit, head_message);
2117 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2118 }
2119 strbuf_addf(&buf, "%s ", comment_line_str);
2120 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2121 strbuf_addf(&buf, "\n%s ", comment_line_str);
2122 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2123 _(skip_first_commit_msg_str) :
2124 _(first_commit_msg_str));
2125 strbuf_addstr(&buf, "\n\n");
2126 if (is_fixup_flag(command, flag))
2127 strbuf_add_commented_lines(&buf, body, strlen(body),
2128 comment_line_str);
2129 else
2130 strbuf_addstr(&buf, body);
2131
2132 repo_unuse_commit_buffer(r, head_commit, head_message);
2133 }
2134
2135 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2136 return error(_("could not read commit message of %s"),
2137 oid_to_hex(&commit->object.oid));
2138 find_commit_subject(message, &body);
2139
2140 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2141 res = append_squash_message(&buf, body, command, opts, flag);
2142 } else if (command == TODO_FIXUP) {
2143 strbuf_addf(&buf, "\n%s ", comment_line_str);
2144 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2145 ++ctx->current_fixup_count + 1);
2146 strbuf_addstr(&buf, "\n\n");
2147 strbuf_add_commented_lines(&buf, body, strlen(body),
2148 comment_line_str);
2149 }
2150 repo_unuse_commit_buffer(r, commit, message);
2151
2152 if (!res)
2153 res = write_message(buf.buf, buf.len, rebase_path_squash_msg(),
2154 0);
2155 strbuf_release(&buf);
2156
2157 if (!res) {
2158 const char *fixup_flag = "";
2159
2160 if (is_fixup_flag(command, flag) && (flag & TODO_EDIT_FIXUP_MSG))
2161 fixup_flag = " -c";
2162
2163 strbuf_addf(&ctx->current_fixups, "%s%s%s %s",
2164 ctx->current_fixups.len ? "\n" : "",
2165 command_to_string(command), fixup_flag,
2166 oid_to_hex(&commit->object.oid));
2167 res = write_message(ctx->current_fixups.buf,
2168 ctx->current_fixups.len,
2169 rebase_path_current_fixups(), 0);
2170 }
2171
2172 return res;
2173 }
2174
2175 static void flush_rewritten_pending(void)
2176 {
2177 struct strbuf buf = STRBUF_INIT;
2178 struct object_id newoid;
2179 FILE *out;
2180
2181 if (strbuf_read_file(&buf, rebase_path_rewritten_pending(), (GIT_MAX_HEXSZ + 1) * 2) > 0 &&
2182 !repo_get_oid(the_repository, "HEAD", &newoid) &&
2183 (out = fopen_or_warn(rebase_path_rewritten_list(), "a"))) {
2184 char *bol = buf.buf, *eol;
2185
2186 while (*bol) {
2187 eol = strchrnul(bol, '\n');
2188 fprintf(out, "%.*s %s\n", (int)(eol - bol),
2189 bol, oid_to_hex(&newoid));
2190 if (!*eol)
2191 break;
2192 bol = eol + 1;
2193 }
2194 fclose(out);
2195 unlink(rebase_path_rewritten_pending());
2196 }
2197 strbuf_release(&buf);
2198 }
2199
2200 static void record_in_rewritten(struct object_id *oid,
2201 enum todo_command next_command)
2202 {
2203 FILE *out = fopen_or_warn(rebase_path_rewritten_pending(), "a");
2204
2205 if (!out)
2206 return;
2207
2208 fprintf(out, "%s\n", oid_to_hex(oid));
2209 fclose(out);
2210
2211 if (!is_fixup(next_command))
2212 flush_rewritten_pending();
2213 }
2214
2215 static int should_edit(struct replay_opts *opts) {
2216 if (opts->edit < 0)
2217 /*
2218 * Note that we only handle the case of non-conflicted
2219 * commits; continue_single_pick() handles the conflicted
2220 * commits itself instead of calling this function.
2221 */
2222 return (opts->action == REPLAY_REVERT && isatty(0)) ? 1 : 0;
2223 return opts->edit;
2224 }
2225
2226 static void refer_to_commit(struct repository *r, struct strbuf *msgbuf,
2227 const struct commit *commit,
2228 bool use_commit_reference)
2229 {
2230 if (use_commit_reference) {
2231 struct pretty_print_context ctx = {
2232 .abbrev = DEFAULT_ABBREV,
2233 .date_mode.type = DATE_SHORT,
2234 };
2235 repo_format_commit_message(r, commit,
2236 "%h (%s, %ad)", msgbuf, &ctx);
2237 } else {
2238 strbuf_add_oid_hex(msgbuf, &commit->object.oid);
2239 }
2240 }
2241
2242 static const char *sequencer_reflog_action(struct replay_opts *opts)
2243 {
2244 if (!opts->reflog_action) {
2245 opts->reflog_action = getenv(GIT_REFLOG_ACTION);
2246 opts->reflog_action =
2247 xstrdup(opts->reflog_action ? opts->reflog_action
2248 : action_name(opts));
2249 }
2250
2251 return opts->reflog_action;
2252 }
2253
2254 __attribute__((format (printf, 3, 4)))
2255 static const char *reflog_message(struct replay_opts *opts,
2256 const char *sub_action, const char *fmt, ...)
2257 {
2258 va_list ap;
2259 static struct strbuf buf = STRBUF_INIT;
2260
2261 va_start(ap, fmt);
2262 strbuf_reset(&buf);
2263 strbuf_addstr(&buf, sequencer_reflog_action(opts));
2264 if (sub_action)
2265 strbuf_addf(&buf, " (%s)", sub_action);
2266 if (fmt) {
2267 strbuf_addstr(&buf, ": ");
2268 strbuf_vaddf(&buf, fmt, ap);
2269 }
2270 va_end(ap);
2271
2272 return buf.buf;
2273 }
2274
2275 enum pick_result {
2276 PICK_RESULT_ERROR = -1,
2277 PICK_RESULT_OK,
2278 PICK_RESULT_CONFLICTS,
2279 PICK_RESULT_DROPPED,
2280 };
2281
2282 static enum pick_result do_pick_commit(struct repository *r,
2283 struct todo_item *item,
2284 struct replay_opts *opts,
2285 int final_fixup, int *check_todo)
2286 {
2287 struct replay_ctx *ctx = opts->ctx;
2288 unsigned int flags = should_edit(opts) ? EDIT_MSG : 0;
2289 const char *msg_file = should_edit(opts) ? NULL : git_path_merge_msg(r);
2290 struct object_id head;
2291 struct commit *base, *next, *parent;
2292 const char *base_label, *next_label, *reflog_action;
2293 char *author = NULL;
2294 struct commit_message msg = { NULL, NULL, NULL, NULL };
2295 int res, unborn = 0, reword = 0, allow, drop_commit = 0;
2296 enum todo_command command = item->command;
2297 struct commit *commit = item->commit;
2298
2299 if (is_rebase_i(opts))
2300 reflog_action = reflog_message(
2301 opts, command_to_string(item->command), NULL);
2302 else
2303 reflog_action = sequencer_reflog_action(opts);
2304
2305 if (opts->no_commit) {
2306 /*
2307 * We do not intend to commit immediately. We just want to
2308 * merge the differences in, so let's compute the tree
2309 * that represents the "current" state for the merge machinery
2310 * to work on.
2311 */
2312 if (write_index_as_tree(&head, r->index, r->index_file, 0, NULL))
2313 return error(_("your index file is unmerged."));
2314 } else {
2315 unborn = repo_get_oid(r, "HEAD", &head);
2316 /* Do we want to generate a root commit? */
2317 if (is_pick_or_similar(command) && opts->have_squash_onto &&
2318 oideq(&head, &opts->squash_onto)) {
2319 if (is_fixup(command))
2320 return error(_("cannot fixup root commit"));
2321 flags |= CREATE_ROOT_COMMIT;
2322 unborn = 1;
2323 } else if (unborn)
2324 oidcpy(&head, the_hash_algo->empty_tree);
2325 if (index_differs_from(r, unborn ? empty_tree_oid_hex(the_repository->hash_algo) : "HEAD",
2326 NULL, 0))
2327 return error_dirty_index(r, opts);
2328 }
2329 discard_index(r->index);
2330
2331 if (!commit->parents)
2332 parent = NULL;
2333 else if (commit->parents->next) {
2334 /* Reverting or cherry-picking a merge commit */
2335 int cnt;
2336 struct commit_list *p;
2337
2338 if (!opts->mainline)
2339 return error(_("commit %s is a merge but no -m option was given."),
2340 oid_to_hex(&commit->object.oid));
2341
2342 for (cnt = 1, p = commit->parents;
2343 cnt != opts->mainline && p;
2344 cnt++)
2345 p = p->next;
2346 if (cnt != opts->mainline || !p)
2347 return error(_("commit %s does not have parent %d"),
2348 oid_to_hex(&commit->object.oid), opts->mainline);
2349 parent = p->item;
2350 } else if (1 < opts->mainline)
2351 /*
2352 * Non-first parent explicitly specified as mainline for
2353 * non-merge commit
2354 */
2355 return error(_("commit %s does not have parent %d"),
2356 oid_to_hex(&commit->object.oid), opts->mainline);
2357 else
2358 parent = commit->parents->item;
2359
2360 if (get_message(commit, &msg) != 0)
2361 return error(_("cannot get commit message for %s"),
2362 oid_to_hex(&commit->object.oid));
2363
2364 if (opts->allow_ff && !is_fixup(command) &&
2365 ((parent && oideq(&parent->object.oid, &head)) ||
2366 (!parent && unborn))) {
2367 if (is_rebase_i(opts))
2368 write_author_script(msg.message);
2369 res = fast_forward_to(r, &commit->object.oid, &head, unborn,
2370 opts);
2371 if (res || command != TODO_REWORD)
2372 goto leave;
2373 reword = 1;
2374 msg_file = NULL;
2375 goto fast_forward_edit;
2376 }
2377 if (parent && repo_parse_commit(r, parent) < 0)
2378 /* TRANSLATORS: The first %s will be a "todo" command like
2379 "revert" or "pick", the second %s a SHA1. */
2380 return error(_("%s: cannot parse parent commit %s"),
2381 command_to_string(command),
2382 oid_to_hex(&parent->object.oid));
2383
2384 /*
2385 * "commit" is an existing commit. We would want to apply
2386 * the difference it introduces since its first parent "prev"
2387 * on top of the current HEAD if we are cherry-pick. Or the
2388 * reverse of it if we are revert.
2389 */
2390
2391 if (command == TODO_REVERT) {
2392 base = commit;
2393 base_label = msg.label;
2394 next = parent;
2395 next_label = msg.parent_label;
2396 sequencer_format_revert_message(r, msg.subject, commit,
2397 parent,
2398 opts->commit_use_reference,
2399 &ctx->message);
2400 } else {
2401 const char *p;
2402
2403 base = parent;
2404 base_label = msg.parent_label;
2405 next = commit;
2406 next_label = msg.label;
2407
2408 /* Append the commit log message to ctx->message. */
2409 if (find_commit_subject(msg.message, &p))
2410 strbuf_addstr(&ctx->message, p);
2411
2412 if (opts->record_origin) {
2413 strbuf_complete_line(&ctx->message);
2414 if (!has_conforming_footer(&ctx->message, NULL, 0))
2415 strbuf_addch(&ctx->message, '\n');
2416 strbuf_addstr(&ctx->message, cherry_picked_prefix);
2417 strbuf_add_oid_hex(&ctx->message, &commit->object.oid);
2418 strbuf_addstr(&ctx->message, ")\n");
2419 }
2420 if (!is_fixup(command))
2421 author = get_author(msg.message);
2422 }
2423 ctx->have_message = 1;
2424
2425 if (command == TODO_REWORD)
2426 reword = 1;
2427 else if (is_fixup(command)) {
2428 if (update_squash_messages(r, command, commit,
2429 opts, item->flags)) {
2430 res = -1;
2431 goto leave;
2432 }
2433 flags |= AMEND_MSG;
2434 if (!final_fixup)
2435 msg_file = rebase_path_squash_msg();
2436 else if (file_exists(rebase_path_fixup_msg())) {
2437 msg_file = rebase_path_fixup_msg();
2438 } else {
2439 const char *dest = git_path_squash_msg(r);
2440 unlink(dest);
2441 if (copy_file(r, dest, rebase_path_squash_msg(), 0666)) {
2442 res = error(_("could not copy '%s' to '%s'"),
2443 rebase_path_squash_msg(), dest);
2444 goto leave;
2445 }
2446 unlink(git_path_merge_msg(r));
2447 msg_file = dest;
2448 flags |= EDIT_MSG;
2449 }
2450 }
2451
2452 if (opts->signoff && !is_fixup(command))
2453 append_signoff(&ctx->message, 0, 0);
2454
2455 if (opts->trailer_args.nr && !is_fixup(command))
2456 amend_strbuf_with_trailers(&ctx->message, &opts->trailer_args);
2457
2458 if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
2459 res = -1;
2460 else if (!opts->strategy ||
2461 !strcmp(opts->strategy, "recursive") ||
2462 !strcmp(opts->strategy, "ort") ||
2463 command == TODO_REVERT) {
2464 res = do_recursive_merge(r, base, next, base_label, next_label,
2465 &head, &ctx->message, opts);
2466 if (res < 0)
2467 goto leave;
2468
2469 res |= write_message(ctx->message.buf, ctx->message.len,
2470 git_path_merge_msg(r), 0);
2471 } else {
2472 struct commit_list *common = NULL;
2473 struct commit_list *remotes = NULL;
2474
2475 if (write_message(ctx->message.buf, ctx->message.len,
2476 git_path_merge_msg(r), 0)) {
2477 res = -1;
2478 goto leave;
2479 }
2480
2481 commit_list_insert(base, &common);
2482 commit_list_insert(next, &remotes);
2483 res = try_merge_command(r, opts->strategy,
2484 opts->xopts.nr, opts->xopts.v,
2485 common, oid_to_hex(&head), remotes);
2486 /*
2487 * If there were conflicts, try_merge_command() returns 1,
2488 * any other no-zero return code means that either the merge
2489 * command could not be run, or it failed to merge.
2490 */
2491 if (res && res != 1)
2492 res = -1;
2493
2494 commit_list_free(common);
2495 commit_list_free(remotes);
2496 }
2497
2498 /*
2499 * If the merge was clean or if it failed due to conflict, we write
2500 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use.
2501 * However, if the merge did not even start, then we don't want to
2502 * write it at all.
2503 */
2504 if ((command == TODO_PICK || command == TODO_REWORD ||
2505 command == TODO_EDIT) && !opts->no_commit &&
2506 (res == 0 || res == 1) &&
2507 refs_update_ref(get_main_ref_store(the_repository), NULL, "CHERRY_PICK_HEAD", &commit->object.oid, NULL,
2508 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2509 res = -1;
2510 if (command == TODO_REVERT && ((opts->no_commit && res == 0) || res == 1) &&
2511 refs_update_ref(get_main_ref_store(the_repository), NULL, "REVERT_HEAD", &commit->object.oid, NULL,
2512 REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
2513 res = -1;
2514
2515 if (res) {
2516 error(command == TODO_REVERT
2517 ? _("could not revert %s... %s")
2518 : _("could not apply %s... %s"),
2519 short_commit_name(r, commit), msg.subject);
2520 print_advice(r, res == 1, opts);
2521 repo_rerere(r, opts->allow_rerere_auto);
2522 goto leave;
2523 }
2524
2525 allow = allow_empty(r, opts, commit);
2526 if (allow < 0) {
2527 res = allow;
2528 goto leave;
2529 } else if (allow == 1) {
2530 flags |= ALLOW_EMPTY;
2531 } else if (allow == 2) {
2532 drop_commit = 1;
2533 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
2534 NULL, REF_NO_DEREF);
2535 unlink(git_path_merge_msg(r));
2536 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
2537 NULL, REF_NO_DEREF);
2538 fprintf(stderr,
2539 _("dropping %s %s -- patch contents already upstream\n"),
2540 oid_to_hex(&commit->object.oid), msg.subject);
2541 } /* else allow == 0 and there's nothing special to do */
2542 if (!opts->no_commit && !drop_commit) {
2543 if (author || command == TODO_REVERT || (flags & AMEND_MSG))
2544 res = do_commit(r, msg_file, author, reflog_action,
2545 opts, flags,
2546 commit? &commit->object.oid : NULL);
2547 else
2548 res = error(_("unable to parse commit author"));
2549 *check_todo = !!(flags & EDIT_MSG);
2550 if (!res && reword) {
2551 fast_forward_edit:
2552 /*
2553 * To reword we amend the commit we just
2554 * picked or fast-forwarded. As the commit has
2555 * already been picked we want to use the same
2556 * set of commit flags regardless of how we
2557 * got here.
2558 */
2559 flags = EDIT_MSG | VERIFY_MSG | AMEND_MSG | ALLOW_EMPTY;
2560 res = run_git_commit(NULL, reflog_action, opts, flags);
2561 *check_todo = 1;
2562 }
2563 /*
2564 * If "git commit" failed to run then res == -1, but we don't
2565 * want reschedule the last command because the picking the
2566 * commit was successful.
2567 */
2568 res = !!res;
2569 }
2570
2571
2572 if (!res && final_fixup) {
2573 unlink(rebase_path_fixup_msg());
2574 unlink(rebase_path_squash_msg());
2575 unlink(rebase_path_current_fixups());
2576 strbuf_reset(&ctx->current_fixups);
2577 ctx->current_fixup_count = 0;
2578 }
2579
2580 leave:
2581 free_message(commit, &msg);
2582 free(author);
2583 update_abort_safety_file();
2584
2585 if (res < 0)
2586 return PICK_RESULT_ERROR;
2587 else if (res > 0)
2588 return PICK_RESULT_CONFLICTS;
2589 else if (drop_commit)
2590 return PICK_RESULT_DROPPED;
2591 else
2592 return PICK_RESULT_OK;
2593 }
2594
2595 static int prepare_revs(struct replay_opts *opts)
2596 {
2597 /*
2598 * picking (but not reverting) ranges (but not individual revisions)
2599 * should be done in reverse
2600 */
2601 if (opts->action == REPLAY_PICK && !opts->revs->no_walk)
2602 opts->revs->reverse ^= 1;
2603
2604 if (prepare_revision_walk(opts->revs))
2605 return error(_("revision walk setup failed"));
2606
2607 return 0;
2608 }
2609
2610 static int read_and_refresh_cache(struct repository *r,
2611 struct replay_opts *opts)
2612 {
2613 struct lock_file index_lock = LOCK_INIT;
2614 int index_fd = repo_hold_locked_index(r, &index_lock, 0);
2615 if (repo_read_index(r) < 0) {
2616 rollback_lock_file(&index_lock);
2617 return error(_("git %s: failed to read the index"),
2618 action_name(opts));
2619 }
2620 refresh_index(r->index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);
2621
2622 if (index_fd >= 0) {
2623 if (write_locked_index(r->index, &index_lock,
2624 COMMIT_LOCK | SKIP_IF_UNCHANGED)) {
2625 return error(_("git %s: failed to refresh the index"),
2626 action_name(opts));
2627 }
2628 }
2629
2630 /*
2631 * If we are resolving merges in any way other than "ort", then
2632 * expand the sparse index.
2633 */
2634 if (opts->strategy && strcmp(opts->strategy, "ort"))
2635 ensure_full_index(r->index);
2636 return 0;
2637 }
2638
2639 void todo_list_release(struct todo_list *todo_list)
2640 {
2641 strbuf_release(&todo_list->buf);
2642 FREE_AND_NULL(todo_list->items);
2643 todo_list->nr = todo_list->alloc = 0;
2644 }
2645
2646 static struct todo_item *append_new_todo(struct todo_list *todo_list)
2647 {
2648 ALLOC_GROW(todo_list->items, todo_list->nr + 1, todo_list->alloc);
2649 return todo_list->items + todo_list->nr++;
2650 }
2651
2652 const char *todo_item_get_arg(struct todo_list *todo_list,
2653 struct todo_item *item)
2654 {
2655 return todo_list->buf.buf + item->arg_offset;
2656 }
2657
2658 static int is_command(enum todo_command command, const char **bol)
2659 {
2660 const char *str = todo_command_info[command].str;
2661 const char nick = todo_command_info[command].c;
2662 const char *p = *bol;
2663
2664 if ((skip_prefix(p, str, &p) || (nick && *p++ == nick)) &&
2665 (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r' || !*p)) {
2666 *bol = p;
2667 return 1;
2668 }
2669 return 0;
2670 }
2671
2672 bool sequencer_parse_todo_command(const char **p, enum todo_command *cmd)
2673 {
2674 const char *s = *p;
2675
2676 for (int i = 0; i < TODO_COMMENT; i++)
2677 if (is_command(i, p)) {
2678 *cmd = i;
2679 return true;
2680 }
2681
2682 if (starts_with(s, comment_line_str)) {
2683 *cmd = TODO_COMMENT;
2684 return true;
2685 } else if (s[0] == '\n' || (s[0] == '\r' && s[1] == '\n') || !s[0]) {
2686 *cmd = TODO_COMMENT;
2687 return true;
2688 }
2689
2690 return false;
2691 }
2692
2693 static int check_label_or_ref_arg(enum todo_command command, const char *arg)
2694 {
2695 switch (command) {
2696 case TODO_LABEL:
2697 /*
2698 * '#' is not a valid label as the merge command uses it to
2699 * separate merge parents from the commit subject.
2700 */
2701 if (!strcmp(arg, "#") ||
2702 check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2703 return error(_("'%s' is not a valid label"), arg);
2704 break;
2705
2706 case TODO_UPDATE_REF:
2707 if (check_refname_format(arg, REFNAME_ALLOW_ONELEVEL))
2708 return error(_("'%s' is not a valid refname"), arg);
2709 if (check_refname_format(arg, 0))
2710 return error(_("update-ref requires a fully qualified "
2711 "refname e.g. refs/heads/%s"), arg);
2712 break;
2713
2714 default:
2715 BUG("unexpected todo_command");
2716 }
2717
2718 return 0;
2719 }
2720
2721 static int check_merge_commit_insn(enum todo_command command)
2722 {
2723 switch(command) {
2724 case TODO_PICK:
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: 'pick' and 'merge -C' should not be
2730 * translated.
2731 */
2732 "'pick' does not take a merge commit. If you wanted to\n"
2733 "replay the merge, use 'merge -C' on the commit."));
2734 return -1;
2735
2736 case TODO_REWORD:
2737 error(_("'%s' does not accept merge commits"),
2738 todo_command_info[command].str);
2739 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2740 /*
2741 * TRANSLATORS: 'reword' and 'merge -c' should not be
2742 * translated.
2743 */
2744 "'reword' does not take a merge commit. If you wanted to\n"
2745 "replay the merge and reword the commit message, use\n"
2746 "'merge -c' on the commit"));
2747 return -1;
2748
2749 case TODO_EDIT:
2750 error(_("'%s' does not accept merge commits"),
2751 todo_command_info[command].str);
2752 advise_if_enabled(ADVICE_REBASE_TODO_ERROR, _(
2753 /*
2754 * TRANSLATORS: 'edit', 'merge -C' and 'break' should
2755 * not be translated.
2756 */
2757 "'edit' does not take a merge commit. If you wanted to\n"
2758 "replay the merge, use 'merge -C' on the commit, and then\n"
2759 "'break' to give the control back to you so that you can\n"
2760 "do 'git commit --amend && git rebase --continue'."));
2761 return -1;
2762
2763 case TODO_FIXUP:
2764 case TODO_SQUASH:
2765 return error(_("cannot squash merge commit into another commit"));
2766
2767 case TODO_MERGE:
2768 case TODO_DROP:
2769 return 0;
2770
2771 default:
2772 BUG("unexpected todo_command");
2773 }
2774 }
2775
2776 static int parse_insn_line(struct repository *r, struct replay_opts *opts,
2777 struct todo_item *item, const char *buf,
2778 const char *bol, char *eol)
2779 {
2780 struct object_id commit_oid;
2781 char *end_of_object_name;
2782 int saved, status, padding;
2783
2784 item->flags = 0;
2785
2786 /* left-trim */
2787 bol += strspn(bol, " \t");
2788
2789 if (!sequencer_parse_todo_command(&bol, &item->command))
2790 return error(_("invalid command '%.*s'"),
2791 (int)strcspn(bol, " \t\r\n"), bol);
2792
2793 if (item->command == TODO_COMMENT) {
2794 item->commit = NULL;
2795 item->arg_offset = bol - buf;
2796 item->arg_len = eol - bol;
2797 return 0;
2798 }
2799
2800 /* Eat up extra spaces/ tabs before object name */
2801 padding = strspn(bol, " \t");
2802 bol += padding;
2803
2804 if (item->command == TODO_NOOP || item->command == TODO_BREAK) {
2805 if (bol != eol)
2806 return error(_("%s does not accept arguments: '%s'"),
2807 command_to_string(item->command), bol);
2808 item->commit = NULL;
2809 item->arg_offset = bol - buf;
2810 item->arg_len = eol - bol;
2811 return 0;
2812 }
2813
2814 if (!padding)
2815 return error(_("missing arguments for %s"),
2816 command_to_string(item->command));
2817
2818 if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
2819 item->command == TODO_RESET || item->command == TODO_UPDATE_REF) {
2820 int ret = 0;
2821
2822 item->commit = NULL;
2823 item->arg_offset = bol - buf;
2824 item->arg_len = (int)(eol - bol);
2825 if (item->command == TODO_LABEL ||
2826 item->command == TODO_UPDATE_REF) {
2827 saved = *eol;
2828 *eol = '\0';
2829 ret = check_label_or_ref_arg(item->command, bol);
2830 *eol = saved;
2831 }
2832 return ret;
2833 }
2834
2835 if (item->command == TODO_FIXUP) {
2836 if (skip_prefix(bol, "-C", &bol)) {
2837 bol += strspn(bol, " \t");
2838 item->flags |= TODO_REPLACE_FIXUP_MSG;
2839 } else if (skip_prefix(bol, "-c", &bol)) {
2840 bol += strspn(bol, " \t");
2841 item->flags |= TODO_EDIT_FIXUP_MSG;
2842 }
2843 }
2844
2845 if (item->command == TODO_MERGE) {
2846 if (skip_prefix(bol, "-C", &bol))
2847 bol += strspn(bol, " \t");
2848 else if (skip_prefix(bol, "-c", &bol)) {
2849 bol += strspn(bol, " \t");
2850 item->flags |= TODO_EDIT_MERGE_MSG;
2851 } else {
2852 item->flags |= TODO_EDIT_MERGE_MSG;
2853 item->commit = NULL;
2854 item->arg_offset = bol - buf;
2855 item->arg_len = (int)(eol - bol);
2856 return 0;
2857 }
2858 }
2859
2860 end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
2861 saved = *end_of_object_name;
2862 *end_of_object_name = '\0';
2863 status = repo_get_oid(r, bol, &commit_oid);
2864 if (status < 0)
2865 error(_("could not parse '%s'"), bol); /* return later */
2866 *end_of_object_name = saved;
2867
2868 bol = end_of_object_name + strspn(end_of_object_name, " \t");
2869 item->arg_offset = bol - buf;
2870 item->arg_len = (int)(eol - bol);
2871
2872 if (status < 0)
2873 return status;
2874
2875 item->commit = lookup_commit_reference(r, &commit_oid);
2876 if (!item->commit)
2877 return -1;
2878 if (is_rebase_i(opts) &&
2879 item->commit->parents && item->commit->parents->next)
2880 return check_merge_commit_insn(item->command);
2881 return 0;
2882 }
2883
2884 int sequencer_get_last_command(struct repository *r UNUSED, enum replay_action *action)
2885 {
2886 const char *todo_file, *bol;
2887 struct strbuf buf = STRBUF_INIT;
2888 int ret = 0;
2889
2890 todo_file = git_path_todo_file();
2891 if (strbuf_read_file(&buf, todo_file, 0) < 0) {
2892 if (errno == ENOENT || errno == ENOTDIR)
2893 return -1;
2894 else
2895 return error_errno("unable to open '%s'", todo_file);
2896 }
2897 bol = buf.buf + strspn(buf.buf, " \t\r\n");
2898 if (is_command(TODO_PICK, &bol) && (*bol == ' ' || *bol == '\t'))
2899 *action = REPLAY_PICK;
2900 else if (is_command(TODO_REVERT, &bol) &&
2901 (*bol == ' ' || *bol == '\t'))
2902 *action = REPLAY_REVERT;
2903 else
2904 ret = -1;
2905
2906 strbuf_release(&buf);
2907
2908 return ret;
2909 }
2910
2911 int todo_list_parse_insn_buffer(struct repository *r, struct replay_opts *opts,
2912 char *buf, struct todo_list *todo_list)
2913 {
2914 struct todo_item *item;
2915 char *p = buf, *next_p;
2916 int i, res = 0, fixup_okay = file_exists(rebase_path_done());
2917
2918 todo_list->current = todo_list->nr = todo_list->total_nr = 0;
2919
2920 for (i = 1; *p; i++, p = next_p) {
2921 char *eol = strchrnul(p, '\n');
2922
2923 next_p = *eol ? eol + 1 /* skip LF */ : eol;
2924
2925 if (p != eol && eol[-1] == '\r')
2926 eol--; /* strip Carriage Return */
2927
2928 item = append_new_todo(todo_list);
2929 item->offset_in_buf = p - todo_list->buf.buf;
2930 if (parse_insn_line(r, opts, item, buf, p, eol)) {
2931 res = error(_("invalid line %d: %.*s"),
2932 i, (int)(eol - p), p);
2933 item->command = TODO_COMMENT + 1;
2934 item->arg_offset = p - buf;
2935 item->arg_len = (int)(eol - p);
2936 item->commit = NULL;
2937 }
2938
2939 if (item->command != TODO_COMMENT)
2940 todo_list->total_nr++;
2941
2942 if (fixup_okay)
2943 ; /* do nothing */
2944 else if (is_fixup(item->command))
2945 res = error(_("cannot '%s' without a previous commit"),
2946 command_to_string(item->command));
2947 else if (!is_noop(item->command))
2948 fixup_okay = 1;
2949 }
2950
2951 return res;
2952 }
2953
2954 static int count_commands(struct todo_list *todo_list)
2955 {
2956 int count = 0, i;
2957
2958 for (i = 0; i < todo_list->nr; i++)
2959 if (todo_list->items[i].command != TODO_COMMENT)
2960 count++;
2961
2962 return count;
2963 }
2964
2965 static int get_item_line_offset(struct todo_list *todo_list, int index)
2966 {
2967 return index < todo_list->nr ?
2968 todo_list->items[index].offset_in_buf : todo_list->buf.len;
2969 }
2970
2971 static const char *get_item_line(struct todo_list *todo_list, int index)
2972 {
2973 return todo_list->buf.buf + get_item_line_offset(todo_list, index);
2974 }
2975
2976 static int get_item_line_length(struct todo_list *todo_list, int index)
2977 {
2978 return get_item_line_offset(todo_list, index + 1)
2979 - get_item_line_offset(todo_list, index);
2980 }
2981
2982 static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
2983 {
2984 int fd;
2985 ssize_t len;
2986
2987 fd = open(path, O_RDONLY);
2988 if (fd < 0)
2989 return error_errno(_("could not open '%s'"), path);
2990 len = strbuf_read(sb, fd, 0);
2991 close(fd);
2992 if (len < 0)
2993 return error(_("could not read '%s'."), path);
2994 return len;
2995 }
2996
2997 static int have_finished_the_last_pick(void)
2998 {
2999 struct strbuf buf = STRBUF_INIT;
3000 const char *eol;
3001 const char *todo_path = git_path_todo_file();
3002 int ret = 0;
3003
3004 if (strbuf_read_file(&buf, todo_path, 0) < 0) {
3005 if (errno == ENOENT) {
3006 return 0;
3007 } else {
3008 error_errno("unable to open '%s'", todo_path);
3009 return 0;
3010 }
3011 }
3012 /* If there is only one line then we are done */
3013 eol = strchr(buf.buf, '\n');
3014 if (!eol || !eol[1])
3015 ret = 1;
3016
3017 strbuf_release(&buf);
3018
3019 return ret;
3020 }
3021
3022 void sequencer_post_commit_cleanup(struct repository *r, int verbose)
3023 {
3024 struct replay_opts opts = REPLAY_OPTS_INIT;
3025 int need_cleanup = 0;
3026
3027 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
3028 if (!refs_delete_ref(get_main_ref_store(r), "",
3029 "CHERRY_PICK_HEAD", NULL, REF_NO_DEREF) &&
3030 verbose)
3031 warning(_("cancelling a cherry picking in progress"));
3032 opts.action = REPLAY_PICK;
3033 need_cleanup = 1;
3034 }
3035
3036 if (refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3037 if (!refs_delete_ref(get_main_ref_store(r), "", "REVERT_HEAD",
3038 NULL, REF_NO_DEREF) &&
3039 verbose)
3040 warning(_("cancelling a revert in progress"));
3041 opts.action = REPLAY_REVERT;
3042 need_cleanup = 1;
3043 }
3044
3045 refs_delete_ref(get_main_ref_store(r), "", "AUTO_MERGE",
3046 NULL, REF_NO_DEREF);
3047
3048 if (!need_cleanup)
3049 goto out;
3050
3051 if (!have_finished_the_last_pick())
3052 goto out;
3053
3054 sequencer_remove_state(&opts);
3055 out:
3056 replay_opts_release(&opts);
3057 }
3058
3059 static void todo_list_write_total_nr(struct todo_list *todo_list)
3060 {
3061 FILE *f = fopen_or_warn(rebase_path_msgtotal(), "w");
3062
3063 if (f) {
3064 fprintf(f, "%d\n", todo_list->total_nr);
3065 fclose(f);
3066 }
3067 }
3068
3069 static int read_populate_todo(struct repository *r,
3070 struct todo_list *todo_list,
3071 struct replay_opts *opts)
3072 {
3073 const char *todo_file = get_todo_path(opts);
3074 int res;
3075
3076 strbuf_reset(&todo_list->buf);
3077 if (strbuf_read_file_or_whine(&todo_list->buf, todo_file) < 0)
3078 return -1;
3079
3080 res = todo_list_parse_insn_buffer(r, opts, todo_list->buf.buf, todo_list);
3081 if (res) {
3082 if (is_rebase_i(opts))
3083 return error(_("please fix this using "
3084 "'git rebase --edit-todo'."));
3085 return error(_("unusable instruction sheet: '%s'"), todo_file);
3086 }
3087
3088 if (!todo_list->nr &&
3089 (!is_rebase_i(opts) || !file_exists(rebase_path_done())))
3090 return error(_("no commits parsed."));
3091
3092 if (!is_rebase_i(opts)) {
3093 enum todo_command valid =
3094 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;
3095 int i;
3096
3097 for (i = 0; i < todo_list->nr; i++)
3098 if (valid == todo_list->items[i].command)
3099 continue;
3100 else if (valid == TODO_PICK)
3101 return error(_("cannot cherry-pick during a revert."));
3102 else
3103 return error(_("cannot revert during a cherry-pick."));
3104 }
3105
3106 if (is_rebase_i(opts)) {
3107 struct todo_list done = TODO_LIST_INIT;
3108
3109 if (strbuf_read_file(&done.buf, rebase_path_done(), 0) > 0 &&
3110 !todo_list_parse_insn_buffer(r, opts, done.buf.buf, &done))
3111 todo_list->done_nr = count_commands(&done);
3112 else
3113 todo_list->done_nr = 0;
3114
3115 todo_list->total_nr = todo_list->done_nr
3116 + count_commands(todo_list);
3117 todo_list_release(&done);
3118
3119 todo_list_write_total_nr(todo_list);
3120 }
3121
3122 return 0;
3123 }
3124
3125 static int git_config_string_dup(char **dest,
3126 const char *var, const char *value)
3127 {
3128 if (!value)
3129 return config_error_nonbool(var);
3130 free(*dest);
3131 *dest = xstrdup(value);
3132 return 0;
3133 }
3134
3135 static int populate_opts_cb(const char *key, const char *value,
3136 const struct config_context *ctx,
3137 void *data)
3138 {
3139 struct replay_opts *opts = data;
3140 int error_flag = 1;
3141
3142 if (!value)
3143 error_flag = 0;
3144 else if (!strcmp(key, "options.no-commit"))
3145 opts->no_commit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3146 else if (!strcmp(key, "options.edit"))
3147 opts->edit = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3148 else if (!strcmp(key, "options.allow-empty"))
3149 opts->allow_empty =
3150 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3151 else if (!strcmp(key, "options.allow-empty-message"))
3152 opts->allow_empty_message =
3153 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3154 else if (!strcmp(key, "options.drop-redundant-commits"))
3155 opts->drop_redundant_commits =
3156 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3157 else if (!strcmp(key, "options.keep-redundant-commits"))
3158 opts->keep_redundant_commits =
3159 git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3160 else if (!strcmp(key, "options.signoff"))
3161 opts->signoff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3162 else if (!strcmp(key, "options.record-origin"))
3163 opts->record_origin = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3164 else if (!strcmp(key, "options.allow-ff"))
3165 opts->allow_ff = git_config_bool_or_int(key, value, ctx->kvi, &error_flag);
3166 else if (!strcmp(key, "options.mainline"))
3167 opts->mainline = git_config_int(key, value, ctx->kvi);
3168 else if (!strcmp(key, "options.strategy"))
3169 git_config_string_dup(&opts->strategy, key, value);
3170 else if (!strcmp(key, "options.gpg-sign"))
3171 git_config_string_dup(&opts->gpg_sign, key, value);
3172 else if (!strcmp(key, "options.strategy-option")) {
3173 strvec_push(&opts->xopts, value);
3174 } else if (!strcmp(key, "options.allow-rerere-auto"))
3175 opts->allow_rerere_auto =
3176 git_config_bool_or_int(key, value, ctx->kvi, &error_flag) ?
3177 RERERE_AUTOUPDATE : RERERE_NOAUTOUPDATE;
3178 else if (!strcmp(key, "options.default-msg-cleanup")) {
3179 opts->explicit_cleanup = 1;
3180 opts->default_msg_cleanup = get_cleanup_mode(value, 1);
3181 } else
3182 return error(_("invalid key: %s"), key);
3183
3184 if (!error_flag)
3185 return error(_("invalid value for '%s': '%s'"), key, value);
3186
3187 return 0;
3188 }
3189
3190 static void parse_strategy_opts(struct replay_opts *opts, char *raw_opts)
3191 {
3192 int i;
3193 int count;
3194 const char **argv;
3195 char *strategy_opts_string = raw_opts;
3196
3197 if (*strategy_opts_string == ' ')
3198 strategy_opts_string++;
3199
3200 count = split_cmdline(strategy_opts_string, &argv);
3201 if (count < 0)
3202 BUG("could not split '%s': %s", strategy_opts_string,
3203 split_cmdline_strerror(count));
3204 for (i = 0; i < count; i++) {
3205 const char *arg = argv[i];
3206
3207 skip_prefix(arg, "--", &arg);
3208 strvec_push(&opts->xopts, arg);
3209 }
3210 free(argv);
3211 }
3212
3213 static void read_strategy_opts(struct replay_opts *opts, struct strbuf *buf)
3214 {
3215 strbuf_reset(buf);
3216 if (!read_oneliner(buf, rebase_path_strategy(), 0))
3217 return;
3218 opts->strategy = strbuf_detach(buf, NULL);
3219 if (!read_oneliner(buf, rebase_path_strategy_opts(), 0))
3220 return;
3221
3222 parse_strategy_opts(opts, buf->buf);
3223 }
3224
3225 static int read_trailers(struct replay_opts *opts, struct strbuf *buf)
3226 {
3227 ssize_t len;
3228
3229 strbuf_reset(buf);
3230 len = strbuf_read_file(buf, rebase_path_trailer(), 0);
3231 if (len > 0) {
3232 char *p = buf->buf, *nl;
3233
3234 trailer_config_init();
3235
3236 while ((nl = strchr(p, '\n'))) {
3237 *nl = '\0';
3238 if (!*p)
3239 return error(_("trailers file contains empty line"));
3240 strvec_push(&opts->trailer_args, p);
3241 p = nl + 1;
3242 }
3243 } else if (!len) {
3244 return error(_("trailers file is empty"));
3245 } else if (errno != ENOENT) {
3246 return error(_("cannot read trailers files"));
3247 }
3248
3249 return 0;
3250 }
3251
3252 static int read_populate_opts(struct replay_opts *opts)
3253 {
3254 struct replay_ctx *ctx = opts->ctx;
3255
3256 if (is_rebase_i(opts)) {
3257 struct strbuf buf = STRBUF_INIT;
3258 int ret = 0;
3259
3260 if (read_oneliner(&buf, rebase_path_gpg_sign_opt(),
3261 READ_ONELINER_SKIP_IF_EMPTY)) {
3262 if (!starts_with(buf.buf, "-S"))
3263 strbuf_reset(&buf);
3264 else {
3265 free(opts->gpg_sign);
3266 opts->gpg_sign = xstrdup(buf.buf + 2);
3267 }
3268 strbuf_reset(&buf);
3269 }
3270
3271 if (read_oneliner(&buf, rebase_path_allow_rerere_autoupdate(),
3272 READ_ONELINER_SKIP_IF_EMPTY)) {
3273 if (!strcmp(buf.buf, "--rerere-autoupdate"))
3274 opts->allow_rerere_auto = RERERE_AUTOUPDATE;
3275 else if (!strcmp(buf.buf, "--no-rerere-autoupdate"))
3276 opts->allow_rerere_auto = RERERE_NOAUTOUPDATE;
3277 strbuf_reset(&buf);
3278 }
3279
3280 if (file_exists(rebase_path_verbose()))
3281 opts->verbose = 1;
3282
3283 if (file_exists(rebase_path_quiet()))
3284 opts->quiet = 1;
3285
3286 if (file_exists(rebase_path_signoff())) {
3287 opts->allow_ff = 0;
3288 opts->signoff = 1;
3289 }
3290
3291 if (file_exists(rebase_path_cdate_is_adate())) {
3292 opts->allow_ff = 0;
3293 opts->committer_date_is_author_date = 1;
3294 }
3295
3296 if (file_exists(rebase_path_ignore_date())) {
3297 opts->allow_ff = 0;
3298 opts->ignore_date = 1;
3299 }
3300
3301 if (file_exists(rebase_path_reschedule_failed_exec()))
3302 opts->reschedule_failed_exec = 1;
3303 else if (file_exists(rebase_path_no_reschedule_failed_exec()))
3304 opts->reschedule_failed_exec = 0;
3305
3306 if (file_exists(rebase_path_drop_redundant_commits()))
3307 opts->drop_redundant_commits = 1;
3308
3309 if (file_exists(rebase_path_keep_redundant_commits()))
3310 opts->keep_redundant_commits = 1;
3311
3312 read_strategy_opts(opts, &buf);
3313
3314 if (read_trailers(opts, &buf)) {
3315 ret = -1;
3316 goto done_rebase_i;
3317 }
3318 strbuf_reset(&buf);
3319
3320 if (read_oneliner(&ctx->current_fixups,
3321 rebase_path_current_fixups(),
3322 READ_ONELINER_SKIP_IF_EMPTY)) {
3323 const char *p = ctx->current_fixups.buf;
3324 ctx->current_fixup_count = 1;
3325 while ((p = strchr(p, '\n'))) {
3326 /*
3327 * Older versions of git accidentally
3328 * inserted blank lines when a fixup
3329 * was skipped.
3330 */
3331 if (p[1] && p[1] != '\n')
3332 ctx->current_fixup_count++;
3333 p++;
3334 }
3335 }
3336
3337 if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
3338 if (repo_get_oid_committish(the_repository, buf.buf, &opts->squash_onto) < 0) {
3339 ret = error(_("unusable squash-onto"));
3340 goto done_rebase_i;
3341 }
3342 opts->have_squash_onto = 1;
3343 }
3344
3345 done_rebase_i:
3346 strbuf_release(&buf);
3347 return ret;
3348 }
3349
3350 if (!file_exists(git_path_opts_file()))
3351 return 0;
3352 /*
3353 * The function git_parse_source(), called from git_config_from_file(),
3354 * may die() in case of a syntactically incorrect file. We do not care
3355 * about this case, though, because we wrote that file ourselves, so we
3356 * are pretty certain that it is syntactically correct.
3357 */
3358 if (git_config_from_file(populate_opts_cb, git_path_opts_file(), opts) < 0)
3359 return error(_("malformed options sheet: '%s'"),
3360 git_path_opts_file());
3361 return 0;
3362 }
3363
3364 static void write_strategy_opts(struct replay_opts *opts)
3365 {
3366 struct strbuf buf = STRBUF_INIT;
3367
3368 /*
3369 * Quote strategy options so that they can be read correctly
3370 * by split_cmdline().
3371 */
3372 quote_cmdline(&buf, opts->xopts.v);
3373 write_file(rebase_path_strategy_opts(), "%s\n", buf.buf);
3374 strbuf_release(&buf);
3375 }
3376
3377 int write_basic_state(struct replay_opts *opts, const char *head_name,
3378 struct commit *onto, const struct object_id *orig_head)
3379 {
3380 if (head_name)
3381 write_file(rebase_path_head_name(), "%s\n", head_name);
3382 if (onto)
3383 write_file(rebase_path_onto(), "%s\n",
3384 oid_to_hex(&onto->object.oid));
3385 if (orig_head)
3386 write_file(rebase_path_orig_head(), "%s\n",
3387 oid_to_hex(orig_head));
3388
3389 if (opts->quiet)
3390 write_file(rebase_path_quiet(), "%s", "");
3391 if (opts->verbose)
3392 write_file(rebase_path_verbose(), "%s", "");
3393 if (opts->strategy)
3394 write_file(rebase_path_strategy(), "%s\n", opts->strategy);
3395 if (opts->xopts.nr > 0)
3396 write_strategy_opts(opts);
3397
3398 if (opts->allow_rerere_auto == RERERE_AUTOUPDATE)
3399 write_file(rebase_path_allow_rerere_autoupdate(), "--rerere-autoupdate\n");
3400 else if (opts->allow_rerere_auto == RERERE_NOAUTOUPDATE)
3401 write_file(rebase_path_allow_rerere_autoupdate(), "--no-rerere-autoupdate\n");
3402
3403 if (opts->gpg_sign)
3404 write_file(rebase_path_gpg_sign_opt(), "-S%s\n", opts->gpg_sign);
3405 if (opts->signoff)
3406 write_file(rebase_path_signoff(), "--signoff\n");
3407 if (opts->drop_redundant_commits)
3408 write_file(rebase_path_drop_redundant_commits(), "%s", "");
3409 if (opts->keep_redundant_commits)
3410 write_file(rebase_path_keep_redundant_commits(), "%s", "");
3411 if (opts->committer_date_is_author_date)
3412 write_file(rebase_path_cdate_is_adate(), "%s", "");
3413 if (opts->ignore_date)
3414 write_file(rebase_path_ignore_date(), "%s", "");
3415 if (opts->reschedule_failed_exec)
3416 write_file(rebase_path_reschedule_failed_exec(), "%s", "");
3417 else
3418 write_file(rebase_path_no_reschedule_failed_exec(), "%s", "");
3419 if (opts->trailer_args.nr) {
3420 struct strbuf buf = STRBUF_INIT;
3421
3422 for (size_t i = 0; i < opts->trailer_args.nr; i++)
3423 strbuf_addf(&buf, "%s\n", opts->trailer_args.v[i]);
3424 write_file(rebase_path_trailer(), "%s", buf.buf);
3425 strbuf_release(&buf);
3426 }
3427
3428 return 0;
3429 }
3430
3431 static int walk_revs_populate_todo(struct todo_list *todo_list,
3432 struct replay_opts *opts)
3433 {
3434 enum todo_command command = opts->action == REPLAY_PICK ?
3435 TODO_PICK : TODO_REVERT;
3436 const char *command_string = todo_command_info[command].str;
3437 const char *encoding;
3438 struct commit *commit;
3439
3440 if (prepare_revs(opts))
3441 return -1;
3442
3443 encoding = get_log_output_encoding();
3444
3445 while ((commit = get_revision(opts->revs))) {
3446 struct todo_item *item = append_new_todo(todo_list);
3447 const char *commit_buffer = repo_logmsg_reencode(the_repository,
3448 commit, NULL,
3449 encoding);
3450 const char *subject;
3451 int subject_len;
3452
3453 item->command = command;
3454 item->commit = commit;
3455 item->arg_offset = 0;
3456 item->arg_len = 0;
3457 item->offset_in_buf = todo_list->buf.len;
3458 subject_len = find_commit_subject(commit_buffer, &subject);
3459 strbuf_addf(&todo_list->buf, "%s %s %.*s\n", command_string,
3460 short_commit_name(the_repository, commit),
3461 subject_len, subject);
3462 repo_unuse_commit_buffer(the_repository, commit,
3463 commit_buffer);
3464 }
3465
3466 if (!todo_list->nr)
3467 return error(_("empty commit set passed"));
3468
3469 return 0;
3470 }
3471
3472 static int create_seq_dir(struct repository *r)
3473 {
3474 enum replay_action action;
3475 const char *in_progress_error = NULL;
3476 const char *in_progress_advice = NULL;
3477 unsigned int advise_skip =
3478 refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD") ||
3479 refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD");
3480
3481 if (!sequencer_get_last_command(r, &action)) {
3482 switch (action) {
3483 case REPLAY_REVERT:
3484 in_progress_error = _("revert is already in progress");
3485 in_progress_advice =
3486 _("try \"git revert (--continue | %s--abort | --quit)\"");
3487 break;
3488 case REPLAY_PICK:
3489 in_progress_error = _("cherry-pick is already in progress");
3490 in_progress_advice =
3491 _("try \"git cherry-pick (--continue | %s--abort | --quit)\"");
3492 break;
3493 default:
3494 BUG("unexpected action in create_seq_dir");
3495 }
3496 }
3497 if (in_progress_error) {
3498 error("%s", in_progress_error);
3499 if (advice_enabled(ADVICE_SEQUENCER_IN_USE))
3500 advise(in_progress_advice,
3501 advise_skip ? "--skip | " : "");
3502 return -1;
3503 }
3504 if (mkdir(git_path_seq_dir(), 0777) < 0)
3505 return error_errno(_("could not create sequencer directory '%s'"),
3506 git_path_seq_dir());
3507
3508 return 0;
3509 }
3510
3511 static int save_head(const char *head)
3512 {
3513 return write_message(head, strlen(head), git_path_head_file(), 1);
3514 }
3515
3516 static int rollback_is_safe(void)
3517 {
3518 struct strbuf sb = STRBUF_INIT;
3519 struct object_id expected_head, actual_head;
3520
3521 if (strbuf_read_file(&sb, git_path_abort_safety_file(), 0) >= 0) {
3522 strbuf_trim(&sb);
3523 if (get_oid_hex(sb.buf, &expected_head)) {
3524 strbuf_release(&sb);
3525 die(_("could not parse %s"), git_path_abort_safety_file());
3526 }
3527 strbuf_release(&sb);
3528 }
3529 else if (errno == ENOENT)
3530 oidclr(&expected_head, the_repository->hash_algo);
3531 else
3532 die_errno(_("could not read '%s'"), git_path_abort_safety_file());
3533
3534 if (repo_get_oid(the_repository, "HEAD", &actual_head))
3535 oidclr(&actual_head, the_repository->hash_algo);
3536
3537 return oideq(&actual_head, &expected_head);
3538 }
3539
3540 static int reset_merge(const struct object_id *oid)
3541 {
3542 struct child_process cmd = CHILD_PROCESS_INIT;
3543
3544 cmd.git_cmd = 1;
3545 strvec_pushl(&cmd.args, "reset", "--merge", NULL);
3546
3547 if (!is_null_oid(oid))
3548 strvec_push(&cmd.args, oid_to_hex(oid));
3549
3550 return run_command(&cmd);
3551 }
3552
3553 static int rollback_single_pick(struct repository *r)
3554 {
3555 struct object_id head_oid;
3556
3557 if (!refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD") &&
3558 !refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD"))
3559 return error(_("no cherry-pick or revert in progress"));
3560 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head_oid, NULL))
3561 return error(_("cannot resolve HEAD"));
3562 if (is_null_oid(&head_oid))
3563 return error(_("cannot abort from a branch yet to be born"));
3564 return reset_merge(&head_oid);
3565 }
3566
3567 static int skip_single_pick(void)
3568 {
3569 struct object_id head;
3570
3571 if (refs_read_ref_full(get_main_ref_store(the_repository), "HEAD", 0, &head, NULL))
3572 return error(_("cannot resolve HEAD"));
3573 return reset_merge(&head);
3574 }
3575
3576 int sequencer_rollback(struct repository *r, struct replay_opts *opts)
3577 {
3578 FILE *f;
3579 struct object_id oid;
3580 struct strbuf buf = STRBUF_INIT;
3581 const char *p;
3582
3583 f = fopen(git_path_head_file(), "r");
3584 if (!f && errno == ENOENT) {
3585 /*
3586 * There is no multiple-cherry-pick in progress.
3587 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates
3588 * a single-cherry-pick in progress, abort that.
3589 */
3590 return rollback_single_pick(r);
3591 }
3592 if (!f)
3593 return error_errno(_("cannot open '%s'"), git_path_head_file());
3594 if (strbuf_getline_lf(&buf, f)) {
3595 error(_("cannot read '%s': %s"), git_path_head_file(),
3596 ferror(f) ? strerror(errno) : _("unexpected end of file"));
3597 fclose(f);
3598 goto fail;
3599 }
3600 fclose(f);
3601 if (parse_oid_hex(buf.buf, &oid, &p) || *p != '\0') {
3602 error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),
3603 git_path_head_file());
3604 goto fail;
3605 }
3606 if (is_null_oid(&oid)) {
3607 error(_("cannot abort from a branch yet to be born"));
3608 goto fail;
3609 }
3610
3611 if (!rollback_is_safe()) {
3612 /* Do not error, just do not rollback */
3613 warning(_("You seem to have moved HEAD. "
3614 "Not rewinding, check your HEAD!"));
3615 } else
3616 if (reset_merge(&oid))
3617 goto fail;
3618 strbuf_release(&buf);
3619 return sequencer_remove_state(opts);
3620 fail:
3621 strbuf_release(&buf);
3622 return -1;
3623 }
3624
3625 int sequencer_skip(struct repository *r, struct replay_opts *opts)
3626 {
3627 enum replay_action action = -1;
3628 sequencer_get_last_command(r, &action);
3629
3630 /*
3631 * Check whether the subcommand requested to skip the commit is actually
3632 * in progress and that it's safe to skip the commit.
3633 *
3634 * opts->action tells us which subcommand requested to skip the commit.
3635 * If the corresponding .git/<ACTION>_HEAD exists, we know that the
3636 * action is in progress and we can skip the commit.
3637 *
3638 * Otherwise we check that the last instruction was related to the
3639 * particular subcommand we're trying to execute and barf if that's not
3640 * the case.
3641 *
3642 * Finally we check that the rollback is "safe", i.e., has the HEAD
3643 * moved? In this case, it doesn't make sense to "reset the merge" and
3644 * "skip the commit" as the user already handled this by committing. But
3645 * we'd not want to barf here, instead give advice on how to proceed. We
3646 * only need to check that when .git/<ACTION>_HEAD doesn't exist because
3647 * it gets removed when the user commits, so if it still exists we're
3648 * sure the user can't have committed before.
3649 */
3650 switch (opts->action) {
3651 case REPLAY_REVERT:
3652 if (!refs_ref_exists(get_main_ref_store(r), "REVERT_HEAD")) {
3653 if (action != REPLAY_REVERT)
3654 return error(_("no revert in progress"));
3655 if (!rollback_is_safe())
3656 goto give_advice;
3657 }
3658 break;
3659 case REPLAY_PICK:
3660 if (!refs_ref_exists(get_main_ref_store(r),
3661 "CHERRY_PICK_HEAD")) {
3662 if (action != REPLAY_PICK)
3663 return error(_("no cherry-pick in progress"));
3664 if (!rollback_is_safe())
3665 goto give_advice;
3666 }
3667 break;
3668 default:
3669 BUG("unexpected action in sequencer_skip");
3670 }
3671
3672 if (skip_single_pick())
3673 return error(_("failed to skip the commit"));
3674 if (!is_directory(git_path_seq_dir()))
3675 return 0;
3676
3677 return sequencer_continue(r, opts);
3678
3679 give_advice:
3680 error(_("there is nothing to skip"));
3681
3682 if (advice_enabled(ADVICE_RESOLVE_CONFLICT)) {
3683 advise(_("have you committed already?\n"
3684 "try \"git %s --continue\""),
3685 action == REPLAY_REVERT ? "revert" : "cherry-pick");
3686 }
3687 return -1;
3688 }
3689
3690 static int save_todo(struct todo_list *todo_list, struct replay_opts *opts,
3691 int reschedule)
3692 {
3693 struct lock_file todo_lock = LOCK_INIT;
3694 const char *todo_path = get_todo_path(opts);
3695 int next = todo_list->current, offset, fd;
3696
3697 /*
3698 * rebase -i writes "git-rebase-todo" without the currently executing
3699 * command, appending it to "done" instead.
3700 */
3701 if (is_rebase_i(opts) && !reschedule)
3702 next++;
3703
3704 fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
3705 if (fd < 0)
3706 return error_errno(_("could not lock '%s'"), todo_path);
3707 offset = get_item_line_offset(todo_list, next);
3708 if (write_in_full(fd, todo_list->buf.buf + offset,
3709 todo_list->buf.len - offset) < 0)
3710 return error_errno(_("could not write to '%s'"), todo_path);
3711 if (commit_lock_file(&todo_lock) < 0)
3712 return error(_("failed to finalize '%s'"), todo_path);
3713
3714 if (is_rebase_i(opts) && !reschedule && next > 0) {
3715 const char *done = rebase_path_done();
3716 int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
3717 int ret = 0;
3718
3719 if (fd < 0)
3720 return 0;
3721 if (write_in_full(fd, get_item_line(todo_list, next - 1),
3722 get_item_line_length(todo_list, next - 1))
3723 < 0)
3724 ret = error_errno(_("could not write to '%s'"), done);
3725 if (close(fd) < 0)
3726 ret = error_errno(_("failed to finalize '%s'"), done);
3727 return ret;
3728 }
3729 return 0;
3730 }
3731
3732 static int save_opts(struct replay_opts *opts)
3733 {
3734 const char *opts_file = git_path_opts_file();
3735 int res = 0;
3736
3737 if (opts->no_commit)
3738 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3739 "options.no-commit", NULL, "true");
3740 if (opts->edit >= 0)
3741 res |= repo_config_set_in_file_gently(the_repository, opts_file, "options.edit", NULL,
3742 opts->edit ? "true" : "false");
3743 if (opts->allow_empty)
3744 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3745 "options.allow-empty", NULL, "true");
3746 if (opts->allow_empty_message)
3747 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3748 "options.allow-empty-message", NULL, "true");
3749 if (opts->drop_redundant_commits)
3750 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3751 "options.drop-redundant-commits", NULL, "true");
3752 if (opts->keep_redundant_commits)
3753 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3754 "options.keep-redundant-commits", NULL, "true");
3755 if (opts->signoff)
3756 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3757 "options.signoff", NULL, "true");
3758 if (opts->record_origin)
3759 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3760 "options.record-origin", NULL, "true");
3761 if (opts->allow_ff)
3762 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3763 "options.allow-ff", NULL, "true");
3764 if (opts->mainline) {
3765 struct strbuf buf = STRBUF_INIT;
3766 strbuf_addf(&buf, "%d", opts->mainline);
3767 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3768 "options.mainline", NULL, buf.buf);
3769 strbuf_release(&buf);
3770 }
3771 if (opts->strategy)
3772 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3773 "options.strategy", NULL, opts->strategy);
3774 if (opts->gpg_sign)
3775 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3776 "options.gpg-sign", NULL, opts->gpg_sign);
3777 for (size_t i = 0; i < opts->xopts.nr; i++)
3778 res |= repo_config_set_multivar_in_file_gently(the_repository, opts_file,
3779 "options.strategy-option",
3780 opts->xopts.v[i], "^$", NULL, 0);
3781 if (opts->allow_rerere_auto)
3782 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3783 "options.allow-rerere-auto", NULL,
3784 opts->allow_rerere_auto == RERERE_AUTOUPDATE ?
3785 "true" : "false");
3786
3787 if (opts->explicit_cleanup)
3788 res |= repo_config_set_in_file_gently(the_repository, opts_file,
3789 "options.default-msg-cleanup", NULL,
3790 describe_cleanup_mode(opts->default_msg_cleanup));
3791 return res;
3792 }
3793
3794 static int make_patch(struct repository *r,
3795 struct commit *commit,
3796 struct replay_opts *opts)
3797 {
3798 struct rev_info log_tree_opt;
3799 const char *subject;
3800 char hex[GIT_MAX_HEXSZ + 1];
3801 int res = 0;
3802
3803 if (!is_rebase_i(opts))
3804 BUG("make_patch should only be called when rebasing");
3805
3806 oid_to_hex_r(hex, &commit->object.oid);
3807 if (write_message(hex, strlen(hex), rebase_path_stopped_sha(), 1) < 0)
3808 return -1;
3809 res |= write_rebase_head(&commit->object.oid);
3810
3811 memset(&log_tree_opt, 0, sizeof(log_tree_opt));
3812 repo_init_revisions(r, &log_tree_opt, NULL);
3813 log_tree_opt.abbrev = 0;
3814 log_tree_opt.diff = 1;
3815 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;
3816 log_tree_opt.disable_stdin = 1;
3817 log_tree_opt.no_commit_id = 1;
3818 log_tree_opt.diffopt.file = fopen(rebase_path_patch(), "w");
3819 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;
3820 if (!log_tree_opt.diffopt.file)
3821 res |= error_errno(_("could not open '%s'"),
3822 rebase_path_patch());
3823 else {
3824 res |= log_tree_commit(&log_tree_opt, commit);
3825 fclose(log_tree_opt.diffopt.file);
3826 }
3827
3828 if (!file_exists(rebase_path_message())) {
3829 const char *encoding = get_commit_output_encoding();
3830 const char *commit_buffer = repo_logmsg_reencode(r,
3831 commit, NULL,
3832 encoding);
3833 find_commit_subject(commit_buffer, &subject);
3834 res |= write_message(subject, strlen(subject), rebase_path_message(), 1);
3835 repo_unuse_commit_buffer(r, commit,
3836 commit_buffer);
3837 }
3838 release_revisions(&log_tree_opt);
3839
3840 return res;
3841 }
3842
3843 static int intend_to_amend(void)
3844 {
3845 struct object_id head;
3846 char *p;
3847
3848 if (repo_get_oid(the_repository, "HEAD", &head))
3849 return error(_("cannot read HEAD"));
3850
3851 p = oid_to_hex(&head);
3852 return write_message(p, strlen(p), rebase_path_amend(), 1);
3853 }
3854
3855 static int error_with_patch(struct repository *r,
3856 struct commit *commit,
3857 const char *subject, int subject_len,
3858 struct replay_opts *opts,
3859 int exit_code, int to_amend)
3860 {
3861 struct replay_ctx *ctx = opts->ctx;
3862
3863 /*
3864 * Write the commit message to be used by "git rebase
3865 * --continue". If a "fixup" or "squash" command has conflicts
3866 * then we will have already written rebase_path_message() in
3867 * error_failed_squash(). If an "edit" command was
3868 * fast-forwarded then we don't have a message in ctx->message
3869 * and rely on make_patch() to write rebase_path_message()
3870 * instead.
3871 */
3872 if (ctx->have_message && !file_exists(rebase_path_message()) &&
3873 write_message(ctx->message.buf, ctx->message.len,
3874 rebase_path_message(), 0))
3875 return error(_("could not write commit message file"));
3876
3877 if (commit && make_patch(r, commit, opts))
3878 return -1;
3879
3880 if (to_amend) {
3881 if (intend_to_amend())
3882 return -1;
3883
3884 fprintf(stderr,
3885 _("You can amend the commit now, with\n"
3886 "\n"
3887 " git commit --amend %s\n"
3888 "\n"
3889 "Once you are satisfied with your changes, run\n"
3890 "\n"
3891 " git rebase --continue\n"),
3892 gpg_sign_opt_quoted(opts));
3893 } else if (exit_code) {
3894 if (commit)
3895 fprintf_ln(stderr, _("Could not apply %s... %.*s"),
3896 short_commit_name(r, commit), subject_len, subject);
3897 else
3898 /*
3899 * We don't have the hash of the parent so
3900 * just print the line from the todo file.
3901 */
3902 fprintf_ln(stderr, _("Could not merge %.*s"),
3903 subject_len, subject);
3904 }
3905
3906 return exit_code;
3907 }
3908
3909 static int error_failed_squash(struct repository *r,
3910 struct commit *commit,
3911 struct replay_opts *opts,
3912 int subject_len,
3913 const char *subject)
3914 {
3915 if (copy_file(r, rebase_path_message(), rebase_path_squash_msg(), 0666))
3916 return error(_("could not copy '%s' to '%s'"),
3917 rebase_path_squash_msg(), rebase_path_message());
3918 unlink(git_path_merge_msg(r));
3919 if (copy_file(r, git_path_merge_msg(r), rebase_path_message(), 0666))
3920 return error(_("could not copy '%s' to '%s'"),
3921 rebase_path_message(),
3922 git_path_merge_msg(r));
3923 return error_with_patch(r, commit, subject, subject_len, opts, 1, 1);
3924 }
3925
3926 static int do_exec(struct repository *r, const char *command_line, int quiet)
3927 {
3928 struct child_process cmd = CHILD_PROCESS_INIT;
3929 int dirty, status;
3930
3931 if (!quiet)
3932 fprintf(stderr, _("Executing: %s\n"), command_line);
3933 cmd.use_shell = 1;
3934 strvec_push(&cmd.args, command_line);
3935 strvec_push(&cmd.env, "GIT_CHERRY_PICK_HELP");
3936 status = run_command(&cmd);
3937
3938 /* force re-reading of the cache */
3939 discard_index(r->index);
3940 if (repo_read_index(r) < 0)
3941 return error(_("could not read index"));
3942
3943 dirty = require_clean_work_tree(r, "rebase", NULL, 1, 1);
3944
3945 if (status) {
3946 warning(_("execution failed: %s\n%s"
3947 "You can fix the problem, and then run\n"
3948 "\n"
3949 " git rebase --continue\n"
3950 "\n"),
3951 command_line,
3952 dirty ? _("and made changes to the index and/or the "
3953 "working tree.\n") : "");
3954 if (status == 127)
3955 /* command not found */
3956 status = 1;
3957 } else if (dirty) {
3958 warning(_("execution succeeded: %s\nbut "
3959 "left changes to the index and/or the working tree.\n"
3960 "Commit or stash your changes, and then run\n"
3961 "\n"
3962 " git rebase --continue\n"
3963 "\n"), command_line);
3964 status = 1;
3965 }
3966
3967 return status;
3968 }
3969
3970 __attribute__((format (printf, 2, 3)))
3971 static int safe_append(const char *filename, const char *fmt, ...)
3972 {
3973 va_list ap;
3974 struct lock_file lock = LOCK_INIT;
3975 int fd = hold_lock_file_for_update(&lock, filename,
3976 LOCK_REPORT_ON_ERROR);
3977 struct strbuf buf = STRBUF_INIT;
3978
3979 if (fd < 0)
3980 return -1;
3981
3982 if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
3983 error_errno(_("could not read '%s'"), filename);
3984 rollback_lock_file(&lock);
3985 return -1;
3986 }
3987 strbuf_complete(&buf, '\n');
3988 va_start(ap, fmt);
3989 strbuf_vaddf(&buf, fmt, ap);
3990 va_end(ap);
3991
3992 if (write_in_full(fd, buf.buf, buf.len) < 0) {
3993 error_errno(_("could not write to '%s'"), filename);
3994 strbuf_release(&buf);
3995 rollback_lock_file(&lock);
3996 return -1;
3997 }
3998 if (commit_lock_file(&lock) < 0) {
3999 strbuf_release(&buf);
4000 return error(_("failed to finalize '%s'"), filename);
4001 }
4002
4003 strbuf_release(&buf);
4004 return 0;
4005 }
4006
4007 static int do_label(struct repository *r, const char *name, int len)
4008 {
4009 struct ref_store *refs = get_main_ref_store(r);
4010 struct ref_transaction *transaction;
4011 struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
4012 struct strbuf msg = STRBUF_INIT;
4013 int ret = 0;
4014 struct object_id head_oid;
4015
4016 if (len == 1 && *name == '#')
4017 return error(_("illegal label name: '%.*s'"), len, name);
4018
4019 strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
4020 strbuf_addf(&msg, "rebase (label) '%.*s'", len, name);
4021
4022 transaction = ref_store_transaction_begin(refs, 0, &err);
4023 if (!transaction) {
4024 error("%s", err.buf);
4025 ret = -1;
4026 } else if (repo_get_oid(r, "HEAD", &head_oid)) {
4027 error(_("could not read HEAD"));
4028 ret = -1;
4029 } else if (ref_transaction_update(transaction, ref_name.buf,
4030 &head_oid, NULL, NULL, NULL,
4031 0, msg.buf, &err) < 0 ||
4032 ref_transaction_commit(transaction, &err)) {
4033 error("%s", err.buf);
4034 ret = -1;
4035 }
4036 ref_transaction_free(transaction);
4037 strbuf_release(&err);
4038 strbuf_release(&msg);
4039
4040 if (!ret)
4041 ret = safe_append(rebase_path_refs_to_delete(),
4042 "%s\n", ref_name.buf);
4043 strbuf_release(&ref_name);
4044
4045 return ret;
4046 }
4047
4048 static struct commit *lookup_label(struct repository *r, const char *label,
4049 int len, struct strbuf *buf)
4050 {
4051 struct commit *commit;
4052 struct object_id oid;
4053
4054 strbuf_reset(buf);
4055 strbuf_addf(buf, "refs/rewritten/%.*s", len, label);
4056 if (!refs_read_ref(get_main_ref_store(the_repository), buf->buf, &oid)) {
4057 commit = lookup_commit_object(r, &oid);
4058 } else {
4059 /* fall back to non-rewritten ref or commit */
4060 strbuf_splice(buf, 0, strlen("refs/rewritten/"), "", 0);
4061 commit = lookup_commit_reference_by_name(buf->buf);
4062 }
4063
4064 if (!commit)
4065 error(_("could not resolve '%s'"), buf->buf);
4066
4067 return commit;
4068 }
4069
4070 static int do_reset(struct repository *r,
4071 const char *name, int len,
4072 struct replay_opts *opts)
4073 {
4074 struct strbuf ref_name = STRBUF_INIT;
4075 struct object_id oid;
4076 struct lock_file lock = LOCK_INIT;
4077 struct tree_desc desc = { 0 };
4078 struct tree *tree;
4079 struct unpack_trees_options unpack_tree_opts = { 0 };
4080 int ret = 0;
4081
4082 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0)
4083 return -1;
4084
4085 if (len == 10 && !strncmp("[new root]", name, len)) {
4086 if (!opts->have_squash_onto) {
4087 const char *hex;
4088 if (commit_tree("", 0, the_hash_algo->empty_tree,
4089 NULL, &opts->squash_onto,
4090 NULL, NULL))
4091 return error(_("writing fake root commit"));
4092 opts->have_squash_onto = 1;
4093 hex = oid_to_hex(&opts->squash_onto);
4094 if (write_message(hex, strlen(hex),
4095 rebase_path_squash_onto(), 0))
4096 return error(_("writing squash-onto"));
4097 }
4098 oidcpy(&oid, &opts->squash_onto);
4099 } else {
4100 int i;
4101 struct commit *commit;
4102
4103 /* Determine the length of the label */
4104 for (i = 0; i < len; i++)
4105 if (isspace(name[i]))
4106 break;
4107 len = i;
4108
4109 commit = lookup_label(r, name, len, &ref_name);
4110 if (!commit) {
4111 ret = -1;
4112 goto cleanup;
4113 }
4114 oid = commit->object.oid;
4115 }
4116
4117 setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
4118 unpack_tree_opts.head_idx = 1;
4119 unpack_tree_opts.src_index = r->index;
4120 unpack_tree_opts.dst_index = r->index;
4121 unpack_tree_opts.fn = oneway_merge;
4122 unpack_tree_opts.merge = 1;
4123 unpack_tree_opts.update = 1;
4124 unpack_tree_opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
4125 unpack_tree_opts.skip_cache_tree_update = 1;
4126 init_checkout_metadata(&unpack_tree_opts.meta, name, &oid, NULL);
4127
4128 if (repo_read_index_unmerged(r)) {
4129 ret = error_resolve_conflict(action_name(opts));
4130 goto cleanup;
4131 }
4132
4133 if (!fill_tree_descriptor(r, &desc, &oid)) {
4134 ret = error(_("failed to find tree of %s"), oid_to_hex(&oid));
4135 goto cleanup;
4136 }
4137
4138 if (unpack_trees(1, &desc, &unpack_tree_opts)) {
4139 ret = -1;
4140 goto cleanup;
4141 }
4142
4143 tree = repo_parse_tree_indirect(the_repository, &oid);
4144 if (!tree)
4145 return error(_("unable to read tree (%s)"), oid_to_hex(&oid));
4146 prime_cache_tree(r, r->index, tree);
4147
4148 if (write_locked_index(r->index, &lock, COMMIT_LOCK) < 0)
4149 ret = error(_("could not write index"));
4150
4151 if (!ret)
4152 ret = refs_update_ref(get_main_ref_store(the_repository), reflog_message(opts, "reset", "'%.*s'",
4153 len, name),
4154 "HEAD", &oid,
4155 NULL, 0, UPDATE_REFS_MSG_ON_ERR);
4156 cleanup:
4157 free((void *)desc.buffer);
4158 if (ret < 0)
4159 rollback_lock_file(&lock);
4160 strbuf_release(&ref_name);
4161 clear_unpack_trees_porcelain(&unpack_tree_opts);
4162 return ret;
4163 }
4164
4165 static int do_merge(struct repository *r,
4166 struct commit *commit,
4167 const char *arg, int arg_len,
4168 int flags, int *check_todo, struct replay_opts *opts)
4169 {
4170 struct replay_ctx *ctx = opts->ctx;
4171 int run_commit_flags = 0;
4172 struct strbuf ref_name = STRBUF_INIT;
4173 struct commit *head_commit, *merge_commit, *i;
4174 struct commit_list *bases = NULL, *j;
4175 struct commit_list *to_merge = NULL, **tail = &to_merge;
4176 const char *strategy = !opts->xopts.nr &&
4177 (!opts->strategy ||
4178 !strcmp(opts->strategy, "recursive") ||
4179 !strcmp(opts->strategy, "ort")) ?
4180 NULL : opts->strategy;
4181 struct merge_options o;
4182 int merge_arg_len, oneline_offset, can_fast_forward, ret, k;
4183 static struct lock_file lock;
4184 const char *p;
4185 const char *reflog_action = reflog_message(opts, "merge", NULL);
4186
4187 if (repo_hold_locked_index(r, &lock, LOCK_REPORT_ON_ERROR) < 0) {
4188 ret = -1;
4189 goto leave_merge;
4190 }
4191
4192 head_commit = lookup_commit_reference_by_name("HEAD");
4193 if (!head_commit) {
4194 ret = error(_("cannot merge without a current revision"));
4195 goto leave_merge;
4196 }
4197
4198 /*
4199 * For octopus merges, the arg starts with the list of revisions to be
4200 * merged. The list is optionally followed by '#' and the oneline.
4201 */
4202 merge_arg_len = oneline_offset = arg_len;
4203 for (p = arg; p - arg < arg_len; p += strspn(p, " \t\n")) {
4204 if (!*p)
4205 break;
4206 if (*p == '#' && (!p[1] || isspace(p[1]))) {
4207 p += 1 + strspn(p + 1, " \t\n");
4208 oneline_offset = p - arg;
4209 break;
4210 }
4211 k = strcspn(p, " \t\n");
4212 if (!k)
4213 continue;
4214 merge_commit = lookup_label(r, p, k, &ref_name);
4215 if (!merge_commit) {
4216 ret = error(_("unable to parse '%.*s'"), k, p);
4217 goto leave_merge;
4218 }
4219 tail = &commit_list_insert(merge_commit, tail)->next;
4220 p += k;
4221 merge_arg_len = p - arg;
4222 }
4223
4224 if (!to_merge) {
4225 ret = error(_("nothing to merge: '%.*s'"), arg_len, arg);
4226 goto leave_merge;
4227 }
4228
4229 if (opts->have_squash_onto &&
4230 oideq(&head_commit->object.oid, &opts->squash_onto)) {
4231 /*
4232 * When the user tells us to "merge" something into a
4233 * "[new root]", let's simply fast-forward to the merge head.
4234 */
4235 rollback_lock_file(&lock);
4236 if (to_merge->next)
4237 ret = error(_("octopus merge cannot be executed on "
4238 "top of a [new root]"));
4239 else
4240 ret = fast_forward_to(r, &to_merge->item->object.oid,
4241 &head_commit->object.oid, 0,
4242 opts);
4243 goto leave_merge;
4244 }
4245
4246 /*
4247 * If HEAD is not identical to the first parent of the original merge
4248 * commit, we cannot fast-forward.
4249 */
4250 can_fast_forward = opts->allow_ff && commit && commit->parents &&
4251 oideq(&commit->parents->item->object.oid,
4252 &head_commit->object.oid);
4253
4254 /*
4255 * If any merge head is different from the original one, we cannot
4256 * fast-forward.
4257 */
4258 if (can_fast_forward) {
4259 struct commit_list *p = commit->parents->next;
4260
4261 for (j = to_merge; j && p; j = j->next, p = p->next)
4262 if (!oideq(&j->item->object.oid,
4263 &p->item->object.oid)) {
4264 can_fast_forward = 0;
4265 break;
4266 }
4267 /*
4268 * If the number of merge heads differs from the original merge
4269 * commit, we cannot fast-forward.
4270 */
4271 if (j || p)
4272 can_fast_forward = 0;
4273 }
4274
4275 if (can_fast_forward) {
4276 rollback_lock_file(&lock);
4277 ret = fast_forward_to(r, &commit->object.oid,
4278 &head_commit->object.oid, 0, opts);
4279 if (flags & TODO_EDIT_MERGE_MSG)
4280 goto fast_forward_edit;
4281
4282 goto leave_merge;
4283 }
4284
4285 if (commit) {
4286 const char *encoding = get_commit_output_encoding();
4287 const char *message = repo_logmsg_reencode(r, commit, NULL,
4288 encoding);
4289 const char *body;
4290 int len;
4291
4292 if (!message) {
4293 ret = error(_("could not get commit message of '%s'"),
4294 oid_to_hex(&commit->object.oid));
4295 goto leave_merge;
4296 }
4297 write_author_script(message);
4298 find_commit_subject(message, &body);
4299 len = strlen(body);
4300 strbuf_add(&ctx->message, body, len);
4301 repo_unuse_commit_buffer(r, commit, message);
4302 } else {
4303 struct strbuf buf = STRBUF_INIT;
4304
4305 strbuf_addf(&buf, "author %s", git_author_info(0));
4306 write_author_script(buf.buf);
4307 strbuf_release(&buf);
4308
4309 if (oneline_offset < arg_len) {
4310 strbuf_add(&ctx->message, arg + oneline_offset,
4311 arg_len - oneline_offset);
4312 } else {
4313 strbuf_addf(&ctx->message, "Merge %s '%.*s'",
4314 to_merge->next ? "branches" : "branch",
4315 merge_arg_len, arg);
4316 }
4317 }
4318 ctx->have_message = 1;
4319 if (write_message(ctx->message.buf, ctx->message.len,
4320 git_path_merge_msg(r), 0)) {
4321 ret = error_errno(_("could not write '%s'"),
4322 git_path_merge_msg(r));
4323 goto leave_merge;
4324 }
4325
4326 if (strategy || to_merge->next) {
4327 /* Octopus merge */
4328 struct child_process cmd = CHILD_PROCESS_INIT;
4329
4330 if (read_env_script(&cmd.env)) {
4331 const char *gpg_opt = gpg_sign_opt_quoted(opts);
4332
4333 ret = error(_(staged_changes_advice), gpg_opt, gpg_opt);
4334 goto leave_merge;
4335 }
4336
4337 if (opts->committer_date_is_author_date)
4338 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
4339 opts->ignore_date ?
4340 "" :
4341 author_date_from_env(&cmd.env));
4342 if (opts->ignore_date)
4343 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
4344
4345 cmd.git_cmd = 1;
4346 strvec_push(&cmd.args, "merge");
4347 strvec_push(&cmd.args, "-s");
4348 if (!strategy)
4349 strvec_push(&cmd.args, "octopus");
4350 else {
4351 strvec_push(&cmd.args, strategy);
4352 for (k = 0; k < opts->xopts.nr; k++)
4353 strvec_pushf(&cmd.args,
4354 "-X%s", opts->xopts.v[k]);
4355 }
4356 if (!(flags & TODO_EDIT_MERGE_MSG))
4357 strvec_push(&cmd.args, "--no-edit");
4358 else
4359 strvec_push(&cmd.args, "--edit");
4360 strvec_push(&cmd.args, "--no-ff");
4361 strvec_push(&cmd.args, "--no-log");
4362 strvec_push(&cmd.args, "--no-stat");
4363 strvec_push(&cmd.args, "-F");
4364 strvec_push(&cmd.args, git_path_merge_msg(r));
4365 if (opts->gpg_sign)
4366 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
4367 else
4368 strvec_push(&cmd.args, "--no-gpg-sign");
4369
4370 /* Add the tips to be merged */
4371 for (j = to_merge; j; j = j->next)
4372 strvec_push(&cmd.args,
4373 oid_to_hex(&j->item->object.oid));
4374
4375 strbuf_release(&ref_name);
4376 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
4377 NULL, REF_NO_DEREF);
4378 rollback_lock_file(&lock);
4379
4380 ret = run_command(&cmd);
4381
4382 /* force re-reading of the cache */
4383 if (!ret) {
4384 discard_index(r->index);
4385 if (repo_read_index(r) < 0)
4386 ret = error(_("could not read index"));
4387 }
4388 goto leave_merge;
4389 }
4390
4391 merge_commit = to_merge->item;
4392 if (repo_get_merge_bases(r, head_commit, merge_commit, &bases) < 0) {
4393 ret = -1;
4394 goto leave_merge;
4395 }
4396
4397 if (bases && oideq(&merge_commit->object.oid,
4398 &bases->item->object.oid)) {
4399 ret = 0;
4400 /* skip merging an ancestor of HEAD */
4401 goto leave_merge;
4402 }
4403
4404 write_message(oid_to_hex(&merge_commit->object.oid), the_hash_algo->hexsz,
4405 git_path_merge_head(r), 0);
4406 write_message("no-ff", 5, git_path_merge_mode(r), 0);
4407
4408 bases = commit_list_reverse(bases);
4409
4410 repo_read_index(r);
4411 init_ui_merge_options(&o, r);
4412 o.branch1 = "HEAD";
4413 o.branch2 = ref_name.buf;
4414 o.buffer_output = 2;
4415
4416 /*
4417 * TODO: Should use merge_incore_recursive() and
4418 * merge_switch_to_result(), skipping the call to
4419 * merge_switch_to_result() when we don't actually need to
4420 * update the index and working copy immediately.
4421 */
4422 ret = merge_ort_recursive(&o, head_commit, merge_commit, bases, &i);
4423 if (ret <= 0)
4424 fputs(o.obuf.buf, stdout);
4425 strbuf_release(&o.obuf);
4426 if (ret < 0) {
4427 error(_("could not even attempt to merge '%.*s'"),
4428 merge_arg_len, arg);
4429 unlink(git_path_merge_msg(r));
4430 goto leave_merge;
4431 }
4432 /*
4433 * The return value of merge_ort_recursive() is 1 on clean, and 0 on
4434 * unclean merge.
4435 *
4436 * Let's reverse that, so that do_merge() returns 0 upon success and
4437 * 1 upon failed merge (keeping the return value -1 for the cases where
4438 * we will want to reschedule the `merge` command).
4439 */
4440 ret = !ret;
4441
4442 if (r->index->cache_changed &&
4443 write_locked_index(r->index, &lock, COMMIT_LOCK)) {
4444 ret = error(_("merge: Unable to write new index file"));
4445 goto leave_merge;
4446 }
4447
4448 rollback_lock_file(&lock);
4449 if (ret)
4450 repo_rerere(r, opts->allow_rerere_auto);
4451 else
4452 /*
4453 * In case of problems, we now want to return a positive
4454 * value (a negative one would indicate that the `merge`
4455 * command needs to be rescheduled).
4456 */
4457 ret = !!run_git_commit(git_path_merge_msg(r), reflog_action,
4458 opts, run_commit_flags);
4459
4460 if (!ret && flags & TODO_EDIT_MERGE_MSG) {
4461 fast_forward_edit:
4462 *check_todo = 1;
4463 run_commit_flags |= AMEND_MSG | EDIT_MSG | VERIFY_MSG;
4464 ret = !!run_git_commit(NULL, reflog_action, opts,
4465 run_commit_flags);
4466 }
4467
4468
4469 leave_merge:
4470 strbuf_release(&ref_name);
4471 rollback_lock_file(&lock);
4472 commit_list_free(to_merge);
4473 commit_list_free(bases);
4474 return ret;
4475 }
4476
4477 static int write_update_refs_state(struct string_list *refs_to_oids)
4478 {
4479 int result = 0;
4480 struct lock_file lock = LOCK_INIT;
4481 FILE *fp = NULL;
4482 struct string_list_item *item;
4483 char *path;
4484
4485 path = rebase_path_update_refs(the_repository->gitdir);
4486
4487 if (!refs_to_oids->nr) {
4488 if (unlink(path) && errno != ENOENT)
4489 result = error_errno(_("could not unlink: %s"), path);
4490 goto cleanup;
4491 }
4492
4493 if (safe_create_leading_directories(the_repository, path)) {
4494 result = error(_("unable to create leading directories of %s"),
4495 path);
4496 goto cleanup;
4497 }
4498
4499 if (hold_lock_file_for_update(&lock, path, 0) < 0) {
4500 result = error(_("another 'rebase' process appears to be running; "
4501 "'%s.lock' already exists"),
4502 path);
4503 goto cleanup;
4504 }
4505
4506 fp = fdopen_lock_file(&lock, "w");
4507 if (!fp) {
4508 result = error_errno(_("could not open '%s' for writing"), path);
4509 rollback_lock_file(&lock);
4510 goto cleanup;
4511 }
4512
4513 for_each_string_list_item(item, refs_to_oids) {
4514 struct update_ref_record *rec = item->util;
4515 fprintf(fp, "%s\n%s\n%s\n", item->string,
4516 oid_to_hex(&rec->before), oid_to_hex(&rec->after));
4517 }
4518
4519 result = commit_lock_file(&lock);
4520
4521 cleanup:
4522 free(path);
4523 return result;
4524 }
4525
4526 /*
4527 * Parse the update-refs file for the current rebase, then remove the
4528 * refs that do not appear in the todo_list (and have not had updated
4529 * values stored) and add refs that are in the todo_list but not
4530 * represented in the update-refs file.
4531 *
4532 * If there are changes to the update-refs list, then write the new state
4533 * to disk.
4534 */
4535 void todo_list_filter_update_refs(struct repository *r,
4536 struct todo_list *todo_list)
4537 {
4538 int i;
4539 int updated = 0;
4540 struct string_list update_refs = STRING_LIST_INIT_DUP;
4541
4542 sequencer_get_update_refs_state(r->gitdir, &update_refs);
4543
4544 /*
4545 * For each item in the update_refs list, if it has no updated
4546 * value and does not appear in the todo_list, then remove it
4547 * from the update_refs list.
4548 */
4549 for (i = 0; i < update_refs.nr; i++) {
4550 int j;
4551 int found = 0;
4552 const char *ref = update_refs.items[i].string;
4553 size_t reflen = strlen(ref);
4554 struct update_ref_record *rec = update_refs.items[i].util;
4555
4556 /* OID already stored as updated. */
4557 if (!is_null_oid(&rec->after))
4558 continue;
4559
4560 for (j = 0; !found && j < todo_list->nr; j++) {
4561 struct todo_item *item = &todo_list->items[j];
4562 const char *arg = todo_list->buf.buf + item->arg_offset;
4563
4564 if (item->command != TODO_UPDATE_REF)
4565 continue;
4566
4567 if (item->arg_len != reflen ||
4568 strncmp(arg, ref, reflen))
4569 continue;
4570
4571 found = 1;
4572 }
4573
4574 if (!found) {
4575 free(update_refs.items[i].string);
4576 free(update_refs.items[i].util);
4577
4578 update_refs.nr--;
4579 MOVE_ARRAY(update_refs.items + i, update_refs.items + i + 1, update_refs.nr - i);
4580
4581 updated = 1;
4582 i--;
4583 }
4584 }
4585
4586 /*
4587 * For each todo_item, check if its ref is in the update_refs list.
4588 * If not, then add it as an un-updated ref.
4589 */
4590 for (i = 0; i < todo_list->nr; i++) {
4591 struct todo_item *item = &todo_list->items[i];
4592 const char *arg = todo_list->buf.buf + item->arg_offset;
4593 int j, found = 0;
4594
4595 if (item->command != TODO_UPDATE_REF)
4596 continue;
4597
4598 for (j = 0; !found && j < update_refs.nr; j++) {
4599 const char *ref = update_refs.items[j].string;
4600
4601 found = strlen(ref) == item->arg_len &&
4602 !strncmp(ref, arg, item->arg_len);
4603 }
4604
4605 if (!found) {
4606 struct string_list_item *inserted;
4607 struct strbuf argref = STRBUF_INIT;
4608
4609 strbuf_add(&argref, arg, item->arg_len);
4610 inserted = string_list_insert(&update_refs, argref.buf);
4611 inserted->util = init_update_ref_record(argref.buf);
4612 strbuf_release(&argref);
4613 updated = 1;
4614 }
4615 }
4616
4617 if (updated)
4618 write_update_refs_state(&update_refs);
4619 string_list_clear(&update_refs, 1);
4620 }
4621
4622 static int do_update_ref(struct repository *r, const char *refname)
4623 {
4624 struct string_list_item *item;
4625 struct string_list list = STRING_LIST_INIT_DUP;
4626
4627 if (sequencer_get_update_refs_state(r->gitdir, &list))
4628 return -1;
4629
4630 for_each_string_list_item(item, &list) {
4631 if (!strcmp(item->string, refname)) {
4632 struct update_ref_record *rec = item->util;
4633 if (refs_read_ref(get_main_ref_store(the_repository), "HEAD", &rec->after))
4634 return -1;
4635 break;
4636 }
4637 }
4638
4639 write_update_refs_state(&list);
4640 string_list_clear(&list, 1);
4641 return 0;
4642 }
4643
4644 static int do_update_refs(struct repository *r, int quiet)
4645 {
4646 int res = 0;
4647 struct string_list_item *item;
4648 struct string_list refs_to_oids = STRING_LIST_INIT_DUP;
4649 struct ref_store *refs = get_main_ref_store(r);
4650 struct strbuf update_msg = STRBUF_INIT;
4651 struct strbuf error_msg = STRBUF_INIT;
4652
4653 if ((res = sequencer_get_update_refs_state(r->gitdir, &refs_to_oids)))
4654 return res;
4655
4656 for_each_string_list_item(item, &refs_to_oids) {
4657 struct update_ref_record *rec = item->util;
4658 int loop_res;
4659
4660 loop_res = refs_update_ref(refs, "rewritten during rebase",
4661 item->string,
4662 &rec->after, &rec->before,
4663 0, UPDATE_REFS_MSG_ON_ERR);
4664 res |= loop_res;
4665
4666 if (quiet)
4667 continue;
4668
4669 if (loop_res)
4670 strbuf_addf(&error_msg, "\t%s\n", item->string);
4671 else
4672 strbuf_addf(&update_msg, "\t%s\n", item->string);
4673 }
4674
4675 if (!quiet &&
4676 (update_msg.len || error_msg.len)) {
4677 fprintf(stderr,
4678 _("Updated the following refs with %s:\n%s"),
4679 "--update-refs",
4680 update_msg.buf);
4681
4682 if (res)
4683 fprintf(stderr,
4684 _("Failed to update the following refs with %s:\n%s"),
4685 "--update-refs",
4686 error_msg.buf);
4687 }
4688
4689 string_list_clear(&refs_to_oids, 1);
4690 strbuf_release(&update_msg);
4691 strbuf_release(&error_msg);
4692 return res;
4693 }
4694
4695 static int is_final_fixup(struct todo_list *todo_list)
4696 {
4697 int i = todo_list->current;
4698
4699 if (!is_fixup(todo_list->items[i].command))
4700 return 0;
4701
4702 while (++i < todo_list->nr)
4703 if (is_fixup(todo_list->items[i].command))
4704 return 0;
4705 else if (!is_noop(todo_list->items[i].command))
4706 break;
4707 return 1;
4708 }
4709
4710 static enum todo_command peek_command(struct todo_list *todo_list, int offset)
4711 {
4712 int i;
4713
4714 for (i = todo_list->current + offset; i < todo_list->nr; i++)
4715 if (!is_noop(todo_list->items[i].command))
4716 return todo_list->items[i].command;
4717
4718 return -1;
4719 }
4720
4721 static void create_autostash_internal(struct repository *r,
4722 const char *path,
4723 const char *refname,
4724 const char *message,
4725 bool silent)
4726 {
4727 struct strbuf buf = STRBUF_INIT;
4728 struct lock_file lock_file = LOCK_INIT;
4729 int fd;
4730
4731 if (path && refname)
4732 BUG("can only pass path or refname");
4733
4734 fd = repo_hold_locked_index(r, &lock_file, 0);
4735 refresh_index(r->index, REFRESH_QUIET, NULL, NULL, NULL);
4736 if (0 <= fd)
4737 repo_update_index_if_able(r, &lock_file);
4738 rollback_lock_file(&lock_file);
4739
4740 if (has_unstaged_changes(r, 1) ||
4741 has_uncommitted_changes(r, 1)) {
4742 struct child_process stash = CHILD_PROCESS_INIT;
4743 struct reset_working_tree_options ropts = {
4744 .flags = RESET_WORKING_TREE_HARD |
4745 RESET_WORKING_TREE_UPDATE_HEAD,
4746 };
4747 struct object_id oid;
4748
4749 strvec_pushl(&stash.args,
4750 "stash", "create",
4751 message ? message : "autostash", NULL);
4752 stash.git_cmd = 1;
4753 stash.no_stdin = 1;
4754 strbuf_reset(&buf);
4755 if (capture_command(&stash, &buf, GIT_MAX_HEXSZ))
4756 die(_("Cannot autostash"));
4757 strbuf_trim_trailing_newline(&buf);
4758 if (repo_get_oid(r, buf.buf, &oid))
4759 die(_("Unexpected stash response: '%s'"),
4760 buf.buf);
4761 strbuf_reset(&buf);
4762 strbuf_add_unique_abbrev(&buf, &oid, DEFAULT_ABBREV);
4763
4764 if (path) {
4765 if (safe_create_leading_directories_const(the_repository, path))
4766 die(_("Could not create directory for '%s'"),
4767 path);
4768 write_file(path, "%s", oid_to_hex(&oid));
4769 } else {
4770 refs_update_ref(get_main_ref_store(r), "", refname,
4771 &oid, null_oid(the_hash_algo), 0, UPDATE_REFS_DIE_ON_ERR);
4772 }
4773
4774 if (!silent)
4775 printf(_("Created autostash: %s\n"), buf.buf);
4776 if (reset_working_tree(r, &ropts) < 0)
4777 die(_("could not reset --hard"));
4778 discard_index(r->index);
4779 if (repo_read_index(r) < 0)
4780 die(_("could not read index"));
4781 }
4782 strbuf_release(&buf);
4783 }
4784
4785 void create_autostash(struct repository *r, const char *path)
4786 {
4787 create_autostash_internal(r, path, NULL, NULL, false);
4788 }
4789
4790 void create_autostash_ref(struct repository *r, const char *refname,
4791 const char *message, bool silent)
4792 {
4793 create_autostash_internal(r, NULL, refname, message, silent);
4794 }
4795
4796 static int apply_save_autostash_oid(const char *stash_oid, int attempt_apply,
4797 const char *label_ours, const char *label_theirs,
4798 const char *label_base,
4799 const char *stash_msg)
4800 {
4801 struct child_process child = CHILD_PROCESS_INIT;
4802 int ret = 0;
4803
4804 if (attempt_apply) {
4805 child.git_cmd = 1;
4806 child.no_stdout = 1;
4807 child.no_stderr = 1;
4808 strvec_push(&child.args, "stash");
4809 strvec_push(&child.args, "apply");
4810 if (label_ours)
4811 strvec_pushf(&child.args, "--label-ours=%s", label_ours);
4812 if (label_theirs)
4813 strvec_pushf(&child.args, "--label-theirs=%s", label_theirs);
4814 if (label_base)
4815 strvec_pushf(&child.args, "--label-base=%s", label_base);
4816 strvec_push(&child.args, stash_oid);
4817 ret = run_command(&child);
4818 }
4819
4820 if (attempt_apply && !ret)
4821 fprintf(stderr, _("Applied autostash.\n"));
4822 else {
4823 struct child_process store = CHILD_PROCESS_INIT;
4824
4825 store.git_cmd = 1;
4826 strvec_push(&store.args, "stash");
4827 strvec_push(&store.args, "store");
4828 strvec_push(&store.args, "-m");
4829 strvec_push(&store.args, stash_msg ? stash_msg : "autostash");
4830 strvec_push(&store.args, "-q");
4831 strvec_push(&store.args, stash_oid);
4832 if (run_command(&store))
4833 ret = error(_("cannot store %s"), stash_oid);
4834 else if (attempt_apply)
4835 fprintf(stderr,
4836 _("Your local changes are stashed, however applying them\n"
4837 "resulted in conflicts. You can either resolve the conflicts\n"
4838 "and then discard the stash with \"git stash drop\", or, if you\n"
4839 "do not want to resolve them now, run \"git reset --hard\" and\n"
4840 "apply the local changes later by running \"git stash pop\".\n"));
4841 else
4842 fprintf(stderr,
4843 _("Autostash exists; creating a new stash entry.\n"
4844 "Your changes are safe in the stash.\n"
4845 "You can run \"git stash pop\" or"
4846 " \"git stash drop\" at any time.\n"));
4847 }
4848
4849 return ret;
4850 }
4851
4852 static int apply_save_autostash(const char *path, int attempt_apply)
4853 {
4854 struct strbuf stash_oid = STRBUF_INIT;
4855 int ret = 0;
4856
4857 if (!read_oneliner(&stash_oid, path,
4858 READ_ONELINER_SKIP_IF_EMPTY)) {
4859 strbuf_release(&stash_oid);
4860 return 0;
4861 }
4862 strbuf_trim(&stash_oid);
4863
4864 ret = apply_save_autostash_oid(stash_oid.buf, attempt_apply,
4865 NULL, NULL, NULL, NULL);
4866
4867 unlink(path);
4868 strbuf_release(&stash_oid);
4869 return ret;
4870 }
4871
4872 int save_autostash(const char *path)
4873 {
4874 return apply_save_autostash(path, 0);
4875 }
4876
4877 int apply_autostash(const char *path)
4878 {
4879 return apply_save_autostash(path, 1);
4880 }
4881
4882 int apply_autostash_oid(const char *stash_oid)
4883 {
4884 return apply_save_autostash_oid(stash_oid, 1, NULL, NULL, NULL, NULL);
4885 }
4886
4887 static int apply_save_autostash_ref(struct repository *r, const char *refname,
4888 int attempt_apply,
4889 const char *label_ours, const char *label_theirs,
4890 const char *label_base,
4891 const char *stash_msg)
4892 {
4893 struct object_id stash_oid;
4894 char stash_oid_hex[GIT_MAX_HEXSZ + 1];
4895 int flag, ret;
4896
4897 if (!refs_ref_exists(get_main_ref_store(r), refname))
4898 return 0;
4899
4900 if (!refs_resolve_ref_unsafe(get_main_ref_store(r), refname,
4901 RESOLVE_REF_READING, &stash_oid, &flag))
4902 return -1;
4903 if (flag & REF_ISSYMREF)
4904 return error(_("autostash reference is a symref"));
4905
4906 oid_to_hex_r(stash_oid_hex, &stash_oid);
4907 ret = apply_save_autostash_oid(stash_oid_hex, attempt_apply,
4908 label_ours, label_theirs, label_base,
4909 stash_msg);
4910
4911 refs_delete_ref(get_main_ref_store(r), "", refname,
4912 &stash_oid, REF_NO_DEREF);
4913
4914 return ret;
4915 }
4916
4917 int save_autostash_ref(struct repository *r, const char *refname)
4918 {
4919 return apply_save_autostash_ref(r, refname, 0,
4920 NULL, NULL, NULL, NULL);
4921 }
4922
4923 int apply_autostash_ref(struct repository *r, const char *refname,
4924 const char *label_ours, const char *label_theirs,
4925 const char *label_base, const char *stash_msg)
4926 {
4927 return apply_save_autostash_ref(r, refname, 1,
4928 label_ours, label_theirs, label_base,
4929 stash_msg);
4930 }
4931
4932 static int checkout_onto(struct repository *r, struct replay_opts *opts,
4933 const char *onto_name, const struct object_id *onto,
4934 const struct object_id *orig_head)
4935 {
4936 struct reset_working_tree_options ropts = {
4937 .oid = onto,
4938 .orig_head = orig_head,
4939 .flags = RESET_WORKING_TREE_DETACH |
4940 RESET_WORKING_TREE_UPDATE_HEAD |
4941 RESET_WORKING_TREE_UPDATE_ORIG_HEAD |
4942 RESET_WORKING_TREE_RUN_POST_CHECKOUT_HOOK,
4943 .head_msg = reflog_message(opts, "start", "checkout %s",
4944 onto_name),
4945 .default_reflog_action = sequencer_reflog_action(opts)
4946 };
4947 if (reset_working_tree(r, &ropts)) {
4948 apply_autostash(rebase_path_autostash());
4949 sequencer_remove_state(opts);
4950 return error(_("could not detach HEAD"));
4951 }
4952
4953 return 0;
4954 }
4955
4956 static int stopped_at_head(struct repository *r)
4957 {
4958 struct object_id head;
4959 struct commit *commit;
4960 struct commit_message message;
4961
4962 if (repo_get_oid(r, "HEAD", &head) ||
4963 !(commit = lookup_commit(r, &head)) ||
4964 repo_parse_commit(r, commit) || get_message(commit, &message))
4965 fprintf(stderr, _("Stopped at HEAD\n"));
4966 else {
4967 fprintf(stderr, _("Stopped at %s\n"), message.label);
4968 free_message(commit, &message);
4969 }
4970 return 0;
4971
4972 }
4973
4974 static int reread_todo_if_changed(struct repository *r,
4975 struct todo_list *todo_list,
4976 struct replay_opts *opts)
4977 {
4978 int offset;
4979 struct strbuf buf = STRBUF_INIT;
4980
4981 if (strbuf_read_file_or_whine(&buf, get_todo_path(opts)) < 0)
4982 return -1;
4983 offset = get_item_line_offset(todo_list, todo_list->current + 1);
4984 if (buf.len != todo_list->buf.len - offset ||
4985 memcmp(buf.buf, todo_list->buf.buf + offset, buf.len)) {
4986 /* Reread the todo file if it has changed. */
4987 todo_list_release(todo_list);
4988 if (read_populate_todo(r, todo_list, opts))
4989 return -1; /* message was printed */
4990 /* `current` will be incremented on return */
4991 todo_list->current = -1;
4992 }
4993 strbuf_release(&buf);
4994
4995 return 0;
4996 }
4997
4998 static const char rescheduled_advice[] =
4999 N_("Could not execute the todo command\n"
5000 "\n"
Showing first 5,000 of 7,018 lines. View raw