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