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