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