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