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