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