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