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