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