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