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