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