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