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