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