]> git.ipfire.org Git - thirdparty/git.git/blob - sequencer.c
Merge branch 'tl/notes-separator'
[thirdparty/git.git] / sequencer.c
1 #include "git-compat-util.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-ll.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 "path.h"
27 #include "revision.h"
28 #include "rerere.h"
29 #include "merge.h"
30 #include "merge-ort.h"
31 #include "merge-ort-wrappers.h"
32 #include "refs.h"
33 #include "sparse-index.h"
34 #include "strvec.h"
35 #include "quote.h"
36 #include "trailer.h"
37 #include "log-tree.h"
38 #include "wt-status.h"
39 #include "hashmap.h"
40 #include "notes-utils.h"
41 #include "sigchain.h"
42 #include "unpack-trees.h"
43 #include "worktree.h"
44 #include "oidmap.h"
45 #include "oidset.h"
46 #include "commit-slab.h"
47 #include "alias.h"
48 #include "commit-reach.h"
49 #include "rebase-interactive.h"
50 #include "reset.h"
51 #include "branch.h"
52 #include "wrapper.h"
53
54 #define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
55
56 static const char sign_off_header[] = "Signed-off-by: ";
57 static const char cherry_picked_prefix[] = "(cherry picked from commit ";
58
59 GIT_PATH_FUNC(git_path_commit_editmsg, "COMMIT_EDITMSG")
60
61 static GIT_PATH_FUNC(git_path_seq_dir, "sequencer")
62
63 static GIT_PATH_FUNC(git_path_todo_file, "sequencer/todo")
64 static GIT_PATH_FUNC(git_path_opts_file, "sequencer/opts")
65 static GIT_PATH_FUNC(git_path_head_file, "sequencer/head")
66 static GIT_PATH_FUNC(git_path_abort_safety_file, "sequencer/abort-safety")
67
68 static GIT_PATH_FUNC(rebase_path, "rebase-merge")
69 /*
70 * The file containing rebase commands, comments, and empty lines.
71 * This file is created by "git rebase -i" then edited by the user. As
72 * the lines are processed, they are removed from the front of this
73 * file and written to the tail of 'done'.
74 */
75 GIT_PATH_FUNC(rebase_path_todo, "rebase-merge/git-rebase-todo")
76 GIT_PATH_FUNC(rebase_path_todo_backup, "rebase-merge/git-rebase-todo.backup")
77
78 GIT_PATH_FUNC(rebase_path_dropped, "rebase-merge/dropped")
79
80 /*
81 * The rebase command lines that have already been processed. A line
82 * is moved here when it is first handled, before any associated user
83 * actions.
84 */
85 static GIT_PATH_FUNC(rebase_path_done, "rebase-merge/done")
86 /*
87 * The file to keep track of how many commands were already processed (e.g.
88 * for the prompt).
89 */
90 static GIT_PATH_FUNC(rebase_path_msgnum, "rebase-merge/msgnum")
91 /*
92 * The file to keep track of how many commands are to be processed in total
93 * (e.g. for the prompt).
94 */
95 static GIT_PATH_FUNC(rebase_path_msgtotal, "rebase-merge/end")
96 /*
97 * The commit message that is planned to be used for any changes that
98 * need to be committed following a user interaction.
99 */
100 static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
101 /*
102 * The file into which is accumulated the suggested commit message for
103 * squash/fixup commands. When the first of a series of squash/fixups
104 * is seen, the file is created and the commit message from the
105 * previous commit and from the first squash/fixup commit are written
106 * to it. The commit message for each subsequent squash/fixup commit
107 * is appended to the file as it is processed.
108 */
109 static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
110 /*
111 * If the current series of squash/fixups has not yet included a squash
112 * command, then this file exists and holds the commit message of the
113 * original "pick" commit. (If the series ends without a "squash"
114 * command, then this can be used as the commit message of the combined
115 * commit without opening the editor.)
116 */
117 static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
118 /*
119 * This file contains the list fixup/squash commands that have been
120 * accumulated into message-fixup or message-squash so far.
121 */
122 static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
123 /*
124 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
125 * GIT_AUTHOR_DATE that will be used for the commit that is currently
126 * being rebased.
127 */
128 static GIT_PATH_FUNC(rebase_path_author_script, "rebase-merge/author-script")
129 /*
130 * When an "edit" rebase command is being processed, the SHA1 of the
131 * commit to be edited is recorded in this file. When "git rebase
132 * --continue" is executed, if there are any staged changes then they
133 * will be amended to the HEAD commit, but only provided the HEAD
134 * commit is still the commit to be edited. When any other rebase
135 * command is processed, this file is deleted.
136 */
137 static GIT_PATH_FUNC(rebase_path_amend, "rebase-merge/amend")
138 /*
139 * When we stop at a given patch via the "edit" command, this file contains
140 * the commit object name of the corresponding patch.
141 */
142 static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
143 /*
144 * For the post-rewrite hook, we make a list of rewritten commits and
145 * their new sha1s. The rewritten-pending list keeps the sha1s of
146 * commits that have been processed, but not committed yet,
147 * e.g. because they are waiting for a 'squash' command.
148 */
149 static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
150 static GIT_PATH_FUNC(rebase_path_rewritten_pending,
151 "rebase-merge/rewritten-pending")
152
153 /*
154 * The path of the file containing the OID of the "squash onto" commit, i.e.
155 * the dummy commit used for `reset [new root]`.
156 */
157 static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
158
159 /*
160 * The path of the file listing refs that need to be deleted after the rebase
161 * finishes. This is used by the `label` command to record the need for cleanup.
162 */
163 static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
164
165 /*
166 * The update-refs file stores a list of refs that will be updated at the end
167 * of the rebase sequence. The 'update-ref <ref>' commands in the todo file
168 * update the OIDs for the refs in this file, but the refs are not updated
169 * until the end of the rebase sequence.
170 *
171 * rebase_path_update_refs() returns the path to this file for a given
172 * worktree directory. For the current worktree, pass the_repository->gitdir.
173 */
174 static char *rebase_path_update_refs(const char *wt_git_dir)
175 {
176 return xstrfmt("%s/rebase-merge/update-refs", wt_git_dir);
177 }
178
179 /*
180 * The following files are written by git-rebase just after parsing the
181 * command-line.
182 */
183 static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
184 static GIT_PATH_FUNC(rebase_path_cdate_is_adate, "rebase-merge/cdate_is_adate")
185 static GIT_PATH_FUNC(rebase_path_ignore_date, "rebase-merge/ignore_date")
186 static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
187 static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
188 static GIT_PATH_FUNC(rebase_path_quiet, "rebase-merge/quiet")
189 static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
190 static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
191 static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
192 static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
193 static GIT_PATH_FUNC(rebase_path_strategy, "rebase-merge/strategy")
194 static GIT_PATH_FUNC(rebase_path_strategy_opts, "rebase-merge/strategy_opts")
195 static GIT_PATH_FUNC(rebase_path_allow_rerere_autoupdate, "rebase-merge/allow_rerere_autoupdate")
196 static GIT_PATH_FUNC(rebase_path_reschedule_failed_exec, "rebase-merge/reschedule-failed-exec")
197 static GIT_PATH_FUNC(rebase_path_no_reschedule_failed_exec, "rebase-merge/no-reschedule-failed-exec")
198 static GIT_PATH_FUNC(rebase_path_drop_redundant_commits, "rebase-merge/drop_redundant_commits")
199 static GIT_PATH_FUNC(rebase_path_keep_redundant_commits, "rebase-merge/keep_redundant_commits")
200
201 /**
202 * A 'struct update_refs_record' represents a value in the update-refs
203 * list. We use a string_list to map refs to these (before, after) pairs.
204 */
205 struct update_ref_record {
206 struct object_id before;
207 struct object_id after;
208 };
209
210 static struct update_ref_record *init_update_ref_record(const char *ref)
211 {
212 struct update_ref_record *rec;
213
214 CALLOC_ARRAY(rec, 1);
215
216 oidcpy(&rec->before, null_oid());
217 oidcpy(&rec->after, null_oid());
218
219 /* This may fail, but that's fine, we will keep the null OID. */
220 read_ref(ref, &rec->before);
221
222 return rec;
223 }
224
225 static int git_sequencer_config(const char *k, const char *v, void *cb)
226 {
227 struct replay_opts *opts = cb;
228 int status;
229
230 if (!strcmp(k, "commit.cleanup")) {
231 const char *s;
232
233 status = git_config_string(&s, k, v);
234 if (status)
235 return status;
236
237 if (!strcmp(s, "verbatim")) {
238 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
239 opts->explicit_cleanup = 1;
240 } else if (!strcmp(s, "whitespace")) {
241 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SPACE;
242 opts->explicit_cleanup = 1;
243 } else if (!strcmp(s, "strip")) {
244 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_ALL;
245 opts->explicit_cleanup = 1;
246 } else if (!strcmp(s, "scissors")) {
247 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_SCISSORS;
248 opts->explicit_cleanup = 1;
249 } else {
250 warning(_("invalid commit message cleanup mode '%s'"),
251 s);
252 }
253
254 free((char *)s);
255 return status;
256 }
257
258 if (!strcmp(k, "commit.gpgsign")) {
259 opts->gpg_sign = git_config_bool(k, v) ? xstrdup("") : NULL;
260 return 0;
261 }
262
263 if (!opts->default_strategy && !strcmp(k, "pull.twohead")) {
264 int ret = git_config_string((const char**)&opts->default_strategy, k, v);
265 if (ret == 0) {
266 /*
267 * pull.twohead is allowed to be multi-valued; we only
268 * care about the first value.
269 */
270 char *tmp = strchr(opts->default_strategy, ' ');
271 if (tmp)
272 *tmp = '\0';
273 }
274 return ret;
275 }
276
277 if (opts->action == REPLAY_REVERT && !strcmp(k, "revert.reference"))
278 opts->commit_use_reference = git_config_bool(k, v);
279
280 return git_diff_basic_config(k, v, NULL);
281 }
282
283 void sequencer_init_config(struct replay_opts *opts)
284 {
285 opts->default_msg_cleanup = COMMIT_MSG_CLEANUP_NONE;
286 git_config(git_sequencer_config, opts);
287 }
288
289 static inline int is_rebase_i(const struct replay_opts *opts)
290 {
291 return opts->action == REPLAY_INTERACTIVE_REBASE;
292 }
293
294 static const char *get_dir(const struct replay_opts *opts)
295 {
296 if (is_rebase_i(opts))
297 return rebase_path();
298 return git_path_seq_dir();
299 }
300
301 static const char *get_todo_path(const struct replay_opts *opts)
302 {
303 if (is_rebase_i(opts))
304 return rebase_path_todo();
305 return git_path_todo_file();
306 }
307
308 /*
309 * Returns 0 for non-conforming footer
310 * Returns 1 for conforming footer
311 * Returns 2 when sob exists within conforming footer
312 * Returns 3 when sob exists within conforming footer as last entry
313 */
314 static int has_conforming_footer(struct strbuf *sb, struct strbuf *sob,
315 size_t ignore_footer)
316 {
317 struct process_trailer_options opts = PROCESS_TRAILER_OPTIONS_INIT;
318 struct trailer_info info;
319 size_t i;
320 int found_sob = 0, found_sob_last = 0;
321 char saved_char;
322
323 opts.no_divider = 1;
324
325 if (ignore_footer) {
326 saved_char = sb->buf[sb->len - ignore_footer];
327 sb->buf[sb->len - ignore_footer] = '\0';
328 }
329
330 trailer_info_get(&info, sb->buf, &opts);
331
332 if (ignore_footer)
333 sb->buf[sb->len - ignore_footer] = saved_char;
334
335 if (info.trailer_start == info.trailer_end)
336 return 0;
337
338 for (i = 0; i < info.trailer_nr; i++)
339 if (sob && !strncmp(info.trailers[i], sob->buf, sob->len)) {
340 found_sob = 1;
341 if (i == info.trailer_nr - 1)
342 found_sob_last = 1;
343 }
344
345 trailer_info_release(&info);
346
347 if (found_sob_last)
348 return 3;
349 if (found_sob)
350 return 2;
351 return 1;
352 }
353
354 static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
355 {
356 static struct strbuf buf = STRBUF_INIT;
357
358 strbuf_reset(&buf);
359 if (opts->gpg_sign)
360 sq_quotef(&buf, "-S%s", opts->gpg_sign);
361 return buf.buf;
362 }
363
364 void replay_opts_release(struct replay_opts *opts)
365 {
366 free(opts->gpg_sign);
367 free(opts->reflog_action);
368 free(opts->default_strategy);
369 free(opts->strategy);
370 strvec_clear (&opts->xopts);
371 strbuf_release(&opts->current_fixups);
372 if (opts->revs)
373 release_revisions(opts->revs);
374 free(opts->revs);
375 }
376
377 int sequencer_remove_state(struct replay_opts *opts)
378 {
379 struct strbuf buf = STRBUF_INIT;
380 int ret = 0;
381
382 if (is_rebase_i(opts) &&
383 strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
384 char *p = buf.buf;
385 while (*p) {
386 char *eol = strchr(p, '\n');
387 if (eol)
388 *eol = '\0';
389 if (delete_ref("(rebase) cleanup", p, NULL, 0) < 0) {
390 warning(_("could not delete '%s'"), p);
391 ret = -1;
392 }
393 if (!eol)
394 break;
395 p = eol + 1;
396 }
397 }
398
399 strbuf_reset(&buf);
400 strbuf_addstr(&buf, get_dir(opts));
401 if (remove_dir_recursively(&buf, 0))
402 ret = error(_("could not remove '%s'"), buf.buf);
403 strbuf_release(&buf);
404
405 return ret;
406 }
407
408 static const char *action_name(const struct replay_opts *opts)
409 {
410 switch (opts->action) {
411 case REPLAY_REVERT:
412 return N_("revert");
413 case REPLAY_PICK:
414 return N_("cherry-pick");
415 case REPLAY_INTERACTIVE_REBASE:
416 return N_("rebase");
417 }
418 die(_("unknown action: %d"), opts->action);
419 }
420
421 struct commit_message {
422 char *parent_label;
423 char *label;
424 char *subject;
425 const char *message;
426 };
427
428 static const char *short_commit_name(struct commit *commit)
429 {
430 return repo_find_unique_abbrev(the_repository, &commit->object.oid,
431 DEFAULT_ABBREV);
432 }
433
434 static int get_message(struct commit *commit, struct commit_message *out)
435 {
436 const char *abbrev, *subject;
437 int subject_len;
438
439 out->message = repo_logmsg_reencode(the_repository, commit, NULL,
440 get_commit_output_encoding());
441 abbrev = short_commit_name(commit);
442
443 subject_len = find_commit_subject(out->message, &subject);
444
445 out->subject = xmemdupz(subject, subject_len);
446 out->label = xstrfmt("%s (%s)", abbrev, out->subject);
447 out->parent_label = xstrfmt("parent of %s", out->label);
448
449 return 0;
450 }
451
452 static void free_message(struct commit *commit, struct commit_message *msg)
453 {
454 free(msg->parent_label);
455 free(msg->label);
456 free(msg->subject);
457 repo_unuse_commit_buffer(the_repository, commit, msg->message);
458 }
459
460 static void print_advice(struct repository *r, int show_hint,
461 struct replay_opts *opts)
462 {
463 char *msg = getenv("GIT_CHERRY_PICK_HELP");
464
465 if (msg) {
466 advise("%s\n", msg);
467 /*
468 * A conflict has occurred but the porcelain
469 * (typically rebase --interactive) wants to take care
470 * of the commit itself so remove CHERRY_PICK_HEAD
471 */
472 refs_delete_ref(get_main_ref_store(r), "", "CHERRY_PICK_HEAD",
473 NULL, 0);
474 return;
475 }
476
477 if (show_hint) {
478 if (opts->no_commit)
479 advise(_("after resolving the conflicts, mark the corrected paths\n"
480 "with 'git add <paths>' or 'git rm <paths>'"));
481 else if (opts->action == REPLAY_PICK)
482 advise(_("After resolving the conflicts, mark them with\n"
483 "\"git add/rm <pathspec>\", then run\n"
484 "\"git cherry-pick --continue\".\n"
485 "You can instead skip this commit with \"git cherry-pick --skip\".\n"
486 "To abort and get back to the state before \"git cherry-pick\",\n"
487 "run \"git cherry-pick --abort\"."));
488 else if (opts->action == REPLAY_REVERT)
489 advise(_("After resolving the conflicts, mark them with\n"
490 "\"git add/rm <pathspec>\", then run\n"
491 "\"git revert --continue\".\n"
492 "You can instead skip this commit with \"git revert --skip\".\n"
493 "To abort and get back to the state before \"git revert\",\n"
494 "run \"git revert --abort\"."));
495 else
496 BUG("unexpected pick action in print_advice()");
497 }
498 }
499
500 static int write_message(const void *buf, size_t len, const char *filename,
501 int append_eol)
502 {
503 struct lock_file msg_file = LOCK_INIT;
504
505 int msg_fd = hold_lock_file_for_update(&msg_file, filename, 0);
506 if (msg_fd < 0)
507 return error_errno(_("could not lock '%s'"), filename);
508 if (write_in_full(msg_fd, buf, len) < 0) {
509 error_errno(_("could not write to '%s'"), filename);
510 rollback_lock_file(&msg_file);
511 return -1;
512 }
513 if (append_eol && write(msg_fd, "\n", 1) < 0) {
514 error_errno(_("could not write eol to '%s'"), filename);
515 rollback_lock_file(&msg_file);
516 return -1;
517 }
518 if (commit_lock_file(&msg_file) < 0)
519 return error(_("failed to finalize '%s'"), filename);
520
521 return 0;
522 }
523
524 int read_oneliner(struct strbuf *buf,
525 const char *path, unsigned flags)
526 {
527 int orig_len = buf->len;
528
529 if (strbuf_read_file(buf, path, 0) < 0) {
530 if ((flags & READ_ONELINER_WARN_MISSING) ||
531 (errno != ENOENT && errno != ENOTDIR))
532 warning_errno(_("could not read '%s'"), path);
533 return 0;
534 }
535
536 if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
537 if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
538 --buf->len;
539 buf->buf[buf->len] = '\0';
540 }
541
542 if ((flags & READ_ONELINER_SKIP_IF_EMPTY) && buf->len == orig_len)
543 return 0;
544
545 return 1;
546 }
547
548 static struct tree *empty_tree(struct repository *r)
549 {
550 return lookup_tree(r, the_hash_algo->empty_tree);
551 }
552
553 static int error_dirty_index(struct repository *repo, struct replay_opts *opts)
554 {
555 if (repo_read_index_unmerged(repo))
556 return error_resolve_conflict(action_name(opts));
557
558 error(_("your local changes would be overwritten by %s."),
559 _(action_name(opts)));
560
561 if (advice_enabled(ADVICE_COMMIT_BEFORE_MERGE))
562 advise(_("commit your changes or stash them to proceed."));
563 return -1;
564 }
565
566 static void update_abort_safety_file(void)
567 {
568 struct object_id head;
569
570 /* Do nothing on a single-pick */
571 if (!file_exists(git_path_seq_dir()))
572 return;
573
574 if (!repo_get_oid(the_repository, "HEAD", &head))
575 write_file(git_path_abort_safety_file(), "%s", oid_to_hex(&head));
576 else
577 write_file(git_path_abort_safety_file(), "%s", "");
578 }
579
580 static int fast_forward_to(struct repository *r,
581 const struct object_id *to,
582 const struct object_id *from,
583 int unborn,
584 struct replay_opts *opts)
585 {
586 struct ref_transaction *transaction;
587 struct strbuf sb = STRBUF_INIT;
588 struct strbuf err = STRBUF_INIT;
589
590 repo_read_index(r);
591 if (checkout_fast_forward(r, from, to, 1))
592 return -1; /* the callee should have complained already */
593
594 strbuf_addf(&sb, "%s: fast-forward", action_name(opts));
595
596 transaction = ref_transaction_begin(&err);
597 if (!transaction ||
598 ref_transaction_update(transaction, "HEAD",
599 to, unborn && !is_rebase_i(opts) ?
600 null_oid() : from,
601 0, sb.buf, &err) ||
602 ref_transaction_commit(transaction, &err)) {
603 ref_transaction_free(transaction);
604 error("%s", err.buf);
605 strbuf_release(&sb);
606 strbuf_release(&err);
607 return -1;
608 }
609
610 strbuf_release(&sb);
611 strbuf_release(&err);
612 ref_transaction_free(transaction);
613 update_abort_safety_file();
614 return 0;
615 }
616
617 enum commit_msg_cleanup_mode get_cleanup_mode(const char *cleanup_arg,
618 int use_editor)
619 {
620 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
621 return use_editor ? COMMIT_MSG_CLEANUP_ALL :
622 COMMIT_MSG_CLEANUP_SPACE;
623 else if (!strcmp(cleanup_arg, "verbatim"))
624 return COMMIT_MSG_CLEANUP_NONE;
625 else if (!strcmp(cleanup_arg, "whitespace"))
626 return COMMIT_MSG_CLEANUP_SPACE;
627 else if (!strcmp(cleanup_arg, "strip"))
628 return COMMIT_MSG_CLEANUP_ALL;
629 else if (!strcmp(cleanup_arg, "scissors"))
630 return use_editor ? COMMIT_MSG_CLEANUP_SCISSORS :
631 COMMIT_MSG_CLEANUP_SPACE;
632 else
633 die(_("Invalid cleanup mode %s"), cleanup_arg);
634 }
635
636 /*
637 * NB using int rather than enum cleanup_mode to stop clang's
638 * -Wtautological-constant-out-of-range-compare complaining that the comparison
639 * is always true.
640 */
641 static const char *describe_cleanup_mode(int cleanup_mode)
642 {
643 static const char *modes[] = { "whitespace",
644 "verbatim",
645 "scissors",
646 "strip" };
647
648 if (cleanup_mode < ARRAY_SIZE(modes))
649 return modes[cleanup_mode];
650
651 BUG("invalid cleanup_mode provided (%d)", cleanup_mode);
652 }
653
654 void append_conflicts_hint(struct index_state *istate,
655 struct strbuf *msgbuf, enum commit_msg_cleanup_mode cleanup_mode)
656 {
657 int i;
658
659 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
660 strbuf_addch(msgbuf, '\n');
661 wt_status_append_cut_line(msgbuf);
662 strbuf_addch(msgbuf, comment_line_char);
663 }
664
665 strbuf_addch(msgbuf, '\n');
666 strbuf_commented_addf(msgbuf, comment_line_char, "Conflicts:\n");
667 for (i = 0; i < istate->cache_nr;) {
668 const struct cache_entry *ce = istate->cache[i++];
669 if (ce_stage(ce)) {
670 strbuf_commented_addf(msgbuf, comment_line_char,
671 "\t%s\n", ce->name);
672 while (i < istate->cache_nr &&
673 !strcmp(ce->name, istate->cache[i]->name))
674 i++;
675 }
676 }
677 }
678
679 static int do_recursive_merge(struct repository *r,
680 struct commit *base, struct commit *next,
681 const char *base_label, const char *next_label,
682 struct object_id *head, struct strbuf *msgbuf,
683 struct replay_opts *opts)
684 {
685 struct merge_options o;
686 struct merge_result result;
687 struct tree *next_tree, *base_tree, *head_tree;
688 int clean, show_output;
689 int i;
690 struct lock_file index_lock = LOCK_INIT;
691
692 if (repo_hold_locked_index(r, &index_lock, LOCK_REPORT_ON_ERROR) < 0)
693 return -1;
694
695 repo_read_index(r);
696
697 init_merge_options(&o, r);
698 o.ancestor = base ? base_label : "(empty tree)";
699 o.branch1 = "HEAD";
700 o.branch2 = next ? next_label : "(empty tree)";
701 if (is_rebase_i(opts))
702 o.buffer_output = 2;
703 o.show_rename_progress = 1;
704
705 head_tree = parse_tree_indirect(head);
706 next_tree = next ? repo_get_commit_tree(r, next) : empty_tree(r);
707 base_tree = base ? repo_get_commit_tree(r, base) : empty_tree(r);
708
709 for (i = 0; i < opts->xopts.nr; i++)
710 parse_merge_opt(&o, opts->xopts.v[i]);
711
712 if (!opts->strategy || !strcmp(opts->strategy, "ort")) {
713 memset(&result, 0, sizeof(result));
714 merge_incore_nonrecursive(&o, base_tree, head_tree, next_tree,
715 &result);
716 show_output = !is_rebase_i(opts) || !result.clean;
717 /*
718 * TODO: merge_switch_to_result will update index/working tree;
719 * we only really want to do that if !result.clean || this is
720 * the final patch to be picked. But determining this is the
721 * final patch would take some work, and "head_tree" would need
722 * to be replace with the tree the index matched before we
723 * started doing any picks.
724 */
725 merge_switch_to_result(&o, head_tree, &result, 1, show_output);
726 clean = result.clean;
727 } else {
728 ensure_full_index(r->index);
729 clean = merge_trees(&o, head_tree, next_tree, base_tree);
730 if (is_rebase_i(opts) && clean <= 0)
731 fputs(o.obuf.buf, stdout);
732 strbuf_release(&o.obuf);
733 }
734 if (clean < 0) {
735 rollback_lock_file(&index_lock);
736 return clean;
737 }
738
739 if (write_locked_index(r->index, &index_lock,
740 COMMIT_LOCK | SKIP_IF_UNCHANGED))
741 /*
742 * TRANSLATORS: %s will be "revert", "cherry-pick" or
743 * "rebase".
744 */
745 return error(_("%s: Unable to write new index file"),
746 _(action_name(opts)));
747
748 if (!clean)
749 append_conflicts_hint(r->index, msgbuf,
750 opts->default_msg_cleanup);
751
752 return !clean;
753 }
754
755 static struct object_id *get_cache_tree_oid(struct index_state *istate)
756 {
757 if (!cache_tree_fully_valid(istate->cache_tree))
758 if (cache_tree_update(istate, 0)) {
759 error(_("unable to update cache tree"));
760 return NULL;
761 }
762
763 return &istate->cache_tree->oid;
764 }
765
766 static int is_index_unchanged(struct repository *r)
767 {
768 struct object_id head_oid, *cache_tree_oid;
769 struct commit *head_commit;
770 struct index_state *istate = r->index;
771
772 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
773 return error(_("could not resolve HEAD commit"));
774
775 head_commit = lookup_commit(r, &head_oid);
776
777 /*
778 * If head_commit is NULL, check_commit, called from
779 * lookup_commit, would have indicated that head_commit is not
780 * a commit object already. repo_parse_commit() will return failure
781 * without further complaints in such a case. Otherwise, if
782 * the commit is invalid, repo_parse_commit() will complain. So
783 * there is nothing for us to say here. Just return failure.
784 */
785 if (repo_parse_commit(r, head_commit))
786 return -1;
787
788 if (!(cache_tree_oid = get_cache_tree_oid(istate)))
789 return -1;
790
791 return oideq(cache_tree_oid, get_commit_tree_oid(head_commit));
792 }
793
794 static int write_author_script(const char *message)
795 {
796 struct strbuf buf = STRBUF_INIT;
797 const char *eol;
798 int res;
799
800 for (;;)
801 if (!*message || starts_with(message, "\n")) {
802 missing_author:
803 /* Missing 'author' line? */
804 unlink(rebase_path_author_script());
805 return 0;
806 } else if (skip_prefix(message, "author ", &message))
807 break;
808 else if ((eol = strchr(message, '\n')))
809 message = eol + 1;
810 else
811 goto missing_author;
812
813 strbuf_addstr(&buf, "GIT_AUTHOR_NAME='");
814 while (*message && *message != '\n' && *message != '\r')
815 if (skip_prefix(message, " <", &message))
816 break;
817 else if (*message != '\'')
818 strbuf_addch(&buf, *(message++));
819 else
820 strbuf_addf(&buf, "'\\%c'", *(message++));
821 strbuf_addstr(&buf, "'\nGIT_AUTHOR_EMAIL='");
822 while (*message && *message != '\n' && *message != '\r')
823 if (skip_prefix(message, "> ", &message))
824 break;
825 else if (*message != '\'')
826 strbuf_addch(&buf, *(message++));
827 else
828 strbuf_addf(&buf, "'\\%c'", *(message++));
829 strbuf_addstr(&buf, "'\nGIT_AUTHOR_DATE='@");
830 while (*message && *message != '\n' && *message != '\r')
831 if (*message != '\'')
832 strbuf_addch(&buf, *(message++));
833 else
834 strbuf_addf(&buf, "'\\%c'", *(message++));
835 strbuf_addch(&buf, '\'');
836 res = write_message(buf.buf, buf.len, rebase_path_author_script(), 1);
837 strbuf_release(&buf);
838 return res;
839 }
840
841 /**
842 * Take a series of KEY='VALUE' lines where VALUE part is
843 * sq-quoted, and append <KEY, VALUE> at the end of the string list
844 */
845 static int parse_key_value_squoted(char *buf, struct string_list *list)
846 {
847 while (*buf) {
848 struct string_list_item *item;
849 char *np;
850 char *cp = strchr(buf, '=');
851 if (!cp) {
852 np = strchrnul(buf, '\n');
853 return error(_("no key present in '%.*s'"),
854 (int) (np - buf), buf);
855 }
856 np = strchrnul(cp, '\n');
857 *cp++ = '\0';
858 item = string_list_append(list, buf);
859
860 buf = np + (*np == '\n');
861 *np = '\0';
862 cp = sq_dequote(cp);
863 if (!cp)
864 return error(_("unable to dequote value of '%s'"),
865 item->string);
866 item->util = xstrdup(cp);
867 }
868 return 0;
869 }
870
871 /**
872 * Reads and parses the state directory's "author-script" file, and sets name,
873 * email and date accordingly.
874 * Returns 0 on success, -1 if the file could not be parsed.
875 *
876 * The author script is of the format:
877 *
878 * GIT_AUTHOR_NAME='$author_name'
879 * GIT_AUTHOR_EMAIL='$author_email'
880 * GIT_AUTHOR_DATE='$author_date'
881 *
882 * where $author_name, $author_email and $author_date are quoted. We are strict
883 * with our parsing, as the file was meant to be eval'd in the now-removed
884 * git-am.sh/git-rebase--interactive.sh scripts, and thus if the file differs
885 * from what this function expects, it is better to bail out than to do
886 * something that the user does not expect.
887 */
888 int read_author_script(const char *path, char **name, char **email, char **date,
889 int allow_missing)
890 {
891 struct strbuf buf = STRBUF_INIT;
892 struct string_list kv = STRING_LIST_INIT_DUP;
893 int retval = -1; /* assume failure */
894 int i, name_i = -2, email_i = -2, date_i = -2, err = 0;
895
896 if (strbuf_read_file(&buf, path, 256) <= 0) {
897 strbuf_release(&buf);
898 if (errno == ENOENT && allow_missing)
899 return 0;
900 else
901 return error_errno(_("could not open '%s' for reading"),
902 path);
903 }
904
905 if (parse_key_value_squoted(buf.buf, &kv))
906 goto finish;
907
908 for (i = 0; i < kv.nr; i++) {
909 if (!strcmp(kv.items[i].string, "GIT_AUTHOR_NAME")) {
910 if (name_i != -2)
911 name_i = error(_("'GIT_AUTHOR_NAME' already given"));
912 else
913 name_i = i;
914 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_EMAIL")) {
915 if (email_i != -2)
916 email_i = error(_("'GIT_AUTHOR_EMAIL' already given"));
917 else
918 email_i = i;
919 } else if (!strcmp(kv.items[i].string, "GIT_AUTHOR_DATE")) {
920 if (date_i != -2)
921 date_i = error(_("'GIT_AUTHOR_DATE' already given"));
922 else
923 date_i = i;
924 } else {
925 err = error(_("unknown variable '%s'"),
926 kv.items[i].string);
927 }
928 }
929 if (name_i == -2)
930 error(_("missing 'GIT_AUTHOR_NAME'"));
931 if (email_i == -2)
932 error(_("missing 'GIT_AUTHOR_EMAIL'"));
933 if (date_i == -2)
934 error(_("missing 'GIT_AUTHOR_DATE'"));
935 if (name_i < 0 || email_i < 0 || date_i < 0 || err)
936 goto finish;
937 *name = kv.items[name_i].util;
938 *email = kv.items[email_i].util;
939 *date = kv.items[date_i].util;
940 retval = 0;
941 finish:
942 string_list_clear(&kv, !!retval);
943 strbuf_release(&buf);
944 return retval;
945 }
946
947 /*
948 * Read a GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL AND GIT_AUTHOR_DATE from a
949 * file with shell quoting into struct strvec. Returns -1 on
950 * error, 0 otherwise.
951 */
952 static int read_env_script(struct strvec *env)
953 {
954 char *name, *email, *date;
955
956 if (read_author_script(rebase_path_author_script(),
957 &name, &email, &date, 0))
958 return -1;
959
960 strvec_pushf(env, "GIT_AUTHOR_NAME=%s", name);
961 strvec_pushf(env, "GIT_AUTHOR_EMAIL=%s", email);
962 strvec_pushf(env, "GIT_AUTHOR_DATE=%s", date);
963 free(name);
964 free(email);
965 free(date);
966
967 return 0;
968 }
969
970 static char *get_author(const char *message)
971 {
972 size_t len;
973 const char *a;
974
975 a = find_commit_header(message, "author", &len);
976 if (a)
977 return xmemdupz(a, len);
978
979 return NULL;
980 }
981
982 static const char *author_date_from_env(const struct strvec *env)
983 {
984 int i;
985 const char *date;
986
987 for (i = 0; i < env->nr; i++)
988 if (skip_prefix(env->v[i],
989 "GIT_AUTHOR_DATE=", &date))
990 return date;
991 /*
992 * If GIT_AUTHOR_DATE is missing we should have already errored out when
993 * reading the script
994 */
995 BUG("GIT_AUTHOR_DATE missing from author script");
996 }
997
998 static const char staged_changes_advice[] =
999 N_("you have staged changes in your working tree\n"
1000 "If these changes are meant to be squashed into the previous commit, run:\n"
1001 "\n"
1002 " git commit --amend %s\n"
1003 "\n"
1004 "If they are meant to go into a new commit, run:\n"
1005 "\n"
1006 " git commit %s\n"
1007 "\n"
1008 "In both cases, once you're done, continue with:\n"
1009 "\n"
1010 " git rebase --continue\n");
1011
1012 #define ALLOW_EMPTY (1<<0)
1013 #define EDIT_MSG (1<<1)
1014 #define AMEND_MSG (1<<2)
1015 #define CLEANUP_MSG (1<<3)
1016 #define VERIFY_MSG (1<<4)
1017 #define CREATE_ROOT_COMMIT (1<<5)
1018 #define VERBATIM_MSG (1<<6)
1019
1020 static int run_command_silent_on_success(struct child_process *cmd)
1021 {
1022 struct strbuf buf = STRBUF_INIT;
1023 int rc;
1024
1025 cmd->stdout_to_stderr = 1;
1026 rc = pipe_command(cmd,
1027 NULL, 0,
1028 NULL, 0,
1029 &buf, 0);
1030
1031 if (rc)
1032 fputs(buf.buf, stderr);
1033 strbuf_release(&buf);
1034 return rc;
1035 }
1036
1037 /*
1038 * If we are cherry-pick, and if the merge did not result in
1039 * hand-editing, we will hit this commit and inherit the original
1040 * author date and name.
1041 *
1042 * If we are revert, or if our cherry-pick results in a hand merge,
1043 * we had better say that the current user is responsible for that.
1044 *
1045 * An exception is when run_git_commit() is called during an
1046 * interactive rebase: in that case, we will want to retain the
1047 * author metadata.
1048 */
1049 static int run_git_commit(const char *defmsg,
1050 struct replay_opts *opts,
1051 unsigned int flags)
1052 {
1053 struct child_process cmd = CHILD_PROCESS_INIT;
1054
1055 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1056 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1057
1058 cmd.git_cmd = 1;
1059
1060 if (is_rebase_i(opts) &&
1061 ((opts->committer_date_is_author_date && !opts->ignore_date) ||
1062 !(!defmsg && (flags & AMEND_MSG))) &&
1063 read_env_script(&cmd.env)) {
1064 const char *gpg_opt = gpg_sign_opt_quoted(opts);
1065
1066 return error(_(staged_changes_advice),
1067 gpg_opt, gpg_opt);
1068 }
1069
1070 strvec_pushf(&cmd.env, GIT_REFLOG_ACTION "=%s", opts->reflog_message);
1071
1072 if (opts->committer_date_is_author_date)
1073 strvec_pushf(&cmd.env, "GIT_COMMITTER_DATE=%s",
1074 opts->ignore_date ?
1075 "" :
1076 author_date_from_env(&cmd.env));
1077 if (opts->ignore_date)
1078 strvec_push(&cmd.env, "GIT_AUTHOR_DATE=");
1079
1080 strvec_push(&cmd.args, "commit");
1081
1082 if (!(flags & VERIFY_MSG))
1083 strvec_push(&cmd.args, "-n");
1084 if ((flags & AMEND_MSG))
1085 strvec_push(&cmd.args, "--amend");
1086 if (opts->gpg_sign)
1087 strvec_pushf(&cmd.args, "-S%s", opts->gpg_sign);
1088 else
1089 strvec_push(&cmd.args, "--no-gpg-sign");
1090 if (defmsg)
1091 strvec_pushl(&cmd.args, "-F", defmsg, NULL);
1092 else if (!(flags & EDIT_MSG))
1093 strvec_pushl(&cmd.args, "-C", "HEAD", NULL);
1094 if ((flags & CLEANUP_MSG))
1095 strvec_push(&cmd.args, "--cleanup=strip");
1096 if ((flags & VERBATIM_MSG))
1097 strvec_push(&cmd.args, "--cleanup=verbatim");
1098 if ((flags & EDIT_MSG))
1099 strvec_push(&cmd.args, "-e");
1100 else if (!(flags & CLEANUP_MSG) &&
1101 !opts->signoff && !opts->record_origin &&
1102 !opts->explicit_cleanup)
1103 strvec_push(&cmd.args, "--cleanup=verbatim");
1104
1105 if ((flags & ALLOW_EMPTY))
1106 strvec_push(&cmd.args, "--allow-empty");
1107
1108 if (!(flags & EDIT_MSG))
1109 strvec_push(&cmd.args, "--allow-empty-message");
1110
1111 if (is_rebase_i(opts) && !(flags & EDIT_MSG))
1112 return run_command_silent_on_success(&cmd);
1113 else
1114 return run_command(&cmd);
1115 }
1116
1117 static int rest_is_empty(const struct strbuf *sb, int start)
1118 {
1119 int i, eol;
1120 const char *nl;
1121
1122 /* Check if the rest is just whitespace and Signed-off-by's. */
1123 for (i = start; i < sb->len; i++) {
1124 nl = memchr(sb->buf + i, '\n', sb->len - i);
1125 if (nl)
1126 eol = nl - sb->buf;
1127 else
1128 eol = sb->len;
1129
1130 if (strlen(sign_off_header) <= eol - i &&
1131 starts_with(sb->buf + i, sign_off_header)) {
1132 i = eol;
1133 continue;
1134 }
1135 while (i < eol)
1136 if (!isspace(sb->buf[i++]))
1137 return 0;
1138 }
1139
1140 return 1;
1141 }
1142
1143 void cleanup_message(struct strbuf *msgbuf,
1144 enum commit_msg_cleanup_mode cleanup_mode, int verbose)
1145 {
1146 if (verbose || /* Truncate the message just before the diff, if any. */
1147 cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
1148 strbuf_setlen(msgbuf, wt_status_locate_end(msgbuf->buf, msgbuf->len));
1149 if (cleanup_mode != COMMIT_MSG_CLEANUP_NONE)
1150 strbuf_stripspace(msgbuf,
1151 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1152 }
1153
1154 /*
1155 * Find out if the message in the strbuf contains only whitespace and
1156 * Signed-off-by lines.
1157 */
1158 int message_is_empty(const struct strbuf *sb,
1159 enum commit_msg_cleanup_mode cleanup_mode)
1160 {
1161 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1162 return 0;
1163 return rest_is_empty(sb, 0);
1164 }
1165
1166 /*
1167 * See if the user edited the message in the editor or left what
1168 * was in the template intact
1169 */
1170 int template_untouched(const struct strbuf *sb, const char *template_file,
1171 enum commit_msg_cleanup_mode cleanup_mode)
1172 {
1173 struct strbuf tmpl = STRBUF_INIT;
1174 const char *start;
1175
1176 if (cleanup_mode == COMMIT_MSG_CLEANUP_NONE && sb->len)
1177 return 0;
1178
1179 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1180 return 0;
1181
1182 strbuf_stripspace(&tmpl,
1183 cleanup_mode == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1184 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1185 start = sb->buf;
1186 strbuf_release(&tmpl);
1187 return rest_is_empty(sb, start - sb->buf);
1188 }
1189
1190 int update_head_with_reflog(const struct commit *old_head,
1191 const struct object_id *new_head,
1192 const char *action, const struct strbuf *msg,
1193 struct strbuf *err)
1194 {
1195 struct ref_transaction *transaction;
1196 struct strbuf sb = STRBUF_INIT;
1197 const char *nl;
1198 int ret = 0;
1199
1200 if (action) {
1201 strbuf_addstr(&sb, action);
1202 strbuf_addstr(&sb, ": ");
1203 }
1204
1205 nl = strchr(msg->buf, '\n');
1206 if (nl) {
1207 strbuf_add(&sb, msg->buf, nl + 1 - msg->buf);
1208 } else {
1209 strbuf_addbuf(&sb, msg);
1210 strbuf_addch(&sb, '\n');
1211 }
1212
1213 transaction = ref_transaction_begin(err);
1214 if (!transaction ||
1215 ref_transaction_update(transaction, "HEAD", new_head,
1216 old_head ? &old_head->object.oid : null_oid(),
1217 0, sb.buf, err) ||
1218 ref_transaction_commit(transaction, err)) {
1219 ret = -1;
1220 }
1221 ref_transaction_free(transaction);
1222 strbuf_release(&sb);
1223
1224 return ret;
1225 }
1226
1227 static int run_rewrite_hook(const struct object_id *oldoid,
1228 const struct object_id *newoid)
1229 {
1230 struct child_process proc = CHILD_PROCESS_INIT;
1231 int code;
1232 struct strbuf sb = STRBUF_INIT;
1233 const char *hook_path = find_hook("post-rewrite");
1234
1235 if (!hook_path)
1236 return 0;
1237
1238 strvec_pushl(&proc.args, hook_path, "amend", NULL);
1239 proc.in = -1;
1240 proc.stdout_to_stderr = 1;
1241 proc.trace2_hook_name = "post-rewrite";
1242
1243 code = start_command(&proc);
1244 if (code)
1245 return code;
1246 strbuf_addf(&sb, "%s %s\n", oid_to_hex(oldoid), oid_to_hex(newoid));
1247 sigchain_push(SIGPIPE, SIG_IGN);
1248 write_in_full(proc.in, sb.buf, sb.len);
1249 close(proc.in);
1250 strbuf_release(&sb);
1251 sigchain_pop(SIGPIPE);
1252 return finish_command(&proc);
1253 }
1254
1255 void commit_post_rewrite(struct repository *r,
1256 const struct commit *old_head,
1257 const struct object_id *new_head)
1258 {
1259 struct notes_rewrite_cfg *cfg;
1260
1261 cfg = init_copy_notes_for_rewrite("amend");
1262 if (cfg) {
1263 /* we are amending, so old_head is not NULL */
1264 copy_note_for_rewrite(cfg, &old_head->object.oid, new_head);
1265 finish_copy_notes_for_rewrite(r, cfg, "Notes added by 'git commit --amend'");
1266 }
1267 run_rewrite_hook(&old_head->object.oid, new_head);
1268 }
1269
1270 static int run_prepare_commit_msg_hook(struct repository *r,
1271 struct strbuf *msg,
1272 const char *commit)
1273 {
1274 int ret = 0;
1275 const char *name, *arg1 = NULL, *arg2 = NULL;
1276
1277 name = git_path_commit_editmsg();
1278 if (write_message(msg->buf, msg->len, name, 0))
1279 return -1;
1280
1281 if (commit) {
1282 arg1 = "commit";
1283 arg2 = commit;
1284 } else {
1285 arg1 = "message";
1286 }
1287 if (run_commit_hook(0, r->index_file, NULL, "prepare-commit-msg", name,
1288 arg1, arg2, NULL))
1289 ret = error(_("'prepare-commit-msg' hook failed"));
1290
1291 return ret;
1292 }
1293
1294 static const char implicit_ident_advice_noconfig[] =
1295 N_("Your name and email address were configured automatically based\n"
1296 "on your username and hostname. Please check that they are accurate.\n"
1297 "You can suppress this message by setting them explicitly. Run the\n"
1298 "following command and follow the instructions in your editor to edit\n"
1299 "your configuration file:\n"
1300 "\n"
1301 " git config --global --edit\n"
1302 "\n"
1303 "After doing this, you may fix the identity used for this commit with:\n"
1304 "\n"
1305 " git commit --amend --reset-author\n");
1306
1307 static const char implicit_ident_advice_config[] =
1308 N_("Your name and email address were configured automatically based\n"
1309 "on your username and hostname. Please check that they are accurate.\n"
1310 "You can suppress this message by setting them explicitly:\n"
1311 "\n"
1312 " git config --global user.name \"Your Name\"\n"
1313 " git config --global user.email you@example.com\n"
1314 "\n"
1315 "After doing this, you may fix the identity used for this commit with:\n"
1316 "\n"
1317 " git commit --amend --reset-author\n");
1318
1319 static const char *implicit_ident_advice(void)
1320 {
1321 char *user_config = interpolate_path("~/.gitconfig", 0);
1322 char *xdg_config = xdg_config_home("config");
1323 int config_exists = file_exists(user_config) || file_exists(xdg_config);
1324
1325 free(user_config);
1326 free(xdg_config);
1327
1328 if (config_exists)
1329 return _(implicit_ident_advice_config);
1330 else
1331 return _(implicit_ident_advice_noconfig);
1332
1333 }
1334
1335 void print_commit_summary(struct repository *r,
1336 const char *prefix,
1337 const struct object_id *oid,
1338 unsigned int flags)
1339 {
1340 struct rev_info rev;
1341 struct commit *commit;
1342 struct strbuf format = STRBUF_INIT;
1343 const char *head;
1344 struct pretty_print_context pctx = {0};
1345 struct strbuf author_ident = STRBUF_INIT;
1346 struct strbuf committer_ident = STRBUF_INIT;
1347 struct ref_store *refs;
1348
1349 commit = lookup_commit(r, oid);
1350 if (!commit)
1351 die(_("couldn't look up newly created commit"));
1352 if (repo_parse_commit(r, commit))
1353 die(_("could not parse newly created commit"));
1354
1355 strbuf_addstr(&format, "format:%h] %s");
1356
1357 repo_format_commit_message(r, commit, "%an <%ae>", &author_ident,
1358 &pctx);
1359 repo_format_commit_message(r, commit, "%cn <%ce>", &committer_ident,
1360 &pctx);
1361 if (strbuf_cmp(&author_ident, &committer_ident)) {
1362 strbuf_addstr(&format, "\n Author: ");
1363 strbuf_addbuf_percentquote(&format, &author_ident);
1364 }
1365 if (flags & SUMMARY_SHOW_AUTHOR_DATE) {
1366 struct strbuf date = STRBUF_INIT;
1367
1368 repo_format_commit_message(r, commit, "%ad", &date, &pctx);
1369 strbuf_addstr(&format, "\n Date: ");
1370 strbuf_addbuf_percentquote(&format, &date);
1371 strbuf_release(&date);
1372 }
1373 if (!committer_ident_sufficiently_given()) {
1374 strbuf_addstr(&format, "\n Committer: ");
1375 strbuf_addbuf_percentquote(&format, &committer_ident);
1376 if (advice_enabled(ADVICE_IMPLICIT_IDENTITY)) {
1377 strbuf_addch(&format, '\n');
1378 strbuf_addstr(&format, implicit_ident_advice());
1379 }
1380 }
1381 strbuf_release(&author_ident);
1382 strbuf_release(&committer_ident);
1383
1384 repo_init_revisions(r, &rev, prefix);
1385 setup_revisions(0, NULL, &rev, NULL);
1386
1387 rev.diff = 1;
1388 rev.diffopt.output_format =
1389 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1390
1391 rev.verbose_header = 1;
1392 rev.show_root_diff = 1;
1393 get_commit_format(format.buf, &rev);
1394 rev.always_show_header = 0;
1395 rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
1396 diff_setup_done(&rev.diffopt);
1397
1398 refs = get_main_ref_store(r);
1399 head = refs_resolve_ref_unsafe(refs, "HEAD", 0, NULL, NULL);
1400 if (!head)
1401 die(_("unable to resolve HEAD after creating commit"));
1402 if (!strcmp(head, "HEAD"))
1403 head = _("detached HEAD");
1404 else
1405 skip_prefix(head, "refs/heads/", &head);
1406 printf("[%s%s ", head, (flags & SUMMARY_INITIAL_COMMIT) ?
1407 _(" (root-commit)") : "");
1408
1409 if (!log_tree_commit(&rev, commit)) {
1410 rev.always_show_header = 1;
1411 rev.use_terminator = 1;
1412 log_tree_commit(&rev, commit);
1413 }
1414
1415 release_revisions(&rev);
1416 strbuf_release(&format);
1417 }
1418
1419 static int parse_head(struct repository *r, struct commit **head)
1420 {
1421 struct commit *current_head;
1422 struct object_id oid;
1423
1424 if (repo_get_oid(r, "HEAD", &oid)) {
1425 current_head = NULL;
1426 } else {
1427 current_head = lookup_commit_reference(r, &oid);
1428 if (!current_head)
1429 return error(_("could not parse HEAD"));
1430 if (!oideq(&oid, &current_head->object.oid)) {
1431 warning(_("HEAD %s is not a commit!"),
1432 oid_to_hex(&oid));
1433 }
1434 if (repo_parse_commit(r, current_head))
1435 return error(_("could not parse HEAD commit"));
1436 }
1437 *head = current_head;
1438
1439 return 0;
1440 }
1441
1442 /*
1443 * Try to commit without forking 'git commit'. In some cases we need
1444 * to run 'git commit' to display an error message
1445 *
1446 * Returns:
1447 * -1 - error unable to commit
1448 * 0 - success
1449 * 1 - run 'git commit'
1450 */
1451 static int try_to_commit(struct repository *r,
1452 struct strbuf *msg, const char *author,
1453 struct replay_opts *opts, unsigned int flags,
1454 struct object_id *oid)
1455 {
1456 struct object_id tree;
1457 struct commit *current_head = NULL;
1458 struct commit_list *parents = NULL;
1459 struct commit_extra_header *extra = NULL;
1460 struct strbuf err = STRBUF_INIT;
1461 struct strbuf commit_msg = STRBUF_INIT;
1462 char *amend_author = NULL;
1463 const char *committer = NULL;
1464 const char *hook_commit = NULL;
1465 enum commit_msg_cleanup_mode cleanup;
1466 int res = 0;
1467
1468 if ((flags & CLEANUP_MSG) && (flags & VERBATIM_MSG))
1469 BUG("CLEANUP_MSG and VERBATIM_MSG are mutually exclusive");
1470
1471 if (parse_head(r, &current_head))
1472 return -1;
1473
1474 if (flags & AMEND_MSG) {
1475 const char *exclude_gpgsig[] = { "gpgsig", "gpgsig-sha256", NULL };
1476 const char *out_enc = get_commit_output_encoding();
1477 const char *message = repo_logmsg_reencode(r, current_head,
1478 NULL, out_enc);
1479
1480 if (!msg) {
1481 const char *orig_message = NULL;
1482
1483 find_commit_subject(message, &orig_message);
1484 msg = &commit_msg;
1485 strbuf_addstr(msg, orig_message);
1486 hook_commit = "HEAD";
1487 }
1488 author = amend_author = get_author(message);
1489 repo_unuse_commit_buffer(r, current_head,
1490 message);
1491 if (!author) {
1492 res = error(_("unable to parse commit author"));
1493 goto out;
1494 }
1495 parents = copy_commit_list(current_head->parents);
1496 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1497 } else if (current_head &&
1498 (!(flags & CREATE_ROOT_COMMIT) || (flags & AMEND_MSG))) {
1499 commit_list_insert(current_head, &parents);
1500 }
1501
1502 if (write_index_as_tree(&tree, r->index, r->index_file, 0, NULL)) {
1503 res = error(_("git write-tree failed to write a tree"));
1504 goto out;
1505 }
1506
1507 if (!(flags & ALLOW_EMPTY)) {
1508 struct commit *first_parent = current_head;
1509
1510 if (flags & AMEND_MSG) {
1511 if (current_head->parents) {
1512 first_parent = current_head->parents->item;
1513 if (repo_parse_commit(r, first_parent)) {
1514 res = error(_("could not parse HEAD commit"));
1515 goto out;
1516 }
1517 } else {
1518 first_parent = NULL;
1519 }
1520 }
1521 if (oideq(first_parent
1522 ? get_commit_tree_oid(first_parent)
1523 : the_hash_algo->empty_tree,
1524 &tree)) {
1525 res = 1; /* run 'git commit' to display error message */
1526 goto out;
1527 }
1528 }
1529
1530 if (hook_exists("prepare-commit-msg")) {
1531 res = run_prepare_commit_msg_hook(r, msg, hook_commit);
1532 if (res)
1533 goto out;
1534 if (strbuf_read_file(&commit_msg, git_path_commit_editmsg(),
1535 2048) < 0) {
1536 res = error_errno(_("unable to read commit message "
1537 "from '%s'"),
1538 git_path_commit_editmsg());
1539 goto out;
1540 }
1541 msg = &commit_msg;
1542 }
1543
1544 if (flags & CLEANUP_MSG)
1545 cleanup = COMMIT_MSG_CLEANUP_ALL;
1546 else if (flags & VERBATIM_MSG)
1547 cleanup = COMMIT_MSG_CLEANUP_NONE;
1548 else if ((opts->signoff || opts->record_origin) &&
1549 !opts->explicit_cleanup)
1550 cleanup = COMMIT_MSG_CLEANUP_SPACE;
1551 else
1552 cleanup = opts->default_msg_cleanup;
1553
1554 if (cleanup != COMMIT_MSG_CLEANUP_NONE)
1555 strbuf_stripspace(msg,
1556 cleanup == COMMIT_MSG_CLEANUP_ALL ? comment_line_char : '\0');
1557 if ((flags & EDIT_MSG) && message_is_empty(msg, cleanup)) {
1558 res = 1; /* run 'git commit' to display error message */
1559 goto out;
1560 }
1561
1562 if (opts->committer_date_is_author_date) {
1563 struct ident_split id;
1564 struct strbuf date = STRBUF_INIT;
1565
1566 if (!opts->ignore_date) {
1567 if (split_ident_line(&id, author, (int)strlen(author)) < 0) {
1568 res = error(_("invalid author identity '%s'"),
1569 author);
1570 goto out;
1571 }
1572 if (!id.date_begin) {
1573 res = error(_(
1574 "corrupt author: missing date information"));
1575 goto out;
1576 }
1577 strbuf_addf(&date, "@%.*s %.*s",
1578 (int)(id.date_end - id.date_begin),
1579 id.date_begin,
1580 (int)(id.tz_end - id.tz_begin),
1581 id.tz_begin);
1582 } else {
1583 reset_ident_date();
1584 }
1585 committer = fmt_ident(getenv("GIT_COMMITTER_NAME"),
1586 getenv("GIT_COMMITTER_EMAIL"),
1587 WANT_COMMITTER_IDENT,
1588 opts->ignore_date ? NULL : date.buf,
1589 IDENT_STRICT);
1590 strbuf_release(&date);
1591 } else {
1592 reset_ident_date();
1593 }
1594
1595 if (opts->ignore_date) {
1596 struct ident_split id;
1597 char *name, *email;
1598
1599 if (split_ident_line(&id, author, strlen(author)) < 0) {
1600 error(_("invalid author identity '%s'"), author);
1601 goto out;
1602 }
1603 name = xmemdupz(id.name_begin, id.name_end - id.name_begin);
1604 email = xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
1605 author = fmt_ident(name, email, WANT_AUTHOR_IDENT, NULL,
1606 IDENT_STRICT);
1607 free(name);
1608 free(email);
1609 }
1610
1611 if (commit_tree_extended(msg->buf, msg->len, &tree, parents, oid,
1612 author, committer, opts->gpg_sign, extra)) {
1613 res = error(_("failed to write commit object"));
1614 goto out;
1615 }
1616
1617 if (update_head_with_reflog(current_head, oid, opts->reflog_message,
1618 msg, &err)) {
1619 res = error("%s", err.buf);
1620 goto out;
1621 }
1622
1623 run_commit_hook(0, r->index_file, NULL, "post-commit", NULL);
1624 if (flags & AMEND_MSG)
1625 commit_post_rewrite(r, current_head, oid);
1626
1627 out:
1628 free_commit_extra_headers(extra);
1629 strbuf_release(&err);
1630 strbuf_release(&commit_msg);
1631 free(amend_author);
1632
1633 return res;
1634 }
1635
1636 static int write_rebase_head(struct object_id *oid)
1637 {
1638 if (update_ref("rebase", "REBASE_HEAD", oid,
1639 NULL, REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR))
1640 return error(_("could not update %s"), "REBASE_HEAD");
1641
1642 return 0;
1643 }
1644
1645 static int do_commit(struct repository *r,
1646 const char *msg_file, const char *author,
1647 struct replay_opts *opts, unsigned int flags,
1648 struct object_id *oid)
1649 {
1650 int res = 1;
1651
1652 if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
1653 struct object_id oid;
1654 struct strbuf sb = STRBUF_INIT;
1655
1656 if (msg_file && strbuf_read_file(&sb, msg_file, 2048) < 0)
1657 return error_errno(_("unable to read commit message "
1658 "from '%s'"),
1659 msg_file);
1660
1661 res = try_to_commit(r, msg_file ? &sb : NULL,
1662 author, opts, flags, &oid);
1663 strbuf_release(&sb);
1664 if (!res) {
1665 refs_delete_ref(get_main_ref_store(r), "",
1666 "CHERRY_PICK_HEAD", NULL, 0);
1667 unlink(git_path_merge_msg(r));
1668 if (!is_rebase_i(opts))
1669 print_commit_summary(r, NULL, &oid,
1670 SUMMARY_SHOW_AUTHOR_DATE);
1671 return res;
1672 }
1673 }
1674 if (res == 1) {
1675 if (is_rebase_i(opts) && oid)
1676 if (write_rebase_head(oid))
1677 return -1;
1678 return run_git_commit(msg_file, opts, flags);
1679 }
1680
1681 return res;
1682 }
1683
1684 static int is_original_commit_empty(struct commit *commit)
1685 {
1686 const struct object_id *ptree_oid;
1687
1688 if (repo_parse_commit(the_repository, commit))
1689 return error(_("could not parse commit %s"),
1690 oid_to_hex(&commit->object.oid));
1691 if (commit->parents) {
1692 struct commit *parent = commit->parents->item;
1693 if (repo_parse_commit(the_repository, parent))
1694 return error(_("could not parse parent commit %s"),
1695 oid_to_hex(&parent->object.oid));
1696 ptree_oid = get_commit_tree_oid(parent);
1697 } else {
1698 ptree_oid = the_hash_algo->empty_tree; /* commit is root */
1699 }
1700
1701 return oideq(ptree_oid, get_commit_tree_oid(commit));
1702 }
1703
1704 /*
1705 * Should empty commits be allowed? Return status:
1706 * <0: Error in is_index_unchanged(r) or is_original_commit_empty(commit)
1707 * 0: Halt on empty commit
1708 * 1: Allow empty commit
1709 * 2: Drop empty commit
1710 */
1711 static int allow_empty(struct repository *r,
1712 struct replay_opts *opts,
1713 struct commit *commit)
1714 {
1715 int index_unchanged, originally_empty;
1716
1717 /*
1718 * Four cases:
1719 *
1720 * (1) we do not allow empty at all and error out.
1721 *
1722 * (2) we allow ones that were initially empty, and
1723 * just drop the ones that become empty
1724 *
1725 * (3) we allow ones that were initially empty, but
1726 * halt for the ones that become empty;
1727 *
1728 * (4) we allow both.
1729 */
1730 if (!opts->allow_empty)
1731 return 0; /* let "git commit" barf as necessary */
1732
1733 index_unchanged = is_index_unchanged(r);
1734 if (index_unchanged < 0)
1735 return index_unchanged;
1736 if (!index_unchanged)
1737 return 0; /* we do not have to say --allow-empty */
1738
1739 if (opts->keep_redundant_commits)
1740 return 1;
1741
1742 originally_empty = is_original_commit_empty(commit);
1743 if (originally_empty < 0)
1744 return originally_empty;
1745 if (originally_empty)
1746 return 1;
1747 else if (opts->drop_redundant_commits)
1748 return 2;
1749 else
1750 return 0;
1751 }
1752
1753 static struct {
1754 char c;
1755 const char *str;
1756 } todo_command_info[] = {
1757 [TODO_PICK] = { 'p', "pick" },
1758 [TODO_REVERT] = { 0, "revert" },
1759 [TODO_EDIT] = { 'e', "edit" },
1760 [TODO_REWORD] = { 'r', "reword" },
1761 [TODO_FIXUP] = { 'f', "fixup" },
1762 [TODO_SQUASH] = { 's', "squash" },
1763 [TODO_EXEC] = { 'x', "exec" },
1764 [TODO_BREAK] = { 'b', "break" },
1765 [TODO_LABEL] = { 'l', "label" },
1766 [TODO_RESET] = { 't', "reset" },
1767 [TODO_MERGE] = { 'm', "merge" },
1768 [TODO_UPDATE_REF] = { 'u', "update-ref" },
1769 [TODO_NOOP] = { 0, "noop" },
1770 [TODO_DROP] = { 'd', "drop" },
1771 [TODO_COMMENT] = { 0, NULL },
1772 };
1773
1774 static const char *command_to_string(const enum todo_command command)
1775 {
1776 if (command < TODO_COMMENT)
1777 return todo_command_info[command].str;
1778 die(_("unknown command: %d"), command);
1779 }
1780
1781 static char command_to_char(const enum todo_command command)
1782 {
1783 if (command < TODO_COMMENT)
1784 return todo_command_info[command].c;
1785 return comment_line_char;
1786 }
1787
1788 static int is_noop(const enum todo_command command)
1789 {
1790 return TODO_NOOP <= command;
1791 }
1792
1793 static int is_fixup(enum todo_command command)
1794 {
1795 return command == TODO_FIXUP || command == TODO_SQUASH;
1796 }
1797
1798 /* Does this command create a (non-merge) commit? */
1799 static int is_pick_or_similar(enum todo_command command)
1800 {
1801 switch (command) {
1802 case TODO_PICK:
1803 case TODO_REVERT:
1804 case TODO_EDIT:
1805 case TODO_REWORD:
1806 case TODO_FIXUP:
1807 case TODO_SQUASH:
1808 return 1;
1809 default:
1810 return 0;
1811 }
1812 }
1813
1814 enum todo_item_flags {
1815 TODO_EDIT_MERGE_MSG = (1 << 0),
1816 TODO_REPLACE_FIXUP_MSG = (1 << 1),
1817 TODO_EDIT_FIXUP_MSG = (1 << 2),
1818 };
1819
1820 static const char first_commit_msg_str[] = N_("This is the 1st commit message:");
1821 static const char nth_commit_msg_fmt[] = N_("This is the commit message #%d:");
1822 static const char skip_first_commit_msg_str[] = N_("The 1st commit message will be skipped:");
1823 static const char skip_nth_commit_msg_fmt[] = N_("The commit message #%d will be skipped:");
1824 static const char combined_commit_msg_fmt[] = N_("This is a combination of %d commits.");
1825
1826 static int is_fixup_flag(enum todo_command command, unsigned flag)
1827 {
1828 return command == TODO_FIXUP && ((flag & TODO_REPLACE_FIXUP_MSG) ||
1829 (flag & TODO_EDIT_FIXUP_MSG));
1830 }
1831
1832 /*
1833 * Wrapper around strbuf_add_commented_lines() which avoids double
1834 * commenting commit subjects.
1835 */
1836 static void add_commented_lines(struct strbuf *buf, const void *str, size_t len)
1837 {
1838 const char *s = str;
1839 while (len > 0 && s[0] == comment_line_char) {
1840 size_t count;
1841 const char *n = memchr(s, '\n', len);
1842 if (!n)
1843 count = len;
1844 else
1845 count = n - s + 1;
1846 strbuf_add(buf, s, count);
1847 s += count;
1848 len -= count;
1849 }
1850 strbuf_add_commented_lines(buf, s, len, comment_line_char);
1851 }
1852
1853 /* Does the current fixup chain contain a squash command? */
1854 static int seen_squash(struct replay_opts *opts)
1855 {
1856 return starts_with(opts->current_fixups.buf, "squash") ||
1857 strstr(opts->current_fixups.buf, "\nsquash");
1858 }
1859
1860 static void update_comment_bufs(struct strbuf *buf1, struct strbuf *buf2, int n)
1861 {
1862 strbuf_setlen(buf1, 2);
1863 strbuf_addf(buf1, _(nth_commit_msg_fmt), n);
1864 strbuf_addch(buf1, '\n');
1865 strbuf_setlen(buf2, 2);
1866 strbuf_addf(buf2, _(skip_nth_commit_msg_fmt), n);
1867 strbuf_addch(buf2, '\n');
1868 }
1869
1870 /*
1871 * Comment out any un-commented commit messages, updating the message comments
1872 * to say they will be skipped but do not comment out the empty lines that
1873 * surround commit messages and their comments.
1874 */
1875 static void update_squash_message_for_fixup(struct strbuf *msg)
1876 {
1877 void (*copy_lines)(struct strbuf *, const void *, size_t) = strbuf_add;
1878 struct strbuf buf1 = STRBUF_INIT, buf2 = STRBUF_INIT;
1879 const char *s, *start;
1880 char *orig_msg;
1881 size_t orig_msg_len;
1882 int i = 1;
1883
1884 strbuf_addf(&buf1, "# %s\n", _(first_commit_msg_str));
1885 strbuf_addf(&buf2, "# %s\n", _(skip_first_commit_msg_str));
1886 s = start = orig_msg = strbuf_detach(msg, &orig_msg_len);
1887 while (s) {
1888 const char *next;
1889 size_t off;
1890 if (skip_prefix(s, buf1.buf, &next)) {
1891 /*
1892 * Copy the last message, preserving the blank line
1893 * preceding the current line
1894 */
1895 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1896 copy_lines(msg, start, s - start - off);
1897 if (off)
1898 strbuf_addch(msg, '\n');
1899 /*
1900 * The next message needs to be commented out but the
1901 * message header is already commented out so just copy
1902 * it and the blank line that follows it.
1903 */
1904 strbuf_addbuf(msg, &buf2);
1905 if (*next == '\n')
1906 strbuf_addch(msg, *next++);
1907 start = s = next;
1908 copy_lines = add_commented_lines;
1909 update_comment_bufs(&buf1, &buf2, ++i);
1910 } else if (skip_prefix(s, buf2.buf, &next)) {
1911 off = (s > start + 1 && s[-2] == '\n') ? 1 : 0;
1912 copy_lines(msg, start, s - start - off);
1913 start = s - off;
1914 s = next;
1915 copy_lines = strbuf_add;
1916 update_comment_bufs(&buf1, &buf2, ++i);
1917 } else {
1918 s = strchr(s, '\n');
1919 if (s)
1920 s++;
1921 }
1922 }
1923 copy_lines(msg, start, orig_msg_len - (start - orig_msg));
1924 free(orig_msg);
1925 strbuf_release(&buf1);
1926 strbuf_release(&buf2);
1927 }
1928
1929 static int append_squash_message(struct strbuf *buf, const char *body,
1930 enum todo_command command, struct replay_opts *opts,
1931 unsigned flag)
1932 {
1933 const char *fixup_msg;
1934 size_t commented_len = 0, fixup_off;
1935 /*
1936 * amend is non-interactive and not normally used with fixup!
1937 * or squash! commits, so only comment out those subjects when
1938 * squashing commit messages.
1939 */
1940 if (starts_with(body, "amend!") ||
1941 ((command == TODO_SQUASH || seen_squash(opts)) &&
1942 (starts_with(body, "squash!") || starts_with(body, "fixup!"))))
1943 commented_len = commit_subject_length(body);
1944
1945 strbuf_addf(buf, "\n%c ", comment_line_char);
1946 strbuf_addf(buf, _(nth_commit_msg_fmt),
1947 ++opts->current_fixup_count + 1);
1948 strbuf_addstr(buf, "\n\n");
1949 strbuf_add_commented_lines(buf, body, commented_len, comment_line_char);
1950 /* buf->buf may be reallocated so store an offset into the buffer */
1951 fixup_off = buf->len;
1952 strbuf_addstr(buf, body + commented_len);
1953
1954 /* fixup -C after squash behaves like squash */
1955 if (is_fixup_flag(command, flag) && !seen_squash(opts)) {
1956 /*
1957 * We're replacing the commit message so we need to
1958 * append the Signed-off-by: trailer if the user
1959 * requested '--signoff'.
1960 */
1961 if (opts->signoff)
1962 append_signoff(buf, 0, 0);
1963
1964 if ((command == TODO_FIXUP) &&
1965 (flag & TODO_REPLACE_FIXUP_MSG) &&
1966 (file_exists(rebase_path_fixup_msg()) ||
1967 !file_exists(rebase_path_squash_msg()))) {
1968 fixup_msg = skip_blank_lines(buf->buf + fixup_off);
1969 if (write_message(fixup_msg, strlen(fixup_msg),
1970 rebase_path_fixup_msg(), 0) < 0)
1971 return error(_("cannot write '%s'"),
1972 rebase_path_fixup_msg());
1973 } else {
1974 unlink(rebase_path_fixup_msg());
1975 }
1976 } else {
1977 unlink(rebase_path_fixup_msg());
1978 }
1979
1980 return 0;
1981 }
1982
1983 static int update_squash_messages(struct repository *r,
1984 enum todo_command command,
1985 struct commit *commit,
1986 struct replay_opts *opts,
1987 unsigned flag)
1988 {
1989 struct strbuf buf = STRBUF_INIT;
1990 int res = 0;
1991 const char *message, *body;
1992 const char *encoding = get_commit_output_encoding();
1993
1994 if (opts->current_fixup_count > 0) {
1995 struct strbuf header = STRBUF_INIT;
1996 char *eol;
1997
1998 if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
1999 return error(_("could not read '%s'"),
2000 rebase_path_squash_msg());
2001
2002 eol = buf.buf[0] != comment_line_char ?
2003 buf.buf : strchrnul(buf.buf, '\n');
2004
2005 strbuf_addf(&header, "%c ", comment_line_char);
2006 strbuf_addf(&header, _(combined_commit_msg_fmt),
2007 opts->current_fixup_count + 2);
2008 strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
2009 strbuf_release(&header);
2010 if (is_fixup_flag(command, flag) && !seen_squash(opts))
2011 update_squash_message_for_fixup(&buf);
2012 } else {
2013 struct object_id head;
2014 struct commit *head_commit;
2015 const char *head_message, *body;
2016
2017 if (repo_get_oid(r, "HEAD", &head))
2018 return error(_("need a HEAD to fixup"));
2019 if (!(head_commit = lookup_commit_reference(r, &head)))
2020 return error(_("could not read HEAD"));
2021 if (!(head_message = repo_logmsg_reencode(r, head_commit, NULL,
2022 encoding)))
2023 return error(_("could not read HEAD's commit message"));
2024
2025 find_commit_subject(head_message, &body);
2026 if (command == TODO_FIXUP && !flag && write_message(body, strlen(body),
2027 rebase_path_fixup_msg(), 0) < 0) {
2028 repo_unuse_commit_buffer(r, head_commit, head_message);
2029 return error(_("cannot write '%s'"), rebase_path_fixup_msg());
2030 }
2031 strbuf_addf(&buf, "%c ", comment_line_char);
2032 strbuf_addf(&buf, _(combined_commit_msg_fmt), 2);
2033 strbuf_addf(&buf, "\n%c ", comment_line_char);
2034 strbuf_addstr(&buf, is_fixup_flag(command, flag) ?
2035 _(skip_first_commit_msg_str) :
2036 _(first_commit_msg_str));
2037 strbuf_addstr(&buf, "\n\n");
2038 if (is_fixup_flag(command, flag))
2039 strbuf_add_commented_lines(&buf, body, strlen(body),
2040 comment_line_char);
2041 else
2042 strbuf_addstr(&buf, body);
2043
2044 repo_unuse_commit_buffer(r, head_commit, head_message);
2045 }
2046
2047 if (!(message = repo_logmsg_reencode(r, commit, NULL, encoding)))
2048 return error(_("could not read commit message of %s"),
2049 oid_to_hex(&commit->object.oid));
2050 find_commit_subject(message, &body);
2051
2052 if (command == TODO_SQUASH || is_fixup_flag(command, flag)) {
2053 res = append_squash_message(&buf, body, command, opts, flag);
2054 } else if (command == TODO_FIXUP) {
2055 strbuf_addf(&buf, "\n%c ", comment_line_char);
2056 strbuf_addf(&buf, _(skip_nth_commit_msg_fmt),
2057 ++opts->current_fixup_count + 1);
2058 strbuf_addstr(&buf, "\n\n");
2059 strbuf_add_commented_lines(&buf, body, strlen(body),
2060 comment_line_char);
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 };
5343
5344 static const char *label_oid(struct object_id *oid, const char *label,
5345 struct label_state *state)
5346 {
5347 struct labels_entry *labels_entry;
5348 struct string_entry *string_entry;
5349 struct object_id dummy;
5350 int i;
5351
5352 string_entry = oidmap_get(&state->commit2label, oid);
5353 if (string_entry)
5354 return string_entry->string;
5355
5356 /*
5357 * For "uninteresting" commits, i.e. commits that are not to be
5358 * rebased, and which can therefore not be labeled, we use a unique
5359 * abbreviation of the commit name. This is slightly more complicated
5360 * than calling repo_find_unique_abbrev() because we also need to make
5361 * sure that the abbreviation does not conflict with any other
5362 * label.
5363 *
5364 * We disallow "interesting" commits to be labeled by a string that
5365 * is a valid full-length hash, to ensure that we always can find an
5366 * abbreviation for any uninteresting commit's names that does not
5367 * clash with any other label.
5368 */
5369 strbuf_reset(&state->buf);
5370 if (!label) {
5371 char *p;
5372
5373 strbuf_grow(&state->buf, GIT_MAX_HEXSZ);
5374 label = p = state->buf.buf;
5375
5376 repo_find_unique_abbrev_r(the_repository, p, oid,
5377 default_abbrev);
5378
5379 /*
5380 * We may need to extend the abbreviated hash so that there is
5381 * no conflicting label.
5382 */
5383 if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
5384 size_t i = strlen(p) + 1;
5385
5386 oid_to_hex_r(p, oid);
5387 for (; i < the_hash_algo->hexsz; i++) {
5388 char save = p[i];
5389 p[i] = '\0';
5390 if (!hashmap_get_from_hash(&state->labels,
5391 strihash(p), p))
5392 break;
5393 p[i] = save;
5394 }
5395 }
5396 } else {
5397 struct strbuf *buf = &state->buf;
5398
5399 /*
5400 * Sanitize labels by replacing non-alpha-numeric characters
5401 * (including white-space ones) by dashes, as they might be
5402 * illegal in file names (and hence in ref names).
5403 *
5404 * Note that we retain non-ASCII UTF-8 characters (identified
5405 * via the most significant bit). They should be all acceptable
5406 * in file names. We do not validate the UTF-8 here, that's not
5407 * the job of this function.
5408 */
5409 for (; *label; label++)
5410 if ((*label & 0x80) || isalnum(*label))
5411 strbuf_addch(buf, *label);
5412 /* avoid leading dash and double-dashes */
5413 else if (buf->len && buf->buf[buf->len - 1] != '-')
5414 strbuf_addch(buf, '-');
5415 if (!buf->len) {
5416 strbuf_addstr(buf, "rev-");
5417 strbuf_add_unique_abbrev(buf, oid, default_abbrev);
5418 }
5419 label = buf->buf;
5420
5421 if ((buf->len == the_hash_algo->hexsz &&
5422 !get_oid_hex(label, &dummy)) ||
5423 (buf->len == 1 && *label == '#') ||
5424 hashmap_get_from_hash(&state->labels,
5425 strihash(label), label)) {
5426 /*
5427 * If the label already exists, or if the label is a
5428 * valid full OID, or the label is a '#' (which we use
5429 * as a separator between merge heads and oneline), we
5430 * append a dash and a number to make it unique.
5431 */
5432 size_t len = buf->len;
5433
5434 for (i = 2; ; i++) {
5435 strbuf_setlen(buf, len);
5436 strbuf_addf(buf, "-%d", i);
5437 if (!hashmap_get_from_hash(&state->labels,
5438 strihash(buf->buf),
5439 buf->buf))
5440 break;
5441 }
5442
5443 label = buf->buf;
5444 }
5445 }
5446
5447 FLEX_ALLOC_STR(labels_entry, label, label);
5448 hashmap_entry_init(&labels_entry->entry, strihash(label));
5449 hashmap_add(&state->labels, &labels_entry->entry);
5450
5451 FLEX_ALLOC_STR(string_entry, string, label);
5452 oidcpy(&string_entry->entry.oid, oid);
5453 oidmap_put(&state->commit2label, string_entry);
5454
5455 return string_entry->string;
5456 }
5457
5458 static int make_script_with_merges(struct pretty_print_context *pp,
5459 struct rev_info *revs, struct strbuf *out,
5460 unsigned flags)
5461 {
5462 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5463 int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
5464 int root_with_onto = flags & TODO_LIST_ROOT_WITH_ONTO;
5465 int skipped_commit = 0;
5466 struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
5467 struct strbuf label = STRBUF_INIT;
5468 struct commit_list *commits = NULL, **tail = &commits, *iter;
5469 struct commit_list *tips = NULL, **tips_tail = &tips;
5470 struct commit *commit;
5471 struct oidmap commit2todo = OIDMAP_INIT;
5472 struct string_entry *entry;
5473 struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
5474 shown = OIDSET_INIT;
5475 struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
5476
5477 int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
5478 const char *cmd_pick = abbr ? "p" : "pick",
5479 *cmd_label = abbr ? "l" : "label",
5480 *cmd_reset = abbr ? "t" : "reset",
5481 *cmd_merge = abbr ? "m" : "merge";
5482
5483 oidmap_init(&commit2todo, 0);
5484 oidmap_init(&state.commit2label, 0);
5485 hashmap_init(&state.labels, labels_cmp, NULL, 0);
5486 strbuf_init(&state.buf, 32);
5487
5488 if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
5489 struct labels_entry *onto_label_entry;
5490 struct object_id *oid = &revs->cmdline.rev[0].item->oid;
5491 FLEX_ALLOC_STR(entry, string, "onto");
5492 oidcpy(&entry->entry.oid, oid);
5493 oidmap_put(&state.commit2label, entry);
5494
5495 FLEX_ALLOC_STR(onto_label_entry, label, "onto");
5496 hashmap_entry_init(&onto_label_entry->entry, strihash("onto"));
5497 hashmap_add(&state.labels, &onto_label_entry->entry);
5498 }
5499
5500 /*
5501 * First phase:
5502 * - get onelines for all commits
5503 * - gather all branch tips (i.e. 2nd or later parents of merges)
5504 * - label all branch tips
5505 */
5506 while ((commit = get_revision(revs))) {
5507 struct commit_list *to_merge;
5508 const char *p1, *p2;
5509 struct object_id *oid;
5510 int is_empty;
5511
5512 tail = &commit_list_insert(commit, tail)->next;
5513 oidset_insert(&interesting, &commit->object.oid);
5514
5515 is_empty = is_original_commit_empty(commit);
5516 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5517 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5518 warning(_("skipped previously applied commit %s"),
5519 short_commit_name(commit));
5520 skipped_commit = 1;
5521 continue;
5522 }
5523 if (is_empty && !keep_empty)
5524 continue;
5525
5526 strbuf_reset(&oneline);
5527 pretty_print_commit(pp, commit, &oneline);
5528
5529 to_merge = commit->parents ? commit->parents->next : NULL;
5530 if (!to_merge) {
5531 /* non-merge commit: easy case */
5532 strbuf_reset(&buf);
5533 strbuf_addf(&buf, "%s %s %s", cmd_pick,
5534 oid_to_hex(&commit->object.oid),
5535 oneline.buf);
5536 if (is_empty)
5537 strbuf_addf(&buf, " %c empty",
5538 comment_line_char);
5539
5540 FLEX_ALLOC_STR(entry, string, buf.buf);
5541 oidcpy(&entry->entry.oid, &commit->object.oid);
5542 oidmap_put(&commit2todo, entry);
5543
5544 continue;
5545 }
5546
5547 /* Create a label */
5548 strbuf_reset(&label);
5549 if (skip_prefix(oneline.buf, "Merge ", &p1) &&
5550 (p1 = strchr(p1, '\'')) &&
5551 (p2 = strchr(++p1, '\'')))
5552 strbuf_add(&label, p1, p2 - p1);
5553 else if (skip_prefix(oneline.buf, "Merge pull request ",
5554 &p1) &&
5555 (p1 = strstr(p1, " from ")))
5556 strbuf_addstr(&label, p1 + strlen(" from "));
5557 else
5558 strbuf_addbuf(&label, &oneline);
5559
5560 strbuf_reset(&buf);
5561 strbuf_addf(&buf, "%s -C %s",
5562 cmd_merge, oid_to_hex(&commit->object.oid));
5563
5564 /* label the tips of merged branches */
5565 for (; to_merge; to_merge = to_merge->next) {
5566 oid = &to_merge->item->object.oid;
5567 strbuf_addch(&buf, ' ');
5568
5569 if (!oidset_contains(&interesting, oid)) {
5570 strbuf_addstr(&buf, label_oid(oid, NULL,
5571 &state));
5572 continue;
5573 }
5574
5575 tips_tail = &commit_list_insert(to_merge->item,
5576 tips_tail)->next;
5577
5578 strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
5579 }
5580 strbuf_addf(&buf, " # %s", oneline.buf);
5581
5582 FLEX_ALLOC_STR(entry, string, buf.buf);
5583 oidcpy(&entry->entry.oid, &commit->object.oid);
5584 oidmap_put(&commit2todo, entry);
5585 }
5586 if (skipped_commit)
5587 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5588 _("use --reapply-cherry-picks to include skipped commits"));
5589
5590 /*
5591 * Second phase:
5592 * - label branch points
5593 * - add HEAD to the branch tips
5594 */
5595 for (iter = commits; iter; iter = iter->next) {
5596 struct commit_list *parent = iter->item->parents;
5597 for (; parent; parent = parent->next) {
5598 struct object_id *oid = &parent->item->object.oid;
5599 if (!oidset_contains(&interesting, oid))
5600 continue;
5601 if (oidset_insert(&child_seen, oid))
5602 label_oid(oid, "branch-point", &state);
5603 }
5604
5605 /* Add HEAD as implicit "tip of branch" */
5606 if (!iter->next)
5607 tips_tail = &commit_list_insert(iter->item,
5608 tips_tail)->next;
5609 }
5610
5611 /*
5612 * Third phase: output the todo list. This is a bit tricky, as we
5613 * want to avoid jumping back and forth between revisions. To
5614 * accomplish that goal, we walk backwards from the branch tips,
5615 * gathering commits not yet shown, reversing the list on the fly,
5616 * then outputting that list (labeling revisions as needed).
5617 */
5618 strbuf_addf(out, "%s onto\n", cmd_label);
5619 for (iter = tips; iter; iter = iter->next) {
5620 struct commit_list *list = NULL, *iter2;
5621
5622 commit = iter->item;
5623 if (oidset_contains(&shown, &commit->object.oid))
5624 continue;
5625 entry = oidmap_get(&state.commit2label, &commit->object.oid);
5626
5627 if (entry)
5628 strbuf_addf(out, "\n%c Branch %s\n", comment_line_char, entry->string);
5629 else
5630 strbuf_addch(out, '\n');
5631
5632 while (oidset_contains(&interesting, &commit->object.oid) &&
5633 !oidset_contains(&shown, &commit->object.oid)) {
5634 commit_list_insert(commit, &list);
5635 if (!commit->parents) {
5636 commit = NULL;
5637 break;
5638 }
5639 commit = commit->parents->item;
5640 }
5641
5642 if (!commit)
5643 strbuf_addf(out, "%s %s\n", cmd_reset,
5644 rebase_cousins || root_with_onto ?
5645 "onto" : "[new root]");
5646 else {
5647 const char *to = NULL;
5648
5649 entry = oidmap_get(&state.commit2label,
5650 &commit->object.oid);
5651 if (entry)
5652 to = entry->string;
5653 else if (!rebase_cousins)
5654 to = label_oid(&commit->object.oid, NULL,
5655 &state);
5656
5657 if (!to || !strcmp(to, "onto"))
5658 strbuf_addf(out, "%s onto\n", cmd_reset);
5659 else {
5660 strbuf_reset(&oneline);
5661 pretty_print_commit(pp, commit, &oneline);
5662 strbuf_addf(out, "%s %s # %s\n",
5663 cmd_reset, to, oneline.buf);
5664 }
5665 }
5666
5667 for (iter2 = list; iter2; iter2 = iter2->next) {
5668 struct object_id *oid = &iter2->item->object.oid;
5669 entry = oidmap_get(&commit2todo, oid);
5670 /* only show if not already upstream */
5671 if (entry)
5672 strbuf_addf(out, "%s\n", entry->string);
5673 entry = oidmap_get(&state.commit2label, oid);
5674 if (entry)
5675 strbuf_addf(out, "%s %s\n",
5676 cmd_label, entry->string);
5677 oidset_insert(&shown, oid);
5678 }
5679
5680 free_commit_list(list);
5681 }
5682
5683 free_commit_list(commits);
5684 free_commit_list(tips);
5685
5686 strbuf_release(&label);
5687 strbuf_release(&oneline);
5688 strbuf_release(&buf);
5689
5690 oidmap_free(&commit2todo, 1);
5691 oidmap_free(&state.commit2label, 1);
5692 hashmap_clear_and_free(&state.labels, struct labels_entry, entry);
5693 strbuf_release(&state.buf);
5694
5695 return 0;
5696 }
5697
5698 int sequencer_make_script(struct repository *r, struct strbuf *out, int argc,
5699 const char **argv, unsigned flags)
5700 {
5701 char *format = NULL;
5702 struct pretty_print_context pp = {0};
5703 struct rev_info revs;
5704 struct commit *commit;
5705 int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
5706 const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
5707 int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
5708 int reapply_cherry_picks = flags & TODO_LIST_REAPPLY_CHERRY_PICKS;
5709 int skipped_commit = 0;
5710 int ret = 0;
5711
5712 repo_init_revisions(r, &revs, NULL);
5713 revs.verbose_header = 1;
5714 if (!rebase_merges)
5715 revs.max_parents = 1;
5716 revs.cherry_mark = !reapply_cherry_picks;
5717 revs.limited = 1;
5718 revs.reverse = 1;
5719 revs.right_only = 1;
5720 revs.sort_order = REV_SORT_IN_GRAPH_ORDER;
5721 revs.topo_order = 1;
5722
5723 revs.pretty_given = 1;
5724 git_config_get_string("rebase.instructionFormat", &format);
5725 if (!format || !*format) {
5726 free(format);
5727 format = xstrdup("%s");
5728 }
5729 get_commit_format(format, &revs);
5730 free(format);
5731 pp.fmt = revs.commit_format;
5732 pp.output_encoding = get_log_output_encoding();
5733
5734 if (setup_revisions(argc, argv, &revs, NULL) > 1) {
5735 ret = error(_("make_script: unhandled options"));
5736 goto cleanup;
5737 }
5738
5739 if (prepare_revision_walk(&revs) < 0) {
5740 ret = error(_("make_script: error preparing revisions"));
5741 goto cleanup;
5742 }
5743
5744 if (rebase_merges) {
5745 ret = make_script_with_merges(&pp, &revs, out, flags);
5746 goto cleanup;
5747 }
5748
5749 while ((commit = get_revision(&revs))) {
5750 int is_empty = is_original_commit_empty(commit);
5751
5752 if (!is_empty && (commit->object.flags & PATCHSAME)) {
5753 if (flags & TODO_LIST_WARN_SKIPPED_CHERRY_PICKS)
5754 warning(_("skipped previously applied commit %s"),
5755 short_commit_name(commit));
5756 skipped_commit = 1;
5757 continue;
5758 }
5759 if (is_empty && !keep_empty)
5760 continue;
5761 strbuf_addf(out, "%s %s ", insn,
5762 oid_to_hex(&commit->object.oid));
5763 pretty_print_commit(&pp, commit, out);
5764 if (is_empty)
5765 strbuf_addf(out, " %c empty", comment_line_char);
5766 strbuf_addch(out, '\n');
5767 }
5768 if (skipped_commit)
5769 advise_if_enabled(ADVICE_SKIPPED_CHERRY_PICKS,
5770 _("use --reapply-cherry-picks to include skipped commits"));
5771 cleanup:
5772 release_revisions(&revs);
5773 return ret;
5774 }
5775
5776 /*
5777 * Add commands after pick and (series of) squash/fixup commands
5778 * in the todo list.
5779 */
5780 static void todo_list_add_exec_commands(struct todo_list *todo_list,
5781 struct string_list *commands)
5782 {
5783 struct strbuf *buf = &todo_list->buf;
5784 size_t base_offset = buf->len;
5785 int i, insert, nr = 0, alloc = 0;
5786 struct todo_item *items = NULL, *base_items = NULL;
5787
5788 CALLOC_ARRAY(base_items, commands->nr);
5789 for (i = 0; i < commands->nr; i++) {
5790 size_t command_len = strlen(commands->items[i].string);
5791
5792 strbuf_addstr(buf, commands->items[i].string);
5793 strbuf_addch(buf, '\n');
5794
5795 base_items[i].command = TODO_EXEC;
5796 base_items[i].offset_in_buf = base_offset;
5797 base_items[i].arg_offset = base_offset;
5798 base_items[i].arg_len = command_len;
5799
5800 base_offset += command_len + 1;
5801 }
5802
5803 /*
5804 * Insert <commands> after every pick. Here, fixup/squash chains
5805 * are considered part of the pick, so we insert the commands *after*
5806 * those chains if there are any.
5807 *
5808 * As we insert the exec commands immediately after rearranging
5809 * any fixups and before the user edits the list, a fixup chain
5810 * can never contain comments (any comments are empty picks that
5811 * have been commented out because the user did not specify
5812 * --keep-empty). So, it is safe to insert an exec command
5813 * without looking at the command following a comment.
5814 */
5815 insert = 0;
5816 for (i = 0; i < todo_list->nr; i++) {
5817 enum todo_command command = todo_list->items[i].command;
5818 if (insert && !is_fixup(command)) {
5819 ALLOC_GROW(items, nr + commands->nr, alloc);
5820 COPY_ARRAY(items + nr, base_items, commands->nr);
5821 nr += commands->nr;
5822
5823 insert = 0;
5824 }
5825
5826 ALLOC_GROW(items, nr + 1, alloc);
5827 items[nr++] = todo_list->items[i];
5828
5829 if (command == TODO_PICK || command == TODO_MERGE)
5830 insert = 1;
5831 }
5832
5833 /* insert or append final <commands> */
5834 if (insert) {
5835 ALLOC_GROW(items, nr + commands->nr, alloc);
5836 COPY_ARRAY(items + nr, base_items, commands->nr);
5837 nr += commands->nr;
5838 }
5839
5840 free(base_items);
5841 FREE_AND_NULL(todo_list->items);
5842 todo_list->items = items;
5843 todo_list->nr = nr;
5844 todo_list->alloc = alloc;
5845 }
5846
5847 static void todo_list_to_strbuf(struct repository *r, struct todo_list *todo_list,
5848 struct strbuf *buf, int num, unsigned flags)
5849 {
5850 struct todo_item *item;
5851 int i, max = todo_list->nr;
5852
5853 if (num > 0 && num < max)
5854 max = num;
5855
5856 for (item = todo_list->items, i = 0; i < max; i++, item++) {
5857 char cmd;
5858
5859 /* if the item is not a command write it and continue */
5860 if (item->command >= TODO_COMMENT) {
5861 strbuf_addf(buf, "%.*s\n", item->arg_len,
5862 todo_item_get_arg(todo_list, item));
5863 continue;
5864 }
5865
5866 /* add command to the buffer */
5867 cmd = command_to_char(item->command);
5868 if ((flags & TODO_LIST_ABBREVIATE_CMDS) && cmd)
5869 strbuf_addch(buf, cmd);
5870 else
5871 strbuf_addstr(buf, command_to_string(item->command));
5872
5873 /* add commit id */
5874 if (item->commit) {
5875 const char *oid = flags & TODO_LIST_SHORTEN_IDS ?
5876 short_commit_name(item->commit) :
5877 oid_to_hex(&item->commit->object.oid);
5878
5879 if (item->command == TODO_FIXUP) {
5880 if (item->flags & TODO_EDIT_FIXUP_MSG)
5881 strbuf_addstr(buf, " -c");
5882 else if (item->flags & TODO_REPLACE_FIXUP_MSG) {
5883 strbuf_addstr(buf, " -C");
5884 }
5885 }
5886
5887 if (item->command == TODO_MERGE) {
5888 if (item->flags & TODO_EDIT_MERGE_MSG)
5889 strbuf_addstr(buf, " -c");
5890 else
5891 strbuf_addstr(buf, " -C");
5892 }
5893
5894 strbuf_addf(buf, " %s", oid);
5895 }
5896
5897 /* add all the rest */
5898 if (!item->arg_len)
5899 strbuf_addch(buf, '\n');
5900 else
5901 strbuf_addf(buf, " %.*s\n", item->arg_len,
5902 todo_item_get_arg(todo_list, item));
5903 }
5904 }
5905
5906 int todo_list_write_to_file(struct repository *r, struct todo_list *todo_list,
5907 const char *file, const char *shortrevisions,
5908 const char *shortonto, int num, unsigned flags)
5909 {
5910 int res;
5911 struct strbuf buf = STRBUF_INIT;
5912
5913 todo_list_to_strbuf(r, todo_list, &buf, num, flags);
5914 if (flags & TODO_LIST_APPEND_TODO_HELP)
5915 append_todo_help(count_commands(todo_list),
5916 shortrevisions, shortonto, &buf);
5917
5918 res = write_message(buf.buf, buf.len, file, 0);
5919 strbuf_release(&buf);
5920
5921 return res;
5922 }
5923
5924 /* skip picking commits whose parents are unchanged */
5925 static int skip_unnecessary_picks(struct repository *r,
5926 struct todo_list *todo_list,
5927 struct object_id *base_oid)
5928 {
5929 struct object_id *parent_oid;
5930 int i;
5931
5932 for (i = 0; i < todo_list->nr; i++) {
5933 struct todo_item *item = todo_list->items + i;
5934
5935 if (item->command >= TODO_NOOP)
5936 continue;
5937 if (item->command != TODO_PICK)
5938 break;
5939 if (repo_parse_commit(r, item->commit)) {
5940 return error(_("could not parse commit '%s'"),
5941 oid_to_hex(&item->commit->object.oid));
5942 }
5943 if (!item->commit->parents)
5944 break; /* root commit */
5945 if (item->commit->parents->next)
5946 break; /* merge commit */
5947 parent_oid = &item->commit->parents->item->object.oid;
5948 if (!oideq(parent_oid, base_oid))
5949 break;
5950 oidcpy(base_oid, &item->commit->object.oid);
5951 }
5952 if (i > 0) {
5953 const char *done_path = rebase_path_done();
5954
5955 if (todo_list_write_to_file(r, todo_list, done_path, NULL, NULL, i, 0)) {
5956 error_errno(_("could not write to '%s'"), done_path);
5957 return -1;
5958 }
5959
5960 MOVE_ARRAY(todo_list->items, todo_list->items + i, todo_list->nr - i);
5961 todo_list->nr -= i;
5962 todo_list->current = 0;
5963 todo_list->done_nr += i;
5964
5965 if (is_fixup(peek_command(todo_list, 0)))
5966 record_in_rewritten(base_oid, peek_command(todo_list, 0));
5967 }
5968
5969 return 0;
5970 }
5971
5972 struct todo_add_branch_context {
5973 struct todo_item *items;
5974 size_t items_nr;
5975 size_t items_alloc;
5976 struct strbuf *buf;
5977 struct commit *commit;
5978 struct string_list refs_to_oids;
5979 };
5980
5981 static int add_decorations_to_list(const struct commit *commit,
5982 struct todo_add_branch_context *ctx)
5983 {
5984 const struct name_decoration *decoration = get_name_decoration(&commit->object);
5985 const char *head_ref = resolve_ref_unsafe("HEAD",
5986 RESOLVE_REF_READING,
5987 NULL,
5988 NULL);
5989
5990 while (decoration) {
5991 struct todo_item *item;
5992 const char *path;
5993 size_t base_offset = ctx->buf->len;
5994
5995 /*
5996 * If the branch is the current HEAD, then it will be
5997 * updated by the default rebase behavior.
5998 */
5999 if (head_ref && !strcmp(head_ref, decoration->name)) {
6000 decoration = decoration->next;
6001 continue;
6002 }
6003
6004 ALLOC_GROW(ctx->items,
6005 ctx->items_nr + 1,
6006 ctx->items_alloc);
6007 item = &ctx->items[ctx->items_nr];
6008 memset(item, 0, sizeof(*item));
6009
6010 /* If the branch is checked out, then leave a comment instead. */
6011 if ((path = branch_checked_out(decoration->name))) {
6012 item->command = TODO_COMMENT;
6013 strbuf_addf(ctx->buf, "# Ref %s checked out at '%s'\n",
6014 decoration->name, path);
6015 } else {
6016 struct string_list_item *sti;
6017 item->command = TODO_UPDATE_REF;
6018 strbuf_addf(ctx->buf, "%s\n", decoration->name);
6019
6020 sti = string_list_insert(&ctx->refs_to_oids,
6021 decoration->name);
6022 sti->util = init_update_ref_record(decoration->name);
6023 }
6024
6025 item->offset_in_buf = base_offset;
6026 item->arg_offset = base_offset;
6027 item->arg_len = ctx->buf->len - base_offset;
6028 ctx->items_nr++;
6029
6030 decoration = decoration->next;
6031 }
6032
6033 return 0;
6034 }
6035
6036 /*
6037 * For each 'pick' command, find out if the commit has a decoration in
6038 * refs/heads/. If so, then add a 'label for-update-refs/' command.
6039 */
6040 static int todo_list_add_update_ref_commands(struct todo_list *todo_list)
6041 {
6042 int i, res;
6043 static struct string_list decorate_refs_exclude = STRING_LIST_INIT_NODUP;
6044 static struct string_list decorate_refs_exclude_config = STRING_LIST_INIT_NODUP;
6045 static struct string_list decorate_refs_include = STRING_LIST_INIT_NODUP;
6046 struct decoration_filter decoration_filter = {
6047 .include_ref_pattern = &decorate_refs_include,
6048 .exclude_ref_pattern = &decorate_refs_exclude,
6049 .exclude_ref_config_pattern = &decorate_refs_exclude_config,
6050 };
6051 struct todo_add_branch_context ctx = {
6052 .buf = &todo_list->buf,
6053 .refs_to_oids = STRING_LIST_INIT_DUP,
6054 };
6055
6056 ctx.items_alloc = 2 * todo_list->nr + 1;
6057 ALLOC_ARRAY(ctx.items, ctx.items_alloc);
6058
6059 string_list_append(&decorate_refs_include, "refs/heads/");
6060 load_ref_decorations(&decoration_filter, 0);
6061
6062 for (i = 0; i < todo_list->nr; ) {
6063 struct todo_item *item = &todo_list->items[i];
6064
6065 /* insert ith item into new list */
6066 ALLOC_GROW(ctx.items,
6067 ctx.items_nr + 1,
6068 ctx.items_alloc);
6069
6070 ctx.items[ctx.items_nr++] = todo_list->items[i++];
6071
6072 if (item->commit) {
6073 ctx.commit = item->commit;
6074 add_decorations_to_list(item->commit, &ctx);
6075 }
6076 }
6077
6078 res = write_update_refs_state(&ctx.refs_to_oids);
6079
6080 string_list_clear(&ctx.refs_to_oids, 1);
6081
6082 if (res) {
6083 /* we failed, so clean up the new list. */
6084 free(ctx.items);
6085 return res;
6086 }
6087
6088 free(todo_list->items);
6089 todo_list->items = ctx.items;
6090 todo_list->nr = ctx.items_nr;
6091 todo_list->alloc = ctx.items_alloc;
6092
6093 return 0;
6094 }
6095
6096 int complete_action(struct repository *r, struct replay_opts *opts, unsigned flags,
6097 const char *shortrevisions, const char *onto_name,
6098 struct commit *onto, const struct object_id *orig_head,
6099 struct string_list *commands, unsigned autosquash,
6100 unsigned update_refs,
6101 struct todo_list *todo_list)
6102 {
6103 char shortonto[GIT_MAX_HEXSZ + 1];
6104 const char *todo_file = rebase_path_todo();
6105 struct todo_list new_todo = TODO_LIST_INIT;
6106 struct strbuf *buf = &todo_list->buf, buf2 = STRBUF_INIT;
6107 struct object_id oid = onto->object.oid;
6108 int res;
6109
6110 repo_find_unique_abbrev_r(r, shortonto, &oid,
6111 DEFAULT_ABBREV);
6112
6113 if (buf->len == 0) {
6114 struct todo_item *item = append_new_todo(todo_list);
6115 item->command = TODO_NOOP;
6116 item->commit = NULL;
6117 item->arg_len = item->arg_offset = item->flags = item->offset_in_buf = 0;
6118 }
6119
6120 if (update_refs && todo_list_add_update_ref_commands(todo_list))
6121 return -1;
6122
6123 if (autosquash && todo_list_rearrange_squash(todo_list))
6124 return -1;
6125
6126 if (commands->nr)
6127 todo_list_add_exec_commands(todo_list, commands);
6128
6129 if (count_commands(todo_list) == 0) {
6130 apply_autostash(rebase_path_autostash());
6131 sequencer_remove_state(opts);
6132
6133 return error(_("nothing to do"));
6134 }
6135
6136 res = edit_todo_list(r, todo_list, &new_todo, shortrevisions,
6137 shortonto, flags);
6138 if (res == -1)
6139 return -1;
6140 else if (res == -2) {
6141 apply_autostash(rebase_path_autostash());
6142 sequencer_remove_state(opts);
6143
6144 return -1;
6145 } else if (res == -3) {
6146 apply_autostash(rebase_path_autostash());
6147 sequencer_remove_state(opts);
6148 todo_list_release(&new_todo);
6149
6150 return error(_("nothing to do"));
6151 } else if (res == -4) {
6152 checkout_onto(r, opts, onto_name, &onto->object.oid, orig_head);
6153 todo_list_release(&new_todo);
6154
6155 return -1;
6156 }
6157
6158 /* Expand the commit IDs */
6159 todo_list_to_strbuf(r, &new_todo, &buf2, -1, 0);
6160 strbuf_swap(&new_todo.buf, &buf2);
6161 strbuf_release(&buf2);
6162 /* Nothing is done yet, and we're reparsing, so let's reset the count */
6163 new_todo.total_nr = 0;
6164 if (todo_list_parse_insn_buffer(r, new_todo.buf.buf, &new_todo) < 0)
6165 BUG("invalid todo list after expanding IDs:\n%s",
6166 new_todo.buf.buf);
6167
6168 if (opts->allow_ff && skip_unnecessary_picks(r, &new_todo, &oid)) {
6169 todo_list_release(&new_todo);
6170 return error(_("could not skip unnecessary pick commands"));
6171 }
6172
6173 if (todo_list_write_to_file(r, &new_todo, todo_file, NULL, NULL, -1,
6174 flags & ~(TODO_LIST_SHORTEN_IDS))) {
6175 todo_list_release(&new_todo);
6176 return error_errno(_("could not write '%s'"), todo_file);
6177 }
6178
6179 res = -1;
6180
6181 if (checkout_onto(r, opts, onto_name, &oid, orig_head))
6182 goto cleanup;
6183
6184 if (require_clean_work_tree(r, "rebase", "", 1, 1))
6185 goto cleanup;
6186
6187 todo_list_write_total_nr(&new_todo);
6188 res = pick_commits(r, &new_todo, opts);
6189
6190 cleanup:
6191 todo_list_release(&new_todo);
6192
6193 return res;
6194 }
6195
6196 struct subject2item_entry {
6197 struct hashmap_entry entry;
6198 int i;
6199 char subject[FLEX_ARRAY];
6200 };
6201
6202 static int subject2item_cmp(const void *fndata UNUSED,
6203 const struct hashmap_entry *eptr,
6204 const struct hashmap_entry *entry_or_key,
6205 const void *key)
6206 {
6207 const struct subject2item_entry *a, *b;
6208
6209 a = container_of(eptr, const struct subject2item_entry, entry);
6210 b = container_of(entry_or_key, const struct subject2item_entry, entry);
6211
6212 return key ? strcmp(a->subject, key) : strcmp(a->subject, b->subject);
6213 }
6214
6215 define_commit_slab(commit_todo_item, struct todo_item *);
6216
6217 static int skip_fixupish(const char *subject, const char **p) {
6218 return skip_prefix(subject, "fixup! ", p) ||
6219 skip_prefix(subject, "amend! ", p) ||
6220 skip_prefix(subject, "squash! ", p);
6221 }
6222
6223 /*
6224 * Rearrange the todo list that has both "pick commit-id msg" and "pick
6225 * commit-id fixup!/squash! msg" in it so that the latter is put immediately
6226 * after the former, and change "pick" to "fixup"/"squash".
6227 *
6228 * Note that if the config has specified a custom instruction format, each log
6229 * message will have to be retrieved from the commit (as the oneline in the
6230 * script cannot be trusted) in order to normalize the autosquash arrangement.
6231 */
6232 int todo_list_rearrange_squash(struct todo_list *todo_list)
6233 {
6234 struct hashmap subject2item;
6235 int rearranged = 0, *next, *tail, i, nr = 0, alloc = 0;
6236 char **subjects;
6237 struct commit_todo_item commit_todo;
6238 struct todo_item *items = NULL;
6239
6240 init_commit_todo_item(&commit_todo);
6241 /*
6242 * The hashmap maps onelines to the respective todo list index.
6243 *
6244 * If any items need to be rearranged, the next[i] value will indicate
6245 * which item was moved directly after the i'th.
6246 *
6247 * In that case, last[i] will indicate the index of the latest item to
6248 * be moved to appear after the i'th.
6249 */
6250 hashmap_init(&subject2item, subject2item_cmp, NULL, todo_list->nr);
6251 ALLOC_ARRAY(next, todo_list->nr);
6252 ALLOC_ARRAY(tail, todo_list->nr);
6253 ALLOC_ARRAY(subjects, todo_list->nr);
6254 for (i = 0; i < todo_list->nr; i++) {
6255 struct strbuf buf = STRBUF_INIT;
6256 struct todo_item *item = todo_list->items + i;
6257 const char *commit_buffer, *subject, *p;
6258 size_t subject_len;
6259 int i2 = -1;
6260 struct subject2item_entry *entry;
6261
6262 next[i] = tail[i] = -1;
6263 if (!item->commit || item->command == TODO_DROP) {
6264 subjects[i] = NULL;
6265 continue;
6266 }
6267
6268 if (is_fixup(item->command)) {
6269 clear_commit_todo_item(&commit_todo);
6270 return error(_("the script was already rearranged."));
6271 }
6272
6273 repo_parse_commit(the_repository, item->commit);
6274 commit_buffer = repo_logmsg_reencode(the_repository,
6275 item->commit, NULL,
6276 "UTF-8");
6277 find_commit_subject(commit_buffer, &subject);
6278 format_subject(&buf, subject, " ");
6279 subject = subjects[i] = strbuf_detach(&buf, &subject_len);
6280 repo_unuse_commit_buffer(the_repository, item->commit,
6281 commit_buffer);
6282 if (skip_fixupish(subject, &p)) {
6283 struct commit *commit2;
6284
6285 for (;;) {
6286 while (isspace(*p))
6287 p++;
6288 if (!skip_fixupish(p, &p))
6289 break;
6290 }
6291
6292 entry = hashmap_get_entry_from_hash(&subject2item,
6293 strhash(p), p,
6294 struct subject2item_entry,
6295 entry);
6296 if (entry)
6297 /* found by title */
6298 i2 = entry->i;
6299 else if (!strchr(p, ' ') &&
6300 (commit2 =
6301 lookup_commit_reference_by_name(p)) &&
6302 *commit_todo_item_at(&commit_todo, commit2))
6303 /* found by commit name */
6304 i2 = *commit_todo_item_at(&commit_todo, commit2)
6305 - todo_list->items;
6306 else {
6307 /* copy can be a prefix of the commit subject */
6308 for (i2 = 0; i2 < i; i2++)
6309 if (subjects[i2] &&
6310 starts_with(subjects[i2], p))
6311 break;
6312 if (i2 == i)
6313 i2 = -1;
6314 }
6315 }
6316 if (i2 >= 0) {
6317 rearranged = 1;
6318 if (starts_with(subject, "fixup!")) {
6319 todo_list->items[i].command = TODO_FIXUP;
6320 } else if (starts_with(subject, "amend!")) {
6321 todo_list->items[i].command = TODO_FIXUP;
6322 todo_list->items[i].flags = TODO_REPLACE_FIXUP_MSG;
6323 } else {
6324 todo_list->items[i].command = TODO_SQUASH;
6325 }
6326 if (tail[i2] < 0) {
6327 next[i] = next[i2];
6328 next[i2] = i;
6329 } else {
6330 next[i] = next[tail[i2]];
6331 next[tail[i2]] = i;
6332 }
6333 tail[i2] = i;
6334 } else if (!hashmap_get_from_hash(&subject2item,
6335 strhash(subject), subject)) {
6336 FLEX_ALLOC_MEM(entry, subject, subject, subject_len);
6337 entry->i = i;
6338 hashmap_entry_init(&entry->entry,
6339 strhash(entry->subject));
6340 hashmap_put(&subject2item, &entry->entry);
6341 }
6342
6343 *commit_todo_item_at(&commit_todo, item->commit) = item;
6344 }
6345
6346 if (rearranged) {
6347 for (i = 0; i < todo_list->nr; i++) {
6348 enum todo_command command = todo_list->items[i].command;
6349 int cur = i;
6350
6351 /*
6352 * Initially, all commands are 'pick's. If it is a
6353 * fixup or a squash now, we have rearranged it.
6354 */
6355 if (is_fixup(command))
6356 continue;
6357
6358 while (cur >= 0) {
6359 ALLOC_GROW(items, nr + 1, alloc);
6360 items[nr++] = todo_list->items[cur];
6361 cur = next[cur];
6362 }
6363 }
6364
6365 FREE_AND_NULL(todo_list->items);
6366 todo_list->items = items;
6367 todo_list->nr = nr;
6368 todo_list->alloc = alloc;
6369 }
6370
6371 free(next);
6372 free(tail);
6373 for (i = 0; i < todo_list->nr; i++)
6374 free(subjects[i]);
6375 free(subjects);
6376 hashmap_clear_and_free(&subject2item, struct subject2item_entry, entry);
6377
6378 clear_commit_todo_item(&commit_todo);
6379
6380 return 0;
6381 }
6382
6383 int sequencer_determine_whence(struct repository *r, enum commit_whence *whence)
6384 {
6385 if (refs_ref_exists(get_main_ref_store(r), "CHERRY_PICK_HEAD")) {
6386 struct object_id cherry_pick_head, rebase_head;
6387
6388 if (file_exists(git_path_seq_dir()))
6389 *whence = FROM_CHERRY_PICK_MULTI;
6390 if (file_exists(rebase_path()) &&
6391 !repo_get_oid(r, "REBASE_HEAD", &rebase_head) &&
6392 !repo_get_oid(r, "CHERRY_PICK_HEAD", &cherry_pick_head) &&
6393 oideq(&rebase_head, &cherry_pick_head))
6394 *whence = FROM_REBASE_PICK;
6395 else
6396 *whence = FROM_CHERRY_PICK_SINGLE;
6397
6398 return 1;
6399 }
6400
6401 return 0;
6402 }
6403
6404 int sequencer_get_update_refs_state(const char *wt_dir,
6405 struct string_list *refs)
6406 {
6407 int result = 0;
6408 FILE *fp = NULL;
6409 struct strbuf ref = STRBUF_INIT;
6410 struct strbuf hash = STRBUF_INIT;
6411 struct update_ref_record *rec = NULL;
6412
6413 char *path = rebase_path_update_refs(wt_dir);
6414
6415 fp = fopen(path, "r");
6416 if (!fp)
6417 goto cleanup;
6418
6419 while (strbuf_getline(&ref, fp) != EOF) {
6420 struct string_list_item *item;
6421
6422 CALLOC_ARRAY(rec, 1);
6423
6424 if (strbuf_getline(&hash, fp) == EOF ||
6425 get_oid_hex(hash.buf, &rec->before)) {
6426 warning(_("update-refs file at '%s' is invalid"),
6427 path);
6428 result = -1;
6429 goto cleanup;
6430 }
6431
6432 if (strbuf_getline(&hash, fp) == EOF ||
6433 get_oid_hex(hash.buf, &rec->after)) {
6434 warning(_("update-refs file at '%s' is invalid"),
6435 path);
6436 result = -1;
6437 goto cleanup;
6438 }
6439
6440 item = string_list_insert(refs, ref.buf);
6441 item->util = rec;
6442 rec = NULL;
6443 }
6444
6445 cleanup:
6446 if (fp)
6447 fclose(fp);
6448 free(path);
6449 free(rec);
6450 strbuf_release(&ref);
6451 strbuf_release(&hash);
6452 return result;
6453 }