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