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