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