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