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