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