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