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