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