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