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