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