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